repo
stringclasses 900
values | file
stringclasses 754
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the Check Map pass"""
import unittest
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister
from qiskit.circuit.library import CXGate
from qiskit.transpiler.passes import CheckMap
from qiskit.transpiler import CouplingMap, Target
from qiskit.converters import circuit_to_dag
from qiskit.test import QiskitTestCase
class TestCheckMapCX(QiskitTestCase):
"""Tests the CheckMap pass with CX gates"""
def test_trivial_nop_map(self):
"""Trivial map in a circuit without entanglement
qr0:---[H]---
qr1:---[H]---
qr2:---[H]---
CouplingMap map: None
"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr)
coupling = CouplingMap()
dag = circuit_to_dag(circuit)
pass_ = CheckMap(coupling)
pass_.run(dag)
self.assertTrue(pass_.property_set["is_swap_mapped"])
def test_trivial_nop_map_target(self):
"""Trivial map in a circuit without entanglement
qr0:---[H]---
qr1:---[H]---
qr2:---[H]---
CouplingMap map: None
"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr)
target = Target()
dag = circuit_to_dag(circuit)
pass_ = CheckMap(target)
pass_.run(dag)
self.assertTrue(pass_.property_set["is_swap_mapped"])
def test_swap_mapped_true(self):
"""Mapped is easy to check
qr0:--(+)-[H]-(+)-
| |
qr1:---.-------|--
|
qr2:-----------.--
CouplingMap map: [1]--[0]--[2]
"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.h(qr[0])
circuit.cx(qr[0], qr[2])
coupling = CouplingMap([[0, 1], [0, 2]])
dag = circuit_to_dag(circuit)
pass_ = CheckMap(coupling)
pass_.run(dag)
self.assertTrue(pass_.property_set["is_swap_mapped"])
def test_swap_mapped_false(self):
"""Needs [0]-[1] in a [0]--[2]--[1]
qr0:--(+)--
|
qr1:---.---
CouplingMap map: [0]--[2]--[1]
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
coupling = CouplingMap([[0, 2], [2, 1]])
dag = circuit_to_dag(circuit)
pass_ = CheckMap(coupling)
pass_.run(dag)
self.assertFalse(pass_.property_set["is_swap_mapped"])
def test_swap_mapped_false_target(self):
"""Needs [0]-[1] in a [0]--[2]--[1]
qr0:--(+)--
|
qr1:---.---
CouplingMap map: [0]--[2]--[1]
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
target = Target(num_qubits=2)
target.add_instruction(CXGate(), {(0, 2): None, (2, 1): None})
dag = circuit_to_dag(circuit)
pass_ = CheckMap(target)
pass_.run(dag)
self.assertFalse(pass_.property_set["is_swap_mapped"])
def test_swap_mapped_cf_true(self):
"""Check control flow blocks are mapped."""
num_qubits = 3
coupling = CouplingMap.from_line(num_qubits)
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
circuit = QuantumCircuit(qr, cr)
true_body = QuantumCircuit(qr, cr)
true_body.swap(0, 1)
true_body.cx(2, 1)
circuit.if_else((cr[0], 0), true_body, None, qr, cr)
dag = circuit_to_dag(circuit)
pass_ = CheckMap(coupling)
pass_.run(dag)
self.assertTrue(pass_.property_set["is_swap_mapped"])
def test_swap_mapped_cf_false(self):
"""Check control flow blocks are not mapped."""
num_qubits = 3
coupling = CouplingMap.from_line(num_qubits)
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
circuit = QuantumCircuit(qr, cr)
true_body = QuantumCircuit(qr)
true_body.cx(0, 2)
circuit.if_else((cr[0], 0), true_body, None, qr, [])
dag = circuit_to_dag(circuit)
pass_ = CheckMap(coupling)
pass_.run(dag)
self.assertFalse(pass_.property_set["is_swap_mapped"])
def test_swap_mapped_cf_layout_change_false(self):
"""Check control flow blocks with layout change are not mapped."""
num_qubits = 3
coupling = CouplingMap.from_line(num_qubits)
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
circuit = QuantumCircuit(qr, cr)
true_body = QuantumCircuit(qr, cr)
true_body.cx(1, 2)
circuit.if_else((cr[0], 0), true_body, None, qr[[1, 0, 2]], cr)
dag = circuit_to_dag(circuit)
pass_ = CheckMap(coupling)
pass_.run(dag)
self.assertFalse(pass_.property_set["is_swap_mapped"])
def test_swap_mapped_cf_layout_change_true(self):
"""Check control flow blocks with layout change are mapped."""
num_qubits = 3
coupling = CouplingMap.from_line(num_qubits)
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
circuit = QuantumCircuit(qr, cr)
true_body = QuantumCircuit(qr)
true_body.cx(0, 2)
circuit.if_else((cr[0], 0), true_body, None, qr[[1, 0, 2]], [])
dag = circuit_to_dag(circuit)
pass_ = CheckMap(coupling)
pass_.run(dag)
self.assertTrue(pass_.property_set["is_swap_mapped"])
def test_swap_mapped_cf_different_bits(self):
"""Check control flow blocks with layout change are mapped."""
num_qubits = 3
coupling = CouplingMap.from_line(num_qubits)
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
circuit = QuantumCircuit(qr, cr)
true_body = QuantumCircuit(3, 1)
true_body.cx(0, 2)
circuit.if_else((cr[0], 0), true_body, None, qr[[1, 0, 2]], [cr[0]])
dag = circuit_to_dag(circuit)
pass_ = CheckMap(coupling)
pass_.run(dag)
self.assertTrue(pass_.property_set["is_swap_mapped"])
def test_disjoint_controlflow_bits(self):
"""test control flow on with different registers"""
num_qubits = 4
coupling = CouplingMap.from_line(num_qubits)
qr1 = QuantumRegister(4, "qr")
qr2 = QuantumRegister(3, "qrif")
cr = ClassicalRegister(3)
circuit = QuantumCircuit(qr1, cr)
true_body = QuantumCircuit(qr2, [cr[0]])
true_body.cx(0, 2)
circuit.if_else((cr[0], 0), true_body, None, qr1[[1, 0, 2]], [cr[0]])
dag = circuit_to_dag(circuit)
pass_ = CheckMap(coupling)
pass_.run(dag)
self.assertTrue(pass_.property_set["is_swap_mapped"])
def test_nested_controlflow_true(self):
"""Test nested controlflow with true evaluation."""
num_qubits = 4
coupling = CouplingMap.from_line(num_qubits)
qr1 = QuantumRegister(4, "qr")
qr2 = QuantumRegister(3, "qrif")
cr1 = ClassicalRegister(1)
cr2 = ClassicalRegister(1)
circuit = QuantumCircuit(qr1, cr1)
true_body = QuantumCircuit(qr2, cr2)
for_body = QuantumCircuit(3)
for_body.cx(0, 2)
true_body.for_loop(range(5), body=for_body, qubits=qr2, clbits=[])
circuit.if_else((cr1[0], 0), true_body, None, qr1[[1, 0, 2]], cr1)
dag = circuit_to_dag(circuit)
pass_ = CheckMap(coupling)
pass_.run(dag)
self.assertTrue(pass_.property_set["is_swap_mapped"])
def test_nested_controlflow_false(self):
"""Test nested controlflow with true evaluation."""
num_qubits = 4
coupling = CouplingMap.from_line(num_qubits)
qr1 = QuantumRegister(4, "qr")
qr2 = QuantumRegister(3, "qrif")
cr1 = ClassicalRegister(1)
cr2 = ClassicalRegister(1)
circuit = QuantumCircuit(qr1, cr1)
true_body = QuantumCircuit(qr2, cr2)
for_body = QuantumCircuit(3)
for_body.cx(0, 2)
true_body.for_loop(range(5), body=for_body, qubits=qr2, clbits=[])
circuit.if_else((cr1[0], 0), true_body, None, qr1[[0, 1, 2]], cr1)
dag = circuit_to_dag(circuit)
pass_ = CheckMap(coupling)
pass_.run(dag)
self.assertFalse(pass_.property_set["is_swap_mapped"])
def test_nested_conditional_unusual_bit_order(self):
"""Test that `CheckMap` succeeds when inner conditional blocks have clbits that are involved
in their own (nested conditionals), and the binding order is not the same as the
bit-definition order. See gh-10394."""
qr = QuantumRegister(2, "q")
cr1 = ClassicalRegister(2, "c1")
cr2 = ClassicalRegister(2, "c2")
# Note that the bits here are not in the same order as in the outer circuit object, but they
# are the same as the binding order in the `if_test`, so everything maps `{x: x}` and it
# should all be fine. This kind of thing is a staple of the control-flow builders.
inner_order = [cr2[0], cr1[0], cr2[1], cr1[1]]
inner = QuantumCircuit(qr, inner_order, cr1, cr2)
inner.cx(0, 1).c_if(cr2, 3)
outer = QuantumCircuit(qr, cr1, cr2)
outer.if_test((cr1, 3), inner, outer.qubits, inner_order)
pass_ = CheckMap(CouplingMap.from_line(2))
pass_(outer)
self.assertTrue(pass_.property_set["is_swap_mapped"])
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Gate cancellation pass testing"""
import unittest
import numpy as np
from qiskit.test import QiskitTestCase
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.circuit.library import U1Gate, RZGate, PhaseGate, CXGate, SXGate
from qiskit.circuit.parameter import Parameter
from qiskit.transpiler.target import Target
from qiskit.transpiler import PassManager, PropertySet
from qiskit.transpiler.passes import CommutationAnalysis, CommutativeCancellation, FixedPoint, Size
from qiskit.quantum_info import Operator
class TestCommutativeCancellation(QiskitTestCase):
"""Test the CommutativeCancellation pass."""
def setUp(self):
super().setUp()
self.com_pass_ = CommutationAnalysis()
self.pass_ = CommutativeCancellation()
self.pset = self.pass_.property_set = PropertySet()
def test_all_gates(self):
"""Test all gates on 1 and 2 qubits
q0:-[H]-[H]--[x]-[x]--[y]-[y]--[rz]-[rz]--[u1]-[u1]-[rx]-[rx]---.--.--.--.--.--.-
| | | | | |
q1:-------------------------------------------------------------X--X--Y--Y--.--.-
=
qr0:---[u1]---
qr1:----------
"""
qr = QuantumRegister(2, "q")
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[0])
circuit.x(qr[0])
circuit.x(qr[0])
circuit.y(qr[0])
circuit.y(qr[0])
circuit.rz(0.5, qr[0])
circuit.rz(0.5, qr[0])
circuit.append(U1Gate(0.5), [qr[0]]) # TODO this should work with Phase gates too
circuit.append(U1Gate(0.5), [qr[0]])
circuit.rx(0.5, qr[0])
circuit.rx(0.5, qr[0])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cy(qr[0], qr[1])
circuit.cy(qr[0], qr[1])
circuit.cz(qr[0], qr[1])
circuit.cz(qr[0], qr[1])
passmanager = PassManager()
passmanager.append(CommutativeCancellation())
new_circuit = passmanager.run(circuit)
expected = QuantumCircuit(qr)
expected.append(RZGate(2.0), [qr[0]])
expected.rx(1.0, qr[0])
self.assertEqual(expected, new_circuit)
def test_commutative_circuit1(self):
"""A simple circuit where three CNOTs commute, the first and the last cancel.
qr0:----.---------------.-- qr0:------------
| |
qr1:---(+)-----(+)-----(+)- = qr1:-------(+)--
| |
qr2:---[H]------.---------- qr2:---[H]--.---
"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.h(qr[2])
circuit.cx(qr[2], qr[1])
circuit.cx(qr[0], qr[1])
passmanager = PassManager()
passmanager.append(CommutativeCancellation())
new_circuit = passmanager.run(circuit)
expected = QuantumCircuit(qr)
expected.h(qr[2])
expected.cx(qr[2], qr[1])
self.assertEqual(expected, new_circuit)
def test_consecutive_cnots(self):
"""A simple circuit equals identity
qr0:----.- ----.-- qr0:------------
| |
qr1:---(+)----(+)- = qr1:------------
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
new_pm = PassManager(CommutativeCancellation())
new_circuit = new_pm.run(circuit)
expected = QuantumCircuit(qr)
self.assertEqual(expected, new_circuit)
def test_consecutive_cnots2(self):
"""
Two CNOTs that equals identity, with rotation gates inserted.
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.rx(np.pi, qr[0])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.rx(np.pi, qr[0])
passmanager = PassManager()
passmanager.append(
[CommutationAnalysis(), CommutativeCancellation(), Size(), FixedPoint("size")],
do_while=lambda property_set: not property_set["size_fixed_point"],
)
new_circuit = passmanager.run(circuit)
expected = QuantumCircuit(qr)
self.assertEqual(expected, new_circuit)
def test_2_alternating_cnots(self):
"""A simple circuit where nothing should be cancelled.
qr0:----.- ---(+)- qr0:----.----(+)-
| | | |
qr1:---(+)-----.-- = qr1:---(+)----.--
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[0])
new_pm = PassManager(CommutativeCancellation())
new_circuit = new_pm.run(circuit)
expected = QuantumCircuit(qr)
expected.cx(qr[0], qr[1])
expected.cx(qr[1], qr[0])
self.assertEqual(expected, new_circuit)
def test_control_bit_of_cnot(self):
"""A simple circuit where nothing should be cancelled.
qr0:----.------[X]------.-- qr0:----.------[X]------.--
| | | |
qr1:---(+)-------------(+)- = qr1:---(+)-------------(+)-
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.x(qr[0])
circuit.cx(qr[0], qr[1])
new_pm = PassManager(CommutativeCancellation())
new_circuit = new_pm.run(circuit)
expected = QuantumCircuit(qr)
expected.cx(qr[0], qr[1])
expected.x(qr[0])
expected.cx(qr[0], qr[1])
self.assertEqual(expected, new_circuit)
def test_control_bit_of_cnot1(self):
"""A simple circuit where the two cnots shoule be cancelled.
qr0:----.------[Z]------.-- qr0:---[Z]---
| |
qr1:---(+)-------------(+)- = qr1:---------
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.z(qr[0])
circuit.cx(qr[0], qr[1])
new_pm = PassManager(CommutativeCancellation())
new_circuit = new_pm.run(circuit)
expected = QuantumCircuit(qr)
expected.z(qr[0])
self.assertEqual(expected, new_circuit)
def test_control_bit_of_cnot2(self):
"""A simple circuit where the two cnots shoule be cancelled.
qr0:----.------[T]------.-- qr0:---[T]---
| |
qr1:---(+)-------------(+)- = qr1:---------
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.t(qr[0])
circuit.cx(qr[0], qr[1])
new_pm = PassManager(CommutativeCancellation())
new_circuit = new_pm.run(circuit)
expected = QuantumCircuit(qr)
expected.t(qr[0])
self.assertEqual(expected, new_circuit)
def test_control_bit_of_cnot3(self):
"""A simple circuit where the two cnots shoule be cancelled.
qr0:----.------[Rz]------.-- qr0:---[Rz]---
| |
qr1:---(+)-------- -----(+)- = qr1:----------
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.rz(np.pi / 3, qr[0])
circuit.cx(qr[0], qr[1])
new_pm = PassManager(CommutativeCancellation())
new_circuit = new_pm.run(circuit)
expected = QuantumCircuit(qr)
expected.rz(np.pi / 3, qr[0])
self.assertEqual(expected, new_circuit)
def test_control_bit_of_cnot4(self):
"""A simple circuit where the two cnots shoule be cancelled.
qr0:----.------[T]------.-- qr0:---[T]---
| |
qr1:---(+)-------------(+)- = qr1:---------
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.t(qr[0])
circuit.cx(qr[0], qr[1])
new_pm = PassManager(CommutativeCancellation())
new_circuit = new_pm.run(circuit)
expected = QuantumCircuit(qr)
expected.t(qr[0])
self.assertEqual(expected, new_circuit)
def test_target_bit_of_cnot(self):
"""A simple circuit where nothing should be cancelled.
qr0:----.---------------.-- qr0:----.---------------.--
| | | |
qr1:---(+)-----[Z]-----(+)- = qr1:---(+)----[Z]------(+)-
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.z(qr[1])
circuit.cx(qr[0], qr[1])
new_pm = PassManager(CommutativeCancellation())
new_circuit = new_pm.run(circuit)
expected = QuantumCircuit(qr)
expected.cx(qr[0], qr[1])
expected.z(qr[1])
expected.cx(qr[0], qr[1])
self.assertEqual(expected, new_circuit)
def test_target_bit_of_cnot1(self):
"""A simple circuit where nothing should be cancelled.
qr0:----.---------------.-- qr0:----.---------------.--
| | | |
qr1:---(+)-----[T]-----(+)- = qr1:---(+)----[T]------(+)-
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.t(qr[1])
circuit.cx(qr[0], qr[1])
new_pm = PassManager(CommutativeCancellation())
new_circuit = new_pm.run(circuit)
expected = QuantumCircuit(qr)
expected.cx(qr[0], qr[1])
expected.t(qr[1])
expected.cx(qr[0], qr[1])
self.assertEqual(expected, new_circuit)
def test_target_bit_of_cnot2(self):
"""A simple circuit where nothing should be cancelled.
qr0:----.---------------.-- qr0:----.---------------.--
| | | |
qr1:---(+)-----[Rz]----(+)- = qr1:---(+)----[Rz]-----(+)-
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.rz(np.pi / 3, qr[1])
circuit.cx(qr[0], qr[1])
new_pm = PassManager(CommutativeCancellation())
new_circuit = new_pm.run(circuit)
expected = QuantumCircuit(qr)
expected.cx(qr[0], qr[1])
expected.rz(np.pi / 3, qr[1])
expected.cx(qr[0], qr[1])
self.assertEqual(expected, new_circuit)
def test_commutative_circuit2(self):
"""
A simple circuit where three CNOTs commute, the first and the last cancel,
also two X gates cancel and two Rz gates combine.
qr0:----.---------------.-------- qr0:-------------
| |
qr1:---(+)---(+)--[X]--(+)--[X]-- = qr1:--------(+)--
| |
qr2:---[Rz]---.---[Rz]-[T]--[S]-- qr2:--[U1]---.---
"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.rz(np.pi / 3, qr[2])
circuit.cx(qr[2], qr[1])
circuit.rz(np.pi / 3, qr[2])
circuit.t(qr[2])
circuit.s(qr[2])
circuit.x(qr[1])
circuit.cx(qr[0], qr[1])
circuit.x(qr[1])
passmanager = PassManager()
passmanager.append(CommutativeCancellation())
new_circuit = passmanager.run(circuit)
expected = QuantumCircuit(qr)
expected.append(RZGate(np.pi * 17 / 12), [qr[2]])
expected.cx(qr[2], qr[1])
expected.global_phase = (np.pi * 17 / 12 - (2 * np.pi / 3)) / 2
self.assertEqual(expected, new_circuit)
def test_commutative_circuit3(self):
"""
A simple circuit where three CNOTs commute, the first and the last cancel,
also two X gates cancel and two Rz gates combine.
qr0:-------.------------------.------------- qr0:-------------
| |
qr1:------(+)------(+)--[X]--(+)-------[X]-- = qr1:--------(+)--
| |
qr2:------[Rz]--.---.----.---[Rz]-[T]--[S]-- qr2:--[U1]---.---
| |
qr3:-[Rz]--[X]-(+)------(+)--[X]-[Rz]------- qr3:--[Rz]-------
"""
qr = QuantumRegister(4, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.rz(np.pi / 3, qr[2])
circuit.rz(np.pi / 3, qr[3])
circuit.x(qr[3])
circuit.cx(qr[2], qr[3])
circuit.cx(qr[2], qr[1])
circuit.cx(qr[2], qr[3])
circuit.rz(np.pi / 3, qr[2])
circuit.t(qr[2])
circuit.x(qr[3])
circuit.rz(np.pi / 3, qr[3])
circuit.s(qr[2])
circuit.x(qr[1])
circuit.cx(qr[0], qr[1])
circuit.x(qr[1])
passmanager = PassManager()
passmanager.append(
[CommutationAnalysis(), CommutativeCancellation(), Size(), FixedPoint("size")],
do_while=lambda property_set: not property_set["size_fixed_point"],
)
new_circuit = passmanager.run(circuit)
expected = QuantumCircuit(qr)
expected.append(RZGate(np.pi * 17 / 12), [qr[2]])
expected.append(RZGate(np.pi * 2 / 3), [qr[3]])
expected.cx(qr[2], qr[1])
self.assertEqual(
expected, new_circuit, msg=f"expected:\n{expected}\nnew_circuit:\n{new_circuit}"
)
def test_cnot_cascade(self):
"""
A cascade of CNOTs that equals identity.
"""
qr = QuantumRegister(10, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[2])
circuit.cx(qr[2], qr[3])
circuit.cx(qr[3], qr[4])
circuit.cx(qr[4], qr[5])
circuit.cx(qr[5], qr[6])
circuit.cx(qr[6], qr[7])
circuit.cx(qr[7], qr[8])
circuit.cx(qr[8], qr[9])
circuit.cx(qr[8], qr[9])
circuit.cx(qr[7], qr[8])
circuit.cx(qr[6], qr[7])
circuit.cx(qr[5], qr[6])
circuit.cx(qr[4], qr[5])
circuit.cx(qr[3], qr[4])
circuit.cx(qr[2], qr[3])
circuit.cx(qr[1], qr[2])
circuit.cx(qr[0], qr[1])
passmanager = PassManager()
# passmanager.append(CommutativeCancellation())
passmanager.append(
[CommutationAnalysis(), CommutativeCancellation(), Size(), FixedPoint("size")],
do_while=lambda property_set: not property_set["size_fixed_point"],
)
new_circuit = passmanager.run(circuit)
expected = QuantumCircuit(qr)
self.assertEqual(expected, new_circuit)
def test_cnot_cascade1(self):
"""
A cascade of CNOTs that equals identity, with rotation gates inserted.
"""
qr = QuantumRegister(10, "qr")
circuit = QuantumCircuit(qr)
circuit.rx(np.pi, qr[0])
circuit.rx(np.pi, qr[1])
circuit.rx(np.pi, qr[2])
circuit.rx(np.pi, qr[3])
circuit.rx(np.pi, qr[4])
circuit.rx(np.pi, qr[5])
circuit.rx(np.pi, qr[6])
circuit.rx(np.pi, qr[7])
circuit.rx(np.pi, qr[8])
circuit.rx(np.pi, qr[9])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[2])
circuit.cx(qr[2], qr[3])
circuit.cx(qr[3], qr[4])
circuit.cx(qr[4], qr[5])
circuit.cx(qr[5], qr[6])
circuit.cx(qr[6], qr[7])
circuit.cx(qr[7], qr[8])
circuit.cx(qr[8], qr[9])
circuit.cx(qr[8], qr[9])
circuit.cx(qr[7], qr[8])
circuit.cx(qr[6], qr[7])
circuit.cx(qr[5], qr[6])
circuit.cx(qr[4], qr[5])
circuit.cx(qr[3], qr[4])
circuit.cx(qr[2], qr[3])
circuit.cx(qr[1], qr[2])
circuit.cx(qr[0], qr[1])
circuit.rx(np.pi, qr[0])
circuit.rx(np.pi, qr[1])
circuit.rx(np.pi, qr[2])
circuit.rx(np.pi, qr[3])
circuit.rx(np.pi, qr[4])
circuit.rx(np.pi, qr[5])
circuit.rx(np.pi, qr[6])
circuit.rx(np.pi, qr[7])
circuit.rx(np.pi, qr[8])
circuit.rx(np.pi, qr[9])
passmanager = PassManager()
# passmanager.append(CommutativeCancellation())
passmanager.append(
[CommutationAnalysis(), CommutativeCancellation(), Size(), FixedPoint("size")],
do_while=lambda property_set: not property_set["size_fixed_point"],
)
new_circuit = passmanager.run(circuit)
expected = QuantumCircuit(qr)
self.assertEqual(expected, new_circuit)
def test_conditional_gates_dont_commute(self):
"""Conditional gates do not commute and do not cancel"""
# ┌───┐┌─┐
# q_0: ┤ H ├┤M├─────────────
# └───┘└╥┘ ┌─┐
# q_1: ──■───╫────■───┤M├───
# ┌─┴─┐ ║ ┌─┴─┐ └╥┘┌─┐
# q_2: ┤ X ├─╫──┤ X ├──╫─┤M├
# └───┘ ║ └─╥─┘ ║ └╥┘
# ║ ┌──╨──┐ ║ ║
# c: 2/══════╩═╡ 0x0 ╞═╩══╩═
# 0 └─────┘ 0 1
circuit = QuantumCircuit(3, 2)
circuit.h(0)
circuit.measure(0, 0)
circuit.cx(1, 2)
circuit.cx(1, 2).c_if(circuit.cregs[0], 0)
circuit.measure([1, 2], [0, 1])
new_pm = PassManager(CommutativeCancellation())
new_circuit = new_pm.run(circuit)
self.assertEqual(circuit, new_circuit)
def test_basis_01(self):
"""Test basis priority change, phase gate"""
circuit = QuantumCircuit(1)
circuit.s(0)
circuit.z(0)
circuit.t(0)
circuit.rz(np.pi, 0)
passmanager = PassManager()
passmanager.append(CommutativeCancellation(basis_gates=["cx", "p", "sx"]))
new_circuit = passmanager.run(circuit)
expected = QuantumCircuit(1)
expected.rz(11 * np.pi / 4, 0)
expected.global_phase = 11 * np.pi / 4 / 2 - np.pi / 2
self.assertEqual(new_circuit, expected)
def test_target_basis_01(self):
"""Test basis priority change, phase gate, with target."""
circuit = QuantumCircuit(1)
circuit.s(0)
circuit.z(0)
circuit.t(0)
circuit.rz(np.pi, 0)
theta = Parameter("theta")
target = Target(num_qubits=2)
target.add_instruction(CXGate())
target.add_instruction(PhaseGate(theta))
target.add_instruction(SXGate())
passmanager = PassManager()
passmanager.append(CommutativeCancellation(target=target))
new_circuit = passmanager.run(circuit)
expected = QuantumCircuit(1)
expected.rz(11 * np.pi / 4, 0)
expected.global_phase = 11 * np.pi / 4 / 2 - np.pi / 2
self.assertEqual(new_circuit, expected)
def test_basis_02(self):
"""Test basis priority change, Rz gate"""
circuit = QuantumCircuit(1)
circuit.s(0)
circuit.z(0)
circuit.t(0)
passmanager = PassManager()
passmanager.append(CommutativeCancellation(basis_gates=["cx", "rz", "sx"]))
new_circuit = passmanager.run(circuit)
expected = QuantumCircuit(1)
expected.rz(7 * np.pi / 4, 0)
expected.global_phase = 7 * np.pi / 4 / 2
self.assertEqual(new_circuit, expected)
def test_basis_03(self):
"""Test no specified basis"""
circuit = QuantumCircuit(1)
circuit.s(0)
circuit.z(0)
circuit.t(0)
passmanager = PassManager()
passmanager.append(CommutativeCancellation())
new_circuit = passmanager.run(circuit)
expected = QuantumCircuit(1)
expected.s(0)
expected.z(0)
expected.t(0)
self.assertEqual(new_circuit, expected)
def test_basis_global_phase_01(self):
"""Test no specified basis, rz"""
circ = QuantumCircuit(1)
circ.rz(np.pi / 2, 0)
circ.p(np.pi / 2, 0)
circ.p(np.pi / 2, 0)
passmanager = PassManager()
passmanager.append(CommutativeCancellation())
ccirc = passmanager.run(circ)
self.assertEqual(Operator(circ), Operator(ccirc))
def test_basis_global_phase_02(self):
"""Test no specified basis, p"""
circ = QuantumCircuit(1)
circ.p(np.pi / 2, 0)
circ.rz(np.pi / 2, 0)
circ.p(np.pi / 2, 0)
passmanager = PassManager()
passmanager.append(CommutativeCancellation())
ccirc = passmanager.run(circ)
self.assertEqual(Operator(circ), Operator(ccirc))
def test_basis_global_phase_03(self):
"""Test global phase preservation if cummulative z-rotation is 0"""
circ = QuantumCircuit(1)
circ.rz(np.pi / 2, 0)
circ.p(np.pi / 2, 0)
circ.z(0)
passmanager = PassManager()
passmanager.append(CommutativeCancellation())
ccirc = passmanager.run(circ)
self.assertEqual(Operator(circ), Operator(ccirc))
def test_basic_classical_wires(self):
"""Test that transpile runs without internal errors when dealing with commutable operations
with classical controls. Regression test for gh-8553."""
original = QuantumCircuit(2, 1)
original.x(0).c_if(original.cregs[0], 0)
original.x(1).c_if(original.cregs[0], 0)
# This transpilation shouldn't change anything, but it should succeed. At one point it was
# triggering an internal logic error and crashing.
transpiled = PassManager([CommutativeCancellation()]).run(original)
self.assertEqual(original, transpiled)
def test_simple_if_else(self):
"""Test that the pass is not confused by if-else."""
base_test1 = QuantumCircuit(3, 3)
base_test1.x(1)
base_test1.cx(0, 1)
base_test1.x(1)
base_test2 = QuantumCircuit(3, 3)
base_test2.rz(0.1, 1)
base_test2.rz(0.1, 1)
test = QuantumCircuit(3, 3)
test.h(0)
test.x(0)
test.rx(0.2, 0)
test.measure(0, 0)
test.x(0)
test.if_else(
(test.clbits[0], True), base_test1.copy(), base_test2.copy(), test.qubits, test.clbits
)
expected = QuantumCircuit(3, 3)
expected.h(0)
expected.rx(np.pi + 0.2, 0)
expected.measure(0, 0)
expected.x(0)
expected_test1 = QuantumCircuit(3, 3)
expected_test1.cx(0, 1)
expected_test2 = QuantumCircuit(3, 3)
expected_test2.rz(0.2, 1)
expected.if_else(
(expected.clbits[0], True),
expected_test1.copy(),
expected_test2.copy(),
expected.qubits,
expected.clbits,
)
passmanager = PassManager([CommutationAnalysis(), CommutativeCancellation()])
new_circuit = passmanager.run(test)
self.assertEqual(new_circuit, expected)
def test_nested_control_flow(self):
"""Test that the pass does not add barrier into nested control flow."""
level2_test = QuantumCircuit(2, 1)
level2_test.cz(0, 1)
level2_test.cz(0, 1)
level2_test.cz(0, 1)
level2_test.measure(0, 0)
level1_test = QuantumCircuit(2, 1)
level1_test.for_loop((0,), None, level2_test.copy(), level1_test.qubits, level1_test.clbits)
level1_test.h(0)
level1_test.h(0)
level1_test.measure(0, 0)
test = QuantumCircuit(2, 1)
test.while_loop((test.clbits[0], True), level1_test.copy(), test.qubits, test.clbits)
test.measure(0, 0)
level2_expected = QuantumCircuit(2, 1)
level2_expected.cz(0, 1)
level2_expected.measure(0, 0)
level1_expected = QuantumCircuit(2, 1)
level1_expected.for_loop(
(0,), None, level2_expected.copy(), level1_expected.qubits, level1_expected.clbits
)
level1_expected.measure(0, 0)
expected = QuantumCircuit(2, 1)
expected.while_loop(
(expected.clbits[0], True), level1_expected.copy(), expected.qubits, expected.clbits
)
expected.measure(0, 0)
passmanager = PassManager([CommutationAnalysis(), CommutativeCancellation()])
new_circuit = passmanager.run(test)
self.assertEqual(new_circuit, expected)
def test_cancellation_not_crossing_block_boundary(self):
"""Test that the pass does cancel gates across control flow op block boundaries."""
test1 = QuantumCircuit(2, 2)
test1.x(1)
with test1.if_test((0, False)):
test1.cx(0, 1)
test1.x(1)
passmanager = PassManager([CommutationAnalysis(), CommutativeCancellation()])
new_circuit = passmanager.run(test1)
self.assertEqual(new_circuit, test1)
def test_cancellation_not_crossing_between_blocks(self):
"""Test that the pass does cancel gates in different control flow ops."""
test2 = QuantumCircuit(2, 2)
with test2.if_test((0, True)):
test2.x(1)
with test2.if_test((0, True)):
test2.cx(0, 1)
test2.x(1)
passmanager = PassManager([CommutationAnalysis(), CommutativeCancellation()])
new_circuit = passmanager.run(test2)
self.assertEqual(new_circuit, test2)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Depth pass testing"""
import unittest
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.converters import circuit_to_dag
from qiskit.transpiler.passes import CountOpsLongestPath
from qiskit.test import QiskitTestCase
class TestCountOpsLongestPathPass(QiskitTestCase):
"""Tests for CountOpsLongestPath analysis methods."""
def test_empty_dag(self):
"""Empty DAG has empty counts."""
circuit = QuantumCircuit()
dag = circuit_to_dag(circuit)
pass_ = CountOpsLongestPath()
_ = pass_.run(dag)
self.assertDictEqual(pass_.property_set["count_ops_longest_path"], {})
def test_just_qubits(self):
"""A dag with 9 operations (3 CXs, 2Xs, 2Ys and 2 Hs) on the longest
path
"""
# ┌───┐┌───┐┌───┐
# q0_0: ──■──┤ X ├┤ Y ├┤ H ├──■───────────────────■──
# ┌─┴─┐└───┘└───┘└───┘┌─┴─┐┌───┐┌───┐┌───┐┌─┴─┐
# q0_1: ┤ X ├───────────────┤ X ├┤ X ├┤ Y ├┤ H ├┤ X ├
# └───┘ └───┘└───┘└───┘└───┘└───┘
qr = QuantumRegister(2)
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.x(qr[0])
circuit.y(qr[0])
circuit.h(qr[0])
circuit.cx(qr[0], qr[1])
circuit.x(qr[1])
circuit.y(qr[1])
circuit.h(qr[1])
circuit.cx(qr[0], qr[1])
dag = circuit_to_dag(circuit)
pass_ = CountOpsLongestPath()
_ = pass_.run(dag)
count_ops = pass_.property_set["count_ops_longest_path"]
self.assertDictEqual(count_ops, {"cx": 3, "x": 2, "y": 2, "h": 2})
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Depth pass testing"""
import unittest
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.converters import circuit_to_dag
from qiskit.transpiler.passes import CountOps
from qiskit.test import QiskitTestCase
class TestCountOpsPass(QiskitTestCase):
"""Tests for CountOps analysis methods."""
def test_empty_dag(self):
"""Empty DAG has empty counts."""
circuit = QuantumCircuit()
dag = circuit_to_dag(circuit)
pass_ = CountOps()
_ = pass_.run(dag)
self.assertDictEqual(pass_.property_set["count_ops"], {})
def test_just_qubits(self):
"""A dag with 8 operations (6 CXs and 2 Hs)"""
# ┌───┐ ┌───┐┌───┐
# q0_0: ┤ H ├──■────■────■────■──┤ X ├┤ X ├
# ├───┤┌─┴─┐┌─┴─┐┌─┴─┐┌─┴─┐└─┬─┘└─┬─┘
# q0_1: ┤ H ├┤ X ├┤ X ├┤ X ├┤ X ├──■────■──
# └───┘└───┘└───┘└───┘└───┘
qr = QuantumRegister(2)
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[0])
circuit.cx(qr[1], qr[0])
dag = circuit_to_dag(circuit)
pass_ = CountOps()
_ = pass_.run(dag)
self.assertDictEqual(pass_.property_set["count_ops"], {"cx": 6, "h": 2})
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Tests for the CrosstalkAdaptiveSchedule transpiler pass.
"""
import unittest
from datetime import datetime
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.transpiler import Layout
from qiskit.transpiler.passes.optimization import CrosstalkAdaptiveSchedule
from qiskit.converters import circuit_to_dag
from qiskit.test import QiskitTestCase
from qiskit.compiler import transpile
from qiskit.providers.models import BackendProperties
from qiskit.providers.models.backendproperties import Nduv, Gate
from qiskit.utils import optionals
def make_noisy_qubit(t_1=50.0, t_2=50.0):
"""Create a qubit for BackendProperties"""
calib_time = datetime(year=2019, month=2, day=1, hour=0, minute=0, second=0)
return [
Nduv(name="T1", date=calib_time, unit="µs", value=t_1),
Nduv(name="T2", date=calib_time, unit="µs", value=t_2),
Nduv(name="frequency", date=calib_time, unit="GHz", value=5.0),
Nduv(name="readout_error", date=calib_time, unit="", value=0.01),
]
def create_fake_machine():
"""Create a 6 qubit machine to test crosstalk adaptive schedules"""
calib_time = datetime(year=2019, month=2, day=1, hour=0, minute=0, second=0)
qubit_list = []
for _ in range(6):
qubit_list.append(make_noisy_qubit())
cx01 = [
Nduv(date=calib_time, name="gate_error", unit="", value=0.05),
Nduv(date=calib_time, name="gate_length", unit="ns", value=500.0),
]
cx12 = [
Nduv(date=calib_time, name="gate_error", unit="", value=0.05),
Nduv(date=calib_time, name="gate_length", unit="ns", value=501.0),
]
cx23 = [
Nduv(date=calib_time, name="gate_error", unit="", value=0.05),
Nduv(date=calib_time, name="gate_length", unit="ns", value=502.0),
]
cx34 = [
Nduv(date=calib_time, name="gate_error", unit="", value=0.05),
Nduv(date=calib_time, name="gate_length", unit="ns", value=503.0),
]
cx45 = [
Nduv(date=calib_time, name="gate_error", unit="", value=0.05),
Nduv(date=calib_time, name="gate_length", unit="ns", value=504.0),
]
gcx01 = Gate(name="CX0_1", gate="cx", parameters=cx01, qubits=[0, 1])
gcx12 = Gate(name="CX1_2", gate="cx", parameters=cx12, qubits=[1, 2])
gcx23 = Gate(name="CX2_3", gate="cx", parameters=cx23, qubits=[2, 3])
gcx34 = Gate(name="CX3_4", gate="cx", parameters=cx34, qubits=[3, 4])
gcx45 = Gate(name="CX4_5", gate="cx", parameters=cx45, qubits=[4, 5])
u_1 = [
Nduv(date=calib_time, name="gate_error", unit="", value=0.001),
Nduv(date=calib_time, name="gate_length", unit="ns", value=100.0),
]
gu10 = Gate(name="u1_0", gate="u1", parameters=u_1, qubits=[0])
gu11 = Gate(name="u1_1", gate="u1", parameters=u_1, qubits=[1])
gu12 = Gate(name="u1_2", gate="u1", parameters=u_1, qubits=[2])
gu13 = Gate(name="u1_3", gate="u1", parameters=u_1, qubits=[3])
gu14 = Gate(name="u1_4", gate="u1", parameters=u_1, qubits=[4])
gu15 = Gate(name="u1_4", gate="u1", parameters=u_1, qubits=[5])
u_2 = [
Nduv(date=calib_time, name="gate_error", unit="", value=0.001),
Nduv(date=calib_time, name="gate_length", unit="ns", value=100.0),
]
gu20 = Gate(name="u2_0", gate="u2", parameters=u_2, qubits=[0])
gu21 = Gate(name="u2_1", gate="u2", parameters=u_2, qubits=[1])
gu22 = Gate(name="u2_2", gate="u2", parameters=u_2, qubits=[2])
gu23 = Gate(name="u2_3", gate="u2", parameters=u_2, qubits=[3])
gu24 = Gate(name="u2_4", gate="u2", parameters=u_2, qubits=[4])
gu25 = Gate(name="u2_4", gate="u2", parameters=u_2, qubits=[5])
u_3 = [
Nduv(date=calib_time, name="gate_error", unit="", value=0.001),
Nduv(date=calib_time, name="gate_length", unit="ns", value=100.0),
]
gu30 = Gate(name="u3_0", gate="u3", parameters=u_3, qubits=[0])
gu31 = Gate(name="u3_1", gate="u3", parameters=u_3, qubits=[1])
gu32 = Gate(name="u3_2", gate="u3", parameters=u_3, qubits=[2])
gu33 = Gate(name="u3_3", gate="u3", parameters=u_3, qubits=[3])
gu34 = Gate(name="u3_4", gate="u3", parameters=u_3, qubits=[4])
gu35 = Gate(name="u3_5", gate="u3", parameters=u_3, qubits=[5])
gate_list = [
gcx01,
gcx12,
gcx23,
gcx34,
gcx45,
gu10,
gu11,
gu12,
gu13,
gu14,
gu15,
gu20,
gu21,
gu22,
gu23,
gu24,
gu25,
gu30,
gu31,
gu32,
gu33,
gu34,
gu35,
]
bprop = BackendProperties(
last_update_date=calib_time,
backend_name="test_backend",
qubits=qubit_list,
backend_version="1.0.0",
gates=gate_list,
general=[],
)
return bprop
@unittest.skipIf(not optionals.HAS_Z3, "z3-solver not installed.")
class TestCrosstalk(QiskitTestCase):
"""
Tests for crosstalk adaptivity
"""
def test_schedule_length1(self):
"""Testing with high crosstalk between CNOT 0,1 and CNOT 2,3"""
bprop = create_fake_machine()
crosstalk_prop = {}
crosstalk_prop[(0, 1)] = {(2, 3): 0.2}
crosstalk_prop[(2, 3)] = {(0, 1): 0.05, (4, 5): 0.05}
crosstalk_prop[(4, 5)] = {(2, 3): 0.05}
crosstalk_prop[(1, 2)] = {(3, 4): 0.05}
crosstalk_prop[(3, 4)] = {(1, 2): 0.05}
qr = QuantumRegister(6, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.cx(qr[2], qr[3])
mapping = [0, 1, 2, 3, 4, 5]
layout = Layout({qr[i]: mapping[i] for i in range(6)})
new_circ = transpile(circuit, initial_layout=layout, basis_gates=["u1", "u2", "u3", "cx"])
dag = circuit_to_dag(new_circ)
pass_ = CrosstalkAdaptiveSchedule(bprop, crosstalk_prop)
scheduled_dag = pass_.run(dag)
self.assertEqual(scheduled_dag.depth(), 3)
def test_schedule_length2(self):
"""Testing with no crosstalk between CNOT 0,1 and CNOT 2,3"""
bprop = create_fake_machine()
crosstalk_prop = {}
crosstalk_prop[(0, 1)] = {(2, 3): 0.05}
crosstalk_prop[(2, 3)] = {(0, 1): 0.05, (4, 5): 0.05}
crosstalk_prop[(4, 5)] = {(2, 3): 0.05}
crosstalk_prop[(1, 2)] = {(3, 4): 0.05}
crosstalk_prop[(3, 4)] = {(1, 2): 0.05}
qr = QuantumRegister(6, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.cx(qr[2], qr[3])
mapping = [0, 1, 2, 3, 4, 5]
layout = Layout({qr[i]: mapping[i] for i in range(6)})
new_circ = transpile(circuit, initial_layout=layout, basis_gates=["u1", "u2", "u3", "cx"])
dag = circuit_to_dag(new_circ)
pass_ = CrosstalkAdaptiveSchedule(bprop, crosstalk_prop)
scheduled_dag = pass_.run(dag)
self.assertEqual(scheduled_dag.depth(), 1)
def test_schedule_length3(self):
"""Testing with repeated calls to run"""
bprop = create_fake_machine()
crosstalk_prop = {}
crosstalk_prop[(0, 1)] = {(2, 3): 0.2}
crosstalk_prop[(2, 3)] = {(0, 1): 0.05, (4, 5): 0.05}
crosstalk_prop[(4, 5)] = {(2, 3): 0.05}
crosstalk_prop[(1, 2)] = {(3, 4): 0.05}
crosstalk_prop[(3, 4)] = {(1, 2): 0.05}
qr = QuantumRegister(6, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.cx(qr[2], qr[3])
mapping = [0, 1, 2, 3, 4, 5]
layout = Layout({qr[i]: mapping[i] for i in range(6)})
new_circ = transpile(circuit, initial_layout=layout, basis_gates=["u1", "u2", "u3", "cx"])
dag = circuit_to_dag(new_circ)
pass_ = CrosstalkAdaptiveSchedule(bprop, crosstalk_prop)
scheduled_dag1 = pass_.run(dag)
scheduled_dag2 = pass_.run(dag)
self.assertEqual(scheduled_dag1.depth(), 3)
self.assertEqual(scheduled_dag2.depth(), 3)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the CSPLayout pass"""
import unittest
from time import process_time
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.transpiler import CouplingMap
from qiskit.transpiler.passes import CSPLayout
from qiskit.converters import circuit_to_dag
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import FakeTenerife, FakeRueschlikon, FakeTokyo, FakeYorktownV2
from qiskit.utils import optionals
@unittest.skipUnless(optionals.HAS_CONSTRAINT, "needs python-constraint")
class TestCSPLayout(QiskitTestCase):
"""Tests the CSPLayout pass"""
seed = 42
def test_2q_circuit_2q_coupling(self):
"""A simple example, without considering the direction
0 - 1
qr1 - qr0
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0]) # qr1 -> qr0
dag = circuit_to_dag(circuit)
pass_ = CSPLayout(CouplingMap([[0, 1]]), strict_direction=False, seed=self.seed)
pass_.run(dag)
layout = pass_.property_set["layout"]
self.assertEqual(layout[qr[0]], 1)
self.assertEqual(layout[qr[1]], 0)
self.assertEqual(pass_.property_set["CSPLayout_stop_reason"], "solution found")
def test_3q_circuit_5q_coupling(self):
"""3 qubits in Tenerife, without considering the direction
qr1
/ |
qr0 - qr2 - 3
| /
4
"""
cmap5 = FakeTenerife().configuration().coupling_map
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0]) # qr1 -> qr0
circuit.cx(qr[0], qr[2]) # qr0 -> qr2
circuit.cx(qr[1], qr[2]) # qr1 -> qr2
dag = circuit_to_dag(circuit)
pass_ = CSPLayout(CouplingMap(cmap5), strict_direction=False, seed=self.seed)
pass_.run(dag)
layout = pass_.property_set["layout"]
self.assertEqual(layout[qr[0]], 3)
self.assertEqual(layout[qr[1]], 2)
self.assertEqual(layout[qr[2]], 4)
self.assertEqual(pass_.property_set["CSPLayout_stop_reason"], "solution found")
def test_3q_circuit_5q_coupling_with_target(self):
"""3 qubits in Yorktown, without considering the direction
qr1
/ |
qr0 - qr2 - 3
| /
4
"""
target = FakeYorktownV2().target
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0]) # qr1 -> qr0
circuit.cx(qr[0], qr[2]) # qr0 -> qr2
circuit.cx(qr[1], qr[2]) # qr1 -> qr2
dag = circuit_to_dag(circuit)
pass_ = CSPLayout(target, strict_direction=False, seed=self.seed)
pass_.run(dag)
layout = pass_.property_set["layout"]
self.assertEqual(layout[qr[0]], 3)
self.assertEqual(layout[qr[1]], 2)
self.assertEqual(layout[qr[2]], 4)
self.assertEqual(pass_.property_set["CSPLayout_stop_reason"], "solution found")
def test_9q_circuit_16q_coupling(self):
"""9 qubits in Rueschlikon, without considering the direction
q0[1] - q0[0] - q1[3] - q0[3] - q1[0] - q1[1] - q1[2] - 8
| | | | | | | |
q0[2] - q1[4] -- 14 ---- 13 ---- 12 ---- 11 ---- 10 --- 9
"""
cmap16 = FakeRueschlikon().configuration().coupling_map
qr0 = QuantumRegister(4, "q0")
qr1 = QuantumRegister(5, "q1")
circuit = QuantumCircuit(qr0, qr1)
circuit.cx(qr0[1], qr0[2]) # q0[1] -> q0[2]
circuit.cx(qr0[0], qr1[3]) # q0[0] -> q1[3]
circuit.cx(qr1[4], qr0[2]) # q1[4] -> q0[2]
dag = circuit_to_dag(circuit)
pass_ = CSPLayout(CouplingMap(cmap16), strict_direction=False, seed=self.seed)
pass_.run(dag)
layout = pass_.property_set["layout"]
self.assertEqual(layout[qr0[0]], 9)
self.assertEqual(layout[qr0[1]], 6)
self.assertEqual(layout[qr0[2]], 7)
self.assertEqual(layout[qr0[3]], 5)
self.assertEqual(layout[qr1[0]], 14)
self.assertEqual(layout[qr1[1]], 12)
self.assertEqual(layout[qr1[2]], 1)
self.assertEqual(layout[qr1[3]], 8)
self.assertEqual(layout[qr1[4]], 10)
self.assertEqual(pass_.property_set["CSPLayout_stop_reason"], "solution found")
def test_2q_circuit_2q_coupling_sd(self):
"""A simple example, considering the direction
0 -> 1
qr1 -> qr0
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0]) # qr1 -> qr0
dag = circuit_to_dag(circuit)
pass_ = CSPLayout(CouplingMap([[0, 1]]), strict_direction=True, seed=self.seed)
pass_.run(dag)
layout = pass_.property_set["layout"]
self.assertEqual(layout[qr[0]], 1)
self.assertEqual(layout[qr[1]], 0)
self.assertEqual(pass_.property_set["CSPLayout_stop_reason"], "solution found")
def test_3q_circuit_5q_coupling_sd(self):
"""3 qubits in Tenerife, considering the direction
qr0
↙ ↑
qr2 ← qr1 ← 3
↑ ↙
4
"""
cmap5 = FakeTenerife().configuration().coupling_map
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0]) # qr1 -> qr0
circuit.cx(qr[0], qr[2]) # qr0 -> qr2
circuit.cx(qr[1], qr[2]) # qr1 -> qr2
dag = circuit_to_dag(circuit)
pass_ = CSPLayout(CouplingMap(cmap5), strict_direction=True, seed=self.seed)
pass_.run(dag)
layout = pass_.property_set["layout"]
self.assertEqual(layout[qr[0]], 1)
self.assertEqual(layout[qr[1]], 2)
self.assertEqual(layout[qr[2]], 0)
self.assertEqual(pass_.property_set["CSPLayout_stop_reason"], "solution found")
def test_9q_circuit_16q_coupling_sd(self):
"""9 qubits in Rueschlikon, considering the direction
q0[1] → q0[0] → q1[3] → q0[3] ← q1[0] ← q1[1] → q1[2] ← 8
↓ ↑ ↓ ↓ ↑ ↓ ↓ ↑
q0[2] ← q1[4] → 14 ← 13 ← 12 → 11 → 10 ← 9
"""
cmap16 = FakeRueschlikon().configuration().coupling_map
qr0 = QuantumRegister(4, "q0")
qr1 = QuantumRegister(5, "q1")
circuit = QuantumCircuit(qr0, qr1)
circuit.cx(qr0[1], qr0[2]) # q0[1] -> q0[2]
circuit.cx(qr0[0], qr1[3]) # q0[0] -> q1[3]
circuit.cx(qr1[4], qr0[2]) # q1[4] -> q0[2]
dag = circuit_to_dag(circuit)
pass_ = CSPLayout(CouplingMap(cmap16), strict_direction=True, seed=self.seed)
pass_.run(dag)
layout = pass_.property_set["layout"]
self.assertEqual(layout[qr0[0]], 9)
self.assertEqual(layout[qr0[1]], 6)
self.assertEqual(layout[qr0[2]], 7)
self.assertEqual(layout[qr0[3]], 5)
self.assertEqual(layout[qr1[0]], 14)
self.assertEqual(layout[qr1[1]], 12)
self.assertEqual(layout[qr1[2]], 1)
self.assertEqual(layout[qr1[3]], 10)
self.assertEqual(layout[qr1[4]], 8)
self.assertEqual(pass_.property_set["CSPLayout_stop_reason"], "solution found")
def test_5q_circuit_16q_coupling_no_solution(self):
"""5 qubits in Rueschlikon, no solution
q0[1] ↖ ↗ q0[2]
q0[0]
q0[3] ↙ ↘ q0[4]
"""
cmap16 = FakeRueschlikon().configuration().coupling_map
qr = QuantumRegister(5, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[2])
circuit.cx(qr[0], qr[3])
circuit.cx(qr[0], qr[4])
dag = circuit_to_dag(circuit)
pass_ = CSPLayout(CouplingMap(cmap16), seed=self.seed)
pass_.run(dag)
layout = pass_.property_set["layout"]
self.assertIsNone(layout)
self.assertEqual(pass_.property_set["CSPLayout_stop_reason"], "nonexistent solution")
@staticmethod
def create_hard_dag():
"""Creates a particularly hard circuit (returns its dag) for Tokyo"""
circuit = QuantumCircuit(20)
circuit.cx(13, 12)
circuit.cx(6, 0)
circuit.cx(5, 10)
circuit.cx(10, 7)
circuit.cx(5, 12)
circuit.cx(2, 15)
circuit.cx(16, 18)
circuit.cx(6, 4)
circuit.cx(10, 3)
circuit.cx(11, 10)
circuit.cx(18, 16)
circuit.cx(5, 12)
circuit.cx(4, 0)
circuit.cx(18, 16)
circuit.cx(2, 15)
circuit.cx(7, 8)
circuit.cx(9, 6)
circuit.cx(16, 17)
circuit.cx(9, 3)
circuit.cx(14, 12)
circuit.cx(2, 15)
circuit.cx(1, 16)
circuit.cx(5, 3)
circuit.cx(8, 12)
circuit.cx(2, 1)
circuit.cx(5, 3)
circuit.cx(13, 5)
circuit.cx(12, 14)
circuit.cx(12, 13)
circuit.cx(6, 4)
circuit.cx(15, 18)
circuit.cx(15, 18)
return circuit_to_dag(circuit)
def test_time_limit(self):
"""Hard to solve situations hit the time limit"""
dag = TestCSPLayout.create_hard_dag()
coupling_map = CouplingMap(FakeTokyo().configuration().coupling_map)
pass_ = CSPLayout(coupling_map, call_limit=None, time_limit=1)
start = process_time()
pass_.run(dag)
runtime = process_time() - start
self.assertLess(runtime, 3)
self.assertEqual(pass_.property_set["CSPLayout_stop_reason"], "time limit reached")
def test_call_limit(self):
"""Hard to solve situations hit the call limit"""
dag = TestCSPLayout.create_hard_dag()
coupling_map = CouplingMap(FakeTokyo().configuration().coupling_map)
pass_ = CSPLayout(coupling_map, call_limit=1, time_limit=None)
start = process_time()
pass_.run(dag)
runtime = process_time() - start
self.assertLess(runtime, 1)
self.assertEqual(pass_.property_set["CSPLayout_stop_reason"], "call limit reached")
def test_seed(self):
"""Different seeds yield different results"""
seed_1 = 42
seed_2 = 43
cmap5 = FakeTenerife().configuration().coupling_map
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0]) # qr1 -> qr0
circuit.cx(qr[0], qr[2]) # qr0 -> qr2
circuit.cx(qr[1], qr[2]) # qr1 -> qr2
dag = circuit_to_dag(circuit)
pass_1 = CSPLayout(CouplingMap(cmap5), seed=seed_1)
pass_1.run(dag)
layout_1 = pass_1.property_set["layout"]
pass_2 = CSPLayout(CouplingMap(cmap5), seed=seed_2)
pass_2.run(dag)
layout_2 = pass_2.property_set["layout"]
self.assertNotEqual(layout_1, layout_2)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for pass cancelling 2 consecutive CNOTs on the same qubits."""
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.circuit import Clbit, Qubit
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import CXCancellation
from qiskit.test import QiskitTestCase
class TestCXCancellation(QiskitTestCase):
"""Test the CXCancellation pass."""
def test_pass_cx_cancellation(self):
"""Test the cx cancellation pass.
It should cancel consecutive cx pairs on same qubits.
"""
qr = QuantumRegister(2)
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[0])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[0])
circuit.cx(qr[1], qr[0])
pass_manager = PassManager()
pass_manager.append(CXCancellation())
out_circuit = pass_manager.run(circuit)
expected = QuantumCircuit(qr)
expected.h(qr[0])
expected.h(qr[0])
self.assertEqual(out_circuit, expected)
def test_pass_cx_cancellation_intermixed_ops(self):
"""Cancellation shouldn't be affected by the order of ops on different qubits."""
qr = QuantumRegister(4)
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[2], qr[3])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[2], qr[3])
pass_manager = PassManager()
pass_manager.append(CXCancellation())
out_circuit = pass_manager.run(circuit)
expected = QuantumCircuit(qr)
expected.h(qr[0])
expected.h(qr[1])
self.assertEqual(out_circuit, expected)
def test_pass_cx_cancellation_chained_cx(self):
"""Include a test were not all operations can be cancelled."""
# ┌───┐
# q0_0: ┤ H ├──■─────────■───────
# ├───┤┌─┴─┐ ┌─┴─┐
# q0_1: ┤ H ├┤ X ├──■──┤ X ├─────
# └───┘└───┘┌─┴─┐└───┘
# q0_2: ──────────┤ X ├──■────■──
# └───┘┌─┴─┐┌─┴─┐
# q0_3: ───────────────┤ X ├┤ X ├
# └───┘└───┘
qr = QuantumRegister(4)
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[2])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[2], qr[3])
circuit.cx(qr[2], qr[3])
pass_manager = PassManager()
pass_manager.append(CXCancellation())
out_circuit = pass_manager.run(circuit)
# ┌───┐
# q0_0: ┤ H ├──■─────────■──
# ├───┤┌─┴─┐ ┌─┴─┐
# q0_1: ┤ H ├┤ X ├──■──┤ X ├
# └───┘└───┘┌─┴─┐└───┘
# q0_2: ──────────┤ X ├─────
# └───┘
# q0_3: ────────────────────
expected = QuantumCircuit(qr)
expected.h(qr[0])
expected.h(qr[1])
expected.cx(qr[0], qr[1])
expected.cx(qr[1], qr[2])
expected.cx(qr[0], qr[1])
self.assertEqual(out_circuit, expected)
def test_swapped_cx(self):
"""Test that CX isn't cancelled if there are intermediary ops."""
qr = QuantumRegister(4)
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0])
circuit.swap(qr[1], qr[2])
circuit.cx(qr[1], qr[0])
pass_manager = PassManager()
pass_manager.append(CXCancellation())
out_circuit = pass_manager.run(circuit)
self.assertEqual(out_circuit, circuit)
def test_inverted_cx(self):
"""Test that CX order dependence is respected."""
qr = QuantumRegister(4)
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[0])
circuit.cx(qr[0], qr[1])
pass_manager = PassManager()
pass_manager.append(CXCancellation())
out_circuit = pass_manager.run(circuit)
self.assertEqual(out_circuit, circuit)
def test_if_else(self):
"""Test that the pass recurses in a simple if-else."""
pass_ = CXCancellation()
inner_test = QuantumCircuit(4, 1)
inner_test.cx(0, 1)
inner_test.cx(0, 1)
inner_test.cx(2, 3)
inner_expected = QuantumCircuit(4, 1)
inner_expected.cx(2, 3)
test = QuantumCircuit(4, 1)
test.h(0)
test.measure(0, 0)
test.if_else((0, True), inner_test.copy(), inner_test.copy(), range(4), [0])
expected = QuantumCircuit(4, 1)
expected.h(0)
expected.measure(0, 0)
expected.if_else((0, True), inner_expected, inner_expected, range(4), [0])
self.assertEqual(pass_(test), expected)
def test_nested_control_flow(self):
"""Test that collection recurses into nested control flow."""
pass_ = CXCancellation()
qubits = [Qubit() for _ in [None] * 4]
clbit = Clbit()
inner_test = QuantumCircuit(qubits, [clbit])
inner_test.cx(0, 1)
inner_test.cx(0, 1)
inner_test.cx(2, 3)
inner_expected = QuantumCircuit(qubits, [clbit])
inner_expected.cx(2, 3)
true_body = QuantumCircuit(qubits, [clbit])
true_body.while_loop((clbit, True), inner_test.copy(), [0, 1, 2, 3], [0])
test = QuantumCircuit(qubits, [clbit])
test.for_loop(range(2), None, inner_test.copy(), [0, 1, 2, 3], [0])
test.if_else((clbit, True), true_body, None, [0, 1, 2, 3], [0])
expected_if_body = QuantumCircuit(qubits, [clbit])
expected_if_body.while_loop((clbit, True), inner_expected, [0, 1, 2, 3], [0])
expected = QuantumCircuit(qubits, [clbit])
expected.for_loop(range(2), None, inner_expected, [0, 1, 2, 3], [0])
expected.if_else((clbit, True), expected_if_body, None, [0, 1, 2, 3], [0])
self.assertEqual(pass_(test), expected)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""DAGFixedPoint pass testing"""
import unittest
from qiskit.transpiler.passes import DAGFixedPoint
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.converters import circuit_to_dag
from qiskit.test import QiskitTestCase
class TestFixedPointPass(QiskitTestCase):
"""Tests for PropertySet methods."""
def test_empty_dag_true(self):
"""Test the dag fixed point of an empty dag."""
circuit = QuantumCircuit()
dag = circuit_to_dag(circuit)
pass_ = DAGFixedPoint()
pass_.run(dag)
self.assertFalse(pass_.property_set["dag_fixed_point"])
pass_.run(dag)
self.assertTrue(pass_.property_set["dag_fixed_point"])
def test_nonempty_dag_false(self):
"""Test the dag false fixed point of a non-empty dag."""
qr = QuantumRegister(2)
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.cx(qr[0], qr[1])
dag = circuit_to_dag(circuit)
pass_ = DAGFixedPoint()
pass_.run(dag)
self.assertFalse(pass_.property_set["dag_fixed_point"])
dag.remove_all_ops_named("h")
pass_.run(dag)
self.assertFalse(pass_.property_set["dag_fixed_point"])
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""DAGFixedPoint pass testing"""
import unittest
from qiskit.transpiler.passes import DAGLongestPath
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.converters import circuit_to_dag
from qiskit.test import QiskitTestCase
class TestDAGLongestPathPass(QiskitTestCase):
"""Tests for PropertySet methods."""
def test_empty_dag_true(self):
"""Test the dag longest path of an empty dag."""
circuit = QuantumCircuit()
dag = circuit_to_dag(circuit)
pass_ = DAGLongestPath()
pass_.run(dag)
self.assertListEqual(pass_.property_set["dag_longest_path"], [])
def test_nonempty_dag_false(self):
"""Test the dag longest path non-empty dag.
path length = 11 = 9 ops + 2 qubits at start and end of path
"""
# ┌───┐┌───┐┌───┐
# q0_0: ──■──┤ X ├┤ Y ├┤ H ├──■───────────────────■──
# ┌─┴─┐└───┘└───┘└───┘┌─┴─┐┌───┐┌───┐┌───┐┌─┴─┐
# q0_1: ┤ X ├───────────────┤ X ├┤ X ├┤ Y ├┤ H ├┤ X ├
# └───┘ └───┘└───┘└───┘└───┘└───┘
qr = QuantumRegister(2)
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.x(qr[0])
circuit.y(qr[0])
circuit.h(qr[0])
circuit.cx(qr[0], qr[1])
circuit.x(qr[1])
circuit.y(qr[1])
circuit.h(qr[1])
circuit.cx(qr[0], qr[1])
dag = circuit_to_dag(circuit)
pass_ = DAGLongestPath()
pass_.run(dag)
self.assertEqual(len(pass_.property_set["dag_longest_path"]), 11)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the decompose pass"""
from numpy import pi
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.transpiler.passes import Decompose
from qiskit.converters import circuit_to_dag
from qiskit.circuit.library import HGate, CCXGate, U2Gate
from qiskit.quantum_info.operators import Operator
from qiskit.test import QiskitTestCase
class TestDecompose(QiskitTestCase):
"""Tests the decompose pass."""
def setUp(self):
super().setUp()
# example complex circuit
# ┌────────┐ ┌───┐┌─────────────┐
# q2_0: ┤0 ├────────────■──┤ H ├┤0 ├
# │ │ │ └───┘│ circuit-57 │
# q2_1: ┤1 gate1 ├────────────■───────┤1 ├
# │ │┌────────┐ │ └─────────────┘
# q2_2: ┤2 ├┤0 ├──■──────────────────────
# └────────┘│ │ │
# q2_3: ──────────┤1 gate2 ├──■──────────────────────
# │ │┌─┴─┐
# q2_4: ──────────┤2 ├┤ X ├────────────────────
# └────────┘└───┘
circ1 = QuantumCircuit(3)
circ1.h(0)
circ1.t(1)
circ1.x(2)
my_gate = circ1.to_gate(label="gate1")
circ2 = QuantumCircuit(3)
circ2.h(0)
circ2.cx(0, 1)
circ2.x(2)
my_gate2 = circ2.to_gate(label="gate2")
circ3 = QuantumCircuit(2)
circ3.x(0)
q_bits = QuantumRegister(5)
qc = QuantumCircuit(q_bits)
qc.append(my_gate, q_bits[:3])
qc.append(my_gate2, q_bits[2:])
qc.mct(q_bits[:4], q_bits[4])
qc.h(0)
qc.append(circ3, [0, 1])
self.complex_circuit = qc
def test_basic(self):
"""Test decompose a single H into u2."""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
dag = circuit_to_dag(circuit)
pass_ = Decompose(HGate)
after_dag = pass_.run(dag)
op_nodes = after_dag.op_nodes()
self.assertEqual(len(op_nodes), 1)
self.assertEqual(op_nodes[0].name, "u2")
def test_decompose_none(self):
"""Test decompose a single H into u2."""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
dag = circuit_to_dag(circuit)
pass_ = Decompose()
after_dag = pass_.run(dag)
op_nodes = after_dag.op_nodes()
self.assertEqual(len(op_nodes), 1)
self.assertEqual(op_nodes[0].name, "u2")
def test_decompose_only_h(self):
"""Test to decompose a single H, without the rest"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.cx(qr[0], qr[1])
dag = circuit_to_dag(circuit)
pass_ = Decompose(HGate)
after_dag = pass_.run(dag)
op_nodes = after_dag.op_nodes()
self.assertEqual(len(op_nodes), 2)
for node in op_nodes:
self.assertIn(node.name, ["cx", "u2"])
def test_decompose_toffoli(self):
"""Test decompose CCX."""
qr1 = QuantumRegister(2, "qr1")
qr2 = QuantumRegister(1, "qr2")
circuit = QuantumCircuit(qr1, qr2)
circuit.ccx(qr1[0], qr1[1], qr2[0])
dag = circuit_to_dag(circuit)
pass_ = Decompose(CCXGate)
after_dag = pass_.run(dag)
op_nodes = after_dag.op_nodes()
self.assertEqual(len(op_nodes), 15)
for node in op_nodes:
self.assertIn(node.name, ["h", "t", "tdg", "cx"])
def test_decompose_conditional(self):
"""Test decompose a 1-qubit gates with a conditional."""
qr = QuantumRegister(1, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr).c_if(cr, 1)
circuit.x(qr).c_if(cr, 1)
dag = circuit_to_dag(circuit)
pass_ = Decompose(HGate)
after_dag = pass_.run(dag)
ref_circuit = QuantumCircuit(qr, cr)
ref_circuit.append(U2Gate(0, pi), [qr[0]]).c_if(cr, 1)
ref_circuit.x(qr).c_if(cr, 1)
ref_dag = circuit_to_dag(ref_circuit)
self.assertEqual(after_dag, ref_dag)
def test_decompose_oversized_instruction(self):
"""Test decompose on a single-op gate that doesn't use all qubits."""
# ref: https://github.com/Qiskit/qiskit-terra/issues/3440
qc1 = QuantumCircuit(2)
qc1.x(0)
gate = qc1.to_gate()
qc2 = QuantumCircuit(2)
qc2.append(gate, [0, 1])
output = qc2.decompose()
self.assertEqual(qc1, output)
def test_decomposition_preserves_qregs_order(self):
"""Test decomposing a gate preserves it's definition registers order"""
qr = QuantumRegister(2, "qr1")
qc1 = QuantumCircuit(qr)
qc1.cx(1, 0)
gate = qc1.to_gate()
qr2 = QuantumRegister(2, "qr2")
qc2 = QuantumCircuit(qr2)
qc2.append(gate, qr2)
expected = QuantumCircuit(qr2)
expected.cx(1, 0)
self.assertEqual(qc2.decompose(), expected)
def test_decompose_global_phase_1q(self):
"""Test decomposition of circuit with global phase"""
qc1 = QuantumCircuit(1)
qc1.rz(0.1, 0)
qc1.ry(0.5, 0)
qc1.global_phase += pi / 4
qcd = qc1.decompose()
self.assertEqual(Operator(qc1), Operator(qcd))
def test_decompose_global_phase_2q(self):
"""Test decomposition of circuit with global phase"""
qc1 = QuantumCircuit(2, global_phase=pi / 4)
qc1.rz(0.1, 0)
qc1.rxx(0.2, 0, 1)
qcd = qc1.decompose()
self.assertEqual(Operator(qc1), Operator(qcd))
def test_decompose_global_phase_1q_composite(self):
"""Test decomposition of circuit with global phase in a composite gate."""
circ = QuantumCircuit(1, global_phase=pi / 2)
circ.x(0)
circ.h(0)
v = circ.to_gate()
qc1 = QuantumCircuit(1)
qc1.append(v, [0])
qcd = qc1.decompose()
self.assertEqual(Operator(qc1), Operator(qcd))
def test_decompose_only_h_gate(self):
"""Test decomposition parameters so that only a certain gate is decomposed."""
circ = QuantumCircuit(2, 1)
circ.h(0)
circ.cz(0, 1)
decom_circ = circ.decompose(["h"])
dag = circuit_to_dag(decom_circ)
self.assertEqual(len(dag.op_nodes()), 2)
self.assertEqual(dag.op_nodes()[0].name, "u2")
self.assertEqual(dag.op_nodes()[1].name, "cz")
def test_decompose_only_given_label(self):
"""Test decomposition parameters so that only a given label is decomposed."""
decom_circ = self.complex_circuit.decompose(["gate2"])
dag = circuit_to_dag(decom_circ)
self.assertEqual(len(dag.op_nodes()), 7)
self.assertEqual(dag.op_nodes()[0].op.label, "gate1")
self.assertEqual(dag.op_nodes()[1].name, "h")
self.assertEqual(dag.op_nodes()[2].name, "cx")
self.assertEqual(dag.op_nodes()[3].name, "x")
self.assertEqual(dag.op_nodes()[4].name, "mcx")
self.assertEqual(dag.op_nodes()[5].name, "h")
self.assertRegex(dag.op_nodes()[6].name, "circuit-")
def test_decompose_only_given_name(self):
"""Test decomposition parameters so that only given name is decomposed."""
decom_circ = self.complex_circuit.decompose(["mcx"])
dag = circuit_to_dag(decom_circ)
self.assertEqual(len(dag.op_nodes()), 13)
self.assertEqual(dag.op_nodes()[0].op.label, "gate1")
self.assertEqual(dag.op_nodes()[1].op.label, "gate2")
self.assertEqual(dag.op_nodes()[2].name, "h")
self.assertEqual(dag.op_nodes()[3].name, "cu1")
self.assertEqual(dag.op_nodes()[4].name, "rcccx")
self.assertEqual(dag.op_nodes()[5].name, "h")
self.assertEqual(dag.op_nodes()[6].name, "h")
self.assertEqual(dag.op_nodes()[7].name, "cu1")
self.assertEqual(dag.op_nodes()[8].name, "rcccx_dg")
self.assertEqual(dag.op_nodes()[9].name, "h")
self.assertEqual(dag.op_nodes()[10].name, "c3sx")
self.assertEqual(dag.op_nodes()[11].name, "h")
self.assertRegex(dag.op_nodes()[12].name, "circuit-")
def test_decompose_mixture_of_names_and_labels(self):
"""Test decomposition parameters so that mixture of names and labels is decomposed"""
decom_circ = self.complex_circuit.decompose(["mcx", "gate2"])
dag = circuit_to_dag(decom_circ)
self.assertEqual(len(dag.op_nodes()), 15)
self.assertEqual(dag.op_nodes()[0].op.label, "gate1")
self.assertEqual(dag.op_nodes()[1].name, "h")
self.assertEqual(dag.op_nodes()[2].name, "cx")
self.assertEqual(dag.op_nodes()[3].name, "x")
self.assertEqual(dag.op_nodes()[4].name, "h")
self.assertEqual(dag.op_nodes()[5].name, "cu1")
self.assertEqual(dag.op_nodes()[6].name, "rcccx")
self.assertEqual(dag.op_nodes()[7].name, "h")
self.assertEqual(dag.op_nodes()[8].name, "h")
self.assertEqual(dag.op_nodes()[9].name, "cu1")
self.assertEqual(dag.op_nodes()[10].name, "rcccx_dg")
self.assertEqual(dag.op_nodes()[11].name, "h")
self.assertEqual(dag.op_nodes()[12].name, "c3sx")
self.assertEqual(dag.op_nodes()[13].name, "h")
self.assertRegex(dag.op_nodes()[14].name, "circuit-")
def test_decompose_name_wildcards(self):
"""Test decomposition parameters so that name wildcards is decomposed"""
decom_circ = self.complex_circuit.decompose(["circuit-*"])
dag = circuit_to_dag(decom_circ)
self.assertEqual(len(dag.op_nodes()), 9)
self.assertEqual(dag.op_nodes()[0].name, "h")
self.assertEqual(dag.op_nodes()[1].name, "t")
self.assertEqual(dag.op_nodes()[2].name, "x")
self.assertEqual(dag.op_nodes()[3].name, "h")
self.assertRegex(dag.op_nodes()[4].name, "cx")
self.assertEqual(dag.op_nodes()[5].name, "x")
self.assertEqual(dag.op_nodes()[6].name, "mcx")
self.assertEqual(dag.op_nodes()[7].name, "h")
self.assertEqual(dag.op_nodes()[8].name, "x")
def test_decompose_label_wildcards(self):
"""Test decomposition parameters so that label wildcards is decomposed"""
decom_circ = self.complex_circuit.decompose(["gate*"])
dag = circuit_to_dag(decom_circ)
self.assertEqual(len(dag.op_nodes()), 9)
self.assertEqual(dag.op_nodes()[0].name, "h")
self.assertEqual(dag.op_nodes()[1].name, "t")
self.assertEqual(dag.op_nodes()[2].name, "x")
self.assertEqual(dag.op_nodes()[3].name, "h")
self.assertEqual(dag.op_nodes()[4].name, "cx")
self.assertEqual(dag.op_nodes()[5].name, "x")
self.assertEqual(dag.op_nodes()[6].name, "mcx")
self.assertEqual(dag.op_nodes()[7].name, "h")
self.assertRegex(dag.op_nodes()[8].name, "circuit-")
def test_decompose_empty_gate(self):
"""Test a gate where the definition is an empty circuit is decomposed."""
empty = QuantumCircuit(1)
circuit = QuantumCircuit(1)
circuit.append(empty.to_gate(), [0])
decomposed = circuit.decompose()
self.assertEqual(len(decomposed.data), 0)
def test_decompose_reps(self):
"""Test decompose reps function is decomposed correctly"""
decom_circ = self.complex_circuit.decompose(reps=2)
decomposed = self.complex_circuit.decompose().decompose()
self.assertEqual(decom_circ, decomposed)
def test_decompose_single_qubit_clbit(self):
"""Test the decomposition of a block with a single qubit and clbit works.
Regression test of Qiskit/qiskit-terra#8591.
"""
block = QuantumCircuit(1, 1)
block.h(0)
circuit = QuantumCircuit(1, 1)
circuit.append(block, [0], [0])
decomposed = circuit.decompose()
self.assertEqual(decomposed, block)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the DenseLayout pass"""
import unittest
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister
from qiskit.circuit import Parameter, Qubit
from qiskit.circuit.library import CXGate, UGate, ECRGate, RZGate
from qiskit.transpiler import CouplingMap, Target, InstructionProperties, TranspilerError
from qiskit.transpiler.passes import DenseLayout
from qiskit.converters import circuit_to_dag
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import FakeTokyo
from qiskit.transpiler.passes.layout.dense_layout import _build_error_matrix
class TestDenseLayout(QiskitTestCase):
"""Tests the DenseLayout pass"""
def setUp(self):
super().setUp()
self.cmap20 = FakeTokyo().configuration().coupling_map
self.target_19 = Target()
rng = np.random.default_rng(12345)
instruction_props = {
edge: InstructionProperties(
duration=rng.uniform(1e-7, 1e-6), error=rng.uniform(1e-4, 1e-3)
)
for edge in CouplingMap.from_heavy_hex(3).get_edges()
}
self.target_19.add_instruction(CXGate(), instruction_props)
def test_5q_circuit_20q_coupling(self):
"""Test finds dense 5q corner in 20q coupling map."""
qr = QuantumRegister(5, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[3])
circuit.cx(qr[3], qr[4])
circuit.cx(qr[3], qr[1])
circuit.cx(qr[0], qr[2])
dag = circuit_to_dag(circuit)
pass_ = DenseLayout(CouplingMap(self.cmap20))
pass_.run(dag)
layout = pass_.property_set["layout"]
self.assertEqual(layout[qr[0]], 11)
self.assertEqual(layout[qr[1]], 10)
self.assertEqual(layout[qr[2]], 6)
self.assertEqual(layout[qr[3]], 5)
self.assertEqual(layout[qr[4]], 0)
def test_6q_circuit_20q_coupling(self):
"""Test finds dense 5q corner in 20q coupling map."""
qr0 = QuantumRegister(3, "q0")
qr1 = QuantumRegister(3, "q1")
circuit = QuantumCircuit(qr0, qr1)
circuit.cx(qr0[0], qr1[2])
circuit.cx(qr1[1], qr0[2])
dag = circuit_to_dag(circuit)
pass_ = DenseLayout(CouplingMap(self.cmap20))
pass_.run(dag)
layout = pass_.property_set["layout"]
self.assertEqual(layout[qr0[0]], 11)
self.assertEqual(layout[qr0[1]], 10)
self.assertEqual(layout[qr0[2]], 6)
self.assertEqual(layout[qr1[0]], 5)
self.assertEqual(layout[qr1[1]], 1)
self.assertEqual(layout[qr1[2]], 0)
def test_5q_circuit_19q_target_with_noise(self):
"""Test layout works finds a dense 5q subgraph in a 19q heavy hex target."""
qr = QuantumRegister(5, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[3])
circuit.cx(qr[3], qr[4])
circuit.cx(qr[3], qr[1])
circuit.cx(qr[0], qr[2])
dag = circuit_to_dag(circuit)
pass_ = DenseLayout(target=self.target_19)
pass_.run(dag)
layout = pass_.property_set["layout"]
self.assertEqual(layout[qr[0]], 9)
self.assertEqual(layout[qr[1]], 3)
self.assertEqual(layout[qr[2]], 11)
self.assertEqual(layout[qr[3]], 15)
self.assertEqual(layout[qr[4]], 4)
def test_5q_circuit_19q_target_without_noise(self):
"""Test layout works finds a dense 5q subgraph in a 19q heavy hex target with no noise."""
qr = QuantumRegister(5, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[3])
circuit.cx(qr[3], qr[4])
circuit.cx(qr[3], qr[1])
circuit.cx(qr[0], qr[2])
dag = circuit_to_dag(circuit)
instruction_props = {edge: None for edge in CouplingMap.from_heavy_hex(3).get_edges()}
noiseless_target = Target()
noiseless_target.add_instruction(CXGate(), instruction_props)
pass_ = DenseLayout(target=noiseless_target)
pass_.run(dag)
layout = pass_.property_set["layout"]
self.assertEqual(layout[qr[0]], 1)
self.assertEqual(layout[qr[1]], 13)
self.assertEqual(layout[qr[2]], 0)
self.assertEqual(layout[qr[3]], 9)
self.assertEqual(layout[qr[4]], 3)
def test_ideal_target_no_coupling(self):
"""Test pass fails as expected if a target without edge constraints exists."""
qr = QuantumRegister(5, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[3])
circuit.cx(qr[3], qr[4])
circuit.cx(qr[3], qr[1])
circuit.cx(qr[0], qr[2])
dag = circuit_to_dag(circuit)
target = Target(num_qubits=19)
target.add_instruction(CXGate())
layout_pass = DenseLayout(target=target)
with self.assertRaises(TranspilerError):
layout_pass.run(dag)
def test_target_too_small_for_circuit(self):
"""Test error is raised when target is too small for circuit."""
target = Target()
target.add_instruction(
CXGate(), {edge: None for edge in CouplingMap.from_line(3).get_edges()}
)
dag = circuit_to_dag(QuantumCircuit(5))
layout_pass = DenseLayout(target=target)
with self.assertRaises(TranspilerError):
layout_pass.run(dag)
def test_19q_target_with_noise_error_matrix(self):
"""Test the error matrix construction works for a just cx target."""
expected_error_mat = np.zeros((19, 19))
for qargs, props in self.target_19["cx"].items():
error = props.error
expected_error_mat[qargs[0]][qargs[1]] = error
error_mat = _build_error_matrix(
self.target_19.num_qubits,
{i: i for i in range(self.target_19.num_qubits)},
target=self.target_19,
)[0]
np.testing.assert_array_equal(expected_error_mat, error_mat)
def test_multiple_gate_error_matrix(self):
"""Test error matrix ona small target with multiple gets on each qubit generates"""
target = Target(num_qubits=3)
phi = Parameter("phi")
lam = Parameter("lam")
theta = Parameter("theta")
target.add_instruction(
RZGate(phi), {(i,): InstructionProperties(duration=0, error=0) for i in range(3)}
)
target.add_instruction(
UGate(theta, phi, lam),
{(i,): InstructionProperties(duration=1e-7, error=1e-2) for i in range(3)},
)
cx_props = {
(0, 1): InstructionProperties(error=1e-3),
(0, 2): InstructionProperties(error=1e-3),
(1, 0): InstructionProperties(error=1e-3),
(1, 2): InstructionProperties(error=1e-3),
(2, 0): InstructionProperties(error=1e-3),
(2, 1): InstructionProperties(error=1e-3),
}
target.add_instruction(CXGate(), cx_props)
ecr_props = {
(0, 1): InstructionProperties(error=2e-2),
(1, 2): InstructionProperties(error=2e-2),
(2, 0): InstructionProperties(error=2e-2),
}
target.add_instruction(ECRGate(), ecr_props)
expected_error_matrix = np.array(
[
[1e-2, 2e-2, 1e-3],
[1e-3, 1e-2, 2e-2],
[2e-2, 1e-3, 1e-2],
]
)
error_mat = _build_error_matrix(
target.num_qubits, {i: i for i in range(target.num_qubits)}, target=target
)[0]
np.testing.assert_array_equal(expected_error_matrix, error_mat)
def test_5q_circuit_20q_with_if_else(self):
"""Test layout works finds a dense 5q subgraph in a 19q heavy hex target."""
qr = QuantumRegister(5, "q")
cr = ClassicalRegister(5)
circuit = QuantumCircuit(qr, cr)
true_body = QuantumCircuit(qr, cr)
false_body = QuantumCircuit(qr, cr)
true_body.cx(qr[0], qr[3])
true_body.cx(qr[3], qr[4])
false_body.cx(qr[3], qr[1])
false_body.cx(qr[0], qr[2])
circuit.if_else((cr, 0), true_body, false_body, qr, cr)
circuit.cx(0, 4)
dag = circuit_to_dag(circuit)
pass_ = DenseLayout(CouplingMap(self.cmap20))
pass_.run(dag)
layout = pass_.property_set["layout"]
self.assertEqual(layout[qr[0]], 11)
self.assertEqual(layout[qr[1]], 10)
self.assertEqual(layout[qr[2]], 6)
self.assertEqual(layout[qr[3]], 5)
self.assertEqual(layout[qr[4]], 0)
def test_loose_bit_circuit(self):
"""Test dense layout works with loose bits outside a register."""
bits = [Qubit() for _ in range(5)]
circuit = QuantumCircuit()
circuit.add_bits(bits)
circuit.h(3)
circuit.cx(3, 4)
circuit.cx(3, 2)
circuit.cx(3, 0)
circuit.cx(3, 1)
dag = circuit_to_dag(circuit)
pass_ = DenseLayout(CouplingMap(self.cmap20))
pass_.run(dag)
layout = pass_.property_set["layout"]
self.assertEqual(layout[bits[0]], 11)
self.assertEqual(layout[bits[1]], 10)
self.assertEqual(layout[bits[2]], 6)
self.assertEqual(layout[bits[3]], 5)
self.assertEqual(layout[bits[4]], 0)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Depth pass testing"""
import unittest
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.converters import circuit_to_dag
from qiskit.transpiler.passes import Depth
from qiskit.test import QiskitTestCase
class TestDepthPass(QiskitTestCase):
"""Tests for Depth analysis methods."""
def test_empty_dag(self):
"""Empty DAG has 0 depth"""
circuit = QuantumCircuit()
dag = circuit_to_dag(circuit)
pass_ = Depth()
_ = pass_.run(dag)
self.assertEqual(pass_.property_set["depth"], 0)
def test_just_qubits(self):
"""A dag with 8 operations and no classic bits"""
# ┌───┐ ┌───┐┌───┐
# q0_0: ┤ H ├──■────■────■────■──┤ X ├┤ X ├
# ├───┤┌─┴─┐┌─┴─┐┌─┴─┐┌─┴─┐└─┬─┘└─┬─┘
# q0_1: ┤ H ├┤ X ├┤ X ├┤ X ├┤ X ├──■────■──
# └───┘└───┘└───┘└───┘└───┘
qr = QuantumRegister(2)
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[0])
circuit.cx(qr[1], qr[0])
dag = circuit_to_dag(circuit)
pass_ = Depth()
_ = pass_.run(dag)
self.assertEqual(pass_.property_set["depth"], 7)
def test_depth_one(self):
"""A dag with operations in parallel and depth 1"""
qr = QuantumRegister(2)
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[1])
dag = circuit_to_dag(circuit)
pass_ = Depth()
_ = pass_.run(dag)
self.assertEqual(pass_.property_set["depth"], 1)
def test_depth_control_flow(self):
"""A DAG with control flow still gives an estimate."""
qc = QuantumCircuit(5, 1)
qc.h(0)
qc.measure(0, 0)
with qc.if_test((qc.clbits[0], True)) as else_:
qc.x(1)
qc.cx(2, 3)
with else_:
qc.x(1)
with qc.for_loop(range(3)):
qc.z(2)
with qc.for_loop((4, 0, 1)):
qc.z(2)
with qc.while_loop((qc.clbits[0], True)):
qc.h(0)
qc.measure(0, 0)
pass_ = Depth(recurse=True)
pass_(qc)
self.assertEqual(pass_.property_set["depth"], 16)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test dynamical decoupling insertion pass."""
import unittest
import numpy as np
from numpy import pi
from ddt import ddt, data
from qiskit.circuit import QuantumCircuit, Delay, Measure, Reset, Parameter
from qiskit.circuit.library import XGate, YGate, RXGate, UGate, CXGate, HGate
from qiskit.quantum_info import Operator
from qiskit.transpiler.instruction_durations import InstructionDurations
from qiskit.transpiler.passes import (
ASAPScheduleAnalysis,
ALAPScheduleAnalysis,
PadDynamicalDecoupling,
)
from qiskit.transpiler.passmanager import PassManager
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.transpiler.target import Target, InstructionProperties
from qiskit import pulse
from qiskit.test import QiskitTestCase
@ddt
class TestPadDynamicalDecoupling(QiskitTestCase):
"""Tests PadDynamicalDecoupling pass."""
def setUp(self):
"""Circuits to test DD on.
┌───┐
q_0: ┤ H ├──■────────────
└───┘┌─┴─┐
q_1: ─────┤ X ├──■───────
└───┘┌─┴─┐
q_2: ──────────┤ X ├──■──
└───┘┌─┴─┐
q_3: ───────────────┤ X ├
└───┘
┌──────────┐
q_0: ──■──┤ U(π,0,π) ├──────────■──
┌─┴─┐└──────────┘ ┌─┴─┐
q_1: ┤ X ├─────■───────────■──┤ X ├
└───┘ ┌─┴─┐ ┌─┐┌─┴─┐└───┘
q_2: ────────┤ X ├────┤M├┤ X ├─────
└───┘ └╥┘└───┘
c: 1/══════════════════╩═══════════
0
"""
super().setUp()
self.ghz4 = QuantumCircuit(4)
self.ghz4.h(0)
self.ghz4.cx(0, 1)
self.ghz4.cx(1, 2)
self.ghz4.cx(2, 3)
self.midmeas = QuantumCircuit(3, 1)
self.midmeas.cx(0, 1)
self.midmeas.cx(1, 2)
self.midmeas.u(pi, 0, pi, 0)
self.midmeas.measure(2, 0)
self.midmeas.cx(1, 2)
self.midmeas.cx(0, 1)
self.durations = InstructionDurations(
[
("h", 0, 50),
("cx", [0, 1], 700),
("cx", [1, 2], 200),
("cx", [2, 3], 300),
("x", None, 50),
("y", None, 50),
("u", None, 100),
("rx", None, 100),
("measure", None, 1000),
("reset", None, 1500),
]
)
def test_insert_dd_ghz(self):
"""Test DD gates are inserted in correct spots.
┌───┐ ┌────────────────┐ ┌───┐ »
q_0: ──────┤ H ├─────────■──┤ Delay(100[dt]) ├──────┤ X ├──────»
┌─────┴───┴─────┐ ┌─┴─┐└────────────────┘┌─────┴───┴─────┐»
q_1: ┤ Delay(50[dt]) ├─┤ X ├────────■─────────┤ Delay(50[dt]) ├»
├───────────────┴┐└───┘ ┌─┴─┐ └───────────────┘»
q_2: ┤ Delay(750[dt]) ├───────────┤ X ├───────────────■────────»
├────────────────┤ └───┘ ┌─┴─┐ »
q_3: ┤ Delay(950[dt]) ├─────────────────────────────┤ X ├──────»
└────────────────┘ └───┘ »
« ┌────────────────┐ ┌───┐ ┌────────────────┐
«q_0: ┤ Delay(200[dt]) ├──────┤ X ├───────┤ Delay(100[dt]) ├─────────────────
« └─────┬───┬──────┘┌─────┴───┴──────┐└─────┬───┬──────┘┌───────────────┐
«q_1: ──────┤ X ├───────┤ Delay(100[dt]) ├──────┤ X ├───────┤ Delay(50[dt]) ├
« └───┘ └────────────────┘ └───┘ └───────────────┘
«q_2: ───────────────────────────────────────────────────────────────────────
«
«q_3: ───────────────────────────────────────────────────────────────────────
«
"""
dd_sequence = [XGate(), XGate()]
pm = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(self.durations, dd_sequence),
]
)
ghz4_dd = pm.run(self.ghz4)
expected = self.ghz4.copy()
expected = expected.compose(Delay(50), [1], front=True)
expected = expected.compose(Delay(750), [2], front=True)
expected = expected.compose(Delay(950), [3], front=True)
expected = expected.compose(Delay(100), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(200), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(100), [0])
expected = expected.compose(Delay(50), [1])
expected = expected.compose(XGate(), [1])
expected = expected.compose(Delay(100), [1])
expected = expected.compose(XGate(), [1])
expected = expected.compose(Delay(50), [1])
self.assertEqual(ghz4_dd, expected)
def test_insert_dd_ghz_with_target(self):
"""Test DD gates are inserted in correct spots.
┌───┐ ┌────────────────┐ ┌───┐ »
q_0: ──────┤ H ├─────────■──┤ Delay(100[dt]) ├──────┤ X ├──────»
┌─────┴───┴─────┐ ┌─┴─┐└────────────────┘┌─────┴───┴─────┐»
q_1: ┤ Delay(50[dt]) ├─┤ X ├────────■─────────┤ Delay(50[dt]) ├»
├───────────────┴┐└───┘ ┌─┴─┐ └───────────────┘»
q_2: ┤ Delay(750[dt]) ├───────────┤ X ├───────────────■────────»
├────────────────┤ └───┘ ┌─┴─┐ »
q_3: ┤ Delay(950[dt]) ├─────────────────────────────┤ X ├──────»
└────────────────┘ └───┘ »
« ┌────────────────┐ ┌───┐ ┌────────────────┐
«q_0: ┤ Delay(200[dt]) ├──────┤ X ├───────┤ Delay(100[dt]) ├─────────────────
« └─────┬───┬──────┘┌─────┴───┴──────┐└─────┬───┬──────┘┌───────────────┐
«q_1: ──────┤ X ├───────┤ Delay(100[dt]) ├──────┤ X ├───────┤ Delay(50[dt]) ├
« └───┘ └────────────────┘ └───┘ └───────────────┘
«q_2: ───────────────────────────────────────────────────────────────────────
«
«q_3: ───────────────────────────────────────────────────────────────────────
«
"""
target = Target(num_qubits=4, dt=1)
target.add_instruction(HGate(), {(0,): InstructionProperties(duration=50)})
target.add_instruction(
CXGate(),
{
(0, 1): InstructionProperties(duration=700),
(1, 2): InstructionProperties(duration=200),
(2, 3): InstructionProperties(duration=300),
},
)
target.add_instruction(
XGate(), {(x,): InstructionProperties(duration=50) for x in range(4)}
)
target.add_instruction(
YGate(), {(x,): InstructionProperties(duration=50) for x in range(4)}
)
target.add_instruction(
UGate(Parameter("theta"), Parameter("phi"), Parameter("lambda")),
{(x,): InstructionProperties(duration=100) for x in range(4)},
)
target.add_instruction(
RXGate(Parameter("theta")),
{(x,): InstructionProperties(duration=100) for x in range(4)},
)
target.add_instruction(
Measure(), {(x,): InstructionProperties(duration=1000) for x in range(4)}
)
target.add_instruction(
Reset(), {(x,): InstructionProperties(duration=1500) for x in range(4)}
)
target.add_instruction(Delay(Parameter("t")), {(x,): None for x in range(4)})
dd_sequence = [XGate(), XGate()]
pm = PassManager(
[
ALAPScheduleAnalysis(target=target),
PadDynamicalDecoupling(target=target, dd_sequence=dd_sequence),
]
)
ghz4_dd = pm.run(self.ghz4)
expected = self.ghz4.copy()
expected = expected.compose(Delay(50), [1], front=True)
expected = expected.compose(Delay(750), [2], front=True)
expected = expected.compose(Delay(950), [3], front=True)
expected = expected.compose(Delay(100), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(200), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(100), [0])
expected = expected.compose(Delay(50), [1])
expected = expected.compose(XGate(), [1])
expected = expected.compose(Delay(100), [1])
expected = expected.compose(XGate(), [1])
expected = expected.compose(Delay(50), [1])
self.assertEqual(ghz4_dd, expected)
def test_insert_dd_ghz_one_qubit(self):
"""Test DD gates are inserted on only one qubit.
┌───┐ ┌────────────────┐ ┌───┐ »
q_0: ──────┤ H ├─────────■──┤ Delay(100[dt]) ├──────┤ X ├───────»
┌─────┴───┴─────┐ ┌─┴─┐└────────────────┘┌─────┴───┴──────┐»
q_1: ┤ Delay(50[dt]) ├─┤ X ├────────■─────────┤ Delay(300[dt]) ├»
├───────────────┴┐└───┘ ┌─┴─┐ └────────────────┘»
q_2: ┤ Delay(750[dt]) ├───────────┤ X ├───────────────■─────────»
├────────────────┤ └───┘ ┌─┴─┐ »
q_3: ┤ Delay(950[dt]) ├─────────────────────────────┤ X ├───────»
└────────────────┘ └───┘ »
meas: 4/═══════════════════════════════════════════════════════════»
»
« ┌────────────────┐┌───┐┌────────────────┐ ░ ┌─┐
« q_0: ┤ Delay(200[dt]) ├┤ X ├┤ Delay(100[dt]) ├─░─┤M├─────────
« └────────────────┘└───┘└────────────────┘ ░ └╥┘┌─┐
« q_1: ──────────────────────────────────────────░──╫─┤M├──────
« ░ ║ └╥┘┌─┐
« q_2: ──────────────────────────────────────────░──╫──╫─┤M├───
« ░ ║ ║ └╥┘┌─┐
« q_3: ──────────────────────────────────────────░──╫──╫──╫─┤M├
« ░ ║ ║ ║ └╥┘
«meas: 4/═════════════════════════════════════════════╩══╩══╩══╩═
« 0 1 2 3
"""
dd_sequence = [XGate(), XGate()]
pm = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(self.durations, dd_sequence, qubits=[0]),
]
)
ghz4_dd = pm.run(self.ghz4.measure_all(inplace=False))
expected = self.ghz4.copy()
expected = expected.compose(Delay(50), [1], front=True)
expected = expected.compose(Delay(750), [2], front=True)
expected = expected.compose(Delay(950), [3], front=True)
expected = expected.compose(Delay(100), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(200), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(100), [0])
expected = expected.compose(Delay(300), [1])
expected.measure_all()
self.assertEqual(ghz4_dd, expected)
def test_insert_dd_ghz_everywhere(self):
"""Test DD gates even on initial idle spots.
┌───┐ ┌────────────────┐┌───┐┌────────────────┐┌───┐»
q_0: ──────┤ H ├─────────■──┤ Delay(100[dt]) ├┤ Y ├┤ Delay(200[dt]) ├┤ Y ├»
┌─────┴───┴─────┐ ┌─┴─┐└────────────────┘└───┘└────────────────┘└───┘»
q_1: ┤ Delay(50[dt]) ├─┤ X ├───────────────────────────────────────────■──»
├───────────────┴┐├───┤┌────────────────┐┌───┐┌────────────────┐┌─┴─┐»
q_2: ┤ Delay(162[dt]) ├┤ Y ├┤ Delay(326[dt]) ├┤ Y ├┤ Delay(162[dt]) ├┤ X ├»
├────────────────┤├───┤├────────────────┤├───┤├────────────────┤└───┘»
q_3: ┤ Delay(212[dt]) ├┤ Y ├┤ Delay(426[dt]) ├┤ Y ├┤ Delay(212[dt]) ├─────»
└────────────────┘└───┘└────────────────┘└───┘└────────────────┘ »
« ┌────────────────┐
«q_0: ┤ Delay(100[dt]) ├─────────────────────────────────────────────
« ├───────────────┬┘┌───┐┌────────────────┐┌───┐┌───────────────┐
«q_1: ┤ Delay(50[dt]) ├─┤ Y ├┤ Delay(100[dt]) ├┤ Y ├┤ Delay(50[dt]) ├
« └───────────────┘ └───┘└────────────────┘└───┘└───────────────┘
«q_2: ────────■──────────────────────────────────────────────────────
« ┌─┴─┐
«q_3: ──────┤ X ├────────────────────────────────────────────────────
« └───┘
"""
dd_sequence = [YGate(), YGate()]
pm = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(self.durations, dd_sequence, skip_reset_qubits=False),
]
)
ghz4_dd = pm.run(self.ghz4)
expected = self.ghz4.copy()
expected = expected.compose(Delay(50), [1], front=True)
expected = expected.compose(Delay(162), [2], front=True)
expected = expected.compose(YGate(), [2], front=True)
expected = expected.compose(Delay(326), [2], front=True)
expected = expected.compose(YGate(), [2], front=True)
expected = expected.compose(Delay(162), [2], front=True)
expected = expected.compose(Delay(212), [3], front=True)
expected = expected.compose(YGate(), [3], front=True)
expected = expected.compose(Delay(426), [3], front=True)
expected = expected.compose(YGate(), [3], front=True)
expected = expected.compose(Delay(212), [3], front=True)
expected = expected.compose(Delay(100), [0])
expected = expected.compose(YGate(), [0])
expected = expected.compose(Delay(200), [0])
expected = expected.compose(YGate(), [0])
expected = expected.compose(Delay(100), [0])
expected = expected.compose(Delay(50), [1])
expected = expected.compose(YGate(), [1])
expected = expected.compose(Delay(100), [1])
expected = expected.compose(YGate(), [1])
expected = expected.compose(Delay(50), [1])
self.assertEqual(ghz4_dd, expected)
def test_insert_dd_ghz_xy4(self):
"""Test XY4 sequence of DD gates.
┌───┐ ┌───────────────┐ ┌───┐ ┌───────────────┐»
q_0: ──────┤ H ├─────────■──┤ Delay(37[dt]) ├──────┤ X ├──────┤ Delay(75[dt]) ├»
┌─────┴───┴─────┐ ┌─┴─┐└───────────────┘┌─────┴───┴─────┐└─────┬───┬─────┘»
q_1: ┤ Delay(50[dt]) ├─┤ X ├────────■────────┤ Delay(12[dt]) ├──────┤ X ├──────»
├───────────────┴┐└───┘ ┌─┴─┐ └───────────────┘ └───┘ »
q_2: ┤ Delay(750[dt]) ├───────────┤ X ├──────────────■─────────────────────────»
├────────────────┤ └───┘ ┌─┴─┐ »
q_3: ┤ Delay(950[dt]) ├────────────────────────────┤ X ├───────────────────────»
└────────────────┘ └───┘ »
« ┌───┐ ┌───────────────┐ ┌───┐ ┌───────────────┐»
«q_0: ──────┤ Y ├──────┤ Delay(76[dt]) ├──────┤ X ├──────┤ Delay(75[dt]) ├»
« ┌─────┴───┴─────┐└─────┬───┬─────┘┌─────┴───┴─────┐└─────┬───┬─────┘»
«q_1: ┤ Delay(25[dt]) ├──────┤ Y ├──────┤ Delay(26[dt]) ├──────┤ X ├──────»
« └───────────────┘ └───┘ └───────────────┘ └───┘ »
«q_2: ────────────────────────────────────────────────────────────────────»
« »
«q_3: ────────────────────────────────────────────────────────────────────»
« »
« ┌───┐ ┌───────────────┐
«q_0: ──────┤ Y ├──────┤ Delay(37[dt]) ├─────────────────
« ┌─────┴───┴─────┐└─────┬───┬─────┘┌───────────────┐
«q_1: ┤ Delay(25[dt]) ├──────┤ Y ├──────┤ Delay(12[dt]) ├
« └───────────────┘ └───┘ └───────────────┘
«q_2: ───────────────────────────────────────────────────
«
«q_3: ───────────────────────────────────────────────────
"""
dd_sequence = [XGate(), YGate(), XGate(), YGate()]
pm = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(self.durations, dd_sequence),
]
)
ghz4_dd = pm.run(self.ghz4)
expected = self.ghz4.copy()
expected = expected.compose(Delay(50), [1], front=True)
expected = expected.compose(Delay(750), [2], front=True)
expected = expected.compose(Delay(950), [3], front=True)
expected = expected.compose(Delay(37), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(75), [0])
expected = expected.compose(YGate(), [0])
expected = expected.compose(Delay(76), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(75), [0])
expected = expected.compose(YGate(), [0])
expected = expected.compose(Delay(37), [0])
expected = expected.compose(Delay(12), [1])
expected = expected.compose(XGate(), [1])
expected = expected.compose(Delay(25), [1])
expected = expected.compose(YGate(), [1])
expected = expected.compose(Delay(26), [1])
expected = expected.compose(XGate(), [1])
expected = expected.compose(Delay(25), [1])
expected = expected.compose(YGate(), [1])
expected = expected.compose(Delay(12), [1])
self.assertEqual(ghz4_dd, expected)
def test_insert_midmeas_hahn_alap(self):
"""Test a single X gate as Hahn echo can absorb in the downstream circuit.
global phase: 3π/2
┌────────────────┐ ┌───┐ ┌────────────────┐»
q_0: ────────■─────────┤ Delay(625[dt]) ├───────┤ X ├───────┤ Delay(625[dt]) ├»
┌─┴─┐ └────────────────┘┌──────┴───┴──────┐└────────────────┘»
q_1: ──────┤ X ├───────────────■─────────┤ Delay(1000[dt]) ├────────■─────────»
┌─────┴───┴──────┐ ┌─┴─┐ └───────┬─┬───────┘ ┌─┴─┐ »
q_2: ┤ Delay(700[dt]) ├──────┤ X ├───────────────┤M├──────────────┤ X ├───────»
└────────────────┘ └───┘ └╥┘ └───┘ »
c: 1/═════════════════════════════════════════════╩═══════════════════════════»
0 »
« ┌───────────────┐
«q_0: ┤ U(0,π/2,-π/2) ├───■──
« └───────────────┘ ┌─┴─┐
«q_1: ──────────────────┤ X ├
« ┌────────────────┐└───┘
«q_2: ┤ Delay(700[dt]) ├─────
« └────────────────┘
«c: 1/═══════════════════════
"""
dd_sequence = [XGate()]
pm = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(self.durations, dd_sequence),
]
)
midmeas_dd = pm.run(self.midmeas)
combined_u = UGate(0, -pi / 2, pi / 2)
expected = QuantumCircuit(3, 1)
expected.cx(0, 1)
expected.delay(625, 0)
expected.x(0)
expected.delay(625, 0)
expected.compose(combined_u, [0], inplace=True)
expected.delay(700, 2)
expected.cx(1, 2)
expected.delay(1000, 1)
expected.measure(2, 0)
expected.cx(1, 2)
expected.cx(0, 1)
expected.delay(700, 2)
expected.global_phase = pi / 2
self.assertEqual(midmeas_dd, expected)
# check the absorption into U was done correctly
self.assertEqual(Operator(combined_u), Operator(XGate()) & Operator(XGate()))
def test_insert_midmeas_hahn_asap(self):
"""Test a single X gate as Hahn echo can absorb in the upstream circuit.
┌──────────────────┐ ┌────────────────┐┌─────────┐»
q_0: ────────■─────────┤ U(3π/4,-π/2,π/2) ├─┤ Delay(600[dt]) ├┤ Rx(π/4) ├»
┌─┴─┐ └──────────────────┘┌┴────────────────┤└─────────┘»
q_1: ──────┤ X ├────────────────■──────────┤ Delay(1000[dt]) ├─────■─────»
┌─────┴───┴──────┐ ┌─┴─┐ └───────┬─┬───────┘ ┌─┴─┐ »
q_2: ┤ Delay(700[dt]) ├───────┤ X ├────────────────┤M├───────────┤ X ├───»
└────────────────┘ └───┘ └╥┘ └───┘ »
c: 1/═══════════════════════════════════════════════╩════════════════════»
0 »
« ┌────────────────┐
«q_0: ┤ Delay(600[dt]) ├──■──
« └────────────────┘┌─┴─┐
«q_1: ──────────────────┤ X ├
« ┌────────────────┐└───┘
«q_2: ┤ Delay(700[dt]) ├─────
« └────────────────┘
«c: 1/═══════════════════════
«
"""
dd_sequence = [RXGate(pi / 4)]
pm = PassManager(
[
ASAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(self.durations, dd_sequence),
]
)
midmeas_dd = pm.run(self.midmeas)
combined_u = UGate(3 * pi / 4, -pi / 2, pi / 2)
expected = QuantumCircuit(3, 1)
expected.cx(0, 1)
expected.compose(combined_u, [0], inplace=True)
expected.delay(600, 0)
expected.rx(pi / 4, 0)
expected.delay(600, 0)
expected.delay(700, 2)
expected.cx(1, 2)
expected.delay(1000, 1)
expected.measure(2, 0)
expected.cx(1, 2)
expected.cx(0, 1)
expected.delay(700, 2)
self.assertEqual(midmeas_dd, expected)
# check the absorption into U was done correctly
self.assertTrue(
Operator(XGate()).equiv(
Operator(UGate(3 * pi / 4, -pi / 2, pi / 2)) & Operator(RXGate(pi / 4))
)
)
def test_insert_ghz_uhrig(self):
"""Test custom spacing (following Uhrig DD [1]).
[1] Uhrig, G. "Keeping a quantum bit alive by optimized π-pulse sequences."
Physical Review Letters 98.10 (2007): 100504.
┌───┐ ┌──────────────┐ ┌───┐ ┌──────────────┐┌───┐»
q_0: ──────┤ H ├─────────■──┤ Delay(3[dt]) ├──────┤ X ├───────┤ Delay(8[dt]) ├┤ X ├»
┌─────┴───┴─────┐ ┌─┴─┐└──────────────┘┌─────┴───┴──────┐└──────────────┘└───┘»
q_1: ┤ Delay(50[dt]) ├─┤ X ├───────■────────┤ Delay(300[dt]) ├─────────────────────»
├───────────────┴┐└───┘ ┌─┴─┐ └────────────────┘ »
q_2: ┤ Delay(750[dt]) ├──────────┤ X ├──────────────■──────────────────────────────»
├────────────────┤ └───┘ ┌─┴─┐ »
q_3: ┤ Delay(950[dt]) ├───────────────────────────┤ X ├────────────────────────────»
└────────────────┘ └───┘ »
« ┌───────────────┐┌───┐┌───────────────┐┌───┐┌───────────────┐┌───┐┌───────────────┐»
«q_0: ┤ Delay(13[dt]) ├┤ X ├┤ Delay(16[dt]) ├┤ X ├┤ Delay(20[dt]) ├┤ X ├┤ Delay(16[dt]) ├»
« └───────────────┘└───┘└───────────────┘└───┘└───────────────┘└───┘└───────────────┘»
«q_1: ───────────────────────────────────────────────────────────────────────────────────»
« »
«q_2: ───────────────────────────────────────────────────────────────────────────────────»
« »
«q_3: ───────────────────────────────────────────────────────────────────────────────────»
« »
« ┌───┐┌───────────────┐┌───┐┌──────────────┐┌───┐┌──────────────┐
«q_0: ┤ X ├┤ Delay(13[dt]) ├┤ X ├┤ Delay(8[dt]) ├┤ X ├┤ Delay(3[dt]) ├
« └───┘└───────────────┘└───┘└──────────────┘└───┘└──────────────┘
«q_1: ────────────────────────────────────────────────────────────────
«
«q_2: ────────────────────────────────────────────────────────────────
«
«q_3: ────────────────────────────────────────────────────────────────
«
"""
n = 8
dd_sequence = [XGate()] * n
# uhrig specifies the location of the k'th pulse
def uhrig(k):
return np.sin(np.pi * (k + 1) / (2 * n + 2)) ** 2
# convert that to spacing between pulses (whatever finite duration pulses have)
spacing = []
for k in range(n):
spacing.append(uhrig(k) - sum(spacing))
spacing.append(1 - sum(spacing))
pm = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(self.durations, dd_sequence, qubits=[0], spacing=spacing),
]
)
ghz4_dd = pm.run(self.ghz4)
expected = self.ghz4.copy()
expected = expected.compose(Delay(50), [1], front=True)
expected = expected.compose(Delay(750), [2], front=True)
expected = expected.compose(Delay(950), [3], front=True)
expected = expected.compose(Delay(3), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(8), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(13), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(16), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(20), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(16), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(13), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(8), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(3), [0])
expected = expected.compose(Delay(300), [1])
self.assertEqual(ghz4_dd, expected)
def test_asymmetric_xy4_in_t2(self):
"""Test insertion of XY4 sequence with unbalanced spacing.
global phase: π
┌───┐┌───┐┌────────────────┐┌───┐┌────────────────┐┌───┐┌────────────────┐»
q_0: ┤ H ├┤ X ├┤ Delay(450[dt]) ├┤ Y ├┤ Delay(450[dt]) ├┤ X ├┤ Delay(450[dt]) ├»
└───┘└───┘└────────────────┘└───┘└────────────────┘└───┘└────────────────┘»
« ┌───┐┌────────────────┐┌───┐
«q_0: ┤ Y ├┤ Delay(450[dt]) ├┤ H ├
« └───┘└────────────────┘└───┘
"""
dd_sequence = [XGate(), YGate()] * 2
spacing = [0] + [1 / 4] * 4
pm = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(self.durations, dd_sequence, spacing=spacing),
]
)
t2 = QuantumCircuit(1)
t2.h(0)
t2.delay(2000, 0)
t2.h(0)
expected = QuantumCircuit(1)
expected.h(0)
expected.x(0)
expected.delay(450, 0)
expected.y(0)
expected.delay(450, 0)
expected.x(0)
expected.delay(450, 0)
expected.y(0)
expected.delay(450, 0)
expected.h(0)
expected.global_phase = pi
t2_dd = pm.run(t2)
self.assertEqual(t2_dd, expected)
# check global phase is correct
self.assertEqual(Operator(t2), Operator(expected))
def test_dd_after_reset(self):
"""Test skip_reset_qubits option works.
┌─────────────────┐┌───┐┌────────────────┐┌───┐┌─────────────────┐»
q_0: ─|0>─┤ Delay(1000[dt]) ├┤ H ├┤ Delay(190[dt]) ├┤ X ├┤ Delay(1710[dt]) ├»
└─────────────────┘└───┘└────────────────┘└───┘└─────────────────┘»
« ┌───┐┌───┐
«q_0: ┤ X ├┤ H ├
« └───┘└───┘
"""
dd_sequence = [XGate(), XGate()]
spacing = [0.1, 0.9]
pm = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(
self.durations, dd_sequence, spacing=spacing, skip_reset_qubits=True
),
]
)
t2 = QuantumCircuit(1)
t2.reset(0)
t2.delay(1000)
t2.h(0)
t2.delay(2000, 0)
t2.h(0)
expected = QuantumCircuit(1)
expected.reset(0)
expected.delay(1000)
expected.h(0)
expected.delay(190, 0)
expected.x(0)
expected.delay(1710, 0)
expected.x(0)
expected.h(0)
t2_dd = pm.run(t2)
self.assertEqual(t2_dd, expected)
def test_insert_dd_bad_sequence(self):
"""Test DD raises when non-identity sequence is inserted."""
dd_sequence = [XGate(), YGate()]
pm = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(self.durations, dd_sequence),
]
)
with self.assertRaises(TranspilerError):
pm.run(self.ghz4)
@data(0.5, 1.5)
def test_dd_with_calibrations_with_parameters(self, param_value):
"""Check that calibrations in a circuit with parameters work fine."""
circ = QuantumCircuit(2)
circ.x(0)
circ.cx(0, 1)
circ.rx(param_value, 1)
rx_duration = int(param_value * 1000)
with pulse.build() as rx:
pulse.play(pulse.Gaussian(rx_duration, 0.1, rx_duration // 4), pulse.DriveChannel(1))
circ.add_calibration("rx", (1,), rx, params=[param_value])
durations = InstructionDurations([("x", None, 100), ("cx", None, 300)])
dd_sequence = [XGate(), XGate()]
pm = PassManager(
[ALAPScheduleAnalysis(durations), PadDynamicalDecoupling(durations, dd_sequence)]
)
self.assertEqual(pm.run(circ).duration, rx_duration + 100 + 300)
def test_insert_dd_ghz_xy4_with_alignment(self):
"""Test DD with pulse alignment constraints.
┌───┐ ┌───────────────┐ ┌───┐ ┌───────────────┐»
q_0: ──────┤ H ├─────────■──┤ Delay(40[dt]) ├──────┤ X ├──────┤ Delay(70[dt]) ├»
┌─────┴───┴─────┐ ┌─┴─┐└───────────────┘┌─────┴───┴─────┐└─────┬───┬─────┘»
q_1: ┤ Delay(50[dt]) ├─┤ X ├────────■────────┤ Delay(20[dt]) ├──────┤ X ├──────»
├───────────────┴┐└───┘ ┌─┴─┐ └───────────────┘ └───┘ »
q_2: ┤ Delay(750[dt]) ├───────────┤ X ├──────────────■─────────────────────────»
├────────────────┤ └───┘ ┌─┴─┐ »
q_3: ┤ Delay(950[dt]) ├────────────────────────────┤ X ├───────────────────────»
└────────────────┘ └───┘ »
« ┌───┐ ┌───────────────┐ ┌───┐ ┌───────────────┐»
«q_0: ──────┤ Y ├──────┤ Delay(70[dt]) ├──────┤ X ├──────┤ Delay(70[dt]) ├»
« ┌─────┴───┴─────┐└─────┬───┬─────┘┌─────┴───┴─────┐└─────┬───┬─────┘»
«q_1: ┤ Delay(20[dt]) ├──────┤ Y ├──────┤ Delay(20[dt]) ├──────┤ X ├──────»
« └───────────────┘ └───┘ └───────────────┘ └───┘ »
«q_2: ────────────────────────────────────────────────────────────────────»
« »
«q_3: ────────────────────────────────────────────────────────────────────»
« »
« ┌───┐ ┌───────────────┐
«q_0: ──────┤ Y ├──────┤ Delay(50[dt]) ├─────────────────
« ┌─────┴───┴─────┐└─────┬───┬─────┘┌───────────────┐
«q_1: ┤ Delay(20[dt]) ├──────┤ Y ├──────┤ Delay(20[dt]) ├
« └───────────────┘ └───┘ └───────────────┘
«q_2: ───────────────────────────────────────────────────
«
«q_3: ───────────────────────────────────────────────────
«
"""
dd_sequence = [XGate(), YGate(), XGate(), YGate()]
pm = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(
self.durations,
dd_sequence,
pulse_alignment=10,
extra_slack_distribution="edges",
),
]
)
ghz4_dd = pm.run(self.ghz4)
expected = self.ghz4.copy()
expected = expected.compose(Delay(50), [1], front=True)
expected = expected.compose(Delay(750), [2], front=True)
expected = expected.compose(Delay(950), [3], front=True)
expected = expected.compose(Delay(40), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(70), [0])
expected = expected.compose(YGate(), [0])
expected = expected.compose(Delay(70), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(70), [0])
expected = expected.compose(YGate(), [0])
expected = expected.compose(Delay(50), [0])
expected = expected.compose(Delay(20), [1])
expected = expected.compose(XGate(), [1])
expected = expected.compose(Delay(20), [1])
expected = expected.compose(YGate(), [1])
expected = expected.compose(Delay(20), [1])
expected = expected.compose(XGate(), [1])
expected = expected.compose(Delay(20), [1])
expected = expected.compose(YGate(), [1])
expected = expected.compose(Delay(20), [1])
self.assertEqual(ghz4_dd, expected)
def test_dd_can_sequentially_called(self):
"""Test if sequentially called DD pass can output the same circuit.
This test verifies:
- if global phase is properly propagated from the previous padding node.
- if node_start_time property is properly updated for new dag circuit.
"""
dd_sequence = [XGate(), YGate(), XGate(), YGate()]
pm1 = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(self.durations, dd_sequence, qubits=[0]),
PadDynamicalDecoupling(self.durations, dd_sequence, qubits=[1]),
]
)
circ1 = pm1.run(self.ghz4)
pm2 = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(self.durations, dd_sequence, qubits=[0, 1]),
]
)
circ2 = pm2.run(self.ghz4)
self.assertEqual(circ1, circ2)
def test_respect_target_instruction_constraints(self):
"""Test if DD pass does not pad delays for qubits that do not support delay instructions
and does not insert DD gates for qubits that do not support necessary gates.
See: https://github.com/Qiskit/qiskit-terra/issues/9993
"""
qc = QuantumCircuit(3)
qc.cx(0, 1)
qc.cx(1, 2)
target = Target(dt=1)
# Y is partially supported (not supported on qubit 2)
target.add_instruction(
XGate(), {(q,): InstructionProperties(duration=100) for q in range(2)}
)
target.add_instruction(
CXGate(),
{
(0, 1): InstructionProperties(duration=1000),
(1, 2): InstructionProperties(duration=1000),
},
)
# delays are not supported
# No DD instructions nor delays are padded due to no delay support in the target
pm_xx = PassManager(
[
ALAPScheduleAnalysis(target=target),
PadDynamicalDecoupling(dd_sequence=[XGate(), XGate()], target=target),
]
)
scheduled = pm_xx.run(qc)
self.assertEqual(qc, scheduled)
# Fails since Y is not supported in the target
with self.assertRaises(TranspilerError):
PassManager(
[
ALAPScheduleAnalysis(target=target),
PadDynamicalDecoupling(
dd_sequence=[XGate(), YGate(), XGate(), YGate()], target=target
),
]
)
# Add delay support to the target
target.add_instruction(Delay(Parameter("t")), {(q,): None for q in range(3)})
# No error but no DD on qubit 2 (just delay is padded) since X is not supported on it
scheduled = pm_xx.run(qc)
expected = QuantumCircuit(3)
expected.delay(1000, [2])
expected.cx(0, 1)
expected.cx(1, 2)
expected.delay(200, [0])
expected.x([0])
expected.delay(400, [0])
expected.x([0])
expected.delay(200, [0])
self.assertEqual(expected, scheduled)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the EchoRZXWeylDecomposition pass"""
import unittest
from math import pi
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.transpiler.passes.optimization.echo_rzx_weyl_decomposition import (
EchoRZXWeylDecomposition,
)
from qiskit.converters import circuit_to_dag, dag_to_circuit
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import FakeParis
import qiskit.quantum_info as qi
from qiskit.quantum_info.synthesis.two_qubit_decompose import (
TwoQubitWeylDecomposition,
)
class TestEchoRZXWeylDecomposition(QiskitTestCase):
"""Tests the EchoRZXWeylDecomposition pass."""
def setUp(self):
super().setUp()
self.backend = FakeParis()
self.inst_map = self.backend.defaults().instruction_schedule_map
def assertRZXgates(self, unitary_circuit, after):
"""Check the number of rzx gates"""
alpha = TwoQubitWeylDecomposition(unitary_circuit).a
beta = TwoQubitWeylDecomposition(unitary_circuit).b
gamma = TwoQubitWeylDecomposition(unitary_circuit).c
expected_rzx_number = 0
if not alpha == 0:
expected_rzx_number += 2
if not beta == 0:
expected_rzx_number += 2
if not gamma == 0:
expected_rzx_number += 2
circuit_rzx_number = QuantumCircuit.count_ops(after)["rzx"]
self.assertEqual(expected_rzx_number, circuit_rzx_number)
@staticmethod
def count_gate_number(gate, circuit):
"""Count the number of a specific gate type in a circuit"""
if gate not in QuantumCircuit.count_ops(circuit):
gate_number = 0
else:
gate_number = QuantumCircuit.count_ops(circuit)[gate]
return gate_number
def test_rzx_number_native_weyl_decomposition(self):
"""Check the number of RZX gates for a hardware-native cx"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
unitary_circuit = qi.Operator(circuit).data
after = EchoRZXWeylDecomposition(self.inst_map)(circuit)
unitary_after = qi.Operator(after).data
self.assertTrue(np.allclose(unitary_circuit, unitary_after))
# check whether the after circuit has the correct number of rzx gates.
self.assertRZXgates(unitary_circuit, after)
def test_h_number_non_native_weyl_decomposition_1(self):
"""Check the number of added Hadamard gates for a native and non-native rzz gate"""
theta = pi / 11
qr = QuantumRegister(2, "qr")
# rzz gate in native direction
circuit = QuantumCircuit(qr)
circuit.rzz(theta, qr[0], qr[1])
# rzz gate in non-native direction
circuit_non_native = QuantumCircuit(qr)
circuit_non_native.rzz(theta, qr[1], qr[0])
dag = circuit_to_dag(circuit)
pass_ = EchoRZXWeylDecomposition(self.inst_map)
after = dag_to_circuit(pass_.run(dag))
dag_non_native = circuit_to_dag(circuit_non_native)
pass_ = EchoRZXWeylDecomposition(self.inst_map)
after_non_native = dag_to_circuit(pass_.run(dag_non_native))
circuit_rzx_number = self.count_gate_number("rzx", after)
circuit_h_number = self.count_gate_number("h", after)
circuit_non_native_h_number = self.count_gate_number("h", after_non_native)
# for each pair of rzx gates four hadamard gates have to be added in
# the case of a non-hardware-native directed gate.
self.assertEqual(
(circuit_rzx_number / 2) * 4, circuit_non_native_h_number - circuit_h_number
)
def test_h_number_non_native_weyl_decomposition_2(self):
"""Check the number of added Hadamard gates for a swap gate"""
qr = QuantumRegister(2, "qr")
# swap gate in native direction.
circuit = QuantumCircuit(qr)
circuit.swap(qr[0], qr[1])
# swap gate in non-native direction.
circuit_non_native = QuantumCircuit(qr)
circuit_non_native.swap(qr[1], qr[0])
dag = circuit_to_dag(circuit)
pass_ = EchoRZXWeylDecomposition(self.inst_map)
after = dag_to_circuit(pass_.run(dag))
dag_non_native = circuit_to_dag(circuit_non_native)
pass_ = EchoRZXWeylDecomposition(self.inst_map)
after_non_native = dag_to_circuit(pass_.run(dag_non_native))
circuit_rzx_number = self.count_gate_number("rzx", after)
circuit_h_number = self.count_gate_number("h", after)
circuit_non_native_h_number = self.count_gate_number("h", after_non_native)
# for each pair of rzx gates four hadamard gates have to be added in
# the case of a non-hardware-native directed gate.
self.assertEqual(
(circuit_rzx_number / 2) * 4, circuit_non_native_h_number - circuit_h_number
)
def test_weyl_decomposition_gate_angles(self):
"""Check the number and angles of the RZX gates for different gates"""
thetas = [pi / 9, 2.1, -0.2]
qr = QuantumRegister(2, "qr")
circuit_rxx = QuantumCircuit(qr)
circuit_rxx.rxx(thetas[0], qr[1], qr[0])
circuit_ryy = QuantumCircuit(qr)
circuit_ryy.ryy(thetas[1], qr[0], qr[1])
circuit_rzz = QuantumCircuit(qr)
circuit_rzz.rzz(thetas[2], qr[1], qr[0])
circuits = [circuit_rxx, circuit_ryy, circuit_rzz]
for circuit in circuits:
unitary_circuit = qi.Operator(circuit).data
dag = circuit_to_dag(circuit)
pass_ = EchoRZXWeylDecomposition(self.inst_map)
after = dag_to_circuit(pass_.run(dag))
dag_after = circuit_to_dag(after)
unitary_after = qi.Operator(after).data
# check whether the unitaries are equivalent.
self.assertTrue(np.allclose(unitary_circuit, unitary_after))
# check whether the after circuit has the correct number of rzx gates.
self.assertRZXgates(unitary_circuit, after)
alpha = TwoQubitWeylDecomposition(unitary_circuit).a
rzx_angles = []
for node in dag_after.two_qubit_ops():
if node.name == "rzx":
rzx_angle = node.op.params[0]
# check whether the absolute values of the RZX gate angles
# are equivalent to the corresponding Weyl parameter.
self.assertAlmostEqual(np.abs(rzx_angle), alpha)
rzx_angles.append(rzx_angle)
# check whether the angles of every RZX gate pair of an echoed RZX gate
# have opposite signs.
for idx in range(1, len(rzx_angles), 2):
self.assertAlmostEqual(rzx_angles[idx - 1], -rzx_angles[idx])
def test_weyl_unitaries_random_circuit(self):
"""Weyl decomposition for a random two-qubit circuit."""
theta = pi / 9
epsilon = 5
delta = -1
eta = 0.2
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
# random two-qubit circuit.
circuit.rzx(theta, 0, 1)
circuit.rzz(epsilon, 0, 1)
circuit.rz(eta, 0)
circuit.swap(1, 0)
circuit.h(0)
circuit.rzz(delta, 1, 0)
circuit.swap(0, 1)
circuit.cx(1, 0)
circuit.swap(0, 1)
circuit.h(1)
circuit.rxx(theta, 0, 1)
circuit.ryy(theta, 1, 0)
circuit.ecr(0, 1)
unitary_circuit = qi.Operator(circuit).data
dag = circuit_to_dag(circuit)
pass_ = EchoRZXWeylDecomposition(self.inst_map)
after = dag_to_circuit(pass_.run(dag))
unitary_after = qi.Operator(after).data
self.assertTrue(np.allclose(unitary_circuit, unitary_after))
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the EnlargeWithAncilla pass"""
import unittest
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.transpiler import Layout
from qiskit.transpiler.passes import EnlargeWithAncilla
from qiskit.converters import circuit_to_dag
from qiskit.test import QiskitTestCase
class TestEnlargeWithAncilla(QiskitTestCase):
"""Tests the EnlargeWithAncilla pass."""
def setUp(self):
super().setUp()
self.qr3 = QuantumRegister(3, "qr")
circuit = QuantumCircuit(self.qr3)
circuit.h(self.qr3)
self.dag = circuit_to_dag(circuit)
def test_no_extension(self):
"""There are no virtual qubits to extend."""
layout = Layout({self.qr3[0]: 0, self.qr3[1]: 1, self.qr3[2]: 2})
pass_ = EnlargeWithAncilla()
pass_.property_set["layout"] = layout
after = pass_.run(self.dag)
qregs = list(after.qregs.values())
self.assertEqual(1, len(qregs))
self.assertEqual(self.qr3, qregs[0])
def test_with_extension(self):
"""There are 2 virtual qubit to extend."""
ancilla = QuantumRegister(2, "ancilla")
layout = Layout(
{0: self.qr3[0], 1: ancilla[0], 2: self.qr3[1], 3: ancilla[1], 4: self.qr3[2]}
)
layout.add_register(ancilla)
pass_ = EnlargeWithAncilla()
pass_.property_set["layout"] = layout
after = pass_.run(self.dag)
qregs = list(after.qregs.values())
self.assertEqual(2, len(qregs))
self.assertEqual(self.qr3, qregs[0])
self.assertEqual(ancilla, qregs[1])
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the CX Direction pass"""
import unittest
from math import pi
import ddt
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit, pulse
from qiskit.circuit import Parameter, Gate
from qiskit.circuit.library import (
CXGate,
CZGate,
ECRGate,
RXXGate,
RYYGate,
RZXGate,
RZZGate,
SwapGate,
)
from qiskit.compiler import transpile
from qiskit.transpiler import TranspilerError, CouplingMap, Target
from qiskit.transpiler.passes import GateDirection
from qiskit.converters import circuit_to_dag
from qiskit.test import QiskitTestCase
@ddt.ddt
class TestGateDirection(QiskitTestCase):
"""Tests the GateDirection pass."""
def test_no_cnots(self):
"""Trivial map in a circuit without entanglement
qr0:---[H]---
qr1:---[H]---
qr2:---[H]---
CouplingMap map: None
"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr)
coupling = CouplingMap()
dag = circuit_to_dag(circuit)
pass_ = GateDirection(coupling)
after = pass_.run(dag)
self.assertEqual(dag, after)
def test_direction_error(self):
"""The mapping cannot be fixed by direction mapper
qr0:---------
qr1:---(+)---
|
qr2:----.----
CouplingMap map: [2] <- [0] -> [1]
"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[2])
coupling = CouplingMap([[0, 1], [0, 2]])
dag = circuit_to_dag(circuit)
pass_ = GateDirection(coupling)
with self.assertRaises(TranspilerError):
pass_.run(dag)
def test_direction_correct(self):
"""The CX is in the right direction
qr0:---(+)---
|
qr1:----.----
CouplingMap map: [0] -> [1]
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
coupling = CouplingMap([[0, 1]])
dag = circuit_to_dag(circuit)
pass_ = GateDirection(coupling)
after = pass_.run(dag)
self.assertEqual(dag, after)
def test_direction_flip(self):
"""Flip a CX
qr0:----.----
|
qr1:---(+)---
CouplingMap map: [0] -> [1]
qr0:-[H]-(+)-[H]--
|
qr1:-[H]--.--[H]--
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0])
coupling = CouplingMap([[0, 1]])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
expected.h(qr[0])
expected.h(qr[1])
expected.cx(qr[0], qr[1])
expected.h(qr[0])
expected.h(qr[1])
pass_ = GateDirection(coupling)
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_ecr_flip(self):
"""Flip a ECR gate.
┌──────┐
q_0: ┤1 ├
│ ECR │
q_1: ┤0 ├
└──────┘
CouplingMap map: [0, 1]
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.ecr(qr[1], qr[0])
coupling = CouplingMap([[0, 1]])
dag = circuit_to_dag(circuit)
# ┌─────────┐ ┌──────┐┌───┐
# qr_0: ┤ Ry(π/2) ├─┤0 ├┤ H ├
# ├─────────┴┐│ Ecr │├───┤
# qr_1: ┤ Ry(-π/2) ├┤1 ├┤ H ├
# └──────────┘└──────┘└───┘
expected = QuantumCircuit(qr)
expected.ry(pi / 2, qr[0])
expected.ry(-pi / 2, qr[1])
expected.ecr(qr[0], qr[1])
expected.h(qr[0])
expected.h(qr[1])
pass_ = GateDirection(coupling)
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_flip_with_measure(self):
"""
qr0: -(+)-[m]-
| |
qr1: --.---|--
|
cr0: ------.--
CouplingMap map: [0] -> [1]
qr0: -[H]--.--[H]-[m]-
| |
qr1: -[H]-(+)-[H]--|--
|
cr0: --------------.--
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.cx(qr[1], qr[0])
circuit.measure(qr[0], cr[0])
coupling = CouplingMap([[0, 1]])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.h(qr[0])
expected.h(qr[1])
expected.cx(qr[0], qr[1])
expected.h(qr[0])
expected.h(qr[1])
expected.measure(qr[0], cr[0])
pass_ = GateDirection(coupling)
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_preserves_conditions(self):
"""Verify GateDirection preserves conditional on CX gates.
┌───┐ ┌───┐
q_0: |0>───■────┤ X ├───■──┤ X ├
┌─┴─┐ └─┬─┘ ┌─┴─┐└─┬─┘
q_1: |0>─┤ X ├────■───┤ X ├──■──
└─┬─┘ │ └───┘
┌──┴──┐┌──┴──┐
c_0: 0 ╡ = 0 ╞╡ = 0 ╞══════════
└─────┘└─────┘
"""
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
circuit = QuantumCircuit(qr, cr)
circuit.cx(qr[0], qr[1]).c_if(cr, 0)
circuit.cx(qr[1], qr[0]).c_if(cr, 0)
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[0])
coupling = CouplingMap([[0, 1]])
dag = circuit_to_dag(circuit)
# ┌───┐ ┌───┐ ┌───┐ ┌───┐
# q_0: ───■───────────┤ H ├────■───────────┤ H ├───■──┤ H ├──■──┤ H ├
# ┌─┴─┐ ┌───┐ └─╥─┘ ┌─┴─┐ ┌───┐ └─╥─┘ ┌─┴─┐├───┤┌─┴─┐├───┤
# q_1: ─┤ X ├──┤ H ├────╫────┤ X ├──┤ H ├────╫───┤ X ├┤ H ├┤ X ├┤ H ├
# └─╥─┘ └─╥─┘ ║ └─╥─┘ └─╥─┘ ║ └───┘└───┘└───┘└───┘
# ┌──╨──┐┌──╨──┐┌──╨──┐┌──╨──┐┌──╨──┐┌──╨──┐
# c: 1/╡ 0x0 ╞╡ 0x0 ╞╡ 0x0 ╞╡ 0x0 ╞╡ 0x0 ╞╡ 0x0 ╞════════════════════
# └─────┘└─────┘└─────┘└─────┘└─────┘└─────┘
expected = QuantumCircuit(qr, cr)
expected.cx(qr[0], qr[1]).c_if(cr, 0)
# Order of H gates is important because DAG comparison will consider
# different conditional order on a creg to be a different circuit.
# See https://github.com/Qiskit/qiskit-terra/issues/3164
expected.h(qr[1]).c_if(cr, 0)
expected.h(qr[0]).c_if(cr, 0)
expected.cx(qr[0], qr[1]).c_if(cr, 0)
expected.h(qr[1]).c_if(cr, 0)
expected.h(qr[0]).c_if(cr, 0)
expected.cx(qr[0], qr[1])
expected.h(qr[1])
expected.h(qr[0])
expected.cx(qr[0], qr[1])
expected.h(qr[1])
expected.h(qr[0])
pass_ = GateDirection(coupling)
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_regression_gh_8387(self):
"""Regression test for flipping of CZ gate"""
qc = QuantumCircuit(3)
qc.cz(1, 0)
qc.barrier()
qc.cz(2, 0)
coupling_map = CouplingMap([[0, 1], [1, 2]])
_ = transpile(
qc,
basis_gates=["cz", "cx", "u3", "u2", "u1"],
coupling_map=coupling_map,
optimization_level=2,
)
@ddt.data(CXGate(), CZGate(), ECRGate())
def test_target_static(self, gate):
"""Test that static 2q gates are swapped correctly both if available and not available."""
circuit = QuantumCircuit(2)
circuit.append(gate, [0, 1], [])
matching = Target(num_qubits=2)
matching.add_instruction(gate, {(0, 1): None})
self.assertEqual(GateDirection(None, target=matching)(circuit), circuit)
swapped = Target(num_qubits=2)
swapped.add_instruction(gate, {(1, 0): None})
self.assertNotEqual(GateDirection(None, target=swapped)(circuit), circuit)
@ddt.data(CZGate(), RZXGate(pi / 3), RXXGate(pi / 3), RYYGate(pi / 3), RZZGate(pi / 3))
def test_target_trivial(self, gate):
"""Test that trivial 2q gates are swapped correctly both if available and not available."""
circuit = QuantumCircuit(2)
circuit.append(gate, [0, 1], [])
matching = Target(num_qubits=2)
matching.add_instruction(gate, {(0, 1): None})
self.assertEqual(GateDirection(None, target=matching)(circuit), circuit)
swapped = Target(num_qubits=2)
swapped.add_instruction(gate, {(1, 0): None})
self.assertNotEqual(GateDirection(None, target=swapped)(circuit), circuit)
@ddt.data(CZGate(), SwapGate(), RXXGate(pi / 3), RYYGate(pi / 3), RZZGate(pi / 3))
def test_symmetric_gates(self, gate):
"""Test symmetric gates on single direction coupling map."""
circuit = QuantumCircuit(2)
circuit.append(gate, [1, 0], [])
expected = QuantumCircuit(2)
expected.append(gate, [0, 1], [])
coupling = CouplingMap.from_line(2, bidirectional=False)
pass_ = GateDirection(coupling)
self.assertEqual(pass_(circuit), expected)
def test_target_parameter_any(self):
"""Test that a parametrised 2q gate is replaced correctly both if available and not
available."""
circuit = QuantumCircuit(2)
circuit.rzx(1.5, 0, 1)
matching = Target(num_qubits=2)
matching.add_instruction(RZXGate(Parameter("a")), {(0, 1): None})
self.assertEqual(GateDirection(None, target=matching)(circuit), circuit)
swapped = Target(num_qubits=2)
swapped.add_instruction(RZXGate(Parameter("a")), {(1, 0): None})
self.assertNotEqual(GateDirection(None, target=swapped)(circuit), circuit)
def test_target_parameter_exact(self):
"""Test that a parametrised 2q gate is detected correctly both if available and not
available."""
circuit = QuantumCircuit(2)
circuit.rzx(1.5, 0, 1)
matching = Target(num_qubits=2)
matching.add_instruction(RZXGate(1.5), {(0, 1): None})
self.assertEqual(GateDirection(None, target=matching)(circuit), circuit)
swapped = Target(num_qubits=2)
swapped.add_instruction(RZXGate(1.5), {(1, 0): None})
self.assertNotEqual(GateDirection(None, target=swapped)(circuit), circuit)
def test_target_parameter_mismatch(self):
"""Test that the pass raises if a gate is not supported due to a parameter mismatch."""
circuit = QuantumCircuit(2)
circuit.rzx(1.5, 0, 1)
matching = Target(num_qubits=2)
matching.add_instruction(RZXGate(2.5), {(0, 1): None})
pass_ = GateDirection(None, target=matching)
with self.assertRaises(TranspilerError):
pass_(circuit)
swapped = Target(num_qubits=2)
swapped.add_instruction(RZXGate(2.5), {(1, 0): None})
pass_ = GateDirection(None, target=swapped)
with self.assertRaises(TranspilerError):
pass_(circuit)
def test_coupling_map_control_flow(self):
"""Test that gates are replaced within nested control-flow blocks."""
circuit = QuantumCircuit(4, 1)
circuit.h(0)
circuit.measure(0, 0)
with circuit.for_loop((1, 2)):
circuit.cx(1, 0)
circuit.cx(0, 1)
with circuit.if_test((circuit.clbits[0], True)) as else_:
circuit.ecr(3, 2)
with else_:
with circuit.while_loop((circuit.clbits[0], True)):
circuit.rzx(2.3, 2, 1)
expected = QuantumCircuit(4, 1)
expected.h(0)
expected.measure(0, 0)
with expected.for_loop((1, 2)):
expected.h([0, 1])
expected.cx(0, 1)
expected.h([0, 1])
expected.cx(0, 1)
with expected.if_test((circuit.clbits[0], True)) as else_:
expected.ry(pi / 2, 2)
expected.ry(-pi / 2, 3)
expected.ecr(2, 3)
expected.h([2, 3])
with else_:
with expected.while_loop((circuit.clbits[0], True)):
expected.h([1, 2])
expected.rzx(2.3, 1, 2)
expected.h([1, 2])
coupling = CouplingMap.from_line(4, bidirectional=False)
pass_ = GateDirection(coupling)
self.assertEqual(pass_(circuit), expected)
def test_target_control_flow(self):
"""Test that gates are replaced within nested control-flow blocks."""
circuit = QuantumCircuit(4, 1)
circuit.h(0)
circuit.measure(0, 0)
with circuit.for_loop((1, 2)):
circuit.cx(1, 0)
circuit.cx(0, 1)
with circuit.if_test((circuit.clbits[0], True)) as else_:
circuit.ecr(3, 2)
with else_:
with circuit.while_loop((circuit.clbits[0], True)):
circuit.rzx(2.3, 2, 1)
expected = QuantumCircuit(4, 1)
expected.h(0)
expected.measure(0, 0)
with expected.for_loop((1, 2)):
expected.h([0, 1])
expected.cx(0, 1)
expected.h([0, 1])
expected.cx(0, 1)
with expected.if_test((circuit.clbits[0], True)) as else_:
expected.ry(pi / 2, 2)
expected.ry(-pi / 2, 3)
expected.ecr(2, 3)
expected.h([2, 3])
with else_:
with expected.while_loop((circuit.clbits[0], True)):
expected.h([1, 2])
expected.rzx(2.3, 1, 2)
expected.h([1, 2])
target = Target(num_qubits=4)
target.add_instruction(CXGate(), {(0, 1): None})
target.add_instruction(ECRGate(), {(2, 3): None})
target.add_instruction(RZXGate(Parameter("a")), {(1, 2): None})
pass_ = GateDirection(None, target)
self.assertEqual(pass_(circuit), expected)
def test_target_cannot_flip_message(self):
"""A suitable error message should be emitted if the gate would be supported if it were
flipped."""
gate = Gate("my_2q_gate", 2, [])
target = Target(num_qubits=2)
target.add_instruction(gate, properties={(0, 1): None})
circuit = QuantumCircuit(2)
circuit.append(gate, (1, 0))
pass_ = GateDirection(None, target)
with self.assertRaisesRegex(TranspilerError, "'my_2q_gate' would be supported.*"):
pass_(circuit)
def test_target_cannot_flip_message_calibrated(self):
"""A suitable error message should be emitted if the gate would be supported if it were
flipped."""
target = Target(num_qubits=2)
target.add_instruction(CXGate(), properties={(0, 1): None})
gate = Gate("my_2q_gate", 2, [])
circuit = QuantumCircuit(2)
circuit.append(gate, (1, 0))
circuit.add_calibration(gate, (0, 1), pulse.ScheduleBlock())
pass_ = GateDirection(None, target)
with self.assertRaisesRegex(TranspilerError, "'my_2q_gate' would be supported.*"):
pass_(circuit)
def test_target_unknown_gate_message(self):
"""A suitable error message should be emitted if the gate isn't valid in either direction on
the target."""
gate = Gate("my_2q_gate", 2, [])
target = Target(num_qubits=2)
target.add_instruction(CXGate(), properties={(0, 1): None})
circuit = QuantumCircuit(2)
circuit.append(gate, (0, 1))
pass_ = GateDirection(None, target)
with self.assertRaisesRegex(TranspilerError, "'my_2q_gate'.*not supported on qubits .*"):
pass_(circuit)
def test_allows_calibrated_gates_coupling_map(self):
"""Test that the gate direction pass allows a gate that's got a calibration to pass through
without error."""
cm = CouplingMap([(1, 0)])
gate = Gate("my_2q_gate", 2, [])
circuit = QuantumCircuit(2)
circuit.append(gate, (0, 1))
circuit.add_calibration(gate, (0, 1), pulse.ScheduleBlock())
pass_ = GateDirection(cm)
self.assertEqual(pass_(circuit), circuit)
def test_allows_calibrated_gates_target(self):
"""Test that the gate direction pass allows a gate that's got a calibration to pass through
without error."""
target = Target(num_qubits=2)
target.add_instruction(CXGate(), properties={(0, 1): None})
gate = Gate("my_2q_gate", 2, [])
circuit = QuantumCircuit(2)
circuit.append(gate, (0, 1))
circuit.add_calibration(gate, (0, 1), pulse.ScheduleBlock())
pass_ = GateDirection(None, target)
self.assertEqual(pass_(circuit), circuit)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the HoareOptimizer pass"""
import unittest
from numpy import pi
from qiskit.utils import optionals
from qiskit.transpiler.passes import HoareOptimizer
from qiskit.converters import circuit_to_dag
from qiskit import QuantumCircuit
from qiskit.test import QiskitTestCase
from qiskit.circuit.library import XGate, RZGate, CSwapGate, SwapGate
from qiskit.dagcircuit import DAGOpNode
from qiskit.quantum_info import Statevector
@unittest.skipUnless(optionals.HAS_Z3, "z3-solver needs to be installed to run these tests")
class TestHoareOptimizer(QiskitTestCase):
"""Test the HoareOptimizer pass"""
def test_phasegate_removal(self):
"""Should remove the phase on a classical state,
but not on a superposition state.
"""
# ┌───┐
# q_0: ┤ Z ├──────
# ├───┤┌───┐
# q_1:─┤ H ├┤ Z ├─
# └───┘└───┘
circuit = QuantumCircuit(3)
circuit.z(0)
circuit.h(1)
circuit.z(1)
# q_0: ───────────
# ┌───┐┌───┐
# q_1:─┤ H ├┤ Z ├─
# └───┘└───┘
expected = QuantumCircuit(3)
expected.h(1)
expected.z(1)
stv = Statevector.from_label("0" * circuit.num_qubits)
self.assertEqual(stv & circuit, stv & expected)
pass_ = HoareOptimizer(size=0)
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_cswap_removal(self):
"""Should remove Fredkin gates because the optimizer
can deduce the targets are in the same state
"""
# ┌───┐┌───┐ ┌───┐ ┌───┐ ┌───┐
# q_0: ┤ X ├┤ X ├──■──┤ X ├──■──┤ X ├──■────■──┤ X ├─────────────────────────────────
# └───┘└─┬─┘┌─┴─┐└─┬─┘ │ └─┬─┘┌─┴─┐ │ └─┬─┘
# q_1: ───────┼──┤ X ├──■────┼────┼──┤ X ├──┼────■───■──■──■──■─────■─────■──────────
# │ └─┬─┘ ┌─┴─┐ │ └─┬─┘┌─┴─┐ │ │ │ │ │ │ │
# q_2: ───────┼────┼───────┤ X ├──■────┼──┤ X ├──■───┼──┼──┼──┼──■──┼──■──┼──■──■──■─
# ┌───┐ │ │ └─┬─┘ │ └─┬─┘ │ │ │ │ │ │ │ │ │ │ │
# q_3: ┤ H ├──■────┼─────────┼─────────┼────┼────────┼──┼──X──X──┼──┼──X──┼──┼──X──┼─
# ├───┤ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │
# q_4: ┤ H ├───────■─────────┼─────────┼────┼────────┼──┼──┼──X──┼──X──┼──┼──X──┼──X─
# ├───┤ │ │ │ │ │ │ │ │ │ │ │ │ │
# q_5: ┤ H ├─────────────────■─────────┼────┼────────┼──┼──┼─────┼──X──┼──X──┼──X──┼─
# ├───┤ │ │ │ │ │ │ │ │ │ │
# q_6: ┤ H ├───────────────────────────■────■────────┼──┼──┼─────┼─────┼──X──┼─────X─
# └───┘ │ │ │ │ │ │
# q_7: ──────────────────────────────────────────────X──┼──┼─────X─────┼─────┼───────
# │ │ │ │ │ │
# q_8: ──────────────────────────────────────────────X──X──┼─────┼─────X─────┼───────
# │ │ │ │
# q_9: ─────────────────────────────────────────────────X──X─────X───────────X───────
circuit = QuantumCircuit(10)
# prep
circuit.x(0)
circuit.h(3)
circuit.h(4)
circuit.h(5)
circuit.h(6)
# find first non-zero bit of reg(3-6), store position in reg(1-2)
circuit.cx(3, 0)
circuit.ccx(0, 4, 1)
circuit.cx(1, 0)
circuit.ccx(0, 5, 2)
circuit.cx(2, 0)
circuit.ccx(0, 6, 1)
circuit.ccx(0, 6, 2)
circuit.ccx(1, 2, 0)
# shift circuit
circuit.cswap(1, 7, 8)
circuit.cswap(1, 8, 9)
circuit.cswap(1, 9, 3)
circuit.cswap(1, 3, 4)
circuit.cswap(1, 4, 5)
circuit.cswap(1, 5, 6)
circuit.cswap(2, 7, 9)
circuit.cswap(2, 8, 3)
circuit.cswap(2, 9, 4)
circuit.cswap(2, 3, 5)
circuit.cswap(2, 4, 6)
# ┌───┐┌───┐ ┌───┐ ┌───┐ ┌───┐
# q_0: ┤ X ├┤ X ├──■──┤ X ├──■──┤ X ├──■────■──┤ X ├───────────────
# └───┘└─┬─┘┌─┴─┐└─┬─┘ │ └─┬─┘┌─┴─┐ │ └─┬─┘
# q_1: ───────┼──┤ X ├──■────┼────┼──┤ X ├──┼────■───■──■──■───────
# │ └─┬─┘ ┌─┴─┐ │ └─┬─┘┌─┴─┐ │ │ │ │
# q_2: ───────┼────┼───────┤ X ├──■────┼──┤ X ├──■───┼──┼──┼──■──■─
# ┌───┐ │ │ └─┬─┘ │ └─┬─┘ │ │ │ │ │
# q_3: ┤ H ├──■────┼─────────┼─────────┼────┼────────X──┼──┼──X──┼─
# ├───┤ │ │ │ │ │ │ │ │ │
# q_4: ┤ H ├───────■─────────┼─────────┼────┼────────X──X──┼──┼──X─
# ├───┤ │ │ │ │ │ │ │
# q_5: ┤ H ├─────────────────■─────────┼────┼───────────X──X──X──┼─
# ├───┤ │ │ │ │
# q_6: ┤ H ├───────────────────────────■────■──────────────X─────X─
# └───┘
# q_7: ────────────────────────────────────────────────────────────
#
# q_8: ────────────────────────────────────────────────────────────
#
# q_9: ────────────────────────────────────────────────────────────
expected = QuantumCircuit(10)
# prep
expected.x(0)
expected.h(3)
expected.h(4)
expected.h(5)
expected.h(6)
# find first non-zero bit of reg(3-6), store position in reg(1-2)
expected.cx(3, 0)
expected.ccx(0, 4, 1)
expected.cx(1, 0)
expected.ccx(0, 5, 2)
expected.cx(2, 0)
expected.ccx(0, 6, 1)
expected.ccx(0, 6, 2)
expected.ccx(1, 2, 0)
# optimized shift circuit
expected.cswap(1, 3, 4)
expected.cswap(1, 4, 5)
expected.cswap(1, 5, 6)
expected.cswap(2, 3, 5)
expected.cswap(2, 4, 6)
stv = Statevector.from_label("0" * circuit.num_qubits)
self.assertEqual(stv & circuit, stv & expected)
pass_ = HoareOptimizer(size=0)
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_lnn_cnot_removal(self):
"""Should remove some cnots from swaps introduced
because of linear nearest architecture. Only uses
single-gate optimization techniques.
"""
# ┌───┐ ┌───┐ »
# q_0: ┤ H ├──■──┤ X ├──■────────────────────────────────────────────────────»
# └───┘┌─┴─┐└─┬─┘┌─┴─┐ ┌───┐ »
# q_1: ─────┤ X ├──■──┤ X ├──■──┤ X ├──■──────────────────────────────────■──»
# └───┘ └───┘┌─┴─┐└─┬─┘┌─┴─┐ ┌───┐ ┌───┐┌─┴─┐»
# q_2: ────────────────────┤ X ├──■──┤ X ├──■──┤ X ├──■─────────■──┤ X ├┤ X ├»
# └───┘ └───┘┌─┴─┐└─┬─┘┌─┴─┐ ┌─┴─┐└─┬─┘└───┘»
# q_3: ───────────────────────────────────┤ X ├──■──┤ X ├──■──┤ X ├──■───────»
# └───┘ └───┘┌─┴─┐└───┘ »
# q_4: ──────────────────────────────────────────────────┤ X ├───────────────»
# └───┘ »
# « ┌───┐
# «q_0: ───────■──┤ X ├
# « ┌───┐┌─┴─┐└─┬─┘
# «q_1: ┤ X ├┤ X ├──■──
# « └─┬─┘└───┘
# «q_2: ──■────────────
# «
# «q_3: ───────────────
# «
# «q_4: ───────────────
circuit = QuantumCircuit(5)
circuit.h(0)
for i in range(0, 3):
circuit.cx(i, i + 1)
circuit.cx(i + 1, i)
circuit.cx(i, i + 1)
circuit.cx(3, 4)
for i in range(3, 0, -1):
circuit.cx(i - 1, i)
circuit.cx(i, i - 1)
# ┌───┐ ┌───┐ ┌───┐
# q_0: ┤ H ├──■──┤ X ├───────────────────────────────────┤ X ├
# └───┘┌─┴─┐└─┬─┘ ┌───┐ ┌───┐└─┬─┘
# q_1: ─────┤ X ├──■────■──┤ X ├────────────────────┤ X ├──■──
# └───┘ ┌─┴─┐└─┬─┘ ┌───┐ ┌───┐└─┬─┘
# q_2: ───────────────┤ X ├──■────■──┤ X ├─────┤ X ├──■───────
# └───┘ ┌─┴─┐└─┬─┘ └─┬─┘
# q_3: ─────────────────────────┤ X ├──■────■────■────────────
# └───┘ ┌─┴─┐
# q_4: ───────────────────────────────────┤ X ├───────────────
# └───┘
expected = QuantumCircuit(5)
expected.h(0)
for i in range(0, 3):
expected.cx(i, i + 1)
expected.cx(i + 1, i)
expected.cx(3, 4)
for i in range(3, 0, -1):
expected.cx(i, i - 1)
stv = Statevector.from_label("0" * circuit.num_qubits)
self.assertEqual(stv & circuit, stv & expected)
pass_ = HoareOptimizer(size=0)
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_lnncnot_advanced_removal(self):
"""Should remove all cnots from swaps introduced
because of linear nearest architecture. This time
using multi-gate optimization techniques.
"""
# ┌───┐ ┌───┐ »
# q_0: ┤ H ├──■──┤ X ├──■────────────────────────────────────────────────────»
# └───┘┌─┴─┐└─┬─┘┌─┴─┐ ┌───┐ »
# q_1: ─────┤ X ├──■──┤ X ├──■──┤ X ├──■──────────────────────────────────■──»
# └───┘ └───┘┌─┴─┐└─┬─┘┌─┴─┐ ┌───┐ ┌───┐┌─┴─┐»
# q_2: ────────────────────┤ X ├──■──┤ X ├──■──┤ X ├──■─────────■──┤ X ├┤ X ├»
# └───┘ └───┘┌─┴─┐└─┬─┘┌─┴─┐ ┌─┴─┐└─┬─┘└───┘»
# q_3: ───────────────────────────────────┤ X ├──■──┤ X ├──■──┤ X ├──■───────»
# └───┘ └───┘┌─┴─┐└───┘ »
# q_4: ──────────────────────────────────────────────────┤ X ├───────────────»
# └───┘ »
# « ┌───┐
# «q_0: ───────■──┤ X ├
# « ┌───┐┌─┴─┐└─┬─┘
# «q_1: ┤ X ├┤ X ├──■──
# « └─┬─┘└───┘
# «q_2: ──■────────────
# «
# «q_3: ───────────────
# «
# «q_4: ───────────────
circuit = QuantumCircuit(5)
circuit.h(0)
for i in range(0, 3):
circuit.cx(i, i + 1)
circuit.cx(i + 1, i)
circuit.cx(i, i + 1)
circuit.cx(3, 4)
for i in range(3, 0, -1):
circuit.cx(i - 1, i)
circuit.cx(i, i - 1)
# ┌───┐
# q_0: ┤ H ├──■─────────────────
# └───┘┌─┴─┐
# q_1: ─────┤ X ├──■────────────
# └───┘┌─┴─┐
# q_2: ──────────┤ X ├──■───────
# └───┘┌─┴─┐
# q_3: ───────────────┤ X ├──■──
# └───┘┌─┴─┐
# q_4: ────────────────────┤ X ├
# └───┘
expected = QuantumCircuit(5)
expected.h(0)
for i in range(0, 4):
expected.cx(i, i + 1)
stv = Statevector.from_label("0" * circuit.num_qubits)
self.assertEqual(stv & circuit, stv & expected)
pass_ = HoareOptimizer(size=6)
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_successive_identity_removal(self):
"""Should remove a successive pair of H gates applying
on the same qubit.
"""
circuit = QuantumCircuit(1)
circuit.h(0)
circuit.h(0)
circuit.h(0)
expected = QuantumCircuit(1)
expected.h(0)
stv = Statevector.from_label("0" * circuit.num_qubits)
self.assertEqual(stv & circuit, stv & expected)
pass_ = HoareOptimizer(size=4)
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_targetsuccessive_identity_removal(self):
"""Should remove pair of controlled target successive
which are the inverse of each other, if they can be
identified to be executed as a unit (either both or none).
"""
# ┌───┐ ┌───┐┌───┐
# q_0: ┤ H ├──■──┤ X ├┤ X ├──■──
# ├───┤ │ └─┬─┘└───┘ │
# q_1: ┤ H ├──■────■─────────■──
# ├───┤┌─┴─┐ ┌─┴─┐
# q_2: ┤ H ├┤ X ├──────────┤ X ├
# └───┘└───┘ └───┘
circuit = QuantumCircuit(3)
circuit.h(0)
circuit.h(1)
circuit.h(2)
circuit.ccx(0, 1, 2)
circuit.cx(1, 0)
circuit.x(0)
circuit.ccx(0, 1, 2)
# ┌───┐┌───┐┌───┐
# q_0: ┤ H ├┤ X ├┤ X ├
# ├───┤└─┬─┘└───┘
# q_1: ┤ H ├──■───────
# ├───┤
# q_2: ┤ H ├──────────
# └───┘
expected = QuantumCircuit(3)
expected.h(0)
expected.h(1)
expected.h(2)
expected.cx(1, 0)
expected.x(0)
stv = Statevector.from_label("0" * circuit.num_qubits)
self.assertEqual(stv & circuit, stv & expected)
pass_ = HoareOptimizer(size=4)
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_targetsuccessive_identity_advanced_removal(self):
"""Should remove target successive identity gates
with DIFFERENT sets of control qubits.
In this case CCCX(4,5,6,7) & CCX(5,6,7).
"""
# ┌───┐┌───┐ »
# q_0: ┤ H ├┤ X ├───────■─────────────────────────────■───────────────────■──»
# ├───┤└─┬─┘ │ │ │ »
# q_1: ┤ H ├──■─────────■─────────────────────────────■───────────────────■──»
# ├───┤┌───┐ │ ┌───┐ │ │ »
# q_2: ┤ H ├┤ X ├───────┼──┤ X ├──■──────────────■────┼───────────────────┼──»
# ├───┤└─┬─┘ ┌─┴─┐└─┬─┘ │ │ ┌─┴─┐ ┌─┴─┐»
# q_3: ┤ H ├──■────■──┤ X ├──■────■──────────────■──┤ X ├──■─────────■──┤ X ├»
# ├───┤┌───┐ │ └───┘ │ ┌───┐ │ └───┘ │ │ └───┘»
# q_4: ┤ H ├┤ X ├──┼──────────────┼──┤ X ├──■────┼─────────┼─────────┼───────»
# ├───┤└─┬─┘┌─┴─┐ ┌─┴─┐└─┬─┘ │ ┌─┴─┐ ┌─┴─┐ ┌─┴─┐ »
# q_5: ┤ H ├──■──┤ X ├──────────┤ X ├──■────■──┤ X ├─────┤ X ├──■──┤ X ├─────»
# └───┘ └───┘ └───┘ ┌─┴─┐└───┘ └───┘┌─┴─┐├───┤ »
# q_6: ───────────────────────────────────┤ X ├───────────────┤ X ├┤ X ├─────»
# └───┘ └───┘└───┘ »
# q_7: ──────────────────────────────────────────────────────────────────────»
# »
# « ┌───┐┌───┐ »
# «q_0: ──────────────────────■──┤ X ├┤ X ├──■─────────────────────────────■──»
# « │ └─┬─┘└─┬─┘ │ │ »
# «q_1: ──────────────────────■────■────■────■─────────────────────────────■──»
# « ┌───┐ │ │ │ ┌───┐ │ »
# «q_2: ──■─────────■──┤ X ├──┼─────────┼────┼──┤ X ├──■──────────────■────┼──»
# « │ │ └─┬─┘┌─┴─┐ │ ┌─┴─┐└─┬─┘ │ │ ┌─┴─┐»
# «q_3: ──■─────────■────■──┤ X ├───────┼──┤ X ├──■────■──────────────■──┤ X ├»
# « │ ┌───┐ │ └───┘ │ └───┘ │ │ ┌───┐ │ └───┘»
# «q_4: ──┼──┤ X ├──┼───────────────────┼─────────┼────┼──┤ X ├──■────┼───────»
# « ┌─┴─┐└─┬─┘┌─┴─┐ │ │ ┌─┴─┐└─┬─┘ │ ┌─┴─┐ »
# «q_5: ┤ X ├──■──┤ X ├─────────────────┼─────────┼──┤ X ├──■────■──┤ X ├─────»
# « └───┘ └───┘ │ │ └───┘ │ │ └───┘ »
# «q_6: ────────────────────────────────■─────────■─────────■────■────────────»
# « ┌─┴─┐ »
# «q_7: ───────────────────────────────────────────────────────┤ X ├──────────»
# « └───┘ »
# «
# «q_0: ───────────────
# «
# «q_1: ───────────────
# « ┌───┐
# «q_2: ─────┤ X ├─────
# « └─┬─┘
# «q_3: ──■────■───────
# « │ ┌───┐
# «q_4: ──┼──┤ X ├─────
# « ┌─┴─┐└─┬─┘
# «q_5: ┤ X ├──■────■──
# « └───┘ │
# «q_6: ────────────■──
# « ┌─┴─┐
# «q_7: ──────────┤ X ├
# « └───┘
circuit = QuantumCircuit(8)
circuit.h(0)
circuit.h(1)
circuit.h(2)
circuit.h(3)
circuit.h(4)
circuit.h(5)
for i in range(3):
circuit.cx(i * 2 + 1, i * 2)
circuit.cx(3, 5)
for i in range(2):
circuit.ccx(i * 2, i * 2 + 1, i * 2 + 3)
circuit.cx(i * 2 + 3, i * 2 + 2)
circuit.ccx(4, 5, 6)
for i in range(1, -1, -1):
circuit.ccx(i * 2, i * 2 + 1, i * 2 + 3)
circuit.cx(3, 5)
circuit.cx(5, 6)
circuit.cx(3, 5)
circuit.x(6)
for i in range(2):
circuit.ccx(i * 2, i * 2 + 1, i * 2 + 3)
for i in range(1, -1, -1):
circuit.cx(i * 2 + 3, i * 2 + 2)
circuit.ccx(i * 2, i * 2 + 1, i * 2 + 3)
circuit.cx(1, 0)
circuit.ccx(6, 1, 0)
circuit.ccx(0, 1, 3)
circuit.ccx(6, 3, 2)
circuit.ccx(2, 3, 5)
circuit.ccx(6, 5, 4)
circuit.append(XGate().control(3), [4, 5, 6, 7], [])
for i in range(1, -1, -1):
circuit.ccx(i * 2, i * 2 + 1, i * 2 + 3)
circuit.cx(3, 5)
for i in range(1, 3):
circuit.cx(i * 2 + 1, i * 2)
circuit.ccx(5, 6, 7)
# ┌───┐┌───┐ »
# q_0: ┤ H ├┤ X ├───────■─────────────────────────────■───────────────────■──»
# ├───┤└─┬─┘ │ │ │ »
# q_1: ┤ H ├──■─────────■─────────────────────────────■───────────────────■──»
# ├───┤┌───┐ │ ┌───┐ │ │ »
# q_2: ┤ H ├┤ X ├───────┼──┤ X ├──■──────────────■────┼───────────────────┼──»
# ├───┤└─┬─┘ ┌─┴─┐└─┬─┘ │ │ ┌─┴─┐ ┌─┴─┐»
# q_3: ┤ H ├──■────■──┤ X ├──■────■──────────────■──┤ X ├──■─────────■──┤ X ├»
# ├───┤┌───┐ │ └───┘ │ ┌───┐ │ └───┘ │ │ └───┘»
# q_4: ┤ H ├┤ X ├──┼──────────────┼──┤ X ├──■────┼─────────┼─────────┼───────»
# ├───┤└─┬─┘┌─┴─┐ ┌─┴─┐└─┬─┘ │ ┌─┴─┐ ┌─┴─┐ ┌─┴─┐ »
# q_5: ┤ H ├──■──┤ X ├──────────┤ X ├──■────■──┤ X ├─────┤ X ├──■──┤ X ├─────»
# └───┘ └───┘ └───┘ ┌─┴─┐└───┘ └───┘┌─┴─┐├───┤ »
# q_6: ───────────────────────────────────┤ X ├───────────────┤ X ├┤ X ├─────»
# └───┘ └───┘└───┘ »
# q_7: ──────────────────────────────────────────────────────────────────────»
# »
# « ┌───┐┌───┐ »
# «q_0: ──────────────────────■──┤ X ├┤ X ├──■────────────────────────■───────»
# « │ └─┬─┘└─┬─┘ │ │ »
# «q_1: ──────────────────────■────■────■────■────────────────────────■───────»
# « ┌───┐ │ │ │ ┌───┐ │ »
# «q_2: ──■─────────■──┤ X ├──┼─────────┼────┼──┤ X ├──■─────────■────┼───────»
# « │ │ └─┬─┘┌─┴─┐ │ ┌─┴─┐└─┬─┘ │ │ ┌─┴─┐ »
# «q_3: ──■─────────■────■──┤ X ├───────┼──┤ X ├──■────■─────────■──┤ X ├──■──»
# « │ ┌───┐ │ └───┘ │ └───┘ │ │ ┌───┐ │ └───┘ │ »
# «q_4: ──┼──┤ X ├──┼───────────────────┼─────────┼────┼──┤ X ├──┼─────────┼──»
# « ┌─┴─┐└─┬─┘┌─┴─┐ │ │ ┌─┴─┐└─┬─┘┌─┴─┐ ┌─┴─┐»
# «q_5: ┤ X ├──■──┤ X ├─────────────────┼─────────┼──┤ X ├──■──┤ X ├─────┤ X ├»
# « └───┘ └───┘ │ │ └───┘ │ └───┘ └───┘»
# «q_6: ────────────────────────────────■─────────■─────────■─────────────────»
# « »
# «q_7: ──────────────────────────────────────────────────────────────────────»
# « »
# «
# «q_0: ─────
# «
# «q_1: ─────
# « ┌───┐
# «q_2: ┤ X ├
# « └─┬─┘
# «q_3: ──■──
# « ┌───┐
# «q_4: ┤ X ├
# « └─┬─┘
# «q_5: ──■──
# «
# «q_6: ─────
# «
# «q_7: ─────
# «
expected = QuantumCircuit(8)
expected.h(0)
expected.h(1)
expected.h(2)
expected.h(3)
expected.h(4)
expected.h(5)
for i in range(3):
expected.cx(i * 2 + 1, i * 2)
expected.cx(3, 5)
for i in range(2):
expected.ccx(i * 2, i * 2 + 1, i * 2 + 3)
expected.cx(i * 2 + 3, i * 2 + 2)
expected.ccx(4, 5, 6)
for i in range(1, -1, -1):
expected.ccx(i * 2, i * 2 + 1, i * 2 + 3)
expected.cx(3, 5)
expected.cx(5, 6)
expected.cx(3, 5)
expected.x(6)
for i in range(2):
expected.ccx(i * 2, i * 2 + 1, i * 2 + 3)
for i in range(1, -1, -1):
expected.cx(i * 2 + 3, i * 2 + 2)
expected.ccx(i * 2, i * 2 + 1, i * 2 + 3)
expected.cx(1, 0)
expected.ccx(6, 1, 0)
expected.ccx(0, 1, 3)
expected.ccx(6, 3, 2)
expected.ccx(2, 3, 5)
expected.ccx(6, 5, 4)
for i in range(1, -1, -1):
expected.ccx(i * 2, i * 2 + 1, i * 2 + 3)
expected.cx(3, 5)
for i in range(1, 3):
expected.cx(i * 2 + 1, i * 2)
stv = Statevector.from_label("0" * circuit.num_qubits)
self.assertEqual(stv & circuit, stv & expected)
pass_ = HoareOptimizer(size=5)
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_control_removal(self):
"""Should replace CX by X."""
# ┌───┐
# q_0: ┤ X ├──■──
# └───┘┌─┴─┐
# q_1: ─────┤ X ├
# └───┘
circuit = QuantumCircuit(2)
circuit.x(0)
circuit.cx(0, 1)
# ┌───┐
# q_0: ┤ X ├
# ├───┤
# q_1: ┤ X ├
# └───┘
expected = QuantumCircuit(2)
expected.x(0)
expected.x(1)
stv = Statevector.from_label("0" * circuit.num_qubits)
self.assertEqual(stv & circuit, stv & expected)
pass_ = HoareOptimizer(size=5)
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
# Should replace CZ by Z
#
# ┌───┐ ┌───┐
# q_0: ┤ H ├─■─┤ H ├
# ├───┤ │ └───┘
# q_1: ┤ X ├─■──────
# └───┘
circuit = QuantumCircuit(2)
circuit.h(0)
circuit.x(1)
circuit.cz(0, 1)
circuit.h(0)
# ┌───┐┌───┐┌───┐
# q_0: ┤ H ├┤ Z ├┤ H ├
# ├───┤└───┘└───┘
# q_1: ┤ X ├──────────
# └───┘
expected = QuantumCircuit(2)
expected.h(0)
expected.x(1)
expected.z(0)
expected.h(0)
stv = Statevector.from_label("0" * circuit.num_qubits)
self.assertEqual(stv & circuit, stv & expected)
pass_ = HoareOptimizer(size=5)
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_is_identity(self):
"""The is_identity function determines whether a pair of gates
forms the identity, when ignoring control qubits.
"""
seq = [DAGOpNode(op=XGate().control()), DAGOpNode(op=XGate().control(2))]
self.assertTrue(HoareOptimizer()._is_identity(seq))
seq = [
DAGOpNode(op=RZGate(-pi / 2).control()),
DAGOpNode(op=RZGate(pi / 2).control(2)),
]
self.assertTrue(HoareOptimizer()._is_identity(seq))
seq = [DAGOpNode(op=CSwapGate()), DAGOpNode(op=SwapGate())]
self.assertTrue(HoareOptimizer()._is_identity(seq))
def test_multiple_pass(self):
"""Verify that multiple pass can be run
with the same Hoare instance.
"""
# ┌───┐┌───┐
# q_0:─┤ H ├┤ Z ├─
# ├───┤└───┘
# q_1: ┤ Z ├──────
# └───┘
circuit1 = QuantumCircuit(2)
circuit1.z(0)
circuit1.h(1)
circuit1.z(1)
circuit2 = QuantumCircuit(2)
circuit2.z(1)
circuit2.h(0)
circuit2.z(0)
# ┌───┐┌───┐
# q_0:─┤ H ├┤ Z ├─
# └───┘└───┘
# q_1: ───────────
expected = QuantumCircuit(2)
expected.h(0)
expected.z(0)
pass_ = HoareOptimizer()
pass_.run(circuit_to_dag(circuit1))
result2 = pass_.run(circuit_to_dag(circuit2))
self.assertEqual(result2, circuit_to_dag(expected))
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Testing legacy instruction alignment pass."""
from qiskit import QuantumCircuit, pulse
from qiskit.test import QiskitTestCase
from qiskit.transpiler import InstructionDurations
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.transpiler.passes import (
AlignMeasures,
ValidatePulseGates,
ALAPSchedule,
TimeUnitConversion,
)
class TestAlignMeasures(QiskitTestCase):
"""A test for measurement alignment pass."""
def setUp(self):
super().setUp()
instruction_durations = InstructionDurations()
instruction_durations.update(
[
("rz", (0,), 0),
("rz", (1,), 0),
("x", (0,), 160),
("x", (1,), 160),
("sx", (0,), 160),
("sx", (1,), 160),
("cx", (0, 1), 800),
("cx", (1, 0), 800),
("measure", None, 1600),
]
)
self.time_conversion_pass = TimeUnitConversion(inst_durations=instruction_durations)
# reproduce old behavior of 0.20.0 before #7655
# currently default write latency is 0
self.scheduling_pass = ALAPSchedule(
durations=instruction_durations,
clbit_write_latency=1600,
conditional_latency=0,
)
self.align_measure_pass = AlignMeasures(alignment=16)
def test_t1_experiment_type(self):
"""Test T1 experiment type circuit.
(input)
┌───┐┌────────────────┐┌─┐
q_0: ┤ X ├┤ Delay(100[dt]) ├┤M├
└───┘└────────────────┘└╥┘
c: 1/════════════════════════╩═
0
(aligned)
┌───┐┌────────────────┐┌─┐
q_0: ┤ X ├┤ Delay(112[dt]) ├┤M├
└───┘└────────────────┘└╥┘
c: 1/════════════════════════╩═
0
This type of experiment slightly changes delay duration of interest.
However the quantization error should be less than alignment * dt.
"""
circuit = QuantumCircuit(1, 1)
circuit.x(0)
circuit.delay(100, 0, unit="dt")
circuit.measure(0, 0)
timed_circuit = self.time_conversion_pass(circuit)
scheduled_circuit = self.scheduling_pass(timed_circuit, property_set={"time_unit": "dt"})
aligned_circuit = self.align_measure_pass(
scheduled_circuit, property_set={"time_unit": "dt"}
)
ref_circuit = QuantumCircuit(1, 1)
ref_circuit.x(0)
ref_circuit.delay(112, 0, unit="dt")
ref_circuit.measure(0, 0)
self.assertEqual(aligned_circuit, ref_circuit)
def test_hanh_echo_experiment_type(self):
"""Test Hahn echo experiment type circuit.
(input)
┌────┐┌────────────────┐┌───┐┌────────────────┐┌────┐┌─┐
q_0: ┤ √X ├┤ Delay(100[dt]) ├┤ X ├┤ Delay(100[dt]) ├┤ √X ├┤M├
└────┘└────────────────┘└───┘└────────────────┘└────┘└╥┘
c: 1/══════════════════════════════════════════════════════╩═
0
(output)
┌────┐┌────────────────┐┌───┐┌────────────────┐┌────┐┌──────────────┐┌─┐
q_0: ┤ √X ├┤ Delay(100[dt]) ├┤ X ├┤ Delay(100[dt]) ├┤ √X ├┤ Delay(8[dt]) ├┤M├
└────┘└────────────────┘└───┘└────────────────┘└────┘└──────────────┘└╥┘
c: 1/══════════════════════════════════════════════════════════════════════╩═
0
This type of experiment doesn't change duration of interest (two in the middle).
However induces slight delay less than alignment * dt before measurement.
This might induce extra amplitude damping error.
"""
circuit = QuantumCircuit(1, 1)
circuit.sx(0)
circuit.delay(100, 0, unit="dt")
circuit.x(0)
circuit.delay(100, 0, unit="dt")
circuit.sx(0)
circuit.measure(0, 0)
timed_circuit = self.time_conversion_pass(circuit)
scheduled_circuit = self.scheduling_pass(timed_circuit, property_set={"time_unit": "dt"})
aligned_circuit = self.align_measure_pass(
scheduled_circuit, property_set={"time_unit": "dt"}
)
ref_circuit = QuantumCircuit(1, 1)
ref_circuit.sx(0)
ref_circuit.delay(100, 0, unit="dt")
ref_circuit.x(0)
ref_circuit.delay(100, 0, unit="dt")
ref_circuit.sx(0)
ref_circuit.delay(8, 0, unit="dt")
ref_circuit.measure(0, 0)
self.assertEqual(aligned_circuit, ref_circuit)
def test_mid_circuit_measure(self):
"""Test circuit with mid circuit measurement.
(input)
┌───┐┌────────────────┐┌─┐┌───────────────┐┌───┐┌────────────────┐┌─┐
q_0: ┤ X ├┤ Delay(100[dt]) ├┤M├┤ Delay(10[dt]) ├┤ X ├┤ Delay(120[dt]) ├┤M├
└───┘└────────────────┘└╥┘└───────────────┘└───┘└────────────────┘└╥┘
c: 2/════════════════════════╩══════════════════════════════════════════╩═
0 1
(output)
┌───┐┌────────────────┐┌─┐┌───────────────┐┌───┐┌────────────────┐┌─┐
q_0: ┤ X ├┤ Delay(112[dt]) ├┤M├┤ Delay(10[dt]) ├┤ X ├┤ Delay(134[dt]) ├┤M├
└───┘└────────────────┘└╥┘└───────────────┘└───┘└────────────────┘└╥┘
c: 2/════════════════════════╩══════════════════════════════════════════╩═
0 1
Extra delay is always added to the existing delay right before the measurement.
Delay after measurement is unchanged.
"""
circuit = QuantumCircuit(1, 2)
circuit.x(0)
circuit.delay(100, 0, unit="dt")
circuit.measure(0, 0)
circuit.delay(10, 0, unit="dt")
circuit.x(0)
circuit.delay(120, 0, unit="dt")
circuit.measure(0, 1)
timed_circuit = self.time_conversion_pass(circuit)
scheduled_circuit = self.scheduling_pass(timed_circuit, property_set={"time_unit": "dt"})
aligned_circuit = self.align_measure_pass(
scheduled_circuit, property_set={"time_unit": "dt"}
)
ref_circuit = QuantumCircuit(1, 2)
ref_circuit.x(0)
ref_circuit.delay(112, 0, unit="dt")
ref_circuit.measure(0, 0)
ref_circuit.delay(10, 0, unit="dt")
ref_circuit.x(0)
ref_circuit.delay(134, 0, unit="dt")
ref_circuit.measure(0, 1)
self.assertEqual(aligned_circuit, ref_circuit)
def test_mid_circuit_multiq_gates(self):
"""Test circuit with mid circuit measurement and multi qubit gates.
(input)
┌───┐┌────────────────┐┌─┐ ┌─┐
q_0: ┤ X ├┤ Delay(100[dt]) ├┤M├──■───────■──┤M├
└───┘└────────────────┘└╥┘┌─┴─┐┌─┐┌─┴─┐└╥┘
q_1: ────────────────────────╫─┤ X ├┤M├┤ X ├─╫─
║ └───┘└╥┘└───┘ ║
c: 2/════════════════════════╩═══════╩═══════╩═
0 1 0
(output)
┌───┐ ┌────────────────┐┌─┐ ┌─────────────────┐ ┌─┐»
q_0: ───────┤ X ├───────┤ Delay(112[dt]) ├┤M├──■──┤ Delay(1600[dt]) ├──■──┤M├»
┌──────┴───┴──────┐└────────────────┘└╥┘┌─┴─┐└───────┬─┬───────┘┌─┴─┐└╥┘»
q_1: ┤ Delay(1872[dt]) ├───────────────────╫─┤ X ├────────┤M├────────┤ X ├─╫─»
└─────────────────┘ ║ └───┘ └╥┘ └───┘ ║ »
c: 2/══════════════════════════════════════╩═══════════════╩═══════════════╩═»
0 1 0 »
«
«q_0: ───────────────────
« ┌─────────────────┐
«q_1: ┤ Delay(1600[dt]) ├
« └─────────────────┘
«c: 2/═══════════════════
«
Delay for the other channel paired by multi-qubit instruction is also scheduled.
Delay (1872dt) = X (160dt) + Delay (100dt + extra 12dt) + Measure (1600dt).
"""
circuit = QuantumCircuit(2, 2)
circuit.x(0)
circuit.delay(100, 0, unit="dt")
circuit.measure(0, 0)
circuit.cx(0, 1)
circuit.measure(1, 1)
circuit.cx(0, 1)
circuit.measure(0, 0)
timed_circuit = self.time_conversion_pass(circuit)
scheduled_circuit = self.scheduling_pass(timed_circuit, property_set={"time_unit": "dt"})
aligned_circuit = self.align_measure_pass(
scheduled_circuit, property_set={"time_unit": "dt"}
)
ref_circuit = QuantumCircuit(2, 2)
ref_circuit.x(0)
ref_circuit.delay(112, 0, unit="dt")
ref_circuit.measure(0, 0)
ref_circuit.delay(160 + 112 + 1600, 1, unit="dt")
ref_circuit.cx(0, 1)
ref_circuit.delay(1600, 0, unit="dt")
ref_circuit.measure(1, 1)
ref_circuit.cx(0, 1)
ref_circuit.delay(1600, 1, unit="dt")
ref_circuit.measure(0, 0)
self.assertEqual(aligned_circuit, ref_circuit)
def test_alignment_is_not_processed(self):
"""Test avoid pass processing if delay is aligned."""
circuit = QuantumCircuit(2, 2)
circuit.x(0)
circuit.delay(160, 0, unit="dt")
circuit.measure(0, 0)
circuit.cx(0, 1)
circuit.measure(1, 1)
circuit.cx(0, 1)
circuit.measure(0, 0)
# pre scheduling is not necessary because alignment is skipped
# this is to minimize breaking changes to existing code.
transpiled = self.align_measure_pass(circuit, property_set={"time_unit": "dt"})
self.assertEqual(transpiled, circuit)
def test_circuit_using_clbit(self):
"""Test a circuit with instructions using a common clbit.
(input)
┌───┐┌────────────────┐┌─┐
q_0: ┤ X ├┤ Delay(100[dt]) ├┤M├──────────────
└───┘└────────────────┘└╥┘ ┌───┐
q_1: ────────────────────────╫────┤ X ├──────
║ └─╥─┘ ┌─┐
q_2: ────────────────────────╫──────╫─────┤M├
║ ┌────╨────┐└╥┘
c: 1/════════════════════════╩═╡ c_0 = T ╞═╩═
0 └─────────┘ 0
(aligned)
┌───┐ ┌────────────────┐┌─┐┌────────────────┐
q_0: ───────┤ X ├───────┤ Delay(112[dt]) ├┤M├┤ Delay(160[dt]) ├───
┌──────┴───┴──────┐└────────────────┘└╥┘└─────┬───┬──────┘
q_1: ┤ Delay(1872[dt]) ├───────────────────╫───────┤ X ├──────────
└┬────────────────┤ ║ └─╥─┘ ┌─┐
q_2: ─┤ Delay(432[dt]) ├───────────────────╫─────────╫─────────┤M├
└────────────────┘ ║ ┌────╨────┐ └╥┘
c: 1/══════════════════════════════════════╩════╡ c_0 = T ╞═════╩═
0 └─────────┘ 0
Looking at the q_0, the total schedule length T becomes
160 (x) + 112 (aligned delay) + 1600 (measure) + 160 (delay) = 2032.
The last delay comes from ALAP scheduling called before the AlignMeasure pass,
which aligns stop times as late as possible, so the start time of x(1).c_if(0)
and the stop time of measure(0, 0) become T - 160.
"""
circuit = QuantumCircuit(3, 1)
circuit.x(0)
circuit.delay(100, 0, unit="dt")
circuit.measure(0, 0)
circuit.x(1).c_if(0, 1)
circuit.measure(2, 0)
timed_circuit = self.time_conversion_pass(circuit)
scheduled_circuit = self.scheduling_pass(timed_circuit, property_set={"time_unit": "dt"})
aligned_circuit = self.align_measure_pass(
scheduled_circuit, property_set={"time_unit": "dt"}
)
self.assertEqual(aligned_circuit.duration, 2032)
ref_circuit = QuantumCircuit(3, 1)
ref_circuit.x(0)
ref_circuit.delay(112, 0, unit="dt")
ref_circuit.delay(1872, 1, unit="dt") # 2032 - 160
ref_circuit.delay(432, 2, unit="dt") # 2032 - 1600
ref_circuit.measure(0, 0)
ref_circuit.x(1).c_if(0, 1)
ref_circuit.delay(160, 0, unit="dt")
ref_circuit.measure(2, 0)
self.assertEqual(aligned_circuit, ref_circuit)
class TestPulseGateValidation(QiskitTestCase):
"""A test for pulse gate validation pass."""
def setUp(self):
super().setUp()
self.pulse_gate_validation_pass = ValidatePulseGates(granularity=16, min_length=64)
def test_invalid_pulse_duration(self):
"""Kill pass manager if invalid pulse gate is found."""
# this is invalid duration pulse
# this will cause backend error since this doesn't fit with waveform memory chunk.
custom_gate = pulse.Schedule(name="custom_x_gate")
custom_gate.insert(
0, pulse.Play(pulse.Constant(100, 0.1), pulse.DriveChannel(0)), inplace=True
)
circuit = QuantumCircuit(1)
circuit.x(0)
circuit.add_calibration("x", qubits=(0,), schedule=custom_gate)
with self.assertRaises(TranspilerError):
self.pulse_gate_validation_pass(circuit)
def test_short_pulse_duration(self):
"""Kill pass manager if invalid pulse gate is found."""
# this is invalid duration pulse
# this will cause backend error since this doesn't fit with waveform memory chunk.
custom_gate = pulse.Schedule(name="custom_x_gate")
custom_gate.insert(
0, pulse.Play(pulse.Constant(32, 0.1), pulse.DriveChannel(0)), inplace=True
)
circuit = QuantumCircuit(1)
circuit.x(0)
circuit.add_calibration("x", qubits=(0,), schedule=custom_gate)
with self.assertRaises(TranspilerError):
self.pulse_gate_validation_pass(circuit)
def test_short_pulse_duration_multiple_pulse(self):
"""Kill pass manager if invalid pulse gate is found."""
# this is invalid duration pulse
# however total gate schedule length is 64, which accidentally satisfies the constraints
# this should fail in the validation
custom_gate = pulse.Schedule(name="custom_x_gate")
custom_gate.insert(
0, pulse.Play(pulse.Constant(32, 0.1), pulse.DriveChannel(0)), inplace=True
)
custom_gate.insert(
32, pulse.Play(pulse.Constant(32, 0.1), pulse.DriveChannel(0)), inplace=True
)
circuit = QuantumCircuit(1)
circuit.x(0)
circuit.add_calibration("x", qubits=(0,), schedule=custom_gate)
with self.assertRaises(TranspilerError):
self.pulse_gate_validation_pass(circuit)
def test_valid_pulse_duration(self):
"""No error raises if valid calibration is provided."""
# this is valid duration pulse
custom_gate = pulse.Schedule(name="custom_x_gate")
custom_gate.insert(
0, pulse.Play(pulse.Constant(160, 0.1), pulse.DriveChannel(0)), inplace=True
)
circuit = QuantumCircuit(1)
circuit.x(0)
circuit.add_calibration("x", qubits=(0,), schedule=custom_gate)
# just not raise an error
self.pulse_gate_validation_pass(circuit)
def test_no_calibration(self):
"""No error raises if no calibration is addedd."""
circuit = QuantumCircuit(1)
circuit.x(0)
# just not raise an error
self.pulse_gate_validation_pass(circuit)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Testing InverseCancellation
"""
import unittest
import numpy as np
from qiskit import QuantumCircuit
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.transpiler.passes import InverseCancellation
from qiskit.transpiler import PassManager
from qiskit.test import QiskitTestCase
from qiskit.circuit.library import RXGate, HGate, CXGate, PhaseGate, XGate, TGate, TdgGate
class TestInverseCancellation(QiskitTestCase):
"""Test the InverseCancellation transpiler pass."""
def test_basic_self_inverse(self):
"""Test that a single self-inverse gate as input can be cancelled."""
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.h(0)
pass_ = InverseCancellation([HGate()])
pm = PassManager(pass_)
new_circ = pm.run(qc)
gates_after = new_circ.count_ops()
self.assertNotIn("h", gates_after)
def test_odd_number_self_inverse(self):
"""Test that an odd number of self-inverse gates leaves one gate remaining."""
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.h(0)
qc.h(0)
pass_ = InverseCancellation([HGate()])
pm = PassManager(pass_)
new_circ = pm.run(qc)
gates_after = new_circ.count_ops()
self.assertIn("h", gates_after)
self.assertEqual(gates_after["h"], 1)
def test_basic_cx_self_inverse(self):
"""Test that a single self-inverse cx gate as input can be cancelled."""
qc = QuantumCircuit(2, 2)
qc.cx(0, 1)
qc.cx(0, 1)
pass_ = InverseCancellation([CXGate()])
pm = PassManager(pass_)
new_circ = pm.run(qc)
gates_after = new_circ.count_ops()
self.assertNotIn("cx", gates_after)
def test_basic_gate_inverse(self):
"""Test that a basic pair of gate inverse can be cancelled."""
qc = QuantumCircuit(2, 2)
qc.rx(np.pi / 4, 0)
qc.rx(-np.pi / 4, 0)
pass_ = InverseCancellation([(RXGate(np.pi / 4), RXGate(-np.pi / 4))])
pm = PassManager(pass_)
new_circ = pm.run(qc)
gates_after = new_circ.count_ops()
self.assertNotIn("rx", gates_after)
def test_non_inverse_do_not_cancel(self):
"""Test that non-inverse gate pairs do not cancel."""
qc = QuantumCircuit(2, 2)
qc.rx(np.pi / 4, 0)
qc.rx(np.pi / 4, 0)
pass_ = InverseCancellation([(RXGate(np.pi / 4), RXGate(-np.pi / 4))])
pm = PassManager(pass_)
new_circ = pm.run(qc)
gates_after = new_circ.count_ops()
self.assertIn("rx", gates_after)
self.assertEqual(gates_after["rx"], 2)
def test_non_consecutive_gates(self):
"""Test that only consecutive gates cancel."""
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.h(0)
qc.h(0)
qc.cx(0, 1)
qc.cx(0, 1)
qc.h(0)
pass_ = InverseCancellation([HGate(), CXGate()])
pm = PassManager(pass_)
new_circ = pm.run(qc)
gates_after = new_circ.count_ops()
self.assertNotIn("cx", gates_after)
self.assertEqual(gates_after["h"], 2)
def test_gate_inverse_phase_gate(self):
"""Test that an inverse pair of a PhaseGate can be cancelled."""
qc = QuantumCircuit(2, 2)
qc.p(np.pi / 4, 0)
qc.p(-np.pi / 4, 0)
pass_ = InverseCancellation([(PhaseGate(np.pi / 4), PhaseGate(-np.pi / 4))])
pm = PassManager(pass_)
new_circ = pm.run(qc)
gates_after = new_circ.count_ops()
self.assertNotIn("p", gates_after)
def test_self_inverse_on_different_qubits(self):
"""Test that self_inverse gates cancel on the correct qubits."""
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.h(1)
qc.h(0)
qc.h(1)
pass_ = InverseCancellation([HGate()])
pm = PassManager(pass_)
new_circ = pm.run(qc)
gates_after = new_circ.count_ops()
self.assertNotIn("h", gates_after)
def test_non_inverse_raise_error(self):
"""Test that non-inverse gate inputs raise an error."""
qc = QuantumCircuit(2, 2)
qc.rx(np.pi / 2, 0)
qc.rx(np.pi / 4, 0)
with self.assertRaises(TranspilerError):
InverseCancellation([RXGate(0.5)])
def test_non_gate_inverse_raise_error(self):
"""Test that non-inverse gate inputs raise an error."""
qc = QuantumCircuit(2, 2)
qc.rx(np.pi / 4, 0)
qc.rx(np.pi / 4, 0)
with self.assertRaises(TranspilerError):
InverseCancellation([(RXGate(np.pi / 4))])
def test_string_gate_error(self):
"""Test that when gate is passed as a string an error is raised."""
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.h(0)
with self.assertRaises(TranspilerError):
InverseCancellation(["h"])
def test_consecutive_self_inverse_h_x_gate(self):
"""Test that only consecutive self-inverse gates cancel."""
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.h(0)
qc.h(0)
qc.x(0)
qc.x(0)
qc.h(0)
pass_ = InverseCancellation([HGate(), XGate()])
pm = PassManager(pass_)
new_circ = pm.run(qc)
gates_after = new_circ.count_ops()
self.assertNotIn("x", gates_after)
self.assertEqual(gates_after["h"], 2)
def test_inverse_with_different_names(self):
"""Test that inverse gates that have different names."""
qc = QuantumCircuit(2, 2)
qc.t(0)
qc.tdg(0)
pass_ = InverseCancellation([(TGate(), TdgGate())])
pm = PassManager(pass_)
new_circ = pm.run(qc)
gates_after = new_circ.count_ops()
self.assertNotIn("t", gates_after)
self.assertNotIn("tdg", gates_after)
def test_three_alternating_inverse_gates(self):
"""Test that inverse cancellation works correctly for alternating sequences
of inverse gates of odd-length."""
qc = QuantumCircuit(2, 2)
qc.p(np.pi / 4, 0)
qc.p(-np.pi / 4, 0)
qc.p(np.pi / 4, 0)
pass_ = InverseCancellation([(PhaseGate(np.pi / 4), PhaseGate(-np.pi / 4))])
pm = PassManager(pass_)
new_circ = pm.run(qc)
gates_after = new_circ.count_ops()
self.assertIn("p", gates_after)
self.assertEqual(gates_after["p"], 1)
def test_four_alternating_inverse_gates(self):
"""Test that inverse cancellation works correctly for alternating sequences
of inverse gates of even-length."""
qc = QuantumCircuit(2, 2)
qc.p(np.pi / 4, 0)
qc.p(-np.pi / 4, 0)
qc.p(np.pi / 4, 0)
qc.p(-np.pi / 4, 0)
pass_ = InverseCancellation([(PhaseGate(np.pi / 4), PhaseGate(-np.pi / 4))])
pm = PassManager(pass_)
new_circ = pm.run(qc)
gates_after = new_circ.count_ops()
self.assertNotIn("p", gates_after)
def test_five_alternating_inverse_gates(self):
"""Test that inverse cancellation works correctly for alternating sequences
of inverse gates of odd-length."""
qc = QuantumCircuit(2, 2)
qc.p(np.pi / 4, 0)
qc.p(-np.pi / 4, 0)
qc.p(np.pi / 4, 0)
qc.p(-np.pi / 4, 0)
qc.p(np.pi / 4, 0)
pass_ = InverseCancellation([(PhaseGate(np.pi / 4), PhaseGate(-np.pi / 4))])
pm = PassManager(pass_)
new_circ = pm.run(qc)
gates_after = new_circ.count_ops()
self.assertIn("p", gates_after)
self.assertEqual(gates_after["p"], 1)
def test_sequence_of_inverse_gates_1(self):
"""Test that inverse cancellation works correctly for more general sequences
of inverse gates. In this test two pairs of inverse gates are supposed to
cancel out."""
qc = QuantumCircuit(2, 2)
qc.p(np.pi / 4, 0)
qc.p(-np.pi / 4, 0)
qc.p(-np.pi / 4, 0)
qc.p(np.pi / 4, 0)
qc.p(np.pi / 4, 0)
pass_ = InverseCancellation([(PhaseGate(np.pi / 4), PhaseGate(-np.pi / 4))])
pm = PassManager(pass_)
new_circ = pm.run(qc)
gates_after = new_circ.count_ops()
self.assertIn("p", gates_after)
self.assertEqual(gates_after["p"], 1)
def test_sequence_of_inverse_gates_2(self):
"""Test that inverse cancellation works correctly for more general sequences
of inverse gates. In this test, in theory three pairs of inverse gates can
cancel out, but in practice only two pairs are back-to-back."""
qc = QuantumCircuit(2, 2)
qc.p(np.pi / 4, 0)
qc.p(np.pi / 4, 0)
qc.p(-np.pi / 4, 0)
qc.p(-np.pi / 4, 0)
qc.p(-np.pi / 4, 0)
qc.p(np.pi / 4, 0)
qc.p(np.pi / 4, 0)
pass_ = InverseCancellation([(PhaseGate(np.pi / 4), PhaseGate(-np.pi / 4))])
pm = PassManager(pass_)
new_circ = pm.run(qc)
gates_after = new_circ.count_ops()
self.assertIn("p", gates_after)
self.assertEqual(gates_after["p"] % 2, 1)
def test_cx_do_not_wrongly_cancel(self):
"""Test that CX(0,1) and CX(1, 0) do not cancel out, when (CX, CX) is passed
as an inverse pair."""
qc = QuantumCircuit(2, 0)
qc.cx(0, 1)
qc.cx(1, 0)
pass_ = InverseCancellation([(CXGate(), CXGate())])
pm = PassManager(pass_)
new_circ = pm.run(qc)
gates_after = new_circ.count_ops()
self.assertIn("cx", gates_after)
self.assertEqual(gates_after["cx"], 2)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test KAK over optimization"""
import unittest
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, transpile
from qiskit.circuit.library import CU1Gate
from qiskit.test import QiskitTestCase
class TestKAKOverOptim(QiskitTestCase):
"""Tests to verify that KAK decomposition
does not over optimize.
"""
def test_cz_optimization(self):
"""Test that KAK does not run on a cz gate"""
qr = QuantumRegister(2)
qc = QuantumCircuit(qr)
qc.cz(qr[0], qr[1])
cz_circ = transpile(
qc,
None,
coupling_map=[[0, 1], [1, 0]],
basis_gates=["u1", "u2", "u3", "id", "cx"],
optimization_level=3,
)
ops = cz_circ.count_ops()
self.assertEqual(ops["u2"], 2)
self.assertEqual(ops["cx"], 1)
self.assertFalse("u3" in ops.keys())
def test_cu1_optimization(self):
"""Test that KAK does run on a cu1 gate and
reduces the cx count from two to one.
"""
qr = QuantumRegister(2)
qc = QuantumCircuit(qr)
qc.append(CU1Gate(np.pi), [qr[0], qr[1]])
cu1_circ = transpile(
qc,
None,
coupling_map=[[0, 1], [1, 0]],
basis_gates=["u1", "u2", "u3", "id", "cx"],
optimization_level=3,
)
ops = cu1_circ.count_ops()
self.assertEqual(ops["cx"], 1)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the Layout Score pass"""
import unittest
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.circuit.library import CXGate
from qiskit.transpiler.passes import Layout2qDistance
from qiskit.transpiler import CouplingMap, Layout
from qiskit.converters import circuit_to_dag
from qiskit.transpiler.target import Target
from qiskit.test import QiskitTestCase
class TestLayoutScoreError(QiskitTestCase):
"""Test error-ish of Layout Score"""
def test_no_layout(self):
"""No Layout. Empty Circuit CouplingMap map: None. Result: None"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
coupling = CouplingMap()
layout = None
dag = circuit_to_dag(circuit)
pass_ = Layout2qDistance(coupling)
pass_.property_set["layout"] = layout
pass_.run(dag)
self.assertIsNone(pass_.property_set["layout_score"])
class TestTrivialLayoutScore(QiskitTestCase):
"""Trivial layout scenarios"""
def test_no_cx(self):
"""Empty Circuit CouplingMap map: None. Result: 0"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
coupling = CouplingMap()
layout = Layout().generate_trivial_layout(qr)
dag = circuit_to_dag(circuit)
pass_ = Layout2qDistance(coupling)
pass_.property_set["layout"] = layout
pass_.run(dag)
self.assertEqual(pass_.property_set["layout_score"], 0)
def test_swap_mapped_true(self):
"""Mapped circuit. Good Layout
qr0 (0):--(+)---(+)-
| |
qr1 (1):---.-----|--
|
qr2 (2):---------.--
CouplingMap map: [1]--[0]--[2]
"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[2])
coupling = CouplingMap([[0, 1], [0, 2]])
layout = Layout().generate_trivial_layout(qr)
dag = circuit_to_dag(circuit)
pass_ = Layout2qDistance(coupling)
pass_.property_set["layout"] = layout
pass_.run(dag)
self.assertEqual(pass_.property_set["layout_score"], 0)
def test_swap_mapped_false(self):
"""Needs [0]-[1] in a [0]--[2]--[1] Result:1
qr0:--(+)--
|
qr1:---.---
CouplingMap map: [0]--[2]--[1]
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
coupling = CouplingMap([[0, 2], [2, 1]])
layout = Layout().generate_trivial_layout(qr)
dag = circuit_to_dag(circuit)
pass_ = Layout2qDistance(coupling)
pass_.property_set["layout"] = layout
pass_.run(dag)
self.assertEqual(pass_.property_set["layout_score"], 1)
def test_swap_mapped_true_target(self):
"""Mapped circuit. Good Layout
qr0 (0):--(+)---(+)-
| |
qr1 (1):---.-----|--
|
qr2 (2):---------.--
CouplingMap map: [1]--[0]--[2]
"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[2])
target = Target()
target.add_instruction(CXGate(), {(0, 1): None, (0, 2): None})
layout = Layout().generate_trivial_layout(qr)
dag = circuit_to_dag(circuit)
pass_ = Layout2qDistance(target)
pass_.property_set["layout"] = layout
pass_.run(dag)
self.assertEqual(pass_.property_set["layout_score"], 0)
def test_swap_mapped_false_target(self):
"""Needs [0]-[1] in a [0]--[2]--[1] Result:1
qr0:--(+)--
|
qr1:---.---
CouplingMap map: [0]--[2]--[1]
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
target = Target()
target.add_instruction(CXGate(), {(0, 2): None, (2, 1): None})
layout = Layout().generate_trivial_layout(qr)
dag = circuit_to_dag(circuit)
pass_ = Layout2qDistance(target)
pass_.property_set["layout"] = layout
pass_.run(dag)
self.assertEqual(pass_.property_set["layout_score"], 1)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the LayoutTransformation pass"""
import unittest
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.converters import circuit_to_dag
from qiskit.test import QiskitTestCase
from qiskit.transpiler import CouplingMap, Layout, Target
from qiskit.circuit.library import CXGate
from qiskit.transpiler.passes import LayoutTransformation
class TestLayoutTransformation(QiskitTestCase):
"""
Tests the LayoutTransformation pass.
"""
def test_three_qubit(self):
"""Test if the permutation {0->2,1->0,2->1} is implemented correctly."""
v = QuantumRegister(3, "v") # virtual qubits
coupling = CouplingMap([[0, 1], [1, 2]])
from_layout = Layout({v[0]: 0, v[1]: 1, v[2]: 2})
to_layout = Layout({v[0]: 2, v[1]: 0, v[2]: 1})
ltpass = LayoutTransformation(
coupling_map=coupling, from_layout=from_layout, to_layout=to_layout, seed=42
)
qc = QuantumCircuit(3)
dag = circuit_to_dag(qc)
output_dag = ltpass.run(dag)
expected = QuantumCircuit(3)
expected.swap(1, 0)
expected.swap(1, 2)
self.assertEqual(circuit_to_dag(expected), output_dag)
def test_four_qubit(self):
"""Test if the permutation {0->3,1->0,2->1,3->2} is implemented correctly."""
v = QuantumRegister(4, "v") # virtual qubits
coupling = CouplingMap([[0, 1], [1, 2], [2, 3]])
from_layout = Layout({v[0]: 0, v[1]: 1, v[2]: 2, v[3]: 3})
to_layout = Layout({v[0]: 3, v[1]: 0, v[2]: 1, v[3]: 2})
ltpass = LayoutTransformation(
coupling_map=coupling, from_layout=from_layout, to_layout=to_layout, seed=42
)
qc = QuantumCircuit(4) # input (empty) physical circuit
dag = circuit_to_dag(qc)
output_dag = ltpass.run(dag)
expected = QuantumCircuit(4)
expected.swap(1, 0)
expected.swap(1, 2)
expected.swap(2, 3)
self.assertEqual(circuit_to_dag(expected), output_dag)
def test_four_qubit_with_target(self):
"""Test if the permutation {0->3,1->0,2->1,3->2} is implemented correctly."""
v = QuantumRegister(4, "v") # virtual qubits
target = Target()
target.add_instruction(CXGate(), {(0, 1): None, (1, 2): None, (2, 3): None})
from_layout = Layout({v[0]: 0, v[1]: 1, v[2]: 2, v[3]: 3})
to_layout = Layout({v[0]: 3, v[1]: 0, v[2]: 1, v[3]: 2})
ltpass = LayoutTransformation(target, from_layout=from_layout, to_layout=to_layout, seed=42)
qc = QuantumCircuit(4) # input (empty) physical circuit
dag = circuit_to_dag(qc)
output_dag = ltpass.run(dag)
expected = QuantumCircuit(4)
expected.swap(1, 0)
expected.swap(1, 2)
expected.swap(2, 3)
self.assertEqual(circuit_to_dag(expected), output_dag)
@unittest.skip("rustworkx token_swapper produces correct, but sometimes random output")
def test_full_connected_coupling_map(self):
"""Test if the permutation {0->3,1->0,2->1,3->2} in a fully connected map."""
# TODO: Remove skip when https://github.com/Qiskit/rustworkx/pull/897 is
# merged and released. Should be rustworkx 0.13.1.
v = QuantumRegister(4, "v") # virtual qubits
from_layout = Layout({v[0]: 0, v[1]: 1, v[2]: 2, v[3]: 3})
to_layout = Layout({v[0]: 3, v[1]: 0, v[2]: 1, v[3]: 2})
ltpass = LayoutTransformation(
coupling_map=None, from_layout=from_layout, to_layout=to_layout, seed=42
)
qc = QuantumCircuit(4) # input (empty) physical circuit
dag = circuit_to_dag(qc)
output_dag = ltpass.run(dag)
expected = QuantumCircuit(4)
expected.swap(1, 0)
expected.swap(2, 1)
expected.swap(3, 2)
self.assertEqual(circuit_to_dag(expected), output_dag)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the LookaheadSwap pass"""
import unittest
from numpy import pi
from qiskit.dagcircuit import DAGCircuit
from qiskit.transpiler.passes import LookaheadSwap
from qiskit.transpiler import CouplingMap, Target
from qiskit.converters import circuit_to_dag
from qiskit.circuit.library import CXGate
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import FakeMelbourne
class TestLookaheadSwap(QiskitTestCase):
"""Tests the LookaheadSwap pass."""
def test_lookahead_swap_doesnt_modify_mapped_circuit(self):
"""Test that lookahead swap is idempotent.
It should not modify a circuit which is already compatible with the
coupling map, and can be applied repeatedly without modifying the circuit.
"""
qr = QuantumRegister(3, name="q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[2])
circuit.cx(qr[0], qr[1])
original_dag = circuit_to_dag(circuit)
# Create coupling map which contains all two-qubit gates in the circuit.
coupling_map = CouplingMap([[0, 1], [0, 2]])
mapped_dag = LookaheadSwap(coupling_map).run(original_dag)
self.assertEqual(original_dag, mapped_dag)
remapped_dag = LookaheadSwap(coupling_map).run(mapped_dag)
self.assertEqual(mapped_dag, remapped_dag)
def test_lookahead_swap_should_add_a_single_swap(self):
"""Test that LookaheadSwap will insert a SWAP to match layout.
For a single cx gate which is not available in the current layout, test
that the mapper inserts a single swap to enable the gate.
"""
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[2])
dag_circuit = circuit_to_dag(circuit)
coupling_map = CouplingMap([[0, 1], [1, 2]])
mapped_dag = LookaheadSwap(coupling_map).run(dag_circuit)
self.assertEqual(
mapped_dag.count_ops().get("swap", 0), dag_circuit.count_ops().get("swap", 0) + 1
)
def test_lookahead_swap_finds_minimal_swap_solution(self):
"""Of many valid SWAPs, test that LookaheadSwap finds the cheapest path.
For a two CNOT circuit: cx q[0],q[2]; cx q[0],q[1]
on the initial layout: qN -> qN
(At least) two solutions exist:
- SWAP q[0],[1], cx q[0],q[2], cx q[0],q[1]
- SWAP q[1],[2], cx q[0],q[2], SWAP q[1],q[2], cx q[0],q[1]
Verify that we find the first solution, as it requires fewer SWAPs.
"""
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[2])
circuit.cx(qr[0], qr[1])
dag_circuit = circuit_to_dag(circuit)
coupling_map = CouplingMap([[0, 1], [1, 2]])
mapped_dag = LookaheadSwap(coupling_map).run(dag_circuit)
self.assertEqual(
mapped_dag.count_ops().get("swap", 0), dag_circuit.count_ops().get("swap", 0) + 1
)
def test_lookahead_swap_maps_measurements(self):
"""Verify measurement nodes are updated to map correct cregs to re-mapped qregs.
Create a circuit with measures on q0 and q2, following a swap between q0 and q2.
Since that swap is not in the coupling, one of the two will be required to move.
Verify that the mapped measure corresponds to one of the two possible layouts following
the swap.
"""
qr = QuantumRegister(3, "q")
cr = ClassicalRegister(2)
circuit = QuantumCircuit(qr, cr)
circuit.cx(qr[0], qr[2])
circuit.measure(qr[0], cr[0])
circuit.measure(qr[2], cr[1])
dag_circuit = circuit_to_dag(circuit)
coupling_map = CouplingMap([[0, 1], [1, 2]])
mapped_dag = LookaheadSwap(coupling_map).run(dag_circuit)
mapped_measure_qargs = {op.qargs[0] for op in mapped_dag.named_nodes("measure")}
self.assertIn(mapped_measure_qargs, [{qr[0], qr[1]}, {qr[1], qr[2]}])
def test_lookahead_swap_maps_measurements_with_target(self):
"""Verify measurement nodes are updated to map correct cregs to re-mapped qregs.
Create a circuit with measures on q0 and q2, following a swap between q0 and q2.
Since that swap is not in the coupling, one of the two will be required to move.
Verify that the mapped measure corresponds to one of the two possible layouts following
the swap.
"""
qr = QuantumRegister(3, "q")
cr = ClassicalRegister(2)
circuit = QuantumCircuit(qr, cr)
circuit.cx(qr[0], qr[2])
circuit.measure(qr[0], cr[0])
circuit.measure(qr[2], cr[1])
dag_circuit = circuit_to_dag(circuit)
target = Target()
target.add_instruction(CXGate(), {(0, 1): None, (1, 2): None})
mapped_dag = LookaheadSwap(target).run(dag_circuit)
mapped_measure_qargs = {op.qargs[0] for op in mapped_dag.named_nodes("measure")}
self.assertIn(mapped_measure_qargs, [{qr[0], qr[1]}, {qr[1], qr[2]}])
def test_lookahead_swap_maps_barriers(self):
"""Verify barrier nodes are updated to re-mapped qregs.
Create a circuit with a barrier on q0 and q2, following a swap between q0 and q2.
Since that swap is not in the coupling, one of the two will be required to move.
Verify that the mapped barrier corresponds to one of the two possible layouts following
the swap.
"""
qr = QuantumRegister(3, "q")
cr = ClassicalRegister(2)
circuit = QuantumCircuit(qr, cr)
circuit.cx(qr[0], qr[2])
circuit.barrier(qr[0], qr[2])
dag_circuit = circuit_to_dag(circuit)
coupling_map = CouplingMap([[0, 1], [1, 2]])
mapped_dag = LookaheadSwap(coupling_map).run(dag_circuit)
mapped_barrier_qargs = [set(op.qargs) for op in mapped_dag.named_nodes("barrier")][0]
self.assertIn(mapped_barrier_qargs, [{qr[0], qr[1]}, {qr[1], qr[2]}])
def test_lookahead_swap_higher_depth_width_is_better(self):
"""Test that lookahead swap finds better circuit with increasing search space.
Increasing the tree width and depth is expected to yield a better (or same) quality
circuit, in the form of fewer SWAPs.
"""
# q_0: ──■───────────────────■───────────────────────────────────────────────»
# ┌─┴─┐ │ ┌───┐ »
# q_1: ┤ X ├──■──────────────┼─────────────────┤ X ├─────────────────────────»
# └───┘┌─┴─┐ │ └─┬─┘┌───┐ ┌───┐ »
# q_2: ─────┤ X ├──■─────────┼───────────────────┼──┤ X ├──────────┤ X ├──■──»
# └───┘┌─┴─┐ ┌─┴─┐ │ └─┬─┘ ┌───┐└─┬─┘ │ »
# q_3: ──────────┤ X ├──■──┤ X ├─────────────────┼────┼────■──┤ X ├──┼────┼──»
# └───┘┌─┴─┐└───┘ ┌───┐ │ │ │ └─┬─┘ │ │ »
# q_4: ───────────────┤ X ├──■────────────┤ X ├──┼────■────┼────┼────┼────┼──»
# └───┘┌─┴─┐ └─┬─┘ │ │ │ │ │ »
# q_5: ────────────────────┤ X ├──■─────────┼────┼─────────┼────■────┼────┼──»
# └───┘┌─┴─┐ │ │ │ │ │ »
# q_6: ─────────────────────────┤ X ├──■────■────┼─────────┼─────────■────┼──»
# └───┘┌─┴─┐ │ ┌─┴─┐ ┌─┴─┐»
# q_7: ──────────────────────────────┤ X ├───────■───────┤ X ├──────────┤ X ├»
# └───┘ └───┘ └───┘»
# «q_0: ──■───────
# « │
# «q_1: ──┼───────
# « │
# «q_2: ──┼───────
# « │
# «q_3: ──┼───────
# « │
# «q_4: ──┼───────
# « │
# «q_5: ──┼────■──
# « ┌─┴─┐ │
# «q_6: ┤ X ├──┼──
# « └───┘┌─┴─┐
# «q_7: ─────┤ X ├
# « └───┘
qr = QuantumRegister(8, name="q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[2])
circuit.cx(qr[2], qr[3])
circuit.cx(qr[3], qr[4])
circuit.cx(qr[4], qr[5])
circuit.cx(qr[5], qr[6])
circuit.cx(qr[6], qr[7])
circuit.cx(qr[0], qr[3])
circuit.cx(qr[6], qr[4])
circuit.cx(qr[7], qr[1])
circuit.cx(qr[4], qr[2])
circuit.cx(qr[3], qr[7])
circuit.cx(qr[5], qr[3])
circuit.cx(qr[6], qr[2])
circuit.cx(qr[2], qr[7])
circuit.cx(qr[0], qr[6])
circuit.cx(qr[5], qr[7])
original_dag = circuit_to_dag(circuit)
# Create a ring of 8 connected qubits
coupling_map = CouplingMap.from_grid(num_rows=2, num_columns=4)
mapped_dag_1 = LookaheadSwap(coupling_map, search_depth=3, search_width=3).run(original_dag)
mapped_dag_2 = LookaheadSwap(coupling_map, search_depth=5, search_width=5).run(original_dag)
num_swaps_1 = mapped_dag_1.count_ops().get("swap", 0)
num_swaps_2 = mapped_dag_2.count_ops().get("swap", 0)
self.assertLessEqual(num_swaps_2, num_swaps_1)
def test_lookahead_swap_hang_in_min_case(self):
"""Verify LookaheadSwap does not stall in minimal case."""
# ref: https://github.com/Qiskit/qiskit-terra/issues/2171
qr = QuantumRegister(14, "q")
qc = QuantumCircuit(qr)
qc.cx(qr[0], qr[13])
qc.cx(qr[1], qr[13])
qc.cx(qr[1], qr[0])
qc.cx(qr[13], qr[1])
dag = circuit_to_dag(qc)
cmap = CouplingMap(FakeMelbourne().configuration().coupling_map)
out = LookaheadSwap(cmap, search_depth=4, search_width=4).run(dag)
self.assertIsInstance(out, DAGCircuit)
def test_lookahead_swap_hang_full_case(self):
"""Verify LookaheadSwap does not stall in reported case."""
# ref: https://github.com/Qiskit/qiskit-terra/issues/2171
qr = QuantumRegister(14, "q")
qc = QuantumCircuit(qr)
qc.cx(qr[0], qr[13])
qc.cx(qr[1], qr[13])
qc.cx(qr[1], qr[0])
qc.cx(qr[13], qr[1])
qc.cx(qr[6], qr[7])
qc.cx(qr[8], qr[7])
qc.cx(qr[8], qr[6])
qc.cx(qr[7], qr[8])
qc.cx(qr[0], qr[13])
qc.cx(qr[1], qr[0])
qc.cx(qr[13], qr[1])
qc.cx(qr[0], qr[1])
dag = circuit_to_dag(qc)
cmap = CouplingMap(FakeMelbourne().configuration().coupling_map)
out = LookaheadSwap(cmap, search_depth=4, search_width=4).run(dag)
self.assertIsInstance(out, DAGCircuit)
def test_global_phase_preservation(self):
"""Test that LookaheadSwap preserves global phase"""
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.global_phase = pi / 3
circuit.cx(qr[0], qr[2])
dag_circuit = circuit_to_dag(circuit)
coupling_map = CouplingMap([[0, 1], [1, 2]])
mapped_dag = LookaheadSwap(coupling_map).run(dag_circuit)
self.assertEqual(mapped_dag.global_phase, circuit.global_phase)
self.assertEqual(
mapped_dag.count_ops().get("swap", 0), dag_circuit.count_ops().get("swap", 0) + 1
)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Meta tests for mappers.
The test checks the output of the swapper to a ground truth DAG (one for each
test/swapper) saved in as a QASM (in `test/python/qasm/`). If they need
to be regenerated, the DAG candidate is compiled and run in a simulator and
the count is checked before being saved. This happens with (in the root
directory):
> python -m test.python.transpiler.test_mappers regenerate
To make a new swapper pass throw all the common tests, create a new class inside the file
`path/to/test_mappers.py` that:
* the class name should start with `Tests...`.
* inheriting from ``SwapperCommonTestCases, QiskitTestCase``
* overwrite the required attribute ``pass_class``
For example::
class TestsSomeSwap(SwapperCommonTestCases, QiskitTestCase):
pass_class = SomeSwap # The pass class
additional_args = {'seed_transpiler': 42} # In case SomeSwap.__init__ requires
# additional arguments
To **add a test for all the swappers**, add a new method ``test_foo``to the
``SwapperCommonTestCases`` class:
* defining the following required ``self`` attributes: ``self.count``,
``self.shots``, ``self.delta``. They are required for the regeneration of the
ground truth.
* use the ``self.assertResult`` assertion for comparing for regeneration of the
ground truth.
* explicitly set a unique ``name`` of the ``QuantumCircuit``, as it it used
for the name of the QASM file of the ground truth.
For example::
def test_a_common_test(self):
self.count = {'000': 512, '110': 512} # The expected count for this circuit
self.shots = 1024 # Shots to run in the backend.
self.delta = 5 # This is delta for the AlmostEqual during
# the count check
coupling_map = [[0, 1], [0, 2]] # The coupling map for this specific test
qr = QuantumRegister(3, 'q') #
cr = ClassicalRegister(3, 'c') # Set the circuit to test
circuit = QuantumCircuit(qr, cr, # and don't forget to put a name
name='some_name') # (it will be used to save the QASM
circuit.h(qr[1]) #
circuit.cx(qr[1], qr[2]) #
circuit.measure(qr, cr) #
result = transpile(circuit, self.create_backend(), coupling_map=coupling_map,
pass_manager=self.create_passmanager(coupling_map))
self.assertResult(result, circuit)
```
"""
# pylint: disable=attribute-defined-outside-init
import unittest
import os
import sys
from qiskit import execute
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit, BasicAer
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import BasicSwap, LookaheadSwap, StochasticSwap, SabreSwap
from qiskit.transpiler.passes import SetLayout
from qiskit.transpiler import CouplingMap, Layout
from qiskit.test import QiskitTestCase
class CommonUtilitiesMixin:
"""Utilities for meta testing.
Subclasses should redefine the ``pass_class`` argument, with a Swap Mapper
class.
Note: This class assumes that the subclass is also inheriting from
``QiskitTestCase``, and it uses ``QiskitTestCase`` methods directly.
"""
regenerate_expected = False
seed_simulator = 42
seed_transpiler = 42
additional_args = {}
pass_class = None
def create_passmanager(self, coupling_map, initial_layout=None):
"""Returns a PassManager using self.pass_class(coupling_map, initial_layout)"""
passmanager = PassManager()
if initial_layout:
passmanager.append(SetLayout(Layout(initial_layout)))
# pylint: disable=not-callable
passmanager.append(self.pass_class(CouplingMap(coupling_map), **self.additional_args))
return passmanager
def create_backend(self):
"""Returns a Backend."""
return BasicAer.get_backend("qasm_simulator")
def generate_ground_truth(self, transpiled_result, filename):
"""Generates the expected result into a file.
Checks if transpiled_result matches self.counts by running in a backend
(self.create_backend()). That's saved in a QASM in filename.
Args:
transpiled_result (DAGCircuit): The DAGCircuit to execute.
filename (string): Where the QASM is saved.
"""
sim_backend = self.create_backend()
job = execute(
transpiled_result,
sim_backend,
seed_simulator=self.seed_simulator,
seed_transpiler=self.seed_transpiler,
shots=self.shots,
)
self.assertDictAlmostEqual(self.counts, job.result().get_counts(), delta=self.delta)
transpiled_result.qasm(formatted=False, filename=filename)
def assertResult(self, result, circuit):
"""Fetches the QASM in circuit.name file and compares it with result."""
qasm_name = f"{type(self).__name__}_{circuit.name}.qasm"
qasm_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm")
filename = os.path.join(qasm_dir, qasm_name)
if self.regenerate_expected:
# Run result in backend to test that is valid.
self.generate_ground_truth(result, filename)
expected = QuantumCircuit.from_qasm_file(filename)
self.assertEqual(result, expected)
class SwapperCommonTestCases(CommonUtilitiesMixin):
"""Tests that are run in several mappers.
The tests here will be run in several mappers. When adding a test, please
ensure that the test:
* defines ``self.count``, ``self.shots``, ``self.delta``.
* uses the ``self.assertResult`` assertion for comparing for regeneration of
the ground truth.
* explicitly sets a unique ``name`` of the ``QuantumCircuit``.
See also ``CommonUtilitiesMixin`` and the module docstring.
"""
def test_a_cx_to_map(self):
"""A single CX needs to be remapped.
q0:----------m-----
|
q1:-[H]-(+)--|-m---
| | |
q2:------.---|-|-m-
| | |
c0:----------.-|-|-
c1:------------.-|-
c2:--------------.-
CouplingMap map: [1]<-[0]->[2]
expected count: '000': 50%
'110': 50%
"""
self.counts = {"000": 512, "110": 512}
self.shots = 1024
self.delta = 5
coupling_map = [[0, 1], [0, 2]]
qr = QuantumRegister(3, "q")
cr = ClassicalRegister(3, "c")
circuit = QuantumCircuit(qr, cr, name="a_cx_to_map")
circuit.h(qr[1])
circuit.cx(qr[1], qr[2])
circuit.measure(qr, cr)
result = self.create_passmanager(coupling_map).run(circuit)
self.assertResult(result, circuit)
def test_initial_layout(self):
"""Using a non-trivial initial_layout.
q3:----------------m--
q0:----------m-----|--
| |
q1:-[H]-(+)--|-m---|--
| | | |
q2:------.---|-|-m-|--
| | | |
c0:----------.-|-|-|--
c1:------------.-|-|--
c2:--------------.-|--
c3:----------------.--
CouplingMap map: [1]<-[0]->[2]->[3]
expected count: '000': 50%
'110': 50%
"""
self.counts = {"0000": 512, "0110": 512}
self.shots = 1024
self.delta = 5
coupling_map = [[0, 1], [0, 2], [2, 3]]
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(4, "c")
circuit = QuantumCircuit(qr, cr, name="initial_layout")
circuit.h(qr[1])
circuit.cx(qr[1], qr[2])
circuit.measure(qr, cr)
layout = {qr[3]: 0, qr[0]: 1, qr[1]: 2, qr[2]: 3}
result = self.create_passmanager(coupling_map, layout).run(circuit)
self.assertResult(result, circuit)
def test_handle_measurement(self):
"""Handle measurement correctly.
q0:--.-----(+)-m-------
| | |
q1:-(+)-(+)-|--|-m-----
| | | |
q2:------|--|--|-|-m---
| | | | |
q3:-[H]--.--.--|-|-|-m-
| | | |
c0:------------.-|-|-|-
c1:--------------.-|-|-
c2:----------------.-|-
c3:------------------.-
CouplingMap map: [0]->[1]->[2]->[3]
expected count: '0000': 50%
'1011': 50%
"""
self.counts = {"1011": 512, "0000": 512}
self.shots = 1024
self.delta = 5
coupling_map = [[0, 1], [1, 2], [2, 3]]
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(4, "c")
circuit = QuantumCircuit(qr, cr, name="handle_measurement")
circuit.h(qr[3])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[3], qr[1])
circuit.cx(qr[3], qr[0])
circuit.measure(qr, cr)
result = self.create_passmanager(coupling_map).run(circuit)
self.assertResult(result, circuit)
class TestsBasicSwap(SwapperCommonTestCases, QiskitTestCase):
"""Test SwapperCommonTestCases using BasicSwap."""
pass_class = BasicSwap
class TestsLookaheadSwap(SwapperCommonTestCases, QiskitTestCase):
"""Test SwapperCommonTestCases using LookaheadSwap."""
pass_class = LookaheadSwap
class TestsStochasticSwap(SwapperCommonTestCases, QiskitTestCase):
"""Test SwapperCommonTestCases using StochasticSwap."""
pass_class = StochasticSwap
additional_args = {"seed": 0}
class TestsSabreSwap(SwapperCommonTestCases, QiskitTestCase):
"""Test SwapperCommonTestCases using SabreSwap."""
pass_class = SabreSwap
additional_args = {"seed": 1242}
if __name__ == "__main__":
if len(sys.argv) >= 2 and sys.argv[1] == "regenerate":
CommonUtilitiesMixin.regenerate_expected = True
del sys.argv[1]
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Testing naming functionality of transpiled circuits"""
import unittest
from qiskit.circuit import QuantumCircuit
from qiskit.compiler import transpile
from qiskit import BasicAer
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.test import QiskitTestCase
class TestNamingTranspiledCircuits(QiskitTestCase):
"""Testing the naming fuctionality for transpiled circuits."""
def setUp(self):
super().setUp()
self.basis_gates = ["u1", "u2", "u3", "cx"]
self.backend = BasicAer.get_backend("qasm_simulator")
self.circuit0 = QuantumCircuit(name="circuit0")
self.circuit1 = QuantumCircuit(name="circuit1")
self.circuit2 = QuantumCircuit(name="circuit2")
self.circuit3 = QuantumCircuit(name="circuit3")
def test_single_circuit_name_singleton(self):
"""Test output_name with a single circuit
Given a single circuit and a output name in form of a string, this test
checks whether that string name is assigned to the transpiled circuit.
"""
trans_cirkie = transpile(
self.circuit0, basis_gates=self.basis_gates, output_name="transpiled-cirkie"
)
self.assertEqual(trans_cirkie.name, "transpiled-cirkie")
def test_single_circuit_name_list(self):
"""Test singleton output_name and a single circuit
Given a single circuit and an output name in form of a single element
list, this test checks whether the transpiled circuit is mapped with
that assigned name in the list.
If list has more than one element, then test checks whether the
Transpile function raises an error.
"""
trans_cirkie = transpile(
self.circuit0, basis_gates=self.basis_gates, output_name=["transpiled-cirkie"]
)
self.assertEqual(trans_cirkie.name, "transpiled-cirkie")
def test_single_circuit_and_multiple_name_list(self):
"""Test multiple output_name and a single circuit"""
# If List has multiple elements, transpile function must raise error
with self.assertRaises(TranspilerError):
transpile(
self.circuit0,
basis_gates=self.basis_gates,
output_name=["cool-cirkie", "new-cirkie", "dope-cirkie", "awesome-cirkie"],
)
def test_multiple_circuits_name_singleton(self):
"""Test output_name raise error if a single name is provided to a list of circuits
Given multiple circuits and a single string as a name, this test checks
whether the Transpile function raises an error.
"""
# Raise Error if single name given to multiple circuits
with self.assertRaises(TranspilerError):
transpile([self.circuit1, self.circuit2], self.backend, output_name="circ")
def test_multiple_circuits_name_list(self):
"""Test output_name with a list of circuits
Given multiple circuits and a list for output names, if
len(list)=len(circuits), then test checks whether transpile func assigns
each element in list to respective circuit.
If lengths are not equal, then test checks whether transpile func raises
error.
"""
# combining multiple circuits
circuits = [self.circuit1, self.circuit2, self.circuit3]
# equal lengths
names = ["awesome-circ1", "awesome-circ2", "awesome-circ3"]
trans_circuits = transpile(circuits, self.backend, output_name=names)
self.assertEqual(trans_circuits[0].name, "awesome-circ1")
self.assertEqual(trans_circuits[1].name, "awesome-circ2")
self.assertEqual(trans_circuits[2].name, "awesome-circ3")
def test_greater_circuits_name_list(self):
"""Test output_names list greater than circuits list"""
# combining multiple circuits
circuits = [self.circuit1, self.circuit2, self.circuit3]
# names list greater than circuits list
names = ["awesome-circ1", "awesome-circ2", "awesome-circ3", "awesome-circ4"]
with self.assertRaises(TranspilerError):
transpile(circuits, self.backend, output_name=names)
def test_smaller_circuits_name_list(self):
"""Test output_names list smaller than circuits list"""
# combining multiple circuits
circuits = [self.circuit1, self.circuit2, self.circuit3]
# names list smaller than circuits list
names = ["awesome-circ1", "awesome-circ2"]
with self.assertRaises(TranspilerError):
transpile(circuits, self.backend, output_name=names)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the NoiseAdaptiveLayout pass"""
from datetime import datetime
import unittest
from qiskit.transpiler.passes import NoiseAdaptiveLayout
from qiskit.converters import circuit_to_dag
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.test import QiskitTestCase
from qiskit.providers.models import BackendProperties
from qiskit.providers.models.backendproperties import Nduv, Gate
def make_qubit_with_error(readout_error):
"""Create a qubit for BackendProperties"""
calib_time = datetime(year=2019, month=2, day=1, hour=0, minute=0, second=0)
return [
Nduv(name="T1", date=calib_time, unit="µs", value=100.0),
Nduv(name="T2", date=calib_time, unit="µs", value=100.0),
Nduv(name="frequency", date=calib_time, unit="GHz", value=5.0),
Nduv(name="readout_error", date=calib_time, unit="", value=readout_error),
]
class TestNoiseAdaptiveLayout(QiskitTestCase):
"""Tests the NoiseAdaptiveLayout pass."""
def test_on_linear_topology(self):
"""
Test that the mapper identifies the correct gate in a linear topology
"""
calib_time = datetime(year=2019, month=2, day=1, hour=0, minute=0, second=0)
qr = QuantumRegister(2, name="q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
dag = circuit_to_dag(circuit)
qubit_list = []
ro_errors = [0.01, 0.01, 0.01]
for ro_error in ro_errors:
qubit_list.append(make_qubit_with_error(ro_error))
p01 = [Nduv(date=calib_time, name="gate_error", unit="", value=0.9)]
g01 = Gate(name="CX0_1", gate="cx", parameters=p01, qubits=[0, 1])
p12 = [Nduv(date=calib_time, name="gate_error", unit="", value=0.1)]
g12 = Gate(name="CX1_2", gate="cx", parameters=p12, qubits=[1, 2])
gate_list = [g01, g12]
bprop = BackendProperties(
last_update_date=calib_time,
backend_name="test_backend",
qubits=qubit_list,
backend_version="1.0.0",
gates=gate_list,
general=[],
)
nalayout = NoiseAdaptiveLayout(bprop)
nalayout.run(dag)
initial_layout = nalayout.property_set["layout"]
self.assertNotEqual(initial_layout[qr[0]], 0)
self.assertNotEqual(initial_layout[qr[1]], 0)
def test_bad_readout(self):
"""Test that the mapper avoids bad readout unit"""
calib_time = datetime(year=2019, month=2, day=1, hour=0, minute=0, second=0)
qr = QuantumRegister(2, name="q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
dag = circuit_to_dag(circuit)
qubit_list = []
ro_errors = [0.01, 0.01, 0.8]
for ro_error in ro_errors:
qubit_list.append(make_qubit_with_error(ro_error))
p01 = [Nduv(date=calib_time, name="gate_error", unit="", value=0.1)]
g01 = Gate(name="CX0_1", gate="cx", parameters=p01, qubits=[0, 1])
p12 = [Nduv(date=calib_time, name="gate_error", unit="", value=0.1)]
g12 = Gate(name="CX1_2", gate="cx", parameters=p12, qubits=[1, 2])
gate_list = [g01, g12]
bprop = BackendProperties(
last_update_date=calib_time,
backend_name="test_backend",
qubits=qubit_list,
backend_version="1.0.0",
gates=gate_list,
general=[],
)
nalayout = NoiseAdaptiveLayout(bprop)
nalayout.run(dag)
initial_layout = nalayout.property_set["layout"]
self.assertNotEqual(initial_layout[qr[0]], 2)
self.assertNotEqual(initial_layout[qr[1]], 2)
def test_grid_layout(self):
"""
Test that the mapper identifies best location for a star-like program graph
Machine row1: (0, 1, 2)
Machine row2: (3, 4, 5)
"""
calib_time = datetime(year=2019, month=2, day=1, hour=0, minute=0, second=0)
qr = QuantumRegister(4, name="q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[3])
circuit.cx(qr[1], qr[3])
circuit.cx(qr[2], qr[3])
dag = circuit_to_dag(circuit)
qubit_list = []
ro_errors = [0.01] * 6
for ro_error in ro_errors:
qubit_list.append(make_qubit_with_error(ro_error))
p01 = [Nduv(date=calib_time, name="gate_error", unit="", value=0.3)]
p03 = [Nduv(date=calib_time, name="gate_error", unit="", value=0.3)]
p12 = [Nduv(date=calib_time, name="gate_error", unit="", value=0.3)]
p14 = [Nduv(date=calib_time, name="gate_error", unit="", value=0.1)]
p34 = [Nduv(date=calib_time, name="gate_error", unit="", value=0.1)]
p45 = [Nduv(date=calib_time, name="gate_error", unit="", value=0.1)]
p25 = [Nduv(date=calib_time, name="gate_error", unit="", value=0.3)]
g01 = Gate(name="CX0_1", gate="cx", parameters=p01, qubits=[0, 1])
g03 = Gate(name="CX0_3", gate="cx", parameters=p03, qubits=[0, 3])
g12 = Gate(name="CX1_2", gate="cx", parameters=p12, qubits=[1, 2])
g14 = Gate(name="CX1_4", gate="cx", parameters=p14, qubits=[1, 4])
g34 = Gate(name="CX3_4", gate="cx", parameters=p34, qubits=[3, 4])
g45 = Gate(name="CX4_5", gate="cx", parameters=p45, qubits=[4, 5])
g25 = Gate(name="CX2_5", gate="cx", parameters=p25, qubits=[2, 5])
gate_list = [g01, g03, g12, g14, g34, g45, g25]
bprop = BackendProperties(
last_update_date=calib_time,
backend_name="test_backend",
qubits=qubit_list,
backend_version="1.0.0",
gates=gate_list,
general=[],
)
nalayout = NoiseAdaptiveLayout(bprop)
nalayout.run(dag)
initial_layout = nalayout.property_set["layout"]
for qid in range(4):
for qloc in [0, 2]:
self.assertNotEqual(initial_layout[qr[qid]], qloc)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the optimize-1q-gate pass"""
import unittest
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import Optimize1qGates, Unroller
from qiskit.converters import circuit_to_dag
from qiskit.test import QiskitTestCase
from qiskit.circuit import Parameter
from qiskit.circuit.library import U1Gate, U2Gate, U3Gate, UGate, PhaseGate
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.transpiler.target import Target
class TestOptimize1qGates(QiskitTestCase):
"""Test for 1q gate optimizations."""
def test_dont_optimize_id(self):
"""Identity gates are like 'wait' commands.
They should never be optimized (even without barriers).
See: https://github.com/Qiskit/qiskit-terra/issues/2373
"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.i(qr)
circuit.i(qr)
dag = circuit_to_dag(circuit)
pass_ = Optimize1qGates()
after = pass_.run(dag)
self.assertEqual(dag, after)
def test_optimize_h_gates_pass_manager(self):
"""Transpile: qr:--[H]-[H]-[H]-- == qr:--[u2]--"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[0])
circuit.h(qr[0])
expected = QuantumCircuit(qr)
expected.append(U2Gate(0, np.pi), [qr[0]])
passmanager = PassManager()
passmanager.append(Unroller(["u2"]))
passmanager.append(Optimize1qGates())
result = passmanager.run(circuit)
self.assertEqual(expected, result)
def test_optimize_1q_gates_collapse_identity_equivalent(self):
"""test optimize_1q_gates removes u1(2*pi) rotations.
See: https://github.com/Qiskit/qiskit-terra/issues/159
"""
# ┌───┐┌───┐┌────────┐┌───┐┌─────────┐┌───────┐┌─────────┐┌───┐ ┌─┐»
# qr_0: ┤ H ├┤ X ├┤ U1(2π) ├┤ X ├┤ U1(π/2) ├┤ U1(π) ├┤ U1(π/2) ├┤ X ├─────────┤M├»
# └───┘└─┬─┘└────────┘└─┬─┘└─────────┘└───────┘└─────────┘└─┬─┘┌───────┐└╥┘»
# qr_1: ───────■──────────────■───────────────────────────────────■──┤ U1(π) ├─╫─»
# └───────┘ ║ »
# cr: 2/═══════════════════════════════════════════════════════════════════════╩═»
# 0 »
# «
# «qr_0: ────────────
# « ┌───────┐┌─┐
# «qr_1: ┤ U1(π) ├┤M├
# « └───────┘└╥┘
# «cr: 2/══════════╩═
# « 1
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
qc = QuantumCircuit(qr, cr)
qc.h(qr[0])
qc.cx(qr[1], qr[0])
qc.append(U1Gate(2 * np.pi), [qr[0]])
qc.cx(qr[1], qr[0])
qc.append(U1Gate(np.pi / 2), [qr[0]]) # these three should combine
qc.append(U1Gate(np.pi), [qr[0]]) # to identity then
qc.append(U1Gate(np.pi / 2), [qr[0]]) # optimized away.
qc.cx(qr[1], qr[0])
qc.append(U1Gate(np.pi), [qr[1]])
qc.append(U1Gate(np.pi), [qr[1]])
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])
dag = circuit_to_dag(qc)
simplified_dag = Optimize1qGates().run(dag)
num_u1_gates_remaining = len(simplified_dag.named_nodes("u1"))
self.assertEqual(num_u1_gates_remaining, 0)
def test_optimize_1q_gates_collapse_identity_equivalent_phase_gate(self):
"""test optimize_1q_gates removes u1(2*pi) rotations.
See: https://github.com/Qiskit/qiskit-terra/issues/159
"""
# ┌───┐┌───┐┌───────┐┌───┐┌────────┐┌──────┐┌────────┐┌───┐ ┌─┐»
# qr_0: ┤ H ├┤ X ├┤ P(2π) ├┤ X ├┤ P(π/2) ├┤ P(π) ├┤ P(π/2) ├┤ X ├────────┤M├»
# └───┘└─┬─┘└───────┘└─┬─┘└────────┘└──────┘└────────┘└─┬─┘┌──────┐└╥┘»
# qr_1: ───────■─────────────■────────────────────────────────■──┤ P(π) ├─╫─»
# └──────┘ ║ »
# cr: 2/══════════════════════════════════════════════════════════════════╩═»
# 0 »
# «
# «qr_0: ───────────
# « ┌──────┐┌─┐
# «qr_1: ┤ P(π) ├┤M├
# « └──────┘└╥┘
# «cr: 2/═════════╩═
# « 1
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
qc = QuantumCircuit(qr, cr)
qc.h(qr[0])
qc.cx(qr[1], qr[0])
qc.append(PhaseGate(2 * np.pi), [qr[0]])
qc.cx(qr[1], qr[0])
qc.append(PhaseGate(np.pi / 2), [qr[0]]) # these three should combine
qc.append(PhaseGate(np.pi), [qr[0]]) # to identity then
qc.append(PhaseGate(np.pi / 2), [qr[0]]) # optimized away.
qc.cx(qr[1], qr[0])
qc.append(PhaseGate(np.pi), [qr[1]])
qc.append(PhaseGate(np.pi), [qr[1]])
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])
dag = circuit_to_dag(qc)
simplified_dag = Optimize1qGates(["p", "u2", "u", "cx", "id"]).run(dag)
num_u1_gates_remaining = len(simplified_dag.named_nodes("p"))
self.assertEqual(num_u1_gates_remaining, 0)
def test_ignores_conditional_rotations(self):
"""Conditional rotations should not be considered in the chain.
qr0:--[U1]-[U1]-[U1]-[U1]- qr0:--[U1]-[U1]-
|| || || ||
cr0:===.================== == cr0:===.====.===
|| ||
cr1:========.============= cr1:========.===
"""
qr = QuantumRegister(1, "qr")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.append(U1Gate(0.1), [qr]).c_if(cr, 1)
circuit.append(U1Gate(0.2), [qr]).c_if(cr, 3)
circuit.append(U1Gate(0.3), [qr])
circuit.append(U1Gate(0.4), [qr])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.append(U1Gate(0.1), [qr]).c_if(cr, 1)
expected.append(U1Gate(0.2), [qr]).c_if(cr, 3)
expected.append(U1Gate(0.7), [qr])
pass_ = Optimize1qGates()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_ignores_conditional_rotations_phase_gates(self):
"""Conditional rotations should not be considered in the chain.
qr0:--[U1]-[U1]-[U1]-[U1]- qr0:--[U1]-[U1]-
|| || || ||
cr0:===.================== == cr0:===.====.===
|| ||
cr1:========.============= cr1:========.===
"""
qr = QuantumRegister(1, "qr")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.append(PhaseGate(0.1), [qr]).c_if(cr, 1)
circuit.append(PhaseGate(0.2), [qr]).c_if(cr, 3)
circuit.append(PhaseGate(0.3), [qr])
circuit.append(PhaseGate(0.4), [qr])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.append(PhaseGate(0.1), [qr]).c_if(cr, 1)
expected.append(PhaseGate(0.2), [qr]).c_if(cr, 3)
expected.append(PhaseGate(0.7), [qr])
pass_ = Optimize1qGates(["p", "u2", "u", "cx", "id"])
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_in_the_back(self):
"""Optimizations can be in the back of the circuit.
See https://github.com/Qiskit/qiskit-terra/issues/2004.
qr0:--[U1]-[U1]-[H]-- qr0:--[U1]-[H]--
"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.append(U1Gate(0.3), [qr])
circuit.append(U1Gate(0.4), [qr])
circuit.h(qr)
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
expected.append(U1Gate(0.7), [qr])
expected.h(qr)
pass_ = Optimize1qGates()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_in_the_back_phase_gate(self):
"""Optimizations can be in the back of the circuit.
See https://github.com/Qiskit/qiskit-terra/issues/2004.
qr0:--[U1]-[U1]-[H]-- qr0:--[U1]-[H]--
"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.append(PhaseGate(0.3), [qr])
circuit.append(PhaseGate(0.4), [qr])
circuit.h(qr)
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
expected.append(PhaseGate(0.7), [qr])
expected.h(qr)
pass_ = Optimize1qGates(["p", "u2", "u", "cx", "id"])
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_single_parameterized_circuit(self):
"""Parameters should be treated as opaque gates."""
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
theta = Parameter("theta")
qc.append(U1Gate(0.3), [qr])
qc.append(U1Gate(0.4), [qr])
qc.append(U1Gate(theta), [qr])
qc.append(U1Gate(0.1), [qr])
qc.append(U1Gate(0.2), [qr])
dag = circuit_to_dag(qc)
expected = QuantumCircuit(qr)
expected.append(U1Gate(theta + 1.0), [qr])
after = Optimize1qGates().run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_parameterized_circuits(self):
"""Parameters should be treated as opaque gates."""
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
theta = Parameter("theta")
qc.append(U1Gate(0.3), [qr])
qc.append(U1Gate(0.4), [qr])
qc.append(U1Gate(theta), [qr])
qc.append(U1Gate(0.1), [qr])
qc.append(U1Gate(0.2), [qr])
qc.append(U1Gate(theta), [qr])
qc.append(U1Gate(0.3), [qr])
qc.append(U1Gate(0.2), [qr])
dag = circuit_to_dag(qc)
expected = QuantumCircuit(qr)
expected.append(U1Gate(2 * theta + 1.5), [qr])
after = Optimize1qGates().run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_parameterized_expressions_in_circuits(self):
"""Expressions of Parameters should be treated as opaque gates."""
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
theta = Parameter("theta")
phi = Parameter("phi")
sum_ = theta + phi
product_ = theta * phi
qc.append(U1Gate(0.3), [qr])
qc.append(U1Gate(0.4), [qr])
qc.append(U1Gate(theta), [qr])
qc.append(U1Gate(phi), [qr])
qc.append(U1Gate(sum_), [qr])
qc.append(U1Gate(product_), [qr])
qc.append(U1Gate(0.3), [qr])
qc.append(U1Gate(0.2), [qr])
dag = circuit_to_dag(qc)
expected = QuantumCircuit(qr)
expected.append(U1Gate(2 * theta + 2 * phi + product_ + 1.2), [qr])
after = Optimize1qGates().run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_global_phase_u3_on_left(self):
"""Check proper phase accumulation with instruction with no definition."""
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
u1 = U1Gate(0.1)
u1.definition.global_phase = np.pi / 2
qc.append(u1, [0])
qc.global_phase = np.pi / 3
qc.append(U3Gate(0.1, 0.2, 0.3), [0])
dag = circuit_to_dag(qc)
after = Optimize1qGates().run(dag)
self.assertAlmostEqual(after.global_phase, 5 * np.pi / 6, 8)
def test_global_phase_u_on_left(self):
"""Check proper phase accumulation with instruction with no definition."""
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
u1 = U1Gate(0.1)
u1.definition.global_phase = np.pi / 2
qc.append(u1, [0])
qc.global_phase = np.pi / 3
qc.append(UGate(0.1, 0.2, 0.3), [0])
dag = circuit_to_dag(qc)
after = Optimize1qGates(["u1", "u2", "u", "cx"]).run(dag)
self.assertAlmostEqual(after.global_phase, 5 * np.pi / 6, 8)
class TestOptimize1qGatesParamReduction(QiskitTestCase):
"""Test for 1q gate optimizations parameter reduction, reduce n in Un"""
def test_optimize_u3_to_u2(self):
"""U3(pi/2, pi/3, pi/4) -> U2(pi/3, pi/4)"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.append(U3Gate(np.pi / 2, np.pi / 3, np.pi / 4), [qr[0]])
expected = QuantumCircuit(qr)
expected.append(U2Gate(np.pi / 3, np.pi / 4), [qr[0]])
passmanager = PassManager()
passmanager.append(Optimize1qGates())
result = passmanager.run(circuit)
self.assertEqual(expected, result)
def test_optimize_u3_to_u2_round(self):
"""U3(1.5707963267948961, 1.0471975511965971, 0.7853981633974489) -> U2(pi/3, pi/4)"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.append(U3Gate(1.5707963267948961, 1.0471975511965971, 0.7853981633974489), [qr[0]])
expected = QuantumCircuit(qr)
expected.append(U2Gate(np.pi / 3, np.pi / 4), [qr[0]])
passmanager = PassManager()
passmanager.append(Optimize1qGates())
result = passmanager.run(circuit)
self.assertEqual(expected, result)
def test_optimize_u3_to_u1(self):
"""U3(0, 0, pi/4) -> U1(pi/4)"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.append(U3Gate(0, 0, np.pi / 4), [qr[0]])
expected = QuantumCircuit(qr)
expected.append(U1Gate(np.pi / 4), [qr[0]])
passmanager = PassManager()
passmanager.append(Optimize1qGates())
result = passmanager.run(circuit)
self.assertEqual(expected, result)
def test_optimize_u3_to_phase_gate(self):
"""U3(0, 0, pi/4) -> U1(pi/4)"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.append(U3Gate(0, 0, np.pi / 4), [qr[0]])
expected = QuantumCircuit(qr)
expected.append(PhaseGate(np.pi / 4), [qr[0]])
passmanager = PassManager()
passmanager.append(Optimize1qGates(["p", "u2", "u", "cx", "id"]))
result = passmanager.run(circuit)
self.assertEqual(expected, result)
def test_optimize_u3_to_u1_round(self):
"""U3(1e-16, 1e-16, pi/4) -> U1(pi/4)"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.append(U3Gate(1e-16, 1e-16, np.pi / 4), [qr[0]])
expected = QuantumCircuit(qr)
expected.append(U1Gate(np.pi / 4), [qr[0]])
passmanager = PassManager()
passmanager.append(Optimize1qGates())
result = passmanager.run(circuit)
self.assertEqual(expected, result)
def test_optimize_u3_to_phase_round(self):
"""U3(1e-16, 1e-16, pi/4) -> U1(pi/4)"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.append(U3Gate(1e-16, 1e-16, np.pi / 4), [qr[0]])
expected = QuantumCircuit(qr)
expected.append(PhaseGate(np.pi / 4), [qr[0]])
passmanager = PassManager()
passmanager.append(Optimize1qGates(["p", "u2", "u", "cx", "id"]))
result = passmanager.run(circuit)
self.assertEqual(expected, result)
class TestOptimize1qGatesBasis(QiskitTestCase):
"""Test for 1q gate optimizations parameter reduction with basis"""
def test_optimize_u3_basis_u3(self):
"""U3(pi/2, pi/3, pi/4) (basis[u3]) -> U3(pi/2, pi/3, pi/4)"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.append(U3Gate(np.pi / 2, np.pi / 3, np.pi / 4), [qr[0]])
passmanager = PassManager()
passmanager.append(Optimize1qGates(["u3"]))
result = passmanager.run(circuit)
self.assertEqual(circuit, result)
def test_optimize_u3_basis_u(self):
"""U3(pi/2, pi/3, pi/4) (basis[u3]) -> U(pi/2, pi/3, pi/4)"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.append(U3Gate(np.pi / 2, np.pi / 3, np.pi / 4), [qr[0]])
passmanager = PassManager()
passmanager.append(Optimize1qGates(["u"]))
result = passmanager.run(circuit)
expected = QuantumCircuit(qr)
expected.append(UGate(np.pi / 2, np.pi / 3, np.pi / 4), [qr[0]])
self.assertEqual(expected, result)
def test_optimize_u3_basis_u2(self):
"""U3(pi/2, 0, pi/4) -> U2(0, pi/4)"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.append(U3Gate(np.pi / 2, 0, np.pi / 4), [qr[0]])
expected = QuantumCircuit(qr)
expected.append(U2Gate(0, np.pi / 4), [qr[0]])
passmanager = PassManager()
passmanager.append(Optimize1qGates(["u2"]))
result = passmanager.run(circuit)
self.assertEqual(expected, result)
def test_optimize_u3_basis_u2_with_target(self):
"""U3(pi/2, 0, pi/4) -> U2(0, pi/4)"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.append(U3Gate(np.pi / 2, 0, np.pi / 4), [qr[0]])
expected = QuantumCircuit(qr)
expected.append(U2Gate(0, np.pi / 4), [qr[0]])
target = Target(num_qubits=1)
target.add_instruction(U2Gate(Parameter("theta"), Parameter("phi")))
passmanager = PassManager()
passmanager.append(Optimize1qGates(target=target))
result = passmanager.run(circuit)
self.assertEqual(expected, result)
def test_optimize_u_basis_u(self):
"""U(pi/2, pi/3, pi/4) (basis[u3]) -> U(pi/2, pi/3, pi/4)"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.append(UGate(np.pi / 2, np.pi / 3, np.pi / 4), [qr[0]])
passmanager = PassManager()
passmanager.append(Optimize1qGates(["u"]))
result = passmanager.run(circuit)
self.assertEqual(circuit, result)
def test_optimize_u3_basis_u2_cx(self):
"""U3(pi/2, 0, pi/4) -> U2(0, pi/4). Basis [u2, cx]."""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.append(U3Gate(np.pi / 2, 0, np.pi / 4), [qr[0]])
circuit.cx(qr[0], qr[1])
expected = QuantumCircuit(qr)
expected.append(U2Gate(0, np.pi / 4), [qr[0]])
expected.cx(qr[0], qr[1])
passmanager = PassManager()
passmanager.append(Optimize1qGates(["u2", "cx"]))
result = passmanager.run(circuit)
self.assertEqual(expected, result)
def test_optimize_u_basis_u2_cx(self):
"""U(pi/2, 0, pi/4) -> U2(0, pi/4). Basis [u2, cx]."""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.append(UGate(np.pi / 2, 0, np.pi / 4), [qr[0]])
circuit.cx(qr[0], qr[1])
expected = QuantumCircuit(qr)
expected.append(U2Gate(0, np.pi / 4), [qr[0]])
expected.cx(qr[0], qr[1])
passmanager = PassManager()
passmanager.append(Optimize1qGates(["u2", "cx"]))
result = passmanager.run(circuit)
self.assertEqual(expected, result)
def test_optimize_u1_basis_u2_u3(self):
"""U1(pi/4) -> U3(0, 0, pi/4). Basis [u2, u3]."""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.append(U1Gate(np.pi / 4), [qr[0]])
expected = QuantumCircuit(qr)
expected.append(U3Gate(0, 0, np.pi / 4), [qr[0]])
passmanager = PassManager()
passmanager.append(Optimize1qGates(["u2", "u3"]))
result = passmanager.run(circuit)
self.assertEqual(expected, result)
def test_optimize_u1_basis_u2_u(self):
"""U1(pi/4) -> U3(0, 0, pi/4). Basis [u2, u3]."""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.append(U1Gate(np.pi / 4), [qr[0]])
expected = QuantumCircuit(qr)
expected.append(UGate(0, 0, np.pi / 4), [qr[0]])
passmanager = PassManager()
passmanager.append(Optimize1qGates(["u2", "u"]))
result = passmanager.run(circuit)
self.assertEqual(expected, result)
def test_optimize_u1_basis_u2(self):
"""U1(pi/4) -> Raises. Basis [u2]"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.append(U1Gate(np.pi / 4), [qr[0]])
expected = QuantumCircuit(qr)
expected.append(U3Gate(0, 0, np.pi / 4), [qr[0]])
passmanager = PassManager()
passmanager.append(Optimize1qGates(["u2"]))
with self.assertRaises(TranspilerError):
_ = passmanager.run(circuit)
def test_optimize_u3_basis_u2_u1(self):
"""U3(pi/2, 0, pi/4) -> U2(0, pi/4). Basis [u2, u1]."""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.append(U3Gate(np.pi / 2, 0, np.pi / 4), [qr[0]])
expected = QuantumCircuit(qr)
expected.append(U2Gate(0, np.pi / 4), [qr[0]])
passmanager = PassManager()
passmanager.append(Optimize1qGates(["u2", "u1"]))
result = passmanager.run(circuit)
self.assertEqual(expected, result)
def test_optimize_u3_basis_u2_phase_gate(self):
"""U3(pi/2, 0, pi/4) -> U2(0, pi/4). Basis [u2, p]."""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.append(U3Gate(np.pi / 2, 0, np.pi / 4), [qr[0]])
expected = QuantumCircuit(qr)
expected.append(U2Gate(0, np.pi / 4), [qr[0]])
passmanager = PassManager()
passmanager.append(Optimize1qGates(["u2", "p"]))
result = passmanager.run(circuit)
self.assertEqual(expected, result)
def test_optimize_u3_basis_u1(self):
"""U3(0, 0, pi/4) -> U1(pi/4). Basis [u1]."""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.append(U3Gate(0, 0, np.pi / 4), [qr[0]])
expected = QuantumCircuit(qr)
expected.append(U1Gate(np.pi / 4), [qr[0]])
passmanager = PassManager()
passmanager.append(Optimize1qGates(["u1"]))
result = passmanager.run(circuit)
self.assertEqual(expected, result)
def test_optimize_u3_basis_phase_gate(self):
"""U3(0, 0, pi/4) -> p(pi/4). Basis [p]."""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.append(U3Gate(0, 0, np.pi / 4), [qr[0]])
expected = QuantumCircuit(qr)
expected.append(PhaseGate(np.pi / 4), [qr[0]])
passmanager = PassManager()
passmanager.append(Optimize1qGates(["p"]))
result = passmanager.run(circuit)
self.assertEqual(expected, result)
def test_optimize_u_basis_u1(self):
"""U(0, 0, pi/4) -> U1(pi/4). Basis [u1]."""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.append(UGate(0, 0, np.pi / 4), [qr[0]])
expected = QuantumCircuit(qr)
expected.append(U1Gate(np.pi / 4), [qr[0]])
passmanager = PassManager()
passmanager.append(Optimize1qGates(["u1"]))
result = passmanager.run(circuit)
self.assertEqual(expected, result)
def test_optimize_u_basis_phase_gate(self):
"""U(0, 0, pi/4) -> p(pi/4). Basis [p]."""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.append(UGate(0, 0, np.pi / 4), [qr[0]])
expected = QuantumCircuit(qr)
expected.append(PhaseGate(np.pi / 4), [qr[0]])
passmanager = PassManager()
passmanager.append(Optimize1qGates(["p"]))
result = passmanager.run(circuit)
self.assertEqual(expected, result)
def test_optimize_u3_with_parameters(self):
"""Test correct behavior for u3 gates."""
phi = Parameter("φ")
alpha = Parameter("α")
qr = QuantumRegister(1, "qr")
qc = QuantumCircuit(qr)
qc.ry(2 * phi, qr[0])
qc.ry(alpha, qr[0])
qc.ry(0.1, qr[0])
qc.ry(0.2, qr[0])
passmanager = PassManager([Unroller(["u3"]), Optimize1qGates()])
result = passmanager.run(qc)
expected = QuantumCircuit(qr)
expected.append(U3Gate(2 * phi, 0, 0), [qr[0]])
expected.append(U3Gate(alpha, 0, 0), [qr[0]])
expected.append(U3Gate(0.3, 0, 0), [qr[0]])
self.assertEqual(expected, result)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test OptimizeSwapBeforeMeasure pass"""
import unittest
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import OptimizeSwapBeforeMeasure, DAGFixedPoint
from qiskit.converters import circuit_to_dag
from qiskit.test import QiskitTestCase
class TestOptimizeSwapBeforeMeasure(QiskitTestCase):
"""Test swap-followed-by-measure optimizations."""
def test_optimize_1swap_1measure(self):
"""Remove a single swap
qr0:--X--m-- qr0:----
| |
qr1:--X--|-- ==> qr1:--m-
| |
cr0:-----.-- cr0:--.-
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.swap(qr[0], qr[1])
circuit.measure(qr[0], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.measure(qr[1], cr[0])
pass_ = OptimizeSwapBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_optimize_1swap_2measure(self):
"""Remove a single swap affecting two measurements
qr0:--X--m-- qr0:--m----
| | |
qr1:--X--|--m ==> qr1:--|--m-
| | | |
cr0:-----.--|-- cr0:--|--.-
cr1:--------.-- cr1:--.----
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.swap(qr[0], qr[1])
circuit.measure(qr[0], cr[0])
circuit.measure(qr[1], cr[1])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.measure(qr[1], cr[0])
expected.measure(qr[0], cr[1])
pass_ = OptimizeSwapBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_optimize_nswap_nmeasure(self):
"""Remove severals swap affecting multiple measurements
┌─┐ ┌─┐
q_0: ─X──X─────X────┤M├───────────────────────────────── q_0: ──────┤M├───────────────
│ │ │ └╥┘ ┌─┐ ┌─┐└╥┘
q_1: ─X──X──X──X──X──╫─────X────┤M├───────────────────── q_1: ───┤M├─╫────────────────
│ │ ║ │ └╥┘ ┌─┐ ┌─┐└╥┘ ║
q_2: ───────X──X──X──╫──X──X─────╫──X────┤M├──────────── q_2: ┤M├─╫──╫────────────────
│ ║ │ ║ │ └╥┘┌─┐ └╥┘ ║ ║ ┌─┐
q_3: ─X─────X──X─────╫──X──X──X──╫──X─────╫─┤M├───────── q_3: ─╫──╫──╫────┤M├─────────
│ │ ║ │ │ ║ ║ └╥┘┌─┐ ║ ║ ║ └╥┘ ┌─┐
q_4: ─X──X──X──X─────╫──X──X──X──╫──X─────╫──╫─┤M├────── ==> q_4: ─╫──╫──╫─────╫───────┤M├
│ │ ║ │ ║ │ ║ ║ └╥┘┌─┐ ║ ║ ║ ┌─┐ ║ └╥┘
q_5: ────X──X──X──X──╫──X──X─────╫──X──X──╫──╫──╫─┤M├─── q_5: ─╫──╫──╫─┤M├─╫────────╫─
│ │ ║ │ ║ │ ║ ║ ║ └╥┘┌─┐ ║ ║ ║ └╥┘ ║ ┌─┐ ║
q_6: ─X──X──X──X──X──╫──X──X─────╫─────X──╫──╫──╫──╫─┤M├ q_6: ─╫──╫──╫──╫──╫─┤M├────╫─
│ │ │ ║ │ ┌─┐ ║ ║ ║ ║ ║ └╥┘ ║ ║ ║ ║ ║ └╥┘┌─┐ ║
q_7: ─X──X─────X─────╫──X─┤M├────╫────────╫──╫──╫──╫──╫─ q_7: ─╫──╫──╫──╫──╫──╫─┤M├─╫─
║ └╥┘ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ └╥┘ ║
c: 8/════════════════╩═════╩═════╩════════╩══╩══╩══╩══╩═ c: 8/═╩══╩══╩══╩══╩══╩══╩══╩═
0 7 1 2 3 4 5 6 0 1 2 3 4 5 6 7
"""
circuit = QuantumCircuit(8, 8)
circuit.swap(3, 4)
circuit.swap(6, 7)
circuit.swap(0, 1)
circuit.swap(6, 7)
circuit.swap(4, 5)
circuit.swap(0, 1)
circuit.swap(5, 6)
circuit.swap(3, 4)
circuit.swap(1, 2)
circuit.swap(6, 7)
circuit.swap(4, 5)
circuit.swap(2, 3)
circuit.swap(0, 1)
circuit.swap(5, 6)
circuit.swap(1, 2)
circuit.swap(6, 7)
circuit.swap(4, 5)
circuit.swap(2, 3)
circuit.swap(3, 4)
circuit.swap(3, 4)
circuit.swap(5, 6)
circuit.swap(1, 2)
circuit.swap(4, 5)
circuit.swap(2, 3)
circuit.swap(5, 6)
circuit.measure(range(8), range(8))
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(8, 8)
expected.measure(0, 2)
expected.measure(1, 1)
expected.measure(2, 0)
expected.measure(3, 4)
expected.measure(4, 7)
expected.measure(5, 3)
expected.measure(6, 5)
expected.measure(7, 6)
pass_ = OptimizeSwapBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_cannot_optimize(self):
"""Cannot optimize when swap is not at the end in all of the successors
qr0:--X-----m--
| |
qr1:--X-[H]-|--
|
cr0:--------.--
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.swap(qr[0], qr[1])
circuit.h(qr[1])
circuit.measure(qr[0], cr[0])
dag = circuit_to_dag(circuit)
pass_ = OptimizeSwapBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(circuit), after)
def test_if_else(self):
"""Test that the pass recurses into a simple if-else."""
pass_ = OptimizeSwapBeforeMeasure()
base_test = QuantumCircuit(2, 1)
base_test.swap(0, 1)
base_test.measure(0, 0)
base_expected = QuantumCircuit(2, 1)
base_expected.measure(1, 0)
test = QuantumCircuit(2, 1)
test.if_else(
(test.clbits[0], True), base_test.copy(), base_test.copy(), test.qubits, test.clbits
)
expected = QuantumCircuit(2, 1)
expected.if_else(
(expected.clbits[0], True),
base_expected.copy(),
base_expected.copy(),
expected.qubits,
expected.clbits,
)
self.assertEqual(pass_(test), expected)
def test_nested_control_flow(self):
"""Test that the pass recurses into nested control flow."""
pass_ = OptimizeSwapBeforeMeasure()
base_test = QuantumCircuit(2, 1)
base_test.swap(0, 1)
base_test.measure(0, 0)
base_expected = QuantumCircuit(2, 1)
base_expected.measure(1, 0)
body_test = QuantumCircuit(2, 1)
body_test.for_loop((0,), None, base_expected.copy(), body_test.qubits, body_test.clbits)
body_expected = QuantumCircuit(2, 1)
body_expected.for_loop(
(0,), None, base_expected.copy(), body_expected.qubits, body_expected.clbits
)
test = QuantumCircuit(2, 1)
test.while_loop((test.clbits[0], True), body_test, test.qubits, test.clbits)
expected = QuantumCircuit(2, 1)
expected.while_loop(
(expected.clbits[0], True), body_expected, expected.qubits, expected.clbits
)
self.assertEqual(pass_(test), expected)
class TestOptimizeSwapBeforeMeasureFixedPoint(QiskitTestCase):
"""Test swap-followed-by-measure optimizations in a transpiler, using fixed point."""
def test_optimize_undone_swap(self):
"""Remove redundant swap
qr0:--X--X--m-- qr0:--m---
| | | |
qr1:--X--X--|-- ==> qr1:--|--
| |
cr0:--------.-- cr0:--.--
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.swap(qr[0], qr[1])
circuit.swap(qr[0], qr[1])
circuit.measure(qr[0], cr[0])
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
pass_manager = PassManager()
pass_manager.append(
[OptimizeSwapBeforeMeasure(), DAGFixedPoint()],
do_while=lambda property_set: not property_set["dag_fixed_point"],
)
after = pass_manager.run(circuit)
self.assertEqual(expected, after)
def test_optimize_overlap_swap(self):
"""Remove two swaps that overlap
qr0:--X-------- qr0:--m--
| |
qr1:--X--X----- qr1:--|--
| ==> |
qr2:-----X--m-- qr2:--|--
| |
cr0:--------.-- cr0:--.--
"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.swap(qr[0], qr[1])
circuit.swap(qr[1], qr[2])
circuit.measure(qr[2], cr[0])
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
pass_manager = PassManager()
pass_manager.append(
[OptimizeSwapBeforeMeasure(), DAGFixedPoint()],
do_while=lambda property_set: not property_set["dag_fixed_point"],
)
after = pass_manager.run(circuit)
self.assertEqual(expected, after)
def test_no_optimize_swap_with_condition(self):
"""Do not remove swap if it has a condition
qr0:--X--m-- qr0:--X--m--
| | | |
qr1:--X--|-- ==> qr1:--X--|--
| | | |
cr0:--1--.-- cr0:--1--.--
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.swap(qr[0], qr[1]).c_if(cr, 1)
circuit.measure(qr[0], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.swap(qr[0], qr[1]).c_if(cr, 1)
expected.measure(qr[0], cr[0])
pass_ = OptimizeSwapBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=missing-class-docstring
"""Test the passmanager logic"""
import copy
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.circuit.library import U2Gate
from qiskit.converters import circuit_to_dag
from qiskit.transpiler import PassManager, PropertySet, TransformationPass, FlowController
from qiskit.transpiler.passes import CommutativeCancellation
from qiskit.transpiler.passes import Optimize1qGates, Unroller
from qiskit.test import QiskitTestCase
class TestPassManager(QiskitTestCase):
"""Test Pass manager logic."""
def test_callback(self):
"""Test the callback parameter."""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr, name="MyCircuit")
circuit.h(qr[0])
circuit.h(qr[0])
circuit.h(qr[0])
expected_start = QuantumCircuit(qr)
expected_start.append(U2Gate(0, np.pi), [qr[0]])
expected_start.append(U2Gate(0, np.pi), [qr[0]])
expected_start.append(U2Gate(0, np.pi), [qr[0]])
expected_start_dag = circuit_to_dag(expected_start)
expected_end = QuantumCircuit(qr)
expected_end.append(U2Gate(0, np.pi), [qr[0]])
expected_end_dag = circuit_to_dag(expected_end)
calls = []
def callback(**kwargs):
out_dict = kwargs
out_dict["dag"] = copy.deepcopy(kwargs["dag"])
calls.append(out_dict)
passmanager = PassManager()
passmanager.append(Unroller(["u2"]))
passmanager.append(Optimize1qGates())
passmanager.run(circuit, callback=callback)
self.assertEqual(len(calls), 2)
self.assertEqual(len(calls[0]), 5)
self.assertEqual(calls[0]["count"], 0)
self.assertEqual(calls[0]["pass_"].name(), "Unroller")
self.assertEqual(expected_start_dag, calls[0]["dag"])
self.assertIsInstance(calls[0]["time"], float)
self.assertEqual(calls[0]["property_set"], PropertySet())
self.assertEqual("MyCircuit", calls[0]["dag"].name)
self.assertEqual(len(calls[1]), 5)
self.assertEqual(calls[1]["count"], 1)
self.assertEqual(calls[1]["pass_"].name(), "Optimize1qGates")
self.assertEqual(expected_end_dag, calls[1]["dag"])
self.assertIsInstance(calls[0]["time"], float)
self.assertEqual(calls[0]["property_set"], PropertySet())
self.assertEqual("MyCircuit", calls[1]["dag"].name)
def test_callback_with_pass_requires(self):
"""Test the callback with a pass with another pass requirement."""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr, name="MyCircuit")
circuit.z(qr[0])
circuit.cx(qr[0], qr[2])
circuit.z(qr[0])
expected_start = QuantumCircuit(qr)
expected_start.z(qr[0])
expected_start.cx(qr[0], qr[2])
expected_start.z(qr[0])
expected_start_dag = circuit_to_dag(expected_start)
expected_end = QuantumCircuit(qr)
expected_end.cx(qr[0], qr[2])
expected_end_dag = circuit_to_dag(expected_end)
calls = []
def callback(**kwargs):
out_dict = kwargs
out_dict["dag"] = copy.deepcopy(kwargs["dag"])
calls.append(out_dict)
passmanager = PassManager()
passmanager.append(CommutativeCancellation(basis_gates=["u1", "u2", "u3", "cx"]))
passmanager.run(circuit, callback=callback)
self.assertEqual(len(calls), 2)
self.assertEqual(len(calls[0]), 5)
self.assertEqual(calls[0]["count"], 0)
self.assertEqual(calls[0]["pass_"].name(), "CommutationAnalysis")
self.assertEqual(expected_start_dag, calls[0]["dag"])
self.assertIsInstance(calls[0]["time"], float)
self.assertIsInstance(calls[0]["property_set"], PropertySet)
self.assertEqual("MyCircuit", calls[0]["dag"].name)
self.assertEqual(len(calls[1]), 5)
self.assertEqual(calls[1]["count"], 1)
self.assertEqual(calls[1]["pass_"].name(), "CommutativeCancellation")
self.assertEqual(expected_end_dag, calls[1]["dag"])
self.assertIsInstance(calls[0]["time"], float)
self.assertIsInstance(calls[0]["property_set"], PropertySet)
self.assertEqual("MyCircuit", calls[1]["dag"].name)
def test_to_flow_controller(self):
"""Test that conversion to a `FlowController` works, and the result can be added to a
circuit and conditioned, with the condition only being called once."""
class DummyPass(TransformationPass):
def __init__(self, x):
super().__init__()
self.x = x
def run(self, dag):
return dag
def repeat(count):
def condition(_):
nonlocal count
if not count:
return False
count -= 1
return True
return condition
def make_inner(prefix):
inner = PassManager()
inner.append(DummyPass(f"{prefix} 1"))
inner.append(DummyPass(f"{prefix} 2"), condition=lambda _: False)
inner.append(DummyPass(f"{prefix} 3"), condition=lambda _: True)
inner.append(DummyPass(f"{prefix} 4"), do_while=repeat(1))
return inner.to_flow_controller()
self.assertIsInstance(make_inner("test"), FlowController)
outer = PassManager()
outer.append(make_inner("first"))
outer.append(make_inner("second"), condition=lambda _: False)
# The intent of this `condition=repeat(1)` is to ensure that the outer condition is only
# checked once and not flattened into the inner controllers; an inner pass invalidating the
# condition should not affect subsequent passes once the initial condition was met.
outer.append(make_inner("third"), condition=repeat(1))
calls = []
def callback(pass_, **_):
self.assertIsInstance(pass_, DummyPass)
calls.append(pass_.x)
outer.run(QuantumCircuit(), callback=callback)
expected = [
"first 1",
"first 3",
# it's a do-while loop, not a while, which is why the `repeat(1)` gives two calls
"first 4",
"first 4",
# If the outer pass-manager condition is called more than once, then only the first of
# the `third` passes will appear.
"third 1",
"third 3",
"third 4",
"third 4",
]
self.assertEqual(calls, expected)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests PassManagerConfig"""
from qiskit import QuantumRegister
from qiskit.providers.backend import Backend
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import FakeMelbourne, FakeArmonk, FakeHanoi, FakeHanoiV2
from qiskit.providers.basicaer import QasmSimulatorPy
from qiskit.transpiler.coupling import CouplingMap
from qiskit.transpiler.passmanager_config import PassManagerConfig
class TestPassManagerConfig(QiskitTestCase):
"""Test PassManagerConfig.from_backend()."""
def test_config_from_backend(self):
"""Test from_backend() with a valid backend.
`FakeHanoi` is used in this testcase. This backend has `defaults` attribute
that contains an instruction schedule map.
"""
backend = FakeHanoi()
config = PassManagerConfig.from_backend(backend)
self.assertEqual(config.basis_gates, backend.configuration().basis_gates)
self.assertEqual(config.inst_map, backend.defaults().instruction_schedule_map)
self.assertEqual(
str(config.coupling_map), str(CouplingMap(backend.configuration().coupling_map))
)
def test_config_from_backend_v2(self):
"""Test from_backend() with a BackendV2 instance."""
backend = FakeHanoiV2()
config = PassManagerConfig.from_backend(backend)
self.assertEqual(config.basis_gates, backend.operation_names)
self.assertEqual(config.inst_map, backend.instruction_schedule_map)
self.assertEqual(config.coupling_map.get_edges(), backend.coupling_map.get_edges())
def test_invalid_backend(self):
"""Test from_backend() with an invalid backend."""
with self.assertRaises(AttributeError):
PassManagerConfig.from_backend(Backend())
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 = FakeMelbourne()
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 = FakeHanoi()
backend.defaults = lambda: None
config = PassManagerConfig.from_backend(backend)
self.assertIsInstance(config, PassManagerConfig)
self.assertIsNone(config.inst_map)
def test_simulator_backend_v1(self):
"""Test that from_backend() works with backendv1 simulator."""
backend = QasmSimulatorPy()
config = PassManagerConfig.from_backend(backend)
self.assertIsInstance(config, PassManagerConfig)
self.assertIsNone(config.inst_map)
self.assertIsNone(config.coupling_map)
def test_invalid_user_option(self):
"""Test from_backend() with an invalid user option."""
with self.assertRaises(TypeError):
PassManagerConfig.from_backend(FakeMelbourne(), invalid_option=None)
def test_str(self):
"""Test string output."""
pm_config = PassManagerConfig.from_backend(FakeArmonk())
# For testing remove instruction schedule map it's str output is non-deterministic
# based on hash seed
pm_config.inst_map = None
str_out = str(pm_config)
expected = """Pass Manager Config:
initial_layout: None
basis_gates: ['id', 'rz', 'sx', 'x']
inst_map: None
coupling_map: None
layout_method: None
routing_method: None
translation_method: None
scheduling_method: None
instruction_durations: id(0,): 7.111111111111111e-08 s
rz(0,): 0.0 s
sx(0,): 7.111111111111111e-08 s
x(0,): 7.111111111111111e-08 s
measure(0,): 4.977777777777777e-06 s
backend_properties: {'backend_name': 'ibmq_armonk',
'backend_version': '2.4.3',
'gates': [{'gate': 'id',
'name': 'id0',
'parameters': [{'date': datetime.datetime(2021, 3, 15, 0, 38, 15, tzinfo=tzoffset(None, -14400)),
'name': 'gate_error',
'unit': '',
'value': 0.00019769550670970334},
{'date': datetime.datetime(2021, 3, 15, 0, 40, 24, tzinfo=tzoffset(None, -14400)),
'name': 'gate_length',
'unit': 'ns',
'value': 71.11111111111111}],
'qubits': [0]},
{'gate': 'rz',
'name': 'rz0',
'parameters': [{'date': datetime.datetime(2021, 3, 15, 0, 40, 24, tzinfo=tzoffset(None, -14400)),
'name': 'gate_error',
'unit': '',
'value': 0},
{'date': datetime.datetime(2021, 3, 15, 0, 40, 24, tzinfo=tzoffset(None, -14400)),
'name': 'gate_length',
'unit': 'ns',
'value': 0}],
'qubits': [0]},
{'gate': 'sx',
'name': 'sx0',
'parameters': [{'date': datetime.datetime(2021, 3, 15, 0, 38, 15, tzinfo=tzoffset(None, -14400)),
'name': 'gate_error',
'unit': '',
'value': 0.00019769550670970334},
{'date': datetime.datetime(2021, 3, 15, 0, 40, 24, tzinfo=tzoffset(None, -14400)),
'name': 'gate_length',
'unit': 'ns',
'value': 71.11111111111111}],
'qubits': [0]},
{'gate': 'x',
'name': 'x0',
'parameters': [{'date': datetime.datetime(2021, 3, 15, 0, 38, 15, tzinfo=tzoffset(None, -14400)),
'name': 'gate_error',
'unit': '',
'value': 0.00019769550670970334},
{'date': datetime.datetime(2021, 3, 15, 0, 40, 24, tzinfo=tzoffset(None, -14400)),
'name': 'gate_length',
'unit': 'ns',
'value': 71.11111111111111}],
'qubits': [0]}],
'general': [],
'last_update_date': datetime.datetime(2021, 3, 15, 0, 40, 24, tzinfo=tzoffset(None, -14400)),
'qubits': [[{'date': datetime.datetime(2021, 3, 15, 0, 36, 17, tzinfo=tzoffset(None, -14400)),
'name': 'T1',
'unit': 'us',
'value': 182.6611165336624},
{'date': datetime.datetime(2021, 3, 14, 0, 33, 45, tzinfo=tzoffset(None, -18000)),
'name': 'T2',
'unit': 'us',
'value': 237.8589220110257},
{'date': datetime.datetime(2021, 3, 15, 0, 40, 24, tzinfo=tzoffset(None, -14400)),
'name': 'frequency',
'unit': 'GHz',
'value': 4.971852852405576},
{'date': datetime.datetime(2021, 3, 15, 0, 40, 24, tzinfo=tzoffset(None, -14400)),
'name': 'anharmonicity',
'unit': 'GHz',
'value': -0.34719293148282626},
{'date': datetime.datetime(2021, 3, 15, 0, 35, 20, tzinfo=tzoffset(None, -14400)),
'name': 'readout_error',
'unit': '',
'value': 0.02400000000000002},
{'date': datetime.datetime(2021, 3, 15, 0, 35, 20, tzinfo=tzoffset(None, -14400)),
'name': 'prob_meas0_prep1',
'unit': '',
'value': 0.0234},
{'date': datetime.datetime(2021, 3, 15, 0, 35, 20, tzinfo=tzoffset(None, -14400)),
'name': 'prob_meas1_prep0',
'unit': '',
'value': 0.024599999999999955},
{'date': datetime.datetime(2021, 3, 15, 0, 35, 20, tzinfo=tzoffset(None, -14400)),
'name': 'readout_length',
'unit': 'ns',
'value': 4977.777777777777}]]}
approximation_degree: None
seed_transpiler: None
timing_constraints: None
unitary_synthesis_method: default
unitary_synthesis_plugin_config: None
target: None
"""
self.assertEqual(str_out, expected)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests PassManager.run()"""
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.circuit.library import CXGate
from qiskit.transpiler.preset_passmanagers import level_1_pass_manager
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import FakeMelbourne
from qiskit.transpiler import Layout, PassManager
from qiskit.transpiler.passmanager_config import PassManagerConfig
class TestPassManagerRun(QiskitTestCase):
"""Test default_pass_manager.run(circuit(s))."""
def test_bare_pass_manager_single(self):
"""Test that PassManager.run(circuit) returns a single circuit."""
qc = QuantumCircuit(1)
pm = PassManager([])
new_qc = pm.run(qc)
self.assertIsInstance(new_qc, QuantumCircuit)
self.assertEqual(qc, new_qc) # pm has no passes
def test_bare_pass_manager_single_list(self):
"""Test that PassManager.run([circuit]) returns a list with a single circuit."""
qc = QuantumCircuit(1)
pm = PassManager([])
result = pm.run([qc])
self.assertIsInstance(result, list)
self.assertEqual(len(result), 1)
self.assertIsInstance(result[0], QuantumCircuit)
self.assertEqual(result[0], qc) # pm has no passes
def test_bare_pass_manager_multiple(self):
"""Test that PassManager.run(circuits) returns a list of circuits."""
qc0 = QuantumCircuit(1)
qc1 = QuantumCircuit(2)
pm = PassManager([])
result = pm.run([qc0, qc1])
self.assertIsInstance(result, list)
self.assertEqual(len(result), 2)
for qc, new_qc in zip([qc0, qc1], result):
self.assertIsInstance(new_qc, QuantumCircuit)
self.assertEqual(new_qc, qc) # pm has no passes
def test_default_pass_manager_single(self):
"""Test default_pass_manager.run(circuit).
circuit:
qr0:-[H]--.------------ -> 1
|
qr1:-----(+)--.-------- -> 2
|
qr2:---------(+)--.---- -> 3
|
qr3:-------------(+)--- -> 5
device:
0 - 1 - 2 - 3 - 4 - 5 - 6
| | | | | |
13 - 12 - 11 - 10 - 9 - 8 - 7
"""
qr = QuantumRegister(4, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[2])
circuit.cx(qr[2], qr[3])
coupling_map = FakeMelbourne().configuration().coupling_map
initial_layout = [None, qr[0], qr[1], qr[2], None, qr[3]]
pass_manager = level_1_pass_manager(
PassManagerConfig.from_backend(
FakeMelbourne(),
initial_layout=Layout.from_qubit_list(initial_layout),
seed_transpiler=42,
)
)
new_circuit = pass_manager.run(circuit)
self.assertIsInstance(new_circuit, QuantumCircuit)
bit_indices = {bit: idx for idx, bit in enumerate(new_circuit.qregs[0])}
for instruction in new_circuit.data:
if isinstance(instruction.operation, CXGate):
self.assertIn([bit_indices[x] for x in instruction.qubits], coupling_map)
def test_default_pass_manager_two(self):
"""Test default_pass_manager.run(circuitS).
circuit1 and circuit2:
qr0:-[H]--.------------ -> 1
|
qr1:-----(+)--.-------- -> 2
|
qr2:---------(+)--.---- -> 3
|
qr3:-------------(+)--- -> 5
device:
0 - 1 - 2 - 3 - 4 - 5 - 6
| | | | | |
13 - 12 - 11 - 10 - 9 - 8 - 7
"""
qr = QuantumRegister(4, "qr")
circuit1 = QuantumCircuit(qr)
circuit1.h(qr[0])
circuit1.cx(qr[0], qr[1])
circuit1.cx(qr[1], qr[2])
circuit1.cx(qr[2], qr[3])
circuit2 = QuantumCircuit(qr)
circuit2.cx(qr[1], qr[2])
circuit2.cx(qr[0], qr[1])
circuit2.cx(qr[2], qr[3])
coupling_map = FakeMelbourne().configuration().coupling_map
initial_layout = [None, qr[0], qr[1], qr[2], None, qr[3]]
pass_manager = level_1_pass_manager(
PassManagerConfig.from_backend(
FakeMelbourne(),
initial_layout=Layout.from_qubit_list(initial_layout),
seed_transpiler=42,
)
)
new_circuits = pass_manager.run([circuit1, circuit2])
self.assertIsInstance(new_circuits, list)
self.assertEqual(len(new_circuits), 2)
for new_circuit in new_circuits:
self.assertIsInstance(new_circuit, QuantumCircuit)
bit_indices = {bit: idx for idx, bit in enumerate(new_circuit.qregs[0])}
for instruction in new_circuit.data:
if isinstance(instruction.operation, CXGate):
self.assertIn([bit_indices[x] for x in instruction.qubits], coupling_map)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test calling passes (passmanager-less)"""
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.circuit.library import ZGate
from qiskit.transpiler.passes import Unroller
from qiskit.test import QiskitTestCase
from qiskit.exceptions import QiskitError
from qiskit.transpiler import PropertySet
from ._dummy_passes import PassD_TP_NR_NP, PassE_AP_NR_NP, PassN_AP_NR_NP
class TestPassCall(QiskitTestCase):
"""Test calling passes (passmanager-less)."""
def assertMessageLog(self, context, messages):
"""Checks the log messages"""
self.assertEqual([record.message for record in context.records], messages)
def test_transformation_pass(self):
"""Call a transformation pass without a scheduler"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr, name="MyCircuit")
pass_d = PassD_TP_NR_NP(argument1=[1, 2])
with self.assertLogs("LocalLogger", level="INFO") as cm:
result = pass_d(circuit)
self.assertMessageLog(cm, ["run transformation pass PassD_TP_NR_NP", "argument [1, 2]"])
self.assertEqual(circuit, result)
def test_analysis_pass_dict(self):
"""Call an analysis pass without a scheduler (property_set dict)"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr, name="MyCircuit")
property_set = {"another_property": "another_value"}
pass_e = PassE_AP_NR_NP("value")
with self.assertLogs("LocalLogger", level="INFO") as cm:
result = pass_e(circuit, property_set)
self.assertMessageLog(cm, ["run analysis pass PassE_AP_NR_NP", "set property as value"])
self.assertEqual(property_set, {"another_property": "another_value", "property": "value"})
self.assertIsInstance(property_set, dict)
self.assertEqual(circuit, result)
def test_analysis_pass_property_set(self):
"""Call an analysis pass without a scheduler (PropertySet dict)"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr, name="MyCircuit")
property_set = PropertySet({"another_property": "another_value"})
pass_e = PassE_AP_NR_NP("value")
with self.assertLogs("LocalLogger", level="INFO") as cm:
result = pass_e(circuit, property_set)
self.assertMessageLog(cm, ["run analysis pass PassE_AP_NR_NP", "set property as value"])
self.assertEqual(
property_set, PropertySet({"another_property": "another_value", "property": "value"})
)
self.assertIsInstance(property_set, PropertySet)
self.assertEqual(circuit, result)
def test_analysis_pass_remove_property(self):
"""Call an analysis pass that removes a property without a scheduler"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr, name="MyCircuit")
property_set = {"to remove": "value to remove", "to none": "value to none"}
pass_e = PassN_AP_NR_NP("to remove", "to none")
with self.assertLogs("LocalLogger", level="INFO") as cm:
result = pass_e(circuit, property_set)
self.assertMessageLog(
cm,
[
"run analysis pass PassN_AP_NR_NP",
"property to remove deleted",
"property to none noned",
],
)
self.assertEqual(property_set, PropertySet({"to none": None}))
self.assertIsInstance(property_set, dict)
self.assertEqual(circuit, result)
def test_error_unknown_defn_unroller_pass(self):
"""Check for proper error message when unroller cannot find the definition
of a gate."""
circuit = ZGate().control(2).definition
basis = ["u1", "u2", "u3", "cx"]
unroller = Unroller(basis)
with self.assertRaises(QiskitError) as cm:
unroller(circuit)
exp_msg = (
"Error decomposing node of instruction 'p': 'NoneType' object has no"
" attribute 'global_phase'. Unable to define instruction 'u' in the basis."
)
self.assertEqual(exp_msg, cm.exception.message)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Transpiler testing"""
import io
from logging import StreamHandler, getLogger
import unittest.mock
import sys
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.transpiler import PassManager, TranspilerError
from qiskit.transpiler.runningpassmanager import (
DoWhileController,
ConditionalController,
FlowController,
)
from qiskit.test import QiskitTestCase
from ._dummy_passes import (
PassA_TP_NR_NP,
PassB_TP_RA_PA,
PassC_TP_RA_PA,
PassD_TP_NR_NP,
PassE_AP_NR_NP,
PassF_reduce_dag_property,
PassI_Bad_AP,
PassJ_Bad_NoReturn,
PassK_check_fixed_point_property,
PassM_AP_NR_NP,
)
class SchedulerTestCase(QiskitTestCase):
"""Asserts for the scheduler."""
def assertScheduler(self, circuit, passmanager, expected):
"""
Run `transpile(circuit, passmanager)` and check
if the passes run as expected.
Args:
circuit (QuantumCircuit): Circuit to transform via transpilation.
passmanager (PassManager): pass manager instance for the transpilation process
expected (list): List of things the passes are logging
"""
logger = "LocalLogger"
with self.assertLogs(logger, level="INFO") as cm:
out = passmanager.run(circuit)
self.assertIsInstance(out, QuantumCircuit)
self.assertEqual([record.message for record in cm.records], expected)
def assertSchedulerRaises(self, circuit, passmanager, expected, exception_type):
"""
Run `transpile(circuit, passmanager)` and check
if the passes run as expected until exception_type is raised.
Args:
circuit (QuantumCircuit): Circuit to transform via transpilation
passmanager (PassManager): pass manager instance for the transpilation process
expected (list): List of things the passes are logging
exception_type (Exception): Exception that is expected to be raised.
"""
logger = "LocalLogger"
with self.assertLogs(logger, level="INFO") as cm:
self.assertRaises(exception_type, passmanager.run, circuit)
self.assertEqual([record.message for record in cm.records], expected)
class TestPassManagerInit(SchedulerTestCase):
"""The pass manager sets things at init time."""
def test_passes(self):
"""A single chain of passes, with Requests and Preserves, at __init__ time"""
circuit = QuantumCircuit(QuantumRegister(1))
passmanager = PassManager(
passes=[
PassC_TP_RA_PA(), # Request: PassA / Preserves: PassA
PassB_TP_RA_PA(), # Request: PassA / Preserves: PassA
PassD_TP_NR_NP(argument1=[1, 2]), # Requires: {}/ Preserves: {}
PassB_TP_RA_PA(),
]
)
self.assertScheduler(
circuit,
passmanager,
[
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassC_TP_RA_PA",
"run transformation pass PassB_TP_RA_PA",
"run transformation pass PassD_TP_NR_NP",
"argument [1, 2]",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassB_TP_RA_PA",
],
)
class TestUseCases(SchedulerTestCase):
"""Combine passes in different ways and checks that passes are run
in the right order."""
def setUp(self):
super().setUp()
self.circuit = QuantumCircuit(QuantumRegister(1))
self.passmanager = PassManager()
def test_chain(self):
"""A single chain of passes, with Requires and Preserves."""
self.passmanager.append(PassC_TP_RA_PA()) # Requires: PassA / Preserves: PassA
self.passmanager.append(PassB_TP_RA_PA()) # Requires: PassA / Preserves: PassA
self.passmanager.append(PassD_TP_NR_NP(argument1=[1, 2])) # Requires: {}/ Preserves: {}
self.passmanager.append(PassB_TP_RA_PA())
self.assertScheduler(
self.circuit,
self.passmanager,
[
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassC_TP_RA_PA",
"run transformation pass PassB_TP_RA_PA",
"run transformation pass PassD_TP_NR_NP",
"argument [1, 2]",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassB_TP_RA_PA",
],
)
def test_conditional_passes_true(self):
"""A pass set with a conditional parameter. The callable is True."""
self.passmanager.append(PassE_AP_NR_NP(True))
self.passmanager.append(
PassA_TP_NR_NP(), condition=lambda property_set: property_set["property"]
)
self.assertScheduler(
self.circuit,
self.passmanager,
[
"run analysis pass PassE_AP_NR_NP",
"set property as True",
"run transformation pass PassA_TP_NR_NP",
],
)
def test_conditional_passes_true_fc(self):
"""A pass set with a conditional parameter (with FlowController). The callable is True."""
self.passmanager.append(PassE_AP_NR_NP(True))
self.passmanager.append(
ConditionalController(
[PassA_TP_NR_NP()], condition=lambda property_set: property_set["property"]
)
)
self.assertScheduler(
self.circuit,
self.passmanager,
[
"run analysis pass PassE_AP_NR_NP",
"set property as True",
"run transformation pass PassA_TP_NR_NP",
],
)
def test_conditional_passes_false(self):
"""A pass set with a conditional parameter. The callable is False."""
self.passmanager.append(PassE_AP_NR_NP(False))
self.passmanager.append(
PassA_TP_NR_NP(), condition=lambda property_set: property_set["property"]
)
self.assertScheduler(
self.circuit,
self.passmanager,
["run analysis pass PassE_AP_NR_NP", "set property as False"],
)
def test_conditional_and_loop(self):
"""Run a conditional first, then a loop."""
self.passmanager.append(PassE_AP_NR_NP(True))
self.passmanager.append(
[PassK_check_fixed_point_property(), PassA_TP_NR_NP(), PassF_reduce_dag_property()],
do_while=lambda property_set: not property_set["property_fixed_point"],
condition=lambda property_set: property_set["property"],
)
self.assertScheduler(
self.circuit,
self.passmanager,
[
"run analysis pass PassE_AP_NR_NP",
"set property as True",
"run analysis pass PassG_calculates_dag_property",
"set property as 8 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 6",
"run analysis pass PassG_calculates_dag_property",
"set property as 6 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 5",
"run analysis pass PassG_calculates_dag_property",
"set property as 5 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 4",
"run analysis pass PassG_calculates_dag_property",
"set property as 4 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 3",
"run analysis pass PassG_calculates_dag_property",
"set property as 3 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 2",
"run analysis pass PassG_calculates_dag_property",
"set property as 2 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 2",
"run analysis pass PassG_calculates_dag_property",
"set property as 2 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 2",
],
)
def test_loop_and_conditional(self):
"""Run a loop first, then a conditional."""
FlowController.remove_flow_controller("condition")
FlowController.add_flow_controller("condition", ConditionalController)
self.passmanager.append(PassK_check_fixed_point_property())
self.passmanager.append(
[PassK_check_fixed_point_property(), PassA_TP_NR_NP(), PassF_reduce_dag_property()],
do_while=lambda property_set: not property_set["property_fixed_point"],
condition=lambda property_set: not property_set["property_fixed_point"],
)
self.assertScheduler(
self.circuit,
self.passmanager,
[
"run analysis pass PassG_calculates_dag_property",
"set property as 8 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 6",
"run analysis pass PassG_calculates_dag_property",
"set property as 6 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 5",
"run analysis pass PassG_calculates_dag_property",
"set property as 5 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 4",
"run analysis pass PassG_calculates_dag_property",
"set property as 4 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 3",
"run analysis pass PassG_calculates_dag_property",
"set property as 3 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 2",
"run analysis pass PassG_calculates_dag_property",
"set property as 2 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 2",
"run analysis pass PassG_calculates_dag_property",
"set property as 2 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 2",
],
)
def test_do_not_repeat_based_on_preservation(self):
"""When a pass is still a valid pass (because the following passes
preserved it), it should not run again."""
self.passmanager.append([PassB_TP_RA_PA(), PassA_TP_NR_NP(), PassB_TP_RA_PA()])
self.assertScheduler(
self.circuit,
self.passmanager,
["run transformation pass PassA_TP_NR_NP", "run transformation pass PassB_TP_RA_PA"],
)
def test_do_not_repeat_based_on_idempotence(self):
"""Repetition can be optimized to a single execution when
the pass is idempotent."""
self.passmanager.append(PassA_TP_NR_NP())
self.passmanager.append([PassA_TP_NR_NP(), PassA_TP_NR_NP()])
self.passmanager.append(PassA_TP_NR_NP())
self.assertScheduler(
self.circuit, self.passmanager, ["run transformation pass PassA_TP_NR_NP"]
)
def test_non_idempotent_pass(self):
"""Two or more runs of a non-idempotent pass cannot be optimized."""
self.passmanager.append(PassF_reduce_dag_property())
self.passmanager.append([PassF_reduce_dag_property(), PassF_reduce_dag_property()])
self.passmanager.append(PassF_reduce_dag_property())
self.assertScheduler(
self.circuit,
self.passmanager,
[
"run transformation pass PassF_reduce_dag_property",
"dag property = 6",
"run transformation pass PassF_reduce_dag_property",
"dag property = 5",
"run transformation pass PassF_reduce_dag_property",
"dag property = 4",
"run transformation pass PassF_reduce_dag_property",
"dag property = 3",
],
)
def test_fenced_dag(self):
"""Analysis passes are not allowed to modified the DAG."""
qr = QuantumRegister(2)
circ = QuantumCircuit(qr)
circ.cx(qr[0], qr[1])
circ.cx(qr[0], qr[1])
circ.cx(qr[1], qr[0])
circ.cx(qr[1], qr[0])
self.passmanager.append(PassI_Bad_AP())
self.assertSchedulerRaises(
circ,
self.passmanager,
["run analysis pass PassI_Bad_AP", "cx_runs: {(4, 5, 6, 7)}"],
TranspilerError,
)
def test_analysis_pass_is_idempotent(self):
"""Analysis passes are idempotent."""
passmanager = PassManager()
passmanager.append(PassE_AP_NR_NP(argument1=1))
passmanager.append(PassE_AP_NR_NP(argument1=1))
self.assertScheduler(
self.circuit, passmanager, ["run analysis pass PassE_AP_NR_NP", "set property as 1"]
)
def test_ap_before_and_after_a_tp(self):
"""A default transformation does not preserves anything
and analysis passes need to be re-run"""
passmanager = PassManager()
passmanager.append(PassE_AP_NR_NP(argument1=1))
passmanager.append(PassA_TP_NR_NP())
passmanager.append(PassE_AP_NR_NP(argument1=1))
self.assertScheduler(
self.circuit,
passmanager,
[
"run analysis pass PassE_AP_NR_NP",
"set property as 1",
"run transformation pass PassA_TP_NR_NP",
"run analysis pass PassE_AP_NR_NP",
"set property as 1",
],
)
def test_pass_no_return(self):
"""Transformation passes that don't return a DAG raise error."""
self.passmanager.append(PassJ_Bad_NoReturn())
self.assertSchedulerRaises(
self.circuit,
self.passmanager,
["run transformation pass PassJ_Bad_NoReturn"],
TranspilerError,
)
def test_fixed_point_pass(self):
"""A pass set with a do_while parameter that checks for a fixed point."""
self.passmanager.append(
[PassK_check_fixed_point_property(), PassA_TP_NR_NP(), PassF_reduce_dag_property()],
do_while=lambda property_set: not property_set["property_fixed_point"],
)
self.assertScheduler(
self.circuit,
self.passmanager,
[
"run analysis pass PassG_calculates_dag_property",
"set property as 8 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 6",
"run analysis pass PassG_calculates_dag_property",
"set property as 6 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 5",
"run analysis pass PassG_calculates_dag_property",
"set property as 5 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 4",
"run analysis pass PassG_calculates_dag_property",
"set property as 4 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 3",
"run analysis pass PassG_calculates_dag_property",
"set property as 3 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 2",
"run analysis pass PassG_calculates_dag_property",
"set property as 2 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 2",
"run analysis pass PassG_calculates_dag_property",
"set property as 2 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 2",
],
)
def test_fixed_point_fc(self):
"""A fixed point scheduler with flow control."""
self.passmanager.append(
DoWhileController(
[PassK_check_fixed_point_property(), PassA_TP_NR_NP(), PassF_reduce_dag_property()],
do_while=lambda property_set: not property_set["property_fixed_point"],
)
)
expected = [
"run analysis pass PassG_calculates_dag_property",
"set property as 8 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 6",
"run analysis pass PassG_calculates_dag_property",
"set property as 6 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 5",
"run analysis pass PassG_calculates_dag_property",
"set property as 5 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 4",
"run analysis pass PassG_calculates_dag_property",
"set property as 4 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 3",
"run analysis pass PassG_calculates_dag_property",
"set property as 3 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 2",
"run analysis pass PassG_calculates_dag_property",
"set property as 2 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 2",
"run analysis pass PassG_calculates_dag_property",
"set property as 2 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 2",
]
self.assertScheduler(self.circuit, self.passmanager, expected)
def test_fixed_point_pass_max_iteration(self):
"""A pass set with a do_while parameter that checks that
the max_iteration is raised."""
self.passmanager.append(
[PassK_check_fixed_point_property(), PassA_TP_NR_NP(), PassF_reduce_dag_property()],
do_while=lambda property_set: not property_set["property_fixed_point"],
max_iteration=2,
)
self.assertSchedulerRaises(
self.circuit,
self.passmanager,
[
"run analysis pass PassG_calculates_dag_property",
"set property as 8 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 6",
"run analysis pass PassG_calculates_dag_property",
"set property as 6 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 5",
],
TranspilerError,
)
def test_fresh_initial_state(self):
"""New construction gives fresh instance."""
self.passmanager.append(PassM_AP_NR_NP(argument1=1))
self.passmanager.append(PassA_TP_NR_NP())
self.passmanager.append(PassM_AP_NR_NP(argument1=1))
self.assertScheduler(
self.circuit,
self.passmanager,
[
"run analysis pass PassM_AP_NR_NP",
"self.argument1 = 2",
"run transformation pass PassA_TP_NR_NP",
"run analysis pass PassM_AP_NR_NP",
"self.argument1 = 2",
],
)
def test_nested_conditional_in_loop(self):
"""Run a loop with a nested conditional."""
nested_conditional = [
ConditionalController(
[PassA_TP_NR_NP()], condition=lambda property_set: property_set["property"] >= 5
)
]
self.passmanager.append(
[PassK_check_fixed_point_property()]
+ nested_conditional
+ [PassF_reduce_dag_property()],
do_while=lambda property_set: not property_set["property_fixed_point"],
)
expected = [
"run analysis pass PassG_calculates_dag_property",
"set property as 8 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 6",
"run analysis pass PassG_calculates_dag_property",
"set property as 6 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 5",
"run analysis pass PassG_calculates_dag_property",
"set property as 5 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 4",
"run analysis pass PassG_calculates_dag_property",
"set property as 4 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassF_reduce_dag_property",
"dag property = 3",
"run analysis pass PassG_calculates_dag_property",
"set property as 3 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassF_reduce_dag_property",
"dag property = 2",
"run analysis pass PassG_calculates_dag_property",
"set property as 2 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassF_reduce_dag_property",
"dag property = 2",
"run analysis pass PassG_calculates_dag_property",
"set property as 2 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassF_reduce_dag_property",
"dag property = 2",
]
self.assertScheduler(self.circuit, self.passmanager, expected)
class DoXTimesController(FlowController):
"""A control-flow plugin for running a set of passes an X amount of times."""
def __init__(self, passes, options, do_x_times=0, **_):
self.do_x_times = do_x_times()
super().__init__(passes, options)
def __iter__(self):
for _ in range(self.do_x_times):
yield from self.passes
class TestControlFlowPlugin(SchedulerTestCase):
"""Testing the control flow plugin system."""
def setUp(self):
super().setUp()
self.passmanager = PassManager()
self.circuit = QuantumCircuit(QuantumRegister(1))
def test_control_flow_plugin(self):
"""Adds a control flow plugin with a single parameter and runs it."""
FlowController.add_flow_controller("do_x_times", DoXTimesController)
self.passmanager.append([PassB_TP_RA_PA(), PassC_TP_RA_PA()], do_x_times=lambda x: 3)
self.assertScheduler(
self.circuit,
self.passmanager,
[
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassB_TP_RA_PA",
"run transformation pass PassC_TP_RA_PA",
"run transformation pass PassB_TP_RA_PA",
"run transformation pass PassC_TP_RA_PA",
"run transformation pass PassB_TP_RA_PA",
"run transformation pass PassC_TP_RA_PA",
],
)
def test_callable_control_flow_plugin(self):
"""Removes do_while, then adds it back. Checks max_iteration still working."""
controllers_length = len(FlowController.registered_controllers)
FlowController.remove_flow_controller("do_while")
self.assertEqual(controllers_length - 1, len(FlowController.registered_controllers))
FlowController.add_flow_controller("do_while", DoWhileController)
self.assertEqual(controllers_length, len(FlowController.registered_controllers))
self.passmanager.append(
[PassB_TP_RA_PA(), PassC_TP_RA_PA()],
do_while=lambda property_set: True,
max_iteration=2,
)
self.assertSchedulerRaises(
self.circuit,
self.passmanager,
[
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassB_TP_RA_PA",
"run transformation pass PassC_TP_RA_PA",
"run transformation pass PassB_TP_RA_PA",
"run transformation pass PassC_TP_RA_PA",
],
TranspilerError,
)
def test_remove_nonexistent_plugin(self):
"""Tries to remove a plugin that does not exist."""
self.assertRaises(KeyError, FlowController.remove_flow_controller, "foo")
def test_bad_conditional(self):
"""Flow controller are not allowed to modify the property set."""
def bad_condition(property_set):
property_set["property"] = "forbidden write"
self.passmanager.append(PassA_TP_NR_NP(), condition=bad_condition)
self.assertRaises(TranspilerError, self.passmanager.run, self.circuit)
class TestDumpPasses(SchedulerTestCase):
"""Testing the passes method."""
def test_passes(self):
"""Dump passes in different FlowControllerLinear"""
passmanager = PassManager()
passmanager.append(PassC_TP_RA_PA())
passmanager.append(PassB_TP_RA_PA())
expected = [
{"flow_controllers": {}, "passes": [PassC_TP_RA_PA()]},
{"flow_controllers": {}, "passes": [PassB_TP_RA_PA()]},
]
self.assertEqual(expected, passmanager.passes())
def test_passes_in_linear(self):
"""Dump passes in the same FlowControllerLinear"""
passmanager = PassManager(
passes=[
PassC_TP_RA_PA(),
PassB_TP_RA_PA(),
PassD_TP_NR_NP(argument1=[1, 2]),
PassB_TP_RA_PA(),
]
)
expected = [
{
"flow_controllers": {},
"passes": [
PassC_TP_RA_PA(),
PassB_TP_RA_PA(),
PassD_TP_NR_NP(argument1=[1, 2]),
PassB_TP_RA_PA(),
],
}
]
self.assertEqual(expected, passmanager.passes())
def test_control_flow_plugin(self):
"""Dump passes in a custom flow controller."""
passmanager = PassManager()
FlowController.add_flow_controller("do_x_times", DoXTimesController)
passmanager.append([PassB_TP_RA_PA(), PassC_TP_RA_PA()], do_x_times=lambda x: 3)
expected = [
{"passes": [PassB_TP_RA_PA(), PassC_TP_RA_PA()], "flow_controllers": {"do_x_times"}}
]
self.assertEqual(expected, passmanager.passes())
def test_conditional_and_loop(self):
"""Dump passes with a conditional and a loop."""
passmanager = PassManager()
passmanager.append(PassE_AP_NR_NP(True))
passmanager.append(
[PassK_check_fixed_point_property(), PassA_TP_NR_NP(), PassF_reduce_dag_property()],
do_while=lambda property_set: not property_set["property_fixed_point"],
condition=lambda property_set: property_set["property_fixed_point"],
)
expected = [
{"passes": [PassE_AP_NR_NP(True)], "flow_controllers": {}},
{
"passes": [
PassK_check_fixed_point_property(),
PassA_TP_NR_NP(),
PassF_reduce_dag_property(),
],
"flow_controllers": {"condition", "do_while"},
},
]
self.assertEqual(expected, passmanager.passes())
class StreamHandlerRaiseException(StreamHandler):
"""Handler class that will raise an exception on formatting errors."""
def handleError(self, record):
raise sys.exc_info()
class TestLogPasses(QiskitTestCase):
"""Testing the log_passes option."""
def setUp(self):
super().setUp()
logger = getLogger()
self.addCleanup(logger.setLevel, logger.level)
logger.setLevel("DEBUG")
self.output = io.StringIO()
logger.addHandler(StreamHandlerRaiseException(self.output))
self.circuit = QuantumCircuit(QuantumRegister(1))
def assertPassLog(self, passmanager, list_of_passes):
"""Runs the passmanager and checks that the elements in
passmanager.property_set['pass_log'] match list_of_passes (the names)."""
passmanager.run(self.circuit)
self.output.seek(0)
# Filter unrelated log lines
output_lines = self.output.readlines()
pass_log_lines = [x for x in output_lines if x.startswith("Pass:")]
for index, pass_name in enumerate(list_of_passes):
self.assertTrue(pass_log_lines[index].startswith("Pass: %s -" % pass_name))
def test_passes(self):
"""Dump passes in different FlowControllerLinear"""
passmanager = PassManager()
passmanager.append(PassC_TP_RA_PA())
passmanager.append(PassB_TP_RA_PA())
self.assertPassLog(passmanager, ["PassA_TP_NR_NP", "PassC_TP_RA_PA", "PassB_TP_RA_PA"])
def test_passes_in_linear(self):
"""Dump passes in the same FlowControllerLinear"""
passmanager = PassManager(
passes=[
PassC_TP_RA_PA(),
PassB_TP_RA_PA(),
PassD_TP_NR_NP(argument1=[1, 2]),
PassB_TP_RA_PA(),
]
)
self.assertPassLog(
passmanager,
[
"PassA_TP_NR_NP",
"PassC_TP_RA_PA",
"PassB_TP_RA_PA",
"PassD_TP_NR_NP",
"PassA_TP_NR_NP",
"PassB_TP_RA_PA",
],
)
def test_control_flow_plugin(self):
"""Dump passes in a custom flow controller."""
passmanager = PassManager()
FlowController.add_flow_controller("do_x_times", DoXTimesController)
passmanager.append([PassB_TP_RA_PA(), PassC_TP_RA_PA()], do_x_times=lambda x: 3)
self.assertPassLog(
passmanager,
[
"PassA_TP_NR_NP",
"PassB_TP_RA_PA",
"PassC_TP_RA_PA",
"PassB_TP_RA_PA",
"PassC_TP_RA_PA",
"PassB_TP_RA_PA",
"PassC_TP_RA_PA",
],
)
def test_conditional_and_loop(self):
"""Dump passes with a conditional and a loop"""
passmanager = PassManager()
passmanager.append(PassE_AP_NR_NP(True))
passmanager.append(
[PassK_check_fixed_point_property(), PassA_TP_NR_NP(), PassF_reduce_dag_property()],
do_while=lambda property_set: not property_set["property_fixed_point"],
condition=lambda property_set: property_set["property_fixed_point"],
)
self.assertPassLog(passmanager, ["PassE_AP_NR_NP"])
class TestPassManagerReuse(SchedulerTestCase):
"""The PassManager instance should be reusable."""
def setUp(self):
super().setUp()
self.passmanager = PassManager()
self.circuit = QuantumCircuit(QuantumRegister(1))
def test_chain_twice(self):
"""Run a chain twice."""
self.passmanager.append(PassC_TP_RA_PA()) # Request: PassA / Preserves: PassA
self.passmanager.append(PassB_TP_RA_PA()) # Request: PassA / Preserves: PassA
expected = [
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassC_TP_RA_PA",
"run transformation pass PassB_TP_RA_PA",
]
self.assertScheduler(self.circuit, self.passmanager, expected)
self.assertScheduler(self.circuit, self.passmanager, expected)
def test_conditional_twice(self):
"""Run a conditional twice."""
self.passmanager.append(PassE_AP_NR_NP(True))
self.passmanager.append(
PassA_TP_NR_NP(), condition=lambda property_set: property_set["property"]
)
expected = [
"run analysis pass PassE_AP_NR_NP",
"set property as True",
"run transformation pass PassA_TP_NR_NP",
]
self.assertScheduler(self.circuit, self.passmanager, expected)
self.assertScheduler(self.circuit, self.passmanager, expected)
def test_fixed_point_twice(self):
"""A fixed point scheduler, twice."""
self.passmanager.append(
[PassK_check_fixed_point_property(), PassA_TP_NR_NP(), PassF_reduce_dag_property()],
do_while=lambda property_set: not property_set["property_fixed_point"],
)
expected = [
"run analysis pass PassG_calculates_dag_property",
"set property as 8 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 6",
"run analysis pass PassG_calculates_dag_property",
"set property as 6 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 5",
"run analysis pass PassG_calculates_dag_property",
"set property as 5 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 4",
"run analysis pass PassG_calculates_dag_property",
"set property as 4 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 3",
"run analysis pass PassG_calculates_dag_property",
"set property as 3 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 2",
"run analysis pass PassG_calculates_dag_property",
"set property as 2 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 2",
"run analysis pass PassG_calculates_dag_property",
"set property as 2 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 2",
]
self.assertScheduler(self.circuit, self.passmanager, expected)
self.assertScheduler(self.circuit, self.passmanager, expected)
class TestPassManagerChanges(SchedulerTestCase):
"""Test PassManager manipulation with changes"""
def setUp(self):
super().setUp()
self.passmanager = PassManager()
self.circuit = QuantumCircuit(QuantumRegister(1))
def test_replace0(self):
"""Test passmanager.replace(0, ...)."""
self.passmanager.append(PassC_TP_RA_PA()) # Request: PassA / Preserves: PassA
self.passmanager.append(PassB_TP_RA_PA()) # Request: PassA / Preserves: PassA
self.passmanager.replace(0, PassB_TP_RA_PA())
expected = [
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassB_TP_RA_PA",
]
self.assertScheduler(self.circuit, self.passmanager, expected)
def test_replace1(self):
"""Test passmanager.replace(1, ...)."""
self.passmanager.append(PassC_TP_RA_PA()) # Request: PassA / Preserves: PassA
self.passmanager.append(PassB_TP_RA_PA()) # Request: PassA / Preserves: PassA
self.passmanager.replace(1, PassC_TP_RA_PA())
expected = [
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassC_TP_RA_PA",
]
self.assertScheduler(self.circuit, self.passmanager, expected)
def test_remove0(self):
"""Test passmanager.remove(0)."""
self.passmanager.append(PassC_TP_RA_PA()) # Request: PassA / Preserves: PassA
self.passmanager.append(PassB_TP_RA_PA()) # Request: PassA / Preserves: PassA
self.passmanager.remove(0)
expected = [
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassB_TP_RA_PA",
]
self.assertScheduler(self.circuit, self.passmanager, expected)
def test_remove1(self):
"""Test passmanager.remove(1)."""
self.passmanager.append(PassC_TP_RA_PA()) # Request: PassA / Preserves: PassA
self.passmanager.append(PassB_TP_RA_PA()) # Request: PassA / Preserves: PassA
self.passmanager.remove(1)
expected = [
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassC_TP_RA_PA",
]
self.assertScheduler(self.circuit, self.passmanager, expected)
def test_remove_minus_1(self):
"""Test passmanager.remove(-1)."""
self.passmanager.append(PassA_TP_NR_NP())
self.passmanager.append(PassB_TP_RA_PA()) # Request: PassA / Preserves: PassA
self.passmanager.remove(-1)
expected = ["run transformation pass PassA_TP_NR_NP"]
self.assertScheduler(self.circuit, self.passmanager, expected)
def test_setitem(self):
"""Test passmanager[1] = ..."""
self.passmanager.append(PassC_TP_RA_PA()) # Request: PassA / Preserves: PassA
self.passmanager.append(PassB_TP_RA_PA()) # Request: PassA / Preserves: PassA
self.passmanager[1] = PassC_TP_RA_PA()
expected = [
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassC_TP_RA_PA",
]
self.assertScheduler(self.circuit, self.passmanager, expected)
def test_replace_with_conditional(self):
"""Replace a pass with a conditional pass."""
self.passmanager.append(PassE_AP_NR_NP(False))
self.passmanager.append(PassB_TP_RA_PA())
self.passmanager.replace(
1, PassA_TP_NR_NP(), condition=lambda property_set: property_set["property"]
)
expected = ["run analysis pass PassE_AP_NR_NP", "set property as False"]
self.assertScheduler(self.circuit, self.passmanager, expected)
def test_replace_error(self):
"""Replace a non-existing index."""
self.passmanager.append(PassB_TP_RA_PA())
with self.assertRaises(TranspilerError):
self.passmanager.replace(99, PassA_TP_NR_NP())
class TestPassManagerSlicing(SchedulerTestCase):
"""test PassManager slicing."""
def setUp(self):
super().setUp()
self.passmanager = PassManager()
self.circuit = QuantumCircuit(QuantumRegister(1))
def test_empty_passmanager_length(self):
"""test len(PassManager) when PassManager is empty"""
length = len(self.passmanager)
expected_length = 0
self.assertEqual(length, expected_length)
def test_passmanager_length(self):
"""test len(PassManager) when PassManager is not empty"""
self.passmanager.append(PassA_TP_NR_NP())
self.passmanager.append(PassA_TP_NR_NP())
length = len(self.passmanager)
expected_length = 2
self.assertEqual(length, expected_length)
def test_accessing_passmanager_by_index(self):
"""test accessing PassManager's passes by index"""
self.passmanager.append(PassB_TP_RA_PA())
self.passmanager.append(PassC_TP_RA_PA())
new_passmanager = self.passmanager[1]
expected = [
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassC_TP_RA_PA",
]
self.assertScheduler(self.circuit, new_passmanager, expected)
def test_accessing_passmanager_by_index_with_condition(self):
"""test accessing PassManager's conditioned passes by index"""
self.passmanager.append(PassF_reduce_dag_property())
self.passmanager.append(
[PassK_check_fixed_point_property(), PassA_TP_NR_NP(), PassF_reduce_dag_property()],
condition=lambda property_set: True,
do_while=lambda property_set: not property_set["property_fixed_point"],
)
new_passmanager = self.passmanager[1]
expected = [
"run analysis pass PassG_calculates_dag_property",
"set property as 8 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 6",
"run analysis pass PassG_calculates_dag_property",
"set property as 6 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 5",
"run analysis pass PassG_calculates_dag_property",
"set property as 5 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 4",
"run analysis pass PassG_calculates_dag_property",
"set property as 4 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 3",
"run analysis pass PassG_calculates_dag_property",
"set property as 3 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 2",
"run analysis pass PassG_calculates_dag_property",
"set property as 2 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 2",
"run analysis pass PassG_calculates_dag_property",
"set property as 2 (from dag.property)",
"run analysis pass PassK_check_fixed_point_property",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassF_reduce_dag_property",
"dag property = 2",
]
self.assertScheduler(self.circuit, new_passmanager, expected)
def test_accessing_passmanager_by_range(self):
"""test accessing PassManager's passes by range"""
self.passmanager.append(PassC_TP_RA_PA())
self.passmanager.append(PassB_TP_RA_PA())
self.passmanager.append(PassC_TP_RA_PA())
self.passmanager.append(PassD_TP_NR_NP())
new_passmanager = self.passmanager[1:3]
expected = [
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassB_TP_RA_PA",
"run transformation pass PassC_TP_RA_PA",
]
self.assertScheduler(self.circuit, new_passmanager, expected)
def test_accessing_passmanager_by_range_with_condition(self):
"""test accessing PassManager's passes by range with condition"""
self.passmanager.append(PassB_TP_RA_PA())
self.passmanager.append(PassE_AP_NR_NP(True))
self.passmanager.append(
PassA_TP_NR_NP(), condition=lambda property_set: property_set["property"]
)
self.passmanager.append(PassB_TP_RA_PA())
new_passmanager = self.passmanager[1:3]
expected = [
"run analysis pass PassE_AP_NR_NP",
"set property as True",
"run transformation pass PassA_TP_NR_NP",
]
self.assertScheduler(self.circuit, new_passmanager, expected)
def test_accessing_passmanager_error(self):
"""testing accessing a pass item not in list"""
self.passmanager.append(PassB_TP_RA_PA())
with self.assertRaises(IndexError):
self.passmanager = self.passmanager[99]
class TestPassManagerConcatenation(SchedulerTestCase):
"""test PassManager concatenation by + operator."""
def setUp(self):
super().setUp()
self.passmanager1 = PassManager()
self.passmanager2 = PassManager()
self.circuit = QuantumCircuit(QuantumRegister(1))
def test_concatenating_passmanagers(self):
"""test adding two PassManagers together"""
self.passmanager1.append(PassB_TP_RA_PA())
self.passmanager2.append(PassC_TP_RA_PA())
new_passmanager = self.passmanager1 + self.passmanager2
expected = [
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassB_TP_RA_PA",
"run transformation pass PassC_TP_RA_PA",
]
self.assertScheduler(self.circuit, new_passmanager, expected)
def test_concatenating_passmanagers_with_condition(self):
"""test adding two pass managers with condition"""
self.passmanager1.append(PassE_AP_NR_NP(True))
self.passmanager1.append(PassB_TP_RA_PA())
self.passmanager2.append(
PassC_TP_RA_PA(), condition=lambda property_set: property_set["property"]
)
self.passmanager2.append(PassB_TP_RA_PA())
new_passmanager = self.passmanager1 + self.passmanager2
expected = [
"run analysis pass PassE_AP_NR_NP",
"set property as True",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassB_TP_RA_PA",
"run transformation pass PassC_TP_RA_PA",
"run transformation pass PassB_TP_RA_PA",
]
self.assertScheduler(self.circuit, new_passmanager, expected)
def test_adding_pass_to_passmanager(self):
"""test adding a pass to PassManager"""
self.passmanager1.append(PassE_AP_NR_NP(argument1=1))
self.passmanager1.append(PassB_TP_RA_PA())
self.passmanager1 += PassC_TP_RA_PA()
expected = [
"run analysis pass PassE_AP_NR_NP",
"set property as 1",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassB_TP_RA_PA",
"run transformation pass PassC_TP_RA_PA",
]
self.assertScheduler(self.circuit, self.passmanager1, expected)
def test_adding_list_of_passes_to_passmanager(self):
"""test adding a list of passes to PassManager"""
self.passmanager1.append(PassE_AP_NR_NP(argument1=1))
self.passmanager1.append(PassB_TP_RA_PA())
self.passmanager1 += [PassC_TP_RA_PA(), PassB_TP_RA_PA()]
expected = [
"run analysis pass PassE_AP_NR_NP",
"set property as 1",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassB_TP_RA_PA",
"run transformation pass PassC_TP_RA_PA",
"run transformation pass PassB_TP_RA_PA",
]
self.assertScheduler(self.circuit, self.passmanager1, expected)
def test_adding_list_of_passes_to_passmanager_with_condition(self):
"""test adding a list of passes to a PassManager that have conditions"""
self.passmanager1.append(PassE_AP_NR_NP(False))
self.passmanager1.append(
PassB_TP_RA_PA(), condition=lambda property_set: property_set["property"]
)
self.passmanager1 += PassC_TP_RA_PA()
expected = [
"run analysis pass PassE_AP_NR_NP",
"set property as False",
"run transformation pass PassA_TP_NR_NP",
"run transformation pass PassC_TP_RA_PA",
]
self.assertScheduler(self.circuit, self.passmanager1, expected)
def test_adding_pass_to_passmanager_error(self):
"""testing adding a non-pass item to PassManager"""
with self.assertRaises(TypeError):
self.passmanager1 += "not a pass"
def test_adding_list_to_passmanager_error(self):
"""testing adding a list having a non-pass item to PassManager"""
with self.assertRaises(TypeError):
self.passmanager1 += [PassB_TP_RA_PA(), "not a pass"]
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests preset pass manager API"""
import unittest
from test import combine
from ddt import ddt, data
import numpy as np
import qiskit
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit.circuit import Qubit, Gate, ControlFlowOp, ForLoopOp
from qiskit.compiler import transpile, assemble
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 (
ALAPScheduleAnalysis,
PadDynamicalDecoupling,
RemoveResetInZeroState,
)
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import (
FakeBelem,
FakeTenerife,
FakeMelbourne,
FakeJohannesburg,
FakeRueschlikon,
FakeTokyo,
FakePoughkeepsie,
FakeLagosV2,
)
from qiskit.converters import circuit_to_dag
from qiskit.circuit.library import GraphState
from qiskit.quantum_info import random_unitary
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
from qiskit.transpiler.preset_passmanagers import level0, level1, level2, level3
from qiskit.transpiler.passes import Collect2qBlocks, GatesInBasis
from qiskit.transpiler.preset_passmanagers.builtin_plugins import OptimizationPassManager
def mock_get_passmanager_stage(
stage_name,
plugin_name,
pm_config,
optimization_level=None, # pylint: disable=unused-argument
) -> PassManager:
"""Mock function for get_passmanager_stage."""
if stage_name == "translation" and plugin_name == "custom_stage_for_test":
pm = PassManager([RemoveResetInZeroState()])
return pm
elif stage_name == "scheduling" and plugin_name == "custom_stage_for_test":
dd_sequence = [XGate(), XGate()]
pm = PassManager(
[
ALAPScheduleAnalysis(pm_config.instruction_durations),
PadDynamicalDecoupling(pm_config.instruction_durations, dd_sequence),
]
)
return pm
elif stage_name == "init":
return PassManager([])
elif stage_name == "routing":
return PassManager([])
elif stage_name == "optimization":
return OptimizationPassManager().pass_manager(pm_config, optimization_level)
elif stage_name == "layout":
return PassManager([])
else:
raise Exception("Failure, unexpected stage plugin combo for test")
def emptycircuit():
"""Empty circuit"""
return QuantumCircuit()
def circuit_2532():
"""See https://github.com/Qiskit/qiskit-terra/issues/2532"""
circuit = QuantumCircuit(5)
circuit.cx(2, 4)
return circuit
@ddt
class TestPresetPassManager(QiskitTestCase):
"""Test preset passmanagers work as expected."""
@combine(level=[0, 1, 2, 3], name="level{level}")
def test_no_coupling_map_with_sabre(self, level):
"""Test that coupling_map can be None with Sabre (level={level})"""
q = QuantumRegister(2, name="q")
circuit = QuantumCircuit(q)
circuit.cz(q[0], q[1])
result = transpile(
circuit,
coupling_map=None,
layout_method="sabre",
routing_method="sabre",
optimization_level=level,
)
self.assertEqual(result, circuit)
@combine(level=[0, 1, 2, 3], name="level{level}")
def test_no_coupling_map(self, level):
"""Test that coupling_map can be None (level={level})"""
q = QuantumRegister(2, name="q")
circuit = QuantumCircuit(q)
circuit.cz(q[0], q[1])
result = transpile(circuit, basis_gates=["u1", "u2", "u3", "cx"], optimization_level=level)
self.assertIsInstance(result, QuantumCircuit)
def test_layout_3239(self, level=3):
"""Test final layout after preset level3 passmanager does not include diagonal gates
See: https://github.com/Qiskit/qiskit-terra/issues/3239
"""
qc = QuantumCircuit(5, 5)
qc.h(0)
qc.cx(range(3), range(1, 4))
qc.z(range(4))
qc.measure(range(4), range(4))
result = transpile(
qc,
basis_gates=["u1", "u2", "u3", "cx"],
layout_method="trivial",
optimization_level=level,
)
dag = circuit_to_dag(result)
op_nodes = [node.name for node in dag.topological_op_nodes()]
self.assertNotIn("u1", op_nodes) # Check if the diagonal Z-Gates (u1) were removed
@combine(level=[0, 1, 2, 3], name="level{level}")
def test_no_basis_gates(self, level):
"""Test that basis_gates can be None (level={level})"""
q = QuantumRegister(2, name="q")
circuit = QuantumCircuit(q)
circuit.h(q[0])
circuit.cz(q[0], q[1])
result = transpile(circuit, basis_gates=None, optimization_level=level)
self.assertEqual(result, circuit)
def test_level0_keeps_reset(self):
"""Test level 0 should keep the reset instructions"""
q = QuantumRegister(2, name="q")
circuit = QuantumCircuit(q)
circuit.reset(q[0])
circuit.reset(q[0])
result = transpile(circuit, basis_gates=None, optimization_level=0)
self.assertEqual(result, circuit)
@combine(level=[0, 1, 2, 3], name="level{level}")
def test_unitary_is_preserved_if_in_basis(self, level):
"""Test that a unitary is not synthesized if in the basis."""
qc = QuantumCircuit(2)
qc.unitary(random_unitary(4, seed=42), [0, 1])
qc.measure_all()
result = transpile(qc, basis_gates=["cx", "u", "unitary"], optimization_level=level)
self.assertEqual(result, qc)
@combine(level=[0, 1, 2, 3], name="level{level}")
def test_unitary_is_preserved_if_basis_is_None(self, level):
"""Test that a unitary is not synthesized if basis is None."""
qc = QuantumCircuit(2)
qc.unitary(random_unitary(4, seed=4242), [0, 1])
qc.measure_all()
result = transpile(qc, basis_gates=None, optimization_level=level)
self.assertEqual(result, qc)
@combine(level=[0, 1, 2, 3], name="level{level}")
def test_unitary_is_preserved_if_in_basis_synthesis_translation(self, level):
"""Test that a unitary is not synthesized if in the basis with synthesis translation."""
qc = QuantumCircuit(2)
qc.unitary(random_unitary(4, seed=424242), [0, 1])
qc.measure_all()
result = transpile(
qc,
basis_gates=["cx", "u", "unitary"],
optimization_level=level,
translation_method="synthesis",
)
self.assertEqual(result, qc)
@combine(level=[0, 1, 2, 3], name="level{level}")
def test_unitary_is_preserved_if_basis_is_None_synthesis_transltion(self, level):
"""Test that a unitary is not synthesized if basis is None with synthesis translation."""
qc = QuantumCircuit(2)
qc.unitary(random_unitary(4, seed=42424242), [0, 1])
qc.measure_all()
result = transpile(
qc, basis_gates=None, optimization_level=level, translation_method="synthesis"
)
self.assertEqual(result, qc)
@combine(level=[0, 1, 2, 3], name="level{level}")
def test_respect_basis(self, level):
"""Test that all levels respect basis"""
qc = QuantumCircuit(3)
qc.h(0)
qc.h(1)
qc.cp(np.pi / 8, 0, 1)
qc.cp(np.pi / 4, 0, 2)
basis_gates = ["id", "rz", "sx", "x", "cx"]
result = transpile(
qc, basis_gates=basis_gates, coupling_map=[[0, 1], [2, 1]], optimization_level=level
)
dag = circuit_to_dag(result)
circuit_ops = {node.name for node in dag.topological_op_nodes()}
self.assertEqual(circuit_ops.union(set(basis_gates)), set(basis_gates))
@combine(level=[0, 1, 2, 3], name="level{level}")
def test_alignment_constraints_called_with_by_default(self, level):
"""Test that TimeUnitConversion is not called if there is no delay in the circuit."""
q = QuantumRegister(2, name="q")
circuit = QuantumCircuit(q)
circuit.h(q[0])
circuit.cz(q[0], q[1])
with unittest.mock.patch("qiskit.transpiler.passes.TimeUnitConversion.run") as mock:
transpile(circuit, backend=FakeJohannesburg(), optimization_level=level)
mock.assert_not_called()
@combine(level=[0, 1, 2, 3], name="level{level}")
def test_alignment_constraints_called_with_delay_in_circuit(self, level):
"""Test that TimeUnitConversion is called if there is a delay in the circuit."""
q = QuantumRegister(2, name="q")
circuit = QuantumCircuit(q)
circuit.h(q[0])
circuit.cz(q[0], q[1])
circuit.delay(9.5, unit="ns")
with unittest.mock.patch(
"qiskit.transpiler.passes.TimeUnitConversion.run", return_value=circuit_to_dag(circuit)
) as mock:
transpile(circuit, backend=FakeJohannesburg(), 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 = FakeBelem()
qv_circuit = QuantumVolume(3)
gates_in_basis_true_count = 0
collect_2q_blocks_count = 0
# pylint: disable=unused-argument
def counting_callback_func(pass_, dag, time, property_set, count):
nonlocal gates_in_basis_true_count
nonlocal collect_2q_blocks_count
if isinstance(pass_, GatesInBasis) and property_set["all_gates_in_basis"]:
gates_in_basis_true_count += 1
if isinstance(pass_, Collect2qBlocks):
collect_2q_blocks_count += 1
transpile(
qv_circuit,
backend=qcomp,
optimization_level=3,
callback=counting_callback_func,
translation_method="synthesis",
)
self.assertEqual(gates_in_basis_true_count + 1, collect_2q_blocks_count)
def test_get_vf2_call_limit_deprecated(self):
"""Test that calling test_get_vf2_call_limit emits deprecation warning."""
with self.assertWarns(DeprecationWarning):
qiskit.transpiler.preset_passmanagers.common.get_vf2_call_limit(optimization_level=3)
@ddt
class TestTranspileLevels(QiskitTestCase):
"""Test transpiler on fake backend"""
@combine(
circuit=[emptycircuit, circuit_2532],
level=[0, 1, 2, 3],
backend=[
FakeTenerife(),
FakeMelbourne(),
FakeRueschlikon(),
FakeTokyo(),
FakePoughkeepsie(),
None,
],
dsc="Transpiler {circuit.__name__} on {backend} backend at level {level}",
name="{circuit.__name__}_{backend}_level{level}",
)
def test(self, circuit, level, backend):
"""All the levels with all the backends"""
result = transpile(circuit(), backend=backend, optimization_level=level, seed_transpiler=42)
self.assertIsInstance(result, QuantumCircuit)
@ddt
class TestPassesInspection(QiskitTestCase):
"""Test run passes under different conditions"""
def setUp(self):
"""Sets self.callback to set self.passes with the passes that have been executed"""
super().setUp()
self.passes = []
def callback(**kwargs):
self.passes.append(kwargs["pass_"].__class__.__name__)
self.callback = callback
@data(0, 1, 2, 3)
def test_no_coupling_map(self, level):
"""Without coupling map, no layout selection nor swapper"""
qr = QuantumRegister(3, "q")
qc = QuantumCircuit(qr)
qc.cx(qr[2], qr[1])
qc.cx(qr[2], qr[0])
_ = transpile(qc, optimization_level=level, callback=self.callback)
self.assertNotIn("SetLayout", self.passes)
self.assertNotIn("TrivialLayout", self.passes)
self.assertNotIn("ApplyLayout", self.passes)
self.assertNotIn("StochasticSwap", self.passes)
self.assertNotIn("SabreSwap", self.passes)
self.assertNotIn("CheckGateDirection", self.passes)
@data(0, 1, 2, 3)
def test_backend(self, level):
"""With backend a layout and a swapper is run"""
qr = QuantumRegister(5, "q")
qc = QuantumCircuit(qr)
qc.cx(qr[2], qr[4])
backend = FakeMelbourne()
_ = transpile(qc, backend, optimization_level=level, callback=self.callback)
self.assertIn("SetLayout", self.passes)
self.assertIn("ApplyLayout", self.passes)
self.assertIn("CheckGateDirection", self.passes)
@data(0, 1, 2, 3)
def test_5409(self, level):
"""The parameter layout_method='noise_adaptive' should be honored
See: https://github.com/Qiskit/qiskit-terra/issues/5409
"""
qr = QuantumRegister(5, "q")
qc = QuantumCircuit(qr)
qc.cx(qr[2], qr[4])
backend = FakeMelbourne()
_ = transpile(
qc,
backend,
layout_method="noise_adaptive",
optimization_level=level,
callback=self.callback,
)
self.assertIn("SetLayout", self.passes)
self.assertIn("ApplyLayout", self.passes)
self.assertIn("NoiseAdaptiveLayout", self.passes)
@data(0, 1, 2, 3)
def test_symmetric_coupling_map(self, level):
"""Symmetric coupling map does not run CheckGateDirection"""
qr = QuantumRegister(2, "q")
qc = QuantumCircuit(qr)
qc.cx(qr[0], qr[1])
coupling_map = [[0, 1], [1, 0]]
_ = transpile(
qc,
coupling_map=coupling_map,
initial_layout=[0, 1],
optimization_level=level,
callback=self.callback,
)
self.assertIn("SetLayout", self.passes)
self.assertIn("ApplyLayout", self.passes)
self.assertNotIn("CheckGateDirection", self.passes)
@data(0, 1, 2, 3)
def test_initial_layout_fully_connected_cm(self, level):
"""Honor initial_layout when coupling_map=None
See: https://github.com/Qiskit/qiskit-terra/issues/5345
"""
qr = QuantumRegister(2, "q")
qc = QuantumCircuit(qr)
qc.h(qr[0])
qc.cx(qr[0], qr[1])
transpiled = transpile(
qc, initial_layout=[0, 1], optimization_level=level, callback=self.callback
)
self.assertIn("SetLayout", self.passes)
self.assertIn("ApplyLayout", self.passes)
self.assertEqual(transpiled._layout.initial_layout, Layout.from_qubit_list([qr[0], qr[1]]))
@data(0, 1, 2, 3)
def test_partial_layout_fully_connected_cm(self, level):
"""Honor initial_layout (partially defined) when coupling_map=None
See: https://github.com/Qiskit/qiskit-terra/issues/5345
"""
qr = QuantumRegister(2, "q")
qc = QuantumCircuit(qr)
qc.h(qr[0])
qc.cx(qr[0], qr[1])
transpiled = transpile(
qc, initial_layout=[4, 2], optimization_level=level, callback=self.callback
)
self.assertIn("SetLayout", self.passes)
self.assertIn("ApplyLayout", self.passes)
ancilla = QuantumRegister(3, "ancilla")
self.assertEqual(
transpiled._layout.initial_layout,
Layout.from_qubit_list([ancilla[0], ancilla[1], qr[1], ancilla[2], qr[0]]),
)
@unittest.mock.patch.object(
level0.PassManagerStagePluginManager,
"get_passmanager_stage",
wraps=mock_get_passmanager_stage,
)
def test_backend_with_custom_stages(self, _plugin_manager_mock):
"""Test transpile() executes backend specific custom stage."""
optimization_level = 1
class TargetBackend(FakeLagosV2):
"""Fake lagos subclass with custom transpiler stages."""
def get_scheduling_stage_plugin(self):
"""Custom scheduling stage."""
return "custom_stage_for_test"
def get_translation_stage_plugin(self):
"""Custom post translation stage."""
return "custom_stage_for_test"
target = TargetBackend()
qr = QuantumRegister(2, "q")
qc = QuantumCircuit(qr)
qc.h(qr[0])
qc.cx(qr[0], qr[1])
_ = transpile(qc, target, optimization_level=optimization_level, callback=self.callback)
self.assertIn("ALAPScheduleAnalysis", self.passes)
self.assertIn("PadDynamicalDecoupling", self.passes)
self.assertIn("RemoveResetInZeroState", self.passes)
def test_level1_runs_vf2post_layout_when_routing_required(self):
"""Test that if we run routing as part of sabre layout VF2PostLayout runs."""
target = FakeLagosV2()
qc = QuantumCircuit(5)
qc.h(0)
qc.cy(0, 1)
qc.cy(0, 2)
qc.cy(0, 3)
qc.cy(0, 4)
qc.measure_all()
_ = transpile(qc, target, optimization_level=1, callback=self.callback)
# Expected call path for layout and routing is:
# 1. TrivialLayout (no perfect match)
# 2. VF2Layout (no perfect match)
# 3. SabreLayout (heuristic layout and also runs routing)
# 4. VF2PostLayout (applies a better layout)
self.assertIn("TrivialLayout", self.passes)
self.assertIn("VF2Layout", self.passes)
self.assertIn("SabreLayout", self.passes)
self.assertIn("VF2PostLayout", self.passes)
# Assert we don't run standalone sabre swap
self.assertNotIn("SabreSwap", self.passes)
def test_level1_runs_vf2post_layout_when_routing_method_set_and_required(self):
"""Test that if we run routing as part of sabre layout VF2PostLayout runs."""
target = FakeLagosV2()
qc = QuantumCircuit(5)
qc.h(0)
qc.cy(0, 1)
qc.cy(0, 2)
qc.cy(0, 3)
qc.cy(0, 4)
qc.measure_all()
_ = transpile(
qc, target, optimization_level=1, routing_method="stochastic", callback=self.callback
)
# Expected call path for layout and routing is:
# 1. TrivialLayout (no perfect match)
# 2. VF2Layout (no perfect match)
# 3. SabreLayout (heuristic layout and also runs routing)
# 4. VF2PostLayout (applies a better layout)
self.assertIn("TrivialLayout", self.passes)
self.assertIn("VF2Layout", self.passes)
self.assertIn("SabreLayout", self.passes)
self.assertIn("VF2PostLayout", self.passes)
self.assertIn("StochasticSwap", self.passes)
def test_level1_not_runs_vf2post_layout_when_layout_method_set(self):
"""Test that if we don't run VF2PostLayout with custom layout_method."""
target = FakeLagosV2()
qc = QuantumCircuit(5)
qc.h(0)
qc.cy(0, 1)
qc.cy(0, 2)
qc.cy(0, 3)
qc.cy(0, 4)
qc.measure_all()
_ = transpile(
qc, target, optimization_level=1, layout_method="dense", callback=self.callback
)
self.assertNotIn("TrivialLayout", self.passes)
self.assertNotIn("VF2Layout", self.passes)
self.assertNotIn("SabreLayout", self.passes)
self.assertNotIn("VF2PostLayout", self.passes)
self.assertIn("DenseLayout", self.passes)
self.assertIn("SabreSwap", self.passes)
def test_level1_not_run_vf2post_layout_when_trivial_is_perfect(self):
"""Test that if we find a trivial perfect layout we don't run vf2post."""
target = FakeLagosV2()
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
_ = transpile(qc, target, optimization_level=1, callback=self.callback)
self.assertIn("TrivialLayout", self.passes)
self.assertNotIn("VF2Layout", self.passes)
self.assertNotIn("SabreLayout", self.passes)
self.assertNotIn("VF2PostLayout", self.passes)
# Assert we don't run standalone sabre swap
self.assertNotIn("SabreSwap", self.passes)
def test_level1_not_run_vf2post_layout_when_vf2layout_is_perfect(self):
"""Test that if we find a vf2 perfect layout we don't run vf2post."""
target = FakeLagosV2()
qc = QuantumCircuit(4)
qc.h(0)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
qc.measure_all()
_ = transpile(qc, target, optimization_level=1, callback=self.callback)
self.assertIn("TrivialLayout", self.passes)
self.assertIn("VF2Layout", self.passes)
self.assertNotIn("SabreLayout", self.passes)
self.assertNotIn("VF2PostLayout", self.passes)
# Assert we don't run standalone sabre swap
self.assertNotIn("SabreSwap", self.passes)
def test_level1_runs_vf2post_layout_when_routing_required_control_flow(self):
"""Test that if we run routing as part of sabre layout VF2PostLayout runs."""
target = FakeLagosV2()
_target = target.target
target._target.add_instruction(ForLoopOp, name="for_loop")
qc = QuantumCircuit(5)
qc.h(0)
qc.cy(0, 1)
qc.cy(0, 2)
qc.cy(0, 3)
qc.cy(0, 4)
with qc.for_loop((1,)):
qc.cx(0, 1)
qc.measure_all()
_ = transpile(qc, target, optimization_level=1, callback=self.callback)
# Expected call path for layout and routing is:
# 1. TrivialLayout (no perfect match)
# 2. VF2Layout (no perfect match)
# 3. SabreLayout (heuristic layout)
# 4. VF2PostLayout (applies a better layout)
self.assertIn("TrivialLayout", self.passes)
self.assertIn("VF2Layout", self.passes)
self.assertIn("SabreLayout", self.passes)
self.assertIn("VF2PostLayout", self.passes)
def test_level1_not_runs_vf2post_layout_when_layout_method_set_control_flow(self):
"""Test that if we don't run VF2PostLayout with custom layout_method."""
target = FakeLagosV2()
_target = target.target
target._target.add_instruction(ForLoopOp, name="for_loop")
qc = QuantumCircuit(5)
qc.h(0)
qc.cy(0, 1)
qc.cy(0, 2)
qc.cy(0, 3)
qc.cy(0, 4)
with qc.for_loop((1,)):
qc.cx(0, 1)
qc.measure_all()
_ = transpile(
qc, target, optimization_level=1, layout_method="dense", callback=self.callback
)
self.assertNotIn("TrivialLayout", self.passes)
self.assertNotIn("VF2Layout", self.passes)
self.assertNotIn("SabreLayout", self.passes)
self.assertNotIn("VF2PostLayout", self.passes)
self.assertIn("DenseLayout", self.passes)
self.assertIn("SabreSwap", self.passes)
def test_level1_not_run_vf2post_layout_when_trivial_is_perfect_control_flow(self):
"""Test that if we find a trivial perfect layout we don't run vf2post."""
target = FakeLagosV2()
_target = target.target
target._target.add_instruction(ForLoopOp, name="for_loop")
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
with qc.for_loop((1,)):
qc.cx(0, 1)
qc.measure_all()
_ = transpile(qc, target, optimization_level=1, callback=self.callback)
self.assertIn("TrivialLayout", self.passes)
self.assertNotIn("VF2Layout", self.passes)
self.assertNotIn("SabreLayout", self.passes)
self.assertNotIn("SabreSwap", self.passes)
self.assertNotIn("VF2PostLayout", self.passes)
def test_level1_not_run_vf2post_layout_when_vf2layout_is_perfect_control_flow(self):
"""Test that if we find a vf2 perfect layout we don't run vf2post."""
target = FakeLagosV2()
_target = target.target
target._target.add_instruction(ForLoopOp, name="for_loop")
qc = QuantumCircuit(4)
qc.h(0)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
with qc.for_loop((1,)):
qc.cx(0, 1)
qc.measure_all()
_ = transpile(qc, target, optimization_level=1, callback=self.callback)
self.assertIn("TrivialLayout", self.passes)
self.assertIn("VF2Layout", self.passes)
self.assertNotIn("SabreLayout", self.passes)
self.assertNotIn("VF2PostLayout", self.passes)
self.assertNotIn("SabreSwap", self.passes)
@ddt
class TestInitialLayouts(QiskitTestCase):
"""Test transpiling with different layouts"""
@data(0, 1, 2, 3)
def test_layout_1711(self, level):
"""Test that a user-given initial layout is respected,
in the qobj.
See: https://github.com/Qiskit/qiskit-terra/issues/1711
"""
# build a circuit which works as-is on the coupling map, using the initial layout
qr = QuantumRegister(3, "q")
cr = ClassicalRegister(3)
ancilla = QuantumRegister(13, "ancilla")
qc = QuantumCircuit(qr, cr)
qc.cx(qr[2], qr[1])
qc.cx(qr[2], qr[0])
initial_layout = {0: qr[1], 2: qr[0], 15: qr[2]}
final_layout = {
0: qr[1],
1: ancilla[0],
2: qr[0],
3: ancilla[1],
4: ancilla[2],
5: ancilla[3],
6: ancilla[4],
7: ancilla[5],
8: ancilla[6],
9: ancilla[7],
10: ancilla[8],
11: ancilla[9],
12: ancilla[10],
13: ancilla[11],
14: ancilla[12],
15: qr[2],
}
backend = FakeRueschlikon()
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(operation.qubits, backend.configuration().coupling_map)
self.assertIn(operation.qubits, [[15, 0], [15, 2]])
@data(0, 1, 2, 3)
def test_layout_2532(self, level):
"""Test that a user-given initial layout is respected,
in the transpiled circuit.
See: https://github.com/Qiskit/qiskit-terra/issues/2532
"""
# build a circuit which works as-is on the coupling map, using the initial layout
qr = QuantumRegister(5, "q")
cr = ClassicalRegister(2)
ancilla = QuantumRegister(9, "ancilla")
qc = QuantumCircuit(qr, cr)
qc.cx(qr[2], qr[4])
initial_layout = {
qr[2]: 11,
qr[4]: 3, # map to [11, 3] connection
qr[0]: 1,
qr[1]: 5,
qr[3]: 9,
}
final_layout = {
0: ancilla[0],
1: qr[0],
2: ancilla[1],
3: qr[4],
4: ancilla[2],
5: qr[1],
6: ancilla[3],
7: ancilla[4],
8: ancilla[5],
9: qr[3],
10: ancilla[6],
11: qr[2],
12: ancilla[7],
13: ancilla[8],
}
backend = FakeMelbourne()
qc_b = transpile(qc, backend, initial_layout=initial_layout, optimization_level=level)
self.assertEqual(qc_b._layout.initial_layout._p2v, final_layout)
output_qr = qc_b.qregs[0]
for instruction in qc_b:
if instruction.operation.name == "cx":
for qubit in instruction.qubits:
self.assertIn(qubit, [output_qr[11], output_qr[3]])
@data(0, 1, 2, 3)
def test_layout_2503(self, level):
"""Test that a user-given initial layout is respected,
even if cnots are not in the coupling map.
See: https://github.com/Qiskit/qiskit-terra/issues/2503
"""
# build a circuit which works as-is on the coupling map, using the initial layout
qr = QuantumRegister(3, "q")
cr = ClassicalRegister(2)
ancilla = QuantumRegister(17, "ancilla")
qc = QuantumCircuit(qr, cr)
qc.append(U3Gate(0.1, 0.2, 0.3), [qr[0]])
qc.append(U2Gate(0.4, 0.5), [qr[2]])
qc.barrier()
qc.cx(qr[0], qr[2])
initial_layout = [6, 7, 12]
final_layout = {
0: ancilla[0],
1: ancilla[1],
2: ancilla[2],
3: ancilla[3],
4: ancilla[4],
5: ancilla[5],
6: qr[0],
7: qr[1],
8: ancilla[6],
9: ancilla[7],
10: ancilla[8],
11: ancilla[9],
12: qr[2],
13: ancilla[10],
14: ancilla[11],
15: ancilla[12],
16: ancilla[13],
17: ancilla[14],
18: ancilla[15],
19: ancilla[16],
}
backend = FakePoughkeepsie()
qc_b = transpile(qc, backend, initial_layout=initial_layout, optimization_level=level)
self.assertEqual(qc_b._layout.initial_layout._p2v, final_layout)
output_qr = qc_b.qregs[0]
self.assertIsInstance(qc_b[0].operation, U3Gate)
self.assertEqual(qc_b[0].qubits[0], output_qr[6])
self.assertIsInstance(qc_b[1].operation, U2Gate)
self.assertEqual(qc_b[1].qubits[0], output_qr[12])
@ddt
class TestFinalLayouts(QiskitTestCase):
"""Test final layouts after preset transpilation"""
@data(0, 1, 2, 3)
def test_layout_tokyo_2845(self, level):
"""Test that final layout in tokyo #2845
See: https://github.com/Qiskit/qiskit-terra/issues/2845
"""
qr1 = QuantumRegister(3, "qr1")
qr2 = QuantumRegister(2, "qr2")
qc = QuantumCircuit(qr1, qr2)
qc.cx(qr1[0], qr1[1])
qc.cx(qr1[1], qr1[2])
qc.cx(qr1[2], qr2[0])
qc.cx(qr2[0], qr2[1])
trivial_layout = {
0: Qubit(QuantumRegister(3, "qr1"), 0),
1: Qubit(QuantumRegister(3, "qr1"), 1),
2: Qubit(QuantumRegister(3, "qr1"), 2),
3: Qubit(QuantumRegister(2, "qr2"), 0),
4: Qubit(QuantumRegister(2, "qr2"), 1),
5: Qubit(QuantumRegister(15, "ancilla"), 0),
6: Qubit(QuantumRegister(15, "ancilla"), 1),
7: Qubit(QuantumRegister(15, "ancilla"), 2),
8: Qubit(QuantumRegister(15, "ancilla"), 3),
9: Qubit(QuantumRegister(15, "ancilla"), 4),
10: Qubit(QuantumRegister(15, "ancilla"), 5),
11: Qubit(QuantumRegister(15, "ancilla"), 6),
12: Qubit(QuantumRegister(15, "ancilla"), 7),
13: Qubit(QuantumRegister(15, "ancilla"), 8),
14: Qubit(QuantumRegister(15, "ancilla"), 9),
15: Qubit(QuantumRegister(15, "ancilla"), 10),
16: Qubit(QuantumRegister(15, "ancilla"), 11),
17: Qubit(QuantumRegister(15, "ancilla"), 12),
18: Qubit(QuantumRegister(15, "ancilla"), 13),
19: Qubit(QuantumRegister(15, "ancilla"), 14),
}
vf2_layout = {
0: Qubit(QuantumRegister(15, "ancilla"), 0),
1: Qubit(QuantumRegister(15, "ancilla"), 1),
2: Qubit(QuantumRegister(15, "ancilla"), 2),
3: Qubit(QuantumRegister(15, "ancilla"), 3),
4: Qubit(QuantumRegister(15, "ancilla"), 4),
5: Qubit(QuantumRegister(15, "ancilla"), 5),
6: Qubit(QuantumRegister(3, "qr1"), 1),
7: Qubit(QuantumRegister(15, "ancilla"), 6),
8: Qubit(QuantumRegister(15, "ancilla"), 7),
9: Qubit(QuantumRegister(15, "ancilla"), 8),
10: Qubit(QuantumRegister(3, "qr1"), 0),
11: Qubit(QuantumRegister(3, "qr1"), 2),
12: Qubit(QuantumRegister(15, "ancilla"), 9),
13: Qubit(QuantumRegister(15, "ancilla"), 10),
14: Qubit(QuantumRegister(15, "ancilla"), 11),
15: Qubit(QuantumRegister(15, "ancilla"), 12),
16: Qubit(QuantumRegister(2, "qr2"), 0),
17: Qubit(QuantumRegister(2, "qr2"), 1),
18: Qubit(QuantumRegister(15, "ancilla"), 13),
19: Qubit(QuantumRegister(15, "ancilla"), 14),
}
# Trivial layout
expected_layout_level0 = trivial_layout
# Dense layout
expected_layout_level1 = vf2_layout
# CSP layout
expected_layout_level2 = vf2_layout
expected_layout_level3 = vf2_layout
expected_layouts = [
expected_layout_level0,
expected_layout_level1,
expected_layout_level2,
expected_layout_level3,
]
backend = FakeTokyo()
result = transpile(qc, backend, optimization_level=level, seed_transpiler=42)
self.assertEqual(result._layout.initial_layout._p2v, expected_layouts[level])
@data(0, 1, 2, 3)
def test_layout_tokyo_fully_connected_cx(self, level):
"""Test that final layout in tokyo in a fully connected circuit"""
qr = QuantumRegister(5, "qr")
qc = QuantumCircuit(qr)
for qubit_target in qr:
for qubit_control in qr:
if qubit_control != qubit_target:
qc.cx(qubit_control, qubit_target)
ancilla = QuantumRegister(15, "ancilla")
trivial_layout = {
0: qr[0],
1: qr[1],
2: qr[2],
3: qr[3],
4: qr[4],
5: ancilla[0],
6: ancilla[1],
7: ancilla[2],
8: ancilla[3],
9: ancilla[4],
10: ancilla[5],
11: ancilla[6],
12: ancilla[7],
13: ancilla[8],
14: ancilla[9],
15: ancilla[10],
16: ancilla[11],
17: ancilla[12],
18: ancilla[13],
19: ancilla[14],
}
sabre_layout = {
0: ancilla[0],
1: qr[4],
2: ancilla[1],
3: ancilla[2],
4: ancilla[3],
5: qr[1],
6: qr[0],
7: ancilla[4],
8: ancilla[5],
9: ancilla[6],
10: qr[2],
11: qr[3],
12: ancilla[7],
13: ancilla[8],
14: ancilla[9],
15: ancilla[10],
16: ancilla[11],
17: ancilla[12],
18: ancilla[13],
19: ancilla[14],
}
sabre_layout_lvl_2 = {
0: ancilla[0],
1: qr[4],
2: ancilla[1],
3: ancilla[2],
4: ancilla[3],
5: qr[1],
6: qr[0],
7: ancilla[4],
8: ancilla[5],
9: ancilla[6],
10: qr[2],
11: qr[3],
12: ancilla[7],
13: ancilla[8],
14: ancilla[9],
15: ancilla[10],
16: ancilla[11],
17: ancilla[12],
18: ancilla[13],
19: ancilla[14],
}
sabre_layout_lvl_3 = {
0: ancilla[0],
1: qr[4],
2: ancilla[1],
3: ancilla[2],
4: ancilla[3],
5: qr[1],
6: qr[0],
7: ancilla[4],
8: ancilla[5],
9: ancilla[6],
10: qr[2],
11: qr[3],
12: ancilla[7],
13: ancilla[8],
14: ancilla[9],
15: ancilla[10],
16: ancilla[11],
17: ancilla[12],
18: ancilla[13],
19: ancilla[14],
}
expected_layout_level0 = trivial_layout
expected_layout_level1 = sabre_layout
expected_layout_level2 = sabre_layout_lvl_2
expected_layout_level3 = sabre_layout_lvl_3
expected_layouts = [
expected_layout_level0,
expected_layout_level1,
expected_layout_level2,
expected_layout_level3,
]
backend = FakeTokyo()
result = transpile(qc, backend, optimization_level=level, seed_transpiler=42)
self.assertEqual(result._layout.initial_layout._p2v, expected_layouts[level])
@data(0, 1, 2, 3)
def test_all_levels_use_trivial_if_perfect(self, level):
"""Test that we always use trivial if it's a perfect match.
See: https://github.com/Qiskit/qiskit-terra/issues/5694 for more
details
"""
backend = FakeTokyo()
config = backend.configuration()
rows = [x[0] for x in config.coupling_map]
cols = [x[1] for x in config.coupling_map]
adjacency_matrix = np.zeros((20, 20))
adjacency_matrix[rows, cols] = 1
qc = GraphState(adjacency_matrix)
qc.measure_all()
expected = {
0: Qubit(QuantumRegister(20, "q"), 0),
1: Qubit(QuantumRegister(20, "q"), 1),
2: Qubit(QuantumRegister(20, "q"), 2),
3: Qubit(QuantumRegister(20, "q"), 3),
4: Qubit(QuantumRegister(20, "q"), 4),
5: Qubit(QuantumRegister(20, "q"), 5),
6: Qubit(QuantumRegister(20, "q"), 6),
7: Qubit(QuantumRegister(20, "q"), 7),
8: Qubit(QuantumRegister(20, "q"), 8),
9: Qubit(QuantumRegister(20, "q"), 9),
10: Qubit(QuantumRegister(20, "q"), 10),
11: Qubit(QuantumRegister(20, "q"), 11),
12: Qubit(QuantumRegister(20, "q"), 12),
13: Qubit(QuantumRegister(20, "q"), 13),
14: Qubit(QuantumRegister(20, "q"), 14),
15: Qubit(QuantumRegister(20, "q"), 15),
16: Qubit(QuantumRegister(20, "q"), 16),
17: Qubit(QuantumRegister(20, "q"), 17),
18: Qubit(QuantumRegister(20, "q"), 18),
19: Qubit(QuantumRegister(20, "q"), 19),
}
trans_qc = transpile(qc, backend, optimization_level=level, seed_transpiler=42)
self.assertEqual(trans_qc._layout.initial_layout._p2v, expected)
@data(0)
def test_trivial_layout(self, level):
"""Test that trivial layout is preferred in level 0
See: https://github.com/Qiskit/qiskit-terra/pull/3657#pullrequestreview-342012465
"""
qr = QuantumRegister(10, "qr")
qc = QuantumCircuit(qr)
qc.cx(qr[0], qr[1])
qc.cx(qr[1], qr[2])
qc.cx(qr[2], qr[6])
qc.cx(qr[3], qr[8])
qc.cx(qr[4], qr[9])
qc.cx(qr[9], qr[8])
qc.cx(qr[8], qr[7])
qc.cx(qr[7], qr[6])
qc.cx(qr[6], qr[5])
qc.cx(qr[5], qr[0])
ancilla = QuantumRegister(10, "ancilla")
trivial_layout = {
0: qr[0],
1: qr[1],
2: qr[2],
3: qr[3],
4: qr[4],
5: qr[5],
6: qr[6],
7: qr[7],
8: qr[8],
9: qr[9],
10: ancilla[0],
11: ancilla[1],
12: ancilla[2],
13: ancilla[3],
14: ancilla[4],
15: ancilla[5],
16: ancilla[6],
17: ancilla[7],
18: ancilla[8],
19: ancilla[9],
}
expected_layouts = [trivial_layout, trivial_layout]
backend = FakeTokyo()
result = transpile(qc, backend, optimization_level=level, seed_transpiler=42)
self.assertEqual(result._layout.initial_layout._p2v, expected_layouts[level])
@data(0, 1, 2, 3)
def test_initial_layout(self, level):
"""When a user provides a layout (initial_layout), it should be used."""
qr = QuantumRegister(10, "qr")
qc = QuantumCircuit(qr)
qc.cx(qr[0], qr[1])
qc.cx(qr[1], qr[2])
qc.cx(qr[2], qr[3])
qc.cx(qr[3], qr[9])
qc.cx(qr[4], qr[9])
qc.cx(qr[9], qr[8])
qc.cx(qr[8], qr[7])
qc.cx(qr[7], qr[6])
qc.cx(qr[6], qr[5])
qc.cx(qr[5], qr[0])
initial_layout = {
0: qr[0],
2: qr[1],
4: qr[2],
6: qr[3],
8: qr[4],
10: qr[5],
12: qr[6],
14: qr[7],
16: qr[8],
18: qr[9],
}
backend = FakeTokyo()
result = transpile(
qc, backend, optimization_level=level, initial_layout=initial_layout, seed_transpiler=42
)
for physical, virtual in initial_layout.items():
self.assertEqual(result._layout.initial_layout._p2v[physical], virtual)
@ddt
class TestTranspileLevelsSwap(QiskitTestCase):
"""Test if swap is in the basis, do not unroll
See https://github.com/Qiskit/qiskit-terra/pull/3963
The circuit in combine should require a swap and that swap should exit at the end
for the transpilation"""
@combine(
circuit=[circuit_2532],
level=[0, 1, 2, 3],
dsc="circuit: {circuit.__name__}, level: {level}",
name="{circuit.__name__}_level{level}",
)
def test_1(self, circuit, level):
"""Simple coupling map (linear 5 qubits)."""
basis = ["u1", "u2", "cx", "swap"]
coupling_map = CouplingMap([(0, 1), (1, 2), (2, 3), (3, 4)])
result = transpile(
circuit(),
optimization_level=level,
basis_gates=basis,
coupling_map=coupling_map,
seed_transpiler=42,
initial_layout=[0, 1, 2, 3, 4],
)
self.assertIsInstance(result, QuantumCircuit)
resulting_basis = {node.name for node in circuit_to_dag(result).op_nodes()}
self.assertIn("swap", resulting_basis)
# Skipping optimization level 3 because the swap gates get absorbed into
# a unitary block as part of the KAK decompostion optimization passes and
# optimized away.
@combine(
level=[0, 1, 2],
dsc="If swap in basis, do not decompose it. level: {level}",
name="level{level}",
)
def test_2(self, level):
"""Simple coupling map (linear 5 qubits).
The circuit requires a swap and that swap should exit at the end
for the transpilation"""
basis = ["u1", "u2", "cx", "swap"]
circuit = QuantumCircuit(5)
circuit.cx(0, 4)
circuit.cx(1, 4)
circuit.cx(2, 4)
circuit.cx(3, 4)
coupling_map = CouplingMap([(0, 1), (1, 2), (2, 3), (3, 4)])
result = transpile(
circuit,
optimization_level=level,
basis_gates=basis,
coupling_map=coupling_map,
seed_transpiler=421234242,
)
self.assertIsInstance(result, QuantumCircuit)
resulting_basis = {node.name for node in circuit_to_dag(result).op_nodes()}
self.assertIn("swap", resulting_basis)
@ddt
class TestOptimizationWithCondition(QiskitTestCase):
"""Test optimization levels with condition in the circuit"""
@data(0, 1, 2, 3)
def test_optimization_condition(self, level):
"""Test optimization levels with condition in the circuit"""
qr = QuantumRegister(2)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
qc.cx(0, 1).c_if(cr, 1)
backend = FakeJohannesburg()
circ = transpile(qc, backend, optimization_level=level)
self.assertIsInstance(circ, QuantumCircuit)
def test_input_dag_copy(self):
"""Test substitute_node_with_dag input_dag copy on condition"""
qc = QuantumCircuit(2, 1)
qc.cx(0, 1).c_if(qc.cregs[0], 1)
qc.cx(1, 0)
circ = transpile(qc, basis_gates=["u3", "cz"])
self.assertIsInstance(circ, QuantumCircuit)
@ddt
class TestOptimizationOnSize(QiskitTestCase):
"""Test the optimization levels for optimization based on
both size and depth of the circuit.
See https://github.com/Qiskit/qiskit-terra/pull/7542
"""
@data(2, 3)
def test_size_optimization(self, level):
"""Test the levels for optimization based on size of circuit"""
qc = QuantumCircuit(8)
qc.cx(1, 2)
qc.cx(2, 3)
qc.cx(5, 4)
qc.cx(6, 5)
qc.cx(4, 5)
qc.cx(3, 4)
qc.cx(5, 6)
qc.cx(5, 4)
qc.cx(3, 4)
qc.cx(2, 3)
qc.cx(1, 2)
qc.cx(6, 7)
qc.cx(6, 5)
qc.cx(5, 4)
qc.cx(7, 6)
qc.cx(6, 7)
circ = transpile(qc, optimization_level=level).decompose()
circ_data = circ.data
free_qubits = {0, 1, 2, 3}
# ensure no gates are using qubits - [0,1,2,3]
for gate in circ_data:
indices = {circ.find_bit(qubit).index for qubit in gate.qubits}
common = indices.intersection(free_qubits)
for common_qubit in common:
self.assertTrue(common_qubit not in free_qubits)
self.assertLess(circ.size(), qc.size())
self.assertLessEqual(circ.depth(), qc.depth())
@ddt
class TestGeenratePresetPassManagers(QiskitTestCase):
"""Test generate_preset_pass_manager function."""
@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 = FakeTokyo()
pm = generate_preset_pass_manager(optimization_level, target)
self.assertIsInstance(pm, PassManager)
@data(0, 1, 2, 3)
def test_with_no_backend(self, optimization_level):
"""Test a passmanager is constructed with no backend and optimization level."""
target = FakeLagosV2()
pm = generate_preset_pass_manager(
optimization_level,
coupling_map=target.coupling_map,
basis_gates=target.operation_names,
inst_map=target.instruction_schedule_map,
instruction_durations=target.instruction_durations,
timing_constraints=target.target.timing_constraints(),
target=target.target,
)
self.assertIsInstance(pm, PassManager)
@data(0, 1, 2, 3)
def test_with_no_backend_only_target(self, optimization_level):
"""Test a passmanager is constructed with a manual target and optimization level."""
target = FakeLagosV2()
pm = generate_preset_pass_manager(optimization_level, target=target.target)
self.assertIsInstance(pm, PassManager)
def test_invalid_optimization_level(self):
"""Assert we fail with an invalid optimization_level."""
with self.assertRaises(ValueError):
generate_preset_pass_manager(42)
@unittest.mock.patch.object(
level2.PassManagerStagePluginManager,
"get_passmanager_stage",
wraps=mock_get_passmanager_stage,
)
def test_backend_with_custom_stages_level2(self, _plugin_manager_mock):
"""Test generated preset pass manager includes backend specific custom stages."""
optimization_level = 2
class TargetBackend(FakeLagosV2):
"""Fake lagos subclass with custom transpiler stages."""
def get_scheduling_stage_plugin(self):
"""Custom scheduling stage."""
return "custom_stage_for_test"
def get_translation_stage_plugin(self):
"""Custom post translation stage."""
return "custom_stage_for_test"
target = TargetBackend()
pm = generate_preset_pass_manager(optimization_level, backend=target)
self.assertIsInstance(pm, PassManager)
pass_list = [y.__class__.__name__ for x in pm.passes() for y in x["passes"]]
self.assertIn("PadDynamicalDecoupling", pass_list)
self.assertIn("ALAPScheduleAnalysis", pass_list)
post_translation_pass_list = [
y.__class__.__name__
for x in pm.translation.passes() # pylint: disable=no-member
for y in x["passes"]
]
self.assertIn("RemoveResetInZeroState", post_translation_pass_list)
@unittest.mock.patch.object(
level1.PassManagerStagePluginManager,
"get_passmanager_stage",
wraps=mock_get_passmanager_stage,
)
def test_backend_with_custom_stages_level1(self, _plugin_manager_mock):
"""Test generated preset pass manager includes backend specific custom stages."""
optimization_level = 1
class TargetBackend(FakeLagosV2):
"""Fake lagos subclass with custom transpiler stages."""
def get_scheduling_stage_plugin(self):
"""Custom scheduling stage."""
return "custom_stage_for_test"
def get_translation_stage_plugin(self):
"""Custom post translation stage."""
return "custom_stage_for_test"
target = TargetBackend()
pm = generate_preset_pass_manager(optimization_level, backend=target)
self.assertIsInstance(pm, PassManager)
pass_list = [y.__class__.__name__ for x in pm.passes() for y in x["passes"]]
self.assertIn("PadDynamicalDecoupling", pass_list)
self.assertIn("ALAPScheduleAnalysis", pass_list)
post_translation_pass_list = [
y.__class__.__name__
for x in pm.translation.passes() # pylint: disable=no-member
for y in x["passes"]
]
self.assertIn("RemoveResetInZeroState", post_translation_pass_list)
@unittest.mock.patch.object(
level3.PassManagerStagePluginManager,
"get_passmanager_stage",
wraps=mock_get_passmanager_stage,
)
def test_backend_with_custom_stages_level3(self, _plugin_manager_mock):
"""Test generated preset pass manager includes backend specific custom stages."""
optimization_level = 3
class TargetBackend(FakeLagosV2):
"""Fake lagos subclass with custom transpiler stages."""
def get_scheduling_stage_plugin(self):
"""Custom scheduling stage."""
return "custom_stage_for_test"
def get_translation_stage_plugin(self):
"""Custom post translation stage."""
return "custom_stage_for_test"
target = TargetBackend()
pm = generate_preset_pass_manager(optimization_level, backend=target)
self.assertIsInstance(pm, PassManager)
pass_list = [y.__class__.__name__ for x in pm.passes() for y in x["passes"]]
self.assertIn("PadDynamicalDecoupling", pass_list)
self.assertIn("ALAPScheduleAnalysis", pass_list)
post_translation_pass_list = [
y.__class__.__name__
for x in pm.translation.passes() # pylint: disable=no-member
for y in x["passes"]
]
self.assertIn("RemoveResetInZeroState", post_translation_pass_list)
@unittest.mock.patch.object(
level0.PassManagerStagePluginManager,
"get_passmanager_stage",
wraps=mock_get_passmanager_stage,
)
def test_backend_with_custom_stages_level0(self, _plugin_manager_mock):
"""Test generated preset pass manager includes backend specific custom stages."""
optimization_level = 0
class TargetBackend(FakeLagosV2):
"""Fake lagos subclass with custom transpiler stages."""
def get_scheduling_stage_plugin(self):
"""Custom scheduling stage."""
return "custom_stage_for_test"
def get_translation_stage_plugin(self):
"""Custom post translation stage."""
return "custom_stage_for_test"
target = TargetBackend()
pm = generate_preset_pass_manager(optimization_level, backend=target)
self.assertIsInstance(pm, PassManager)
pass_list = [y.__class__.__name__ for x in pm.passes() for y in x["passes"]]
self.assertIn("PadDynamicalDecoupling", pass_list)
self.assertIn("ALAPScheduleAnalysis", pass_list)
post_translation_pass_list = [
y.__class__.__name__
for x in pm.translation.passes() # pylint: disable=no-member
for y in x["passes"]
]
self.assertIn("RemoveResetInZeroState", post_translation_pass_list)
@ddt
class TestIntegrationControlFlow(QiskitTestCase):
"""Integration tests for control-flow circuits through the preset pass managers."""
@data(0, 1, 2, 3)
def test_default_compilation(self, optimization_level):
"""Test that a simple circuit with each type of control-flow passes a full transpilation
pipeline with the defaults."""
class CustomCX(Gate):
"""Custom CX"""
def __init__(self):
super().__init__("custom_cx", 2, [])
def _define(self):
self._definition = QuantumCircuit(2)
self._definition.cx(0, 1)
circuit = QuantumCircuit(6, 1)
circuit.h(0)
circuit.measure(0, 0)
circuit.cx(0, 1)
circuit.cz(0, 2)
circuit.append(CustomCX(), [1, 2], [])
with circuit.for_loop((1,)):
circuit.cx(0, 1)
circuit.cz(0, 2)
circuit.append(CustomCX(), [1, 2], [])
with circuit.if_test((circuit.clbits[0], True)) as else_:
circuit.cx(0, 1)
circuit.cz(0, 2)
circuit.append(CustomCX(), [1, 2], [])
with else_:
circuit.cx(3, 4)
circuit.cz(3, 5)
circuit.append(CustomCX(), [4, 5], [])
with circuit.while_loop((circuit.clbits[0], True)):
circuit.cx(3, 4)
circuit.cz(3, 5)
circuit.append(CustomCX(), [4, 5], [])
coupling_map = CouplingMap.from_line(6)
transpiled = transpile(
circuit,
basis_gates=["sx", "rz", "cx", "if_else", "for_loop", "while_loop"],
coupling_map=coupling_map,
optimization_level=optimization_level,
seed_transpiler=2022_10_04,
)
# Tests of the complete validity of a circuit are mostly done at the indiviual pass level;
# here we're just checking that various passes do appear to have run.
self.assertIsInstance(transpiled, QuantumCircuit)
# Assert layout ran.
self.assertIsNot(getattr(transpiled, "_layout", None), None)
def _visit_block(circuit, stack=None):
"""Assert that every block contains at least one swap to imply that routing has run."""
if stack is None:
# List of (instruction_index, block_index).
stack = ()
seen_cx = 0
for i, instruction in enumerate(circuit):
if isinstance(instruction.operation, ControlFlowOp):
for j, block in enumerate(instruction.operation.blocks):
_visit_block(block, stack + ((i, j),))
elif isinstance(instruction.operation, CXGate):
seen_cx += 1
# Assert unrolling ran.
self.assertNotIsInstance(instruction.operation, CustomCX)
# Assert translation ran.
self.assertNotIsInstance(instruction.operation, CZGate)
# There are three "natural" swaps in each block (one for each 2q operation), so if
# routing ran, we should see more than that.
self.assertGreater(seen_cx, 3, msg=f"no swaps in block at indices: {stack}")
# Assert routing ran.
_visit_block(transpiled)
@data(0, 1, 2, 3)
def test_allow_overriding_defaults(self, optimization_level):
"""Test that the method options can be overridden."""
circuit = QuantumCircuit(3, 1)
circuit.h(0)
circuit.measure(0, 0)
with circuit.for_loop((1,)):
circuit.h(0)
circuit.cx(0, 1)
circuit.cz(0, 2)
circuit.cx(1, 2)
coupling_map = CouplingMap.from_line(3)
calls = set()
def callback(pass_, **_):
calls.add(pass_.name())
transpiled = transpile(
circuit,
basis_gates=["u3", "cx", "if_else", "for_loop", "while_loop"],
layout_method="trivial",
translation_method="unroller",
coupling_map=coupling_map,
optimization_level=optimization_level,
seed_transpiler=2022_10_04,
callback=callback,
)
self.assertIsInstance(transpiled, QuantumCircuit)
self.assertIsNot(getattr(transpiled, "_layout", None), None)
self.assertIn("TrivialLayout", calls)
self.assertIn("Unroller", calls)
self.assertNotIn("DenseLayout", calls)
self.assertNotIn("SabreLayout", calls)
self.assertNotIn("BasisTranslator", calls)
@data(0, 1, 2, 3)
def test_invalid_methods_raise_on_control_flow(self, optimization_level):
"""Test that trying to use an invalid method with control flow fails."""
qc = QuantumCircuit(1)
with qc.for_loop((1,)):
qc.x(0)
with self.assertRaisesRegex(TranspilerError, "Got routing_method="):
transpile(qc, routing_method="lookahead", optimization_level=optimization_level)
with self.assertRaisesRegex(TranspilerError, "Got scheduling_method="):
transpile(qc, scheduling_method="alap", optimization_level=optimization_level)
@data(0, 1, 2, 3)
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 = FakeTokyo()
qc = QuantumCircuit(1, 1)
with qc.for_loop((0,)):
pass
with self.assertRaisesRegex(TranspilerError, "The control-flow construct.*not supported"):
transpile(qc, backend, optimization_level=optimization_level)
qc = QuantumCircuit(1, 1)
with qc.if_test((qc.clbits[0], False)):
pass
with self.assertRaisesRegex(TranspilerError, "The control-flow construct.*not supported"):
transpile(qc, backend, optimization_level=optimization_level)
qc = QuantumCircuit(1, 1)
with qc.while_loop((qc.clbits[0], False)):
pass
with qc.for_loop((0, 1, 2)):
pass
with self.assertRaisesRegex(TranspilerError, "The control-flow construct.*not supported"):
transpile(qc, backend, optimization_level=optimization_level)
@data(0, 1, 2, 3)
def test_unsupported_targets_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 `Target` will raise a more sensible error."""
target = Target(num_qubits=2)
target.add_instruction(CXGate(), {(0, 1): None})
qc = QuantumCircuit(1, 1)
with qc.for_loop((0,)):
pass
with self.assertRaisesRegex(TranspilerError, "The control-flow construct.*not supported"):
transpile(qc, target=target, optimization_level=optimization_level)
qc = QuantumCircuit(1, 1)
with qc.if_test((qc.clbits[0], False)):
pass
with self.assertRaisesRegex(TranspilerError, "The control-flow construct.*not supported"):
transpile(qc, target=target, optimization_level=optimization_level)
qc = QuantumCircuit(1, 1)
with qc.while_loop((qc.clbits[0], False)):
pass
with qc.for_loop((0, 1, 2)):
pass
with self.assertRaisesRegex(TranspilerError, "The control-flow construct.*not supported"):
transpile(qc, target=target, optimization_level=optimization_level)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Transpiler pulse gate pass testing."""
import ddt
from qiskit import pulse, circuit, transpile
from qiskit.providers.fake_provider import FakeAthens, FakeAthensV2
from qiskit.quantum_info.random import random_unitary
from qiskit.test import QiskitTestCase
@ddt.ddt
class TestPulseGate(QiskitTestCase):
"""Integration test of pulse gate pass with custom backend."""
def setUp(self):
super().setUp()
self.sched_param = circuit.Parameter("P0")
with pulse.build(name="sx_q0") as custom_sx_q0:
pulse.play(pulse.Constant(100, 0.1), pulse.DriveChannel(0))
self.custom_sx_q0 = custom_sx_q0
with pulse.build(name="sx_q1") as custom_sx_q1:
pulse.play(pulse.Constant(100, 0.2), pulse.DriveChannel(1))
self.custom_sx_q1 = custom_sx_q1
with pulse.build(name="cx_q01") as custom_cx_q01:
pulse.play(pulse.Constant(100, 0.4), pulse.ControlChannel(0))
self.custom_cx_q01 = custom_cx_q01
with pulse.build(name="my_gate_q0") as my_gate_q0:
pulse.shift_phase(self.sched_param, pulse.DriveChannel(0))
pulse.play(pulse.Constant(120, 0.1), pulse.DriveChannel(0))
self.my_gate_q0 = my_gate_q0
with pulse.build(name="my_gate_q1") as my_gate_q1:
pulse.shift_phase(self.sched_param, pulse.DriveChannel(1))
pulse.play(pulse.Constant(120, 0.2), pulse.DriveChannel(1))
self.my_gate_q1 = my_gate_q1
def test_transpile_with_bare_backend(self):
"""Test transpile without custom calibrations."""
backend = FakeAthens()
qc = circuit.QuantumCircuit(2)
qc.sx(0)
qc.x(0)
qc.rz(0, 0)
qc.sx(1)
qc.measure_all()
transpiled_qc = transpile(qc, backend, initial_layout=[0, 1])
ref_calibration = {}
self.assertDictEqual(transpiled_qc.calibrations, ref_calibration)
def test_transpile_with_backend_target(self):
"""Test transpile without custom calibrations from target."""
backend = FakeAthensV2()
target = backend.target
qc = circuit.QuantumCircuit(2)
qc.sx(0)
qc.x(0)
qc.rz(0, 0)
qc.sx(1)
qc.measure_all()
transpiled_qc = transpile(qc, initial_layout=[0, 1], target=target)
ref_calibration = {}
self.assertDictEqual(transpiled_qc.calibrations, ref_calibration)
def test_transpile_with_custom_basis_gate(self):
"""Test transpile with custom calibrations."""
backend = FakeAthens()
backend.defaults().instruction_schedule_map.add("sx", (0,), self.custom_sx_q0)
backend.defaults().instruction_schedule_map.add("sx", (1,), self.custom_sx_q1)
qc = circuit.QuantumCircuit(2)
qc.sx(0)
qc.x(0)
qc.rz(0, 0)
qc.sx(1)
qc.measure_all()
transpiled_qc = transpile(qc, backend, initial_layout=[0, 1])
ref_calibration = {
"sx": {
((0,), ()): self.custom_sx_q0,
((1,), ()): self.custom_sx_q1,
}
}
self.assertDictEqual(transpiled_qc.calibrations, ref_calibration)
def test_transpile_with_custom_basis_gate_in_target(self):
"""Test transpile with custom calibrations."""
backend = FakeAthensV2()
target = backend.target
target["sx"][(0,)].calibration = self.custom_sx_q0
target["sx"][(1,)].calibration = self.custom_sx_q1
qc = circuit.QuantumCircuit(2)
qc.sx(0)
qc.x(0)
qc.rz(0, 0)
qc.sx(1)
qc.measure_all()
transpiled_qc = transpile(qc, initial_layout=[0, 1], target=target)
ref_calibration = {
"sx": {
((0,), ()): self.custom_sx_q0,
((1,), ()): self.custom_sx_q1,
}
}
self.assertDictEqual(transpiled_qc.calibrations, ref_calibration)
def test_transpile_with_instmap(self):
"""Test providing instruction schedule map."""
instmap = FakeAthens().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 = FakeAthens()
qc = circuit.QuantumCircuit(2)
qc.sx(0)
qc.x(0)
qc.rz(0, 0)
qc.sx(1)
qc.measure_all()
transpiled_qc = transpile(qc, backend, inst_map=instmap, initial_layout=[0, 1])
ref_calibration = {
"sx": {
((0,), ()): self.custom_sx_q0,
((1,), ()): self.custom_sx_q1,
}
}
self.assertDictEqual(transpiled_qc.calibrations, ref_calibration)
def test_transpile_with_custom_gate(self):
"""Test providing non-basis gate."""
backend = FakeAthens()
backend.defaults().instruction_schedule_map.add(
"my_gate", (0,), self.my_gate_q0, arguments=["P0"]
)
backend.defaults().instruction_schedule_map.add(
"my_gate", (1,), self.my_gate_q1, arguments=["P0"]
)
qc = circuit.QuantumCircuit(2)
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])
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)
ref_calibration = {
"my_gate": {
((0,), (1.0,)): my_gate_q0_1_0,
((1,), (2.0,)): my_gate_q1_2_0,
}
}
self.assertDictEqual(transpiled_qc.calibrations, ref_calibration)
def test_transpile_with_parameterized_custom_gate(self):
"""Test providing non-basis gate, which is kept parameterized throughout transpile."""
backend = FakeAthens()
backend.defaults().instruction_schedule_map.add(
"my_gate", (0,), self.my_gate_q0, arguments=["P0"]
)
param = circuit.Parameter("new_P0")
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])
my_gate_q0_p = self.my_gate_q0.assign_parameters({self.sched_param: param}, inplace=False)
ref_calibration = {
"my_gate": {
((0,), (param,)): my_gate_q0_p,
}
}
self.assertDictEqual(transpiled_qc.calibrations, ref_calibration)
def test_transpile_with_multiple_circuits(self):
"""Test transpile with multiple circuits with custom gate."""
backend = FakeAthens()
backend.defaults().instruction_schedule_map.add(
"my_gate", (0,), self.my_gate_q0, arguments=["P0"]
)
params = [0.0, 1.0, 2.0, 3.0]
circs = []
for param in params:
qc = circuit.QuantumCircuit(1)
qc.append(circuit.Gate("my_gate", 1, [param]), [0])
circs.append(qc)
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(
{self.sched_param: param}, inplace=False
)
ref_calibration = {"my_gate": {((0,), (param,)): my_gate_q0_x}}
self.assertDictEqual(transpiled_qc.calibrations, ref_calibration)
def test_multiple_instructions_with_different_parameters(self):
"""Test adding many instruction with different parameter binding."""
backend = FakeAthens()
backend.defaults().instruction_schedule_map.add(
"my_gate", (0,), self.my_gate_q0, arguments=["P0"]
)
qc = circuit.QuantumCircuit(1)
qc.append(circuit.Gate("my_gate", 1, [1.0]), [0])
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])
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)
my_gate_q0_3_0 = self.my_gate_q0.assign_parameters({self.sched_param: 3.0}, inplace=False)
ref_calibration = {
"my_gate": {
((0,), (1.0,)): my_gate_q0_1_0,
((0,), (2.0,)): my_gate_q0_2_0,
((0,), (3.0,)): my_gate_q0_3_0,
}
}
self.assertDictEqual(transpiled_qc.calibrations, ref_calibration)
def test_transpile_with_different_qubit(self):
"""Test transpile with qubit without custom gate."""
backend = FakeAthens()
backend.defaults().instruction_schedule_map.add("sx", (0,), self.custom_sx_q0)
qc = circuit.QuantumCircuit(1)
qc.sx(0)
qc.measure_all()
transpiled_qc = transpile(qc, backend, initial_layout=[3])
self.assertDictEqual(transpiled_qc.calibrations, {})
@ddt.data(0, 1, 2, 3)
def test_transpile_with_both_instmap_and_empty_target(self, opt_level):
"""Test when instmap and target are both provided
and only instmap contains custom schedules.
Test case from Qiskit/qiskit-terra/#9489
"""
instmap = FakeAthens().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)
# This doesn't have custom schedule definition
target = FakeAthensV2().target
qc = circuit.QuantumCircuit(2)
qc.append(random_unitary(4, seed=123), [0, 1])
qc.measure_all()
transpiled_qc = transpile(
qc,
optimization_level=opt_level,
basis_gates=["sx", "rz", "x", "cx"],
inst_map=instmap,
target=target,
initial_layout=[0, 1],
)
ref_calibration = {
"sx": {
((0,), ()): self.custom_sx_q0,
((1,), ()): self.custom_sx_q1,
},
"cx": {
((0, 1), ()): self.custom_cx_q01,
},
}
self.assertDictEqual(transpiled_qc.calibrations, ref_calibration)
@ddt.data(0, 1, 2, 3)
def test_transpile_with_instmap_with_v2backend(self, opt_level):
"""Test when instmap is provided with V2 backend.
Test case from Qiskit/qiskit-terra/#9489
"""
instmap = FakeAthens().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)
qc = circuit.QuantumCircuit(2)
qc.append(random_unitary(4, seed=123), [0, 1])
qc.measure_all()
transpiled_qc = transpile(
qc,
FakeAthensV2(),
optimization_level=opt_level,
inst_map=instmap,
initial_layout=[0, 1],
)
ref_calibration = {
"sx": {
((0,), ()): self.custom_sx_q0,
((1,), ()): self.custom_sx_q1,
},
"cx": {
((0, 1), ()): self.custom_cx_q01,
},
}
self.assertDictEqual(transpiled_qc.calibrations, ref_calibration)
@ddt.data(0, 1, 2, 3)
def test_transpile_with_instmap_with_v2backend_with_custom_gate(self, opt_level):
"""Test when instmap is provided with V2 backend.
In this test case, instmap contains a custom gate which doesn't belong to
Qiskit standard gate. Target must define a custom gete on the fly
to reflect user-provided instmap.
Test case from Qiskit/qiskit-terra/#9489
"""
with pulse.build(name="custom") as rabi12:
pulse.play(pulse.Constant(100, 0.4), pulse.DriveChannel(0))
instmap = FakeAthens().defaults().instruction_schedule_map
instmap.add("rabi12", (0,), rabi12)
gate = circuit.Gate("rabi12", 1, [])
qc = circuit.QuantumCircuit(1)
qc.append(gate, [0])
qc.measure_all()
transpiled_qc = transpile(
qc,
FakeAthensV2(),
optimization_level=opt_level,
inst_map=instmap,
initial_layout=[0],
)
ref_calibration = {
"rabi12": {
((0,), ()): rabi12,
}
}
self.assertDictEqual(transpiled_qc.calibrations, ref_calibration)
def test_transpile_with_instmap_not_mutate_backend(self):
"""Do not override default backend target when transpile with inst map.
Providing an instmap for the transpile arguments may override target,
which might be pulled from the provided backend instance.
This should not override the source object since the same backend may
be used for future transpile without intention of instruction overriding.
"""
backend = FakeAthensV2()
original_sx0 = backend.target["sx"][(0,)].calibration
instmap = FakeAthens().defaults().instruction_schedule_map
instmap.add("sx", (0,), self.custom_sx_q0)
qc = circuit.QuantumCircuit(1)
qc.sx(0)
qc.measure_all()
transpiled_qc = transpile(
qc,
FakeAthensV2(),
inst_map=instmap,
initial_layout=[0],
)
self.assertTrue(transpiled_qc.has_calibration_for(transpiled_qc.data[0]))
self.assertEqual(
backend.target["sx"][(0,)].calibration,
original_sx0,
)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the RemoveBarriers pass"""
import unittest
from qiskit.transpiler.passes import RemoveBarriers
from qiskit.converters import circuit_to_dag
from qiskit import QuantumCircuit
from qiskit.test import QiskitTestCase
class TestMergeAdjacentBarriers(QiskitTestCase):
"""Test the MergeAdjacentBarriers pass"""
def test_remove_barriers(self):
"""Remove all barriers"""
circuit = QuantumCircuit(2)
circuit.barrier()
circuit.barrier()
pass_ = RemoveBarriers()
result_dag = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result_dag.size(), 0)
def test_remove_barriers_other_gates(self):
"""Remove all barriers, leave other gates intact"""
circuit = QuantumCircuit(1)
circuit.barrier()
circuit.x(0)
circuit.barrier()
circuit.h(0)
pass_ = RemoveBarriers()
result_dag = pass_.run(circuit_to_dag(circuit))
op_nodes = result_dag.op_nodes()
self.assertEqual(result_dag.size(), 2)
for ii, name in enumerate(["x", "h"]):
self.assertEqual(op_nodes[ii].name, name)
def test_simple_if_else(self):
"""Test that the pass recurses into an if-else."""
pass_ = RemoveBarriers()
base_test = QuantumCircuit(1, 1)
base_test.barrier()
base_test.measure(0, 0)
base_expected = QuantumCircuit(1, 1)
base_expected.measure(0, 0)
test = QuantumCircuit(1, 1)
test.if_else(
(test.clbits[0], True), base_test.copy(), base_test.copy(), test.qubits, test.clbits
)
expected = QuantumCircuit(1, 1)
expected.if_else(
(expected.clbits[0], True),
base_expected.copy(),
base_expected.copy(),
expected.qubits,
expected.clbits,
)
self.assertEqual(pass_(test), expected)
def test_nested_control_flow(self):
"""Test that the pass recurses into nested control flow."""
pass_ = RemoveBarriers()
base_test = QuantumCircuit(1, 1)
base_test.barrier()
base_test.measure(0, 0)
base_expected = QuantumCircuit(1, 1)
base_expected.measure(0, 0)
body_test = QuantumCircuit(1, 1)
body_test.for_loop((0,), None, base_expected.copy(), body_test.qubits, body_test.clbits)
body_expected = QuantumCircuit(1, 1)
body_expected.for_loop(
(0,), None, base_expected.copy(), body_expected.qubits, body_expected.clbits
)
test = QuantumCircuit(1, 1)
test.while_loop((test.clbits[0], True), body_test, test.qubits, test.clbits)
expected = QuantumCircuit(1, 1)
expected.while_loop(
(expected.clbits[0], True), body_expected, expected.qubits, expected.clbits
)
self.assertEqual(pass_(test), expected)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test RemoveDiagonalGatesBeforeMeasure pass"""
import unittest
from copy import deepcopy
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister
from qiskit.circuit.library import U1Gate, CU1Gate
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import RemoveDiagonalGatesBeforeMeasure, DAGFixedPoint
from qiskit.converters import circuit_to_dag
from qiskit.test import QiskitTestCase
class TesRemoveDiagonalGatesBeforeMeasure(QiskitTestCase):
"""Test remove_diagonal_gates_before_measure optimizations."""
def test_optimize_1rz_1measure(self):
"""Remove a single RZGate
qr0:-RZ--m-- qr0:--m-
| |
qr1:-----|-- ==> qr1:--|-
| |
cr0:-----.-- cr0:--.-
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.rz(0.1, qr[0])
circuit.measure(qr[0], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_optimize_1z_1measure(self):
"""Remove a single ZGate
qr0:--Z--m-- qr0:--m-
| |
qr1:-----|-- ==> qr1:--|-
| |
cr0:-----.-- cr0:--.-
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.z(qr[0])
circuit.measure(qr[0], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_optimize_1t_1measure(self):
"""Remove a single TGate, SGate, TdgGate, SdgGate, U1Gate
qr0:--T--m-- qr0:--m-
| |
qr1:-----|-- ==> qr1:--|-
| |
cr0:-----.-- cr0:--.-
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.t(qr[0])
circuit.measure(qr[0], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_optimize_1s_1measure(self):
"""Remove a single SGate
qr0:--S--m-- qr0:--m-
| |
qr1:-----|-- ==> qr1:--|-
| |
cr0:-----.-- cr0:--.-
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.s(qr[0])
circuit.measure(qr[0], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_optimize_1tdg_1measure(self):
"""Remove a single TdgGate
qr0:-Tdg-m-- qr0:--m-
| |
qr1:-----|-- ==> qr1:--|-
| |
cr0:-----.-- cr0:--.-
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.tdg(qr[0])
circuit.measure(qr[0], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_optimize_1sdg_1measure(self):
"""Remove a single SdgGate
qr0:-Sdg--m-- qr0:--m-
| |
qr1:------|-- ==> qr1:--|-
| |
cr0:------.-- cr0:--.-
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.sdg(qr[0])
circuit.measure(qr[0], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_optimize_1u1_1measure(self):
"""Remove a single U1Gate
qr0:--U1-m-- qr0:--m-
| |
qr1:-----|-- ==> qr1:--|-
| |
cr0:-----.-- cr0:--.-
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.append(U1Gate(0.1), [qr[0]])
circuit.measure(qr[0], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_optimize_1rz_1z_1measure(self):
"""Remove a single RZ and leave the other Z
qr0:-RZ--m-- qr0:----m-
| |
qr1:--Z--|-- ==> qr1:--Z-|-
| |
cr0:-----.-- cr0:----.-
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.rz(0.1, qr[0])
circuit.z(qr[1])
circuit.measure(qr[0], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.z(qr[1])
expected.measure(qr[0], cr[0])
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_simple_if_else(self):
"""Test that the pass recurses into an if-else."""
pass_ = RemoveDiagonalGatesBeforeMeasure()
base_test = QuantumCircuit(1, 1)
base_test.z(0)
base_test.measure(0, 0)
base_expected = QuantumCircuit(1, 1)
base_expected.measure(0, 0)
test = QuantumCircuit(1, 1)
test.if_else(
(test.clbits[0], True), base_test.copy(), base_test.copy(), test.qubits, test.clbits
)
expected = QuantumCircuit(1, 1)
expected.if_else(
(expected.clbits[0], True),
base_expected.copy(),
base_expected.copy(),
expected.qubits,
expected.clbits,
)
self.assertEqual(pass_(test), expected)
def test_nested_control_flow(self):
"""Test that the pass recurses into nested control flow."""
pass_ = RemoveDiagonalGatesBeforeMeasure()
base_test = QuantumCircuit(2, 1)
base_test.cz(0, 1)
base_test.measure(0, 0)
base_expected = QuantumCircuit(2, 1)
base_expected.measure(1, 0)
body_test = QuantumCircuit(2, 1)
body_test.for_loop((0,), None, base_expected.copy(), body_test.qubits, body_test.clbits)
body_expected = QuantumCircuit(2, 1)
body_expected.for_loop(
(0,), None, base_expected.copy(), body_expected.qubits, body_expected.clbits
)
test = QuantumCircuit(2, 1)
test.while_loop((test.clbits[0], True), body_test, test.qubits, test.clbits)
expected = QuantumCircuit(2, 1)
expected.while_loop(
(expected.clbits[0], True), body_expected, expected.qubits, expected.clbits
)
self.assertEqual(pass_(test), expected)
class TesRemoveDiagonalControlGatesBeforeMeasure(QiskitTestCase):
"""Test remove diagonal control gates before measure."""
def test_optimize_1cz_2measure(self):
"""Remove a single CZGate
qr0:--Z--m--- qr0:--m---
| | |
qr1:--.--|-m- ==> qr1:--|-m-
| | | |
cr0:-----.-.- cr0:--.-.-
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.cz(qr[0], qr[1])
circuit.measure(qr[0], cr[0])
circuit.measure(qr[1], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
expected.measure(qr[1], cr[0])
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_optimize_1crz_2measure(self):
"""Remove a single CRZGate
qr0:-RZ--m--- qr0:--m---
| | |
qr1:--.--|-m- ==> qr1:--|-m-
| | | |
cr0:-----.-.- cr0:--.-.-
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.crz(0.1, qr[0], qr[1])
circuit.measure(qr[0], cr[0])
circuit.measure(qr[1], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
expected.measure(qr[1], cr[0])
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_optimize_1cu1_2measure(self):
"""Remove a single CU1Gate
qr0:-CU1-m--- qr0:--m---
| | |
qr1:--.--|-m- ==> qr1:--|-m-
| | | |
cr0:-----.-.- cr0:--.-.-
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.append(CU1Gate(0.1), [qr[0], qr[1]])
circuit.measure(qr[0], cr[0])
circuit.measure(qr[1], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
expected.measure(qr[1], cr[0])
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_optimize_1rzz_2measure(self):
"""Remove a single RZZGate
qr0:--.----m--- qr0:--m---
|zz | |
qr1:--.----|-m- ==> qr1:--|-m-
| | | |
cr0:-------.-.- cr0:--.-.-
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.rzz(0.1, qr[0], qr[1])
circuit.measure(qr[0], cr[0])
circuit.measure(qr[1], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
expected.measure(qr[1], cr[0])
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
class TestRemoveDiagonalGatesBeforeMeasureOveroptimizations(QiskitTestCase):
"""Test situations where remove_diagonal_gates_before_measure should not optimize"""
def test_optimize_1cz_1measure(self):
"""Do not remove a CZGate because measure happens on only one of the wires
Compare with test_optimize_1cz_2measure.
qr0:--Z--m---
| |
qr1:--.--|---
|
cr0:-----.---
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.cz(qr[0], qr[1])
circuit.measure(qr[0], cr[0])
dag = circuit_to_dag(circuit)
expected = deepcopy(dag)
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(expected, after)
def test_do_not_optimize_with_conditional(self):
"""Diagonal gates with conditionals on a measurement target.
See https://github.com/Qiskit/qiskit-terra/pull/2208#issuecomment-487238819
░ ┌───┐┌─┐
qr_0: |0>────────────░─┤ H ├┤M├
┌─────────┐ ░ └───┘└╥┘
qr_1: |0>┤ Rz(0.1) ├─░───────╫─
└─┬──┴──┬─┘ ░ ║
cr_0: 0 ══╡ = 1 ╞═══════════╩═
└─────┘
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.rz(0.1, qr[1]).c_if(cr, 1)
circuit.barrier()
circuit.h(qr[0])
circuit.measure(qr[0], cr[0])
dag = circuit_to_dag(circuit)
expected = deepcopy(dag)
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(expected, after)
class TestRemoveDiagonalGatesBeforeMeasureFixedPoint(QiskitTestCase):
"""Test remove_diagonal_gates_before_measure optimizations in
a transpiler, using fixed point."""
def test_optimize_rz_z(self):
"""Remove two swaps that overlap
qr0:--RZ-Z--m-- qr0:--m--
| |
cr0:--------.-- cr0:--.--
"""
qr = QuantumRegister(1, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.rz(0.1, qr[0])
circuit.z(qr[0])
circuit.measure(qr[0], cr[0])
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
pass_manager = PassManager()
pass_manager.append(
[RemoveDiagonalGatesBeforeMeasure(), DAGFixedPoint()],
do_while=lambda property_set: not property_set["dag_fixed_point"],
)
after = pass_manager.run(circuit)
self.assertEqual(expected, after)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test RemoveFinalMeasurements pass"""
import unittest
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
from qiskit.circuit.classicalregister import Clbit
from qiskit.transpiler.passes import RemoveFinalMeasurements
from qiskit.converters import circuit_to_dag
from qiskit.test import QiskitTestCase
class TestRemoveFinalMeasurements(QiskitTestCase):
"""Test removing final measurements."""
def test_multi_bit_register_removed_with_clbits(self):
"""Remove register when all clbits removed."""
def expected_dag():
q0 = QuantumRegister(2, "q0")
qc = QuantumCircuit(q0)
return circuit_to_dag(qc)
q0 = QuantumRegister(2, "q0")
c0 = ClassicalRegister(2, "c0")
qc = QuantumCircuit(q0, c0)
# measure into all clbits of c0
qc.measure(0, 0)
qc.measure(1, 1)
dag = circuit_to_dag(qc)
dag = RemoveFinalMeasurements().run(dag)
self.assertFalse(dag.cregs)
self.assertFalse(dag.clbits)
self.assertEqual(dag, expected_dag())
def test_register_kept_if_measured_clbit_busy(self):
"""
A register is kept if the measure destination bit is still
busy after measure removal.
"""
def expected_dag():
q0 = QuantumRegister(1, "q0")
c0 = ClassicalRegister(1, "c0")
qc = QuantumCircuit(q0, c0)
qc.x(0).c_if(c0[0], 0)
return circuit_to_dag(qc)
q0 = QuantumRegister(1, "q0")
c0 = ClassicalRegister(1, "c0")
qc = QuantumCircuit(q0, c0)
# make c0 busy
qc.x(0).c_if(c0[0], 0)
# measure into c0
qc.measure(0, c0[0])
dag = circuit_to_dag(qc)
dag = RemoveFinalMeasurements().run(dag)
self.assertListEqual(list(dag.cregs.values()), [c0])
self.assertListEqual(dag.clbits, list(c0))
self.assertEqual(dag, expected_dag())
def test_multi_bit_register_kept_if_not_measured_clbit_busy(self):
"""
A multi-bit register is kept if it contains a busy bit even if
the measure destination bit itself is idle.
"""
def expected_dag():
q0 = QuantumRegister(1, "q0")
c0 = ClassicalRegister(2, "c0")
qc = QuantumCircuit(q0, c0)
qc.x(q0[0]).c_if(c0[0], 0)
return circuit_to_dag(qc)
q0 = QuantumRegister(1, "q0")
c0 = ClassicalRegister(2, "c0")
qc = QuantumCircuit(q0, c0)
# make c0[0] busy
qc.x(q0[0]).c_if(c0[0], 0)
# measure into not busy c0[1]
qc.measure(0, c0[1])
dag = circuit_to_dag(qc)
dag = RemoveFinalMeasurements().run(dag)
# c0 should not be removed because it has busy bit c0[0]
self.assertListEqual(list(dag.cregs.values()), [c0])
# note: c0[1] should not be removed even though it is now idle
# because it is referenced by creg c0.
self.assertListEqual(dag.clbits, list(c0))
self.assertEqual(dag, expected_dag())
def test_overlapping_register_removal(self):
"""Only registers that become idle directly as a result of
final op removal are removed. In this test, a 5-bit creg
is implicitly created with its own bits, along with cregs
``c0_lower_3`` and ``c0_upper_3`` which reuse those underlying bits.
``c0_lower_3`` and ``c0_upper_3`` reference only 1 bit in common.
A final measure is performed into a bit that exists in ``c0_lower_3``
but not in ``c0_upper_3``, and subsequently is removed. Consequently,
both ``c0_lower_3`` and the 5-bit register are removed, because they
have become unused as a result of the final measure removal.
``c0_upper_3`` remains, because it was idle beforehand, not as a
result of the measure removal, along with all of its bits,
including the bit shared with ``c0_lower_3``."""
def expected_dag():
q0 = QuantumRegister(3, "q0")
c0 = ClassicalRegister(5, "c0")
c0_upper_3 = ClassicalRegister(name="c0_upper_3", bits=c0[2:])
# note c0 is *not* added to circuit!
qc = QuantumCircuit(q0, c0_upper_3)
return circuit_to_dag(qc)
q0 = QuantumRegister(3, "q0")
c0 = ClassicalRegister(5, "c0")
qc = QuantumCircuit(q0, c0)
c0_lower_3 = ClassicalRegister(name="c0_lower_3", bits=c0[:3])
c0_upper_3 = ClassicalRegister(name="c0_upper_3", bits=c0[2:])
# Only qc.clbits[2] is shared between the two.
qc.add_register(c0_lower_3)
qc.add_register(c0_upper_3)
qc.measure(0, c0_lower_3[0])
dag = circuit_to_dag(qc)
dag = RemoveFinalMeasurements().run(dag)
self.assertListEqual(list(dag.cregs.values()), [c0_upper_3])
self.assertListEqual(dag.clbits, list(c0_upper_3))
self.assertEqual(dag, expected_dag())
def test_multi_bit_register_removed_if_all_bits_idle(self):
"""A multibit register is removed when all bits are idle."""
def expected_dag():
q0 = QuantumRegister(1, "q0")
qc = QuantumCircuit(q0)
return circuit_to_dag(qc)
q0 = QuantumRegister(1, "q0")
c0 = ClassicalRegister(2, "c0")
qc = QuantumCircuit(q0, c0)
# measure into single bit c0[0] of c0
qc.measure(0, 0)
dag = circuit_to_dag(qc)
dag = RemoveFinalMeasurements().run(dag)
self.assertFalse(dag.cregs)
self.assertFalse(dag.clbits)
self.assertEqual(dag, expected_dag())
def test_multi_reg_shared_bits_removed(self):
"""All registers sharing removed bits should be removed."""
def expected_dag():
q0 = QuantumRegister(2, "q0")
qc = QuantumCircuit(q0)
return circuit_to_dag(qc)
q0 = QuantumRegister(2, "q0")
c0 = ClassicalRegister(2, "c0")
qc = QuantumCircuit(q0, c0)
# Create reg with shared bits (same as c0)
c1 = ClassicalRegister(name="c1", bits=qc.clbits)
qc.add_register(c1)
# measure into all clbits of c0
qc.measure(0, c0[0])
qc.measure(1, c0[1])
dag = circuit_to_dag(qc)
dag = RemoveFinalMeasurements().run(dag)
self.assertFalse(dag.cregs)
self.assertFalse(dag.clbits)
self.assertEqual(dag, expected_dag())
def test_final_measures_share_dest(self):
"""Multiple final measurements use the same clbit."""
def expected_dag():
qc = QuantumCircuit(QuantumRegister(2, "q0"))
return circuit_to_dag(qc)
rq = QuantumRegister(2, "q0")
rc = ClassicalRegister(1, "c0")
qc = QuantumCircuit(rq, rc)
qc.measure(0, 0)
qc.measure(1, 0)
dag = circuit_to_dag(qc)
dag = RemoveFinalMeasurements().run(dag)
self.assertEqual(dag, expected_dag())
def test_remove_chained_final_measurements(self):
"""Remove successive final measurements."""
def expected_dag():
q0 = QuantumRegister(1, "q0")
q1 = QuantumRegister(1, "q1")
c0 = ClassicalRegister(1, "c0")
qc = QuantumCircuit(q0, c0, q1)
qc.measure(q0, c0)
qc.measure(q0, c0)
qc.barrier()
qc.h(q1)
return circuit_to_dag(qc)
q0 = QuantumRegister(1, "q0")
q1 = QuantumRegister(1, "q1")
c0 = ClassicalRegister(1, "c0")
c1 = ClassicalRegister(1, "c1")
qc = QuantumCircuit(q0, c0, q1, c1)
qc.measure(q0, c0)
qc.measure(q0, c0)
qc.barrier()
qc.h(q1)
qc.measure(q1, c1)
qc.measure(q0, c1)
dag = circuit_to_dag(qc)
dag = RemoveFinalMeasurements().run(dag)
self.assertEqual(dag, expected_dag())
def test_remove_clbits_without_register(self):
"""clbits of final measurements not in a register are removed."""
def expected_dag():
q0 = QuantumRegister(1, "q0")
qc = QuantumCircuit(q0)
return circuit_to_dag(qc)
q0 = QuantumRegister(1, "q0")
qc = QuantumCircuit(q0)
# Add clbit without adding register
qc.add_bits([Clbit()])
self.assertFalse(qc.cregs)
# Measure to regless clbit
qc.measure(0, 0)
dag = circuit_to_dag(qc)
dag = RemoveFinalMeasurements().run(dag)
self.assertFalse(dag.cregs)
self.assertFalse(dag.clbits)
self.assertEqual(dag, expected_dag())
def test_final_barriers_and_measures_complex(self):
"""Test complex final barrier and measure removal."""
def expected_dag():
q0 = QuantumRegister(5, "q0")
c1 = ClassicalRegister(1, "c1")
qc = QuantumCircuit(q0, c1)
qc.h(q0[0])
return circuit_to_dag(qc)
# ┌───┐┌─┐ ░ ░ ┌─┐
# q0_0: ┤ H ├┤M├─░─────░─┤M├───────────────
# └┬─┬┘└╥┘ ░ ░ └╥┘┌─┐
# q0_1: ─┤M├──╫──░─────░──╫─┤M├────────────
# └╥┘ ║ ░ ░ ░ ║ └╥┘┌─┐
# q0_2: ──╫───╫──░──░──░──╫──╫─┤M├─────────
# ║ ║ ░ ░ ░ ║ ║ └╥┘┌─┐
# q0_3: ──╫───╫──░──░──░──╫──╫──╫─┤M├──────
# ║ ║ ░ ░ ░ ║ ║ ║ └╥┘┌─┐ ░
# q0_4: ──╫───╫──░─────░──╫──╫──╫──╫─┤M├─░─
# ║ ║ ░ ░ ║ ║ ║ ║ └╥┘ ░
# c0: 1/══╩═══╩═══════════╬══╬══╬══╬══╬════
# 0 0 ║ ║ ║ ║ ║
# ║ ║ ║ ║ ║
# c1: 1/══════════════════╬══╬══╬══╬══╬════
# ║ ║ ║ ║ ║
# meas: 5/════════════════╩══╩══╩══╩══╩════
# 0 1 2 3 4
q0 = QuantumRegister(5, "q0")
c0 = ClassicalRegister(1, "c0")
c1 = ClassicalRegister(1, "c1")
qc = QuantumCircuit(q0, c0, c1)
qc.measure(q0[1], c0)
qc.h(q0[0])
qc.measure(q0[0], c0[0])
qc.barrier()
qc.barrier(q0[2], q0[3])
qc.measure_all()
qc.barrier(q0[4])
dag = circuit_to_dag(qc)
dag = RemoveFinalMeasurements().run(dag)
self.assertEqual(dag, expected_dag())
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test RemoveResetInZeroState pass"""
import unittest
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import RemoveResetInZeroState, DAGFixedPoint
from qiskit.converters import circuit_to_dag
from qiskit.test import QiskitTestCase
class TestRemoveResetInZeroState(QiskitTestCase):
"""Test swap-followed-by-measure optimizations."""
def test_optimize_single_reset(self):
"""Remove a single reset
qr0:--|0>-- ==> qr0:----
"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.reset(qr)
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
pass_ = RemoveResetInZeroState()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_dont_optimize_non_zero_state(self):
"""Do not remove reset if not in a zero state
qr0:--[H]--|0>-- ==> qr0:--[H]--|0>--
"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr)
circuit.reset(qr)
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
expected.h(qr)
expected.reset(qr)
pass_ = RemoveResetInZeroState()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_optimize_single_reset_in_diff_qubits(self):
"""Remove a single reset in different qubits
qr0:--|0>-- qr0:----
==>
qr1:--|0>-- qr1:----
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.reset(qr)
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
pass_ = RemoveResetInZeroState()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
class TestRemoveResetInZeroStateFixedPoint(QiskitTestCase):
"""Test RemoveResetInZeroState in a transpiler, using fixed point."""
def test_two_resets(self):
"""Remove two initial resets
qr0:--|0>-|0>-- ==> qr0:----
"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.reset(qr[0])
circuit.reset(qr[0])
expected = QuantumCircuit(qr)
pass_manager = PassManager()
pass_manager.append(
[RemoveResetInZeroState(), DAGFixedPoint()],
do_while=lambda property_set: not property_set["dag_fixed_point"],
)
after = pass_manager.run(circuit)
self.assertEqual(expected, after)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the ResetAfterMeasureSimplification pass"""
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit.circuit.classicalregister import Clbit
from qiskit.transpiler.passes.optimization import ResetAfterMeasureSimplification
from qiskit.test import QiskitTestCase
class TestResetAfterMeasureSimplificationt(QiskitTestCase):
"""Test ResetAfterMeasureSimplification transpiler pass."""
def test_simple(self):
"""Test simple"""
qc = QuantumCircuit(1, 1)
qc.measure(0, 0)
qc.reset(0)
new_qc = ResetAfterMeasureSimplification()(qc)
ans_qc = QuantumCircuit(1, 1)
ans_qc.measure(0, 0)
ans_qc.x(0).c_if(ans_qc.clbits[0], 1)
self.assertEqual(new_qc, ans_qc)
def test_simple_null(self):
"""Test simple no change in circuit"""
qc = QuantumCircuit(1, 1)
qc.measure(0, 0)
qc.x(0)
qc.reset(0)
new_qc = ResetAfterMeasureSimplification()(qc)
self.assertEqual(new_qc, qc)
def test_simple_multi_reg(self):
"""Test simple, multiple registers"""
cr1 = ClassicalRegister(1, "c1")
cr2 = ClassicalRegister(1, "c2")
qr = QuantumRegister(1, "q")
qc = QuantumCircuit(qr, cr1, cr2)
qc.measure(0, 1)
qc.reset(0)
new_qc = ResetAfterMeasureSimplification()(qc)
ans_qc = QuantumCircuit(qr, cr1, cr2)
ans_qc.measure(0, 1)
ans_qc.x(0).c_if(cr2[0], 1)
self.assertEqual(new_qc, ans_qc)
def test_simple_multi_reg_null(self):
"""Test simple, multiple registers, null change"""
cr1 = ClassicalRegister(1, "c1")
cr2 = ClassicalRegister(1, "c2")
qr = QuantumRegister(2, "q")
qc = QuantumCircuit(qr, cr1, cr2)
qc.measure(0, 1)
qc.reset(1) # reset not on same qubit as meas
new_qc = ResetAfterMeasureSimplification()(qc)
self.assertEqual(new_qc, qc)
def test_simple_multi_resets(self):
"""Only first reset is collapsed"""
qc = QuantumCircuit(1, 2)
qc.measure(0, 0)
qc.reset(0)
qc.reset(0)
new_qc = ResetAfterMeasureSimplification()(qc)
ans_qc = QuantumCircuit(1, 2)
ans_qc.measure(0, 0)
ans_qc.x(0).c_if(ans_qc.clbits[0], 1)
ans_qc.reset(0)
self.assertEqual(new_qc, ans_qc)
def test_simple_multi_resets_with_resets_before_measure(self):
"""Reset BEFORE measurement not collapsed"""
qc = QuantumCircuit(2, 2)
qc.measure(0, 0)
qc.reset(0)
qc.reset(1)
qc.measure(1, 1)
new_qc = ResetAfterMeasureSimplification()(qc)
ans_qc = QuantumCircuit(2, 2)
ans_qc.measure(0, 0)
ans_qc.x(0).c_if(Clbit(ClassicalRegister(2, "c"), 0), 1)
ans_qc.reset(1)
ans_qc.measure(1, 1)
self.assertEqual(new_qc, ans_qc)
def test_barriers_work(self):
"""Test that barriers block consolidation"""
qc = QuantumCircuit(1, 1)
qc.measure(0, 0)
qc.barrier(0)
qc.reset(0)
new_qc = ResetAfterMeasureSimplification()(qc)
self.assertEqual(new_qc, qc)
def test_bv_circuit(self):
"""Test Bernstein Vazirani circuit with midcircuit measurement."""
bitstring = "11111"
qc = QuantumCircuit(2, len(bitstring))
qc.x(1)
qc.h(1)
for idx, bit in enumerate(bitstring[::-1]):
qc.h(0)
if int(bit):
qc.cx(0, 1)
qc.h(0)
qc.measure(0, idx)
if idx != len(bitstring) - 1:
qc.reset(0)
# reset control
qc.reset(1)
qc.x(1)
qc.h(1)
new_qc = ResetAfterMeasureSimplification()(qc)
for op in new_qc.data:
if op.operation.name == "reset":
self.assertEqual(op.qubits[0], new_qc.qubits[1])
def test_simple_if_else(self):
"""Test that the pass recurses into an if-else."""
pass_ = ResetAfterMeasureSimplification()
base_test = QuantumCircuit(1, 1)
base_test.measure(0, 0)
base_test.reset(0)
base_expected = QuantumCircuit(1, 1)
base_expected.measure(0, 0)
base_expected.x(0).c_if(0, True)
test = QuantumCircuit(1, 1)
test.if_else(
(test.clbits[0], True), base_test.copy(), base_test.copy(), test.qubits, test.clbits
)
expected = QuantumCircuit(1, 1)
expected.if_else(
(expected.clbits[0], True),
base_expected.copy(),
base_expected.copy(),
expected.qubits,
expected.clbits,
)
self.assertEqual(pass_(test), expected)
def test_nested_control_flow(self):
"""Test that the pass recurses into nested control flow."""
pass_ = ResetAfterMeasureSimplification()
base_test = QuantumCircuit(1, 1)
base_test.measure(0, 0)
base_test.reset(0)
base_expected = QuantumCircuit(1, 1)
base_expected.measure(0, 0)
base_expected.x(0).c_if(0, True)
body_test = QuantumCircuit(1, 1)
body_test.for_loop((0,), None, base_expected.copy(), body_test.qubits, body_test.clbits)
body_expected = QuantumCircuit(1, 1)
body_expected.for_loop(
(0,), None, base_expected.copy(), body_expected.qubits, body_expected.clbits
)
test = QuantumCircuit(1, 1)
test.while_loop((test.clbits[0], True), body_test, test.qubits, test.clbits)
expected = QuantumCircuit(1, 1)
expected.while_loop(
(expected.clbits[0], True), body_expected, expected.qubits, expected.clbits
)
self.assertEqual(pass_(test), expected)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""ResourceEstimation pass testing"""
import unittest
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import ResourceEstimation
from qiskit.test import QiskitTestCase
class TestResourceEstimationPass(QiskitTestCase):
"""Tests for PropertySet methods."""
def test_empty_dag(self):
"""Empty DAG."""
circuit = QuantumCircuit()
passmanager = PassManager()
passmanager.append(ResourceEstimation())
passmanager.run(circuit)
self.assertEqual(passmanager.property_set["size"], 0)
self.assertEqual(passmanager.property_set["depth"], 0)
self.assertEqual(passmanager.property_set["width"], 0)
self.assertDictEqual(passmanager.property_set["count_ops"], {})
def test_just_qubits(self):
"""A dag with 8 operations and no classic bits"""
qr = QuantumRegister(2)
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[0])
circuit.cx(qr[1], qr[0])
passmanager = PassManager()
passmanager.append(ResourceEstimation())
passmanager.run(circuit)
self.assertEqual(passmanager.property_set["size"], 8)
self.assertEqual(passmanager.property_set["depth"], 7)
self.assertEqual(passmanager.property_set["width"], 2)
self.assertDictEqual(passmanager.property_set["count_ops"], {"cx": 6, "h": 2})
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the SabreLayout pass"""
import unittest
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.transpiler import CouplingMap
from qiskit.transpiler.passes import SabreLayout
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.converters import circuit_to_dag
from qiskit.test import QiskitTestCase
from qiskit.compiler.transpiler import transpile
from qiskit.providers.fake_provider import FakeAlmaden, FakeAlmadenV2
from qiskit.providers.fake_provider import FakeKolkata
from qiskit.providers.fake_provider import FakeMontreal
class TestSabreLayout(QiskitTestCase):
"""Tests the SabreLayout pass"""
def setUp(self):
super().setUp()
self.cmap20 = FakeAlmaden().configuration().coupling_map
def test_5q_circuit_20q_coupling(self):
"""Test finds layout for 5q circuit on 20q device."""
# ┌───┐
# q_0: ──■───────┤ X ├───────────────
# │ └─┬─┘┌───┐
# q_1: ──┼────■────┼──┤ X ├───────■──
# ┌─┴─┐ │ │ ├───┤┌───┐┌─┴─┐
# q_2: ┤ X ├──┼────┼──┤ X ├┤ X ├┤ X ├
# └───┘┌─┴─┐ │ └───┘└─┬─┘└───┘
# q_3: ─────┤ X ├──■─────────┼───────
# └───┘ │
# q_4: ──────────────────────■───────
qr = QuantumRegister(5, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[2])
circuit.cx(qr[1], qr[3])
circuit.cx(qr[3], qr[0])
circuit.x(qr[2])
circuit.cx(qr[4], qr[2])
circuit.x(qr[1])
circuit.cx(qr[1], qr[2])
dag = circuit_to_dag(circuit)
pass_ = SabreLayout(CouplingMap(self.cmap20), seed=0, swap_trials=32, layout_trials=32)
pass_.run(dag)
layout = pass_.property_set["layout"]
self.assertEqual([layout[q] for q in circuit.qubits], [18, 11, 13, 12, 14])
def test_6q_circuit_20q_coupling(self):
"""Test finds layout for 6q circuit on 20q device."""
# ┌───┐┌───┐┌───┐┌───┐┌───┐
# q0_0: ┤ X ├┤ X ├┤ X ├┤ X ├┤ X ├
# └─┬─┘└─┬─┘└─┬─┘└─┬─┘└─┬─┘
# q0_1: ──┼────■────┼────┼────┼──
# │ ┌───┐ │ │ │
# q0_2: ──┼──┤ X ├──┼────■────┼──
# │ └───┘ │ │
# q1_0: ──■─────────┼─────────┼──
# ┌───┐ │ │
# q1_1: ─────┤ X ├──┼─────────■──
# └───┘ │
# q1_2: ────────────■────────────
qr0 = QuantumRegister(3, "q0")
qr1 = QuantumRegister(3, "q1")
circuit = QuantumCircuit(qr0, qr1)
circuit.cx(qr1[0], qr0[0])
circuit.cx(qr0[1], qr0[0])
circuit.cx(qr1[2], qr0[0])
circuit.x(qr0[2])
circuit.cx(qr0[2], qr0[0])
circuit.x(qr1[1])
circuit.cx(qr1[1], qr0[0])
dag = circuit_to_dag(circuit)
pass_ = SabreLayout(CouplingMap(self.cmap20), seed=0, swap_trials=32, layout_trials=32)
pass_.run(dag)
layout = pass_.property_set["layout"]
self.assertEqual([layout[q] for q in circuit.qubits], [7, 8, 12, 6, 11, 13])
def test_6q_circuit_20q_coupling_with_target(self):
"""Test finds layout for 6q circuit on 20q device."""
# ┌───┐┌───┐┌───┐┌───┐┌───┐
# q0_0: ┤ X ├┤ X ├┤ X ├┤ X ├┤ X ├
# └─┬─┘└─┬─┘└─┬─┘└─┬─┘└─┬─┘
# q0_1: ──┼────■────┼────┼────┼──
# │ ┌───┐ │ │ │
# q0_2: ──┼──┤ X ├──┼────■────┼──
# │ └───┘ │ │
# q1_0: ──■─────────┼─────────┼──
# ┌───┐ │ │
# q1_1: ─────┤ X ├──┼─────────■──
# └───┘ │
# q1_2: ────────────■────────────
qr0 = QuantumRegister(3, "q0")
qr1 = QuantumRegister(3, "q1")
circuit = QuantumCircuit(qr0, qr1)
circuit.cx(qr1[0], qr0[0])
circuit.cx(qr0[1], qr0[0])
circuit.cx(qr1[2], qr0[0])
circuit.x(qr0[2])
circuit.cx(qr0[2], qr0[0])
circuit.x(qr1[1])
circuit.cx(qr1[1], qr0[0])
dag = circuit_to_dag(circuit)
target = FakeAlmadenV2().target
pass_ = SabreLayout(target, seed=0, swap_trials=32, layout_trials=32)
pass_.run(dag)
layout = pass_.property_set["layout"]
self.assertEqual([layout[q] for q in circuit.qubits], [7, 8, 12, 6, 11, 13])
def test_layout_with_classical_bits(self):
"""Test sabre layout with classical bits recreate from issue #8635."""
qc = QuantumCircuit.from_qasm_str(
"""
OPENQASM 2.0;
include "qelib1.inc";
qreg q4833[1];
qreg q4834[6];
qreg q4835[7];
creg c982[2];
creg c983[2];
creg c984[2];
rzz(0) q4833[0],q4834[4];
cu(0,-6.1035156e-05,0,1e-05) q4834[1],q4835[2];
swap q4834[0],q4834[2];
cu(-1.1920929e-07,0,-0.33333333,0) q4833[0],q4834[2];
ccx q4835[2],q4834[5],q4835[4];
measure q4835[4] -> c984[0];
ccx q4835[2],q4835[5],q4833[0];
measure q4835[5] -> c984[1];
measure q4834[0] -> c982[1];
u(10*pi,0,1.9) q4834[5];
measure q4834[3] -> c984[1];
measure q4835[0] -> c982[0];
rz(0) q4835[1];
"""
)
res = transpile(qc, FakeKolkata(), layout_method="sabre", seed_transpiler=1234)
self.assertIsInstance(res, QuantumCircuit)
layout = res._layout.initial_layout
self.assertEqual(
[layout[q] for q in qc.qubits], [13, 10, 11, 12, 17, 14, 22, 26, 5, 16, 25, 19, 7, 8]
)
# pylint: disable=line-too-long
def test_layout_many_search_trials(self):
"""Test recreate failure from randomized testing that overflowed."""
qc = QuantumCircuit.from_qasm_str(
"""
OPENQASM 2.0;
include "qelib1.inc";
qreg q18585[14];
creg c1423[5];
creg c1424[4];
creg c1425[3];
barrier q18585[4],q18585[5],q18585[12],q18585[1];
cz q18585[11],q18585[3];
cswap q18585[8],q18585[10],q18585[6];
u(-2.00001,6.1035156e-05,-1.9) q18585[2];
barrier q18585[3],q18585[6],q18585[5],q18585[8],q18585[10],q18585[9],q18585[11],q18585[2],q18585[12],q18585[7],q18585[13],q18585[4],q18585[0],q18585[1];
cp(0) q18585[2],q18585[4];
cu(-0.99999,0,0,0) q18585[7],q18585[1];
cu(0,0,0,2.1507119) q18585[6],q18585[3];
barrier q18585[13],q18585[0],q18585[12],q18585[3],q18585[2],q18585[10];
ry(-1.1044662) q18585[13];
barrier q18585[13];
id q18585[12];
barrier q18585[12],q18585[6];
cu(-1.9,1.9,-1.5,0) q18585[10],q18585[0];
barrier q18585[13];
id q18585[8];
barrier q18585[12];
barrier q18585[12],q18585[1],q18585[9];
sdg q18585[2];
rz(-10*pi) q18585[6];
u(0,27.566433,1.9) q18585[1];
barrier q18585[12],q18585[11],q18585[9],q18585[4],q18585[7],q18585[0],q18585[13],q18585[3];
cu(-0.99999,-5.9604645e-08,-0.5,2.00001) q18585[3],q18585[13];
rx(-5.9604645e-08) q18585[7];
p(1.1) q18585[13];
barrier q18585[12],q18585[13],q18585[10],q18585[9],q18585[7],q18585[4];
z q18585[10];
measure q18585[7] -> c1423[2];
barrier q18585[0],q18585[3],q18585[7],q18585[4],q18585[1],q18585[8],q18585[6],q18585[11],q18585[5];
barrier q18585[5],q18585[2],q18585[8],q18585[3],q18585[6];
"""
)
res = transpile(
qc,
FakeMontreal(),
layout_method="sabre",
routing_method="stochastic",
seed_transpiler=12345,
)
self.assertIsInstance(res, QuantumCircuit)
layout = res._layout.initial_layout
self.assertEqual(
[layout[q] for q in qc.qubits], [7, 19, 14, 18, 10, 6, 12, 16, 13, 20, 15, 21, 1, 17]
)
class TestDisjointDeviceSabreLayout(QiskitTestCase):
"""Test SabreLayout with a disjoint coupling map."""
def setUp(self):
super().setUp()
self.dual_grid_cmap = CouplingMap(
[[0, 1], [0, 2], [1, 3], [2, 3], [4, 5], [4, 6], [5, 7], [5, 8]]
)
def test_dual_ghz(self):
"""Test a basic example with 2 circuit components and 2 cmap components."""
qc = QuantumCircuit(8, name="double dhz")
qc.h(0)
qc.cz(0, 1)
qc.cz(0, 2)
qc.h(3)
qc.cx(3, 4)
qc.cx(3, 5)
qc.cx(3, 6)
qc.cx(3, 7)
layout_routing_pass = SabreLayout(
self.dual_grid_cmap, seed=123456, swap_trials=1, layout_trials=1
)
layout_routing_pass(qc)
layout = layout_routing_pass.property_set["layout"]
self.assertEqual([layout[q] for q in qc.qubits], [3, 1, 2, 5, 4, 6, 7, 8])
def test_dual_ghz_with_wide_barrier(self):
"""Test a basic example with 2 circuit components and 2 cmap components."""
qc = QuantumCircuit(8, name="double dhz")
qc.h(0)
qc.cz(0, 1)
qc.cz(0, 2)
qc.h(3)
qc.cx(3, 4)
qc.cx(3, 5)
qc.cx(3, 6)
qc.cx(3, 7)
qc.measure_all()
layout_routing_pass = SabreLayout(
self.dual_grid_cmap, seed=123456, swap_trials=1, layout_trials=1
)
layout_routing_pass(qc)
layout = layout_routing_pass.property_set["layout"]
self.assertEqual([layout[q] for q in qc.qubits], [3, 1, 2, 5, 4, 6, 7, 8])
def test_dual_ghz_with_intermediate_barriers(self):
"""Test dual ghz circuit with intermediate barriers local to each componennt."""
qc = QuantumCircuit(8, name="double dhz")
qc.h(0)
qc.cz(0, 1)
qc.cz(0, 2)
qc.barrier(0, 1, 2)
qc.h(3)
qc.cx(3, 4)
qc.cx(3, 5)
qc.barrier(4, 5, 6)
qc.cx(3, 6)
qc.cx(3, 7)
qc.measure_all()
layout_routing_pass = SabreLayout(
self.dual_grid_cmap, seed=123456, swap_trials=1, layout_trials=1
)
layout_routing_pass(qc)
layout = layout_routing_pass.property_set["layout"]
self.assertEqual([layout[q] for q in qc.qubits], [3, 1, 2, 5, 4, 6, 7, 8])
def test_dual_ghz_with_intermediate_spanning_barriers(self):
"""Test dual ghz circuit with barrier in the middle across components."""
qc = QuantumCircuit(8, name="double dhz")
qc.h(0)
qc.cz(0, 1)
qc.cz(0, 2)
qc.barrier(0, 1, 2, 4, 5)
qc.h(3)
qc.cx(3, 4)
qc.cx(3, 5)
qc.cx(3, 6)
qc.cx(3, 7)
qc.measure_all()
layout_routing_pass = SabreLayout(
self.dual_grid_cmap, seed=123456, swap_trials=1, layout_trials=1
)
layout_routing_pass(qc)
layout = layout_routing_pass.property_set["layout"]
self.assertEqual([layout[q] for q in qc.qubits], [3, 1, 2, 5, 4, 6, 7, 8])
def test_too_large_components(self):
"""Assert trying to run a circuit with too large a connected component raises."""
qc = QuantumCircuit(8)
qc.h(0)
for i in range(1, 6):
qc.cx(0, i)
qc.h(7)
qc.cx(7, 6)
layout_routing_pass = SabreLayout(
self.dual_grid_cmap, seed=123456, swap_trials=1, layout_trials=1
)
with self.assertRaises(TranspilerError):
layout_routing_pass(qc)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the Sabre Swap pass"""
import unittest
import itertools
import ddt
import numpy.random
from qiskit.circuit import Clbit, ControlFlowOp, Qubit
from qiskit.circuit.library import CCXGate, HGate, Measure, SwapGate
from qiskit.circuit.classical import expr
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 FakeMumbai, FakeMumbaiV2
from qiskit.transpiler.passes import SabreSwap, TrivialLayout, CheckMap
from qiskit.transpiler import CouplingMap, Layout, PassManager, Target, TranspilerError
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
from qiskit.test import QiskitTestCase
from qiskit.test._canonical import canonicalize_control_flow
from qiskit.utils import optionals
def looping_circuit(uphill_swaps=1, additional_local_minimum_gates=0):
"""A circuit that causes SabreSwap to loop infinitely.
This looks like (using cz gates to show the symmetry, though we actually output cx for testing
purposes):
.. parsed-literal::
q_0: ─■────────────────
│
q_1: ─┼──■─────────────
│ │
q_2: ─┼──┼──■──────────
│ │ │
q_3: ─┼──┼──┼──■───────
│ │ │ │
q_4: ─┼──┼──┼──┼─────■─
│ │ │ │ │
q_5: ─┼──┼──┼──┼──■──■─
│ │ │ │ │
q_6: ─┼──┼──┼──┼──┼────
│ │ │ │ │
q_7: ─┼──┼──┼──┼──■──■─
│ │ │ │ │
q_8: ─┼──┼──┼──┼─────■─
│ │ │ │
q_9: ─┼──┼──┼──■───────
│ │ │
q_10: ─┼──┼──■──────────
│ │
q_11: ─┼──■─────────────
│
q_12: ─■────────────────
where `uphill_swaps` is the number of qubits separating the inner-most gate (representing how
many swaps need to be made that all increase the heuristics), and
`additional_local_minimum_gates` is how many extra gates to add on the outside (these increase
the size of the region of stability).
"""
outers = 4 + additional_local_minimum_gates
n_qubits = 2 * outers + 4 + uphill_swaps
# This is (most of) the front layer, which is a bunch of outer qubits in the
# coupling map.
outer_pairs = [(i, n_qubits - i - 1) for i in range(outers)]
inner_heuristic_peak = [
# This gate is completely "inside" all the others in the front layer in
# terms of the coupling map, so it's the only one that we can in theory
# make progress towards without making the others worse.
(outers + 1, outers + 2 + uphill_swaps),
# These are the only two gates in the extended set, and they both get
# further apart if you make a swap to bring the above gate closer
# together, which is the trick that creates the "heuristic hill".
(outers, outers + 1),
(outers + 2 + uphill_swaps, outers + 3 + uphill_swaps),
]
qc = QuantumCircuit(n_qubits)
for pair in outer_pairs + inner_heuristic_peak:
qc.cx(*pair)
return qc
@ddt.ddt
class TestSabreSwap(QiskitTestCase):
"""Tests the SabreSwap pass."""
def test_trivial_case(self):
"""Test that an already mapped circuit is unchanged.
┌───┐┌───┐
q_0: ──■──┤ H ├┤ X ├──■──
┌─┴─┐└───┘└─┬─┘ │
q_1: ┤ X ├──■────■────┼──
└───┘┌─┴─┐ │
q_2: ──■──┤ X ├───────┼──
┌─┴─┐├───┤ │
q_3: ┤ X ├┤ X ├───────┼──
└───┘└─┬─┘ ┌─┴─┐
q_4: ───────■───────┤ X ├
└───┘
"""
coupling = CouplingMap.from_ring(5)
qr = QuantumRegister(5, "q")
qc = QuantumCircuit(qr)
qc.cx(0, 1) # free
qc.cx(2, 3) # free
qc.h(0) # free
qc.cx(1, 2) # F
qc.cx(1, 0)
qc.cx(4, 3) # F
qc.cx(0, 4)
passmanager = PassManager(SabreSwap(coupling, "basic"))
new_qc = passmanager.run(qc)
self.assertEqual(new_qc, qc)
def test_trivial_with_target(self):
"""Test that an already mapped circuit is unchanged with target."""
coupling = CouplingMap.from_ring(5)
target = Target(num_qubits=5)
target.add_instruction(SwapGate(), {edge: None for edge in coupling.get_edges()})
qr = QuantumRegister(5, "q")
qc = QuantumCircuit(qr)
qc.cx(0, 1) # free
qc.cx(2, 3) # free
qc.h(0) # free
qc.cx(1, 2) # F
qc.cx(1, 0)
qc.cx(4, 3) # F
qc.cx(0, 4)
passmanager = PassManager(SabreSwap(target, "basic"))
new_qc = passmanager.run(qc)
self.assertEqual(new_qc, qc)
def test_lookahead_mode(self):
"""Test lookahead mode's lookahead finds single SWAP gate.
┌───┐
q_0: ──■──┤ H ├───────────────
┌─┴─┐└───┘
q_1: ┤ X ├──■────■─────────■──
└───┘┌─┴─┐ │ │
q_2: ──■──┤ X ├──┼────■────┼──
┌─┴─┐└───┘┌─┴─┐┌─┴─┐┌─┴─┐
q_3: ┤ X ├─────┤ X ├┤ X ├┤ X ├
└───┘ └───┘└───┘└───┘
q_4: ─────────────────────────
"""
coupling = CouplingMap.from_line(5)
qr = QuantumRegister(5, "q")
qc = QuantumCircuit(qr)
qc.cx(0, 1) # free
qc.cx(2, 3) # free
qc.h(0) # free
qc.cx(1, 2) # free
qc.cx(1, 3) # F
qc.cx(2, 3) # E
qc.cx(1, 3) # E
pm = PassManager(SabreSwap(coupling, "lookahead"))
new_qc = pm.run(qc)
self.assertEqual(new_qc.num_nonlocal_gates(), 7)
def test_do_not_change_cm(self):
"""Coupling map should not change.
See https://github.com/Qiskit/qiskit-terra/issues/5675"""
cm_edges = [(1, 0), (2, 0), (2, 1), (3, 2), (3, 4), (4, 2)]
coupling = CouplingMap(cm_edges)
passmanager = PassManager(SabreSwap(coupling))
_ = passmanager.run(QuantumCircuit(coupling.size()))
self.assertEqual(set(cm_edges), set(coupling.get_edges()))
def test_do_not_reorder_measurements(self):
"""Test that SabreSwap doesn't reorder measurements to the same classical bit.
With the particular coupling map used in this test and the 3q ccx gate, the routing would
invariably the measurements if the classical successors are not accurately tracked.
Regression test of gh-7950."""
coupling = CouplingMap([(0, 2), (2, 0), (1, 2), (2, 1)])
qc = QuantumCircuit(3, 1)
qc.compose(CCXGate().definition, [0, 1, 2], []) # Unroll CCX to 2q operations.
qc.h(0)
qc.barrier()
qc.measure(0, 0) # This measure is 50/50 between the Z states.
qc.measure(1, 0) # This measure always overwrites with 0.
passmanager = PassManager(SabreSwap(coupling))
transpiled = passmanager.run(qc)
last_h = transpiled.data[-4]
self.assertIsInstance(last_h.operation, HGate)
first_measure = transpiled.data[-2]
second_measure = transpiled.data[-1]
self.assertIsInstance(first_measure.operation, Measure)
self.assertIsInstance(second_measure.operation, Measure)
# Assert that the first measure is on the same qubit that the HGate was applied to, and the
# second measurement is on a different qubit (though we don't care which exactly - that
# depends a little on the randomisation of the pass).
self.assertEqual(last_h.qubits, first_measure.qubits)
self.assertNotEqual(last_h.qubits, second_measure.qubits)
# The 'basic' method can't get stuck in the same way.
@ddt.data("lookahead", "decay")
def test_no_infinite_loop(self, method):
"""Test that the 'release value' mechanisms allow SabreSwap to make progress even on
circuits that get stuck in a stable local minimum of the lookahead parameters."""
qc = looping_circuit(3, 1)
qc.measure_all()
coupling_map = CouplingMap.from_line(qc.num_qubits)
routing_pass = PassManager(SabreSwap(coupling_map, method))
n_swap_gates = 0
def leak_number_of_swaps(cls, *args, **kwargs):
nonlocal n_swap_gates
n_swap_gates += 1
if n_swap_gates > 1_000:
raise Exception("SabreSwap seems to be stuck in a loop")
# pylint: disable=bad-super-call
return super(SwapGate, cls).__new__(cls, *args, **kwargs)
with unittest.mock.patch.object(SwapGate, "__new__", leak_number_of_swaps):
routed = routing_pass.run(qc)
routed_ops = routed.count_ops()
del routed_ops["swap"]
self.assertEqual(routed_ops, qc.count_ops())
couplings = {
tuple(routed.find_bit(bit).index for bit in instruction.qubits)
for instruction in routed.data
if len(instruction.qubits) == 2
}
# Asserting equality to the empty set gives better errors on failure than asserting that
# `couplings <= coupling_map`.
self.assertEqual(couplings - set(coupling_map.get_edges()), set())
# 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
from qiskit import Aer
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):
"""Test that :class:`.SabreSwap` correctly accounts for classical conditions in its
reckoning on whether a node is resolved or not. If it is not handled correctly, the second
gate might not appear in the output.
Regression test of gh-8040."""
with self.subTest("1 bit in register"):
qc = QuantumCircuit(2, 1)
qc.z(0)
qc.z(0).c_if(qc.cregs[0], 0)
cm = CouplingMap([(0, 1), (1, 0)])
expected = PassManager([TrivialLayout(cm)]).run(qc)
actual = PassManager([TrivialLayout(cm), SabreSwap(cm)]).run(qc)
self.assertEqual(expected, actual)
with self.subTest("multiple registers"):
cregs = [ClassicalRegister(3), ClassicalRegister(4)]
qc = QuantumCircuit(QuantumRegister(2, name="q"), *cregs)
qc.z(0)
qc.z(0).c_if(cregs[0], 0)
qc.z(0).c_if(cregs[1], 0)
cm = CouplingMap([(0, 1), (1, 0)])
expected = PassManager([TrivialLayout(cm)]).run(qc)
actual = PassManager([TrivialLayout(cm), SabreSwap(cm)]).run(qc)
self.assertEqual(expected, actual)
def test_classical_condition_cargs(self):
"""Test that classical conditions are preserved even if missing from cargs DAGNode field.
Created from reproduction in https://github.com/Qiskit/qiskit-terra/issues/8675
"""
with self.subTest("missing measurement"):
qc = QuantumCircuit(3, 1)
qc.cx(0, 2).c_if(0, 0)
qc.measure(1, 0)
qc.h(2).c_if(0, 0)
expected = QuantumCircuit(3, 1)
expected.swap(1, 2)
expected.cx(0, 1).c_if(0, 0)
expected.measure(2, 0)
expected.h(1).c_if(0, 0)
result = SabreSwap(CouplingMap.from_line(3), seed=12345)(qc)
self.assertEqual(result, expected)
with self.subTest("reordered measurement"):
qc = QuantumCircuit(3, 1)
qc.cx(0, 1).c_if(0, 0)
qc.measure(1, 0)
qc.h(0).c_if(0, 0)
expected = QuantumCircuit(3, 1)
expected.cx(0, 1).c_if(0, 0)
expected.measure(1, 0)
expected.h(0).c_if(0, 0)
result = SabreSwap(CouplingMap.from_line(3), seed=12345)(qc)
self.assertEqual(result, expected)
def test_conditional_measurement(self):
"""Test that instructions with cargs and conditions are handled correctly."""
qc = QuantumCircuit(3, 2)
qc.cx(0, 2).c_if(0, 0)
qc.measure(2, 0).c_if(1, 0)
qc.h(2).c_if(0, 0)
qc.measure(1, 1)
expected = QuantumCircuit(3, 2)
expected.swap(1, 2)
expected.cx(0, 1).c_if(0, 0)
expected.measure(1, 0).c_if(1, 0)
expected.h(1).c_if(0, 0)
expected.measure(2, 1)
result = SabreSwap(CouplingMap.from_line(3), seed=12345)(qc)
self.assertEqual(result, expected)
@ddt.data("basic", "lookahead", "decay")
def test_deterministic(self, heuristic):
"""Test that the output of the SabreSwap pass is deterministic for a given random seed."""
width = 40
# The actual circuit is unimportant, we just need one with lots of scoring degeneracy.
qc = QuantumCircuit(width)
for i in range(width // 2):
qc.cx(i, i + (width // 2))
for i in range(0, width, 2):
qc.cx(i, i + 1)
dag = circuit_to_dag(qc)
coupling = CouplingMap.from_line(width)
pass_0 = SabreSwap(coupling, heuristic, seed=0, trials=1)
pass_1 = SabreSwap(coupling, heuristic, seed=1, trials=1)
dag_0 = pass_0.run(dag)
dag_1 = pass_1.run(dag)
# This deliberately avoids using a topological order, because that introduces an opportunity
# for the re-ordering to sort the swaps back into a canonical order.
def normalize_nodes(dag):
return [(node.op.name, node.qargs, node.cargs) for node in dag.op_nodes()]
# A sanity check for the test - if unequal seeds don't produce different outputs for this
# degenerate circuit, then the test probably needs fixing (or Sabre is ignoring the seed).
self.assertNotEqual(normalize_nodes(dag_0), normalize_nodes(dag_1))
# Check that a re-run with the same seed produces the same circuit in the exact same order.
self.assertEqual(normalize_nodes(dag_0), normalize_nodes(pass_0.run(dag)))
def test_rejects_too_many_qubits(self):
"""Test that a sensible Python-space error message is emitted if the DAG has an incorrect
number of qubits."""
pass_ = SabreSwap(CouplingMap.from_line(4))
qc = QuantumCircuit(QuantumRegister(5, "q"))
with self.assertRaisesRegex(TranspilerError, "More qubits in the circuit"):
pass_(qc)
def test_rejects_too_few_qubits(self):
"""Test that a sensible Python-space error message is emitted if the DAG has an incorrect
number of qubits."""
pass_ = SabreSwap(CouplingMap.from_line(4))
qc = QuantumCircuit(QuantumRegister(3, "q"))
with self.assertRaisesRegex(TranspilerError, "Fewer qubits in the circuit"):
pass_(qc)
@ddt.ddt
class TestSabreSwapControlFlow(QiskitTestCase):
"""Tests for control flow in sabre swap."""
def test_shared_block(self):
"""Test multiple control flow ops sharing the same block instance."""
inner = QuantumCircuit(2)
inner.cx(0, 1)
qreg = QuantumRegister(4, "q")
outer = QuantumCircuit(qreg, ClassicalRegister(1))
for pair in itertools.permutations(range(outer.num_qubits), 2):
outer.if_test((outer.cregs[0], 1), inner, pair, [])
coupling = CouplingMap.from_line(4)
cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(circuit_to_dag(outer))
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
def test_blocks_use_registers(self):
"""Test that control flow ops using registers still use registers after routing."""
num_qubits = 2
qreg = QuantumRegister(num_qubits, "q")
cr1 = ClassicalRegister(1)
cr2 = ClassicalRegister(1)
qc = QuantumCircuit(qreg, cr1, cr2)
with qc.if_test((cr1, False)):
qc.cx(0, 1)
qc.measure(0, cr2[0])
with qc.if_test((cr2, 0)):
qc.cx(0, 1)
coupling = CouplingMap.from_line(num_qubits)
cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(circuit_to_dag(qc))
outer_if_op = cdag.op_nodes(ControlFlowOp)[0].op
self.assertEqual(outer_if_op.condition[0], cr1)
inner_if_op = circuit_to_dag(outer_if_op.blocks[0]).op_nodes(ControlFlowOp)[0].op
self.assertEqual(inner_if_op.condition[0], cr2)
def test_pre_if_else_route(self):
"""test swap with if else controlflow construct"""
num_qubits = 5
qreg = QuantumRegister(num_qubits, "q")
creg = ClassicalRegister(num_qubits)
coupling = CouplingMap.from_line(num_qubits)
qc = QuantumCircuit(qreg, creg)
qc.h(0)
qc.cx(0, 2)
qc.measure(2, 2)
true_body = QuantumCircuit(qreg, creg[[2]])
true_body.x(3)
false_body = QuantumCircuit(qreg, creg[[2]])
false_body.x(4)
qc.if_else((creg[2], 0), true_body, false_body, qreg, creg[[2]])
qc.barrier(qreg)
qc.measure(qreg, creg)
dag = circuit_to_dag(qc)
cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
expected.h(0)
expected.swap(1, 2)
expected.cx(0, 1)
expected.measure(1, 2)
etrue_body = QuantumCircuit(qreg[[3, 4]], creg[[2]])
etrue_body.x(0)
efalse_body = QuantumCircuit(qreg[[3, 4]], creg[[2]])
efalse_body.x(1)
new_order = [0, 2, 1, 3, 4]
expected.if_else((creg[2], 0), etrue_body, efalse_body, qreg[[3, 4]], creg[[2]])
expected.barrier(qreg)
expected.measure(qreg, creg[new_order])
self.assertEqual(dag_to_circuit(cdag), expected)
def test_pre_if_else_route_post_x(self):
"""test swap with if else controlflow construct; pre-cx and post x"""
num_qubits = 5
qreg = QuantumRegister(num_qubits, "q")
creg = ClassicalRegister(num_qubits)
coupling = CouplingMap([(i, i + 1) for i in range(num_qubits - 1)])
qc = QuantumCircuit(qreg, creg)
qc.h(0)
qc.cx(0, 2)
qc.measure(2, 2)
true_body = QuantumCircuit(qreg, creg[[0]])
true_body.x(3)
false_body = QuantumCircuit(qreg, creg[[0]])
false_body.x(4)
qc.if_else((creg[2], 0), true_body, false_body, qreg, creg[[0]])
qc.x(1)
qc.barrier(qreg)
qc.measure(qreg, creg)
dag = circuit_to_dag(qc)
cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
expected.h(0)
expected.swap(1, 2)
expected.cx(0, 1)
expected.measure(1, 2)
new_order = [0, 2, 1, 3, 4]
etrue_body = QuantumCircuit(qreg[[3, 4]], creg[[0]])
etrue_body.x(0)
efalse_body = QuantumCircuit(qreg[[3, 4]], creg[[0]])
efalse_body.x(1)
expected.if_else((creg[2], 0), etrue_body, efalse_body, qreg[[3, 4]], creg[[0]])
expected.x(2)
expected.barrier(qreg)
expected.measure(qreg, creg[new_order])
self.assertEqual(dag_to_circuit(cdag), expected)
def test_post_if_else_route(self):
"""test swap with if else controlflow construct; post cx"""
num_qubits = 5
qreg = QuantumRegister(num_qubits, "q")
creg = ClassicalRegister(num_qubits)
coupling = CouplingMap([(i, i + 1) for i in range(num_qubits - 1)])
qc = QuantumCircuit(qreg, creg)
qc.h(0)
qc.measure(0, 0)
true_body = QuantumCircuit(qreg, creg[[0]])
true_body.x(3)
false_body = QuantumCircuit(qreg, creg[[0]])
false_body.x(4)
qc.barrier(qreg)
qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]])
qc.barrier(qreg)
qc.cx(0, 2)
qc.barrier(qreg)
qc.measure(qreg, creg)
dag = circuit_to_dag(qc)
cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
expected.h(0)
expected.measure(0, 0)
etrue_body = QuantumCircuit(qreg[[3, 4]], creg[[0]])
etrue_body.x(0)
efalse_body = QuantumCircuit(qreg[[3, 4]], creg[[0]])
efalse_body.x(1)
expected.barrier(qreg)
expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg[[3, 4]], creg[[0]])
expected.barrier(qreg)
expected.swap(1, 2)
expected.cx(0, 1)
expected.barrier(qreg)
expected.measure(qreg, creg[[0, 2, 1, 3, 4]])
self.assertEqual(dag_to_circuit(cdag), expected)
def test_pre_if_else2(self):
"""test swap with if else controlflow construct; cx in if statement"""
num_qubits = 5
qreg = QuantumRegister(num_qubits, "q")
creg = ClassicalRegister(num_qubits)
coupling = CouplingMap([(i, i + 1) for i in range(num_qubits - 1)])
qc = QuantumCircuit(qreg, creg)
qc.h(0)
qc.cx(0, 2)
qc.x(1)
qc.measure(0, 0)
true_body = QuantumCircuit(qreg, creg[[0]])
true_body.x(0)
false_body = QuantumCircuit(qreg, creg[[0]])
qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]])
qc.barrier(qreg)
qc.measure(qreg, creg)
dag = circuit_to_dag(qc)
cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
expected.h(0)
expected.x(1)
expected.swap(1, 2)
expected.cx(0, 1)
expected.measure(0, 0)
etrue_body = QuantumCircuit(qreg[[0]], creg[[0]])
etrue_body.x(0)
efalse_body = QuantumCircuit(qreg[[0]], creg[[0]])
new_order = [0, 2, 1, 3, 4]
expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg[[0]], creg[[0]])
expected.barrier(qreg)
expected.measure(qreg, creg[new_order])
self.assertEqual(dag_to_circuit(cdag), expected)
def test_intra_if_else_route(self):
"""test swap with if else controlflow construct"""
num_qubits = 5
qreg = QuantumRegister(num_qubits, "q")
creg = ClassicalRegister(num_qubits)
coupling = CouplingMap([(i, i + 1) for i in range(num_qubits - 1)])
qc = QuantumCircuit(qreg, creg)
qc.h(0)
qc.x(1)
qc.measure(0, 0)
true_body = QuantumCircuit(qreg, creg[[0]])
true_body.cx(0, 2)
false_body = QuantumCircuit(qreg, creg[[0]])
false_body.cx(0, 4)
qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]])
qc.measure(qreg, creg)
dag = circuit_to_dag(qc)
cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
expected.h(0)
expected.x(1)
expected.measure(0, 0)
etrue_body = QuantumCircuit(qreg, creg[[0]])
etrue_body.swap(1, 2)
etrue_body.cx(0, 1)
etrue_body.swap(1, 2)
efalse_body = QuantumCircuit(qreg, creg[[0]])
efalse_body.swap(0, 1)
efalse_body.swap(3, 4)
efalse_body.swap(2, 3)
efalse_body.cx(1, 2)
efalse_body.swap(0, 1)
efalse_body.swap(2, 3)
efalse_body.swap(3, 4)
expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg, creg[[0]])
expected.measure(qreg, creg)
self.assertEqual(dag_to_circuit(cdag), expected)
def test_pre_intra_if_else(self):
"""test swap with if else controlflow construct; cx in if statement"""
num_qubits = 5
qreg = QuantumRegister(num_qubits, "q")
creg = ClassicalRegister(num_qubits)
coupling = CouplingMap([(i, i + 1) for i in range(num_qubits - 1)])
qc = QuantumCircuit(qreg, creg)
qc.h(0)
qc.cx(0, 2)
qc.x(1)
qc.measure(0, 0)
true_body = QuantumCircuit(qreg, creg[[0]])
true_body.cx(0, 2)
false_body = QuantumCircuit(qreg, creg[[0]])
false_body.cx(0, 4)
qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]])
qc.measure(qreg, creg)
dag = circuit_to_dag(qc)
cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
etrue_body = QuantumCircuit(qreg, creg[[0]])
efalse_body = QuantumCircuit(qreg, creg[[0]])
expected.h(0)
expected.x(1)
expected.swap(1, 2)
expected.cx(0, 1)
expected.measure(0, 0)
etrue_body.cx(0, 1)
efalse_body.swap(0, 1)
efalse_body.swap(3, 4)
efalse_body.swap(2, 3)
efalse_body.cx(1, 2)
efalse_body.swap(0, 1)
efalse_body.swap(2, 3)
efalse_body.swap(3, 4)
expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg, creg[[0]])
expected.measure(qreg, creg[[0, 2, 1, 3, 4]])
self.assertEqual(dag_to_circuit(cdag), expected)
def test_pre_intra_post_if_else(self):
"""test swap with if else controlflow construct; cx before, in, and after if
statement"""
num_qubits = 5
qreg = QuantumRegister(num_qubits, "q")
creg = ClassicalRegister(num_qubits)
coupling = CouplingMap.from_line(num_qubits)
qc = QuantumCircuit(qreg, creg)
qc.h(0)
qc.cx(0, 2)
qc.x(1)
qc.measure(0, 0)
true_body = QuantumCircuit(qreg, creg[[0]])
true_body.cx(0, 2)
false_body = QuantumCircuit(qreg, creg[[0]])
false_body.cx(0, 4)
qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]])
qc.h(3)
qc.cx(3, 0)
qc.barrier()
qc.measure(qreg, creg)
dag = circuit_to_dag(qc)
cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
expected.h(0)
expected.x(1)
expected.swap(0, 1)
expected.cx(1, 2)
expected.measure(1, 0)
etrue_body = QuantumCircuit(qreg[[1, 2, 3, 4]], creg[[0]])
etrue_body.cx(0, 1)
efalse_body = QuantumCircuit(qreg[[1, 2, 3, 4]], creg[[0]])
efalse_body.swap(0, 1)
efalse_body.swap(2, 3)
efalse_body.cx(1, 2)
efalse_body.swap(0, 1)
efalse_body.swap(2, 3)
expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg[[1, 2, 3, 4]], creg[[0]])
expected.h(3)
expected.swap(1, 2)
expected.cx(3, 2)
expected.barrier()
expected.measure(qreg, creg[[1, 2, 0, 3, 4]])
self.assertEqual(dag_to_circuit(cdag), expected)
def test_if_expr(self):
"""Test simple if conditional with an `Expr` condition."""
coupling = CouplingMap.from_line(4)
body = QuantumCircuit(4)
body.cx(0, 1)
body.cx(0, 2)
body.cx(0, 3)
qc = QuantumCircuit(4, 2)
qc.if_test(expr.logic_and(qc.clbits[0], qc.clbits[1]), body, [0, 1, 2, 3], [])
dag = circuit_to_dag(qc)
cdag = SabreSwap(coupling, "lookahead", seed=58, trials=1).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
def test_if_else_expr(self):
"""Test simple if/else conditional with an `Expr` condition."""
coupling = CouplingMap.from_line(4)
true = QuantumCircuit(4)
true.cx(0, 1)
true.cx(0, 2)
true.cx(0, 3)
false = QuantumCircuit(4)
false.cx(3, 0)
false.cx(3, 1)
false.cx(3, 2)
qc = QuantumCircuit(4, 2)
qc.if_else(expr.logic_and(qc.clbits[0], qc.clbits[1]), true, false, [0, 1, 2, 3], [])
dag = circuit_to_dag(qc)
cdag = SabreSwap(coupling, "lookahead", seed=58, trials=1).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
def test_no_layout_change(self):
"""test controlflow with no layout change needed"""
num_qubits = 5
qreg = QuantumRegister(num_qubits, "q")
creg = ClassicalRegister(num_qubits)
coupling = CouplingMap.from_line(num_qubits)
qc = QuantumCircuit(qreg, creg)
qc.h(0)
qc.cx(0, 2)
qc.x(1)
qc.measure(0, 0)
true_body = QuantumCircuit(qreg, creg[[0]])
true_body.x(2)
false_body = QuantumCircuit(qreg, creg[[0]])
false_body.x(4)
qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]])
qc.barrier(qreg)
qc.measure(qreg, creg)
dag = circuit_to_dag(qc)
cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
expected.h(0)
expected.x(1)
expected.swap(1, 2)
expected.cx(0, 1)
expected.measure(0, 0)
etrue_body = QuantumCircuit(qreg[[1, 4]], creg[[0]])
etrue_body.x(0)
efalse_body = QuantumCircuit(qreg[[1, 4]], creg[[0]])
efalse_body.x(1)
expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg[[1, 4]], creg[[0]])
expected.barrier(qreg)
expected.measure(qreg, creg[[0, 2, 1, 3, 4]])
self.assertEqual(dag_to_circuit(cdag), expected)
@ddt.data(1, 2, 3)
def test_for_loop(self, nloops):
"""test stochastic swap with for_loop"""
num_qubits = 3
qreg = QuantumRegister(num_qubits, "q")
creg = ClassicalRegister(num_qubits)
coupling = CouplingMap.from_line(num_qubits)
qc = QuantumCircuit(qreg, creg)
qc.h(0)
qc.x(1)
for_body = QuantumCircuit(qreg)
for_body.cx(0, 2)
loop_parameter = None
qc.for_loop(range(nloops), loop_parameter, for_body, qreg, [])
qc.measure(qreg, creg)
dag = circuit_to_dag(qc)
cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
expected.h(0)
expected.x(1)
efor_body = QuantumCircuit(qreg)
efor_body.swap(1, 2)
efor_body.cx(0, 1)
efor_body.swap(1, 2)
loop_parameter = None
expected.for_loop(range(nloops), loop_parameter, efor_body, qreg, [])
expected.measure(qreg, creg)
self.assertEqual(dag_to_circuit(cdag), expected)
def test_while_loop(self):
"""test while loop"""
num_qubits = 4
qreg = QuantumRegister(num_qubits, "q")
creg = ClassicalRegister(len(qreg))
coupling = CouplingMap.from_line(num_qubits)
qc = QuantumCircuit(qreg, creg)
while_body = QuantumCircuit(qreg, creg)
while_body.reset(qreg[2:])
while_body.h(qreg[2:])
while_body.cx(0, 3)
while_body.measure(qreg[3], creg[3])
qc.while_loop((creg, 0), while_body, qc.qubits, qc.clbits)
qc.barrier()
qc.measure(qreg, creg)
dag = circuit_to_dag(qc)
cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
ewhile_body = QuantumCircuit(qreg, creg)
ewhile_body.reset(qreg[2:])
ewhile_body.h(qreg[2:])
ewhile_body.swap(0, 1)
ewhile_body.swap(2, 3)
ewhile_body.cx(1, 2)
ewhile_body.measure(qreg[2], creg[3])
ewhile_body.swap(1, 0)
ewhile_body.swap(3, 2)
expected.while_loop((creg, 0), ewhile_body, expected.qubits, expected.clbits)
expected.barrier()
expected.measure(qreg, creg)
self.assertEqual(dag_to_circuit(cdag), expected)
def test_while_loop_expr(self):
"""Test simple while loop with an `Expr` condition."""
coupling = CouplingMap.from_line(4)
body = QuantumCircuit(4)
body.cx(0, 1)
body.cx(0, 2)
body.cx(0, 3)
qc = QuantumCircuit(4, 2)
qc.while_loop(expr.logic_and(qc.clbits[0], qc.clbits[1]), body, [0, 1, 2, 3], [])
dag = circuit_to_dag(qc)
cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
def test_switch_implicit_carg_use(self):
"""Test that a switch statement that uses cargs only implicitly via its ``target`` attribute
and not explicitly in bodies of the cases is routed correctly, with the dependencies
fulfilled correctly."""
coupling = CouplingMap.from_line(4)
pass_ = SabreSwap(coupling, "lookahead", seed=82, trials=1)
body = QuantumCircuit([Qubit()])
body.x(0)
# If the classical wire condition isn't respected, then the switch would appear in the front
# layer and be immediately eligible for routing, which would produce invalid output.
qc = QuantumCircuit(4, 1)
qc.cx(0, 1)
qc.cx(1, 2)
qc.cx(0, 2)
qc.measure(2, 0)
qc.switch(expr.lift(qc.clbits[0]), [(False, body.copy()), (True, body.copy())], [3], [])
expected = QuantumCircuit(4, 1)
expected.cx(0, 1)
expected.cx(1, 2)
expected.swap(2, 1)
expected.cx(0, 1)
expected.measure(1, 0)
expected.switch(
expr.lift(expected.clbits[0]), [(False, body.copy()), (True, body.copy())], [3], []
)
self.assertEqual(pass_(qc), expected)
def test_switch_single_case(self):
"""Test routing of 'switch' with just a single case."""
qreg = QuantumRegister(5, "q")
creg = ClassicalRegister(3, "c")
qc = QuantumCircuit(qreg, creg)
case0 = QuantumCircuit(qreg[[0, 1, 2]], creg[:])
case0.cx(0, 1)
case0.cx(1, 2)
case0.cx(2, 0)
qc.switch(creg, [(0, case0)], qreg[[0, 1, 2]], creg)
coupling = CouplingMap.from_line(len(qreg))
pass_ = SabreSwap(coupling, "lookahead", seed=82, trials=1)
test = pass_(qc)
check = CheckMap(coupling)
check(test)
self.assertTrue(check.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
case0 = QuantumCircuit(qreg[[0, 1, 2]], creg[:])
case0.cx(0, 1)
case0.cx(1, 2)
case0.swap(0, 1)
case0.cx(2, 1)
case0.swap(0, 1)
expected.switch(creg, [(0, case0)], qreg[[0, 1, 2]], creg[:])
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
def test_switch_nonexhaustive(self):
"""Test routing of 'switch' with several but nonexhaustive cases."""
qreg = QuantumRegister(5, "q")
creg = ClassicalRegister(3, "c")
qc = QuantumCircuit(qreg, creg)
case0 = QuantumCircuit(qreg, creg[:])
case0.cx(0, 1)
case0.cx(1, 2)
case0.cx(2, 0)
case1 = QuantumCircuit(qreg, creg[:])
case1.cx(1, 2)
case1.cx(2, 3)
case1.cx(3, 1)
case2 = QuantumCircuit(qreg, creg[:])
case2.cx(2, 3)
case2.cx(3, 4)
case2.cx(4, 2)
qc.switch(creg, [(0, case0), ((1, 2), case1), (3, case2)], qreg, creg)
coupling = CouplingMap.from_line(len(qreg))
pass_ = SabreSwap(coupling, "lookahead", seed=82, trials=1)
test = pass_(qc)
check = CheckMap(coupling)
check(test)
self.assertTrue(check.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
case0 = QuantumCircuit(qreg, creg[:])
case0.cx(0, 1)
case0.cx(1, 2)
case0.swap(0, 1)
case0.cx(2, 1)
case0.swap(0, 1)
case1 = QuantumCircuit(qreg, creg[:])
case1.cx(1, 2)
case1.cx(2, 3)
case1.swap(1, 2)
case1.cx(3, 2)
case1.swap(1, 2)
case2 = QuantumCircuit(qreg, creg[:])
case2.cx(2, 3)
case2.cx(3, 4)
case2.swap(2, 3)
case2.cx(4, 3)
case2.swap(2, 3)
expected.switch(creg, [(0, case0), ((1, 2), case1), (3, case2)], qreg, creg)
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
def test_switch_expr_single_case(self):
"""Test routing of 'switch' with an `Expr` target and just a single case."""
qreg = QuantumRegister(5, "q")
creg = ClassicalRegister(3, "c")
qc = QuantumCircuit(qreg, creg)
case0 = QuantumCircuit(qreg[[0, 1, 2]], creg[:])
case0.cx(0, 1)
case0.cx(1, 2)
case0.cx(2, 0)
qc.switch(expr.bit_or(creg, 5), [(0, case0)], qreg[[0, 1, 2]], creg)
coupling = CouplingMap.from_line(len(qreg))
pass_ = SabreSwap(coupling, "lookahead", seed=82, trials=1)
test = pass_(qc)
check = CheckMap(coupling)
check(test)
self.assertTrue(check.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
case0 = QuantumCircuit(qreg[[0, 1, 2]], creg[:])
case0.cx(0, 1)
case0.cx(1, 2)
case0.swap(0, 1)
case0.cx(2, 1)
case0.swap(0, 1)
expected.switch(expr.bit_or(creg, 5), [(0, case0)], qreg[[0, 1, 2]], creg[:])
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
def test_switch_expr_nonexhaustive(self):
"""Test routing of 'switch' with an `Expr` target and several but nonexhaustive cases."""
qreg = QuantumRegister(5, "q")
creg = ClassicalRegister(3, "c")
qc = QuantumCircuit(qreg, creg)
case0 = QuantumCircuit(qreg, creg[:])
case0.cx(0, 1)
case0.cx(1, 2)
case0.cx(2, 0)
case1 = QuantumCircuit(qreg, creg[:])
case1.cx(1, 2)
case1.cx(2, 3)
case1.cx(3, 1)
case2 = QuantumCircuit(qreg, creg[:])
case2.cx(2, 3)
case2.cx(3, 4)
case2.cx(4, 2)
qc.switch(expr.bit_or(creg, 5), [(0, case0), ((1, 2), case1), (3, case2)], qreg, creg)
coupling = CouplingMap.from_line(len(qreg))
pass_ = SabreSwap(coupling, "lookahead", seed=82, trials=1)
test = pass_(qc)
check = CheckMap(coupling)
check(test)
self.assertTrue(check.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
case0 = QuantumCircuit(qreg, creg[:])
case0.cx(0, 1)
case0.cx(1, 2)
case0.swap(0, 1)
case0.cx(2, 1)
case0.swap(0, 1)
case1 = QuantumCircuit(qreg, creg[:])
case1.cx(1, 2)
case1.cx(2, 3)
case1.swap(1, 2)
case1.cx(3, 2)
case1.swap(1, 2)
case2 = QuantumCircuit(qreg, creg[:])
case2.cx(2, 3)
case2.cx(3, 4)
case2.swap(2, 3)
case2.cx(4, 3)
case2.swap(2, 3)
expected.switch(expr.bit_or(creg, 5), [(0, case0), ((1, 2), case1), (3, case2)], qreg, creg)
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
def test_nested_inner_cnot(self):
"""test swap in nested if else controlflow construct; swap in inner"""
num_qubits = 3
qreg = QuantumRegister(num_qubits, "q")
creg = ClassicalRegister(num_qubits)
coupling = CouplingMap.from_line(num_qubits)
qc = QuantumCircuit(qreg, creg)
qc.h(0)
qc.x(1)
qc.measure(0, 0)
true_body = QuantumCircuit(qreg, creg[[0]])
true_body.x(0)
for_body = QuantumCircuit(qreg)
for_body.delay(10, 0)
for_body.barrier(qreg)
for_body.cx(0, 2)
loop_parameter = None
true_body.for_loop(range(3), loop_parameter, for_body, qreg, [])
false_body = QuantumCircuit(qreg, creg[[0]])
false_body.y(0)
qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]])
qc.measure(qreg, creg)
dag = circuit_to_dag(qc)
cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
expected.h(0)
expected.x(1)
expected.measure(0, 0)
etrue_body = QuantumCircuit(qreg, creg[[0]])
etrue_body.x(0)
efor_body = QuantumCircuit(qreg)
efor_body.delay(10, 0)
efor_body.barrier(qreg)
efor_body.swap(1, 2)
efor_body.cx(0, 1)
efor_body.swap(1, 2)
etrue_body.for_loop(range(3), loop_parameter, efor_body, qreg, [])
efalse_body = QuantumCircuit(qreg, creg[[0]])
efalse_body.y(0)
expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg, creg[[0]])
expected.measure(qreg, creg)
self.assertEqual(dag_to_circuit(cdag), expected)
def test_nested_outer_cnot(self):
"""test swap with nested if else controlflow construct; swap in outer"""
num_qubits = 5
qreg = QuantumRegister(num_qubits, "q")
creg = ClassicalRegister(num_qubits)
coupling = CouplingMap.from_line(num_qubits)
qc = QuantumCircuit(qreg, creg)
qc.h(0)
qc.x(1)
qc.measure(0, 0)
true_body = QuantumCircuit(qreg, creg[[0]])
true_body.cx(0, 2)
true_body.x(0)
for_body = QuantumCircuit(qreg)
for_body.delay(10, 0)
for_body.barrier(qreg)
for_body.cx(1, 3)
loop_parameter = None
true_body.for_loop(range(3), loop_parameter, for_body, qreg, [])
false_body = QuantumCircuit(qreg, creg[[0]])
false_body.y(0)
qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]])
qc.measure(qreg, creg)
dag = circuit_to_dag(qc)
cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
expected.h(0)
expected.x(1)
expected.measure(0, 0)
etrue_body = QuantumCircuit(qreg, creg[[0]])
etrue_body.swap(1, 2)
etrue_body.cx(0, 1)
etrue_body.x(0)
efor_body = QuantumCircuit(qreg)
efor_body.delay(10, 0)
efor_body.barrier(qreg)
efor_body.cx(2, 3)
etrue_body.for_loop(range(3), loop_parameter, efor_body, qreg[[0, 1, 2, 3, 4]], [])
etrue_body.swap(1, 2)
efalse_body = QuantumCircuit(qreg, creg[[0]])
efalse_body.y(0)
expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg, creg[[0]])
expected.measure(qreg, creg[[0, 1, 2, 3, 4]])
self.assertEqual(dag_to_circuit(cdag), expected)
def test_disjoint_looping(self):
"""Test looping controlflow on different qubit register"""
num_qubits = 4
cm = CouplingMap.from_line(num_qubits)
qr = QuantumRegister(num_qubits, "q")
qc = QuantumCircuit(qr)
loop_body = QuantumCircuit(2)
loop_body.cx(0, 1)
qc.for_loop((0,), None, loop_body, [0, 2], [])
cqc = SabreSwap(cm, "lookahead", seed=82, trials=1)(qc)
expected = QuantumCircuit(qr)
efor_body = QuantumCircuit(qr[[0, 1, 2]])
efor_body.swap(1, 2)
efor_body.cx(0, 1)
efor_body.swap(1, 2)
expected.for_loop((0,), None, efor_body, [0, 1, 2], [])
self.assertEqual(cqc, expected)
def test_disjoint_multiblock(self):
"""Test looping controlflow on different qubit register"""
num_qubits = 4
cm = CouplingMap.from_line(num_qubits)
qr = QuantumRegister(num_qubits, "q")
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
true_body = QuantumCircuit(qr[0:3] + cr[:])
true_body.cx(0, 1)
false_body = QuantumCircuit(qr[0:3] + cr[:])
false_body.cx(0, 2)
qc.if_else((cr[0], 1), true_body, false_body, [0, 1, 2], [0])
cqc = SabreSwap(cm, "lookahead", seed=82, trials=1)(qc)
expected = QuantumCircuit(qr, cr)
etrue_body = QuantumCircuit(qr[[0, 1, 2]], cr[[0]])
etrue_body.cx(0, 1)
efalse_body = QuantumCircuit(qr[[0, 1, 2]], cr[[0]])
efalse_body.swap(1, 2)
efalse_body.cx(0, 1)
efalse_body.swap(1, 2)
expected.if_else((cr[0], 1), etrue_body, efalse_body, [0, 1, 2], cr[[0]])
self.assertEqual(cqc, expected)
def test_multiple_ops_per_layer(self):
"""Test circuits with multiple operations per layer"""
num_qubits = 6
coupling = CouplingMap.from_line(num_qubits)
check_map_pass = CheckMap(coupling)
qr = QuantumRegister(num_qubits, "q")
qc = QuantumCircuit(qr)
# This cx and the for_loop are in the same layer.
qc.cx(0, 2)
with qc.for_loop((0,)):
qc.cx(3, 5)
cqc = SabreSwap(coupling, "lookahead", seed=82, trials=1)(qc)
check_map_pass(cqc)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qr)
expected.swap(1, 2)
expected.cx(0, 1)
efor_body = QuantumCircuit(qr[[3, 4, 5]])
efor_body.swap(1, 2)
efor_body.cx(0, 1)
efor_body.swap(2, 1)
expected.for_loop((0,), None, efor_body, [3, 4, 5], [])
self.assertEqual(cqc, expected)
def test_if_no_else_restores_layout(self):
"""Test that an if block with no else branch restores the initial layout."""
qc = QuantumCircuit(8, 1)
with qc.if_test((qc.clbits[0], False)):
# Just some arbitrary gates with no perfect layout.
qc.cx(3, 5)
qc.cx(4, 6)
qc.cx(1, 4)
qc.cx(7, 4)
qc.cx(0, 5)
qc.cx(7, 3)
qc.cx(1, 3)
qc.cx(5, 2)
qc.cx(6, 7)
qc.cx(3, 2)
qc.cx(6, 2)
qc.cx(2, 0)
qc.cx(7, 6)
coupling = CouplingMap.from_line(8)
pass_ = SabreSwap(coupling, "lookahead", seed=82, trials=1)
transpiled = pass_(qc)
# Check the pass claims to have done things right.
initial_layout = Layout.generate_trivial_layout(*qc.qubits)
self.assertEqual(initial_layout, pass_.property_set["final_layout"])
# Check that pass really did do it right.
inner_block = transpiled.data[0].operation.blocks[0]
running_layout = initial_layout.copy()
for instruction in inner_block:
if instruction.operation.name == "swap":
running_layout.swap(*instruction.qubits)
self.assertEqual(initial_layout, running_layout)
@ddt.ddt
class TestSabreSwapRandomCircuitValidOutput(QiskitTestCase):
"""Assert the output of a transpilation with stochastic swap is a physical circuit."""
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.backend = FakeMumbai()
cls.coupling_edge_set = {tuple(x) for x in cls.backend.configuration().coupling_map}
cls.basis_gates = set(cls.backend.configuration().basis_gates)
cls.basis_gates.update(["for_loop", "while_loop", "if_else"])
def assert_valid_circuit(self, transpiled):
"""Assert circuit complies with constraints of backend."""
self.assertIsInstance(transpiled, QuantumCircuit)
self.assertIsNotNone(getattr(transpiled, "_layout", None))
def _visit_block(circuit, qubit_mapping=None):
for instruction in circuit:
if instruction.operation.name in {"barrier", "measure"}:
continue
self.assertIn(instruction.operation.name, self.basis_gates)
qargs = tuple(qubit_mapping[x] for x in instruction.qubits)
if not isinstance(instruction.operation, ControlFlowOp):
if len(qargs) > 2 or len(qargs) < 0:
raise Exception("Invalid number of qargs for instruction")
if len(qargs) == 2:
self.assertIn(qargs, self.coupling_edge_set)
else:
self.assertLessEqual(qargs[0], 26)
else:
for block in instruction.operation.blocks:
self.assertEqual(block.num_qubits, len(instruction.qubits))
self.assertEqual(block.num_clbits, len(instruction.clbits))
new_mapping = {
inner: qubit_mapping[outer]
for outer, inner in zip(instruction.qubits, block.qubits)
}
_visit_block(block, new_mapping)
# Assert routing ran.
_visit_block(
transpiled,
qubit_mapping={qubit: index for index, qubit in enumerate(transpiled.qubits)},
)
@ddt.data(*range(1, 27))
def test_random_circuit_no_control_flow(self, size):
"""Test that transpiled random circuits without control flow are physical circuits."""
circuit = random_circuit(size, 3, measure=True, seed=12342)
tqc = transpile(
circuit,
self.backend,
routing_method="sabre",
layout_method="sabre",
seed_transpiler=12342,
)
self.assert_valid_circuit(tqc)
@ddt.data(*range(1, 27))
def test_random_circuit_no_control_flow_target(self, size):
"""Test that transpiled random circuits without control flow are physical circuits."""
circuit = random_circuit(size, 3, measure=True, seed=12342)
tqc = transpile(
circuit,
routing_method="sabre",
layout_method="sabre",
seed_transpiler=12342,
target=FakeMumbaiV2().target,
)
self.assert_valid_circuit(tqc)
@ddt.data(*range(4, 27))
def test_random_circuit_for_loop(self, size):
"""Test that transpiled random circuits with nested for loops are physical circuits."""
circuit = random_circuit(size, 3, measure=False, seed=12342)
for_block = random_circuit(3, 2, measure=False, seed=12342)
inner_for_block = random_circuit(2, 1, measure=False, seed=12342)
with circuit.for_loop((1,)):
with circuit.for_loop((1,)):
circuit.append(inner_for_block, [0, 3])
circuit.append(for_block, [1, 0, 2])
circuit.measure_all()
tqc = transpile(
circuit,
self.backend,
basis_gates=list(self.basis_gates),
routing_method="sabre",
layout_method="sabre",
seed_transpiler=12342,
)
self.assert_valid_circuit(tqc)
@ddt.data(*range(6, 27))
def test_random_circuit_if_else(self, size):
"""Test that transpiled random circuits with if else blocks are physical circuits."""
circuit = random_circuit(size, 3, measure=True, seed=12342)
if_block = random_circuit(3, 2, measure=True, seed=12342)
else_block = random_circuit(2, 1, measure=True, seed=12342)
rng = numpy.random.default_rng(seed=12342)
inner_clbit_count = max((if_block.num_clbits, else_block.num_clbits))
if inner_clbit_count > circuit.num_clbits:
circuit.add_bits([Clbit() for _ in [None] * (inner_clbit_count - circuit.num_clbits)])
clbit_indices = list(range(circuit.num_clbits))
rng.shuffle(clbit_indices)
with circuit.if_test((circuit.clbits[0], True)) as else_:
circuit.append(if_block, [0, 2, 1], clbit_indices[: if_block.num_clbits])
with else_:
circuit.append(else_block, [2, 5], clbit_indices[: else_block.num_clbits])
tqc = transpile(
circuit,
self.backend,
basis_gates=list(self.basis_gates),
routing_method="sabre",
layout_method="sabre",
seed_transpiler=12342,
)
self.assert_valid_circuit(tqc)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the Scheduling/PadDelay passes"""
import unittest
from ddt import ddt, data, unpack
from qiskit import QuantumCircuit
from qiskit.circuit import Measure
from qiskit.circuit.library import CXGate, HGate
from qiskit.pulse import Schedule, Play, Constant, DriveChannel
from qiskit.test import QiskitTestCase
from qiskit.transpiler.instruction_durations import InstructionDurations
from qiskit.transpiler.passes import (
ASAPScheduleAnalysis,
ALAPScheduleAnalysis,
PadDelay,
SetIOLatency,
)
from qiskit.transpiler.passmanager import PassManager
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.transpiler.target import Target, InstructionProperties
@ddt
class TestSchedulingAndPaddingPass(QiskitTestCase):
"""Tests the Scheduling passes"""
def test_alap_agree_with_reverse_asap_reverse(self):
"""Test if ALAP schedule agrees with doubly-reversed ASAP schedule."""
qc = QuantumCircuit(2)
qc.h(0)
qc.delay(500, 1)
qc.cx(0, 1)
qc.measure_all()
durations = InstructionDurations(
[("h", 0, 200), ("cx", [0, 1], 700), ("measure", None, 1000)]
)
pm = PassManager([ALAPScheduleAnalysis(durations), PadDelay()])
alap_qc = pm.run(qc)
pm = PassManager([ASAPScheduleAnalysis(durations), PadDelay()])
new_qc = pm.run(qc.reverse_ops())
new_qc = new_qc.reverse_ops()
new_qc.name = new_qc.name
self.assertEqual(alap_qc, new_qc)
def test_alap_agree_with_reverse_asap_with_target(self):
"""Test if ALAP schedule agrees with doubly-reversed ASAP schedule."""
qc = QuantumCircuit(2)
qc.h(0)
qc.delay(500, 1)
qc.cx(0, 1)
qc.measure_all()
target = Target(num_qubits=2, dt=3.5555555555555554)
target.add_instruction(HGate(), {(0,): InstructionProperties(duration=200)})
target.add_instruction(CXGate(), {(0, 1): InstructionProperties(duration=700)})
target.add_instruction(
Measure(),
{
(0,): InstructionProperties(duration=1000),
(1,): InstructionProperties(duration=1000),
},
)
pm = PassManager([ALAPScheduleAnalysis(target=target), PadDelay()])
alap_qc = pm.run(qc)
pm = PassManager([ASAPScheduleAnalysis(target=target), PadDelay()])
new_qc = pm.run(qc.reverse_ops())
new_qc = new_qc.reverse_ops()
new_qc.name = new_qc.name
self.assertEqual(alap_qc, new_qc)
@data(ALAPScheduleAnalysis, ASAPScheduleAnalysis)
def test_classically_controlled_gate_after_measure(self, schedule_pass):
"""Test if ALAP/ASAP schedules circuits with c_if after measure with a common clbit.
See: https://github.com/Qiskit/qiskit-terra/issues/7654
(input)
┌─┐
q_0: ┤M├───────────
└╥┘ ┌───┐
q_1: ─╫────┤ X ├───
║ └─╥─┘
║ ┌────╨────┐
c: 1/═╩═╡ c_0 = T ╞
0 └─────────┘
(scheduled)
┌─┐┌────────────────┐
q_0: ───────────────────┤M├┤ Delay(200[dt]) ├
┌─────────────────┐└╥┘└─────┬───┬──────┘
q_1: ┤ Delay(1000[dt]) ├─╫───────┤ X ├───────
└─────────────────┘ ║ └─╥─┘
║ ┌────╨────┐
c: 1/════════════════════╩════╡ c_0=0x1 ╞════
0 └─────────┘
"""
qc = QuantumCircuit(2, 1)
qc.measure(0, 0)
qc.x(1).c_if(0, True)
durations = InstructionDurations([("x", None, 200), ("measure", None, 1000)])
pm = PassManager([schedule_pass(durations), PadDelay()])
scheduled = pm.run(qc)
expected = QuantumCircuit(2, 1)
expected.measure(0, 0)
expected.delay(1000, 1) # x.c_if starts after measure
expected.x(1).c_if(0, True)
expected.delay(200, 0)
self.assertEqual(expected, scheduled)
@data(ALAPScheduleAnalysis, ASAPScheduleAnalysis)
def test_measure_after_measure(self, schedule_pass):
"""Test if ALAP/ASAP schedules circuits with measure after measure with a common clbit.
See: https://github.com/Qiskit/qiskit-terra/issues/7654
(input)
┌───┐┌─┐
q_0: ┤ X ├┤M├───
└───┘└╥┘┌─┐
q_1: ──────╫─┤M├
║ └╥┘
c: 1/══════╩══╩═
0 0
(scheduled)
┌───┐ ┌─┐┌─────────────────┐
q_0: ───────┤ X ├───────┤M├┤ Delay(1000[dt]) ├
┌──────┴───┴──────┐└╥┘└───────┬─┬───────┘
q_1: ┤ Delay(1200[dt]) ├─╫─────────┤M├────────
└─────────────────┘ ║ └╥┘
c: 1/════════════════════╩══════════╩═════════
0 0
"""
qc = QuantumCircuit(2, 1)
qc.x(0)
qc.measure(0, 0)
qc.measure(1, 0)
durations = InstructionDurations([("x", None, 200), ("measure", None, 1000)])
pm = PassManager([schedule_pass(durations), PadDelay()])
scheduled = pm.run(qc)
expected = QuantumCircuit(2, 1)
expected.x(0)
expected.measure(0, 0)
expected.delay(1200, 1)
expected.measure(1, 0)
expected.delay(1000, 0)
self.assertEqual(expected, scheduled)
@data(ALAPScheduleAnalysis, ASAPScheduleAnalysis)
def test_c_if_on_different_qubits(self, schedule_pass):
"""Test if ALAP/ASAP schedules circuits with `c_if`s on different qubits.
(input)
┌─┐
q_0: ┤M├──────────────────────
└╥┘ ┌───┐
q_1: ─╫────┤ X ├──────────────
║ └─╥─┘ ┌───┐
q_2: ─╫──────╫────────┤ X ├───
║ ║ └─╥─┘
║ ┌────╨────┐┌────╨────┐
c: 1/═╩═╡ c_0 = T ╞╡ c_0 = T ╞
0 └─────────┘└─────────┘
(scheduled)
┌─┐┌────────────────┐
q_0: ───────────────────┤M├┤ Delay(200[dt]) ├───────────
┌─────────────────┐└╥┘└─────┬───┬──────┘
q_1: ┤ Delay(1000[dt]) ├─╫───────┤ X ├──────────────────
├─────────────────┤ ║ └─╥─┘ ┌───┐
q_2: ┤ Delay(1000[dt]) ├─╫─────────╫────────────┤ X ├───
└─────────────────┘ ║ ║ └─╥─┘
║ ┌────╨────┐ ┌────╨────┐
c: 1/════════════════════╩════╡ c_0=0x1 ╞════╡ c_0=0x1 ╞
0 └─────────┘ └─────────┘
"""
qc = QuantumCircuit(3, 1)
qc.measure(0, 0)
qc.x(1).c_if(0, True)
qc.x(2).c_if(0, True)
durations = InstructionDurations([("x", None, 200), ("measure", None, 1000)])
pm = PassManager([schedule_pass(durations), PadDelay()])
scheduled = pm.run(qc)
expected = QuantumCircuit(3, 1)
expected.measure(0, 0)
expected.delay(1000, 1)
expected.delay(1000, 2)
expected.x(1).c_if(0, True)
expected.x(2).c_if(0, True)
expected.delay(200, 0)
self.assertEqual(expected, scheduled)
@data(ALAPScheduleAnalysis, ASAPScheduleAnalysis)
def test_shorter_measure_after_measure(self, schedule_pass):
"""Test if ALAP/ASAP schedules circuits with shorter measure after measure with a common clbit.
(input)
┌─┐
q_0: ┤M├───
└╥┘┌─┐
q_1: ─╫─┤M├
║ └╥┘
c: 1/═╩══╩═
0 0
(scheduled)
┌─┐┌────────────────┐
q_0: ───────────────────┤M├┤ Delay(700[dt]) ├
┌─────────────────┐└╥┘└──────┬─┬───────┘
q_1: ┤ Delay(1000[dt]) ├─╫────────┤M├────────
└─────────────────┘ ║ └╥┘
c: 1/════════════════════╩═════════╩═════════
0 0
"""
qc = QuantumCircuit(2, 1)
qc.measure(0, 0)
qc.measure(1, 0)
durations = InstructionDurations([("measure", [0], 1000), ("measure", [1], 700)])
pm = PassManager([schedule_pass(durations), PadDelay()])
scheduled = pm.run(qc)
expected = QuantumCircuit(2, 1)
expected.measure(0, 0)
expected.delay(1000, 1)
expected.measure(1, 0)
expected.delay(700, 0)
self.assertEqual(expected, scheduled)
@data(ALAPScheduleAnalysis, ASAPScheduleAnalysis)
def test_measure_after_c_if(self, schedule_pass):
"""Test if ALAP/ASAP schedules circuits with c_if after measure with a common clbit.
(input)
┌─┐
q_0: ┤M├──────────────
└╥┘ ┌───┐
q_1: ─╫────┤ X ├──────
║ └─╥─┘ ┌─┐
q_2: ─╫──────╫─────┤M├
║ ┌────╨────┐└╥┘
c: 1/═╩═╡ c_0 = T ╞═╩═
0 └─────────┘ 0
(scheduled)
┌─┐┌─────────────────┐
q_0: ───────────────────┤M├┤ Delay(1000[dt]) ├──────────────────
┌─────────────────┐└╥┘└──────┬───┬──────┘┌────────────────┐
q_1: ┤ Delay(1000[dt]) ├─╫────────┤ X ├───────┤ Delay(800[dt]) ├
├─────────────────┤ ║ └─╥─┘ └──────┬─┬───────┘
q_2: ┤ Delay(1000[dt]) ├─╫──────────╫────────────────┤M├────────
└─────────────────┘ ║ ┌────╨────┐ └╥┘
c: 1/════════════════════╩═════╡ c_0=0x1 ╞════════════╩═════════
0 └─────────┘ 0
"""
qc = QuantumCircuit(3, 1)
qc.measure(0, 0)
qc.x(1).c_if(0, 1)
qc.measure(2, 0)
durations = InstructionDurations([("x", None, 200), ("measure", None, 1000)])
pm = PassManager([schedule_pass(durations), PadDelay()])
scheduled = pm.run(qc)
expected = QuantumCircuit(3, 1)
expected.delay(1000, 1)
expected.delay(1000, 2)
expected.measure(0, 0)
expected.x(1).c_if(0, 1)
expected.measure(2, 0)
expected.delay(1000, 0)
expected.delay(800, 1)
self.assertEqual(expected, scheduled)
def test_parallel_gate_different_length(self):
"""Test circuit having two parallel instruction with different length.
(input)
┌───┐┌─┐
q_0: ┤ X ├┤M├───
├───┤└╥┘┌─┐
q_1: ┤ X ├─╫─┤M├
└───┘ ║ └╥┘
c: 2/══════╩══╩═
0 1
(expected, ALAP)
┌────────────────┐┌───┐┌─┐
q_0: ┤ Delay(200[dt]) ├┤ X ├┤M├
└─────┬───┬──────┘└┬─┬┘└╥┘
q_1: ──────┤ X ├────────┤M├──╫─
└───┘ └╥┘ ║
c: 2/════════════════════╩═══╩═
1 0
(expected, ASAP)
┌───┐┌─┐┌────────────────┐
q_0: ┤ X ├┤M├┤ Delay(200[dt]) ├
├───┤└╥┘└──────┬─┬───────┘
q_1: ┤ X ├─╫────────┤M├────────
└───┘ ║ └╥┘
c: 2/══════╩═════════╩═════════
0 1
"""
qc = QuantumCircuit(2, 2)
qc.x(0)
qc.x(1)
qc.measure(0, 0)
qc.measure(1, 1)
durations = InstructionDurations(
[("x", [0], 200), ("x", [1], 400), ("measure", None, 1000)]
)
pm = PassManager([ALAPScheduleAnalysis(durations), PadDelay()])
qc_alap = pm.run(qc)
alap_expected = QuantumCircuit(2, 2)
alap_expected.delay(200, 0)
alap_expected.x(0)
alap_expected.x(1)
alap_expected.measure(0, 0)
alap_expected.measure(1, 1)
self.assertEqual(qc_alap, alap_expected)
pm = PassManager([ASAPScheduleAnalysis(durations), PadDelay()])
qc_asap = pm.run(qc)
asap_expected = QuantumCircuit(2, 2)
asap_expected.x(0)
asap_expected.x(1)
asap_expected.measure(0, 0) # immediately start after X gate
asap_expected.measure(1, 1)
asap_expected.delay(200, 0)
self.assertEqual(qc_asap, asap_expected)
def test_parallel_gate_different_length_with_barrier(self):
"""Test circuit having two parallel instruction with different length with barrier.
(input)
┌───┐┌─┐
q_0: ┤ X ├┤M├───
├───┤└╥┘┌─┐
q_1: ┤ X ├─╫─┤M├
└───┘ ║ └╥┘
c: 2/══════╩══╩═
0 1
(expected, ALAP)
┌────────────────┐┌───┐ ░ ┌─┐
q_0: ┤ Delay(200[dt]) ├┤ X ├─░─┤M├───
└─────┬───┬──────┘└───┘ ░ └╥┘┌─┐
q_1: ──────┤ X ├─────────────░──╫─┤M├
└───┘ ░ ║ └╥┘
c: 2/═══════════════════════════╩══╩═
0 1
(expected, ASAP)
┌───┐┌────────────────┐ ░ ┌─┐
q_0: ┤ X ├┤ Delay(200[dt]) ├─░─┤M├───
├───┤└────────────────┘ ░ └╥┘┌─┐
q_1: ┤ X ├───────────────────░──╫─┤M├
└───┘ ░ ║ └╥┘
c: 2/═══════════════════════════╩══╩═
0 1
"""
qc = QuantumCircuit(2, 2)
qc.x(0)
qc.x(1)
qc.barrier()
qc.measure(0, 0)
qc.measure(1, 1)
durations = InstructionDurations(
[("x", [0], 200), ("x", [1], 400), ("measure", None, 1000)]
)
pm = PassManager([ALAPScheduleAnalysis(durations), PadDelay()])
qc_alap = pm.run(qc)
alap_expected = QuantumCircuit(2, 2)
alap_expected.delay(200, 0)
alap_expected.x(0)
alap_expected.x(1)
alap_expected.barrier()
alap_expected.measure(0, 0)
alap_expected.measure(1, 1)
self.assertEqual(qc_alap, alap_expected)
pm = PassManager([ASAPScheduleAnalysis(durations), PadDelay()])
qc_asap = pm.run(qc)
asap_expected = QuantumCircuit(2, 2)
asap_expected.x(0)
asap_expected.delay(200, 0)
asap_expected.x(1)
asap_expected.barrier()
asap_expected.measure(0, 0)
asap_expected.measure(1, 1)
self.assertEqual(qc_asap, asap_expected)
def test_measure_after_c_if_on_edge_locking(self):
"""Test if ALAP/ASAP schedules circuits with c_if after measure with a common clbit.
The scheduler is configured to reproduce behavior of the 0.20.0,
in which clbit lock is applied to the end-edge of measure instruction.
See https://github.com/Qiskit/qiskit-terra/pull/7655
(input)
┌─┐
q_0: ┤M├──────────────
└╥┘ ┌───┐
q_1: ─╫────┤ X ├──────
║ └─╥─┘ ┌─┐
q_2: ─╫──────╫─────┤M├
║ ┌────╨────┐└╥┘
c: 1/═╩═╡ c_0 = T ╞═╩═
0 └─────────┘ 0
(ASAP scheduled)
┌─┐┌────────────────┐
q_0: ───────────────────┤M├┤ Delay(200[dt]) ├─────────────────────
┌─────────────────┐└╥┘└─────┬───┬──────┘
q_1: ┤ Delay(1000[dt]) ├─╫───────┤ X ├────────────────────────────
└─────────────────┘ ║ └─╥─┘ ┌─┐┌────────────────┐
q_2: ────────────────────╫─────────╫─────────┤M├┤ Delay(200[dt]) ├
║ ┌────╨────┐ └╥┘└────────────────┘
c: 1/════════════════════╩════╡ c_0=0x1 ╞═════╩═══════════════════
0 └─────────┘ 0
(ALAP scheduled)
┌─┐┌────────────────┐
q_0: ───────────────────┤M├┤ Delay(200[dt]) ├───
┌─────────────────┐└╥┘└─────┬───┬──────┘
q_1: ┤ Delay(1000[dt]) ├─╫───────┤ X ├──────────
└┬────────────────┤ ║ └─╥─┘ ┌─┐
q_2: ─┤ Delay(200[dt]) ├─╫─────────╫─────────┤M├
└────────────────┘ ║ ┌────╨────┐ └╥┘
c: 1/════════════════════╩════╡ c_0=0x1 ╞═════╩═
0 └─────────┘ 0
"""
qc = QuantumCircuit(3, 1)
qc.measure(0, 0)
qc.x(1).c_if(0, 1)
qc.measure(2, 0)
durations = InstructionDurations([("x", None, 200), ("measure", None, 1000)])
# lock at the end edge
actual_asap = PassManager(
[
SetIOLatency(clbit_write_latency=1000),
ASAPScheduleAnalysis(durations),
PadDelay(),
]
).run(qc)
actual_alap = PassManager(
[
SetIOLatency(clbit_write_latency=1000),
ALAPScheduleAnalysis(durations),
PadDelay(),
]
).run(qc)
# start times of 2nd measure depends on ASAP/ALAP
expected_asap = QuantumCircuit(3, 1)
expected_asap.measure(0, 0)
expected_asap.delay(1000, 1)
expected_asap.x(1).c_if(0, 1)
expected_asap.measure(2, 0)
expected_asap.delay(200, 0)
expected_asap.delay(200, 2)
self.assertEqual(expected_asap, actual_asap)
expected_alap = QuantumCircuit(3, 1)
expected_alap.measure(0, 0)
expected_alap.delay(1000, 1)
expected_alap.x(1).c_if(0, 1)
expected_alap.delay(200, 2)
expected_alap.measure(2, 0)
expected_alap.delay(200, 0)
self.assertEqual(expected_alap, actual_alap)
@data([100, 200], [500, 0], [1000, 200])
@unpack
def test_active_reset_circuit(self, write_lat, cond_lat):
"""Test practical example of reset circuit.
Because of the stimulus pulse overlap with the previous XGate on the q register,
measure instruction is always triggered after XGate regardless of write latency.
Thus only conditional latency matters in the scheduling.
(input)
┌─┐ ┌───┐ ┌─┐ ┌───┐ ┌─┐ ┌───┐
q: ┤M├───┤ X ├───┤M├───┤ X ├───┤M├───┤ X ├───
└╥┘ └─╥─┘ └╥┘ └─╥─┘ └╥┘ └─╥─┘
║ ┌────╨────┐ ║ ┌────╨────┐ ║ ┌────╨────┐
c: 1/═╩═╡ c_0=0x1 ╞═╩═╡ c_0=0x1 ╞═╩═╡ c_0=0x1 ╞
0 └─────────┘ 0 └─────────┘ 0 └─────────┘
"""
qc = QuantumCircuit(1, 1)
qc.measure(0, 0)
qc.x(0).c_if(0, 1)
qc.measure(0, 0)
qc.x(0).c_if(0, 1)
qc.measure(0, 0)
qc.x(0).c_if(0, 1)
durations = InstructionDurations([("x", None, 100), ("measure", None, 1000)])
actual_asap = PassManager(
[
SetIOLatency(clbit_write_latency=write_lat, conditional_latency=cond_lat),
ASAPScheduleAnalysis(durations),
PadDelay(),
]
).run(qc)
actual_alap = PassManager(
[
SetIOLatency(clbit_write_latency=write_lat, conditional_latency=cond_lat),
ALAPScheduleAnalysis(durations),
PadDelay(),
]
).run(qc)
expected = QuantumCircuit(1, 1)
expected.measure(0, 0)
if cond_lat > 0:
expected.delay(cond_lat, 0)
expected.x(0).c_if(0, 1)
expected.measure(0, 0)
if cond_lat > 0:
expected.delay(cond_lat, 0)
expected.x(0).c_if(0, 1)
expected.measure(0, 0)
if cond_lat > 0:
expected.delay(cond_lat, 0)
expected.x(0).c_if(0, 1)
self.assertEqual(expected, actual_asap)
self.assertEqual(expected, actual_alap)
def test_random_complicated_circuit(self):
"""Test scheduling complicated circuit with control flow.
(input)
┌────────────────┐ ┌───┐ ░ ┌───┐ »
q_0: ┤ Delay(100[dt]) ├───┤ X ├────░──────────────────┤ X ├───»
└────────────────┘ └─╥─┘ ░ ┌───┐ └─╥─┘ »
q_1: ───────────────────────╫──────░───────┤ X ├────────╫─────»
║ ░ ┌─┐ └─╥─┘ ║ »
q_2: ───────────────────────╫──────░─┤M├─────╫──────────╫─────»
┌────╨────┐ ░ └╥┘┌────╨────┐┌────╨────┐»
c: 1/══════════════════╡ c_0=0x1 ╞════╩═╡ c_0=0x0 ╞╡ c_0=0x0 ╞»
└─────────┘ 0 └─────────┘└─────────┘»
« ┌────────────────┐┌───┐
«q_0: ┤ Delay(300[dt]) ├┤ X ├─────■─────
« └────────────────┘└───┘ ┌─┴─┐
«q_1: ────────■─────────────────┤ X ├───
« ┌─┴─┐ ┌─┐ └─╥─┘
«q_2: ──────┤ X ├────────┤M├──────╫─────
« └───┘ └╥┘ ┌────╨────┐
«c: 1/════════════════════╩══╡ c_0=0x0 ╞
« 0 └─────────┘
(ASAP scheduled) duration = 2800 dt
┌────────────────┐ ┌───┐ ░ ┌─────────────────┐ »
q_0: ┤ Delay(200[dt]) ├───┤ X ├────░─┤ Delay(1400[dt]) ├───────────»
├────────────────┤ └─╥─┘ ░ ├─────────────────┤ ┌───┐ »
q_1: ┤ Delay(300[dt]) ├─────╫──────░─┤ Delay(1200[dt]) ├───┤ X ├───»
├────────────────┤ ║ ░ └───────┬─┬───────┘ └─╥─┘ »
q_2: ┤ Delay(300[dt]) ├─────╫──────░─────────┤M├─────────────╫─────»
└────────────────┘┌────╨────┐ ░ └╥┘ ┌────╨────┐»
c: 1/══════════════════╡ c_0=0x1 ╞════════════╩═════════╡ c_0=0x0 ╞»
└─────────┘ 0 └─────────┘»
« ┌───┐ ┌────────────────┐ ┌───┐ »
«q_0: ─────────────────────┤ X ├───┤ Delay(300[dt]) ├──────┤ X ├───────»
« └─╥─┘ └────────────────┘┌─────┴───┴──────┐»
«q_1: ───────────────────────╫─────────────■─────────┤ Delay(400[dt]) ├»
« ┌────────────────┐ ║ ┌─┴─┐ ├────────────────┤»
«q_2: ┤ Delay(300[dt]) ├─────╫───────────┤ X ├───────┤ Delay(300[dt]) ├»
« └────────────────┘┌────╨────┐ └───┘ └────────────────┘»
«c: 1/══════════════════╡ c_0=0x0 ╞════════════════════════════════════»
« └─────────┘ »
« ┌────────────────┐
«q_0: ─────■─────┤ Delay(700[dt]) ├
« ┌─┴─┐ ├────────────────┤
«q_1: ───┤ X ├───┤ Delay(700[dt]) ├
« └─╥─┘ └──────┬─┬───────┘
«q_2: ─────╫────────────┤M├────────
« ┌────╨────┐ └╥┘
«c: 1/╡ c_0=0x0 ╞════════╩═════════
« └─────────┘ 0
(ALAP scheduled) duration = 3100
┌────────────────┐ ┌───┐ ░ ┌─────────────────┐ »
q_0: ┤ Delay(200[dt]) ├───┤ X ├────░─┤ Delay(1400[dt]) ├───────────»
├────────────────┤ └─╥─┘ ░ ├─────────────────┤ ┌───┐ »
q_1: ┤ Delay(300[dt]) ├─────╫──────░─┤ Delay(1200[dt]) ├───┤ X ├───»
├────────────────┤ ║ ░ └───────┬─┬───────┘ └─╥─┘ »
q_2: ┤ Delay(300[dt]) ├─────╫──────░─────────┤M├─────────────╫─────»
└────────────────┘┌────╨────┐ ░ └╥┘ ┌────╨────┐»
c: 1/══════════════════╡ c_0=0x1 ╞════════════╩═════════╡ c_0=0x0 ╞»
└─────────┘ 0 └─────────┘»
« ┌───┐ ┌────────────────┐ ┌───┐ »
«q_0: ─────────────────────┤ X ├───┤ Delay(300[dt]) ├──────┤ X ├───────»
« ┌────────────────┐ └─╥─┘ └────────────────┘┌─────┴───┴──────┐»
«q_1: ┤ Delay(300[dt]) ├─────╫─────────────■─────────┤ Delay(100[dt]) ├»
« ├────────────────┤ ║ ┌─┴─┐ └──────┬─┬───────┘»
«q_2: ┤ Delay(600[dt]) ├─────╫───────────┤ X ├──────────────┤M├────────»
« └────────────────┘┌────╨────┐ └───┘ └╥┘ »
«c: 1/══════════════════╡ c_0=0x0 ╞══════════════════════════╩═════════»
« └─────────┘ 0 »
« ┌────────────────┐
«q_0: ─────■─────┤ Delay(700[dt]) ├
« ┌─┴─┐ ├────────────────┤
«q_1: ───┤ X ├───┤ Delay(700[dt]) ├
« └─╥─┘ └────────────────┘
«q_2: ─────╫───────────────────────
« ┌────╨────┐
«c: 1/╡ c_0=0x0 ╞══════════════════
« └─────────┘
"""
qc = QuantumCircuit(3, 1)
qc.delay(100, 0)
qc.x(0).c_if(0, 1)
qc.barrier()
qc.measure(2, 0)
qc.x(1).c_if(0, 0)
qc.x(0).c_if(0, 0)
qc.delay(300, 0)
qc.cx(1, 2)
qc.x(0)
qc.cx(0, 1).c_if(0, 0)
qc.measure(2, 0)
durations = InstructionDurations(
[("x", None, 100), ("measure", None, 1000), ("cx", None, 200)]
)
actual_asap = PassManager(
[
SetIOLatency(clbit_write_latency=100, conditional_latency=200),
ASAPScheduleAnalysis(durations),
PadDelay(),
]
).run(qc)
actual_alap = PassManager(
[
SetIOLatency(clbit_write_latency=100, conditional_latency=200),
ALAPScheduleAnalysis(durations),
PadDelay(),
]
).run(qc)
expected_asap = QuantumCircuit(3, 1)
expected_asap.delay(200, 0) # due to conditional latency of 200dt
expected_asap.delay(300, 1)
expected_asap.delay(300, 2)
expected_asap.x(0).c_if(0, 1)
expected_asap.barrier()
expected_asap.delay(1400, 0)
expected_asap.delay(1200, 1)
expected_asap.measure(2, 0)
expected_asap.x(1).c_if(0, 0)
expected_asap.x(0).c_if(0, 0)
expected_asap.delay(300, 0)
expected_asap.x(0)
expected_asap.delay(300, 2)
expected_asap.cx(1, 2)
expected_asap.delay(400, 1)
expected_asap.cx(0, 1).c_if(0, 0)
expected_asap.delay(700, 0) # creg is released at t0 of cx(0,1).c_if(0,0)
expected_asap.delay(
700, 1
) # no creg write until 100dt. thus measure can move left by 300dt.
expected_asap.delay(300, 2)
expected_asap.measure(2, 0)
self.assertEqual(expected_asap, actual_asap)
self.assertEqual(actual_asap.duration, 3100)
expected_alap = QuantumCircuit(3, 1)
expected_alap.delay(200, 0) # due to conditional latency of 200dt
expected_alap.delay(300, 1)
expected_alap.delay(300, 2)
expected_alap.x(0).c_if(0, 1)
expected_alap.barrier()
expected_alap.delay(1400, 0)
expected_alap.delay(1200, 1)
expected_alap.measure(2, 0)
expected_alap.x(1).c_if(0, 0)
expected_alap.x(0).c_if(0, 0)
expected_alap.delay(300, 0)
expected_alap.x(0)
expected_alap.delay(300, 1)
expected_alap.delay(600, 2)
expected_alap.cx(1, 2)
expected_alap.delay(100, 1)
expected_alap.cx(0, 1).c_if(0, 0)
expected_alap.measure(2, 0)
expected_alap.delay(700, 0)
expected_alap.delay(700, 1)
self.assertEqual(expected_alap, actual_alap)
self.assertEqual(actual_alap.duration, 3100)
def test_dag_introduces_extra_dependency_between_conditionals(self):
"""Test dependency between conditional operations in the scheduling.
In the below example circuit, the conditional x on q1 could start at time 0,
however it must be scheduled after the conditional x on q0 in ASAP scheduling.
That is because circuit model used in the transpiler passes (DAGCircuit)
interprets instructions acting on common clbits must be run in the order
given by the original circuit (QuantumCircuit).
(input)
┌────────────────┐ ┌───┐
q_0: ┤ Delay(100[dt]) ├───┤ X ├───
└─────┬───┬──────┘ └─╥─┘
q_1: ──────┤ X ├────────────╫─────
└─╥─┘ ║
┌────╨────┐ ┌────╨────┐
c: 1/═══╡ c_0=0x1 ╞════╡ c_0=0x1 ╞
└─────────┘ └─────────┘
(ASAP scheduled)
┌────────────────┐ ┌───┐
q_0: ┤ Delay(100[dt]) ├───┤ X ├──────────────
├────────────────┤ └─╥─┘ ┌───┐
q_1: ┤ Delay(100[dt]) ├─────╫────────┤ X ├───
└────────────────┘ ║ └─╥─┘
┌────╨────┐┌────╨────┐
c: 1/══════════════════╡ c_0=0x1 ╞╡ c_0=0x1 ╞
└─────────┘└─────────┘
"""
qc = QuantumCircuit(2, 1)
qc.delay(100, 0)
qc.x(0).c_if(0, True)
qc.x(1).c_if(0, True)
durations = InstructionDurations([("x", None, 160)])
pm = PassManager([ASAPScheduleAnalysis(durations), PadDelay()])
scheduled = pm.run(qc)
expected = QuantumCircuit(2, 1)
expected.delay(100, 0)
expected.delay(100, 1) # due to extra dependency on clbits
expected.x(0).c_if(0, True)
expected.x(1).c_if(0, True)
self.assertEqual(expected, scheduled)
def test_scheduling_with_calibration(self):
"""Test if calibrated instruction can update node duration."""
qc = QuantumCircuit(2)
qc.x(0)
qc.cx(0, 1)
qc.x(1)
qc.cx(0, 1)
xsched = Schedule(Play(Constant(300, 0.1), DriveChannel(0)))
qc.add_calibration("x", (0,), xsched)
durations = InstructionDurations([("x", None, 160), ("cx", None, 600)])
pm = PassManager([ASAPScheduleAnalysis(durations), PadDelay()])
scheduled = pm.run(qc)
expected = QuantumCircuit(2)
expected.x(0)
expected.delay(300, 1)
expected.cx(0, 1)
expected.x(1)
expected.delay(160, 0)
expected.cx(0, 1)
expected.add_calibration("x", (0,), xsched)
self.assertEqual(expected, scheduled)
def test_padding_not_working_without_scheduling(self):
"""Test padding fails when un-scheduled DAG is input."""
qc = QuantumCircuit(1, 1)
qc.delay(100, 0)
qc.x(0)
qc.measure(0, 0)
with self.assertRaises(TranspilerError):
PassManager(PadDelay()).run(qc)
def test_no_pad_very_end_of_circuit(self):
"""Test padding option that inserts no delay at the very end of circuit.
This circuit will be unchanged after ASAP-schedule/padding.
┌────────────────┐┌─┐
q_0: ┤ Delay(100[dt]) ├┤M├
└─────┬───┬──────┘└╥┘
q_1: ──────┤ X ├────────╫─
└───┘ ║
c: 1/═══════════════════╩═
0
"""
qc = QuantumCircuit(2, 1)
qc.delay(100, 0)
qc.x(1)
qc.measure(0, 0)
durations = InstructionDurations([("x", None, 160), ("measure", None, 1000)])
scheduled = PassManager(
[
ASAPScheduleAnalysis(durations),
PadDelay(fill_very_end=False),
]
).run(qc)
self.assertEqual(scheduled, qc)
@data(ALAPScheduleAnalysis, ASAPScheduleAnalysis)
def test_respect_target_instruction_constraints(self, schedule_pass):
"""Test if DD pass does not pad delays for qubits that do not support delay instructions.
See: https://github.com/Qiskit/qiskit-terra/issues/9993
"""
qc = QuantumCircuit(3)
qc.cx(1, 2)
target = Target(dt=1)
target.add_instruction(CXGate(), {(1, 2): InstructionProperties(duration=1000)})
# delays are not supported
pm = PassManager([schedule_pass(target=target), PadDelay(target=target)])
scheduled = pm.run(qc)
self.assertEqual(qc, scheduled)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the SetLayout pass"""
import unittest
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister
from qiskit.transpiler import CouplingMap, Layout
from qiskit.transpiler.passes import SetLayout, ApplyLayout, FullAncillaAllocation
from qiskit.test import QiskitTestCase
from qiskit.transpiler import PassManager, TranspilerError
class TestSetLayout(QiskitTestCase):
"""Tests the SetLayout pass"""
def assertEqualToReference(self, result_to_compare):
"""Compare result_to_compare to a reference
┌───┐ ░ ┌─┐
q_0 -> 0 ┤ H ├─░─┤M├───────────────
├───┤ ░ └╥┘┌─┐
q_1 -> 1 ┤ H ├─░──╫─┤M├────────────
├───┤ ░ ║ └╥┘ ┌─┐
q_4 -> 2 ┤ H ├─░──╫──╫───────┤M├───
├───┤ ░ ║ ║ ┌─┐ └╥┘
q_2 -> 3 ┤ H ├─░──╫──╫─┤M├────╫────
└───┘ ░ ║ ║ └╥┘ ║
ancilla_0 -> 4 ─────────╫──╫──╫─────╫────
┌───┐ ░ ║ ║ ║ ┌─┐ ║
q_3 -> 5 ┤ H ├─░──╫──╫──╫─┤M├─╫────
├───┤ ░ ║ ║ ║ └╥┘ ║ ┌─┐
q_5 -> 6 ┤ H ├─░──╫──╫──╫──╫──╫─┤M├
└───┘ ░ ║ ║ ║ ║ ║ └╥┘
meas: 6/═════════╩══╩══╩══╩══╩══╩═
0 1 2 3 4 5
"""
qr = QuantumRegister(6, "q")
ancilla = QuantumRegister(1, "ancilla")
cl = ClassicalRegister(6, "meas")
reference = QuantumCircuit(qr, ancilla, cl)
reference.h(qr)
reference.barrier(qr)
reference.measure(qr, cl)
pass_manager = PassManager()
pass_manager.append(
SetLayout(
Layout({qr[0]: 0, qr[1]: 1, qr[4]: 2, qr[2]: 3, ancilla[0]: 4, qr[3]: 5, qr[5]: 6})
)
)
pass_manager.append(ApplyLayout())
self.assertEqual(result_to_compare, pass_manager.run(reference))
def test_setlayout_as_Layout(self):
"""Construct SetLayout with a Layout."""
qr = QuantumRegister(6, "q")
circuit = QuantumCircuit(qr)
circuit.h(qr)
circuit.measure_all()
pass_manager = PassManager()
pass_manager.append(
SetLayout(Layout.from_intlist([0, 1, 3, 5, 2, 6], QuantumRegister(6, "q")))
)
pass_manager.append(FullAncillaAllocation(CouplingMap.from_line(7)))
pass_manager.append(ApplyLayout())
result = pass_manager.run(circuit)
self.assertEqualToReference(result)
def test_setlayout_as_list(self):
"""Construct SetLayout with a list."""
qr = QuantumRegister(6, "q")
circuit = QuantumCircuit(qr)
circuit.h(qr)
circuit.measure_all()
pass_manager = PassManager()
pass_manager.append(SetLayout([0, 1, 3, 5, 2, 6]))
pass_manager.append(FullAncillaAllocation(CouplingMap.from_line(7)))
pass_manager.append(ApplyLayout())
result = pass_manager.run(circuit)
self.assertEqualToReference(result)
def test_raise_when_layout_len_does_not_match(self):
"""Test error is raised if layout defined as list does not match the circuit size."""
qr = QuantumRegister(42, "q")
circuit = QuantumCircuit(qr)
pass_manager = PassManager()
pass_manager.append(SetLayout([0, 1, 3, 5, 2, 6]))
pass_manager.append(FullAncillaAllocation(CouplingMap.from_line(7)))
pass_manager.append(ApplyLayout())
with self.assertRaises(TranspilerError):
pass_manager.run(circuit)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Size pass testing"""
import unittest
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.converters import circuit_to_dag
from qiskit.transpiler.passes import Size
from qiskit.test import QiskitTestCase
class TestSizePass(QiskitTestCase):
"""Tests for Depth analysis methods."""
def test_empty_dag(self):
"""Empty DAG has 0 size"""
circuit = QuantumCircuit()
dag = circuit_to_dag(circuit)
pass_ = Size()
_ = pass_.run(dag)
self.assertEqual(pass_.property_set["size"], 0)
def test_just_qubits(self):
"""A dag with 8 operations and no classic bits"""
qr = QuantumRegister(2)
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[0])
circuit.cx(qr[1], qr[0])
dag = circuit_to_dag(circuit)
pass_ = Size()
_ = pass_.run(dag)
self.assertEqual(pass_.property_set["size"], 8)
def test_depth_one(self):
"""A dag with operations in parallel and size 2"""
qr = QuantumRegister(2)
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[1])
dag = circuit_to_dag(circuit)
pass_ = Size()
_ = pass_.run(dag)
self.assertEqual(pass_.property_set["size"], 2)
def test_size_control_flow(self):
"""A DAG with control flow still gives an estimate."""
qc = QuantumCircuit(5, 1)
qc.h(0)
qc.measure(0, 0)
with qc.if_test((qc.clbits[0], True)) as else_:
qc.x(1)
qc.cx(2, 3)
with else_:
qc.x(1)
with qc.for_loop(range(3)):
qc.z(2)
with qc.for_loop((4, 0, 1)):
qc.z(2)
with qc.while_loop((qc.clbits[0], True)):
qc.h(0)
qc.measure(0, 0)
pass_ = Size(recurse=True)
pass_(qc)
self.assertEqual(pass_.property_set["size"], 19)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the Solovay Kitaev transpilation pass."""
import unittest
import math
import numpy as np
import scipy
from ddt import ddt, data
from qiskit.test import QiskitTestCase
from qiskit import transpile
from qiskit.circuit import QuantumCircuit
from qiskit.circuit.library import TGate, TdgGate, HGate, SGate, SdgGate, IGate, QFT
from qiskit.converters import circuit_to_dag, dag_to_circuit
from qiskit.quantum_info import Operator
from qiskit.synthesis.discrete_basis.generate_basis_approximations import (
generate_basic_approximations,
)
from qiskit.synthesis.discrete_basis.commutator_decompose import commutator_decompose
from qiskit.synthesis.discrete_basis.gate_sequence import GateSequence
from qiskit.transpiler import PassManager
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.transpiler.passes import UnitarySynthesis, Collect1qRuns, ConsolidateBlocks
from qiskit.transpiler.passes.synthesis import SolovayKitaev, SolovayKitaevSynthesis
def _trace_distance(circuit1, circuit2):
"""Return the trace distance of the two input circuits."""
op1, op2 = Operator(circuit1), Operator(circuit2)
return 0.5 * np.trace(scipy.linalg.sqrtm(np.conj(op1 - op2).T.dot(op1 - op2))).real
def _generate_x_rotation(angle: float) -> np.ndarray:
return np.array(
[[1, 0, 0], [0, math.cos(angle), -math.sin(angle)], [0, math.sin(angle), math.cos(angle)]]
)
def _generate_y_rotation(angle: float) -> np.ndarray:
return np.array(
[[math.cos(angle), 0, math.sin(angle)], [0, 1, 0], [-math.sin(angle), 0, math.cos(angle)]]
)
def _generate_z_rotation(angle: float) -> np.ndarray:
return np.array(
[[math.cos(angle), -math.sin(angle), 0], [math.sin(angle), math.cos(angle), 0], [0, 0, 1]]
)
def is_so3_matrix(array: np.ndarray) -> bool:
"""Check if the input array is a SO(3) matrix."""
if array.shape != (3, 3):
return False
if abs(np.linalg.det(array) - 1.0) > 1e-10:
return False
if False in np.isreal(array):
return False
return True
@ddt
class TestSolovayKitaev(QiskitTestCase):
"""Test the Solovay Kitaev algorithm and transformation pass."""
def setUp(self):
super().setUp()
self.basic_approx = generate_basic_approximations([HGate(), TGate(), TdgGate()], 3)
def test_unitary_synthesis(self):
"""Test the unitary synthesis transpiler pass with Solovay-Kitaev."""
circuit = QuantumCircuit(2)
circuit.rx(0.8, 0)
circuit.cx(0, 1)
circuit.x(1)
_1q = Collect1qRuns()
_cons = ConsolidateBlocks()
_synth = UnitarySynthesis(["h", "s"], method="sk")
passes = PassManager([_1q, _cons, _synth])
compiled = passes.run(circuit)
diff = np.linalg.norm(Operator(compiled) - Operator(circuit))
self.assertLess(diff, 1)
self.assertEqual(set(compiled.count_ops().keys()), {"h", "s", "cx"})
def test_plugin(self):
"""Test calling the plugin directly."""
circuit = QuantumCircuit(1)
circuit.rx(0.8, 0)
unitary = Operator(circuit).data
plugin = SolovayKitaevSynthesis()
out = plugin.run(unitary, basis_gates=["h", "s"])
reference = QuantumCircuit(1, global_phase=3 * np.pi / 4)
reference.h(0)
reference.s(0)
reference.h(0)
self.assertEqual(dag_to_circuit(out), reference)
def test_generating_default_approximation(self):
"""Test the approximation set is generated by default."""
skd = SolovayKitaev()
circuit = QuantumCircuit(1)
dummy = skd(circuit)
self.assertIsNotNone(skd._sk.basic_approximations)
def test_i_returns_empty_circuit(self):
"""Test that ``SolovayKitaev`` returns an empty circuit when
it approximates the I-gate."""
circuit = QuantumCircuit(1)
circuit.i(0)
skd = SolovayKitaev(3, self.basic_approx)
decomposed_circuit = skd(circuit)
self.assertEqual(QuantumCircuit(1), decomposed_circuit)
def test_exact_decomposition_acts_trivially(self):
"""Test that the a circuit that can be represented exactly is represented exactly."""
circuit = QuantumCircuit(1)
circuit.t(0)
circuit.h(0)
circuit.tdg(0)
synth = SolovayKitaev(3, self.basic_approx)
dag = circuit_to_dag(circuit)
decomposed_dag = synth.run(dag)
decomposed_circuit = dag_to_circuit(decomposed_dag)
self.assertEqual(circuit, decomposed_circuit)
def test_fails_with_no_to_matrix(self):
"""Test failer if gate does not have to_matrix."""
circuit = QuantumCircuit(1)
circuit.initialize("0")
synth = SolovayKitaev(3, self.basic_approx)
dag = circuit_to_dag(circuit)
with self.assertRaises(TranspilerError) as cm:
_ = synth.run(dag)
self.assertEqual(
"SolovayKitaev does not support gate without to_matrix method: initialize",
cm.exception.message,
)
def test_str_basis_gates(self):
"""Test specifying the basis gates by string works."""
circuit = QuantumCircuit(1)
circuit.rx(0.8, 0)
basic_approx = generate_basic_approximations(["h", "t", "s"], 3)
synth = SolovayKitaev(2, basic_approx)
dag = circuit_to_dag(circuit)
discretized = dag_to_circuit(synth.run(dag))
reference = QuantumCircuit(1, global_phase=7 * np.pi / 8)
reference.h(0)
reference.t(0)
reference.h(0)
self.assertEqual(discretized, reference)
def test_approximation_on_qft(self):
"""Test the Solovay-Kitaev decomposition on the QFT circuit."""
qft = QFT(3)
transpiled = transpile(qft, basis_gates=["u", "cx"], optimization_level=1)
skd = SolovayKitaev(1)
with self.subTest("1 recursion"):
discretized = skd(transpiled)
self.assertLess(_trace_distance(transpiled, discretized), 15)
skd.recursion_degree = 2
with self.subTest("2 recursions"):
discretized = skd(transpiled)
self.assertLess(_trace_distance(transpiled, discretized), 7)
def test_u_gates_work(self):
"""Test SK works on Qiskit's UGate.
Regression test of Qiskit/qiskit-terra#9437.
"""
circuit = QuantumCircuit(1)
circuit.u(np.pi / 2, -np.pi, -np.pi, 0)
circuit.u(np.pi / 2, np.pi / 2, -np.pi, 0)
circuit.u(-np.pi / 4, 0, -np.pi / 2, 0)
circuit.u(np.pi / 4, -np.pi / 16, 0, 0)
circuit.u(0, 0, np.pi / 16, 0)
circuit.u(0, np.pi / 4, np.pi / 4, 0)
circuit.u(np.pi / 2, 0, -15 * np.pi / 16, 0)
circuit.p(-np.pi / 4, 0)
circuit.p(np.pi / 4, 0)
circuit.u(np.pi / 2, 0, -3 * np.pi / 4, 0)
circuit.u(0, 0, -np.pi / 16, 0)
circuit.u(np.pi / 2, 0, 15 * np.pi / 16, 0)
depth = 4
basis_gates = ["h", "t", "tdg", "s", "z"]
gate_approx_library = generate_basic_approximations(basis_gates=basis_gates, depth=depth)
skd = SolovayKitaev(recursion_degree=2, basic_approximations=gate_approx_library)
discretized = skd(circuit)
included_gates = set(discretized.count_ops().keys())
self.assertEqual(set(basis_gates), included_gates)
@ddt
class TestGateSequence(QiskitTestCase):
"""Test the ``GateSequence`` class."""
def test_append(self):
"""Test append."""
seq = GateSequence([IGate()])
seq.append(HGate())
ref = GateSequence([IGate(), HGate()])
self.assertEqual(seq, ref)
def test_eq(self):
"""Test equality."""
base = GateSequence([HGate(), HGate()])
seq1 = GateSequence([HGate(), HGate()])
seq2 = GateSequence([IGate()])
seq3 = GateSequence([HGate(), HGate()])
seq3.global_phase = 0.12
seq4 = GateSequence([IGate(), HGate()])
with self.subTest("equal"):
self.assertEqual(base, seq1)
with self.subTest("same product, but different repr (-> false)"):
self.assertNotEqual(base, seq2)
with self.subTest("differing global phase (-> false)"):
self.assertNotEqual(base, seq3)
with self.subTest("same num gates, but different gates (-> false)"):
self.assertNotEqual(base, seq4)
def test_to_circuit(self):
"""Test converting a gate sequence to a circuit."""
seq = GateSequence([HGate(), HGate(), TGate(), SGate(), SdgGate()])
ref = QuantumCircuit(1)
ref.h(0)
ref.h(0)
ref.t(0)
ref.s(0)
ref.sdg(0)
# a GateSequence is SU(2), so add the right phase
z = 1 / np.sqrt(np.linalg.det(Operator(ref)))
ref.global_phase = np.arctan2(np.imag(z), np.real(z))
self.assertEqual(seq.to_circuit(), ref)
def test_adjoint(self):
"""Test adjoint."""
seq = GateSequence([TGate(), SGate(), HGate(), IGate()])
inv = GateSequence([IGate(), HGate(), SdgGate(), TdgGate()])
self.assertEqual(seq.adjoint(), inv)
def test_copy(self):
"""Test copy."""
seq = GateSequence([IGate()])
copied = seq.copy()
seq.gates.append(HGate())
self.assertEqual(len(seq.gates), 2)
self.assertEqual(len(copied.gates), 1)
@data(0, 1, 10)
def test_len(self, n):
"""Test __len__."""
seq = GateSequence([IGate()] * n)
self.assertEqual(len(seq), n)
def test_getitem(self):
"""Test __getitem__."""
seq = GateSequence([IGate(), HGate(), IGate()])
self.assertEqual(seq[0], IGate())
self.assertEqual(seq[1], HGate())
self.assertEqual(seq[2], IGate())
self.assertEqual(seq[-2], HGate())
def test_from_su2_matrix(self):
"""Test from_matrix with an SU2 matrix."""
matrix = np.array([[1, 1], [1, -1]], dtype=complex) / np.sqrt(2)
matrix /= np.sqrt(np.linalg.det(matrix))
seq = GateSequence.from_matrix(matrix)
ref = GateSequence([HGate()])
self.assertEqual(seq.gates, [])
self.assertTrue(np.allclose(seq.product, ref.product))
self.assertEqual(seq.global_phase, 0)
def test_from_so3_matrix(self):
"""Test from_matrix with an SO3 matrix."""
matrix = np.array([[0, 0, -1], [0, -1, 0], [-1, 0, 0]])
seq = GateSequence.from_matrix(matrix)
ref = GateSequence([HGate()])
self.assertEqual(seq.gates, [])
self.assertTrue(np.allclose(seq.product, ref.product))
self.assertEqual(seq.global_phase, 0)
def test_from_invalid_matrix(self):
"""Test from_matrix with invalid matrices."""
with self.subTest("2x2 but not SU2"):
matrix = np.array([[1, 1], [1, -1]], dtype=complex) / np.sqrt(2)
with self.assertRaises(ValueError):
_ = GateSequence.from_matrix(matrix)
with self.subTest("not 2x2 or 3x3"):
with self.assertRaises(ValueError):
_ = GateSequence.from_matrix(np.array([[1]]))
def test_dot(self):
"""Test dot."""
seq1 = GateSequence([HGate()])
seq2 = GateSequence([TGate(), SGate()])
composed = seq1.dot(seq2)
ref = GateSequence([TGate(), SGate(), HGate()])
# check the product matches
self.assertTrue(np.allclose(ref.product, composed.product))
# check the circuit & phases are equivalent
self.assertTrue(Operator(ref.to_circuit()).equiv(composed.to_circuit()))
@ddt
class TestSolovayKitaevUtils(QiskitTestCase):
"""Test the public functions in the Solovay Kitaev utils."""
@data(
_generate_x_rotation(0.1),
_generate_y_rotation(0.2),
_generate_z_rotation(0.3),
np.dot(_generate_z_rotation(0.5), _generate_y_rotation(0.4)),
np.dot(_generate_y_rotation(0.5), _generate_x_rotation(0.4)),
)
def test_commutator_decompose_return_type(self, u_so3: np.ndarray):
"""Test that ``commutator_decompose`` returns two SO(3) gate sequences."""
v, w = commutator_decompose(u_so3)
self.assertTrue(is_so3_matrix(v.product))
self.assertTrue(is_so3_matrix(w.product))
self.assertIsInstance(v, GateSequence)
self.assertIsInstance(w, GateSequence)
@data(
_generate_x_rotation(0.1),
_generate_y_rotation(0.2),
_generate_z_rotation(0.3),
np.dot(_generate_z_rotation(0.5), _generate_y_rotation(0.4)),
np.dot(_generate_y_rotation(0.5), _generate_x_rotation(0.4)),
)
def test_commutator_decompose_decomposes_correctly(self, u_so3):
"""Test that ``commutator_decompose`` exactly decomposes the input."""
v, w = commutator_decompose(u_so3)
v_so3 = v.product
w_so3 = w.product
actual_commutator = np.dot(v_so3, np.dot(w_so3, np.dot(np.conj(v_so3).T, np.conj(w_so3).T)))
self.assertTrue(np.allclose(actual_commutator, u_so3))
def test_generate_basis_approximation_gates(self):
"""Test the basis approximation generation works for all supported gates.
Regression test of Qiskit/qiskit-terra#9585.
"""
basis = ["i", "x", "y", "z", "h", "t", "tdg", "s", "sdg"]
approx = generate_basic_approximations(basis, depth=2)
# This mainly checks that there are no errors in the generation (like
# in computing the inverse as described in #9585), so a simple check is enough.
self.assertGreater(len(approx), len(basis))
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the Stochastic Swap pass"""
import unittest
import numpy.random
from ddt import ddt, data
from qiskit.transpiler.passes import StochasticSwap
from qiskit.transpiler import CouplingMap, PassManager, Layout
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.converters import circuit_to_dag, dag_to_circuit
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.test import QiskitTestCase
from qiskit.test._canonical import canonicalize_control_flow
from qiskit.transpiler.passes.utils import CheckMap
from qiskit.circuit.random import random_circuit
from qiskit.providers.fake_provider import FakeMumbai, FakeMumbaiV2
from qiskit.compiler.transpiler import transpile
from qiskit.circuit import ControlFlowOp, Clbit, CASE_DEFAULT
from qiskit.circuit.classical import expr
@ddt
class TestStochasticSwap(QiskitTestCase):
"""
Tests the StochasticSwap pass.
All of the tests use a fixed seed since the results
may depend on it.
"""
def test_trivial_case(self):
"""
q0:--(+)-[H]-(+)-
| |
q1:---.-------|--
|
q2:-----------.--
Coupling map: [1]--[0]--[2]
"""
coupling = CouplingMap([[0, 1], [0, 2]])
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.h(qr[0])
circuit.cx(qr[0], qr[2])
dag = circuit_to_dag(circuit)
pass_ = StochasticSwap(coupling, 20, 13)
after = pass_.run(dag)
self.assertEqual(dag, after)
def test_trivial_in_same_layer(self):
"""
q0:--(+)--
|
q1:---.---
q2:--(+)--
|
q3:---.---
Coupling map: [0]--[1]--[2]--[3]
"""
coupling = CouplingMap([[0, 1], [1, 2], [2, 3]])
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[2], qr[3])
circuit.cx(qr[0], qr[1])
dag = circuit_to_dag(circuit)
pass_ = StochasticSwap(coupling, 20, 13)
after = pass_.run(dag)
self.assertEqual(dag, after)
def test_permute_wires_1(self):
"""
q0:--------
q1:---.----
|
q2:--(+)---
Coupling map: [1]--[0]--[2]
q0:--x-(+)-
| |
q1:--|--.--
|
q2:--x-----
"""
coupling = CouplingMap([[0, 1], [0, 2]])
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[2])
dag = circuit_to_dag(circuit)
pass_ = StochasticSwap(coupling, 20, 11)
after = pass_.run(dag)
expected = QuantumCircuit(qr)
expected.swap(qr[0], qr[2])
expected.cx(qr[1], qr[0])
self.assertEqual(circuit_to_dag(expected), after)
def test_permute_wires_2(self):
"""
qr0:---.---[H]--
|
qr1:---|--------
|
qr2:--(+)-------
Coupling map: [0]--[1]--[2]
qr0:----.---[H]-
|
qr1:-x-(+)------
|
qr2:-x----------
"""
coupling = CouplingMap([[1, 0], [1, 2]])
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[2])
circuit.h(qr[0])
dag = circuit_to_dag(circuit)
pass_ = StochasticSwap(coupling, 20, 11)
after = pass_.run(dag)
expected = QuantumCircuit(qr)
expected.swap(qr[1], qr[2])
expected.cx(qr[0], qr[1])
expected.h(qr[0])
self.assertEqual(expected, dag_to_circuit(after))
def test_permute_wires_3(self):
"""
qr0:--(+)---.--
| |
qr1:---|----|--
| |
qr2:---|----|--
| |
qr3:---.---(+)-
Coupling map: [0]--[1]--[2]--[3]
qr0:-x------------
|
qr1:-x--(+)---.---
| |
qr2:-x---.---(+)--
|
qr3:-x------------
"""
coupling = CouplingMap([[0, 1], [1, 2], [2, 3]])
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[3])
circuit.cx(qr[3], qr[0])
dag = circuit_to_dag(circuit)
pass_ = StochasticSwap(coupling, 20, 13)
after = pass_.run(dag)
expected = QuantumCircuit(qr)
expected.swap(qr[0], qr[1])
expected.swap(qr[2], qr[3])
expected.cx(qr[1], qr[2])
expected.cx(qr[2], qr[1])
self.assertEqual(circuit_to_dag(expected), after)
def test_permute_wires_4(self):
"""No qubit label permutation occurs if the first
layer has only single-qubit gates. This is suboptimal
but seems to be the current behavior.
qr0:------(+)--
|
qr1:-------|---
|
qr2:-------|---
|
qr3:--[H]--.---
Coupling map: [0]--[1]--[2]--[3]
qr0:------X---------
|
qr1:------X-(+)-----
|
qr2:------X--.------
|
qr3:-[H]--X---------
"""
coupling = CouplingMap([[0, 1], [1, 2], [2, 3]])
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.h(qr[3])
circuit.cx(qr[3], qr[0])
dag = circuit_to_dag(circuit)
pass_ = StochasticSwap(coupling, 20, 13)
after = pass_.run(dag)
expected = QuantumCircuit(qr)
expected.h(qr[3])
expected.swap(qr[2], qr[3])
expected.swap(qr[0], qr[1])
expected.cx(qr[2], qr[1])
self.assertEqual(circuit_to_dag(expected), after)
def test_permute_wires_5(self):
"""This is the same case as permute_wires_4
except the single qubit gate is after the two-qubit
gate, so the layout is adjusted.
qr0:--(+)------
|
qr1:---|-------
|
qr2:---|-------
|
qr3:---.--[H]--
Coupling map: [0]--[1]--[2]--[3]
qr0:-x-----------
|
qr1:-x--(+)------
|
qr2:-x---.--[H]--
|
qr3:-x-----------
"""
coupling = CouplingMap([[0, 1], [1, 2], [2, 3]])
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[3], qr[0])
circuit.h(qr[3])
dag = circuit_to_dag(circuit)
pass_ = StochasticSwap(coupling, 20, 13)
after = pass_.run(dag)
expected = QuantumCircuit(qr)
expected.swap(qr[0], qr[1])
expected.swap(qr[2], qr[3])
expected.cx(qr[2], qr[1])
expected.h(qr[2])
self.assertEqual(circuit_to_dag(expected), after)
def test_all_single_qubit(self):
"""Test all trivial layers."""
coupling = CouplingMap([[0, 1], [1, 2], [1, 3]])
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(4, "c")
circ = QuantumCircuit(qr, cr)
circ.h(qr)
circ.z(qr)
circ.s(qr)
circ.t(qr)
circ.tdg(qr)
circ.measure(qr[0], cr[0]) # intentional duplicate
circ.measure(qr[0], cr[0])
circ.measure(qr[1], cr[1])
circ.measure(qr[2], cr[2])
circ.measure(qr[3], cr[3])
dag = circuit_to_dag(circ)
pass_ = StochasticSwap(coupling, 20, 13)
after = pass_.run(dag)
self.assertEqual(dag, after)
def test_overoptimization_case(self):
"""Check mapper overoptimization.
The mapper should not change the semantics of the input.
An overoptimization introduced issue #81:
https://github.com/Qiskit/qiskit-terra/issues/81
"""
coupling = CouplingMap([[0, 2], [1, 2], [2, 3]])
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(4, "c")
circuit = QuantumCircuit(qr, cr)
circuit.x(qr[0])
circuit.y(qr[1])
circuit.z(qr[2])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[2], qr[3])
circuit.s(qr[1])
circuit.t(qr[2])
circuit.h(qr[3])
circuit.cx(qr[1], qr[2])
circuit.measure(qr[0], cr[0])
circuit.measure(qr[1], cr[1])
circuit.measure(qr[2], cr[2])
circuit.measure(qr[3], cr[3])
dag = circuit_to_dag(circuit)
# ┌───┐ ┌─┐
# q_0: | 0 >┤ X ├────────────■───────────────────────────┤M├─────────
# └───┘┌───┐ ┌─┴─┐ ┌───┐ └╥┘┌─┐
# q_1: | 0 >─────┤ Y ├─────┤ X ├─────┤ S ├────────────■───╫─┤M├──────
# └───┘┌───┐└───┘ └───┘┌───┐ ┌─┴─┐ ║ └╥┘┌─┐
# q_2: | 0 >──────────┤ Z ├───────■───────┤ T ├─────┤ X ├─╫──╫─┤M├───
# └───┘ ┌─┴─┐ └───┘┌───┐└───┘ ║ ║ └╥┘┌─┐
# q_3: | 0 >────────────────────┤ X ├──────────┤ H ├──────╫──╫──╫─┤M├
# └───┘ └───┘ ║ ║ ║ └╥┘
# c_0: 0 ══════════════════════════════════════════════╩══╬══╬══╬═
# ║ ║ ║
# c_1: 0 ═════════════════════════════════════════════════╩══╬══╬═
# ║ ║
# c_2: 0 ════════════════════════════════════════════════════╩══╬═
# ║
# c_3: 0 ═══════════════════════════════════════════════════════╩═
#
expected = QuantumCircuit(qr, cr)
expected.z(qr[2])
expected.y(qr[1])
expected.x(qr[0])
expected.swap(qr[0], qr[2])
expected.cx(qr[2], qr[1])
expected.swap(qr[0], qr[2])
expected.cx(qr[2], qr[3])
expected.s(qr[1])
expected.t(qr[2])
expected.h(qr[3])
expected.measure(qr[0], cr[0])
expected.cx(qr[1], qr[2])
expected.measure(qr[3], cr[3])
expected.measure(qr[1], cr[1])
expected.measure(qr[2], cr[2])
expected_dag = circuit_to_dag(expected)
# ┌───┐ ┌─┐
# q_0: ┤ X ├─X───────X──────┤M├────────────────
# ├───┤ │ ┌───┐ │ ┌───┐└╥┘ ┌─┐
# q_1: ┤ Y ├─┼─┤ X ├─┼─┤ S ├─╫────────■──┤M├───
# ├───┤ │ └─┬─┘ │ └───┘ ║ ┌───┐┌─┴─┐└╥┘┌─┐
# q_2: ┤ Z ├─X───■───X───■───╫─┤ T ├┤ X ├─╫─┤M├
# └───┘ ┌─┴─┐ ║ ├───┤└┬─┬┘ ║ └╥┘
# q_3: ────────────────┤ X ├─╫─┤ H ├─┤M├──╫──╫─
# └───┘ ║ └───┘ └╥┘ ║ ║
# c: 4/══════════════════════╩════════╩═══╩══╩═
# 0 3 1 2
#
# Layout --
# {qr[0]: 0,
# qr[1]: 1,
# qr[2]: 2,
# qr[3]: 3}
pass_ = StochasticSwap(coupling, 20, 19)
after = pass_.run(dag)
self.assertEqual(expected_dag, after)
def test_already_mapped(self):
"""Circuit not remapped if matches topology.
See: https://github.com/Qiskit/qiskit-terra/issues/342
"""
coupling = CouplingMap(
[
[1, 0],
[1, 2],
[2, 3],
[3, 4],
[3, 14],
[5, 4],
[6, 5],
[6, 7],
[6, 11],
[7, 10],
[8, 7],
[9, 8],
[9, 10],
[11, 10],
[12, 5],
[12, 11],
[12, 13],
[13, 4],
[13, 14],
[15, 0],
[15, 0],
[15, 2],
[15, 14],
]
)
qr = QuantumRegister(16, "q")
cr = ClassicalRegister(16, "c")
circ = QuantumCircuit(qr, cr)
circ.cx(qr[3], qr[14])
circ.cx(qr[5], qr[4])
circ.h(qr[9])
circ.cx(qr[9], qr[8])
circ.x(qr[11])
circ.cx(qr[3], qr[4])
circ.cx(qr[12], qr[11])
circ.cx(qr[13], qr[4])
for j in range(16):
circ.measure(qr[j], cr[j])
dag = circuit_to_dag(circ)
pass_ = StochasticSwap(coupling, 20, 13)
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(circ), after)
def test_congestion(self):
"""Test code path that falls back to serial layers."""
coupling = CouplingMap([[0, 1], [1, 2], [1, 3]])
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(4, "c")
circ = QuantumCircuit(qr, cr)
circ.cx(qr[1], qr[2])
circ.cx(qr[0], qr[3])
circ.measure(qr[0], cr[0])
circ.h(qr)
circ.cx(qr[0], qr[1])
circ.cx(qr[2], qr[3])
circ.measure(qr[0], cr[0])
circ.measure(qr[1], cr[1])
circ.measure(qr[2], cr[2])
circ.measure(qr[3], cr[3])
dag = circuit_to_dag(circ)
# Input:
# ┌─┐┌───┐ ┌─┐
# q_0: |0>─────────────────■──────────────────┤M├┤ H ├──■─────┤M├
# ┌───┐ │ └╥┘└───┘┌─┴─┐┌─┐└╥┘
# q_1: |0>──■───────┤ H ├──┼───────────────────╫──────┤ X ├┤M├─╫─
# ┌─┴─┐┌───┐└───┘ │ ┌─┐ ║ └───┘└╥┘ ║
# q_2: |0>┤ X ├┤ H ├───────┼─────────■─────┤M├─╫────────────╫──╫─
# └───┘└───┘ ┌─┴─┐┌───┐┌─┴─┐┌─┐└╥┘ ║ ║ ║
# q_3: |0>───────────────┤ X ├┤ H ├┤ X ├┤M├─╫──╫────────────╫──╫─
# └───┘└───┘└───┘└╥┘ ║ ║ ║ ║
# c_0: 0 ═══════════════════════════════╬══╬══╩════════════╬══╩═
# ║ ║ ║
# c_1: 0 ═══════════════════════════════╬══╬═══════════════╩════
# ║ ║
# c_2: 0 ═══════════════════════════════╬══╩════════════════════
# ║
# c_3: 0 ═══════════════════════════════╩═══════════════════════
#
# Expected output (with seed 999):
# ┌───┐ ┌─┐
# q_0: ───────X──┤ H ├─────────────────X──────┤M├──────
# │ └───┘ ┌─┐ ┌───┐ │ ┌───┐└╥┘ ┌─┐
# q_1: ──■────X────■───────┤M├─X─┤ X ├─X─┤ X ├─╫────┤M├
# ┌─┴─┐┌───┐ │ └╥┘ │ └─┬─┘┌─┐└─┬─┘ ║ └╥┘
# q_2: ┤ X ├┤ H ├──┼────────╫──┼───■──┤M├──┼───╫─────╫─
# └───┘└───┘┌─┴─┐┌───┐ ║ │ ┌───┐└╥┘ │ ║ ┌─┐ ║
# q_3: ──────────┤ X ├┤ H ├─╫──X─┤ H ├─╫───■───╫─┤M├─╫─
# └───┘└───┘ ║ └───┘ ║ ║ └╥┘ ║
# c: 4/═════════════════════╩══════════╩═══════╩══╩══╩═
# 0 2 3 0 1
#
# Target coupling graph:
# 2
# |
# 0 - 1 - 3
expected = QuantumCircuit(qr, cr)
expected.cx(qr[1], qr[2])
expected.h(qr[2])
expected.swap(qr[0], qr[1])
expected.h(qr[0])
expected.cx(qr[1], qr[3])
expected.h(qr[3])
expected.measure(qr[1], cr[0])
expected.swap(qr[1], qr[3])
expected.cx(qr[2], qr[1])
expected.h(qr[3])
expected.swap(qr[0], qr[1])
expected.measure(qr[2], cr[2])
expected.cx(qr[3], qr[1])
expected.measure(qr[0], cr[3])
expected.measure(qr[3], cr[0])
expected.measure(qr[1], cr[1])
expected_dag = circuit_to_dag(expected)
pass_ = StochasticSwap(coupling, 20, 999)
after = pass_.run(dag)
self.assertEqual(expected_dag, after)
def test_only_output_cx_and_swaps_in_coupling_map(self):
"""Test that output DAG contains only 2q gates from the the coupling map."""
coupling = CouplingMap([[0, 1], [1, 2], [2, 3]])
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(4, "c")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[2])
circuit.cx(qr[0], qr[3])
circuit.measure(qr, cr)
dag = circuit_to_dag(circuit)
pass_ = StochasticSwap(coupling, 20, 5)
after = pass_.run(dag)
valid_couplings = [{qr[a], qr[b]} for (a, b) in coupling.get_edges()]
for _2q_gate in after.two_qubit_ops():
self.assertIn(set(_2q_gate.qargs), valid_couplings)
def test_len_cm_vs_dag(self):
"""Test error if the coupling map is smaller than the dag."""
coupling = CouplingMap([[0, 1], [1, 2]])
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(4, "c")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[2])
circuit.cx(qr[0], qr[3])
circuit.measure(qr, cr)
dag = circuit_to_dag(circuit)
pass_ = StochasticSwap(coupling)
with self.assertRaises(TranspilerError):
_ = pass_.run(dag)
def test_single_gates_omitted(self):
"""Test if single qubit gates are omitted."""
coupling_map = [[0, 1], [1, 0], [1, 2], [1, 3], [2, 1], [3, 1], [3, 4], [4, 3]]
# q_0: ──■──────────────────
# │
# q_1: ──┼─────────■────────
# │ ┌─┴─┐
# q_2: ──┼───────┤ X ├──────
# │ ┌────┴───┴─────┐
# q_3: ──┼──┤ U(1,1.5,0.7) ├
# ┌─┴─┐└──────────────┘
# q_4: ┤ X ├────────────────
# └───┘
qr = QuantumRegister(5, "q")
cr = ClassicalRegister(5, "c")
circuit = QuantumCircuit(qr, cr)
circuit.cx(qr[0], qr[4])
circuit.cx(qr[1], qr[2])
circuit.u(1, 1.5, 0.7, qr[3])
# q_0: ─────────────────X──────
# │
# q_1: ───────■─────────X───■──
# ┌─┴─┐ │
# q_2: ─────┤ X ├───────────┼──
# ┌────┴───┴─────┐ ┌─┴─┐
# q_3: ┤ U(1,1.5,0.7) ├─X─┤ X ├
# └──────────────┘ │ └───┘
# q_4: ─────────────────X──────
expected = QuantumCircuit(qr, cr)
expected.cx(qr[1], qr[2])
expected.u(1, 1.5, 0.7, qr[3])
expected.swap(qr[0], qr[1])
expected.swap(qr[3], qr[4])
expected.cx(qr[1], qr[3])
expected_dag = circuit_to_dag(expected)
stochastic = StochasticSwap(CouplingMap(coupling_map), seed=0)
after = PassManager(stochastic).run(circuit)
after = circuit_to_dag(after)
self.assertEqual(expected_dag, after)
@ddt
class TestStochasticSwapControlFlow(QiskitTestCase):
"""Tests for control flow in stochastic swap."""
def test_pre_if_else_route(self):
"""test swap with if else controlflow construct"""
num_qubits = 5
qreg = QuantumRegister(num_qubits, "q")
creg = ClassicalRegister(num_qubits)
coupling = CouplingMap.from_line(num_qubits)
qc = QuantumCircuit(qreg, creg)
qc.h(0)
qc.cx(0, 2)
qc.measure(2, 2)
true_body = QuantumCircuit(qreg, creg[[2]])
true_body.x(3)
false_body = QuantumCircuit(qreg, creg[[2]])
false_body.x(4)
qc.if_else((creg[2], 0), true_body, false_body, qreg, creg[[2]])
qc.barrier(qreg)
qc.measure(qreg, creg)
dag = circuit_to_dag(qc)
cdag = StochasticSwap(coupling, seed=82).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
expected.h(0)
expected.swap(0, 1)
expected.cx(1, 2)
expected.measure(2, 2)
etrue_body = QuantumCircuit(qreg[[3, 4]], creg[[2]])
etrue_body.x(0)
efalse_body = QuantumCircuit(qreg[[3, 4]], creg[[2]])
efalse_body.x(1)
new_order = [1, 0, 2, 3, 4]
expected.if_else((creg[2], 0), etrue_body, efalse_body, qreg[[3, 4]], creg[[2]])
expected.barrier(qreg)
expected.measure(qreg, creg[new_order])
self.assertEqual(dag_to_circuit(cdag), expected)
def test_pre_if_else_route_post_x(self):
"""test swap with if else controlflow construct; pre-cx and post x"""
num_qubits = 5
qreg = QuantumRegister(num_qubits, "q")
creg = ClassicalRegister(num_qubits)
coupling = CouplingMap([(i, i + 1) for i in range(num_qubits - 1)])
qc = QuantumCircuit(qreg, creg)
qc.h(0)
qc.cx(0, 2)
qc.measure(2, 2)
true_body = QuantumCircuit(qreg, creg[[0]])
true_body.x(3)
false_body = QuantumCircuit(qreg, creg[[0]])
false_body.x(4)
qc.if_else((creg[2], 0), true_body, false_body, qreg, creg[[0]])
qc.x(1)
qc.barrier(qreg)
qc.measure(qreg, creg)
dag = circuit_to_dag(qc)
cdag = StochasticSwap(coupling, seed=431).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
expected.h(0)
expected.swap(1, 2)
expected.cx(0, 1)
expected.measure(1, 2)
new_order = [0, 2, 1, 3, 4]
etrue_body = QuantumCircuit(qreg[[3, 4]], creg[[0]])
etrue_body.x(0)
efalse_body = QuantumCircuit(qreg[[3, 4]], creg[[0]])
efalse_body.x(1)
expected.if_else((creg[2], 0), etrue_body, efalse_body, qreg[[3, 4]], creg[[0]])
expected.x(2)
expected.barrier(qreg)
expected.measure(qreg, creg[new_order])
self.assertEqual(dag_to_circuit(cdag), expected)
def test_post_if_else_route(self):
"""test swap with if else controlflow construct; post cx"""
num_qubits = 5
qreg = QuantumRegister(num_qubits, "q")
creg = ClassicalRegister(num_qubits)
coupling = CouplingMap([(i, i + 1) for i in range(num_qubits - 1)])
qc = QuantumCircuit(qreg, creg)
qc.h(0)
qc.measure(0, 0)
true_body = QuantumCircuit(qreg, creg[[0]])
true_body.x(3)
false_body = QuantumCircuit(qreg, creg[[0]])
false_body.x(4)
qc.barrier(qreg)
qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]])
qc.barrier(qreg)
qc.cx(0, 2)
qc.barrier(qreg)
qc.measure(qreg, creg)
dag = circuit_to_dag(qc)
cdag = StochasticSwap(coupling, seed=6508).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
expected.h(0)
expected.measure(0, 0)
etrue_body = QuantumCircuit(qreg[[3, 4]], creg[[0]])
etrue_body.x(0)
efalse_body = QuantumCircuit(qreg[[3, 4]], creg[[0]])
efalse_body.x(1)
expected.barrier(qreg)
expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg[[3, 4]], creg[[0]])
expected.barrier(qreg)
expected.swap(0, 1)
expected.cx(1, 2)
expected.barrier(qreg)
expected.measure(qreg, creg[[1, 0, 2, 3, 4]])
self.assertEqual(dag_to_circuit(cdag), expected)
def test_pre_if_else2(self):
"""test swap with if else controlflow construct; cx in if statement"""
num_qubits = 5
qreg = QuantumRegister(num_qubits, "q")
creg = ClassicalRegister(num_qubits)
coupling = CouplingMap([(i, i + 1) for i in range(num_qubits - 1)])
qc = QuantumCircuit(qreg, creg)
qc.h(0)
qc.cx(0, 2)
qc.x(1)
qc.measure(0, 0)
true_body = QuantumCircuit(qreg, creg[[0]])
true_body.x(0)
false_body = QuantumCircuit(qreg, creg[[0]])
qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]])
qc.barrier(qreg)
qc.measure(qreg, creg)
dag = circuit_to_dag(qc)
cdag = StochasticSwap(coupling, seed=38).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
expected.h(0)
expected.x(1)
expected.swap(0, 1)
expected.cx(1, 2)
expected.measure(1, 0)
etrue_body = QuantumCircuit(qreg[[1]], creg[[0]])
etrue_body.x(0)
efalse_body = QuantumCircuit(qreg[[1]], creg[[0]])
new_order = [1, 0, 2, 3, 4]
expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg[[1]], creg[[0]])
expected.barrier(qreg)
expected.measure(qreg, creg[new_order])
self.assertEqual(dag_to_circuit(cdag), expected)
def test_intra_if_else_route(self):
"""test swap with if else controlflow construct"""
num_qubits = 5
qreg = QuantumRegister(num_qubits, "q")
creg = ClassicalRegister(num_qubits)
coupling = CouplingMap([(i, i + 1) for i in range(num_qubits - 1)])
qc = QuantumCircuit(qreg, creg)
qc.h(0)
qc.x(1)
qc.measure(0, 0)
true_body = QuantumCircuit(qreg, creg[[0]])
true_body.cx(0, 2)
false_body = QuantumCircuit(qreg, creg[[0]])
false_body.cx(0, 4)
qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]])
qc.measure(qreg, creg)
dag = circuit_to_dag(qc)
cdag = StochasticSwap(coupling, seed=8).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
expected.h(0)
expected.x(1)
expected.measure(0, 0)
etrue_body = QuantumCircuit(qreg, creg[[0]])
etrue_body.swap(0, 1)
etrue_body.cx(1, 2)
etrue_body.swap(1, 2)
etrue_body.swap(3, 4)
efalse_body = QuantumCircuit(qreg, creg[[0]])
efalse_body.swap(0, 1)
efalse_body.swap(1, 2)
efalse_body.swap(3, 4)
efalse_body.cx(2, 3)
expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg, creg[[0]])
new_order = [1, 2, 0, 4, 3]
expected.measure(qreg, creg[new_order])
self.assertEqual(dag_to_circuit(cdag), expected)
def test_pre_intra_if_else(self):
"""test swap with if else controlflow construct; cx in if statement"""
num_qubits = 5
qreg = QuantumRegister(num_qubits, "q")
creg = ClassicalRegister(num_qubits)
coupling = CouplingMap([(i, i + 1) for i in range(num_qubits - 1)])
qc = QuantumCircuit(qreg, creg)
qc.h(0)
qc.cx(0, 2)
qc.x(1)
qc.measure(0, 0)
true_body = QuantumCircuit(qreg, creg[[0]])
true_body.cx(0, 2)
false_body = QuantumCircuit(qreg, creg[[0]])
false_body.cx(0, 4)
qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]])
qc.measure(qreg, creg)
dag = circuit_to_dag(qc)
cdag = StochasticSwap(coupling, seed=2, trials=20).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
etrue_body = QuantumCircuit(qreg[[1, 2, 3, 4]], creg[[0]])
efalse_body = QuantumCircuit(qreg[[1, 2, 3, 4]], creg[[0]])
expected.h(0)
expected.x(1)
expected.swap(0, 1)
expected.cx(1, 2)
expected.measure(1, 0)
etrue_body.cx(0, 1)
etrue_body.swap(2, 3)
etrue_body.swap(0, 1)
efalse_body.swap(0, 1)
efalse_body.swap(2, 3)
efalse_body.cx(1, 2)
expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg[[1, 2, 3, 4]], creg[[0]])
expected.measure(qreg, creg[[1, 2, 0, 4, 3]])
self.assertEqual(dag_to_circuit(cdag), expected)
def test_pre_intra_post_if_else(self):
"""test swap with if else controlflow construct; cx before, in, and after if
statement"""
num_qubits = 5
qreg = QuantumRegister(num_qubits, "q")
creg = ClassicalRegister(num_qubits)
coupling = CouplingMap.from_line(num_qubits)
qc = QuantumCircuit(qreg, creg)
qc.h(0)
qc.cx(0, 2)
qc.x(1)
qc.measure(0, 0)
true_body = QuantumCircuit(qreg, creg[[0]])
true_body.cx(0, 2)
false_body = QuantumCircuit(qreg, creg[[0]])
false_body.cx(0, 4)
qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]])
qc.h(3)
qc.cx(3, 0)
qc.barrier()
qc.measure(qreg, creg)
dag = circuit_to_dag(qc)
cdag = StochasticSwap(coupling, seed=1).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
expected.h(0)
expected.x(1)
expected.swap(1, 2)
expected.cx(0, 1)
expected.measure(0, 0)
etrue_body = QuantumCircuit(qreg, creg[[0]])
etrue_body.cx(0, 1)
etrue_body.swap(0, 1)
etrue_body.swap(4, 3)
etrue_body.swap(2, 3)
efalse_body = QuantumCircuit(qreg, creg[[0]])
efalse_body.swap(0, 1)
efalse_body.swap(3, 4)
efalse_body.swap(2, 3)
efalse_body.cx(1, 2)
expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg[[0, 1, 2, 3, 4]], creg[[0]])
expected.swap(1, 2)
expected.h(4)
expected.swap(3, 4)
expected.cx(3, 2)
expected.barrier()
expected.measure(qreg, creg[[2, 4, 0, 3, 1]])
self.assertEqual(dag_to_circuit(cdag), expected)
def test_if_expr(self):
"""Test simple if conditional with an `Expr` condition."""
coupling = CouplingMap.from_line(4)
body = QuantumCircuit(4)
body.cx(0, 1)
body.cx(0, 2)
body.cx(0, 3)
qc = QuantumCircuit(4, 2)
qc.if_test(expr.logic_and(qc.clbits[0], qc.clbits[1]), body, [0, 1, 2, 3], [])
dag = circuit_to_dag(qc)
cdag = StochasticSwap(coupling, seed=58).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
def test_if_else_expr(self):
"""Test simple if/else conditional with an `Expr` condition."""
coupling = CouplingMap.from_line(4)
true = QuantumCircuit(4)
true.cx(0, 1)
true.cx(0, 2)
true.cx(0, 3)
false = QuantumCircuit(4)
false.cx(3, 0)
false.cx(3, 1)
false.cx(3, 2)
qc = QuantumCircuit(4, 2)
qc.if_else(expr.logic_and(qc.clbits[0], qc.clbits[1]), true, false, [0, 1, 2, 3], [])
dag = circuit_to_dag(qc)
cdag = StochasticSwap(coupling, seed=58).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
def test_no_layout_change(self):
"""test controlflow with no layout change needed"""
num_qubits = 5
qreg = QuantumRegister(num_qubits, "q")
creg = ClassicalRegister(num_qubits)
coupling = CouplingMap.from_line(num_qubits)
qc = QuantumCircuit(qreg, creg)
qc.h(0)
qc.cx(0, 2)
qc.x(1)
qc.measure(0, 0)
true_body = QuantumCircuit(qreg, creg[[0]])
true_body.x(2)
false_body = QuantumCircuit(qreg, creg[[0]])
false_body.x(4)
qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]])
qc.barrier(qreg)
qc.measure(qreg, creg)
dag = circuit_to_dag(qc)
cdag = StochasticSwap(coupling, seed=23).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
expected.h(0)
expected.x(1)
expected.swap(1, 2)
expected.cx(0, 1)
expected.measure(0, 0)
etrue_body = QuantumCircuit(qreg[[1, 4]], creg[[0]])
etrue_body.x(0)
efalse_body = QuantumCircuit(qreg[[1, 4]], creg[[0]])
efalse_body.x(1)
expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg[[1, 4]], creg[[0]])
expected.barrier(qreg)
expected.measure(qreg, creg[[0, 2, 1, 3, 4]])
self.assertEqual(dag_to_circuit(cdag), expected)
@data(1, 2, 3)
def test_for_loop(self, nloops):
"""test stochastic swap with for_loop"""
# if the loop has only one iteration it isn't necessary for the pass
# to swap back to the starting layout. This test would check that
# optimization.
num_qubits = 3
qreg = QuantumRegister(num_qubits, "q")
creg = ClassicalRegister(num_qubits)
coupling = CouplingMap.from_line(num_qubits)
qc = QuantumCircuit(qreg, creg)
qc.h(0)
qc.x(1)
for_body = QuantumCircuit(qreg)
for_body.cx(0, 2)
loop_parameter = None
qc.for_loop(range(nloops), loop_parameter, for_body, qreg, [])
qc.measure(qreg, creg)
dag = circuit_to_dag(qc)
cdag = StochasticSwap(coupling, seed=687).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
expected.h(0)
expected.x(1)
efor_body = QuantumCircuit(qreg)
efor_body.swap(0, 1)
efor_body.cx(1, 2)
efor_body.swap(0, 1)
loop_parameter = None
expected.for_loop(range(nloops), loop_parameter, efor_body, qreg, [])
expected.measure(qreg, creg)
self.assertEqual(dag_to_circuit(cdag), expected)
def test_while_loop(self):
"""test while loop"""
num_qubits = 4
qreg = QuantumRegister(num_qubits, "q")
creg = ClassicalRegister(len(qreg))
coupling = CouplingMap.from_line(num_qubits)
qc = QuantumCircuit(qreg, creg)
while_body = QuantumCircuit(qreg, creg)
while_body.reset(qreg[2:])
while_body.h(qreg[2:])
while_body.cx(0, 3)
while_body.measure(qreg[3], creg[3])
qc.while_loop((creg, 0), while_body, qc.qubits, qc.clbits)
qc.barrier()
qc.measure(qreg, creg)
dag = circuit_to_dag(qc)
cdag = StochasticSwap(coupling, seed=58).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
ewhile_body = QuantumCircuit(qreg, creg[:])
ewhile_body.reset(qreg[2:])
ewhile_body.h(qreg[2:])
ewhile_body.swap(0, 1)
ewhile_body.swap(2, 3)
ewhile_body.cx(1, 2)
ewhile_body.measure(qreg[2], creg[3])
ewhile_body.swap(1, 0)
ewhile_body.swap(3, 2)
expected.while_loop((creg, 0), ewhile_body, expected.qubits, expected.clbits)
expected.barrier()
expected.measure(qreg, creg)
self.assertEqual(dag_to_circuit(cdag), expected)
def test_while_loop_expr(self):
"""Test simple while loop with an `Expr` condition."""
coupling = CouplingMap.from_line(4)
body = QuantumCircuit(4)
body.cx(0, 1)
body.cx(0, 2)
body.cx(0, 3)
qc = QuantumCircuit(4, 2)
qc.while_loop(expr.logic_and(qc.clbits[0], qc.clbits[1]), body, [0, 1, 2, 3], [])
dag = circuit_to_dag(qc)
cdag = StochasticSwap(coupling, seed=58).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
def test_switch_single_case(self):
"""Test routing of 'switch' with just a single case."""
qreg = QuantumRegister(5, "q")
creg = ClassicalRegister(3, "c")
qc = QuantumCircuit(qreg, creg)
case0 = QuantumCircuit(qreg[[0, 1, 2]], creg[:])
case0.cx(0, 1)
case0.cx(1, 2)
case0.cx(2, 0)
qc.switch(creg, [(0, case0)], qreg[[0, 1, 2]], creg)
coupling = CouplingMap.from_line(len(qreg))
pass_ = StochasticSwap(coupling, seed=58)
test = pass_(qc)
check = CheckMap(coupling)
check(test)
self.assertTrue(check.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
case0 = QuantumCircuit(qreg[[0, 1, 2]], creg[:])
case0.cx(0, 1)
case0.cx(1, 2)
case0.swap(0, 1)
case0.cx(2, 1)
case0.swap(0, 1)
expected.switch(creg, [(0, case0)], qreg[[0, 1, 2]], creg[:])
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
def test_switch_nonexhaustive(self):
"""Test routing of 'switch' with several but nonexhaustive cases."""
qreg = QuantumRegister(5, "q")
creg = ClassicalRegister(3, "c")
qc = QuantumCircuit(qreg, creg)
case0 = QuantumCircuit(qreg, creg[:])
case0.cx(0, 1)
case0.cx(1, 2)
case0.cx(2, 0)
case1 = QuantumCircuit(qreg, creg[:])
case1.cx(1, 2)
case1.cx(2, 3)
case1.cx(3, 1)
case2 = QuantumCircuit(qreg, creg[:])
case2.cx(2, 3)
case2.cx(3, 4)
case2.cx(4, 2)
qc.switch(creg, [(0, case0), ((1, 2), case1), (3, case2)], qreg, creg)
coupling = CouplingMap.from_line(len(qreg))
pass_ = StochasticSwap(coupling, seed=58)
test = pass_(qc)
check = CheckMap(coupling)
check(test)
self.assertTrue(check.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
case0 = QuantumCircuit(qreg, creg[:])
case0.cx(0, 1)
case0.cx(1, 2)
case0.swap(0, 1)
case0.cx(2, 1)
case0.swap(0, 1)
case1 = QuantumCircuit(qreg, creg[:])
case1.cx(1, 2)
case1.cx(2, 3)
case1.swap(1, 2)
case1.cx(3, 2)
case1.swap(1, 2)
case2 = QuantumCircuit(qreg, creg[:])
case2.cx(2, 3)
case2.cx(3, 4)
case2.swap(3, 4)
case2.cx(3, 2)
case2.swap(3, 4)
expected.switch(creg, [(0, case0), ((1, 2), case1), (3, case2)], qreg, creg)
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
@data((0, 1, 2, 3), (CASE_DEFAULT,))
def test_switch_exhaustive(self, labels):
"""Test routing of 'switch' with exhaustive cases; we should not require restoring the
layout afterwards."""
qreg = QuantumRegister(5, "q")
creg = ClassicalRegister(2, "c")
qc = QuantumCircuit(qreg, creg)
case0 = QuantumCircuit(qreg[[0, 1, 2]], creg[:])
case0.cx(0, 1)
case0.cx(1, 2)
case0.cx(2, 0)
qc.switch(creg, [(labels, case0)], qreg[[0, 1, 2]], creg)
coupling = CouplingMap.from_line(len(qreg))
pass_ = StochasticSwap(coupling, seed=58)
test = pass_(qc)
check = CheckMap(coupling)
check(test)
self.assertTrue(check.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
case0 = QuantumCircuit(qreg[[0, 1, 2]], creg[:])
case0.cx(0, 1)
case0.cx(1, 2)
case0.swap(0, 1)
case0.cx(2, 1)
expected.switch(creg, [(labels, case0)], qreg[[0, 1, 2]], creg)
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
def test_switch_nonexhaustive_expr(self):
"""Test routing of 'switch' with an `Expr` target and several but nonexhaustive cases."""
qreg = QuantumRegister(5, "q")
creg = ClassicalRegister(3, "c")
qc = QuantumCircuit(qreg, creg)
case0 = QuantumCircuit(qreg, creg[:])
case0.cx(0, 1)
case0.cx(1, 2)
case0.cx(2, 0)
case1 = QuantumCircuit(qreg, creg[:])
case1.cx(1, 2)
case1.cx(2, 3)
case1.cx(3, 1)
case2 = QuantumCircuit(qreg, creg[:])
case2.cx(2, 3)
case2.cx(3, 4)
case2.cx(4, 2)
qc.switch(expr.bit_or(creg, 5), [(0, case0), ((1, 2), case1), (3, case2)], qreg, creg)
coupling = CouplingMap.from_line(len(qreg))
pass_ = StochasticSwap(coupling, seed=58)
test = pass_(qc)
check = CheckMap(coupling)
check(test)
self.assertTrue(check.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
case0 = QuantumCircuit(qreg, creg[:])
case0.cx(0, 1)
case0.cx(1, 2)
case0.swap(0, 1)
case0.cx(2, 1)
case0.swap(0, 1)
case1 = QuantumCircuit(qreg, creg[:])
case1.cx(1, 2)
case1.cx(2, 3)
case1.swap(1, 2)
case1.cx(3, 2)
case1.swap(1, 2)
case2 = QuantumCircuit(qreg, creg[:])
case2.cx(2, 3)
case2.cx(3, 4)
case2.swap(3, 4)
case2.cx(3, 2)
case2.swap(3, 4)
expected.switch(expr.bit_or(creg, 5), [(0, case0), ((1, 2), case1), (3, case2)], qreg, creg)
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
@data((0, 1, 2, 3), (CASE_DEFAULT,))
def test_switch_exhaustive_expr(self, labels):
"""Test routing of 'switch' with exhaustive cases on an `Expr` target; we should not require
restoring the layout afterwards."""
qreg = QuantumRegister(5, "q")
creg = ClassicalRegister(2, "c")
qc = QuantumCircuit(qreg, creg)
case0 = QuantumCircuit(qreg[[0, 1, 2]], creg[:])
case0.cx(0, 1)
case0.cx(1, 2)
case0.cx(2, 0)
qc.switch(expr.bit_or(creg, 3), [(labels, case0)], qreg[[0, 1, 2]], creg)
coupling = CouplingMap.from_line(len(qreg))
pass_ = StochasticSwap(coupling, seed=58)
test = pass_(qc)
check = CheckMap(coupling)
check(test)
self.assertTrue(check.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
case0 = QuantumCircuit(qreg[[0, 1, 2]], creg[:])
case0.cx(0, 1)
case0.cx(1, 2)
case0.swap(0, 1)
case0.cx(2, 1)
expected.switch(expr.bit_or(creg, 3), [(labels, case0)], qreg[[0, 1, 2]], creg)
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
def test_nested_inner_cnot(self):
"""test swap in nested if else controlflow construct; swap in inner"""
seed = 1
num_qubits = 3
qreg = QuantumRegister(num_qubits, "q")
creg = ClassicalRegister(num_qubits)
coupling = CouplingMap.from_line(num_qubits)
check_map_pass = CheckMap(coupling)
qc = QuantumCircuit(qreg, creg)
qc.h(0)
qc.x(1)
qc.measure(0, 0)
true_body = QuantumCircuit(qreg, creg[[0]])
true_body.x(0)
for_body = QuantumCircuit(qreg)
for_body.delay(10, 0)
for_body.barrier(qreg)
for_body.cx(0, 2)
loop_parameter = None
true_body.for_loop(range(3), loop_parameter, for_body, qreg, [])
false_body = QuantumCircuit(qreg, creg[[0]])
false_body.y(0)
qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]])
qc.measure(qreg, creg)
dag = circuit_to_dag(qc)
cdag = StochasticSwap(coupling, seed=seed).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
expected.h(0)
expected.x(1)
expected.measure(0, 0)
etrue_body = QuantumCircuit(qreg, creg[[0]])
etrue_body.x(0)
efor_body = QuantumCircuit(qreg)
efor_body.delay(10, 0)
efor_body.barrier(qreg)
efor_body.swap(1, 2)
efor_body.cx(0, 1)
efor_body.swap(1, 2)
etrue_body.for_loop(range(3), loop_parameter, efor_body, qreg, [])
efalse_body = QuantumCircuit(qreg, creg[[0]])
efalse_body.y(0)
expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg, creg[[0]])
expected.measure(qreg, creg)
self.assertEqual(dag_to_circuit(cdag), expected)
def test_nested_outer_cnot(self):
"""test swap with nested if else controlflow construct; swap in outer"""
seed = 200
num_qubits = 5
qreg = QuantumRegister(num_qubits, "q")
creg = ClassicalRegister(num_qubits)
coupling = CouplingMap.from_line(num_qubits)
qc = QuantumCircuit(qreg, creg)
qc.h(0)
qc.x(1)
qc.measure(0, 0)
true_body = QuantumCircuit(qreg, creg[[0]])
true_body.cx(0, 2)
true_body.x(0)
for_body = QuantumCircuit(qreg)
for_body.delay(10, 0)
for_body.barrier(qreg)
for_body.cx(1, 3)
loop_parameter = None
true_body.for_loop(range(3), loop_parameter, for_body, qreg, [])
false_body = QuantumCircuit(qreg, creg[[0]])
false_body.y(0)
qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]])
qc.measure(qreg, creg)
dag = circuit_to_dag(qc)
cdag = StochasticSwap(coupling, seed=seed).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
expected.h(0)
expected.x(1)
expected.measure(0, 0)
etrue_body = QuantumCircuit(qreg, creg[[0]])
etrue_body.swap(1, 2)
etrue_body.cx(0, 1)
etrue_body.x(0)
efor_body = QuantumCircuit(qreg)
efor_body.delay(10, 0)
efor_body.barrier(qreg)
efor_body.cx(2, 3)
etrue_body.for_loop(range(3), loop_parameter, efor_body, qreg[[0, 1, 2, 3, 4]], [])
efalse_body = QuantumCircuit(qreg, creg[[0]])
efalse_body.y(0)
efalse_body.swap(1, 2)
expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg, creg[[0]])
expected.measure(qreg, creg[[0, 2, 1, 3, 4]])
self.assertEqual(dag_to_circuit(cdag), expected)
def test_disjoint_looping(self):
"""Test looping controlflow on different qubit register"""
num_qubits = 4
cm = CouplingMap.from_line(num_qubits)
qr = QuantumRegister(num_qubits, "q")
qc = QuantumCircuit(qr)
loop_body = QuantumCircuit(2)
loop_body.cx(0, 1)
qc.for_loop((0,), None, loop_body, [0, 2], [])
cqc = StochasticSwap(cm, seed=0)(qc)
expected = QuantumCircuit(qr)
efor_body = QuantumCircuit(qr[[0, 1, 2]])
efor_body.swap(1, 2)
efor_body.cx(0, 1)
efor_body.swap(1, 2)
expected.for_loop((0,), None, efor_body, [0, 1, 2], [])
self.assertEqual(cqc, expected)
def test_disjoint_multiblock(self):
"""Test looping controlflow on different qubit register"""
num_qubits = 4
cm = CouplingMap.from_line(num_qubits)
qr = QuantumRegister(num_qubits, "q")
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
true_body = QuantumCircuit(3, 1)
true_body.cx(0, 1)
false_body = QuantumCircuit(3, 1)
false_body.cx(0, 2)
qc.if_else((cr[0], 1), true_body, false_body, [0, 1, 2], [0])
cqc = StochasticSwap(cm, seed=353)(qc)
expected = QuantumCircuit(qr, cr)
etrue_body = QuantumCircuit(qr[[0, 1, 2]], cr[[0]])
etrue_body.cx(0, 1)
etrue_body.swap(0, 1)
efalse_body = QuantumCircuit(qr[[0, 1, 2]], cr[[0]])
efalse_body.swap(0, 1)
efalse_body.cx(1, 2)
expected.if_else((cr[0], 1), etrue_body, efalse_body, [0, 1, 2], cr[[0]])
self.assertEqual(cqc, expected)
def test_multiple_ops_per_layer(self):
"""Test circuits with multiple operations per layer"""
num_qubits = 6
coupling = CouplingMap.from_line(num_qubits)
check_map_pass = CheckMap(coupling)
qr = QuantumRegister(num_qubits, "q")
qc = QuantumCircuit(qr)
# This cx and the for_loop are in the same layer.
qc.cx(0, 2)
with qc.for_loop((0,)):
qc.cx(3, 5)
cqc = StochasticSwap(coupling, seed=0)(qc)
check_map_pass(cqc)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qr)
expected.swap(0, 1)
expected.cx(1, 2)
efor_body = QuantumCircuit(qr[[3, 4, 5]])
efor_body.swap(1, 2)
efor_body.cx(0, 1)
efor_body.swap(2, 1)
expected.for_loop((0,), None, efor_body, [3, 4, 5], [])
self.assertEqual(cqc, expected)
def test_if_no_else_restores_layout(self):
"""Test that an if block with no else branch restores the initial layout. If there is an
else branch, we don't need to guarantee this."""
qc = QuantumCircuit(8, 1)
with qc.if_test((qc.clbits[0], False)):
# Just some arbitrary gates with no perfect layout.
qc.cx(3, 5)
qc.cx(4, 6)
qc.cx(1, 4)
qc.cx(7, 4)
qc.cx(0, 5)
qc.cx(7, 3)
qc.cx(1, 3)
qc.cx(5, 2)
qc.cx(6, 7)
qc.cx(3, 2)
qc.cx(6, 2)
qc.cx(2, 0)
qc.cx(7, 6)
coupling = CouplingMap.from_line(8)
pass_ = StochasticSwap(coupling, seed=2022_10_13)
transpiled = pass_(qc)
# Check the pass claims to have done things right.
initial_layout = Layout.generate_trivial_layout(*qc.qubits)
self.assertEqual(initial_layout, pass_.property_set["final_layout"])
# Check that pass really did do it right.
inner_block = transpiled.data[0].operation.blocks[0]
running_layout = initial_layout.copy()
for instruction in inner_block:
if instruction.operation.name == "swap":
running_layout.swap(*instruction.qubits)
self.assertEqual(initial_layout, running_layout)
@ddt
class TestStochasticSwapRandomCircuitValidOutput(QiskitTestCase):
"""Assert the output of a transpilation with stochastic swap is a physical circuit."""
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.backend = FakeMumbai()
cls.coupling_edge_set = {tuple(x) for x in cls.backend.configuration().coupling_map}
cls.basis_gates = set(cls.backend.configuration().basis_gates)
cls.basis_gates.update(["for_loop", "while_loop", "if_else"])
def assert_valid_circuit(self, transpiled):
"""Assert circuit complies with constraints of backend."""
self.assertIsInstance(transpiled, QuantumCircuit)
self.assertIsNotNone(getattr(transpiled, "_layout", None))
def _visit_block(circuit, qubit_mapping=None):
for instruction in circuit:
if instruction.operation.name in {"barrier", "measure"}:
continue
self.assertIn(instruction.operation.name, self.basis_gates)
qargs = tuple(qubit_mapping[x] for x in instruction.qubits)
if not isinstance(instruction.operation, ControlFlowOp):
if len(qargs) > 2 or len(qargs) < 0:
raise Exception("Invalid number of qargs for instruction")
if len(qargs) == 2:
self.assertIn(qargs, self.coupling_edge_set)
else:
self.assertLessEqual(qargs[0], 26)
else:
for block in instruction.operation.blocks:
self.assertEqual(block.num_qubits, len(instruction.qubits))
self.assertEqual(block.num_clbits, len(instruction.clbits))
new_mapping = {
inner: qubit_mapping[outer]
for outer, inner in zip(instruction.qubits, block.qubits)
}
_visit_block(block, new_mapping)
# Assert routing ran.
_visit_block(
transpiled,
qubit_mapping={qubit: index for index, qubit in enumerate(transpiled.qubits)},
)
@data(*range(1, 27))
def test_random_circuit_no_control_flow(self, size):
"""Test that transpiled random circuits without control flow are physical circuits."""
circuit = random_circuit(size, 3, measure=True, seed=12342)
tqc = transpile(
circuit,
self.backend,
routing_method="stochastic",
layout_method="dense",
seed_transpiler=12342,
)
self.assert_valid_circuit(tqc)
@data(*range(1, 27))
def test_random_circuit_no_control_flow_target(self, size):
"""Test that transpiled random circuits without control flow are physical circuits."""
circuit = random_circuit(size, 3, measure=True, seed=12342)
tqc = transpile(
circuit,
routing_method="stochastic",
layout_method="dense",
seed_transpiler=12342,
target=FakeMumbaiV2().target,
)
self.assert_valid_circuit(tqc)
@data(*range(4, 27))
def test_random_circuit_for_loop(self, size):
"""Test that transpiled random circuits with nested for loops are physical circuits."""
circuit = random_circuit(size, 3, measure=False, seed=12342)
for_block = random_circuit(3, 2, measure=False, seed=12342)
inner_for_block = random_circuit(2, 1, measure=False, seed=12342)
with circuit.for_loop((1,)):
with circuit.for_loop((1,)):
circuit.append(inner_for_block, [0, 3])
circuit.append(for_block, [1, 0, 2])
circuit.measure_all()
tqc = transpile(
circuit,
self.backend,
basis_gates=list(self.basis_gates),
routing_method="stochastic",
layout_method="dense",
seed_transpiler=12342,
)
self.assert_valid_circuit(tqc)
@data(*range(6, 27))
def test_random_circuit_if_else(self, size):
"""Test that transpiled random circuits with if else blocks are physical circuits."""
circuit = random_circuit(size, 3, measure=True, seed=12342)
if_block = random_circuit(3, 2, measure=True, seed=12342)
else_block = random_circuit(2, 1, measure=True, seed=12342)
rng = numpy.random.default_rng(seed=12342)
inner_clbit_count = max((if_block.num_clbits, else_block.num_clbits))
if inner_clbit_count > circuit.num_clbits:
circuit.add_bits([Clbit() for _ in [None] * (inner_clbit_count - circuit.num_clbits)])
clbit_indices = list(range(circuit.num_clbits))
rng.shuffle(clbit_indices)
with circuit.if_test((circuit.clbits[0], True)) as else_:
circuit.append(if_block, [0, 2, 1], clbit_indices[: if_block.num_clbits])
with else_:
circuit.append(else_block, [2, 5], clbit_indices[: else_block.num_clbits])
tqc = transpile(
circuit,
self.backend,
basis_gates=list(self.basis_gates),
routing_method="stochastic",
layout_method="dense",
seed_transpiler=12342,
)
self.assert_valid_circuit(tqc)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for swap strategies."""
from typing import List
from ddt import data, ddt, unpack
import numpy as np
from qiskit import QiskitError
from qiskit.test import QiskitTestCase
from qiskit.transpiler import CouplingMap
from qiskit.transpiler.passes.routing.commuting_2q_gate_routing import SwapStrategy
@ddt
class TestSwapStrategy(QiskitTestCase):
"""A class to test the swap strategies."""
def setUp(self):
super().setUp()
self.line_coupling_map = CouplingMap(
couplinglist=[
(0, 1),
(1, 2),
(2, 3),
(3, 4),
(1, 0),
(2, 1),
(3, 2),
(4, 3),
]
)
self.line_swap_layers = (
((0, 1), (2, 3)),
((1, 2), (3, 4)),
((0, 1), (2, 3)),
((1, 2), (3, 4)),
((0, 1), (2, 3)),
)
self.line_edge_coloring = {(0, 1): 0, (1, 2): 1, (2, 3): 0, (3, 4): 1}
self.line_strategy = SwapStrategy(self.line_coupling_map, self.line_swap_layers)
@data(
(0, [0, 1, 2, 3, 4]),
(1, [1, 0, 3, 2, 4]),
(2, [1, 3, 0, 4, 2]),
(3, [3, 1, 4, 0, 2]),
(4, [3, 4, 1, 2, 0]),
(5, [4, 3, 2, 1, 0]),
)
@unpack
def test_inverse_composed_permutation(self, layer_idx: int, expected: List[int]):
"""Test the inverse of the permutations."""
self.assertEqual(self.line_strategy.inverse_composed_permutation(layer_idx), expected)
def test_apply_swap_layer(self):
"""Test that swapping a list of elements is correct."""
list_to_swap = [0, 10, 20, 30, 40]
swapped_list = self.line_strategy.apply_swap_layer(list_to_swap, 0)
self.assertEqual(swapped_list, [10, 0, 30, 20, 40])
self.assertFalse(list_to_swap == swapped_list)
swapped_list = self.line_strategy.apply_swap_layer(list_to_swap, 1, inplace=True)
self.assertEqual(swapped_list, [0, 20, 10, 40, 30])
self.assertTrue(list_to_swap == swapped_list)
def test_length(self):
"""Test the __len__ operator."""
self.assertEqual(len(self.line_strategy), 5)
def test_swapped_coupling_map(self):
"""Test the edges generated by a swap strategy."""
edge_set = {(2, 0), (0, 4), (4, 1), (1, 3), (3, 1), (1, 4), (4, 0), (0, 2)}
swapped_map = self.line_strategy.swapped_coupling_map(3)
self.assertEqual(edge_set, set(swapped_map.get_edges()))
def test_check_configuration(self):
"""Test that tries to initialize an invalid swap strategy."""
with self.assertRaises(QiskitError):
SwapStrategy(
coupling_map=self.line_coupling_map,
swap_layers=(((0, 1), (2, 3)), ((1, 3), (2, 4))),
)
def test_only_one_swap_per_qubit_per_layer(self):
"""Test that tries to initialize an invalid swap strategy."""
message = "The 0th swap layer contains a qubit with multiple swaps."
with self.assertRaises(QiskitError, msg=message):
SwapStrategy(
coupling_map=self.line_coupling_map,
swap_layers=(((0, 1), (1, 2)),),
)
def test_distance_matrix(self):
"""Test the computation of the swap strategy distance matrix."""
line_distance_matrix = np.array(
[
[0, 0, 3, 1, 2],
[0, 0, 0, 2, 3],
[3, 0, 0, 0, 1],
[1, 2, 0, 0, 0],
[2, 3, 1, 0, 0],
]
)
self.assertTrue(np.all(line_distance_matrix == self.line_strategy.distance_matrix))
# Check that the distance matrix cannot be written to.
with self.assertRaises(ValueError):
self.line_strategy.distance_matrix[1, 2] = 5
def test_reaches_full_connectivity(self):
"""Test to reach full connectivity on the longest line of Mumbai."""
# The longest line on e.g. Mumbai has 21 qubits
ll27 = list(range(21))
ll27_map = [[ll27[idx], ll27[idx + 1]] for idx in range(len(ll27) - 1)]
ll27_map += [[ll27[idx + 1], ll27[idx]] for idx in range(len(ll27) - 1)]
# Create a line swap strategy on this line
layer1 = tuple((ll27[idx], ll27[idx + 1]) for idx in range(0, len(ll27) - 1, 2))
layer2 = tuple((ll27[idx], ll27[idx + 1]) for idx in range(1, len(ll27), 2))
n = len(ll27)
for n_layers, result in [
(n - 4, False),
(n - 3, False),
(n - 2, True),
(n - 1, True),
]:
swap_strat_ll = []
for idx in range(n_layers):
if idx % 2 == 0:
swap_strat_ll.append(layer1)
else:
swap_strat_ll.append(layer2)
strat = SwapStrategy(CouplingMap(ll27_map), tuple(swap_strat_ll))
self.assertEqual(len(strat.missing_couplings) == 0, result)
def test_new_connections(self):
"""Test the new connections method."""
new_cnx = self.line_strategy.new_connections(0)
expected = [{1, 0}, {2, 1}, {3, 2}, {4, 3}]
self.assertListEqual(new_cnx, expected)
# Test after first swap layer (0, 1) first
new_cnx = self.line_strategy.new_connections(1)
expected = [{3, 0}, {4, 2}]
self.assertListEqual(new_cnx, expected)
def test_possible_edges(self):
"""Test that possible edges works as expected."""
coupling_map = CouplingMap(couplinglist=[(0, 1), (1, 2), (2, 3)])
strat = SwapStrategy(coupling_map, (((0, 1), (2, 3)), ((1, 2),)))
expected = set()
for i in range(4):
for j in range(4):
if i != j:
expected.add((i, j))
self.assertSetEqual(strat.possible_edges, expected)
class TestSwapStrategyExceptions(QiskitTestCase):
"""A class to test the exceptions raised by swap strategies."""
def test_invalid_strategy(self):
"""Test that a raise properly occurs."""
coupling_map = CouplingMap(couplinglist=[(0, 1), (1, 2)])
swap_layers = (((0, 1), (2, 3)), ((1, 2), (3, 4)))
with self.assertRaises(QiskitError):
SwapStrategy(coupling_map, swap_layers)
def test_invalid_line_strategy(self):
"""Test the number of layers."""
message = "Negative number -1 passed for number of swap layers."
with self.assertRaises(ValueError, msg=message):
SwapStrategy.from_line([0, 1, 2], -1)
class TestLineSwapStrategy(QiskitTestCase):
"""A class to test the line swap strategy."""
def test_invalid_line(self):
"""Test that lines should be longer than 1."""
message = "The line cannot have less than two elements, but is [1]"
with self.assertRaises(ValueError, msg=message):
SwapStrategy.from_line([1], 0)
def test_full_line(self):
"""Test to reach full connectivity on a line."""
n_nodes = 5
strategy = SwapStrategy.from_line(list(range(n_nodes)))
self.assertEqual(len(strategy._swap_layers), n_nodes - 2)
# The LineSwapStrategy will apply the following permutations
layers = [
[0, 1, 2, 3, 4], # coupling map
[1, 0, 3, 2, 4], # layer 1
[1, 3, 0, 4, 2], # layer 2
[3, 1, 4, 0, 2], # layer 3 <-- full connectivity is reached.
]
for layer_idx, layer in enumerate(layers):
expected = set()
for idx in range(len(layer) - 1):
expected.add((layer[idx], layer[idx + 1]))
expected.add((layer[idx + 1], layer[idx]))
strat_edges = strategy.swapped_coupling_map(layer_idx).get_edges()
self.assertEqual(len(strat_edges), len(expected))
for edge in strat_edges:
self.assertTrue(edge in expected)
self.assertEqual(strategy.swap_layer(0), [(0, 1), (2, 3)])
self.assertEqual(strategy.swap_layer(1), [(1, 2), (3, 4)])
self.assertEqual(strategy.swap_layer(2), [(0, 1), (2, 3)])
self.assertEqual(len(strategy.missing_couplings), 0)
def test_line(self):
"""Test the creation of a line swap strategy."""
n_nodes = 5
strategy = SwapStrategy.from_line(list(range(n_nodes)))
self.assertEqual(strategy.swap_layer(0), [(0, 1), (2, 3)])
self.assertEqual(strategy.swap_layer(1), [(1, 2), (3, 4)])
self.assertEqual(strategy.swap_layer(2), [(0, 1), (2, 3)])
self.assertEqual(len(strategy.missing_couplings), 0)
def test_repr(self):
"""The the representation."""
expected = (
"SwapStrategy with swap layers:\n((0, 1),),\non "
"[[0, 1], [1, 0], [1, 2], [2, 1]] coupling map."
)
self.assertEqual(repr(SwapStrategy.from_line([0, 1, 2])), expected)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=missing-docstring
import math
from qiskit.circuit.library import (
RZGate,
SXGate,
XGate,
CXGate,
RYGate,
RXGate,
RXXGate,
RGate,
IGate,
ECRGate,
UGate,
CCXGate,
RZXGate,
CZGate,
)
from qiskit.circuit import IfElseOp, ForLoopOp, WhileLoopOp, SwitchCaseOp
from qiskit.circuit.measure import Measure
from qiskit.circuit.parameter import Parameter
from qiskit import pulse
from qiskit.pulse.instruction_schedule_map import InstructionScheduleMap
from qiskit.pulse.calibration_entries import CalibrationPublisher, ScheduleDef
from qiskit.transpiler.coupling import CouplingMap
from qiskit.transpiler.instruction_durations import InstructionDurations
from qiskit.transpiler.timing_constraints import TimingConstraints
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.transpiler import Target
from qiskit.transpiler import InstructionProperties
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import (
FakeBackendV2,
FakeMumbaiFractionalCX,
FakeVigo,
FakeNairobi,
FakeGeneva,
)
class TestTarget(QiskitTestCase):
def setUp(self):
super().setUp()
self.fake_backend = FakeBackendV2()
self.fake_backend_target = self.fake_backend.target
self.theta = Parameter("theta")
self.phi = Parameter("phi")
self.ibm_target = Target()
i_props = {
(0,): InstructionProperties(duration=35.5e-9, error=0.000413),
(1,): InstructionProperties(duration=35.5e-9, error=0.000502),
(2,): InstructionProperties(duration=35.5e-9, error=0.0004003),
(3,): InstructionProperties(duration=35.5e-9, error=0.000614),
(4,): InstructionProperties(duration=35.5e-9, error=0.006149),
}
self.ibm_target.add_instruction(IGate(), i_props)
rz_props = {
(0,): InstructionProperties(duration=0, error=0),
(1,): InstructionProperties(duration=0, error=0),
(2,): InstructionProperties(duration=0, error=0),
(3,): InstructionProperties(duration=0, error=0),
(4,): InstructionProperties(duration=0, error=0),
}
self.ibm_target.add_instruction(RZGate(self.theta), rz_props)
sx_props = {
(0,): InstructionProperties(duration=35.5e-9, error=0.000413),
(1,): InstructionProperties(duration=35.5e-9, error=0.000502),
(2,): InstructionProperties(duration=35.5e-9, error=0.0004003),
(3,): InstructionProperties(duration=35.5e-9, error=0.000614),
(4,): InstructionProperties(duration=35.5e-9, error=0.006149),
}
self.ibm_target.add_instruction(SXGate(), sx_props)
x_props = {
(0,): InstructionProperties(duration=35.5e-9, error=0.000413),
(1,): InstructionProperties(duration=35.5e-9, error=0.000502),
(2,): InstructionProperties(duration=35.5e-9, error=0.0004003),
(3,): InstructionProperties(duration=35.5e-9, error=0.000614),
(4,): InstructionProperties(duration=35.5e-9, error=0.006149),
}
self.ibm_target.add_instruction(XGate(), x_props)
cx_props = {
(3, 4): InstructionProperties(duration=270.22e-9, error=0.00713),
(4, 3): InstructionProperties(duration=305.77e-9, error=0.00713),
(3, 1): InstructionProperties(duration=462.22e-9, error=0.00929),
(1, 3): InstructionProperties(duration=497.77e-9, error=0.00929),
(1, 2): InstructionProperties(duration=227.55e-9, error=0.00659),
(2, 1): InstructionProperties(duration=263.11e-9, error=0.00659),
(0, 1): InstructionProperties(duration=519.11e-9, error=0.01201),
(1, 0): InstructionProperties(duration=554.66e-9, error=0.01201),
}
self.ibm_target.add_instruction(CXGate(), cx_props)
measure_props = {
(0,): InstructionProperties(duration=5.813e-6, error=0.0751),
(1,): InstructionProperties(duration=5.813e-6, error=0.0225),
(2,): InstructionProperties(duration=5.813e-6, error=0.0146),
(3,): InstructionProperties(duration=5.813e-6, error=0.0215),
(4,): InstructionProperties(duration=5.813e-6, error=0.0333),
}
self.ibm_target.add_instruction(Measure(), measure_props)
self.aqt_target = Target(description="AQT Target")
rx_props = {
(0,): None,
(1,): None,
(2,): None,
(3,): None,
(4,): None,
}
self.aqt_target.add_instruction(RXGate(self.theta), rx_props)
ry_props = {
(0,): None,
(1,): None,
(2,): None,
(3,): None,
(4,): None,
}
self.aqt_target.add_instruction(RYGate(self.theta), ry_props)
rz_props = {
(0,): None,
(1,): None,
(2,): None,
(3,): None,
(4,): None,
}
self.aqt_target.add_instruction(RZGate(self.theta), rz_props)
r_props = {
(0,): None,
(1,): None,
(2,): None,
(3,): None,
(4,): None,
}
self.aqt_target.add_instruction(RGate(self.theta, self.phi), r_props)
rxx_props = {
(0, 1): None,
(0, 2): None,
(0, 3): None,
(0, 4): None,
(1, 0): None,
(2, 0): None,
(3, 0): None,
(4, 0): None,
(1, 2): None,
(1, 3): None,
(1, 4): None,
(2, 1): None,
(3, 1): None,
(4, 1): None,
(2, 3): None,
(2, 4): None,
(3, 2): None,
(4, 2): None,
(3, 4): None,
(4, 3): None,
}
self.aqt_target.add_instruction(RXXGate(self.theta), rxx_props)
measure_props = {
(0,): None,
(1,): None,
(2,): None,
(3,): None,
(4,): None,
}
self.aqt_target.add_instruction(Measure(), measure_props)
self.empty_target = Target()
self.ideal_sim_target = Target(num_qubits=3, description="Ideal Simulator")
self.lam = Parameter("lam")
for inst in [
UGate(self.theta, self.phi, self.lam),
RXGate(self.theta),
RYGate(self.theta),
RZGate(self.theta),
CXGate(),
ECRGate(),
CCXGate(),
Measure(),
]:
self.ideal_sim_target.add_instruction(inst, {None: None})
def test_qargs(self):
self.assertEqual(set(), self.empty_target.qargs)
expected_ibm = {
(0,),
(1,),
(2,),
(3,),
(4,),
(3, 4),
(4, 3),
(3, 1),
(1, 3),
(1, 2),
(2, 1),
(0, 1),
(1, 0),
}
self.assertEqual(expected_ibm, self.ibm_target.qargs)
expected_aqt = {
(0,),
(1,),
(2,),
(3,),
(4,),
(0, 1),
(0, 2),
(0, 3),
(0, 4),
(1, 0),
(2, 0),
(3, 0),
(4, 0),
(1, 2),
(1, 3),
(1, 4),
(2, 1),
(3, 1),
(4, 1),
(2, 3),
(2, 4),
(3, 2),
(4, 2),
(3, 4),
(4, 3),
}
self.assertEqual(expected_aqt, self.aqt_target.qargs)
expected_fake = {
(0,),
(1,),
(0, 1),
(1, 0),
}
self.assertEqual(expected_fake, self.fake_backend_target.qargs)
self.assertEqual(None, self.ideal_sim_target.qargs)
def test_qargs_for_operation_name(self):
with self.assertRaises(KeyError):
self.empty_target.qargs_for_operation_name("rz")
self.assertEqual(
self.ibm_target.qargs_for_operation_name("rz"), {(0,), (1,), (2,), (3,), (4,)}
)
self.assertEqual(
self.aqt_target.qargs_for_operation_name("rz"), {(0,), (1,), (2,), (3,), (4,)}
)
self.assertEqual(self.fake_backend_target.qargs_for_operation_name("cx"), {(0, 1)})
self.assertEqual(
self.fake_backend_target.qargs_for_operation_name("ecr"),
{
(1, 0),
},
)
self.assertEqual(self.ideal_sim_target.qargs_for_operation_name("cx"), None)
def test_instruction_names(self):
self.assertEqual(self.empty_target.operation_names, set())
self.assertEqual(self.ibm_target.operation_names, {"rz", "id", "sx", "x", "cx", "measure"})
self.assertEqual(self.aqt_target.operation_names, {"rz", "ry", "rx", "rxx", "r", "measure"})
self.assertEqual(
self.fake_backend_target.operation_names, {"u", "cx", "measure", "ecr", "rx_30", "rx"}
)
self.assertEqual(
self.ideal_sim_target.operation_names,
{"u", "rz", "ry", "rx", "cx", "ecr", "ccx", "measure"},
)
def test_operations(self):
self.assertEqual(self.empty_target.operations, [])
ibm_expected = [RZGate(self.theta), IGate(), SXGate(), XGate(), CXGate(), Measure()]
for gate in ibm_expected:
self.assertIn(gate, self.ibm_target.operations)
aqt_expected = [
RZGate(self.theta),
RXGate(self.theta),
RYGate(self.theta),
RGate(self.theta, self.phi),
RXXGate(self.theta),
]
for gate in aqt_expected:
self.assertIn(gate, self.aqt_target.operations)
fake_expected = [
UGate(self.fake_backend._theta, self.fake_backend._phi, self.fake_backend._lam),
CXGate(),
Measure(),
ECRGate(),
RXGate(math.pi / 6),
RXGate(self.fake_backend._theta),
]
for gate in fake_expected:
self.assertIn(gate, self.fake_backend_target.operations)
ideal_sim_expected = [
UGate(self.theta, self.phi, self.lam),
RXGate(self.theta),
RYGate(self.theta),
RZGate(self.theta),
CXGate(),
ECRGate(),
CCXGate(),
Measure(),
]
for gate in ideal_sim_expected:
self.assertIn(gate, self.ideal_sim_target.operations)
def test_instructions(self):
self.assertEqual(self.empty_target.instructions, [])
ibm_expected = [
(IGate(), (0,)),
(IGate(), (1,)),
(IGate(), (2,)),
(IGate(), (3,)),
(IGate(), (4,)),
(RZGate(self.theta), (0,)),
(RZGate(self.theta), (1,)),
(RZGate(self.theta), (2,)),
(RZGate(self.theta), (3,)),
(RZGate(self.theta), (4,)),
(SXGate(), (0,)),
(SXGate(), (1,)),
(SXGate(), (2,)),
(SXGate(), (3,)),
(SXGate(), (4,)),
(XGate(), (0,)),
(XGate(), (1,)),
(XGate(), (2,)),
(XGate(), (3,)),
(XGate(), (4,)),
(CXGate(), (3, 4)),
(CXGate(), (4, 3)),
(CXGate(), (3, 1)),
(CXGate(), (1, 3)),
(CXGate(), (1, 2)),
(CXGate(), (2, 1)),
(CXGate(), (0, 1)),
(CXGate(), (1, 0)),
(Measure(), (0,)),
(Measure(), (1,)),
(Measure(), (2,)),
(Measure(), (3,)),
(Measure(), (4,)),
]
self.assertEqual(ibm_expected, self.ibm_target.instructions)
ideal_sim_expected = [
(UGate(self.theta, self.phi, self.lam), None),
(RXGate(self.theta), None),
(RYGate(self.theta), None),
(RZGate(self.theta), None),
(CXGate(), None),
(ECRGate(), None),
(CCXGate(), None),
(Measure(), None),
]
self.assertEqual(ideal_sim_expected, self.ideal_sim_target.instructions)
def test_instruction_properties(self):
i_gate_2 = self.ibm_target.instruction_properties(2)
self.assertEqual(i_gate_2.error, 0.0004003)
self.assertIsNone(self.ideal_sim_target.instruction_properties(4))
def test_get_instruction_from_name(self):
with self.assertRaises(KeyError):
self.empty_target.operation_from_name("measure")
self.assertEqual(self.ibm_target.operation_from_name("measure"), Measure())
self.assertEqual(self.fake_backend_target.operation_from_name("rx_30"), RXGate(math.pi / 6))
self.assertEqual(
self.fake_backend_target.operation_from_name("rx"),
RXGate(self.fake_backend._theta),
)
self.assertEqual(self.ideal_sim_target.operation_from_name("ccx"), CCXGate())
def test_get_instructions_for_qargs(self):
with self.assertRaises(KeyError):
self.empty_target.operations_for_qargs((0,))
expected = [RZGate(self.theta), IGate(), SXGate(), XGate(), Measure()]
res = self.ibm_target.operations_for_qargs((0,))
for gate in expected:
self.assertIn(gate, res)
expected = [ECRGate()]
res = self.fake_backend_target.operations_for_qargs((1, 0))
for gate in expected:
self.assertIn(gate, res)
expected = [CXGate()]
res = self.fake_backend_target.operations_for_qargs((0, 1))
self.assertEqual(expected, res)
ideal_sim_expected = [
UGate(self.theta, self.phi, self.lam),
RXGate(self.theta),
RYGate(self.theta),
RZGate(self.theta),
CXGate(),
ECRGate(),
CCXGate(),
Measure(),
]
for gate in ideal_sim_expected:
self.assertIn(gate, self.ideal_sim_target.operations_for_qargs(None))
def test_get_operation_for_qargs_global(self):
expected = [
RXGate(self.theta),
RYGate(self.theta),
RZGate(self.theta),
RGate(self.theta, self.phi),
Measure(),
]
res = self.aqt_target.operations_for_qargs((0,))
self.assertEqual(len(expected), len(res))
for x in expected:
self.assertIn(x, res)
expected = [RXXGate(self.theta)]
res = self.aqt_target.operations_for_qargs((0, 1))
self.assertEqual(len(expected), len(res))
for x in expected:
self.assertIn(x, res)
def test_get_invalid_operations_for_qargs(self):
with self.assertRaises(KeyError):
self.ibm_target.operations_for_qargs((0, 102))
with self.assertRaises(KeyError):
self.ibm_target.operations_for_qargs(None)
def test_get_operation_names_for_qargs(self):
with self.assertRaises(KeyError):
self.empty_target.operation_names_for_qargs((0,))
expected = {"rz", "id", "sx", "x", "measure"}
res = self.ibm_target.operation_names_for_qargs((0,))
for gate in expected:
self.assertIn(gate, res)
expected = {"ecr"}
res = self.fake_backend_target.operation_names_for_qargs((1, 0))
for gate in expected:
self.assertIn(gate, res)
expected = {"cx"}
res = self.fake_backend_target.operation_names_for_qargs((0, 1))
self.assertEqual(expected, res)
ideal_sim_expected = ["u", "rx", "ry", "rz", "cx", "ecr", "ccx", "measure"]
for gate in ideal_sim_expected:
self.assertIn(gate, self.ideal_sim_target.operation_names_for_qargs(None))
def test_get_operation_names_for_qargs_invalid_qargs(self):
with self.assertRaises(KeyError):
self.ibm_target.operation_names_for_qargs((0, 102))
with self.assertRaises(KeyError):
self.ibm_target.operation_names_for_qargs(None)
def test_get_operation_names_for_qargs_global_insts(self):
expected = {"r", "rx", "rz", "ry", "measure"}
self.assertEqual(self.aqt_target.operation_names_for_qargs((0,)), expected)
expected = {
"rxx",
}
self.assertEqual(self.aqt_target.operation_names_for_qargs((0, 1)), expected)
def test_coupling_map(self):
self.assertEqual(
CouplingMap().get_edges(), self.empty_target.build_coupling_map().get_edges()
)
self.assertEqual(
set(CouplingMap.from_full(5).get_edges()),
set(self.aqt_target.build_coupling_map().get_edges()),
)
self.assertEqual(
{(0, 1), (1, 0)}, set(self.fake_backend_target.build_coupling_map().get_edges())
)
self.assertEqual(
{
(3, 4),
(4, 3),
(3, 1),
(1, 3),
(1, 2),
(2, 1),
(0, 1),
(1, 0),
},
set(self.ibm_target.build_coupling_map().get_edges()),
)
self.assertEqual(None, self.ideal_sim_target.build_coupling_map())
def test_coupling_map_mutations_do_not_propagate(self):
cm = CouplingMap.from_line(5, bidirectional=False)
cx_props = {
edge: InstructionProperties(duration=270.22e-9, error=0.00713)
for edge in cm.get_edges()
}
target = Target()
target.add_instruction(CXGate(), cx_props)
self.assertEqual(cm, target.build_coupling_map())
symmetric = target.build_coupling_map()
symmetric.make_symmetric()
self.assertNotEqual(cm, symmetric) # sanity check for the test.
# Verify that mutating the output of `build_coupling_map` doesn't affect the target.
self.assertNotEqual(target.build_coupling_map(), symmetric)
def test_coupling_map_filtered_mutations_do_not_propagate(self):
cm = CouplingMap.from_line(5, bidirectional=False)
cx_props = {
edge: InstructionProperties(duration=270.22e-9, error=0.00713)
for edge in cm.get_edges()
if 2 not in edge
}
target = Target()
target.add_instruction(CXGate(), cx_props)
symmetric = target.build_coupling_map(filter_idle_qubits=True)
symmetric.make_symmetric()
self.assertNotEqual(cm, symmetric) # sanity check for the test.
# Verify that mutating the output of `build_coupling_map` doesn't affect the target.
self.assertNotEqual(target.build_coupling_map(filter_idle_qubits=True), symmetric)
def test_coupling_map_no_filter_mutations_do_not_propagate(self):
cm = CouplingMap.from_line(5, bidirectional=False)
cx_props = {
edge: InstructionProperties(duration=270.22e-9, error=0.00713)
for edge in cm.get_edges()
}
target = Target()
target.add_instruction(CXGate(), cx_props)
# The filter here does not actually do anything, because there's no idle qubits. This is
# just a test that this path is also not cached.
self.assertEqual(cm, target.build_coupling_map(filter_idle_qubits=True))
symmetric = target.build_coupling_map(filter_idle_qubits=True)
symmetric.make_symmetric()
self.assertNotEqual(cm, symmetric) # sanity check for the test.
# Verify that mutating the output of `build_coupling_map` doesn't affect the target.
self.assertNotEqual(target.build_coupling_map(filter_idle_qubits=True), symmetric)
def test_coupling_map_2q_gate(self):
cmap = self.fake_backend_target.build_coupling_map("ecr")
self.assertEqual(
[
(1, 0),
],
cmap.get_edges(),
)
def test_coupling_map_3q_gate(self):
fake_target = Target()
ccx_props = {
(0, 1, 2): None,
(1, 0, 2): None,
(2, 1, 0): None,
}
fake_target.add_instruction(CCXGate(), ccx_props)
with self.assertLogs("qiskit.transpiler.target", level="WARN") as log:
cmap = fake_target.build_coupling_map()
self.assertEqual(
log.output,
[
"WARNING:qiskit.transpiler.target:"
"This Target object contains multiqubit gates that "
"operate on > 2 qubits. This will not be reflected in "
"the output coupling map."
],
)
self.assertEqual([], cmap.get_edges())
with self.assertRaises(ValueError):
fake_target.build_coupling_map("ccx")
def test_coupling_map_mixed_ideal_global_1q_and_2q_gates(self):
n_qubits = 3
target = Target()
target.add_instruction(CXGate(), {(i, i + 1): None for i in range(n_qubits - 1)})
target.add_instruction(RXGate(Parameter("theta")), {None: None})
cmap = target.build_coupling_map()
self.assertEqual([(0, 1), (1, 2)], cmap.get_edges())
def test_coupling_map_mixed_global_1q_and_2q_gates(self):
n_qubits = 3
target = Target()
target.add_instruction(CXGate(), {(i, i + 1): None for i in range(n_qubits - 1)})
target.add_instruction(RXGate(Parameter("theta")))
cmap = target.build_coupling_map()
self.assertEqual([(0, 1), (1, 2)], cmap.get_edges())
def test_coupling_map_mixed_ideal_global_2q_and_real_2q_gates(self):
n_qubits = 3
target = Target()
target.add_instruction(CXGate(), {(i, i + 1): None for i in range(n_qubits - 1)})
target.add_instruction(ECRGate())
cmap = target.build_coupling_map()
self.assertIsNone(cmap)
def test_physical_qubits(self):
self.assertEqual([], self.empty_target.physical_qubits)
self.assertEqual(list(range(5)), self.ibm_target.physical_qubits)
self.assertEqual(list(range(5)), self.aqt_target.physical_qubits)
self.assertEqual(list(range(2)), self.fake_backend_target.physical_qubits)
self.assertEqual(list(range(3)), self.ideal_sim_target.physical_qubits)
def test_duplicate_instruction_add_instruction(self):
target = Target()
target.add_instruction(XGate(), {(0,): None})
with self.assertRaises(AttributeError):
target.add_instruction(XGate(), {(1,): None})
def test_durations(self):
empty_durations = self.empty_target.durations()
self.assertEqual(
empty_durations.duration_by_name_qubits, InstructionDurations().duration_by_name_qubits
)
aqt_durations = self.aqt_target.durations()
self.assertEqual(aqt_durations.duration_by_name_qubits, {})
ibm_durations = self.ibm_target.durations()
expected = {
("cx", (0, 1)): (5.1911e-07, "s"),
("cx", (1, 0)): (5.5466e-07, "s"),
("cx", (1, 2)): (2.2755e-07, "s"),
("cx", (1, 3)): (4.9777e-07, "s"),
("cx", (2, 1)): (2.6311e-07, "s"),
("cx", (3, 1)): (4.6222e-07, "s"),
("cx", (3, 4)): (2.7022e-07, "s"),
("cx", (4, 3)): (3.0577e-07, "s"),
("id", (0,)): (3.55e-08, "s"),
("id", (1,)): (3.55e-08, "s"),
("id", (2,)): (3.55e-08, "s"),
("id", (3,)): (3.55e-08, "s"),
("id", (4,)): (3.55e-08, "s"),
("measure", (0,)): (5.813e-06, "s"),
("measure", (1,)): (5.813e-06, "s"),
("measure", (2,)): (5.813e-06, "s"),
("measure", (3,)): (5.813e-06, "s"),
("measure", (4,)): (5.813e-06, "s"),
("rz", (0,)): (0, "s"),
("rz", (1,)): (0, "s"),
("rz", (2,)): (0, "s"),
("rz", (3,)): (0, "s"),
("rz", (4,)): (0, "s"),
("sx", (0,)): (3.55e-08, "s"),
("sx", (1,)): (3.55e-08, "s"),
("sx", (2,)): (3.55e-08, "s"),
("sx", (3,)): (3.55e-08, "s"),
("sx", (4,)): (3.55e-08, "s"),
("x", (0,)): (3.55e-08, "s"),
("x", (1,)): (3.55e-08, "s"),
("x", (2,)): (3.55e-08, "s"),
("x", (3,)): (3.55e-08, "s"),
("x", (4,)): (3.55e-08, "s"),
}
self.assertEqual(ibm_durations.duration_by_name_qubits, expected)
def test_mapping(self):
with self.assertRaises(KeyError):
_res = self.empty_target["cx"]
expected = {
(0,): None,
(1,): None,
(2,): None,
(3,): None,
(4,): None,
}
self.assertEqual(self.aqt_target["r"], expected)
self.assertEqual(["rx", "ry", "rz", "r", "rxx", "measure"], list(self.aqt_target))
expected_values = [
{
(0,): None,
(1,): None,
(2,): None,
(3,): None,
(4,): None,
},
{
(0,): None,
(1,): None,
(2,): None,
(3,): None,
(4,): None,
},
{
(0,): None,
(1,): None,
(2,): None,
(3,): None,
(4,): None,
},
{
(0,): None,
(1,): None,
(2,): None,
(3,): None,
(4,): None,
},
{
(0, 1): None,
(0, 2): None,
(0, 3): None,
(0, 4): None,
(1, 0): None,
(2, 0): None,
(3, 0): None,
(4, 0): None,
(1, 2): None,
(1, 3): None,
(1, 4): None,
(2, 1): None,
(3, 1): None,
(4, 1): None,
(2, 3): None,
(2, 4): None,
(3, 2): None,
(4, 2): None,
(3, 4): None,
(4, 3): None,
},
{
(0,): None,
(1,): None,
(2,): None,
(3,): None,
(4,): None,
},
]
self.assertEqual(expected_values, list(self.aqt_target.values()))
expected_items = {
"rx": {
(0,): None,
(1,): None,
(2,): None,
(3,): None,
(4,): None,
},
"ry": {
(0,): None,
(1,): None,
(2,): None,
(3,): None,
(4,): None,
},
"rz": {
(0,): None,
(1,): None,
(2,): None,
(3,): None,
(4,): None,
},
"r": {
(0,): None,
(1,): None,
(2,): None,
(3,): None,
(4,): None,
},
"rxx": {
(0, 1): None,
(0, 2): None,
(0, 3): None,
(0, 4): None,
(1, 0): None,
(2, 0): None,
(3, 0): None,
(4, 0): None,
(1, 2): None,
(1, 3): None,
(1, 4): None,
(2, 1): None,
(3, 1): None,
(4, 1): None,
(2, 3): None,
(2, 4): None,
(3, 2): None,
(4, 2): None,
(3, 4): None,
(4, 3): None,
},
"measure": {
(0,): None,
(1,): None,
(2,): None,
(3,): None,
(4,): None,
},
}
self.assertEqual(expected_items, dict(self.aqt_target.items()))
self.assertIn("cx", self.ibm_target)
self.assertNotIn("ecr", self.ibm_target)
self.assertEqual(len(self.ibm_target), 6)
def test_update_instruction_properties(self):
self.aqt_target.update_instruction_properties(
"rxx",
(0, 1),
InstructionProperties(duration=1e-6, error=1e-5),
)
self.assertEqual(self.aqt_target["rxx"][(0, 1)].duration, 1e-6)
self.assertEqual(self.aqt_target["rxx"][(0, 1)].error, 1e-5)
def test_update_instruction_properties_invalid_instruction(self):
with self.assertRaises(KeyError):
self.ibm_target.update_instruction_properties("rxx", (0, 1), None)
def test_update_instruction_properties_invalid_qarg(self):
with self.assertRaises(KeyError):
self.fake_backend_target.update_instruction_properties("ecr", (0, 1), None)
def test_str(self):
expected = """Target
Number of qubits: 5
Instructions:
id
(0,):
Duration: 3.55e-08 sec.
Error Rate: 0.000413
(1,):
Duration: 3.55e-08 sec.
Error Rate: 0.000502
(2,):
Duration: 3.55e-08 sec.
Error Rate: 0.0004003
(3,):
Duration: 3.55e-08 sec.
Error Rate: 0.000614
(4,):
Duration: 3.55e-08 sec.
Error Rate: 0.006149
rz
(0,):
Duration: 0 sec.
Error Rate: 0
(1,):
Duration: 0 sec.
Error Rate: 0
(2,):
Duration: 0 sec.
Error Rate: 0
(3,):
Duration: 0 sec.
Error Rate: 0
(4,):
Duration: 0 sec.
Error Rate: 0
sx
(0,):
Duration: 3.55e-08 sec.
Error Rate: 0.000413
(1,):
Duration: 3.55e-08 sec.
Error Rate: 0.000502
(2,):
Duration: 3.55e-08 sec.
Error Rate: 0.0004003
(3,):
Duration: 3.55e-08 sec.
Error Rate: 0.000614
(4,):
Duration: 3.55e-08 sec.
Error Rate: 0.006149
x
(0,):
Duration: 3.55e-08 sec.
Error Rate: 0.000413
(1,):
Duration: 3.55e-08 sec.
Error Rate: 0.000502
(2,):
Duration: 3.55e-08 sec.
Error Rate: 0.0004003
(3,):
Duration: 3.55e-08 sec.
Error Rate: 0.000614
(4,):
Duration: 3.55e-08 sec.
Error Rate: 0.006149
cx
(3, 4):
Duration: 2.7022e-07 sec.
Error Rate: 0.00713
(4, 3):
Duration: 3.0577e-07 sec.
Error Rate: 0.00713
(3, 1):
Duration: 4.6222e-07 sec.
Error Rate: 0.00929
(1, 3):
Duration: 4.9777e-07 sec.
Error Rate: 0.00929
(1, 2):
Duration: 2.2755e-07 sec.
Error Rate: 0.00659
(2, 1):
Duration: 2.6311e-07 sec.
Error Rate: 0.00659
(0, 1):
Duration: 5.1911e-07 sec.
Error Rate: 0.01201
(1, 0):
Duration: 5.5466e-07 sec.
Error Rate: 0.01201
measure
(0,):
Duration: 5.813e-06 sec.
Error Rate: 0.0751
(1,):
Duration: 5.813e-06 sec.
Error Rate: 0.0225
(2,):
Duration: 5.813e-06 sec.
Error Rate: 0.0146
(3,):
Duration: 5.813e-06 sec.
Error Rate: 0.0215
(4,):
Duration: 5.813e-06 sec.
Error Rate: 0.0333
"""
self.assertEqual(expected, str(self.ibm_target))
aqt_expected = """Target: AQT Target
Number of qubits: 5
Instructions:
rx
(0,)
(1,)
(2,)
(3,)
(4,)
ry
(0,)
(1,)
(2,)
(3,)
(4,)
rz
(0,)
(1,)
(2,)
(3,)
(4,)
r
(0,)
(1,)
(2,)
(3,)
(4,)
rxx
(0, 1)
(0, 2)
(0, 3)
(0, 4)
(1, 0)
(2, 0)
(3, 0)
(4, 0)
(1, 2)
(1, 3)
(1, 4)
(2, 1)
(3, 1)
(4, 1)
(2, 3)
(2, 4)
(3, 2)
(4, 2)
(3, 4)
(4, 3)
measure
(0,)
(1,)
(2,)
(3,)
(4,)
"""
self.assertEqual(aqt_expected, str(self.aqt_target))
sim_expected = """Target: Ideal Simulator
Number of qubits: 3
Instructions:
u
rx
ry
rz
cx
ecr
ccx
measure
"""
self.assertEqual(sim_expected, str(self.ideal_sim_target))
def test_extra_props_str(self):
target = Target(description="Extra Properties")
class ExtraProperties(InstructionProperties):
"""An example properties subclass."""
def __init__(
self,
duration=None,
error=None,
calibration=None,
tuned=None,
diamond_norm_error=None,
):
super().__init__(duration=duration, error=error, calibration=calibration)
self.tuned = tuned
self.diamond_norm_error = diamond_norm_error
cx_props = {
(3, 4): ExtraProperties(
duration=270.22e-9, error=0.00713, tuned=False, diamond_norm_error=2.12e-6
),
}
target.add_instruction(CXGate(), cx_props)
expected = """Target: Extra Properties
Number of qubits: 5
Instructions:
cx
(3, 4):
Duration: 2.7022e-07 sec.
Error Rate: 0.00713
"""
self.assertEqual(expected, str(target))
def test_timing_constraints(self):
generated_constraints = self.aqt_target.timing_constraints()
expected_constraints = TimingConstraints()
for i in ["granularity", "min_length", "pulse_alignment", "acquire_alignment"]:
self.assertEqual(
getattr(generated_constraints, i),
getattr(expected_constraints, i),
f"Generated constraints differs from expected for attribute {i}"
f"{getattr(generated_constraints, i)}!={getattr(expected_constraints, i)}",
)
def test_get_non_global_operation_name_ideal_backend(self):
self.assertEqual(self.aqt_target.get_non_global_operation_names(), [])
self.assertEqual(self.ideal_sim_target.get_non_global_operation_names(), [])
self.assertEqual(self.ibm_target.get_non_global_operation_names(), [])
self.assertEqual(self.fake_backend_target.get_non_global_operation_names(), [])
def test_get_non_global_operation_name_ideal_backend_strict_direction(self):
self.assertEqual(self.aqt_target.get_non_global_operation_names(True), [])
self.assertEqual(self.ideal_sim_target.get_non_global_operation_names(True), [])
self.assertEqual(self.ibm_target.get_non_global_operation_names(True), [])
self.assertEqual(
self.fake_backend_target.get_non_global_operation_names(True), ["cx", "ecr"]
)
def test_instruction_supported(self):
self.assertTrue(self.aqt_target.instruction_supported("r", (0,)))
self.assertFalse(self.aqt_target.instruction_supported("cx", (0, 1)))
self.assertTrue(self.ideal_sim_target.instruction_supported("cx", (0, 1)))
self.assertFalse(self.ideal_sim_target.instruction_supported("cx", (0, 524)))
self.assertTrue(self.fake_backend_target.instruction_supported("cx", (0, 1)))
self.assertFalse(self.fake_backend_target.instruction_supported("cx", (1, 0)))
self.assertFalse(self.ideal_sim_target.instruction_supported("cx", (0, 1, 2)))
def test_instruction_supported_parameters(self):
mumbai = FakeMumbaiFractionalCX()
self.assertTrue(
mumbai.target.instruction_supported(
qargs=(0, 1), operation_class=RZXGate, parameters=[math.pi / 4]
)
)
self.assertTrue(mumbai.target.instruction_supported(qargs=(0, 1), operation_class=RZXGate))
self.assertTrue(
mumbai.target.instruction_supported(operation_class=RZXGate, parameters=[math.pi / 4])
)
self.assertFalse(mumbai.target.instruction_supported("rzx", parameters=[math.pi / 4]))
self.assertTrue(mumbai.target.instruction_supported("rz", parameters=[Parameter("angle")]))
self.assertTrue(
mumbai.target.instruction_supported("rzx_45", qargs=(0, 1), parameters=[math.pi / 4])
)
self.assertTrue(mumbai.target.instruction_supported("rzx_45", qargs=(0, 1)))
self.assertTrue(mumbai.target.instruction_supported("rzx_45", parameters=[math.pi / 4]))
self.assertFalse(mumbai.target.instruction_supported("rzx_45", parameters=[math.pi / 6]))
self.assertFalse(
mumbai.target.instruction_supported("rzx_45", parameters=[Parameter("angle")])
)
self.assertTrue(
self.ideal_sim_target.instruction_supported(
qargs=(0,), operation_class=RXGate, parameters=[Parameter("angle")]
)
)
self.assertTrue(
self.ideal_sim_target.instruction_supported(
qargs=(0,), operation_class=RXGate, parameters=[math.pi]
)
)
self.assertTrue(
self.ideal_sim_target.instruction_supported(
operation_class=RXGate, parameters=[math.pi]
)
)
self.assertTrue(
self.ideal_sim_target.instruction_supported(
operation_class=RXGate, parameters=[Parameter("angle")]
)
)
self.assertTrue(
self.ideal_sim_target.instruction_supported(
"rx", qargs=(0,), parameters=[Parameter("angle")]
)
)
self.assertTrue(
self.ideal_sim_target.instruction_supported("rx", qargs=(0,), parameters=[math.pi])
)
self.assertTrue(self.ideal_sim_target.instruction_supported("rx", parameters=[math.pi]))
self.assertTrue(
self.ideal_sim_target.instruction_supported("rx", parameters=[Parameter("angle")])
)
def test_instruction_supported_multiple_parameters(self):
target = Target(1)
target.add_instruction(
UGate(self.theta, self.phi, self.lam),
{(0,): InstructionProperties(duration=270.22e-9, error=0.00713)},
)
self.assertFalse(target.instruction_supported("u", parameters=[math.pi]))
self.assertTrue(target.instruction_supported("u", parameters=[math.pi, math.pi, math.pi]))
self.assertTrue(
target.instruction_supported(
operation_class=UGate, parameters=[math.pi, math.pi, math.pi]
)
)
self.assertFalse(
target.instruction_supported(operation_class=UGate, parameters=[Parameter("x")])
)
def test_instruction_supported_arg_len_mismatch(self):
self.assertFalse(
self.ideal_sim_target.instruction_supported(operation_class=UGate, parameters=[math.pi])
)
self.assertFalse(self.ideal_sim_target.instruction_supported("u", parameters=[math.pi]))
def test_instruction_supported_class_not_in_target(self):
self.assertFalse(
self.ibm_target.instruction_supported(operation_class=CZGate, parameters=[math.pi])
)
def test_instruction_supported_no_args(self):
self.assertFalse(self.ibm_target.instruction_supported())
def test_instruction_supported_no_operation(self):
self.assertFalse(self.ibm_target.instruction_supported(qargs=(0,), parameters=[math.pi]))
class TestPulseTarget(QiskitTestCase):
def setUp(self):
super().setUp()
self.pulse_target = Target(
dt=3e-7, granularity=2, min_length=4, pulse_alignment=8, acquire_alignment=8
)
with pulse.build(name="sx_q0") as self.custom_sx_q0:
pulse.play(pulse.Constant(100, 0.1), pulse.DriveChannel(0))
with pulse.build(name="sx_q1") as self.custom_sx_q1:
pulse.play(pulse.Constant(100, 0.2), pulse.DriveChannel(1))
sx_props = {
(0,): InstructionProperties(
duration=35.5e-9, error=0.000413, calibration=self.custom_sx_q0
),
(1,): InstructionProperties(
duration=35.5e-9, error=0.000502, calibration=self.custom_sx_q1
),
}
self.pulse_target.add_instruction(SXGate(), sx_props)
def test_instruction_schedule_map(self):
inst_map = self.pulse_target.instruction_schedule_map()
self.assertIn("sx", inst_map.instructions)
self.assertEqual(inst_map.qubits_with_instruction("sx"), [0, 1])
self.assertTrue("sx" in inst_map.qubit_instructions(0))
def test_instruction_schedule_map_ideal_sim_backend(self):
ideal_sim_target = Target(num_qubits=3)
theta = Parameter("theta")
phi = Parameter("phi")
lam = Parameter("lambda")
for inst in [
UGate(theta, phi, lam),
RXGate(theta),
RYGate(theta),
RZGate(theta),
CXGate(),
ECRGate(),
CCXGate(),
Measure(),
]:
ideal_sim_target.add_instruction(inst, {None: None})
inst_map = ideal_sim_target.instruction_schedule_map()
self.assertEqual(InstructionScheduleMap(), inst_map)
def test_str(self):
expected = """Target
Number of qubits: 2
Instructions:
sx
(0,):
Duration: 3.55e-08 sec.
Error Rate: 0.000413
With pulse schedule calibration
(1,):
Duration: 3.55e-08 sec.
Error Rate: 0.000502
With pulse schedule calibration
"""
self.assertEqual(expected, str(self.pulse_target))
def test_update_from_instruction_schedule_map_add_instruction(self):
target = Target()
inst_map = InstructionScheduleMap()
inst_map.add("sx", 0, self.custom_sx_q0)
inst_map.add("sx", 1, self.custom_sx_q1)
target.update_from_instruction_schedule_map(inst_map, {"sx": SXGate()})
self.assertEqual(inst_map, target.instruction_schedule_map())
def test_update_from_instruction_schedule_map_with_schedule_parameter(self):
self.pulse_target.dt = None
inst_map = InstructionScheduleMap()
duration = Parameter("duration")
with pulse.build(name="sx_q0") as custom_sx:
pulse.play(pulse.Constant(duration, 0.2), pulse.DriveChannel(0))
inst_map.add("sx", 0, custom_sx, ["duration"])
target = Target(dt=3e-7)
target.update_from_instruction_schedule_map(inst_map, {"sx": SXGate()})
self.assertEqual(inst_map, target.instruction_schedule_map())
def test_update_from_instruction_schedule_map_update_schedule(self):
self.pulse_target.dt = None
inst_map = InstructionScheduleMap()
with pulse.build(name="sx_q1") as custom_sx:
pulse.play(pulse.Constant(1000, 0.2), pulse.DriveChannel(1))
inst_map.add("sx", 0, self.custom_sx_q0)
inst_map.add("sx", 1, custom_sx)
self.pulse_target.update_from_instruction_schedule_map(inst_map, {"sx": SXGate()})
self.assertEqual(inst_map, self.pulse_target.instruction_schedule_map())
# Calibration doesn't change for q0
self.assertEqual(self.pulse_target["sx"][(0,)].duration, 35.5e-9)
self.assertEqual(self.pulse_target["sx"][(0,)].error, 0.000413)
# Calibration is updated for q1 without error dict and gate time
self.assertIsNone(self.pulse_target["sx"][(1,)].duration)
self.assertIsNone(self.pulse_target["sx"][(1,)].error)
def test_update_from_instruction_schedule_map_new_instruction_no_name_map(self):
target = Target()
inst_map = InstructionScheduleMap()
inst_map.add("sx", 0, self.custom_sx_q0)
inst_map.add("sx", 1, self.custom_sx_q1)
target.update_from_instruction_schedule_map(inst_map)
self.assertEqual(target["sx"][(0,)].calibration, self.custom_sx_q0)
self.assertEqual(target["sx"][(1,)].calibration, self.custom_sx_q1)
def test_update_from_instruction_schedule_map_new_qarg_raises(self):
inst_map = InstructionScheduleMap()
inst_map.add("sx", 0, self.custom_sx_q0)
inst_map.add("sx", 1, self.custom_sx_q1)
inst_map.add("sx", 2, self.custom_sx_q1)
self.pulse_target.update_from_instruction_schedule_map(inst_map)
self.assertFalse(self.pulse_target.instruction_supported("sx", (2,)))
def test_update_from_instruction_schedule_map_with_dt_set(self):
inst_map = InstructionScheduleMap()
with pulse.build(name="sx_q1") as custom_sx:
pulse.play(pulse.Constant(1000, 0.2), pulse.DriveChannel(1))
inst_map.add("sx", 0, self.custom_sx_q0)
inst_map.add("sx", 1, custom_sx)
self.pulse_target.dt = 1.0
self.pulse_target.update_from_instruction_schedule_map(inst_map, {"sx": SXGate()})
self.assertEqual(inst_map, self.pulse_target.instruction_schedule_map())
self.assertEqual(self.pulse_target["sx"][(1,)].duration, 1000.0)
self.assertIsNone(self.pulse_target["sx"][(1,)].error)
# This is an edge case.
# System dt is read-only property and changing it will break all underlying calibrations.
# duration of sx0 returns previous value since calibration doesn't change.
self.assertEqual(self.pulse_target["sx"][(0,)].duration, 35.5e-9)
self.assertEqual(self.pulse_target["sx"][(0,)].error, 0.000413)
def test_update_from_instruction_schedule_map_with_error_dict(self):
inst_map = InstructionScheduleMap()
with pulse.build(name="sx_q1") as custom_sx:
pulse.play(pulse.Constant(1000, 0.2), pulse.DriveChannel(1))
inst_map.add("sx", 0, self.custom_sx_q0)
inst_map.add("sx", 1, custom_sx)
self.pulse_target.dt = 1.0
error_dict = {"sx": {(1,): 1.0}}
self.pulse_target.update_from_instruction_schedule_map(
inst_map, {"sx": SXGate()}, error_dict=error_dict
)
self.assertEqual(self.pulse_target["sx"][(1,)].error, 1.0)
self.assertEqual(self.pulse_target["sx"][(0,)].error, 0.000413)
def test_timing_constraints(self):
generated_constraints = self.pulse_target.timing_constraints()
expected_constraints = TimingConstraints(2, 4, 8, 8)
for i in ["granularity", "min_length", "pulse_alignment", "acquire_alignment"]:
self.assertEqual(
getattr(generated_constraints, i),
getattr(expected_constraints, i),
f"Generated constraints differs from expected for attribute {i}"
f"{getattr(generated_constraints, i)}!={getattr(expected_constraints, i)}",
)
def test_default_instmap_has_no_custom_gate(self):
backend = FakeGeneva()
target = backend.target
# This copies .calibraiton of InstructionProperties of each instruction
# This must not convert PulseQobj to Schedule during this.
# See qiskit-terra/#9595
inst_map = target.instruction_schedule_map()
self.assertFalse(inst_map.has_custom_gate())
# Get pulse schedule. This generates Schedule provided by backend.
sched = inst_map.get("sx", (0,))
self.assertEqual(sched.metadata["publisher"], CalibrationPublisher.BACKEND_PROVIDER)
self.assertFalse(inst_map.has_custom_gate())
# Update target with custom instruction. This is user provided schedule.
new_prop = InstructionProperties(
duration=self.custom_sx_q0.duration,
error=None,
calibration=self.custom_sx_q0,
)
target.update_instruction_properties(instruction="sx", qargs=(0,), properties=new_prop)
inst_map = target.instruction_schedule_map()
self.assertTrue(inst_map.has_custom_gate())
empty = InstructionProperties()
target.update_instruction_properties(instruction="sx", qargs=(0,), properties=empty)
inst_map = target.instruction_schedule_map()
self.assertFalse(inst_map.has_custom_gate())
def test_get_empty_target_calibration(self):
target = Target()
properties = {(0,): InstructionProperties(duration=100, error=0.1)}
target.add_instruction(XGate(), properties)
self.assertIsNone(target["x"][(0,)].calibration)
def test_loading_legacy_ugate_instmap(self):
# This is typical IBM backend situation.
# IBM provider used to have u1, u2, u3 in the basis gates and
# these have been replaced with sx and rz.
# However, IBM provider still provides calibration of these u gates,
# and the inst map loads them as backend calibrations.
# Target is implicitly updated with inst map when it is set in transpile.
# If u gates are not excluded, they may appear in the transpiled circuit.
# These gates are no longer supported by hardware.
entry = ScheduleDef()
entry.define(pulse.Schedule(name="fake_u3"), user_provided=False) # backend provided
instmap = InstructionScheduleMap()
instmap._add("u3", (0,), entry)
# Today's standard IBM backend target with sx, rz basis
target = Target()
target.add_instruction(SXGate(), {(0,): InstructionProperties()})
target.add_instruction(RZGate(Parameter("θ")), {(0,): InstructionProperties()})
target.add_instruction(Measure(), {(0,): InstructionProperties()})
names_before = set(target.operation_names)
target.update_from_instruction_schedule_map(instmap)
names_after = set(target.operation_names)
# Otherwise u3 and sx-rz basis conflict in 1q decomposition.
self.assertSetEqual(names_before, names_after)
class TestGlobalVariableWidthOperations(QiskitTestCase):
def setUp(self):
super().setUp()
self.theta = Parameter("theta")
self.phi = Parameter("phi")
self.lam = Parameter("lambda")
self.target_global_gates_only = Target(num_qubits=5)
self.target_global_gates_only.add_instruction(CXGate())
self.target_global_gates_only.add_instruction(UGate(self.theta, self.phi, self.lam))
self.target_global_gates_only.add_instruction(Measure())
self.target_global_gates_only.add_instruction(IfElseOp, name="if_else")
self.target_global_gates_only.add_instruction(ForLoopOp, name="for_loop")
self.target_global_gates_only.add_instruction(WhileLoopOp, name="while_loop")
self.target_global_gates_only.add_instruction(SwitchCaseOp, name="switch_case")
self.ibm_target = Target()
i_props = {
(0,): InstructionProperties(duration=35.5e-9, error=0.000413),
(1,): InstructionProperties(duration=35.5e-9, error=0.000502),
(2,): InstructionProperties(duration=35.5e-9, error=0.0004003),
(3,): InstructionProperties(duration=35.5e-9, error=0.000614),
(4,): InstructionProperties(duration=35.5e-9, error=0.006149),
}
self.ibm_target.add_instruction(IGate(), i_props)
rz_props = {
(0,): InstructionProperties(duration=0, error=0),
(1,): InstructionProperties(duration=0, error=0),
(2,): InstructionProperties(duration=0, error=0),
(3,): InstructionProperties(duration=0, error=0),
(4,): InstructionProperties(duration=0, error=0),
}
self.ibm_target.add_instruction(RZGate(self.theta), rz_props)
sx_props = {
(0,): InstructionProperties(duration=35.5e-9, error=0.000413),
(1,): InstructionProperties(duration=35.5e-9, error=0.000502),
(2,): InstructionProperties(duration=35.5e-9, error=0.0004003),
(3,): InstructionProperties(duration=35.5e-9, error=0.000614),
(4,): InstructionProperties(duration=35.5e-9, error=0.006149),
}
self.ibm_target.add_instruction(SXGate(), sx_props)
x_props = {
(0,): InstructionProperties(duration=35.5e-9, error=0.000413),
(1,): InstructionProperties(duration=35.5e-9, error=0.000502),
(2,): InstructionProperties(duration=35.5e-9, error=0.0004003),
(3,): InstructionProperties(duration=35.5e-9, error=0.000614),
(4,): InstructionProperties(duration=35.5e-9, error=0.006149),
}
self.ibm_target.add_instruction(XGate(), x_props)
cx_props = {
(3, 4): InstructionProperties(duration=270.22e-9, error=0.00713),
(4, 3): InstructionProperties(duration=305.77e-9, error=0.00713),
(3, 1): InstructionProperties(duration=462.22e-9, error=0.00929),
(1, 3): InstructionProperties(duration=497.77e-9, error=0.00929),
(1, 2): InstructionProperties(duration=227.55e-9, error=0.00659),
(2, 1): InstructionProperties(duration=263.11e-9, error=0.00659),
(0, 1): InstructionProperties(duration=519.11e-9, error=0.01201),
(1, 0): InstructionProperties(duration=554.66e-9, error=0.01201),
}
self.ibm_target.add_instruction(CXGate(), cx_props)
measure_props = {
(0,): InstructionProperties(duration=5.813e-6, error=0.0751),
(1,): InstructionProperties(duration=5.813e-6, error=0.0225),
(2,): InstructionProperties(duration=5.813e-6, error=0.0146),
(3,): InstructionProperties(duration=5.813e-6, error=0.0215),
(4,): InstructionProperties(duration=5.813e-6, error=0.0333),
}
self.ibm_target.add_instruction(Measure(), measure_props)
self.ibm_target.add_instruction(IfElseOp, name="if_else")
self.ibm_target.add_instruction(ForLoopOp, name="for_loop")
self.ibm_target.add_instruction(WhileLoopOp, name="while_loop")
self.ibm_target.add_instruction(SwitchCaseOp, name="switch_case")
self.aqt_target = Target(description="AQT Target")
rx_props = {
(0,): None,
(1,): None,
(2,): None,
(3,): None,
(4,): None,
}
self.aqt_target.add_instruction(RXGate(self.theta), rx_props)
ry_props = {
(0,): None,
(1,): None,
(2,): None,
(3,): None,
(4,): None,
}
self.aqt_target.add_instruction(RYGate(self.theta), ry_props)
rz_props = {
(0,): None,
(1,): None,
(2,): None,
(3,): None,
(4,): None,
}
self.aqt_target.add_instruction(RZGate(self.theta), rz_props)
r_props = {
(0,): None,
(1,): None,
(2,): None,
(3,): None,
(4,): None,
}
self.aqt_target.add_instruction(RGate(self.theta, self.phi), r_props)
rxx_props = {
(0, 1): None,
(0, 2): None,
(0, 3): None,
(0, 4): None,
(1, 0): None,
(2, 0): None,
(3, 0): None,
(4, 0): None,
(1, 2): None,
(1, 3): None,
(1, 4): None,
(2, 1): None,
(3, 1): None,
(4, 1): None,
(2, 3): None,
(2, 4): None,
(3, 2): None,
(4, 2): None,
(3, 4): None,
(4, 3): None,
}
self.aqt_target.add_instruction(RXXGate(self.theta), rxx_props)
measure_props = {
(0,): None,
(1,): None,
(2,): None,
(3,): None,
(4,): None,
}
self.aqt_target.add_instruction(Measure(), measure_props)
self.aqt_target.add_instruction(IfElseOp, name="if_else")
self.aqt_target.add_instruction(ForLoopOp, name="for_loop")
self.aqt_target.add_instruction(WhileLoopOp, name="while_loop")
self.aqt_target.add_instruction(SwitchCaseOp, name="switch_case")
def test_qargs(self):
expected_ibm = {
(0,),
(1,),
(2,),
(3,),
(4,),
(3, 4),
(4, 3),
(3, 1),
(1, 3),
(1, 2),
(2, 1),
(0, 1),
(1, 0),
}
self.assertEqual(expected_ibm, self.ibm_target.qargs)
expected_aqt = {
(0,),
(1,),
(2,),
(3,),
(4,),
(0, 1),
(0, 2),
(0, 3),
(0, 4),
(1, 0),
(2, 0),
(3, 0),
(4, 0),
(1, 2),
(1, 3),
(1, 4),
(2, 1),
(3, 1),
(4, 1),
(2, 3),
(2, 4),
(3, 2),
(4, 2),
(3, 4),
(4, 3),
}
self.assertEqual(expected_aqt, self.aqt_target.qargs)
self.assertEqual(None, self.target_global_gates_only.qargs)
def test_qargs_single_qarg(self):
target = Target()
target.add_instruction(XGate(), {(0,): None})
self.assertEqual(
{
(0,),
},
target.qargs,
)
def test_qargs_for_operation_name(self):
self.assertEqual(
self.ibm_target.qargs_for_operation_name("rz"), {(0,), (1,), (2,), (3,), (4,)}
)
self.assertEqual(
self.aqt_target.qargs_for_operation_name("rz"), {(0,), (1,), (2,), (3,), (4,)}
)
self.assertIsNone(self.target_global_gates_only.qargs_for_operation_name("cx"))
self.assertIsNone(self.ibm_target.qargs_for_operation_name("if_else"))
self.assertIsNone(self.aqt_target.qargs_for_operation_name("while_loop"))
self.assertIsNone(self.aqt_target.qargs_for_operation_name("switch_case"))
def test_instruction_names(self):
self.assertEqual(
self.ibm_target.operation_names,
{
"rz",
"id",
"sx",
"x",
"cx",
"measure",
"if_else",
"while_loop",
"for_loop",
"switch_case",
},
)
self.assertEqual(
self.aqt_target.operation_names,
{
"rz",
"ry",
"rx",
"rxx",
"r",
"measure",
"if_else",
"while_loop",
"for_loop",
"switch_case",
},
)
self.assertEqual(
self.target_global_gates_only.operation_names,
{"u", "cx", "measure", "if_else", "while_loop", "for_loop", "switch_case"},
)
def test_operations_for_qargs(self):
expected = [
IGate(),
RZGate(self.theta),
SXGate(),
XGate(),
Measure(),
IfElseOp,
ForLoopOp,
WhileLoopOp,
SwitchCaseOp,
]
res = self.ibm_target.operations_for_qargs((0,))
self.assertEqual(len(expected), len(res))
for x in expected:
self.assertIn(x, res)
expected = [
CXGate(),
IfElseOp,
ForLoopOp,
WhileLoopOp,
SwitchCaseOp,
]
res = self.ibm_target.operations_for_qargs((0, 1))
self.assertEqual(len(expected), len(res))
for x in expected:
self.assertIn(x, res)
expected = [
RXGate(self.theta),
RYGate(self.theta),
RZGate(self.theta),
RGate(self.theta, self.phi),
Measure(),
IfElseOp,
ForLoopOp,
WhileLoopOp,
SwitchCaseOp,
]
res = self.aqt_target.operations_for_qargs((0,))
self.assertEqual(len(expected), len(res))
for x in expected:
self.assertIn(x, res)
expected = [RXXGate(self.theta), IfElseOp, ForLoopOp, WhileLoopOp, SwitchCaseOp]
res = self.aqt_target.operations_for_qargs((0, 1))
self.assertEqual(len(expected), len(res))
for x in expected:
self.assertIn(x, res)
def test_operation_names_for_qargs(self):
expected = {
"id",
"rz",
"sx",
"x",
"measure",
"if_else",
"for_loop",
"while_loop",
"switch_case",
}
self.assertEqual(expected, self.ibm_target.operation_names_for_qargs((0,)))
expected = {
"cx",
"if_else",
"for_loop",
"while_loop",
"switch_case",
}
self.assertEqual(expected, self.ibm_target.operation_names_for_qargs((0, 1)))
expected = {
"rx",
"ry",
"rz",
"r",
"measure",
"if_else",
"for_loop",
"while_loop",
"switch_case",
}
self.assertEqual(self.aqt_target.operation_names_for_qargs((0,)), expected)
expected = {"rxx", "if_else", "for_loop", "while_loop", "switch_case"}
self.assertEqual(self.aqt_target.operation_names_for_qargs((0, 1)), expected)
def test_operations(self):
ibm_expected = [
RZGate(self.theta),
IGate(),
SXGate(),
XGate(),
CXGate(),
Measure(),
WhileLoopOp,
IfElseOp,
ForLoopOp,
SwitchCaseOp,
]
for gate in ibm_expected:
self.assertIn(gate, self.ibm_target.operations)
aqt_expected = [
RZGate(self.theta),
RXGate(self.theta),
RYGate(self.theta),
RGate(self.theta, self.phi),
RXXGate(self.theta),
ForLoopOp,
IfElseOp,
WhileLoopOp,
SwitchCaseOp,
]
for gate in aqt_expected:
self.assertIn(gate, self.aqt_target.operations)
fake_expected = [
UGate(self.theta, self.phi, self.lam),
CXGate(),
Measure(),
ForLoopOp,
WhileLoopOp,
IfElseOp,
SwitchCaseOp,
]
for gate in fake_expected:
self.assertIn(gate, self.target_global_gates_only.operations)
def test_add_invalid_instruction(self):
inst_props = {(0, 1, 2, 3): None}
target = Target()
with self.assertRaises(TranspilerError):
target.add_instruction(CXGate(), inst_props)
def test_instructions(self):
ibm_expected = [
(IGate(), (0,)),
(IGate(), (1,)),
(IGate(), (2,)),
(IGate(), (3,)),
(IGate(), (4,)),
(RZGate(self.theta), (0,)),
(RZGate(self.theta), (1,)),
(RZGate(self.theta), (2,)),
(RZGate(self.theta), (3,)),
(RZGate(self.theta), (4,)),
(SXGate(), (0,)),
(SXGate(), (1,)),
(SXGate(), (2,)),
(SXGate(), (3,)),
(SXGate(), (4,)),
(XGate(), (0,)),
(XGate(), (1,)),
(XGate(), (2,)),
(XGate(), (3,)),
(XGate(), (4,)),
(CXGate(), (3, 4)),
(CXGate(), (4, 3)),
(CXGate(), (3, 1)),
(CXGate(), (1, 3)),
(CXGate(), (1, 2)),
(CXGate(), (2, 1)),
(CXGate(), (0, 1)),
(CXGate(), (1, 0)),
(Measure(), (0,)),
(Measure(), (1,)),
(Measure(), (2,)),
(Measure(), (3,)),
(Measure(), (4,)),
(IfElseOp, None),
(ForLoopOp, None),
(WhileLoopOp, None),
(SwitchCaseOp, None),
]
self.assertEqual(ibm_expected, self.ibm_target.instructions)
ideal_sim_expected = [
(CXGate(), None),
(UGate(self.theta, self.phi, self.lam), None),
(Measure(), None),
(IfElseOp, None),
(ForLoopOp, None),
(WhileLoopOp, None),
(SwitchCaseOp, None),
]
self.assertEqual(ideal_sim_expected, self.target_global_gates_only.instructions)
def test_instruction_supported(self):
self.assertTrue(self.aqt_target.instruction_supported("r", (0,)))
self.assertFalse(self.aqt_target.instruction_supported("cx", (0, 1)))
self.assertTrue(self.target_global_gates_only.instruction_supported("cx", (0, 1)))
self.assertFalse(self.target_global_gates_only.instruction_supported("cx", (0, 524)))
self.assertFalse(self.target_global_gates_only.instruction_supported("cx", (0, 1, 2)))
self.assertTrue(self.aqt_target.instruction_supported("while_loop", (0, 1, 2, 3)))
self.assertTrue(
self.aqt_target.instruction_supported(operation_class=WhileLoopOp, qargs=(0, 1, 2, 3))
)
self.assertTrue(
self.aqt_target.instruction_supported(operation_class=SwitchCaseOp, qargs=(0, 1, 2, 3))
)
self.assertFalse(
self.ibm_target.instruction_supported(
operation_class=IfElseOp, qargs=(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
)
)
self.assertFalse(
self.ibm_target.instruction_supported(operation_class=IfElseOp, qargs=(0, 425))
)
self.assertFalse(self.ibm_target.instruction_supported("for_loop", qargs=(0, 425)))
def test_coupling_map(self):
self.assertIsNone(self.target_global_gates_only.build_coupling_map())
self.assertEqual(
set(CouplingMap.from_full(5).get_edges()),
set(self.aqt_target.build_coupling_map().get_edges()),
)
self.assertEqual(
{
(3, 4),
(4, 3),
(3, 1),
(1, 3),
(1, 2),
(2, 1),
(0, 1),
(1, 0),
},
set(self.ibm_target.build_coupling_map().get_edges()),
)
class TestInstructionProperties(QiskitTestCase):
def test_empty_repr(self):
properties = InstructionProperties()
self.assertEqual(
repr(properties),
"InstructionProperties(duration=None, error=None, calibration=None)",
)
class TestTargetFromConfiguration(QiskitTestCase):
"""Test the from_configuration() constructor."""
def test_basis_gates_qubits_only(self):
"""Test construction with only basis gates."""
target = Target.from_configuration(["u", "cx"], 3)
self.assertEqual(target.operation_names, {"u", "cx"})
def test_basis_gates_no_qubits(self):
target = Target.from_configuration(["u", "cx"])
self.assertEqual(target.operation_names, {"u", "cx"})
def test_basis_gates_coupling_map(self):
"""Test construction with only basis gates."""
target = Target.from_configuration(
["u", "cx"], 3, CouplingMap.from_ring(3, bidirectional=False)
)
self.assertEqual(target.operation_names, {"u", "cx"})
self.assertEqual({(0,), (1,), (2,)}, target["u"].keys())
self.assertEqual({(0, 1), (1, 2), (2, 0)}, target["cx"].keys())
def test_properties(self):
fake_backend = FakeVigo()
config = fake_backend.configuration()
properties = fake_backend.properties()
target = Target.from_configuration(
basis_gates=config.basis_gates,
num_qubits=config.num_qubits,
coupling_map=CouplingMap(config.coupling_map),
backend_properties=properties,
)
self.assertEqual(0, target["rz"][(0,)].error)
self.assertEqual(0, target["rz"][(0,)].duration)
def test_properties_with_durations(self):
fake_backend = FakeVigo()
config = fake_backend.configuration()
properties = fake_backend.properties()
durations = InstructionDurations([("rz", 0, 0.5)], dt=1.0)
target = Target.from_configuration(
basis_gates=config.basis_gates,
num_qubits=config.num_qubits,
coupling_map=CouplingMap(config.coupling_map),
backend_properties=properties,
instruction_durations=durations,
dt=config.dt,
)
self.assertEqual(0.5, target["rz"][(0,)].duration)
def test_inst_map(self):
fake_backend = FakeNairobi()
config = fake_backend.configuration()
properties = fake_backend.properties()
defaults = fake_backend.defaults()
constraints = TimingConstraints(**config.timing_constraints)
target = Target.from_configuration(
basis_gates=config.basis_gates,
num_qubits=config.num_qubits,
coupling_map=CouplingMap(config.coupling_map),
backend_properties=properties,
dt=config.dt,
inst_map=defaults.instruction_schedule_map,
timing_constraints=constraints,
)
self.assertIsNotNone(target["sx"][(0,)].calibration)
self.assertEqual(target.granularity, constraints.granularity)
self.assertEqual(target.min_length, constraints.min_length)
self.assertEqual(target.pulse_alignment, constraints.pulse_alignment)
self.assertEqual(target.acquire_alignment, constraints.acquire_alignment)
def test_concurrent_measurements(self):
fake_backend = FakeVigo()
config = fake_backend.configuration()
target = Target.from_configuration(
basis_gates=config.basis_gates,
concurrent_measurements=config.meas_map,
)
self.assertEqual(target.concurrent_measurements, config.meas_map)
def test_custom_basis_gates(self):
basis_gates = ["my_x", "cx"]
custom_name_mapping = {"my_x": XGate()}
target = Target.from_configuration(
basis_gates=basis_gates, num_qubits=2, custom_name_mapping=custom_name_mapping
)
self.assertEqual(target.operation_names, {"my_x", "cx"})
def test_missing_custom_basis_no_coupling(self):
basis_gates = ["my_X", "cx"]
with self.assertRaisesRegex(KeyError, "is not present in the standard gate names"):
Target.from_configuration(basis_gates, num_qubits=4)
def test_missing_custom_basis_with_coupling(self):
basis_gates = ["my_X", "cx"]
cmap = CouplingMap.from_line(3)
with self.assertRaisesRegex(KeyError, "is not present in the standard gate names"):
Target.from_configuration(basis_gates, 3, cmap)
def test_over_two_qubit_gate_without_coupling(self):
basis_gates = ["ccx", "cx", "swap", "u"]
target = Target.from_configuration(basis_gates, 15)
self.assertEqual(target.operation_names, {"ccx", "cx", "swap", "u"})
def test_over_two_qubits_with_coupling(self):
basis_gates = ["ccx", "cx", "swap", "u"]
cmap = CouplingMap.from_line(15)
with self.assertRaisesRegex(TranspilerError, "This constructor method only supports"):
Target.from_configuration(basis_gates, 15, cmap)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the TemplateOptimization pass."""
import unittest
from test.python.quantum_info.operators.symplectic.test_clifford import random_clifford_circuit
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.circuit import Parameter
from qiskit.quantum_info import Operator
from qiskit.circuit.library.templates.nct import template_nct_2a_2, template_nct_5a_3
from qiskit.circuit.library.templates.clifford import (
clifford_2_1,
clifford_2_2,
clifford_2_3,
clifford_2_4,
clifford_3_1,
clifford_4_1,
clifford_4_2,
)
from qiskit.converters.circuit_to_dag import circuit_to_dag
from qiskit.converters.circuit_to_dagdependency import circuit_to_dagdependency
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import TemplateOptimization
from qiskit.transpiler.passes.calibration.rzx_templates import rzx_templates
from qiskit.test import QiskitTestCase
from qiskit.transpiler.exceptions import TranspilerError
def _ry_to_rz_template_pass(parameter: Parameter = None, extra_costs=None):
"""Create a simple pass manager that runs a template optimisation with a single transformation.
It turns ``RX(pi/2).RY(parameter).RX(-pi/2)`` into the equivalent virtual ``RZ`` rotation, where
if ``parameter`` is given, it will be the instance used in the template."""
if parameter is None:
parameter = Parameter("_ry_rz_template_inner")
template = QuantumCircuit(1)
template.rx(-np.pi / 2, 0)
template.ry(parameter, 0)
template.rx(np.pi / 2, 0)
template.rz(-parameter, 0) # pylint: disable=invalid-unary-operand-type
costs = {"rx": 16, "ry": 16, "rz": 0}
if extra_costs is not None:
costs.update(extra_costs)
return PassManager(TemplateOptimization([template], user_cost_dict=costs))
class TestTemplateMatching(QiskitTestCase):
"""Test the TemplateOptimization pass."""
def test_pass_cx_cancellation_no_template_given(self):
"""
Check the cancellation of CX gates for the apply of the three basic
template x-x, cx-cx. ccx-ccx.
"""
qr = QuantumRegister(3)
circuit_in = QuantumCircuit(qr)
circuit_in.h(qr[0])
circuit_in.h(qr[0])
circuit_in.cx(qr[0], qr[1])
circuit_in.cx(qr[0], qr[1])
circuit_in.cx(qr[0], qr[1])
circuit_in.cx(qr[0], qr[1])
circuit_in.cx(qr[1], qr[0])
circuit_in.cx(qr[1], qr[0])
pass_manager = PassManager()
pass_manager.append(TemplateOptimization())
circuit_in_opt = pass_manager.run(circuit_in)
circuit_out = QuantumCircuit(qr)
circuit_out.h(qr[0])
circuit_out.h(qr[0])
self.assertEqual(circuit_in_opt, circuit_out)
def test_pass_cx_cancellation_own_template(self):
"""
Check the cancellation of CX gates for the apply of a self made template cx-cx.
"""
qr = QuantumRegister(2, "qr")
circuit_in = QuantumCircuit(qr)
circuit_in.h(qr[0])
circuit_in.h(qr[0])
circuit_in.cx(qr[0], qr[1])
circuit_in.cx(qr[0], qr[1])
circuit_in.cx(qr[0], qr[1])
circuit_in.cx(qr[0], qr[1])
circuit_in.cx(qr[1], qr[0])
circuit_in.cx(qr[1], qr[0])
dag_in = circuit_to_dag(circuit_in)
qrt = QuantumRegister(2, "qrc")
qct = QuantumCircuit(qrt)
qct.cx(0, 1)
qct.cx(0, 1)
template_list = [qct]
pass_ = TemplateOptimization(template_list)
dag_opt = pass_.run(dag_in)
circuit_expected = QuantumCircuit(qr)
circuit_expected.h(qr[0])
circuit_expected.h(qr[0])
dag_expected = circuit_to_dag(circuit_expected)
self.assertEqual(dag_opt, dag_expected)
def test_pass_cx_cancellation_template_from_library(self):
"""
Check the cancellation of CX gates for the apply of the library template cx-cx (2a_2).
"""
qr = QuantumRegister(2, "qr")
circuit_in = QuantumCircuit(qr)
circuit_in.h(qr[0])
circuit_in.h(qr[0])
circuit_in.cx(qr[0], qr[1])
circuit_in.cx(qr[0], qr[1])
circuit_in.cx(qr[0], qr[1])
circuit_in.cx(qr[0], qr[1])
circuit_in.cx(qr[1], qr[0])
circuit_in.cx(qr[1], qr[0])
dag_in = circuit_to_dag(circuit_in)
template_list = [template_nct_2a_2()]
pass_ = TemplateOptimization(template_list)
dag_opt = pass_.run(dag_in)
circuit_expected = QuantumCircuit(qr)
circuit_expected.h(qr[0])
circuit_expected.h(qr[0])
dag_expected = circuit_to_dag(circuit_expected)
self.assertEqual(dag_opt, dag_expected)
def test_pass_template_nct_5a(self):
"""
Verify the result of template matching and substitution with the template 5a_3.
q_0: ───────■─────────■────■──
┌─┴─┐ ┌─┴─┐ │
q_1: ──■──┤ X ├──■──┤ X ├──┼──
┌─┴─┐└───┘┌─┴─┐└───┘┌─┴─┐
q_2: ┤ X ├─────┤ X ├─────┤ X ├
└───┘ └───┘ └───┘
The circuit before optimization is:
┌───┐ ┌───┐
qr_0: ┤ X ├───────────────┤ X ├─────
└─┬─┘ ┌───┐┌───┐└─┬─┘
qr_1: ──┼────■──┤ X ├┤ Z ├──┼────■──
│ │ └─┬─┘└───┘ │ │
qr_2: ──┼────┼────■────■────■────┼──
│ │ ┌───┐┌─┴─┐ │ │
qr_3: ──■────┼──┤ H ├┤ X ├──■────┼──
│ ┌─┴─┐└───┘└───┘ ┌─┴─┐
qr_4: ──■──┤ X ├───────────────┤ X ├
└───┘ └───┘
The match is given by [0,1][1,2][2,7], after substitution the circuit becomes:
┌───┐ ┌───┐
qr_0: ┤ X ├───────────────┤ X ├
└─┬─┘ ┌───┐┌───┐└─┬─┘
qr_1: ──┼───────┤ X ├┤ Z ├──┼──
│ └─┬─┘└───┘ │
qr_2: ──┼────■────■────■────■──
│ │ ┌───┐┌─┴─┐ │
qr_3: ──■────┼──┤ H ├┤ X ├──■──
│ ┌─┴─┐└───┘└───┘
qr_4: ──■──┤ X ├───────────────
└───┘
"""
qr = QuantumRegister(5, "qr")
circuit_in = QuantumCircuit(qr)
circuit_in.ccx(qr[3], qr[4], qr[0])
circuit_in.cx(qr[1], qr[4])
circuit_in.cx(qr[2], qr[1])
circuit_in.h(qr[3])
circuit_in.z(qr[1])
circuit_in.cx(qr[2], qr[3])
circuit_in.ccx(qr[2], qr[3], qr[0])
circuit_in.cx(qr[1], qr[4])
dag_in = circuit_to_dag(circuit_in)
template_list = [template_nct_5a_3()]
pass_ = TemplateOptimization(template_list)
dag_opt = pass_.run(dag_in)
# note: cx(2, 1) commutes both with ccx(3, 4, 0) and with cx(2, 4),
# so there is no real difference with the circuit drawn on the picture above.
circuit_expected = QuantumCircuit(qr)
circuit_expected.cx(qr[2], qr[1])
circuit_expected.ccx(qr[3], qr[4], qr[0])
circuit_expected.cx(qr[2], qr[4])
circuit_expected.z(qr[1])
circuit_expected.h(qr[3])
circuit_expected.cx(qr[2], qr[3])
circuit_expected.ccx(qr[2], qr[3], qr[0])
dag_expected = circuit_to_dag(circuit_expected)
self.assertEqual(dag_opt, dag_expected)
def test_pass_template_wrong_type(self):
"""
If a template is not equivalent to the identity, it raises an error.
"""
qr = QuantumRegister(2, "qr")
circuit_in = QuantumCircuit(qr)
circuit_in.h(qr[0])
circuit_in.h(qr[0])
circuit_in.cx(qr[0], qr[1])
circuit_in.cx(qr[0], qr[1])
circuit_in.cx(qr[0], qr[1])
circuit_in.cx(qr[0], qr[1])
circuit_in.cx(qr[1], qr[0])
circuit_in.cx(qr[1], qr[0])
dag_in = circuit_to_dag(circuit_in)
qrt = QuantumRegister(2, "qrc")
qct = QuantumCircuit(qrt)
qct.cx(0, 1)
qct.x(0)
qct.h(1)
template_list = [qct]
pass_ = TemplateOptimization(template_list)
self.assertRaises(TranspilerError, pass_.run, dag_in)
def test_accept_dagdependency(self):
"""
Check that users can supply DAGDependency in the template list.
"""
circuit_in = QuantumCircuit(2)
circuit_in.cnot(0, 1)
circuit_in.cnot(0, 1)
templates = [circuit_to_dagdependency(circuit_in)]
pass_ = TemplateOptimization(template_list=templates)
circuit_out = PassManager(pass_).run(circuit_in)
# these are NOT equal if template optimization works
self.assertNotEqual(circuit_in, circuit_out)
# however these are equivalent if the operators are the same
self.assertTrue(Operator(circuit_in).equiv(circuit_out))
def test_parametric_template(self):
"""
Check matching where template has parameters.
┌───────────┐ ┌────────┐
q_0: ┤ P(-1.0*β) ├──■────────────■──┤0 ├
├───────────┤┌─┴─┐┌──────┐┌─┴─┐│ CU(2β)│
q_1: ┤ P(-1.0*β) ├┤ X ├┤ P(β) ├┤ X ├┤1 ├
└───────────┘└───┘└──────┘└───┘└────────┘
First test try match on
┌───────┐
q_0: ┤ P(-2) ├──■────────────■─────────────────────────────
├───────┤┌─┴─┐┌──────┐┌─┴─┐┌───────┐
q_1: ┤ P(-2) ├┤ X ├┤ P(2) ├┤ X ├┤ P(-3) ├──■────────────■──
├───────┤└───┘└──────┘└───┘└───────┘┌─┴─┐┌──────┐┌─┴─┐
q_2: ┤ P(-3) ├───────────────────────────┤ X ├┤ P(3) ├┤ X ├
└───────┘ └───┘└──────┘└───┘
Second test try match on
┌───────┐
q_0: ┤ P(-2) ├──■────────────■────────────────────────────
├───────┤┌─┴─┐┌──────┐┌─┴─┐┌──────┐
q_1: ┤ P(-2) ├┤ X ├┤ P(2) ├┤ X ├┤ P(3) ├──■────────────■──
└┬──────┤└───┘└──────┘└───┘└──────┘┌─┴─┐┌──────┐┌─┴─┐
q_2: ─┤ P(3) ├──────────────────────────┤ X ├┤ P(3) ├┤ X ├
└──────┘ └───┘└──────┘└───┘
"""
beta = Parameter("β")
template = QuantumCircuit(2)
template.p(-beta, 0)
template.p(-beta, 1)
template.cx(0, 1)
template.p(beta, 1)
template.cx(0, 1)
template.cu(0, 2.0 * beta, 0, 0, 0, 1)
def count_cx(qc):
"""Counts the number of CX gates for testing."""
return qc.count_ops().get("cx", 0)
circuit_in = QuantumCircuit(3)
circuit_in.p(-2, 0)
circuit_in.p(-2, 1)
circuit_in.cx(0, 1)
circuit_in.p(2, 1)
circuit_in.cx(0, 1)
circuit_in.p(-3, 1)
circuit_in.p(-3, 2)
circuit_in.cx(1, 2)
circuit_in.p(3, 2)
circuit_in.cx(1, 2)
pass_ = TemplateOptimization(
template_list=[template],
user_cost_dict={"cx": 6, "p": 0, "cu": 8},
)
circuit_out = PassManager(pass_).run(circuit_in)
np.testing.assert_almost_equal(Operator(circuit_out).data[3, 3], np.exp(-4.0j))
np.testing.assert_almost_equal(Operator(circuit_out).data[7, 7], np.exp(-10.0j))
self.assertEqual(count_cx(circuit_out), 0) # Two matches => no CX gates.
np.testing.assert_almost_equal(Operator(circuit_in).data, Operator(circuit_out).data)
circuit_in = QuantumCircuit(3)
circuit_in.p(-2, 0)
circuit_in.p(-2, 1)
circuit_in.cx(0, 1)
circuit_in.p(2, 1)
circuit_in.cx(0, 1)
circuit_in.p(3, 1)
circuit_in.p(3, 2)
circuit_in.cx(1, 2)
circuit_in.p(3, 2)
circuit_in.cx(1, 2)
pass_ = TemplateOptimization(
template_list=[template],
user_cost_dict={"cx": 6, "p": 0, "cu": 8},
)
circuit_out = PassManager(pass_).run(circuit_in)
# these are NOT equal if template optimization works
self.assertNotEqual(circuit_in, circuit_out)
# however these are equivalent if the operators are the same
self.assertTrue(Operator(circuit_in).equiv(circuit_out))
def test_optimizer_does_not_replace_unbound_partial_match(self):
"""
Test that partial matches with parameters will not raise errors.
This tests that if parameters are still in the temporary template after
_attempt_bind then they will not be used.
"""
beta = Parameter("β")
template = QuantumCircuit(2)
template.cx(1, 0)
template.cx(1, 0)
template.p(beta, 1)
template.cu(0, 0, 0, -beta, 0, 1)
circuit_in = QuantumCircuit(2)
circuit_in.cx(1, 0)
circuit_in.cx(1, 0)
pass_ = TemplateOptimization(
template_list=[template],
user_cost_dict={"cx": 6, "p": 0, "cu": 8},
)
circuit_out = PassManager(pass_).run(circuit_in)
# The template optimisation should not have replaced anything, because
# that would require it to leave dummy parameters in place without
# binding them.
self.assertEqual(circuit_in, circuit_out)
def test_unbound_parameters_in_rzx_template(self):
"""
Test that rzx template ('zz2') functions correctly for a simple
circuit with an unbound ParameterExpression. This uses the same
Parameter (theta) as the template, so this also checks that template
substitution handle this correctly.
"""
theta = Parameter("ϴ")
circuit_in = QuantumCircuit(2)
circuit_in.cx(0, 1)
circuit_in.p(2 * theta, 1)
circuit_in.cx(0, 1)
pass_ = TemplateOptimization(**rzx_templates(["zz2"]))
circuit_out = PassManager(pass_).run(circuit_in)
# these are NOT equal if template optimization works
self.assertNotEqual(circuit_in, circuit_out)
# however these are equivalent if the operators are the same
theta_set = 0.42
self.assertTrue(
Operator(circuit_in.bind_parameters({theta: theta_set})).equiv(
circuit_out.bind_parameters({theta: theta_set})
)
)
def test_two_parameter_template(self):
"""
Test a two-Parameter template based on rzx_templates(["zz3"]),
┌───┐┌───────┐┌───┐┌────────────┐»
q_0: ──■─────────────■──┤ X ├┤ Rz(φ) ├┤ X ├┤ Rz(-1.0*φ) ├»
┌─┴─┐┌───────┐┌─┴─┐└─┬─┘└───────┘└─┬─┘└────────────┘»
q_1: ┤ X ├┤ Rz(θ) ├┤ X ├──■─────────────■────────────────»
└───┘└───────┘└───┘
« ┌─────────┐┌─────────┐┌─────────┐┌───────────┐┌──────────────┐»
«q_0: ┤ Rz(π/2) ├┤ Rx(π/2) ├┤ Rz(π/2) ├┤ Rx(1.0*φ) ├┤1 ├»
« └─────────┘└─────────┘└─────────┘└───────────┘│ Rzx(-1.0*φ) │»
«q_1: ──────────────────────────────────────────────┤0 ├»
« └──────────────┘»
« ┌─────────┐ ┌─────────┐┌─────────┐ »
«q_0: ─┤ Rz(π/2) ├──┤ Rx(π/2) ├┤ Rz(π/2) ├────────────────────────»
« ┌┴─────────┴─┐├─────────┤├─────────┤┌─────────┐┌───────────┐»
«q_1: ┤ Rz(-1.0*θ) ├┤ Rz(π/2) ├┤ Rx(π/2) ├┤ Rz(π/2) ├┤ Rx(1.0*θ) ├»
« └────────────┘└─────────┘└─────────┘└─────────┘└───────────┘»
« ┌──────────────┐
«q_0: ┤0 ├─────────────────────────────────
« │ Rzx(-1.0*θ) │┌─────────┐┌─────────┐┌─────────┐
«q_1: ┤1 ├┤ Rz(π/2) ├┤ Rx(π/2) ├┤ Rz(π/2) ├
« └──────────────┘└─────────┘└─────────┘└─────────┘
correctly template matches into a unique circuit, but that it is
equivalent to the input circuit when the Parameters are bound to floats
and checked with Operator equivalence.
"""
theta = Parameter("θ")
phi = Parameter("φ")
template = QuantumCircuit(2)
template.cx(0, 1)
template.rz(theta, 1)
template.cx(0, 1)
template.cx(1, 0)
template.rz(phi, 0)
template.cx(1, 0)
template.rz(-phi, 0)
template.rz(np.pi / 2, 0)
template.rx(np.pi / 2, 0)
template.rz(np.pi / 2, 0)
template.rx(phi, 0)
template.rzx(-phi, 1, 0)
template.rz(np.pi / 2, 0)
template.rz(-theta, 1)
template.rx(np.pi / 2, 0)
template.rz(np.pi / 2, 1)
template.rz(np.pi / 2, 0)
template.rx(np.pi / 2, 1)
template.rz(np.pi / 2, 1)
template.rx(theta, 1)
template.rzx(-theta, 0, 1)
template.rz(np.pi / 2, 1)
template.rx(np.pi / 2, 1)
template.rz(np.pi / 2, 1)
alpha = Parameter("$\\alpha$")
beta = Parameter("$\\beta$")
circuit_in = QuantumCircuit(2)
circuit_in.cx(0, 1)
circuit_in.rz(2 * alpha, 1)
circuit_in.cx(0, 1)
circuit_in.cx(1, 0)
circuit_in.rz(3 * beta, 0)
circuit_in.cx(1, 0)
pass_ = TemplateOptimization(
[template],
user_cost_dict={"cx": 6, "rz": 0, "rx": 1, "rzx": 0},
)
circuit_out = PassManager(pass_).run(circuit_in)
# these are NOT equal if template optimization works
self.assertNotEqual(circuit_in, circuit_out)
# however these are equivalent if the operators are the same
alpha_set = 0.37
beta_set = 0.42
self.assertTrue(
Operator(circuit_in.bind_parameters({alpha: alpha_set, beta: beta_set})).equiv(
circuit_out.bind_parameters({alpha: alpha_set, beta: beta_set})
)
)
def test_exact_substitution_numeric_parameter(self):
"""Test that a template match produces the expected value for numeric parameters."""
circuit_in = QuantumCircuit(1)
circuit_in.rx(-np.pi / 2, 0)
circuit_in.ry(1.45, 0)
circuit_in.rx(np.pi / 2, 0)
circuit_out = _ry_to_rz_template_pass().run(circuit_in)
expected = QuantumCircuit(1)
expected.rz(1.45, 0)
self.assertEqual(circuit_out, expected)
def test_exact_substitution_symbolic_parameter(self):
"""Test that a template match produces the expected value for numeric parameters."""
a_circuit = Parameter("a")
circuit_in = QuantumCircuit(1)
circuit_in.h(0)
circuit_in.rx(-np.pi / 2, 0)
circuit_in.ry(a_circuit, 0)
circuit_in.rx(np.pi / 2, 0)
circuit_out = _ry_to_rz_template_pass(extra_costs={"h": 1}).run(circuit_in)
expected = QuantumCircuit(1)
expected.h(0)
expected.rz(a_circuit, 0)
self.assertEqual(circuit_out, expected)
def test_naming_clash(self):
"""Test that the template matching works and correctly replaces a template if there is a
naming clash between it and the circuit. This should include binding a partial match with a
parameter."""
# Two instances of parameters with the same name---this is how naming clashes might occur.
a_template = Parameter("a")
a_circuit = Parameter("a")
circuit_in = QuantumCircuit(1)
circuit_in.h(0)
circuit_in.rx(-np.pi / 2, 0)
circuit_in.ry(a_circuit, 0)
circuit_in.rx(np.pi / 2, 0)
circuit_out = _ry_to_rz_template_pass(a_template, extra_costs={"h": 1}).run(circuit_in)
expected = QuantumCircuit(1)
expected.h(0)
expected.rz(a_circuit, 0)
self.assertEqual(circuit_out, expected)
# Ensure that the bound parameter in the output is referentially the same as the one we put
# in the input circuit..
self.assertEqual(len(circuit_out.parameters), 1)
self.assertIs(circuit_in.parameters[0], a_circuit)
self.assertIs(circuit_out.parameters[0], a_circuit)
def test_naming_clash_in_expression(self):
"""Test that the template matching works and correctly replaces a template if there is a
naming clash between it and the circuit. This should include binding a partial match with a
parameter."""
a_template = Parameter("a")
a_circuit = Parameter("a")
circuit_in = QuantumCircuit(1)
circuit_in.h(0)
circuit_in.rx(-np.pi / 2, 0)
circuit_in.ry(2 * a_circuit, 0)
circuit_in.rx(np.pi / 2, 0)
circuit_out = _ry_to_rz_template_pass(a_template, extra_costs={"h": 1}).run(circuit_in)
expected = QuantumCircuit(1)
expected.h(0)
expected.rz(2 * a_circuit, 0)
self.assertEqual(circuit_out, expected)
# Ensure that the bound parameter in the output is referentially the same as the one we put
# in the input circuit..
self.assertEqual(len(circuit_out.parameters), 1)
self.assertIs(circuit_in.parameters[0], a_circuit)
self.assertIs(circuit_out.parameters[0], a_circuit)
def test_template_match_with_uninvolved_parameter(self):
"""Test that the template matching algorithm succeeds at matching a circuit that contains an
unbound parameter that is not involved in the subcircuit that matches."""
b_circuit = Parameter("b")
circuit_in = QuantumCircuit(2)
circuit_in.rz(b_circuit, 0)
circuit_in.rx(-np.pi / 2, 1)
circuit_in.ry(1.45, 1)
circuit_in.rx(np.pi / 2, 1)
circuit_out = _ry_to_rz_template_pass().run(circuit_in)
expected = QuantumCircuit(2)
expected.rz(b_circuit, 0)
expected.rz(1.45, 1)
self.assertEqual(circuit_out, expected)
def test_multiple_numeric_matches_same_template(self):
"""Test that the template matching will change both instances of a partial match within a
longer circuit."""
circuit_in = QuantumCircuit(2)
# Qubit 0
circuit_in.rx(-np.pi / 2, 0)
circuit_in.ry(1.32, 0)
circuit_in.rx(np.pi / 2, 0)
# Qubit 1
circuit_in.rx(-np.pi / 2, 1)
circuit_in.ry(2.54, 1)
circuit_in.rx(np.pi / 2, 1)
circuit_out = _ry_to_rz_template_pass().run(circuit_in)
expected = QuantumCircuit(2)
expected.rz(1.32, 0)
expected.rz(2.54, 1)
self.assertEqual(circuit_out, expected)
def test_multiple_symbolic_matches_same_template(self):
"""Test that the template matching will change both instances of a partial match within a
longer circuit."""
a, b = Parameter("a"), Parameter("b")
circuit_in = QuantumCircuit(2)
# Qubit 0
circuit_in.rx(-np.pi / 2, 0)
circuit_in.ry(a, 0)
circuit_in.rx(np.pi / 2, 0)
# Qubit 1
circuit_in.rx(-np.pi / 2, 1)
circuit_in.ry(b, 1)
circuit_in.rx(np.pi / 2, 1)
circuit_out = _ry_to_rz_template_pass().run(circuit_in)
expected = QuantumCircuit(2)
expected.rz(a, 0)
expected.rz(b, 1)
self.assertEqual(circuit_out, expected)
def test_template_match_multiparameter(self):
"""Test that the template matching works on instructions that take more than one
parameter."""
a = Parameter("a")
b = Parameter("b")
template = QuantumCircuit(1)
template.u(0, a, b, 0)
template.rz(-a - b, 0)
circuit_in = QuantumCircuit(1)
circuit_in.u(0, 1.23, 2.45, 0)
pm = PassManager(TemplateOptimization([template], user_cost_dict={"u": 16, "rz": 0}))
circuit_out = pm.run(circuit_in)
expected = QuantumCircuit(1)
expected.rz(1.23 + 2.45, 0)
self.assertEqual(circuit_out, expected)
def test_naming_clash_multiparameter(self):
"""Test that the naming clash prevention mechanism works with instructions that take
multiple parameters."""
a_template = Parameter("a")
b_template = Parameter("b")
template = QuantumCircuit(1)
template.u(0, a_template, b_template, 0)
template.rz(-a_template - b_template, 0)
a_circuit = Parameter("a")
b_circuit = Parameter("b")
circuit_in = QuantumCircuit(1)
circuit_in.u(0, a_circuit, b_circuit, 0)
pm = PassManager(TemplateOptimization([template], user_cost_dict={"u": 16, "rz": 0}))
circuit_out = pm.run(circuit_in)
expected = QuantumCircuit(1)
expected.rz(a_circuit + b_circuit, 0)
self.assertEqual(circuit_out, expected)
def test_consecutive_templates_apply(self):
"""Test the scenario where one template optimization creates an opportunity for
another template optimization.
This is the original circuit:
┌───┐
q_0: ┤ X ├──■───X───────■─
└─┬─┘┌─┴─┐ │ ┌───┐ │
q_1: ──■──┤ X ├─X─┤ H ├─■─
└───┘ └───┘
The clifford_4_1 template allows to replace the two CNOTs followed by the SWAP by a
single CNOT:
q_0: ──■────────■─
┌─┴─┐┌───┐ │
q_1: ┤ X ├┤ H ├─■─
└───┘└───┘
At these point, the clifford_4_2 template allows to replace the circuit by a single
Hadamard gate:
q_0: ─────
┌───┐
q_1: ┤ H ├
└───┘
The second optimization would not have been possible without the applying the first
optimization.
"""
qc = QuantumCircuit(2)
qc.cx(1, 0)
qc.cx(0, 1)
qc.swap(0, 1)
qc.h(1)
qc.cz(0, 1)
qc_expected = QuantumCircuit(2)
qc_expected.h(1)
costs = {"h": 1, "cx": 2, "cz": 2, "swap": 3}
# Check that consecutively applying both templates leads to the expected circuit.
qc_opt = TemplateOptimization(
template_list=[clifford_4_1(), clifford_4_2()], user_cost_dict=costs
)(qc)
self.assertEqual(qc_opt, qc_expected)
# Also check that applying the second template by itself does not do anything.
qc_non_opt = TemplateOptimization(template_list=[clifford_4_2()], user_cost_dict=costs)(qc)
self.assertEqual(qc, qc_non_opt)
def test_consecutive_templates_do_not_apply(self):
"""Test that applying one template optimization does not allow incorrectly
applying other templates (which could happen if the DagDependency graph is
not constructed correctly after the optimization).
"""
template_list = [
clifford_2_2(),
clifford_2_3(),
]
pm = PassManager(TemplateOptimization(template_list=template_list))
qc = QuantumCircuit(2)
qc.cx(0, 1)
qc.cx(0, 1)
qc.h(0)
qc.swap(0, 1)
qc.h(0)
qc_opt = pm.run(qc)
self.assertTrue(Operator(qc) == Operator(qc_opt))
def test_clifford_templates(self):
"""Tests TemplateOptimization pass on several larger examples."""
template_list = [
clifford_2_1(),
clifford_2_2(),
clifford_2_3(),
clifford_2_4(),
clifford_3_1(),
]
pm = PassManager(TemplateOptimization(template_list=template_list))
for seed in range(10):
qc = random_clifford_circuit(
num_qubits=5,
num_gates=100,
gates=["x", "y", "z", "h", "s", "sdg", "cx", "cz", "swap"],
seed=seed,
)
qc_opt = pm.run(qc)
self.assertTrue(Operator(qc) == Operator(qc_opt))
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""NumTensorFactors pass testing"""
import unittest
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.converters import circuit_to_dag
from qiskit.transpiler.passes import NumTensorFactors
from qiskit.test import QiskitTestCase
class TestNumTensorsFactorPass(QiskitTestCase):
"""Tests for NumTensorFactors analysis methods."""
def test_empty_dag(self):
"""Empty DAG has 0 number of tensor factors."""
circuit = QuantumCircuit()
dag = circuit_to_dag(circuit)
pass_ = NumTensorFactors()
_ = pass_.run(dag)
self.assertEqual(pass_.property_set["num_tensor_factors"], 0)
def test_just_qubits(self):
"""A dag with 8 operations and 1 tensor factor."""
qr = QuantumRegister(2)
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[0])
circuit.cx(qr[1], qr[0])
dag = circuit_to_dag(circuit)
pass_ = NumTensorFactors()
_ = pass_.run(dag)
self.assertEqual(pass_.property_set["num_tensor_factors"], 1)
def test_depth_one(self):
"""A dag with operations in parallel (2 tensor factors)"""
qr = QuantumRegister(2)
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[1])
dag = circuit_to_dag(circuit)
pass_ = NumTensorFactors()
_ = pass_.run(dag)
self.assertEqual(pass_.property_set["num_tensor_factors"], 2)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the TrivialLayout pass"""
import unittest
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
from qiskit.transpiler import CouplingMap
from qiskit.transpiler.passes import TrivialLayout
from qiskit.transpiler.target import Target
from qiskit.circuit.library import CXGate
from qiskit.transpiler import TranspilerError
from qiskit.converters import circuit_to_dag
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import FakeTenerife, FakeRueschlikon
class TestTrivialLayout(QiskitTestCase):
"""Tests the TrivialLayout pass"""
def setUp(self):
super().setUp()
self.cmap5 = FakeTenerife().configuration().coupling_map
self.cmap16 = FakeRueschlikon().configuration().coupling_map
def test_3q_circuit_5q_coupling(self):
"""Test finds trivial layout for 3q circuit on 5q device."""
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0])
circuit.cx(qr[0], qr[2])
circuit.cx(qr[1], qr[2])
dag = circuit_to_dag(circuit)
pass_ = TrivialLayout(CouplingMap(self.cmap5))
pass_.run(dag)
layout = pass_.property_set["layout"]
for i in range(3):
self.assertEqual(layout[qr[i]], i)
def test_3q_circuit_5q_coupling_with_target(self):
"""Test finds trivial layout for 3q circuit on 5q device."""
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0])
circuit.cx(qr[0], qr[2])
circuit.cx(qr[1], qr[2])
dag = circuit_to_dag(circuit)
target = Target()
target.add_instruction(CXGate(), {tuple(edge): None for edge in self.cmap5})
pass_ = TrivialLayout(target)
pass_.run(dag)
layout = pass_.property_set["layout"]
for i in range(3):
self.assertEqual(layout[qr[i]], i)
def test_9q_circuit_16q_coupling(self):
"""Test finds trivial layout for 9q circuit with 2 registers on 16q device."""
qr0 = QuantumRegister(4, "q0")
qr1 = QuantumRegister(5, "q1")
cr = ClassicalRegister(2, "c")
circuit = QuantumCircuit(qr0, qr1, cr)
circuit.cx(qr0[1], qr0[2])
circuit.cx(qr0[0], qr1[3])
circuit.cx(qr1[4], qr0[2])
circuit.measure(qr1[1], cr[0])
circuit.measure(qr0[2], cr[1])
dag = circuit_to_dag(circuit)
pass_ = TrivialLayout(CouplingMap(self.cmap16))
pass_.run(dag)
layout = pass_.property_set["layout"]
for i in range(4):
self.assertEqual(layout[qr0[i]], i)
for i in range(5):
self.assertEqual(layout[qr1[i]], i + 4)
def test_raises_wider_circuit(self):
"""Test error is raised if the circuit is wider than coupling map."""
qr0 = QuantumRegister(3, "q0")
qr1 = QuantumRegister(3, "q1")
circuit = QuantumCircuit(qr0, qr1)
circuit.cx(qr0, qr1)
dag = circuit_to_dag(circuit)
with self.assertRaises(TranspilerError):
pass_ = TrivialLayout(CouplingMap(self.cmap5))
pass_.run(dag)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=missing-function-docstring
"""
Tests for the default UnitarySynthesis transpiler pass.
"""
from test import combine
import unittest
import numpy as np
from ddt import ddt, data
from qiskit import transpile
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import FakeVigo, FakeMumbaiFractionalCX, FakeBelemV2
from qiskit.providers.fake_provider.fake_backend_v2 import FakeBackendV2, FakeBackend5QV2
from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.circuit.library import QuantumVolume
from qiskit.converters import circuit_to_dag, dag_to_circuit
from qiskit.transpiler.passes import UnitarySynthesis
from qiskit.quantum_info.operators import Operator
from qiskit.quantum_info.random import random_unitary
from qiskit.transpiler import PassManager, CouplingMap, Target, InstructionProperties
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.exceptions import QiskitError
from qiskit.transpiler.passes import (
Collect2qBlocks,
ConsolidateBlocks,
Optimize1qGates,
SabreLayout,
Unroll3qOrMore,
CheckMap,
BarrierBeforeFinalMeasurements,
SabreSwap,
TrivialLayout,
)
from qiskit.circuit.library import (
IGate,
CXGate,
RZGate,
RXGate,
SXGate,
XGate,
iSwapGate,
ECRGate,
UGate,
ZGate,
RYYGate,
RZZGate,
RXXGate,
)
from qiskit.circuit import Measure
from qiskit.circuit.controlflow import IfElseOp
from qiskit.circuit import Parameter, Gate
@ddt
class TestUnitarySynthesis(QiskitTestCase):
"""Test UnitarySynthesis pass."""
def test_empty_basis_gates(self):
"""Verify when basis_gates is None, we do not synthesize unitaries."""
qc = QuantumCircuit(3)
op_1q = random_unitary(2, seed=0)
op_2q = random_unitary(4, seed=0)
op_3q = random_unitary(8, seed=0)
qc.unitary(op_1q.data, [0])
qc.unitary(op_2q.data, [0, 1])
qc.unitary(op_3q.data, [0, 1, 2])
out = UnitarySynthesis(basis_gates=None, min_qubits=2)(qc)
self.assertEqual(out.count_ops(), {"unitary": 3})
@data(
["u3", "cx"],
["u1", "u2", "u3", "cx"],
["rx", "ry", "rxx"],
["rx", "rz", "iswap"],
["u3", "rx", "rz", "cz", "iswap"],
)
def test_two_qubit_synthesis_to_basis(self, basis_gates):
"""Verify two qubit unitaries are synthesized to match basis gates."""
bell = QuantumCircuit(2)
bell.h(0)
bell.cx(0, 1)
bell_op = Operator(bell)
qc = QuantumCircuit(2)
qc.unitary(bell_op, [0, 1])
dag = circuit_to_dag(qc)
out = UnitarySynthesis(basis_gates).run(dag)
self.assertTrue(set(out.count_ops()).issubset(basis_gates))
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 = FakeVigo()
conf = backend.configuration()
qr = QuantumRegister(2)
coupling_map = CouplingMap(conf.coupling_map)
triv_layout_pass = TrivialLayout(coupling_map)
qc = QuantumCircuit(qr)
qc.unitary(random_unitary(4, seed=12), [0, 1])
unisynth_pass = UnitarySynthesis(
basis_gates=conf.basis_gates,
coupling_map=None,
backend_props=backend.properties(),
pulse_optimize=True,
natural_direction=False,
)
pm = PassManager([triv_layout_pass, unisynth_pass])
qc_out = pm.run(qc)
unisynth_pass_nat = UnitarySynthesis(
basis_gates=conf.basis_gates,
coupling_map=None,
backend_props=backend.properties(),
pulse_optimize=True,
natural_direction=True,
)
pm_nat = PassManager([triv_layout_pass, unisynth_pass_nat])
qc_out_nat = pm_nat.run(qc)
self.assertEqual(Operator(qc), Operator(qc_out))
self.assertEqual(Operator(qc), Operator(qc_out_nat))
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 = FakeVigo()
conf = backend.configuration()
qr = QuantumRegister(2)
coupling_map = CouplingMap(conf.coupling_map)
triv_layout_pass = TrivialLayout(coupling_map)
qc = QuantumCircuit(qr)
qc.swap(qr[0], qr[1])
unisynth_pass = UnitarySynthesis(
basis_gates=conf.basis_gates,
coupling_map=None,
backend_props=backend.properties(),
pulse_optimize=True,
natural_direction=False,
)
pm = PassManager([triv_layout_pass, unisynth_pass])
qc_out = pm.run(qc)
unisynth_pass_nat = UnitarySynthesis(
basis_gates=conf.basis_gates,
coupling_map=None,
backend_props=backend.properties(),
pulse_optimize=True,
natural_direction=True,
)
pm_nat = PassManager([triv_layout_pass, unisynth_pass_nat])
qc_out_nat = pm_nat.run(qc)
self.assertEqual(Operator(qc), Operator(qc_out))
self.assertEqual(Operator(qc), Operator(qc_out_nat))
def test_two_qubit_synthesis_to_directional_cx_multiple_registers(self):
"""Verify two qubit unitaries are synthesized to match basis gates
across multiple registers."""
# TODO: should make check more explicit e.g. explicitly set gate
# direction in test instead of using specific fake backend
backend = FakeVigo()
conf = backend.configuration()
qr0 = QuantumRegister(1)
qr1 = QuantumRegister(1)
coupling_map = CouplingMap(conf.coupling_map)
triv_layout_pass = TrivialLayout(coupling_map)
qc = QuantumCircuit(qr0, qr1)
qc.unitary(random_unitary(4, seed=12), [qr0[0], qr1[0]])
unisynth_pass = UnitarySynthesis(
basis_gates=conf.basis_gates,
coupling_map=None,
backend_props=backend.properties(),
pulse_optimize=True,
natural_direction=False,
)
pm = PassManager([triv_layout_pass, unisynth_pass])
qc_out = pm.run(qc)
unisynth_pass_nat = UnitarySynthesis(
basis_gates=conf.basis_gates,
coupling_map=None,
backend_props=backend.properties(),
pulse_optimize=True,
natural_direction=True,
)
pm_nat = PassManager([triv_layout_pass, unisynth_pass_nat])
qc_out_nat = pm_nat.run(qc)
self.assertEqual(Operator(qc), Operator(qc_out))
self.assertEqual(Operator(qc), Operator(qc_out_nat))
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 = FakeVigo()
conf = backend.configuration()
qr = QuantumRegister(2)
coupling_map = CouplingMap([[0, 1], [1, 2], [1, 3], [3, 4]])
triv_layout_pass = TrivialLayout(coupling_map)
qc = QuantumCircuit(qr)
qc.unitary(random_unitary(4, seed=12), [0, 1])
unisynth_pass = UnitarySynthesis(
basis_gates=conf.basis_gates,
coupling_map=coupling_map,
backend_props=backend.properties(),
pulse_optimize=True,
natural_direction=False,
)
pm = PassManager([triv_layout_pass, unisynth_pass])
qc_out = pm.run(qc)
unisynth_pass_nat = UnitarySynthesis(
basis_gates=conf.basis_gates,
coupling_map=coupling_map,
backend_props=backend.properties(),
pulse_optimize=True,
natural_direction=True,
)
pm_nat = PassManager([triv_layout_pass, unisynth_pass_nat])
qc_out_nat = pm_nat.run(qc)
# the decomposer defaults to the [1, 0] direction but the coupling
# map specifies a [0, 1] direction. Check that this is respected.
self.assertTrue(
all(((qr[1], qr[0]) == instr.qubits for instr in qc_out.get_instructions("cx")))
)
self.assertTrue(
all(((qr[0], qr[1]) == instr.qubits for instr in qc_out_nat.get_instructions("cx")))
)
self.assertEqual(Operator(qc), Operator(qc_out))
self.assertEqual(Operator(qc), Operator(qc_out_nat))
def test_two_qubit_synthesis_to_directional_cx_from_coupling_map_natural_none(self):
"""Verify natural cx direction is used when specified in coupling map
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 = FakeVigo()
conf = backend.configuration()
qr = QuantumRegister(2)
coupling_map = CouplingMap([[0, 1], [1, 2], [1, 3], [3, 4]])
triv_layout_pass = TrivialLayout(coupling_map)
qc = QuantumCircuit(qr)
qc.unitary(random_unitary(4, seed=12), [0, 1])
unisynth_pass = UnitarySynthesis(
basis_gates=conf.basis_gates,
coupling_map=coupling_map,
backend_props=backend.properties(),
pulse_optimize=True,
natural_direction=False,
)
pm = PassManager([triv_layout_pass, unisynth_pass])
qc_out = pm.run(qc)
unisynth_pass_nat = UnitarySynthesis(
basis_gates=conf.basis_gates,
coupling_map=coupling_map,
backend_props=backend.properties(),
pulse_optimize=True,
natural_direction=None,
)
pm_nat = PassManager([triv_layout_pass, unisynth_pass_nat])
qc_out_nat = pm_nat.run(qc)
# the decomposer defaults to the [1, 0] direction but the coupling
# map specifies a [0, 1] direction. Check that this is respected.
self.assertTrue(
all(((qr[1], qr[0]) == instr.qubits for instr in qc_out.get_instructions("cx")))
)
self.assertTrue(
all(((qr[0], qr[1]) == instr.qubits for instr in qc_out_nat.get_instructions("cx")))
)
self.assertEqual(Operator(qc), Operator(qc_out))
self.assertEqual(Operator(qc), Operator(qc_out_nat))
def test_two_qubit_synthesis_to_directional_cx_from_coupling_map_natural_false(self):
"""Verify natural cx direction is used when specified in coupling map
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 = FakeVigo()
conf = backend.configuration()
qr = QuantumRegister(2)
coupling_map = CouplingMap([[0, 1], [1, 2], [1, 3], [3, 4]])
triv_layout_pass = TrivialLayout(coupling_map)
qc = QuantumCircuit(qr)
qc.unitary(random_unitary(4, seed=12), [0, 1])
unisynth_pass = UnitarySynthesis(
basis_gates=conf.basis_gates,
coupling_map=coupling_map,
backend_props=backend.properties(),
pulse_optimize=True,
natural_direction=False,
)
pm = PassManager([triv_layout_pass, unisynth_pass])
qc_out = pm.run(qc)
unisynth_pass_nat = UnitarySynthesis(
basis_gates=conf.basis_gates,
coupling_map=coupling_map,
backend_props=backend.properties(),
pulse_optimize=True,
natural_direction=False,
)
pm_nat = PassManager([triv_layout_pass, unisynth_pass_nat])
qc_out_nat = pm_nat.run(qc)
# the decomposer defaults to the [1, 0] direction but the coupling
# map specifies a [0, 1] direction. Check that this is respected.
self.assertTrue(
all(((qr[1], qr[0]) == instr.qubits for instr in qc_out.get_instructions("cx")))
)
self.assertTrue(
all(((qr[1], qr[0]) == instr.qubits for instr in qc_out_nat.get_instructions("cx")))
)
self.assertEqual(Operator(qc), Operator(qc_out))
self.assertEqual(Operator(qc), Operator(qc_out_nat))
def test_two_qubit_synthesis_not_pulse_optimal(self):
"""Verify not attempting pulse optimal decomposition when pulse_optimize==False."""
backend = FakeVigo()
conf = backend.configuration()
qr = QuantumRegister(2)
coupling_map = CouplingMap([[0, 1], [1, 2], [1, 3], [3, 4]])
triv_layout_pass = TrivialLayout(coupling_map)
qc = QuantumCircuit(qr)
qc.unitary(random_unitary(4, seed=12), [0, 1])
unisynth_pass = UnitarySynthesis(
basis_gates=conf.basis_gates,
coupling_map=coupling_map,
backend_props=backend.properties(),
pulse_optimize=False,
natural_direction=True,
)
pm = PassManager([triv_layout_pass, unisynth_pass])
qc_out = pm.run(qc)
if isinstance(qc_out, QuantumCircuit):
num_ops = qc_out.count_ops()
else:
num_ops = qc_out[0].count_ops()
self.assertIn("sx", num_ops)
self.assertGreaterEqual(num_ops["sx"], 16)
def test_two_qubit_pulse_optimal_true_raises(self):
"""Verify raises if pulse optimal==True but cx is not in the backend basis."""
backend = FakeVigo()
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]
qr = QuantumRegister(2)
coupling_map = CouplingMap([[0, 1], [1, 2], [1, 3], [3, 4]])
triv_layout_pass = TrivialLayout(coupling_map)
qc = QuantumCircuit(qr)
qc.unitary(random_unitary(4, seed=12), [0, 1])
unisynth_pass = UnitarySynthesis(
basis_gates=conf.basis_gates,
coupling_map=coupling_map,
backend_props=backend.properties(),
pulse_optimize=True,
natural_direction=True,
)
pm = PassManager([triv_layout_pass, unisynth_pass])
with self.assertRaises(QiskitError):
pm.run(qc)
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 = FakeVigo()
conf = backend.configuration()
# conf.basis_gates = [gate if gate != "cx" else "iswap" for gate in conf.basis_gates]
qr = QuantumRegister(2)
coupling_map = CouplingMap([[0, 1], [1, 0], [1, 2], [1, 3], [3, 4]])
triv_layout_pass = TrivialLayout(coupling_map)
qc = QuantumCircuit(qr)
qc.unitary(random_unitary(4, seed=12), [0, 1])
unisynth_pass = UnitarySynthesis(
basis_gates=conf.basis_gates,
coupling_map=coupling_map,
backend_props=backend.properties(),
pulse_optimize=True,
natural_direction=True,
)
pm = PassManager([triv_layout_pass, unisynth_pass])
qc_out = pm.run(qc)
self.assertTrue(
all(((qr[0], qr[1]) == instr.qubits for instr in qc_out.get_instructions("cx")))
)
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 = FakeVigo()
conf = backend.configuration()
for _, nduv in backend.properties()._gates["cx"].items():
nduv["gate_length"] = (4e-7, nduv["gate_length"][1])
nduv["gate_error"] = (7e-3, nduv["gate_error"][1])
qr = QuantumRegister(2)
coupling_map = CouplingMap([[0, 1], [1, 0], [1, 2], [1, 3], [3, 4]])
triv_layout_pass = TrivialLayout(coupling_map)
qc = QuantumCircuit(qr)
qc.unitary(random_unitary(4, seed=12), [0, 1])
unisynth_pass = UnitarySynthesis(
basis_gates=conf.basis_gates,
backend_props=backend.properties(),
pulse_optimize=True,
natural_direction=True,
)
pm = PassManager([triv_layout_pass, unisynth_pass])
with self.assertRaises(TranspilerError):
pm.run(qc)
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 = FakeVigo()
conf = backend.configuration()
qr = QuantumRegister(2)
coupling_map = CouplingMap([[0, 1], [1, 2], [1, 3], [3, 4]])
triv_layout_pass = TrivialLayout(coupling_map)
qc = QuantumCircuit(qr)
qc.unitary(random_unitary(4, seed=12), [0, 1])
unisynth_pass = UnitarySynthesis(
basis_gates=conf.basis_gates,
coupling_map=coupling_map,
backend_props=backend.properties(),
pulse_optimize=None,
natural_direction=True,
)
pm = PassManager([triv_layout_pass, unisynth_pass])
qc_out = pm.run(qc)
if isinstance(qc_out, QuantumCircuit):
num_ops = qc_out.count_ops()
else:
num_ops = qc_out[0].count_ops()
self.assertIn("sx", num_ops)
self.assertLessEqual(num_ops["sx"], 12)
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 = FakeVigo()
conf = backend.configuration()
conf.basis_gates = [gate if gate != "cx" else "iswap" for gate in conf.basis_gates]
qr = QuantumRegister(2)
coupling_map = CouplingMap([[0, 1], [1, 2], [1, 3], [3, 4]])
triv_layout_pass = TrivialLayout(coupling_map)
qc = QuantumCircuit(qr)
qc.unitary(random_unitary(4, seed=12), [0, 1])
unisynth_pass = UnitarySynthesis(
basis_gates=conf.basis_gates,
coupling_map=coupling_map,
backend_props=backend.properties(),
pulse_optimize=None,
natural_direction=True,
)
pm = PassManager([triv_layout_pass, unisynth_pass])
try:
qc_out = pm.run(qc)
except QiskitError:
self.fail("pulse_optimize=None raised exception unexpectedly")
if isinstance(qc_out, QuantumCircuit):
num_ops = qc_out.count_ops()
else:
num_ops = qc_out[0].count_ops()
self.assertIn("sx", num_ops)
self.assertLessEqual(num_ops["sx"], 14)
def test_qv_natural(self):
"""check that quantum volume circuit compiles for natural direction"""
qv64 = QuantumVolume(5, seed=15)
def construct_passmanager(basis_gates, coupling_map, synthesis_fidelity, pulse_optimize):
seed = 2
_map = [SabreLayout(coupling_map, max_iterations=2, seed=seed)]
_unroll3q = Unroll3qOrMore()
_swap_check = CheckMap(coupling_map)
_swap = [
BarrierBeforeFinalMeasurements(),
SabreSwap(coupling_map, heuristic="lookahead", seed=seed),
]
_optimize = [
Collect2qBlocks(),
ConsolidateBlocks(basis_gates=basis_gates),
UnitarySynthesis(
basis_gates,
synthesis_fidelity,
coupling_map,
pulse_optimize=pulse_optimize,
natural_direction=True,
),
Optimize1qGates(basis_gates),
]
pm = PassManager()
pm.append(_map) # map to hardware by inserting swaps
pm.append(_unroll3q)
pm.append(_swap_check)
pm.append(_swap)
pm.append(_optimize)
return pm
coupling_map = CouplingMap([[0, 1], [1, 2], [3, 2], [3, 4], [5, 4]])
basis_gates = ["rz", "sx", "cx"]
pm1 = construct_passmanager(
basis_gates=basis_gates,
coupling_map=coupling_map,
synthesis_fidelity=0.99,
pulse_optimize=True,
)
pm2 = construct_passmanager(
basis_gates=basis_gates,
coupling_map=coupling_map,
synthesis_fidelity=0.99,
pulse_optimize=False,
)
qv64_1 = pm1.run(qv64.decompose())
qv64_2 = pm2.run(qv64.decompose())
edges = [list(edge) for edge in coupling_map.get_edges()]
self.assertTrue(
all(
[qv64_1.qubits.index(qubit) for qubit in instr.qubits] in edges
for instr in qv64_1.get_instructions("cx")
)
)
self.assertEqual(Operator(qv64_1), Operator(qv64_2))
@data(1, 2, 3)
def test_coupling_map_transpile(self, opt):
"""test natural_direction works with transpile/execute"""
qr = QuantumRegister(2)
circ = QuantumCircuit(qr)
circ.append(random_unitary(4, seed=1), [0, 1])
circ_01 = transpile(
circ, basis_gates=["rz", "sx", "cx"], optimization_level=opt, coupling_map=[[0, 1]]
)
circ_10 = transpile(
circ, basis_gates=["rz", "sx", "cx"], optimization_level=opt, coupling_map=[[1, 0]]
)
circ_01_index = {qubit: index for index, qubit in enumerate(circ_01.qubits)}
circ_10_index = {qubit: index for index, qubit in enumerate(circ_10.qubits)}
self.assertTrue(
all(
(
(1, 0) == (circ_10_index[instr.qubits[0]], circ_10_index[instr.qubits[1]])
for instr in circ_10.get_instructions("cx")
)
)
)
self.assertTrue(
all(
(
(0, 1) == (circ_01_index[instr.qubits[0]], circ_01_index[instr.qubits[1]])
for instr in circ_01.get_instructions("cx")
)
)
)
@combine(
opt_level=[0, 1, 2, 3],
bidirectional=[True, False],
dsc=(
"test natural_direction works with transpile using opt_level {opt_level} on"
" target with multiple 2q gates with bidirectional={bidirectional}"
),
name="opt_level_{opt_level}_bidirectional_{bidirectional}",
)
def test_coupling_map_transpile_with_backendv2(self, opt_level, bidirectional):
backend = FakeBackend5QV2(bidirectional)
qr = QuantumRegister(2)
circ = QuantumCircuit(qr)
circ.append(random_unitary(4, seed=1), [0, 1])
circ_01 = transpile(
circ, backend=backend, optimization_level=opt_level, layout_method="trivial"
)
circ_01_index = {qubit: index for index, qubit in enumerate(circ_01.qubits)}
self.assertGreaterEqual(len(circ_01.get_instructions("cx")), 1)
for instr in circ_01.get_instructions("cx"):
self.assertEqual(
(0, 1), (circ_01_index[instr.qubits[0]], circ_01_index[instr.qubits[1]])
)
@data(1, 2, 3)
def test_coupling_map_unequal_durations(self, opt):
"""Test direction with transpile/execute with backend durations."""
qr = QuantumRegister(2)
circ = QuantumCircuit(qr)
circ.append(random_unitary(4, seed=1), [1, 0])
backend = FakeVigo()
tqc = transpile(
circ,
backend=backend,
optimization_level=opt,
translation_method="synthesis",
layout_method="trivial",
)
tqc_index = {qubit: index for index, qubit in enumerate(tqc.qubits)}
self.assertTrue(
all(
(
(0, 1) == (tqc_index[instr.qubits[0]], tqc_index[instr.qubits[1]])
for instr in tqc.get_instructions("cx")
)
)
)
@combine(
opt_level=[0, 1, 2, 3],
bidirectional=[True, False],
dsc=(
"Test direction with transpile using opt_level {opt_level} on"
" target with multiple 2q gates with bidirectional={bidirectional}"
"direction [0, 1] is lower error and should be picked."
),
name="opt_level_{opt_level}_bidirectional_{bidirectional}",
)
def test_coupling_unequal_duration_with_backendv2(self, opt_level, bidirectional):
qr = QuantumRegister(2)
circ = QuantumCircuit(qr)
circ.append(random_unitary(4, seed=1), [1, 0])
backend = FakeBackend5QV2(bidirectional)
tqc = transpile(
circ,
backend=backend,
optimization_level=opt_level,
translation_method="synthesis",
layout_method="trivial",
)
tqc_index = {qubit: index for index, qubit in enumerate(tqc.qubits)}
self.assertGreaterEqual(len(tqc.get_instructions("cx")), 1)
for instr in tqc.get_instructions("cx"):
self.assertEqual((0, 1), (tqc_index[instr.qubits[0]], tqc_index[instr.qubits[1]]))
@combine(
opt_level=[0, 1, 2, 3],
dsc=(
"Test direction with transpile using opt_level {opt_level} on"
" target with multiple 2q gates"
),
name="opt_level_{opt_level}",
)
def test_non_overlapping_kak_gates_with_backendv2(self, opt_level):
qr = QuantumRegister(2)
circ = QuantumCircuit(qr)
circ.append(random_unitary(4, seed=1), [1, 0])
backend = FakeBackendV2()
tqc = transpile(
circ,
backend=backend,
optimization_level=opt_level,
translation_method="synthesis",
layout_method="trivial",
)
tqc_index = {qubit: index for index, qubit in enumerate(tqc.qubits)}
self.assertGreaterEqual(len(tqc.get_instructions("ecr")), 1)
for instr in tqc.get_instructions("ecr"):
self.assertEqual((1, 0), (tqc_index[instr.qubits[0]], tqc_index[instr.qubits[1]]))
def test_fractional_cx_with_backendv2(self):
"""Test fractional CX gets used if present in target."""
qr = QuantumRegister(2)
circ = QuantumCircuit(qr)
circ.append(random_unitary(4, seed=1), [0, 1])
backend = FakeMumbaiFractionalCX()
synth_pass = UnitarySynthesis(target=backend.target)
tqc = synth_pass(circ)
tqc_index = {qubit: index for index, qubit in enumerate(tqc.qubits)}
self.assertGreaterEqual(len(tqc.get_instructions("rzx")), 1)
for instr in tqc.get_instructions("rzx"):
self.assertEqual((0, 1), (tqc_index[instr.qubits[0]], tqc_index[instr.qubits[1]]))
@combine(
opt_level=[0, 1, 2, 3],
dsc=(
"Test direction with transpile using opt_level {opt_level} on"
"target with multiple 2q gates available in reverse direction"
),
name="opt_level_{opt_level}",
)
def test_reverse_direction(self, opt_level):
target = Target(2)
target.add_instruction(CXGate(), {(0, 1): InstructionProperties(error=1.2e-6)})
target.add_instruction(ECRGate(), {(0, 1): InstructionProperties(error=1.2e-7)})
target.add_instruction(
UGate(Parameter("theta"), Parameter("phi"), Parameter("lam")), {(0,): None, (1,): None}
)
qr = QuantumRegister(2)
circ = QuantumCircuit(qr)
circ.append(random_unitary(4, seed=1), [1, 0])
tqc = transpile(
circ,
target=target,
optimization_level=opt_level,
translation_method="synthesis",
layout_method="trivial",
)
tqc_index = {qubit: index for index, qubit in enumerate(tqc.qubits)}
self.assertGreaterEqual(len(tqc.get_instructions("ecr")), 1)
for instr in tqc.get_instructions("ecr"):
self.assertEqual((0, 1), (tqc_index[instr.qubits[0]], tqc_index[instr.qubits[1]]))
@combine(
opt_level=[0, 1, 2, 3],
dsc=("Test controlled but not supercontrolled basis"),
name="opt_level_{opt_level}",
)
def test_controlled_basis(self, opt_level):
target = Target(2)
target.add_instruction(RYYGate(np.pi / 8), {(0, 1): InstructionProperties(error=1.2e-6)})
target.add_instruction(
UGate(Parameter("theta"), Parameter("phi"), Parameter("lam")), {(0,): None, (1,): None}
)
qr = QuantumRegister(2)
circ = QuantumCircuit(qr)
circ.append(random_unitary(4, seed=1), [1, 0])
tqc = transpile(
circ,
target=target,
optimization_level=opt_level,
translation_method="synthesis",
layout_method="trivial",
)
self.assertGreaterEqual(len(tqc.get_instructions("ryy")), 1)
self.assertEqual(Operator(tqc), Operator(circ))
def test_approximation_controlled(self):
target = Target(2)
target.add_instruction(RZZGate(np.pi / 10), {(0, 1): InstructionProperties(error=0.006)})
target.add_instruction(RXXGate(np.pi / 3), {(0, 1): InstructionProperties(error=0.01)})
target.add_instruction(
UGate(Parameter("theta"), Parameter("phi"), Parameter("lam")),
{(0,): InstructionProperties(error=0.001), (1,): InstructionProperties(error=0.002)},
)
circ = QuantumCircuit(2)
circ.append(random_unitary(4, seed=7), [1, 0])
dag = circuit_to_dag(circ)
dag_100 = UnitarySynthesis(target=target, approximation_degree=1.0).run(dag)
dag_99 = UnitarySynthesis(target=target, approximation_degree=0.99).run(dag)
self.assertGreaterEqual(dag_100.depth(), dag_99.depth())
self.assertEqual(Operator(dag_to_circuit(dag_100)), Operator(circ))
def test_if_simple(self):
"""Test a simple if statement."""
basis_gates = {"u", "cx"}
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc_uni = QuantumCircuit(2)
qc_uni.h(0)
qc_uni.cx(0, 1)
qc_uni_mat = Operator(qc_uni)
qc_true_body = QuantumCircuit(2)
qc_true_body.unitary(qc_uni_mat, [0, 1])
qc = QuantumCircuit(qr, cr)
qc.if_test((cr, 1), qc_true_body, [0, 1], [])
dag = circuit_to_dag(qc)
cdag = UnitarySynthesis(basis_gates=basis_gates).run(dag)
cqc = dag_to_circuit(cdag)
cbody = cqc.data[0].operation.params[0]
self.assertEqual(cbody.count_ops().keys(), basis_gates)
self.assertEqual(qc_uni_mat, Operator(cbody))
def test_nested_control_flow(self):
"""Test unrolling nested control flow blocks."""
qr = QuantumRegister(2)
cr = ClassicalRegister(1)
qc_uni1 = QuantumCircuit(2)
qc_uni1.swap(0, 1)
qc_uni1_mat = Operator(qc_uni1)
qc = QuantumCircuit(qr, cr)
with qc.for_loop(range(3)):
with qc.while_loop((cr, 0)):
qc.unitary(qc_uni1_mat, [0, 1])
dag = circuit_to_dag(qc)
cdag = UnitarySynthesis(basis_gates=["u", "cx"]).run(dag)
cqc = dag_to_circuit(cdag)
cbody = cqc.data[0].operation.params[2].data[0].operation.params[0]
self.assertEqual(cbody.count_ops().keys(), {"u", "cx"})
self.assertEqual(qc_uni1_mat, Operator(cbody))
def test_mapping_control_flow(self):
"""Test that inner dags use proper qubit mapping."""
qr = QuantumRegister(3, "q")
qc = QuantumCircuit(qr)
# Create target that supports CX only between 0 and 2.
fake_target = Target()
fake_target.add_instruction(CXGate(), {(0, 2): None})
fake_target.add_instruction(
UGate(Parameter("t"), Parameter("p"), Parameter("l")),
{
(0,): None,
(1,): None,
(2,): None,
},
)
qc_uni1 = QuantumCircuit(2)
qc_uni1.swap(0, 1)
qc_uni1_mat = Operator(qc_uni1)
loop_body = QuantumCircuit(2)
loop_body.unitary(qc_uni1_mat, [0, 1])
# Loop body uses qubits 0 and 2, mapped to 0 and 1 in the block.
# If synthesis doesn't handle recursive mapping, it'll incorrectly
# look for a CX on (0, 1) instead of on (0, 2).
qc.for_loop((0,), None, loop_body, [0, 2], [])
dag = circuit_to_dag(qc)
UnitarySynthesis(basis_gates=["u", "cx"], target=fake_target).run(dag)
def test_single_qubit_with_target(self):
"""Test input circuit with only 1q works with target."""
qc = QuantumCircuit(1)
qc.append(ZGate(), [qc.qubits[0]])
dag = circuit_to_dag(qc)
unitary_synth_pass = UnitarySynthesis(target=FakeBelemV2().target)
result_dag = unitary_synth_pass.run(dag)
result_qc = dag_to_circuit(result_dag)
self.assertEqual(qc, result_qc)
def test_single_qubit_identity_with_target(self):
"""Test input single qubit identity works with target."""
qc = QuantumCircuit(1)
qc.unitary([[1.0, 0.0], [0.0, 1.0]], 0)
dag = circuit_to_dag(qc)
unitary_synth_pass = UnitarySynthesis(target=FakeBelemV2().target)
result_dag = unitary_synth_pass.run(dag)
result_qc = dag_to_circuit(result_dag)
self.assertEqual(result_qc, QuantumCircuit(1))
def test_unitary_synthesis_with_ideal_and_variable_width_ops(self):
"""Test unitary synthesis works with a target that contains ideal and variadic ops."""
qc = QuantumCircuit(2)
qc.unitary(np.eye(4), [0, 1])
dag = circuit_to_dag(qc)
target = FakeBelemV2().target
target.add_instruction(IfElseOp, name="if_else")
target.add_instruction(ZGate())
target.add_instruction(ECRGate())
unitary_synth_pass = UnitarySynthesis(target=target)
result_dag = unitary_synth_pass.run(dag)
result_qc = dag_to_circuit(result_dag)
self.assertEqual(result_qc, QuantumCircuit(2))
def test_unitary_synthesis_custom_gate_target(self):
qc = QuantumCircuit(2)
qc.unitary(np.eye(4), [0, 1])
dag = circuit_to_dag(qc)
class CustomGate(Gate):
"""Custom Opaque Gate"""
def __init__(self):
super().__init__("custom", 2, [])
target = Target(num_qubits=2)
target.add_instruction(
UGate(Parameter("t"), Parameter("p"), Parameter("l")), {(0,): None, (1,): None}
)
target.add_instruction(CustomGate(), {(0, 1): None, (1, 0): None})
unitary_synth_pass = UnitarySynthesis(target=target)
result_dag = unitary_synth_pass.run(dag)
result_qc = dag_to_circuit(result_dag)
self.assertEqual(result_qc, qc)
def test_default_does_not_fail_on_no_syntheses(self):
qc = QuantumCircuit(1)
qc.unitary(np.eye(2), [0])
pass_ = UnitarySynthesis(["unknown", "gates"])
self.assertEqual(qc, pass_(qc))
def test_iswap_no_cx_synthesis_succeeds(self):
"""Test basis set with iswap but no cx can synthesize a circuit"""
target = Target()
theta = Parameter("theta")
i_props = {
(0,): InstructionProperties(duration=35.5e-9, error=0.000413),
(1,): InstructionProperties(duration=35.5e-9, error=0.000502),
}
target.add_instruction(IGate(), i_props)
rz_props = {
(0,): InstructionProperties(duration=0, error=0),
(1,): InstructionProperties(duration=0, error=0),
}
target.add_instruction(RZGate(theta), rz_props)
sx_props = {
(0,): InstructionProperties(duration=35.5e-9, error=0.000413),
(1,): InstructionProperties(duration=35.5e-9, error=0.000502),
}
target.add_instruction(SXGate(), sx_props)
x_props = {
(0,): InstructionProperties(duration=35.5e-9, error=0.000413),
(1,): InstructionProperties(duration=35.5e-9, error=0.000502),
}
target.add_instruction(XGate(), x_props)
iswap_props = {
(0, 1): InstructionProperties(duration=519.11e-9, error=0.01201),
(1, 0): InstructionProperties(duration=554.66e-9, error=0.01201),
}
target.add_instruction(iSwapGate(), iswap_props)
measure_props = {
(0,): InstructionProperties(duration=5.813e-6, error=0.0751),
(1,): InstructionProperties(duration=5.813e-6, error=0.0225),
}
target.add_instruction(Measure(), measure_props)
qc = QuantumCircuit(2)
cxmat = Operator(CXGate()).to_matrix()
qc.unitary(cxmat, [0, 1])
unitary_synth_pass = UnitarySynthesis(target=target)
dag = circuit_to_dag(qc)
result_dag = unitary_synth_pass.run(dag)
result_qc = dag_to_circuit(result_dag)
self.assertTrue(np.allclose(Operator(result_qc.to_gate()).to_matrix(), cxmat))
def test_parameterized_basis_gate_in_target(self):
"""Test synthesis with parameterized RXX gate."""
theta = Parameter("θ")
lam = Parameter("λ")
target = Target(num_qubits=2)
target.add_instruction(RZGate(lam))
target.add_instruction(RXGate(theta))
target.add_instruction(RXXGate(theta))
qc = QuantumCircuit(2)
qc.cp(np.pi / 2, 0, 1)
qc_transpiled = transpile(qc, target=target, optimization_level=3, seed_transpiler=42)
opcount = qc_transpiled.count_ops()
self.assertTrue(set(opcount).issubset({"rz", "rx", "rxx"}))
self.assertTrue(np.allclose(Operator(qc_transpiled), Operator(qc)))
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the Unroller pass"""
from numpy import pi
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.extensions.simulator import Snapshot
from qiskit.transpiler.passes import Unroller
from qiskit.converters import circuit_to_dag, dag_to_circuit
from qiskit.quantum_info import Operator
from qiskit.test import QiskitTestCase
from qiskit.exceptions import QiskitError
from qiskit.circuit import Parameter, Qubit, Clbit
from qiskit.circuit.library import U1Gate, U2Gate, U3Gate, CU1Gate, CU3Gate
from qiskit.transpiler.target import Target
class TestUnroller(QiskitTestCase):
"""Tests the Unroller pass."""
def test_basic_unroll(self):
"""Test decompose a single H into u2."""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
dag = circuit_to_dag(circuit)
pass_ = Unroller(["u2"])
unrolled_dag = pass_.run(dag)
op_nodes = unrolled_dag.op_nodes()
self.assertEqual(len(op_nodes), 1)
self.assertEqual(op_nodes[0].name, "u2")
def test_basic_unroll_target(self):
"""Test decompose a single H into U2 from target."""
qc = QuantumCircuit(1)
qc.h(0)
target = Target(num_qubits=1)
phi = Parameter("phi")
lam = Parameter("lam")
target.add_instruction(U2Gate(phi, lam))
dag = circuit_to_dag(qc)
pass_ = Unroller(target=target)
unrolled_dag = pass_.run(dag)
op_nodes = unrolled_dag.op_nodes()
self.assertEqual(len(op_nodes), 1)
self.assertEqual(op_nodes[0].name, "u2")
def test_unroll_toffoli(self):
"""Test unroll toffoli on multi regs to h, t, tdg, cx."""
qr1 = QuantumRegister(2, "qr1")
qr2 = QuantumRegister(1, "qr2")
circuit = QuantumCircuit(qr1, qr2)
circuit.ccx(qr1[0], qr1[1], qr2[0])
dag = circuit_to_dag(circuit)
pass_ = Unroller(["h", "t", "tdg", "cx"])
unrolled_dag = pass_.run(dag)
op_nodes = unrolled_dag.op_nodes()
self.assertEqual(len(op_nodes), 15)
for node in op_nodes:
self.assertIn(node.name, ["h", "t", "tdg", "cx"])
def test_unroll_1q_chain_conditional(self):
"""Test unroll chain of 1-qubit gates interrupted by conditional."""
qr = QuantumRegister(1, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr)
circuit.tdg(qr)
circuit.z(qr)
circuit.t(qr)
circuit.ry(0.5, qr)
circuit.rz(0.3, qr)
circuit.rx(0.1, qr)
circuit.measure(qr, cr)
circuit.x(qr).c_if(cr, 1)
circuit.y(qr).c_if(cr, 1)
circuit.z(qr).c_if(cr, 1)
dag = circuit_to_dag(circuit)
pass_ = Unroller(["u1", "u2", "u3"])
unrolled_dag = pass_.run(dag)
# Pick up -1 * 0.3 / 2 global phase for one RZ -> U1.
ref_circuit = QuantumCircuit(qr, cr, global_phase=-0.3 / 2)
ref_circuit.append(U2Gate(0, pi), [qr[0]])
ref_circuit.append(U1Gate(-pi / 4), [qr[0]])
ref_circuit.append(U1Gate(pi), [qr[0]])
ref_circuit.append(U1Gate(pi / 4), [qr[0]])
ref_circuit.append(U3Gate(0.5, 0, 0), [qr[0]])
ref_circuit.append(U1Gate(0.3), [qr[0]])
ref_circuit.append(U3Gate(0.1, -pi / 2, pi / 2), [qr[0]])
ref_circuit.measure(qr[0], cr[0])
ref_circuit.append(U3Gate(pi, 0, pi), [qr[0]]).c_if(cr, 1)
ref_circuit.append(U3Gate(pi, pi / 2, pi / 2), [qr[0]]).c_if(cr, 1)
ref_circuit.append(U1Gate(pi), [qr[0]]).c_if(cr, 1)
ref_dag = circuit_to_dag(ref_circuit)
self.assertEqual(unrolled_dag, ref_dag)
def test_unroll_no_basis(self):
"""Test when a given gate has no decompositions."""
qr = QuantumRegister(1, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr)
dag = circuit_to_dag(circuit)
pass_ = Unroller(basis=[])
with self.assertRaises(QiskitError):
pass_.run(dag)
def test_simple_unroll_parameterized_without_expressions(self):
"""Verify unrolling parameterized gates without expressions."""
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
theta = Parameter("theta")
qc.rz(theta, qr[0])
dag = circuit_to_dag(qc)
unrolled_dag = Unroller(["u1", "u3", "cx"]).run(dag)
expected = QuantumCircuit(qr, global_phase=-theta / 2)
expected.append(U1Gate(theta), [qr[0]])
self.assertEqual(circuit_to_dag(expected), unrolled_dag)
def test_simple_unroll_parameterized_with_expressions(self):
"""Verify unrolling parameterized gates with expressions."""
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
theta = Parameter("theta")
phi = Parameter("phi")
sum_ = theta + phi
qc.rz(sum_, qr[0])
dag = circuit_to_dag(qc)
unrolled_dag = Unroller(["u1", "u3", "cx"]).run(dag)
expected = QuantumCircuit(qr, global_phase=-sum_ / 2)
expected.append(U1Gate(sum_), [qr[0]])
self.assertEqual(circuit_to_dag(expected), unrolled_dag)
def test_definition_unroll_parameterized(self):
"""Verify that unrolling complex gates with parameters does not raise."""
qr = QuantumRegister(2)
qc = QuantumCircuit(qr)
theta = Parameter("theta")
qc.append(CU1Gate(theta), [qr[1], qr[0]])
qc.append(CU1Gate(theta * theta), [qr[0], qr[1]])
dag = circuit_to_dag(qc)
out_dag = Unroller(["u1", "cx"]).run(dag)
self.assertEqual(out_dag.count_ops(), {"u1": 6, "cx": 4})
def test_unrolling_parameterized_composite_gates(self):
"""Verify unrolling circuits with parameterized composite gates."""
qr1 = QuantumRegister(2)
subqc = QuantumCircuit(qr1)
theta = Parameter("theta")
subqc.rz(theta, qr1[0])
subqc.cx(qr1[0], qr1[1])
subqc.rz(theta, qr1[1])
# Expanding across register with shared parameter
qr2 = QuantumRegister(4)
qc = QuantumCircuit(qr2)
qc.append(subqc.to_instruction(), [qr2[0], qr2[1]])
qc.append(subqc.to_instruction(), [qr2[2], qr2[3]])
dag = circuit_to_dag(qc)
out_dag = Unroller(["u1", "u3", "cx"]).run(dag)
# Pick up -1 * theta / 2 global phase four twice (once for each RZ -> P
# in each of the two sub_instr instructions).
expected = QuantumCircuit(qr2, global_phase=-1 * 4 * theta / 2.0)
expected.append(U1Gate(theta), [qr2[0]])
expected.cx(qr2[0], qr2[1])
expected.append(U1Gate(theta), [qr2[1]])
expected.append(U1Gate(theta), [qr2[2]])
expected.cx(qr2[2], qr2[3])
expected.append(U1Gate(theta), [qr2[3]])
self.assertEqual(circuit_to_dag(expected), out_dag)
# Expanding across register with shared parameter
qc = QuantumCircuit(qr2)
phi = Parameter("phi")
gamma = Parameter("gamma")
qc.append(subqc.to_instruction({theta: phi}), [qr2[0], qr2[1]])
qc.append(subqc.to_instruction({theta: gamma}), [qr2[2], qr2[3]])
dag = circuit_to_dag(qc)
out_dag = Unroller(["u1", "u3", "cx"]).run(dag)
expected = QuantumCircuit(qr2, global_phase=-1 * (2 * phi + 2 * gamma) / 2.0)
expected.append(U1Gate(phi), [qr2[0]])
expected.cx(qr2[0], qr2[1])
expected.append(U1Gate(phi), [qr2[1]])
expected.append(U1Gate(gamma), [qr2[2]])
expected.cx(qr2[2], qr2[3])
expected.append(U1Gate(gamma), [qr2[3]])
self.assertEqual(circuit_to_dag(expected), out_dag)
def test_unrolling_preserves_qregs_order(self):
"""Test unrolling a gate preseveres it's definition registers order"""
qr = QuantumRegister(2, "qr1")
qc = QuantumCircuit(qr)
qc.cx(1, 0)
gate = qc.to_gate()
qr2 = QuantumRegister(2, "qr2")
qc2 = QuantumCircuit(qr2)
qc2.append(gate, qr2)
dag = circuit_to_dag(qc2)
out_dag = Unroller(["cx"]).run(dag)
expected = QuantumCircuit(qr2)
expected.cx(1, 0)
self.assertEqual(circuit_to_dag(expected), out_dag)
def test_unrolling_nested_gates_preserves_qregs_order(self):
"""Test unrolling a nested gate preseveres it's definition registers order."""
qr = QuantumRegister(2, "qr1")
qc = QuantumCircuit(qr)
qc.cx(1, 0)
gate_level_1 = qc.to_gate()
qr2 = QuantumRegister(2, "qr2")
qc2 = QuantumCircuit(qr2)
qc2.append(gate_level_1, [1, 0])
qc2.cp(pi, 1, 0)
gate_level_2 = qc2.to_gate()
qr3 = QuantumRegister(2, "qr3")
qc3 = QuantumCircuit(qr3)
qc3.append(gate_level_2, [1, 0])
qc3.cu(pi, pi, pi, 0, 1, 0)
gate_level_3 = qc3.to_gate()
qr4 = QuantumRegister(2, "qr4")
qc4 = QuantumCircuit(qr4)
qc4.append(gate_level_3, [0, 1])
dag = circuit_to_dag(qc4)
out_dag = Unroller(["cx", "cp", "cu"]).run(dag)
expected = QuantumCircuit(qr4)
expected.cx(1, 0)
expected.cp(pi, 0, 1)
expected.cu(pi, pi, pi, 0, 1, 0)
self.assertEqual(circuit_to_dag(expected), out_dag)
def test_unrolling_global_phase_1q(self):
"""Test unrolling a circuit with global phase in a composite gate."""
circ = QuantumCircuit(1, global_phase=pi / 2)
circ.x(0)
circ.h(0)
v = circ.to_gate()
qc = QuantumCircuit(1)
qc.append(v, [0])
dag = circuit_to_dag(qc)
out_dag = Unroller(["cx", "x", "h"]).run(dag)
qcd = dag_to_circuit(out_dag)
self.assertEqual(Operator(qc), Operator(qcd))
def test_unrolling_global_phase_nested_gates(self):
"""Test unrolling a nested gate preseveres global phase."""
qc = QuantumCircuit(1, global_phase=pi)
qc.x(0)
gate = qc.to_gate()
qc = QuantumCircuit(1)
qc.append(gate, [0])
gate = qc.to_gate()
qc = QuantumCircuit(1)
qc.append(gate, [0])
dag = circuit_to_dag(qc)
out_dag = Unroller(["x", "u"]).run(dag)
qcd = dag_to_circuit(out_dag)
self.assertEqual(Operator(qc), Operator(qcd))
def test_if_simple(self):
"""Test a simple if statement unrolls correctly."""
qubits = [Qubit(), Qubit()]
clbits = [Clbit(), Clbit()]
qc = QuantumCircuit(qubits, clbits)
qc.h(0)
qc.measure(0, 0)
with qc.if_test((clbits[0], 0)):
qc.x(0)
qc.h(0)
qc.measure(0, 1)
with qc.if_test((clbits[1], 0)):
qc.h(1)
qc.cx(1, 0)
dag = circuit_to_dag(qc)
unrolled_dag = Unroller(["u", "cx"]).run(dag)
expected = QuantumCircuit(qubits, clbits)
expected.u(pi / 2, 0, pi, 0)
expected.measure(0, 0)
with expected.if_test((clbits[0], 0)):
expected.u(pi, 0, pi, 0)
expected.u(pi / 2, 0, pi, 0)
expected.measure(0, 1)
with expected.if_test((clbits[1], 0)):
expected.u(pi / 2, 0, pi, 1)
expected.cx(1, 0)
expected_dag = circuit_to_dag(expected)
self.assertEqual(unrolled_dag, expected_dag)
def test_if_else_simple(self):
"""Test a simple if-else statement unrolls correctly."""
qubits = [Qubit(), Qubit()]
clbits = [Clbit(), Clbit()]
qc = QuantumCircuit(qubits, clbits)
qc.h(0)
qc.measure(0, 0)
with qc.if_test((clbits[0], 0)) as else_:
qc.x(0)
with else_:
qc.z(0)
qc.h(0)
qc.measure(0, 1)
with qc.if_test((clbits[1], 0)) as else_:
qc.h(1)
qc.cx(1, 0)
with else_:
qc.h(0)
qc.cx(0, 1)
dag = circuit_to_dag(qc)
unrolled_dag = Unroller(["u", "cx"]).run(dag)
expected = QuantumCircuit(qubits, clbits)
expected.u(pi / 2, 0, pi, 0)
expected.measure(0, 0)
with expected.if_test((clbits[0], 0)) as else_:
expected.u(pi, 0, pi, 0)
with else_:
expected.u(0, 0, pi, 0)
expected.u(pi / 2, 0, pi, 0)
expected.measure(0, 1)
with expected.if_test((clbits[1], 0)) as else_:
expected.u(pi / 2, 0, pi, 1)
expected.cx(1, 0)
with else_:
expected.u(pi / 2, 0, pi, 0)
expected.cx(0, 1)
expected_dag = circuit_to_dag(expected)
self.assertEqual(unrolled_dag, expected_dag)
def test_nested_control_flow(self):
"""Test unrolling nested control flow blocks."""
qr = QuantumRegister(2)
cr1 = ClassicalRegister(1)
cr2 = ClassicalRegister(1)
cr3 = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr1, cr2, cr3)
with qc.for_loop(range(3)):
with qc.while_loop((cr1, 0)):
qc.x(0)
with qc.while_loop((cr2, 0)):
qc.y(0)
with qc.while_loop((cr3, 0)):
qc.z(0)
dag = circuit_to_dag(qc)
unrolled_dag = Unroller(["u", "cx"]).run(dag)
expected = QuantumCircuit(qr, cr1, cr2, cr3)
with expected.for_loop(range(3)):
with expected.while_loop((cr1, 0)):
expected.u(pi, 0, pi, 0)
with expected.while_loop((cr2, 0)):
expected.u(pi, pi / 2, pi / 2, 0)
with expected.while_loop((cr3, 0)):
expected.u(0, 0, pi, 0)
expected_dag = circuit_to_dag(expected)
self.assertEqual(unrolled_dag, expected_dag)
def test_parameterized_angle(self):
"""Test unrolling with parameterized angle"""
qc = QuantumCircuit(1)
index = Parameter("index")
with qc.for_loop((0, 0.5 * pi), index) as param:
qc.rx(param, 0)
dag = circuit_to_dag(qc)
unrolled_dag = Unroller(["u", "cx"]).run(dag)
expected = QuantumCircuit(1)
with expected.for_loop((0, 0.5 * pi), index) as param:
expected.u(param, -pi / 2, pi / 2, 0)
expected_dag = circuit_to_dag(expected)
self.assertEqual(unrolled_dag, expected_dag)
class TestUnrollAllInstructions(QiskitTestCase):
"""Test unrolling a circuit containing all standard instructions."""
def setUp(self):
super().setUp()
qr = self.qr = QuantumRegister(3, "qr")
cr = self.cr = ClassicalRegister(3, "cr")
self.circuit = QuantumCircuit(qr, cr)
self.ref_circuit = QuantumCircuit(qr, cr)
self.pass_ = Unroller(basis=["u3", "cx", "id"])
def compare_dags(self):
"""compare dags in class tests"""
dag = circuit_to_dag(self.circuit)
unrolled_dag = self.pass_.run(dag)
ref_dag = circuit_to_dag(self.ref_circuit)
self.assertEqual(unrolled_dag, ref_dag)
def test_unroll_crx(self):
"""test unroll crx"""
# qr_1: ─────■───── qr_1: ─────────────────■─────────────────────■─────────────────────
# ┌────┴────┐ = ┌─────────────┐┌─┴─┐┌───────────────┐┌─┴─┐┌─────────────────┐
# qr_2: ┤ Rx(0.5) ├ qr_2: ┤ U3(0,0,π/2) ├┤ X ├┤ U3(-0.25,0,0) ├┤ X ├┤ U3(0.25,-π/2,0) ├
# └─────────┘ └─────────────┘└───┘└───────────────┘└───┘└─────────────────┘
self.circuit.crx(0.5, 1, 2)
self.ref_circuit.append(U3Gate(0, 0, pi / 2), [2])
self.ref_circuit.cx(1, 2)
self.ref_circuit.append(U3Gate(-0.25, 0, 0), [2])
self.ref_circuit.cx(1, 2)
self.ref_circuit.append(U3Gate(0.25, -pi / 2, 0), [2])
self.compare_dags()
def test_unroll_cry(self):
"""test unroll cry"""
# qr_1: ─────■───── qr_1: ──────────────────■─────────────────────■──
# ┌────┴────┐ = ┌──────────────┐┌─┴─┐┌───────────────┐┌─┴─┐
# qr_2: ┤ Ry(0.5) ├ qr_2: ┤ U3(0.25,0,0) ├┤ X ├┤ U3(-0.25,0,0) ├┤ X ├
# └─────────┘ └──────────────┘└───┘└───────────────┘└───┘
self.circuit.cry(0.5, 1, 2)
self.ref_circuit.append(U3Gate(0.25, 0, 0), [2])
self.ref_circuit.cx(1, 2)
self.ref_circuit.append(U3Gate(-0.25, 0, 0), [2])
self.ref_circuit.cx(1, 2)
self.compare_dags()
def test_unroll_ccx(self):
"""test unroll ccx"""
# qr_0: ──■── qr_0: ──────────────────────────────────────■──────────────────────»
# │ │ »
# qr_1: ──■── = qr_1: ─────────────────■────────────────────┼───────────────────■──»
# ┌─┴─┐ ┌─────────────┐┌─┴─┐┌──────────────┐┌─┴─┐┌─────────────┐┌─┴─┐»
# qr_2: ┤ X ├ qr_2: ┤ U3(π/2,0,π) ├┤ X ├┤ U3(0,0,-π/4) ├┤ X ├┤ U3(0,0,π/4) ├┤ X ├»
# └───┘ └─────────────┘└───┘└──────────────┘└───┘└─────────────┘└───┘»
# « ┌─────────────┐
# «qr_0: ──────────────────■─────────■───────┤ U3(0,0,π/4) ├───■──
# « ┌─────────────┐ │ ┌─┴─┐ ├─────────────┴┐┌─┴─┐
# «qr_1: ┤ U3(0,0,π/4) ├───┼───────┤ X ├─────┤ U3(0,0,-π/4) ├┤ X ├
# « ├─────────────┴┐┌─┴─┐┌────┴───┴────┐├─────────────┬┘└───┘
# «qr_2: ┤ U3(0,0,-π/4) ├┤ X ├┤ U3(0,0,π/4) ├┤ U3(π/2,0,π) ├──────
# « └──────────────┘└───┘└─────────────┘└─────────────┘
self.circuit.ccx(0, 1, 2)
self.ref_circuit.append(U3Gate(pi / 2, 0, pi), [2])
self.ref_circuit.cx(1, 2)
self.ref_circuit.append(U3Gate(0, 0, -pi / 4), [2])
self.ref_circuit.cx(0, 2)
self.ref_circuit.append(U3Gate(0, 0, pi / 4), [2])
self.ref_circuit.cx(1, 2)
self.ref_circuit.append(U3Gate(0, 0, pi / 4), [1])
self.ref_circuit.append(U3Gate(0, 0, -pi / 4), [2])
self.ref_circuit.cx(0, 2)
self.ref_circuit.cx(0, 1)
self.ref_circuit.append(U3Gate(0, 0, pi / 4), [0])
self.ref_circuit.append(U3Gate(0, 0, -pi / 4), [1])
self.ref_circuit.cx(0, 1)
self.ref_circuit.append(U3Gate(0, 0, pi / 4), [2])
self.ref_circuit.append(U3Gate(pi / 2, 0, pi), [2])
self.compare_dags()
def test_unroll_ch(self):
"""test unroll ch"""
# qr_0: ──■── qr_0: ───────────────────────────────────────────────■──────────────────»
# ┌─┴─┐ = ┌─────────────┐┌─────────────┐┌─────────────┐┌─┴─┐┌──────────────┐»
# qr_2: ┤ H ├ qr_2: ┤ U3(0,0,π/2) ├┤ U3(π/2,0,π) ├┤ U3(0,0,π/4) ├┤ X ├┤ U3(0,0,-π/4) ├»
# └───┘ └─────────────┘└─────────────┘└─────────────┘└───┘└──────────────┘»
# «
# «qr_0: ───────────────────────────────
# « ┌─────────────┐┌──────────────┐
# «qr_2: ┤ U3(π/2,0,π) ├┤ U3(0,0,-π/2) ├
# « └─────────────┘└──────────────┘
self.circuit.ch(0, 2)
self.ref_circuit.append(U3Gate(0, 0, pi / 2), [2])
self.ref_circuit.append(U3Gate(pi / 2, 0, pi), [2])
self.ref_circuit.append(U3Gate(0, 0, pi / 4), [2])
self.ref_circuit.cx(0, 2)
self.ref_circuit.append(U3Gate(0, 0, -pi / 4), [2])
self.ref_circuit.append(U3Gate(pi / 2, 0, pi), [2])
self.ref_circuit.append(U3Gate(0, 0, -pi / 2), [2])
self.compare_dags()
def test_unroll_crz(self):
"""test unroll crz"""
# qr_1: ─────■───── qr_1: ──────────────────■─────────────────────■──
# ┌────┴────┐ = ┌──────────────┐┌─┴─┐┌───────────────┐┌─┴─┐
# qr_2: ┤ Rz(0.5) ├ qr_2: ┤ U3(0,0,0.25) ├┤ X ├┤ U3(0,0,-0.25) ├┤ X ├
# └─────────┘ └──────────────┘└───┘└───────────────┘└───┘
self.circuit.crz(0.5, 1, 2)
self.ref_circuit.append(U3Gate(0, 0, 0.25), [2])
self.ref_circuit.cx(1, 2)
self.ref_circuit.append(U3Gate(0, 0, -0.25), [2])
self.ref_circuit.cx(1, 2)
def test_unroll_cswap(self):
"""test unroll cswap"""
# ┌───┐ »
# qr_0: ─X─ qr_0: ┤ X ├─────────────────■────────────────────────────────────────■──»
# │ └─┬─┘ │ │ »
# qr_1: ─■─ = qr_1: ──┼───────────────────┼────────────────────■───────────────────┼──»
# │ │ ┌─────────────┐┌─┴─┐┌──────────────┐┌─┴─┐┌─────────────┐┌─┴─┐»
# qr_2: ─X─ qr_2: ──■──┤ U3(π/2,0,π) ├┤ X ├┤ U3(0,0,-π/4) ├┤ X ├┤ U3(0,0,π/4) ├┤ X ├»
# └─────────────┘└───┘└──────────────┘└───┘└─────────────┘└───┘»
# « ┌─────────────┐ ┌───┐ ┌──────────────┐┌───┐┌───┐
# «qr_0: ┤ U3(0,0,π/4) ├───────────┤ X ├─────┤ U3(0,0,-π/4) ├┤ X ├┤ X ├
# « └─────────────┘ └─┬─┘ ├─────────────┬┘└─┬─┘└─┬─┘
# «qr_1: ──────────────────■─────────■───────┤ U3(0,0,π/4) ├───■────┼──
# « ┌──────────────┐┌─┴─┐┌─────────────┐├─────────────┤ │
# «qr_2: ┤ U3(0,0,-π/4) ├┤ X ├┤ U3(0,0,π/4) ├┤ U3(π/2,0,π) ├────────■──
# « └──────────────┘└───┘└─────────────┘└─────────────┘
self.circuit.cswap(1, 0, 2)
self.ref_circuit.cx(2, 0)
self.ref_circuit.append(U3Gate(pi / 2, 0, pi), [2])
self.ref_circuit.cx(0, 2)
self.ref_circuit.append(U3Gate(0, 0, -pi / 4), [2])
self.ref_circuit.cx(1, 2)
self.ref_circuit.append(U3Gate(0, 0, pi / 4), [2])
self.ref_circuit.cx(0, 2)
self.ref_circuit.append(U3Gate(0, 0, pi / 4), [0])
self.ref_circuit.append(U3Gate(0, 0, -pi / 4), [2])
self.ref_circuit.cx(1, 2)
self.ref_circuit.cx(1, 0)
self.ref_circuit.append(U3Gate(0, 0, -pi / 4), [0])
self.ref_circuit.append(U3Gate(0, 0, pi / 4), [1])
self.ref_circuit.cx(1, 0)
self.ref_circuit.append(U3Gate(0, 0, pi / 4), [2])
self.ref_circuit.append(U3Gate(pi / 2, 0, pi), [2])
self.ref_circuit.cx(2, 0)
self.compare_dags()
def test_unroll_cu1(self):
"""test unroll cu1"""
# ┌──────────────┐
# qr_0: ─■──────── qr_0: ┤ U3(0,0,0.05) ├──■─────────────────────■──────────────────
# │U1(0.1) = └──────────────┘┌─┴─┐┌───────────────┐┌─┴─┐┌──────────────┐
# qr_2: ─■──────── qr_2: ────────────────┤ X ├┤ U3(0,0,-0.05) ├┤ X ├┤ U3(0,0,0.05) ├
# └───┘└───────────────┘└───┘└──────────────┘
self.circuit.append(CU1Gate(0.1), [0, 2])
self.ref_circuit.append(U3Gate(0, 0, 0.05), [0])
self.ref_circuit.cx(0, 2)
self.ref_circuit.append(U3Gate(0, 0, -0.05), [2])
self.ref_circuit.cx(0, 2)
self.ref_circuit.append(U3Gate(0, 0, 0.05), [2])
self.compare_dags()
def test_unroll_cu3(self):
"""test unroll cu3"""
# ┌──────────────┐
# q_1: ────────■──────── q_1: ─┤ U3(0,0,0.05) ├──■────────────────────────■───────────────────
# ┌───────┴───────┐ = ┌┴──────────────┤┌─┴─┐┌──────────────────┐┌─┴─┐┌───────────────┐
# q_2: ┤ U3(0.2,0.1,0) ├ q_2: ┤ U3(0,0,-0.05) ├┤ X ├┤ U3(-0.1,0,-0.05) ├┤ X ├┤ U3(0.1,0.1,0) ├
# └───────────────┘ └───────────────┘└───┘└──────────────────┘└───┘└───────────────┘
self.circuit.append(CU3Gate(0.2, 0.1, 0.0), [1, 2])
self.ref_circuit.append(U3Gate(0, 0, 0.05), [1])
self.ref_circuit.append(U3Gate(0, 0, -0.05), [2])
self.ref_circuit.cx(1, 2)
self.ref_circuit.append(U3Gate(-0.1, 0, -0.05), [2])
self.ref_circuit.cx(1, 2)
self.ref_circuit.append(U3Gate(0.1, 0.1, 0), [2])
self.compare_dags()
def test_unroll_cx(self):
"""test unroll cx"""
self.circuit.cx(1, 0)
self.ref_circuit.cx(1, 0)
self.compare_dags()
def test_unroll_cy(self):
"""test unroll cy"""
# qr_1: ──■── qr_1: ──────────────────■─────────────────
# ┌─┴─┐ = ┌──────────────┐┌─┴─┐┌─────────────┐
# qr_2: ┤ Y ├ qr_2: ┤ U3(0,0,-π/2) ├┤ X ├┤ U3(0,0,π/2) ├
# └───┘ └──────────────┘└───┘└─────────────┘
self.circuit.cy(1, 2)
self.ref_circuit.append(U3Gate(0, 0, -pi / 2), [2])
self.ref_circuit.cx(1, 2)
self.ref_circuit.append(U3Gate(0, 0, pi / 2), [2])
self.compare_dags()
def test_unroll_cz(self):
"""test unroll cz"""
# ┌─────────────┐┌───┐┌─────────────┐
# qr_0: ─■─ qr_0: ┤ U3(π/2,0,π) ├┤ X ├┤ U3(π/2,0,π) ├
# │ = └─────────────┘└─┬─┘└─────────────┘
# qr_2: ─■─ qr_2: ─────────────────■─────────────────
self.circuit.cz(2, 0)
self.ref_circuit.append(U3Gate(pi / 2, 0, pi), [0])
self.ref_circuit.cx(2, 0)
self.ref_circuit.append(U3Gate(pi / 2, 0, pi), [0])
self.compare_dags()
def test_unroll_h(self):
"""test unroll h"""
self.circuit.h(1)
self.ref_circuit.append(U3Gate(pi / 2, 0, pi), [1])
self.compare_dags()
def test_unroll_i(self):
"""test unroll i"""
self.circuit.i(0)
self.ref_circuit.i(0)
self.compare_dags()
def test_unroll_rx(self):
"""test unroll rx"""
self.circuit.rx(0.1, 0)
self.ref_circuit.append(U3Gate(0.1, -pi / 2, pi / 2), [0])
self.compare_dags()
def test_unroll_ry(self):
"""test unroll ry"""
self.circuit.ry(0.2, 1)
self.ref_circuit.append(U3Gate(0.2, 0, 0), [1])
self.compare_dags()
def test_unroll_rz(self):
"""test unroll rz"""
self.circuit.rz(0.3, 2)
self.ref_circuit.global_phase = -1 * 0.3 / 2
self.ref_circuit.append(U3Gate(0, 0, 0.3), [2])
self.compare_dags()
def test_unroll_rzz(self):
"""test unroll rzz"""
# global phase: 5.9832
# ┌───┐┌─────────────┐┌───┐
# qr_0: ─■──────── qr_0: ┤ X ├┤ U3(0,0,0.6) ├┤ X ├
# │ZZ(0.6) = └─┬─┘└─────────────┘└─┬─┘
# qr_1: ─■──────── qr_1: ──■───────────────────■──
self.circuit.rzz(0.6, 1, 0)
self.ref_circuit.global_phase = -1 * 0.6 / 2
self.ref_circuit.cx(1, 0)
self.ref_circuit.append(U3Gate(0, 0, 0.6), [0])
self.ref_circuit.cx(1, 0)
self.compare_dags()
def test_unroll_s(self):
"""test unroll s"""
self.circuit.s(0)
self.ref_circuit.append(U3Gate(0, 0, pi / 2), [0])
self.compare_dags()
def test_unroll_sdg(self):
"""test unroll sdg"""
self.circuit.sdg(1)
self.ref_circuit.append(U3Gate(0, 0, -pi / 2), [1])
self.compare_dags()
def test_unroll_swap(self):
"""test unroll swap"""
# ┌───┐
# qr_1: ─X─ qr_1: ──■──┤ X ├──■──
# │ = ┌─┴─┐└─┬─┘┌─┴─┐
# qr_2: ─X─ qr_2: ┤ X ├──■──┤ X ├
# └───┘ └───┘
self.circuit.swap(1, 2)
self.ref_circuit.cx(1, 2)
self.ref_circuit.cx(2, 1)
self.ref_circuit.cx(1, 2)
self.compare_dags()
def test_unroll_t(self):
"""test unroll t"""
self.circuit.t(2)
self.ref_circuit.append(U3Gate(0, 0, pi / 4), [2])
self.compare_dags()
def test_unroll_tdg(self):
"""test unroll tdg"""
self.circuit.tdg(0)
self.ref_circuit.append(U3Gate(0, 0, -pi / 4), [0])
self.compare_dags()
def test_unroll_u1(self):
"""test unroll u1"""
self.circuit.append(U1Gate(0.1), [1])
self.ref_circuit.append(U3Gate(0, 0, 0.1), [1])
self.compare_dags()
def test_unroll_u2(self):
"""test unroll u2"""
self.circuit.append(U2Gate(0.2, -0.1), [0])
self.ref_circuit.append(U3Gate(pi / 2, 0.2, -0.1), [0])
self.compare_dags()
def test_unroll_u3(self):
"""test unroll u3"""
self.circuit.append(U3Gate(0.3, 0.0, -0.1), [2])
self.ref_circuit.append(U3Gate(0.3, 0.0, -0.1), [2])
self.compare_dags()
def test_unroll_x(self):
"""test unroll x"""
self.circuit.x(2)
self.ref_circuit.append(U3Gate(pi, 0, pi), [2])
self.compare_dags()
def test_unroll_y(self):
"""test unroll y"""
self.circuit.y(1)
self.ref_circuit.append(U3Gate(pi, pi / 2, pi / 2), [1])
self.compare_dags()
def test_unroll_z(self):
"""test unroll z"""
self.circuit.z(0)
self.ref_circuit.append(U3Gate(0, 0, pi), [0])
self.compare_dags()
def test_unroll_snapshot(self):
"""test unroll snapshot"""
num_qubits = self.circuit.num_qubits
instr = Snapshot("0", num_qubits=num_qubits)
self.circuit.append(instr, range(num_qubits))
self.ref_circuit.append(instr, range(num_qubits))
self.compare_dags()
def test_unroll_measure(self):
"""test unroll measure"""
self.circuit.measure(self.qr, self.cr)
self.ref_circuit.measure(self.qr, self.cr)
self.compare_dags()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the Unroll3qOrMore pass"""
import numpy as np
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.circuit import Qubit, Clbit
from qiskit.circuit.library import CCXGate, RCCXGate
from qiskit.transpiler.passes import Unroll3qOrMore
from qiskit.converters import circuit_to_dag, dag_to_circuit
from qiskit.quantum_info.operators import Operator
from qiskit.quantum_info.random import random_unitary
from qiskit.test import QiskitTestCase
from qiskit.extensions import UnitaryGate
from qiskit.transpiler import Target
class TestUnroll3qOrMore(QiskitTestCase):
"""Tests the Unroll3qOrMore pass, for unrolling all
gates until reaching only 1q or 2q gates."""
def test_ccx(self):
"""Test decompose CCX."""
qr1 = QuantumRegister(2, "qr1")
qr2 = QuantumRegister(1, "qr2")
circuit = QuantumCircuit(qr1, qr2)
circuit.ccx(qr1[0], qr1[1], qr2[0])
dag = circuit_to_dag(circuit)
pass_ = Unroll3qOrMore()
after_dag = pass_.run(dag)
op_nodes = after_dag.op_nodes()
self.assertEqual(len(op_nodes), 15)
for node in op_nodes:
self.assertIn(node.name, ["h", "t", "tdg", "cx"])
def test_cswap(self):
"""Test decompose CSwap (recursively)."""
qr1 = QuantumRegister(2, "qr1")
qr2 = QuantumRegister(1, "qr2")
circuit = QuantumCircuit(qr1, qr2)
circuit.cswap(qr1[0], qr1[1], qr2[0])
dag = circuit_to_dag(circuit)
pass_ = Unroll3qOrMore()
after_dag = pass_.run(dag)
op_nodes = after_dag.op_nodes()
self.assertEqual(len(op_nodes), 17)
for node in op_nodes:
self.assertIn(node.name, ["h", "t", "tdg", "cx"])
def test_decompose_conditional(self):
"""Test decompose a 3-qubit gate with a conditional."""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.ccx(qr[0], qr[1], qr[2]).c_if(cr, 0)
dag = circuit_to_dag(circuit)
pass_ = Unroll3qOrMore()
after_dag = pass_.run(dag)
op_nodes = after_dag.op_nodes()
self.assertEqual(len(op_nodes), 15)
for node in op_nodes:
self.assertIn(node.name, ["h", "t", "tdg", "cx"])
self.assertEqual(node.op.condition, (cr, 0))
def test_decompose_unitary(self):
"""Test unrolling of unitary gate over 4qubits."""
qr = QuantumRegister(4, "qr")
circuit = QuantumCircuit(qr)
unitary = random_unitary(16, seed=42)
circuit.unitary(unitary, [0, 1, 2, 3])
dag = circuit_to_dag(circuit)
pass_ = Unroll3qOrMore()
after_dag = pass_.run(dag)
after_circ = dag_to_circuit(after_dag)
self.assertTrue(Operator(circuit).equiv(Operator(after_circ)))
def test_identity(self):
"""Test unrolling of identity gate over 3qubits."""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
gate = UnitaryGate(np.eye(2**3))
circuit.append(gate, range(3))
dag = circuit_to_dag(circuit)
pass_ = Unroll3qOrMore()
after_dag = pass_.run(dag)
after_circ = dag_to_circuit(after_dag)
self.assertTrue(Operator(circuit).equiv(Operator(after_circ)))
def test_target(self):
"""Test target is respected by the unroll 3q or more pass."""
target = Target(num_qubits=3)
target.add_instruction(CCXGate())
qc = QuantumCircuit(3)
qc.ccx(0, 1, 2)
qc.append(RCCXGate(), [0, 1, 2])
unroll_pass = Unroll3qOrMore(target=target)
res = unroll_pass(qc)
self.assertIn("ccx", res.count_ops())
self.assertNotIn("rccx", res.count_ops())
def test_basis_gates(self):
"""Test basis_gates are respected by the unroll 3q or more pass."""
basis_gates = ["rccx"]
qc = QuantumCircuit(3)
qc.ccx(0, 1, 2)
qc.append(RCCXGate(), [0, 1, 2])
unroll_pass = Unroll3qOrMore(basis_gates=basis_gates)
res = unroll_pass(qc)
self.assertNotIn("ccx", res.count_ops())
self.assertIn("rccx", res.count_ops())
def test_target_over_basis_gates(self):
"""Test target is respected over basis_gates by the unroll 3q or more pass."""
target = Target(num_qubits=3)
basis_gates = ["rccx"]
target.add_instruction(CCXGate())
qc = QuantumCircuit(3)
qc.ccx(0, 1, 2)
qc.append(RCCXGate(), [0, 1, 2])
unroll_pass = Unroll3qOrMore(target=target, basis_gates=basis_gates)
res = unroll_pass(qc)
self.assertIn("ccx", res.count_ops())
self.assertNotIn("rccx", res.count_ops())
def test_if_else(self):
"""Test that a simple if-else over 3+ qubits unrolls correctly."""
pass_ = Unroll3qOrMore(basis_gates=["u", "cx"])
true_body = QuantumCircuit(3, 1)
true_body.h(0)
true_body.ccx(0, 1, 2)
false_body = QuantumCircuit(3, 1)
false_body.rccx(2, 1, 0)
test = QuantumCircuit(3, 1)
test.h(0)
test.measure(0, 0)
test.if_else((0, True), true_body, false_body, [0, 1, 2], [0])
expected = QuantumCircuit(3, 1)
expected.h(0)
expected.measure(0, 0)
expected.if_else((0, True), pass_(true_body), pass_(false_body), [0, 1, 2], [0])
self.assertEqual(pass_(test), expected)
def test_nested_control_flow(self):
"""Test that the unroller recurses into nested control flow."""
pass_ = Unroll3qOrMore(basis_gates=["u", "cx"])
qubits = [Qubit() for _ in [None] * 3]
clbit = Clbit()
for_body = QuantumCircuit(qubits, [clbit])
for_body.ccx(0, 1, 2)
while_body = QuantumCircuit(qubits, [clbit])
while_body.rccx(0, 1, 2)
true_body = QuantumCircuit(qubits, [clbit])
true_body.while_loop((clbit, True), while_body, [0, 1, 2], [0])
test = QuantumCircuit(qubits, [clbit])
test.for_loop(range(2), None, for_body, [0, 1, 2], [0])
test.if_else((clbit, True), true_body, None, [0, 1, 2], [0])
expected_if_body = QuantumCircuit(qubits, [clbit])
expected_if_body.while_loop((clbit, True), pass_(while_body), [0, 1, 2], [0])
expected = QuantumCircuit(qubits, [clbit])
expected.for_loop(range(2), None, pass_(for_body), [0, 1, 2], [0])
expected.if_else(range(2), pass_(expected_if_body), None, [0, 1, 2], [0])
self.assertEqual(pass_(test), expected)
def test_if_else_in_basis(self):
"""Test that a simple if-else over 3+ qubits unrolls correctly."""
pass_ = Unroll3qOrMore(basis_gates=["u", "cx", "if_else", "for_loop", "while_loop"])
true_body = QuantumCircuit(3, 1)
true_body.h(0)
true_body.ccx(0, 1, 2)
false_body = QuantumCircuit(3, 1)
false_body.rccx(2, 1, 0)
test = QuantumCircuit(3, 1)
test.h(0)
test.measure(0, 0)
test.if_else((0, True), true_body, false_body, [0, 1, 2], [0])
expected = QuantumCircuit(3, 1)
expected.h(0)
expected.measure(0, 0)
expected.if_else((0, True), pass_(true_body), pass_(false_body), [0, 1, 2], [0])
self.assertEqual(pass_(test), expected)
def test_nested_control_flow_in_basis(self):
"""Test that the unroller recurses into nested control flow."""
pass_ = Unroll3qOrMore(basis_gates=["u", "cx", "if_else", "for_loop", "while_loop"])
qubits = [Qubit() for _ in [None] * 3]
clbit = Clbit()
for_body = QuantumCircuit(qubits, [clbit])
for_body.ccx(0, 1, 2)
while_body = QuantumCircuit(qubits, [clbit])
while_body.rccx(0, 1, 2)
true_body = QuantumCircuit(qubits, [clbit])
true_body.while_loop((clbit, True), while_body, [0, 1, 2], [0])
test = QuantumCircuit(qubits, [clbit])
test.for_loop(range(2), None, for_body, [0, 1, 2], [0])
test.if_else((clbit, True), true_body, None, [0, 1, 2], [0])
expected_if_body = QuantumCircuit(qubits, [clbit])
expected_if_body.while_loop((clbit, True), pass_(while_body), [0, 1, 2], [0])
expected = QuantumCircuit(qubits, [clbit])
expected.for_loop(range(2), None, pass_(for_body), [0, 1, 2], [0])
expected.if_else(range(2), pass_(expected_if_body), None, [0, 1, 2], [0])
self.assertEqual(pass_(test), expected)
def test_custom_block_over_3q(self):
"""Test a custom instruction is unrolled in a control flow block."""
pass_ = Unroll3qOrMore(basis_gates=["u", "cx", "if_else", "for_loop", "while_loop"])
ghz = QuantumCircuit(5, 5)
ghz.h(0)
ghz.cx(0, 1)
ghz.cx(0, 2)
ghz.cx(0, 3)
ghz.cx(0, 4)
ghz.measure(0, 0)
ghz.measure(1, 1)
ghz.measure(2, 2)
ghz.measure(3, 3)
ghz.measure(4, 4)
ghz.reset(0)
ghz.reset(1)
ghz.reset(2)
ghz.reset(3)
ghz.reset(4)
for_block = QuantumCircuit(5, 5, name="ghz")
for_block.append(ghz, list(range(5)), list(range(5)))
qc = QuantumCircuit(5, 5)
qc.for_loop((1,), None, for_block, [2, 4, 1, 3, 0], [0, 1, 2, 3, 4])
result = pass_(qc)
expected = QuantumCircuit(5, 5)
expected.for_loop((1,), None, ghz, [2, 4, 1, 3, 0], [0, 1, 2, 3, 4])
self.assertEqual(result, expected)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the VF2Layout pass"""
import io
import pickle
import unittest
from math import pi
import ddt
import numpy
import rustworkx
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister
from qiskit.circuit import ControlFlowOp
from qiskit.transpiler import CouplingMap, Target, TranspilerError
from qiskit.transpiler.passes.layout.vf2_layout import VF2Layout, VF2LayoutStopReason
from qiskit._accelerate.error_map import ErrorMap
from qiskit.converters import circuit_to_dag
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import (
FakeTenerife,
FakeVigoV2,
FakeRueschlikon,
FakeManhattan,
FakeYorktown,
FakeGuadalupeV2,
)
from qiskit.circuit import Measure
from qiskit.circuit.library import GraphState, CXGate, XGate, HGate
from qiskit.transpiler import PassManager, AnalysisPass
from qiskit.transpiler.target import InstructionProperties
from qiskit.transpiler.preset_passmanagers.common import generate_embed_passmanager
class LayoutTestCase(QiskitTestCase):
"""VF2Layout assertions"""
seed = 42
def assertLayout(self, dag, coupling_map, property_set, strict_direction=False):
"""Checks if the circuit in dag was a perfect layout in property_set for the given
coupling_map"""
self.assertEqual(property_set["VF2Layout_stop_reason"], VF2LayoutStopReason.SOLUTION_FOUND)
layout = property_set["layout"]
edges = coupling_map.graph.edge_list()
def run(dag, wire_map):
for gate in dag.two_qubit_ops():
if dag.has_calibration_for(gate) or isinstance(gate.op, ControlFlowOp):
continue
physical_q0 = wire_map[gate.qargs[0]]
physical_q1 = wire_map[gate.qargs[1]]
if strict_direction:
result = (physical_q0, physical_q1) in edges
else:
result = (physical_q0, physical_q1) in edges or (
physical_q1,
physical_q0,
) in edges
self.assertTrue(result)
for node in dag.op_nodes(ControlFlowOp):
for block in node.op.blocks:
inner_wire_map = {
inner: wire_map[outer] for outer, inner in zip(node.qargs, block.qubits)
}
run(circuit_to_dag(block), inner_wire_map)
run(dag, {bit: layout[bit] for bit in dag.qubits})
@ddt.ddt
class TestVF2LayoutSimple(LayoutTestCase):
"""Tests the VF2Layout pass"""
def test_1q_component_influence(self):
"""Assert that the 1q component of a connected interaction graph is scored correctly."""
target = Target()
target.add_instruction(
CXGate(),
{
(0, 1): InstructionProperties(error=0.0),
(1, 2): InstructionProperties(error=0.0),
(2, 3): InstructionProperties(error=0.0),
},
)
target.add_instruction(
HGate(),
{
(0,): InstructionProperties(error=0.0),
(1,): InstructionProperties(error=0.0),
(2,): InstructionProperties(error=0.0),
},
)
target.add_instruction(
Measure(),
{
(0,): InstructionProperties(error=0.1),
(1,): InstructionProperties(error=0.1),
(2,): InstructionProperties(error=0.9),
},
)
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.cx(1, 0)
qc.measure(0, 0)
qc.measure(1, 1)
vf2_pass = VF2Layout(target=target, seed=self.seed)
vf2_pass(qc)
layout = vf2_pass.property_set["layout"]
self.assertEqual([1, 0], list(layout._p2v.keys()))
def test_2q_circuit_2q_coupling(self):
"""A simple example, without considering the direction
0 - 1
qr1 - qr0
"""
cmap = CouplingMap([[0, 1]])
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0]) # qr1 -> qr0
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap, strict_direction=False, seed=self.seed, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, cmap, pass_.property_set)
def test_2q_circuit_2q_coupling_sd(self):
"""A simple example, considering the direction
0 -> 1
qr1 -> qr0
"""
cmap = CouplingMap([[0, 1]])
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0]) # qr1 -> qr0
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap, strict_direction=True, seed=self.seed, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, cmap, pass_.property_set, strict_direction=True)
@ddt.data(True, False)
def test_2q_circuit_simple_control_flow(self, strict_direction):
"""Test that simple control-flow can be routed on a 2q coupling map."""
cmap = CouplingMap([(0, 1)])
circuit = QuantumCircuit(2)
with circuit.for_loop((1,)):
circuit.cx(1, 0)
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap, strict_direction=strict_direction, seed=self.seed, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, cmap, pass_.property_set, strict_direction=strict_direction)
@ddt.data(True, False)
def test_2q_circuit_nested_control_flow(self, strict_direction):
"""Test that simple control-flow can be routed on a 2q coupling map."""
cmap = CouplingMap([(0, 1)])
circuit = QuantumCircuit(2, 1)
with circuit.while_loop((circuit.clbits[0], True)):
with circuit.if_test((circuit.clbits[0], True)) as else_:
circuit.cx(1, 0)
with else_:
circuit.cx(1, 0)
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap, strict_direction=strict_direction, seed=self.seed, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, cmap, pass_.property_set, strict_direction=strict_direction)
def test_3q_circuit_3q_coupling_non_induced(self):
"""A simple example, check for non-induced subgraph
1 qr0 -> qr1 -> qr2
/ \
0 - 2
"""
cmap = CouplingMap([[0, 1], [1, 2], [2, 0]])
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1]) # qr0-> qr1
circuit.cx(qr[1], qr[2]) # qr1-> qr2
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap, seed=-1, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, cmap, pass_.property_set)
def test_3q_circuit_3q_coupling_non_induced_control_flow(self):
r"""A simple example, check for non-induced subgraph
1 qr0 -> qr1 -> qr2
/ \
0 - 2
"""
cmap = CouplingMap([[0, 1], [1, 2], [2, 0]])
circuit = QuantumCircuit(3, 1)
with circuit.for_loop((1,)):
circuit.cx(0, 1) # qr0-> qr1
with circuit.if_test((circuit.clbits[0], True)) as else_:
pass
with else_:
with circuit.while_loop((circuit.clbits[0], True)):
circuit.cx(1, 2) # qr1-> qr2
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap, seed=-1, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, cmap, pass_.property_set)
def test_call_limit(self):
"""Test that call limit is enforce."""
cmap = CouplingMap([[0, 1], [1, 2], [2, 0]])
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1]) # qr0-> qr1
circuit.cx(qr[1], qr[2]) # qr1-> qr2
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap, seed=-1, call_limit=1)
pass_.run(dag)
self.assertEqual(
pass_.property_set["VF2Layout_stop_reason"], VF2LayoutStopReason.NO_SOLUTION_FOUND
)
def test_coupling_map_and_target(self):
"""Test that a Target is used instead of a CouplingMap if both are specified."""
cmap = CouplingMap([[0, 1], [1, 2]])
target = Target()
target.add_instruction(CXGate(), {(0, 1): None, (1, 2): None, (1, 0): None})
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1]) # qr0-> qr1
circuit.cx(qr[1], qr[2]) # qr1-> qr2
circuit.cx(qr[1], qr[0]) # qr1-> qr0
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap, seed=-1, max_trials=1, target=target)
pass_.run(dag)
self.assertLayout(dag, target.build_coupling_map(), pass_.property_set)
def test_neither_coupling_map_or_target(self):
"""Test that we raise if neither a target or coupling map is specified."""
vf2_pass = VF2Layout(seed=123, call_limit=1000, time_limit=20, max_trials=7)
circuit = QuantumCircuit(2)
dag = circuit_to_dag(circuit)
with self.assertRaises(TranspilerError):
vf2_pass.run(dag)
def test_target_no_error(self):
"""Test that running vf2layout on a pass against a target with no error rates works."""
n_qubits = 15
target = Target()
target.add_instruction(CXGate(), {(i, i + 1): None for i in range(n_qubits - 1)})
vf2_pass = VF2Layout(target=target)
circuit = QuantumCircuit(2)
circuit.cx(0, 1)
dag = circuit_to_dag(circuit)
vf2_pass.run(dag)
self.assertLayout(dag, target.build_coupling_map(), vf2_pass.property_set)
def test_target_some_error(self):
"""Test that running vf2layout on a pass against a target with some error rates works."""
n_qubits = 15
target = Target()
target.add_instruction(
XGate(), {(i,): InstructionProperties(error=0.00123) for i in range(n_qubits)}
)
target.add_instruction(CXGate(), {(i, i + 1): None for i in range(n_qubits - 1)})
vf2_pass = VF2Layout(target=target)
circuit = QuantumCircuit(2)
circuit.h(0)
circuit.cx(0, 1)
dag = circuit_to_dag(circuit)
vf2_pass.run(dag)
self.assertLayout(dag, target.build_coupling_map(), vf2_pass.property_set)
class TestVF2LayoutLattice(LayoutTestCase):
"""Fit in 25x25 hexagonal lattice coupling map"""
cmap25 = CouplingMap.from_hexagonal_lattice(25, 25, bidirectional=False)
def graph_state_from_pygraph(self, graph):
"""Creates a GraphState circuit from a PyGraph"""
adjacency_matrix = rustworkx.adjacency_matrix(graph)
return GraphState(adjacency_matrix).decompose()
def test_hexagonal_lattice_graph_20_in_25(self):
"""A 20x20 interaction map in 25x25 coupling map"""
graph_20_20 = rustworkx.generators.hexagonal_lattice_graph(20, 20)
circuit = self.graph_state_from_pygraph(graph_20_20)
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(self.cmap25, seed=self.seed, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, self.cmap25, pass_.property_set)
def test_hexagonal_lattice_graph_9_in_25(self):
"""A 9x9 interaction map in 25x25 coupling map"""
graph_9_9 = rustworkx.generators.hexagonal_lattice_graph(9, 9)
circuit = self.graph_state_from_pygraph(graph_9_9)
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(self.cmap25, seed=self.seed, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, self.cmap25, pass_.property_set)
class TestVF2LayoutBackend(LayoutTestCase):
"""Tests VF2Layout against backends"""
def test_5q_circuit_Rueschlikon_no_solution(self):
"""5 qubits in Rueschlikon, no solution
q0[1] ↖ ↗ q0[2]
q0[0]
q0[3] ↙ ↘ q0[4]
"""
cmap16 = FakeRueschlikon().configuration().coupling_map
qr = QuantumRegister(5, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[2])
circuit.cx(qr[0], qr[3])
circuit.cx(qr[0], qr[4])
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(CouplingMap(cmap16), seed=self.seed, max_trials=1)
pass_.run(dag)
layout = pass_.property_set["layout"]
self.assertIsNone(layout)
self.assertEqual(
pass_.property_set["VF2Layout_stop_reason"], VF2LayoutStopReason.NO_SOLUTION_FOUND
)
def test_9q_circuit_Rueschlikon_sd(self):
"""9 qubits in Rueschlikon, considering the direction
1 → 2 → 3 → 4 ← 5 ← 6 → 7 ← 8
↓ ↑ ↓ ↓ ↑ ↓ ↓ ↑
0 ← 15 → 14 ← 13 ← 12 → 11 → 10 ← 9
"""
cmap16 = CouplingMap(FakeRueschlikon().configuration().coupling_map)
qr0 = QuantumRegister(4, "q0")
qr1 = QuantumRegister(5, "q1")
circuit = QuantumCircuit(qr0, qr1)
circuit.cx(qr0[1], qr0[2]) # q0[1] -> q0[2]
circuit.cx(qr0[0], qr1[3]) # q0[0] -> q1[3]
circuit.cx(qr1[4], qr0[2]) # q1[4] -> q0[2]
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap16, strict_direction=True, seed=self.seed, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, cmap16, pass_.property_set)
def test_4q_circuit_Tenerife_loose_nodes(self):
"""4 qubits in Tenerife, with loose nodes
1
↙ ↑
0 ← 2 ← 3
↑ ↙
4
"""
cmap5 = CouplingMap(FakeTenerife().configuration().coupling_map)
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0]) # qr1 -> qr0
circuit.cx(qr[0], qr[2]) # qr0 -> qr2
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap5, seed=self.seed, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, cmap5, pass_.property_set)
def test_3q_circuit_Tenerife_sd(self):
"""3 qubits in Tenerife, considering the direction
1 1
↙ ↑ ↙ ↑
0 ← 2 ← 3 0 ← qr2 ← qr1
↑ ↙ ↑ ↙
4 qr0
"""
cmap5 = CouplingMap(FakeTenerife().configuration().coupling_map)
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0]) # qr1 -> qr0
circuit.cx(qr[0], qr[2]) # qr0 -> qr2
circuit.cx(qr[1], qr[2]) # qr1 -> qr2
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap5, strict_direction=True, seed=self.seed, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, cmap5, pass_.property_set, strict_direction=True)
def test_9q_circuit_Rueschlikon(self):
"""9 qubits in Rueschlikon, without considering the direction
1 → 2 → 3 → 4 ← 5 ← 6 → 7 ← 8
↓ ↑ ↓ ↓ ↑ ↓ ↓ ↑
0 ← 15 → 14 ← 13 ← 12 → 11 → 10 ← 9
1 -- q1_0 - q1_1 - 4 --- 5 -- 6 - 7 --- q0_1
| | | | | | | |
q1_2 - q1_3 - q0_0 - 13 - q0_3 - 11 - q1_4 - q0_2
"""
cmap16 = CouplingMap(FakeRueschlikon().configuration().coupling_map)
qr0 = QuantumRegister(4, "q0")
qr1 = QuantumRegister(5, "q1")
circuit = QuantumCircuit(qr0, qr1)
circuit.cx(qr0[1], qr0[2]) # q0[1] -> q0[2]
circuit.cx(qr0[0], qr1[3]) # q0[0] -> q1[3]
circuit.cx(qr1[4], qr0[2]) # q1[4] -> q0[2]
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap16, strict_direction=False, seed=self.seed, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, cmap16, pass_.property_set)
def test_3q_circuit_Tenerife(self):
"""3 qubits in Tenerife, without considering the direction
1 1
↙ ↑ / |
0 ← 2 ← 3 0 - qr1 - qr2
↑ ↙ | /
4 qr0
"""
cmap5 = CouplingMap(FakeTenerife().configuration().coupling_map)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0]) # qr1 -> qr0
circuit.cx(qr[0], qr[2]) # qr0 -> qr2
circuit.cx(qr[1], qr[2]) # qr1 -> qr2
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap5, strict_direction=False, seed=self.seed, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, cmap5, pass_.property_set)
def test_3q_circuit_vigo_with_custom_scores(self):
"""Test custom ErrorMap from analysis pass are used for scoring."""
backend = FakeVigoV2()
target = backend.target
class FakeScore(AnalysisPass):
"""Fake analysis pass with custom scoring."""
def run(self, dag):
error_map = ErrorMap(9)
error_map.add_error((0, 0), 0.1)
error_map.add_error((0, 1), 0.5)
error_map.add_error((1, 1), 0.2)
error_map.add_error((1, 2), 0.8)
error_map.add_error((1, 3), 0.75)
error_map.add_error((2, 2), 0.123)
error_map.add_error((3, 3), 0.333)
error_map.add_error((3, 4), 0.12345423)
error_map.add_error((4, 4), 0.2222)
self.property_set["vf2_avg_error_map"] = error_map
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0]) # qr1 -> qr0
circuit.cx(qr[0], qr[2]) # qr0 -> qr2
vf2_pass = VF2Layout(target=target, seed=1234568942)
property_set = {}
vf2_pass(circuit, property_set)
pm = PassManager([FakeScore(), VF2Layout(target=target, seed=1234568942)])
pm.run(circuit)
# Assert layout is different from backend properties
self.assertNotEqual(property_set["layout"], pm.property_set["layout"])
self.assertLayout(circuit_to_dag(circuit), backend.coupling_map, pm.property_set)
def test_error_map_pickle(self):
"""Test that the `ErrorMap` Rust structure correctly pickles and depickles."""
errors = {(0, 1): 0.2, (1, 0): 0.2, (0, 0): 0.05, (1, 1): 0.02}
error_map = ErrorMap.from_dict(errors)
with io.BytesIO() as fptr:
pickle.dump(error_map, fptr)
fptr.seek(0)
loaded = pickle.load(fptr)
self.assertEqual(len(loaded), len(errors))
self.assertEqual({k: loaded[k] for k in errors}, errors)
def test_perfect_fit_Manhattan(self):
"""A circuit that fits perfectly in Manhattan (65 qubits)
See https://github.com/Qiskit/qiskit-terra/issues/5694"""
manhattan_cm = FakeManhattan().configuration().coupling_map
cmap65 = CouplingMap(manhattan_cm)
rows = [x[0] for x in manhattan_cm]
cols = [x[1] for x in manhattan_cm]
adj_matrix = numpy.zeros((65, 65))
adj_matrix[rows, cols] = 1
circuit = GraphState(adj_matrix).decompose()
circuit.measure_all()
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap65, seed=self.seed, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, cmap65, pass_.property_set)
class TestVF2LayoutOther(LayoutTestCase):
"""Other VF2Layout tests"""
def test_seed(self):
"""Different seeds yield different results"""
seed_1 = 42
seed_2 = 45
cmap5 = FakeTenerife().configuration().coupling_map
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0]) # qr1 -> qr0
circuit.cx(qr[0], qr[2]) # qr0 -> qr2
circuit.cx(qr[1], qr[2]) # qr1 -> qr2
dag = circuit_to_dag(circuit)
pass_1 = VF2Layout(CouplingMap(cmap5), seed=seed_1, max_trials=1)
pass_1.run(dag)
layout_1 = pass_1.property_set["layout"]
self.assertEqual(
pass_1.property_set["VF2Layout_stop_reason"], VF2LayoutStopReason.SOLUTION_FOUND
)
pass_2 = VF2Layout(CouplingMap(cmap5), seed=seed_2, max_trials=1)
pass_2.run(dag)
layout_2 = pass_2.property_set["layout"]
self.assertEqual(
pass_2.property_set["VF2Layout_stop_reason"], VF2LayoutStopReason.SOLUTION_FOUND
)
self.assertNotEqual(layout_1, layout_2)
def test_3_q_gate(self):
"""The pass does not handle gates with more than 2 qubits"""
seed_1 = 42
cmap5 = FakeTenerife().configuration().coupling_map
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.ccx(qr[1], qr[0], qr[2])
dag = circuit_to_dag(circuit)
pass_1 = VF2Layout(CouplingMap(cmap5), seed=seed_1, max_trials=1)
pass_1.run(dag)
self.assertEqual(
pass_1.property_set["VF2Layout_stop_reason"], VF2LayoutStopReason.MORE_THAN_2Q
)
class TestMultipleTrials(QiskitTestCase):
"""Test the passes behavior with >1 trial."""
def test_no_properties(self):
"""Test it finds the lowest degree perfect layout with no properties."""
vf2_pass = VF2Layout(
CouplingMap(
[
(0, 1),
(0, 2),
(0, 3),
(1, 0),
(1, 2),
(1, 3),
(2, 0),
(2, 1),
(2, 2),
(2, 3),
(3, 0),
(3, 1),
(3, 2),
(4, 0),
(0, 4),
(5, 1),
(1, 5),
]
)
)
qr = QuantumRegister(2)
qc = QuantumCircuit(qr)
qc.x(qr)
qc.measure_all()
property_set = {}
vf2_pass(qc, property_set)
self.assertEqual(set(property_set["layout"].get_physical_bits()), {4, 5})
def test_with_properties(self):
"""Test it finds the least noise perfect layout with no properties."""
backend = FakeYorktown()
qr = QuantumRegister(2)
qc = QuantumCircuit(qr)
qc.x(qr)
qc.measure_all()
cmap = CouplingMap(backend.configuration().coupling_map)
properties = backend.properties()
vf2_pass = VF2Layout(cmap, properties=properties)
property_set = {}
vf2_pass(qc, property_set)
self.assertEqual(set(property_set["layout"].get_physical_bits()), {1, 3})
def test_max_trials_exceeded(self):
"""Test it exits when max_trials is reached."""
backend = FakeYorktown()
qr = QuantumRegister(2)
qc = QuantumCircuit(qr)
qc.x(qr)
qc.cx(0, 1)
qc.measure_all()
cmap = CouplingMap(backend.configuration().coupling_map)
properties = backend.properties()
vf2_pass = VF2Layout(cmap, properties=properties, seed=-1, max_trials=1)
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 1 is >= configured max trials 1",
cm.output,
)
self.assertEqual(set(property_set["layout"].get_physical_bits()), {2, 0})
def test_time_limit_exceeded(self):
"""Test the pass stops after time_limit is reached."""
backend = FakeYorktown()
qr = QuantumRegister(2)
qc = QuantumCircuit(qr)
qc.x(qr)
qc.cx(0, 1)
qc.measure_all()
cmap = CouplingMap(backend.configuration().coupling_map)
properties = backend.properties()
vf2_pass = VF2Layout(cmap, properties=properties, seed=-1, time_limit=0.0)
property_set = {}
with self.assertLogs("qiskit.transpiler.passes.layout.vf2_layout", level="DEBUG") as cm:
vf2_pass(qc, property_set)
for output in cm.output:
if output.startswith(
"DEBUG:qiskit.transpiler.passes.layout.vf2_layout:VF2Layout has taken"
) and output.endswith("which exceeds configured max time: 0.0"):
break
else:
self.fail("No failure debug log message found")
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 = FakeManhattan()
qc = QuantumCircuit(5)
qc.cx(2, 3)
qc.cx(0, 1)
cmap = CouplingMap(backend.configuration().coupling_map)
properties = backend.properties()
# Run without any limits set
vf2_pass = VF2Layout(cmap, properties=properties, 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 159 is >= configured max trials 159",
cm.output,
)
self.assertEqual(set(property_set["layout"].get_physical_bits()), {49, 40, 33, 0, 34})
def test_no_limits_with_negative(self):
"""Test that we're not enforcing a trial limit if set to negative."""
backend = FakeYorktown()
qc = QuantumCircuit(3)
qc.h(0)
cmap = CouplingMap(backend.configuration().coupling_map)
properties = backend.properties()
# Run without any limits set
vf2_pass = VF2Layout(
cmap,
properties=properties,
seed=42,
max_trials=0,
)
property_set = {}
with self.assertLogs("qiskit.transpiler.passes.layout.vf2_layout", level="DEBUG") as cm:
vf2_pass(qc, property_set)
for output in cm.output:
self.assertNotIn("is >= configured max trials", output)
self.assertEqual(set(property_set["layout"].get_physical_bits()), {3, 1, 0})
def test_qregs_valid_layout_output(self):
"""Test that vf2 layout doesn't add extra qubits.
Reproduce from https://github.com/Qiskit/qiskit-terra/issues/8667
"""
backend = FakeGuadalupeV2()
qr = QuantumRegister(16, name="qr")
cr = ClassicalRegister(5)
qc = QuantumCircuit(qr, cr)
qc.rz(pi / 2, qr[0])
qc.sx(qr[0])
qc.sx(qr[1])
qc.rz(-pi / 4, qr[1])
qc.sx(qr[1])
qc.rz(pi / 2, qr[1])
qc.rz(2.8272143, qr[0])
qc.rz(0.43324854, qr[1])
qc.sx(qr[1])
qc.rz(-0.95531662, qr[7])
qc.sx(qr[7])
qc.rz(3 * pi / 4, qr[7])
qc.barrier([qr[1], qr[10], qr[4], qr[0], qr[7]])
vf2_pass = VF2Layout(
seed=12345,
target=backend.target,
)
vf2_pass(qc)
self.assertEqual(len(vf2_pass.property_set["layout"].get_physical_bits()), 16)
self.assertEqual(len(vf2_pass.property_set["layout"].get_virtual_bits()), 16)
pm = PassManager(
[
VF2Layout(
seed=12345,
target=backend.target,
)
]
)
pm += generate_embed_passmanager(backend.coupling_map)
res = pm.run(qc)
self.assertEqual(res.num_qubits, 16)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the VF2Layout pass"""
import rustworkx
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.circuit import ControlFlowOp
from qiskit.circuit.library import CXGate, XGate
from qiskit.transpiler import CouplingMap, Layout, TranspilerError
from qiskit.transpiler.passes.layout.vf2_post_layout import VF2PostLayout, VF2PostLayoutStopReason
from qiskit.converters import circuit_to_dag
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import FakeLima, FakeYorktown, FakeLimaV2, FakeYorktownV2
from qiskit.circuit import Qubit
from qiskit.compiler.transpiler import transpile
from qiskit.transpiler.target import Target, InstructionProperties
class TestVF2PostLayout(QiskitTestCase):
"""Tests the VF2Layout pass"""
seed = 42
def assertLayout(self, dag, coupling_map, property_set):
"""Checks if the circuit in dag was a perfect layout in property_set for the given
coupling_map"""
self.assertEqual(
property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.SOLUTION_FOUND
)
layout = property_set["post_layout"]
edges = coupling_map.graph.edge_list()
def run(dag, wire_map):
for gate in dag.two_qubit_ops():
if dag.has_calibration_for(gate) or isinstance(gate.op, ControlFlowOp):
continue
physical_q0 = wire_map[gate.qargs[0]]
physical_q1 = wire_map[gate.qargs[1]]
self.assertTrue((physical_q0, physical_q1) in edges)
for node in dag.op_nodes(ControlFlowOp):
for block in node.op.blocks:
inner_wire_map = {
inner: wire_map[outer] for outer, inner in zip(node.qargs, block.qubits)
}
run(circuit_to_dag(block), inner_wire_map)
run(dag, {bit: layout[bit] for bit in dag.qubits if bit in layout})
def assertLayoutV2(self, dag, target, property_set):
"""Checks if the circuit in dag was a perfect layout in property_set for the given
coupling_map"""
self.assertEqual(
property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.SOLUTION_FOUND
)
layout = property_set["post_layout"]
def run(dag, wire_map):
for gate in dag.two_qubit_ops():
if dag.has_calibration_for(gate) or isinstance(gate.op, ControlFlowOp):
continue
physical_q0 = wire_map[gate.qargs[0]]
physical_q1 = wire_map[gate.qargs[1]]
qargs = (physical_q0, physical_q1)
self.assertTrue(target.instruction_supported(gate.name, qargs))
for node in dag.op_nodes(ControlFlowOp):
for block in node.op.blocks:
inner_wire_map = {
inner: wire_map[outer] for outer, inner in zip(node.qargs, block.qubits)
}
run(circuit_to_dag(block), inner_wire_map)
run(dag, {bit: layout[bit] for bit in dag.qubits if bit in layout})
def test_no_constraints(self):
"""Test we raise at runtime if no target or coupling graph specified."""
qc = QuantumCircuit(2)
empty_pass = VF2PostLayout()
with self.assertRaises(TranspilerError):
empty_pass.run(circuit_to_dag(qc))
def test_no_backend_properties(self):
"""Test we raise at runtime if no properties are provided with a coupling graph."""
qc = QuantumCircuit(2)
empty_pass = VF2PostLayout(coupling_map=CouplingMap([(0, 1), (1, 2)]))
with self.assertRaises(TranspilerError):
empty_pass.run(circuit_to_dag(qc))
def test_empty_circuit(self):
"""Test no solution found for empty circuit"""
qc = QuantumCircuit(2, 2)
backend = FakeLima()
cmap = CouplingMap(backend.configuration().coupling_map)
props = backend.properties()
vf2_pass = VF2PostLayout(coupling_map=cmap, properties=props)
vf2_pass.run(circuit_to_dag(qc))
self.assertEqual(
vf2_pass.property_set["VF2PostLayout_stop_reason"],
VF2PostLayoutStopReason.NO_SOLUTION_FOUND,
)
def test_empty_circuit_v2(self):
"""Test no solution found for empty circuit with v2 backend"""
qc = QuantumCircuit(2, 2)
backend = FakeLimaV2()
vf2_pass = VF2PostLayout(target=backend.target)
vf2_pass.run(circuit_to_dag(qc))
self.assertEqual(
vf2_pass.property_set["VF2PostLayout_stop_reason"],
VF2PostLayoutStopReason.NO_SOLUTION_FOUND,
)
def test_skip_3q_circuit(self):
"""Test that the pass is a no-op on circuits with >2q gates."""
qc = QuantumCircuit(3)
qc.ccx(0, 1, 2)
backend = FakeLima()
cmap = CouplingMap(backend.configuration().coupling_map)
props = backend.properties()
vf2_pass = VF2PostLayout(coupling_map=cmap, properties=props)
vf2_pass.run(circuit_to_dag(qc))
self.assertEqual(
vf2_pass.property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.MORE_THAN_2Q
)
def test_skip_3q_circuit_control_flow(self):
"""Test that the pass is a no-op on circuits with >2q gates."""
qc = QuantumCircuit(3)
with qc.for_loop((1,)):
qc.ccx(0, 1, 2)
backend = FakeLima()
cmap = CouplingMap(backend.configuration().coupling_map)
props = backend.properties()
vf2_pass = VF2PostLayout(coupling_map=cmap, properties=props)
vf2_pass.run(circuit_to_dag(qc))
self.assertEqual(
vf2_pass.property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.MORE_THAN_2Q
)
def test_skip_3q_circuit_v2(self):
"""Test that the pass is a no-op on circuits with >2q gates with a target."""
qc = QuantumCircuit(3)
qc.ccx(0, 1, 2)
backend = FakeLimaV2()
vf2_pass = VF2PostLayout(target=backend.target)
vf2_pass.run(circuit_to_dag(qc))
self.assertEqual(
vf2_pass.property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.MORE_THAN_2Q
)
def test_skip_3q_circuit_control_flow_v2(self):
"""Test that the pass is a no-op on circuits with >2q gates with a target."""
qc = QuantumCircuit(3)
with qc.for_loop((1,)):
qc.ccx(0, 1, 2)
backend = FakeLimaV2()
vf2_pass = VF2PostLayout(target=backend.target)
vf2_pass.run(circuit_to_dag(qc))
self.assertEqual(
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"""
backend = FakeLima()
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
qr1 - qr0
"""
backend = FakeYorktown()
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.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_controlflow(self):
"""A simple example, without considering the direction
0 - 1
qr1 - qr0
"""
backend = FakeYorktown()
circuit = QuantumCircuit(2, 1)
with circuit.for_loop((1,)):
circuit.cx(1, 0) # qr1 -> qr0
with circuit.if_test((circuit.clbits[0], True)) as else_:
pass
with else_:
with circuit.while_loop((circuit.clbits[0], True)):
circuit.cx(1, 0) # qr1 -> qr0
initial_layout = Layout(dict(enumerate(circuit.qubits)))
circuit._layout = initial_layout
dag = circuit_to_dag(circuit)
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_max_trials(self):
"""A simple example, without considering the direction
0 - 1
qr1 - qr0
"""
max_trials = 11
backend = FakeYorktown()
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.configuration().coupling_map)
props = backend.properties()
pass_ = VF2PostLayout(
coupling_map=cmap, properties=props, 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,
)
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):
"""Test best mappings with multiple registers"""
backend = FakeLimaV2()
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)
pass_ = VF2PostLayout(target=backend.target, seed=self.seed)
pass_.run(dag)
self.assertLayoutV2(dag, backend.target, pass_.property_set)
self.assertNotEqual(pass_.property_set["post_layout"], initial_layout)
def test_2q_circuit_5q_backend_v2(self):
"""A simple example, without considering the direction
0 - 1
qr1 - qr0
"""
backend = FakeYorktownV2()
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)
pass_ = VF2PostLayout(target=backend.target, seed=self.seed)
pass_.run(dag)
self.assertLayoutV2(dag, backend.target, pass_.property_set)
self.assertNotEqual(pass_.property_set["post_layout"], initial_layout)
def test_2q_circuit_5q_backend_v2_control_flow(self):
"""A simple example, without considering the direction
0 - 1
qr1 - qr0
"""
backend = FakeYorktownV2()
circuit = QuantumCircuit(2, 1)
with circuit.for_loop((1,)):
circuit.cx(1, 0) # qr1 -> qr0
with circuit.if_test((circuit.clbits[0], True)) as else_:
pass
with else_:
with circuit.while_loop((circuit.clbits[0], True)):
circuit.cx(1, 0) # qr1 -> qr0
initial_layout = Layout(dict(enumerate(circuit.qubits)))
circuit._layout = initial_layout
dag = circuit_to_dag(circuit)
pass_ = VF2PostLayout(target=backend.target, seed=self.seed)
pass_.run(dag)
self.assertLayoutV2(dag, backend.target, pass_.property_set)
self.assertNotEqual(pass_.property_set["post_layout"], initial_layout)
def test_target_invalid_2q_gate(self):
"""Test that we don't find a solution with a gate outside target."""
backend = FakeYorktownV2()
qc = QuantumCircuit(2)
qc.ecr(0, 1)
dag = circuit_to_dag(qc)
pass_ = VF2PostLayout(target=backend.target, seed=self.seed)
pass_.run(dag)
self.assertEqual(
pass_.property_set["VF2PostLayout_stop_reason"],
VF2PostLayoutStopReason.NO_SOLUTION_FOUND,
)
def test_target_invalid_2q_gate_control_flow(self):
"""Test that we don't find a solution with a gate outside target."""
backend = FakeYorktownV2()
qc = QuantumCircuit(2)
with qc.for_loop((1,)):
qc.ecr(0, 1)
dag = circuit_to_dag(qc)
pass_ = VF2PostLayout(target=backend.target, seed=self.seed)
pass_.run(dag)
self.assertEqual(
pass_.property_set["VF2PostLayout_stop_reason"],
VF2PostLayoutStopReason.NO_SOLUTION_FOUND,
)
def test_target_no_error(self):
"""Test that running vf2layout on a pass against a target with no error rates works."""
n_qubits = 15
target = Target()
target.add_instruction(CXGate(), {(i, i + 1): None for i in range(n_qubits - 1)})
vf2_pass = VF2PostLayout(target=target)
circuit = QuantumCircuit(2)
circuit.cx(0, 1)
dag = circuit_to_dag(circuit)
vf2_pass.run(dag)
self.assertNotIn("post_layout", vf2_pass.property_set)
def test_target_some_error(self):
"""Test that running vf2layout on a pass against a target with some error rates works."""
n_qubits = 15
target = Target()
target.add_instruction(
XGate(), {(i,): InstructionProperties(error=0.00123) for i in range(n_qubits)}
)
target.add_instruction(CXGate(), {(i, i + 1): None for i in range(n_qubits - 1)})
vf2_pass = VF2PostLayout(target=target, seed=1234, strict_direction=False)
circuit = QuantumCircuit(2)
circuit.h(0)
circuit.cx(0, 1)
dag = circuit_to_dag(circuit)
vf2_pass.run(dag)
# No layout selected because nothing will beat initial layout
self.assertNotIn("post_layout", vf2_pass.property_set)
class TestVF2PostLayoutScoring(QiskitTestCase):
"""Test scoring heuristic function for VF2PostLayout."""
def test_empty_score(self):
"""Test error rate is 0 for empty circuit."""
bit_map = {}
reverse_bit_map = {}
im_graph = rustworkx.PyDiGraph()
backend = FakeYorktownV2()
vf2_pass = VF2PostLayout(target=backend.target)
layout = Layout()
score = vf2_pass._score_layout(layout, bit_map, reverse_bit_map, im_graph)
self.assertEqual(0, score)
def test_all_1q_score(self):
"""Test error rate for all 1q input."""
bit_map = {Qubit(): 0, Qubit(): 1}
reverse_bit_map = {v: k for k, v in bit_map.items()}
im_graph = rustworkx.PyDiGraph()
im_graph.add_node({"sx": 1})
im_graph.add_node({"sx": 1})
backend = FakeYorktownV2()
vf2_pass = VF2PostLayout(target=backend.target)
layout = Layout(bit_map)
score = vf2_pass._score_layout(layout, bit_map, reverse_bit_map, im_graph)
self.assertAlmostEqual(0.002925, score, places=5)
class TestVF2PostLayoutUndirected(QiskitTestCase):
"""Tests the VF2Layout pass"""
seed = 42
def assertLayout(self, dag, coupling_map, property_set):
"""Checks if the circuit in dag was a perfect layout in property_set for the given
coupling_map"""
self.assertEqual(
property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.SOLUTION_FOUND
)
layout = property_set["post_layout"]
for gate in dag.two_qubit_ops():
if dag.has_calibration_for(gate):
continue
physical_q0 = layout[gate.qargs[0]]
physical_q1 = layout[gate.qargs[1]]
self.assertTrue(coupling_map.graph.has_edge(physical_q0, physical_q1))
def assertLayoutV2(self, dag, target, property_set):
"""Checks if the circuit in dag was a perfect layout in property_set for the given
coupling_map"""
self.assertEqual(
property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.SOLUTION_FOUND
)
layout = property_set["post_layout"]
for gate in dag.two_qubit_ops():
if dag.has_calibration_for(gate):
continue
physical_q0 = layout[gate.qargs[0]]
physical_q1 = layout[gate.qargs[1]]
qargs = (physical_q0, physical_q1)
self.assertTrue(target.instruction_supported(gate.name, qargs))
def test_no_constraints(self):
"""Test we raise at runtime if no target or coupling graph specified."""
qc = QuantumCircuit(2)
empty_pass = VF2PostLayout(strict_direction=False)
with self.assertRaises(TranspilerError):
empty_pass.run(circuit_to_dag(qc))
def test_no_backend_properties(self):
"""Test we raise at runtime if no properties are provided with a coupling graph."""
qc = QuantumCircuit(2)
empty_pass = VF2PostLayout(
coupling_map=CouplingMap([(0, 1), (1, 2)]), strict_direction=False
)
with self.assertRaises(TranspilerError):
empty_pass.run(circuit_to_dag(qc))
def test_empty_circuit(self):
"""Test no solution found for empty circuit"""
qc = QuantumCircuit(2, 2)
backend = FakeLima()
cmap = CouplingMap(backend.configuration().coupling_map)
props = backend.properties()
vf2_pass = VF2PostLayout(coupling_map=cmap, properties=props, strict_direction=False)
vf2_pass.run(circuit_to_dag(qc))
self.assertEqual(
vf2_pass.property_set["VF2PostLayout_stop_reason"],
VF2PostLayoutStopReason.NO_SOLUTION_FOUND,
)
def test_empty_circuit_v2(self):
"""Test no solution found for empty circuit with v2 backend"""
qc = QuantumCircuit(2, 2)
backend = FakeLimaV2()
vf2_pass = VF2PostLayout(target=backend.target, strict_direction=False)
vf2_pass.run(circuit_to_dag(qc))
self.assertEqual(
vf2_pass.property_set["VF2PostLayout_stop_reason"],
VF2PostLayoutStopReason.NO_SOLUTION_FOUND,
)
def test_skip_3q_circuit(self):
"""Test that the pass is a no-op on circuits with >2q gates."""
qc = QuantumCircuit(3)
qc.ccx(0, 1, 2)
backend = FakeLima()
cmap = CouplingMap(backend.configuration().coupling_map)
props = backend.properties()
vf2_pass = VF2PostLayout(coupling_map=cmap, properties=props, strict_direction=False)
vf2_pass.run(circuit_to_dag(qc))
self.assertEqual(
vf2_pass.property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.MORE_THAN_2Q
)
def test_skip_3q_circuit_v2(self):
"""Test that the pass is a no-op on circuits with >2q gates with a target."""
qc = QuantumCircuit(3)
qc.ccx(0, 1, 2)
backend = FakeLimaV2()
vf2_pass = VF2PostLayout(target=backend.target, strict_direction=False)
vf2_pass.run(circuit_to_dag(qc))
self.assertEqual(
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"""
backend = FakeLima()
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, 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(self):
"""A simple example, without considering the direction
0 - 1
qr1 - qr0
"""
backend = FakeYorktown()
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.configuration().coupling_map)
props = backend.properties()
pass_ = VF2PostLayout(
coupling_map=cmap, properties=props, 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_v2(self):
"""Test best mappings with multiple registers"""
backend = FakeLimaV2()
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)
pass_ = VF2PostLayout(target=backend.target, seed=self.seed, strict_direction=False)
pass_.run(dag)
self.assertLayoutV2(dag, backend.target, pass_.property_set)
self.assertNotEqual(pass_.property_set["post_layout"], initial_layout)
def test_2q_circuit_5q_backend_v2(self):
"""A simple example, without considering the direction
0 - 1
qr1 - qr0
"""
backend = FakeYorktownV2()
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)
pass_ = VF2PostLayout(target=backend.target, seed=self.seed, strict_direction=False)
pass_.run(dag)
self.assertLayoutV2(dag, backend.target, pass_.property_set)
self.assertNotEqual(pass_.property_set["post_layout"], initial_layout)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Width pass testing"""
import unittest
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.converters import circuit_to_dag
from qiskit.transpiler.passes import Width
from qiskit.test import QiskitTestCase
class TestWidthPass(QiskitTestCase):
"""Tests for Depth analysis methods."""
def test_empty_dag(self):
"""Empty DAG has 0 depth"""
circuit = QuantumCircuit()
dag = circuit_to_dag(circuit)
pass_ = Width()
_ = pass_.run(dag)
self.assertEqual(pass_.property_set["width"], 0)
def test_just_qubits(self):
"""A dag with 8 operations and no classic bits"""
qr = QuantumRegister(2)
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[0])
circuit.cx(qr[1], qr[0])
dag = circuit_to_dag(circuit)
pass_ = Width()
_ = pass_.run(dag)
self.assertEqual(pass_.property_set["width"], 2)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Tests AQC plugin.
"""
import numpy as np
from qiskit import QuantumCircuit
from qiskit.algorithms.optimizers import SLSQP
from qiskit.converters import dag_to_circuit, circuit_to_dag
from qiskit.quantum_info import Operator
from qiskit.test import QiskitTestCase
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import UnitarySynthesis
from qiskit.transpiler.synthesis.aqc.aqc_plugin import AQCSynthesisPlugin
class TestAQCSynthesisPlugin(QiskitTestCase):
"""Basic tests of the AQC synthesis plugin."""
def setUp(self):
super().setUp()
self._qc = QuantumCircuit(3)
self._qc.mcx(
[
0,
1,
],
2,
)
self._target_unitary = Operator(self._qc).data
self._seed_config = {"seed": 12345}
def test_aqc_plugin(self):
"""Basic test of the plugin."""
plugin = AQCSynthesisPlugin()
dag = plugin.run(self._target_unitary, config=self._seed_config)
approx_circuit = dag_to_circuit(dag)
approx_unitary = Operator(approx_circuit).data
np.testing.assert_array_almost_equal(self._target_unitary, approx_unitary, 3)
def test_plugin_setup(self):
"""Tests the plugin via unitary synthesis pass"""
transpiler_pass = UnitarySynthesis(
basis_gates=["rx", "ry", "rz", "cx"], method="aqc", plugin_config=self._seed_config
)
dag = circuit_to_dag(self._qc)
dag = transpiler_pass.run(dag)
approx_circuit = dag_to_circuit(dag)
approx_unitary = Operator(approx_circuit).data
np.testing.assert_array_almost_equal(self._target_unitary, approx_unitary, 3)
def test_plugin_configuration(self):
"""Tests plugin with a custom configuration."""
config = {
"network_layout": "sequ",
"connectivity_type": "full",
"depth": 0,
"seed": 12345,
"optimizer": SLSQP(),
}
transpiler_pass = UnitarySynthesis(
basis_gates=["rx", "ry", "rz", "cx"], method="aqc", plugin_config=config
)
dag = circuit_to_dag(self._qc)
dag = transpiler_pass.run(dag)
approx_circuit = dag_to_circuit(dag)
approx_unitary = Operator(approx_circuit).data
np.testing.assert_array_almost_equal(self._target_unitary, approx_unitary, 3)
def test_with_pass_manager(self):
"""Tests the plugin via pass manager"""
qc = QuantumCircuit(3)
qc.unitary(np.eye(8), [0, 1, 2])
aqc = PassManager(
[
UnitarySynthesis(
basis_gates=["u", "cx"], method="aqc", plugin_config=self._seed_config
)
]
).run(qc)
approx_unitary = Operator(aqc).data
np.testing.assert_array_almost_equal(np.eye(8), approx_unitary, 3)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Tests for Layer1Q implementation.
"""
import unittest
from random import randint
import test.python.transpiler.aqc.fast_gradient.utils_for_testing as tut
import numpy as np
import qiskit.transpiler.synthesis.aqc.fast_gradient.layer as lr
from qiskit.transpiler.synthesis.aqc.fast_gradient.pmatrix import PMatrix
from qiskit.test import QiskitTestCase
class TestLayer1q(QiskitTestCase):
"""
Tests for Layer1Q class.
"""
max_num_qubits = 5 # maximum number of qubits in tests
num_repeats = 50 # number of repetitions in tests
def setUp(self):
super().setUp()
np.random.seed(0x0696969)
def test_layer1q_matrix(self):
"""
Tests: (1) the correctness of Layer2Q matrix construction;
(2) matrix multiplication interleaved with permutations.
"""
mat_kind = "complex"
eps = 100.0 * np.finfo(float).eps
max_rel_err = 0.0
for n in range(2, self.max_num_qubits + 1):
dim = 2**n
iden = tut.eye_int(n)
for k in range(n):
m_mat = tut.rand_matrix(dim=dim, kind=mat_kind)
t_mat, g_mat = tut.make_test_matrices2x2(n=n, k=k, kind=mat_kind)
lmat = lr.Layer1Q(num_qubits=n, k=k, g2x2=g_mat)
g2, perm, inv_perm = lmat.get_attr()
self.assertTrue(m_mat.dtype == t_mat.dtype == g_mat.dtype == g2.dtype)
self.assertTrue(np.all(g_mat == g2))
self.assertTrue(np.all(iden[perm].T == iden[inv_perm]))
g_mat = np.kron(tut.eye_int(n - 1), g_mat)
# T == P^t @ G @ P.
err = tut.relative_error(t_mat, iden[perm].T @ g_mat @ iden[perm])
self.assertLess(err, eps, "err = {:0.16f}".format(err))
max_rel_err = max(max_rel_err, err)
# Multiplication by permutation matrix of the left can be
# replaced by row permutations.
tm = t_mat @ m_mat
err1 = tut.relative_error(iden[perm].T @ g_mat @ m_mat[perm], tm)
err2 = tut.relative_error((g_mat @ m_mat[perm])[inv_perm], tm)
# Multiplication by permutation matrix of the right can be
# replaced by column permutations.
mt = m_mat @ t_mat
err3 = tut.relative_error(m_mat @ iden[perm].T @ g_mat @ iden[perm], mt)
err4 = tut.relative_error((m_mat[:, perm] @ g_mat)[:, inv_perm], mt)
self.assertTrue(
err1 < eps and err2 < eps and err3 < eps and err4 < eps,
"err1 = {:f}, err2 = {:f}, "
"err3 = {:f}, err4 = {:f}".format(err1, err2, err3, err4),
)
max_rel_err = max(max_rel_err, err1, err2, err3, err4)
def test_pmatrix_class(self):
"""
Test the class PMatrix.
"""
_eps = 100.0 * np.finfo(float).eps
mat_kind = "complex"
max_rel_err = 0.0
for n in range(2, self.max_num_qubits + 1):
dim = 2**n
tmp1 = np.ndarray((dim, dim), dtype=np.cfloat)
tmp2 = tmp1.copy()
for _ in range(self.num_repeats):
k0 = randint(0, n - 1)
k1 = randint(0, n - 1)
k2 = randint(0, n - 1)
k3 = randint(0, n - 1)
k4 = randint(0, n - 1)
t0, g0 = tut.make_test_matrices2x2(n=n, k=k0, kind=mat_kind)
t1, g1 = tut.make_test_matrices2x2(n=n, k=k1, kind=mat_kind)
t2, g2 = tut.make_test_matrices2x2(n=n, k=k2, kind=mat_kind)
t3, g3 = tut.make_test_matrices2x2(n=n, k=k3, kind=mat_kind)
t4, g4 = tut.make_test_matrices2x2(n=n, k=k4, kind=mat_kind)
c0 = lr.Layer1Q(num_qubits=n, k=k0, g2x2=g0)
c1 = lr.Layer1Q(num_qubits=n, k=k1, g2x2=g1)
c2 = lr.Layer1Q(num_qubits=n, k=k2, g2x2=g2)
c3 = lr.Layer1Q(num_qubits=n, k=k3, g2x2=g3)
c4 = lr.Layer1Q(num_qubits=n, k=k4, g2x2=g4)
m_mat = tut.rand_matrix(dim=dim, kind=mat_kind)
ttmtt = t0 @ t1 @ m_mat @ np.conj(t2).T @ np.conj(t3).T
pmat = PMatrix(n)
pmat.set_matrix(m_mat)
pmat.mul_left_q1(layer=c1, temp_mat=tmp1)
pmat.mul_left_q1(layer=c0, temp_mat=tmp1)
pmat.mul_right_q1(layer=c2, temp_mat=tmp1, dagger=True)
pmat.mul_right_q1(layer=c3, temp_mat=tmp1, dagger=True)
alt_ttmtt = pmat.finalize(temp_mat=tmp1)
err1 = tut.relative_error(alt_ttmtt, ttmtt)
self.assertLess(err1, _eps, "relative error: {:f}".format(err1))
prod = np.cfloat(np.trace(ttmtt @ t4))
alt_prod = pmat.product_q1(layer=c4, tmp1=tmp1, tmp2=tmp2)
err2 = abs(alt_prod - prod) / abs(prod)
self.assertLess(err2, _eps, "relative error: {:f}".format(err2))
max_rel_err = max(max_rel_err, err1, err2)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Tests for Layer2Q implementation.
"""
import unittest
from random import randint
import test.python.transpiler.aqc.fast_gradient.utils_for_testing as tut
import numpy as np
import qiskit.transpiler.synthesis.aqc.fast_gradient.layer as lr
from qiskit.transpiler.synthesis.aqc.fast_gradient.pmatrix import PMatrix
from qiskit.test import QiskitTestCase
class TestLayer2q(QiskitTestCase):
"""
Tests for Layer2Q class.
"""
max_num_qubits = 5 # maximum number of qubits in tests
num_repeats = 50 # number of repetitions in tests
def setUp(self):
super().setUp()
np.random.seed(0x0696969)
def test_layer2q_matrix(self):
"""
Tests: (1) the correctness of Layer2Q matrix construction;
(2) matrix multiplication interleaved with permutations.
"""
mat_kind = "complex"
_eps = 100.0 * np.finfo(float).eps
max_rel_err = 0.0
for n in range(2, self.max_num_qubits + 1):
dim = 2**n
iden = tut.eye_int(n)
for j in range(n):
for k in range(n):
if j == k:
continue
m_mat = tut.rand_matrix(dim=dim, kind=mat_kind)
t_mat, g_mat = tut.make_test_matrices4x4(n=n, j=j, k=k, kind=mat_kind)
lmat = lr.Layer2Q(num_qubits=n, j=j, k=k, g4x4=g_mat)
g2, perm, inv_perm = lmat.get_attr()
self.assertTrue(m_mat.dtype == t_mat.dtype == g_mat.dtype == g2.dtype)
self.assertTrue(np.all(g_mat == g2))
self.assertTrue(np.all(iden[perm].T == iden[inv_perm]))
g_mat = np.kron(tut.eye_int(n - 2), g_mat)
# T == P^t @ G @ P.
err = tut.relative_error(t_mat, iden[perm].T @ g_mat @ iden[perm])
self.assertLess(err, _eps, "err = {:0.16f}".format(err))
max_rel_err = max(max_rel_err, err)
# Multiplication by permutation matrix of the left can be
# replaced by row permutations.
tm = t_mat @ m_mat
err1 = tut.relative_error(iden[perm].T @ g_mat @ m_mat[perm], tm)
err2 = tut.relative_error((g_mat @ m_mat[perm])[inv_perm], tm)
# Multiplication by permutation matrix of the right can be
# replaced by column permutations.
mt = m_mat @ t_mat
err3 = tut.relative_error(m_mat @ iden[perm].T @ g_mat @ iden[perm], mt)
err4 = tut.relative_error((m_mat[:, perm] @ g_mat)[:, inv_perm], mt)
self.assertTrue(
err1 < _eps and err2 < _eps and err3 < _eps and err4 < _eps,
"err1 = {:f}, err2 = {:f}, "
"err3 = {:f}, err4 = {:f}".format(err1, err2, err3, err4),
)
max_rel_err = max(max_rel_err, err1, err2, err3, err4)
def test_pmatrix_class(self):
"""
Test the class PMatrix.
"""
_eps = 100.0 * np.finfo(float).eps
mat_kind = "complex"
max_rel_err = 0.0
for n in range(2, self.max_num_qubits + 1):
dim = 2**n
tmp1 = np.ndarray((dim, dim), dtype=np.cfloat)
tmp2 = tmp1.copy()
for _ in range(self.num_repeats):
j0 = randint(0, n - 1)
k0 = (j0 + randint(1, n - 1)) % n
j1 = randint(0, n - 1)
k1 = (j1 + randint(1, n - 1)) % n
j2 = randint(0, n - 1)
k2 = (j2 + randint(1, n - 1)) % n
j3 = randint(0, n - 1)
k3 = (j3 + randint(1, n - 1)) % n
j4 = randint(0, n - 1)
k4 = (j4 + randint(1, n - 1)) % n
t0, g0 = tut.make_test_matrices4x4(n=n, j=j0, k=k0, kind=mat_kind)
t1, g1 = tut.make_test_matrices4x4(n=n, j=j1, k=k1, kind=mat_kind)
t2, g2 = tut.make_test_matrices4x4(n=n, j=j2, k=k2, kind=mat_kind)
t3, g3 = tut.make_test_matrices4x4(n=n, j=j3, k=k3, kind=mat_kind)
t4, g4 = tut.make_test_matrices4x4(n=n, j=j4, k=k4, kind=mat_kind)
c0 = lr.Layer2Q(num_qubits=n, j=j0, k=k0, g4x4=g0)
c1 = lr.Layer2Q(num_qubits=n, j=j1, k=k1, g4x4=g1)
c2 = lr.Layer2Q(num_qubits=n, j=j2, k=k2, g4x4=g2)
c3 = lr.Layer2Q(num_qubits=n, j=j3, k=k3, g4x4=g3)
c4 = lr.Layer2Q(num_qubits=n, j=j4, k=k4, g4x4=g4)
m_mat = tut.rand_matrix(dim=dim, kind=mat_kind)
ttmtt = t0 @ t1 @ m_mat @ np.conj(t2).T @ np.conj(t3).T
pmat = PMatrix(n)
pmat.set_matrix(m_mat)
pmat.mul_left_q2(layer=c1, temp_mat=tmp1)
pmat.mul_left_q2(layer=c0, temp_mat=tmp1)
pmat.mul_right_q2(layer=c2, temp_mat=tmp1)
pmat.mul_right_q2(layer=c3, temp_mat=tmp1)
alt_ttmtt = pmat.finalize(temp_mat=tmp1)
err1 = tut.relative_error(alt_ttmtt, ttmtt)
self.assertLess(err1, _eps, "relative error: {:f}".format(err1))
prod = np.cfloat(np.trace(ttmtt @ t4))
alt_prod = pmat.product_q2(layer=c4, tmp1=tmp1, tmp2=tmp2)
err2 = abs(alt_prod - prod) / abs(prod)
self.assertLess(err2, _eps, "relative error: {:f}".format(err2))
max_rel_err = max(max_rel_err, err1, err2)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for visualization tools."""
import unittest
import numpy as np
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.circuit import Qubit, Clbit
from qiskit.visualization.circuit import _utils
from qiskit.visualization import array_to_latex
from qiskit.test import QiskitTestCase
from qiskit.utils import optionals
class TestVisualizationUtils(QiskitTestCase):
"""Tests for circuit drawer utilities."""
def setUp(self):
super().setUp()
self.qr1 = QuantumRegister(2, "qr1")
self.qr2 = QuantumRegister(2, "qr2")
self.cr1 = ClassicalRegister(2, "cr1")
self.cr2 = ClassicalRegister(2, "cr2")
self.circuit = QuantumCircuit(self.qr1, self.qr2, self.cr1, self.cr2)
self.circuit.cx(self.qr2[0], self.qr2[1])
self.circuit.measure(self.qr2[0], self.cr2[0])
self.circuit.cx(self.qr2[1], self.qr2[0])
self.circuit.measure(self.qr2[1], self.cr2[1])
self.circuit.cx(self.qr1[0], self.qr1[1])
self.circuit.measure(self.qr1[0], self.cr1[0])
self.circuit.cx(self.qr1[1], self.qr1[0])
self.circuit.measure(self.qr1[1], self.cr1[1])
def test_get_layered_instructions(self):
"""_get_layered_instructions without reverse_bits"""
(qregs, cregs, layered_ops) = _utils._get_layered_instructions(self.circuit)
exp = [
[("cx", (self.qr2[0], self.qr2[1]), ()), ("cx", (self.qr1[0], self.qr1[1]), ())],
[("measure", (self.qr2[0],), (self.cr2[0],))],
[("measure", (self.qr1[0],), (self.cr1[0],))],
[("cx", (self.qr2[1], self.qr2[0]), ()), ("cx", (self.qr1[1], self.qr1[0]), ())],
[("measure", (self.qr2[1],), (self.cr2[1],))],
[("measure", (self.qr1[1],), (self.cr1[1],))],
]
self.assertEqual([self.qr1[0], self.qr1[1], self.qr2[0], self.qr2[1]], qregs)
self.assertEqual([self.cr1[0], self.cr1[1], self.cr2[0], self.cr2[1]], cregs)
self.assertEqual(
exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops]
)
def test_get_layered_instructions_reverse_bits(self):
"""_get_layered_instructions with reverse_bits=True"""
(qregs, cregs, layered_ops) = _utils._get_layered_instructions(
self.circuit, reverse_bits=True
)
exp = [
[("cx", (self.qr2[0], self.qr2[1]), ()), ("cx", (self.qr1[0], self.qr1[1]), ())],
[("measure", (self.qr2[0],), (self.cr2[0],))],
[("measure", (self.qr1[0],), (self.cr1[0],)), ("cx", (self.qr2[1], self.qr2[0]), ())],
[("cx", (self.qr1[1], self.qr1[0]), ())],
[("measure", (self.qr2[1],), (self.cr2[1],))],
[("measure", (self.qr1[1],), (self.cr1[1],))],
]
self.assertEqual([self.qr2[1], self.qr2[0], self.qr1[1], self.qr1[0]], qregs)
self.assertEqual([self.cr2[1], self.cr2[0], self.cr1[1], self.cr1[0]], cregs)
self.assertEqual(
exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops]
)
def test_get_layered_instructions_remove_idle_wires(self):
"""_get_layered_instructions with idle_wires=False"""
qr1 = QuantumRegister(3, "qr1")
qr2 = QuantumRegister(3, "qr2")
cr1 = ClassicalRegister(3, "cr1")
cr2 = ClassicalRegister(3, "cr2")
circuit = QuantumCircuit(qr1, qr2, cr1, cr2)
circuit.cx(qr2[0], qr2[1])
circuit.measure(qr2[0], cr2[0])
circuit.cx(qr2[1], qr2[0])
circuit.measure(qr2[1], cr2[1])
circuit.cx(qr1[0], qr1[1])
circuit.measure(qr1[0], cr1[0])
circuit.cx(qr1[1], qr1[0])
circuit.measure(qr1[1], cr1[1])
(qregs, cregs, layered_ops) = _utils._get_layered_instructions(circuit, idle_wires=False)
exp = [
[("cx", (qr2[0], qr2[1]), ()), ("cx", (qr1[0], qr1[1]), ())],
[("measure", (qr2[0],), (cr2[0],))],
[("measure", (qr1[0],), (cr1[0],))],
[("cx", (qr2[1], qr2[0]), ()), ("cx", (qr1[1], qr1[0]), ())],
[("measure", (qr2[1],), (cr2[1],))],
[("measure", (qr1[1],), (cr1[1],))],
]
self.assertEqual([qr1[0], qr1[1], qr2[0], qr2[1]], qregs)
self.assertEqual([cr1[0], cr1[1], cr2[0], cr2[1]], cregs)
self.assertEqual(
exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops]
)
def test_get_layered_instructions_left_justification_simple(self):
"""Test _get_layered_instructions left justification simple since #2802
q_0: |0>───────■──
┌───┐ │
q_1: |0>┤ H ├──┼──
├───┤ │
q_2: |0>┤ H ├──┼──
└───┘┌─┴─┐
q_3: |0>─────┤ X ├
└───┘
"""
qc = QuantumCircuit(4)
qc.h(1)
qc.h(2)
qc.cx(0, 3)
(_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="left")
l_exp = [
[
("h", (Qubit(QuantumRegister(4, "q"), 1),), ()),
("h", (Qubit(QuantumRegister(4, "q"), 2),), ()),
],
[("cx", (Qubit(QuantumRegister(4, "q"), 0), Qubit(QuantumRegister(4, "q"), 3)), ())],
]
self.assertEqual(
l_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops]
)
def test_get_layered_instructions_right_justification_simple(self):
"""Test _get_layered_instructions right justification simple since #2802
q_0: |0>──■───────
│ ┌───┐
q_1: |0>──┼──┤ H ├
│ ├───┤
q_2: |0>──┼──┤ H ├
┌─┴─┐└───┘
q_3: |0>┤ X ├─────
└───┘
"""
qc = QuantumCircuit(4)
qc.h(1)
qc.h(2)
qc.cx(0, 3)
(_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="right")
r_exp = [
[("cx", (Qubit(QuantumRegister(4, "q"), 0), Qubit(QuantumRegister(4, "q"), 3)), ())],
[
("h", (Qubit(QuantumRegister(4, "q"), 1),), ()),
("h", (Qubit(QuantumRegister(4, "q"), 2),), ()),
],
]
self.assertEqual(
r_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops]
)
def test_get_layered_instructions_left_justification_less_simple(self):
"""Test _get_layered_instructions left justification
less simple example since #2802
┌────────────┐┌───┐┌────────────┐ ┌─┐┌────────────┐┌───┐┌────────────┐
q_0: |0>┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├──────────────┤M├┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├
├────────────┤└─┬─┘├────────────┤┌────────────┐└╥┘└────────────┘└─┬─┘├────────────┤
q_1: |0>┤ U2(0,pi/1) ├──■──┤ U2(0,pi/1) ├┤ U2(0,pi/1) ├─╫─────────────────■──┤ U2(0,pi/1) ├
└────────────┘ └────────────┘└────────────┘ ║ └────────────┘
q_2: |0>────────────────────────────────────────────────╫──────────────────────────────────
║
q_3: |0>────────────────────────────────────────────────╫──────────────────────────────────
║
q_4: |0>────────────────────────────────────────────────╫──────────────────────────────────
║
c1_0: 0 ════════════════════════════════════════════════╩══════════════════════════════════
"""
qasm = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[5];
creg c1[1];
u2(0,3.14159265358979) q[0];
u2(0,3.14159265358979) q[1];
cx q[1],q[0];
u2(0,3.14159265358979) q[0];
u2(0,3.14159265358979) q[1];
u2(0,3.14159265358979) q[1];
measure q[0] -> c1[0];
u2(0,3.14159265358979) q[0];
cx q[1],q[0];
u2(0,3.14159265358979) q[0];
u2(0,3.14159265358979) q[1];
"""
qc = QuantumCircuit.from_qasm_str(qasm)
(_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="left")
l_exp = [
[
("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()),
("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()),
],
[("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())],
[
("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()),
("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()),
],
[("u2", (Qubit(QuantumRegister(5, "q"), 1),), ())],
[
(
"measure",
(Qubit(QuantumRegister(5, "q"), 0),),
(Clbit(ClassicalRegister(1, "c1"), 0),),
)
],
[("u2", (Qubit(QuantumRegister(5, "q"), 0),), ())],
[("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())],
[
("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()),
("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()),
],
]
self.assertEqual(
l_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops]
)
def test_get_layered_instructions_right_justification_less_simple(self):
"""Test _get_layered_instructions right justification
less simple example since #2802
┌────────────┐┌───┐┌────────────┐┌─┐┌────────────┐┌───┐┌────────────┐
q_0: |0>┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├┤M├┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├
├────────────┤└─┬─┘├────────────┤└╥┘├────────────┤└─┬─┘├────────────┤
q_1: |0>┤ U2(0,pi/1) ├──■──┤ U2(0,pi/1) ├─╫─┤ U2(0,pi/1) ├──■──┤ U2(0,pi/1) ├
└────────────┘ └────────────┘ ║ └────────────┘ └────────────┘
q_2: |0>──────────────────────────────────╫──────────────────────────────────
║
q_3: |0>──────────────────────────────────╫──────────────────────────────────
║
q_4: |0>──────────────────────────────────╫──────────────────────────────────
║
c1_0: 0 ══════════════════════════════════╩══════════════════════════════════
"""
qasm = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[5];
creg c1[1];
u2(0,3.14159265358979) q[0];
u2(0,3.14159265358979) q[1];
cx q[1],q[0];
u2(0,3.14159265358979) q[0];
u2(0,3.14159265358979) q[1];
u2(0,3.14159265358979) q[1];
measure q[0] -> c1[0];
u2(0,3.14159265358979) q[0];
cx q[1],q[0];
u2(0,3.14159265358979) q[0];
u2(0,3.14159265358979) q[1];
"""
qc = QuantumCircuit.from_qasm_str(qasm)
(_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="right")
r_exp = [
[
("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()),
("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()),
],
[("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())],
[
("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()),
("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()),
],
[
(
"measure",
(Qubit(QuantumRegister(5, "q"), 0),),
(Clbit(ClassicalRegister(1, "c1"), 0),),
)
],
[
("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()),
("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()),
],
[("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())],
[
("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()),
("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()),
],
]
self.assertEqual(
r_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops]
)
def test_get_layered_instructions_op_with_cargs(self):
"""Test _get_layered_instructions op with cargs right of measure
┌───┐┌─┐
q_0: |0>┤ H ├┤M├─────────────
└───┘└╥┘┌───────────┐
q_1: |0>──────╫─┤0 ├
║ │ add_circ │
c_0: 0 ══════╩═╡0 ╞
└───────────┘
c_1: 0 ═════════════════════
"""
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.measure(0, 0)
qc_2 = QuantumCircuit(1, 1, name="add_circ")
qc_2.h(0).c_if(qc_2.cregs[0], 1)
qc_2.measure(0, 0)
qc.append(qc_2, [1], [0])
(_, _, layered_ops) = _utils._get_layered_instructions(qc)
expected = [
[("h", (Qubit(QuantumRegister(2, "q"), 0),), ())],
[
(
"measure",
(Qubit(QuantumRegister(2, "q"), 0),),
(Clbit(ClassicalRegister(2, "c"), 0),),
)
],
[
(
"add_circ",
(Qubit(QuantumRegister(2, "q"), 1),),
(Clbit(ClassicalRegister(2, "c"), 0),),
)
],
]
self.assertEqual(
expected, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops]
)
@unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc")
def test_generate_latex_label_nomathmode(self):
"""Test generate latex label default."""
self.assertEqual("abc", _utils.generate_latex_label("abc"))
@unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc")
def test_generate_latex_label_nomathmode_utf8char(self):
"""Test generate latex label utf8 characters."""
self.assertEqual(
"{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y",
_utils.generate_latex_label("∭X∀Y"),
)
@unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc")
def test_generate_latex_label_mathmode_utf8char(self):
"""Test generate latex label mathtext with utf8."""
self.assertEqual(
"abc_{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y",
_utils.generate_latex_label("$abc_$∭X∀Y"),
)
@unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc")
def test_generate_latex_label_mathmode_underscore_outside(self):
"""Test generate latex label with underscore outside mathmode."""
self.assertEqual(
"abc_{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y",
_utils.generate_latex_label("$abc$_∭X∀Y"),
)
@unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc")
def test_generate_latex_label_escaped_dollar_signs(self):
"""Test generate latex label with escaped dollarsign."""
self.assertEqual("${\\ensuremath{\\forall}}$", _utils.generate_latex_label(r"\$∀\$"))
@unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc")
def test_generate_latex_label_escaped_dollar_sign_in_mathmode(self):
"""Test generate latex label with escaped dollar sign in mathmode."""
self.assertEqual(
"a$bc_{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y",
_utils.generate_latex_label(r"$a$bc$_∭X∀Y"),
)
def test_array_to_latex(self):
"""Test array_to_latex produces correct latex string"""
matrix = [
[np.sqrt(1 / 2), 1 / 16, 1 / np.sqrt(8) + 3j, -0.5 + 0.5j],
[1 / 3 - 1 / 3j, np.sqrt(1 / 2) * 1j, 34.3210, -9 / 2],
]
matrix = np.array(matrix)
exp_str = (
"\\begin{bmatrix}\\frac{\\sqrt{2}}{2}&\\frac{1}{16}&"
"\\frac{\\sqrt{2}}{4}+3i&-\\frac{1}{2}+\\frac{i}{2}\\\\"
"\\frac{1}{3}+\\frac{i}{3}&\\frac{\\sqrt{2}i}{2}&34.321&-"
"\\frac{9}{2}\\\\\\end{bmatrix}"
)
result = array_to_latex(matrix, source=True).replace(" ", "").replace("\n", "")
self.assertEqual(exp_str, result)
if __name__ == "__main__":
unittest.main(verbosity=2)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Utility functions for debugging and testing.
"""
from typing import Tuple
import numpy as np
from scipy.stats import unitary_group
import qiskit.transpiler.synthesis.aqc.fast_gradient.fast_grad_utils as fgu
def relative_error(a_mat: np.ndarray, b_mat: np.ndarray) -> float:
"""
Computes relative residual between two matrices in Frobenius norm.
"""
return float(np.linalg.norm(a_mat - b_mat, "fro")) / float(np.linalg.norm(b_mat, "fro"))
def make_unit_vector(pos: int, nbits: int) -> np.ndarray:
"""
Makes a unit vector ``e = (0 ... 0 1 0 ... 0)`` of size ``2^n`` with
unit at the position ``num``. **Note**: result depends on bit ordering.
Args:
pos: position of unit in vector.
nbits: number of meaningful bit in the number "pos".
Returns:
unit vector of size ``2^n``.
"""
vec = np.zeros((2**nbits,), dtype=np.int64)
vec[fgu.reverse_bits(pos, nbits, enable=True)] = 1
return vec
def eye_int(n: int) -> np.ndarray:
"""
Creates an identity matrix with integer entries.
Args:
n: number of bits.
Returns:
unit matrix of size ``2^n`` with integer entries.
"""
return np.eye(2**n, dtype=np.int64)
def kron3(a_mat: np.ndarray, b_mat: np.ndarray, c_mat: np.ndarray) -> np.ndarray:
"""
Computes Kronecker product of 3 matrices.
"""
return np.kron(a_mat, np.kron(b_mat, c_mat))
def kron5(
a_mat: np.ndarray, b_mat: np.ndarray, c_mat: np.ndarray, d_mat: np.ndarray, e_mat: np.ndarray
) -> np.ndarray:
"""
Computes Kronecker product of 5 matrices.
"""
return np.kron(np.kron(np.kron(np.kron(a_mat, b_mat), c_mat), d_mat), e_mat)
def rand_matrix(dim: int, kind: str = "complex") -> np.ndarray:
"""
Generates a random complex or integer value matrix.
Args:
dim: matrix size dim-x-dim.
kind: "complex" or "randint".
Returns:
a random matrix.
"""
if kind == "complex":
return (
np.random.rand(dim, dim).astype(np.cfloat)
+ np.random.rand(dim, dim).astype(np.cfloat) * 1j
)
else:
return np.random.randint(low=1, high=100, size=(dim, dim), dtype=np.int64)
def make_test_matrices2x2(n: int, k: int, kind: str = "complex") -> Tuple[np.ndarray, np.ndarray]:
"""
Creates a ``2^n x 2^n`` random matrix made as a Kronecker product of identity
ones and a single 1-qubit gate. This models a layer in quantum circuit with
an arbitrary 1-qubit gate somewhere in the middle.
Args:
n: number of qubits.
k: index of qubit a 1-qubit gate is acting on.
kind: entries of the output matrix are defined as:
"complex", "primes" or "randint".
Returns:
A tuple of (1) ``2^n x 2^n`` random matrix; (2) ``2 x 2`` matrix of 1-qubit
gate used for matrix construction.
"""
if kind == "primes":
a_mat = np.asarray([[2, 3], [5, 7]], dtype=np.int64)
else:
a_mat = rand_matrix(dim=2, kind=kind)
m_mat = kron3(eye_int(k), a_mat, eye_int(n - k - 1))
return m_mat, a_mat
def make_test_matrices4x4(
n: int, j: int, k: int, kind: str = "complex"
) -> Tuple[np.ndarray, np.ndarray]:
"""
Creates a ``2^n x 2^n`` random matrix made as a Kronecker product of identity
ones and a single 2-qubit gate. This models a layer in quantum circuit with
an arbitrary 2-qubit gate somewhere in the middle.
Args:
n: number of qubits.
j: index of the first qubit the 2-qubit gate acting on.
k: index of the second qubit the 2-qubit gate acting on.
kind: entries of the output matrix are defined as:
"complex", "primes" or "randint".
Returns:
A tuple of (1) ``2^n x 2^n`` random matrix; (2) ``4 x 4`` matrix of
2-qubit gate used for matrix construction.
"""
if kind == "primes":
a_mat = np.asarray([[2, 3], [5, 7]], dtype=np.int64)
b_mat = np.asarray([[11, 13], [17, 19]], dtype=np.int64)
c_mat = np.asarray([[47, 53], [41, 43]], dtype=np.int64)
d_mat = np.asarray([[31, 37], [23, 29]], dtype=np.int64)
else:
a_mat, b_mat = rand_matrix(dim=2, kind=kind), rand_matrix(dim=2, kind=kind)
c_mat, d_mat = rand_matrix(dim=2, kind=kind), rand_matrix(dim=2, kind=kind)
if j < k:
m_mat = kron5(eye_int(j), a_mat, eye_int(k - j - 1), b_mat, eye_int(n - k - 1)) + kron5(
eye_int(j), c_mat, eye_int(k - j - 1), d_mat, eye_int(n - k - 1)
)
else:
m_mat = kron5(eye_int(k), b_mat, eye_int(j - k - 1), a_mat, eye_int(n - j - 1)) + kron5(
eye_int(k), d_mat, eye_int(j - k - 1), c_mat, eye_int(n - j - 1)
)
g_mat = np.kron(a_mat, b_mat) + np.kron(c_mat, d_mat)
return m_mat, g_mat
def rand_circuit(num_qubits: int, depth: int) -> np.ndarray:
"""
Generates a random circuit of unit blocks for debugging and testing.
"""
blocks = np.tile(np.arange(num_qubits).reshape(num_qubits, 1), depth)
for i in range(depth):
np.random.shuffle(blocks[:, i])
return blocks[0:2, :].copy()
def rand_su_mat(dim: int) -> np.ndarray:
"""
Generates a random SU matrix.
Args:
dim: matrix size ``dim-x-dim``.
Returns:
random SU matrix.
"""
u_mat = unitary_group.rvs(dim)
u_mat /= np.linalg.det(u_mat) ** (1.0 / float(dim))
return u_mat
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Testing legacy instruction alignment pass."""
from qiskit import QuantumCircuit, pulse
from qiskit.test import QiskitTestCase
from qiskit.transpiler import InstructionDurations
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.transpiler.passes import (
AlignMeasures,
ValidatePulseGates,
ALAPSchedule,
TimeUnitConversion,
)
class TestAlignMeasures(QiskitTestCase):
"""A test for measurement alignment pass."""
def setUp(self):
super().setUp()
instruction_durations = InstructionDurations()
instruction_durations.update(
[
("rz", (0,), 0),
("rz", (1,), 0),
("x", (0,), 160),
("x", (1,), 160),
("sx", (0,), 160),
("sx", (1,), 160),
("cx", (0, 1), 800),
("cx", (1, 0), 800),
("measure", None, 1600),
]
)
self.time_conversion_pass = TimeUnitConversion(inst_durations=instruction_durations)
# reproduce old behavior of 0.20.0 before #7655
# currently default write latency is 0
self.scheduling_pass = ALAPSchedule(
durations=instruction_durations,
clbit_write_latency=1600,
conditional_latency=0,
)
self.align_measure_pass = AlignMeasures(alignment=16)
def test_t1_experiment_type(self):
"""Test T1 experiment type circuit.
(input)
┌───┐┌────────────────┐┌─┐
q_0: ┤ X ├┤ Delay(100[dt]) ├┤M├
└───┘└────────────────┘└╥┘
c: 1/════════════════════════╩═
0
(aligned)
┌───┐┌────────────────┐┌─┐
q_0: ┤ X ├┤ Delay(112[dt]) ├┤M├
└───┘└────────────────┘└╥┘
c: 1/════════════════════════╩═
0
This type of experiment slightly changes delay duration of interest.
However the quantization error should be less than alignment * dt.
"""
circuit = QuantumCircuit(1, 1)
circuit.x(0)
circuit.delay(100, 0, unit="dt")
circuit.measure(0, 0)
timed_circuit = self.time_conversion_pass(circuit)
scheduled_circuit = self.scheduling_pass(timed_circuit, property_set={"time_unit": "dt"})
aligned_circuit = self.align_measure_pass(
scheduled_circuit, property_set={"time_unit": "dt"}
)
ref_circuit = QuantumCircuit(1, 1)
ref_circuit.x(0)
ref_circuit.delay(112, 0, unit="dt")
ref_circuit.measure(0, 0)
self.assertEqual(aligned_circuit, ref_circuit)
def test_hanh_echo_experiment_type(self):
"""Test Hahn echo experiment type circuit.
(input)
┌────┐┌────────────────┐┌───┐┌────────────────┐┌────┐┌─┐
q_0: ┤ √X ├┤ Delay(100[dt]) ├┤ X ├┤ Delay(100[dt]) ├┤ √X ├┤M├
└────┘└────────────────┘└───┘└────────────────┘└────┘└╥┘
c: 1/══════════════════════════════════════════════════════╩═
0
(output)
┌────┐┌────────────────┐┌───┐┌────────────────┐┌────┐┌──────────────┐┌─┐
q_0: ┤ √X ├┤ Delay(100[dt]) ├┤ X ├┤ Delay(100[dt]) ├┤ √X ├┤ Delay(8[dt]) ├┤M├
└────┘└────────────────┘└───┘└────────────────┘└────┘└──────────────┘└╥┘
c: 1/══════════════════════════════════════════════════════════════════════╩═
0
This type of experiment doesn't change duration of interest (two in the middle).
However induces slight delay less than alignment * dt before measurement.
This might induce extra amplitude damping error.
"""
circuit = QuantumCircuit(1, 1)
circuit.sx(0)
circuit.delay(100, 0, unit="dt")
circuit.x(0)
circuit.delay(100, 0, unit="dt")
circuit.sx(0)
circuit.measure(0, 0)
timed_circuit = self.time_conversion_pass(circuit)
scheduled_circuit = self.scheduling_pass(timed_circuit, property_set={"time_unit": "dt"})
aligned_circuit = self.align_measure_pass(
scheduled_circuit, property_set={"time_unit": "dt"}
)
ref_circuit = QuantumCircuit(1, 1)
ref_circuit.sx(0)
ref_circuit.delay(100, 0, unit="dt")
ref_circuit.x(0)
ref_circuit.delay(100, 0, unit="dt")
ref_circuit.sx(0)
ref_circuit.delay(8, 0, unit="dt")
ref_circuit.measure(0, 0)
self.assertEqual(aligned_circuit, ref_circuit)
def test_mid_circuit_measure(self):
"""Test circuit with mid circuit measurement.
(input)
┌───┐┌────────────────┐┌─┐┌───────────────┐┌───┐┌────────────────┐┌─┐
q_0: ┤ X ├┤ Delay(100[dt]) ├┤M├┤ Delay(10[dt]) ├┤ X ├┤ Delay(120[dt]) ├┤M├
└───┘└────────────────┘└╥┘└───────────────┘└───┘└────────────────┘└╥┘
c: 2/════════════════════════╩══════════════════════════════════════════╩═
0 1
(output)
┌───┐┌────────────────┐┌─┐┌───────────────┐┌───┐┌────────────────┐┌─┐
q_0: ┤ X ├┤ Delay(112[dt]) ├┤M├┤ Delay(10[dt]) ├┤ X ├┤ Delay(134[dt]) ├┤M├
└───┘└────────────────┘└╥┘└───────────────┘└───┘└────────────────┘└╥┘
c: 2/════════════════════════╩══════════════════════════════════════════╩═
0 1
Extra delay is always added to the existing delay right before the measurement.
Delay after measurement is unchanged.
"""
circuit = QuantumCircuit(1, 2)
circuit.x(0)
circuit.delay(100, 0, unit="dt")
circuit.measure(0, 0)
circuit.delay(10, 0, unit="dt")
circuit.x(0)
circuit.delay(120, 0, unit="dt")
circuit.measure(0, 1)
timed_circuit = self.time_conversion_pass(circuit)
scheduled_circuit = self.scheduling_pass(timed_circuit, property_set={"time_unit": "dt"})
aligned_circuit = self.align_measure_pass(
scheduled_circuit, property_set={"time_unit": "dt"}
)
ref_circuit = QuantumCircuit(1, 2)
ref_circuit.x(0)
ref_circuit.delay(112, 0, unit="dt")
ref_circuit.measure(0, 0)
ref_circuit.delay(10, 0, unit="dt")
ref_circuit.x(0)
ref_circuit.delay(134, 0, unit="dt")
ref_circuit.measure(0, 1)
self.assertEqual(aligned_circuit, ref_circuit)
def test_mid_circuit_multiq_gates(self):
"""Test circuit with mid circuit measurement and multi qubit gates.
(input)
┌───┐┌────────────────┐┌─┐ ┌─┐
q_0: ┤ X ├┤ Delay(100[dt]) ├┤M├──■───────■──┤M├
└───┘└────────────────┘└╥┘┌─┴─┐┌─┐┌─┴─┐└╥┘
q_1: ────────────────────────╫─┤ X ├┤M├┤ X ├─╫─
║ └───┘└╥┘└───┘ ║
c: 2/════════════════════════╩═══════╩═══════╩═
0 1 0
(output)
┌───┐ ┌────────────────┐┌─┐ ┌─────────────────┐ ┌─┐»
q_0: ───────┤ X ├───────┤ Delay(112[dt]) ├┤M├──■──┤ Delay(1600[dt]) ├──■──┤M├»
┌──────┴───┴──────┐└────────────────┘└╥┘┌─┴─┐└───────┬─┬───────┘┌─┴─┐└╥┘»
q_1: ┤ Delay(1872[dt]) ├───────────────────╫─┤ X ├────────┤M├────────┤ X ├─╫─»
└─────────────────┘ ║ └───┘ └╥┘ └───┘ ║ »
c: 2/══════════════════════════════════════╩═══════════════╩═══════════════╩═»
0 1 0 »
«
«q_0: ───────────────────
« ┌─────────────────┐
«q_1: ┤ Delay(1600[dt]) ├
« └─────────────────┘
«c: 2/═══════════════════
«
Delay for the other channel paired by multi-qubit instruction is also scheduled.
Delay (1872dt) = X (160dt) + Delay (100dt + extra 12dt) + Measure (1600dt).
"""
circuit = QuantumCircuit(2, 2)
circuit.x(0)
circuit.delay(100, 0, unit="dt")
circuit.measure(0, 0)
circuit.cx(0, 1)
circuit.measure(1, 1)
circuit.cx(0, 1)
circuit.measure(0, 0)
timed_circuit = self.time_conversion_pass(circuit)
scheduled_circuit = self.scheduling_pass(timed_circuit, property_set={"time_unit": "dt"})
aligned_circuit = self.align_measure_pass(
scheduled_circuit, property_set={"time_unit": "dt"}
)
ref_circuit = QuantumCircuit(2, 2)
ref_circuit.x(0)
ref_circuit.delay(112, 0, unit="dt")
ref_circuit.measure(0, 0)
ref_circuit.delay(160 + 112 + 1600, 1, unit="dt")
ref_circuit.cx(0, 1)
ref_circuit.delay(1600, 0, unit="dt")
ref_circuit.measure(1, 1)
ref_circuit.cx(0, 1)
ref_circuit.delay(1600, 1, unit="dt")
ref_circuit.measure(0, 0)
self.assertEqual(aligned_circuit, ref_circuit)
def test_alignment_is_not_processed(self):
"""Test avoid pass processing if delay is aligned."""
circuit = QuantumCircuit(2, 2)
circuit.x(0)
circuit.delay(160, 0, unit="dt")
circuit.measure(0, 0)
circuit.cx(0, 1)
circuit.measure(1, 1)
circuit.cx(0, 1)
circuit.measure(0, 0)
# pre scheduling is not necessary because alignment is skipped
# this is to minimize breaking changes to existing code.
transpiled = self.align_measure_pass(circuit, property_set={"time_unit": "dt"})
self.assertEqual(transpiled, circuit)
def test_circuit_using_clbit(self):
"""Test a circuit with instructions using a common clbit.
(input)
┌───┐┌────────────────┐┌─┐
q_0: ┤ X ├┤ Delay(100[dt]) ├┤M├──────────────
└───┘└────────────────┘└╥┘ ┌───┐
q_1: ────────────────────────╫────┤ X ├──────
║ └─╥─┘ ┌─┐
q_2: ────────────────────────╫──────╫─────┤M├
║ ┌────╨────┐└╥┘
c: 1/════════════════════════╩═╡ c_0 = T ╞═╩═
0 └─────────┘ 0
(aligned)
┌───┐ ┌────────────────┐┌─┐┌────────────────┐
q_0: ───────┤ X ├───────┤ Delay(112[dt]) ├┤M├┤ Delay(160[dt]) ├───
┌──────┴───┴──────┐└────────────────┘└╥┘└─────┬───┬──────┘
q_1: ┤ Delay(1872[dt]) ├───────────────────╫───────┤ X ├──────────
└┬────────────────┤ ║ └─╥─┘ ┌─┐
q_2: ─┤ Delay(432[dt]) ├───────────────────╫─────────╫─────────┤M├
└────────────────┘ ║ ┌────╨────┐ └╥┘
c: 1/══════════════════════════════════════╩════╡ c_0 = T ╞═════╩═
0 └─────────┘ 0
Looking at the q_0, the total schedule length T becomes
160 (x) + 112 (aligned delay) + 1600 (measure) + 160 (delay) = 2032.
The last delay comes from ALAP scheduling called before the AlignMeasure pass,
which aligns stop times as late as possible, so the start time of x(1).c_if(0)
and the stop time of measure(0, 0) become T - 160.
"""
circuit = QuantumCircuit(3, 1)
circuit.x(0)
circuit.delay(100, 0, unit="dt")
circuit.measure(0, 0)
circuit.x(1).c_if(0, 1)
circuit.measure(2, 0)
timed_circuit = self.time_conversion_pass(circuit)
scheduled_circuit = self.scheduling_pass(timed_circuit, property_set={"time_unit": "dt"})
aligned_circuit = self.align_measure_pass(
scheduled_circuit, property_set={"time_unit": "dt"}
)
self.assertEqual(aligned_circuit.duration, 2032)
ref_circuit = QuantumCircuit(3, 1)
ref_circuit.x(0)
ref_circuit.delay(112, 0, unit="dt")
ref_circuit.delay(1872, 1, unit="dt") # 2032 - 160
ref_circuit.delay(432, 2, unit="dt") # 2032 - 1600
ref_circuit.measure(0, 0)
ref_circuit.x(1).c_if(0, 1)
ref_circuit.delay(160, 0, unit="dt")
ref_circuit.measure(2, 0)
self.assertEqual(aligned_circuit, ref_circuit)
class TestPulseGateValidation(QiskitTestCase):
"""A test for pulse gate validation pass."""
def setUp(self):
super().setUp()
self.pulse_gate_validation_pass = ValidatePulseGates(granularity=16, min_length=64)
def test_invalid_pulse_duration(self):
"""Kill pass manager if invalid pulse gate is found."""
# this is invalid duration pulse
# this will cause backend error since this doesn't fit with waveform memory chunk.
custom_gate = pulse.Schedule(name="custom_x_gate")
custom_gate.insert(
0, pulse.Play(pulse.Constant(100, 0.1), pulse.DriveChannel(0)), inplace=True
)
circuit = QuantumCircuit(1)
circuit.x(0)
circuit.add_calibration("x", qubits=(0,), schedule=custom_gate)
with self.assertRaises(TranspilerError):
self.pulse_gate_validation_pass(circuit)
def test_short_pulse_duration(self):
"""Kill pass manager if invalid pulse gate is found."""
# this is invalid duration pulse
# this will cause backend error since this doesn't fit with waveform memory chunk.
custom_gate = pulse.Schedule(name="custom_x_gate")
custom_gate.insert(
0, pulse.Play(pulse.Constant(32, 0.1), pulse.DriveChannel(0)), inplace=True
)
circuit = QuantumCircuit(1)
circuit.x(0)
circuit.add_calibration("x", qubits=(0,), schedule=custom_gate)
with self.assertRaises(TranspilerError):
self.pulse_gate_validation_pass(circuit)
def test_short_pulse_duration_multiple_pulse(self):
"""Kill pass manager if invalid pulse gate is found."""
# this is invalid duration pulse
# however total gate schedule length is 64, which accidentally satisfies the constraints
# this should fail in the validation
custom_gate = pulse.Schedule(name="custom_x_gate")
custom_gate.insert(
0, pulse.Play(pulse.Constant(32, 0.1), pulse.DriveChannel(0)), inplace=True
)
custom_gate.insert(
32, pulse.Play(pulse.Constant(32, 0.1), pulse.DriveChannel(0)), inplace=True
)
circuit = QuantumCircuit(1)
circuit.x(0)
circuit.add_calibration("x", qubits=(0,), schedule=custom_gate)
with self.assertRaises(TranspilerError):
self.pulse_gate_validation_pass(circuit)
def test_valid_pulse_duration(self):
"""No error raises if valid calibration is provided."""
# this is valid duration pulse
custom_gate = pulse.Schedule(name="custom_x_gate")
custom_gate.insert(
0, pulse.Play(pulse.Constant(160, 0.1), pulse.DriveChannel(0)), inplace=True
)
circuit = QuantumCircuit(1)
circuit.x(0)
circuit.add_calibration("x", qubits=(0,), schedule=custom_gate)
# just not raise an error
self.pulse_gate_validation_pass(circuit)
def test_no_calibration(self):
"""No error raises if no calibration is addedd."""
circuit = QuantumCircuit(1)
circuit.x(0)
# just not raise an error
self.pulse_gate_validation_pass(circuit)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the legacy Scheduling passes"""
import unittest
from ddt import ddt, data, unpack
from qiskit import QuantumCircuit
from qiskit.circuit import Delay, Parameter
from qiskit.circuit.library.standard_gates import XGate, YGate, CXGate
from qiskit.test import QiskitTestCase
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.transpiler.instruction_durations import InstructionDurations
from qiskit.transpiler.passes import ASAPSchedule, ALAPSchedule, DynamicalDecoupling
from qiskit.transpiler.passmanager import PassManager
from qiskit.transpiler.target import Target, InstructionProperties
@ddt
class TestSchedulingPass(QiskitTestCase):
"""Tests the Scheduling passes"""
def test_alap_agree_with_reverse_asap_reverse(self):
"""Test if ALAP schedule agrees with doubly-reversed ASAP schedule."""
qc = QuantumCircuit(2)
qc.h(0)
qc.delay(500, 1)
qc.cx(0, 1)
qc.measure_all()
durations = InstructionDurations(
[("h", 0, 200), ("cx", [0, 1], 700), ("measure", None, 1000)]
)
pm = PassManager(ALAPSchedule(durations))
alap_qc = pm.run(qc)
pm = PassManager(ASAPSchedule(durations))
new_qc = pm.run(qc.reverse_ops())
new_qc = new_qc.reverse_ops()
new_qc.name = new_qc.name
self.assertEqual(alap_qc, new_qc)
@data(ALAPSchedule, ASAPSchedule)
def test_classically_controlled_gate_after_measure(self, schedule_pass):
"""Test if ALAP/ASAP schedules circuits with c_if after measure with a common clbit.
See: https://github.com/Qiskit/qiskit-terra/issues/7654
(input)
┌─┐
q_0: ┤M├───────────
└╥┘ ┌───┐
q_1: ─╫────┤ X ├───
║ └─╥─┘
║ ┌────╨────┐
c: 1/═╩═╡ c_0 = T ╞
0 └─────────┘
(scheduled)
┌─┐┌────────────────┐
q_0: ───────────────────┤M├┤ Delay(200[dt]) ├
┌─────────────────┐└╥┘└─────┬───┬──────┘
q_1: ┤ Delay(1000[dt]) ├─╫───────┤ X ├───────
└─────────────────┘ ║ └─╥─┘
║ ┌────╨────┐
c: 1/════════════════════╩════╡ c_0=0x1 ╞════
0 └─────────┘
"""
qc = QuantumCircuit(2, 1)
qc.measure(0, 0)
qc.x(1).c_if(0, True)
durations = InstructionDurations([("x", None, 200), ("measure", None, 1000)])
pm = PassManager(schedule_pass(durations))
scheduled = pm.run(qc)
expected = QuantumCircuit(2, 1)
expected.measure(0, 0)
expected.delay(1000, 1) # x.c_if starts after measure
expected.x(1).c_if(0, True)
expected.delay(200, 0)
self.assertEqual(expected, scheduled)
@data(ALAPSchedule, ASAPSchedule)
def test_measure_after_measure(self, schedule_pass):
"""Test if ALAP/ASAP schedules circuits with measure after measure with a common clbit.
See: https://github.com/Qiskit/qiskit-terra/issues/7654
(input)
┌───┐┌─┐
q_0: ┤ X ├┤M├───
└───┘└╥┘┌─┐
q_1: ──────╫─┤M├
║ └╥┘
c: 1/══════╩══╩═
0 0
(scheduled)
┌───┐ ┌─┐┌─────────────────┐
q_0: ───────┤ X ├───────┤M├┤ Delay(1000[dt]) ├
┌──────┴───┴──────┐└╥┘└───────┬─┬───────┘
q_1: ┤ Delay(1200[dt]) ├─╫─────────┤M├────────
└─────────────────┘ ║ └╥┘
c: 1/════════════════════╩══════════╩═════════
0 0
"""
qc = QuantumCircuit(2, 1)
qc.x(0)
qc.measure(0, 0)
qc.measure(1, 0)
durations = InstructionDurations([("x", None, 200), ("measure", None, 1000)])
pm = PassManager(schedule_pass(durations))
scheduled = pm.run(qc)
expected = QuantumCircuit(2, 1)
expected.x(0)
expected.measure(0, 0)
expected.delay(1200, 1)
expected.measure(1, 0)
expected.delay(1000, 0)
self.assertEqual(expected, scheduled)
@data(ALAPSchedule, ASAPSchedule)
def test_c_if_on_different_qubits(self, schedule_pass):
"""Test if ALAP/ASAP schedules circuits with `c_if`s on different qubits.
(input)
┌─┐
q_0: ┤M├──────────────────────
└╥┘ ┌───┐
q_1: ─╫────┤ X ├──────────────
║ └─╥─┘ ┌───┐
q_2: ─╫──────╫────────┤ X ├───
║ ║ └─╥─┘
║ ┌────╨────┐┌────╨────┐
c: 1/═╩═╡ c_0 = T ╞╡ c_0 = T ╞
0 └─────────┘└─────────┘
(scheduled)
┌─┐┌────────────────┐
q_0: ───────────────────┤M├┤ Delay(200[dt]) ├───────────
┌─────────────────┐└╥┘└─────┬───┬──────┘
q_1: ┤ Delay(1000[dt]) ├─╫───────┤ X ├──────────────────
├─────────────────┤ ║ └─╥─┘ ┌───┐
q_2: ┤ Delay(1000[dt]) ├─╫─────────╫────────────┤ X ├───
└─────────────────┘ ║ ║ └─╥─┘
║ ┌────╨────┐ ┌────╨────┐
c: 1/════════════════════╩════╡ c_0=0x1 ╞════╡ c_0=0x1 ╞
0 └─────────┘ └─────────┘
"""
qc = QuantumCircuit(3, 1)
qc.measure(0, 0)
qc.x(1).c_if(0, True)
qc.x(2).c_if(0, True)
durations = InstructionDurations([("x", None, 200), ("measure", None, 1000)])
pm = PassManager(schedule_pass(durations))
scheduled = pm.run(qc)
expected = QuantumCircuit(3, 1)
expected.measure(0, 0)
expected.delay(1000, 1)
expected.delay(1000, 2)
expected.x(1).c_if(0, True)
expected.x(2).c_if(0, True)
expected.delay(200, 0)
self.assertEqual(expected, scheduled)
@data(ALAPSchedule, ASAPSchedule)
def test_shorter_measure_after_measure(self, schedule_pass):
"""Test if ALAP/ASAP schedules circuits with shorter measure after measure with a common clbit.
(input)
┌─┐
q_0: ┤M├───
└╥┘┌─┐
q_1: ─╫─┤M├
║ └╥┘
c: 1/═╩══╩═
0 0
(scheduled)
┌─┐┌────────────────┐
q_0: ───────────────────┤M├┤ Delay(700[dt]) ├
┌─────────────────┐└╥┘└──────┬─┬───────┘
q_1: ┤ Delay(1000[dt]) ├─╫────────┤M├────────
└─────────────────┘ ║ └╥┘
c: 1/════════════════════╩═════════╩═════════
0 0
"""
qc = QuantumCircuit(2, 1)
qc.measure(0, 0)
qc.measure(1, 0)
durations = InstructionDurations([("measure", [0], 1000), ("measure", [1], 700)])
pm = PassManager(schedule_pass(durations))
scheduled = pm.run(qc)
expected = QuantumCircuit(2, 1)
expected.measure(0, 0)
expected.delay(1000, 1)
expected.measure(1, 0)
expected.delay(700, 0)
self.assertEqual(expected, scheduled)
@data(ALAPSchedule, ASAPSchedule)
def test_measure_after_c_if(self, schedule_pass):
"""Test if ALAP/ASAP schedules circuits with c_if after measure with a common clbit.
(input)
┌─┐
q_0: ┤M├──────────────
└╥┘ ┌───┐
q_1: ─╫────┤ X ├──────
║ └─╥─┘ ┌─┐
q_2: ─╫──────╫─────┤M├
║ ┌────╨────┐└╥┘
c: 1/═╩═╡ c_0 = T ╞═╩═
0 └─────────┘ 0
(scheduled)
┌─┐┌─────────────────┐
q_0: ───────────────────┤M├┤ Delay(1000[dt]) ├──────────────────
┌─────────────────┐└╥┘└──────┬───┬──────┘┌────────────────┐
q_1: ┤ Delay(1000[dt]) ├─╫────────┤ X ├───────┤ Delay(800[dt]) ├
├─────────────────┤ ║ └─╥─┘ └──────┬─┬───────┘
q_2: ┤ Delay(1000[dt]) ├─╫──────────╫────────────────┤M├────────
└─────────────────┘ ║ ┌────╨────┐ └╥┘
c: 1/════════════════════╩═════╡ c_0=0x1 ╞════════════╩═════════
0 └─────────┘ 0
"""
qc = QuantumCircuit(3, 1)
qc.measure(0, 0)
qc.x(1).c_if(0, 1)
qc.measure(2, 0)
durations = InstructionDurations([("x", None, 200), ("measure", None, 1000)])
pm = PassManager(schedule_pass(durations))
scheduled = pm.run(qc)
expected = QuantumCircuit(3, 1)
expected.delay(1000, 1)
expected.delay(1000, 2)
expected.measure(0, 0)
expected.x(1).c_if(0, 1)
expected.measure(2, 0)
expected.delay(1000, 0)
expected.delay(800, 1)
self.assertEqual(expected, scheduled)
def test_parallel_gate_different_length(self):
"""Test circuit having two parallel instruction with different length.
(input)
┌───┐┌─┐
q_0: ┤ X ├┤M├───
├───┤└╥┘┌─┐
q_1: ┤ X ├─╫─┤M├
└───┘ ║ └╥┘
c: 2/══════╩══╩═
0 1
(expected, ALAP)
┌────────────────┐┌───┐┌─┐
q_0: ┤ Delay(200[dt]) ├┤ X ├┤M├
└─────┬───┬──────┘└┬─┬┘└╥┘
q_1: ──────┤ X ├────────┤M├──╫─
└───┘ └╥┘ ║
c: 2/════════════════════╩═══╩═
1 0
(expected, ASAP)
┌───┐┌─┐┌────────────────┐
q_0: ┤ X ├┤M├┤ Delay(200[dt]) ├
├───┤└╥┘└──────┬─┬───────┘
q_1: ┤ X ├─╫────────┤M├────────
└───┘ ║ └╥┘
c: 2/══════╩═════════╩═════════
0 1
"""
qc = QuantumCircuit(2, 2)
qc.x(0)
qc.x(1)
qc.measure(0, 0)
qc.measure(1, 1)
durations = InstructionDurations(
[("x", [0], 200), ("x", [1], 400), ("measure", None, 1000)]
)
pm = PassManager(ALAPSchedule(durations))
qc_alap = pm.run(qc)
alap_expected = QuantumCircuit(2, 2)
alap_expected.delay(200, 0)
alap_expected.x(0)
alap_expected.x(1)
alap_expected.measure(0, 0)
alap_expected.measure(1, 1)
self.assertEqual(qc_alap, alap_expected)
pm = PassManager(ASAPSchedule(durations))
qc_asap = pm.run(qc)
asap_expected = QuantumCircuit(2, 2)
asap_expected.x(0)
asap_expected.x(1)
asap_expected.measure(0, 0) # immediately start after X gate
asap_expected.measure(1, 1)
asap_expected.delay(200, 0)
self.assertEqual(qc_asap, asap_expected)
def test_parallel_gate_different_length_with_barrier(self):
"""Test circuit having two parallel instruction with different length with barrier.
(input)
┌───┐┌─┐
q_0: ┤ X ├┤M├───
├───┤└╥┘┌─┐
q_1: ┤ X ├─╫─┤M├
└───┘ ║ └╥┘
c: 2/══════╩══╩═
0 1
(expected, ALAP)
┌────────────────┐┌───┐ ░ ┌─┐
q_0: ┤ Delay(200[dt]) ├┤ X ├─░─┤M├───
└─────┬───┬──────┘└───┘ ░ └╥┘┌─┐
q_1: ──────┤ X ├─────────────░──╫─┤M├
└───┘ ░ ║ └╥┘
c: 2/═══════════════════════════╩══╩═
0 1
(expected, ASAP)
┌───┐┌────────────────┐ ░ ┌─┐
q_0: ┤ X ├┤ Delay(200[dt]) ├─░─┤M├───
├───┤└────────────────┘ ░ └╥┘┌─┐
q_1: ┤ X ├───────────────────░──╫─┤M├
└───┘ ░ ║ └╥┘
c: 2/═══════════════════════════╩══╩═
0 1
"""
qc = QuantumCircuit(2, 2)
qc.x(0)
qc.x(1)
qc.barrier()
qc.measure(0, 0)
qc.measure(1, 1)
durations = InstructionDurations(
[("x", [0], 200), ("x", [1], 400), ("measure", None, 1000)]
)
pm = PassManager(ALAPSchedule(durations))
qc_alap = pm.run(qc)
alap_expected = QuantumCircuit(2, 2)
alap_expected.delay(200, 0)
alap_expected.x(0)
alap_expected.x(1)
alap_expected.barrier()
alap_expected.measure(0, 0)
alap_expected.measure(1, 1)
self.assertEqual(qc_alap, alap_expected)
pm = PassManager(ASAPSchedule(durations))
qc_asap = pm.run(qc)
asap_expected = QuantumCircuit(2, 2)
asap_expected.x(0)
asap_expected.delay(200, 0)
asap_expected.x(1)
asap_expected.barrier()
asap_expected.measure(0, 0)
asap_expected.measure(1, 1)
self.assertEqual(qc_asap, asap_expected)
def test_measure_after_c_if_on_edge_locking(self):
"""Test if ALAP/ASAP schedules circuits with c_if after measure with a common clbit.
The scheduler is configured to reproduce behavior of the 0.20.0,
in which clbit lock is applied to the end-edge of measure instruction.
See https://github.com/Qiskit/qiskit-terra/pull/7655
(input)
┌─┐
q_0: ┤M├──────────────
└╥┘ ┌───┐
q_1: ─╫────┤ X ├──────
║ └─╥─┘ ┌─┐
q_2: ─╫──────╫─────┤M├
║ ┌────╨────┐└╥┘
c: 1/═╩═╡ c_0 = T ╞═╩═
0 └─────────┘ 0
(ASAP scheduled)
┌─┐┌────────────────┐
q_0: ───────────────────┤M├┤ Delay(200[dt]) ├─────────────────────
┌─────────────────┐└╥┘└─────┬───┬──────┘
q_1: ┤ Delay(1000[dt]) ├─╫───────┤ X ├────────────────────────────
└─────────────────┘ ║ └─╥─┘ ┌─┐┌────────────────┐
q_2: ────────────────────╫─────────╫─────────┤M├┤ Delay(200[dt]) ├
║ ┌────╨────┐ └╥┘└────────────────┘
c: 1/════════════════════╩════╡ c_0=0x1 ╞═════╩═══════════════════
0 └─────────┘ 0
(ALAP scheduled)
┌─┐┌────────────────┐
q_0: ───────────────────┤M├┤ Delay(200[dt]) ├───
┌─────────────────┐└╥┘└─────┬───┬──────┘
q_1: ┤ Delay(1000[dt]) ├─╫───────┤ X ├──────────
└┬────────────────┤ ║ └─╥─┘ ┌─┐
q_2: ─┤ Delay(200[dt]) ├─╫─────────╫─────────┤M├
└────────────────┘ ║ ┌────╨────┐ └╥┘
c: 1/════════════════════╩════╡ c_0=0x1 ╞═════╩═
0 └─────────┘ 0
"""
qc = QuantumCircuit(3, 1)
qc.measure(0, 0)
qc.x(1).c_if(0, 1)
qc.measure(2, 0)
durations = InstructionDurations([("x", None, 200), ("measure", None, 1000)])
# lock at the end edge
actual_asap = PassManager(ASAPSchedule(durations, clbit_write_latency=1000)).run(qc)
actual_alap = PassManager(ALAPSchedule(durations, clbit_write_latency=1000)).run(qc)
# start times of 2nd measure depends on ASAP/ALAP
expected_asap = QuantumCircuit(3, 1)
expected_asap.measure(0, 0)
expected_asap.delay(1000, 1)
expected_asap.x(1).c_if(0, 1)
expected_asap.measure(2, 0)
expected_asap.delay(200, 0)
expected_asap.delay(200, 2)
self.assertEqual(expected_asap, actual_asap)
expected_alap = QuantumCircuit(3, 1)
expected_alap.measure(0, 0)
expected_alap.delay(1000, 1)
expected_alap.x(1).c_if(0, 1)
expected_alap.delay(200, 2)
expected_alap.measure(2, 0)
expected_alap.delay(200, 0)
self.assertEqual(expected_alap, actual_alap)
@data([100, 200], [500, 0], [1000, 200])
@unpack
def test_active_reset_circuit(self, write_lat, cond_lat):
"""Test practical example of reset circuit.
Because of the stimulus pulse overlap with the previous XGate on the q register,
measure instruction is always triggered after XGate regardless of write latency.
Thus only conditional latency matters in the scheduling.
(input)
┌─┐ ┌───┐ ┌─┐ ┌───┐ ┌─┐ ┌───┐
q: ┤M├───┤ X ├───┤M├───┤ X ├───┤M├───┤ X ├───
└╥┘ └─╥─┘ └╥┘ └─╥─┘ └╥┘ └─╥─┘
║ ┌────╨────┐ ║ ┌────╨────┐ ║ ┌────╨────┐
c: 1/═╩═╡ c_0=0x1 ╞═╩═╡ c_0=0x1 ╞═╩═╡ c_0=0x1 ╞
0 └─────────┘ 0 └─────────┘ 0 └─────────┘
"""
qc = QuantumCircuit(1, 1)
qc.measure(0, 0)
qc.x(0).c_if(0, 1)
qc.measure(0, 0)
qc.x(0).c_if(0, 1)
qc.measure(0, 0)
qc.x(0).c_if(0, 1)
durations = InstructionDurations([("x", None, 100), ("measure", None, 1000)])
actual_asap = PassManager(
ASAPSchedule(durations, clbit_write_latency=write_lat, conditional_latency=cond_lat)
).run(qc)
actual_alap = PassManager(
ALAPSchedule(durations, clbit_write_latency=write_lat, conditional_latency=cond_lat)
).run(qc)
expected = QuantumCircuit(1, 1)
expected.measure(0, 0)
if cond_lat > 0:
expected.delay(cond_lat, 0)
expected.x(0).c_if(0, 1)
expected.measure(0, 0)
if cond_lat > 0:
expected.delay(cond_lat, 0)
expected.x(0).c_if(0, 1)
expected.measure(0, 0)
if cond_lat > 0:
expected.delay(cond_lat, 0)
expected.x(0).c_if(0, 1)
self.assertEqual(expected, actual_asap)
self.assertEqual(expected, actual_alap)
def test_random_complicated_circuit(self):
"""Test scheduling complicated circuit with control flow.
(input)
┌────────────────┐ ┌───┐ ░ ┌───┐ »
q_0: ┤ Delay(100[dt]) ├───┤ X ├────░──────────────────┤ X ├───»
└────────────────┘ └─╥─┘ ░ ┌───┐ └─╥─┘ »
q_1: ───────────────────────╫──────░───────┤ X ├────────╫─────»
║ ░ ┌─┐ └─╥─┘ ║ »
q_2: ───────────────────────╫──────░─┤M├─────╫──────────╫─────»
┌────╨────┐ ░ └╥┘┌────╨────┐┌────╨────┐»
c: 1/══════════════════╡ c_0=0x1 ╞════╩═╡ c_0=0x0 ╞╡ c_0=0x0 ╞»
└─────────┘ 0 └─────────┘└─────────┘»
« ┌────────────────┐┌───┐
«q_0: ┤ Delay(300[dt]) ├┤ X ├─────■─────
« └────────────────┘└───┘ ┌─┴─┐
«q_1: ────────■─────────────────┤ X ├───
« ┌─┴─┐ ┌─┐ └─╥─┘
«q_2: ──────┤ X ├────────┤M├──────╫─────
« └───┘ └╥┘ ┌────╨────┐
«c: 1/════════════════════╩══╡ c_0=0x0 ╞
« 0 └─────────┘
(ASAP scheduled) duration = 2800 dt
┌────────────────┐┌────────────────┐ ┌───┐ ░ ┌─────────────────┐»
q_0: ┤ Delay(100[dt]) ├┤ Delay(100[dt]) ├───┤ X ├────░─┤ Delay(1400[dt]) ├»
├────────────────┤└────────────────┘ └─╥─┘ ░ ├─────────────────┤»
q_1: ┤ Delay(300[dt]) ├───────────────────────╫──────░─┤ Delay(1200[dt]) ├»
├────────────────┤ ║ ░ └───────┬─┬───────┘»
q_2: ┤ Delay(300[dt]) ├───────────────────────╫──────░─────────┤M├────────»
└────────────────┘ ┌────╨────┐ ░ └╥┘ »
c: 1/════════════════════════════════════╡ c_0=0x1 ╞════════════╩═════════»
└─────────┘ 0 »
« ┌───┐ ┌────────────────┐»
«q_0: ────────────────────────────────┤ X ├───┤ Delay(300[dt]) ├»
« ┌───┐ └─╥─┘ └────────────────┘»
«q_1: ───┤ X ├──────────────────────────╫─────────────■─────────»
« └─╥─┘ ┌────────────────┐ ║ ┌─┴─┐ »
«q_2: ─────╫─────┤ Delay(300[dt]) ├─────╫───────────┤ X ├───────»
« ┌────╨────┐└────────────────┘┌────╨────┐ └───┘ »
«c: 1/╡ c_0=0x0 ╞══════════════════╡ c_0=0x0 ╞══════════════════»
« └─────────┘ └─────────┘ »
« ┌───┐ ┌────────────────┐
«q_0: ──────┤ X ├────────────■─────┤ Delay(700[dt]) ├
« ┌─────┴───┴──────┐ ┌─┴─┐ ├────────────────┤
«q_1: ┤ Delay(400[dt]) ├───┤ X ├───┤ Delay(700[dt]) ├
« ├────────────────┤ └─╥─┘ └──────┬─┬───────┘
«q_2: ┤ Delay(300[dt]) ├─────╫────────────┤M├────────
« └────────────────┘┌────╨────┐ └╥┘
«c: 1/══════════════════╡ c_0=0x0 ╞════════╩═════════
« └─────────┘ 0
(ALAP scheduled) duration = 3100
┌────────────────┐┌────────────────┐ ┌───┐ ░ ┌─────────────────┐»
q_0: ┤ Delay(100[dt]) ├┤ Delay(100[dt]) ├───┤ X ├────░─┤ Delay(1400[dt]) ├»
├────────────────┤└────────────────┘ └─╥─┘ ░ ├─────────────────┤»
q_1: ┤ Delay(300[dt]) ├───────────────────────╫──────░─┤ Delay(1200[dt]) ├»
├────────────────┤ ║ ░ └───────┬─┬───────┘»
q_2: ┤ Delay(300[dt]) ├───────────────────────╫──────░─────────┤M├────────»
└────────────────┘ ┌────╨────┐ ░ └╥┘ »
c: 1/════════════════════════════════════╡ c_0=0x1 ╞════════════╩═════════»
└─────────┘ 0 »
« ┌───┐ ┌────────────────┐»
«q_0: ────────────────────────────────┤ X ├───┤ Delay(300[dt]) ├»
« ┌───┐ ┌────────────────┐ └─╥─┘ └────────────────┘»
«q_1: ───┤ X ├───┤ Delay(300[dt]) ├─────╫─────────────■─────────»
« └─╥─┘ ├────────────────┤ ║ ┌─┴─┐ »
«q_2: ─────╫─────┤ Delay(600[dt]) ├─────╫───────────┤ X ├───────»
« ┌────╨────┐└────────────────┘┌────╨────┐ └───┘ »
«c: 1/╡ c_0=0x0 ╞══════════════════╡ c_0=0x0 ╞══════════════════»
« └─────────┘ └─────────┘ »
« ┌───┐ ┌────────────────┐
«q_0: ──────┤ X ├────────────■─────┤ Delay(700[dt]) ├
« ┌─────┴───┴──────┐ ┌─┴─┐ ├────────────────┤
«q_1: ┤ Delay(100[dt]) ├───┤ X ├───┤ Delay(700[dt]) ├
« └──────┬─┬───────┘ └─╥─┘ └────────────────┘
«q_2: ───────┤M├─────────────╫───────────────────────
« └╥┘ ┌────╨────┐
«c: 1/════════╩═════════╡ c_0=0x0 ╞══════════════════
« 0 └─────────┘
"""
qc = QuantumCircuit(3, 1)
qc.delay(100, 0)
qc.x(0).c_if(0, 1)
qc.barrier()
qc.measure(2, 0)
qc.x(1).c_if(0, 0)
qc.x(0).c_if(0, 0)
qc.delay(300, 0)
qc.cx(1, 2)
qc.x(0)
qc.cx(0, 1).c_if(0, 0)
qc.measure(2, 0)
durations = InstructionDurations(
[("x", None, 100), ("measure", None, 1000), ("cx", None, 200)]
)
actual_asap = PassManager(
ASAPSchedule(durations, clbit_write_latency=100, conditional_latency=200)
).run(qc)
actual_alap = PassManager(
ALAPSchedule(durations, clbit_write_latency=100, conditional_latency=200)
).run(qc)
expected_asap = QuantumCircuit(3, 1)
expected_asap.delay(100, 0)
expected_asap.delay(100, 0) # due to conditional latency of 200dt
expected_asap.delay(300, 1)
expected_asap.delay(300, 2)
expected_asap.x(0).c_if(0, 1)
expected_asap.barrier()
expected_asap.delay(1400, 0)
expected_asap.delay(1200, 1)
expected_asap.measure(2, 0)
expected_asap.x(1).c_if(0, 0)
expected_asap.x(0).c_if(0, 0)
expected_asap.delay(300, 0)
expected_asap.x(0)
expected_asap.delay(300, 2)
expected_asap.cx(1, 2)
expected_asap.delay(400, 1)
expected_asap.cx(0, 1).c_if(0, 0)
expected_asap.delay(700, 0) # creg is released at t0 of cx(0,1).c_if(0,0)
expected_asap.delay(
700, 1
) # no creg write until 100dt. thus measure can move left by 300dt.
expected_asap.delay(300, 2)
expected_asap.measure(2, 0)
self.assertEqual(expected_asap, actual_asap)
self.assertEqual(actual_asap.duration, 3100)
expected_alap = QuantumCircuit(3, 1)
expected_alap.delay(100, 0)
expected_alap.delay(100, 0) # due to conditional latency of 200dt
expected_alap.delay(300, 1)
expected_alap.delay(300, 2)
expected_alap.x(0).c_if(0, 1)
expected_alap.barrier()
expected_alap.delay(1400, 0)
expected_alap.delay(1200, 1)
expected_alap.measure(2, 0)
expected_alap.x(1).c_if(0, 0)
expected_alap.x(0).c_if(0, 0)
expected_alap.delay(300, 0)
expected_alap.x(0)
expected_alap.delay(300, 1)
expected_alap.delay(600, 2)
expected_alap.cx(1, 2)
expected_alap.delay(100, 1)
expected_alap.cx(0, 1).c_if(0, 0)
expected_alap.measure(2, 0)
expected_alap.delay(700, 0)
expected_alap.delay(700, 1)
self.assertEqual(expected_alap, actual_alap)
self.assertEqual(actual_alap.duration, 3100)
def test_dag_introduces_extra_dependency_between_conditionals(self):
"""Test dependency between conditional operations in the scheduling.
In the below example circuit, the conditional x on q1 could start at time 0,
however it must be scheduled after the conditional x on q0 in ASAP scheduling.
That is because circuit model used in the transpiler passes (DAGCircuit)
interprets instructions acting on common clbits must be run in the order
given by the original circuit (QuantumCircuit).
(input)
┌────────────────┐ ┌───┐
q_0: ┤ Delay(100[dt]) ├───┤ X ├───
└─────┬───┬──────┘ └─╥─┘
q_1: ──────┤ X ├────────────╫─────
└─╥─┘ ║
┌────╨────┐ ┌────╨────┐
c: 1/═══╡ c_0=0x1 ╞════╡ c_0=0x1 ╞
└─────────┘ └─────────┘
(ASAP scheduled)
┌────────────────┐ ┌───┐
q_0: ┤ Delay(100[dt]) ├───┤ X ├──────────────
├────────────────┤ └─╥─┘ ┌───┐
q_1: ┤ Delay(100[dt]) ├─────╫────────┤ X ├───
└────────────────┘ ║ └─╥─┘
┌────╨────┐┌────╨────┐
c: 1/══════════════════╡ c_0=0x1 ╞╡ c_0=0x1 ╞
└─────────┘└─────────┘
"""
qc = QuantumCircuit(2, 1)
qc.delay(100, 0)
qc.x(0).c_if(0, True)
qc.x(1).c_if(0, True)
durations = InstructionDurations([("x", None, 160)])
pm = PassManager(ASAPSchedule(durations))
scheduled = pm.run(qc)
expected = QuantumCircuit(2, 1)
expected.delay(100, 0)
expected.delay(100, 1) # due to extra dependency on clbits
expected.x(0).c_if(0, True)
expected.x(1).c_if(0, True)
self.assertEqual(expected, scheduled)
@data(ALAPSchedule, ASAPSchedule)
def test_respect_target_instruction_constraints(self, schedule_pass):
"""Test if ALAP/ASAP does not pad delays for qubits that do not support delay instructions.
See: https://github.com/Qiskit/qiskit-terra/issues/9993
"""
target = Target(dt=1)
target.add_instruction(XGate(), {(1,): InstructionProperties(duration=200)})
# delays are not supported
qc = QuantumCircuit(2)
qc.x(1)
pm = PassManager(schedule_pass(target=target))
scheduled = pm.run(qc)
expected = QuantumCircuit(2)
expected.x(1)
# no delay on qubit 0
self.assertEqual(expected, scheduled)
def test_dd_respect_target_instruction_constraints(self):
"""Test if DD pass does not pad delays for qubits that do not support delay instructions
and does not insert DD gates for qubits that do not support necessary gates.
See: https://github.com/Qiskit/qiskit-terra/issues/9993
"""
qc = QuantumCircuit(3)
qc.cx(0, 1)
qc.cx(1, 2)
target = Target(dt=1)
# Y is partially supported (not supported on qubit 2)
target.add_instruction(
XGate(), {(q,): InstructionProperties(duration=100) for q in range(2)}
)
target.add_instruction(
CXGate(),
{
(0, 1): InstructionProperties(duration=1000),
(1, 2): InstructionProperties(duration=1000),
},
)
# delays are not supported
# No DD instructions nor delays are padded due to no delay support in the target
pm_xx = PassManager(
[
ALAPSchedule(target=target),
DynamicalDecoupling(durations=None, dd_sequence=[XGate(), XGate()], target=target),
]
)
scheduled = pm_xx.run(qc)
self.assertEqual(qc, scheduled)
# Fails since Y is not supported in the target
with self.assertRaises(TranspilerError):
PassManager(
[
ALAPSchedule(target=target),
DynamicalDecoupling(
durations=None,
dd_sequence=[XGate(), YGate(), XGate(), YGate()],
target=target,
),
]
)
# Add delay support to the target
target.add_instruction(Delay(Parameter("t")), {(q,): None for q in range(3)})
# No error but no DD on qubit 2 (just delay is padded) since X is not supported on it
scheduled = pm_xx.run(qc)
expected = QuantumCircuit(3)
expected.delay(1000, [2])
expected.cx(0, 1)
expected.cx(1, 2)
expected.delay(200, [0])
expected.x([0])
expected.delay(400, [0])
expected.x([0])
expected.delay(200, [0])
self.assertEqual(expected, scheduled)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021, 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=invalid-name
"""
Test of measurement calibration:
1) Preparation of the basis states, generating the calibration circuits
(without noise), computing the calibration matrices,
and validating that they equal
to the identity matrices
2) Generating ideal (equally distributed) results, computing
the calibration output (without noise),
and validating that it is equally distributed
3) Testing the the measurement calibration on a circuit
(without noise), verifying that it is close to the
expected (equally distributed) result
4) Testing the fitters on pre-generated data with noise
"""
import unittest
import numpy as np
import qiskit
from qiskit.test import QiskitTestCase
from qiskit.result.result import Result
from qiskit.utils.mitigation import (
CompleteMeasFitter,
TensoredMeasFitter,
complete_meas_cal,
tensored_meas_cal,
)
from qiskit.utils.mitigation._filters import MeasurementFilter
from qiskit.utils.mitigation.circuits import count_keys
from qiskit.utils import optionals
if optionals.HAS_AER:
# pylint: disable=no-name-in-module
from qiskit_aer import AerSimulator
from qiskit_aer.noise import NoiseModel
from qiskit_aer.noise.errors.standard_errors import pauli_error
# fixed seed for tests - for both simulator and transpiler
SEED = 42
def convert_ndarray_to_list_in_data(data: np.ndarray):
"""
converts ndarray format into list format (keeps all the dicts in the array)
also convert inner ndarrays into lists (recursively)
Args:
data: ndarray containing dicts or ndarrays in it
Returns:
list: same array, converted to list format (in order to save it as json)
"""
new_data = []
for item in data:
if isinstance(item, np.ndarray):
new_item = convert_ndarray_to_list_in_data(item)
elif isinstance(item, dict):
new_item = {}
for key, value in item.items():
new_item[key] = value.tolist()
else:
new_item = item
new_data.append(new_item)
return new_data
def meas_calib_circ_creation():
"""
create measurement calibration circuits and a GHZ state circuit for the tests
Returns:
QuantumCircuit: the measurement calibrations circuits
list[str]: the mitigation pattern
QuantumCircuit: ghz circuit with 5 qubits (3 are used)
"""
qubit_list = [1, 2, 3]
total_number_of_qubit = 5
meas_calibs, state_labels = complete_meas_cal(qubit_list=qubit_list, qr=total_number_of_qubit)
# Choose 3 qubits
qubit_1 = qubit_list[0]
qubit_2 = qubit_list[1]
qubit_3 = qubit_list[2]
ghz = qiskit.QuantumCircuit(total_number_of_qubit, len(qubit_list))
ghz.h(qubit_1)
ghz.cx(qubit_1, qubit_2)
ghz.cx(qubit_1, qubit_3)
for i in qubit_list:
ghz.measure(i, i - 1)
return meas_calibs, state_labels, ghz
def tensored_calib_circ_creation():
"""
create tensored measurement calibration circuits and a GHZ state circuit for the tests
Returns:
QuantumCircuit: the tensored measurement calibration circuit
list[list[int]]: the mitigation pattern
QuantumCircuit: ghz circuit with 5 qubits (3 are used)
"""
mit_pattern = [[2], [4, 1]]
meas_layout = [2, 4, 1]
qr = qiskit.QuantumRegister(5)
# Generate the calibration circuits
meas_calibs, mit_pattern = tensored_meas_cal(mit_pattern, qr=qr)
cr = qiskit.ClassicalRegister(3)
ghz_circ = qiskit.QuantumCircuit(qr, cr)
ghz_circ.h(mit_pattern[0][0])
ghz_circ.cx(mit_pattern[0][0], mit_pattern[1][0])
ghz_circ.cx(mit_pattern[0][0], mit_pattern[1][1])
ghz_circ.measure(mit_pattern[0][0], cr[0])
ghz_circ.measure(mit_pattern[1][0], cr[1])
ghz_circ.measure(mit_pattern[1][1], cr[2])
return meas_calibs, mit_pattern, ghz_circ, meas_layout
def meas_calibration_circ_execution(shots: int, seed: int):
"""
create measurement calibration circuits and simulate them with noise
Args:
shots (int): number of shots per simulation
seed (int): the seed to use in the simulations
Returns:
list: list of Results of the measurement calibration simulations
list: list of all the possible states with this amount of qubits
dict: dictionary of results counts of GHZ circuit simulation with measurement errors
"""
# define the circuits
meas_calibs, state_labels, ghz = meas_calib_circ_creation()
# define noise
prob = 0.2
error_meas = pauli_error([("X", prob), ("I", 1 - prob)])
noise_model = NoiseModel()
noise_model.add_all_qubit_quantum_error(error_meas, "measure")
# run the circuits multiple times
backend = AerSimulator()
cal_results = qiskit.execute(
meas_calibs, backend=backend, shots=shots, noise_model=noise_model, seed_simulator=seed
).result()
ghz_results = (
qiskit.execute(
ghz, backend=backend, shots=shots, noise_model=noise_model, seed_simulator=seed
)
.result()
.get_counts()
)
return cal_results, state_labels, ghz_results
def tensored_calib_circ_execution(shots: int, seed: int):
"""
create tensored measurement calibration circuits and simulate them with noise
Args:
shots (int): number of shots per simulation
seed (int): the seed to use in the simulations
Returns:
list: list of Results of the measurement calibration simulations
list: the mitigation pattern
dict: dictionary of results counts of GHZ circuit simulation with measurement errors
"""
# define the circuits
meas_calibs, mit_pattern, ghz_circ, meas_layout = tensored_calib_circ_creation()
# define noise
prob = 0.2
error_meas = pauli_error([("X", prob), ("I", 1 - prob)])
noise_model = NoiseModel()
noise_model.add_all_qubit_quantum_error(error_meas, "measure")
# run the circuits multiple times
backend = AerSimulator()
cal_results = qiskit.execute(
meas_calibs, backend=backend, shots=shots, noise_model=noise_model, seed_simulator=seed
).result()
ghz_results = qiskit.execute(
ghz_circ, backend=backend, shots=shots, noise_model=noise_model, seed_simulator=seed
).result()
return cal_results, mit_pattern, ghz_results, meas_layout
@unittest.skipUnless(optionals.HAS_AER, "Qiskit aer is required to run these tests")
class TestMeasCal(QiskitTestCase):
"""The test class."""
def setUp(self):
super().setUp()
self.nq_list = [1, 2, 3, 4, 5] # Test up to 5 qubits
self.shots = 1024 # Number of shots (should be a power of 2)
@staticmethod
def choose_calibration(nq, pattern_type):
"""
Generate a calibration circuit
Args:
nq (int): number of qubits
pattern_type (int): a pattern in range(1, 2**nq)
Returns:
qubits: a list of qubits according to the given pattern
weight: the weight of the pattern_type,
equals to the number of qubits
Additional Information:
qr[i] exists if and only if the i-th bit in the binary
expression of
pattern_type equals 1
"""
qubits = []
weight = 0
for i in range(nq):
pattern_bit = pattern_type & 1
pattern_type = pattern_type >> 1
if pattern_bit == 1:
qubits.append(i)
weight += 1
return qubits, weight
def generate_ideal_results(self, state_labels, weight):
"""
Generate ideal equally distributed results
Args:
state_labels (list): a list of calibration state labels
weight (int): the number of qubits
Returns:
results_dict: a dictionary of equally distributed results
results_list: a list of equally distributed results
Additional Information:
for each state in state_labels:
result_dict[state] = #shots/len(state_labels)
"""
results_dict = {}
results_list = [0] * (2**weight)
state_num = len(state_labels)
for state in state_labels:
shots_per_state = self.shots / state_num
results_dict[state] = shots_per_state
# converting state (binary) to an integer
place = int(state, 2)
results_list[place] = shots_per_state
return results_dict, results_list
def test_ideal_meas_cal(self):
"""Test ideal execution, without noise."""
for nq in self.nq_list:
for pattern_type in range(1, 2**nq):
# Generate the quantum register according to the pattern
qubits, weight = self.choose_calibration(nq, pattern_type)
with self.assertWarns(DeprecationWarning):
# Generate the calibration circuits
meas_calibs, state_labels = complete_meas_cal(
qubit_list=qubits, circlabel="test"
)
# Perform an ideal execution on the generated circuits
backend = AerSimulator()
job = qiskit.execute(meas_calibs, backend=backend, shots=self.shots)
cal_results = job.result()
with self.assertWarns(DeprecationWarning):
# Make a calibration matrix
meas_cal = CompleteMeasFitter(cal_results, state_labels, circlabel="test")
# Assert that the calibration matrix is equal to identity
IdentityMatrix = np.identity(2**weight)
self.assertListEqual(
meas_cal.cal_matrix.tolist(),
IdentityMatrix.tolist(),
"Error: the calibration matrix is not equal to identity",
)
# Assert that the readout fidelity is equal to 1
self.assertEqual(
meas_cal.readout_fidelity(),
1.0,
"Error: the average fidelity is not equal to 1",
)
# Generate ideal (equally distributed) results
results_dict, results_list = self.generate_ideal_results(state_labels, weight)
with self.assertWarns(DeprecationWarning):
# Output the filter
meas_filter = meas_cal.filter
# Apply the calibration matrix to results
# in list and dict forms using different methods
results_dict_1 = meas_filter.apply(results_dict, method="least_squares")
results_dict_0 = meas_filter.apply(results_dict, method="pseudo_inverse")
results_list_1 = meas_filter.apply(results_list, method="least_squares")
results_list_0 = meas_filter.apply(results_list, method="pseudo_inverse")
# Assert that the results are equally distributed
self.assertListEqual(results_list, results_list_0.tolist())
self.assertListEqual(results_list, np.round(results_list_1).tolist())
self.assertDictEqual(results_dict, results_dict_0)
round_results = {}
for key, val in results_dict_1.items():
round_results[key] = np.round(val)
self.assertDictEqual(results_dict, round_results)
def test_meas_cal_on_circuit(self):
"""Test an execution on a circuit."""
# Generate the calibration circuits
with self.assertWarns(DeprecationWarning):
meas_calibs, state_labels, ghz = meas_calib_circ_creation()
# Run the calibration circuits
backend = AerSimulator()
job = qiskit.execute(
meas_calibs,
backend=backend,
shots=self.shots,
seed_simulator=SEED,
seed_transpiler=SEED,
)
cal_results = job.result()
with self.assertWarns(DeprecationWarning):
# Make a calibration matrix
meas_cal = CompleteMeasFitter(cal_results, state_labels)
# Calculate the fidelity
fidelity = meas_cal.readout_fidelity()
job = qiskit.execute(
[ghz], backend=backend, shots=self.shots, seed_simulator=SEED, seed_transpiler=SEED
)
results = job.result()
# Predicted equally distributed results
predicted_results = {"000": 0.5, "111": 0.5}
with self.assertWarns(DeprecationWarning):
meas_filter = meas_cal.filter
# Calculate the results after mitigation
output_results_pseudo_inverse = meas_filter.apply(
results, method="pseudo_inverse"
).get_counts(0)
output_results_least_square = meas_filter.apply(results, method="least_squares").get_counts(
0
)
# Compare with expected fidelity and expected results
self.assertAlmostEqual(fidelity, 1.0)
self.assertAlmostEqual(
output_results_pseudo_inverse["000"] / self.shots, predicted_results["000"], places=1
)
self.assertAlmostEqual(
output_results_least_square["000"] / self.shots, predicted_results["000"], places=1
)
self.assertAlmostEqual(
output_results_pseudo_inverse["111"] / self.shots, predicted_results["111"], places=1
)
self.assertAlmostEqual(
output_results_least_square["111"] / self.shots, predicted_results["111"], places=1
)
def test_ideal_tensored_meas_cal(self):
"""Test ideal execution, without noise."""
mit_pattern = [[1, 2], [3, 4, 5], [6]]
meas_layout = [1, 2, 3, 4, 5, 6]
# Generate the calibration circuits
with self.assertWarns(DeprecationWarning):
meas_calibs, _ = tensored_meas_cal(mit_pattern=mit_pattern)
# Perform an ideal execution on the generated circuits
backend = AerSimulator()
cal_results = qiskit.execute(meas_calibs, backend=backend, shots=self.shots).result()
with self.assertWarns(DeprecationWarning):
# Make calibration matrices
meas_cal = TensoredMeasFitter(cal_results, mit_pattern=mit_pattern)
# Assert that the calibration matrices are equal to identity
cal_matrices = meas_cal.cal_matrices
self.assertEqual(
len(mit_pattern), len(cal_matrices), "Wrong number of calibration matrices"
)
for qubit_list, cal_mat in zip(mit_pattern, cal_matrices):
IdentityMatrix = np.identity(2 ** len(qubit_list))
self.assertListEqual(
cal_mat.tolist(),
IdentityMatrix.tolist(),
"Error: the calibration matrix is not equal to identity",
)
# Assert that the readout fidelity is equal to 1
self.assertEqual(
meas_cal.readout_fidelity(),
1.0,
"Error: the average fidelity is not equal to 1",
)
with self.assertWarns(DeprecationWarning):
# Generate ideal (equally distributed) results
results_dict, _ = self.generate_ideal_results(count_keys(6), 6)
# Output the filter
meas_filter = meas_cal.filter
# Apply the calibration matrix to results
# in list and dict forms using different methods
results_dict_1 = meas_filter.apply(
results_dict, method="least_squares", meas_layout=meas_layout
)
results_dict_0 = meas_filter.apply(
results_dict, method="pseudo_inverse", meas_layout=meas_layout
)
# Assert that the results are equally distributed
self.assertDictEqual(results_dict, results_dict_0)
round_results = {}
for key, val in results_dict_1.items():
round_results[key] = np.round(val)
self.assertDictEqual(results_dict, round_results)
def test_tensored_meas_cal_on_circuit(self):
"""Test an execution on a circuit."""
with self.assertWarns(DeprecationWarning):
# Generate the calibration circuits
meas_calibs, mit_pattern, ghz, meas_layout = tensored_calib_circ_creation()
# Run the calibration circuits
backend = AerSimulator()
cal_results = qiskit.execute(
meas_calibs,
backend=backend,
shots=self.shots,
seed_simulator=SEED,
seed_transpiler=SEED,
).result()
with self.assertWarns(DeprecationWarning):
# Make a calibration matrix
meas_cal = TensoredMeasFitter(cal_results, mit_pattern=mit_pattern)
# Calculate the fidelity
fidelity = meas_cal.readout_fidelity(0) * meas_cal.readout_fidelity(1)
results = qiskit.execute(
[ghz], backend=backend, shots=self.shots, seed_simulator=SEED, seed_transpiler=SEED
).result()
# Predicted equally distributed results
predicted_results = {"000": 0.5, "111": 0.5}
with self.assertWarns(DeprecationWarning):
meas_filter = meas_cal.filter
# Calculate the results after mitigation
output_results_pseudo_inverse = meas_filter.apply(
results, method="pseudo_inverse", meas_layout=meas_layout
).get_counts(0)
output_results_least_square = meas_filter.apply(
results, method="least_squares", meas_layout=meas_layout
).get_counts(0)
# Compare with expected fidelity and expected results
self.assertAlmostEqual(fidelity, 1.0)
self.assertAlmostEqual(
output_results_pseudo_inverse["000"] / self.shots, predicted_results["000"], places=1
)
self.assertAlmostEqual(
output_results_least_square["000"] / self.shots, predicted_results["000"], places=1
)
self.assertAlmostEqual(
output_results_pseudo_inverse["111"] / self.shots, predicted_results["111"], places=1
)
self.assertAlmostEqual(
output_results_least_square["111"] / self.shots, predicted_results["111"], places=1
)
def test_meas_fitter_with_noise(self):
"""Test the MeasurementFitter with noise."""
tests = []
runs = 3
with self.assertWarns(DeprecationWarning):
for run in range(runs):
cal_results, state_labels, circuit_results = meas_calibration_circ_execution(
1000, SEED + run
)
meas_cal = CompleteMeasFitter(cal_results, state_labels)
meas_filter = MeasurementFilter(meas_cal.cal_matrix, state_labels)
# Calculate the results after mitigation
results_pseudo_inverse = meas_filter.apply(circuit_results, method="pseudo_inverse")
results_least_square = meas_filter.apply(circuit_results, method="least_squares")
tests.append(
{
"cal_matrix": convert_ndarray_to_list_in_data(meas_cal.cal_matrix),
"fidelity": meas_cal.readout_fidelity(),
"results": circuit_results,
"results_pseudo_inverse": results_pseudo_inverse,
"results_least_square": results_least_square,
}
)
# Set the state labels
state_labels = ["000", "001", "010", "011", "100", "101", "110", "111"]
meas_cal = CompleteMeasFitter(None, state_labels, circlabel="test")
for tst_index, _ in enumerate(tests):
# Set the calibration matrix
meas_cal.cal_matrix = tests[tst_index]["cal_matrix"]
# Calculate the fidelity
fidelity = meas_cal.readout_fidelity()
meas_filter = MeasurementFilter(tests[tst_index]["cal_matrix"], state_labels)
# Calculate the results after mitigation
output_results_pseudo_inverse = meas_filter.apply(
tests[tst_index]["results"], method="pseudo_inverse"
)
output_results_least_square = meas_filter.apply(
tests[tst_index]["results"], method="least_squares"
)
# Compare with expected fidelity and expected results
self.assertAlmostEqual(fidelity, tests[tst_index]["fidelity"], places=0)
self.assertAlmostEqual(
output_results_pseudo_inverse["000"],
tests[tst_index]["results_pseudo_inverse"]["000"],
places=0,
)
self.assertAlmostEqual(
output_results_least_square["000"],
tests[tst_index]["results_least_square"]["000"],
places=0,
)
self.assertAlmostEqual(
output_results_pseudo_inverse["111"],
tests[tst_index]["results_pseudo_inverse"]["111"],
places=0,
)
self.assertAlmostEqual(
output_results_least_square["111"],
tests[tst_index]["results_least_square"]["111"],
places=0,
)
def test_tensored_meas_fitter_with_noise(self):
"""Test the TensoredFitter with noise."""
with self.assertWarns(DeprecationWarning):
cal_results, mit_pattern, circuit_results, meas_layout = tensored_calib_circ_execution(
1000, SEED
)
meas_cal = TensoredMeasFitter(cal_results, mit_pattern=mit_pattern)
meas_filter = meas_cal.filter
# Calculate the results after mitigation
results_pseudo_inverse = meas_filter.apply(
circuit_results.get_counts(), method="pseudo_inverse", meas_layout=meas_layout
)
results_least_square = meas_filter.apply(
circuit_results.get_counts(), method="least_squares", meas_layout=meas_layout
)
saved_info = {
"cal_results": cal_results.to_dict(),
"results": circuit_results.to_dict(),
"mit_pattern": mit_pattern,
"meas_layout": meas_layout,
"fidelity": meas_cal.readout_fidelity(),
"results_pseudo_inverse": results_pseudo_inverse,
"results_least_square": results_least_square,
}
saved_info["cal_results"] = Result.from_dict(saved_info["cal_results"])
saved_info["results"] = Result.from_dict(saved_info["results"])
with self.assertWarns(DeprecationWarning):
meas_cal = TensoredMeasFitter(
saved_info["cal_results"], mit_pattern=saved_info["mit_pattern"]
)
# Calculate the fidelity
fidelity = meas_cal.readout_fidelity(0) * meas_cal.readout_fidelity(1)
# Compare with expected fidelity and expected results
self.assertAlmostEqual(fidelity, saved_info["fidelity"], places=0)
with self.assertWarns(DeprecationWarning):
meas_filter = meas_cal.filter
# Calculate the results after mitigation
output_results_pseudo_inverse = meas_filter.apply(
saved_info["results"].get_counts(0),
method="pseudo_inverse",
meas_layout=saved_info["meas_layout"],
)
output_results_least_square = meas_filter.apply(
saved_info["results"], method="least_squares", meas_layout=saved_info["meas_layout"]
)
self.assertAlmostEqual(
output_results_pseudo_inverse["000"],
saved_info["results_pseudo_inverse"]["000"],
places=0,
)
self.assertAlmostEqual(
output_results_least_square.get_counts(0)["000"],
saved_info["results_least_square"]["000"],
places=0,
)
self.assertAlmostEqual(
output_results_pseudo_inverse["111"],
saved_info["results_pseudo_inverse"]["111"],
places=0,
)
self.assertAlmostEqual(
output_results_least_square.get_counts(0)["111"],
saved_info["results_least_square"]["111"],
places=0,
)
substates_list = []
with self.assertWarns(DeprecationWarning):
for qubit_list in saved_info["mit_pattern"]:
substates_list.append(count_keys(len(qubit_list))[::-1])
fitter_other_order = TensoredMeasFitter(
saved_info["cal_results"],
substate_labels_list=substates_list,
mit_pattern=saved_info["mit_pattern"],
)
fidelity = fitter_other_order.readout_fidelity(0) * meas_cal.readout_fidelity(1)
self.assertAlmostEqual(fidelity, saved_info["fidelity"], places=0)
with self.assertWarns(DeprecationWarning):
meas_filter = fitter_other_order.filter
# Calculate the results after mitigation
output_results_pseudo_inverse = meas_filter.apply(
saved_info["results"].get_counts(0),
method="pseudo_inverse",
meas_layout=saved_info["meas_layout"],
)
output_results_least_square = meas_filter.apply(
saved_info["results"], method="least_squares", meas_layout=saved_info["meas_layout"]
)
self.assertAlmostEqual(
output_results_pseudo_inverse["000"],
saved_info["results_pseudo_inverse"]["000"],
places=0,
)
self.assertAlmostEqual(
output_results_least_square.get_counts(0)["000"],
saved_info["results_least_square"]["000"],
places=0,
)
self.assertAlmostEqual(
output_results_pseudo_inverse["111"],
saved_info["results_pseudo_inverse"]["111"],
places=0,
)
self.assertAlmostEqual(
output_results_least_square.get_counts(0)["111"],
saved_info["results_least_square"]["111"],
places=0,
)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=missing-docstring
import unittest
import os
from unittest.mock import patch
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.test import QiskitTestCase
from qiskit.utils import optionals
from qiskit import visualization
from qiskit.visualization.circuit import text
from qiskit.visualization.exceptions import VisualizationError
if optionals.HAS_MATPLOTLIB:
from matplotlib import figure
if optionals.HAS_PIL:
from PIL import Image
_latex_drawer_condition = unittest.skipUnless(
all(
(
optionals.HAS_PYLATEX,
optionals.HAS_PIL,
optionals.HAS_PDFLATEX,
optionals.HAS_PDFTOCAIRO,
)
),
"Skipped because not all of PIL, pylatex, pdflatex and pdftocairo are available",
)
class TestCircuitDrawer(QiskitTestCase):
def test_default_output(self):
with patch("qiskit.user_config.get_config", return_value={}):
circuit = QuantumCircuit()
out = visualization.circuit_drawer(circuit)
self.assertIsInstance(out, text.TextDrawing)
@unittest.skipUnless(optionals.HAS_MATPLOTLIB, "Skipped because matplotlib is not available")
def test_user_config_default_output(self):
with patch("qiskit.user_config.get_config", return_value={"circuit_drawer": "mpl"}):
circuit = QuantumCircuit()
out = visualization.circuit_drawer(circuit)
self.assertIsInstance(out, figure.Figure)
def test_default_output_with_user_config_not_set(self):
with patch("qiskit.user_config.get_config", return_value={"other_option": True}):
circuit = QuantumCircuit()
out = visualization.circuit_drawer(circuit)
self.assertIsInstance(out, text.TextDrawing)
@unittest.skipUnless(optionals.HAS_MATPLOTLIB, "Skipped because matplotlib is not available")
def test_kwarg_priority_over_user_config_default_output(self):
with patch("qiskit.user_config.get_config", return_value={"circuit_drawer": "latex"}):
circuit = QuantumCircuit()
out = visualization.circuit_drawer(circuit, output="mpl")
self.assertIsInstance(out, figure.Figure)
@unittest.skipUnless(optionals.HAS_MATPLOTLIB, "Skipped because matplotlib is not available")
def test_default_backend_auto_output_with_mpl(self):
with patch("qiskit.user_config.get_config", return_value={"circuit_drawer": "auto"}):
circuit = QuantumCircuit()
out = visualization.circuit_drawer(circuit)
self.assertIsInstance(out, figure.Figure)
def test_default_backend_auto_output_without_mpl(self):
with patch("qiskit.user_config.get_config", return_value={"circuit_drawer": "auto"}):
with optionals.HAS_MATPLOTLIB.disable_locally():
circuit = QuantumCircuit()
out = visualization.circuit_drawer(circuit)
self.assertIsInstance(out, text.TextDrawing)
@_latex_drawer_condition
def test_latex_unsupported_image_format_error_message(self):
with patch("qiskit.user_config.get_config", return_value={"circuit_drawer": "latex"}):
circuit = QuantumCircuit()
with self.assertRaises(VisualizationError, msg="Pillow could not write the image file"):
visualization.circuit_drawer(circuit, filename="file.spooky")
@_latex_drawer_condition
def test_latex_output_file_correct_format(self):
with patch("qiskit.user_config.get_config", return_value={"circuit_drawer": "latex"}):
circuit = QuantumCircuit()
filename = "file.gif"
visualization.circuit_drawer(circuit, filename=filename)
with Image.open(filename) as im:
if filename.endswith("jpg"):
self.assertIn(im.format.lower(), "jpeg")
else:
self.assertIn(im.format.lower(), filename.split(".")[-1])
os.remove(filename)
def test_wire_order(self):
"""Test wire_order
See: https://github.com/Qiskit/qiskit-terra/pull/9893"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(4, "c")
cr2 = ClassicalRegister(2, "ca")
circuit = QuantumCircuit(qr, cr, cr2)
circuit.h(0)
circuit.h(3)
circuit.x(1)
circuit.x(3).c_if(cr, 10)
expected = "\n".join(
[
" ",
" q_2: ────────────",
" ┌───┐ ┌───┐ ",
" q_3: ┤ H ├─┤ X ├─",
" ├───┤ └─╥─┘ ",
" q_0: ┤ H ├───╫───",
" ├───┤ ║ ",
" q_1: ┤ X ├───╫───",
" └───┘┌──╨──┐",
" c: 4/═════╡ 0xa ╞",
" └─────┘",
"ca: 2/════════════",
" ",
]
)
result = visualization.circuit_drawer(circuit, wire_order=[2, 3, 0, 1])
self.assertEqual(result.__str__(), expected)
def test_wire_order_cregbundle(self):
"""Test wire_order with cregbundle=True
See: https://github.com/Qiskit/qiskit-terra/pull/9893"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(4, "c")
cr2 = ClassicalRegister(2, "ca")
circuit = QuantumCircuit(qr, cr, cr2)
circuit.h(0)
circuit.h(3)
circuit.x(1)
circuit.x(3).c_if(cr, 10)
expected = "\n".join(
[
" ",
" q_2: ────────────",
" ┌───┐ ┌───┐ ",
" q_3: ┤ H ├─┤ X ├─",
" ├───┤ └─╥─┘ ",
" q_0: ┤ H ├───╫───",
" ├───┤ ║ ",
" q_1: ┤ X ├───╫───",
" └───┘┌──╨──┐",
" c: 4/═════╡ 0xa ╞",
" └─────┘",
"ca: 2/════════════",
" ",
]
)
result = visualization.circuit_drawer(circuit, wire_order=[2, 3, 0, 1], cregbundle=True)
self.assertEqual(result.__str__(), expected)
def test_wire_order_raises(self):
"""Verify we raise if using wire order incorrectly."""
circuit = QuantumCircuit(3, 3)
circuit.x(1)
with self.assertRaisesRegex(VisualizationError, "should not have repeated elements"):
visualization.circuit_drawer(circuit, wire_order=[2, 1, 0, 3, 1, 5])
with self.assertRaisesRegex(VisualizationError, "cannot be set when the reverse_bits"):
visualization.circuit_drawer(circuit, wire_order=[0, 1, 2, 5, 4, 3], reverse_bits=True)
with self.assertWarnsRegex(RuntimeWarning, "cregbundle set"):
visualization.circuit_drawer(circuit, cregbundle=True, wire_order=[0, 1, 2, 5, 4, 3])
def test_reverse_bits(self):
"""Test reverse_bits should not raise warnings when no classical qubits:
See: https://github.com/Qiskit/qiskit-terra/pull/8689"""
circuit = QuantumCircuit(3)
circuit.x(1)
expected = "\n".join(
[
" ",
"q_2: ─────",
" ┌───┐",
"q_1: ┤ X ├",
" └───┘",
"q_0: ─────",
" ",
]
)
result = visualization.circuit_drawer(circuit, output="text", reverse_bits=True)
self.assertEqual(result.__str__(), expected)
@unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc for LaTeX conversion")
def test_no_explict_cregbundle(self):
"""Test no explicit cregbundle should not raise warnings about being disabled
See: https://github.com/Qiskit/qiskit-terra/issues/8690"""
inner = QuantumCircuit(1, 1, name="inner")
inner.measure(0, 0)
circuit = QuantumCircuit(2, 2)
circuit.append(inner, [0], [0])
expected = "\n".join(
[
" ┌────────┐",
"q_0: ┤0 ├",
" │ │",
"q_1: ┤ inner ├",
" │ │",
"c_0: ╡0 ╞",
" └────────┘",
"c_1: ══════════",
" ",
]
)
result = circuit.draw("text")
self.assertEqual(result.__str__(), expected)
# Extra tests that no cregbundle (or any other) warning is raised with the default settings
# for the other drawers, if they're available to test.
circuit.draw("latex_source")
if optionals.HAS_MATPLOTLIB and optionals.HAS_PYLATEX:
circuit.draw("mpl")
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for visualization of circuit with Latex drawer."""
import os
import unittest
import math
import numpy as np
from qiskit.visualization import circuit_drawer
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, transpile
from qiskit.providers.fake_provider import FakeTenerife
from qiskit.circuit.library import XGate, MCXGate, RZZGate, SwapGate, DCXGate, CPhaseGate
from qiskit.extensions import HamiltonianGate
from qiskit.circuit import Parameter, Qubit, Clbit
from qiskit.circuit.library import IQP
from qiskit.quantum_info.random import random_unitary
from qiskit.utils import optionals
from .visualization import QiskitVisualizationTestCase
pi = np.pi
@unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc")
class TestLatexSourceGenerator(QiskitVisualizationTestCase):
"""Qiskit latex source generator tests."""
def _get_resource_path(self, filename):
reference_dir = os.path.dirname(os.path.abspath(__file__))
return os.path.join(reference_dir, filename)
def test_empty_circuit(self):
"""Test draw an empty circuit"""
filename = self._get_resource_path("test_latex_empty.tex")
circuit = QuantumCircuit(1)
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_tiny_circuit(self):
"""Test draw tiny circuit."""
filename = self._get_resource_path("test_latex_tiny.tex")
circuit = QuantumCircuit(1)
circuit.h(0)
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_multi_underscore_reg_names(self):
"""Test multi-underscores in register names display properly"""
filename1 = self._get_resource_path("test_latex_multi_underscore_true.tex")
filename2 = self._get_resource_path("test_latex_multi_underscore_false.tex")
q_reg1 = QuantumRegister(1, "q1_re__g__g")
q_reg3 = QuantumRegister(3, "q3_re_g__g")
c_reg1 = ClassicalRegister(1, "c1_re_g__g")
c_reg3 = ClassicalRegister(3, "c3_re_g__g")
circuit = QuantumCircuit(q_reg1, q_reg3, c_reg1, c_reg3)
circuit_drawer(circuit, cregbundle=True, filename=filename1, output="latex_source")
circuit_drawer(circuit, cregbundle=False, filename=filename2, output="latex_source")
self.assertEqualToReference(filename1)
self.assertEqualToReference(filename2)
def test_normal_circuit(self):
"""Test draw normal size circuit."""
filename = self._get_resource_path("test_latex_normal.tex")
circuit = QuantumCircuit(5)
for qubit in range(5):
circuit.h(qubit)
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_4597(self):
"""Test cregbundle and conditional gates.
See: https://github.com/Qiskit/qiskit-terra/pull/4597"""
filename = self._get_resource_path("test_latex_4597.tex")
qr = QuantumRegister(3, "q")
cr = ClassicalRegister(3, "c")
circuit = QuantumCircuit(qr, cr)
circuit.x(qr[2]).c_if(cr, 2)
circuit.draw(output="latex_source", cregbundle=True)
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_deep_circuit(self):
"""Test draw deep circuit."""
filename = self._get_resource_path("test_latex_deep.tex")
circuit = QuantumCircuit(1)
for _ in range(100):
circuit.h(0)
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_huge_circuit(self):
"""Test draw huge circuit."""
filename = self._get_resource_path("test_latex_huge.tex")
circuit = QuantumCircuit(40)
for qubit in range(39):
circuit.h(qubit)
circuit.cx(qubit, 39)
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_teleport(self):
"""Test draw teleport circuit."""
filename = self._get_resource_path("test_latex_teleport.tex")
qr = QuantumRegister(3, "q")
cr = ClassicalRegister(3, "c")
circuit = QuantumCircuit(qr, cr)
# Prepare an initial state
circuit.u(0.3, 0.2, 0.1, [qr[0]])
# Prepare a Bell pair
circuit.h(qr[1])
circuit.cx(qr[1], qr[2])
# Barrier following state preparation
circuit.barrier(qr)
# Measure in the Bell basis
circuit.cx(qr[0], qr[1])
circuit.h(qr[0])
circuit.measure(qr[0], cr[0])
circuit.measure(qr[1], cr[1])
# Apply a correction
circuit.z(qr[2]).c_if(cr, 1)
circuit.x(qr[2]).c_if(cr, 2)
circuit.measure(qr[2], cr[2])
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_global_phase(self):
"""Test circuit with global phase"""
filename = self._get_resource_path("test_latex_global_phase.tex")
circuit = QuantumCircuit(3, global_phase=1.57079632679)
circuit.h(range(3))
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_no_ops(self):
"""Test circuit with no ops.
See https://github.com/Qiskit/qiskit-terra/issues/5393"""
filename = self._get_resource_path("test_latex_no_ops.tex")
circuit = QuantumCircuit(2, 3)
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_long_name(self):
"""Test to see that long register names can be seen completely
As reported in #2605
"""
filename = self._get_resource_path("test_latex_long_name.tex")
# add a register with a very long name
qr = QuantumRegister(4, "veryLongQuantumRegisterName")
# add another to make sure adjustments are made based on longest
qrr = QuantumRegister(1, "q0")
circuit = QuantumCircuit(qr, qrr)
# check gates are shifted over accordingly
circuit.h(qr)
circuit.h(qr)
circuit.h(qr)
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_conditional(self):
"""Test that circuits with conditionals draw correctly"""
filename = self._get_resource_path("test_latex_conditional.tex")
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
circuit = QuantumCircuit(qr, cr)
# check gates are shifted over accordingly
circuit.h(qr)
circuit.measure(qr, cr)
circuit.h(qr[0]).c_if(cr, 2)
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_plot_partial_barrier(self):
"""Test plotting of partial barriers."""
filename = self._get_resource_path("test_latex_plot_partial_barriers.tex")
# generate a circuit with barrier and other barrier like instructions in
q = QuantumRegister(2, "q")
c = ClassicalRegister(2, "c")
circuit = QuantumCircuit(q, c)
# check for barriers
circuit.h(q[0])
circuit.barrier(0)
circuit.h(q[0])
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_plot_barriers(self):
"""Test to see that plotting barriers works.
If it is set to False, no blank columns are introduced"""
filename1 = self._get_resource_path("test_latex_plot_barriers_true.tex")
filename2 = self._get_resource_path("test_latex_plot_barriers_false.tex")
# generate a circuit with barriers and other barrier like instructions in
q = QuantumRegister(2, "q")
c = ClassicalRegister(2, "c")
circuit = QuantumCircuit(q, c)
# check for barriers
circuit.h(q[0])
circuit.barrier()
# check for other barrier like commands
circuit.h(q[1])
# this import appears to be unused, but is actually needed to get snapshot instruction
import qiskit.extensions.simulator # pylint: disable=unused-import
circuit.snapshot("sn 1")
# check the barriers plot properly when plot_barriers= True
circuit_drawer(circuit, filename=filename1, output="latex_source", plot_barriers=True)
self.assertEqualToReference(filename1)
circuit_drawer(circuit, filename=filename2, output="latex_source", plot_barriers=False)
self.assertEqualToReference(filename2)
def test_no_barriers_false(self):
"""Generate the same circuit as test_plot_barriers but without the barrier commands
as this is what the circuit should look like when displayed with plot barriers false"""
filename = self._get_resource_path("test_latex_no_barriers_false.tex")
q1 = QuantumRegister(2, "q")
c1 = ClassicalRegister(2, "c")
circuit = QuantumCircuit(q1, c1)
circuit.h(q1[0])
circuit.h(q1[1])
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_barrier_label(self):
"""Test the barrier label"""
filename = self._get_resource_path("test_latex_barrier_label.tex")
qr = QuantumRegister(2, "q")
circuit = QuantumCircuit(qr)
circuit.x(0)
circuit.y(1)
circuit.barrier()
circuit.y(0)
circuit.x(1)
circuit.barrier(label="End Y/X")
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_big_gates(self):
"""Test large gates with params"""
filename = self._get_resource_path("test_latex_big_gates.tex")
qr = QuantumRegister(6, "q")
circuit = QuantumCircuit(qr)
circuit.append(IQP([[6, 5, 3], [5, 4, 5], [3, 5, 1]]), [0, 1, 2])
desired_vector = [
1 / math.sqrt(16) * complex(0, 1),
1 / math.sqrt(8) * complex(1, 0),
1 / math.sqrt(16) * complex(1, 1),
0,
0,
1 / math.sqrt(8) * complex(1, 2),
1 / math.sqrt(16) * complex(1, 0),
0,
]
circuit.initialize(desired_vector, [qr[3], qr[4], qr[5]])
circuit.unitary([[1, 0], [0, 1]], [qr[0]])
matrix = np.zeros((4, 4))
theta = Parameter("theta")
circuit.append(HamiltonianGate(matrix, theta), [qr[1], qr[2]])
circuit = circuit.bind_parameters({theta: 1})
circuit.isometry(np.eye(4, 4), list(range(3, 5)), [])
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_cnot(self):
"""Test different cnot gates (ccnot, mcx, etc)"""
filename = self._get_resource_path("test_latex_cnot.tex")
qr = QuantumRegister(5, "q")
circuit = QuantumCircuit(qr)
circuit.x(0)
circuit.cx(0, 1)
circuit.ccx(0, 1, 2)
circuit.append(XGate().control(3, ctrl_state="010"), [qr[2], qr[3], qr[0], qr[1]])
circuit.append(MCXGate(num_ctrl_qubits=3, ctrl_state="101"), [qr[0], qr[1], qr[2], qr[4]])
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_pauli_clifford(self):
"""Test Pauli(green) and Clifford(blue) gates"""
filename = self._get_resource_path("test_latex_pauli_clifford.tex")
qr = QuantumRegister(5, "q")
circuit = QuantumCircuit(qr)
circuit.x(0)
circuit.y(0)
circuit.z(0)
circuit.id(0)
circuit.h(1)
circuit.cx(1, 2)
circuit.cy(1, 2)
circuit.cz(1, 2)
circuit.swap(3, 4)
circuit.s(3)
circuit.sdg(3)
circuit.iswap(3, 4)
circuit.dcx(3, 4)
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_u_gates(self):
"""Test U 1, 2, & 3 gates"""
filename = self._get_resource_path("test_latex_u_gates.tex")
from qiskit.circuit.library import U1Gate, U2Gate, U3Gate, CU1Gate, CU3Gate
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.append(U1Gate(3 * pi / 2), [0])
circuit.append(U2Gate(3 * pi / 2, 2 * pi / 3), [1])
circuit.append(U3Gate(3 * pi / 2, 4.5, pi / 4), [2])
circuit.append(CU1Gate(pi / 4), [0, 1])
circuit.append(U2Gate(pi / 2, 3 * pi / 2).control(1), [2, 3])
circuit.append(CU3Gate(3 * pi / 2, -3 * pi / 4, -pi / 2), [0, 1])
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_creg_initial(self):
"""Test cregbundle and initial state options"""
filename1 = self._get_resource_path("test_latex_creg_initial_true.tex")
filename2 = self._get_resource_path("test_latex_creg_initial_false.tex")
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
circuit = QuantumCircuit(qr, cr)
circuit.x(0)
circuit.h(0)
circuit.x(1)
circuit_drawer(
circuit, filename=filename1, output="latex_source", cregbundle=True, initial_state=True
)
self.assertEqualToReference(filename1)
circuit_drawer(
circuit,
filename=filename2,
output="latex_source",
cregbundle=False,
initial_state=False,
)
self.assertEqualToReference(filename2)
def test_r_gates(self):
"""Test all R gates"""
filename = self._get_resource_path("test_latex_r_gates.tex")
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.r(3 * pi / 4, 3 * pi / 8, 0)
circuit.rx(pi / 2, 1)
circuit.ry(-pi / 2, 2)
circuit.rz(3 * pi / 4, 3)
circuit.rxx(pi / 2, 0, 1)
circuit.ryy(3 * pi / 4, 2, 3)
circuit.rzx(-pi / 2, 0, 1)
circuit.rzz(pi / 2, 2, 3)
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_cswap_rzz(self):
"""Test controlled swap and rzz gates"""
filename = self._get_resource_path("test_latex_cswap_rzz.tex")
qr = QuantumRegister(5, "q")
circuit = QuantumCircuit(qr)
circuit.x(0)
circuit.x(1)
circuit.cswap(0, 1, 2)
circuit.append(RZZGate(3 * pi / 4).control(3, ctrl_state="010"), [2, 1, 4, 3, 0])
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_ghz_to_gate(self):
"""Test controlled GHZ to_gate circuit"""
filename = self._get_resource_path("test_latex_ghz_to_gate.tex")
qr = QuantumRegister(5, "q")
circuit = QuantumCircuit(qr)
ghz_circuit = QuantumCircuit(3, name="Ctrl-GHZ Circuit")
ghz_circuit.h(0)
ghz_circuit.cx(0, 1)
ghz_circuit.cx(1, 2)
ghz = ghz_circuit.to_gate()
ccghz = ghz.control(2, ctrl_state="10")
circuit.append(ccghz, [4, 0, 1, 3, 2])
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_scale(self):
"""Tests scale
See: https://github.com/Qiskit/qiskit-terra/issues/4179"""
filename1 = self._get_resource_path("test_latex_scale_default.tex")
filename2 = self._get_resource_path("test_latex_scale_half.tex")
filename3 = self._get_resource_path("test_latex_scale_double.tex")
circuit = QuantumCircuit(5)
circuit.unitary(random_unitary(2**5), circuit.qubits)
circuit_drawer(circuit, filename=filename1, output="latex_source")
self.assertEqualToReference(filename1)
circuit_drawer(circuit, filename=filename2, output="latex_source", scale=0.5)
self.assertEqualToReference(filename2)
circuit_drawer(circuit, filename=filename3, output="latex_source", scale=2.0)
self.assertEqualToReference(filename3)
def test_pi_param_expr(self):
"""Text pi in circuit with parameter expression."""
filename = self._get_resource_path("test_latex_pi_param_expr.tex")
x, y = Parameter("x"), Parameter("y")
circuit = QuantumCircuit(1)
circuit.rx((pi - x) * (pi - y), 0)
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
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")
circuit = QuantumCircuit(3)
circuit.h(1)
transpiled = transpile(
circuit,
backend=FakeTenerife(),
optimization_level=0,
initial_layout=[1, 2, 0],
seed_transpiler=0,
)
circuit_drawer(transpiled, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_init_reset(self):
"""Test reset and initialize with 1 and 2 qubits"""
filename = self._get_resource_path("test_latex_init_reset.tex")
circuit = QuantumCircuit(2)
circuit.initialize([0, 1], 0)
circuit.reset(1)
circuit.initialize([0, 1, 0, 0], [0, 1])
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_iqx_colors(self):
"""Tests with iqx color scheme"""
filename = self._get_resource_path("test_latex_iqx.tex")
circuit = QuantumCircuit(7)
circuit.h(0)
circuit.x(0)
circuit.cx(0, 1)
circuit.ccx(0, 1, 2)
circuit.swap(0, 1)
circuit.cswap(0, 1, 2)
circuit.append(SwapGate().control(2), [0, 1, 2, 3])
circuit.dcx(0, 1)
circuit.append(DCXGate().control(1), [0, 1, 2])
circuit.append(DCXGate().control(2), [0, 1, 2, 3])
circuit.z(4)
circuit.s(4)
circuit.sdg(4)
circuit.t(4)
circuit.tdg(4)
circuit.p(pi / 2, 4)
circuit.p(pi / 2, 4)
circuit.cz(5, 6)
circuit.cp(pi / 2, 5, 6)
circuit.y(5)
circuit.rx(pi / 3, 5)
circuit.rzx(pi / 2, 5, 6)
circuit.u(pi / 2, pi / 2, pi / 2, 5)
circuit.barrier(5, 6)
circuit.reset(5)
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_reverse_bits(self):
"""Tests reverse_bits parameter"""
filename = self._get_resource_path("test_latex_reverse_bits.tex")
circuit = QuantumCircuit(3)
circuit.h(0)
circuit.cx(0, 1)
circuit.ccx(2, 1, 0)
circuit_drawer(circuit, filename=filename, output="latex_source", reverse_bits=True)
self.assertEqualToReference(filename)
def test_meas_condition(self):
"""Tests measure with a condition"""
filename = self._get_resource_path("test_latex_meas_condition.tex")
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0])
circuit.measure(qr[0], cr[0])
circuit.h(qr[1]).c_if(cr, 1)
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_inst_with_cbits(self):
"""Test custom instructions with classical bits"""
filename = self._get_resource_path("test_latex_inst_with_cbits.tex")
qinst = QuantumRegister(2, "q")
cinst = ClassicalRegister(2, "c")
inst = QuantumCircuit(qinst, cinst, name="instruction").to_instruction()
qr = QuantumRegister(4, "qr")
cr = ClassicalRegister(4, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.append(inst, [qr[1], qr[2]], [cr[2], cr[1]])
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_cif_single_bit(self):
"""Tests conditioning gates on single classical bit"""
filename = self._get_resource_path("test_latex_cif_single_bit.tex")
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0]).c_if(cr[1], 0)
circuit.x(qr[1]).c_if(cr[0], 1)
circuit_drawer(circuit, cregbundle=False, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_cif_single_bit_cregbundle(self):
"""Tests conditioning gates on single classical bit with cregbundle"""
filename = self._get_resource_path("test_latex_cif_single_bit_bundle.tex")
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0]).c_if(cr[1], 0)
circuit.x(qr[1]).c_if(cr[0], 1)
circuit_drawer(circuit, cregbundle=True, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_registerless_one_bit(self):
"""Text circuit with one-bit registers and registerless bits."""
filename = self._get_resource_path("test_latex_registerless_one_bit.tex")
qrx = QuantumRegister(2, "qrx")
qry = QuantumRegister(1, "qry")
crx = ClassicalRegister(2, "crx")
circuit = QuantumCircuit(qrx, [Qubit(), Qubit()], qry, [Clbit(), Clbit()], crx)
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_measures_with_conditions(self):
"""Test that a measure containing a condition displays"""
filename1 = self._get_resource_path("test_latex_meas_cond_false.tex")
filename2 = self._get_resource_path("test_latex_meas_cond_true.tex")
qr = QuantumRegister(2, "qr")
cr1 = ClassicalRegister(2, "cr1")
cr2 = ClassicalRegister(2, "cr2")
circuit = QuantumCircuit(qr, cr1, cr2)
circuit.h(0)
circuit.h(1)
circuit.measure(0, cr1[1])
circuit.measure(1, cr2[0]).c_if(cr1, 1)
circuit.h(0).c_if(cr2, 3)
circuit_drawer(circuit, cregbundle=False, filename=filename1, output="latex_source")
circuit_drawer(circuit, cregbundle=True, filename=filename2, output="latex_source")
self.assertEqualToReference(filename1)
self.assertEqualToReference(filename2)
def test_measures_with_conditions_with_bits(self):
"""Condition and measure on single bits cregbundle true"""
filename1 = self._get_resource_path("test_latex_meas_cond_bits_false.tex")
filename2 = self._get_resource_path("test_latex_meas_cond_bits_true.tex")
bits = [Qubit(), Qubit(), Clbit(), Clbit()]
cr = ClassicalRegister(2, "cr")
crx = ClassicalRegister(3, "cs")
circuit = QuantumCircuit(bits, cr, [Clbit()], crx)
circuit.x(0).c_if(crx[1], 0)
circuit.measure(0, bits[3])
circuit_drawer(circuit, cregbundle=False, filename=filename1, output="latex_source")
circuit_drawer(circuit, cregbundle=True, filename=filename2, output="latex_source")
self.assertEqualToReference(filename1)
self.assertEqualToReference(filename2)
def test_conditions_with_bits_reverse(self):
"""Test that gates with conditions and measures work with bits reversed"""
filename = self._get_resource_path("test_latex_cond_reverse.tex")
bits = [Qubit(), Qubit(), Clbit(), Clbit()]
cr = ClassicalRegister(2, "cr")
crx = ClassicalRegister(3, "cs")
circuit = QuantumCircuit(bits, cr, [Clbit()], crx)
circuit.x(0).c_if(bits[3], 0)
circuit_drawer(
circuit, cregbundle=False, reverse_bits=True, filename=filename, output="latex_source"
)
self.assertEqualToReference(filename)
def test_sidetext_with_condition(self):
"""Test that sidetext gates align properly with a condition"""
filename = self._get_resource_path("test_latex_sidetext_condition.tex")
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
circuit = QuantumCircuit(qr, cr)
circuit.append(CPhaseGate(pi / 2), [qr[0], qr[1]]).c_if(cr[1], 1)
circuit_drawer(circuit, cregbundle=False, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_idle_wires_barrier(self):
"""Test that idle_wires False works with barrier"""
filename = self._get_resource_path("test_latex_idle_wires_barrier.tex")
circuit = QuantumCircuit(4, 4)
circuit.x(2)
circuit.barrier()
circuit_drawer(circuit, idle_wires=False, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_wire_order(self):
"""Test the wire_order option to latex drawer"""
filename = self._get_resource_path("test_latex_wire_order.tex")
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(4, "c")
cr2 = ClassicalRegister(2, "ca")
circuit = QuantumCircuit(qr, cr, cr2)
circuit.h(0)
circuit.h(3)
circuit.x(1)
circuit.x(3).c_if(cr, 12)
circuit_drawer(
circuit,
cregbundle=False,
wire_order=[2, 1, 3, 0, 6, 8, 9, 5, 4, 7],
filename=filename,
output="latex_source",
)
self.assertEqualToReference(filename)
if __name__ == "__main__":
unittest.main(verbosity=2)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""`_text_circuit_drawer` draws a circuit in ascii art"""
import pathlib
import os
import tempfile
import unittest.mock
from codecs import encode
from math import pi
import numpy
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, transpile
from qiskit.circuit import Gate, Parameter, Qubit, Clbit, Instruction
from qiskit.quantum_info.operators import SuperOp
from qiskit.quantum_info.random import random_unitary
from qiskit.test import QiskitTestCase
from qiskit.transpiler.layout import Layout, TranspileLayout
from qiskit.visualization import circuit_drawer
from qiskit.visualization.circuit import text as elements
from qiskit.visualization.circuit.circuit_visualization import _text_circuit_drawer
from qiskit.extensions import UnitaryGate, HamiltonianGate
from qiskit.extensions.quantum_initializer import UCGate
from qiskit.circuit.library import (
HGate,
U2Gate,
U3Gate,
XGate,
CZGate,
ZGate,
YGate,
U1Gate,
SwapGate,
RZZGate,
CU3Gate,
CU1Gate,
CPhaseGate,
)
from qiskit.transpiler.passes import ApplyLayout
from qiskit.utils.optionals import HAS_TWEEDLEDUM
from .visualization import path_to_diagram_reference, QiskitVisualizationTestCase
if HAS_TWEEDLEDUM:
from qiskit.circuit.classicalfunction import classical_function
from qiskit.circuit.classicalfunction.types import Int1
class TestTextDrawerElement(QiskitTestCase):
"""Draw each element"""
def assertEqualElement(self, expected, element):
"""
Asserts the top,mid,bot trio
Args:
expected (list[top,mid,bot]): What is expected.
element (DrawElement): The element to check.
"""
try:
encode("\n".join(expected), encoding="cp437")
except UnicodeEncodeError:
self.fail("_text_circuit_drawer() should only use extended ascii (aka code page 437).")
self.assertEqual(expected[0], element.top)
self.assertEqual(expected[1], element.mid)
self.assertEqual(expected[2], element.bot)
def test_measure_to(self):
"""MeasureTo element."""
element = elements.MeasureTo()
# fmt: off
expected = [" ║ ",
"═╩═",
" "]
# fmt: on
self.assertEqualElement(expected, element)
def test_measure_to_label(self):
"""MeasureTo element with cregbundle"""
element = elements.MeasureTo("1")
# fmt: off
expected = [" ║ ",
"═╩═",
" 1 "]
# fmt: on
self.assertEqualElement(expected, element)
def test_measure_from(self):
"""MeasureFrom element."""
element = elements.MeasureFrom()
# fmt: off
expected = ["┌─┐",
"┤M├",
"└╥┘"]
# fmt: on
self.assertEqualElement(expected, element)
def test_text_empty(self):
"""The empty circuit."""
expected = ""
circuit = QuantumCircuit()
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_pager(self):
"""The pager breaks the circuit when the drawing does not fit in the console."""
expected = "\n".join(
[
" ┌───┐ »",
"q_0: |0>┤ X ├──■──»",
" └─┬─┘┌─┴─┐»",
"q_1: |0>──■──┤ X ├»",
" └───┘»",
" c: 0 1/══════════»",
" »",
"« ┌─┐┌───┐ »",
"«q_0: ┤M├┤ X ├──■──»",
"« └╥┘└─┬─┘┌─┴─┐»",
"«q_1: ─╫───■──┤ X ├»",
"« ║ └───┘»",
"«c: 1/═╩═══════════»",
"« 0 »",
"« ┌─┐┌───┐ ",
"«q_0: ┤M├┤ X ├──■──",
"« └╥┘└─┬─┘┌─┴─┐",
"«q_1: ─╫───■──┤ X ├",
"« ║ └───┘",
"«c: 1/═╩═══════════",
"« 0 ",
]
)
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
circuit = QuantumCircuit(qr, cr)
circuit.cx(qr[1], qr[0])
circuit.cx(qr[0], qr[1])
circuit.measure(qr[0], cr[0])
circuit.cx(qr[1], qr[0])
circuit.cx(qr[0], qr[1])
circuit.measure(qr[0], cr[0])
circuit.cx(qr[1], qr[0])
circuit.cx(qr[0], qr[1])
self.assertEqual(str(_text_circuit_drawer(circuit, fold=20)), expected)
def test_text_no_pager(self):
"""The pager can be disable."""
qr = QuantumRegister(1, "q")
circuit = QuantumCircuit(qr)
for _ in range(100):
circuit.h(qr[0])
amount_of_lines = str(_text_circuit_drawer(circuit, fold=-1)).count("\n")
self.assertEqual(amount_of_lines, 2)
class TestTextDrawerGatesInCircuit(QiskitTestCase):
"""Gate by gate checks in different settings."""
def test_text_measure_cregbundle(self):
"""The measure operator, using 3-bit-length registers with cregbundle=True."""
expected = "\n".join(
[
" ┌─┐ ",
"q_0: |0>┤M├──────",
" └╥┘┌─┐ ",
"q_1: |0>─╫─┤M├───",
" ║ └╥┘┌─┐",
"q_2: |0>─╫──╫─┤M├",
" ║ ║ └╥┘",
" c: 0 3/═╩══╩══╩═",
" 0 1 2 ",
]
)
qr = QuantumRegister(3, "q")
cr = ClassicalRegister(3, "c")
circuit = QuantumCircuit(qr, cr)
circuit.measure(qr, cr)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_measure_cregbundle_2(self):
"""The measure operator, using 2 classical registers with cregbundle=True."""
expected = "\n".join(
[
" ┌─┐ ",
"q_0: |0>┤M├───",
" └╥┘┌─┐",
"q_1: |0>─╫─┤M├",
" ║ └╥┘",
"cA: 0 1/═╩══╬═",
" 0 ║ ",
"cB: 0 1/════╩═",
" 0 ",
]
)
qr = QuantumRegister(2, "q")
cr_a = ClassicalRegister(1, "cA")
cr_b = ClassicalRegister(1, "cB")
circuit = QuantumCircuit(qr, cr_a, cr_b)
circuit.measure(qr[0], cr_a[0])
circuit.measure(qr[1], cr_b[0])
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_measure_1(self):
"""The measure operator, using 3-bit-length registers."""
expected = "\n".join(
[
" ┌─┐ ",
"q_0: |0>┤M├──────",
" └╥┘┌─┐ ",
"q_1: |0>─╫─┤M├───",
" ║ └╥┘┌─┐",
"q_2: |0>─╫──╫─┤M├",
" ║ ║ └╥┘",
" c_0: 0 ═╩══╬══╬═",
" ║ ║ ",
" c_1: 0 ════╩══╬═",
" ║ ",
" c_2: 0 ═══════╩═",
" ",
]
)
qr = QuantumRegister(3, "q")
cr = ClassicalRegister(3, "c")
circuit = QuantumCircuit(qr, cr)
circuit.measure(qr, cr)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_text_measure_1_reverse_bits(self):
"""The measure operator, using 3-bit-length registers, with reverse_bits"""
expected = "\n".join(
[
" ┌─┐",
"q_2: |0>──────┤M├",
" ┌─┐└╥┘",
"q_1: |0>───┤M├─╫─",
" ┌─┐└╥┘ ║ ",
"q_0: |0>┤M├─╫──╫─",
" └╥┘ ║ ║ ",
" c: 0 3/═╩══╩══╩═",
" 0 1 2 ",
]
)
qr = QuantumRegister(3, "q")
cr = ClassicalRegister(3, "c")
circuit = QuantumCircuit(qr, cr)
circuit.measure(qr, cr)
self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected)
def test_text_measure_2(self):
"""The measure operator, using some registers."""
expected = "\n".join(
[
" ",
"q1_0: |0>──────",
" ",
"q1_1: |0>──────",
" ┌─┐ ",
"q2_0: |0>┤M├───",
" └╥┘┌─┐",
"q2_1: |0>─╫─┤M├",
" ║ └╥┘",
" c1: 0 2/═╬══╬═",
" ║ ║ ",
" c2: 0 2/═╩══╩═",
" 0 1 ",
]
)
qr1 = QuantumRegister(2, "q1")
cr1 = ClassicalRegister(2, "c1")
qr2 = QuantumRegister(2, "q2")
cr2 = ClassicalRegister(2, "c2")
circuit = QuantumCircuit(qr1, qr2, cr1, cr2)
circuit.measure(qr2, cr2)
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_measure_2_reverse_bits(self):
"""The measure operator, using some registers, with reverse_bits"""
expected = "\n".join(
[
" ┌─┐",
"q2_1: |0>───┤M├",
" ┌─┐└╥┘",
"q2_0: |0>┤M├─╫─",
" └╥┘ ║ ",
"q1_1: |0>─╫──╫─",
" ║ ║ ",
"q1_0: |0>─╫──╫─",
" ║ ║ ",
" c2: 0 2/═╩══╩═",
" 0 1 ",
" c1: 0 2/══════",
" ",
]
)
qr1 = QuantumRegister(2, "q1")
cr1 = ClassicalRegister(2, "c1")
qr2 = QuantumRegister(2, "q2")
cr2 = ClassicalRegister(2, "c2")
circuit = QuantumCircuit(qr1, qr2, cr1, cr2)
circuit.measure(qr2, cr2)
self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected)
def test_wire_order(self):
"""Test the wire_order option"""
expected = "\n".join(
[
" ",
"q_2: |0>────────────",
" ┌───┐ ",
"q_1: |0>┤ X ├───────",
" ├───┤ ┌───┐ ",
"q_3: |0>┤ H ├─┤ X ├─",
" ├───┤ └─╥─┘ ",
"q_0: |0>┤ H ├───╫───",
" └───┘┌──╨──┐",
" c: 0 4/═════╡ 0xa ╞",
" └─────┘",
"ca: 0 2/════════════",
" ",
]
)
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(4, "c")
cr2 = ClassicalRegister(2, "ca")
circuit = QuantumCircuit(qr, cr, cr2)
circuit.h(0)
circuit.h(3)
circuit.x(1)
circuit.x(3).c_if(cr, 10)
self.assertEqual(
str(_text_circuit_drawer(circuit, wire_order=[2, 1, 3, 0, 6, 8, 9, 5, 4, 7])), expected
)
def test_text_swap(self):
"""Swap drawing."""
expected = "\n".join(
[
" ",
"q1_0: |0>─X────",
" │ ",
"q1_1: |0>─┼──X─",
" │ │ ",
"q2_0: |0>─X──┼─",
" │ ",
"q2_1: |0>────X─",
" ",
]
)
qr1 = QuantumRegister(2, "q1")
qr2 = QuantumRegister(2, "q2")
circuit = QuantumCircuit(qr1, qr2)
circuit.swap(qr1, qr2)
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_swap_reverse_bits(self):
"""Swap drawing with reverse_bits."""
expected = "\n".join(
[
" ",
"q2_1: |0>────X─",
" │ ",
"q2_0: |0>─X──┼─",
" │ │ ",
"q1_1: |0>─┼──X─",
" │ ",
"q1_0: |0>─X────",
" ",
]
)
qr1 = QuantumRegister(2, "q1")
qr2 = QuantumRegister(2, "q2")
circuit = QuantumCircuit(qr1, qr2)
circuit.swap(qr1, qr2)
self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected)
def test_text_reverse_bits_read_from_config(self):
"""Swap drawing with reverse_bits set in the configuration file."""
expected_forward = "\n".join(
[
" ",
"q1_0: ─X────",
" │ ",
"q1_1: ─┼──X─",
" │ │ ",
"q2_0: ─X──┼─",
" │ ",
"q2_1: ────X─",
" ",
]
)
expected_reverse = "\n".join(
[
" ",
"q2_1: ────X─",
" │ ",
"q2_0: ─X──┼─",
" │ │ ",
"q1_1: ─┼──X─",
" │ ",
"q1_0: ─X────",
" ",
]
)
qr1 = QuantumRegister(2, "q1")
qr2 = QuantumRegister(2, "q2")
circuit = QuantumCircuit(qr1, qr2)
circuit.swap(qr1, qr2)
self.assertEqual(str(circuit_drawer(circuit, output="text")), expected_forward)
config_content = """
[default]
circuit_reverse_bits = true
"""
with tempfile.TemporaryDirectory() as dir_path:
file_path = pathlib.Path(dir_path) / "qiskit.conf"
with open(file_path, "w") as fptr:
fptr.write(config_content)
with unittest.mock.patch.dict(os.environ, {"QISKIT_SETTINGS": str(file_path)}):
test_reverse = str(circuit_drawer(circuit, output="text"))
self.assertEqual(test_reverse, expected_reverse)
def test_text_cswap(self):
"""CSwap drawing."""
expected = "\n".join(
[
" ",
"q_0: |0>─■──X──X─",
" │ │ │ ",
"q_1: |0>─X──■──X─",
" │ │ │ ",
"q_2: |0>─X──X──■─",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cswap(qr[0], qr[1], qr[2])
circuit.cswap(qr[1], qr[0], qr[2])
circuit.cswap(qr[2], qr[1], qr[0])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_cswap_reverse_bits(self):
"""CSwap drawing with reverse_bits."""
expected = "\n".join(
[
" ",
"q_2: |0>─X──X──■─",
" │ │ │ ",
"q_1: |0>─X──■──X─",
" │ │ │ ",
"q_0: |0>─■──X──X─",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cswap(qr[0], qr[1], qr[2])
circuit.cswap(qr[1], qr[0], qr[2])
circuit.cswap(qr[2], qr[1], qr[0])
self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected)
def test_text_cu3(self):
"""cu3 drawing."""
expected = "\n".join(
[
" ┌─────────────────┐",
"q_0: |0>─────────■─────────┤ U3(π/2,π/2,π/2) ├",
" ┌────────┴────────┐└────────┬────────┘",
"q_1: |0>┤ U3(π/2,π/2,π/2) ├─────────┼─────────",
" └─────────────────┘ │ ",
"q_2: |0>────────────────────────────■─────────",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.append(CU3Gate(pi / 2, pi / 2, pi / 2), [qr[0], qr[1]])
circuit.append(CU3Gate(pi / 2, pi / 2, pi / 2), [qr[2], qr[0]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_cu3_reverse_bits(self):
"""cu3 drawing with reverse_bits"""
expected = "\n".join(
[
" ",
"q_2: |0>────────────────────────────■─────────",
" ┌─────────────────┐ │ ",
"q_1: |0>┤ U3(π/2,π/2,π/2) ├─────────┼─────────",
" └────────┬────────┘┌────────┴────────┐",
"q_0: |0>─────────■─────────┤ U3(π/2,π/2,π/2) ├",
" └─────────────────┘",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.append(CU3Gate(pi / 2, pi / 2, pi / 2), [qr[0], qr[1]])
circuit.append(CU3Gate(pi / 2, pi / 2, pi / 2), [qr[2], qr[0]])
self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected)
def test_text_crz(self):
"""crz drawing."""
expected = "\n".join(
[
" ┌─────────┐",
"q_0: |0>─────■─────┤ Rz(π/2) ├",
" ┌────┴────┐└────┬────┘",
"q_1: |0>┤ Rz(π/2) ├─────┼─────",
" └─────────┘ │ ",
"q_2: |0>────────────────■─────",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.crz(pi / 2, qr[0], qr[1])
circuit.crz(pi / 2, qr[2], qr[0])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_cry(self):
"""cry drawing."""
expected = "\n".join(
[
" ┌─────────┐",
"q_0: |0>─────■─────┤ Ry(π/2) ├",
" ┌────┴────┐└────┬────┘",
"q_1: |0>┤ Ry(π/2) ├─────┼─────",
" └─────────┘ │ ",
"q_2: |0>────────────────■─────",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cry(pi / 2, qr[0], qr[1])
circuit.cry(pi / 2, qr[2], qr[0])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_crx(self):
"""crx drawing."""
expected = "\n".join(
[
" ┌─────────┐",
"q_0: |0>─────■─────┤ Rx(π/2) ├",
" ┌────┴────┐└────┬────┘",
"q_1: |0>┤ Rx(π/2) ├─────┼─────",
" └─────────┘ │ ",
"q_2: |0>────────────────■─────",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.crx(pi / 2, qr[0], qr[1])
circuit.crx(pi / 2, qr[2], qr[0])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_cx(self):
"""cx drawing."""
expected = "\n".join(
[
" ┌───┐",
"q_0: |0>──■──┤ X ├",
" ┌─┴─┐└─┬─┘",
"q_1: |0>┤ X ├──┼──",
" └───┘ │ ",
"q_2: |0>───────■──",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.cx(qr[2], qr[0])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_cy(self):
"""cy drawing."""
expected = "\n".join(
[
" ┌───┐",
"q_0: |0>──■──┤ Y ├",
" ┌─┴─┐└─┬─┘",
"q_1: |0>┤ Y ├──┼──",
" └───┘ │ ",
"q_2: |0>───────■──",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cy(qr[0], qr[1])
circuit.cy(qr[2], qr[0])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_cz(self):
"""cz drawing."""
expected = "\n".join(
[
" ",
"q_0: |0>─■──■─",
" │ │ ",
"q_1: |0>─■──┼─",
" │ ",
"q_2: |0>────■─",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cz(qr[0], qr[1])
circuit.cz(qr[2], qr[0])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_ch(self):
"""ch drawing."""
expected = "\n".join(
[
" ┌───┐",
"q_0: |0>──■──┤ H ├",
" ┌─┴─┐└─┬─┘",
"q_1: |0>┤ H ├──┼──",
" └───┘ │ ",
"q_2: |0>───────■──",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.ch(qr[0], qr[1])
circuit.ch(qr[2], qr[0])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_rzz(self):
"""rzz drawing. See #1957"""
expected = "\n".join(
[
" ",
"q_0: |0>─■────────────────",
" │ZZ(0) ",
"q_1: |0>─■───────■────────",
" │ZZ(π/2) ",
"q_2: |0>─────────■────────",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.rzz(0, qr[0], qr[1])
circuit.rzz(pi / 2, qr[2], qr[1])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_cu1(self):
"""cu1 drawing."""
expected = "\n".join(
[
" ",
"q_0: |0>─■─────────■────────",
" │U1(π/2) │ ",
"q_1: |0>─■─────────┼────────",
" │U1(π/2) ",
"q_2: |0>───────────■────────",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.append(CU1Gate(pi / 2), [qr[0], qr[1]])
circuit.append(CU1Gate(pi / 2), [qr[2], qr[0]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_cp(self):
"""cp drawing."""
expected = "\n".join(
[
" ",
"q_0: |0>─■────────■───────",
" │P(π/2) │ ",
"q_1: |0>─■────────┼───────",
" │P(π/2) ",
"q_2: |0>──────────■───────",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.append(CPhaseGate(pi / 2), [qr[0], qr[1]])
circuit.append(CPhaseGate(pi / 2), [qr[2], qr[0]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_cu1_condition(self):
"""Test cu1 with condition"""
expected = "\n".join(
[
" ",
"q_0: ────────■────────",
" │U1(π/2) ",
"q_1: ────────■────────",
" ║ ",
"q_2: ────────╫────────",
" ┌────╨────┐ ",
"c: 3/═══╡ c_1=0x1 ╞═══",
" └─────────┘ ",
]
)
qr = QuantumRegister(3, "q")
cr = ClassicalRegister(3, "c")
circuit = QuantumCircuit(qr, cr)
circuit.append(CU1Gate(pi / 2), [qr[0], qr[1]]).c_if(cr[1], 1)
self.assertEqual(str(_text_circuit_drawer(circuit, initial_state=False)), expected)
def test_text_rzz_condition(self):
"""Test rzz with condition"""
expected = "\n".join(
[
" ",
"q_0: ────────■────────",
" │ZZ(π/2) ",
"q_1: ────────■────────",
" ║ ",
"q_2: ────────╫────────",
" ┌────╨────┐ ",
"c: 3/═══╡ c_1=0x1 ╞═══",
" └─────────┘ ",
]
)
qr = QuantumRegister(3, "q")
cr = ClassicalRegister(3, "c")
circuit = QuantumCircuit(qr, cr)
circuit.append(RZZGate(pi / 2), [qr[0], qr[1]]).c_if(cr[1], 1)
self.assertEqual(str(_text_circuit_drawer(circuit, initial_state=False)), expected)
def test_text_cp_condition(self):
"""Test cp with condition"""
expected = "\n".join(
[
" ",
"q_0: ───────■───────",
" │P(π/2) ",
"q_1: ───────■───────",
" ║ ",
"q_2: ───────╫───────",
" ┌────╨────┐ ",
"c: 3/══╡ c_1=0x1 ╞══",
" └─────────┘ ",
]
)
qr = QuantumRegister(3, "q")
cr = ClassicalRegister(3, "c")
circuit = QuantumCircuit(qr, cr)
circuit.append(CPhaseGate(pi / 2), [qr[0], qr[1]]).c_if(cr[1], 1)
self.assertEqual(str(_text_circuit_drawer(circuit, initial_state=False)), expected)
def test_text_cu1_reverse_bits(self):
"""cu1 drawing with reverse_bits"""
expected = "\n".join(
[
" ",
"q_2: |0>───────────■────────",
" │ ",
"q_1: |0>─■─────────┼────────",
" │U1(π/2) │U1(π/2) ",
"q_0: |0>─■─────────■────────",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.append(CU1Gate(pi / 2), [qr[0], qr[1]])
circuit.append(CU1Gate(pi / 2), [qr[2], qr[0]])
self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected)
def test_text_ccx(self):
"""cx drawing."""
expected = "\n".join(
[
" ┌───┐",
"q_0: |0>──■────■──┤ X ├",
" │ ┌─┴─┐└─┬─┘",
"q_1: |0>──■──┤ X ├──■──",
" ┌─┴─┐└─┬─┘ │ ",
"q_2: |0>┤ X ├──■────■──",
" └───┘ ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.ccx(qr[0], qr[1], qr[2])
circuit.ccx(qr[2], qr[0], qr[1])
circuit.ccx(qr[2], qr[1], qr[0])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_reset(self):
"""Reset drawing."""
expected = "\n".join(
[
" ",
"q1_0: |0>─|0>─",
" ",
"q1_1: |0>─|0>─",
" ",
"q2_0: |0>─────",
" ",
"q2_1: |0>─|0>─",
" ",
]
)
qr1 = QuantumRegister(2, "q1")
qr2 = QuantumRegister(2, "q2")
circuit = QuantumCircuit(qr1, qr2)
circuit.reset(qr1)
circuit.reset(qr2[1])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_single_gate(self):
"""Single Qbit gate drawing."""
expected = "\n".join(
[
" ┌───┐",
"q1_0: |0>┤ H ├",
" ├───┤",
"q1_1: |0>┤ H ├",
" └───┘",
"q2_0: |0>─────",
" ┌───┐",
"q2_1: |0>┤ H ├",
" └───┘",
]
)
qr1 = QuantumRegister(2, "q1")
qr2 = QuantumRegister(2, "q2")
circuit = QuantumCircuit(qr1, qr2)
circuit.h(qr1)
circuit.h(qr2[1])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_id(self):
"""Id drawing."""
expected = "\n".join(
[
" ┌───┐",
"q1_0: |0>┤ I ├",
" ├───┤",
"q1_1: |0>┤ I ├",
" └───┘",
"q2_0: |0>─────",
" ┌───┐",
"q2_1: |0>┤ I ├",
" └───┘",
]
)
qr1 = QuantumRegister(2, "q1")
qr2 = QuantumRegister(2, "q2")
circuit = QuantumCircuit(qr1, qr2)
circuit.id(qr1)
circuit.id(qr2[1])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_barrier(self):
"""Barrier drawing."""
expected = "\n".join(
[
" ░ ",
"q1_0: |0>─░─",
" ░ ",
"q1_1: |0>─░─",
" ░ ",
"q2_0: |0>───",
" ░ ",
"q2_1: |0>─░─",
" ░ ",
]
)
qr1 = QuantumRegister(2, "q1")
qr2 = QuantumRegister(2, "q2")
circuit = QuantumCircuit(qr1, qr2)
circuit.barrier(qr1)
circuit.barrier(qr2[1])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_no_barriers(self):
"""Drawing without plotbarriers."""
expected = "\n".join(
[
" ┌───┐ ",
"q1_0: |0>┤ H ├─────",
" ├───┤ ",
"q1_1: |0>┤ H ├─────",
" ├───┤ ",
"q2_0: |0>┤ H ├─────",
" └───┘┌───┐",
"q2_1: |0>─────┤ H ├",
" └───┘",
]
)
qr1 = QuantumRegister(2, "q1")
qr2 = QuantumRegister(2, "q2")
circuit = QuantumCircuit(qr1, qr2)
circuit.h(qr1)
circuit.barrier(qr1)
circuit.barrier(qr2[1])
circuit.h(qr2)
self.assertEqual(str(_text_circuit_drawer(circuit, plot_barriers=False)), expected)
def test_text_measure_html(self):
"""The measure operator. HTML representation."""
expected = "\n".join(
[
'<pre style="word-wrap: normal;'
"white-space: pre;"
"background: #fff0;"
"line-height: 1.1;"
'font-family: "Courier New",Courier,monospace">'
" ┌─┐",
" q: |0>┤M├",
" └╥┘",
"c: 0 1/═╩═",
" 0 </pre>",
]
)
qr = QuantumRegister(1, "q")
cr = ClassicalRegister(1, "c")
circuit = QuantumCircuit(qr, cr)
circuit.measure(qr, cr)
self.assertEqual(_text_circuit_drawer(circuit)._repr_html_(), expected)
def test_text_repr(self):
"""The measure operator. repr."""
expected = "\n".join(
[
" ┌─┐",
" q: |0>┤M├",
" └╥┘",
"c: 0 1/═╩═",
" 0 ",
]
)
qr = QuantumRegister(1, "q")
cr = ClassicalRegister(1, "c")
circuit = QuantumCircuit(qr, cr)
circuit.measure(qr, cr)
self.assertEqual(_text_circuit_drawer(circuit).__repr__(), expected)
def test_text_justify_left(self):
"""Drawing with left justify"""
expected = "\n".join(
[
" ┌───┐ ",
"q1_0: |0>┤ X ├───",
" ├───┤┌─┐",
"q1_1: |0>┤ H ├┤M├",
" └───┘└╥┘",
" c1: 0 2/══════╩═",
" 1 ",
]
)
qr1 = QuantumRegister(2, "q1")
cr1 = ClassicalRegister(2, "c1")
circuit = QuantumCircuit(qr1, cr1)
circuit.x(qr1[0])
circuit.h(qr1[1])
circuit.measure(qr1[1], cr1[1])
self.assertEqual(str(_text_circuit_drawer(circuit, justify="left")), expected)
def test_text_justify_right(self):
"""Drawing with right justify"""
expected = "\n".join(
[
" ┌───┐",
"q1_0: |0>─────┤ X ├",
" ┌───┐└┬─┬┘",
"q1_1: |0>┤ H ├─┤M├─",
" └───┘ └╥┘ ",
" c1: 0 2/═══════╩══",
" 1 ",
]
)
qr1 = QuantumRegister(2, "q1")
cr1 = ClassicalRegister(2, "c1")
circuit = QuantumCircuit(qr1, cr1)
circuit.x(qr1[0])
circuit.h(qr1[1])
circuit.measure(qr1[1], cr1[1])
self.assertEqual(str(_text_circuit_drawer(circuit, justify="right")), expected)
def test_text_justify_none(self):
"""Drawing with none justify"""
expected = "\n".join(
[
" ┌───┐ ",
"q1_0: |0>┤ X ├────────",
" └───┘┌───┐┌─┐",
"q1_1: |0>─────┤ H ├┤M├",
" └───┘└╥┘",
" c1: 0 2/═══════════╩═",
" 1 ",
]
)
qr1 = QuantumRegister(2, "q1")
cr1 = ClassicalRegister(2, "c1")
circuit = QuantumCircuit(qr1, cr1)
circuit.x(qr1[0])
circuit.h(qr1[1])
circuit.measure(qr1[1], cr1[1])
self.assertEqual(str(_text_circuit_drawer(circuit, justify="none")), expected)
def test_text_justify_left_barrier(self):
"""Left justify respects barriers"""
expected = "\n".join(
[
" ┌───┐ ░ ",
"q1_0: |0>┤ H ├─░──────",
" └───┘ ░ ┌───┐",
"q1_1: |0>──────░─┤ H ├",
" ░ └───┘",
]
)
qr1 = QuantumRegister(2, "q1")
circuit = QuantumCircuit(qr1)
circuit.h(qr1[0])
circuit.barrier(qr1)
circuit.h(qr1[1])
self.assertEqual(str(_text_circuit_drawer(circuit, justify="left")), expected)
def test_text_justify_right_barrier(self):
"""Right justify respects barriers"""
expected = "\n".join(
[
" ┌───┐ ░ ",
"q1_0: |0>┤ H ├─░──────",
" └───┘ ░ ┌───┐",
"q1_1: |0>──────░─┤ H ├",
" ░ └───┘",
]
)
qr1 = QuantumRegister(2, "q1")
circuit = QuantumCircuit(qr1)
circuit.h(qr1[0])
circuit.barrier(qr1)
circuit.h(qr1[1])
self.assertEqual(str(_text_circuit_drawer(circuit, justify="right")), expected)
def test_text_barrier_label(self):
"""Show barrier label"""
expected = "\n".join(
[
" ┌───┐ ░ ┌───┐ End Y/X ",
"q_0: |0>┤ X ├─░─┤ Y ├────░────",
" ├───┤ ░ ├───┤ ░ ",
"q_1: |0>┤ Y ├─░─┤ X ├────░────",
" └───┘ ░ └───┘ ░ ",
]
)
qr = QuantumRegister(2, "q")
circuit = QuantumCircuit(qr)
circuit.x(0)
circuit.y(1)
circuit.barrier()
circuit.y(0)
circuit.x(1)
circuit.barrier(label="End Y/X")
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_overlap_cx(self):
"""Overlapping CX gates are drawn not overlapping"""
expected = "\n".join(
[
" ",
"q1_0: |0>──■───────",
" │ ",
"q1_1: |0>──┼────■──",
" │ ┌─┴─┐",
"q1_2: |0>──┼──┤ X ├",
" ┌─┴─┐└───┘",
"q1_3: |0>┤ X ├─────",
" └───┘ ",
]
)
qr1 = QuantumRegister(4, "q1")
circuit = QuantumCircuit(qr1)
circuit.cx(qr1[0], qr1[3])
circuit.cx(qr1[1], qr1[2])
self.assertEqual(str(_text_circuit_drawer(circuit, justify="left")), expected)
def test_text_overlap_measure(self):
"""Measure is drawn not overlapping"""
expected = "\n".join(
[
" ┌─┐ ",
"q1_0: |0>┤M├─────",
" └╥┘┌───┐",
"q1_1: |0>─╫─┤ X ├",
" ║ └───┘",
" c1: 0 2/═╩══════",
" 0 ",
]
)
qr1 = QuantumRegister(2, "q1")
cr1 = ClassicalRegister(2, "c1")
circuit = QuantumCircuit(qr1, cr1)
circuit.measure(qr1[0], cr1[0])
circuit.x(qr1[1])
self.assertEqual(str(_text_circuit_drawer(circuit, justify="left")), expected)
def test_text_overlap_swap(self):
"""Swap is drawn in 2 separate columns"""
expected = "\n".join(
[
" ",
"q1_0: |0>─X────",
" │ ",
"q1_1: |0>─┼──X─",
" │ │ ",
"q2_0: |0>─X──┼─",
" │ ",
"q2_1: |0>────X─",
" ",
]
)
qr1 = QuantumRegister(2, "q1")
qr2 = QuantumRegister(2, "q2")
circuit = QuantumCircuit(qr1, qr2)
circuit.swap(qr1, qr2)
self.assertEqual(str(_text_circuit_drawer(circuit, justify="left")), expected)
def test_text_justify_right_measure_resize(self):
"""Measure gate can resize if necessary"""
expected = "\n".join(
[
" ┌───┐",
"q1_0: |0>┤ X ├",
" └┬─┬┘",
"q1_1: |0>─┤M├─",
" └╥┘ ",
" c1: 0 2/══╩══",
" 1 ",
]
)
qr1 = QuantumRegister(2, "q1")
cr1 = ClassicalRegister(2, "c1")
circuit = QuantumCircuit(qr1, cr1)
circuit.x(qr1[0])
circuit.measure(qr1[1], cr1[1])
self.assertEqual(str(_text_circuit_drawer(circuit, justify="right")), expected)
def test_text_box_length(self):
"""The length of boxes is independent of other boxes in the layer
https://github.com/Qiskit/qiskit-terra/issues/1882"""
expected = "\n".join(
[
" ┌───┐ ┌───┐",
"q1_0: |0>────┤ H ├────┤ H ├",
" └───┘ └───┘",
"q1_1: |0>──────────────────",
" ┌───────────┐ ",
"q1_2: |0>┤ Rz(1e-07) ├─────",
" └───────────┘ ",
]
)
qr = QuantumRegister(3, "q1")
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[0])
circuit.rz(0.0000001, qr[2])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_spacing_2378(self):
"""Small gates in the same layer as long gates.
See https://github.com/Qiskit/qiskit-terra/issues/2378"""
expected = "\n".join(
[
" ",
"q_0: |0>──────X──────",
" │ ",
"q_1: |0>──────X──────",
" ┌───────────┐",
"q_2: |0>┤ Rz(11111) ├",
" └───────────┘",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.swap(qr[0], qr[1])
circuit.rz(11111, qr[2])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
@unittest.skipUnless(HAS_TWEEDLEDUM, "Tweedledum is required for these tests.")
def test_text_synth_no_registerless(self):
"""Test synthesis's label when registerless=False.
See https://github.com/Qiskit/qiskit-terra/issues/9363"""
expected = "\n".join(
[
" ",
" a: |0>──■──",
" │ ",
" b: |0>──■──",
" │ ",
" c: |0>──o──",
" ┌─┴─┐",
"return: |0>┤ X ├",
" └───┘",
]
)
@classical_function
def grover_oracle(a: Int1, b: Int1, c: Int1) -> Int1:
return a and b and not c
circuit = grover_oracle.synth(registerless=False)
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
class TestTextDrawerLabels(QiskitTestCase):
"""Gates with labels."""
def test_label(self):
"""Test a gate with a label."""
# fmt: off
expected = "\n".join([" ┌───────────┐",
"q: |0>┤ an H gate ├",
" └───────────┘"])
# fmt: on
circuit = QuantumCircuit(1)
circuit.append(HGate(label="an H gate"), [0])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_controlled_gate_with_label(self):
"""Test a controlled gate-with-a-label."""
expected = "\n".join(
[
" ",
"q_0: |0>──────■──────",
" ┌─────┴─────┐",
"q_1: |0>┤ an H gate ├",
" └───────────┘",
]
)
circuit = QuantumCircuit(2)
circuit.append(HGate(label="an H gate").control(1), [0, 1])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_label_on_controlled_gate(self):
"""Test a controlled gate with a label (as a as a whole)."""
expected = "\n".join(
[
" a controlled H gate ",
"q_0: |0>──────────■──────────",
" ┌─┴─┐ ",
"q_1: |0>────────┤ H ├────────",
" └───┘ ",
]
)
circuit = QuantumCircuit(2)
circuit.append(HGate().control(1, label="a controlled H gate"), [0, 1])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_rzz_on_wide_layer(self):
"""Test a labeled gate (RZZ) in a wide layer.
See https://github.com/Qiskit/qiskit-terra/issues/4838"""
expected = "\n".join(
[
" ",
"q_0: |0>────────────────■──────────────────────",
" │ZZ(π/2) ",
"q_1: |0>────────────────■──────────────────────",
" ┌─────────────────────────────────────┐",
"q_2: |0>┤ This is a really long long long box ├",
" └─────────────────────────────────────┘",
]
)
circuit = QuantumCircuit(3)
circuit.rzz(pi / 2, 0, 1)
circuit.x(2, label="This is a really long long long box")
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_cu1_on_wide_layer(self):
"""Test a labeled gate (CU1) in a wide layer.
See https://github.com/Qiskit/qiskit-terra/issues/4838"""
expected = "\n".join(
[
" ",
"q_0: |0>────────────────■──────────────────────",
" │U1(π/2) ",
"q_1: |0>────────────────■──────────────────────",
" ┌─────────────────────────────────────┐",
"q_2: |0>┤ This is a really long long long box ├",
" └─────────────────────────────────────┘",
]
)
circuit = QuantumCircuit(3)
circuit.append(CU1Gate(pi / 2), [0, 1])
circuit.x(2, label="This is a really long long long box")
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
class TestTextDrawerMultiQGates(QiskitTestCase):
"""Gates implying multiple qubits."""
def test_2Qgate(self):
"""2Q no params."""
expected = "\n".join(
[
" ┌───────┐",
"q_1: |0>┤1 ├",
" │ twoQ │",
"q_0: |0>┤0 ├",
" └───────┘",
]
)
qr = QuantumRegister(2, "q")
circuit = QuantumCircuit(qr)
my_gate2 = Gate(name="twoQ", num_qubits=2, params=[], label="twoQ")
circuit.append(my_gate2, [qr[0], qr[1]])
self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected)
def test_2Qgate_cross_wires(self):
"""2Q no params, with cross wires"""
expected = "\n".join(
[
" ┌───────┐",
"q_1: |0>┤0 ├",
" │ twoQ │",
"q_0: |0>┤1 ├",
" └───────┘",
]
)
qr = QuantumRegister(2, "q")
circuit = QuantumCircuit(qr)
my_gate2 = Gate(name="twoQ", num_qubits=2, params=[], label="twoQ")
circuit.append(my_gate2, [qr[1], qr[0]])
self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected)
def test_3Qgate_cross_wires(self):
"""3Q no params, with cross wires"""
expected = "\n".join(
[
" ┌─────────┐",
"q_2: |0>┤1 ├",
" │ │",
"q_1: |0>┤0 threeQ ├",
" │ │",
"q_0: |0>┤2 ├",
" └─────────┘",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
my_gate3 = Gate(name="threeQ", num_qubits=3, params=[], label="threeQ")
circuit.append(my_gate3, [qr[1], qr[2], qr[0]])
self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected)
def test_2Qgate_nottogether(self):
"""2Q that are not together"""
expected = "\n".join(
[
" ┌───────┐",
"q_2: |0>┤1 ├",
" │ │",
"q_1: |0>┤ twoQ ├",
" │ │",
"q_0: |0>┤0 ├",
" └───────┘",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
my_gate2 = Gate(name="twoQ", num_qubits=2, params=[], label="twoQ")
circuit.append(my_gate2, [qr[0], qr[2]])
self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected)
def test_2Qgate_nottogether_across_4(self):
"""2Q that are 2 bits apart"""
expected = "\n".join(
[
" ┌───────┐",
"q_3: |0>┤1 ├",
" │ │",
"q_2: |0>┤ ├",
" │ twoQ │",
"q_1: |0>┤ ├",
" │ │",
"q_0: |0>┤0 ├",
" └───────┘",
]
)
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
my_gate2 = Gate(name="twoQ", num_qubits=2, params=[], label="twoQ")
circuit.append(my_gate2, [qr[0], qr[3]])
self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected)
def test_unitary_nottogether_across_4(self):
"""unitary that are 2 bits apart"""
expected = "\n".join(
[
" ┌──────────┐",
"q_0: |0>┤0 ├",
" │ │",
"q_1: |0>┤ ├",
" │ Unitary │",
"q_2: |0>┤ ├",
" │ │",
"q_3: |0>┤1 ├",
" └──────────┘",
]
)
qr = QuantumRegister(4, "q")
qc = QuantumCircuit(qr)
qc.append(random_unitary(4, seed=42), [qr[0], qr[3]])
self.assertEqual(str(_text_circuit_drawer(qc)), expected)
def test_kraus(self):
"""Test Kraus.
See https://github.com/Qiskit/qiskit-terra/pull/2238#issuecomment-487630014"""
# fmt: off
expected = "\n".join([" ┌───────┐",
"q: |0>┤ kraus ├",
" └───────┘"])
# fmt: on
error = SuperOp(0.75 * numpy.eye(4) + 0.25 * numpy.diag([1, -1, -1, 1]))
qr = QuantumRegister(1, name="q")
qc = QuantumCircuit(qr)
qc.append(error, [qr[0]])
self.assertEqual(str(_text_circuit_drawer(qc)), expected)
def test_multiplexer(self):
"""Test Multiplexer.
See https://github.com/Qiskit/qiskit-terra/pull/2238#issuecomment-487630014"""
expected = "\n".join(
[
" ┌──────────────┐",
"q_0: |0>┤0 ├",
" │ Multiplexer │",
"q_1: |0>┤1 ├",
" └──────────────┘",
]
)
cx_multiplexer = UCGate([numpy.eye(2), numpy.array([[0, 1], [1, 0]])])
qr = QuantumRegister(2, name="q")
qc = QuantumCircuit(qr)
qc.append(cx_multiplexer, [qr[0], qr[1]])
self.assertEqual(str(_text_circuit_drawer(qc)), expected)
def test_label_over_name_2286(self):
"""If there is a label, it should be used instead of the name
See https://github.com/Qiskit/qiskit-terra/issues/2286"""
expected = "\n".join(
[
" ┌───┐┌───────┐┌────────┐",
"q_0: |0>┤ X ├┤ alt-X ├┤0 ├",
" └───┘└───────┘│ iswap │",
"q_1: |0>──────────────┤1 ├",
" └────────┘",
]
)
qr = QuantumRegister(2, "q")
circ = QuantumCircuit(qr)
circ.append(XGate(), [qr[0]])
circ.append(XGate(label="alt-X"), [qr[0]])
circ.append(UnitaryGate(numpy.eye(4), label="iswap"), [qr[0], qr[1]])
self.assertEqual(str(_text_circuit_drawer(circ)), expected)
def test_label_turns_to_box_2286(self):
"""If there is a label, non-boxes turn into boxes
See https://github.com/Qiskit/qiskit-terra/issues/2286"""
expected = "\n".join(
[
" cz label ",
"q_0: |0>─■─────■─────",
" │ │ ",
"q_1: |0>─■─────■─────",
" ",
]
)
qr = QuantumRegister(2, "q")
circ = QuantumCircuit(qr)
circ.append(CZGate(), [qr[0], qr[1]])
circ.append(CZGate(label="cz label"), [qr[0], qr[1]])
self.assertEqual(str(_text_circuit_drawer(circ)), expected)
def test_control_gate_with_base_label_4361(self):
"""Control gate has a label and a base gate with a label
See https://github.com/Qiskit/qiskit-terra/issues/4361"""
expected = "\n".join(
[
" ┌──────┐ my ch ┌──────┐",
"q_0: |0>┤ my h ├───■────┤ my h ├",
" └──────┘┌──┴───┐└──┬───┘",
"q_1: |0>────────┤ my h ├───■────",
" └──────┘ my ch ",
]
)
qr = QuantumRegister(2, "q")
circ = QuantumCircuit(qr)
hgate = HGate(label="my h")
controlh = hgate.control(label="my ch")
circ.append(hgate, [0])
circ.append(controlh, [0, 1])
circ.append(controlh, [1, 0])
self.assertEqual(str(_text_circuit_drawer(circ)), expected)
def test_control_gate_label_with_cond_1_low(self):
"""Control gate has a label and a conditional (compression=low)
See https://github.com/Qiskit/qiskit-terra/issues/4361"""
expected = "\n".join(
[
" my ch ",
"q_0: |0>───■────",
" │ ",
" ┌──┴───┐",
"q_1: |0>┤ my h ├",
" └──╥───┘",
" ┌──╨──┐ ",
" c: 0 1/╡ 0x1 ╞═",
" └─────┘ ",
]
)
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
circ = QuantumCircuit(qr, cr)
hgate = HGate(label="my h")
controlh = hgate.control(label="my ch").c_if(cr, 1)
circ.append(controlh, [0, 1])
self.assertEqual(str(_text_circuit_drawer(circ, vertical_compression="low")), expected)
def test_control_gate_label_with_cond_1_low_cregbundle(self):
"""Control gate has a label and a conditional (compression=low) with cregbundle
See https://github.com/Qiskit/qiskit-terra/issues/4361"""
expected = "\n".join(
[
" my ch ",
"q_0: |0>───■────",
" │ ",
" ┌──┴───┐",
"q_1: |0>┤ my h ├",
" └──╥───┘",
" ┌──╨──┐ ",
" c: 0 1/╡ 0x1 ╞═",
" └─────┘ ",
]
)
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
circ = QuantumCircuit(qr, cr)
hgate = HGate(label="my h")
controlh = hgate.control(label="my ch").c_if(cr, 1)
circ.append(controlh, [0, 1])
self.assertEqual(
str(_text_circuit_drawer(circ, vertical_compression="low", cregbundle=True)), expected
)
def test_control_gate_label_with_cond_1_med(self):
"""Control gate has a label and a conditional (compression=med)
See https://github.com/Qiskit/qiskit-terra/issues/4361"""
expected = "\n".join(
[
" my ch ",
"q_0: |0>───■────",
" ┌──┴───┐",
"q_1: |0>┤ my h ├",
" └──╥───┘",
" c: 0 ═══■════",
" 0x1 ",
]
)
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
circ = QuantumCircuit(qr, cr)
hgate = HGate(label="my h")
controlh = hgate.control(label="my ch").c_if(cr, 1)
circ.append(controlh, [0, 1])
self.assertEqual(
str(_text_circuit_drawer(circ, cregbundle=False, vertical_compression="medium")),
expected,
)
def test_control_gate_label_with_cond_1_med_cregbundle(self):
"""Control gate has a label and a conditional (compression=med) with cregbundle
See https://github.com/Qiskit/qiskit-terra/issues/4361"""
expected = "\n".join(
[
" my ch ",
"q_0: |0>───■────",
" ┌──┴───┐",
"q_1: |0>┤ my h ├",
" └──╥───┘",
" ┌──╨──┐ ",
" c: 0 1/╡ 0x1 ╞═",
" └─────┘ ",
]
)
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
circ = QuantumCircuit(qr, cr)
hgate = HGate(label="my h")
controlh = hgate.control(label="my ch").c_if(cr, 1)
circ.append(controlh, [0, 1])
self.assertEqual(
str(_text_circuit_drawer(circ, vertical_compression="medium", cregbundle=True)),
expected,
)
def test_control_gate_label_with_cond_1_high(self):
"""Control gate has a label and a conditional (compression=high)
See https://github.com/Qiskit/qiskit-terra/issues/4361"""
expected = "\n".join(
[
" my ch ",
"q_0: |0>───■────",
" ┌──┴───┐",
"q_1: |0>┤ my h ├",
" └──╥───┘",
" c: 0 ═══■════",
" 0x1 ",
]
)
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
circ = QuantumCircuit(qr, cr)
hgate = HGate(label="my h")
controlh = hgate.control(label="my ch").c_if(cr, 1)
circ.append(controlh, [0, 1])
self.assertEqual(
str(_text_circuit_drawer(circ, cregbundle=False, vertical_compression="high")), expected
)
def test_control_gate_label_with_cond_1_high_cregbundle(self):
"""Control gate has a label and a conditional (compression=high) with cregbundle
See https://github.com/Qiskit/qiskit-terra/issues/4361"""
expected = "\n".join(
[
" my ch ",
"q_0: |0>───■────",
" ┌──┴───┐",
"q_1: |0>┤ my h ├",
" ├──╨──┬┘",
" c: 0 1/╡ 0x1 ╞═",
" └─────┘ ",
]
)
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
circ = QuantumCircuit(qr, cr)
hgate = HGate(label="my h")
controlh = hgate.control(label="my ch").c_if(cr, 1)
circ.append(controlh, [0, 1])
self.assertEqual(
str(_text_circuit_drawer(circ, vertical_compression="high", cregbundle=True)), expected
)
def test_control_gate_label_with_cond_2_med_space(self):
"""Control gate has a label and a conditional (on label, compression=med)
See https://github.com/Qiskit/qiskit-terra/issues/4361"""
expected = "\n".join(
[
" ┌──────┐",
"q_0: |0>┤ my h ├",
" └──┬───┘",
"q_1: |0>───■────",
" my ch ",
" ┌──╨──┐ ",
" c: 0 1/╡ 0x1 ╞═",
" └─────┘ ",
]
)
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
circ = QuantumCircuit(qr, cr)
hgate = HGate(label="my h")
controlh = hgate.control(label="my ch").c_if(cr, 1)
circ.append(controlh, [1, 0])
self.assertEqual(str(_text_circuit_drawer(circ, vertical_compression="medium")), expected)
def test_control_gate_label_with_cond_2_med(self):
"""Control gate has a label and a conditional (on label, compression=med)
See https://github.com/Qiskit/qiskit-terra/issues/4361"""
expected = "\n".join(
[
" ┌──────┐ ",
"q_0: |0>──┤ my h ├─",
" └──┬───┘ ",
"q_1: |0>─────■─────",
" my ctrl-h ",
" ║ ",
" c: 0 ═════■═════",
" 0x1 ",
]
)
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
circ = QuantumCircuit(qr, cr)
hgate = HGate(label="my h")
controlh = hgate.control(label="my ctrl-h").c_if(cr, 1)
circ.append(controlh, [1, 0])
self.assertEqual(
str(_text_circuit_drawer(circ, cregbundle=False, vertical_compression="medium")),
expected,
)
def test_control_gate_label_with_cond_2_med_cregbundle(self):
"""Control gate has a label and a conditional (on label, compression=med) with cregbundle
See https://github.com/Qiskit/qiskit-terra/issues/4361"""
expected = "\n".join(
[
" ┌──────┐",
"q_0: |0>┤ my h ├",
" └──┬───┘",
"q_1: |0>───■────",
" my ch ",
" ┌──╨──┐ ",
" c: 0 1/╡ 0x1 ╞═",
" └─────┘ ",
]
)
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
circ = QuantumCircuit(qr, cr)
hgate = HGate(label="my h")
controlh = hgate.control(label="my ch").c_if(cr, 1)
circ.append(controlh, [1, 0])
self.assertEqual(
str(_text_circuit_drawer(circ, vertical_compression="medium", cregbundle=True)),
expected,
)
def test_control_gate_label_with_cond_2_low(self):
"""Control gate has a label and a conditional (on label, compression=low)
See https://github.com/Qiskit/qiskit-terra/issues/4361"""
expected = "\n".join(
[
" ┌──────┐",
"q_0: |0>┤ my h ├",
" └──┬───┘",
" │ ",
"q_1: |0>───■────",
" my ch ",
" ║ ",
" c: 0 ═══■════",
" 0x1 ",
]
)
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
circ = QuantumCircuit(qr, cr)
hgate = HGate(label="my h")
controlh = hgate.control(label="my ch").c_if(cr, 1)
circ.append(controlh, [1, 0])
self.assertEqual(
str(_text_circuit_drawer(circ, cregbundle=False, vertical_compression="low")), expected
)
def test_control_gate_label_with_cond_2_low_cregbundle(self):
"""Control gate has a label and a conditional (on label, compression=low) with cregbundle
See https://github.com/Qiskit/qiskit-terra/issues/4361"""
expected = "\n".join(
[
" ┌──────┐",
"q_0: |0>┤ my h ├",
" └──┬───┘",
" │ ",
"q_1: |0>───■────",
" my ch ",
" ┌──╨──┐ ",
" c: 0 1/╡ 0x1 ╞═",
" └─────┘ ",
]
)
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
circ = QuantumCircuit(qr, cr)
hgate = HGate(label="my h")
controlh = hgate.control(label="my ch").c_if(cr, 1)
circ.append(controlh, [1, 0])
self.assertEqual(
str(_text_circuit_drawer(circ, vertical_compression="low", cregbundle=True)), expected
)
class TestTextDrawerParams(QiskitTestCase):
"""Test drawing parameters."""
def test_text_no_parameters(self):
"""Test drawing with no parameters"""
expected = "\n".join(
[
" ┌───┐",
"q: |0>┤ X ├",
" └───┘",
]
)
qr = QuantumRegister(1, "q")
circuit = QuantumCircuit(qr)
circuit.x(0)
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_parameters_mix(self):
"""cu3 drawing with parameters"""
expected = "\n".join(
[
" ",
"q_0: |0>─────────■──────────",
" ┌────────┴─────────┐",
"q_1: |0>┤ U(π/2,theta,π,0) ├",
" └──────────────────┘",
]
)
qr = QuantumRegister(2, "q")
circuit = QuantumCircuit(qr)
circuit.cu(pi / 2, Parameter("theta"), pi, 0, qr[0], qr[1])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_bound_parameters(self):
"""Bound parameters
See: https://github.com/Qiskit/qiskit-terra/pull/3876"""
# fmt: off
expected = "\n".join([" ┌────────────┐",
"qr: |0>┤ my_u2(π,π) ├",
" └────────────┘"])
# fmt: on
my_u2_circuit = QuantumCircuit(1, name="my_u2")
phi = Parameter("phi")
lam = Parameter("lambda")
my_u2_circuit.u(3.141592653589793, phi, lam, 0)
my_u2 = my_u2_circuit.to_gate()
qr = QuantumRegister(1, name="qr")
circuit = QuantumCircuit(qr, name="circuit")
circuit.append(my_u2, [qr[0]])
circuit = circuit.bind_parameters({phi: 3.141592653589793, lam: 3.141592653589793})
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_pi_param_expr(self):
"""Text pi in circuit with parameter expression."""
expected = "\n".join(
[
" ┌─────────────────────┐",
"q: ┤ Rx((π - x)*(π - y)) ├",
" └─────────────────────┘",
]
)
x, y = Parameter("x"), Parameter("y")
circuit = QuantumCircuit(1)
circuit.rx((pi - x) * (pi - y), 0)
self.assertEqual(circuit.draw(output="text").single_string(), expected)
def test_text_utf8(self):
"""Test that utf8 characters work in windows CI env."""
# fmt: off
expected = "\n".join([" ┌──────────┐",
"q: ┤ U(0,φ,λ) ├",
" └──────────┘"])
# fmt: on
phi, lam = Parameter("φ"), Parameter("λ")
circuit = QuantumCircuit(1)
circuit.u(0, phi, lam, 0)
self.assertEqual(circuit.draw(output="text").single_string(), expected)
def test_text_ndarray_parameters(self):
"""Test that if params are type ndarray, params are not displayed."""
# fmt: off
expected = "\n".join([" ┌─────────┐",
"q: |0>┤ Unitary ├",
" └─────────┘"])
# fmt: on
qr = QuantumRegister(1, "q")
circuit = QuantumCircuit(qr)
circuit.unitary(numpy.array([[0, 1], [1, 0]]), 0)
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_qc_parameters(self):
"""Test that if params are type QuantumCircuit, params are not displayed."""
expected = "\n".join(
[
" ┌───────┐",
"q_0: |0>┤0 ├",
" │ name │",
"q_1: |0>┤1 ├",
" └───────┘",
]
)
my_qc_param = QuantumCircuit(2)
my_qc_param.h(0)
my_qc_param.cx(0, 1)
inst = Instruction("name", 2, 0, [my_qc_param])
qr = QuantumRegister(2, "q")
circuit = QuantumCircuit(qr)
circuit.append(inst, [0, 1])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
class TestTextDrawerVerticalCompressionLow(QiskitTestCase):
"""Test vertical_compression='low'"""
def test_text_conditional_1(self):
"""Conditional drawing with 1-bit-length regs."""
qasm_string = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[1];
creg c0[1];
creg c1[1];
if(c0==1) x q[0];
if(c1==1) x q[0];
"""
expected = "\n".join(
[
" ┌───┐┌───┐",
"q: |0>┤ X ├┤ X ├",
" └─╥─┘└─╥─┘",
" ║ ║ ",
"c0: 0 ══■════╬══",
" 0x1 ║ ",
" ║ ",
"c1: 0 ═══════■══",
" 0x1 ",
]
)
circuit = QuantumCircuit.from_qasm_str(qasm_string)
self.assertEqual(
str(_text_circuit_drawer(circuit, cregbundle=False, vertical_compression="low")),
expected,
)
def test_text_conditional_1_bundle(self):
"""Conditional drawing with 1-bit-length regs."""
qasm_string = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[1];
creg c0[1];
creg c1[1];
if(c0==1) x q[0];
if(c1==1) x q[0];
"""
expected = "\n".join(
[
" ┌───┐ ┌───┐ ",
" q: |0>─┤ X ├──┤ X ├─",
" └─╥─┘ └─╥─┘ ",
" ┌──╨──┐ ║ ",
"c0: 0 1/╡ 0x1 ╞═══╬═══",
" └─────┘ ║ ",
" ┌──╨──┐",
"c1: 0 1/═══════╡ 0x1 ╞",
" └─────┘",
]
)
circuit = QuantumCircuit.from_qasm_str(qasm_string)
self.assertEqual(
str(_text_circuit_drawer(circuit, vertical_compression="low", cregbundle=True)),
expected,
)
def test_text_conditional_reverse_bits_true(self):
"""Conditional drawing with 1-bit-length regs."""
cr = ClassicalRegister(2, "cr")
cr2 = ClassicalRegister(1, "cr2")
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr, cr, cr2)
circuit.h(0)
circuit.h(1)
circuit.h(2)
circuit.x(0)
circuit.x(0)
circuit.measure(2, 1)
circuit.x(2).c_if(cr, 2)
expected = "\n".join(
[
" ┌───┐ ┌─┐ ┌───┐",
"qr_2: |0>┤ H ├─────┤M├─────┤ X ├",
" └───┘ └╥┘ └─╥─┘",
" ┌───┐ ║ ║ ",
"qr_1: |0>┤ H ├──────╫────────╫──",
" └───┘ ║ ║ ",
" ┌───┐┌───┐ ║ ┌───┐ ║ ",
"qr_0: |0>┤ H ├┤ X ├─╫─┤ X ├──╫──",
" └───┘└───┘ ║ └───┘ ║ ",
" ║ ║ ",
" cr2: 0 ═══════════╬════════╬══",
" ║ ║ ",
" ║ ║ ",
" cr_1: 0 ═══════════╩════════■══",
" ║ ",
" ║ ",
" cr_0: 0 ════════════════════o══",
" 0x2 ",
]
)
self.assertEqual(
str(
_text_circuit_drawer(
circuit, vertical_compression="low", cregbundle=False, reverse_bits=True
)
),
expected,
)
def test_text_conditional_reverse_bits_false(self):
"""Conditional drawing with 1-bit-length regs."""
cr = ClassicalRegister(2, "cr")
cr2 = ClassicalRegister(1, "cr2")
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr, cr, cr2)
circuit.h(0)
circuit.h(1)
circuit.h(2)
circuit.x(0)
circuit.x(0)
circuit.measure(2, 1)
circuit.x(2).c_if(cr, 2)
expected = "\n".join(
[
" ┌───┐┌───┐┌───┐",
"qr_0: |0>┤ H ├┤ X ├┤ X ├",
" └───┘└───┘└───┘",
" ┌───┐ ",
"qr_1: |0>┤ H ├──────────",
" └───┘ ",
" ┌───┐ ┌─┐ ┌───┐",
"qr_2: |0>┤ H ├─┤M├─┤ X ├",
" └───┘ └╥┘ └─╥─┘",
" ║ ║ ",
" cr_0: 0 ═══════╬════o══",
" ║ ║ ",
" ║ ║ ",
" cr_1: 0 ═══════╩════■══",
" 0x2 ",
" ",
" cr2: 0 ═══════════════",
" ",
]
)
self.assertEqual(
str(
_text_circuit_drawer(
circuit, vertical_compression="low", cregbundle=False, reverse_bits=False
)
),
expected,
)
def test_text_justify_right(self):
"""Drawing with right justify"""
expected = "\n".join(
[
" ┌───┐",
"q1_0: |0>─────┤ X ├",
" └───┘",
" ┌───┐ ┌─┐ ",
"q1_1: |0>┤ H ├─┤M├─",
" └───┘ └╥┘ ",
" ║ ",
" c1: 0 2/═══════╩══",
" 1 ",
]
)
qr1 = QuantumRegister(2, "q1")
cr1 = ClassicalRegister(2, "c1")
circuit = QuantumCircuit(qr1, cr1)
circuit.x(qr1[0])
circuit.h(qr1[1])
circuit.measure(qr1[1], cr1[1])
self.assertEqual(
str(_text_circuit_drawer(circuit, justify="right", vertical_compression="low")),
expected,
)
class TestTextDrawerVerticalCompressionMedium(QiskitTestCase):
"""Test vertical_compression='medium'"""
def test_text_conditional_1(self):
"""Medium vertical compression avoids box overlap."""
qasm_string = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[1];
creg c0[1];
creg c1[1];
if(c0==1) x q[0];
if(c1==1) x q[0];
"""
expected = "\n".join(
[
" ┌───┐┌───┐",
"q: |0>┤ X ├┤ X ├",
" └─╥─┘└─╥─┘",
"c0: 0 ══■════╬══",
" 0x1 ║ ",
"c1: 0 ═══════■══",
" 0x1 ",
]
)
circuit = QuantumCircuit.from_qasm_str(qasm_string)
self.assertEqual(
str(_text_circuit_drawer(circuit, cregbundle=False, vertical_compression="medium")),
expected,
)
def test_text_conditional_1_bundle(self):
"""Medium vertical compression avoids box overlap."""
qasm_string = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[1];
creg c0[1];
creg c1[1];
if(c0==1) x q[0];
if(c1==1) x q[0];
"""
expected = "\n".join(
[
" ┌───┐ ┌───┐ ",
" q: |0>─┤ X ├──┤ X ├─",
" └─╥─┘ └─╥─┘ ",
" ┌──╨──┐ ║ ",
"c0: 0 1/╡ 0x1 ╞═══╬═══",
" └─────┘┌──╨──┐",
"c1: 0 1/═══════╡ 0x1 ╞",
" └─────┘",
]
)
circuit = QuantumCircuit.from_qasm_str(qasm_string)
self.assertEqual(
str(_text_circuit_drawer(circuit, vertical_compression="medium", cregbundle=True)),
expected,
)
def test_text_measure_with_spaces(self):
"""Measure wire might have extra spaces
Found while reproducing
https://quantumcomputing.stackexchange.com/q/10194/1859"""
qasm_string = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[2];
creg c[3];
measure q[0] -> c[1];
if(c==1) x q[1];
"""
expected = "\n".join(
[
" ┌─┐ ",
"q_0: |0>┤M├─────",
" └╥┘┌───┐",
"q_1: |0>─╫─┤ X ├",
" ║ └─╥─┘",
" c_0: 0 ═╬═══■══",
" ║ ║ ",
" c_1: 0 ═╩═══o══",
" ║ ",
" c_2: 0 ═════o══",
" 0x1 ",
]
)
circuit = QuantumCircuit.from_qasm_str(qasm_string)
self.assertEqual(
str(_text_circuit_drawer(circuit, cregbundle=False, vertical_compression="medium")),
expected,
)
def test_text_measure_with_spaces_bundle(self):
"""Measure wire might have extra spaces
Found while reproducing
https://quantumcomputing.stackexchange.com/q/10194/1859"""
qasm_string = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[2];
creg c[3];
measure q[0] -> c[1];
if(c==1) x q[1];
"""
expected = "\n".join(
[
" ┌─┐ ",
"q_0: |0>┤M├───────",
" └╥┘ ┌───┐ ",
"q_1: |0>─╫──┤ X ├─",
" ║ └─╥─┘ ",
" ║ ┌──╨──┐",
" c: 0 3/═╩═╡ 0x1 ╞",
" 1 └─────┘",
]
)
circuit = QuantumCircuit.from_qasm_str(qasm_string)
self.assertEqual(
str(_text_circuit_drawer(circuit, vertical_compression="medium", cregbundle=True)),
expected,
)
def test_text_barrier_med_compress_1(self):
"""Medium vertical compression avoids connection break."""
circuit = QuantumCircuit(4)
circuit.cx(1, 3)
circuit.x(1)
circuit.barrier((2, 3), label="Bar 1")
expected = "\n".join(
[
" ",
"q_0: |0>────────────",
" ┌───┐ ",
"q_1: |0>──■───┤ X ├─",
" │ └───┘ ",
" │ Bar 1 ",
"q_2: |0>──┼─────░───",
" ┌─┴─┐ ░ ",
"q_3: |0>┤ X ├───░───",
" └───┘ ░ ",
]
)
self.assertEqual(
str(_text_circuit_drawer(circuit, vertical_compression="medium", cregbundle=False)),
expected,
)
def test_text_barrier_med_compress_2(self):
"""Medium vertical compression avoids overprint."""
circuit = QuantumCircuit(4)
circuit.barrier((0, 1, 2), label="a")
circuit.cx(1, 3)
circuit.x(1)
circuit.barrier((2, 3), label="Bar 1")
expected = "\n".join(
[
" a ",
"q_0: |0>─░─────────────",
" ░ ┌───┐ ",
"q_1: |0>─░───■───┤ X ├─",
" ░ │ └───┘ ",
" ░ │ Bar 1 ",
"q_2: |0>─░───┼─────░───",
" ░ ┌─┴─┐ ░ ",
"q_3: |0>───┤ X ├───░───",
" └───┘ ░ ",
]
)
self.assertEqual(
str(_text_circuit_drawer(circuit, vertical_compression="medium", cregbundle=False)),
expected,
)
def test_text_barrier_med_compress_3(self):
"""Medium vertical compression avoids conditional connection break."""
qr = QuantumRegister(1, "qr")
qc1 = ClassicalRegister(3, "cr")
qc2 = ClassicalRegister(1, "cr2")
circuit = QuantumCircuit(qr, qc1, qc2)
circuit.x(0).c_if(qc1, 3)
circuit.x(0).c_if(qc2[0], 1)
expected = "\n".join(
[
" ┌───┐┌───┐",
" qr: |0>┤ X ├┤ X ├",
" └─╥─┘└─╥─┘",
"cr_0: 0 ══■════╬══",
" ║ ║ ",
"cr_2: 0 ══o════╬══",
" ║ ║ ",
" cr2: 0 ══╬════■══",
" ║ ",
"cr_1: 0 ══■═══════",
" 0x3 ",
]
)
self.assertEqual(
str(
_text_circuit_drawer(
circuit,
vertical_compression="medium",
wire_order=[0, 1, 3, 4, 2],
cregbundle=False,
)
),
expected,
)
class TestTextConditional(QiskitTestCase):
"""Gates with conditionals"""
def test_text_conditional_1_cregbundle(self):
"""Conditional drawing with 1-bit-length regs and cregbundle."""
qasm_string = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[1];
creg c0[1];
creg c1[1];
if(c0==1) x q[0];
if(c1==1) x q[0];
"""
expected = "\n".join(
[
" ┌───┐ ┌───┐ ",
" q: |0>─┤ X ├──┤ X ├─",
" ┌┴─╨─┴┐ └─╥─┘ ",
"c0: 0 1/╡ 0x1 ╞═══╬═══",
" └─────┘┌──╨──┐",
"c1: 0 1/═══════╡ 0x1 ╞",
" └─────┘",
]
)
circuit = QuantumCircuit.from_qasm_str(qasm_string)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_conditional_1(self):
"""Conditional drawing with 1-bit-length regs."""
qasm_string = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[1];
creg c0[1];
creg c1[1];
if(c0==1) x q[0];
if(c1==1) x q[0];
"""
expected = "\n".join(
[
" ┌───┐┌───┐",
"q: |0>┤ X ├┤ X ├",
" └─╥─┘└─╥─┘",
"c0: 0 ══■════╬══",
" 0x1 ║ ",
"c1: 0 ═══════■══",
" 0x1 ",
]
)
circuit = QuantumCircuit.from_qasm_str(qasm_string)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_text_conditional_2_cregbundle(self):
"""Conditional drawing with 2-bit-length regs with cregbundle"""
qasm_string = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[1];
creg c0[2];
creg c1[2];
if(c0==2) x q[0];
if(c1==2) x q[0];
"""
expected = "\n".join(
[
" ┌───┐ ┌───┐ ",
" q: |0>─┤ X ├──┤ X ├─",
" ┌┴─╨─┴┐ └─╥─┘ ",
"c0: 0 2/╡ 0x2 ╞═══╬═══",
" └─────┘┌──╨──┐",
"c1: 0 2/═══════╡ 0x2 ╞",
" └─────┘",
]
)
circuit = QuantumCircuit.from_qasm_str(qasm_string)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_conditional_2(self):
"""Conditional drawing with 2-bit-length regs."""
qasm_string = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[1];
creg c0[2];
creg c1[2];
if(c0==2) x q[0];
if(c1==2) x q[0];
"""
expected = "\n".join(
[
" ┌───┐┌───┐",
" q: |0>┤ X ├┤ X ├",
" └─╥─┘└─╥─┘",
"c0_0: 0 ══o════╬══",
" ║ ║ ",
"c0_1: 0 ══■════╬══",
" 0x2 ║ ",
"c1_0: 0 ═══════o══",
" ║ ",
"c1_1: 0 ═══════■══",
" 0x2 ",
]
)
circuit = QuantumCircuit.from_qasm_str(qasm_string)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_text_conditional_3_cregbundle(self):
"""Conditional drawing with 3-bit-length regs with cregbundle."""
qasm_string = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[1];
creg c0[3];
creg c1[3];
if(c0==3) x q[0];
if(c1==3) x q[0];
"""
expected = "\n".join(
[
" ┌───┐ ┌───┐ ",
" q: |0>─┤ X ├──┤ X ├─",
" ┌┴─╨─┴┐ └─╥─┘ ",
"c0: 0 3/╡ 0x3 ╞═══╬═══",
" └─────┘┌──╨──┐",
"c1: 0 3/═══════╡ 0x3 ╞",
" └─────┘",
]
)
circuit = QuantumCircuit.from_qasm_str(qasm_string)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_conditional_3(self):
"""Conditional drawing with 3-bit-length regs."""
qasm_string = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[1];
creg c0[3];
creg c1[3];
if(c0==3) x q[0];
if(c1==3) x q[0];
"""
expected = "\n".join(
[
" ┌───┐┌───┐",
" q: |0>┤ X ├┤ X ├",
" └─╥─┘└─╥─┘",
"c0_0: 0 ══■════╬══",
" ║ ║ ",
"c0_1: 0 ══■════╬══",
" ║ ║ ",
"c0_2: 0 ══o════╬══",
" 0x3 ║ ",
"c1_0: 0 ═══════■══",
" ║ ",
"c1_1: 0 ═══════■══",
" ║ ",
"c1_2: 0 ═══════o══",
" 0x3 ",
]
)
circuit = QuantumCircuit.from_qasm_str(qasm_string)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_text_conditional_4(self):
"""Conditional drawing with 4-bit-length regs."""
qasm_string = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[1];
creg c0[4];
creg c1[4];
if(c0==4) x q[0];
if(c1==4) x q[0];
"""
expected = "\n".join(
[
" ┌───┐ ┌───┐ ",
" q: |0>─┤ X ├──┤ X ├─",
" ┌┴─╨─┴┐ └─╥─┘ ",
"c0: 0 4/╡ 0x4 ╞═══╬═══",
" └─────┘┌──╨──┐",
"c1: 0 4/═══════╡ 0x4 ╞",
" └─────┘",
]
)
circuit = QuantumCircuit.from_qasm_str(qasm_string)
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_conditional_5(self):
"""Conditional drawing with 5-bit-length regs."""
qasm_string = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[1];
creg c0[5];
creg c1[5];
if(c0==5) x q[0];
if(c1==5) x q[0];
"""
expected = "\n".join(
[
" ┌───┐┌───┐",
" q: |0>┤ X ├┤ X ├",
" └─╥─┘└─╥─┘",
"c0_0: 0 ══■════╬══",
" ║ ║ ",
"c0_1: 0 ══o════╬══",
" ║ ║ ",
"c0_2: 0 ══■════╬══",
" ║ ║ ",
"c0_3: 0 ══o════╬══",
" ║ ║ ",
"c0_4: 0 ══o════╬══",
" 0x5 ║ ",
"c1_0: 0 ═══════■══",
" ║ ",
"c1_1: 0 ═══════o══",
" ║ ",
"c1_2: 0 ═══════■══",
" ║ ",
"c1_3: 0 ═══════o══",
" ║ ",
"c1_4: 0 ═══════o══",
" 0x5 ",
]
)
circuit = QuantumCircuit.from_qasm_str(qasm_string)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_text_conditional_cz_no_space_cregbundle(self):
"""Conditional CZ without space"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.cz(qr[0], qr[1]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>───■───",
" │ ",
"qr_1: |0>───■───",
" ┌──╨──┐",
" cr: 0 1/╡ 0x1 ╞",
" └─────┘",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_conditional_cz_no_space(self):
"""Conditional CZ without space"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.cz(qr[0], qr[1]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>──■──",
" │ ",
"qr_1: |0>──■──",
" ║ ",
" cr: 0 ══■══",
" 0x1 ",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_text_conditional_cz_cregbundle(self):
"""Conditional CZ with a wire in the middle"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.cz(qr[0], qr[1]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>───■───",
" │ ",
"qr_1: |0>───■───",
" ║ ",
"qr_2: |0>───╫───",
" ┌──╨──┐",
" cr: 0 1/╡ 0x1 ╞",
" └─────┘",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_conditional_cz(self):
"""Conditional CZ with a wire in the middle"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.cz(qr[0], qr[1]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>──■──",
" │ ",
"qr_1: |0>──■──",
" ║ ",
"qr_2: |0>──╫──",
" ║ ",
" cr: 0 ══■══",
" 0x1 ",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_text_conditional_cx_ct_cregbundle(self):
"""Conditional CX (control-target) with a wire in the middle"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.cx(qr[0], qr[1]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>───■───",
" ┌─┴─┐ ",
"qr_1: |0>─┤ X ├─",
" └─╥─┘ ",
"qr_2: |0>───╫───",
" ┌──╨──┐",
" cr: 0 1/╡ 0x1 ╞",
" └─────┘",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_conditional_cx_ct(self):
"""Conditional CX (control-target) with a wire in the middle"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.cx(qr[0], qr[1]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>──■──",
" ┌─┴─┐",
"qr_1: |0>┤ X ├",
" └─╥─┘",
"qr_2: |0>──╫──",
" ║ ",
" cr: 0 ══■══",
" 0x1 ",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_text_conditional_cx_tc_cregbundle(self):
"""Conditional CX (target-control) with a wire in the middle with cregbundle."""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.cx(qr[1], qr[0]).c_if(cr, 1)
expected = "\n".join(
[
" ┌───┐ ",
"qr_0: |0>─┤ X ├─",
" └─┬─┘ ",
"qr_1: |0>───■───",
" ║ ",
"qr_2: |0>───╫───",
" ┌──╨──┐",
" cr: 0 1/╡ 0x1 ╞",
" └─────┘",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_conditional_cx_tc(self):
"""Conditional CX (target-control) with a wire in the middle"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.cx(qr[1], qr[0]).c_if(cr, 1)
expected = "\n".join(
[
" ┌───┐",
"qr_0: |0>┤ X ├",
" └─┬─┘",
"qr_1: |0>──■──",
" ║ ",
"qr_2: |0>──╫──",
" ║ ",
" cr: 0 ══■══",
" 0x1 ",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_text_conditional_cu3_ct_cregbundle(self):
"""Conditional Cu3 (control-target) with a wire in the middle with cregbundle"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.append(CU3Gate(pi / 2, pi / 2, pi / 2), [qr[0], qr[1]]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>─────────■─────────",
" ┌────────┴────────┐",
"qr_1: |0>┤ U3(π/2,π/2,π/2) ├",
" └────────╥────────┘",
"qr_2: |0>─────────╫─────────",
" ┌──╨──┐ ",
" cr: 0 1/══════╡ 0x1 ╞══════",
" └─────┘ ",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_conditional_cu3_ct(self):
"""Conditional Cu3 (control-target) with a wire in the middle"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.append(CU3Gate(pi / 2, pi / 2, pi / 2), [qr[0], qr[1]]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>─────────■─────────",
" ┌────────┴────────┐",
"qr_1: |0>┤ U3(π/2,π/2,π/2) ├",
" └────────╥────────┘",
"qr_2: |0>─────────╫─────────",
" ║ ",
" cr: 0 ═════════■═════════",
" 0x1 ",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_text_conditional_cu3_tc_cregbundle(self):
"""Conditional Cu3 (target-control) with a wire in the middle with cregbundle"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.append(CU3Gate(pi / 2, pi / 2, pi / 2), [qr[1], qr[0]]).c_if(cr, 1)
expected = "\n".join(
[
" ┌─────────────────┐",
"qr_0: |0>┤ U3(π/2,π/2,π/2) ├",
" └────────┬────────┘",
"qr_1: |0>─────────■─────────",
" ║ ",
"qr_2: |0>─────────╫─────────",
" ┌──╨──┐ ",
" cr: 0 1/══════╡ 0x1 ╞══════",
" └─────┘ ",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_conditional_cu3_tc(self):
"""Conditional Cu3 (target-control) with a wire in the middle"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.append(CU3Gate(pi / 2, pi / 2, pi / 2), [qr[1], qr[0]]).c_if(cr, 1)
expected = "\n".join(
[
" ┌─────────────────┐",
"qr_0: |0>┤ U3(π/2,π/2,π/2) ├",
" └────────┬────────┘",
"qr_1: |0>─────────■─────────",
" ║ ",
"qr_2: |0>─────────╫─────────",
" ║ ",
" cr: 0 ═════════■═════════",
" 0x1 ",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_text_conditional_ccx_cregbundle(self):
"""Conditional CCX with a wire in the middle with cregbundle"""
qr = QuantumRegister(4, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.ccx(qr[0], qr[1], qr[2]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>───■───",
" │ ",
"qr_1: |0>───■───",
" ┌─┴─┐ ",
"qr_2: |0>─┤ X ├─",
" └─╥─┘ ",
"qr_3: |0>───╫───",
" ┌──╨──┐",
" cr: 0 1/╡ 0x1 ╞",
" └─────┘",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_conditional_ccx(self):
"""Conditional CCX with a wire in the middle"""
qr = QuantumRegister(4, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.ccx(qr[0], qr[1], qr[2]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>──■──",
" │ ",
"qr_1: |0>──■──",
" ┌─┴─┐",
"qr_2: |0>┤ X ├",
" └─╥─┘",
"qr_3: |0>──╫──",
" ║ ",
" cr: 0 ══■══",
" 0x1 ",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_text_conditional_ccx_no_space_cregbundle(self):
"""Conditional CCX without space with cregbundle"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.ccx(qr[0], qr[1], qr[2]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>───■───",
" │ ",
"qr_1: |0>───■───",
" ┌─┴─┐ ",
"qr_2: |0>─┤ X ├─",
" ┌┴─╨─┴┐",
" cr: 0 1/╡ 0x1 ╞",
" └─────┘",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_conditional_ccx_no_space(self):
"""Conditional CCX without space"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.ccx(qr[0], qr[1], qr[2]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>──■──",
" │ ",
"qr_1: |0>──■──",
" ┌─┴─┐",
"qr_2: |0>┤ X ├",
" └─╥─┘",
" cr: 0 ══■══",
" 0x1 ",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_text_conditional_h_cregbundle(self):
"""Conditional H with a wire in the middle with cregbundle"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0]).c_if(cr, 1)
expected = "\n".join(
[
" ┌───┐ ",
"qr_0: |0>─┤ H ├─",
" └─╥─┘ ",
"qr_1: |0>───╫───",
" ┌──╨──┐",
" cr: 0 1/╡ 0x1 ╞",
" └─────┘",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_conditional_h(self):
"""Conditional H with a wire in the middle"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0]).c_if(cr, 1)
expected = "\n".join(
[
" ┌───┐",
"qr_0: |0>┤ H ├",
" └─╥─┘",
"qr_1: |0>──╫──",
" ║ ",
" cr: 0 ══■══",
" 0x1 ",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_text_conditional_swap_cregbundle(self):
"""Conditional SWAP with cregbundle"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.swap(qr[0], qr[1]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>───X───",
" │ ",
"qr_1: |0>───X───",
" ║ ",
"qr_2: |0>───╫───",
" ┌──╨──┐",
" cr: 0 1/╡ 0x1 ╞",
" └─────┘",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_conditional_swap(self):
"""Conditional SWAP"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.swap(qr[0], qr[1]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>──X──",
" │ ",
"qr_1: |0>──X──",
" ║ ",
"qr_2: |0>──╫──",
" ║ ",
" cr: 0 ══■══",
" 0x1 ",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_text_conditional_cswap_cregbundle(self):
"""Conditional CSwap with cregbundle"""
qr = QuantumRegister(4, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.cswap(qr[0], qr[1], qr[2]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>───■───",
" │ ",
"qr_1: |0>───X───",
" │ ",
"qr_2: |0>───X───",
" ║ ",
"qr_3: |0>───╫───",
" ┌──╨──┐",
" cr: 0 1/╡ 0x1 ╞",
" └─────┘",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_conditional_cswap(self):
"""Conditional CSwap"""
qr = QuantumRegister(4, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.cswap(qr[0], qr[1], qr[2]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>──■──",
" │ ",
"qr_1: |0>──X──",
" │ ",
"qr_2: |0>──X──",
" ║ ",
"qr_3: |0>──╫──",
" ║ ",
" cr: 0 ══■══",
" 0x1 ",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_conditional_reset_cregbundle(self):
"""Reset drawing with cregbundle."""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.reset(qr[0]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>──|0>──",
" ║ ",
"qr_1: |0>───╫───",
" ┌──╨──┐",
" cr: 0 1/╡ 0x1 ╞",
" └─────┘",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_conditional_reset(self):
"""Reset drawing."""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.reset(qr[0]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>─|0>─",
" ║ ",
"qr_1: |0>──╫──",
" ║ ",
" cr: 0 ══■══",
" 0x1 ",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_conditional_multiplexer_cregbundle(self):
"""Test Multiplexer with cregbundle."""
cx_multiplexer = UCGate([numpy.eye(2), numpy.array([[0, 1], [1, 0]])])
qr = QuantumRegister(3, name="qr")
cr = ClassicalRegister(1, "cr")
qc = QuantumCircuit(qr, cr)
qc.append(cx_multiplexer.c_if(cr, 1), [qr[0], qr[1]])
expected = "\n".join(
[
" ┌──────────────┐",
"qr_0: |0>┤0 ├",
" │ Multiplexer │",
"qr_1: |0>┤1 ├",
" └──────╥───────┘",
"qr_2: |0>───────╫────────",
" ┌──╨──┐ ",
" cr: 0 1/════╡ 0x1 ╞═════",
" └─────┘ ",
]
)
self.assertEqual(str(_text_circuit_drawer(qc, cregbundle=True)), expected)
def test_conditional_multiplexer(self):
"""Test Multiplexer."""
cx_multiplexer = UCGate([numpy.eye(2), numpy.array([[0, 1], [1, 0]])])
qr = QuantumRegister(3, name="qr")
cr = ClassicalRegister(1, "cr")
qc = QuantumCircuit(qr, cr)
qc.append(cx_multiplexer.c_if(cr, 1), [qr[0], qr[1]])
expected = "\n".join(
[
" ┌──────────────┐",
"qr_0: |0>┤0 ├",
" │ Multiplexer │",
"qr_1: |0>┤1 ├",
" └──────╥───────┘",
"qr_2: |0>───────╫────────",
" ║ ",
" cr: 0 ═══════■════════",
" 0x1 ",
]
)
self.assertEqual(str(_text_circuit_drawer(qc, cregbundle=False)), expected)
def test_text_conditional_measure_cregbundle(self):
"""Conditional with measure on same clbit with cregbundle"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0])
circuit.measure(qr[0], cr[0])
circuit.h(qr[1]).c_if(cr, 1)
expected = "\n".join(
[
" ┌───┐┌─┐ ",
"qr_0: |0>┤ H ├┤M├───────",
" └───┘└╥┘ ┌───┐ ",
"qr_1: |0>──────╫──┤ H ├─",
" ║ ┌┴─╨─┴┐",
" cr: 0 2/══════╩═╡ 0x1 ╞",
" 0 └─────┘",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_conditional_measure(self):
"""Conditional with measure on same clbit"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0])
circuit.measure(qr[0], cr[0])
circuit.h(qr[1]).c_if(cr, 1)
expected = "\n".join(
[
" ┌───┐┌─┐ ",
"qr_0: |0>┤ H ├┤M├─────",
" └───┘└╥┘┌───┐",
"qr_1: |0>──────╫─┤ H ├",
" ║ └─╥─┘",
" cr_0: 0 ══════╩═══■══",
" ║ ",
" cr_1: 0 ══════════o══",
" 0x1 ",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_text_bit_conditional(self):
"""Test bit conditions on gates"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0]).c_if(cr[0], 1)
circuit.h(qr[1]).c_if(cr[1], 0)
expected = "\n".join(
[
" ┌───┐ ",
"qr_0: |0>┤ H ├─────",
" └─╥─┘┌───┐",
"qr_1: |0>──╫──┤ H ├",
" ║ └─╥─┘",
" cr_0: 0 ══■════╬══",
" ║ ",
" cr_1: 0 ═══════o══",
" ",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_text_bit_conditional_cregbundle(self):
"""Test bit conditions on gates when cregbundle=True"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0]).c_if(cr[0], 1)
circuit.h(qr[1]).c_if(cr[1], 0)
expected = "\n".join(
[
" ┌───┐ ",
"qr_0: |0>───┤ H ├────────────────",
" └─╥─┘ ┌───┐ ",
"qr_1: |0>─────╫─────────┤ H ├────",
" ║ └─╥─┘ ",
" ┌────╨─────┐┌────╨─────┐",
" cr: 0 2/╡ cr_0=0x1 ╞╡ cr_1=0x0 ╞",
" └──────────┘└──────────┘",
]
)
self.assertEqual(
str(_text_circuit_drawer(circuit, cregbundle=True, vertical_compression="medium")),
expected,
)
def test_text_condition_measure_bits_true(self):
"""Condition and measure on single bits cregbundle true"""
bits = [Qubit(), Qubit(), Clbit(), Clbit()]
cr = ClassicalRegister(2, "cr")
crx = ClassicalRegister(3, "cs")
circuit = QuantumCircuit(bits, cr, [Clbit()], crx)
circuit.x(0).c_if(crx[1], 0)
circuit.measure(0, bits[3])
expected = "\n".join(
[
" ┌───┐ ┌─┐",
" 0: ───┤ X ├────┤M├",
" └─╥─┘ └╥┘",
" 1: ─────╫───────╫─",
" ║ ║ ",
" 0: ═════╬═══════╬═",
" ║ ║ ",
" 1: ═════╬═══════╩═",
" ║ ",
"cr: 2/═════╬═════════",
" ║ ",
" 4: ═════╬═════════",
" ┌────╨─────┐ ",
"cs: 3/╡ cs_1=0x0 ╞═══",
" └──────────┘ ",
]
)
self.assertEqual(
str(_text_circuit_drawer(circuit, cregbundle=True, initial_state=False)), expected
)
def test_text_condition_measure_bits_false(self):
"""Condition and measure on single bits cregbundle false"""
bits = [Qubit(), Qubit(), Clbit(), Clbit()]
cr = ClassicalRegister(2, "cr")
crx = ClassicalRegister(3, "cs")
circuit = QuantumCircuit(bits, cr, [Clbit()], crx)
circuit.x(0).c_if(crx[1], 0)
circuit.measure(0, bits[3])
expected = "\n".join(
[
" ┌───┐┌─┐",
" 0: ┤ X ├┤M├",
" └─╥─┘└╥┘",
" 1: ──╫───╫─",
" ║ ║ ",
" 0: ══╬═══╬═",
" ║ ║ ",
" 1: ══╬═══╩═",
" ║ ",
"cr_0: ══╬═════",
" ║ ",
"cr_1: ══╬═════",
" ║ ",
" 4: ══╬═════",
" ║ ",
"cs_0: ══╬═════",
" ║ ",
"cs_1: ══o═════",
" ",
"cs_2: ════════",
" ",
]
)
self.assertEqual(
str(_text_circuit_drawer(circuit, cregbundle=False, initial_state=False)), expected
)
def test_text_conditional_reverse_bits_1(self):
"""Classical condition on 2q2c circuit with cregbundle=False and reverse bits"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0])
circuit.measure(qr[0], cr[0])
circuit.h(qr[1]).c_if(cr, 1)
expected = "\n".join(
[
" ┌───┐",
"qr_1: |0>────────┤ H ├",
" ┌───┐┌─┐└─╥─┘",
"qr_0: |0>┤ H ├┤M├──╫──",
" └───┘└╥┘ ║ ",
" cr_1: 0 ══════╬═══o══",
" ║ ║ ",
" cr_0: 0 ══════╩═══■══",
" 0x1 ",
]
)
self.assertEqual(
str(_text_circuit_drawer(circuit, cregbundle=False, reverse_bits=True)), expected
)
def test_text_conditional_reverse_bits_2(self):
"""Classical condition on 3q3c circuit with cergbundle=False and reverse bits"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(3, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0]).c_if(cr, 6)
circuit.h(qr[1]).c_if(cr, 1)
circuit.h(qr[2]).c_if(cr, 2)
circuit.cx(0, 1).c_if(cr, 3)
expected = "\n".join(
[
" ┌───┐ ",
"qr_2: |0>──────────┤ H ├─────",
" ┌───┐└─╥─┘┌───┐",
"qr_1: |0>─────┤ H ├──╫──┤ X ├",
" ┌───┐└─╥─┘ ║ └─┬─┘",
"qr_0: |0>┤ H ├──╫────╫────■──",
" └─╥─┘ ║ ║ ║ ",
" cr_2: 0 ══■════o════o════o══",
" ║ ║ ║ ║ ",
" cr_1: 0 ══■════o════■════■══",
" ║ ║ ║ ║ ",
" cr_0: 0 ══o════■════o════■══",
" 0x6 0x1 0x2 0x3 ",
]
)
self.assertEqual(
str(_text_circuit_drawer(circuit, cregbundle=False, reverse_bits=True)), expected
)
def test_text_condition_bits_reverse(self):
"""Condition and measure on single bits cregbundle true and reverse_bits true"""
bits = [Qubit(), Qubit(), Clbit(), Clbit()]
cr = ClassicalRegister(2, "cr")
crx = ClassicalRegister(3, "cs")
circuit = QuantumCircuit(bits, cr, [Clbit()], crx)
circuit.x(0).c_if(bits[3], 0)
expected = "\n".join(
[
" ",
" 1: ─────",
" ┌───┐",
" 0: ┤ X ├",
" └─╥─┘",
"cs: 3/══╬══",
" ║ ",
" 4: ══╬══",
" ║ ",
"cr: 2/══╬══",
" ║ ",
" 1: ══o══",
" ",
" 0: ═════",
" ",
]
)
self.assertEqual(
str(
_text_circuit_drawer(
circuit, cregbundle=True, initial_state=False, reverse_bits=True
)
),
expected,
)
class TestTextIdleWires(QiskitTestCase):
"""The idle_wires option"""
def test_text_h(self):
"""Remove QuWires."""
# fmt: off
expected = "\n".join([" ┌───┐",
"q1_1: |0>┤ H ├",
" └───┘"])
# fmt: on
qr1 = QuantumRegister(3, "q1")
circuit = QuantumCircuit(qr1)
circuit.h(qr1[1])
self.assertEqual(str(_text_circuit_drawer(circuit, idle_wires=False)), expected)
def test_text_measure(self):
"""Remove QuWires and ClWires."""
expected = "\n".join(
[
" ┌─┐ ",
"q2_0: |0>┤M├───",
" └╥┘┌─┐",
"q2_1: |0>─╫─┤M├",
" ║ └╥┘",
" c2: 0 2/═╩══╩═",
" 0 1 ",
]
)
qr1 = QuantumRegister(2, "q1")
cr1 = ClassicalRegister(2, "c1")
qr2 = QuantumRegister(2, "q2")
cr2 = ClassicalRegister(2, "c2")
circuit = QuantumCircuit(qr1, qr2, cr1, cr2)
circuit.measure(qr2, cr2)
self.assertEqual(str(_text_circuit_drawer(circuit, idle_wires=False)), expected)
def test_text_empty_circuit(self):
"""Remove everything in an empty circuit."""
expected = ""
circuit = QuantumCircuit()
self.assertEqual(str(_text_circuit_drawer(circuit, idle_wires=False)), expected)
def test_text_barrier(self):
"""idle_wires should ignore barrier
See https://github.com/Qiskit/qiskit-terra/issues/4391"""
# fmt: off
expected = "\n".join([" ┌───┐ ░ ",
"qr_1: |0>┤ H ├─░─",
" └───┘ ░ "])
# fmt: on
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr[1])
circuit.barrier(qr[1], qr[2])
self.assertEqual(str(_text_circuit_drawer(circuit, idle_wires=False)), expected)
def test_text_barrier_delay(self):
"""idle_wires should ignore delay"""
# fmt: off
expected = "\n".join([" ┌───┐ ░ ",
"qr_1: |0>┤ H ├─░──",
" └───┘ ░ "])
# fmt: on
qr = QuantumRegister(4, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr[1])
circuit.barrier()
circuit.delay(100, qr[2])
self.assertEqual(str(_text_circuit_drawer(circuit, idle_wires=False)), expected)
def test_does_not_mutate_circuit(self):
"""Using 'idle_wires=False' should not mutate the circuit. Regression test of gh-8739."""
circuit = QuantumCircuit(1)
before_qubits = circuit.num_qubits
circuit.draw(idle_wires=False)
self.assertEqual(circuit.num_qubits, before_qubits)
class TestTextNonRational(QiskitTestCase):
"""non-rational numbers are correctly represented"""
def test_text_pifrac(self):
"""u drawing with -5pi/8 fraction"""
# fmt: off
expected = "\n".join(
[" ┌──────────────┐",
"q: |0>┤ U(π,-5π/8,0) ├",
" └──────────────┘"]
)
# fmt: on
qr = QuantumRegister(1, "q")
circuit = QuantumCircuit(qr)
circuit.u(pi, -5 * pi / 8, 0, qr[0])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_complex(self):
"""Complex numbers show up in the text
See https://github.com/Qiskit/qiskit-terra/issues/3640"""
expected = "\n".join(
[
" ┌────────────────────────────────────┐",
"q_0: ┤0 ├",
" │ Initialize(0.5+0.1j,0,0,0.86023j) │",
"q_1: ┤1 ├",
" └────────────────────────────────────┘",
]
)
ket = numpy.array([0.5 + 0.1 * 1j, 0, 0, 0.8602325267042626 * 1j])
circuit = QuantumCircuit(2)
circuit.initialize(ket, [0, 1])
self.assertEqual(circuit.draw(output="text").single_string(), expected)
def test_text_complex_pireal(self):
"""Complex numbers including pi show up in the text
See https://github.com/Qiskit/qiskit-terra/issues/3640"""
expected = "\n".join(
[
" ┌────────────────────────────────┐",
"q_0: |0>┤0 ├",
" │ Initialize(π/10,0,0,0.94937j) │",
"q_1: |0>┤1 ├",
" └────────────────────────────────┘",
]
)
ket = numpy.array([0.1 * numpy.pi, 0, 0, 0.9493702944526474 * 1j])
circuit = QuantumCircuit(2)
circuit.initialize(ket, [0, 1])
self.assertEqual(circuit.draw(output="text", initial_state=True).single_string(), expected)
def test_text_complex_piimaginary(self):
"""Complex numbers including pi show up in the text
See https://github.com/Qiskit/qiskit-terra/issues/3640"""
expected = "\n".join(
[
" ┌────────────────────────────────┐",
"q_0: |0>┤0 ├",
" │ Initialize(0.94937,0,0,π/10j) │",
"q_1: |0>┤1 ├",
" └────────────────────────────────┘",
]
)
ket = numpy.array([0.9493702944526474, 0, 0, 0.1 * numpy.pi * 1j])
circuit = QuantumCircuit(2)
circuit.initialize(ket, [0, 1])
self.assertEqual(circuit.draw(output="text", initial_state=True).single_string(), expected)
class TestTextInstructionWithBothWires(QiskitTestCase):
"""Composite instructions with both kind of wires
See https://github.com/Qiskit/qiskit-terra/issues/2973"""
def test_text_all_1q_1c(self):
"""Test q0-c0 in q0-c0"""
expected = "\n".join(
[
" ┌───────┐",
"qr: |0>┤0 ├",
" │ name │",
" cr: 0 ╡0 ╞",
" └───────┘",
]
)
qr1 = QuantumRegister(1, "qr")
cr1 = ClassicalRegister(1, "cr")
inst = QuantumCircuit(qr1, cr1, name="name").to_instruction()
circuit = QuantumCircuit(qr1, cr1)
circuit.append(inst, qr1[:], cr1[:])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_all_2q_2c(self):
"""Test q0-q1-c0-c1 in q0-q1-c0-c1"""
expected = "\n".join(
[
" ┌───────┐",
"qr_0: |0>┤0 ├",
" │ │",
"qr_1: |0>┤1 ├",
" │ name │",
" cr_0: 0 ╡0 ╞",
" │ │",
" cr_1: 0 ╡1 ╞",
" └───────┘",
]
)
qr2 = QuantumRegister(2, "qr")
cr2 = ClassicalRegister(2, "cr")
inst = QuantumCircuit(qr2, cr2, name="name").to_instruction()
circuit = QuantumCircuit(qr2, cr2)
circuit.append(inst, qr2[:], cr2[:])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_all_2q_2c_cregbundle(self):
"""Test q0-q1-c0-c1 in q0-q1-c0-c1. Ignore cregbundle=True"""
expected = "\n".join(
[
" ┌───────┐",
"qr_0: |0>┤0 ├",
" │ │",
"qr_1: |0>┤1 ├",
" │ name │",
" cr_0: 0 ╡0 ╞",
" │ │",
" cr_1: 0 ╡1 ╞",
" └───────┘",
]
)
qr2 = QuantumRegister(2, "qr")
cr2 = ClassicalRegister(2, "cr")
inst = QuantumCircuit(qr2, cr2, name="name").to_instruction()
circuit = QuantumCircuit(qr2, cr2)
circuit.append(inst, qr2[:], cr2[:])
with self.assertWarns(RuntimeWarning):
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_4q_2c(self):
"""Test q1-q2-q3-q4-c1-c2 in q0-q1-q2-q3-q4-q5-c0-c1-c2-c3-c4-c5"""
expected = "\n".join(
[
" ",
"q_0: |0>─────────",
" ┌───────┐",
"q_1: |0>┤0 ├",
" │ │",
"q_2: |0>┤1 ├",
" │ │",
"q_3: |0>┤2 ├",
" │ │",
"q_4: |0>┤3 ├",
" │ name │",
"q_5: |0>┤ ├",
" │ │",
" c_0: 0 ╡ ╞",
" │ │",
" c_1: 0 ╡0 ╞",
" │ │",
" c_2: 0 ╡1 ╞",
" └───────┘",
" c_3: 0 ═════════",
" ",
" c_4: 0 ═════════",
" ",
" c_5: 0 ═════════",
" ",
]
)
qr4 = QuantumRegister(4)
cr4 = ClassicalRegister(2)
inst = QuantumCircuit(qr4, cr4, name="name").to_instruction()
qr6 = QuantumRegister(6, "q")
cr6 = ClassicalRegister(6, "c")
circuit = QuantumCircuit(qr6, cr6)
circuit.append(inst, qr6[1:5], cr6[1:3])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_2q_1c(self):
"""Test q0-c0 in q0-q1-c0
See https://github.com/Qiskit/qiskit-terra/issues/4066"""
expected = "\n".join(
[
" ┌───────┐",
"q_0: |0>┤0 ├",
" │ │",
"q_1: |0>┤ Name ├",
" │ │",
" c: 0 ╡0 ╞",
" └───────┘",
]
)
qr = QuantumRegister(2, name="q")
cr = ClassicalRegister(1, name="c")
circuit = QuantumCircuit(qr, cr)
inst = QuantumCircuit(1, 1, name="Name").to_instruction()
circuit.append(inst, [qr[0]], [cr[0]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_3q_3c_qlabels_inverted(self):
"""Test q3-q0-q1-c0-c1-c_10 in q0-q1-q2-q3-c0-c1-c2-c_10-c_11
See https://github.com/Qiskit/qiskit-terra/issues/6178"""
expected = "\n".join(
[
" ┌───────┐",
"q_0: |0>┤1 ├",
" │ │",
"q_1: |0>┤2 ├",
" │ │",
"q_2: |0>┤ ├",
" │ │",
"q_3: |0>┤0 ├",
" │ Name │",
" c_0: 0 ╡0 ╞",
" │ │",
" c_1: 0 ╡1 ╞",
" │ │",
" c_2: 0 ╡ ╞",
" │ │",
"c1_0: 0 ╡2 ╞",
" └───────┘",
"c1_1: 0 ═════════",
" ",
]
)
qr = QuantumRegister(4, name="q")
cr = ClassicalRegister(3, name="c")
cr1 = ClassicalRegister(2, name="c1")
circuit = QuantumCircuit(qr, cr, cr1)
inst = QuantumCircuit(3, 3, name="Name").to_instruction()
circuit.append(inst, [qr[3], qr[0], qr[1]], [cr[0], cr[1], cr1[0]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_3q_3c_clabels_inverted(self):
"""Test q0-q1-q3-c_11-c0-c_10 in q0-q1-q2-q3-c0-c1-c2-c_10-c_11
See https://github.com/Qiskit/qiskit-terra/issues/6178"""
expected = "\n".join(
[
" ┌───────┐",
"q_0: |0>┤0 ├",
" │ │",
"q_1: |0>┤1 ├",
" │ │",
"q_2: |0>┤ ├",
" │ │",
"q_3: |0>┤2 ├",
" │ │",
" c_0: 0 ╡1 Name ╞",
" │ │",
" c_1: 0 ╡ ╞",
" │ │",
" c_2: 0 ╡ ╞",
" │ │",
"c1_0: 0 ╡2 ╞",
" │ │",
"c1_1: 0 ╡0 ╞",
" └───────┘",
]
)
qr = QuantumRegister(4, name="q")
cr = ClassicalRegister(3, name="c")
cr1 = ClassicalRegister(2, name="c1")
circuit = QuantumCircuit(qr, cr, cr1)
inst = QuantumCircuit(3, 3, name="Name").to_instruction()
circuit.append(inst, [qr[0], qr[1], qr[3]], [cr1[1], cr[0], cr1[0]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_3q_3c_qclabels_inverted(self):
"""Test q3-q1-q2-c_11-c0-c_10 in q0-q1-q2-q3-c0-c1-c2-c_10-c_11
See https://github.com/Qiskit/qiskit-terra/issues/6178"""
expected = "\n".join(
[
" ",
"q_0: |0>─────────",
" ┌───────┐",
"q_1: |0>┤1 ├",
" │ │",
"q_2: |0>┤2 ├",
" │ │",
"q_3: |0>┤0 ├",
" │ │",
" c_0: 0 ╡1 ╞",
" │ Name │",
" c_1: 0 ╡ ╞",
" │ │",
" c_2: 0 ╡ ╞",
" │ │",
"c1_0: 0 ╡2 ╞",
" │ │",
"c1_1: 0 ╡0 ╞",
" └───────┘",
]
)
qr = QuantumRegister(4, name="q")
cr = ClassicalRegister(3, name="c")
cr1 = ClassicalRegister(2, name="c1")
circuit = QuantumCircuit(qr, cr, cr1)
inst = QuantumCircuit(3, 3, name="Name").to_instruction()
circuit.append(inst, [qr[3], qr[1], qr[2]], [cr1[1], cr[0], cr1[0]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
class TestTextDrawerAppendedLargeInstructions(QiskitTestCase):
"""Composite instructions with more than 10 qubits
See https://github.com/Qiskit/qiskit-terra/pull/4095"""
def test_text_11q(self):
"""Test q0-...-q10 in q0-...-q10"""
expected = "\n".join(
[
" ┌────────┐",
" q_0: |0>┤0 ├",
" │ │",
" q_1: |0>┤1 ├",
" │ │",
" q_2: |0>┤2 ├",
" │ │",
" q_3: |0>┤3 ├",
" │ │",
" q_4: |0>┤4 ├",
" │ │",
" q_5: |0>┤5 Name ├",
" │ │",
" q_6: |0>┤6 ├",
" │ │",
" q_7: |0>┤7 ├",
" │ │",
" q_8: |0>┤8 ├",
" │ │",
" q_9: |0>┤9 ├",
" │ │",
"q_10: |0>┤10 ├",
" └────────┘",
]
)
qr = QuantumRegister(11, "q")
circuit = QuantumCircuit(qr)
inst = QuantumCircuit(11, name="Name").to_instruction()
circuit.append(inst, qr)
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_11q_1c(self):
"""Test q0-...-q10-c0 in q0-...-q10-c0"""
expected = "\n".join(
[
" ┌────────┐",
" q_0: |0>┤0 ├",
" │ │",
" q_1: |0>┤1 ├",
" │ │",
" q_2: |0>┤2 ├",
" │ │",
" q_3: |0>┤3 ├",
" │ │",
" q_4: |0>┤4 ├",
" │ │",
" q_5: |0>┤5 ├",
" │ Name │",
" q_6: |0>┤6 ├",
" │ │",
" q_7: |0>┤7 ├",
" │ │",
" q_8: |0>┤8 ├",
" │ │",
" q_9: |0>┤9 ├",
" │ │",
"q_10: |0>┤10 ├",
" │ │",
" c: 0 ╡0 ╞",
" └────────┘",
]
)
qr = QuantumRegister(11, "q")
cr = ClassicalRegister(1, "c")
circuit = QuantumCircuit(qr, cr)
inst = QuantumCircuit(11, 1, name="Name").to_instruction()
circuit.append(inst, qr, cr)
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
class TestTextControlledGate(QiskitTestCase):
"""Test controlled gates"""
def test_cch_bot(self):
"""Controlled CH (bottom)"""
expected = "\n".join(
[
" ",
"q_0: |0>──■──",
" │ ",
"q_1: |0>──■──",
" ┌─┴─┐",
"q_2: |0>┤ H ├",
" └───┘",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.append(HGate().control(2), [qr[0], qr[1], qr[2]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_cch_mid(self):
"""Controlled CH (middle)"""
expected = "\n".join(
[
" ",
"q_0: |0>──■──",
" ┌─┴─┐",
"q_1: |0>┤ H ├",
" └─┬─┘",
"q_2: |0>──■──",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.append(HGate().control(2), [qr[0], qr[2], qr[1]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_cch_top(self):
"""Controlled CH"""
expected = "\n".join(
[
" ┌───┐",
"q_0: |0>┤ H ├",
" └─┬─┘",
"q_1: |0>──■──",
" │ ",
"q_2: |0>──■──",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.append(HGate().control(2), [qr[2], qr[1], qr[0]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_c3h(self):
"""Controlled Controlled CH"""
expected = "\n".join(
[
" ",
"q_0: |0>──■──",
" │ ",
"q_1: |0>──■──",
" │ ",
"q_2: |0>──■──",
" ┌─┴─┐",
"q_3: |0>┤ H ├",
" └───┘",
]
)
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.append(HGate().control(3), [qr[0], qr[1], qr[2], qr[3]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_c3h_middle(self):
"""Controlled Controlled CH (middle)"""
expected = "\n".join(
[
" ",
"q_0: |0>──■──",
" ┌─┴─┐",
"q_1: |0>┤ H ├",
" └─┬─┘",
"q_2: |0>──■──",
" │ ",
"q_3: |0>──■──",
" ",
]
)
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.append(HGate().control(3), [qr[0], qr[3], qr[2], qr[1]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_c3u2(self):
"""Controlled Controlled U2"""
expected = "\n".join(
[
" ",
"q_0: |0>───────■───────",
" ┌──────┴──────┐",
"q_1: |0>┤ U2(π,-5π/8) ├",
" └──────┬──────┘",
"q_2: |0>───────■───────",
" │ ",
"q_3: |0>───────■───────",
" ",
]
)
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.append(U2Gate(pi, -5 * pi / 8).control(3), [qr[0], qr[3], qr[2], qr[1]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_controlled_composite_gate_edge(self):
"""Controlled composite gates (edge)
See: https://github.com/Qiskit/qiskit-terra/issues/3546"""
expected = "\n".join(
[
" ┌──────┐",
"q_0: |0>┤0 ├",
" │ │",
"q_1: |0>■ ├",
" │ ghz │",
"q_2: |0>┤1 ├",
" │ │",
"q_3: |0>┤2 ├",
" └──────┘",
]
)
ghz_circuit = QuantumCircuit(3, name="ghz")
ghz_circuit.h(0)
ghz_circuit.cx(0, 1)
ghz_circuit.cx(1, 2)
ghz = ghz_circuit.to_gate()
cghz = ghz.control(1)
circuit = QuantumCircuit(4)
circuit.append(cghz, [1, 0, 2, 3])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_controlled_composite_gate_top(self):
"""Controlled composite gates (top)"""
expected = "\n".join(
[
" ",
"q_0: |0>───■────",
" ┌──┴───┐",
"q_1: |0>┤0 ├",
" │ │",
"q_2: |0>┤2 ghz ├",
" │ │",
"q_3: |0>┤1 ├",
" └──────┘",
]
)
ghz_circuit = QuantumCircuit(3, name="ghz")
ghz_circuit.h(0)
ghz_circuit.cx(0, 1)
ghz_circuit.cx(1, 2)
ghz = ghz_circuit.to_gate()
cghz = ghz.control(1)
circuit = QuantumCircuit(4)
circuit.append(cghz, [0, 1, 3, 2])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_controlled_composite_gate_bot(self):
"""Controlled composite gates (bottom)"""
expected = "\n".join(
[
" ┌──────┐",
"q_0: |0>┤1 ├",
" │ │",
"q_1: |0>┤0 ghz ├",
" │ │",
"q_2: |0>┤2 ├",
" └──┬───┘",
"q_3: |0>───■────",
" ",
]
)
ghz_circuit = QuantumCircuit(3, name="ghz")
ghz_circuit.h(0)
ghz_circuit.cx(0, 1)
ghz_circuit.cx(1, 2)
ghz = ghz_circuit.to_gate()
cghz = ghz.control(1)
circuit = QuantumCircuit(4)
circuit.append(cghz, [3, 1, 0, 2])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_controlled_composite_gate_top_bot(self):
"""Controlled composite gates (top and bottom)"""
expected = "\n".join(
[
" ",
"q_0: |0>───■────",
" ┌──┴───┐",
"q_1: |0>┤0 ├",
" │ │",
"q_2: |0>┤1 ghz ├",
" │ │",
"q_3: |0>┤2 ├",
" └──┬───┘",
"q_4: |0>───■────",
" ",
]
)
ghz_circuit = QuantumCircuit(3, name="ghz")
ghz_circuit.h(0)
ghz_circuit.cx(0, 1)
ghz_circuit.cx(1, 2)
ghz = ghz_circuit.to_gate()
ccghz = ghz.control(2)
circuit = QuantumCircuit(5)
circuit.append(ccghz, [4, 0, 1, 2, 3])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_controlled_composite_gate_all(self):
"""Controlled composite gates (top, bot, and edge)"""
expected = "\n".join(
[
" ",
"q_0: |0>───■────",
" ┌──┴───┐",
"q_1: |0>┤0 ├",
" │ │",
"q_2: |0>■ ├",
" │ ghz │",
"q_3: |0>┤1 ├",
" │ │",
"q_4: |0>┤2 ├",
" └──┬───┘",
"q_5: |0>───■────",
" ",
]
)
ghz_circuit = QuantumCircuit(3, name="ghz")
ghz_circuit.h(0)
ghz_circuit.cx(0, 1)
ghz_circuit.cx(1, 2)
ghz = ghz_circuit.to_gate()
ccghz = ghz.control(3)
circuit = QuantumCircuit(6)
circuit.append(ccghz, [0, 2, 5, 1, 3, 4])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_controlled_composite_gate_even_label(self):
"""Controlled composite gates (top and bottom) with a even label length"""
expected = "\n".join(
[
" ",
"q_0: |0>────■────",
" ┌───┴───┐",
"q_1: |0>┤0 ├",
" │ │",
"q_2: |0>┤1 cghz ├",
" │ │",
"q_3: |0>┤2 ├",
" └───┬───┘",
"q_4: |0>────■────",
" ",
]
)
ghz_circuit = QuantumCircuit(3, name="cghz")
ghz_circuit.h(0)
ghz_circuit.cx(0, 1)
ghz_circuit.cx(1, 2)
ghz = ghz_circuit.to_gate()
ccghz = ghz.control(2)
circuit = QuantumCircuit(5)
circuit.append(ccghz, [4, 0, 1, 2, 3])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
class TestTextOpenControlledGate(QiskitTestCase):
"""Test open controlled gates"""
def test_ch_bot(self):
"""Open controlled H (bottom)"""
# fmt: off
expected = "\n".join(
[" ",
"q_0: |0>──o──",
" ┌─┴─┐",
"q_1: |0>┤ H ├",
" └───┘"]
)
# fmt: on
qr = QuantumRegister(2, "q")
circuit = QuantumCircuit(qr)
circuit.append(HGate().control(1, ctrl_state=0), [qr[0], qr[1]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_cz_bot(self):
"""Open controlled Z (bottom)"""
# fmt: off
expected = "\n".join([" ",
"q_0: |0>─o─",
" │ ",
"q_1: |0>─■─",
" "])
# fmt: on
qr = QuantumRegister(2, "q")
circuit = QuantumCircuit(qr)
circuit.append(ZGate().control(1, ctrl_state=0), [qr[0], qr[1]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_ccz_bot(self):
"""Closed-Open controlled Z (bottom)"""
expected = "\n".join(
[
" ",
"q_0: |0>─■─",
" │ ",
"q_1: |0>─o─",
" │ ",
"q_2: |0>─■─",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.append(ZGate().control(2, ctrl_state="01"), [qr[0], qr[1], qr[2]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_cccz_conditional(self):
"""Closed-Open controlled Z (with conditional)"""
expected = "\n".join(
[
" ",
"q_0: |0>───■───",
" │ ",
"q_1: |0>───o───",
" │ ",
"q_2: |0>───■───",
" │ ",
"q_3: |0>───■───",
" ┌──╨──┐",
" c: 0 1/╡ 0x1 ╞",
" └─────┘",
]
)
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(1, "c")
circuit = QuantumCircuit(qr, cr)
circuit.append(
ZGate().control(3, ctrl_state="101").c_if(cr, 1), [qr[0], qr[1], qr[2], qr[3]]
)
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_cch_bot(self):
"""Controlled CH (bottom)"""
expected = "\n".join(
[
" ",
"q_0: |0>──o──",
" │ ",
"q_1: |0>──■──",
" ┌─┴─┐",
"q_2: |0>┤ H ├",
" └───┘",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.append(HGate().control(2, ctrl_state="10"), [qr[0], qr[1], qr[2]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_cch_mid(self):
"""Controlled CH (middle)"""
expected = "\n".join(
[
" ",
"q_0: |0>──o──",
" ┌─┴─┐",
"q_1: |0>┤ H ├",
" └─┬─┘",
"q_2: |0>──■──",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.append(HGate().control(2, ctrl_state="10"), [qr[0], qr[2], qr[1]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_cch_top(self):
"""Controlled CH"""
expected = "\n".join(
[
" ┌───┐",
"q_0: |0>┤ H ├",
" └─┬─┘",
"q_1: |0>──o──",
" │ ",
"q_2: |0>──■──",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.append(HGate().control(2, ctrl_state="10"), [qr[1], qr[2], qr[0]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_c3h(self):
"""Controlled Controlled CH"""
expected = "\n".join(
[
" ",
"q_0: |0>──o──",
" │ ",
"q_1: |0>──o──",
" │ ",
"q_2: |0>──■──",
" ┌─┴─┐",
"q_3: |0>┤ H ├",
" └───┘",
]
)
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.append(HGate().control(3, ctrl_state="100"), [qr[0], qr[1], qr[2], qr[3]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_c3h_middle(self):
"""Controlled Controlled CH (middle)"""
expected = "\n".join(
[
" ",
"q_0: |0>──o──",
" ┌─┴─┐",
"q_1: |0>┤ H ├",
" └─┬─┘",
"q_2: |0>──o──",
" │ ",
"q_3: |0>──■──",
" ",
]
)
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.append(HGate().control(3, ctrl_state="010"), [qr[0], qr[3], qr[2], qr[1]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_c3u2(self):
"""Controlled Controlled U2"""
expected = "\n".join(
[
" ",
"q_0: |0>───────o───────",
" ┌──────┴──────┐",
"q_1: |0>┤ U2(π,-5π/8) ├",
" └──────┬──────┘",
"q_2: |0>───────■───────",
" │ ",
"q_3: |0>───────o───────",
" ",
]
)
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.append(
U2Gate(pi, -5 * pi / 8).control(3, ctrl_state="100"), [qr[0], qr[3], qr[2], qr[1]]
)
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_controlled_composite_gate_edge(self):
"""Controlled composite gates (edge)
See: https://github.com/Qiskit/qiskit-terra/issues/3546"""
expected = "\n".join(
[
" ┌──────┐",
"q_0: |0>┤0 ├",
" │ │",
"q_1: |0>o ├",
" │ ghz │",
"q_2: |0>┤1 ├",
" │ │",
"q_3: |0>┤2 ├",
" └──────┘",
]
)
ghz_circuit = QuantumCircuit(3, name="ghz")
ghz_circuit.h(0)
ghz_circuit.cx(0, 1)
ghz_circuit.cx(1, 2)
ghz = ghz_circuit.to_gate()
cghz = ghz.control(1, ctrl_state="0")
circuit = QuantumCircuit(4)
circuit.append(cghz, [1, 0, 2, 3])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_controlled_composite_gate_top(self):
"""Controlled composite gates (top)"""
expected = "\n".join(
[
" ",
"q_0: |0>───o────",
" ┌──┴───┐",
"q_1: |0>┤0 ├",
" │ │",
"q_2: |0>┤2 ghz ├",
" │ │",
"q_3: |0>┤1 ├",
" └──────┘",
]
)
ghz_circuit = QuantumCircuit(3, name="ghz")
ghz_circuit.h(0)
ghz_circuit.cx(0, 1)
ghz_circuit.cx(1, 2)
ghz = ghz_circuit.to_gate()
cghz = ghz.control(1, ctrl_state="0")
circuit = QuantumCircuit(4)
circuit.append(cghz, [0, 1, 3, 2])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_controlled_composite_gate_bot(self):
"""Controlled composite gates (bottom)"""
expected = "\n".join(
[
" ┌──────┐",
"q_0: |0>┤1 ├",
" │ │",
"q_1: |0>┤0 ghz ├",
" │ │",
"q_2: |0>┤2 ├",
" └──┬───┘",
"q_3: |0>───o────",
" ",
]
)
ghz_circuit = QuantumCircuit(3, name="ghz")
ghz_circuit.h(0)
ghz_circuit.cx(0, 1)
ghz_circuit.cx(1, 2)
ghz = ghz_circuit.to_gate()
cghz = ghz.control(1, ctrl_state="0")
circuit = QuantumCircuit(4)
circuit.append(cghz, [3, 1, 0, 2])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_controlled_composite_gate_top_bot(self):
"""Controlled composite gates (top and bottom)"""
expected = "\n".join(
[
" ",
"q_0: |0>───o────",
" ┌──┴───┐",
"q_1: |0>┤0 ├",
" │ │",
"q_2: |0>┤1 ghz ├",
" │ │",
"q_3: |0>┤2 ├",
" └──┬───┘",
"q_4: |0>───■────",
" ",
]
)
ghz_circuit = QuantumCircuit(3, name="ghz")
ghz_circuit.h(0)
ghz_circuit.cx(0, 1)
ghz_circuit.cx(1, 2)
ghz = ghz_circuit.to_gate()
ccghz = ghz.control(2, ctrl_state="01")
circuit = QuantumCircuit(5)
circuit.append(ccghz, [4, 0, 1, 2, 3])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_controlled_composite_gate_all(self):
"""Controlled composite gates (top, bot, and edge)"""
expected = "\n".join(
[
" ",
"q_0: |0>───o────",
" ┌──┴───┐",
"q_1: |0>┤0 ├",
" │ │",
"q_2: |0>o ├",
" │ ghz │",
"q_3: |0>┤1 ├",
" │ │",
"q_4: |0>┤2 ├",
" └──┬───┘",
"q_5: |0>───o────",
" ",
]
)
ghz_circuit = QuantumCircuit(3, name="ghz")
ghz_circuit.h(0)
ghz_circuit.cx(0, 1)
ghz_circuit.cx(1, 2)
ghz = ghz_circuit.to_gate()
ccghz = ghz.control(3, ctrl_state="000")
circuit = QuantumCircuit(6)
circuit.append(ccghz, [0, 2, 5, 1, 3, 4])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_open_controlled_x(self):
"""Controlled X gates.
See https://github.com/Qiskit/qiskit-terra/issues/4180"""
expected = "\n".join(
[
" ",
"qr_0: |0>──o────o────o────o────■──",
" ┌─┴─┐ │ │ │ │ ",
"qr_1: |0>┤ X ├──o────■────■────o──",
" └───┘┌─┴─┐┌─┴─┐ │ │ ",
"qr_2: |0>─────┤ X ├┤ X ├──o────o──",
" └───┘└───┘┌─┴─┐┌─┴─┐",
"qr_3: |0>───────────────┤ X ├┤ X ├",
" └───┘└─┬─┘",
"qr_4: |0>──────────────────────■──",
" ",
]
)
qreg = QuantumRegister(5, "qr")
circuit = QuantumCircuit(qreg)
control1 = XGate().control(1, ctrl_state="0")
circuit.append(control1, [0, 1])
control2 = XGate().control(2, ctrl_state="00")
circuit.append(control2, [0, 1, 2])
control2_2 = XGate().control(2, ctrl_state="10")
circuit.append(control2_2, [0, 1, 2])
control3 = XGate().control(3, ctrl_state="010")
circuit.append(control3, [0, 1, 2, 3])
control3 = XGate().control(4, ctrl_state="0101")
circuit.append(control3, [0, 1, 4, 2, 3])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_open_controlled_y(self):
"""Controlled Y gates.
See https://github.com/Qiskit/qiskit-terra/issues/4180"""
expected = "\n".join(
[
" ",
"qr_0: |0>──o────o────o────o────■──",
" ┌─┴─┐ │ │ │ │ ",
"qr_1: |0>┤ Y ├──o────■────■────o──",
" └───┘┌─┴─┐┌─┴─┐ │ │ ",
"qr_2: |0>─────┤ Y ├┤ Y ├──o────o──",
" └───┘└───┘┌─┴─┐┌─┴─┐",
"qr_3: |0>───────────────┤ Y ├┤ Y ├",
" └───┘└─┬─┘",
"qr_4: |0>──────────────────────■──",
" ",
]
)
qreg = QuantumRegister(5, "qr")
circuit = QuantumCircuit(qreg)
control1 = YGate().control(1, ctrl_state="0")
circuit.append(control1, [0, 1])
control2 = YGate().control(2, ctrl_state="00")
circuit.append(control2, [0, 1, 2])
control2_2 = YGate().control(2, ctrl_state="10")
circuit.append(control2_2, [0, 1, 2])
control3 = YGate().control(3, ctrl_state="010")
circuit.append(control3, [0, 1, 2, 3])
control3 = YGate().control(4, ctrl_state="0101")
circuit.append(control3, [0, 1, 4, 2, 3])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_open_controlled_z(self):
"""Controlled Z gates."""
expected = "\n".join(
[
" ",
"qr_0: |0>─o──o──o──o──■─",
" │ │ │ │ │ ",
"qr_1: |0>─■──o──■──■──o─",
" │ │ │ │ ",
"qr_2: |0>────■──■──o──o─",
" │ │ ",
"qr_3: |0>──────────■──■─",
" │ ",
"qr_4: |0>─────────────■─",
" ",
]
)
qreg = QuantumRegister(5, "qr")
circuit = QuantumCircuit(qreg)
control1 = ZGate().control(1, ctrl_state="0")
circuit.append(control1, [0, 1])
control2 = ZGate().control(2, ctrl_state="00")
circuit.append(control2, [0, 1, 2])
control2_2 = ZGate().control(2, ctrl_state="10")
circuit.append(control2_2, [0, 1, 2])
control3 = ZGate().control(3, ctrl_state="010")
circuit.append(control3, [0, 1, 2, 3])
control3 = ZGate().control(4, ctrl_state="0101")
circuit.append(control3, [0, 1, 4, 2, 3])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_open_controlled_u1(self):
"""Controlled U1 gates."""
expected = "\n".join(
[
" ",
"qr_0: |0>─o─────────o─────────o─────────o─────────■────────",
" │U1(0.1) │ │ │ │ ",
"qr_1: |0>─■─────────o─────────■─────────■─────────o────────",
" │U1(0.2) │U1(0.3) │ │ ",
"qr_2: |0>───────────■─────────■─────────o─────────o────────",
" │U1(0.4) │ ",
"qr_3: |0>───────────────────────────────■─────────■────────",
" │U1(0.5) ",
"qr_4: |0>─────────────────────────────────────────■────────",
" ",
]
)
qreg = QuantumRegister(5, "qr")
circuit = QuantumCircuit(qreg)
control1 = U1Gate(0.1).control(1, ctrl_state="0")
circuit.append(control1, [0, 1])
control2 = U1Gate(0.2).control(2, ctrl_state="00")
circuit.append(control2, [0, 1, 2])
control2_2 = U1Gate(0.3).control(2, ctrl_state="10")
circuit.append(control2_2, [0, 1, 2])
control3 = U1Gate(0.4).control(3, ctrl_state="010")
circuit.append(control3, [0, 1, 2, 3])
control3 = U1Gate(0.5).control(4, ctrl_state="0101")
circuit.append(control3, [0, 1, 4, 2, 3])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_open_controlled_swap(self):
"""Controlled SWAP gates."""
expected = "\n".join(
[
" ",
"qr_0: |0>─o──o──o──o─",
" │ │ │ │ ",
"qr_1: |0>─X──o──■──■─",
" │ │ │ │ ",
"qr_2: |0>─X──X──X──o─",
" │ │ │ ",
"qr_3: |0>────X──X──X─",
" │ ",
"qr_4: |0>──────────X─",
" ",
]
)
qreg = QuantumRegister(5, "qr")
circuit = QuantumCircuit(qreg)
control1 = SwapGate().control(1, ctrl_state="0")
circuit.append(control1, [0, 1, 2])
control2 = SwapGate().control(2, ctrl_state="00")
circuit.append(control2, [0, 1, 2, 3])
control2_2 = SwapGate().control(2, ctrl_state="10")
circuit.append(control2_2, [0, 1, 2, 3])
control3 = SwapGate().control(3, ctrl_state="010")
circuit.append(control3, [0, 1, 2, 3, 4])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_open_controlled_rzz(self):
"""Controlled RZZ gates."""
expected = "\n".join(
[
" ",
"qr_0: |0>─o───────o───────o───────o──────",
" │ │ │ │ ",
"qr_1: |0>─■───────o───────■───────■──────",
" │ZZ(1) │ │ │ ",
"qr_2: |0>─■───────■───────■───────o──────",
" │ZZ(1) │ZZ(1) │ ",
"qr_3: |0>─────────■───────■───────■──────",
" │ZZ(1) ",
"qr_4: |0>─────────────────────────■──────",
" ",
]
)
qreg = QuantumRegister(5, "qr")
circuit = QuantumCircuit(qreg)
control1 = RZZGate(1).control(1, ctrl_state="0")
circuit.append(control1, [0, 1, 2])
control2 = RZZGate(1).control(2, ctrl_state="00")
circuit.append(control2, [0, 1, 2, 3])
control2_2 = RZZGate(1).control(2, ctrl_state="10")
circuit.append(control2_2, [0, 1, 2, 3])
control3 = RZZGate(1).control(3, ctrl_state="010")
circuit.append(control3, [0, 1, 2, 3, 4])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_open_out_of_order(self):
"""Out of order CXs
See: https://github.com/Qiskit/qiskit-terra/issues/4052#issuecomment-613736911"""
expected = "\n".join(
[
" ",
"q_0: |0>──■──",
" │ ",
"q_1: |0>──■──",
" ┌─┴─┐",
"q_2: |0>┤ X ├",
" └─┬─┘",
"q_3: |0>──o──",
" ",
"q_4: |0>─────",
" ",
]
)
qr = QuantumRegister(5, "q")
circuit = QuantumCircuit(qr)
circuit.append(XGate().control(3, ctrl_state="101"), [qr[0], qr[3], qr[1], qr[2]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
class TestTextWithLayout(QiskitTestCase):
"""The with_layout option"""
def test_with_no_layout(self):
"""A circuit without layout"""
expected = "\n".join(
[
" ",
"q_0: |0>─────",
" ┌───┐",
"q_1: |0>┤ H ├",
" └───┘",
"q_2: |0>─────",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.h(qr[1])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_mixed_layout(self):
"""With a mixed layout."""
expected = "\n".join(
[
" ┌───┐",
" v_0 -> 0 |0>┤ H ├",
" └───┘",
"ancilla_1 -> 1 |0>─────",
" ",
"ancilla_0 -> 2 |0>─────",
" ┌───┐",
" v_1 -> 3 |0>┤ H ├",
" └───┘",
]
)
qr = QuantumRegister(2, "v")
ancilla = QuantumRegister(2, "ancilla")
circuit = QuantumCircuit(qr, ancilla)
circuit.h(qr)
pass_ = ApplyLayout()
pass_.property_set["layout"] = Layout({qr[0]: 0, ancilla[1]: 1, ancilla[0]: 2, qr[1]: 3})
circuit_with_layout = pass_(circuit)
self.assertEqual(str(_text_circuit_drawer(circuit_with_layout)), expected)
def test_partial_layout(self):
"""With a partial layout.
See: https://github.com/Qiskit/qiskit-terra/issues/4757"""
expected = "\n".join(
[
" ┌───┐",
"v_0 -> 0 |0>┤ H ├",
" └───┘",
" 1 |0>─────",
" ",
" 2 |0>─────",
" ┌───┐",
"v_1 -> 3 |0>┤ H ├",
" └───┘",
]
)
qr = QuantumRegister(2, "v")
pqr = QuantumRegister(4, "physical")
circuit = QuantumCircuit(pqr)
circuit.h(0)
circuit.h(3)
circuit._layout = TranspileLayout(
Layout({0: qr[0], 1: None, 2: None, 3: qr[1]}),
{qubit: index for index, qubit in enumerate(circuit.qubits)},
)
circuit._layout.initial_layout.add_register(qr)
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_with_classical_regs(self):
"""Involving classical registers"""
expected = "\n".join(
[
" ",
"qr1_0 -> 0 |0>──────",
" ",
"qr1_1 -> 1 |0>──────",
" ┌─┐ ",
"qr2_0 -> 2 |0>┤M├───",
" └╥┘┌─┐",
"qr2_1 -> 3 |0>─╫─┤M├",
" ║ └╥┘",
" cr: 0 2/═╩══╩═",
" 0 1 ",
]
)
qr1 = QuantumRegister(2, "qr1")
qr2 = QuantumRegister(2, "qr2")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr1, qr2, cr)
circuit.measure(qr2[0], cr[0])
circuit.measure(qr2[1], cr[1])
pass_ = ApplyLayout()
pass_.property_set["layout"] = Layout({qr1[0]: 0, qr1[1]: 1, qr2[0]: 2, qr2[1]: 3})
circuit_with_layout = pass_(circuit)
self.assertEqual(str(_text_circuit_drawer(circuit_with_layout)), expected)
def test_with_layout_but_disable(self):
"""With parameter without_layout=False"""
expected = "\n".join(
[
" ",
"q_0: |0>──────",
" ",
"q_1: |0>──────",
" ┌─┐ ",
"q_2: |0>┤M├───",
" └╥┘┌─┐",
"q_3: |0>─╫─┤M├",
" ║ └╥┘",
"cr: 0 2/═╩══╩═",
" 0 1 ",
]
)
pqr = QuantumRegister(4, "q")
qr1 = QuantumRegister(2, "qr1")
cr = ClassicalRegister(2, "cr")
qr2 = QuantumRegister(2, "qr2")
circuit = QuantumCircuit(pqr, cr)
circuit._layout = Layout({qr1[0]: 0, qr1[1]: 1, qr2[0]: 2, qr2[1]: 3})
circuit.measure(pqr[2], cr[0])
circuit.measure(pqr[3], cr[1])
self.assertEqual(str(_text_circuit_drawer(circuit, with_layout=False)), expected)
def test_after_transpile(self):
"""After transpile, the drawing should include the layout"""
expected = "\n".join(
[
" ┌─────────┐┌─────────┐┌───┐┌─────────┐┌─┐ ",
" userqr_0 -> 0 ┤ U2(0,π) ├┤ U2(0,π) ├┤ X ├┤ U2(0,π) ├┤M├───",
" ├─────────┤├─────────┤└─┬─┘├─────────┤└╥┘┌─┐",
" userqr_1 -> 1 ┤ U2(0,π) ├┤ U2(0,π) ├──■──┤ U2(0,π) ├─╫─┤M├",
" └─────────┘└─────────┘ └─────────┘ ║ └╥┘",
" ancilla_0 -> 2 ───────────────────────────────────────╫──╫─",
" ║ ║ ",
" ancilla_1 -> 3 ───────────────────────────────────────╫──╫─",
" ║ ║ ",
" ancilla_2 -> 4 ───────────────────────────────────────╫──╫─",
" ║ ║ ",
" ancilla_3 -> 5 ───────────────────────────────────────╫──╫─",
" ║ ║ ",
" ancilla_4 -> 6 ───────────────────────────────────────╫──╫─",
" ║ ║ ",
" ancilla_5 -> 7 ───────────────────────────────────────╫──╫─",
" ║ ║ ",
" ancilla_6 -> 8 ───────────────────────────────────────╫──╫─",
" ║ ║ ",
" ancilla_7 -> 9 ───────────────────────────────────────╫──╫─",
" ║ ║ ",
" ancilla_8 -> 10 ───────────────────────────────────────╫──╫─",
" ║ ║ ",
" ancilla_9 -> 11 ───────────────────────────────────────╫──╫─",
" ║ ║ ",
"ancilla_10 -> 12 ───────────────────────────────────────╫──╫─",
" ║ ║ ",
"ancilla_11 -> 13 ───────────────────────────────────────╫──╫─",
" ║ ║ ",
" c0_0: ═══════════════════════════════════════╩══╬═",
" ║ ",
" c0_1: ══════════════════════════════════════════╩═",
" ",
]
)
qr = QuantumRegister(2, "userqr")
cr = ClassicalRegister(2, "c0")
qc = QuantumCircuit(qr, cr)
qc.h(qr)
qc.cx(qr[0], qr[1])
qc.measure(qr, cr)
coupling_map = [
[1, 0],
[1, 2],
[2, 3],
[4, 3],
[4, 10],
[5, 4],
[5, 6],
[5, 9],
[6, 8],
[7, 8],
[9, 8],
[9, 10],
[11, 3],
[11, 10],
[11, 12],
[12, 2],
[13, 1],
[13, 12],
]
qc_result = transpile(
qc,
basis_gates=["u1", "u2", "u3", "cx", "id"],
coupling_map=coupling_map,
optimization_level=0,
seed_transpiler=0,
)
self.assertEqual(qc_result.draw(output="text", cregbundle=False).single_string(), expected)
class TestTextInitialValue(QiskitTestCase):
"""Testing the initial_state parameter"""
def setUp(self) -> None:
super().setUp()
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
self.circuit = QuantumCircuit(qr, cr)
self.circuit.measure(qr, cr)
def test_draw_initial_value_default(self):
"""Text drawer (.draw) default initial_state parameter (False)."""
expected = "\n".join(
[
" ┌─┐ ",
"q_0: ┤M├───",
" └╥┘┌─┐",
"q_1: ─╫─┤M├",
" ║ └╥┘",
"c_0: ═╩══╬═",
" ║ ",
"c_1: ════╩═",
" ",
]
)
self.assertEqual(
self.circuit.draw(output="text", cregbundle=False).single_string(), expected
)
def test_draw_initial_value_true(self):
"""Text drawer .draw(initial_state=True)."""
expected = "\n".join(
[
" ┌─┐ ",
"q_0: |0>┤M├───",
" └╥┘┌─┐",
"q_1: |0>─╫─┤M├",
" ║ └╥┘",
" c_0: 0 ═╩══╬═",
" ║ ",
" c_1: 0 ════╩═",
" ",
]
)
self.assertEqual(
self.circuit.draw(output="text", initial_state=True, cregbundle=False).single_string(),
expected,
)
def test_initial_value_false(self):
"""Text drawer with initial_state parameter False."""
expected = "\n".join(
[
" ┌─┐ ",
"q_0: ┤M├───",
" └╥┘┌─┐",
"q_1: ─╫─┤M├",
" ║ └╥┘",
"c: 2/═╩══╩═",
" 0 1 ",
]
)
self.assertEqual(str(_text_circuit_drawer(self.circuit, initial_state=False)), expected)
class TestTextHamiltonianGate(QiskitTestCase):
"""Testing the Hamiltonian gate drawer"""
def test_draw_hamiltonian_single(self):
"""Text Hamiltonian gate with single qubit."""
# fmt: off
expected = "\n".join([" ┌─────────────┐",
"q0: ┤ Hamiltonian ├",
" └─────────────┘"])
# fmt: on
qr = QuantumRegister(1, "q0")
circuit = QuantumCircuit(qr)
matrix = numpy.zeros((2, 2))
theta = Parameter("theta")
circuit.append(HamiltonianGate(matrix, theta), [qr[0]])
circuit = circuit.bind_parameters({theta: 1})
self.assertEqual(circuit.draw(output="text").single_string(), expected)
def test_draw_hamiltonian_multi(self):
"""Text Hamiltonian gate with mutiple qubits."""
expected = "\n".join(
[
" ┌──────────────┐",
"q0_0: ┤0 ├",
" │ Hamiltonian │",
"q0_1: ┤1 ├",
" └──────────────┘",
]
)
qr = QuantumRegister(2, "q0")
circuit = QuantumCircuit(qr)
matrix = numpy.zeros((4, 4))
theta = Parameter("theta")
circuit.append(HamiltonianGate(matrix, theta), [qr[0], qr[1]])
circuit = circuit.bind_parameters({theta: 1})
self.assertEqual(circuit.draw(output="text").single_string(), expected)
class TestTextPhase(QiskitTestCase):
"""Testing the draweing a circuit with phase"""
def test_bell(self):
"""Text Bell state with phase."""
expected = "\n".join(
[
"global phase: \u03C0/2",
" ┌───┐ ",
"q_0: ┤ H ├──■──",
" └───┘┌─┴─┐",
"q_1: ─────┤ X ├",
" └───┘",
]
)
qr = QuantumRegister(2, "q")
circuit = QuantumCircuit(qr)
circuit.global_phase = 3.141592653589793 / 2
circuit.h(0)
circuit.cx(0, 1)
self.assertEqual(circuit.draw(output="text").single_string(), expected)
def test_empty(self):
"""Text empty circuit (two registers) with phase."""
# fmt: off
expected = "\n".join(["global phase: 3",
" ",
"q_0: ",
" ",
"q_1: ",
" "])
# fmt: on
qr = QuantumRegister(2, "q")
circuit = QuantumCircuit(qr)
circuit.global_phase = 3
self.assertEqual(circuit.draw(output="text").single_string(), expected)
def test_empty_noregs(self):
"""Text empty circuit (no registers) with phase."""
expected = "\n".join(["global phase: 4.21"])
circuit = QuantumCircuit()
circuit.global_phase = 4.21
self.assertEqual(circuit.draw(output="text").single_string(), expected)
def test_registerless_one_bit(self):
"""Text circuit with one-bit registers and registerless bits."""
# fmt: off
expected = "\n".join([" ",
"qrx_0: ",
" ",
"qrx_1: ",
" ",
" 2: ",
" ",
" 3: ",
" ",
" qry: ",
" ",
" 0: ",
" ",
" 1: ",
" ",
"crx: 2/",
" "])
# fmt: on
qrx = QuantumRegister(2, "qrx")
qry = QuantumRegister(1, "qry")
crx = ClassicalRegister(2, "crx")
circuit = QuantumCircuit(qrx, [Qubit(), Qubit()], qry, [Clbit(), Clbit()], crx)
self.assertEqual(circuit.draw(output="text", cregbundle=True).single_string(), expected)
class TestCircuitVisualizationImplementation(QiskitVisualizationTestCase):
"""Tests utf8 and cp437 encoding."""
text_reference_utf8 = path_to_diagram_reference("circuit_text_ref_utf8.txt")
text_reference_cp437 = path_to_diagram_reference("circuit_text_ref_cp437.txt")
def sample_circuit(self):
"""Generate a sample circuit that includes the most common elements of
quantum circuits.
"""
qr = QuantumRegister(3, "q")
cr = ClassicalRegister(3, "c")
circuit = QuantumCircuit(qr, cr)
circuit.x(qr[0])
circuit.y(qr[0])
circuit.z(qr[0])
circuit.barrier(qr[0])
circuit.barrier(qr[1])
circuit.barrier(qr[2])
circuit.h(qr[0])
circuit.s(qr[0])
circuit.sdg(qr[0])
circuit.t(qr[0])
circuit.tdg(qr[0])
circuit.sx(qr[0])
circuit.sxdg(qr[0])
circuit.i(qr[0])
circuit.reset(qr[0])
circuit.rx(pi, qr[0])
circuit.ry(pi, qr[0])
circuit.rz(pi, qr[0])
circuit.append(U1Gate(pi), [qr[0]])
circuit.append(U2Gate(pi, pi), [qr[0]])
circuit.append(U3Gate(pi, pi, pi), [qr[0]])
circuit.swap(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cy(qr[0], qr[1])
circuit.cz(qr[0], qr[1])
circuit.ch(qr[0], qr[1])
circuit.append(CU1Gate(pi), [qr[0], qr[1]])
circuit.append(CU3Gate(pi, pi, pi), [qr[0], qr[1]])
circuit.crz(pi, qr[0], qr[1])
circuit.cry(pi, qr[0], qr[1])
circuit.crx(pi, qr[0], qr[1])
circuit.ccx(qr[0], qr[1], qr[2])
circuit.cswap(qr[0], qr[1], qr[2])
circuit.measure(qr, cr)
return circuit
def test_text_drawer_utf8(self):
"""Test that text drawer handles utf8 encoding."""
filename = "current_textplot_utf8.txt"
qc = self.sample_circuit()
output = _text_circuit_drawer(
qc, filename=filename, fold=-1, initial_state=True, cregbundle=False, encoding="utf8"
)
try:
encode(str(output), encoding="utf8")
except UnicodeEncodeError:
self.fail("_text_circuit_drawer() should be utf8.")
self.assertFilesAreEqual(filename, self.text_reference_utf8, "utf8")
os.remove(filename)
def test_text_drawer_cp437(self):
"""Test that text drawer handles cp437 encoding."""
filename = "current_textplot_cp437.txt"
qc = self.sample_circuit()
output = _text_circuit_drawer(
qc, filename=filename, fold=-1, initial_state=True, cregbundle=False, encoding="cp437"
)
try:
encode(str(output), encoding="cp437")
except UnicodeEncodeError:
self.fail("_text_circuit_drawer() should be cp437.")
self.assertFilesAreEqual(filename, self.text_reference_cp437, "cp437")
os.remove(filename)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""A test for visualizing device coupling maps"""
import unittest
from io import BytesIO
from ddt import ddt, data
from qiskit.providers.fake_provider import (
FakeProvider,
FakeKolkata,
FakeWashington,
FakeKolkataV2,
FakeWashingtonV2,
)
from qiskit.visualization import (
plot_gate_map,
plot_coupling_map,
plot_circuit_layout,
plot_error_map,
)
from qiskit.utils import optionals
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.transpiler.layout import Layout, TranspileLayout
from .visualization import path_to_diagram_reference, QiskitVisualizationTestCase
if optionals.HAS_MATPLOTLIB:
import matplotlib.pyplot as plt
if optionals.HAS_PIL:
from PIL import Image
@ddt
@unittest.skipUnless(optionals.HAS_MATPLOTLIB, "matplotlib not available.")
@unittest.skipUnless(optionals.HAS_PIL, "PIL not available")
@unittest.skipUnless(optionals.HAS_SEABORN, "seaborn not available")
class TestGateMap(QiskitVisualizationTestCase):
"""visual tests for plot_gate_map"""
backends = list(
filter(
lambda x: not x.configuration().simulator
and x.configuration().num_qubits in range(5, 21),
FakeProvider().backends(),
)
)
@data(*backends)
def test_plot_gate_map(self, backend):
"""tests plotting of gate map of a device (20 qubit, 16 qubit, 14 qubit and 5 qubit)"""
n = backend.configuration().n_qubits
img_ref = path_to_diagram_reference(str(n) + "bit_quantum_computer.png")
fig = plot_gate_map(backend)
with BytesIO() as img_buffer:
fig.savefig(img_buffer, format="png")
img_buffer.seek(0)
self.assertImagesAreEqual(Image.open(img_buffer), img_ref, 0.2)
plt.close(fig)
@data(*backends)
def test_plot_circuit_layout(self, backend):
"""tests plot_circuit_layout for each device"""
layout_length = int(backend._configuration.n_qubits / 2)
qr = QuantumRegister(layout_length, "qr")
circuit = QuantumCircuit(qr)
circuit._layout = TranspileLayout(
Layout({qr[i]: i * 2 for i in range(layout_length)}),
{qubit: index for index, qubit in enumerate(circuit.qubits)},
)
circuit._layout.initial_layout.add_register(qr)
n = backend.configuration().n_qubits
img_ref = path_to_diagram_reference(str(n) + "_plot_circuit_layout.png")
fig = plot_circuit_layout(circuit, backend)
with BytesIO() as img_buffer:
fig.savefig(img_buffer, format="png")
img_buffer.seek(0)
self.assertImagesAreEqual(Image.open(img_buffer), img_ref, 0.1)
plt.close(fig)
def test_plot_gate_map_no_backend(self):
"""tests plotting of gate map without a device"""
n_qubits = 8
coupling_map = [[0, 1], [1, 2], [2, 3], [3, 5], [4, 5], [5, 6], [2, 4], [6, 7]]
qubit_coordinates = [[0, 1], [1, 1], [1, 0], [1, 2], [2, 0], [2, 2], [2, 1], [3, 1]]
img_ref = path_to_diagram_reference(str(n_qubits) + "qubits.png")
fig = plot_coupling_map(
num_qubits=n_qubits, qubit_coordinates=qubit_coordinates, coupling_map=coupling_map
)
with BytesIO() as img_buffer:
fig.savefig(img_buffer, format="png")
img_buffer.seek(0)
self.assertImagesAreEqual(Image.open(img_buffer), img_ref, 0.2)
plt.close(fig)
def test_plot_error_map_backend_v1(self):
"""Test plotting error map with fake backend v1."""
backend = FakeKolkata()
img_ref = path_to_diagram_reference("kolkata_error.png")
fig = plot_error_map(backend)
with BytesIO() as img_buffer:
fig.savefig(img_buffer, format="png")
img_buffer.seek(0)
self.assertImagesAreEqual(Image.open(img_buffer), img_ref, 0.2)
plt.close(fig)
def test_plot_error_map_backend_v2(self):
"""Test plotting error map with fake backend v2."""
backend = FakeKolkataV2()
img_ref = path_to_diagram_reference("kolkata_v2_error.png")
fig = plot_error_map(backend)
with BytesIO() as img_buffer:
fig.savefig(img_buffer, format="png")
img_buffer.seek(0)
self.assertImagesAreEqual(Image.open(img_buffer), img_ref, 0.2)
plt.close(fig)
def test_plot_error_map_over_100_qubit(self):
"""Test plotting error map with large fake backend."""
backend = FakeWashington()
img_ref = path_to_diagram_reference("washington_error.png")
fig = plot_error_map(backend)
with BytesIO() as img_buffer:
fig.savefig(img_buffer, format="png")
img_buffer.seek(0)
self.assertImagesAreEqual(Image.open(img_buffer), img_ref, 0.2)
plt.close(fig)
def test_plot_error_map_over_100_qubit_backend_v2(self):
"""Test plotting error map with large fake backendv2."""
backend = FakeWashingtonV2()
img_ref = path_to_diagram_reference("washington_v2_error.png")
fig = plot_error_map(backend)
with BytesIO() as img_buffer:
fig.savefig(img_buffer, format="png")
img_buffer.seek(0)
self.assertImagesAreEqual(Image.open(img_buffer), img_ref, 0.2)
plt.close(fig)
if __name__ == "__main__":
unittest.main(verbosity=2)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for pass manager visualization tool."""
import unittest
import os
from qiskit.transpiler import CouplingMap, Layout
from qiskit.transpiler.passmanager import PassManager
from qiskit import QuantumRegister
from qiskit.transpiler.passes import GateDirection, Unroller
from qiskit.transpiler.passes import CheckMap
from qiskit.transpiler.passes import SetLayout
from qiskit.transpiler.passes import TrivialLayout
from qiskit.transpiler.passes import BarrierBeforeFinalMeasurements
from qiskit.transpiler.passes import FullAncillaAllocation
from qiskit.transpiler.passes import EnlargeWithAncilla
from qiskit.transpiler.passes import RemoveResetInZeroState
from qiskit.utils import optionals
from .visualization import QiskitVisualizationTestCase, path_to_diagram_reference
@unittest.skipUnless(optionals.HAS_GRAPHVIZ, "Graphviz not installed.")
@unittest.skipUnless(optionals.HAS_PYDOT, "pydot not installed")
@unittest.skipUnless(optionals.HAS_PIL, "Pillow not installed")
class TestPassManagerDrawer(QiskitVisualizationTestCase):
"""Qiskit pass manager drawer tests."""
def setUp(self):
super().setUp()
coupling = [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6]]
coupling_map = CouplingMap(couplinglist=coupling)
basis_gates = ["u1", "u3", "u2", "cx"]
qr = QuantumRegister(7, "q")
layout = Layout({qr[i]: i for i in range(coupling_map.size())})
# Create a pass manager with a variety of passes and flow control structures
self.pass_manager = PassManager()
self.pass_manager.append(SetLayout(layout))
self.pass_manager.append(TrivialLayout(coupling_map), condition=lambda x: True)
self.pass_manager.append(FullAncillaAllocation(coupling_map))
self.pass_manager.append(EnlargeWithAncilla())
self.pass_manager.append(Unroller(basis_gates))
self.pass_manager.append(CheckMap(coupling_map))
self.pass_manager.append(BarrierBeforeFinalMeasurements(), do_while=lambda x: False)
self.pass_manager.append(GateDirection(coupling_map))
self.pass_manager.append(RemoveResetInZeroState())
def test_pass_manager_drawer_basic(self):
"""Test to see if the drawer draws a normal pass manager correctly"""
filename = "current_standard.dot"
self.pass_manager.draw(filename=filename, raw=True)
try:
self.assertFilesAreEqual(
filename, path_to_diagram_reference("pass_manager_standard.dot")
)
finally:
os.remove(filename)
def test_pass_manager_drawer_style(self):
"""Test to see if the colours are updated when provided by the user"""
# set colours for some passes, but leave others to take the default values
style = {
SetLayout: "cyan",
CheckMap: "green",
EnlargeWithAncilla: "pink",
RemoveResetInZeroState: "grey",
}
filename = "current_style.dot"
self.pass_manager.draw(filename=filename, style=style, raw=True)
try:
self.assertFilesAreEqual(filename, path_to_diagram_reference("pass_manager_style.dot"))
finally:
os.remove(filename)
if __name__ == "__main__":
unittest.main(verbosity=2)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for visualization tools."""
import unittest
import numpy as np
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.circuit import Qubit, Clbit
from qiskit.visualization.circuit import _utils
from qiskit.visualization import array_to_latex
from qiskit.test import QiskitTestCase
from qiskit.utils import optionals
class TestVisualizationUtils(QiskitTestCase):
"""Tests for circuit drawer utilities."""
def setUp(self):
super().setUp()
self.qr1 = QuantumRegister(2, "qr1")
self.qr2 = QuantumRegister(2, "qr2")
self.cr1 = ClassicalRegister(2, "cr1")
self.cr2 = ClassicalRegister(2, "cr2")
self.circuit = QuantumCircuit(self.qr1, self.qr2, self.cr1, self.cr2)
self.circuit.cx(self.qr2[0], self.qr2[1])
self.circuit.measure(self.qr2[0], self.cr2[0])
self.circuit.cx(self.qr2[1], self.qr2[0])
self.circuit.measure(self.qr2[1], self.cr2[1])
self.circuit.cx(self.qr1[0], self.qr1[1])
self.circuit.measure(self.qr1[0], self.cr1[0])
self.circuit.cx(self.qr1[1], self.qr1[0])
self.circuit.measure(self.qr1[1], self.cr1[1])
def test_get_layered_instructions(self):
"""_get_layered_instructions without reverse_bits"""
(qregs, cregs, layered_ops) = _utils._get_layered_instructions(self.circuit)
exp = [
[("cx", (self.qr2[0], self.qr2[1]), ()), ("cx", (self.qr1[0], self.qr1[1]), ())],
[("measure", (self.qr2[0],), (self.cr2[0],))],
[("measure", (self.qr1[0],), (self.cr1[0],))],
[("cx", (self.qr2[1], self.qr2[0]), ()), ("cx", (self.qr1[1], self.qr1[0]), ())],
[("measure", (self.qr2[1],), (self.cr2[1],))],
[("measure", (self.qr1[1],), (self.cr1[1],))],
]
self.assertEqual([self.qr1[0], self.qr1[1], self.qr2[0], self.qr2[1]], qregs)
self.assertEqual([self.cr1[0], self.cr1[1], self.cr2[0], self.cr2[1]], cregs)
self.assertEqual(
exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops]
)
def test_get_layered_instructions_reverse_bits(self):
"""_get_layered_instructions with reverse_bits=True"""
(qregs, cregs, layered_ops) = _utils._get_layered_instructions(
self.circuit, reverse_bits=True
)
exp = [
[("cx", (self.qr2[0], self.qr2[1]), ()), ("cx", (self.qr1[0], self.qr1[1]), ())],
[("measure", (self.qr2[0],), (self.cr2[0],))],
[("measure", (self.qr1[0],), (self.cr1[0],)), ("cx", (self.qr2[1], self.qr2[0]), ())],
[("cx", (self.qr1[1], self.qr1[0]), ())],
[("measure", (self.qr2[1],), (self.cr2[1],))],
[("measure", (self.qr1[1],), (self.cr1[1],))],
]
self.assertEqual([self.qr2[1], self.qr2[0], self.qr1[1], self.qr1[0]], qregs)
self.assertEqual([self.cr2[1], self.cr2[0], self.cr1[1], self.cr1[0]], cregs)
self.assertEqual(
exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops]
)
def test_get_layered_instructions_remove_idle_wires(self):
"""_get_layered_instructions with idle_wires=False"""
qr1 = QuantumRegister(3, "qr1")
qr2 = QuantumRegister(3, "qr2")
cr1 = ClassicalRegister(3, "cr1")
cr2 = ClassicalRegister(3, "cr2")
circuit = QuantumCircuit(qr1, qr2, cr1, cr2)
circuit.cx(qr2[0], qr2[1])
circuit.measure(qr2[0], cr2[0])
circuit.cx(qr2[1], qr2[0])
circuit.measure(qr2[1], cr2[1])
circuit.cx(qr1[0], qr1[1])
circuit.measure(qr1[0], cr1[0])
circuit.cx(qr1[1], qr1[0])
circuit.measure(qr1[1], cr1[1])
(qregs, cregs, layered_ops) = _utils._get_layered_instructions(circuit, idle_wires=False)
exp = [
[("cx", (qr2[0], qr2[1]), ()), ("cx", (qr1[0], qr1[1]), ())],
[("measure", (qr2[0],), (cr2[0],))],
[("measure", (qr1[0],), (cr1[0],))],
[("cx", (qr2[1], qr2[0]), ()), ("cx", (qr1[1], qr1[0]), ())],
[("measure", (qr2[1],), (cr2[1],))],
[("measure", (qr1[1],), (cr1[1],))],
]
self.assertEqual([qr1[0], qr1[1], qr2[0], qr2[1]], qregs)
self.assertEqual([cr1[0], cr1[1], cr2[0], cr2[1]], cregs)
self.assertEqual(
exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops]
)
def test_get_layered_instructions_left_justification_simple(self):
"""Test _get_layered_instructions left justification simple since #2802
q_0: |0>───────■──
┌───┐ │
q_1: |0>┤ H ├──┼──
├───┤ │
q_2: |0>┤ H ├──┼──
└───┘┌─┴─┐
q_3: |0>─────┤ X ├
└───┘
"""
qc = QuantumCircuit(4)
qc.h(1)
qc.h(2)
qc.cx(0, 3)
(_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="left")
l_exp = [
[
("h", (Qubit(QuantumRegister(4, "q"), 1),), ()),
("h", (Qubit(QuantumRegister(4, "q"), 2),), ()),
],
[("cx", (Qubit(QuantumRegister(4, "q"), 0), Qubit(QuantumRegister(4, "q"), 3)), ())],
]
self.assertEqual(
l_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops]
)
def test_get_layered_instructions_right_justification_simple(self):
"""Test _get_layered_instructions right justification simple since #2802
q_0: |0>──■───────
│ ┌───┐
q_1: |0>──┼──┤ H ├
│ ├───┤
q_2: |0>──┼──┤ H ├
┌─┴─┐└───┘
q_3: |0>┤ X ├─────
└───┘
"""
qc = QuantumCircuit(4)
qc.h(1)
qc.h(2)
qc.cx(0, 3)
(_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="right")
r_exp = [
[("cx", (Qubit(QuantumRegister(4, "q"), 0), Qubit(QuantumRegister(4, "q"), 3)), ())],
[
("h", (Qubit(QuantumRegister(4, "q"), 1),), ()),
("h", (Qubit(QuantumRegister(4, "q"), 2),), ()),
],
]
self.assertEqual(
r_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops]
)
def test_get_layered_instructions_left_justification_less_simple(self):
"""Test _get_layered_instructions left justification
less simple example since #2802
┌────────────┐┌───┐┌────────────┐ ┌─┐┌────────────┐┌───┐┌────────────┐
q_0: |0>┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├──────────────┤M├┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├
├────────────┤└─┬─┘├────────────┤┌────────────┐└╥┘└────────────┘└─┬─┘├────────────┤
q_1: |0>┤ U2(0,pi/1) ├──■──┤ U2(0,pi/1) ├┤ U2(0,pi/1) ├─╫─────────────────■──┤ U2(0,pi/1) ├
└────────────┘ └────────────┘└────────────┘ ║ └────────────┘
q_2: |0>────────────────────────────────────────────────╫──────────────────────────────────
║
q_3: |0>────────────────────────────────────────────────╫──────────────────────────────────
║
q_4: |0>────────────────────────────────────────────────╫──────────────────────────────────
║
c1_0: 0 ════════════════════════════════════════════════╩══════════════════════════════════
"""
qasm = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[5];
creg c1[1];
u2(0,3.14159265358979) q[0];
u2(0,3.14159265358979) q[1];
cx q[1],q[0];
u2(0,3.14159265358979) q[0];
u2(0,3.14159265358979) q[1];
u2(0,3.14159265358979) q[1];
measure q[0] -> c1[0];
u2(0,3.14159265358979) q[0];
cx q[1],q[0];
u2(0,3.14159265358979) q[0];
u2(0,3.14159265358979) q[1];
"""
qc = QuantumCircuit.from_qasm_str(qasm)
(_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="left")
l_exp = [
[
("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()),
("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()),
],
[("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())],
[
("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()),
("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()),
],
[("u2", (Qubit(QuantumRegister(5, "q"), 1),), ())],
[
(
"measure",
(Qubit(QuantumRegister(5, "q"), 0),),
(Clbit(ClassicalRegister(1, "c1"), 0),),
)
],
[("u2", (Qubit(QuantumRegister(5, "q"), 0),), ())],
[("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())],
[
("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()),
("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()),
],
]
self.assertEqual(
l_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops]
)
def test_get_layered_instructions_right_justification_less_simple(self):
"""Test _get_layered_instructions right justification
less simple example since #2802
┌────────────┐┌───┐┌────────────┐┌─┐┌────────────┐┌───┐┌────────────┐
q_0: |0>┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├┤M├┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├
├────────────┤└─┬─┘├────────────┤└╥┘├────────────┤└─┬─┘├────────────┤
q_1: |0>┤ U2(0,pi/1) ├──■──┤ U2(0,pi/1) ├─╫─┤ U2(0,pi/1) ├──■──┤ U2(0,pi/1) ├
└────────────┘ └────────────┘ ║ └────────────┘ └────────────┘
q_2: |0>──────────────────────────────────╫──────────────────────────────────
║
q_3: |0>──────────────────────────────────╫──────────────────────────────────
║
q_4: |0>──────────────────────────────────╫──────────────────────────────────
║
c1_0: 0 ══════════════════════════════════╩══════════════════════════════════
"""
qasm = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[5];
creg c1[1];
u2(0,3.14159265358979) q[0];
u2(0,3.14159265358979) q[1];
cx q[1],q[0];
u2(0,3.14159265358979) q[0];
u2(0,3.14159265358979) q[1];
u2(0,3.14159265358979) q[1];
measure q[0] -> c1[0];
u2(0,3.14159265358979) q[0];
cx q[1],q[0];
u2(0,3.14159265358979) q[0];
u2(0,3.14159265358979) q[1];
"""
qc = QuantumCircuit.from_qasm_str(qasm)
(_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="right")
r_exp = [
[
("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()),
("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()),
],
[("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())],
[
("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()),
("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()),
],
[
(
"measure",
(Qubit(QuantumRegister(5, "q"), 0),),
(Clbit(ClassicalRegister(1, "c1"), 0),),
)
],
[
("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()),
("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()),
],
[("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())],
[
("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()),
("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()),
],
]
self.assertEqual(
r_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops]
)
def test_get_layered_instructions_op_with_cargs(self):
"""Test _get_layered_instructions op with cargs right of measure
┌───┐┌─┐
q_0: |0>┤ H ├┤M├─────────────
└───┘└╥┘┌───────────┐
q_1: |0>──────╫─┤0 ├
║ │ add_circ │
c_0: 0 ══════╩═╡0 ╞
└───────────┘
c_1: 0 ═════════════════════
"""
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.measure(0, 0)
qc_2 = QuantumCircuit(1, 1, name="add_circ")
qc_2.h(0).c_if(qc_2.cregs[0], 1)
qc_2.measure(0, 0)
qc.append(qc_2, [1], [0])
(_, _, layered_ops) = _utils._get_layered_instructions(qc)
expected = [
[("h", (Qubit(QuantumRegister(2, "q"), 0),), ())],
[
(
"measure",
(Qubit(QuantumRegister(2, "q"), 0),),
(Clbit(ClassicalRegister(2, "c"), 0),),
)
],
[
(
"add_circ",
(Qubit(QuantumRegister(2, "q"), 1),),
(Clbit(ClassicalRegister(2, "c"), 0),),
)
],
]
self.assertEqual(
expected, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops]
)
@unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc")
def test_generate_latex_label_nomathmode(self):
"""Test generate latex label default."""
self.assertEqual("abc", _utils.generate_latex_label("abc"))
@unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc")
def test_generate_latex_label_nomathmode_utf8char(self):
"""Test generate latex label utf8 characters."""
self.assertEqual(
"{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y",
_utils.generate_latex_label("∭X∀Y"),
)
@unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc")
def test_generate_latex_label_mathmode_utf8char(self):
"""Test generate latex label mathtext with utf8."""
self.assertEqual(
"abc_{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y",
_utils.generate_latex_label("$abc_$∭X∀Y"),
)
@unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc")
def test_generate_latex_label_mathmode_underscore_outside(self):
"""Test generate latex label with underscore outside mathmode."""
self.assertEqual(
"abc_{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y",
_utils.generate_latex_label("$abc$_∭X∀Y"),
)
@unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc")
def test_generate_latex_label_escaped_dollar_signs(self):
"""Test generate latex label with escaped dollarsign."""
self.assertEqual("${\\ensuremath{\\forall}}$", _utils.generate_latex_label(r"\$∀\$"))
@unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc")
def test_generate_latex_label_escaped_dollar_sign_in_mathmode(self):
"""Test generate latex label with escaped dollar sign in mathmode."""
self.assertEqual(
"a$bc_{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y",
_utils.generate_latex_label(r"$a$bc$_∭X∀Y"),
)
def test_array_to_latex(self):
"""Test array_to_latex produces correct latex string"""
matrix = [
[np.sqrt(1 / 2), 1 / 16, 1 / np.sqrt(8) + 3j, -0.5 + 0.5j],
[1 / 3 - 1 / 3j, np.sqrt(1 / 2) * 1j, 34.3210, -9 / 2],
]
matrix = np.array(matrix)
exp_str = (
"\\begin{bmatrix}\\frac{\\sqrt{2}}{2}&\\frac{1}{16}&"
"\\frac{\\sqrt{2}}{4}+3i&-\\frac{1}{2}+\\frac{i}{2}\\\\"
"\\frac{1}{3}+\\frac{i}{3}&\\frac{\\sqrt{2}i}{2}&34.321&-"
"\\frac{9}{2}\\\\\\end{bmatrix}"
)
result = array_to_latex(matrix, source=True).replace(" ", "").replace("\n", "")
self.assertEqual(exp_str, result)
if __name__ == "__main__":
unittest.main(verbosity=2)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for core modules of timeline drawer."""
from qiskit import QuantumCircuit, transpile
from qiskit.test import QiskitTestCase
from qiskit.visualization.timeline import core, stylesheet, generators, layouts
class TestCanvas(QiskitTestCase):
"""Test for canvas."""
def setUp(self):
super().setUp()
self.style = stylesheet.QiskitTimelineStyle()
circ = QuantumCircuit(4)
circ.h(0)
circ.barrier()
circ.cx(0, 2)
circ.cx(1, 3)
self.circ = transpile(
circ,
scheduling_method="alap",
basis_gates=["h", "cx"],
instruction_durations=[("h", 0, 200), ("cx", [0, 2], 1000), ("cx", [1, 3], 1000)],
optimization_level=0,
)
def test_time_range(self):
"""Test calculating time range."""
canvas = core.DrawerCanvas(stylesheet=self.style)
canvas.formatter = {"margin.left_percent": 0.1, "margin.right_percent": 0.1}
canvas.time_range = (0, 100)
ref_range = [-10.0, 110.0]
self.assertListEqual(list(canvas.time_range), ref_range)
def test_load_program(self):
"""Test loading program."""
canvas = core.DrawerCanvas(stylesheet=self.style)
canvas.generator = {
"gates": [generators.gen_sched_gate],
"bits": [],
"barriers": [],
"gate_links": [],
}
canvas.layout = {
"bit_arrange": layouts.qreg_creg_ascending,
"time_axis_map": layouts.time_map_in_dt,
}
canvas.load_program(self.circ)
canvas.update()
drawings_tested = list(canvas.collections)
self.assertEqual(len(drawings_tested), 8)
ref_coord = {
self.circ.qregs[0][0]: -1.0,
self.circ.qregs[0][1]: -2.0,
self.circ.qregs[0][2]: -3.0,
self.circ.qregs[0][3]: -4.0,
}
self.assertDictEqual(canvas.assigned_coordinates, ref_coord)
def test_gate_link_overlap(self):
"""Test shifting gate link overlap."""
canvas = core.DrawerCanvas(stylesheet=self.style)
canvas.formatter.update(
{
"margin.link_interval_percent": 0.01,
"margin.left_percent": 0,
"margin.right_percent": 0,
}
)
canvas.generator = {
"gates": [],
"bits": [],
"barriers": [],
"gate_links": [generators.gen_gate_link],
}
canvas.layout = {
"bit_arrange": layouts.qreg_creg_ascending,
"time_axis_map": layouts.time_map_in_dt,
}
canvas.load_program(self.circ)
canvas.update()
drawings_tested = list(canvas.collections)
self.assertEqual(len(drawings_tested), 2)
self.assertListEqual(drawings_tested[0][1].xvals, [706.0])
self.assertListEqual(drawings_tested[1][1].xvals, [694.0])
ref_keys = list(canvas._collections.keys())
self.assertEqual(drawings_tested[0][0], ref_keys[0])
self.assertEqual(drawings_tested[1][0], ref_keys[1])
def test_object_outside_xlimit(self):
"""Test eliminating drawings outside the horizontal limit."""
canvas = core.DrawerCanvas(stylesheet=self.style)
canvas.generator = {
"gates": [generators.gen_sched_gate],
"bits": [generators.gen_bit_name, generators.gen_timeslot],
"barriers": [],
"gate_links": [],
}
canvas.layout = {
"bit_arrange": layouts.qreg_creg_ascending,
"time_axis_map": layouts.time_map_in_dt,
}
canvas.load_program(self.circ)
canvas.set_time_range(t_start=400, t_end=600)
canvas.update()
drawings_tested = list(canvas.collections)
self.assertEqual(len(drawings_tested), 12)
def test_non_transpiled_delay_circuit(self):
"""Test non-transpiled circuit containing instruction which is trivial on duration."""
circ = QuantumCircuit(1)
circ.delay(10, 0)
canvas = core.DrawerCanvas(stylesheet=self.style)
canvas.generator = {
"gates": [generators.gen_sched_gate],
"bits": [],
"barriers": [],
"gate_links": [],
}
with self.assertWarns(DeprecationWarning):
canvas.load_program(circ)
self.assertEqual(len(canvas._collections), 1)
def test_multi_measurement_with_clbit_not_shown(self):
"""Test generating bit link drawings of measurements when clbits is disabled."""
circ = QuantumCircuit(2, 2)
circ.measure(0, 0)
circ.measure(1, 1)
circ = transpile(
circ,
scheduling_method="alap",
basis_gates=[],
instruction_durations=[("measure", 0, 2000), ("measure", 1, 2000)],
optimization_level=0,
)
canvas = core.DrawerCanvas(stylesheet=self.style)
canvas.formatter.update({"control.show_clbits": False})
canvas.layout = {
"bit_arrange": layouts.qreg_creg_ascending,
"time_axis_map": layouts.time_map_in_dt,
}
canvas.generator = {
"gates": [],
"bits": [],
"barriers": [],
"gate_links": [generators.gen_gate_link],
}
canvas.load_program(circ)
canvas.update()
self.assertEqual(len(canvas._output_dataset), 0)
def test_multi_measurement_with_clbit_shown(self):
"""Test generating bit link drawings of measurements when clbits is enabled."""
circ = QuantumCircuit(2, 2)
circ.measure(0, 0)
circ.measure(1, 1)
circ = transpile(
circ,
scheduling_method="alap",
basis_gates=[],
instruction_durations=[("measure", 0, 2000), ("measure", 1, 2000)],
optimization_level=0,
)
canvas = core.DrawerCanvas(stylesheet=self.style)
canvas.formatter.update({"control.show_clbits": True})
canvas.layout = {
"bit_arrange": layouts.qreg_creg_ascending,
"time_axis_map": layouts.time_map_in_dt,
}
canvas.generator = {
"gates": [],
"bits": [],
"barriers": [],
"gate_links": [generators.gen_gate_link],
}
canvas.load_program(circ)
canvas.update()
self.assertEqual(len(canvas._output_dataset), 2)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for drawing of timeline drawer."""
import numpy as np
import qiskit
from qiskit.test import QiskitTestCase
from qiskit.visualization.timeline import drawings, types
class TestDrawingObjects(QiskitTestCase):
"""Tests for drawings."""
def setUp(self) -> None:
"""Setup."""
super().setUp()
# bits
self.qubits = list(qiskit.QuantumRegister(2))
# metadata
self.meta1 = {"val1": 0, "val2": 1}
self.meta2 = {"val1": 2, "val2": 3}
# style data
self.style1 = {"property1": 0, "property2": 1}
self.style2 = {"property1": 2, "property2": 3}
def test_line_data_equivalent(self):
"""Test LineData equivalent check."""
xs = list(np.arange(10))
ys = list(np.ones(10))
obj1 = drawings.LineData(
data_type=types.LineType.BARRIER,
bit=self.qubits[0],
xvals=xs,
yvals=ys,
meta=self.meta1,
styles=self.style1,
)
obj2 = drawings.LineData(
data_type=types.LineType.BARRIER,
bit=self.qubits[0],
xvals=xs,
yvals=ys,
meta=self.meta2,
styles=self.style2,
)
self.assertEqual(obj1, obj2)
def test_line_data_equivalent_abstract_coord(self):
"""Test LineData equivalent check with abstract coordinate."""
xs = [types.AbstractCoordinate.LEFT, types.AbstractCoordinate.RIGHT]
ys = [types.AbstractCoordinate.BOTTOM, types.AbstractCoordinate.TOP]
obj1 = drawings.LineData(
data_type=types.LineType.BARRIER,
bit=self.qubits[0],
xvals=xs,
yvals=ys,
meta=self.meta1,
styles=self.style1,
)
obj2 = drawings.LineData(
data_type=types.LineType.BARRIER,
bit=self.qubits[0],
xvals=xs,
yvals=ys,
meta=self.meta2,
styles=self.style2,
)
self.assertEqual(obj1, obj2)
def test_box_data_equivalent(self):
"""Test BoxData equivalent check."""
xs = [0, 1]
ys = [0, 1]
obj1 = drawings.BoxData(
data_type=types.BoxType.SCHED_GATE,
bit=self.qubits[0],
xvals=xs,
yvals=ys,
meta=self.meta1,
styles=self.style1,
)
obj2 = drawings.BoxData(
data_type=types.BoxType.SCHED_GATE,
bit=self.qubits[0],
xvals=xs,
yvals=ys,
meta=self.meta2,
styles=self.style2,
)
self.assertEqual(obj1, obj2)
def test_box_data_equivalent_abstract_coord(self):
"""Test BoxData equivalent check with abstract coordinate."""
xs = [types.AbstractCoordinate.LEFT, types.AbstractCoordinate.RIGHT]
ys = [types.AbstractCoordinate.BOTTOM, types.AbstractCoordinate.TOP]
obj1 = drawings.BoxData(
data_type=types.BoxType.SCHED_GATE,
bit=self.qubits[0],
xvals=xs,
yvals=ys,
meta=self.meta1,
styles=self.style1,
)
obj2 = drawings.BoxData(
data_type=types.BoxType.SCHED_GATE,
bit=self.qubits[0],
xvals=xs,
yvals=ys,
meta=self.meta2,
styles=self.style2,
)
self.assertEqual(obj1, obj2)
def test_text_data_equivalent(self):
"""Test TextData equivalent check."""
obj1 = drawings.TextData(
data_type=types.LabelType.GATE_NAME,
bit=self.qubits[0],
xval=0,
yval=0,
text="test",
latex="test",
meta=self.meta1,
styles=self.style1,
)
obj2 = drawings.TextData(
data_type=types.LabelType.GATE_NAME,
bit=self.qubits[0],
xval=0,
yval=0,
text="test",
latex="test",
meta=self.meta2,
styles=self.style2,
)
self.assertEqual(obj1, obj2)
def test_text_data_equivalent_abstract_coord(self):
"""Test TextData equivalent check with abstract coordinate."""
obj1 = drawings.TextData(
data_type=types.LabelType.GATE_NAME,
bit=self.qubits[0],
xval=types.AbstractCoordinate.LEFT,
yval=types.AbstractCoordinate.BOTTOM,
text="test",
latex="test",
meta=self.meta1,
styles=self.style1,
)
obj2 = drawings.TextData(
data_type=types.LabelType.GATE_NAME,
bit=self.qubits[0],
xval=types.AbstractCoordinate.LEFT,
yval=types.AbstractCoordinate.BOTTOM,
text="test",
latex="test",
meta=self.meta2,
styles=self.style2,
)
self.assertEqual(obj1, obj2)
def test_bit_link_data_equivalent(self):
"""Test BitLinkData equivalent check."""
obj1 = drawings.GateLinkData(
bits=[self.qubits[0], self.qubits[1]], xval=0, styles=self.style1
)
obj2 = drawings.GateLinkData(
bits=[self.qubits[0], self.qubits[1]], xval=0, styles=self.style2
)
self.assertEqual(obj1, obj2)
def test_bit_link_data_equivalent_abstract_coord(self):
"""Test BitLinkData equivalent check with abstract coordinate."""
obj1 = drawings.GateLinkData(
bits=[self.qubits[0], self.qubits[1]],
xval=types.AbstractCoordinate.LEFT,
styles=self.style1,
)
obj2 = drawings.GateLinkData(
bits=[self.qubits[0], self.qubits[1]],
xval=types.AbstractCoordinate.LEFT,
styles=self.style2,
)
self.assertEqual(obj1, obj2)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for core modules of pulse drawer."""
from qiskit import pulse, circuit
from qiskit.test import QiskitTestCase
from qiskit.visualization.pulse_v2 import events
class TestChannelEvents(QiskitTestCase):
"""Tests for ChannelEvents."""
def test_parse_program(self):
"""Test typical pulse program."""
test_pulse = pulse.Gaussian(10, 0.1, 3)
sched = pulse.Schedule()
sched = sched.insert(0, pulse.SetPhase(3.14, pulse.DriveChannel(0)))
sched = sched.insert(0, pulse.Play(test_pulse, pulse.DriveChannel(0)))
sched = sched.insert(10, pulse.ShiftPhase(-1.57, pulse.DriveChannel(0)))
sched = sched.insert(10, pulse.Play(test_pulse, pulse.DriveChannel(0)))
ch_events = events.ChannelEvents.load_program(sched, pulse.DriveChannel(0))
# check waveform data
waveforms = list(ch_events.get_waveforms())
inst_data0 = waveforms[0]
self.assertEqual(inst_data0.t0, 0)
self.assertEqual(inst_data0.frame.phase, 3.14)
self.assertEqual(inst_data0.frame.freq, 0)
self.assertEqual(inst_data0.inst, pulse.Play(test_pulse, pulse.DriveChannel(0)))
inst_data1 = waveforms[1]
self.assertEqual(inst_data1.t0, 10)
self.assertEqual(inst_data1.frame.phase, 1.57)
self.assertEqual(inst_data1.frame.freq, 0)
self.assertEqual(inst_data1.inst, pulse.Play(test_pulse, pulse.DriveChannel(0)))
# check frame data
frames = list(ch_events.get_frame_changes())
inst_data0 = frames[0]
self.assertEqual(inst_data0.t0, 0)
self.assertEqual(inst_data0.frame.phase, 3.14)
self.assertEqual(inst_data0.frame.freq, 0)
self.assertListEqual(inst_data0.inst, [pulse.SetPhase(3.14, pulse.DriveChannel(0))])
inst_data1 = frames[1]
self.assertEqual(inst_data1.t0, 10)
self.assertEqual(inst_data1.frame.phase, -1.57)
self.assertEqual(inst_data1.frame.freq, 0)
self.assertListEqual(inst_data1.inst, [pulse.ShiftPhase(-1.57, pulse.DriveChannel(0))])
def test_multiple_frames_at_the_same_time(self):
"""Test multiple frame instruction at the same time."""
# shift phase followed by set phase
sched = pulse.Schedule()
sched = sched.insert(0, pulse.ShiftPhase(-1.57, pulse.DriveChannel(0)))
sched = sched.insert(0, pulse.SetPhase(3.14, pulse.DriveChannel(0)))
ch_events = events.ChannelEvents.load_program(sched, pulse.DriveChannel(0))
frames = list(ch_events.get_frame_changes())
inst_data0 = frames[0]
self.assertAlmostEqual(inst_data0.frame.phase, 3.14)
# set phase followed by shift phase
sched = pulse.Schedule()
sched = sched.insert(0, pulse.SetPhase(3.14, pulse.DriveChannel(0)))
sched = sched.insert(0, pulse.ShiftPhase(-1.57, pulse.DriveChannel(0)))
ch_events = events.ChannelEvents.load_program(sched, pulse.DriveChannel(0))
frames = list(ch_events.get_frame_changes())
inst_data0 = frames[0]
self.assertAlmostEqual(inst_data0.frame.phase, 1.57)
def test_frequency(self):
"""Test parse frequency."""
sched = pulse.Schedule()
sched = sched.insert(0, pulse.ShiftFrequency(1.0, pulse.DriveChannel(0)))
sched = sched.insert(5, pulse.SetFrequency(5.0, pulse.DriveChannel(0)))
ch_events = events.ChannelEvents.load_program(sched, pulse.DriveChannel(0))
ch_events.set_config(dt=0.1, init_frequency=3.0, init_phase=0)
frames = list(ch_events.get_frame_changes())
inst_data0 = frames[0]
self.assertAlmostEqual(inst_data0.frame.freq, 1.0)
inst_data1 = frames[1]
self.assertAlmostEqual(inst_data1.frame.freq, 1.0)
def test_parameterized_parametric_pulse(self):
"""Test generating waveforms that are parameterized."""
param = circuit.Parameter("amp")
test_waveform = pulse.Play(pulse.Constant(10, param), pulse.DriveChannel(0))
ch_events = events.ChannelEvents(
waveforms={0: test_waveform}, frames={}, channel=pulse.DriveChannel(0)
)
pulse_inst = list(ch_events.get_waveforms())[0]
self.assertTrue(pulse_inst.is_opaque)
self.assertEqual(pulse_inst.inst, test_waveform)
def test_parameterized_frame_change(self):
"""Test generating waveforms that are parameterized.
Parameterized phase should be ignored when calculating waveform frame.
This is due to phase modulated representation of waveforms,
i.e. we cannot calculate the phase factor of waveform if the phase is unbound.
"""
param = circuit.Parameter("phase")
test_fc1 = pulse.ShiftPhase(param, pulse.DriveChannel(0))
test_fc2 = pulse.ShiftPhase(1.57, pulse.DriveChannel(0))
test_waveform = pulse.Play(pulse.Constant(10, 0.1), pulse.DriveChannel(0))
ch_events = events.ChannelEvents(
waveforms={0: test_waveform},
frames={0: [test_fc1, test_fc2]},
channel=pulse.DriveChannel(0),
)
# waveform frame
pulse_inst = list(ch_events.get_waveforms())[0]
self.assertFalse(pulse_inst.is_opaque)
self.assertEqual(pulse_inst.frame.phase, 1.57)
# framechange
pulse_inst = list(ch_events.get_frame_changes())[0]
self.assertTrue(pulse_inst.is_opaque)
self.assertEqual(pulse_inst.frame.phase, param + 1.57)
def test_zero_duration_delay(self):
"""Test generating waveforms that contains zero duration delay.
Zero duration delay should be ignored.
"""
ch = pulse.DriveChannel(0)
test_sched = pulse.Schedule()
test_sched += pulse.Play(pulse.Gaussian(160, 0.1, 40), ch)
test_sched += pulse.Delay(0, ch)
test_sched += pulse.Play(pulse.Gaussian(160, 0.1, 40), ch)
test_sched += pulse.Delay(1, ch)
test_sched += pulse.Play(pulse.Gaussian(160, 0.1, 40), ch)
ch_events = events.ChannelEvents.load_program(test_sched, ch)
self.assertEqual(len(list(ch_events.get_waveforms())), 4)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=invalid-name
"""Tests for generator of timeline drawer."""
import qiskit
from qiskit.test import QiskitTestCase
from qiskit.visualization.timeline import generators, types, stylesheet
from qiskit.circuit import library, Delay
class TestGates(QiskitTestCase):
"""Tests for generator.gates."""
def setUp(self) -> None:
"""Setup."""
super().setUp()
self.qubit = list(qiskit.QuantumRegister(1))[0]
self.u1 = types.ScheduledGate(
t0=100, operand=library.U1Gate(0), duration=0, bits=[self.qubit], bit_position=0
)
self.u3 = types.ScheduledGate(
t0=100, operand=library.U3Gate(0, 0, 0), duration=20, bits=[self.qubit], bit_position=0
)
self.delay = types.ScheduledGate(
t0=100, operand=Delay(20), duration=20, bits=[self.qubit], bit_position=0
)
style = stylesheet.QiskitTimelineStyle()
self.formatter = style.formatter
def test_gen_sched_gate_with_finite_duration(self):
"""Test test_gen_sched_gate generator with finite duration gate."""
drawing_obj = generators.gen_sched_gate(self.u3, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.BoxType.SCHED_GATE.value))
self.assertListEqual(list(drawing_obj.xvals), [100, 120])
self.assertListEqual(
list(drawing_obj.yvals),
[-0.5 * self.formatter["box_height.gate"], 0.5 * self.formatter["box_height.gate"]],
)
self.assertListEqual(drawing_obj.bits, [self.qubit])
ref_meta = {
"name": "u3",
"label": "n/a",
"bits": str(self.qubit.register.name),
"t0": 100,
"duration": 20,
"unitary": "[[1.+0.j 0.-0.j]\n [0.+0.j 1.+0.j]]",
"parameters": "0, 0, 0",
}
self.assertDictEqual(ref_meta, drawing_obj.meta)
ref_styles = {
"zorder": self.formatter["layer.gate"],
"facecolor": self.formatter["color.gates"]["u3"],
"alpha": self.formatter["alpha.gate"],
"linewidth": self.formatter["line_width.gate"],
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
def test_gen_sched_gate_with_zero_duration(self):
"""Test test_gen_sched_gate generator with zero duration gate."""
drawing_obj = generators.gen_sched_gate(self.u1, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.SymbolType.FRAME.value))
self.assertListEqual(list(drawing_obj.xvals), [100])
self.assertListEqual(list(drawing_obj.yvals), [0])
self.assertListEqual(drawing_obj.bits, [self.qubit])
self.assertEqual(drawing_obj.text, self.formatter["unicode_symbol.frame_change"])
self.assertEqual(drawing_obj.latex, self.formatter["latex_symbol.frame_change"])
ref_styles = {
"zorder": self.formatter["layer.frame_change"],
"color": self.formatter["color.gates"]["u1"],
"size": self.formatter["text_size.frame_change"],
"va": "center",
"ha": "center",
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
def test_gen_sched_gate_with_delay(self):
"""Test test_gen_sched_gate generator with delay."""
drawing_obj = generators.gen_sched_gate(self.delay, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.BoxType.DELAY.value))
def test_gen_full_gate_name_with_finite_duration(self):
"""Test gen_full_gate_name generator with finite duration gate."""
drawing_obj = generators.gen_full_gate_name(self.u3, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value))
self.assertListEqual(list(drawing_obj.xvals), [110.0])
self.assertListEqual(list(drawing_obj.yvals), [0.0])
self.assertListEqual(drawing_obj.bits, [self.qubit])
self.assertEqual(drawing_obj.text, "u3(0.00, 0.00, 0.00)[20]")
ref_latex = "{name}(0.00, 0.00, 0.00)[20]".format(
name=self.formatter["latex_symbol.gates"]["u3"]
)
self.assertEqual(drawing_obj.latex, ref_latex)
ref_styles = {
"zorder": self.formatter["layer.gate_name"],
"color": self.formatter["color.gate_name"],
"size": self.formatter["text_size.gate_name"],
"va": "center",
"ha": "center",
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
def test_gen_full_gate_name_with_zero_duration(self):
"""Test gen_full_gate_name generator with zero duration gate."""
drawing_obj = generators.gen_full_gate_name(self.u1, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value))
self.assertListEqual(list(drawing_obj.xvals), [100.0])
self.assertListEqual(list(drawing_obj.yvals), [self.formatter["label_offset.frame_change"]])
self.assertListEqual(drawing_obj.bits, [self.qubit])
self.assertEqual(drawing_obj.text, "u1(0.00)")
ref_latex = "{name}(0.00)".format(name=self.formatter["latex_symbol.gates"]["u1"])
self.assertEqual(drawing_obj.latex, ref_latex)
ref_styles = {
"zorder": self.formatter["layer.gate_name"],
"color": self.formatter["color.gate_name"],
"size": self.formatter["text_size.gate_name"],
"va": "bottom",
"ha": "center",
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
def test_gen_full_gate_name_with_delay(self):
"""Test gen_full_gate_name generator with delay."""
drawing_obj = generators.gen_full_gate_name(self.delay, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LabelType.DELAY.value))
def test_gen_short_gate_name_with_finite_duration(self):
"""Test gen_short_gate_name generator with finite duration gate."""
drawing_obj = generators.gen_short_gate_name(self.u3, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value))
self.assertListEqual(list(drawing_obj.xvals), [110.0])
self.assertListEqual(list(drawing_obj.yvals), [0.0])
self.assertListEqual(drawing_obj.bits, [self.qubit])
self.assertEqual(drawing_obj.text, "u3")
ref_latex = "{name}".format(name=self.formatter["latex_symbol.gates"]["u3"])
self.assertEqual(drawing_obj.latex, ref_latex)
ref_styles = {
"zorder": self.formatter["layer.gate_name"],
"color": self.formatter["color.gate_name"],
"size": self.formatter["text_size.gate_name"],
"va": "center",
"ha": "center",
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
def test_gen_short_gate_name_with_zero_duration(self):
"""Test gen_short_gate_name generator with zero duration gate."""
drawing_obj = generators.gen_short_gate_name(self.u1, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value))
self.assertListEqual(list(drawing_obj.xvals), [100.0])
self.assertListEqual(list(drawing_obj.yvals), [self.formatter["label_offset.frame_change"]])
self.assertListEqual(drawing_obj.bits, [self.qubit])
self.assertEqual(drawing_obj.text, "u1")
ref_latex = "{name}".format(name=self.formatter["latex_symbol.gates"]["u1"])
self.assertEqual(drawing_obj.latex, ref_latex)
ref_styles = {
"zorder": self.formatter["layer.gate_name"],
"color": self.formatter["color.gate_name"],
"size": self.formatter["text_size.gate_name"],
"va": "bottom",
"ha": "center",
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
def test_gen_short_gate_name_with_delay(self):
"""Test gen_short_gate_name generator with delay."""
drawing_obj = generators.gen_short_gate_name(self.delay, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LabelType.DELAY.value))
class TestTimeslot(QiskitTestCase):
"""Tests for generator.bits."""
def setUp(self) -> None:
"""Setup."""
super().setUp()
self.qubit = list(qiskit.QuantumRegister(1))[0]
style = stylesheet.QiskitTimelineStyle()
self.formatter = style.formatter
def test_gen_timeslot(self):
"""Test gen_timeslot generator."""
drawing_obj = generators.gen_timeslot(self.qubit, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.BoxType.TIMELINE.value))
self.assertListEqual(
list(drawing_obj.xvals), [types.AbstractCoordinate.LEFT, types.AbstractCoordinate.RIGHT]
)
self.assertListEqual(
list(drawing_obj.yvals),
[
-0.5 * self.formatter["box_height.timeslot"],
0.5 * self.formatter["box_height.timeslot"],
],
)
self.assertListEqual(drawing_obj.bits, [self.qubit])
ref_styles = {
"zorder": self.formatter["layer.timeslot"],
"alpha": self.formatter["alpha.timeslot"],
"linewidth": self.formatter["line_width.timeslot"],
"facecolor": self.formatter["color.timeslot"],
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
def test_gen_bit_name(self):
"""Test gen_bit_name generator."""
drawing_obj = generators.gen_bit_name(self.qubit, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LabelType.BIT_NAME.value))
self.assertListEqual(list(drawing_obj.xvals), [types.AbstractCoordinate.LEFT])
self.assertListEqual(list(drawing_obj.yvals), [0])
self.assertListEqual(drawing_obj.bits, [self.qubit])
self.assertEqual(drawing_obj.text, str(self.qubit.register.name))
ref_latex = r"{{\rm {register}}}_{{{index}}}".format(
register=self.qubit.register.prefix, index=self.qubit.index
)
self.assertEqual(drawing_obj.latex, ref_latex)
ref_styles = {
"zorder": self.formatter["layer.bit_name"],
"color": self.formatter["color.bit_name"],
"size": self.formatter["text_size.bit_name"],
"va": "center",
"ha": "right",
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
class TestBarrier(QiskitTestCase):
"""Tests for generator.barriers."""
def setUp(self) -> None:
"""Setup."""
super().setUp()
self.qubits = list(qiskit.QuantumRegister(3))
self.barrier = types.Barrier(t0=100, bits=self.qubits, bit_position=1)
style = stylesheet.QiskitTimelineStyle()
self.formatter = style.formatter
def test_gen_barrier(self):
"""Test gen_barrier generator."""
drawing_obj = generators.gen_barrier(self.barrier, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LineType.BARRIER.value))
self.assertListEqual(list(drawing_obj.xvals), [100, 100])
self.assertListEqual(list(drawing_obj.yvals), [-0.5, 0.5])
self.assertListEqual(drawing_obj.bits, [self.qubits[1]])
ref_styles = {
"alpha": self.formatter["alpha.barrier"],
"zorder": self.formatter["layer.barrier"],
"linewidth": self.formatter["line_width.barrier"],
"linestyle": self.formatter["line_style.barrier"],
"color": self.formatter["color.barrier"],
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
class TestGateLink(QiskitTestCase):
"""Tests for generator.gate_links."""
def setUp(self) -> None:
"""Setup."""
super().setUp()
self.qubits = list(qiskit.QuantumRegister(2))
self.gate_link = types.GateLink(t0=100, opname="cx", bits=self.qubits)
style = stylesheet.QiskitTimelineStyle()
self.formatter = style.formatter
def gen_bit_link(self):
"""Test gen_bit_link generator."""
drawing_obj = generators.gen_gate_link(self.gate_link, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LineType.GATE_LINK.value))
self.assertListEqual(list(drawing_obj.xvals), [100])
self.assertListEqual(list(drawing_obj.yvals), [0])
self.assertListEqual(drawing_obj.bits, self.qubits)
ref_styles = {
"alpha": self.formatter["alpha.bit_link"],
"zorder": self.formatter["layer.bit_link"],
"linewidth": self.formatter["line_width.bit_link"],
"linestyle": self.formatter["line_style.bit_link"],
"color": self.formatter["color.gates"]["cx"],
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for layouts of timeline drawer."""
import qiskit
from qiskit.test import QiskitTestCase
from qiskit.visualization.timeline import layouts
class TestBitArrange(QiskitTestCase):
"""Tests for layout.bit_arrange."""
def setUp(self) -> None:
"""Setup."""
super().setUp()
qregs = qiskit.QuantumRegister(3)
cregs = qiskit.ClassicalRegister(3)
self.regs = list(qregs) + list(cregs)
def test_qreg_creg_ascending(self):
"""Test qreg_creg_ascending layout function."""
sorted_regs = layouts.qreg_creg_ascending(self.regs)
ref_regs = [
self.regs[0],
self.regs[1],
self.regs[2],
self.regs[3],
self.regs[4],
self.regs[5],
]
self.assertListEqual(sorted_regs, ref_regs)
def test_qreg_creg_descending(self):
"""Test qreg_creg_descending layout function."""
sorted_regs = layouts.qreg_creg_descending(self.regs)
ref_regs = [
self.regs[2],
self.regs[1],
self.regs[0],
self.regs[5],
self.regs[4],
self.regs[3],
]
self.assertListEqual(sorted_regs, ref_regs)
class TestAxisMap(QiskitTestCase):
"""Tests for layout.time_axis_map."""
def test_time_map_in_dt(self):
"""Test time_map_in_dt layout function."""
axis_config = layouts.time_map_in_dt(time_window=(-100, 500))
self.assertEqual(axis_config.window, (-100, 500))
self.assertEqual(axis_config.label, "System cycle time (dt)")
ref_map = {0: "0", 100: "100", 200: "200", 300: "300", 400: "400", 500: "500"}
self.assertDictEqual(axis_config.axis_map, ref_map)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for core modules of timeline drawer."""
from qiskit import QuantumCircuit, transpile
from qiskit.test import QiskitTestCase
from qiskit.visualization.timeline import core, stylesheet, generators, layouts
class TestCanvas(QiskitTestCase):
"""Test for canvas."""
def setUp(self):
super().setUp()
self.style = stylesheet.QiskitTimelineStyle()
circ = QuantumCircuit(4)
circ.h(0)
circ.barrier()
circ.cx(0, 2)
circ.cx(1, 3)
self.circ = transpile(
circ,
scheduling_method="alap",
basis_gates=["h", "cx"],
instruction_durations=[("h", 0, 200), ("cx", [0, 2], 1000), ("cx", [1, 3], 1000)],
optimization_level=0,
)
def test_time_range(self):
"""Test calculating time range."""
canvas = core.DrawerCanvas(stylesheet=self.style)
canvas.formatter = {"margin.left_percent": 0.1, "margin.right_percent": 0.1}
canvas.time_range = (0, 100)
ref_range = [-10.0, 110.0]
self.assertListEqual(list(canvas.time_range), ref_range)
def test_load_program(self):
"""Test loading program."""
canvas = core.DrawerCanvas(stylesheet=self.style)
canvas.generator = {
"gates": [generators.gen_sched_gate],
"bits": [],
"barriers": [],
"gate_links": [],
}
canvas.layout = {
"bit_arrange": layouts.qreg_creg_ascending,
"time_axis_map": layouts.time_map_in_dt,
}
canvas.load_program(self.circ)
canvas.update()
drawings_tested = list(canvas.collections)
self.assertEqual(len(drawings_tested), 8)
ref_coord = {
self.circ.qregs[0][0]: -1.0,
self.circ.qregs[0][1]: -2.0,
self.circ.qregs[0][2]: -3.0,
self.circ.qregs[0][3]: -4.0,
}
self.assertDictEqual(canvas.assigned_coordinates, ref_coord)
def test_gate_link_overlap(self):
"""Test shifting gate link overlap."""
canvas = core.DrawerCanvas(stylesheet=self.style)
canvas.formatter.update(
{
"margin.link_interval_percent": 0.01,
"margin.left_percent": 0,
"margin.right_percent": 0,
}
)
canvas.generator = {
"gates": [],
"bits": [],
"barriers": [],
"gate_links": [generators.gen_gate_link],
}
canvas.layout = {
"bit_arrange": layouts.qreg_creg_ascending,
"time_axis_map": layouts.time_map_in_dt,
}
canvas.load_program(self.circ)
canvas.update()
drawings_tested = list(canvas.collections)
self.assertEqual(len(drawings_tested), 2)
self.assertListEqual(drawings_tested[0][1].xvals, [706.0])
self.assertListEqual(drawings_tested[1][1].xvals, [694.0])
ref_keys = list(canvas._collections.keys())
self.assertEqual(drawings_tested[0][0], ref_keys[0])
self.assertEqual(drawings_tested[1][0], ref_keys[1])
def test_object_outside_xlimit(self):
"""Test eliminating drawings outside the horizontal limit."""
canvas = core.DrawerCanvas(stylesheet=self.style)
canvas.generator = {
"gates": [generators.gen_sched_gate],
"bits": [generators.gen_bit_name, generators.gen_timeslot],
"barriers": [],
"gate_links": [],
}
canvas.layout = {
"bit_arrange": layouts.qreg_creg_ascending,
"time_axis_map": layouts.time_map_in_dt,
}
canvas.load_program(self.circ)
canvas.set_time_range(t_start=400, t_end=600)
canvas.update()
drawings_tested = list(canvas.collections)
self.assertEqual(len(drawings_tested), 12)
def test_non_transpiled_delay_circuit(self):
"""Test non-transpiled circuit containing instruction which is trivial on duration."""
circ = QuantumCircuit(1)
circ.delay(10, 0)
canvas = core.DrawerCanvas(stylesheet=self.style)
canvas.generator = {
"gates": [generators.gen_sched_gate],
"bits": [],
"barriers": [],
"gate_links": [],
}
with self.assertWarns(DeprecationWarning):
canvas.load_program(circ)
self.assertEqual(len(canvas._collections), 1)
def test_multi_measurement_with_clbit_not_shown(self):
"""Test generating bit link drawings of measurements when clbits is disabled."""
circ = QuantumCircuit(2, 2)
circ.measure(0, 0)
circ.measure(1, 1)
circ = transpile(
circ,
scheduling_method="alap",
basis_gates=[],
instruction_durations=[("measure", 0, 2000), ("measure", 1, 2000)],
optimization_level=0,
)
canvas = core.DrawerCanvas(stylesheet=self.style)
canvas.formatter.update({"control.show_clbits": False})
canvas.layout = {
"bit_arrange": layouts.qreg_creg_ascending,
"time_axis_map": layouts.time_map_in_dt,
}
canvas.generator = {
"gates": [],
"bits": [],
"barriers": [],
"gate_links": [generators.gen_gate_link],
}
canvas.load_program(circ)
canvas.update()
self.assertEqual(len(canvas._output_dataset), 0)
def test_multi_measurement_with_clbit_shown(self):
"""Test generating bit link drawings of measurements when clbits is enabled."""
circ = QuantumCircuit(2, 2)
circ.measure(0, 0)
circ.measure(1, 1)
circ = transpile(
circ,
scheduling_method="alap",
basis_gates=[],
instruction_durations=[("measure", 0, 2000), ("measure", 1, 2000)],
optimization_level=0,
)
canvas = core.DrawerCanvas(stylesheet=self.style)
canvas.formatter.update({"control.show_clbits": True})
canvas.layout = {
"bit_arrange": layouts.qreg_creg_ascending,
"time_axis_map": layouts.time_map_in_dt,
}
canvas.generator = {
"gates": [],
"bits": [],
"barriers": [],
"gate_links": [generators.gen_gate_link],
}
canvas.load_program(circ)
canvas.update()
self.assertEqual(len(canvas._output_dataset), 2)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for drawing of timeline drawer."""
import numpy as np
import qiskit
from qiskit.test import QiskitTestCase
from qiskit.visualization.timeline import drawings, types
class TestDrawingObjects(QiskitTestCase):
"""Tests for drawings."""
def setUp(self) -> None:
"""Setup."""
super().setUp()
# bits
self.qubits = list(qiskit.QuantumRegister(2))
# metadata
self.meta1 = {"val1": 0, "val2": 1}
self.meta2 = {"val1": 2, "val2": 3}
# style data
self.style1 = {"property1": 0, "property2": 1}
self.style2 = {"property1": 2, "property2": 3}
def test_line_data_equivalent(self):
"""Test LineData equivalent check."""
xs = list(np.arange(10))
ys = list(np.ones(10))
obj1 = drawings.LineData(
data_type=types.LineType.BARRIER,
bit=self.qubits[0],
xvals=xs,
yvals=ys,
meta=self.meta1,
styles=self.style1,
)
obj2 = drawings.LineData(
data_type=types.LineType.BARRIER,
bit=self.qubits[0],
xvals=xs,
yvals=ys,
meta=self.meta2,
styles=self.style2,
)
self.assertEqual(obj1, obj2)
def test_line_data_equivalent_abstract_coord(self):
"""Test LineData equivalent check with abstract coordinate."""
xs = [types.AbstractCoordinate.LEFT, types.AbstractCoordinate.RIGHT]
ys = [types.AbstractCoordinate.BOTTOM, types.AbstractCoordinate.TOP]
obj1 = drawings.LineData(
data_type=types.LineType.BARRIER,
bit=self.qubits[0],
xvals=xs,
yvals=ys,
meta=self.meta1,
styles=self.style1,
)
obj2 = drawings.LineData(
data_type=types.LineType.BARRIER,
bit=self.qubits[0],
xvals=xs,
yvals=ys,
meta=self.meta2,
styles=self.style2,
)
self.assertEqual(obj1, obj2)
def test_box_data_equivalent(self):
"""Test BoxData equivalent check."""
xs = [0, 1]
ys = [0, 1]
obj1 = drawings.BoxData(
data_type=types.BoxType.SCHED_GATE,
bit=self.qubits[0],
xvals=xs,
yvals=ys,
meta=self.meta1,
styles=self.style1,
)
obj2 = drawings.BoxData(
data_type=types.BoxType.SCHED_GATE,
bit=self.qubits[0],
xvals=xs,
yvals=ys,
meta=self.meta2,
styles=self.style2,
)
self.assertEqual(obj1, obj2)
def test_box_data_equivalent_abstract_coord(self):
"""Test BoxData equivalent check with abstract coordinate."""
xs = [types.AbstractCoordinate.LEFT, types.AbstractCoordinate.RIGHT]
ys = [types.AbstractCoordinate.BOTTOM, types.AbstractCoordinate.TOP]
obj1 = drawings.BoxData(
data_type=types.BoxType.SCHED_GATE,
bit=self.qubits[0],
xvals=xs,
yvals=ys,
meta=self.meta1,
styles=self.style1,
)
obj2 = drawings.BoxData(
data_type=types.BoxType.SCHED_GATE,
bit=self.qubits[0],
xvals=xs,
yvals=ys,
meta=self.meta2,
styles=self.style2,
)
self.assertEqual(obj1, obj2)
def test_text_data_equivalent(self):
"""Test TextData equivalent check."""
obj1 = drawings.TextData(
data_type=types.LabelType.GATE_NAME,
bit=self.qubits[0],
xval=0,
yval=0,
text="test",
latex="test",
meta=self.meta1,
styles=self.style1,
)
obj2 = drawings.TextData(
data_type=types.LabelType.GATE_NAME,
bit=self.qubits[0],
xval=0,
yval=0,
text="test",
latex="test",
meta=self.meta2,
styles=self.style2,
)
self.assertEqual(obj1, obj2)
def test_text_data_equivalent_abstract_coord(self):
"""Test TextData equivalent check with abstract coordinate."""
obj1 = drawings.TextData(
data_type=types.LabelType.GATE_NAME,
bit=self.qubits[0],
xval=types.AbstractCoordinate.LEFT,
yval=types.AbstractCoordinate.BOTTOM,
text="test",
latex="test",
meta=self.meta1,
styles=self.style1,
)
obj2 = drawings.TextData(
data_type=types.LabelType.GATE_NAME,
bit=self.qubits[0],
xval=types.AbstractCoordinate.LEFT,
yval=types.AbstractCoordinate.BOTTOM,
text="test",
latex="test",
meta=self.meta2,
styles=self.style2,
)
self.assertEqual(obj1, obj2)
def test_bit_link_data_equivalent(self):
"""Test BitLinkData equivalent check."""
obj1 = drawings.GateLinkData(
bits=[self.qubits[0], self.qubits[1]], xval=0, styles=self.style1
)
obj2 = drawings.GateLinkData(
bits=[self.qubits[0], self.qubits[1]], xval=0, styles=self.style2
)
self.assertEqual(obj1, obj2)
def test_bit_link_data_equivalent_abstract_coord(self):
"""Test BitLinkData equivalent check with abstract coordinate."""
obj1 = drawings.GateLinkData(
bits=[self.qubits[0], self.qubits[1]],
xval=types.AbstractCoordinate.LEFT,
styles=self.style1,
)
obj2 = drawings.GateLinkData(
bits=[self.qubits[0], self.qubits[1]],
xval=types.AbstractCoordinate.LEFT,
styles=self.style2,
)
self.assertEqual(obj1, obj2)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=invalid-name
"""Tests for generator of timeline drawer."""
import qiskit
from qiskit.test import QiskitTestCase
from qiskit.visualization.timeline import generators, types, stylesheet
from qiskit.circuit import library, Delay
class TestGates(QiskitTestCase):
"""Tests for generator.gates."""
def setUp(self) -> None:
"""Setup."""
super().setUp()
self.qubit = list(qiskit.QuantumRegister(1))[0]
self.u1 = types.ScheduledGate(
t0=100, operand=library.U1Gate(0), duration=0, bits=[self.qubit], bit_position=0
)
self.u3 = types.ScheduledGate(
t0=100, operand=library.U3Gate(0, 0, 0), duration=20, bits=[self.qubit], bit_position=0
)
self.delay = types.ScheduledGate(
t0=100, operand=Delay(20), duration=20, bits=[self.qubit], bit_position=0
)
style = stylesheet.QiskitTimelineStyle()
self.formatter = style.formatter
def test_gen_sched_gate_with_finite_duration(self):
"""Test test_gen_sched_gate generator with finite duration gate."""
drawing_obj = generators.gen_sched_gate(self.u3, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.BoxType.SCHED_GATE.value))
self.assertListEqual(list(drawing_obj.xvals), [100, 120])
self.assertListEqual(
list(drawing_obj.yvals),
[-0.5 * self.formatter["box_height.gate"], 0.5 * self.formatter["box_height.gate"]],
)
self.assertListEqual(drawing_obj.bits, [self.qubit])
ref_meta = {
"name": "u3",
"label": "n/a",
"bits": str(self.qubit.register.name),
"t0": 100,
"duration": 20,
"unitary": "[[1.+0.j 0.-0.j]\n [0.+0.j 1.+0.j]]",
"parameters": "0, 0, 0",
}
self.assertDictEqual(ref_meta, drawing_obj.meta)
ref_styles = {
"zorder": self.formatter["layer.gate"],
"facecolor": self.formatter["color.gates"]["u3"],
"alpha": self.formatter["alpha.gate"],
"linewidth": self.formatter["line_width.gate"],
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
def test_gen_sched_gate_with_zero_duration(self):
"""Test test_gen_sched_gate generator with zero duration gate."""
drawing_obj = generators.gen_sched_gate(self.u1, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.SymbolType.FRAME.value))
self.assertListEqual(list(drawing_obj.xvals), [100])
self.assertListEqual(list(drawing_obj.yvals), [0])
self.assertListEqual(drawing_obj.bits, [self.qubit])
self.assertEqual(drawing_obj.text, self.formatter["unicode_symbol.frame_change"])
self.assertEqual(drawing_obj.latex, self.formatter["latex_symbol.frame_change"])
ref_styles = {
"zorder": self.formatter["layer.frame_change"],
"color": self.formatter["color.gates"]["u1"],
"size": self.formatter["text_size.frame_change"],
"va": "center",
"ha": "center",
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
def test_gen_sched_gate_with_delay(self):
"""Test test_gen_sched_gate generator with delay."""
drawing_obj = generators.gen_sched_gate(self.delay, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.BoxType.DELAY.value))
def test_gen_full_gate_name_with_finite_duration(self):
"""Test gen_full_gate_name generator with finite duration gate."""
drawing_obj = generators.gen_full_gate_name(self.u3, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value))
self.assertListEqual(list(drawing_obj.xvals), [110.0])
self.assertListEqual(list(drawing_obj.yvals), [0.0])
self.assertListEqual(drawing_obj.bits, [self.qubit])
self.assertEqual(drawing_obj.text, "u3(0.00, 0.00, 0.00)[20]")
ref_latex = "{name}(0.00, 0.00, 0.00)[20]".format(
name=self.formatter["latex_symbol.gates"]["u3"]
)
self.assertEqual(drawing_obj.latex, ref_latex)
ref_styles = {
"zorder": self.formatter["layer.gate_name"],
"color": self.formatter["color.gate_name"],
"size": self.formatter["text_size.gate_name"],
"va": "center",
"ha": "center",
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
def test_gen_full_gate_name_with_zero_duration(self):
"""Test gen_full_gate_name generator with zero duration gate."""
drawing_obj = generators.gen_full_gate_name(self.u1, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value))
self.assertListEqual(list(drawing_obj.xvals), [100.0])
self.assertListEqual(list(drawing_obj.yvals), [self.formatter["label_offset.frame_change"]])
self.assertListEqual(drawing_obj.bits, [self.qubit])
self.assertEqual(drawing_obj.text, "u1(0.00)")
ref_latex = "{name}(0.00)".format(name=self.formatter["latex_symbol.gates"]["u1"])
self.assertEqual(drawing_obj.latex, ref_latex)
ref_styles = {
"zorder": self.formatter["layer.gate_name"],
"color": self.formatter["color.gate_name"],
"size": self.formatter["text_size.gate_name"],
"va": "bottom",
"ha": "center",
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
def test_gen_full_gate_name_with_delay(self):
"""Test gen_full_gate_name generator with delay."""
drawing_obj = generators.gen_full_gate_name(self.delay, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LabelType.DELAY.value))
def test_gen_short_gate_name_with_finite_duration(self):
"""Test gen_short_gate_name generator with finite duration gate."""
drawing_obj = generators.gen_short_gate_name(self.u3, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value))
self.assertListEqual(list(drawing_obj.xvals), [110.0])
self.assertListEqual(list(drawing_obj.yvals), [0.0])
self.assertListEqual(drawing_obj.bits, [self.qubit])
self.assertEqual(drawing_obj.text, "u3")
ref_latex = "{name}".format(name=self.formatter["latex_symbol.gates"]["u3"])
self.assertEqual(drawing_obj.latex, ref_latex)
ref_styles = {
"zorder": self.formatter["layer.gate_name"],
"color": self.formatter["color.gate_name"],
"size": self.formatter["text_size.gate_name"],
"va": "center",
"ha": "center",
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
def test_gen_short_gate_name_with_zero_duration(self):
"""Test gen_short_gate_name generator with zero duration gate."""
drawing_obj = generators.gen_short_gate_name(self.u1, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value))
self.assertListEqual(list(drawing_obj.xvals), [100.0])
self.assertListEqual(list(drawing_obj.yvals), [self.formatter["label_offset.frame_change"]])
self.assertListEqual(drawing_obj.bits, [self.qubit])
self.assertEqual(drawing_obj.text, "u1")
ref_latex = "{name}".format(name=self.formatter["latex_symbol.gates"]["u1"])
self.assertEqual(drawing_obj.latex, ref_latex)
ref_styles = {
"zorder": self.formatter["layer.gate_name"],
"color": self.formatter["color.gate_name"],
"size": self.formatter["text_size.gate_name"],
"va": "bottom",
"ha": "center",
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
def test_gen_short_gate_name_with_delay(self):
"""Test gen_short_gate_name generator with delay."""
drawing_obj = generators.gen_short_gate_name(self.delay, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LabelType.DELAY.value))
class TestTimeslot(QiskitTestCase):
"""Tests for generator.bits."""
def setUp(self) -> None:
"""Setup."""
super().setUp()
self.qubit = list(qiskit.QuantumRegister(1))[0]
style = stylesheet.QiskitTimelineStyle()
self.formatter = style.formatter
def test_gen_timeslot(self):
"""Test gen_timeslot generator."""
drawing_obj = generators.gen_timeslot(self.qubit, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.BoxType.TIMELINE.value))
self.assertListEqual(
list(drawing_obj.xvals), [types.AbstractCoordinate.LEFT, types.AbstractCoordinate.RIGHT]
)
self.assertListEqual(
list(drawing_obj.yvals),
[
-0.5 * self.formatter["box_height.timeslot"],
0.5 * self.formatter["box_height.timeslot"],
],
)
self.assertListEqual(drawing_obj.bits, [self.qubit])
ref_styles = {
"zorder": self.formatter["layer.timeslot"],
"alpha": self.formatter["alpha.timeslot"],
"linewidth": self.formatter["line_width.timeslot"],
"facecolor": self.formatter["color.timeslot"],
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
def test_gen_bit_name(self):
"""Test gen_bit_name generator."""
drawing_obj = generators.gen_bit_name(self.qubit, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LabelType.BIT_NAME.value))
self.assertListEqual(list(drawing_obj.xvals), [types.AbstractCoordinate.LEFT])
self.assertListEqual(list(drawing_obj.yvals), [0])
self.assertListEqual(drawing_obj.bits, [self.qubit])
self.assertEqual(drawing_obj.text, str(self.qubit.register.name))
ref_latex = r"{{\rm {register}}}_{{{index}}}".format(
register=self.qubit.register.prefix, index=self.qubit.index
)
self.assertEqual(drawing_obj.latex, ref_latex)
ref_styles = {
"zorder": self.formatter["layer.bit_name"],
"color": self.formatter["color.bit_name"],
"size": self.formatter["text_size.bit_name"],
"va": "center",
"ha": "right",
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
class TestBarrier(QiskitTestCase):
"""Tests for generator.barriers."""
def setUp(self) -> None:
"""Setup."""
super().setUp()
self.qubits = list(qiskit.QuantumRegister(3))
self.barrier = types.Barrier(t0=100, bits=self.qubits, bit_position=1)
style = stylesheet.QiskitTimelineStyle()
self.formatter = style.formatter
def test_gen_barrier(self):
"""Test gen_barrier generator."""
drawing_obj = generators.gen_barrier(self.barrier, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LineType.BARRIER.value))
self.assertListEqual(list(drawing_obj.xvals), [100, 100])
self.assertListEqual(list(drawing_obj.yvals), [-0.5, 0.5])
self.assertListEqual(drawing_obj.bits, [self.qubits[1]])
ref_styles = {
"alpha": self.formatter["alpha.barrier"],
"zorder": self.formatter["layer.barrier"],
"linewidth": self.formatter["line_width.barrier"],
"linestyle": self.formatter["line_style.barrier"],
"color": self.formatter["color.barrier"],
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
class TestGateLink(QiskitTestCase):
"""Tests for generator.gate_links."""
def setUp(self) -> None:
"""Setup."""
super().setUp()
self.qubits = list(qiskit.QuantumRegister(2))
self.gate_link = types.GateLink(t0=100, opname="cx", bits=self.qubits)
style = stylesheet.QiskitTimelineStyle()
self.formatter = style.formatter
def gen_bit_link(self):
"""Test gen_bit_link generator."""
drawing_obj = generators.gen_gate_link(self.gate_link, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LineType.GATE_LINK.value))
self.assertListEqual(list(drawing_obj.xvals), [100])
self.assertListEqual(list(drawing_obj.yvals), [0])
self.assertListEqual(drawing_obj.bits, self.qubits)
ref_styles = {
"alpha": self.formatter["alpha.bit_link"],
"zorder": self.formatter["layer.bit_link"],
"linewidth": self.formatter["line_width.bit_link"],
"linestyle": self.formatter["line_style.bit_link"],
"color": self.formatter["color.gates"]["cx"],
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for layouts of timeline drawer."""
import qiskit
from qiskit.test import QiskitTestCase
from qiskit.visualization.timeline import layouts
class TestBitArrange(QiskitTestCase):
"""Tests for layout.bit_arrange."""
def setUp(self) -> None:
"""Setup."""
super().setUp()
qregs = qiskit.QuantumRegister(3)
cregs = qiskit.ClassicalRegister(3)
self.regs = list(qregs) + list(cregs)
def test_qreg_creg_ascending(self):
"""Test qreg_creg_ascending layout function."""
sorted_regs = layouts.qreg_creg_ascending(self.regs)
ref_regs = [
self.regs[0],
self.regs[1],
self.regs[2],
self.regs[3],
self.regs[4],
self.regs[5],
]
self.assertListEqual(sorted_regs, ref_regs)
def test_qreg_creg_descending(self):
"""Test qreg_creg_descending layout function."""
sorted_regs = layouts.qreg_creg_descending(self.regs)
ref_regs = [
self.regs[2],
self.regs[1],
self.regs[0],
self.regs[5],
self.regs[4],
self.regs[3],
]
self.assertListEqual(sorted_regs, ref_regs)
class TestAxisMap(QiskitTestCase):
"""Tests for layout.time_axis_map."""
def test_time_map_in_dt(self):
"""Test time_map_in_dt layout function."""
axis_config = layouts.time_map_in_dt(time_window=(-100, 500))
self.assertEqual(axis_config.window, (-100, 500))
self.assertEqual(axis_config.label, "System cycle time (dt)")
ref_map = {0: "0", 100: "100", 200: "200", 300: "300", 400: "400", 500: "500"}
self.assertDictEqual(axis_config.axis_map, ref_map)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
#!/usr/bin/env python3
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test cases to verify qpy backwards compatibility."""
import argparse
import itertools
import random
import re
import sys
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.circuit.classicalregister import Clbit
from qiskit.circuit.quantumregister import Qubit
from qiskit.circuit.parameter import Parameter
from qiskit.circuit.parametervector import ParameterVector
from qiskit.quantum_info.random import random_unitary
from qiskit.circuit.library import U1Gate, U2Gate, U3Gate, QFT, DCXGate, PauliGate
from qiskit.circuit.gate import Gate
try:
from qiskit.qpy import dump, load
except ModuleNotFoundError:
from qiskit.circuit.qpy_serialization import dump, load
# This version pattern is taken from the pypa packaging project:
# https://github.com/pypa/packaging/blob/21.3/packaging/version.py#L223-L254
# which is dual licensed Apache 2.0 and BSD see the source for the original
# authors and other details
VERSION_PATTERN = (
"^"
+ r"""
v?
(?:
(?:(?P<epoch>[0-9]+)!)? # epoch
(?P<release>[0-9]+(?:\.[0-9]+)*) # release segment
(?P<pre> # pre-release
[-_\.]?
(?P<pre_l>(a|b|c|rc|alpha|beta|pre|preview))
[-_\.]?
(?P<pre_n>[0-9]+)?
)?
(?P<post> # post release
(?:-(?P<post_n1>[0-9]+))
|
(?:
[-_\.]?
(?P<post_l>post|rev|r)
[-_\.]?
(?P<post_n2>[0-9]+)?
)
)?
(?P<dev> # dev release
[-_\.]?
(?P<dev_l>dev)
[-_\.]?
(?P<dev_n>[0-9]+)?
)?
)
(?:\+(?P<local>[a-z0-9]+(?:[-_\.][a-z0-9]+)*))? # local version
"""
+ "$"
)
def generate_full_circuit():
"""Generate a multiregister circuit with name, metadata, phase."""
qr_a = QuantumRegister(4, "a")
qr_b = QuantumRegister(4, "b")
cr_c = ClassicalRegister(4, "c")
cr_d = ClassicalRegister(4, "d")
full_circuit = QuantumCircuit(
qr_a,
qr_b,
cr_c,
cr_d,
name="MyCircuit",
metadata={"test": 1, "a": 2},
global_phase=3.14159,
)
full_circuit.h(qr_a)
full_circuit.cx(qr_a, qr_b)
full_circuit.barrier(qr_a)
full_circuit.barrier(qr_b)
full_circuit.measure(qr_a, cr_c)
full_circuit.measure(qr_b, cr_d)
return full_circuit
def generate_unitary_gate_circuit():
"""Generate a circuit with a unitary gate."""
unitary_circuit = QuantumCircuit(5, name="unitary_circuit")
unitary_circuit.unitary(random_unitary(32, seed=100), [0, 1, 2, 3, 4])
unitary_circuit.measure_all()
return unitary_circuit
def generate_random_circuits():
"""Generate multiple random circuits."""
random_circuits = []
for i in range(1, 15):
qc = QuantumCircuit(i, name=f"random_circuit-{i}")
qc.h(0)
if i > 1:
for j in range(i - 1):
qc.cx(0, j + 1)
qc.measure_all()
for j in range(i):
qc.reset(j)
qc.x(0).c_if(qc.cregs[0], i)
for j in range(i):
qc.measure(j, j)
random_circuits.append(qc)
return random_circuits
def generate_string_parameters():
"""Generate a circuit for the XYZ pauli string."""
op_circuit = QuantumCircuit(3, name="X^Y^Z")
op_circuit.append(PauliGate("XYZ"), op_circuit.qubits, [])
return op_circuit
def generate_register_edge_cases():
"""Generate register edge case circuits."""
register_edge_cases = []
# Circuit with shared bits in a register
qubits = [Qubit() for _ in range(5)]
shared_qc = QuantumCircuit(name="shared_bits")
shared_qc.add_bits(qubits)
shared_qr = QuantumRegister(bits=qubits)
shared_qc.add_register(shared_qr)
shared_qc.h(shared_qr)
shared_qc.cx(0, 1)
shared_qc.cx(0, 2)
shared_qc.cx(0, 3)
shared_qc.cx(0, 4)
shared_qc.measure_all()
register_edge_cases.append(shared_qc)
# Circuit with registers that have a mix of standalone and shared register
# bits
qr = QuantumRegister(5, "foo")
qr = QuantumRegister(name="bar", bits=qr[:3] + [Qubit(), Qubit()])
cr = ClassicalRegister(5, "foo")
cr = ClassicalRegister(name="classical_bar", bits=cr[:3] + [Clbit(), Clbit()])
hybrid_qc = QuantumCircuit(qr, cr, name="mix_standalone_bits_registers")
hybrid_qc.h(0)
hybrid_qc.cx(0, 1)
hybrid_qc.cx(0, 2)
hybrid_qc.cx(0, 3)
hybrid_qc.cx(0, 4)
hybrid_qc.measure(qr, cr)
register_edge_cases.append(hybrid_qc)
# Circuit with mixed standalone and shared registers
qubits = [Qubit() for _ in range(5)]
clbits = [Clbit() for _ in range(5)]
mixed_qc = QuantumCircuit(name="mix_standalone_bits_with_registers")
mixed_qc.add_bits(qubits)
mixed_qc.add_bits(clbits)
qr = QuantumRegister(bits=qubits)
cr = ClassicalRegister(bits=clbits)
mixed_qc.add_register(qr)
mixed_qc.add_register(cr)
qr_standalone = QuantumRegister(2, "standalone")
mixed_qc.add_register(qr_standalone)
cr_standalone = ClassicalRegister(2, "classical_standalone")
mixed_qc.add_register(cr_standalone)
mixed_qc.unitary(random_unitary(32, seed=42), qr)
mixed_qc.unitary(random_unitary(4, seed=100), qr_standalone)
mixed_qc.measure(qr, cr)
mixed_qc.measure(qr_standalone, cr_standalone)
register_edge_cases.append(mixed_qc)
# Circuit with out of order register bits
qr_standalone = QuantumRegister(2, "standalone")
qubits = [Qubit() for _ in range(5)]
clbits = [Clbit() for _ in range(5)]
ooo_qc = QuantumCircuit(name="out_of_order_bits")
ooo_qc.add_bits(qubits)
ooo_qc.add_bits(clbits)
random.seed(42)
random.shuffle(qubits)
random.shuffle(clbits)
qr = QuantumRegister(bits=qubits)
cr = ClassicalRegister(bits=clbits)
ooo_qc.add_register(qr)
ooo_qc.add_register(cr)
qr_standalone = QuantumRegister(2, "standalone")
cr_standalone = ClassicalRegister(2, "classical_standalone")
ooo_qc.add_bits([qr_standalone[1], qr_standalone[0]])
ooo_qc.add_bits([cr_standalone[1], cr_standalone[0]])
ooo_qc.add_register(qr_standalone)
ooo_qc.add_register(cr_standalone)
ooo_qc.unitary(random_unitary(32, seed=42), qr)
ooo_qc.unitary(random_unitary(4, seed=100), qr_standalone)
ooo_qc.measure(qr, cr)
ooo_qc.measure(qr_standalone, cr_standalone)
register_edge_cases.append(ooo_qc)
return register_edge_cases
def generate_parameterized_circuit():
"""Generate a circuit with parameters and parameter expressions."""
param_circuit = QuantumCircuit(1, name="parameterized")
theta = Parameter("theta")
lam = Parameter("λ")
theta_pi = 3.14159 * theta
pe = theta_pi / lam
param_circuit.append(U3Gate(theta, theta_pi, lam), [0])
param_circuit.append(U1Gate(pe), [0])
param_circuit.append(U2Gate(theta_pi, lam), [0])
return param_circuit
def generate_qft_circuit():
"""Generate a QFT circuit with initialization."""
k = 5
state = (1 / np.sqrt(8)) * np.array(
[
np.exp(-1j * 2 * np.pi * k * (0) / 8),
np.exp(-1j * 2 * np.pi * k * (1) / 8),
np.exp(-1j * 2 * np.pi * k * (2) / 8),
np.exp(-1j * 2 * np.pi * k * 3 / 8),
np.exp(-1j * 2 * np.pi * k * 4 / 8),
np.exp(-1j * 2 * np.pi * k * 5 / 8),
np.exp(-1j * 2 * np.pi * k * 6 / 8),
np.exp(-1j * 2 * np.pi * k * 7 / 8),
]
)
qubits = 3
qft_circ = QuantumCircuit(qubits, qubits, name="QFT")
qft_circ.initialize(state)
qft_circ.append(QFT(qubits), range(qubits))
qft_circ.measure(range(qubits), range(qubits))
return qft_circ
def generate_param_phase():
"""Generate circuits with parameterize global phase."""
output_circuits = []
# Generate circuit with ParameterExpression global phase
theta = Parameter("theta")
phi = Parameter("phi")
sum_param = theta + phi
qc = QuantumCircuit(5, 1, global_phase=sum_param, name="parameter_phase")
qc.h(0)
for i in range(4):
qc.cx(i, i + 1)
qc.barrier()
qc.rz(sum_param, range(3))
qc.rz(phi, 3)
qc.rz(theta, 4)
qc.barrier()
for i in reversed(range(4)):
qc.cx(i, i + 1)
qc.h(0)
qc.measure(0, 0)
output_circuits.append(qc)
# Generate circuit with Parameter global phase
theta = Parameter("theta")
bell_qc = QuantumCircuit(2, global_phase=theta, name="bell_param_global_phase")
bell_qc.h(0)
bell_qc.cx(0, 1)
bell_qc.measure_all()
output_circuits.append(bell_qc)
return output_circuits
def generate_single_clbit_condition_teleportation(): # pylint: disable=invalid-name
"""Generate single clbit condition teleportation circuit."""
qr = QuantumRegister(1)
cr = ClassicalRegister(2, name="name")
teleport_qc = QuantumCircuit(qr, cr, name="Reset Test")
teleport_qc.x(0)
teleport_qc.measure(0, cr[0])
teleport_qc.x(0).c_if(cr[0], 1)
teleport_qc.measure(0, cr[1])
return teleport_qc
def generate_parameter_vector():
"""Generate tests for parameter vector element ordering."""
qc = QuantumCircuit(11, name="parameter_vector")
input_params = ParameterVector("x_par", 11)
user_params = ParameterVector("θ_par", 11)
for i, param in enumerate(user_params):
qc.ry(param, i)
for i, param in enumerate(input_params):
qc.rz(param, i)
return qc
def generate_parameter_vector_expression(): # pylint: disable=invalid-name
"""Generate tests for parameter vector element ordering."""
qc = QuantumCircuit(7, name="vector_expansion")
entanglement = [[i, i + 1] for i in range(7 - 1)]
input_params = ParameterVector("x_par", 14)
user_params = ParameterVector("\u03B8_par", 1)
for i in range(qc.num_qubits):
qc.ry(user_params[0], qc.qubits[i])
for source, target in entanglement:
qc.cz(qc.qubits[source], qc.qubits[target])
for i in range(qc.num_qubits):
qc.rz(-2 * input_params[2 * i + 1], qc.qubits[i])
qc.rx(-2 * input_params[2 * i], qc.qubits[i])
return qc
def generate_evolution_gate():
"""Generate a circuit with a pauli evolution gate."""
# Runtime import since this only exists in terra 0.19.0
from qiskit.circuit.library import PauliEvolutionGate
from qiskit.synthesis import SuzukiTrotter
from qiskit.quantum_info import SparsePauliOp
synthesis = SuzukiTrotter()
op = SparsePauliOp.from_list([("ZI", 1), ("IZ", 1)])
evo = PauliEvolutionGate([op] * 5, time=2.0, synthesis=synthesis)
qc = QuantumCircuit(2, name="pauli_evolution_circuit")
qc.append(evo, range(2))
return qc
def generate_control_flow_circuits():
"""Test qpy serialization with control flow instructions."""
from qiskit.circuit.controlflow import WhileLoopOp, IfElseOp, ForLoopOp
# If instruction
circuits = []
qc = QuantumCircuit(2, 2, name="control_flow")
qc.h(0)
qc.measure(0, 0)
true_body = QuantumCircuit(1)
true_body.x(0)
if_op = IfElseOp((qc.clbits[0], True), true_body=true_body)
qc.append(if_op, [1])
qc.measure(1, 1)
circuits.append(qc)
# If else instruction
qc = QuantumCircuit(2, 2, name="if_else")
qc.h(0)
qc.measure(0, 0)
false_body = QuantumCircuit(1)
false_body.y(0)
if_else_op = IfElseOp((qc.clbits[0], True), true_body, false_body)
qc.append(if_else_op, [1])
qc.measure(1, 1)
circuits.append(qc)
# While loop
qc = QuantumCircuit(2, 1, name="while_loop")
block = QuantumCircuit(2, 1)
block.h(0)
block.cx(0, 1)
block.measure(0, 0)
while_loop = WhileLoopOp((qc.clbits[0], 0), block)
qc.append(while_loop, [0, 1], [0])
circuits.append(qc)
# for loop range
qc = QuantumCircuit(2, 1, name="for_loop")
body = QuantumCircuit(2, 1)
body.h(0)
body.cx(0, 1)
body.measure(0, 0)
body.break_loop().c_if(0, True)
for_loop_op = ForLoopOp(range(5), None, body=body)
qc.append(for_loop_op, [0, 1], [0])
circuits.append(qc)
# For loop iterator
qc = QuantumCircuit(2, 1, name="for_loop_iterator")
for_loop_op = ForLoopOp(iter(range(5)), None, body=body)
qc.append(for_loop_op, [0, 1], [0])
circuits.append(qc)
return circuits
def generate_control_flow_switch_circuits():
"""Generate circuits with switch-statement instructions."""
from qiskit.circuit.controlflow import CASE_DEFAULT
circuits = []
qc = QuantumCircuit(2, 1, name="switch_clbit")
case_t = qc.copy_empty_like()
case_t.x(0)
case_f = qc.copy_empty_like()
case_f.z(1)
qc.switch(qc.clbits[0], [(True, case_t), (False, case_f)], qc.qubits, qc.clbits)
circuits.append(qc)
qreg = QuantumRegister(2, "q")
creg = ClassicalRegister(3, "c")
qc = QuantumCircuit(qreg, creg, name="switch_creg")
case_0 = QuantumCircuit(qreg, creg)
case_0.x(0)
case_1 = QuantumCircuit(qreg, creg)
case_1.z(1)
case_2 = QuantumCircuit(qreg, creg)
case_2.x(1)
qc.switch(
creg, [(0, case_0), ((1, 2), case_1), ((3, 4, CASE_DEFAULT), case_2)], qc.qubits, qc.clbits
)
circuits.append(qc)
return circuits
def generate_schedule_blocks():
"""Standard QPY testcase for schedule blocks."""
from qiskit.pulse import builder, channels, library
from qiskit.utils import optionals
# Parameterized schedule test is avoided.
# Generated reference and loaded QPY object may induce parameter uuid mismatch.
# As workaround, we need test with bounded parameters, however, schedule.parameters
# are returned as Set and thus its order is random.
# Since schedule parameters are validated, we cannot assign random numbers.
# We need to upgrade testing framework.
schedule_blocks = []
# Instructions without parameters
with builder.build() as block:
with builder.align_sequential():
builder.set_frequency(5e9, channels.DriveChannel(0))
builder.shift_frequency(10e6, channels.DriveChannel(1))
builder.set_phase(1.57, channels.DriveChannel(0))
builder.shift_phase(0.1, channels.DriveChannel(1))
builder.barrier(channels.DriveChannel(0), channels.DriveChannel(1))
builder.play(library.Gaussian(160, 0.1j, 40), channels.DriveChannel(0))
builder.play(library.GaussianSquare(800, 0.1, 64, 544), channels.ControlChannel(0))
builder.play(library.Drag(160, 0.1, 40, 1.5), channels.DriveChannel(1))
builder.play(library.Constant(800, 0.1), channels.MeasureChannel(0))
builder.acquire(1000, channels.AcquireChannel(0), channels.MemorySlot(0))
schedule_blocks.append(block)
# Raw symbolic pulse
if optionals.HAS_SYMENGINE:
import symengine as sym
else:
import sympy as sym
duration, amp, t = sym.symbols("duration amp t") # pylint: disable=invalid-name
expr = amp * sym.sin(2 * sym.pi * t / duration)
my_pulse = library.SymbolicPulse(
pulse_type="Sinusoidal",
duration=100,
parameters={"amp": 0.1},
envelope=expr,
valid_amp_conditions=sym.Abs(amp) <= 1.0,
)
with builder.build() as block:
builder.play(my_pulse, channels.DriveChannel(0))
schedule_blocks.append(block)
# Raw waveform
my_waveform = 0.1 * np.sin(2 * np.pi * np.linspace(0, 1, 100))
with builder.build() as block:
builder.play(my_waveform, channels.DriveChannel(0))
schedule_blocks.append(block)
return schedule_blocks
def generate_referenced_schedule():
"""Test for QPY serialization of unassigned reference schedules."""
from qiskit.pulse import builder, channels, library
schedule_blocks = []
# Completely unassigned schedule
with builder.build() as block:
builder.reference("cr45p", "q0", "q1")
builder.reference("x", "q0")
builder.reference("cr45m", "q0", "q1")
schedule_blocks.append(block)
# Partly assigned schedule
with builder.build() as x_q0:
builder.play(library.Constant(100, 0.1), channels.DriveChannel(0))
with builder.build() as block:
builder.reference("cr45p", "q0", "q1")
builder.call(x_q0)
builder.reference("cr45m", "q0", "q1")
schedule_blocks.append(block)
return schedule_blocks
def generate_calibrated_circuits():
"""Test for QPY serialization with calibrations."""
from qiskit.pulse import builder, Constant, DriveChannel
circuits = []
# custom gate
mygate = Gate("mygate", 1, [])
qc = QuantumCircuit(1, name="calibrated_circuit_1")
qc.append(mygate, [0])
with builder.build() as caldef:
builder.play(Constant(100, 0.1), DriveChannel(0))
qc.add_calibration(mygate, (0,), caldef)
circuits.append(qc)
# override instruction
qc = QuantumCircuit(1, name="calibrated_circuit_2")
qc.x(0)
with builder.build() as caldef:
builder.play(Constant(100, 0.1), DriveChannel(0))
qc.add_calibration("x", (0,), caldef)
circuits.append(qc)
return circuits
def generate_controlled_gates():
"""Test QPY serialization with custom ControlledGates."""
circuits = []
qc = QuantumCircuit(3, name="custom_controlled_gates")
controlled_gate = DCXGate().control(1)
qc.append(controlled_gate, [0, 1, 2])
circuits.append(qc)
custom_gate = Gate("black_box", 1, [])
custom_definition = QuantumCircuit(1)
custom_definition.h(0)
custom_definition.rz(1.5, 0)
custom_definition.sdg(0)
custom_gate.definition = custom_definition
nested_qc = QuantumCircuit(3, name="nested_qc")
qc.append(custom_gate, [0])
controlled_gate = custom_gate.control(2)
nested_qc.append(controlled_gate, [0, 1, 2])
nested_qc.measure_all()
circuits.append(nested_qc)
qc_open = QuantumCircuit(2, name="open_cx")
qc_open.cx(0, 1, ctrl_state=0)
circuits.append(qc_open)
return circuits
def generate_open_controlled_gates():
"""Test QPY serialization with custom ControlledGates with open controls."""
circuits = []
qc = QuantumCircuit(3, name="open_controls_simple")
controlled_gate = DCXGate().control(1, ctrl_state=0)
qc.append(controlled_gate, [0, 1, 2])
circuits.append(qc)
custom_gate = Gate("black_box", 1, [])
custom_definition = QuantumCircuit(1)
custom_definition.h(0)
custom_definition.rz(1.5, 0)
custom_definition.sdg(0)
custom_gate.definition = custom_definition
nested_qc = QuantumCircuit(3, name="open_controls_nested")
nested_qc.append(custom_gate, [0])
controlled_gate = custom_gate.control(2, ctrl_state=1)
nested_qc.append(controlled_gate, [0, 1, 2])
nested_qc.measure_all()
circuits.append(nested_qc)
return circuits
def generate_acquire_instruction_with_kernel_and_discriminator():
"""Test QPY serialization with Acquire instruction with kernel and discriminator."""
from qiskit.pulse import builder, AcquireChannel, MemorySlot, Discriminator, Kernel
schedule_blocks = []
with builder.build() as block:
builder.acquire(
100,
AcquireChannel(0),
MemorySlot(0),
kernel=Kernel(
name="my_kernel", my_params_1={"param1": 0.1, "param2": 0.2}, my_params_2=[0, 1]
),
)
schedule_blocks.append(block)
with builder.build() as block:
builder.acquire(
100,
AcquireChannel(0),
MemorySlot(0),
discriminator=Discriminator(
name="my_disc", my_params_1={"param1": 0.1, "param2": 0.2}, my_params_2=[0, 1]
),
)
schedule_blocks.append(block)
return schedule_blocks
def generate_layout_circuits():
"""Test qpy circuits with layout set."""
from qiskit.transpiler.layout import TranspileLayout, Layout
qr = QuantumRegister(3, "foo")
qc = QuantumCircuit(qr, name="GHZ with layout")
qc.h(0)
qc.cx(0, 1)
qc.swap(0, 1)
qc.cx(0, 2)
input_layout = {qr[index]: index for index in range(len(qc.qubits))}
qc._layout = TranspileLayout(
Layout(input_layout),
input_qubit_mapping=input_layout,
final_layout=Layout.from_qubit_list([qc.qubits[1], qc.qubits[0], qc.qubits[2]]),
)
return [qc]
def generate_control_flow_expr():
"""`IfElseOp`, `WhileLoopOp` and `SwitchCaseOp` with `Expr` nodes in their discriminators."""
from qiskit.circuit.classical import expr, types
body1 = QuantumCircuit(1)
body1.x(0)
qr1 = QuantumRegister(2, "q1")
cr1 = ClassicalRegister(2, "c1")
qc1 = QuantumCircuit(qr1, cr1)
qc1.if_test(expr.equal(cr1, 3), body1.copy(), [0], [])
qc1.while_loop(expr.logic_not(cr1[1]), body1.copy(), [0], [])
inner2 = QuantumCircuit(1)
inner2.x(0)
outer2 = QuantumCircuit(1, 1)
outer2.if_test(expr.logic_not(outer2.clbits[0]), inner2, [0], [])
qr2 = QuantumRegister(2, "q2")
cr1_2 = ClassicalRegister(3, "c1")
cr2_2 = ClassicalRegister(3, "c2")
qc2 = QuantumCircuit(qr2, cr1_2, cr2_2)
qc2.if_test(expr.logic_or(expr.less(cr1_2, cr2_2), cr1_2[1]), outer2, [1], [1])
inner3 = QuantumCircuit(1)
inner3.x(0)
outer3 = QuantumCircuit(1, 1)
outer3.switch(expr.logic_not(outer2.clbits[0]), [(False, inner2)], [0], [])
qr3 = QuantumRegister(2, "q2")
cr1_3 = ClassicalRegister(3, "c1")
cr2_3 = ClassicalRegister(3, "c2")
qc3 = QuantumCircuit(qr3, cr1_3, cr2_3)
qc3.switch(expr.bit_xor(cr1_3, cr2_3), [(0, outer2)], [1], [1])
cr1_4 = ClassicalRegister(256, "c1")
cr2_4 = ClassicalRegister(4, "c2")
cr3_4 = ClassicalRegister(4, "c3")
inner4 = QuantumCircuit(1)
inner4.x(0)
outer_loose = Clbit()
outer4 = QuantumCircuit(QuantumRegister(2, "q_outer"), cr2_4, [outer_loose], cr1_4)
outer4.if_test(
expr.logic_and(
expr.logic_or(
expr.greater(expr.bit_or(cr2_4, 7), 10),
expr.equal(expr.bit_and(cr1_4, cr1_4), expr.bit_not(cr1_4)),
),
expr.logic_or(
outer_loose,
expr.cast(cr1_4, types.Bool()),
),
),
inner4,
[0],
[],
)
qc4_loose = Clbit()
qc4 = QuantumCircuit(QuantumRegister(2, "qr4"), cr1_4, cr2_4, cr3_4, [qc4_loose])
qc4.rz(np.pi, 0)
qc4.switch(
expr.logic_and(
expr.logic_or(
expr.logic_or(
expr.less(cr2_4, cr3_4),
expr.logic_not(expr.greater_equal(cr3_4, cr2_4)),
),
expr.logic_or(
expr.logic_not(expr.less_equal(cr3_4, cr2_4)),
expr.greater(cr2_4, cr3_4),
),
),
expr.logic_and(
expr.equal(cr3_4, 2),
expr.not_equal(expr.bit_xor(cr1_4, 0x0F), 0x0F),
),
),
[(False, outer4)],
[1, 0],
list(cr2_4) + [qc4_loose] + list(cr1_4),
)
qc4.rz(np.pi, 0)
return [qc1, qc2, qc3, qc4]
def generate_circuits(version_parts):
"""Generate reference circuits."""
output_circuits = {
"full.qpy": [generate_full_circuit()],
"unitary.qpy": [generate_unitary_gate_circuit()],
"multiple.qpy": generate_random_circuits(),
"string_parameters.qpy": [generate_string_parameters()],
"register_edge_cases.qpy": generate_register_edge_cases(),
"parameterized.qpy": [generate_parameterized_circuit()],
}
if version_parts is None:
return output_circuits
if version_parts >= (0, 18, 1):
output_circuits["qft_circuit.qpy"] = [generate_qft_circuit()]
output_circuits["teleport.qpy"] = [generate_single_clbit_condition_teleportation()]
if version_parts >= (0, 19, 0):
output_circuits["param_phase.qpy"] = generate_param_phase()
if version_parts >= (0, 19, 1):
output_circuits["parameter_vector.qpy"] = [generate_parameter_vector()]
output_circuits["pauli_evo.qpy"] = [generate_evolution_gate()]
output_circuits["parameter_vector_expression.qpy"] = [
generate_parameter_vector_expression()
]
if version_parts >= (0, 19, 2):
output_circuits["control_flow.qpy"] = generate_control_flow_circuits()
if version_parts >= (0, 21, 0):
output_circuits["schedule_blocks.qpy"] = generate_schedule_blocks()
output_circuits["pulse_gates.qpy"] = generate_calibrated_circuits()
if version_parts >= (0, 24, 0):
output_circuits["referenced_schedule_blocks.qpy"] = generate_referenced_schedule()
output_circuits["control_flow_switch.qpy"] = generate_control_flow_switch_circuits()
if version_parts >= (0, 24, 1):
output_circuits["open_controlled_gates.qpy"] = generate_open_controlled_gates()
output_circuits["controlled_gates.qpy"] = generate_controlled_gates()
if version_parts >= (0, 24, 2):
output_circuits["layout.qpy"] = generate_layout_circuits()
if version_parts >= (0, 25, 0):
output_circuits[
"acquire_inst_with_kernel_and_disc.qpy"
] = generate_acquire_instruction_with_kernel_and_discriminator()
output_circuits["control_flow_expr.qpy"] = generate_control_flow_expr()
return output_circuits
def assert_equal(reference, qpy, count, version_parts, bind=None):
"""Compare two circuits."""
if bind is not None:
reference_parameter_names = [x.name for x in reference.parameters]
qpy_parameter_names = [x.name for x in qpy.parameters]
if reference_parameter_names != qpy_parameter_names:
msg = (
f"Circuit {count} parameter mismatch:"
f" {reference_parameter_names} != {qpy_parameter_names}"
)
sys.stderr.write(msg)
sys.exit(4)
reference = reference.bind_parameters(bind)
qpy = qpy.bind_parameters(bind)
if reference != qpy:
msg = (
f"Reference Circuit {count}:\n{reference}\nis not equivalent to "
f"qpy loaded circuit {count}:\n{qpy}\n"
)
sys.stderr.write(msg)
sys.exit(1)
# Check deprecated bit properties, if set. The QPY dumping code before Terra 0.23.2 didn't
# include enough information for us to fully reconstruct this, so we only test if newer.
if version_parts >= (0, 23, 2) and isinstance(reference, QuantumCircuit):
for ref_bit, qpy_bit in itertools.chain(
zip(reference.qubits, qpy.qubits), zip(reference.clbits, qpy.clbits)
):
if ref_bit._register is not None and ref_bit != qpy_bit:
msg = (
f"Reference Circuit {count}:\n"
"deprecated bit-level register information mismatch\n"
f"reference bit: {ref_bit}\n"
f"loaded bit: {qpy_bit}\n"
)
sys.stderr.write(msg)
sys.exit(1)
if (
version_parts >= (0, 24, 2)
and isinstance(reference, QuantumCircuit)
and reference.layout != qpy.layout
):
msg = f"Circuit {count} layout mismatch {reference.layout} != {qpy.layout}\n"
sys.stderr.write(msg)
sys.exit(4)
# Don't compare name on bound circuits
if bind is None and reference.name != qpy.name:
msg = f"Circuit {count} name mismatch {reference.name} != {qpy.name}\n{reference}\n{qpy}"
sys.stderr.write(msg)
sys.exit(2)
if reference.metadata != qpy.metadata:
msg = f"Circuit {count} metadata mismatch: {reference.metadata} != {qpy.metadata}"
sys.stderr.write(msg)
sys.exit(3)
def generate_qpy(qpy_files):
"""Generate qpy files from reference circuits."""
for path, circuits in qpy_files.items():
with open(path, "wb") as fd:
dump(circuits, fd)
def load_qpy(qpy_files, version_parts):
"""Load qpy circuits from files and compare to reference circuits."""
for path, circuits in qpy_files.items():
print(f"Loading qpy file: {path}")
with open(path, "rb") as fd:
qpy_circuits = load(fd)
for i, circuit in enumerate(circuits):
bind = None
if path == "parameterized.qpy":
bind = [1, 2]
elif path == "param_phase.qpy":
if i == 0:
bind = [1, 2]
else:
bind = [1]
elif path == "parameter_vector.qpy":
bind = np.linspace(1.0, 2.0, 22)
elif path == "parameter_vector_expression.qpy":
bind = np.linspace(1.0, 2.0, 15)
assert_equal(circuit, qpy_circuits[i], i, version_parts, bind=bind)
def _main():
parser = argparse.ArgumentParser(description="Test QPY backwards compatibilty")
parser.add_argument("command", choices=["generate", "load"])
parser.add_argument(
"--version",
"-v",
help=(
"Optionally specify the version being tested. "
"This will enable additional circuit features "
"to test generating and loading QPY."
),
)
args = parser.parse_args()
# Terra 0.18.0 was the first release with QPY, so that's the default.
version_parts = (0, 18, 0)
if args.version:
version_match = re.search(VERSION_PATTERN, args.version, re.VERBOSE | re.IGNORECASE)
version_parts = tuple(int(x) for x in version_match.group("release").split("."))
qpy_files = generate_circuits(version_parts)
if args.command == "generate":
generate_qpy(qpy_files)
else:
load_qpy(qpy_files, version_parts)
if __name__ == "__main__":
_main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Randomized tests of quantum synthesis."""
import unittest
from test.python.quantum_info.test_synthesis import CheckDecompositions
from hypothesis import given, strategies, settings
import numpy as np
from qiskit import execute
from qiskit.circuit import QuantumCircuit, QuantumRegister
from qiskit.extensions import UnitaryGate
from qiskit.providers.basicaer import UnitarySimulatorPy
from qiskit.quantum_info.random import random_unitary
from qiskit.quantum_info.synthesis.two_qubit_decompose import (
two_qubit_cnot_decompose,
TwoQubitBasisDecomposer,
Ud,
)
class TestSynthesis(CheckDecompositions):
"""Test synthesis"""
seed = strategies.integers(min_value=0, max_value=2**32 - 1)
rotation = strategies.floats(min_value=-np.pi * 10, max_value=np.pi * 10)
@given(seed)
def test_1q_random(self, seed):
"""Checks one qubit decompositions"""
unitary = random_unitary(2, seed=seed)
self.check_one_qubit_euler_angles(unitary)
self.check_one_qubit_euler_angles(unitary, "U3")
self.check_one_qubit_euler_angles(unitary, "U1X")
self.check_one_qubit_euler_angles(unitary, "PSX")
self.check_one_qubit_euler_angles(unitary, "ZSX")
self.check_one_qubit_euler_angles(unitary, "ZYZ")
self.check_one_qubit_euler_angles(unitary, "ZXZ")
self.check_one_qubit_euler_angles(unitary, "XYX")
self.check_one_qubit_euler_angles(unitary, "RR")
@settings(deadline=None)
@given(seed)
def test_2q_random(self, seed):
"""Checks two qubit decompositions"""
unitary = random_unitary(4, seed=seed)
self.check_exact_decomposition(unitary.data, two_qubit_cnot_decompose)
@given(strategies.tuples(*[seed] * 5))
def test_exact_supercontrolled_decompose_random(self, seeds):
"""Exact decomposition for random supercontrolled basis and random target"""
k1 = np.kron(random_unitary(2, seed=seeds[0]).data, random_unitary(2, seed=seeds[1]).data)
k2 = np.kron(random_unitary(2, seed=seeds[2]).data, random_unitary(2, seed=seeds[3]).data)
basis_unitary = k1 @ Ud(np.pi / 4, 0, 0) @ k2
decomposer = TwoQubitBasisDecomposer(UnitaryGate(basis_unitary))
self.check_exact_decomposition(random_unitary(4, seed=seeds[4]).data, decomposer)
@given(strategies.tuples(*[rotation] * 6), seed)
def test_cx_equivalence_0cx_random(self, rnd, seed):
"""Check random circuits with 0 cx gates locally equivalent to identity."""
qr = QuantumRegister(2, name="q")
qc = QuantumCircuit(qr)
qc.u(rnd[0], rnd[1], rnd[2], qr[0])
qc.u(rnd[3], rnd[4], rnd[5], qr[1])
sim = UnitarySimulatorPy()
unitary = execute(qc, sim, seed_simulator=seed).result().get_unitary()
self.assertEqual(two_qubit_cnot_decompose.num_basis_gates(unitary), 0)
@given(strategies.tuples(*[rotation] * 12), seed)
def test_cx_equivalence_1cx_random(self, rnd, seed):
"""Check random circuits with 1 cx gates locally equivalent to a cx."""
qr = QuantumRegister(2, name="q")
qc = QuantumCircuit(qr)
qc.u(rnd[0], rnd[1], rnd[2], qr[0])
qc.u(rnd[3], rnd[4], rnd[5], qr[1])
qc.cx(qr[1], qr[0])
qc.u(rnd[6], rnd[7], rnd[8], qr[0])
qc.u(rnd[9], rnd[10], rnd[11], qr[1])
sim = UnitarySimulatorPy()
unitary = execute(qc, sim, seed_simulator=seed).result().get_unitary()
self.assertEqual(two_qubit_cnot_decompose.num_basis_gates(unitary), 1)
@given(strategies.tuples(*[rotation] * 18), seed)
def test_cx_equivalence_2cx_random(self, rnd, seed):
"""Check random circuits with 2 cx gates locally equivalent to some circuit with 2 cx."""
qr = QuantumRegister(2, name="q")
qc = QuantumCircuit(qr)
qc.u(rnd[0], rnd[1], rnd[2], qr[0])
qc.u(rnd[3], rnd[4], rnd[5], qr[1])
qc.cx(qr[1], qr[0])
qc.u(rnd[6], rnd[7], rnd[8], qr[0])
qc.u(rnd[9], rnd[10], rnd[11], qr[1])
qc.cx(qr[0], qr[1])
qc.u(rnd[12], rnd[13], rnd[14], qr[0])
qc.u(rnd[15], rnd[16], rnd[17], qr[1])
sim = UnitarySimulatorPy()
unitary = execute(qc, sim, seed_simulator=seed).result().get_unitary()
self.assertEqual(two_qubit_cnot_decompose.num_basis_gates(unitary), 2)
@given(strategies.tuples(*[rotation] * 24), seed)
def test_cx_equivalence_3cx_random(self, rnd, seed):
"""Check random circuits with 3 cx gates are outside the 0, 1, and 2 qubit regions."""
qr = QuantumRegister(2, name="q")
qc = QuantumCircuit(qr)
qc.u(rnd[0], rnd[1], rnd[2], qr[0])
qc.u(rnd[3], rnd[4], rnd[5], qr[1])
qc.cx(qr[1], qr[0])
qc.u(rnd[6], rnd[7], rnd[8], qr[0])
qc.u(rnd[9], rnd[10], rnd[11], qr[1])
qc.cx(qr[0], qr[1])
qc.u(rnd[12], rnd[13], rnd[14], qr[0])
qc.u(rnd[15], rnd[16], rnd[17], qr[1])
qc.cx(qr[1], qr[0])
qc.u(rnd[18], rnd[19], rnd[20], qr[0])
qc.u(rnd[21], rnd[22], rnd[23], qr[1])
sim = UnitarySimulatorPy()
unitary = execute(qc, sim, seed_simulator=seed).result().get_unitary()
self.assertEqual(two_qubit_cnot_decompose.num_basis_gates(unitary), 3)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=invalid-name
"""Randomized tests of transpiler circuit equivalence.
This test can be optionally configured (e.g. by CI) via the
following env vars:
QISKIT_RANDOMIZED_TEST_LAYOUT_METHODS
A space-delimited list of layout method names from which the
randomizer should pick the layout method. Defaults to all
available built-in methods if unspecified.
QISKIT_RANDOMIZED_TEST_ROUTING_METHODS
A space-delimited list of routing method names from which the
randomizer should pick the routing method. Defaults to all
available built-in methods if unspecified.
QISKIT_RANDOMIZED_TEST_SCHEDULING_METHODS
A space-delimited list of scheduling method names from which the
randomizer should pick the scheduling method. Defaults to all
available built-in methods if unspecified.
QISKIT_RANDOMIZED_TEST_BACKEND_NEEDS_DURATIONS
A boolean value (e.g. "true", "Y", etc.) which, when true, forces
the randomizer to pick a backend which fully supports scheduling
(i.e. has fully specified duration info). Defaults to False.
QISKIT_RANDOMIZED_TEST_ALLOW_BARRIERS
A boolean value (e.g. "true", "Y", etc.) which, when false,
prevents the randomizer from emitting barrier instructions.
Defaults to True.
"""
import os
from math import pi
from hypothesis import assume, settings, HealthCheck
from hypothesis.stateful import multiple, rule, precondition, invariant
from hypothesis.stateful import Bundle, RuleBasedStateMachine
import hypothesis.strategies as st
from qiskit import transpile, Aer
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.circuit import Measure, Reset, Gate, Barrier
from qiskit.providers.fake_provider import (
FakeProvider,
FakeOpenPulse2Q,
FakeOpenPulse3Q,
FakeYorktown,
FakeTenerife,
FakeOurense,
FakeVigo,
FakeMelbourne,
FakeRueschlikon,
FakeTokyo,
FakePoughkeepsie,
FakeAlmaden,
FakeSingapore,
FakeJohannesburg,
FakeBoeblingen,
FakeRochester,
FakeBurlington,
FakeCambridge,
FakeCambridgeAlternativeBasis,
FakeEssex,
FakeLondon,
FakeQasmSimulator,
FakeArmonk,
FakeRome,
FakeSantiago,
FakeSydney,
FakeToronto,
FakeValencia,
)
from qiskit.test.base import dicts_almost_equal
# pylint: disable=wildcard-import,unused-wildcard-import
from qiskit.circuit.library.standard_gates import *
default_profile = "transpiler_equivalence"
settings.register_profile(
default_profile,
report_multiple_bugs=False,
max_examples=200,
deadline=None,
suppress_health_check=[HealthCheck.filter_too_much],
)
settings.load_profile(os.getenv("HYPOTHESIS_PROFILE", default_profile))
BASE_INSTRUCTIONS = {
# Key is (n_qubits, n_clbits, n_params). All gates here should be directly known by Aer so they
# can be simulated without an initial transpile (whether that's via `execute` or not).
(1, 0, 0): [HGate, IGate, SGate, SdgGate, TGate, TdgGate, XGate, YGate, ZGate, Reset],
(2, 0, 0): [CXGate, CYGate, CZGate, SwapGate],
(3, 0, 0): [CCXGate, CSwapGate],
(1, 0, 1): [PhaseGate, RXGate, RYGate, RZGate],
(1, 0, 3): [UGate],
(2, 0, 1): [RZZGate, CPhaseGate],
(2, 0, 4): [CUGate],
(1, 1, 0): [Measure],
}
variadic_gates = [Barrier]
def _strtobool(s):
return s.lower() in ("y", "yes", "t", "true", "on", "1")
if not _strtobool(os.getenv("QISKIT_RANDOMIZED_TEST_ALLOW_BARRIERS", "True")):
variadic_gates.remove(Barrier)
def _getenv_list(var_name):
value = os.getenv(var_name)
return None if value is None else value.split()
# Note: a value of `None` for any of the following methods means that
# the selected pass manager gets to choose. However, to avoid complexity,
# its not possible to specify `None` when overriding these with environment
# variables. Really, `None` is useful only for testing Terra's pass managers,
# and if you're overriding these, your goal is probably to test a specific
# pass or set of passes instead.
layout_methods = _getenv_list("QISKIT_RANDOMIZED_TEST_LAYOUT_METHODS") or [
None,
"trivial",
"dense",
"noise_adaptive",
"sabre",
]
routing_methods = _getenv_list("QISKIT_RANDOMIZED_TEST_ROUTING_METHODS") or [
None,
"basic",
"stochastic",
"lookahead",
"sabre",
]
scheduling_methods = _getenv_list("QISKIT_RANDOMIZED_TEST_SCHEDULING_METHODS") or [
None,
"alap",
"asap",
]
backend_needs_durations = _strtobool(
os.getenv("QISKIT_RANDOMIZED_TEST_BACKEND_NEEDS_DURATIONS", "False")
)
def _fully_supports_scheduling(backend):
"""Checks if backend is not in the set of backends known not to have specified gate durations."""
return not isinstance(
backend,
(
# no coupling map
FakeArmonk,
# no measure durations
FakeAlmaden,
FakeBurlington,
FakeCambridge,
FakeCambridgeAlternativeBasis,
FakeEssex,
FakeJohannesburg,
FakeLondon,
FakeOpenPulse2Q,
FakeOpenPulse3Q,
FakePoughkeepsie,
FakeQasmSimulator,
FakeRochester,
FakeRueschlikon,
FakeSingapore,
FakeTenerife,
FakeTokyo,
# No reset duration
FakeAlmaden,
FakeArmonk,
FakeBoeblingen,
FakeBurlington,
FakeCambridge,
FakeCambridgeAlternativeBasis,
FakeEssex,
FakeJohannesburg,
FakeLondon,
FakeMelbourne,
FakeOpenPulse2Q,
FakeOpenPulse3Q,
FakeOurense,
FakePoughkeepsie,
FakeQasmSimulator,
FakeRochester,
FakeRome,
FakeRueschlikon,
FakeSantiago,
FakeSingapore,
FakeSydney,
FakeTenerife,
FakeTokyo,
FakeToronto,
FakeValencia,
FakeVigo,
FakeYorktown,
),
)
fake_provider = FakeProvider()
mock_backends = fake_provider.backends()
mock_backends_with_scheduling = [b for b in mock_backends if _fully_supports_scheduling(b)]
@st.composite
def transpiler_conf(draw):
"""Composite search strategy to pick a valid transpiler config."""
all_backends = st.one_of(st.none(), st.sampled_from(mock_backends))
scheduling_backends = st.sampled_from(mock_backends_with_scheduling)
scheduling_method = draw(st.sampled_from(scheduling_methods))
backend = (
draw(scheduling_backends)
if scheduling_method or backend_needs_durations
else draw(all_backends)
)
return {
"backend": backend,
"optimization_level": draw(st.integers(min_value=0, max_value=3)),
"layout_method": draw(st.sampled_from(layout_methods)),
"routing_method": draw(st.sampled_from(routing_methods)),
"scheduling_method": scheduling_method,
"seed_transpiler": draw(st.integers(min_value=0, max_value=1_000_000)),
}
class QCircuitMachine(RuleBasedStateMachine):
"""Build a Hypothesis rule based state machine for constructing, transpiling
and simulating a series of random QuantumCircuits.
Build circuits with up to QISKIT_RANDOM_QUBITS qubits, apply a random
selection of gates from qiskit.circuit.library with randomly selected
qargs, cargs, and parameters. At random intervals, transpile the circuit for
a random backend with a random optimization level and simulate both the
initial and the transpiled circuits to verify that their counts are the
same.
"""
qubits = Bundle("qubits")
clbits = Bundle("clbits")
backend = Aer.get_backend("aer_simulator")
max_qubits = int(backend.configuration().n_qubits / 2)
# Limit reg generation for more interesting circuits
max_qregs = 3
max_cregs = 3
def __init__(self):
super().__init__()
self.qc = QuantumCircuit()
self.enable_variadic = bool(variadic_gates)
@precondition(lambda self: len(self.qc.qubits) < self.max_qubits)
@precondition(lambda self: len(self.qc.qregs) < self.max_qregs)
@rule(target=qubits, n=st.integers(min_value=1, max_value=max_qubits))
def add_qreg(self, n):
"""Adds a new variable sized qreg to the circuit, up to max_qubits."""
n = min(n, self.max_qubits - len(self.qc.qubits))
qreg = QuantumRegister(n)
self.qc.add_register(qreg)
return multiple(*list(qreg))
@precondition(lambda self: len(self.qc.cregs) < self.max_cregs)
@rule(target=clbits, n=st.integers(1, 5))
def add_creg(self, n):
"""Add a new variable sized creg to the circuit."""
creg = ClassicalRegister(n)
self.qc.add_register(creg)
return multiple(*list(creg))
# Gates of various shapes
@precondition(lambda self: self.qc.num_qubits > 0 and self.qc.num_clbits > 0)
@rule(n_arguments=st.sampled_from(sorted(BASE_INSTRUCTIONS.keys())), data=st.data())
def add_gate(self, n_arguments, data):
"""Append a random fixed gate to the circuit."""
n_qubits, n_clbits, n_params = n_arguments
gate_class = data.draw(st.sampled_from(BASE_INSTRUCTIONS[n_qubits, n_clbits, n_params]))
qubits = data.draw(st.lists(self.qubits, min_size=n_qubits, max_size=n_qubits, unique=True))
clbits = data.draw(st.lists(self.clbits, min_size=n_clbits, max_size=n_clbits, unique=True))
params = data.draw(
st.lists(
st.floats(
allow_nan=False, allow_infinity=False, min_value=-10 * pi, max_value=10 * pi
),
min_size=n_params,
max_size=n_params,
)
)
self.qc.append(gate_class(*params), qubits, clbits)
@precondition(lambda self: self.enable_variadic)
@rule(gate=st.sampled_from(variadic_gates), qargs=st.lists(qubits, min_size=1, unique=True))
def add_variQ_gate(self, gate, qargs):
"""Append a gate with a variable number of qargs."""
self.qc.append(gate(len(qargs)), qargs)
@precondition(lambda self: len(self.qc.data) > 0)
@rule(carg=clbits, data=st.data())
def add_c_if_last_gate(self, carg, data):
"""Modify the last gate to be conditional on a classical register."""
creg = self.qc.find_bit(carg).registers[0][0]
val = data.draw(st.integers(min_value=0, max_value=2 ** len(creg) - 1))
last_gate = self.qc.data[-1]
# Conditional instructions are not supported
assume(isinstance(last_gate[0], Gate))
last_gate[0].c_if(creg, val)
# Properties to check
@invariant()
def qasm(self):
"""After each circuit operation, it should be possible to build QASM."""
self.qc.qasm()
@precondition(lambda self: any(isinstance(d[0], Measure) for d in self.qc.data))
@rule(kwargs=transpiler_conf())
def equivalent_transpile(self, kwargs):
"""Simulate, transpile and simulate the present circuit. Verify that the
counts are not significantly different before and after transpilation.
"""
assume(
kwargs["backend"] is None
or kwargs["backend"].configuration().n_qubits >= len(self.qc.qubits)
)
call = (
"transpile(qc, "
+ ", ".join(f"{key:s}={value!r}" for key, value in kwargs.items() if value is not None)
+ ")"
)
print(f"Evaluating {call} for:\n{self.qc.qasm()}")
shots = 4096
# Note that there's no transpilation here, which is why the gates are limited to only ones
# that Aer supports natively.
aer_counts = self.backend.run(self.qc, shots=shots).result().get_counts()
try:
xpiled_qc = transpile(self.qc, **kwargs)
except Exception as e:
failed_qasm = f"Exception caught during transpilation of circuit: \n{self.qc.qasm()}"
raise RuntimeError(failed_qasm) from e
xpiled_aer_counts = self.backend.run(xpiled_qc, shots=shots).result().get_counts()
count_differences = dicts_almost_equal(aer_counts, xpiled_aer_counts, 0.05 * shots)
assert (
count_differences == ""
), "Counts not equivalent: {}\nFailing QASM Input:\n{}\n\nFailing QASM Output:\n{}".format(
count_differences, self.qc.qasm(), xpiled_qc.qasm()
)
TestQuantumCircuit = QCircuitMachine.TestCase
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# Testing Circuits
import warnings
warnings.simplefilter("ignore")
%run "mpl/circuit/test_circuit_matplotlib_drawer.py"
# Testing Graphs
%run "mpl/graph/test_graph_matplotlib_drawer.py"
%run -i "results.py"
RESULTS_CIRCUIT
RESULTS_GRAPH
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for circuit MPL drawer"""
import unittest
import os
import math
from test.visual import VisualTestUtilities
from pathlib import Path
import numpy as np
from numpy import pi
from qiskit.test import QiskitTestCase
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, transpile
from qiskit.providers.fake_provider import FakeTenerife
from qiskit.visualization.circuit.circuit_visualization import _matplotlib_circuit_drawer
from qiskit.circuit.library import (
XGate,
MCXGate,
HGate,
RZZGate,
SwapGate,
DCXGate,
ZGate,
SGate,
U1Gate,
CPhaseGate,
)
from qiskit.circuit.library import MCXVChain
from qiskit.extensions import HamiltonianGate
from qiskit.circuit import Parameter, Qubit, Clbit
from qiskit.circuit.library import IQP
from qiskit.quantum_info.random import random_unitary
from qiskit.utils import optionals
if optionals.HAS_MATPLOTLIB:
from matplotlib.pyplot import close as mpl_close
else:
raise ImportError('Must have Matplotlib installed. To install, run "pip install matplotlib".')
BASE_DIR = Path(__file__).parent
RESULT_DIR = Path(BASE_DIR) / "circuit_results"
TEST_REFERENCE_DIR = Path(BASE_DIR) / "references"
FAILURE_DIFF_DIR = Path(BASE_DIR).parent / "visual_test_failures"
FAILURE_PREFIX = "circuit_failure_"
class TestCircuitMatplotlibDrawer(QiskitTestCase):
"""Circuit MPL visualization"""
def setUp(self):
super().setUp()
self.circuit_drawer = VisualTestUtilities.save_data_wrap(
_matplotlib_circuit_drawer, str(self), RESULT_DIR
)
if not os.path.exists(FAILURE_DIFF_DIR):
os.makedirs(FAILURE_DIFF_DIR)
if not os.path.exists(RESULT_DIR):
os.makedirs(RESULT_DIR)
def tearDown(self):
super().tearDown()
mpl_close("all")
@staticmethod
def _image_path(image_name):
return os.path.join(RESULT_DIR, image_name)
@staticmethod
def _reference_path(image_name):
return os.path.join(TEST_REFERENCE_DIR, image_name)
def test_empty_circuit(self):
"""Test empty circuit"""
circuit = QuantumCircuit()
fname = "empty_circut.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_calibrations(self):
"""Test calibrations annotations
See https://github.com/Qiskit/qiskit-terra/issues/5920
"""
circuit = QuantumCircuit(2, 2)
circuit.h(0)
from qiskit import pulse
with pulse.build(name="hadamard") as h_q0:
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(0)
)
circuit.add_calibration("h", [0], h_q0)
fname = "calibrations.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_calibrations_with_control_gates(self):
"""Test calibrations annotations
See https://github.com/Qiskit/qiskit-terra/issues/5920
"""
circuit = QuantumCircuit(2, 2)
circuit.cx(0, 1)
circuit.ch(0, 1)
from qiskit import pulse
with pulse.build(name="cnot") as cx_q01:
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(1)
)
circuit.add_calibration("cx", [0, 1], cx_q01)
with pulse.build(name="ch") as ch_q01:
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(1)
)
circuit.add_calibration("ch", [0, 1], ch_q01)
fname = "calibrations_with_control_gates.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_calibrations_with_swap_and_reset(self):
"""Test calibrations annotations
See https://github.com/Qiskit/qiskit-terra/issues/5920
"""
circuit = QuantumCircuit(2, 2)
circuit.swap(0, 1)
circuit.reset(0)
from qiskit import pulse
with pulse.build(name="swap") as swap_q01:
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(1)
)
circuit.add_calibration("swap", [0, 1], swap_q01)
with pulse.build(name="reset") as reset_q0:
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(1)
)
circuit.add_calibration("reset", [0], reset_q0)
fname = "calibrations_with_swap_and_reset.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_calibrations_with_rzz_and_rxx(self):
"""Test calibrations annotations
See https://github.com/Qiskit/qiskit-terra/issues/5920
"""
circuit = QuantumCircuit(2, 2)
circuit.rzz(pi, 0, 1)
circuit.rxx(pi, 0, 1)
from qiskit import pulse
with pulse.build(name="rzz") as rzz_q01:
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(1)
)
circuit.add_calibration("rzz", [0, 1], rzz_q01)
with pulse.build(name="rxx") as rxx_q01:
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(1)
)
circuit.add_calibration("rxx", [0, 1], rxx_q01)
fname = "calibrations_with_rzz_and_rxx.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_no_ops(self):
"""Test circuit with no ops.
See https://github.com/Qiskit/qiskit-terra/issues/5393"""
circuit = QuantumCircuit(2, 3)
fname = "no_op_circut.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_long_name(self):
"""Test to see that long register names can be seen completely
As reported in #2605
"""
# add a register with a very long name
qr = QuantumRegister(4, "veryLongQuantumRegisterName")
# add another to make sure adjustments are made based on longest
qrr = QuantumRegister(1, "q0")
circuit = QuantumCircuit(qr, qrr)
# check gates are shifted over accordingly
circuit.h(qr)
circuit.h(qr)
circuit.h(qr)
fname = "long_name.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_multi_underscore_reg_names(self):
"""Test that multi-underscores in register names display properly"""
q_reg1 = QuantumRegister(1, "q1_re__g__g")
q_reg3 = QuantumRegister(3, "q3_re_g__g")
c_reg1 = ClassicalRegister(1, "c1_re_g__g")
c_reg3 = ClassicalRegister(3, "c3_re_g__g")
circuit = QuantumCircuit(q_reg1, q_reg3, c_reg1, c_reg3)
fname = "multi_underscore_true.png"
self.circuit_drawer(circuit, cregbundle=True, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
fname2 = "multi_underscore_false.png"
self.circuit_drawer(circuit, cregbundle=False, filename=fname2)
ratio2 = VisualTestUtilities._save_diff(
self._image_path(fname2),
self._reference_path(fname2),
fname2,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
self.assertGreaterEqual(ratio2, 0.9999)
def test_conditional(self):
"""Test that circuits with conditionals draw correctly"""
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
circuit = QuantumCircuit(qr, cr)
# check gates are shifted over accordingly
circuit.h(qr)
circuit.measure(qr, cr)
circuit.h(qr[0]).c_if(cr, 2)
fname = "reg_conditional.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_bit_conditional_with_cregbundle(self):
"""Test that circuits with single bit conditionals draw correctly
with cregbundle=True."""
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
circuit = QuantumCircuit(qr, cr)
circuit.x(qr[0])
circuit.measure(qr, cr)
circuit.h(qr[0]).c_if(cr[0], 1)
circuit.x(qr[1]).c_if(cr[1], 0)
fname = "bit_conditional_bundle.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_bit_conditional_no_cregbundle(self):
"""Test that circuits with single bit conditionals draw correctly
with cregbundle=False."""
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
circuit = QuantumCircuit(qr, cr)
circuit.x(qr[0])
circuit.measure(qr, cr)
circuit.h(qr[0]).c_if(cr[0], 1)
circuit.x(qr[1]).c_if(cr[1], 0)
fname = "bit_conditional_no_bundle.png"
self.circuit_drawer(circuit, filename=fname, cregbundle=False)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_plot_partial_barrier(self):
"""Test plotting of partial barriers."""
# generate a circuit with barrier and other barrier like instructions in
q = QuantumRegister(2, "q")
c = ClassicalRegister(2, "c")
circuit = QuantumCircuit(q, c)
# check for barriers
circuit.h(q[0])
circuit.barrier(0)
circuit.h(q[0])
fname = "plot_partial_barrier.png"
self.circuit_drawer(circuit, filename=fname, plot_barriers=True)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_plot_barriers(self):
"""Test to see that plotting barriers works.
If it is set to False, no blank columns are introduced"""
# generate a circuit with barriers and other barrier like instructions in
q = QuantumRegister(2, "q")
c = ClassicalRegister(2, "c")
circuit = QuantumCircuit(q, c)
# check for barriers
circuit.h(q[0])
circuit.barrier()
# check for other barrier like commands
circuit.h(q[1])
# this import appears to be unused, but is actually needed to get snapshot instruction
import qiskit.extensions.simulator # pylint: disable=unused-import
circuit.snapshot("1")
# check the barriers plot properly when plot_barriers= True
fname = "plot_barriers_true.png"
self.circuit_drawer(circuit, filename=fname, plot_barriers=True)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
fname2 = "plot_barriers_false.png"
self.circuit_drawer(circuit, filename=fname2, plot_barriers=False)
ratio2 = VisualTestUtilities._save_diff(
self._image_path(fname2),
self._reference_path(fname2),
fname2,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
self.assertGreaterEqual(ratio2, 0.9999)
def test_no_barriers_false(self):
"""Generate the same circuit as test_plot_barriers but without the barrier commands
as this is what the circuit should look like when displayed with plot barriers false"""
q1 = QuantumRegister(2, "q")
c1 = ClassicalRegister(2, "c")
circuit = QuantumCircuit(q1, c1)
circuit.h(q1[0])
circuit.h(q1[1])
fname = "no_barriers.png"
self.circuit_drawer(circuit, filename=fname, plot_barriers=False)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_fold_minus1(self):
"""Test to see that fold=-1 is no folding"""
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
circuit = QuantumCircuit(qr, cr)
for _ in range(3):
circuit.h(0)
circuit.x(0)
fname = "fold_minus1.png"
self.circuit_drawer(circuit, fold=-1, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_fold_4(self):
"""Test to see that fold=4 is folding"""
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
circuit = QuantumCircuit(qr, cr)
for _ in range(3):
circuit.h(0)
circuit.x(0)
fname = "fold_4.png"
self.circuit_drawer(circuit, fold=4, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_big_gates(self):
"""Test large gates with params"""
qr = QuantumRegister(6, "q")
circuit = QuantumCircuit(qr)
circuit.append(IQP([[6, 5, 3], [5, 4, 5], [3, 5, 1]]), [0, 1, 2])
desired_vector = [
1 / math.sqrt(16) * complex(0, 1),
1 / math.sqrt(8) * complex(1, 0),
1 / math.sqrt(16) * complex(1, 1),
0,
0,
1 / math.sqrt(8) * complex(1, 2),
1 / math.sqrt(16) * complex(1, 0),
0,
]
circuit.initialize(desired_vector, [qr[3], qr[4], qr[5]])
circuit.unitary([[1, 0], [0, 1]], [qr[0]])
matrix = np.zeros((4, 4))
theta = Parameter("theta")
circuit.append(HamiltonianGate(matrix, theta), [qr[1], qr[2]])
circuit = circuit.bind_parameters({theta: 1})
circuit.isometry(np.eye(4, 4), list(range(3, 5)), [])
fname = "big_gates.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_cnot(self):
"""Test different cnot gates (ccnot, mcx, etc)"""
qr = QuantumRegister(6, "q")
circuit = QuantumCircuit(qr)
circuit.x(0)
circuit.cx(0, 1)
circuit.ccx(0, 1, 2)
circuit.append(XGate().control(3, ctrl_state="010"), [qr[2], qr[3], qr[0], qr[1]])
circuit.append(MCXGate(num_ctrl_qubits=3, ctrl_state="101"), [qr[0], qr[1], qr[2], qr[4]])
circuit.append(MCXVChain(3, dirty_ancillas=True), [qr[0], qr[1], qr[2], qr[3], qr[5]])
fname = "cnot.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_cz(self):
"""Test Z and Controlled-Z Gates"""
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.z(0)
circuit.cz(0, 1)
circuit.append(ZGate().control(3, ctrl_state="101"), [0, 1, 2, 3])
circuit.append(ZGate().control(2), [1, 2, 3])
circuit.append(ZGate().control(1, ctrl_state="0", label="CZ Gate"), [2, 3])
fname = "cz.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_pauli_clifford(self):
"""Test Pauli(green) and Clifford(blue) gates"""
qr = QuantumRegister(5, "q")
circuit = QuantumCircuit(qr)
circuit.x(0)
circuit.y(0)
circuit.z(0)
circuit.id(0)
circuit.h(1)
circuit.cx(1, 2)
circuit.cy(1, 2)
circuit.cz(1, 2)
circuit.swap(3, 4)
circuit.s(3)
circuit.sdg(3)
circuit.iswap(3, 4)
circuit.dcx(3, 4)
fname = "pauli_clifford.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_creg_initial(self):
"""Test cregbundle and initial state options"""
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
circuit = QuantumCircuit(qr, cr)
circuit.x(0)
circuit.h(0)
circuit.x(1)
fname = "creg_initial_true.png"
self.circuit_drawer(circuit, filename=fname, cregbundle=True, initial_state=True)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
fname2 = "creg_initial_false.png"
self.circuit_drawer(circuit, filename=fname2, cregbundle=False, initial_state=False)
ratio2 = VisualTestUtilities._save_diff(
self._image_path(fname2),
self._reference_path(fname2),
fname2,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
self.assertGreaterEqual(ratio2, 0.9999)
def test_r_gates(self):
"""Test all R gates"""
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.r(3 * pi / 4, 3 * pi / 8, 0)
circuit.rx(pi / 2, 1)
circuit.ry(-pi / 2, 2)
circuit.rz(3 * pi / 4, 3)
circuit.rxx(pi / 2, 0, 1)
circuit.ryy(3 * pi / 4, 2, 3)
circuit.rzx(-pi / 2, 0, 1)
circuit.rzz(pi / 2, 2, 3)
fname = "r_gates.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_ctrl_labels(self):
"""Test control labels"""
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.cy(1, 0, label="Bottom Y label")
circuit.cu(pi / 2, pi / 2, pi / 2, 0, 2, 3, label="Top U label")
circuit.ch(0, 1, label="Top H label")
circuit.append(
HGate(label="H gate label").control(3, label="H control label", ctrl_state="010"),
[qr[1], qr[2], qr[3], qr[0]],
)
fname = "ctrl_labels.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_cswap_rzz(self):
"""Test controlled swap and rzz gates"""
qr = QuantumRegister(5, "q")
circuit = QuantumCircuit(qr)
circuit.cswap(0, 1, 2)
circuit.append(RZZGate(3 * pi / 4).control(3, ctrl_state="010"), [2, 1, 4, 3, 0])
fname = "cswap_rzz.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_ghz_to_gate(self):
"""Test controlled GHZ to_gate circuit"""
qr = QuantumRegister(5, "q")
circuit = QuantumCircuit(qr)
ghz_circuit = QuantumCircuit(3, name="this is a WWWWWWWWWWWide name Ctrl-GHZ Circuit")
ghz_circuit.h(0)
ghz_circuit.cx(0, 1)
ghz_circuit.cx(1, 2)
ghz = ghz_circuit.to_gate()
ccghz = ghz.control(2, ctrl_state="10")
circuit.append(ccghz, [4, 0, 1, 3, 2])
fname = "ghz_to_gate.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_scale(self):
"""Tests scale
See: https://github.com/Qiskit/qiskit-terra/issues/4179"""
circuit = QuantumCircuit(5)
circuit.unitary(random_unitary(2**5), circuit.qubits)
fname = "scale_default.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
fname2 = "scale_half.png"
self.circuit_drawer(circuit, filename=fname2, scale=0.5)
ratio2 = VisualTestUtilities._save_diff(
self._image_path(fname2),
self._reference_path(fname2),
fname2,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
fname3 = "scale_double.png"
self.circuit_drawer(circuit, filename=fname3, scale=2)
ratio3 = VisualTestUtilities._save_diff(
self._image_path(fname3),
self._reference_path(fname3),
fname3,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
self.assertGreaterEqual(ratio2, 0.9999)
self.assertGreaterEqual(ratio3, 0.9999)
def test_pi_param_expr(self):
"""Test pi in circuit with parameter expression."""
x, y = Parameter("x"), Parameter("y")
circuit = QuantumCircuit(1)
circuit.rx((pi - x) * (pi - y), 0)
fname = "pi_in_param_expr.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_partial_layout(self):
"""Tests partial_layout
See: https://github.com/Qiskit/qiskit-terra/issues/4757"""
circuit = QuantumCircuit(3)
circuit.h(1)
transpiled = transpile(
circuit,
backend=FakeTenerife(),
basis_gates=["id", "cx", "rz", "sx", "x"],
optimization_level=0,
initial_layout=[1, 2, 0],
seed_transpiler=0,
)
fname = "partial_layout.png"
self.circuit_drawer(transpiled, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_init_reset(self):
"""Test reset and initialize with 1 and 2 qubits"""
circuit = QuantumCircuit(2)
circuit.initialize([0, 1], 0)
circuit.reset(1)
circuit.initialize([0, 1, 0, 0], [0, 1])
fname = "init_reset.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_with_global_phase(self):
"""Tests with global phase"""
circuit = QuantumCircuit(3, global_phase=1.57079632679)
circuit.h(range(3))
fname = "global_phase.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_alternative_colors(self):
"""Tests alternative color schemes"""
ratios = []
for style in ["iqx", "iqx-dark", "textbook"]:
with self.subTest(style=style):
circuit = QuantumCircuit(7)
circuit.h(0)
circuit.x(0)
circuit.cx(0, 1)
circuit.ccx(0, 1, 2)
circuit.swap(0, 1)
circuit.cswap(0, 1, 2)
circuit.append(SwapGate().control(2), [0, 1, 2, 3])
circuit.dcx(0, 1)
circuit.append(DCXGate().control(1), [0, 1, 2])
circuit.append(DCXGate().control(2), [0, 1, 2, 3])
circuit.z(4)
circuit.s(4)
circuit.sdg(4)
circuit.t(4)
circuit.tdg(4)
circuit.p(pi / 2, 4)
circuit.cz(5, 6)
circuit.cp(pi / 2, 5, 6)
circuit.y(5)
circuit.rx(pi / 3, 5)
circuit.rzx(pi / 2, 5, 6)
circuit.u(pi / 2, pi / 2, pi / 2, 5)
circuit.barrier(5, 6)
circuit.reset(5)
fname = f"{style}_color.png"
self.circuit_drawer(circuit, style={"name": style}, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
ratios.append(ratio)
for ratio in ratios:
self.assertGreaterEqual(ratio, 0.9999)
def test_reverse_bits(self):
"""Tests reverse_bits parameter"""
circuit = QuantumCircuit(3)
circuit.h(0)
circuit.cx(0, 1)
circuit.ccx(2, 1, 0)
fname = "reverse_bits.png"
self.circuit_drawer(circuit, reverse_bits=True, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_bw(self):
"""Tests black and white style parameter"""
circuit = QuantumCircuit(3, 3)
circuit.h(0)
circuit.x(1)
circuit.sdg(2)
circuit.cx(0, 1)
circuit.ccx(2, 1, 0)
circuit.swap(1, 2)
circuit.measure_all()
fname = "bw.png"
self.circuit_drawer(circuit, style={"name": "bw"}, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_user_style(self):
"""Tests loading a user style"""
circuit = QuantumCircuit(7)
circuit.h(0)
circuit.append(HGate(label="H2"), [1])
circuit.x(0)
circuit.cx(0, 1)
circuit.ccx(0, 1, 2)
circuit.swap(0, 1)
circuit.cswap(0, 1, 2)
circuit.append(SwapGate().control(2), [0, 1, 2, 3])
circuit.dcx(0, 1)
circuit.append(DCXGate().control(1), [0, 1, 2])
circuit.append(DCXGate().control(2), [0, 1, 2, 3])
circuit.z(4)
circuit.append(SGate(label="S1"), [4])
circuit.sdg(4)
circuit.t(4)
circuit.tdg(4)
circuit.p(pi / 2, 4)
circuit.cz(5, 6)
circuit.cp(pi / 2, 5, 6)
circuit.y(5)
circuit.rx(pi / 3, 5)
circuit.rzx(pi / 2, 5, 6)
circuit.u(pi / 2, pi / 2, pi / 2, 5)
circuit.barrier(5, 6)
circuit.reset(5)
fname = "user_style.png"
self.circuit_drawer(
circuit,
style={
"name": "user_style",
"displaytext": {"H2": "H_2"},
"displaycolor": {"H2": ("#EEDD00", "#FF0000")},
},
filename=fname,
)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_subfont_change(self):
"""Tests changing the subfont size"""
circuit = QuantumCircuit(3)
circuit.h(0)
circuit.x(0)
circuit.u(pi / 2, pi / 2, pi / 2, 1)
circuit.p(pi / 2, 2)
style = {"name": "iqx", "subfontsize": 11}
fname = "subfont.png"
self.circuit_drawer(circuit, style=style, filename=fname)
self.assertEqual(style, {"name": "iqx", "subfontsize": 11}) # check does not change style
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_meas_condition(self):
"""Tests measure with a condition"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0])
circuit.measure(qr[0], cr[0])
circuit.h(qr[1]).c_if(cr, 1)
fname = "meas_condition.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_reverse_bits_condition(self):
"""Tests reverse_bits with a condition and gate above"""
cr = ClassicalRegister(2, "cr")
cr2 = ClassicalRegister(1, "cr2")
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr, cr, cr2)
circuit.h(0)
circuit.h(1)
circuit.h(2)
circuit.x(0)
circuit.x(0)
circuit.measure(2, 1)
circuit.x(2).c_if(cr, 2)
fname = "reverse_bits_cond_true.png"
self.circuit_drawer(circuit, cregbundle=False, reverse_bits=True, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
fname2 = "reverse_bits_cond_false.png"
self.circuit_drawer(circuit, cregbundle=False, reverse_bits=False, filename=fname2)
ratio2 = VisualTestUtilities._save_diff(
self._image_path(fname2),
self._reference_path(fname2),
fname2,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
self.assertGreaterEqual(ratio2, 0.9999)
def test_style_custom_gates(self):
"""Tests style for custom gates"""
def cnotnot(gate_label):
gate_circuit = QuantumCircuit(3, name=gate_label)
gate_circuit.cnot(0, 1)
gate_circuit.cnot(0, 2)
gate = gate_circuit.to_gate()
return gate
q = QuantumRegister(3, name="q")
circuit = QuantumCircuit(q)
circuit.append(cnotnot("CNOTNOT"), [q[0], q[1], q[2]])
circuit.append(cnotnot("CNOTNOT_PRIME"), [q[0], q[1], q[2]])
circuit.h(q[0])
fname = "style_custom_gates.png"
self.circuit_drawer(
circuit,
style={
"displaycolor": {"CNOTNOT": ("#000000", "#FFFFFF"), "h": ("#A1A1A1", "#043812")},
"displaytext": {"CNOTNOT_PRIME": "$\\mathrm{CNOTNOT}'$"},
},
filename=fname,
)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_6095(self):
"""Tests controlled-phase gate style
See https://github.com/Qiskit/qiskit-terra/issues/6095"""
circuit = QuantumCircuit(2)
circuit.cp(1.0, 0, 1)
circuit.h(1)
fname = "6095.png"
self.circuit_drawer(
circuit,
style={"displaycolor": {"cp": ("#A27486", "#000000"), "h": ("#A27486", "#000000")}},
filename=fname,
)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_instruction_1q_1c(self):
"""Tests q0-cr0 instruction on a circuit"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
inst = QuantumCircuit(1, 1, name="Inst").to_instruction()
circuit.append(inst, [qr[0]], [cr[0]])
fname = "instruction_1q_1c.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_instruction_3q_3c_circ1(self):
"""Tests q0-q1-q2-cr_20-cr0-cr1 instruction on a circuit"""
qr = QuantumRegister(4, "qr")
cr = ClassicalRegister(2, "cr")
cr2 = ClassicalRegister(2, "cr2")
circuit = QuantumCircuit(qr, cr, cr2)
inst = QuantumCircuit(3, 3, name="Inst").to_instruction()
circuit.append(inst, [qr[0], qr[1], qr[2]], [cr2[0], cr[0], cr[1]])
fname = "instruction_3q_3c_circ1.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_instruction_3q_3c_circ2(self):
"""Tests q3-q0-q2-cr0-cr1-cr_20 instruction on a circuit"""
qr = QuantumRegister(4, "qr")
cr = ClassicalRegister(2, "cr")
cr2 = ClassicalRegister(2, "cr2")
circuit = QuantumCircuit(qr, cr, cr2)
inst = QuantumCircuit(3, 3, name="Inst").to_instruction()
circuit.append(inst, [qr[3], qr[0], qr[2]], [cr[0], cr[1], cr2[0]])
fname = "instruction_3q_3c_circ2.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_instruction_3q_3c_circ3(self):
"""Tests q3-q1-q2-cr_31-cr1-cr_30 instruction on a circuit"""
qr = QuantumRegister(4, "qr")
cr = ClassicalRegister(2, "cr")
cr2 = ClassicalRegister(1, "cr2")
cr3 = ClassicalRegister(2, "cr3")
circuit = QuantumCircuit(qr, cr, cr2, cr3)
inst = QuantumCircuit(3, 3, name="Inst").to_instruction()
circuit.append(inst, [qr[3], qr[1], qr[2]], [cr3[1], cr[1], cr3[0]])
fname = "instruction_3q_3c_circ3.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_overwide_gates(self):
"""Test gates don't exceed width of default fold"""
circuit = QuantumCircuit(5)
initial_state = np.zeros(2**5)
initial_state[5] = 1
circuit.initialize(initial_state)
fname = "wide_params.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_one_bit_regs(self):
"""Test registers with only one bit display without number"""
qr1 = QuantumRegister(1, "qr1")
qr2 = QuantumRegister(2, "qr2")
cr1 = ClassicalRegister(1, "cr1")
cr2 = ClassicalRegister(2, "cr2")
circuit = QuantumCircuit(qr1, qr2, cr1, cr2)
circuit.h(0)
circuit.measure(0, 0)
fname = "one_bit_regs.png"
self.circuit_drawer(circuit, cregbundle=False, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_user_ax_subplot(self):
"""Test for when user supplies ax for a subplot"""
import matplotlib.pyplot as plt
fig = plt.figure(1, figsize=(6, 4))
fig.patch.set_facecolor("white")
ax1 = fig.add_subplot(1, 2, 1)
ax2 = fig.add_subplot(1, 2, 2)
ax1.plot([1, 2, 3])
circuit = QuantumCircuit(4)
circuit.h(0)
circuit.cx(0, 1)
circuit.h(1)
circuit.cx(1, 2)
plt.close(fig)
fname = "user_ax.png"
self.circuit_drawer(circuit, ax=ax2, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_figwidth(self):
"""Test style dict 'figwidth'"""
circuit = QuantumCircuit(3)
circuit.h(0)
circuit.cx(0, 1)
circuit.x(1)
circuit.cx(1, 2)
circuit.x(2)
fname = "figwidth.png"
self.circuit_drawer(circuit, style={"figwidth": 5}, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_registerless_one_bit(self):
"""Test circuit with one-bit registers and registerless bits."""
qrx = QuantumRegister(2, "qrx")
qry = QuantumRegister(1, "qry")
crx = ClassicalRegister(2, "crx")
circuit = QuantumCircuit(qrx, [Qubit(), Qubit()], qry, [Clbit(), Clbit()], crx)
fname = "registerless_one_bit.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_measures_with_conditions(self):
"""Test that a measure containing a condition displays"""
qr = QuantumRegister(2, "qr")
cr1 = ClassicalRegister(2, "cr1")
cr2 = ClassicalRegister(2, "cr2")
circuit = QuantumCircuit(qr, cr1, cr2)
circuit.h(0)
circuit.h(1)
circuit.measure(0, cr1[1])
circuit.measure(1, cr2[0]).c_if(cr1, 1)
circuit.h(0).c_if(cr2, 3)
fname = "measure_cond_false.png"
self.circuit_drawer(circuit, cregbundle=False, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
fname2 = "measure_cond_true.png"
self.circuit_drawer(circuit, cregbundle=True, filename=fname2)
ratio2 = VisualTestUtilities._save_diff(
self._image_path(fname2),
self._reference_path(fname2),
fname2,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
self.assertGreaterEqual(ratio2, 0.9999)
def test_conditions_measures_with_bits(self):
"""Test that gates with conditions and measures work with bits"""
bits = [Qubit(), Qubit(), Clbit(), Clbit()]
cr = ClassicalRegister(2, "cr")
crx = ClassicalRegister(3, "cs")
circuit = QuantumCircuit(bits, cr, [Clbit()], crx)
circuit.x(0).c_if(crx[1], 0)
circuit.measure(0, bits[3])
fname = "measure_cond_bits_false.png"
self.circuit_drawer(circuit, cregbundle=False, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
fname2 = "measure_cond_bits_true.png"
self.circuit_drawer(circuit, cregbundle=True, filename=fname2)
ratio2 = VisualTestUtilities._save_diff(
self._image_path(fname2),
self._reference_path(fname2),
fname2,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
self.assertGreaterEqual(ratio2, 0.9999)
def test_conditional_gates_right_of_measures_with_bits(self):
"""Test that gates with conditions draw to right of measures when same bit"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0])
circuit.measure(qr[0], cr[1])
circuit.h(qr[1]).c_if(cr[1], 0)
circuit.h(qr[2]).c_if(cr[0], 0)
fname = "measure_cond_bits_right.png"
self.circuit_drawer(circuit, cregbundle=False, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_conditions_with_bits_reverse(self):
"""Test that gates with conditions work with bits reversed"""
bits = [Qubit(), Qubit(), Clbit(), Clbit()]
cr = ClassicalRegister(2, "cr")
crx = ClassicalRegister(2, "cs")
circuit = QuantumCircuit(bits, cr, [Clbit()], crx)
circuit.x(0).c_if(bits[3], 0)
fname = "cond_bits_reverse.png"
self.circuit_drawer(circuit, cregbundle=False, reverse_bits=True, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_sidetext_with_condition(self):
"""Test that sidetext gates align properly with conditions"""
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
circuit = QuantumCircuit(qr, cr)
circuit.append(CPhaseGate(pi / 2), [qr[0], qr[1]]).c_if(cr[1], 1)
fname = "sidetext_condition.png"
self.circuit_drawer(circuit, cregbundle=False, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_fold_with_conditions(self):
"""Test that gates with conditions draw correctly when folding"""
qr = QuantumRegister(3)
cr = ClassicalRegister(5)
circuit = QuantumCircuit(qr, cr)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 1)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 3)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 5)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 7)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 9)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 11)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 13)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 15)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 17)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 19)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 21)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 23)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 25)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 27)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 29)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 31)
fname = "fold_with_conditions.png"
self.circuit_drawer(circuit, cregbundle=False, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_idle_wires_barrier(self):
"""Test that idle_wires False works with barrier"""
circuit = QuantumCircuit(4, 4)
circuit.x(2)
circuit.barrier()
fname = "idle_wires_barrier.png"
self.circuit_drawer(circuit, cregbundle=False, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_wire_order(self):
"""Test the wire_order option"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(4, "c")
cr2 = ClassicalRegister(2, "cx")
circuit = QuantumCircuit(qr, cr, cr2)
circuit.h(0)
circuit.h(3)
circuit.x(1)
circuit.x(3).c_if(cr, 10)
fname = "wire_order.png"
self.circuit_drawer(
circuit,
cregbundle=False,
wire_order=[2, 1, 3, 0, 6, 8, 9, 5, 4, 7],
filename=fname,
)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_barrier_label(self):
"""Test the barrier label"""
circuit = QuantumCircuit(2)
circuit.x(0)
circuit.y(1)
circuit.barrier()
circuit.y(0)
circuit.x(1)
circuit.barrier(label="End Y/X")
fname = "barrier_label.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_if_op(self):
"""Test the IfElseOp with if only"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
with circuit.if_test((cr[1], 1)):
circuit.h(0)
circuit.cx(0, 1)
fname = "if_op.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_if_else_op(self):
"""Test the IfElseOp with else"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
with circuit.if_test((cr[1], 1)) as _else:
circuit.h(0)
circuit.cx(0, 1)
with _else:
circuit.cx(0, 1)
fname = "if_else_op.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_if_else_op_textbook_style(self):
"""Test the IfElseOp with else in textbook style"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
with circuit.if_test((cr[1], 1)) as _else:
circuit.h(0)
circuit.cx(0, 1)
with _else:
circuit.cx(0, 1)
fname = "if_else_op_textbook.png"
self.circuit_drawer(circuit, style="textbook", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_if_else_with_body(self):
"""Test the IfElseOp with adding a body manually"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(3, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(0)
circuit.h(1)
circuit.measure(0, 1)
circuit.measure(1, 2)
circuit.x(2)
circuit.x(2, label="XLabel").c_if(cr, 2)
qr2 = QuantumRegister(3, "qr2")
qc2 = QuantumCircuit(qr2, cr)
qc2.x(1)
qc2.y(1)
qc2.z(0)
qc2.x(0, label="X1i").c_if(cr, 4)
circuit.if_else((cr[1], 1), qc2, None, [0, 1, 2], [0, 1, 2])
circuit.x(0, label="X1i")
fname = "if_else_body.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_if_else_op_nested(self):
"""Test the IfElseOp with complex nested if/else"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(3, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(0)
with circuit.if_test((cr[1], 1)) as _else:
circuit.x(0, label="X c_if").c_if(cr, 4)
with circuit.if_test((cr[2], 1)):
circuit.z(0)
circuit.y(1)
with circuit.if_test((cr[1], 1)):
circuit.y(1)
circuit.z(2)
with circuit.if_test((cr[2], 1)):
circuit.cx(0, 1)
with circuit.if_test((cr[1], 1)):
circuit.h(0)
circuit.x(1)
with _else:
circuit.y(1)
with circuit.if_test((cr[2], 1)):
circuit.x(0)
circuit.x(1)
inst = QuantumCircuit(2, 2, name="Inst").to_instruction()
circuit.append(inst, [qr[0], qr[1]], [cr[0], cr[1]])
circuit.x(0)
fname = "if_else_op_nested.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_if_else_op_wire_order(self):
"""Test the IfElseOp with complex nested if/else and wire_order"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(3, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(0)
with circuit.if_test((cr[1], 1)) as _else:
circuit.x(0, label="X c_if").c_if(cr, 4)
with circuit.if_test((cr[2], 1)):
circuit.z(0)
circuit.y(1)
with circuit.if_test((cr[1], 1)):
circuit.y(1)
circuit.z(2)
with circuit.if_test((cr[2], 1)):
circuit.cx(0, 1)
with circuit.if_test((cr[1], 1)):
circuit.h(0)
circuit.x(1)
with _else:
circuit.y(1)
with circuit.if_test((cr[2], 1)):
circuit.x(0)
circuit.x(1)
inst = QuantumCircuit(2, 2, name="Inst").to_instruction()
circuit.append(inst, [qr[0], qr[1]], [cr[0], cr[1]])
circuit.x(0)
fname = "if_else_op_wire_order.png"
self.circuit_drawer(circuit, wire_order=[2, 0, 3, 1, 4, 5, 6], filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_if_else_op_fold(self):
"""Test the IfElseOp with complex nested if/else and fold"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(3, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(0)
with circuit.if_test((cr[1], 1)) as _else:
circuit.x(0, label="X c_if").c_if(cr, 4)
with circuit.if_test((cr[2], 1)):
circuit.z(0)
circuit.y(1)
with circuit.if_test((cr[1], 1)):
circuit.y(1)
circuit.z(2)
with circuit.if_test((cr[2], 1)):
circuit.cx(0, 1)
with circuit.if_test((cr[1], 1)):
circuit.h(0)
circuit.x(1)
with _else:
circuit.y(1)
with circuit.if_test((cr[2], 1)):
circuit.x(0)
circuit.x(1)
inst = QuantumCircuit(2, 2, name="Inst").to_instruction()
circuit.append(inst, [qr[0], qr[1]], [cr[0], cr[1]])
circuit.x(0)
fname = "if_else_op_fold.png"
self.circuit_drawer(circuit, fold=7, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_while_loop_op(self):
"""Test the WhileLoopOp"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(3, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(0)
circuit.measure(0, 2)
with circuit.while_loop((cr[0], 0)):
circuit.h(0)
circuit.cx(0, 1)
circuit.measure(0, 0)
with circuit.if_test((cr[2], 1)):
circuit.x(0)
fname = "while_loop.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_for_loop_op(self):
"""Test the ForLoopOp"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(3, "cr")
circuit = QuantumCircuit(qr, cr)
a = Parameter("a")
circuit.h(0)
circuit.measure(0, 2)
with circuit.for_loop((2, 4, 8, 16), loop_parameter=a):
circuit.h(0)
circuit.cx(0, 1)
circuit.rx(pi / a, 1)
circuit.measure(0, 0)
with circuit.if_test((cr[2], 1)):
circuit.z(0)
fname = "for_loop.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_switch_case_op(self):
"""Test the SwitchCaseOp"""
qreg = QuantumRegister(3, "q")
creg = ClassicalRegister(3, "cr")
circuit = QuantumCircuit(qreg, creg)
circuit.h([0, 1, 2])
circuit.measure([0, 1, 2], [0, 1, 2])
with circuit.switch(creg) as case:
with case(0, 1, 2):
circuit.x(0)
with case(3, 4, 5):
circuit.y(1)
circuit.y(0)
circuit.y(0)
with case(case.DEFAULT):
circuit.cx(0, 1)
circuit.h(0)
fname = "switch_case.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
if __name__ == "__main__":
unittest.main(verbosity=1)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for graph MPL drawer"""
import unittest
import os
from test.visual import VisualTestUtilities
from contextlib import contextmanager
from pathlib import Path
from qiskit import BasicAer, execute
from qiskit.test import QiskitTestCase
from qiskit import QuantumCircuit
from qiskit.utils import optionals
from qiskit.visualization.state_visualization import state_drawer
from qiskit.visualization.counts_visualization import plot_histogram
from qiskit.visualization.gate_map import plot_gate_map, plot_coupling_map
from qiskit.providers.fake_provider import (
FakeArmonk,
FakeBelem,
FakeCasablanca,
FakeRueschlikon,
FakeMumbai,
FakeManhattan,
)
if optionals.HAS_MATPLOTLIB:
from matplotlib.pyplot import close as mpl_close
else:
raise ImportError('Must have Matplotlib installed. To install, run "pip install matplotlib".')
BASE_DIR = Path(__file__).parent
RESULT_DIR = Path(BASE_DIR) / "graph_results"
TEST_REFERENCE_DIR = Path(BASE_DIR) / "references"
FAILURE_DIFF_DIR = Path(BASE_DIR).parent / "visual_test_failures"
FAILURE_PREFIX = "graph_failure_"
@contextmanager
def cwd(path):
"""A context manager to run in a particular path"""
oldpwd = os.getcwd()
os.chdir(path)
try:
yield
finally:
os.chdir(oldpwd)
class TestGraphMatplotlibDrawer(QiskitTestCase):
"""Graph MPL visualization"""
def setUp(self):
super().setUp()
self.graph_state_drawer = VisualTestUtilities.save_data_wrap(
state_drawer, str(self), RESULT_DIR
)
self.graph_count_drawer = VisualTestUtilities.save_data_wrap(
plot_histogram, str(self), RESULT_DIR
)
self.graph_plot_gate_map = VisualTestUtilities.save_data_wrap(
plot_gate_map, str(self), RESULT_DIR
)
self.graph_plot_coupling_map = VisualTestUtilities.save_data_wrap(
plot_coupling_map, str(self), RESULT_DIR
)
if not os.path.exists(FAILURE_DIFF_DIR):
os.makedirs(FAILURE_DIFF_DIR)
if not os.path.exists(RESULT_DIR):
os.makedirs(RESULT_DIR)
def tearDown(self):
super().tearDown()
mpl_close("all")
@staticmethod
def _image_path(image_name):
return os.path.join(RESULT_DIR, image_name)
@staticmethod
def _reference_path(image_name):
return os.path.join(TEST_REFERENCE_DIR, image_name)
def test_plot_bloch_multivector(self):
"""test bloch sphere
See https://github.com/Qiskit/qiskit-terra/issues/6397.
"""
circuit = QuantumCircuit(1)
circuit.h(0)
# getting the state using backend
backend = BasicAer.get_backend("statevector_simulator")
result = execute(circuit, backend).result()
state = result.get_statevector(circuit)
fname = "bloch_multivector.png"
self.graph_state_drawer(state=state, output="bloch", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_state_hinton(self):
"""test plot_state_hinton"""
circuit = QuantumCircuit(1)
circuit.x(0)
# getting the state using backend
backend = BasicAer.get_backend("statevector_simulator")
result = execute(circuit, backend).result()
state = result.get_statevector(circuit)
fname = "hinton.png"
self.graph_state_drawer(state=state, output="hinton", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_state_qsphere(self):
"""test for plot_state_qsphere"""
circuit = QuantumCircuit(1)
circuit.x(0)
# getting the state using backend
backend = BasicAer.get_backend("statevector_simulator")
result = execute(circuit, backend).result()
state = result.get_statevector(circuit)
fname = "qsphere.png"
self.graph_state_drawer(state=state, output="qsphere", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_state_city(self):
"""test for plot_state_city"""
circuit = QuantumCircuit(1)
circuit.x(0)
# getting the state using backend
backend = BasicAer.get_backend("statevector_simulator")
result = execute(circuit, backend).result()
state = result.get_statevector(circuit)
fname = "state_city.png"
self.graph_state_drawer(state=state, output="city", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_state_paulivec(self):
"""test for plot_state_paulivec"""
circuit = QuantumCircuit(1)
circuit.x(0)
# getting the state using backend
backend = BasicAer.get_backend("statevector_simulator")
result = execute(circuit, backend).result()
state = result.get_statevector(circuit)
fname = "paulivec.png"
self.graph_state_drawer(state=state, output="paulivec", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_histogram(self):
"""for testing the plot_histogram"""
# specifing counts because we do not want oscillation of
# result until a changes is made to plot_histogram
counts = {"11": 500, "00": 500}
fname = "histogram.png"
self.graph_count_drawer(counts, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_histogram_with_rest(self):
"""test plot_histogram with 2 datasets and number_to_keep"""
data = [{"00": 3, "01": 5, "10": 6, "11": 12}]
fname = "histogram_with_rest.png"
self.graph_count_drawer(data, number_to_keep=2, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_histogram_2_sets_with_rest(self):
"""test plot_histogram with 2 datasets and number_to_keep"""
data = [
{"00": 3, "01": 5, "10": 6, "11": 12},
{"00": 5, "01": 7, "10": 6, "11": 12},
]
fname = "histogram_2_sets_with_rest.png"
self.graph_count_drawer(data, number_to_keep=2, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_histogram_color(self):
"""Test histogram with single color"""
counts = {"00": 500, "11": 500}
fname = "histogram_color.png"
self.graph_count_drawer(data=counts, color="#204940", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_histogram_multiple_colors(self):
"""Test histogram with multiple custom colors"""
counts = [
{"00": 10, "01": 15, "10": 20, "11": 25},
{"00": 25, "01": 20, "10": 15, "11": 10},
]
fname = "histogram_multiple_colors.png"
self.graph_count_drawer(
data=counts,
color=["#204940", "#c26219"],
filename=fname,
)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_histogram_hamming(self):
"""Test histogram with hamming distance"""
counts = {"101": 500, "010": 500, "001": 500, "100": 500}
fname = "histogram_hamming.png"
self.graph_count_drawer(data=counts, sort="hamming", target_string="101", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_histogram_value_sort(self):
"""Test histogram with sorting by value"""
counts = {"101": 300, "010": 240, "001": 80, "100": 150, "110": 160, "000": 280, "111": 60}
fname = "histogram_value_sort.png"
self.graph_count_drawer(data=counts, sort="value", target_string="000", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_histogram_desc_value_sort(self):
"""Test histogram with sorting by descending value"""
counts = {"101": 150, "010": 50, "001": 180, "100": 10, "110": 190, "000": 80, "111": 260}
fname = "histogram_desc_value_sort.png"
self.graph_count_drawer(
data=counts,
sort="value_desc",
target_string="000",
filename=fname,
)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_histogram_legend(self):
"""Test histogram with legend"""
counts = [{"0": 50, "1": 30}, {"0": 30, "1": 40}]
fname = "histogram_legend.png"
self.graph_count_drawer(
data=counts,
legend=["first", "second"],
filename=fname,
figsize=(15, 5),
)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_histogram_title(self):
"""Test histogram with title"""
counts = [{"0": 50, "1": 30}, {"0": 30, "1": 40}]
fname = "histogram_title.png"
self.graph_count_drawer(data=counts, title="My Histogram", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_1_qubit_gate_map(self):
"""Test plot_gate_map using 1 qubit backend"""
# getting the mock backend from FakeProvider
backend = FakeArmonk()
fname = "1_qubit_gate_map.png"
self.graph_plot_gate_map(backend=backend, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_5_qubit_gate_map(self):
"""Test plot_gate_map using 5 qubit backend"""
# getting the mock backend from FakeProvider
backend = FakeBelem()
fname = "5_qubit_gate_map.png"
self.graph_plot_gate_map(backend=backend, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_7_qubit_gate_map(self):
"""Test plot_gate_map using 7 qubit backend"""
# getting the mock backend from FakeProvider
backend = FakeCasablanca()
fname = "7_qubit_gate_map.png"
self.graph_plot_gate_map(backend=backend, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_16_qubit_gate_map(self):
"""Test plot_gate_map using 16 qubit backend"""
# getting the mock backend from FakeProvider
backend = FakeRueschlikon()
fname = "16_qubit_gate_map.png"
self.graph_plot_gate_map(backend=backend, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_27_qubit_gate_map(self):
"""Test plot_gate_map using 27 qubit backend"""
# getting the mock backend from FakeProvider
backend = FakeMumbai()
fname = "27_qubit_gate_map.png"
self.graph_plot_gate_map(backend=backend, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_65_qubit_gate_map(self):
"""test for plot_gate_map using 65 qubit backend"""
# getting the mock backend from FakeProvider
backend = FakeManhattan()
fname = "65_qubit_gate_map.png"
self.graph_plot_gate_map(backend=backend, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_figsize(self):
"""Test figsize parameter of plot_gate_map"""
# getting the mock backend from FakeProvider
backend = FakeBelem()
fname = "figsize.png"
self.graph_plot_gate_map(backend=backend, figsize=(10, 10), filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_qubit_size(self):
"""Test qubit_size parameter of plot_gate_map"""
# getting the mock backend from FakeProvider
backend = FakeBelem()
fname = "qubit_size.png"
self.graph_plot_gate_map(backend=backend, qubit_size=38, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_qubit_color(self):
"""Test qubit_color parameter of plot_gate_map"""
# getting the mock backend from FakeProvider
backend = FakeCasablanca()
fname = "qubit_color.png"
self.graph_plot_gate_map(backend=backend, qubit_color=["#ff0000"] * 7, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_qubit_labels(self):
"""Test qubit_labels parameter of plot_gate_map"""
# getting the mock backend from FakeProvider
backend = FakeCasablanca()
fname = "qubit_labels.png"
self.graph_plot_gate_map(
backend=backend, qubit_labels=list(range(10, 17, 1)), filename=fname
)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_line_color(self):
"""Test line_color parameter of plot_gate_map"""
# getting the mock backend from FakeProvider
backend = FakeManhattan()
fname = "line_color.png"
self.graph_plot_gate_map(backend=backend, line_color=["#00ff00"] * 144, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_font_color(self):
"""Test font_color parameter of plot_gate_map"""
# getting the mock backend from FakeProvider
backend = FakeManhattan()
fname = "font_color.png"
self.graph_plot_gate_map(backend=backend, font_color="#ff00ff", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_coupling_map(self):
"""Test plot_coupling_map"""
num_qubits = 5
qubit_coordinates = [[1, 0], [0, 1], [1, 1], [1, 2], [2, 1]]
coupling_map = [[1, 0], [1, 2], [1, 3], [3, 4]]
fname = "coupling_map.png"
self.graph_plot_coupling_map(
num_qubits=num_qubits,
qubit_coordinates=qubit_coordinates,
coupling_map=coupling_map,
filename=fname,
)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_bloch_multivector_figsize_improvements(self):
"""test bloch sphere figsize, font_size, title_font_size and title_pad
See https://github.com/Qiskit/qiskit-terra/issues/7263
and https://github.com/Qiskit/qiskit-terra/pull/7264.
"""
circuit = QuantumCircuit(3)
circuit.h(1)
circuit.sxdg(2)
# getting the state using backend
backend = BasicAer.get_backend("statevector_simulator")
result = execute(circuit, backend).result()
state = result.get_statevector(circuit)
fname = "bloch_multivector_figsize_improvements.png"
self.graph_state_drawer(
state=state,
output="bloch",
figsize=(3, 2),
font_size=10,
title="|0+R> state",
title_font_size=14,
title_pad=8,
filename=fname,
)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
if __name__ == "__main__":
unittest.main(verbosity=1)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
#!/usr/bin/env python3
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Utility to check that slow imports are not used in the default path."""
import subprocess
import sys
# This is not unused: importing it sets up sys.modules
import qiskit # pylint: disable=unused-import
def _main():
optional_imports = [
"networkx",
"sympy",
"pydot",
"pygments",
"ipywidgets",
"scipy.stats",
"matplotlib",
"qiskit.providers.aer",
"qiskit.providers.ibmq",
"qiskit.ignis",
"qiskit.aqua",
"docplex",
]
modules_imported = []
for mod in optional_imports:
if mod in sys.modules:
modules_imported.append(mod)
if not modules_imported:
sys.exit(0)
res = subprocess.run(
[sys.executable, "-X", "importtime", "-c", "import qiskit"],
capture_output=True,
encoding="utf8",
check=True,
)
import_tree = [
x.split("|")[-1]
for x in res.stderr.split("\n")
if "RuntimeWarning" not in x or "warnings.warn" not in x
]
indent = -1
matched_module = None
for module in import_tree:
line_indent = len(module) - len(module.lstrip())
module_name = module.strip()
if module_name in modules_imported:
if indent > 0:
continue
indent = line_indent
matched_module = module_name
if indent > 0:
if line_indent < indent:
print(f"ERROR: {matched_module} is imported via {module_name}")
indent = -1
matched_module = None
sys.exit(len(modules_imported))
if __name__ == "__main__":
_main()
|
https://github.com/renatawong/clifford-data-regression-qiskit
|
renatawong
|
'''
(C) Copyright Renata Wong 2023.
This code is licensed under the Apache License, Version 2.0. You may obtain a copy of this license
at http://www.apache.org/licenses/LICENSE-2.0.
Any modifications or derivative works of this code must retain this copyright notice, and modified files
need to carry a notice indicating that they have been altered from the originals.
For details see
Piotr Czarnik, Andrew Arrasmith, Patrick J. Coles, and Lukasz Cincio.
"Error mitigation with Clifford quantum-circuit data". Quantum 5, 592 (2021).
'''
from qiskit import QuantumCircuit, QuantumRegister
import numpy as np
# imports for generating training circuits
from qiskit.circuit import QuantumCircuit
from qiskit.converters import circuit_to_dag
from qiskit.transpiler import TransformationPass
import numpy as np
import random
from random import choices
nqubits = 2
nshots = 20000
def getParity(n):
parity = 0
while n:
parity = ~parity
n = n & (n - 1)
return parity
import itertools
def expectation_value_from_counts(counts):
exp_val = 0
for x in map(''.join, itertools.product('01', repeat=nqubits)):
if x in counts: # making sure that x is in the output as the counts dictionary contains no values with 0 occurrence
if getParity(int(x,2)) == -1:
exp_val = exp_val - counts[x]
if getParity(int(x,2)) == 0:
exp_val = exp_val + counts[x]
return exp_val/nshots
# mapping circuit to near Clifford circuits with N = number of non-Clifford gates
# Z gates with these angles/exponents are Clifford gates.
clifford_exponents = np.array([0.0, 0.5, 1.0, 1.5])
clifford_angles = [exponent * np.pi for exponent in clifford_exponents]
# replacing some non-Clifford gates with Clifford gates in the input circuit
class RZTranslator(TransformationPass):
"""A transpiler pass to replace RZ(a) gates with RZ(pi/2)^n gates, for n = 0, 1, 2, 3 at random."""
def run(self, dag):
N = 0.3 # TUNABLE: here, replace 30% of the non-Clifford gates
# iterate over all operations
for node in dag.op_nodes():
# if we hit a RZ gate replace it by RZ(pi/2)^n at random
if node.op.name in ["rz"]:
# get the rotation angle
angle = node.op.params[0]
# calculate the replacement
replacement = QuantumCircuit(1)
if node.op.name == "rz":
if angle not in clifford_angles:
if choices([0,1], [N, 1-N])[0] == 0:
replacement.rz(random.choice(clifford_angles),0)
else:
replacement.rz(angle,0)
# replace the node with our new decomposition
dag.substitute_node_with_dag(node, circuit_to_dag(replacement))
return dag
# Least-squares regression from scipy
#from scipy.stats import linregress
def least_squares_regression(noiseless_exp_vals, noisy_exp_vals):
result = scipy.stats.linregress(noisy_exp_vals, noiseless_exp_vals)
return (result.slope, result.intercept)
'''
EXAMPLE CIRCUIT. ADJUSTABLE.
'''
def append_gates(qc):
for rep in range(5):
for qubit in range(nqubits):
qc.h(qubit)
for qubit in range(nqubits)[::2]:
qc.rz(1.75, qubit)
for qubit in range(nqubits)[1::2]:
qc.rz(2.31, qubit)
for qubit in range(nqubits)[::2]:
qc.cx(qubit, qubit+1)
for qubit in range(nqubits)[::2]:
qc.rz(-1.17, qubit)
for qubit in range(nqubits)[1::2]:
qc.rz(3.23, qubit)
for qubit in range(nqubits):
qc.rx(np.pi/2, qubit)
return qc
# The original vcircuit
qc = QuantumCircuit(nqubits)
append_gates(qc)
training_circuits_no_measurement_all = []
for _ in range(500):
training_circuits_no_measurement_all.append(RZTranslator()(qc))
print(*training_circuits_no_measurement_all)
# wrapping the circuit into a statefunction
# This does not take simulation output into account, hence is always the same, while simulation with measurement varies.
from qiskit.opflow import Z, StateFn, CircuitStateFn
observable = Z ^ 2
# expectation value of the original circuit
psi_qc = CircuitStateFn(qc)
exp_val_qc = (~psi_qc @ observable @ psi_qc).eval()
print('Exact expectation value of circuit of interest:', exp_val_qc.real)
noiseless_exp_vals = []
training_circuits_no_measurement = []
for circuit in training_circuits_no_measurement_all:
psi = CircuitStateFn(circuit)
expectation_value = (~psi @ observable @ psi).eval()
if expectation_value >= exp_val_qc.real-0.05 and expectation_value <= exp_val_qc.real+0.05:
noiseless_exp_vals.append(expectation_value.real)
training_circuits_no_measurement.append(circuit)
for exp_val in noiseless_exp_vals:
print('Exact expectation value:', exp_val)
'''
Generate training circuits with measurement for noisy simulation on quantum devices
'''
from qiskit import ClassicalRegister
# original circuit with measurement
qr_qc = QuantumRegister(nqubits)
cr_qc = ClassicalRegister(nqubits)
circ_qc = QuantumCircuit(qr_qc, cr_qc)
circ_qc.append(qc.to_instruction(), [qubit for qubit in range(nqubits)])
circ_qc.measure(qr_qc, cr_qc)
training_circuits_with_measurement = []
for circuit in training_circuits_no_measurement:
qr = QuantumRegister(nqubits)
cr = ClassicalRegister(nqubits)
circ = QuantumCircuit(qr, cr)
circ.append(circuit.to_instruction(), [qubit for qubit in range(nqubits)])
circ.measure(qr, cr)
training_circuits_with_measurement.append(circ)
print(*training_circuits_with_measurement)
'''
Adding a noise model to our simulation
'''
from qiskit import transpile
from qiskit.providers.aer.noise import NoiseModel
from qiskit.test.mock import FakeVigo
from qiskit.providers.aer import AerSimulator
device_backend = FakeVigo()
coupling_map = device_backend.configuration().coupling_map
sim_vigo = AerSimulator.from_backend(device_backend)
noisy_exp_vals = []
for circuit in training_circuits_with_measurement:
tqc = transpile(circuit, sim_vigo)
result_noise = sim_vigo.run(tqc, shots=nshots).result()
counts_noise = result_noise.get_counts(0)
noisy_exp_val = expectation_value_from_counts(counts_noise)
print('Noisy expectation value from counts: ', noisy_exp_val)
noisy_exp_vals.append(noisy_exp_val)
import scipy
result = least_squares_regression(noiseless_exp_vals, noisy_exp_vals)
slope = result[0]
intercept = result[1]
print('Slope: ', slope, ' Intercept: ', intercept)
import matplotlib.pyplot as plt
plt.plot(noisy_exp_vals, noiseless_exp_vals, 'o', label='original data')
noisy_exp_vals = np.array(noisy_exp_vals)
plt.plot(noisy_exp_vals, slope*noisy_exp_vals + intercept, 'r', label='fitted line')
plt.legend()
plt.show()
'''
Prediction: run the original circuit and measure (= X_exact).
Then, apply the function X_exact = slope*X_noisy + intercept to obtain the mitigated value.
'''
# Running classical simulation
from qiskit import Aer, execute
from qiskit.visualization import plot_histogram
# Testing: classical exact expectation value from the original circuit
psi_test = CircuitStateFn(qc)
exact_exp_val_test = (~psi_test @ observable @ psi_test).eval().real
print('Exact expectation value: ', exact_exp_val_test)
'''
For execution on qasm simulator:
simulator = Aer.get_backend('qasm_simulator')
exact_result = execute(qc, simulator, shots=nshots).result()
exact_counts = exact_result.get_counts(qc)
exact_exp_val = expectation_value_from_counts(exact_counts)
print('Exact expectation value from counts: ', exact_exp_val)
'''
# Testing: quantum noisy expectation value on the original circuit
from qiskit.providers.aer.noise import NoiseModel
from qiskit.test.mock import FakeVigo
from qiskit import transpile
from qiskit.providers.aer import AerSimulator
device_backend = FakeVigo()
coupling_map = device_backend.configuration().coupling_map
sim_vigo = AerSimulator.from_backend(device_backend)
tqc = transpile(circ_qc, sim_vigo)
'''
For execution on quantum backends:
IBMQ.load_account()
provider = IBMQ.get_provider('ibm-q')
qcomp = provider.get_backend('ibmq_lima')
tqc = transpile(qc_, qcomp)
unmitigated_result = execute(qc, backend=qcomp, shots=nshots).result()
unmitigated_counts = unmitigated_result.get_counts(0)
unmitigated_exp_val = expectation_value_from_counts(unmitigated_counts)
print('Unmitigated expectation value from counts: ', unmitigated_exp_val)
'''
unmitigated_result = execute(circ_qc, backend=device_backend, shots=nshots).result()
unmitigated_counts = unmitigated_result.get_counts(0)
unmitigated_exp_val = expectation_value_from_counts(unmitigated_counts)
# Mitigation
mitigated_exp_val = slope*unmitigated_exp_val + intercept
print('Mitigated expectation value from counts:', mitigated_exp_val)
# Error calculation
error_unmitigated = abs(unmitigated_exp_val-exact_exp_val_test)
error_mitigated = abs(mitigated_exp_val-exact_exp_val_test)
print("Error (unmitigated):", error_unmitigated)
print("Error (mitigated with CDR):", error_mitigated)
print("Relative error (unmitigated):", (error_unmitigated/exact_exp_val_test))
print("Relative error (mitigated with CDR):", error_mitigated/exact_exp_val_test)
print(f"Error reduction with CDR: {(error_unmitigated-error_mitigated)/error_unmitigated :.1%}.")
|
https://github.com/mrvee-qC-bee/SMU_Feb1
|
mrvee-qC-bee
|
#make sure your qiskit version is up to date
import qiskit.tools.jupyter
%qiskit_version_table
from qiskit import QuantumCircuit
# Create a Quantum Circuit acting on a quantum register of two qubits
circ = QuantumCircuit(2)
print(circ)
# Add a H gate on qubit 0, putting this qubit in superposition.
circ.h(0)
# Add a CX (CNOT) gate on control qubit 0 and target qubit 1, putting
# the qubits in a Bell state.
circ.cx(0, 1)
circ.draw('mpl', style="iqp")
#One can also draw this as an ascii drawing
circ.draw()
from qiskit.primitives import Sampler
#Instantiate a new Sampler object
sampler = Sampler()
#We'll also need to add measurement
circ = QuantumCircuit(2)
circ.h(0)
circ.cx(0, 1)
# Insert measurements on all qubits
circ.measure_all()
circ.draw('mpl', style='iqp')
# Now run the job and examine the results
sampler_job = sampler.run(circ)
result = sampler_job.result()
print(f"Job Result:\n>>> {result}")
print(f" > Quasi-probability distribution (integer): {result.quasi_dists[0]}")
print(f" > Quasi-probability distribution (bits): {result.quasi_dists[0].binary_probabilities(2)}")
print(f" > Metadata: {result.metadata[0]}")
from qiskit.tools.visualization import plot_distribution
prob_distribution = sampler_job.result().quasi_dists[0].binary_probabilities()
plot_distribution(prob_distribution)
from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Session
#Initialize a QiskitRuntimeService object
service = QiskitRuntimeService()
#We will use the 127-qubit ibm_nazca or 133-qubit ibm_torino backend
backend = service.get_backend('ibm_cusco')
session = Session(service=service, backend=backend)
# sampler = Sampler(backend=backend)
sampler = Sampler(session=session)
job = sampler.run(circ)
print(f">>> Job ID: {job.job_id()}")
print(f">>> Session ID: {job.session_id}")
print(f">>> Job Status: {job.status()}")
# Use a job id from a previous result
job = service.job("cnxwrpjmbjng0081zhc0")
print(f">>> Job Status: {job.status()}")
result = job.result()
print(f"Job Result:\n>>> {result}")
print(f" > Quasi-probability distribution (integer): {result.quasi_dists[0]}")
print(f" > Quasi-probability distribution (bits): {result.quasi_dists[0].binary_probabilities(2)}")
print(f" > Metadata: {result.metadata[0]}")
from qiskit.visualization import plot_distribution
import matplotlib.pyplot as plt
plt.style.use('dark_background')
#plot_distribution(result.quasi_dists[0])
plot_distribution([result.quasi_dists[0].binary_probabilities(2),prob_distribution])
from qiskit import QuantumRegister, ClassicalRegister
#Create the circuit
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
# we can also write "qc = QuantumCircuit(2,2)"
#Add the hadamard and CNOT gates to the circuit
qc.h(0)
qc.cx(0, 1)
qc.draw('mpl', style="iqp")
# Import the SparesPauliOp class and create our observables variable
from qiskit.quantum_info import SparsePauliOp
observable = SparsePauliOp(["II", "XX", "YY", "ZZ"], coeffs=[1, 1, -1, 1])
# Import qiskit primitives
from qiskit.primitives import Estimator
estimator = Estimator()
job = estimator.run(qc, observable)
result_exact = job.result()
print(result_exact)
print(f"Expectation Value of <II+XX-YY+ZZ> = {result_exact.values[0]:.3f}")
from qiskit_ibm_runtime import Estimator, Session
#Initialize a QiskitRuntimeService object
service = QiskitRuntimeService()
#We will use the 127-qubit ibm_nazca backend
backend = service.get_backend('ibm_torino')
# create a Runtime session for efficient execution (optional)
session = Session(service=service, backend=backend)
# estimator = Estimator(backend=backend)
estimator = Estimator(session=session)
#Here we can get some status information about the backend
status = backend.status()
is_operational = status.operational
jobs_in_queue = status.pending_jobs
print('Operational?: {} \n Jobs in Queue: {}\n'.format(is_operational, jobs_in_queue))
# We can also obtain some configuration information
config = backend.configuration()
print(64*"#","\nConfiguration for: {}, version: {}".format(config.backend_name, config.backend_version))
print(" Number of Qubits: {}".format(config.n_qubits))
print(" Basis Gates: {}".format(config.basis_gates))
print(" OpenPulse Enabled: {}".format(config.open_pulse))
job = estimator.run(qc, observable)
print(f">>> Job ID: {job.job_id()}")
print(f">>> Session ID: {job.session_id}")
print(f">>> Job Status: {job.status()}")
# Use a job id from a previous result
job = service.job("cnxwwhtmbjng0081zhxg")
print(f">>> Job Status: {job.status()}")
#Examine our results once the job has completed
result = job.result()
print(f">>> {result}")
print(f" > Expectation value: {result.values[0]}")
print(f" > Metadata: {result.metadata[0]}")
from qiskit.visualization import plot_histogram
import matplotlib.pyplot as plt
plt.style.use('dark_background')
data = {"Ideal": result_exact.values[0],"Result": result.values[0]}
plt.bar(range(len(data)), data.values(), align='center', color = "#7793f2")
plt.xticks(range(len(data)), list(data.keys()))
plt.show()
from qiskit_ibm_runtime import Options
# To set our resilience and optimization level we need to create this `Options` object
options = Options()
options.resilience_level = 2
options.optimization_level = 3
# We'll prepare the same example circuit as before
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
# we can also write "qc = QuantumCircuit(2,2)"
#Add the hadamard and CNOT gates to the circuit
qc.h(0)
qc.cx(0, 1)
# We'll also instantiate a new Runtime Estimator() object
# estimator = Estimator(options=options, backend=backend)
estimator = Estimator(options=options, session=session)
# and use the same observable as before
observable = SparsePauliOp(["II", "XX", "YY", "ZZ"], coeffs=[1, 1, -1, 1])
job = estimator.run(circuits=qc, observables=observable)
print(f">>> Job ID: {job.job_id()}")
print(f">>> Session ID: {job.session_id}")
print(f">>> Job Status: {job.status()}")
# Use a job id from a previous result
job = service.job("cnxwx04ja3gg0085f6cg")
print(f">>> Job Status: {job.status()}")
#Examine our results once the job has completed
result_mitigated = job.result()
print(f">>> {result_mitigated}")
print(f" > Expectation value: {result_mitigated.values[0]}")
print(f" > Metadata: {result_mitigated.metadata[0]}")
from qiskit.visualization import plot_histogram
import matplotlib.pyplot as plt
plt.style.use('dark_background')
data = {"Ideal": result_exact.values[0],"Result": result.values[0],"Mitigated result": result_mitigated.values[0]}
plt.bar(range(len(data)), data.values(), align='center', color = "#7793f2")
plt.xticks(range(len(data)), list(data.keys()))
plt.show()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/adamjm/qiskit-portfolio-optimisation-extended
|
adamjm
|
from qiskit import Aer
from qiskit.algorithms import VQE, QAOA, NumPyMinimumEigensolver
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import TwoLocal
from qiskit.utils import QuantumInstance
from qiskit_finance.applications.optimization import PortfolioOptimization
from qiskit_finance.data_providers import RandomDataProvider
from qiskit_optimization.algorithms import MinimumEigenOptimizer
from qiskit_optimization.applications import OptimizationApplication
from qiskit_optimization.converters import QuadraticProgramToQubo
from qiskit_finance import QiskitFinanceError
from qiskit_finance.data_providers import *
from qiskit import IBMQ, assemble, transpile
from qiskit.utils import algorithm_globals
import numpy as np
import matplotlib.pyplot as plt
import datetime
provider = IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
for backend in provider.backends():
print(backend)
for backend in provider.backends():
print(backend.status().to_dict())
#backend = provider.get_backend('ibmq_santiago')
backend = Aer.get_backend('statevector_simulator')
## Load Stock market Data
stocks = ["AEO", "AAPL", "AEP", "AAL"]
try:
data = YahooDataProvider(
tickers = stocks,
start=datetime.datetime(2018, 1, 1),
end=datetime.datetime(2018, 12, 31))
data.run()
except QiskitFinanceError as ex:
data = None
print(ex)
#Plot Tickers over the time period
for (cnt, s) in enumerate(data._tickers):
plt.plot(data._data[cnt], label=s)
plt.legend(loc='upper center', bbox_to_anchor=(0.5, 1.1), ncol=3)
plt.xticks(rotation=90)
plt.show()
# # set number of assets (= number of qubits)
# num_assets = 4
# seed = 124
# # Generate expected return and covariance matrix from (random) time-series
# stocks = [("TICKER%s" % i) for i in range(num_assets)]
# data = RandomDataProvider(tickers=stocks,
# start=datetime.datetime(2016,1,1),
# end=datetime.datetime(2016,1,30),
# seed=seed)
# data.run()
mu = data.get_period_return_mean_vector()
sigma = data.get_period_return_covariance_matrix()
print(stocks)
print(mu)
# plot sigma
plt.imshow(sigma, interpolation='nearest')
plt.show()
q = 0.5
num_assets = 4
seed = 123# set risk factor
budget = num_assets // 2 # set budget
penalty = num_assets # set parameter to scale the budget penalty term
portfolio = PortfolioOptimization(expected_returns=mu, covariances=sigma, risk_factor=q, budget=budget)
qp = portfolio.to_quadratic_program()
qp
def index_to_selection(i, num_assets):
s = "{0:b}".format(i).rjust(num_assets)
x = np.array([1 if s[i]=='1' else 0 for i in reversed(range(num_assets))])
return x
def print_result(result):
selection = result.x
value = result.fval
print('Optimal: selection {}, value {:.4f}'.format(selection, value))
eigenstate = result.min_eigen_solver_result.eigenstate
eigenvector = eigenstate if isinstance(eigenstate, np.ndarray) else eigenstate.to_matrix()
probabilities = np.abs(eigenvector)**2
i_sorted = reversed(np.argsort(probabilities))
print('\n----------------- Full result ---------------------')
print('selection\tvalue\t\tprobability')
print('---------------------------------------------------')
for i in i_sorted:
x = index_to_selection(i, num_assets)
value = QuadraticProgramToQubo().convert(qp).objective.evaluate(x)
#value = portfolio.to_quadratic_program().objective.evaluate(x)
probability = probabilities[i]
print('%10s\t%.4f\t\t%.4f' %(x, value, probability))
exact_mes = NumPyMinimumEigensolver()
exact_eigensolver = MinimumEigenOptimizer(exact_mes)
result = exact_eigensolver.solve(qp)
print_result(result)
## Classical Optimiser
cobyla = COBYLA()
cobyla.set_options(maxiter=5)
#ry == Ansatz
ry = TwoLocal(num_assets, 'ry', 'cz', reps=3, entanglement='full')
print(ry)
#Variation Quantum Eigensolver
quantum_instance = QuantumInstance(backend=backend, seed_simulator=seed, seed_transpiler=seed)
vqe_mes = VQE(ry, optimizer=cobyla, quantum_instance=quantum_instance)
vqe = MinimumEigenOptimizer(vqe_mes)
result = vqe.solve(qp)
print_result(result)
algorithm_globals.random_seed = 1234
#backend = Aer.get_backend('statevector_simulator')
cobyla = COBYLA()
cobyla.set_options(maxiter=250)
quantum_instance = QuantumInstance(backend=backend, seed_simulator=seed, seed_transpiler=seed)
qaoa_mes = QAOA(optimizer=cobyla, reps=3, quantum_instance=quantum_instance)
qaoa = MinimumEigenOptimizer(qaoa_mes)
result = qaoa.solve(qp)
print_result(result)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/RevanthK/ShorsAlgorithmIBMQiskit
|
RevanthK
|
# initialization
import numpy as np
# importing Qiskit
from qiskit import IBMQ, BasicAer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, execute, Aer
from qiskit.tools.jupyter import *
provider = IBMQ.load_account()
# import basic plot tools
from qiskit.visualization import plot_histogram
def initialize(circuit, n, m):
circuit.h(range(n)) # Hadamard transform on measurment register
circuit.x(n+m-1) # X gate on last qubit
def c_amod15(a, x):
if a not in [2,7,8,11,13]:
raise ValueError("'a' must be 2,7,8,11 or 13") # remember that a needs to be co-prime with N
unitary = QuantumCircuit(4)
for iteration in range(x):
# bitwise arithmetic to represent modular exponentiation function
if a in [2,13]:
unitary.swap(0,1)
unitary.swap(1,2)
unitary.swap(2,3)
if a in [7,8]:
unitary.swap(2,3)
unitary.swap(1,2)
unitary.swap(0,1)
if a == 11:
unitary.swap(1,3)
unitary.swap(0,2)
if a in [7,11,13]:
for q in range(4):
unitary.x(q)
unitary = unitary.to_gate()
unitary.name = "%i^%i mod 15" % (a, x)
# But we need to make it a controlled operation for phase kickback
c_unitary = unitary.control()
return c_unitary
def modular_exponentiation(circuit, n, m, a):
for exp in range(n):
exponent = 2**exp
circuit.append(a_x_mod15(a, exponent), [exp] + list(range(n, n+m)))
from qiskit.circuit.library import QFT
def apply_iqft(circuit, measurement_qubits):
circuit.append(QFT( len(measurement_qubits), do_swaps=False).inverse(), measurement_qubits)
def shor_algo(n, m, a):
# set up the circuit
circ = QuantumCircuit(n+m, n)
# initialize the registers
initialize(circ, n, m)
circ.barrier()
# map modular exponentiation problem onto qubits
modular_exponentiation(circ, n, m, a)
circ.barrier()
# apply inverse QFT -- expose period
apply_iqft(circ, range(n))
# measure the measurement register
circ.measure(range(n), range(n))
return circ
n = 4; m = 4; a = 11
mycircuit = shor_algo(n, m, a)
mycircuit.draw('mpl')
simulator = Aer.get_backend('qasm_simulator')
counts = execute(mycircuit, backend=simulator, shots=1024).result().get_counts(mycircuit)
plot_histogram(counts)
for measured_value in counts:
print(f"Measured {int(measured_value[::-1], 2)}")
from math import gcd
from math import sqrt
from itertools import count, islice
for measured_value in counts:
measured_value_decimal = int(measured_value[::-1], 2)
print(f"Measured {measured_value_decimal}")
if measured_value_decimal % 2 != 0:
print("Failed. Measured value is not an even number")
continue
x = int((a ** (measured_value_decimal/2)) % 15)
if (x + 1) % 15 == 0:
print("Failed. x + 1 = 0 (mod N) where x = a^(r/2) (mod N)")
continue
guesses = gcd(x + 1, 15), gcd(x - 1, 15)
print(guesses)
def is_prime(n):
return n > 1 and all(n % i for i in islice(count(2), int(sqrt(n)-1)))
if is_prime(guesses[0]) and is_prime(guesses[1]):
print(f"**The prime factors are {guesses[0]} and {guesses[1]}**")
|
https://github.com/parton-quark/RLSB-CongX-Qiskit
|
parton-quark
|
# (c) Copyright 2020 Shin Nishio, parton@sfc.wide.ad.jp
def tfc_to_qiskit(tfc_path):
tfc_file = open(tfc_path, "r", encoding = "utf_8")
# convert tfc_file into list of lines
tfc_lines = tfc_file.readlines()
# prepare .py file
tfc_path_left = tfc_path.split('.')
py_file_name = "RLSBCQ_" + str(tfc_path_left[0]) + ".py"
py_file = open(py_file_name, "w", encoding = "utf_8")
# py_file.write(text)で書き込める
_write_head(py_file)
tfc_line_number = 0
for tfc_line in tfc_lines:
tfc_line_number += 1
if tfc_line.startswith('t'):
_gt(py_file, tfc_line, valiables_dict)
elif tfc_line.startswith('f'):
_gf(py_file, tfc_line, valiables_dict)
elif tfc_line.startswith('#'):
_write_comment(py_file, tfc_line)
elif tfc_line.startswith('.v'):
# get list of valiables
valiables_dict = _valiables(py_file, tfc_line)
# make_register
_prepare_register(py_file, valiables_dict)
elif tfc_line.startswith('.i'):
# get inputs
input_dict = _inputs(py_file, tfc_line, valiables_dict)
elif tfc_line.startswith('.o'):
# get outputs
output_dict = _outputs(py_file, tfc_line, valiables_dict)
elif tfc_line.startswith('.ol'):
# get outputs list
ol_dict = _outputs_list(py_file, tfc_line, valiables_dict)
elif tfc_line.startswith('.c'):
# get constants
constants_ = _constants(py_file, tfc_line, valiables_dict)
elif tfc_line.startswith('BEGIN'):
py_file.write('# BEGIN\n')
elif tfc_line.startswith('END'):
py_file.write('# END\n')
py_file.close()
else:
print("The first letter of the" + tfc_line_number + "line of the input is strange.")
#終わり
tfc_file.close()
return
def _write_head(py_file):
lisences = _license_info()
# import SDKs
import_qiskit = 'from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\n'
import_CongX = 'from CongX.extensions.standard import cnx\n'
# Comments from RLSB-CongX-Qiskit
comments_from_RLSB_CongX_Qiskit = '# Can be run by installing Qiskit and CongX.\n' + '# !pip install qiskit\n' + '# !pip install CongX\n'
py_file.write(lisences)
py_file.write(import_qiskit)
py_file.write(import_CongX)
py_file.write(comments_from_RLSB_CongX_Qiskit)
def _license_info():
original_lisence = '# LISENCE\n'
congx_lisence = '# This file is converted by RLSB-CongX-Qiskit. RLSB-CongX-Qiskit is written by Shin Nishio. bib file is https://github.com/parton-quark/RLSB-CongX-Qiskit/blob/master/RLSB-CongX-Qiskit.bib \n'
license_info = original_lisence + congx_lisence
return license_info
def _prepare_register(py_file, valiables_dict):
num_qubits = len(valiables_dict)
q = 'q = QuantumRegister(' + str(num_qubits) + ')\n'
# c = ClassicalRegister(0)
qc = 'qc = QuantumCircuit(q)\n'
py_file.write(q)
py_file.write(qc)
def _write_comment(py_file, tfc_line):
# Write as it is
py_file.write(tfc_line)
def _gt(py_file, tfc_line, valiables_dict):
'''
e.g.
input t3 b,c,d
{b:1, c:2, d:3}
output qc.cnx(valiables_dict[b],valiables_dict[c],valiables_dict[d])
'''
# delete tn
tfc_line = tfc_line.lstrip('t')
# Delete the head number
tfc_line = tfc_line.strip()
tfc_line = tfc_line.strip(' ')
operand_number = int(tfc_line[0])
tfc_line = tfc_line[2:]
# make valuable list
val_list = tfc_line.split(',')
operand_list = []
for i in val_list:
operand = valiables_dict[str(i)]
operand_list.append(operand)
operand_str = ', '.join(map(str, operand_list))
cnx = "qc.cnx(" + operand_str + ")"
py_file.write(cnx)
py_file.write('\n')
def _gf(py_file, tfc_line, valiables_dict):
message = 'Generalized Fredkin is under construction\n'
return message
def _valiables(py_file, tfc_line):
'''
e.g.
input .v a,b,c,d
output {'a':0, 'b':1, 'c':2, 'd':3}
'''
# delete str = '.v'
tfc_line = tfc_line.lstrip('.v ')
# remove whitespace
tfc_line = tfc_line.strip()
tfc_line = tfc_line.strip(' ')
# make valuable list
val_list = tfc_line.split(',')
num_qubit = len(val_list)
qubit_list = [i for i in range(num_qubit)]
# make valuable_list and qubit_list to dict
valiables_dict = dict(zip(val_list,qubit_list))
py_file.write('# valuables' + str(valiables_dict) + '\n')
return valiables_dict
def _inputs(py_file, tfc_line, valiables_dict):
'''
e.g.
input i. a,b,c,d
output {'a':0, 'b':1, 'c':2, 'd':3}
'''
# delete str = '.v'
tfc_line = tfc_line.lstrip('.i')
# remove whitespace
tfc_line = tfc_line.strip()
# make valuable list
input_list = tfc_line.split(',')
qubit_list = []
for i in input_list:
qubit_number = valiables_dict[i]
qubit_list.append(qubit_number)
# make valuable_list and qubit_list to dict
input_dict = dict(zip(input_list,qubit_list))
py_file.write('# inputs' + str(input_dict) + '\n')
return input_dict
def _outputs(py_file, tfc_line, valiables_dict):
'''
e.g.
input o. a,b,c,d
output {'a':0, 'b':1, 'c':2, 'd':3}
'''
# delete str = '.v'
tfc_line = tfc_line.lstrip('.o')
# remove whitespace
tfc_line = tfc_line.strip()
# make valuable list
output_list = tfc_line.split(',')
qubit_list = []
for i in output_list:
qubit_number = valiables_dict[i]
qubit_list.append(qubit_number)
# make valuable_list and qubit_list to dict
output_dict = dict(zip(output_list,qubit_list))
py_file.write('# outputs' + str(output_dict) + '\n')
return output_dict
def _outputs_list(py_file, tfc_line, valiables_dict):
'''
e.g.
input .ol b1,b2,b3,b4,b5,b6,b7,b8,b9
output {'a':0, 'b':1, 'c':2, 'd':3}
'''
# delete str = '.v'
tfc_line = tfc_line.lstrip('.ol')
# remove whitespace
tfc_line = tfc_line.strip()
# make valuable list
ol_list = tfc_line.split(',')
qubit_list = []
for i in ol_list:
qubit_number = valiables_dict[i]
qubit_list.append(qubit_number)
# make valuable_list and qubit_list to dict
ol_dict = dict(zip(ol_list, qubit_list))
py_file.write('#' + str(ol_dict) + '\n')
return ol_dict
def _constants(py_file, tfc_line):
'''
e.g.
input .c 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
output {'c0':0, 'c1':0, 'c2':2, 'c3':3....}
'''
# delete str = '.c'
tfc_line = tfc_line.lstrip('.c')
# remove whitespace
tfc_line = tfc_line.strip()
# make valuable list
contstants = tfc_line.split(',')
py_file.write('#' + str(contstants) + '\n')
return contstants
|
https://github.com/parton-quark/RLSB-CongX-Qiskit
|
parton-quark
|
!pip install qiskit
!pip install CongX
from tfc_to_qiskit import tfc_to_qiskit
tfc_to_qiskit('test.tfc.txt')
import RLSBCQ_test
RLSBCQ_test.qc.draw(output='mpl')
from qiskit.compiler import transpile
transpiled = transpile(RLSBCQ_test.qc, backend=None, basis_gates=None, coupling_map=None, backend_properties=None, initial_layout=None, seed_transpiler=None, optimization_level=None, pass_manager=None, callback=None, output_name=None)
transpiled.draw(output='mpl')
|
https://github.com/parton-quark/RLSB-CongX-Qiskit
|
parton-quark
|
!pip install qiskit
!pip install CongX
from tfc_to_qiskit import tfc_to_qiskit
tfc_to_qiskit('test.tfc.txt')
import RLSBCQ_test
RLSBCQ_test.qc.draw(output='mpl')
from qiskit.compiler import transpile
transpiled = transpile(RLSBCQ_test.qc, backend=None, basis_gates=None, coupling_map=None, backend_properties=None, initial_layout=None, seed_transpiler=None, optimization_level=None, pass_manager=None, callback=None, output_name=None)
transpiled.draw(output='mpl')
|
https://github.com/parton-quark/RLSB-CongX-Qiskit
|
parton-quark
|
def tfc_to_qiskit(tfc_path):
tfc_file = open(tfc_path, "r", encoding = "utf_8")
# convert tfc_file into list of lines
tfc_lines = tfc.readlines()
# prepare .py file
py_file_name = "RLSBQC" + str(tfc_path) + ".py"
py_file = open(py_file_name, "w", encoding = "utf_8")
# py_file.write(text)で書き込める
_write_head(py_file)
tfc_line_number = 0
for tfc_line in tfc_lines:
tfc_line_number += 1
if tfc_lines.startswith('t'):
_gt(py_file, tfc_line, valiable_list)
elif tfc_lines.startswith('f'):
_gf(py_file, tfc_line, valiable_list)
elif tfc_lines.startswith('#'):
_write_comment(py_file, tfc_line)
elif tfc_lines.startswith('.v'):
# get list of valiables
_valiables(py_file, tfc_line)
elif tfc_lines.startswith('.i'):
# get inputs
_inputs(py_file, tfc_line)
elif tfc_lines.startswith('.o'):
# get outputs
outputs
elif tfc_lines.startswith('.ol'):
# get outputs list
elif tfc_lines.startswith('.c'):
# get constants
elif tfc_lines.startswith('BEGIN'):
py_file.write('# BEGIN')
elif tfc_lines.startswith('END'):
py_file.write('# END')
py_file.close()
else:
print("The first letter of the" + tfc_line_number + "line of the input is strange.")
#終わり
tfc_file.close()
def _write_head(py_file):
lisences = _license_info()
# import SDKs
import_qiskit = 'from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister'
import_CongX = 'from CongX.extensions.standard import cnx'
# Comments from RLSB-CongX-Qiskit
comments_from_RLSB_CongX_Qiskit = '""\n' + 'なんかコメントするよん qiskit, congxをインポートしてね!' + '"""'
py_file.write(lisences)
py_file.write(import_qiskit)
py_file.write(import_CongX)
py_file.write(comments_from_RLSB_CongX_Qiskit)
def _license_info:
original_lisence = ''
congx_lisence = 'This file is converted by RLSB-CongX-Qiskit. RLSB-CongX-Qiskit はpartonによって書かれたソフトウェアです。→bib fileのアドレス'
# (c) Copyright 2020 Shin Nishio, parton@sfc.wide.ad.jp 入れるか考える
def _prepare_register(line_qubit):
line_qubit = line_qubit.replace(' ', '')
line_qubit = line_qubit.replace(' ', '')
# line_qubit = line_qubit.replace('.', '')
if line_qubit[0:2] == '.v':
line_qubit = line_qubit.lstrip('.v')
num_qubit = _count_num_qubits(line_qubit) + 1
return num_qubit
else:
print('error, prepare_register() have some problem')
print(line_qubit)
def _input_qubits(line_qubit):
line_qubit = line_qubit.replace(' ', '')
line_qubit = line_qubit.replace(' ', '')
# line_qubit = line_qubit.replace('.', '')
if line_qubit[0:2] == '.i':
line_qubit = line_qubit.lstrip('.i')
i_qubits = abcを数字のリストに直したやつ
return num_qubits
else:
print('error, input_qubits() have some problem')
print(line_qubit)
def _output_qubits(line_qubit):
line_qubit = line_qubit.replace(' ', '')
line_qubit = line_qubit.replace(' ', '')
# line_qubit = line_qubit.replace('.', '')
if line_qubit[0:2] == '.o':
line_qubit = line_qubit.lstrip('.o')
o_qubits = abcを数字のリストにしたやつ
return o_qubits
else:
print('error, output_qubits() have some problem')
print(line_qubit)
def _count_num_qubits(qubit_str):
alphabets = {'a':0,'b':1,'c':2,'d':3,'e':4,'f':5,'g':6,'h':7,'i':8,'j':9,'k':10,'l':11,'m':12,'n':13,'o':14,'p':15,'q':16,'r':17,'s':18,'t':19,'u':20,'v':21,'w':22,'x':23,'y':24,'z':25}
if qubit_str[0] == 'a':
num = alphabets[qubit_str[-1]]
return num
else:
print('error, count_num_qubits() have some problem')
print(qubit_str)
def _write_comment(py_file):
コメント来た時の対処
コメントとして書き込む
|
https://github.com/mentesniker/Quantum-error-mitigation
|
mentesniker
|
from qiskit import QuantumCircuit, QuantumRegister, Aer, execute, ClassicalRegister
from qiskit.ignis.verification.topological_codes import RepetitionCode
from qiskit.ignis.verification.topological_codes import lookuptable_decoding
from qiskit.ignis.verification.topological_codes import GraphDecoder
from qiskit.providers.aer.noise import NoiseModel
from qiskit.providers.aer.noise.errors import pauli_error, depolarizing_error
from qiskit.ignis.mitigation.measurement import (complete_meas_cal,CompleteMeasFitter)
from qiskit.visualization import plot_histogram
import random
backend = Aer.get_backend('qasm_simulator')
#These two functions were taken from https://stackoverflow.com/questions/10237926/convert-string-to-list-of-bits-and-viceversa
def tobits(s):
result = []
for c in s:
bits = bin(ord(c))[2:]
bits = '00000000'[len(bits):] + bits
result.extend([int(b) for b in bits])
return ''.join([str(x) for x in result])
def frombits(bits):
chars = []
for b in range(int(len(bits) / 8)):
byte = bits[b*8:(b+1)*8]
chars.append(chr(int(''.join([str(bit) for bit in byte]), 2)))
return ''.join(chars)
def get_noise(circuit,probability,qubits):
random_number = random.uniform(0, 1)
if(random_number <= probability):
qubit = random.randint(0,len(qubits)-1)
circuit.x(qubit)
return circuit
def codificate(bitString):
qubits = list()
for i in range(len(bitString)):
mycircuit = QuantumCircuit(1,1)
if(bitString[i] == "1"):
mycircuit.x(0)
qubits.append(mycircuit)
return qubits
m0 = tobits("I like dogs")
qubits = codificate(m0)
measurements = list()
for i in range(len(qubits)):
qubit = qubits[i]
qubit.measure(0,0)
result = execute(qubit, backend, shots=1, memory=True).result()
measurements.append(int(result.get_memory()[0]))
print(frombits(measurements))
m0 = tobits("I like dogs")
qubits = codificate(m0)
measurements = list()
for i in range(len(qubits)):
qubit = qubits[i]
qubit = get_noise(qubit,0.2,range(qubit.num_qubits))
qubit.measure(0,0)
result = execute(qubit, backend, shots=1, memory=True).result()
measurements.append(int(result.get_memory()[0]))
print(frombits(measurements))
for i in range(len(qubits)):
cb = QuantumRegister(1,'code_qubit')
lq = QuantumRegister(4,'ancilla_qubit')
sb = ClassicalRegister(2,'syndrome_bit')
out = ClassicalRegister(1,'output_bit')
mycircuit = QuantumCircuit(cb,lq,sb,out)
if(m0[i] == "1"):
mycircuit.x(0)
mycircuit.cx(0,1)
mycircuit.cx(1,2)
mycircuit = get_noise(mycircuit,0.2,range(3))
mycircuit.cx(0,3)
mycircuit.cx(1,3)
mycircuit.cx(0,4)
mycircuit.cx(2,4)
mycircuit.measure(3,0)
mycircuit.measure(4,1)
qubits[i] = mycircuit
measurements = list()
raw_bits = list()
for i in range(len(qubits)):
qubit = qubits[i]
qubit.measure(0,2)
result = execute(qubit, backend, shots=1, memory=True).result()
bits = result.get_memory()[0]
raw_bits.append(int(bits[0]))
for i in range(len(qubits)):
qubit = qubits[i]
result = execute(qubit, backend, shots=1, memory=True).result()
bits = result.get_memory()[0]
if(bits[2] == '1' and bits[3] == '0'):
qubit.x(2)
if(bits[2] == '0' and bits[3] == '1'):
qubit.x(1)
if(bits[2] == '1' and bits[3] == '1'):
qubit.x(0)
qubit.measure(0,2)
result = execute(qubit, backend, shots=1, memory=True).result()
bits = result.get_memory()[0]
measurements.append(int(bits[0]))
print("without error correction the string was: " + frombits(raw_bits))
print("with error correction the string was: " + frombits(measurements))
|
https://github.com/mentesniker/Quantum-error-mitigation
|
mentesniker
|
from qiskit import QuantumCircuit, QuantumRegister, Aer, execute, ClassicalRegister
from qiskit.ignis.verification.topological_codes import RepetitionCode
from qiskit.ignis.verification.topological_codes import lookuptable_decoding
from qiskit.ignis.verification.topological_codes import GraphDecoder
from qiskit.providers.aer.noise import NoiseModel
from qiskit.providers.aer.noise.errors import pauli_error, depolarizing_error
from qiskit.ignis.mitigation.measurement import (complete_meas_cal,CompleteMeasFitter)
from qiskit.visualization import plot_histogram
backend = Aer.get_backend('qasm_simulator')
#These two functions were taken from https://stackoverflow.com/questions/10237926/convert-string-to-list-of-bits-and-viceversa
def tobits(s):
result = []
for c in s:
bits = bin(ord(c))[2:]
bits = '00000000'[len(bits):] + bits
result.extend([int(b) for b in bits])
return ''.join([str(x) for x in result])
def frombits(bits):
chars = []
for b in range(int(len(bits) / 8)):
byte = bits[b*8:(b+1)*8]
chars.append(chr(int(''.join([str(bit) for bit in byte]), 2)))
return ''.join(chars)
def get_noise(p):
error_meas = pauli_error([('X',p), ('I', 1 - p)])
noise_model = NoiseModel()
noise_model.add_all_qubit_quantum_error(error_meas, "measure")
return noise_model
def codificate(bitString):
qubits = list()
for i in range(len(bitString)):
mycircuit = QuantumCircuit(1,1)
if(bitString[i] == "1"):
mycircuit.x(0)
qubits.append(mycircuit)
return qubits
def count(array):
numZero = 0
numOne = 0
for i in array:
if i == "0":
numZero += 1
elif i == "1":
numOne += 1
return dict({"0":numZero, "1":numOne})
m0 = tobits("I like dogs")
qubits = codificate(m0)
measurements = list()
for i in range(len(qubits)):
qubit = qubits[i]
qubit.measure(0,0)
result = execute(qubit, backend, shots=1, memory=True).result()
measurements.append(int(result.get_memory()[0]))
print(frombits(measurements))
m0 = tobits("I like dogs")
qubits = codificate(m0)
measurements = list()
for i in range(len(qubits)):
qubit = qubits[i]
qubit.measure(0,0)
result = execute(qubit, backend, shots=1, memory=True, noise_model=get_noise(0.2)).result()
measurements.append(int(result.get_memory()[0]))
print(frombits(measurements))
for state in ['0','1']:
qc = QuantumCircuit(1,1)
if state[0]=='1':
qc.x(0)
qc.measure(qc.qregs[0],qc.cregs[0])
print(state+' becomes',
execute(qc, Aer.get_backend('qasm_simulator'),noise_model=get_noise(0.2),shots=1000).result().get_counts())
qubit = qubits[0]
result = execute(qubit, backend, shots=1000, memory=True, noise_model=get_noise(0.2)).result()
print(result.get_counts())
import numpy as np
import scipy.linalg as la
M = [[0.389,0.611],
[0.593,0.407]]
Cnoisy = [[397],[603]]
Minv = la.inv(M)
Cmitigated = np.dot(Minv, Cnoisy)
print('C_mitigated =\n',Cmitigated)
Cmitigated = np.floor(Cmitigated)
if(Cmitigated[1][0] < 0):
Cmitigated[1][0] = 0
print('C_mitigated =\n',Cmitigated)
qr = QuantumRegister(1)
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
backend = Aer.get_backend('qasm_simulator')
job = execute(meas_calibs, backend=backend, shots=1000,noise_model=get_noise(0.2))
cal_results = job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
print(meas_fitter.cal_matrix)
qubit = qubits[2]
qubit.measure(0,0)
results = execute(qubit, backend=backend, shots=10000, noise_model=get_noise(0.2),memory=True).result()
noisy_counts = count(results.get_memory())
print(noisy_counts)
Minv = la.inv(meas_fitter.cal_matrix)
Cmitigated = np.dot(Minv, np.array(list(noisy_counts.values())))
print('C_mitigated =\n',Cmitigated)
outputs = list()
for i in range(len(qubits)):
qubit = qubits[i]
qubit.measure(0,0)
results = execute(qubit, backend=backend, shots=10000, memory=True, noise_model=get_noise(0.2)).result()
noisy_counts = count(results.get_memory())
Minv = la.inv(meas_fitter.cal_matrix)
Cmitigated = np.dot(Minv, np.array(list(noisy_counts.values())))
if(Cmitigated[0] > Cmitigated[1]):
outputs.append('0')
else:
outputs.append('1')
print(frombits(''.join(outputs)))
outputs = list()
meas_filter = meas_fitter.filter
for i in range(len(qubits)):
qubit = qubits[i]
qubit.measure(0,0)
results = execute(qubit, backend=backend, shots=10000, memory=True, noise_model=get_noise(0.2)).result()
noisy_counts = count(results.get_memory())
# Results with mitigation
mitigated_counts = meas_filter.apply(noisy_counts)
if('1' not in mitigated_counts):
outputs.append('0')
elif('0' not in mitigated_counts):
outputs.append('1')
elif(mitigated_counts['0'] > mitigated_counts['1']):
outputs.append('0')
else:
outputs.append('1')
print(frombits(''.join(outputs)))
|
https://github.com/mentesniker/Quantum-error-mitigation
|
mentesniker
|
from qiskit import QuantumCircuit, QuantumRegister, Aer, execute, ClassicalRegister
from qiskit.ignis.verification.topological_codes import RepetitionCode
from qiskit.ignis.verification.topological_codes import lookuptable_decoding
from qiskit.ignis.verification.topological_codes import GraphDecoder
from qiskit.providers.aer.noise import NoiseModel
from qiskit.providers.aer.noise.errors import pauli_error, depolarizing_error
from qiskit.ignis.mitigation.measurement import (complete_meas_cal,CompleteMeasFitter)
from qiskit.visualization import plot_histogram
import random
backend = Aer.get_backend('qasm_simulator')
#These two functions were taken from https://stackoverflow.com/questions/10237926/convert-string-to-list-of-bits-and-viceversa
def tobits(s):
result = []
for c in s:
bits = bin(ord(c))[2:]
bits = '00000000'[len(bits):] + bits
result.extend([int(b) for b in bits])
return ''.join([str(x) for x in result])
def frombits(bits):
chars = []
for b in range(int(len(bits) / 8)):
byte = bits[b*8:(b+1)*8]
chars.append(chr(int(''.join([str(bit) for bit in byte]), 2)))
return ''.join(chars)
def get_noise(circuit,probability,qubits):
random_number = random.uniform(0, 1)
if(random_number <= probability):
qubit = random.randint(0,len(qubits)-1)
if(random.randint(0,3) == 0):
circuit.x(qubit)
if(random.randint(0,3) == 1):
circuit.y(qubit)
if(random.randint(0,3) == 2):
circuit.z(qubit)
return circuit
def codificate(bitString):
qubits = list()
for i in range(len(bitString)):
mycircuit = QuantumCircuit(1,1)
if(bitString[i] == "1"):
mycircuit.x(0)
mycircuit.h(0)
qubits.append(mycircuit)
return qubits
m0 = tobits("I like dogs")
qubits = codificate(m0)
measurements = list()
for i in range(len(qubits)):
qubit = qubits[i]
qubit.h(0)
qubit.measure(0,0)
result = execute(qubit, backend, shots=1, memory=True).result()
measurements.append(int(result.get_memory()[0]))
print(frombits(measurements))
for i in range(len(qubits)):
cb = QuantumRegister(1,'code_qubit')
lq = QuantumRegister(8,'ancilla_qubit')
out = ClassicalRegister(1,'output_bit')
mycircuit = QuantumCircuit(cb,lq,out)
if(m0[i] == "1"):
mycircuit.x(0)
mycircuit.cx(0,[3,6])
mycircuit.h([0,3,6])
mycircuit.cx(0,[1,2])
mycircuit.cx(3,[4,5])
mycircuit.cx(6,[7,8])
mycircuit.barrier()
mycircuit = get_noise(mycircuit,0.2,range(9))
mycircuit.barrier()
mycircuit.cx(0,[1,2])
mycircuit.cx(3,[4,5])
mycircuit.cx(6,[7,8])
mycircuit.ccx(2,1,0)
mycircuit.ccx(5,4,3)
mycircuit.ccx(8,7,6)
mycircuit.h([0,3,6])
mycircuit.cx(0,[3,6])
mycircuit.ccx(6,2,0)
mycircuit.measure(0,0)
qubits[i] = mycircuit
qubits[0].draw()
raw_bits = list()
for i in range(len(qubits)):
qubit = qubits[i]
qubit.measure(0,0)
result = execute(qubit, backend, shots=1, memory=True).result()
bits = result.get_memory()[0]
raw_bits.append(int(bits[0]))
print("with error correction the string was: " + frombits(raw_bits))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.