repo
stringclasses
900 values
file
stringclasses
754 values
content
stringlengths
4
215k
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# 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 qiskit.quantum_info.analysis""" import unittest import qiskit from qiskit import BasicAer from qiskit.quantum_info.analysis.average import average_data from qiskit.quantum_info.analysis.make_observable import make_dict_observable from qiskit.quantum_info.analysis import hellinger_fidelity from qiskit.test import QiskitTestCase class TestAnalyzation(QiskitTestCase): """Test qiskit.Result API""" def test_average_data_dict_observable(self): """Test average_data for dictionary observable input""" qr = qiskit.QuantumRegister(2) cr = qiskit.ClassicalRegister(2) qc = qiskit.QuantumCircuit(qr, cr, name="qc") qc.h(qr[0]) qc.cx(qr[0], qr[1]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) shots = 10000 backend = BasicAer.get_backend("qasm_simulator") result = qiskit.execute(qc, backend, shots=shots).result() counts = result.get_counts(qc) observable = {"00": 1, "11": 1, "01": -1, "10": -1} mean_zz = average_data(counts=counts, observable=observable) observable = {"00": 1, "11": -1, "01": 1, "10": -1} mean_zi = average_data(counts, observable) observable = {"00": 1, "11": -1, "01": -1, "10": 1} mean_iz = average_data(counts, observable) self.assertAlmostEqual(mean_zz, 1, places=1) self.assertAlmostEqual(mean_zi, 0, places=1) self.assertAlmostEqual(mean_iz, 0, places=1) def test_average_data_list_observable(self): """Test average_data for list observable input.""" qr = qiskit.QuantumRegister(3) cr = qiskit.ClassicalRegister(3) qc = qiskit.QuantumCircuit(qr, cr, name="qc") qc.h(qr[0]) qc.cx(qr[0], qr[1]) qc.cx(qr[0], qr[2]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) qc.measure(qr[2], cr[2]) shots = 10000 backend = BasicAer.get_backend("qasm_simulator") result = qiskit.execute(qc, backend, shots=shots).result() counts = result.get_counts(qc) observable = [1, -1, -1, 1, -1, 1, 1, -1] mean_zzz = average_data(counts=counts, observable=observable) observable = [1, 1, 1, 1, -1, -1, -1, -1] mean_zii = average_data(counts, observable) observable = [1, 1, -1, -1, 1, 1, -1, -1] mean_izi = average_data(counts, observable) observable = [1, 1, -1, -1, -1, -1, 1, 1] mean_zzi = average_data(counts, observable) self.assertAlmostEqual(mean_zzz, 0, places=1) self.assertAlmostEqual(mean_zii, 0, places=1) self.assertAlmostEqual(mean_izi, 0, places=1) self.assertAlmostEqual(mean_zzi, 1, places=1) def test_average_data_matrix_observable(self): """Test average_data for matrix observable input.""" qr = qiskit.QuantumRegister(2) cr = qiskit.ClassicalRegister(2) qc = qiskit.QuantumCircuit(qr, cr, name="qc") qc.h(qr[0]) qc.cx(qr[0], qr[1]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) shots = 10000 backend = BasicAer.get_backend("qasm_simulator") result = qiskit.execute(qc, backend, shots=shots).result() counts = result.get_counts(qc) observable = [[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]] mean_zz = average_data(counts=counts, observable=observable) observable = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, -1, 0], [0, 0, 0, -1]] mean_zi = average_data(counts, observable) observable = [[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, 1, 0], [0, 0, 0, -1]] mean_iz = average_data(counts, observable) self.assertAlmostEqual(mean_zz, 1, places=1) self.assertAlmostEqual(mean_zi, 0, places=1) self.assertAlmostEqual(mean_iz, 0, places=1) def test_make_dict_observable(self): """Test make_dict_observable.""" list_in = [1, 1, -1, -1] list_out = make_dict_observable(list_in) list_expected = {"00": 1, "01": 1, "10": -1, "11": -1} matrix_in = [[4, 0, 0, 0], [0, -3, 0, 0], [0, 0, 2, 0], [0, 0, 0, -1]] matrix_out = make_dict_observable(matrix_in) matrix_expected = {"00": 4, "01": -3, "10": 2, "11": -1} long_list_in = [1, 1, -1, -1, -1, -1, 1, 1] long_list_out = make_dict_observable(long_list_in) long_list_expected = { "000": 1, "001": 1, "010": -1, "011": -1, "100": -1, "101": -1, "110": 1, "111": 1, } self.assertEqual(list_out, list_expected) self.assertEqual(matrix_out, matrix_expected) self.assertEqual(long_list_out, long_list_expected) def test_hellinger_fidelity_same(self): """Test hellinger fidelity is one for same dist.""" qc = qiskit.QuantumCircuit(5, 5) qc.h(2) qc.cx(2, 1) qc.cx(2, 3) qc.cx(3, 4) qc.cx(1, 0) qc.measure(range(5), range(5)) sim = BasicAer.get_backend("qasm_simulator") res = qiskit.execute(qc, sim).result() ans = hellinger_fidelity(res.get_counts(), res.get_counts()) self.assertEqual(ans, 1.0) def test_hellinger_fidelity_no_overlap(self): """Test hellinger fidelity is zero for no overlap.""" # β”Œβ”€β”€β”€β” β”Œβ”€β” # q_0: ─────────── X β”œβ”€β”€β”€β”€β”€β”€Mβ”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ # β”Œβ”€β”€β”€β”β””β”€β”¬β”€β”˜ β””β•₯β”˜β”Œβ”€β” # q_1: ────── X β”œβ”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β•«β”€β”€Mβ”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€ # β”Œβ”€β”€β”€β”β””β”€β”¬β”€β”˜ β•‘ β””β•₯β”˜β”Œβ”€β” # q_2: ─ H β”œβ”€β”€β– β”€β”€β”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β•«β”€β”€β•«β”€β”€Mβ”œβ”€β”€β”€β”€β”€β”€ # β””β”€β”€β”€β”˜ β”Œβ”€β”΄β”€β” β•‘ β•‘ β””β•₯β”˜β”Œβ”€β” # q_3: ─────────── X β”œβ”€β”€β– β”€β”€β”€β•«β”€β”€β•«β”€β”€β•«β”€β”€Mβ”œβ”€β”€β”€ # β””β”€β”€β”€β”˜β”Œβ”€β”΄β”€β” β•‘ β•‘ β•‘ β””β•₯β”˜β”Œβ”€β” # q_4: ──────────────── X β”œβ”€β•«β”€β”€β•«β”€β”€β•«β”€β”€β•«β”€β”€Mβ”œ # β””β”€β”€β”€β”˜ β•‘ β•‘ β•‘ β•‘ β””β•₯β”˜ # c: 5/═════════════════════╩══╩══╩══╩══╩═ # 0 1 2 3 4 qc = qiskit.QuantumCircuit(5, 5) qc.h(2) qc.cx(2, 1) qc.cx(2, 3) qc.cx(3, 4) qc.cx(1, 0) qc.measure(range(5), range(5)) # β”Œβ”€β”€β”€β” β”Œβ”€β” # q_0: ─────────── X β”œβ”€β”€β”€β”€β”€β”€Mβ”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€ # β”Œβ”€β”€β”€β”β””β”€β”¬β”€β”˜ β””β•₯β”˜β”Œβ”€β” # q_1: ────── X β”œβ”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β•«β”€β”€Mβ”œβ”€β”€β”€β”€β”€β”€ # β”Œβ”€β”€β”€β”β””β”€β”¬β”€β”˜β”Œβ”€β”€β”€β” β•‘ β””β•₯β”˜β”Œβ”€β” # q_2: ─ H β”œβ”€β”€β– β”€β”€β”€ Y β”œβ”€β”€β– β”€β”€β”€β•«β”€β”€β•«β”€β”€Mβ”œβ”€β”€β”€ # β””β”€β”€β”€β”˜ β””β”€β”€β”€β”˜β”Œβ”€β”΄β”€β” β•‘ β•‘ β””β•₯β”˜β”Œβ”€β” # q_3: ──────────────── X β”œβ”€β•«β”€β”€β•«β”€β”€β•«β”€β”€Mβ”œ # β”Œβ”€β” β””β”€β”€β”€β”˜ β•‘ β•‘ β•‘ β””β•₯β”˜ # q_4: ──Mβ”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β•«β”€β”€β•«β”€β”€β•«β”€β”€β•«β”€ # β””β•₯β”˜ β•‘ β•‘ β•‘ β•‘ # c: 5/══╩══════════════════╩══╩══╩══╩═ # 4 0 1 2 3 qc2 = qiskit.QuantumCircuit(5, 5) qc2.h(2) qc2.cx(2, 1) qc2.y(2) qc2.cx(2, 3) qc2.cx(1, 0) qc2.measure(range(5), range(5)) sim = BasicAer.get_backend("qasm_simulator") res1 = qiskit.execute(qc, sim).result() res2 = qiskit.execute(qc2, sim).result() ans = hellinger_fidelity(res1.get_counts(), res2.get_counts()) self.assertEqual(ans, 0.0) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# 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 """Tests for Operator matrix linear operator class.""" import unittest import logging import copy from test import combine import numpy as np from ddt import ddt from numpy.testing import assert_allclose import scipy.linalg as la from qiskit import QiskitError from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.circuit.library import HGate, CHGate, CXGate, QFT from qiskit.test import QiskitTestCase from qiskit.transpiler.layout import Layout, TranspileLayout from qiskit.quantum_info.operators import Operator, ScalarOp from qiskit.quantum_info.operators.predicates import matrix_equal from qiskit.compiler.transpiler import transpile from qiskit.circuit import Qubit from qiskit.circuit.library import Permutation, PermutationGate logger = logging.getLogger(__name__) class OperatorTestCase(QiskitTestCase): """Test utils for Operator""" # Pauli-matrix unitaries UI = np.eye(2) UX = np.array([[0, 1], [1, 0]]) UY = np.array([[0, -1j], [1j, 0]]) UZ = np.diag([1, -1]) UH = np.array([[1, 1], [1, -1]]) / np.sqrt(2) @classmethod def rand_rho(cls, n): """Return random density matrix""" seed = np.random.randint(0, np.iinfo(np.int32).max) logger.debug("rand_rho default_rng seeded with seed=%s", seed) rng = np.random.default_rng(seed) psi = rng.random(n) + 1j * rng.random(n) rho = np.outer(psi, psi.conj()) rho /= np.trace(rho) return rho @classmethod def rand_matrix(cls, rows, cols=None, real=False): """Return a random matrix.""" seed = np.random.randint(0, np.iinfo(np.int32).max) logger.debug("rand_matrix default_rng seeded with seed=%s", seed) rng = np.random.default_rng(seed) if cols is None: cols = rows if real: return rng.random(size=(rows, cols)) return rng.random(size=(rows, cols)) + 1j * rng.random(size=(rows, cols)) def simple_circuit_no_measure(self): """Return a unitary circuit and the corresponding unitary array.""" qr = QuantumRegister(3) circ = QuantumCircuit(qr) circ.h(qr[0]) circ.x(qr[1]) circ.ry(np.pi / 2, qr[2]) y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]]) target = Operator(np.kron(y90, np.kron(self.UX, self.UH))) return circ, target def simple_circuit_with_measure(self): """Return a unitary circuit with measurement.""" qr = QuantumRegister(2) cr = ClassicalRegister(2) circ = QuantumCircuit(qr, cr) circ.h(qr[0]) circ.x(qr[1]) circ.measure(qr, cr) return circ @ddt class TestOperator(OperatorTestCase): """Tests for Operator linear operator class.""" def test_init_array_qubit(self): """Test subsystem initialization from N-qubit array.""" # Test automatic inference of qubit subsystems mat = self.rand_matrix(8, 8) op = Operator(mat) assert_allclose(op.data, mat) self.assertEqual(op.dim, (8, 8)) self.assertEqual(op.input_dims(), (2, 2, 2)) self.assertEqual(op.output_dims(), (2, 2, 2)) self.assertEqual(op.num_qubits, 3) op = Operator(mat, input_dims=8, output_dims=8) assert_allclose(op.data, mat) self.assertEqual(op.dim, (8, 8)) self.assertEqual(op.input_dims(), (2, 2, 2)) self.assertEqual(op.output_dims(), (2, 2, 2)) self.assertEqual(op.num_qubits, 3) def test_init_array(self): """Test initialization from array.""" mat = np.eye(3) op = Operator(mat) assert_allclose(op.data, mat) self.assertEqual(op.dim, (3, 3)) self.assertEqual(op.input_dims(), (3,)) self.assertEqual(op.output_dims(), (3,)) self.assertIsNone(op.num_qubits) mat = self.rand_matrix(2 * 3 * 4, 4 * 5) op = Operator(mat, input_dims=[4, 5], output_dims=[2, 3, 4]) assert_allclose(op.data, mat) self.assertEqual(op.dim, (4 * 5, 2 * 3 * 4)) self.assertEqual(op.input_dims(), (4, 5)) self.assertEqual(op.output_dims(), (2, 3, 4)) self.assertIsNone(op.num_qubits) def test_init_array_except(self): """Test initialization exception from array.""" mat = self.rand_matrix(4, 4) self.assertRaises(QiskitError, Operator, mat, input_dims=[4, 2]) self.assertRaises(QiskitError, Operator, mat, input_dims=[2, 4]) self.assertRaises(QiskitError, Operator, mat, input_dims=5) def test_init_operator(self): """Test initialization from Operator.""" op1 = Operator(self.rand_matrix(4, 4)) op2 = Operator(op1) self.assertEqual(op1, op2) def test_circuit_init(self): """Test initialization from a circuit.""" # Test tensor product of 1-qubit gates circuit = QuantumCircuit(3) circuit.h(0) circuit.x(1) circuit.ry(np.pi / 2, 2) op = Operator(circuit) y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]]) target = np.kron(y90, np.kron(self.UX, self.UH)) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) # Test decomposition of Controlled-Phase gate lam = np.pi / 4 circuit = QuantumCircuit(2) circuit.cp(lam, 0, 1) op = Operator(circuit) target = np.diag([1, 1, 1, np.exp(1j * lam)]) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) # Test decomposition of controlled-H gate circuit = QuantumCircuit(2) circuit.ch(0, 1) op = Operator(circuit) target = np.kron(self.UI, np.diag([1, 0])) + np.kron(self.UH, np.diag([0, 1])) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) def test_instruction_init(self): """Test initialization from a circuit.""" gate = CXGate() op = Operator(gate).data target = gate.to_matrix() global_phase_equivalent = matrix_equal(op, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) gate = CHGate() op = Operator(gate).data had = HGate().to_matrix() target = np.kron(had, np.diag([0, 1])) + np.kron(np.eye(2), np.diag([1, 0])) global_phase_equivalent = matrix_equal(op, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) def test_circuit_init_except(self): """Test initialization from circuit with measure raises exception.""" circuit = self.simple_circuit_with_measure() self.assertRaises(QiskitError, Operator, circuit) def test_equal(self): """Test __eq__ method""" mat = self.rand_matrix(2, 2, real=True) self.assertEqual(Operator(np.array(mat, dtype=complex)), Operator(mat)) mat = self.rand_matrix(4, 4) self.assertEqual(Operator(mat.tolist()), Operator(mat)) def test_data(self): """Test Operator representation string property.""" mat = self.rand_matrix(2, 2) op = Operator(mat) assert_allclose(mat, op.data) def test_to_matrix(self): """Test Operator to_matrix method.""" mat = self.rand_matrix(2, 2) op = Operator(mat) assert_allclose(mat, op.to_matrix()) def test_dim(self): """Test Operator dim property.""" mat = self.rand_matrix(4, 4) self.assertEqual(Operator(mat).dim, (4, 4)) self.assertEqual(Operator(mat, input_dims=[4], output_dims=[4]).dim, (4, 4)) self.assertEqual(Operator(mat, input_dims=[2, 2], output_dims=[2, 2]).dim, (4, 4)) def test_input_dims(self): """Test Operator input_dims method.""" op = Operator(self.rand_matrix(2 * 3 * 4, 4 * 5), input_dims=[4, 5], output_dims=[2, 3, 4]) self.assertEqual(op.input_dims(), (4, 5)) self.assertEqual(op.input_dims(qargs=[0, 1]), (4, 5)) self.assertEqual(op.input_dims(qargs=[1, 0]), (5, 4)) self.assertEqual(op.input_dims(qargs=[0]), (4,)) self.assertEqual(op.input_dims(qargs=[1]), (5,)) def test_output_dims(self): """Test Operator output_dims method.""" op = Operator(self.rand_matrix(2 * 3 * 4, 4 * 5), input_dims=[4, 5], output_dims=[2, 3, 4]) self.assertEqual(op.output_dims(), (2, 3, 4)) self.assertEqual(op.output_dims(qargs=[0, 1, 2]), (2, 3, 4)) self.assertEqual(op.output_dims(qargs=[2, 1, 0]), (4, 3, 2)) self.assertEqual(op.output_dims(qargs=[2, 0, 1]), (4, 2, 3)) self.assertEqual(op.output_dims(qargs=[0]), (2,)) self.assertEqual(op.output_dims(qargs=[1]), (3,)) self.assertEqual(op.output_dims(qargs=[2]), (4,)) self.assertEqual(op.output_dims(qargs=[0, 2]), (2, 4)) self.assertEqual(op.output_dims(qargs=[2, 0]), (4, 2)) def test_reshape(self): """Test Operator reshape method.""" op = Operator(self.rand_matrix(8, 8)) reshaped1 = op.reshape(input_dims=[8], output_dims=[8]) reshaped2 = op.reshape(input_dims=[4, 2], output_dims=[2, 4]) self.assertEqual(op.output_dims(), (2, 2, 2)) self.assertEqual(op.input_dims(), (2, 2, 2)) self.assertEqual(reshaped1.output_dims(), (8,)) self.assertEqual(reshaped1.input_dims(), (8,)) self.assertEqual(reshaped2.output_dims(), (2, 4)) self.assertEqual(reshaped2.input_dims(), (4, 2)) def test_reshape_num_qubits(self): """Test Operator reshape method with num_qubits.""" op = Operator(self.rand_matrix(8, 8), input_dims=(4, 2), output_dims=(2, 4)) reshaped = op.reshape(num_qubits=3) self.assertEqual(reshaped.num_qubits, 3) self.assertEqual(reshaped.output_dims(), (2, 2, 2)) self.assertEqual(reshaped.input_dims(), (2, 2, 2)) def test_reshape_raise(self): """Test Operator reshape method with invalid args.""" op = Operator(self.rand_matrix(3, 3)) self.assertRaises(QiskitError, op.reshape, num_qubits=2) def test_copy(self): """Test Operator copy method""" mat = np.eye(2) with self.subTest("Deep copy"): orig = Operator(mat) cpy = orig.copy() cpy._data[0, 0] = 0.0 self.assertFalse(cpy == orig) with self.subTest("Shallow copy"): orig = Operator(mat) clone = copy.copy(orig) clone._data[0, 0] = 0.0 self.assertTrue(clone == orig) def test_is_unitary(self): """Test is_unitary method.""" # X-90 rotation X90 = la.expm(-1j * 0.5 * np.pi * np.array([[0, 1], [1, 0]]) / 2) self.assertTrue(Operator(X90).is_unitary()) # Non-unitary should return false self.assertFalse(Operator([[1, 0], [0, 0]]).is_unitary()) def test_to_operator(self): """Test to_operator method.""" op1 = Operator(self.rand_matrix(4, 4)) op2 = op1.to_operator() self.assertEqual(op1, op2) def test_conjugate(self): """Test conjugate method.""" matr = self.rand_matrix(2, 4, real=True) mati = self.rand_matrix(2, 4, real=True) op = Operator(matr + 1j * mati) uni_conj = op.conjugate() self.assertEqual(uni_conj, Operator(matr - 1j * mati)) def test_transpose(self): """Test transpose method.""" matr = self.rand_matrix(2, 4, real=True) mati = self.rand_matrix(2, 4, real=True) op = Operator(matr + 1j * mati) uni_t = op.transpose() self.assertEqual(uni_t, Operator(matr.T + 1j * mati.T)) def test_adjoint(self): """Test adjoint method.""" matr = self.rand_matrix(2, 4, real=True) mati = self.rand_matrix(2, 4, real=True) op = Operator(matr + 1j * mati) uni_adj = op.adjoint() self.assertEqual(uni_adj, Operator(matr.T - 1j * mati.T)) def test_compose_except(self): """Test compose different dimension exception""" self.assertRaises(QiskitError, Operator(np.eye(2)).compose, Operator(np.eye(3))) self.assertRaises(QiskitError, Operator(np.eye(2)).compose, 2) def test_compose(self): """Test compose method.""" op1 = Operator(self.UX) op2 = Operator(self.UY) targ = Operator(np.dot(self.UY, self.UX)) self.assertEqual(op1.compose(op2), targ) self.assertEqual(op1 & op2, targ) targ = Operator(np.dot(self.UX, self.UY)) self.assertEqual(op2.compose(op1), targ) self.assertEqual(op2 & op1, targ) def test_dot(self): """Test dot method.""" op1 = Operator(self.UY) op2 = Operator(self.UX) targ = Operator(np.dot(self.UY, self.UX)) self.assertEqual(op1.dot(op2), targ) self.assertEqual(op1 @ op2, targ) targ = Operator(np.dot(self.UX, self.UY)) self.assertEqual(op2.dot(op1), targ) self.assertEqual(op2 @ op1, targ) def test_compose_front(self): """Test front compose method.""" opYX = Operator(self.UY).compose(Operator(self.UX), front=True) matYX = np.dot(self.UY, self.UX) self.assertEqual(opYX, Operator(matYX)) opXY = Operator(self.UX).compose(Operator(self.UY), front=True) matXY = np.dot(self.UX, self.UY) self.assertEqual(opXY, Operator(matXY)) def test_compose_subsystem(self): """Test subsystem compose method.""" # 3-qubit operator mat = self.rand_matrix(8, 8) mat_a = self.rand_matrix(2, 2) mat_b = self.rand_matrix(2, 2) mat_c = self.rand_matrix(2, 2) op = Operator(mat) op1 = Operator(mat_a) op2 = Operator(np.kron(mat_b, mat_a)) op3 = Operator(np.kron(mat_c, np.kron(mat_b, mat_a))) # op3 qargs=[0, 1, 2] targ = np.dot(np.kron(mat_c, np.kron(mat_b, mat_a)), mat) self.assertEqual(op.compose(op3, qargs=[0, 1, 2]), Operator(targ)) self.assertEqual(op.compose(op3([0, 1, 2])), Operator(targ)) self.assertEqual(op & op3([0, 1, 2]), Operator(targ)) # op3 qargs=[2, 1, 0] targ = np.dot(np.kron(mat_a, np.kron(mat_b, mat_c)), mat) self.assertEqual(op.compose(op3, qargs=[2, 1, 0]), Operator(targ)) self.assertEqual(op & op3([2, 1, 0]), Operator(targ)) # op2 qargs=[0, 1] targ = np.dot(np.kron(np.eye(2), np.kron(mat_b, mat_a)), mat) self.assertEqual(op.compose(op2, qargs=[0, 1]), Operator(targ)) self.assertEqual(op & op2([0, 1]), Operator(targ)) # op2 qargs=[2, 0] targ = np.dot(np.kron(mat_a, np.kron(np.eye(2), mat_b)), mat) self.assertEqual(op.compose(op2, qargs=[2, 0]), Operator(targ)) self.assertEqual(op & op2([2, 0]), Operator(targ)) # op1 qargs=[0] targ = np.dot(np.kron(np.eye(4), mat_a), mat) self.assertEqual(op.compose(op1, qargs=[0]), Operator(targ)) self.assertEqual(op & op1([0]), Operator(targ)) # op1 qargs=[1] targ = np.dot(np.kron(np.eye(2), np.kron(mat_a, np.eye(2))), mat) self.assertEqual(op.compose(op1, qargs=[1]), Operator(targ)) self.assertEqual(op & op1([1]), Operator(targ)) # op1 qargs=[2] targ = np.dot(np.kron(mat_a, np.eye(4)), mat) self.assertEqual(op.compose(op1, qargs=[2]), Operator(targ)) self.assertEqual(op & op1([2]), Operator(targ)) def test_dot_subsystem(self): """Test subsystem dot method.""" # 3-qubit operator mat = self.rand_matrix(8, 8) mat_a = self.rand_matrix(2, 2) mat_b = self.rand_matrix(2, 2) mat_c = self.rand_matrix(2, 2) op = Operator(mat) op1 = Operator(mat_a) op2 = Operator(np.kron(mat_b, mat_a)) op3 = Operator(np.kron(mat_c, np.kron(mat_b, mat_a))) # op3 qargs=[0, 1, 2] targ = np.dot(mat, np.kron(mat_c, np.kron(mat_b, mat_a))) self.assertEqual(op.dot(op3, qargs=[0, 1, 2]), Operator(targ)) self.assertEqual(op.dot(op3([0, 1, 2])), Operator(targ)) # op3 qargs=[2, 1, 0] targ = np.dot(mat, np.kron(mat_a, np.kron(mat_b, mat_c))) self.assertEqual(op.dot(op3, qargs=[2, 1, 0]), Operator(targ)) self.assertEqual(op.dot(op3([2, 1, 0])), Operator(targ)) # op2 qargs=[0, 1] targ = np.dot(mat, np.kron(np.eye(2), np.kron(mat_b, mat_a))) self.assertEqual(op.dot(op2, qargs=[0, 1]), Operator(targ)) self.assertEqual(op.dot(op2([0, 1])), Operator(targ)) # op2 qargs=[2, 0] targ = np.dot(mat, np.kron(mat_a, np.kron(np.eye(2), mat_b))) self.assertEqual(op.dot(op2, qargs=[2, 0]), Operator(targ)) self.assertEqual(op.dot(op2([2, 0])), Operator(targ)) # op1 qargs=[0] targ = np.dot(mat, np.kron(np.eye(4), mat_a)) self.assertEqual(op.dot(op1, qargs=[0]), Operator(targ)) self.assertEqual(op.dot(op1([0])), Operator(targ)) # op1 qargs=[1] targ = np.dot(mat, np.kron(np.eye(2), np.kron(mat_a, np.eye(2)))) self.assertEqual(op.dot(op1, qargs=[1]), Operator(targ)) self.assertEqual(op.dot(op1([1])), Operator(targ)) # op1 qargs=[2] targ = np.dot(mat, np.kron(mat_a, np.eye(4))) self.assertEqual(op.dot(op1, qargs=[2]), Operator(targ)) self.assertEqual(op.dot(op1([2])), Operator(targ)) def test_compose_front_subsystem(self): """Test subsystem front compose method.""" # 3-qubit operator mat = self.rand_matrix(8, 8) mat_a = self.rand_matrix(2, 2) mat_b = self.rand_matrix(2, 2) mat_c = self.rand_matrix(2, 2) op = Operator(mat) op1 = Operator(mat_a) op2 = Operator(np.kron(mat_b, mat_a)) op3 = Operator(np.kron(mat_c, np.kron(mat_b, mat_a))) # op3 qargs=[0, 1, 2] targ = np.dot(mat, np.kron(mat_c, np.kron(mat_b, mat_a))) self.assertEqual(op.compose(op3, qargs=[0, 1, 2], front=True), Operator(targ)) # op3 qargs=[2, 1, 0] targ = np.dot(mat, np.kron(mat_a, np.kron(mat_b, mat_c))) self.assertEqual(op.compose(op3, qargs=[2, 1, 0], front=True), Operator(targ)) # op2 qargs=[0, 1] targ = np.dot(mat, np.kron(np.eye(2), np.kron(mat_b, mat_a))) self.assertEqual(op.compose(op2, qargs=[0, 1], front=True), Operator(targ)) # op2 qargs=[2, 0] targ = np.dot(mat, np.kron(mat_a, np.kron(np.eye(2), mat_b))) self.assertEqual(op.compose(op2, qargs=[2, 0], front=True), Operator(targ)) # op1 qargs=[0] targ = np.dot(mat, np.kron(np.eye(4), mat_a)) self.assertEqual(op.compose(op1, qargs=[0], front=True), Operator(targ)) # op1 qargs=[1] targ = np.dot(mat, np.kron(np.eye(2), np.kron(mat_a, np.eye(2)))) self.assertEqual(op.compose(op1, qargs=[1], front=True), Operator(targ)) # op1 qargs=[2] targ = np.dot(mat, np.kron(mat_a, np.eye(4))) self.assertEqual(op.compose(op1, qargs=[2], front=True), Operator(targ)) def test_power(self): """Test power method.""" X90 = la.expm(-1j * 0.5 * np.pi * np.array([[0, 1], [1, 0]]) / 2) op = Operator(X90) self.assertEqual(op.power(2), Operator([[0, -1j], [-1j, 0]])) self.assertEqual(op.power(4), Operator(-1 * np.eye(2))) self.assertEqual(op.power(8), Operator(np.eye(2))) def test_expand(self): """Test expand method.""" mat1 = self.UX mat2 = np.eye(3, dtype=complex) mat21 = np.kron(mat2, mat1) op21 = Operator(mat1).expand(Operator(mat2)) self.assertEqual(op21.dim, (6, 6)) assert_allclose(op21.data, Operator(mat21).data) mat12 = np.kron(mat1, mat2) op12 = Operator(mat2).expand(Operator(mat1)) self.assertEqual(op12.dim, (6, 6)) assert_allclose(op12.data, Operator(mat12).data) def test_tensor(self): """Test tensor method.""" mat1 = self.UX mat2 = np.eye(3, dtype=complex) mat21 = np.kron(mat2, mat1) op21 = Operator(mat2).tensor(Operator(mat1)) self.assertEqual(op21.dim, (6, 6)) assert_allclose(op21.data, Operator(mat21).data) mat12 = np.kron(mat1, mat2) op12 = Operator(mat1).tensor(Operator(mat2)) self.assertEqual(op12.dim, (6, 6)) assert_allclose(op12.data, Operator(mat12).data) def test_power_except(self): """Test power method raises exceptions if not square.""" op = Operator(self.rand_matrix(2, 3)) # Non-integer power raises error self.assertRaises(QiskitError, op.power, 0.5) def test_add(self): """Test add method.""" mat1 = self.rand_matrix(4, 4) mat2 = self.rand_matrix(4, 4) op1 = Operator(mat1) op2 = Operator(mat2) self.assertEqual(op1._add(op2), Operator(mat1 + mat2)) self.assertEqual(op1 + op2, Operator(mat1 + mat2)) self.assertEqual(op1 - op2, Operator(mat1 - mat2)) def test_add_except(self): """Test add method raises exceptions.""" op1 = Operator(self.rand_matrix(2, 2)) op2 = Operator(self.rand_matrix(3, 3)) self.assertRaises(QiskitError, op1._add, op2) def test_add_qargs(self): """Test add method with qargs.""" mat = self.rand_matrix(8, 8) mat0 = self.rand_matrix(2, 2) mat1 = self.rand_matrix(2, 2) op = Operator(mat) op0 = Operator(mat0) op01 = Operator(np.kron(mat1, mat0)) with self.subTest(msg="qargs=[0]"): value = op + op0([0]) target = op + Operator(np.kron(np.eye(4), mat0)) self.assertEqual(value, target) with self.subTest(msg="qargs=[1]"): value = op + op0([1]) target = op + Operator(np.kron(np.kron(np.eye(2), mat0), np.eye(2))) self.assertEqual(value, target) with self.subTest(msg="qargs=[2]"): value = op + op0([2]) target = op + Operator(np.kron(mat0, np.eye(4))) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 1]"): value = op + op01([0, 1]) target = op + Operator(np.kron(np.eye(2), np.kron(mat1, mat0))) self.assertEqual(value, target) with self.subTest(msg="qargs=[1, 0]"): value = op + op01([1, 0]) target = op + Operator(np.kron(np.eye(2), np.kron(mat0, mat1))) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 2]"): value = op + op01([0, 2]) target = op + Operator(np.kron(mat1, np.kron(np.eye(2), mat0))) self.assertEqual(value, target) with self.subTest(msg="qargs=[2, 0]"): value = op + op01([2, 0]) target = op + Operator(np.kron(mat0, np.kron(np.eye(2), mat1))) self.assertEqual(value, target) def test_sub_qargs(self): """Test subtract method with qargs.""" mat = self.rand_matrix(8, 8) mat0 = self.rand_matrix(2, 2) mat1 = self.rand_matrix(2, 2) op = Operator(mat) op0 = Operator(mat0) op01 = Operator(np.kron(mat1, mat0)) with self.subTest(msg="qargs=[0]"): value = op - op0([0]) target = op - Operator(np.kron(np.eye(4), mat0)) self.assertEqual(value, target) with self.subTest(msg="qargs=[1]"): value = op - op0([1]) target = op - Operator(np.kron(np.kron(np.eye(2), mat0), np.eye(2))) self.assertEqual(value, target) with self.subTest(msg="qargs=[2]"): value = op - op0([2]) target = op - Operator(np.kron(mat0, np.eye(4))) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 1]"): value = op - op01([0, 1]) target = op - Operator(np.kron(np.eye(2), np.kron(mat1, mat0))) self.assertEqual(value, target) with self.subTest(msg="qargs=[1, 0]"): value = op - op01([1, 0]) target = op - Operator(np.kron(np.eye(2), np.kron(mat0, mat1))) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 2]"): value = op - op01([0, 2]) target = op - Operator(np.kron(mat1, np.kron(np.eye(2), mat0))) self.assertEqual(value, target) with self.subTest(msg="qargs=[2, 0]"): value = op - op01([2, 0]) target = op - Operator(np.kron(mat0, np.kron(np.eye(2), mat1))) self.assertEqual(value, target) def test_multiply(self): """Test multiply method.""" mat = self.rand_matrix(4, 4) val = np.exp(5j) op = Operator(mat) self.assertEqual(op._multiply(val), Operator(val * mat)) self.assertEqual(val * op, Operator(val * mat)) self.assertEqual(op * val, Operator(mat * val)) def test_multiply_except(self): """Test multiply method raises exceptions.""" op = Operator(self.rand_matrix(2, 2)) self.assertRaises(QiskitError, op._multiply, "s") self.assertRaises(QiskitError, op.__rmul__, "s") self.assertRaises(QiskitError, op._multiply, op) self.assertRaises(QiskitError, op.__rmul__, op) def test_negate(self): """Test negate method""" mat = self.rand_matrix(4, 4) op = Operator(mat) self.assertEqual(-op, Operator(-1 * mat)) def test_equiv(self): """Test negate method""" mat = np.diag([1, np.exp(1j * np.pi / 2)]) phase = np.exp(-1j * np.pi / 4) op = Operator(mat) self.assertTrue(op.equiv(phase * mat)) self.assertTrue(op.equiv(Operator(phase * mat))) self.assertFalse(op.equiv(2 * mat)) def test_reverse_qargs(self): """Test reverse_qargs method""" circ1 = QFT(5) circ2 = circ1.reverse_bits() state1 = Operator(circ1) state2 = Operator(circ2) self.assertEqual(state1.reverse_qargs(), state2) def test_drawings(self): """Test draw method""" qc1 = QFT(5) op = Operator.from_circuit(qc1) with self.subTest(msg="str(operator)"): str(op) for drawtype in ["repr", "text", "latex_source"]: with self.subTest(msg=f"draw('{drawtype}')"): op.draw(drawtype) with self.subTest(msg=" draw('latex')"): op.draw("latex") def test_from_circuit_constructor_no_layout(self): """Test initialization from a circuit using the from_circuit constructor.""" # Test tensor product of 1-qubit gates circuit = QuantumCircuit(3) circuit.h(0) circuit.x(1) circuit.ry(np.pi / 2, 2) op = Operator.from_circuit(circuit) y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]]) target = np.kron(y90, np.kron(self.UX, self.UH)) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) # Test decomposition of Controlled-Phase gate lam = np.pi / 4 circuit = QuantumCircuit(2) circuit.cp(lam, 0, 1) op = Operator.from_circuit(circuit) target = np.diag([1, 1, 1, np.exp(1j * lam)]) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) # Test decomposition of controlled-H gate circuit = QuantumCircuit(2) circuit.ch(0, 1) op = Operator.from_circuit(circuit) target = np.kron(self.UI, np.diag([1, 0])) + np.kron(self.UH, np.diag([0, 1])) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) def test_from_circuit_constructor_reverse_embedded_layout(self): """Test initialization from a circuit with an embedded reverse layout.""" # Test tensor product of 1-qubit gates circuit = QuantumCircuit(3) circuit.h(2) circuit.x(1) circuit.ry(np.pi / 2, 0) circuit._layout = TranspileLayout( Layout({circuit.qubits[2]: 0, circuit.qubits[1]: 1, circuit.qubits[0]: 2}), {qubit: index for index, qubit in enumerate(circuit.qubits)}, ) op = Operator.from_circuit(circuit) y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]]) target = np.kron(y90, np.kron(self.UX, self.UH)) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) # Test decomposition of Controlled-Phase gate lam = np.pi / 4 circuit = QuantumCircuit(2) circuit.cp(lam, 1, 0) circuit._layout = TranspileLayout( Layout({circuit.qubits[1]: 0, circuit.qubits[0]: 1}), {qubit: index for index, qubit in enumerate(circuit.qubits)}, ) op = Operator.from_circuit(circuit) target = np.diag([1, 1, 1, np.exp(1j * lam)]) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) # Test decomposition of controlled-H gate circuit = QuantumCircuit(2) circuit.ch(1, 0) circuit._layout = TranspileLayout( Layout({circuit.qubits[1]: 0, circuit.qubits[0]: 1}), {qubit: index for index, qubit in enumerate(circuit.qubits)}, ) op = Operator.from_circuit(circuit) target = np.kron(self.UI, np.diag([1, 0])) + np.kron(self.UH, np.diag([0, 1])) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) def test_from_circuit_constructor_reverse_embedded_layout_from_transpile(self): """Test initialization from a circuit with an embedded final layout.""" # Test tensor product of 1-qubit gates circuit = QuantumCircuit(3) circuit.h(0) circuit.x(1) circuit.ry(np.pi / 2, 2) output = transpile(circuit, initial_layout=[2, 1, 0]) op = Operator.from_circuit(output) y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]]) target = np.kron(y90, np.kron(self.UX, self.UH)) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) def test_from_circuit_constructor_reverse_embedded_layout_from_transpile_with_registers(self): """Test initialization from a circuit with an embedded final layout.""" # Test tensor product of 1-qubit gates qr = QuantumRegister(3, name="test_reg") circuit = QuantumCircuit(qr) circuit.h(0) circuit.x(1) circuit.ry(np.pi / 2, 2) output = transpile(circuit, initial_layout=[2, 1, 0]) op = Operator.from_circuit(output) y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]]) target = np.kron(y90, np.kron(self.UX, self.UH)) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) def test_from_circuit_constructor_reverse_embedded_layout_and_final_layout(self): """Test initialization from a circuit with an embedded final layout.""" # Test tensor product of 1-qubit gates qr = QuantumRegister(3, name="test_reg") circuit = QuantumCircuit(qr) circuit.h(2) circuit.x(1) circuit.ry(np.pi / 2, 0) circuit._layout = TranspileLayout( Layout({circuit.qubits[2]: 0, circuit.qubits[1]: 1, circuit.qubits[0]: 2}), {qubit: index for index, qubit in enumerate(circuit.qubits)}, Layout({circuit.qubits[0]: 1, circuit.qubits[1]: 2, circuit.qubits[2]: 0}), ) circuit.swap(0, 1) circuit.swap(1, 2) op = Operator.from_circuit(circuit) y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]]) target = np.kron(y90, np.kron(self.UX, self.UH)) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) def test_from_circuit_constructor_reverse_embedded_layout_and_manual_final_layout(self): """Test initialization from a circuit with an embedded final layout.""" # Test tensor product of 1-qubit gates qr = QuantumRegister(3, name="test_reg") circuit = QuantumCircuit(qr) circuit.h(2) circuit.x(1) circuit.ry(np.pi / 2, 0) circuit._layout = TranspileLayout( Layout({circuit.qubits[2]: 0, circuit.qubits[1]: 1, circuit.qubits[0]: 2}), {qubit: index for index, qubit in enumerate(circuit.qubits)}, ) final_layout = Layout({circuit.qubits[0]: 1, circuit.qubits[1]: 2, circuit.qubits[2]: 0}) circuit.swap(0, 1) circuit.swap(1, 2) op = Operator.from_circuit(circuit, final_layout=final_layout) y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]]) target = np.kron(y90, np.kron(self.UX, self.UH)) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) def test_from_circuit_constructor_reverse_embedded_layout_ignore_set_layout(self): """Test initialization from a circuit with an ignored embedded reverse layout.""" # Test tensor product of 1-qubit gates circuit = QuantumCircuit(3) circuit.h(2) circuit.x(1) circuit.ry(np.pi / 2, 0) circuit._layout = TranspileLayout( Layout({circuit.qubits[2]: 0, circuit.qubits[1]: 1, circuit.qubits[0]: 2}), {qubit: index for index, qubit in enumerate(circuit.qubits)}, ) op = Operator.from_circuit(circuit, ignore_set_layout=True).reverse_qargs() y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]]) target = np.kron(y90, np.kron(self.UX, self.UH)) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) # Test decomposition of Controlled-Phase gate lam = np.pi / 4 circuit = QuantumCircuit(2) circuit.cp(lam, 1, 0) circuit._layout = TranspileLayout( Layout({circuit.qubits[1]: 0, circuit.qubits[0]: 1}), {qubit: index for index, qubit in enumerate(circuit.qubits)}, ) op = Operator.from_circuit(circuit, ignore_set_layout=True).reverse_qargs() target = np.diag([1, 1, 1, np.exp(1j * lam)]) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) # Test decomposition of controlled-H gate circuit = QuantumCircuit(2) circuit.ch(1, 0) circuit._layout = TranspileLayout( Layout({circuit.qubits[1]: 0, circuit.qubits[0]: 1}), {qubit: index for index, qubit in enumerate(circuit.qubits)}, ) op = Operator.from_circuit(circuit, ignore_set_layout=True).reverse_qargs() target = np.kron(self.UI, np.diag([1, 0])) + np.kron(self.UH, np.diag([0, 1])) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) def test_from_circuit_constructor_reverse_user_specified_layout(self): """Test initialization from a circuit with a user specified reverse layout.""" # Test tensor product of 1-qubit gates circuit = QuantumCircuit(3) circuit.h(2) circuit.x(1) circuit.ry(np.pi / 2, 0) layout = Layout({circuit.qubits[2]: 0, circuit.qubits[1]: 1, circuit.qubits[0]: 2}) op = Operator.from_circuit(circuit, layout=layout) y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]]) target = np.kron(y90, np.kron(self.UX, self.UH)) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) # Test decomposition of Controlled-Phase gate lam = np.pi / 4 circuit = QuantumCircuit(2) circuit.cp(lam, 1, 0) layout = Layout({circuit.qubits[1]: 0, circuit.qubits[0]: 1}) op = Operator.from_circuit(circuit, layout=layout) target = np.diag([1, 1, 1, np.exp(1j * lam)]) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) # Test decomposition of controlled-H gate circuit = QuantumCircuit(2) circuit.ch(1, 0) layout = Layout({circuit.qubits[1]: 0, circuit.qubits[0]: 1}) op = Operator.from_circuit(circuit, layout=layout) target = np.kron(self.UI, np.diag([1, 0])) + np.kron(self.UH, np.diag([0, 1])) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) def test_from_circuit_constructor_ghz_out_of_order_layout(self): """Test an out of order ghz state with a layout set.""" circuit = QuantumCircuit(5) circuit.h(3) circuit.cx(3, 4) circuit.cx(3, 2) circuit.cx(3, 0) circuit.cx(3, 1) circuit._layout = TranspileLayout( Layout( { circuit.qubits[3]: 0, circuit.qubits[4]: 1, circuit.qubits[2]: 2, circuit.qubits[0]: 3, circuit.qubits[1]: 4, } ), {qubit: index for index, qubit in enumerate(circuit.qubits)}, ) result = Operator.from_circuit(circuit) expected = QuantumCircuit(5) expected.h(0) expected.cx(0, 1) expected.cx(0, 2) expected.cx(0, 3) expected.cx(0, 4) expected_op = Operator(expected) self.assertTrue(expected_op.equiv(result)) def test_from_circuit_empty_circuit_empty_layout(self): """Test an out of order ghz state with a layout set.""" circuit = QuantumCircuit() circuit._layout = TranspileLayout(Layout(), {}) op = Operator.from_circuit(circuit) self.assertEqual(Operator([1]), op) def test_from_circuit_constructor_empty_layout(self): """Test an out of order ghz state with a layout set.""" circuit = QuantumCircuit(2) circuit.h(0) circuit.cx(0, 1) layout = Layout() with self.assertRaises(IndexError): Operator.from_circuit(circuit, layout=layout) def test_compose_scalar(self): """Test that composition works with a scalar-valued operator over no qubits.""" base = Operator(np.eye(2, dtype=np.complex128)) scalar = Operator(np.array([[-1.0 + 0.0j]])) composed = base.compose(scalar, qargs=[]) self.assertEqual(composed, Operator(-np.eye(2, dtype=np.complex128))) def test_compose_scalar_op(self): """Test that composition works with an explicit scalar operator over no qubits.""" base = Operator(np.eye(2, dtype=np.complex128)) scalar = ScalarOp(coeff=-1.0 + 0.0j) composed = base.compose(scalar, qargs=[]) self.assertEqual(composed, Operator(-np.eye(2, dtype=np.complex128))) def test_from_circuit_single_flat_default_register_transpiled(self): """Test a transpiled circuit with layout set from default register.""" circuit = QuantumCircuit(5) circuit.h(3) circuit.cx(3, 4) circuit.cx(3, 2) circuit.cx(3, 0) circuit.cx(3, 1) init_layout = Layout( { circuit.qubits[0]: 3, circuit.qubits[1]: 4, circuit.qubits[2]: 1, circuit.qubits[3]: 2, circuit.qubits[4]: 0, } ) tqc = transpile(circuit, initial_layout=init_layout) result = Operator.from_circuit(tqc) self.assertTrue(Operator.from_circuit(circuit).equiv(result)) def test_from_circuit_loose_bits_transpiled(self): """Test a transpiled circuit with layout set from loose bits.""" 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) init_layout = Layout( { circuit.qubits[0]: 3, circuit.qubits[1]: 4, circuit.qubits[2]: 1, circuit.qubits[3]: 2, circuit.qubits[4]: 0, } ) tqc = transpile(circuit, initial_layout=init_layout) result = Operator.from_circuit(tqc) self.assertTrue(Operator(circuit).equiv(result)) def test_from_circuit_multiple_registers_bits_transpiled(self): """Test a transpiled circuit with layout set from loose bits.""" regs = [QuantumRegister(1, name=f"custom_reg-{i}") for i in range(5)] circuit = QuantumCircuit() for reg in regs: circuit.add_register(reg) circuit.h(3) circuit.cx(3, 4) circuit.cx(3, 2) circuit.cx(3, 0) circuit.cx(3, 1) tqc = transpile(circuit, initial_layout=[3, 4, 1, 2, 0]) result = Operator.from_circuit(tqc) self.assertTrue(Operator(circuit).equiv(result)) def test_from_circuit_single_flat_custom_register_transpiled(self): """Test a transpiled circuit with layout set from loose bits.""" circuit = QuantumCircuit(QuantumRegister(5, name="custom_reg")) circuit.h(3) circuit.cx(3, 4) circuit.cx(3, 2) circuit.cx(3, 0) circuit.cx(3, 1) tqc = transpile(circuit, initial_layout=[3, 4, 1, 2, 0]) result = Operator.from_circuit(tqc) self.assertTrue(Operator(circuit).equiv(result)) def test_from_circuit_mixed_reg_loose_bits_transpiled(self): """Test a transpiled circuit with layout set from loose bits.""" bits = [Qubit(), Qubit()] circuit = QuantumCircuit() circuit.add_bits(bits) circuit.add_register(QuantumRegister(3, name="a_reg")) circuit.h(3) circuit.cx(3, 4) circuit.cx(3, 2) circuit.cx(3, 0) circuit.cx(3, 1) init_layout = Layout( { circuit.qubits[0]: 3, circuit.qubits[1]: 4, circuit.qubits[2]: 1, circuit.qubits[3]: 2, circuit.qubits[4]: 0, } ) tqc = transpile(circuit, initial_layout=init_layout) result = Operator.from_circuit(tqc) self.assertTrue(Operator(circuit).equiv(result)) def test_apply_permutation_back(self): """Test applying permutation to the operator, where the operator is applied first and the permutation second.""" op = Operator(self.rand_matrix(64, 64)) pattern = [1, 2, 0, 3, 5, 4] # Consider several methods of computing this operator and show # they all lead to the same result. # Compose the operator with the operator constructed from the # permutation circuit. op2 = op.copy() perm_op = Operator(Permutation(6, pattern)) op2 &= perm_op # Compose the operator with the operator constructed from the # permutation gate. op3 = op.copy() perm_op = Operator(PermutationGate(pattern)) op3 &= perm_op # Modify the operator using apply_permutation method. op4 = op.copy() op4 = op4.apply_permutation(pattern, front=False) self.assertEqual(op2, op3) self.assertEqual(op2, op4) def test_apply_permutation_front(self): """Test applying permutation to the operator, where the permutation is applied first and the operator second""" op = Operator(self.rand_matrix(64, 64)) pattern = [1, 2, 0, 3, 5, 4] # Consider several methods of computing this operator and show # they all lead to the same result. # Compose the operator with the operator constructed from the # permutation circuit. op2 = op.copy() perm_op = Operator(Permutation(6, pattern)) op2 = perm_op & op2 # Compose the operator with the operator constructed from the # permutation gate. op3 = op.copy() perm_op = Operator(PermutationGate(pattern)) op3 = perm_op & op3 # Modify the operator using apply_permutation method. op4 = op.copy() op4 = op4.apply_permutation(pattern, front=True) self.assertEqual(op2, op3) self.assertEqual(op2, op4) def test_apply_permutation_qudits_back(self): """Test applying permutation to the operator with heterogeneous qudit spaces, where the operator O is applied first and the permutation P second. The matrix of the resulting operator is the product [P][O] and corresponds to suitably permuting the rows of O's matrix. """ mat = np.array(range(6 * 6)).reshape((6, 6)) op = Operator(mat, input_dims=(2, 3), output_dims=(2, 3)) perm = [1, 0] actual = op.apply_permutation(perm, front=False) # Rows of mat are ordered to 00, 01, 02, 10, 11, 12; # perm maps these to 00, 10, 20, 01, 11, 21, # while the default ordering is 00, 01, 10, 11, 20, 21. permuted_mat = mat.copy()[[0, 2, 4, 1, 3, 5]] expected = Operator(permuted_mat, input_dims=(2, 3), output_dims=(3, 2)) self.assertEqual(actual, expected) def test_apply_permutation_qudits_front(self): """Test applying permutation to the operator with heterogeneous qudit spaces, where the permutation P is applied first and the operator O is applied second. The matrix of the resulting operator is the product [O][P] and corresponds to suitably permuting the columns of O's matrix. """ mat = np.array(range(6 * 6)).reshape((6, 6)) op = Operator(mat, input_dims=(2, 3), output_dims=(2, 3)) perm = [1, 0] actual = op.apply_permutation(perm, front=True) # Columns of mat are ordered to 00, 01, 02, 10, 11, 12; # perm maps these to 00, 10, 20, 01, 11, 21, # while the default ordering is 00, 01, 10, 11, 20, 21. permuted_mat = mat.copy()[:, [0, 2, 4, 1, 3, 5]] expected = Operator(permuted_mat, input_dims=(3, 2), output_dims=(2, 3)) self.assertEqual(actual, expected) @combine( dims=((2, 3, 4, 5), (5, 2, 4, 3), (3, 5, 2, 4), (5, 3, 4, 2), (4, 5, 2, 3), (4, 3, 2, 5)) ) def test_reverse_qargs_as_apply_permutation(self, dims): """Test reversing qargs by pre- and post-composing with reversal permutation. """ perm = [3, 2, 1, 0] op = Operator( np.array(range(120 * 120)).reshape((120, 120)), input_dims=dims, output_dims=dims ) op2 = op.reverse_qargs() op3 = op.apply_permutation(perm, front=True).apply_permutation(perm, front=False) self.assertEqual(op2, op3) def test_apply_permutation_exceptions(self): """Checks that applying permutation raises an error when dimensions do not match.""" op = Operator( np.array(range(24 * 30)).reshape((24, 30)), input_dims=(6, 5), output_dims=(2, 3, 4) ) with self.assertRaises(QiskitError): op.apply_permutation([1, 0], front=False) with self.assertRaises(QiskitError): op.apply_permutation([2, 1, 0], front=True) def test_apply_permutation_dimensions(self): """Checks the dimensions of the operator after applying permutation.""" op = Operator( np.array(range(24 * 30)).reshape((24, 30)), input_dims=(6, 5), output_dims=(2, 3, 4) ) op2 = op.apply_permutation([1, 2, 0], front=False) self.assertEqual(op2.output_dims(), (4, 2, 3)) op = Operator( np.array(range(24 * 30)).reshape((30, 24)), input_dims=(2, 3, 4), output_dims=(6, 5) ) op2 = op.apply_permutation([2, 0, 1], front=True) self.assertEqual(op2.input_dims(), (4, 2, 3)) if __name__ == "__main__": unittest.main()
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# 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 Chi quantum channel representation class.""" import copy import unittest import numpy as np from numpy.testing import assert_allclose from qiskit import QiskitError from qiskit.quantum_info.states import DensityMatrix from qiskit.quantum_info.operators.channel import Chi from .channel_test_case import ChannelTestCase class TestChi(ChannelTestCase): """Tests for Chi channel representation.""" def test_init(self): """Test initialization""" mat4 = np.eye(4) / 2.0 chan = Chi(mat4) assert_allclose(chan.data, mat4) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(chan.num_qubits, 1) mat16 = np.eye(16) / 4 chan = Chi(mat16) assert_allclose(chan.data, mat16) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(chan.num_qubits, 2) # Wrong input or output dims should raise exception self.assertRaises(QiskitError, Chi, mat16, input_dims=2, output_dims=4) # Non multi-qubit dimensions should raise exception self.assertRaises(QiskitError, Chi, np.eye(6) / 2, input_dims=3, output_dims=2) def test_circuit_init(self): """Test initialization from a circuit.""" circuit, target = self.simple_circuit_no_measure() op = Chi(circuit) target = Chi(target) self.assertEqual(op, target) def test_circuit_init_except(self): """Test initialization from circuit with measure raises exception.""" circuit = self.simple_circuit_with_measure() self.assertRaises(QiskitError, Chi, circuit) def test_equal(self): """Test __eq__ method""" mat = self.rand_matrix(4, 4, real=True) self.assertEqual(Chi(mat), Chi(mat)) def test_copy(self): """Test copy method""" mat = np.eye(4) with self.subTest("Deep copy"): orig = Chi(mat) cpy = orig.copy() cpy._data[0, 0] = 0.0 self.assertFalse(cpy == orig) with self.subTest("Shallow copy"): orig = Chi(mat) clone = copy.copy(orig) clone._data[0, 0] = 0.0 self.assertTrue(clone == orig) def test_is_cptp(self): """Test is_cptp method.""" self.assertTrue(Chi(self.depol_chi(0.25)).is_cptp()) # Non-CPTP should return false self.assertFalse(Chi(1.25 * self.chiI - 0.25 * self.depol_chi(1)).is_cptp()) def test_compose_except(self): """Test compose different dimension exception""" self.assertRaises(QiskitError, Chi(np.eye(4)).compose, Chi(np.eye(16))) self.assertRaises(QiskitError, Chi(np.eye(4)).compose, 2) def test_compose(self): """Test compose method.""" # Random input test state rho = DensityMatrix(self.rand_rho(2)) # UnitaryChannel evolution chan1 = Chi(self.chiX) chan2 = Chi(self.chiY) chan = chan1.compose(chan2) target = rho.evolve(Chi(self.chiZ)) output = rho.evolve(chan) self.assertEqual(output, target) # 50% depolarizing channel chan1 = Chi(self.depol_chi(0.5)) chan = chan1.compose(chan1) target = rho.evolve(Chi(self.depol_chi(0.75))) output = rho.evolve(chan) self.assertEqual(output, target) # Compose random chi1 = self.rand_matrix(4, 4, real=True) chi2 = self.rand_matrix(4, 4, real=True) chan1 = Chi(chi1, input_dims=2, output_dims=2) chan2 = Chi(chi2, input_dims=2, output_dims=2) target = rho.evolve(chan1).evolve(chan2) chan = chan1.compose(chan2) output = rho.evolve(chan) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(output, target) chan = chan1 & chan2 output = rho.evolve(chan) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(output, target) def test_dot(self): """Test dot method.""" # Random input test state rho = DensityMatrix(self.rand_rho(2)) # UnitaryChannel evolution chan1 = Chi(self.chiX) chan2 = Chi(self.chiY) target = rho.evolve(Chi(self.chiZ)) output = rho.evolve(chan2.dot(chan1)) self.assertEqual(output, target) # Compose random chi1 = self.rand_matrix(4, 4, real=True) chi2 = self.rand_matrix(4, 4, real=True) chan1 = Chi(chi1, input_dims=2, output_dims=2) chan2 = Chi(chi2, input_dims=2, output_dims=2) target = rho.evolve(chan1).evolve(chan2) chan = chan2.dot(chan1) output = rho.evolve(chan) self.assertEqual(output, target) chan = chan2 @ chan1 output = rho.evolve(chan) self.assertEqual(output, target) def test_compose_front(self): """Test front compose method.""" # Random input test state rho = DensityMatrix(self.rand_rho(2)) # UnitaryChannel evolution chan1 = Chi(self.chiX) chan2 = Chi(self.chiY) chan = chan2.compose(chan1, front=True) target = rho.evolve(Chi(self.chiZ)) output = rho.evolve(chan) self.assertEqual(output, target) # Compose random chi1 = self.rand_matrix(4, 4, real=True) chi2 = self.rand_matrix(4, 4, real=True) chan1 = Chi(chi1, input_dims=2, output_dims=2) chan2 = Chi(chi2, input_dims=2, output_dims=2) target = rho.evolve(chan1).evolve(chan2) chan = chan2.compose(chan1, front=True) output = rho.evolve(chan) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(output, target) def test_expand(self): """Test expand method.""" # Pauli channels paulis = [self.chiI, self.chiX, self.chiY, self.chiZ] targs = 4 * np.eye(16) # diagonals of Pauli channel Chi mats for i, chi1 in enumerate(paulis): for j, chi2 in enumerate(paulis): chan1 = Chi(chi1) chan2 = Chi(chi2) chan = chan1.expand(chan2) # Target for diagonal Pauli channel targ = Chi(np.diag(targs[i + 4 * j])) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(chan, targ) # Completely depolarizing rho = DensityMatrix(np.diag([1, 0, 0, 0])) chan_dep = Chi(self.depol_chi(1)) chan = chan_dep.expand(chan_dep) target = DensityMatrix(np.diag([1, 1, 1, 1]) / 4) output = rho.evolve(chan) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(output, target) def test_tensor(self): """Test tensor method.""" # Pauli channels paulis = [self.chiI, self.chiX, self.chiY, self.chiZ] targs = 4 * np.eye(16) # diagonals of Pauli channel Chi mats for i, chi1 in enumerate(paulis): for j, chi2 in enumerate(paulis): chan1 = Chi(chi1) chan2 = Chi(chi2) chan = chan2.tensor(chan1) # Target for diagonal Pauli channel targ = Chi(np.diag(targs[i + 4 * j])) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(chan, targ) # Test overload chan = chan2 ^ chan1 self.assertEqual(chan.dim, (4, 4)) self.assertEqual(chan, targ) # Completely depolarizing rho = DensityMatrix(np.diag([1, 0, 0, 0])) chan_dep = Chi(self.depol_chi(1)) chan = chan_dep.tensor(chan_dep) target = DensityMatrix(np.diag([1, 1, 1, 1]) / 4) output = rho.evolve(chan) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(output, target) # Test operator overload chan = chan_dep ^ chan_dep output = rho.evolve(chan) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(output, target) def test_power(self): """Test power method.""" # 10% depolarizing channel p_id = 0.9 depol = Chi(self.depol_chi(1 - p_id)) # Compose 3 times p_id3 = p_id**3 chan3 = depol.power(3) targ3 = Chi(self.depol_chi(1 - p_id3)) self.assertEqual(chan3, targ3) def test_add(self): """Test add method.""" mat1 = 0.5 * self.chiI mat2 = 0.5 * self.depol_chi(1) chan1 = Chi(mat1) chan2 = Chi(mat2) targ = Chi(mat1 + mat2) self.assertEqual(chan1._add(chan2), targ) self.assertEqual(chan1 + chan2, targ) targ = Chi(mat1 - mat2) self.assertEqual(chan1 - chan2, targ) def test_add_qargs(self): """Test add method with qargs.""" mat = self.rand_matrix(8**2, 8**2) mat0 = self.rand_matrix(4, 4) mat1 = self.rand_matrix(4, 4) op = Chi(mat) op0 = Chi(mat0) op1 = Chi(mat1) op01 = op1.tensor(op0) eye = Chi(self.chiI) with self.subTest(msg="qargs=[0]"): value = op + op0([0]) target = op + eye.tensor(eye).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[1]"): value = op + op0([1]) target = op + eye.tensor(op0).tensor(eye) self.assertEqual(value, target) with self.subTest(msg="qargs=[2]"): value = op + op0([2]) target = op + op0.tensor(eye).tensor(eye) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 1]"): value = op + op01([0, 1]) target = op + eye.tensor(op1).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[1, 0]"): value = op + op01([1, 0]) target = op + eye.tensor(op0).tensor(op1) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 2]"): value = op + op01([0, 2]) target = op + op1.tensor(eye).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[2, 0]"): value = op + op01([2, 0]) target = op + op0.tensor(eye).tensor(op1) self.assertEqual(value, target) def test_sub_qargs(self): """Test subtract method with qargs.""" mat = self.rand_matrix(8**2, 8**2) mat0 = self.rand_matrix(4, 4) mat1 = self.rand_matrix(4, 4) op = Chi(mat) op0 = Chi(mat0) op1 = Chi(mat1) op01 = op1.tensor(op0) eye = Chi(self.chiI) with self.subTest(msg="qargs=[0]"): value = op - op0([0]) target = op - eye.tensor(eye).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[1]"): value = op - op0([1]) target = op - eye.tensor(op0).tensor(eye) self.assertEqual(value, target) with self.subTest(msg="qargs=[2]"): value = op - op0([2]) target = op - op0.tensor(eye).tensor(eye) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 1]"): value = op - op01([0, 1]) target = op - eye.tensor(op1).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[1, 0]"): value = op - op01([1, 0]) target = op - eye.tensor(op0).tensor(op1) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 2]"): value = op - op01([0, 2]) target = op - op1.tensor(eye).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[2, 0]"): value = op - op01([2, 0]) target = op - op0.tensor(eye).tensor(op1) self.assertEqual(value, target) def test_add_except(self): """Test add method raises exceptions.""" chan1 = Chi(self.chiI) chan2 = Chi(np.eye(16)) self.assertRaises(QiskitError, chan1._add, chan2) self.assertRaises(QiskitError, chan1._add, 5) def test_multiply(self): """Test multiply method.""" chan = Chi(self.chiI) val = 0.5 targ = Chi(val * self.chiI) self.assertEqual(chan._multiply(val), targ) self.assertEqual(val * chan, targ) targ = Chi(self.chiI * val) self.assertEqual(chan * val, targ) def test_multiply_except(self): """Test multiply method raises exceptions.""" chan = Chi(self.chiI) self.assertRaises(QiskitError, chan._multiply, "s") self.assertRaises(QiskitError, chan.__rmul__, "s") self.assertRaises(QiskitError, chan._multiply, chan) self.assertRaises(QiskitError, chan.__rmul__, chan) def test_negate(self): """Test negate method""" chan = Chi(self.chiI) targ = Chi(-self.chiI) self.assertEqual(-chan, targ) if __name__ == "__main__": unittest.main()
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# 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 """Tests for Choi quantum channel representation class.""" import copy import unittest import numpy as np from numpy.testing import assert_allclose from qiskit import QiskitError from qiskit.quantum_info.states import DensityMatrix from qiskit.quantum_info.operators.channel import Choi from .channel_test_case import ChannelTestCase class TestChoi(ChannelTestCase): """Tests for Choi channel representation.""" def test_init(self): """Test initialization""" mat4 = np.eye(4) / 2.0 chan = Choi(mat4) assert_allclose(chan.data, mat4) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(chan.num_qubits, 1) mat8 = np.eye(8) / 2.0 chan = Choi(mat8, input_dims=4) assert_allclose(chan.data, mat8) self.assertEqual(chan.dim, (4, 2)) self.assertIsNone(chan.num_qubits) chan = Choi(mat8, input_dims=2) assert_allclose(chan.data, mat8) self.assertEqual(chan.dim, (2, 4)) self.assertIsNone(chan.num_qubits) mat16 = np.eye(16) / 4 chan = Choi(mat16) assert_allclose(chan.data, mat16) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(chan.num_qubits, 2) # Wrong input or output dims should raise exception self.assertRaises(QiskitError, Choi, mat8, input_dims=[4], output_dims=[4]) def test_circuit_init(self): """Test initialization from a circuit.""" circuit, target = self.simple_circuit_no_measure() op = Choi(circuit) target = Choi(target) self.assertEqual(op, target) def test_circuit_init_except(self): """Test initialization from circuit with measure raises exception.""" circuit = self.simple_circuit_with_measure() self.assertRaises(QiskitError, Choi, circuit) def test_equal(self): """Test __eq__ method""" mat = self.rand_matrix(4, 4) self.assertEqual(Choi(mat), Choi(mat)) def test_copy(self): """Test copy method""" mat = np.eye(2) with self.subTest("Deep copy"): orig = Choi(mat) cpy = orig.copy() cpy._data[0, 0] = 0.0 self.assertFalse(cpy == orig) with self.subTest("Shallow copy"): orig = Choi(mat) clone = copy.copy(orig) clone._data[0, 0] = 0.0 self.assertTrue(clone == orig) def test_clone(self): """Test clone method""" mat = np.eye(4) orig = Choi(mat) clone = copy.copy(orig) clone._data[0, 0] = 0.0 self.assertTrue(clone == orig) def test_is_cptp(self): """Test is_cptp method.""" self.assertTrue(Choi(self.depol_choi(0.25)).is_cptp()) # Non-CPTP should return false self.assertFalse(Choi(1.25 * self.choiI - 0.25 * self.depol_choi(1)).is_cptp()) def test_conjugate(self): """Test conjugate method.""" # Test channel measures in Z basis and prepares in Y basis # Zp -> Yp, Zm -> Ym Zp, Zm = np.diag([1, 0]), np.diag([0, 1]) Yp, Ym = np.array([[1, -1j], [1j, 1]]) / 2, np.array([[1, 1j], [-1j, 1]]) / 2 chan = Choi(np.kron(Zp, Yp) + np.kron(Zm, Ym)) # Conjugate channel swaps Y-basis states targ = Choi(np.kron(Zp, Ym) + np.kron(Zm, Yp)) chan_conj = chan.conjugate() self.assertEqual(chan_conj, targ) def test_transpose(self): """Test transpose method.""" # Test channel measures in Z basis and prepares in Y basis # Zp -> Yp, Zm -> Ym Zp, Zm = np.diag([1, 0]), np.diag([0, 1]) Yp, Ym = np.array([[1, -1j], [1j, 1]]) / 2, np.array([[1, 1j], [-1j, 1]]) / 2 chan = Choi(np.kron(Zp, Yp) + np.kron(Zm, Ym)) # Transpose channel swaps basis targ = Choi(np.kron(Yp, Zp) + np.kron(Ym, Zm)) chan_t = chan.transpose() self.assertEqual(chan_t, targ) def test_adjoint(self): """Test adjoint method.""" # Test channel measures in Z basis and prepares in Y basis # Zp -> Yp, Zm -> Ym Zp, Zm = np.diag([1, 0]), np.diag([0, 1]) Yp, Ym = np.array([[1, -1j], [1j, 1]]) / 2, np.array([[1, 1j], [-1j, 1]]) / 2 chan = Choi(np.kron(Zp, Yp) + np.kron(Zm, Ym)) # Ajoint channel swaps Y-basis elements and Z<->Y bases targ = Choi(np.kron(Ym, Zp) + np.kron(Yp, Zm)) chan_adj = chan.adjoint() self.assertEqual(chan_adj, targ) def test_compose_except(self): """Test compose different dimension exception""" self.assertRaises(QiskitError, Choi(np.eye(4)).compose, Choi(np.eye(8))) self.assertRaises(QiskitError, Choi(np.eye(4)).compose, 2) def test_compose(self): """Test compose method.""" # UnitaryChannel evolution chan1 = Choi(self.choiX) chan2 = Choi(self.choiY) chan = chan1.compose(chan2) targ = Choi(self.choiZ) self.assertEqual(chan, targ) # 50% depolarizing channel chan1 = Choi(self.depol_choi(0.5)) chan = chan1.compose(chan1) targ = Choi(self.depol_choi(0.75)) self.assertEqual(chan, targ) # Measure and rotation Zp, Zm = np.diag([1, 0]), np.diag([0, 1]) Xp, Xm = np.array([[1, 1], [1, 1]]) / 2, np.array([[1, -1], [-1, 1]]) / 2 chan1 = Choi(np.kron(Zp, Xp) + np.kron(Zm, Xm)) chan2 = Choi(self.choiX) # X-gate second does nothing targ = Choi(np.kron(Zp, Xp) + np.kron(Zm, Xm)) self.assertEqual(chan1.compose(chan2), targ) self.assertEqual(chan1 & chan2, targ) # X-gate first swaps Z states targ = Choi(np.kron(Zm, Xp) + np.kron(Zp, Xm)) self.assertEqual(chan2.compose(chan1), targ) self.assertEqual(chan2 & chan1, targ) # Compose different dimensions chan1 = Choi(np.eye(8) / 4, input_dims=2, output_dims=4) chan2 = Choi(np.eye(8) / 2, input_dims=4, output_dims=2) chan = chan1.compose(chan2) self.assertEqual(chan.dim, (2, 2)) chan = chan2.compose(chan1) self.assertEqual(chan.dim, (4, 4)) def test_dot(self): """Test dot method.""" # UnitaryChannel evolution chan1 = Choi(self.choiX) chan2 = Choi(self.choiY) targ = Choi(self.choiZ) self.assertEqual(chan1.dot(chan2), targ) self.assertEqual(chan1 @ chan2, targ) # 50% depolarizing channel chan1 = Choi(self.depol_choi(0.5)) targ = Choi(self.depol_choi(0.75)) self.assertEqual(chan1.dot(chan1), targ) self.assertEqual(chan1 @ chan1, targ) # Measure and rotation Zp, Zm = np.diag([1, 0]), np.diag([0, 1]) Xp, Xm = np.array([[1, 1], [1, 1]]) / 2, np.array([[1, -1], [-1, 1]]) / 2 chan1 = Choi(np.kron(Zp, Xp) + np.kron(Zm, Xm)) chan2 = Choi(self.choiX) # X-gate second does nothing targ = Choi(np.kron(Zp, Xp) + np.kron(Zm, Xm)) self.assertEqual(chan2.dot(chan1), targ) self.assertEqual(chan2 @ chan1, targ) # X-gate first swaps Z states targ = Choi(np.kron(Zm, Xp) + np.kron(Zp, Xm)) self.assertEqual(chan1.dot(chan2), targ) self.assertEqual(chan1 @ chan2, targ) # Compose different dimensions chan1 = Choi(np.eye(8) / 4, input_dims=2, output_dims=4) chan2 = Choi(np.eye(8) / 2, input_dims=4, output_dims=2) chan = chan1.dot(chan2) self.assertEqual(chan.dim, (4, 4)) chan = chan1 @ chan2 self.assertEqual(chan.dim, (4, 4)) chan = chan2.dot(chan1) self.assertEqual(chan.dim, (2, 2)) chan = chan2 @ chan1 self.assertEqual(chan.dim, (2, 2)) def test_compose_front(self): """Test front compose method.""" # UnitaryChannel evolution chan1 = Choi(self.choiX) chan2 = Choi(self.choiY) chan = chan1.compose(chan2, front=True) targ = Choi(self.choiZ) self.assertEqual(chan, targ) # 50% depolarizing channel chan1 = Choi(self.depol_choi(0.5)) chan = chan1.compose(chan1, front=True) targ = Choi(self.depol_choi(0.75)) self.assertEqual(chan, targ) # Measure and rotation Zp, Zm = np.diag([1, 0]), np.diag([0, 1]) Xp, Xm = np.array([[1, 1], [1, 1]]) / 2, np.array([[1, -1], [-1, 1]]) / 2 chan1 = Choi(np.kron(Zp, Xp) + np.kron(Zm, Xm)) chan2 = Choi(self.choiX) # X-gate second does nothing chan = chan2.compose(chan1, front=True) targ = Choi(np.kron(Zp, Xp) + np.kron(Zm, Xm)) self.assertEqual(chan, targ) # X-gate first swaps Z states chan = chan1.compose(chan2, front=True) targ = Choi(np.kron(Zm, Xp) + np.kron(Zp, Xm)) self.assertEqual(chan, targ) # Compose different dimensions chan1 = Choi(np.eye(8) / 4, input_dims=2, output_dims=4) chan2 = Choi(np.eye(8) / 2, input_dims=4, output_dims=2) chan = chan1.compose(chan2, front=True) self.assertEqual(chan.dim, (4, 4)) chan = chan2.compose(chan1, front=True) self.assertEqual(chan.dim, (2, 2)) def test_expand(self): """Test expand method.""" rho0, rho1 = np.diag([1, 0]), np.diag([0, 1]) rho_init = DensityMatrix(np.kron(rho0, rho0)) chan1 = Choi(self.choiI) chan2 = Choi(self.choiX) # X \otimes I chan = chan1.expand(chan2) rho_targ = DensityMatrix(np.kron(rho1, rho0)) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) # I \otimes X chan = chan2.expand(chan1) rho_targ = DensityMatrix(np.kron(rho0, rho1)) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) # Completely depolarizing chan_dep = Choi(self.depol_choi(1)) chan = chan_dep.expand(chan_dep) rho_targ = DensityMatrix(np.diag([1, 1, 1, 1]) / 4) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) def test_tensor(self): """Test tensor method.""" rho0, rho1 = np.diag([1, 0]), np.diag([0, 1]) rho_init = DensityMatrix(np.kron(rho0, rho0)) chan1 = Choi(self.choiI) chan2 = Choi(self.choiX) # X \otimes I rho_targ = DensityMatrix(np.kron(rho1, rho0)) chan = chan2.tensor(chan1) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) chan = chan2 ^ chan1 self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) # I \otimes X rho_targ = DensityMatrix(np.kron(rho0, rho1)) chan = chan1.tensor(chan2) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) chan = chan1 ^ chan2 self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) # Completely depolarizing rho_targ = DensityMatrix(np.diag([1, 1, 1, 1]) / 4) chan_dep = Choi(self.depol_choi(1)) chan = chan_dep.tensor(chan_dep) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) chan = chan_dep ^ chan_dep self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) def test_power(self): """Test power method.""" # 10% depolarizing channel p_id = 0.9 depol = Choi(self.depol_choi(1 - p_id)) # Compose 3 times p_id3 = p_id**3 chan3 = depol.power(3) targ3 = Choi(self.depol_choi(1 - p_id3)) self.assertEqual(chan3, targ3) def test_add(self): """Test add method.""" mat1 = 0.5 * self.choiI mat2 = 0.5 * self.depol_choi(1) chan1 = Choi(mat1) chan2 = Choi(mat2) targ = Choi(mat1 + mat2) self.assertEqual(chan1._add(chan2), targ) self.assertEqual(chan1 + chan2, targ) targ = Choi(mat1 - mat2) self.assertEqual(chan1 - chan2, targ) def test_add_qargs(self): """Test add method with qargs.""" mat = self.rand_matrix(8**2, 8**2) mat0 = self.rand_matrix(4, 4) mat1 = self.rand_matrix(4, 4) op = Choi(mat) op0 = Choi(mat0) op1 = Choi(mat1) op01 = op1.tensor(op0) eye = Choi(self.choiI) with self.subTest(msg="qargs=[0]"): value = op + op0([0]) target = op + eye.tensor(eye).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[1]"): value = op + op0([1]) target = op + eye.tensor(op0).tensor(eye) self.assertEqual(value, target) with self.subTest(msg="qargs=[2]"): value = op + op0([2]) target = op + op0.tensor(eye).tensor(eye) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 1]"): value = op + op01([0, 1]) target = op + eye.tensor(op1).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[1, 0]"): value = op + op01([1, 0]) target = op + eye.tensor(op0).tensor(op1) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 2]"): value = op + op01([0, 2]) target = op + op1.tensor(eye).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[2, 0]"): value = op + op01([2, 0]) target = op + op0.tensor(eye).tensor(op1) self.assertEqual(value, target) def test_sub_qargs(self): """Test subtract method with qargs.""" mat = self.rand_matrix(8**2, 8**2) mat0 = self.rand_matrix(4, 4) mat1 = self.rand_matrix(4, 4) op = Choi(mat) op0 = Choi(mat0) op1 = Choi(mat1) op01 = op1.tensor(op0) eye = Choi(self.choiI) with self.subTest(msg="qargs=[0]"): value = op - op0([0]) target = op - eye.tensor(eye).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[1]"): value = op - op0([1]) target = op - eye.tensor(op0).tensor(eye) self.assertEqual(value, target) with self.subTest(msg="qargs=[2]"): value = op - op0([2]) target = op - op0.tensor(eye).tensor(eye) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 1]"): value = op - op01([0, 1]) target = op - eye.tensor(op1).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[1, 0]"): value = op - op01([1, 0]) target = op - eye.tensor(op0).tensor(op1) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 2]"): value = op - op01([0, 2]) target = op - op1.tensor(eye).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[2, 0]"): value = op - op01([2, 0]) target = op - op0.tensor(eye).tensor(op1) self.assertEqual(value, target) def test_add_except(self): """Test add method raises exceptions.""" chan1 = Choi(self.choiI) chan2 = Choi(np.eye(8)) self.assertRaises(QiskitError, chan1._add, chan2) self.assertRaises(QiskitError, chan1._add, 5) def test_multiply(self): """Test multiply method.""" chan = Choi(self.choiI) val = 0.5 targ = Choi(val * self.choiI) self.assertEqual(chan._multiply(val), targ) self.assertEqual(val * chan, targ) targ = Choi(self.choiI * val) self.assertEqual(chan * val, targ) def test_multiply_except(self): """Test multiply method raises exceptions.""" chan = Choi(self.choiI) self.assertRaises(QiskitError, chan._multiply, "s") self.assertRaises(QiskitError, chan.__rmul__, "s") self.assertRaises(QiskitError, chan._multiply, chan) self.assertRaises(QiskitError, chan.__rmul__, chan) def test_negate(self): """Test negate method""" chan = Choi(self.choiI) targ = Choi(-1 * self.choiI) self.assertEqual(-chan, targ) if __name__ == "__main__": unittest.main()
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# 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 Kraus quantum channel representation class.""" import copy import unittest import numpy as np from numpy.testing import assert_allclose from qiskit import QiskitError from qiskit.quantum_info.states import DensityMatrix from qiskit.quantum_info import Kraus from .channel_test_case import ChannelTestCase class TestKraus(ChannelTestCase): """Tests for Kraus channel representation.""" def test_init(self): """Test initialization""" # Initialize from unitary chan = Kraus(self.UI) assert_allclose(chan.data, [self.UI]) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(chan.num_qubits, 1) # Initialize from Kraus chan = Kraus(self.depol_kraus(0.5)) assert_allclose(chan.data, self.depol_kraus(0.5)) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(chan.num_qubits, 1) # Initialize from Non-CPTP kraus_l, kraus_r = [self.UI, self.UX], [self.UY, self.UZ] chan = Kraus((kraus_l, kraus_r)) assert_allclose(chan.data, (kraus_l, kraus_r)) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(chan.num_qubits, 1) # Initialize with redundant second op chan = Kraus((kraus_l, kraus_l)) assert_allclose(chan.data, kraus_l) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(chan.num_qubits, 1) # Initialize from rectangular kraus = [np.zeros((4, 2))] chan = Kraus(kraus) assert_allclose(chan.data, kraus) self.assertEqual(chan.dim, (2, 4)) self.assertIsNone(chan.num_qubits) # Wrong input or output dims should raise exception self.assertRaises(QiskitError, Kraus, kraus, input_dims=4, output_dims=4) def test_circuit_init(self): """Test initialization from a circuit.""" circuit, target = self.simple_circuit_no_measure() op = Kraus(circuit) target = Kraus(target) self.assertEqual(op, target) def test_circuit_init_except(self): """Test initialization from circuit with measure raises exception.""" circuit = self.simple_circuit_with_measure() self.assertRaises(QiskitError, Kraus, circuit) def test_equal(self): """Test __eq__ method""" kraus = [self.rand_matrix(2, 2) for _ in range(2)] self.assertEqual(Kraus(kraus), Kraus(kraus)) def test_copy(self): """Test copy method""" mat = np.eye(2) with self.subTest("Deep copy"): orig = Kraus(mat) cpy = orig.copy() cpy._data[0][0][0, 0] = 0.0 self.assertFalse(cpy == orig) with self.subTest("Shallow copy"): orig = Kraus(mat) clone = copy.copy(orig) clone._data[0][0][0, 0] = 0.0 self.assertTrue(clone == orig) def test_clone(self): """Test clone method""" mat = np.eye(4) orig = Kraus(mat) clone = copy.copy(orig) clone._data[0][0][0, 0] = 0.0 self.assertTrue(clone == orig) def test_is_cptp(self): """Test is_cptp method.""" self.assertTrue(Kraus(self.depol_kraus(0.5)).is_cptp()) self.assertTrue(Kraus(self.UX).is_cptp()) # Non-CPTP should return false self.assertFalse(Kraus(([self.UI], [self.UX])).is_cptp()) self.assertFalse(Kraus([self.UI, self.UX]).is_cptp()) def test_conjugate(self): """Test conjugate method.""" kraus_l, kraus_r = self.rand_kraus(2, 4, 4), self.rand_kraus(2, 4, 4) # Single Kraus list targ = Kraus([np.conjugate(k) for k in kraus_l]) chan1 = Kraus(kraus_l) chan = chan1.conjugate() self.assertEqual(chan, targ) self.assertEqual(chan.dim, (2, 4)) # Double Kraus list targ = Kraus(([np.conjugate(k) for k in kraus_l], [np.conjugate(k) for k in kraus_r])) chan1 = Kraus((kraus_l, kraus_r)) chan = chan1.conjugate() self.assertEqual(chan, targ) self.assertEqual(chan.dim, (2, 4)) def test_transpose(self): """Test transpose method.""" kraus_l, kraus_r = self.rand_kraus(2, 4, 4), self.rand_kraus(2, 4, 4) # Single Kraus list targ = Kraus([np.transpose(k) for k in kraus_l]) chan1 = Kraus(kraus_l) chan = chan1.transpose() self.assertEqual(chan, targ) self.assertEqual(chan.dim, (4, 2)) # Double Kraus list targ = Kraus(([np.transpose(k) for k in kraus_l], [np.transpose(k) for k in kraus_r])) chan1 = Kraus((kraus_l, kraus_r)) chan = chan1.transpose() self.assertEqual(chan, targ) self.assertEqual(chan.dim, (4, 2)) def test_adjoint(self): """Test adjoint method.""" kraus_l, kraus_r = self.rand_kraus(2, 4, 4), self.rand_kraus(2, 4, 4) # Single Kraus list targ = Kraus([np.transpose(k).conj() for k in kraus_l]) chan1 = Kraus(kraus_l) chan = chan1.adjoint() self.assertEqual(chan, targ) self.assertEqual(chan.dim, (4, 2)) # Double Kraus list targ = Kraus( ([np.transpose(k).conj() for k in kraus_l], [np.transpose(k).conj() for k in kraus_r]) ) chan1 = Kraus((kraus_l, kraus_r)) chan = chan1.adjoint() self.assertEqual(chan, targ) self.assertEqual(chan.dim, (4, 2)) def test_compose_except(self): """Test compose different dimension exception""" self.assertRaises(QiskitError, Kraus(np.eye(2)).compose, Kraus(np.eye(4))) self.assertRaises(QiskitError, Kraus(np.eye(2)).compose, 2) def test_compose(self): """Test compose method.""" # Random input test state rho = DensityMatrix(self.rand_rho(2)) # UnitaryChannel evolution chan1 = Kraus(self.UX) chan2 = Kraus(self.UY) chan = chan1.compose(chan2) targ = rho & Kraus(self.UZ) self.assertEqual(rho & chan, targ) # 50% depolarizing channel chan1 = Kraus(self.depol_kraus(0.5)) chan = chan1.compose(chan1) targ = rho & Kraus(self.depol_kraus(0.75)) self.assertEqual(rho & chan, targ) # Compose different dimensions kraus1, kraus2 = self.rand_kraus(2, 4, 4), self.rand_kraus(4, 2, 4) chan1 = Kraus(kraus1) chan2 = Kraus(kraus2) targ = rho & chan1 & chan2 chan = chan1.compose(chan2) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(rho & chan, targ) chan = chan1 & chan2 self.assertEqual(chan.dim, (2, 2)) self.assertEqual(rho & chan, targ) def test_dot(self): """Test dot method.""" # Random input test state rho = DensityMatrix(self.rand_rho(2)) # UnitaryChannel evolution chan1 = Kraus(self.UX) chan2 = Kraus(self.UY) targ = rho.evolve(Kraus(self.UZ)) self.assertEqual(rho.evolve(chan1.dot(chan2)), targ) self.assertEqual(rho.evolve(chan1 @ chan2), targ) # 50% depolarizing channel chan1 = Kraus(self.depol_kraus(0.5)) targ = rho & Kraus(self.depol_kraus(0.75)) self.assertEqual(rho.evolve(chan1.dot(chan1)), targ) self.assertEqual(rho.evolve(chan1 @ chan1), targ) # Compose different dimensions kraus1, kraus2 = self.rand_kraus(2, 4, 4), self.rand_kraus(4, 2, 4) chan1 = Kraus(kraus1) chan2 = Kraus(kraus2) targ = rho & chan1 & chan2 self.assertEqual(rho.evolve(chan2.dot(chan1)), targ) self.assertEqual(rho.evolve(chan2 @ chan1), targ) def test_compose_front(self): """Test deprecated front compose method.""" # Random input test state rho = DensityMatrix(self.rand_rho(2)) # UnitaryChannel evolution chan1 = Kraus(self.UX) chan2 = Kraus(self.UY) chan = chan1.compose(chan2, front=True) targ = rho & Kraus(self.UZ) self.assertEqual(rho & chan, targ) # 50% depolarizing channel chan1 = Kraus(self.depol_kraus(0.5)) chan = chan1.compose(chan1, front=True) targ = rho & Kraus(self.depol_kraus(0.75)) self.assertEqual(rho & chan, targ) # Compose different dimensions kraus1, kraus2 = self.rand_kraus(2, 4, 4), self.rand_kraus(4, 2, 4) chan1 = Kraus(kraus1) chan2 = Kraus(kraus2) targ = rho & chan1 & chan2 chan = chan2.compose(chan1, front=True) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(rho & chan, targ) def test_expand(self): """Test expand method.""" rho0, rho1 = np.diag([1, 0]), np.diag([0, 1]) rho_init = DensityMatrix(np.kron(rho0, rho0)) chan1 = Kraus(self.UI) chan2 = Kraus(self.UX) # X \otimes I chan = chan1.expand(chan2) rho_targ = DensityMatrix(np.kron(rho1, rho0)) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init & chan, rho_targ) # I \otimes X chan = chan2.expand(chan1) rho_targ = DensityMatrix(np.kron(rho0, rho1)) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init & chan, rho_targ) # Completely depolarizing chan_dep = Kraus(self.depol_kraus(1)) chan = chan_dep.expand(chan_dep) rho_targ = DensityMatrix(np.diag([1, 1, 1, 1]) / 4) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init & chan, rho_targ) def test_tensor(self): """Test tensor method.""" rho0, rho1 = np.diag([1, 0]), np.diag([0, 1]) rho_init = DensityMatrix(np.kron(rho0, rho0)) chan1 = Kraus(self.UI) chan2 = Kraus(self.UX) # X \otimes I chan = chan2.tensor(chan1) rho_targ = DensityMatrix(np.kron(rho1, rho0)) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init & chan, rho_targ) # I \otimes X chan = chan1.tensor(chan2) rho_targ = DensityMatrix(np.kron(rho0, rho1)) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init & chan, rho_targ) # Completely depolarizing chan_dep = Kraus(self.depol_kraus(1)) chan = chan_dep.tensor(chan_dep) rho_targ = DensityMatrix(np.diag([1, 1, 1, 1]) / 4) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init & chan, rho_targ) def test_power(self): """Test power method.""" # 10% depolarizing channel rho = DensityMatrix(np.diag([1, 0])) p_id = 0.9 chan = Kraus(self.depol_kraus(1 - p_id)) # Compose 3 times p_id3 = p_id**3 chan3 = chan.power(3) targ3a = rho & chan & chan & chan self.assertEqual(rho & chan3, targ3a) targ3b = rho & Kraus(self.depol_kraus(1 - p_id3)) self.assertEqual(rho & chan3, targ3b) def test_add(self): """Test add method.""" # Random input test state rho = DensityMatrix(self.rand_rho(2)) kraus1, kraus2 = self.rand_kraus(2, 4, 4), self.rand_kraus(2, 4, 4) # Random Single-Kraus maps chan1 = Kraus(kraus1) chan2 = Kraus(kraus2) targ = (rho & chan1) + (rho & chan2) chan = chan1._add(chan2) self.assertEqual(rho & chan, targ) chan = chan1 + chan2 self.assertEqual(rho & chan, targ) # Random Single-Kraus maps chan = Kraus((kraus1, kraus2)) targ = 2 * (rho & chan) chan = chan._add(chan) self.assertEqual(rho & chan, targ) def test_add_qargs(self): """Test add method with qargs.""" rho = DensityMatrix(self.rand_rho(8)) kraus = self.rand_kraus(8, 8, 4) kraus0 = self.rand_kraus(2, 2, 4) op = Kraus(kraus) op0 = Kraus(kraus0) eye = Kraus(self.UI) with self.subTest(msg="qargs=[0]"): value = op + op0([0]) target = op + eye.tensor(eye).tensor(op0) self.assertEqual(rho & value, rho & target) with self.subTest(msg="qargs=[1]"): value = op + op0([1]) target = op + eye.tensor(op0).tensor(eye) self.assertEqual(rho & value, rho & target) with self.subTest(msg="qargs=[2]"): value = op + op0([2]) target = op + op0.tensor(eye).tensor(eye) self.assertEqual(rho & value, rho & target) def test_sub_qargs(self): """Test sub method with qargs.""" rho = DensityMatrix(self.rand_rho(8)) kraus = self.rand_kraus(8, 8, 4) kraus0 = self.rand_kraus(2, 2, 4) op = Kraus(kraus) op0 = Kraus(kraus0) eye = Kraus(self.UI) with self.subTest(msg="qargs=[0]"): value = op - op0([0]) target = op - eye.tensor(eye).tensor(op0) self.assertEqual(rho & value, rho & target) with self.subTest(msg="qargs=[1]"): value = op - op0([1]) target = op - eye.tensor(op0).tensor(eye) self.assertEqual(rho & value, rho & target) with self.subTest(msg="qargs=[2]"): value = op - op0([2]) target = op - op0.tensor(eye).tensor(eye) self.assertEqual(rho & value, rho & target) def test_subtract(self): """Test subtract method.""" # Random input test state rho = DensityMatrix(self.rand_rho(2)) kraus1, kraus2 = self.rand_kraus(2, 4, 4), self.rand_kraus(2, 4, 4) # Random Single-Kraus maps chan1 = Kraus(kraus1) chan2 = Kraus(kraus2) targ = (rho & chan1) - (rho & chan2) chan = chan1 - chan2 self.assertEqual(rho & chan, targ) # Random Single-Kraus maps chan = Kraus((kraus1, kraus2)) targ = 0 * (rho & chan) chan = chan - chan self.assertEqual(rho & chan, targ) def test_multiply(self): """Test multiply method.""" # Random initial state and Kraus ops rho = DensityMatrix(self.rand_rho(2)) val = 0.5 kraus1, kraus2 = self.rand_kraus(2, 4, 4), self.rand_kraus(2, 4, 4) # Single Kraus set chan1 = Kraus(kraus1) targ = val * (rho & chan1) chan = chan1._multiply(val) self.assertEqual(rho & chan, targ) chan = val * chan1 self.assertEqual(rho & chan, targ) targ = (rho & chan1) * val chan = chan1 * val self.assertEqual(rho & chan, targ) # Double Kraus set chan2 = Kraus((kraus1, kraus2)) targ = val * (rho & chan2) chan = chan2._multiply(val) self.assertEqual(rho & chan, targ) chan = val * chan2 self.assertEqual(rho & chan, targ) def test_multiply_except(self): """Test multiply method raises exceptions.""" chan = Kraus(self.depol_kraus(1)) self.assertRaises(QiskitError, chan._multiply, "s") self.assertRaises(QiskitError, chan.__rmul__, "s") self.assertRaises(QiskitError, chan._multiply, chan) self.assertRaises(QiskitError, chan.__rmul__, chan) def test_negate(self): """Test negate method""" rho = DensityMatrix(np.diag([1, 0])) targ = DensityMatrix(np.diag([-0.5, -0.5])) chan = -Kraus(self.depol_kraus(1)) self.assertEqual(rho & chan, targ) if __name__ == "__main__": unittest.main()
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# 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 PTM quantum channel representation class.""" import copy import unittest import numpy as np from numpy.testing import assert_allclose from qiskit import QiskitError from qiskit.quantum_info.states import DensityMatrix from qiskit.quantum_info.operators.channel import PTM from .channel_test_case import ChannelTestCase class TestPTM(ChannelTestCase): """Tests for PTM channel representation.""" def test_init(self): """Test initialization""" mat4 = np.eye(4) / 2.0 chan = PTM(mat4) assert_allclose(chan.data, mat4) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(chan.num_qubits, 1) mat16 = np.eye(16) / 4 chan = PTM(mat16) assert_allclose(chan.data, mat16) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(chan.num_qubits, 2) # Wrong input or output dims should raise exception self.assertRaises(QiskitError, PTM, mat16, input_dims=2, output_dims=4) # Non multi-qubit dimensions should raise exception self.assertRaises(QiskitError, PTM, np.eye(6) / 2, input_dims=3, output_dims=2) def test_circuit_init(self): """Test initialization from a circuit.""" circuit, target = self.simple_circuit_no_measure() op = PTM(circuit) target = PTM(target) self.assertEqual(op, target) def test_circuit_init_except(self): """Test initialization from circuit with measure raises exception.""" circuit = self.simple_circuit_with_measure() self.assertRaises(QiskitError, PTM, circuit) def test_equal(self): """Test __eq__ method""" mat = self.rand_matrix(4, 4, real=True) self.assertEqual(PTM(mat), PTM(mat)) def test_copy(self): """Test copy method""" mat = np.eye(4) with self.subTest("Deep copy"): orig = PTM(mat) cpy = orig.copy() cpy._data[0, 0] = 0.0 self.assertFalse(cpy == orig) with self.subTest("Shallow copy"): orig = PTM(mat) clone = copy.copy(orig) clone._data[0, 0] = 0.0 self.assertTrue(clone == orig) def test_clone(self): """Test clone method""" mat = np.eye(4) orig = PTM(mat) clone = copy.copy(orig) clone._data[0, 0] = 0.0 self.assertTrue(clone == orig) def test_is_cptp(self): """Test is_cptp method.""" self.assertTrue(PTM(self.depol_ptm(0.25)).is_cptp()) # Non-CPTP should return false self.assertFalse(PTM(1.25 * self.ptmI - 0.25 * self.depol_ptm(1)).is_cptp()) def test_compose_except(self): """Test compose different dimension exception""" self.assertRaises(QiskitError, PTM(np.eye(4)).compose, PTM(np.eye(16))) self.assertRaises(QiskitError, PTM(np.eye(4)).compose, 2) def test_compose(self): """Test compose method.""" # Random input test state rho = DensityMatrix(self.rand_rho(2)) # UnitaryChannel evolution chan1 = PTM(self.ptmX) chan2 = PTM(self.ptmY) chan = chan1.compose(chan2) rho_targ = rho.evolve(PTM(self.ptmZ)) self.assertEqual(rho.evolve(chan), rho_targ) # 50% depolarizing channel chan1 = PTM(self.depol_ptm(0.5)) chan = chan1.compose(chan1) rho_targ = rho.evolve(PTM(self.depol_ptm(0.75))) self.assertEqual(rho.evolve(chan), rho_targ) # Compose random ptm1 = self.rand_matrix(4, 4, real=True) ptm2 = self.rand_matrix(4, 4, real=True) chan1 = PTM(ptm1, input_dims=2, output_dims=2) chan2 = PTM(ptm2, input_dims=2, output_dims=2) rho_targ = rho.evolve(chan1).evolve(chan2) chan = chan1.compose(chan2) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(rho.evolve(chan), rho_targ) chan = chan1 & chan2 self.assertEqual(chan.dim, (2, 2)) self.assertEqual(rho.evolve(chan), rho_targ) def test_dot(self): """Test dot method.""" # Random input test state rho = DensityMatrix(self.rand_rho(2)) # UnitaryChannel evolution chan1 = PTM(self.ptmX) chan2 = PTM(self.ptmY) rho_targ = rho.evolve(PTM(self.ptmZ)) self.assertEqual(rho.evolve(chan2.dot(chan1)), rho_targ) self.assertEqual(rho.evolve(chan2 @ chan1), rho_targ) # Compose random ptm1 = self.rand_matrix(4, 4, real=True) ptm2 = self.rand_matrix(4, 4, real=True) chan1 = PTM(ptm1, input_dims=2, output_dims=2) chan2 = PTM(ptm2, input_dims=2, output_dims=2) rho_targ = rho.evolve(chan1).evolve(chan2) self.assertEqual(rho.evolve(chan2.dot(chan1)), rho_targ) self.assertEqual(rho.evolve(chan2 @ chan1), rho_targ) def test_compose_front(self): """Test deprecated front compose method.""" # Random input test state rho = DensityMatrix(self.rand_rho(2)) # UnitaryChannel evolution chan1 = PTM(self.ptmX) chan2 = PTM(self.ptmY) chan = chan2.compose(chan1, front=True) rho_targ = rho.evolve(PTM(self.ptmZ)) self.assertEqual(rho.evolve(chan), rho_targ) # Compose random ptm1 = self.rand_matrix(4, 4, real=True) ptm2 = self.rand_matrix(4, 4, real=True) chan1 = PTM(ptm1, input_dims=2, output_dims=2) chan2 = PTM(ptm2, input_dims=2, output_dims=2) rho_targ = rho.evolve(chan1).evolve(chan2) chan = chan2.compose(chan1, front=True) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(rho.evolve(chan), rho_targ) def test_expand(self): """Test expand method.""" rho0, rho1 = np.diag([1, 0]), np.diag([0, 1]) rho_init = DensityMatrix(np.kron(rho0, rho0)) chan1 = PTM(self.ptmI) chan2 = PTM(self.ptmX) # X \otimes I chan = chan1.expand(chan2) rho_targ = DensityMatrix(np.kron(rho1, rho0)) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) # I \otimes X chan = chan2.expand(chan1) rho_targ = DensityMatrix(np.kron(rho0, rho1)) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) # Completely depolarizing chan_dep = PTM(self.depol_ptm(1)) chan = chan_dep.expand(chan_dep) rho_targ = DensityMatrix(np.diag([1, 1, 1, 1]) / 4) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) def test_tensor(self): """Test tensor method.""" rho0, rho1 = np.diag([1, 0]), np.diag([0, 1]) rho_init = DensityMatrix(np.kron(rho0, rho0)) chan1 = PTM(self.ptmI) chan2 = PTM(self.ptmX) # X \otimes I chan = chan2.tensor(chan1) rho_targ = DensityMatrix(np.kron(rho1, rho0)) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) # I \otimes X chan = chan1.tensor(chan2) rho_targ = DensityMatrix(np.kron(rho0, rho1)) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) # Completely depolarizing chan_dep = PTM(self.depol_ptm(1)) chan = chan_dep.tensor(chan_dep) rho_targ = DensityMatrix(np.diag([1, 1, 1, 1]) / 4) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) def test_power(self): """Test power method.""" # 10% depolarizing channel p_id = 0.9 depol = PTM(self.depol_ptm(1 - p_id)) # Compose 3 times p_id3 = p_id**3 chan3 = depol.power(3) targ3 = PTM(self.depol_ptm(1 - p_id3)) self.assertEqual(chan3, targ3) def test_add(self): """Test add method.""" mat1 = 0.5 * self.ptmI mat2 = 0.5 * self.depol_ptm(1) chan1 = PTM(mat1) chan2 = PTM(mat2) targ = PTM(mat1 + mat2) self.assertEqual(chan1._add(chan2), targ) self.assertEqual(chan1 + chan2, targ) targ = PTM(mat1 - mat2) self.assertEqual(chan1 - chan2, targ) def test_add_qargs(self): """Test add method with qargs.""" mat = self.rand_matrix(8**2, 8**2) mat0 = self.rand_matrix(4, 4) mat1 = self.rand_matrix(4, 4) op = PTM(mat) op0 = PTM(mat0) op1 = PTM(mat1) op01 = op1.tensor(op0) eye = PTM(self.ptmI) with self.subTest(msg="qargs=[0]"): value = op + op0([0]) target = op + eye.tensor(eye).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[1]"): value = op + op0([1]) target = op + eye.tensor(op0).tensor(eye) self.assertEqual(value, target) with self.subTest(msg="qargs=[2]"): value = op + op0([2]) target = op + op0.tensor(eye).tensor(eye) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 1]"): value = op + op01([0, 1]) target = op + eye.tensor(op1).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[1, 0]"): value = op + op01([1, 0]) target = op + eye.tensor(op0).tensor(op1) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 2]"): value = op + op01([0, 2]) target = op + op1.tensor(eye).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[2, 0]"): value = op + op01([2, 0]) target = op + op0.tensor(eye).tensor(op1) self.assertEqual(value, target) def test_sub_qargs(self): """Test subtract method with qargs.""" mat = self.rand_matrix(8**2, 8**2) mat0 = self.rand_matrix(4, 4) mat1 = self.rand_matrix(4, 4) op = PTM(mat) op0 = PTM(mat0) op1 = PTM(mat1) op01 = op1.tensor(op0) eye = PTM(self.ptmI) with self.subTest(msg="qargs=[0]"): value = op - op0([0]) target = op - eye.tensor(eye).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[1]"): value = op - op0([1]) target = op - eye.tensor(op0).tensor(eye) self.assertEqual(value, target) with self.subTest(msg="qargs=[2]"): value = op - op0([2]) target = op - op0.tensor(eye).tensor(eye) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 1]"): value = op - op01([0, 1]) target = op - eye.tensor(op1).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[1, 0]"): value = op - op01([1, 0]) target = op - eye.tensor(op0).tensor(op1) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 2]"): value = op - op01([0, 2]) target = op - op1.tensor(eye).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[2, 0]"): value = op - op01([2, 0]) target = op - op0.tensor(eye).tensor(op1) self.assertEqual(value, target) def test_add_except(self): """Test add method raises exceptions.""" chan1 = PTM(self.ptmI) chan2 = PTM(np.eye(16)) self.assertRaises(QiskitError, chan1._add, chan2) self.assertRaises(QiskitError, chan1._add, 5) def test_multiply(self): """Test multiply method.""" chan = PTM(self.ptmI) val = 0.5 targ = PTM(val * self.ptmI) self.assertEqual(chan._multiply(val), targ) self.assertEqual(val * chan, targ) targ = PTM(self.ptmI * val) self.assertEqual(chan * val, targ) def test_multiply_except(self): """Test multiply method raises exceptions.""" chan = PTM(self.ptmI) self.assertRaises(QiskitError, chan._multiply, "s") self.assertRaises(QiskitError, chan.__rmul__, "s") self.assertRaises(QiskitError, chan._multiply, chan) self.assertRaises(QiskitError, chan.__rmul__, chan) def test_negate(self): """Test negate method""" chan = PTM(self.ptmI) targ = PTM(-self.ptmI) self.assertEqual(-chan, targ) if __name__ == "__main__": unittest.main()
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# 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 Stinespring quantum channel representation class.""" import copy import unittest import numpy as np from numpy.testing import assert_allclose from qiskit import QiskitError from qiskit.quantum_info.states import DensityMatrix from qiskit.quantum_info import Stinespring from .channel_test_case import ChannelTestCase class TestStinespring(ChannelTestCase): """Tests for Stinespring channel representation.""" def test_init(self): """Test initialization""" # Initialize from unitary chan = Stinespring(self.UI) assert_allclose(chan.data, self.UI) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(chan.num_qubits, 1) # Initialize from Stinespring chan = Stinespring(self.depol_stine(0.5)) assert_allclose(chan.data, self.depol_stine(0.5)) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(chan.num_qubits, 1) # Initialize from Non-CPTP stine_l, stine_r = self.rand_matrix(4, 2), self.rand_matrix(4, 2) chan = Stinespring((stine_l, stine_r)) assert_allclose(chan.data, (stine_l, stine_r)) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(chan.num_qubits, 1) # Initialize with redundant second op chan = Stinespring((stine_l, stine_l)) assert_allclose(chan.data, stine_l) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(chan.num_qubits, 1) # Wrong input or output dims should raise exception self.assertRaises(QiskitError, Stinespring, stine_l, input_dims=4, output_dims=4) def test_circuit_init(self): """Test initialization from a circuit.""" circuit, target = self.simple_circuit_no_measure() op = Stinespring(circuit) target = Stinespring(target) self.assertEqual(op, target) def test_circuit_init_except(self): """Test initialization from circuit with measure raises exception.""" circuit = self.simple_circuit_with_measure() self.assertRaises(QiskitError, Stinespring, circuit) def test_equal(self): """Test __eq__ method""" stine = tuple(self.rand_matrix(4, 2) for _ in range(2)) self.assertEqual(Stinespring(stine), Stinespring(stine)) def test_copy(self): """Test copy method""" mat = np.eye(4) with self.subTest("Deep copy"): orig = Stinespring(mat) cpy = orig.copy() cpy._data[0][0, 0] = 0.0 self.assertFalse(cpy == orig) with self.subTest("Shallow copy"): orig = Stinespring(mat) clone = copy.copy(orig) clone._data[0][0, 0] = 0.0 self.assertTrue(clone == orig) def test_clone(self): """Test clone method""" mat = np.eye(4) orig = Stinespring(mat) clone = copy.copy(orig) clone._data[0][0, 0] = 0.0 self.assertTrue(clone == orig) def test_is_cptp(self): """Test is_cptp method.""" self.assertTrue(Stinespring(self.depol_stine(0.5)).is_cptp()) self.assertTrue(Stinespring(self.UX).is_cptp()) # Non-CP stine_l, stine_r = self.rand_matrix(4, 2), self.rand_matrix(4, 2) self.assertFalse(Stinespring((stine_l, stine_r)).is_cptp()) self.assertFalse(Stinespring(self.UI + self.UX).is_cptp()) def test_conjugate(self): """Test conjugate method.""" stine_l, stine_r = self.rand_matrix(16, 2), self.rand_matrix(16, 2) # Single Stinespring list targ = Stinespring(stine_l.conj(), output_dims=4) chan1 = Stinespring(stine_l, output_dims=4) chan = chan1.conjugate() self.assertEqual(chan, targ) self.assertEqual(chan.dim, (2, 4)) # Double Stinespring list targ = Stinespring((stine_l.conj(), stine_r.conj()), output_dims=4) chan1 = Stinespring((stine_l, stine_r), output_dims=4) chan = chan1.conjugate() self.assertEqual(chan, targ) self.assertEqual(chan.dim, (2, 4)) def test_transpose(self): """Test transpose method.""" stine_l, stine_r = self.rand_matrix(4, 2), self.rand_matrix(4, 2) # Single square Stinespring list targ = Stinespring(stine_l.T, 4, 2) chan1 = Stinespring(stine_l, 2, 4) chan = chan1.transpose() self.assertEqual(chan, targ) self.assertEqual(chan.dim, (4, 2)) # Double square Stinespring list targ = Stinespring((stine_l.T, stine_r.T), 4, 2) chan1 = Stinespring((stine_l, stine_r), 2, 4) chan = chan1.transpose() self.assertEqual(chan, targ) self.assertEqual(chan.dim, (4, 2)) def test_adjoint(self): """Test adjoint method.""" stine_l, stine_r = self.rand_matrix(4, 2), self.rand_matrix(4, 2) # Single square Stinespring list targ = Stinespring(stine_l.T.conj(), 4, 2) chan1 = Stinespring(stine_l, 2, 4) chan = chan1.adjoint() self.assertEqual(chan, targ) self.assertEqual(chan.dim, (4, 2)) # Double square Stinespring list targ = Stinespring((stine_l.T.conj(), stine_r.T.conj()), 4, 2) chan1 = Stinespring((stine_l, stine_r), 2, 4) chan = chan1.adjoint() self.assertEqual(chan, targ) self.assertEqual(chan.dim, (4, 2)) def test_compose_except(self): """Test compose different dimension exception""" self.assertRaises(QiskitError, Stinespring(np.eye(2)).compose, Stinespring(np.eye(4))) self.assertRaises(QiskitError, Stinespring(np.eye(2)).compose, 2) def test_compose(self): """Test compose method.""" # Random input test state rho_init = DensityMatrix(self.rand_rho(2)) # UnitaryChannel evolution chan1 = Stinespring(self.UX) chan2 = Stinespring(self.UY) chan = chan1.compose(chan2) rho_targ = rho_init & Stinespring(self.UZ) self.assertEqual(rho_init.evolve(chan), rho_targ) # 50% depolarizing channel chan1 = Stinespring(self.depol_stine(0.5)) chan = chan1.compose(chan1) rho_targ = rho_init & Stinespring(self.depol_stine(0.75)) self.assertEqual(rho_init.evolve(chan), rho_targ) # Compose different dimensions stine1, stine2 = self.rand_matrix(16, 2), self.rand_matrix(8, 4) chan1 = Stinespring(stine1, input_dims=2, output_dims=4) chan2 = Stinespring(stine2, input_dims=4, output_dims=2) rho_targ = rho_init & chan1 & chan2 chan = chan1.compose(chan2) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(rho_init.evolve(chan), rho_targ) chan = chan1 & chan2 self.assertEqual(chan.dim, (2, 2)) self.assertEqual(rho_init.evolve(chan), rho_targ) def test_dot(self): """Test deprecated front compose method.""" # Random input test state rho_init = DensityMatrix(self.rand_rho(2)) # UnitaryChannel evolution chan1 = Stinespring(self.UX) chan2 = Stinespring(self.UY) rho_targ = rho_init.evolve(Stinespring(self.UZ)) self.assertEqual(rho_init.evolve(chan1.dot(chan2)), rho_targ) self.assertEqual(rho_init.evolve(chan1 @ chan2), rho_targ) # 50% depolarizing channel chan1 = Stinespring(self.depol_stine(0.5)) rho_targ = rho_init & Stinespring(self.depol_stine(0.75)) self.assertEqual(rho_init.evolve(chan1.dot(chan1)), rho_targ) self.assertEqual(rho_init.evolve(chan1 @ chan1), rho_targ) # Compose different dimensions stine1, stine2 = self.rand_matrix(16, 2), self.rand_matrix(8, 4) chan1 = Stinespring(stine1, input_dims=2, output_dims=4) chan2 = Stinespring(stine2, input_dims=4, output_dims=2) rho_targ = rho_init & chan1 & chan2 self.assertEqual(rho_init.evolve(chan2.dot(chan1)), rho_targ) self.assertEqual(rho_init.evolve(chan2 @ chan1), rho_targ) def test_compose_front(self): """Test deprecated front compose method.""" # Random input test state rho_init = DensityMatrix(self.rand_rho(2)) # UnitaryChannel evolution chan1 = Stinespring(self.UX) chan2 = Stinespring(self.UY) chan = chan1.compose(chan2, front=True) rho_targ = rho_init & Stinespring(self.UZ) self.assertEqual(rho_init.evolve(chan), rho_targ) # 50% depolarizing channel chan1 = Stinespring(self.depol_stine(0.5)) chan = chan1.compose(chan1, front=True) rho_targ = rho_init & Stinespring(self.depol_stine(0.75)) self.assertEqual(rho_init.evolve(chan), rho_targ) # Compose different dimensions stine1, stine2 = self.rand_matrix(16, 2), self.rand_matrix(8, 4) chan1 = Stinespring(stine1, input_dims=2, output_dims=4) chan2 = Stinespring(stine2, input_dims=4, output_dims=2) rho_targ = rho_init & chan1 & chan2 chan = chan2.compose(chan1, front=True) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(rho_init.evolve(chan), rho_targ) def test_expand(self): """Test expand method.""" rho0, rho1 = np.diag([1, 0]), np.diag([0, 1]) rho_init = DensityMatrix(np.kron(rho0, rho0)) chan1 = Stinespring(self.UI) chan2 = Stinespring(self.UX) # X \otimes I chan = chan1.expand(chan2) rho_targ = DensityMatrix(np.kron(rho1, rho0)) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) # I \otimes X chan = chan2.expand(chan1) rho_targ = DensityMatrix(np.kron(rho0, rho1)) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) # Completely depolarizing chan_dep = Stinespring(self.depol_stine(1)) chan = chan_dep.expand(chan_dep) rho_targ = DensityMatrix(np.diag([1, 1, 1, 1]) / 4) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) def test_tensor(self): """Test tensor method.""" rho0, rho1 = np.diag([1, 0]), np.diag([0, 1]) rho_init = DensityMatrix(np.kron(rho0, rho0)) chan1 = Stinespring(self.UI) chan2 = Stinespring(self.UX) # X \otimes I chan = chan2.tensor(chan1) rho_targ = DensityMatrix(np.kron(rho1, rho0)) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) # I \otimes X chan = chan1.tensor(chan2) rho_targ = DensityMatrix(np.kron(rho0, rho1)) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) # Completely depolarizing chan_dep = Stinespring(self.depol_stine(1)) chan = chan_dep.tensor(chan_dep) rho_targ = DensityMatrix(np.diag([1, 1, 1, 1]) / 4) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) def test_power(self): """Test power method.""" # 10% depolarizing channel rho_init = DensityMatrix(np.diag([1, 0])) p_id = 0.9 chan1 = Stinespring(self.depol_stine(1 - p_id)) # Compose 3 times p_id3 = p_id**3 chan = chan1.power(3) rho_targ = rho_init & chan1 & chan1 & chan1 self.assertEqual(rho_init & chan, rho_targ) rho_targ = rho_init & Stinespring(self.depol_stine(1 - p_id3)) self.assertEqual(rho_init & chan, rho_targ) def test_add(self): """Test add method.""" # Random input test state rho_init = DensityMatrix(self.rand_rho(2)) stine1, stine2 = self.rand_matrix(16, 2), self.rand_matrix(16, 2) # Random Single-Stinespring maps chan1 = Stinespring(stine1, input_dims=2, output_dims=4) chan2 = Stinespring(stine2, input_dims=2, output_dims=4) rho_targ = (rho_init & chan1) + (rho_init & chan2) chan = chan1._add(chan2) self.assertEqual(rho_init.evolve(chan), rho_targ) chan = chan1 + chan2 self.assertEqual(rho_init.evolve(chan), rho_targ) # Random Single-Stinespring maps chan = Stinespring((stine1, stine2)) rho_targ = 2 * (rho_init & chan) chan = chan._add(chan) self.assertEqual(rho_init.evolve(chan), rho_targ) def test_subtract(self): """Test subtract method.""" # Random input test state rho_init = DensityMatrix(self.rand_rho(2)) stine1, stine2 = self.rand_matrix(16, 2), self.rand_matrix(16, 2) # Random Single-Stinespring maps chan1 = Stinespring(stine1, input_dims=2, output_dims=4) chan2 = Stinespring(stine2, input_dims=2, output_dims=4) rho_targ = (rho_init & chan1) - (rho_init & chan2) chan = chan1 - chan2 self.assertEqual(rho_init.evolve(chan), rho_targ) # Random Single-Stinespring maps chan = Stinespring((stine1, stine2)) rho_targ = 0 * (rho_init & chan) chan = chan - chan self.assertEqual(rho_init.evolve(chan), rho_targ) def test_add_qargs(self): """Test add method with qargs.""" rho = DensityMatrix(self.rand_rho(8)) stine = self.rand_matrix(32, 8) stine0 = self.rand_matrix(8, 2) op = Stinespring(stine) op0 = Stinespring(stine0) eye = Stinespring(self.UI) with self.subTest(msg="qargs=[0]"): value = op + op0([0]) target = op + eye.tensor(eye).tensor(op0) self.assertEqual(rho & value, rho & target) with self.subTest(msg="qargs=[1]"): value = op + op0([1]) target = op + eye.tensor(op0).tensor(eye) self.assertEqual(rho & value, rho & target) with self.subTest(msg="qargs=[2]"): value = op + op0([2]) target = op + op0.tensor(eye).tensor(eye) self.assertEqual(rho & value, rho & target) def test_sub_qargs(self): """Test sub method with qargs.""" rho = DensityMatrix(self.rand_rho(8)) stine = self.rand_matrix(32, 8) stine0 = self.rand_matrix(8, 2) op = Stinespring(stine) op0 = Stinespring(stine0) eye = Stinespring(self.UI) with self.subTest(msg="qargs=[0]"): value = op - op0([0]) target = op - eye.tensor(eye).tensor(op0) self.assertEqual(rho & value, rho & target) with self.subTest(msg="qargs=[1]"): value = op - op0([1]) target = op - eye.tensor(op0).tensor(eye) self.assertEqual(rho & value, rho & target) with self.subTest(msg="qargs=[2]"): value = op - op0([2]) target = op - op0.tensor(eye).tensor(eye) self.assertEqual(rho & value, rho & target) def test_multiply(self): """Test multiply method.""" # Random initial state and Stinespring ops rho_init = DensityMatrix(self.rand_rho(2)) val = 0.5 stine1, stine2 = self.rand_matrix(16, 2), self.rand_matrix(16, 2) # Single Stinespring set chan1 = Stinespring(stine1, input_dims=2, output_dims=4) rho_targ = val * (rho_init & chan1) chan = chan1._multiply(val) self.assertEqual(rho_init.evolve(chan), rho_targ) chan = val * chan1 self.assertEqual(rho_init.evolve(chan), rho_targ) rho_targ = (rho_init & chan1) * val chan = chan1 * val self.assertEqual(rho_init.evolve(chan), rho_targ) # Double Stinespring set chan2 = Stinespring((stine1, stine2), input_dims=2, output_dims=4) rho_targ = val * (rho_init & chan2) chan = chan2._multiply(val) self.assertEqual(rho_init.evolve(chan), rho_targ) chan = val * chan2 self.assertEqual(rho_init.evolve(chan), rho_targ) def test_multiply_except(self): """Test multiply method raises exceptions.""" chan = Stinespring(self.depol_stine(1)) self.assertRaises(QiskitError, chan._multiply, "s") self.assertRaises(QiskitError, chan.__rmul__, "s") self.assertRaises(QiskitError, chan._multiply, chan) self.assertRaises(QiskitError, chan.__rmul__, chan) def test_negate(self): """Test negate method""" rho_init = DensityMatrix(np.diag([1, 0])) rho_targ = DensityMatrix(np.diag([-0.5, -0.5])) chan = -Stinespring(self.depol_stine(1)) self.assertEqual(rho_init.evolve(chan), rho_targ) if __name__ == "__main__": unittest.main()
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# 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 SuperOp quantum channel representation class.""" import copy import unittest import numpy as np from numpy.testing import assert_allclose from qiskit import QiskitError, QuantumCircuit from qiskit.quantum_info.states import DensityMatrix from qiskit.quantum_info.operators import Operator from qiskit.quantum_info.operators.channel import SuperOp from .channel_test_case import ChannelTestCase class TestSuperOp(ChannelTestCase): """Tests for SuperOp channel representation.""" def test_init(self): """Test initialization""" chan = SuperOp(self.sopI) assert_allclose(chan.data, self.sopI) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(chan.num_qubits, 1) mat = np.zeros((4, 16)) chan = SuperOp(mat) assert_allclose(chan.data, mat) self.assertEqual(chan.dim, (4, 2)) self.assertIsNone(chan.num_qubits) chan = SuperOp(mat.T) assert_allclose(chan.data, mat.T) self.assertEqual(chan.dim, (2, 4)) self.assertIsNone(chan.num_qubits) # Wrong input or output dims should raise exception self.assertRaises(QiskitError, SuperOp, mat, input_dims=[4], output_dims=[4]) def test_circuit_init(self): """Test initialization from a circuit.""" # Test tensor product of 1-qubit gates circuit = QuantumCircuit(3) circuit.h(0) circuit.x(1) circuit.ry(np.pi / 2, 2) op = SuperOp(circuit) y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]]) target = SuperOp(Operator(np.kron(y90, np.kron(self.UX, self.UH)))) self.assertEqual(target, op) # Test decomposition of Controlled-Phase gate lam = np.pi / 4 circuit = QuantumCircuit(2) circuit.cp(lam, 0, 1) op = SuperOp(circuit) target = SuperOp(Operator(np.diag([1, 1, 1, np.exp(1j * lam)]))) self.assertEqual(target, op) # Test decomposition of controlled-H gate circuit = QuantumCircuit(2) circuit.ch(0, 1) op = SuperOp(circuit) target = SuperOp( Operator(np.kron(self.UI, np.diag([1, 0])) + np.kron(self.UH, np.diag([0, 1]))) ) self.assertEqual(target, op) def test_circuit_init_except(self): """Test initialization from circuit with measure raises exception.""" circuit = self.simple_circuit_with_measure() self.assertRaises(QiskitError, SuperOp, circuit) def test_equal(self): """Test __eq__ method""" mat = self.rand_matrix(4, 4) self.assertEqual(SuperOp(mat), SuperOp(mat)) def test_copy(self): """Test copy method""" mat = np.eye(4) with self.subTest("Deep copy"): orig = SuperOp(mat) cpy = orig.copy() cpy._data[0, 0] = 0.0 self.assertFalse(cpy == orig) with self.subTest("Shallow copy"): orig = SuperOp(mat) clone = copy.copy(orig) clone._data[0, 0] = 0.0 self.assertTrue(clone == orig) def test_clone(self): """Test clone method""" mat = np.eye(4) orig = SuperOp(mat) clone = copy.copy(orig) clone._data[0, 0] = 0.0 self.assertTrue(clone == orig) def test_evolve(self): """Test evolve method.""" input_rho = DensityMatrix([[0, 0], [0, 1]]) # Identity channel chan = SuperOp(self.sopI) target_rho = DensityMatrix([[0, 0], [0, 1]]) self.assertEqual(input_rho.evolve(chan), target_rho) # Hadamard channel mat = np.array([[1, 1], [1, -1]]) / np.sqrt(2) chan = SuperOp(np.kron(mat.conj(), mat)) target_rho = DensityMatrix(np.array([[1, -1], [-1, 1]]) / 2) self.assertEqual(input_rho.evolve(chan), target_rho) # Completely depolarizing channel chan = SuperOp(self.depol_sop(1)) target_rho = DensityMatrix(np.eye(2) / 2) self.assertEqual(input_rho.evolve(chan), target_rho) def test_evolve_subsystem(self): """Test subsystem evolve method.""" # Single-qubit random superoperators op_a = SuperOp(self.rand_matrix(4, 4)) op_b = SuperOp(self.rand_matrix(4, 4)) op_c = SuperOp(self.rand_matrix(4, 4)) id1 = SuperOp(np.eye(4)) id2 = SuperOp(np.eye(16)) rho = DensityMatrix(self.rand_rho(8)) # Test evolving single-qubit of 3-qubit system op = op_a # Evolve on qubit 0 full_op = id2.tensor(op_a) rho_targ = rho.evolve(full_op) rho_test = rho.evolve(op, qargs=[0]) self.assertEqual(rho_test, rho_targ) # Evolve on qubit 1 full_op = id1.tensor(op_a).tensor(id1) rho_targ = rho.evolve(full_op) rho_test = rho.evolve(op, qargs=[1]) self.assertEqual(rho_test, rho_targ) # Evolve on qubit 2 full_op = op_a.tensor(id2) rho_targ = rho.evolve(full_op) rho_test = rho.evolve(op, qargs=[2]) self.assertEqual(rho_test, rho_targ) # Test 2-qubit evolution op = op_b.tensor(op_a) # Evolve on qubits [0, 2] full_op = op_b.tensor(id1).tensor(op_a) rho_targ = rho.evolve(full_op) rho_test = rho.evolve(op, qargs=[0, 2]) self.assertEqual(rho_test, rho_targ) # Evolve on qubits [2, 0] full_op = op_a.tensor(id1).tensor(op_b) rho_targ = rho.evolve(full_op) rho_test = rho.evolve(op, qargs=[2, 0]) self.assertEqual(rho_test, rho_targ) # Test 3-qubit evolution op = op_c.tensor(op_b).tensor(op_a) # Evolve on qubits [0, 1, 2] full_op = op rho_targ = rho.evolve(full_op) rho_test = rho.evolve(op, qargs=[0, 1, 2]) self.assertEqual(rho_test, rho_targ) # Evolve on qubits [2, 1, 0] full_op = op_a.tensor(op_b).tensor(op_c) rho_targ = rho.evolve(full_op) rho_test = rho.evolve(op, qargs=[2, 1, 0]) self.assertEqual(rho_test, rho_targ) def test_is_cptp(self): """Test is_cptp method.""" self.assertTrue(SuperOp(self.depol_sop(0.25)).is_cptp()) # Non-CPTP should return false self.assertFalse(SuperOp(1.25 * self.sopI - 0.25 * self.depol_sop(1)).is_cptp()) def test_conjugate(self): """Test conjugate method.""" mat = self.rand_matrix(4, 4) chan = SuperOp(mat) targ = SuperOp(np.conjugate(mat)) self.assertEqual(chan.conjugate(), targ) def test_transpose(self): """Test transpose method.""" mat = self.rand_matrix(4, 4) chan = SuperOp(mat) targ = SuperOp(np.transpose(mat)) self.assertEqual(chan.transpose(), targ) def test_adjoint(self): """Test adjoint method.""" mat = self.rand_matrix(4, 4) chan = SuperOp(mat) targ = SuperOp(np.transpose(np.conj(mat))) self.assertEqual(chan.adjoint(), targ) def test_compose_except(self): """Test compose different dimension exception""" self.assertRaises(QiskitError, SuperOp(np.eye(4)).compose, SuperOp(np.eye(16))) self.assertRaises(QiskitError, SuperOp(np.eye(4)).compose, 2) def test_compose(self): """Test compose method.""" # UnitaryChannel evolution chan1 = SuperOp(self.sopX) chan2 = SuperOp(self.sopY) chan = chan1.compose(chan2) targ = SuperOp(self.sopZ) self.assertEqual(chan, targ) # 50% depolarizing channel chan1 = SuperOp(self.depol_sop(0.5)) chan = chan1.compose(chan1) targ = SuperOp(self.depol_sop(0.75)) self.assertEqual(chan, targ) # Random superoperator mat1 = self.rand_matrix(4, 4) mat2 = self.rand_matrix(4, 4) chan1 = SuperOp(mat1) chan2 = SuperOp(mat2) targ = SuperOp(np.dot(mat2, mat1)) self.assertEqual(chan1.compose(chan2), targ) self.assertEqual(chan1 & chan2, targ) targ = SuperOp(np.dot(mat1, mat2)) self.assertEqual(chan2.compose(chan1), targ) self.assertEqual(chan2 & chan1, targ) # Compose different dimensions chan1 = SuperOp(self.rand_matrix(16, 4)) chan2 = SuperOp( self.rand_matrix(4, 16), ) chan = chan1.compose(chan2) self.assertEqual(chan.dim, (2, 2)) chan = chan2.compose(chan1) self.assertEqual(chan.dim, (4, 4)) def test_dot(self): """Test dot method.""" # UnitaryChannel evolution chan1 = SuperOp(self.sopX) chan2 = SuperOp(self.sopY) targ = SuperOp(self.sopZ) self.assertEqual(chan1.dot(chan2), targ) self.assertEqual(chan1 @ chan2, targ) # 50% depolarizing channel chan1 = SuperOp(self.depol_sop(0.5)) targ = SuperOp(self.depol_sop(0.75)) self.assertEqual(chan1.dot(chan1), targ) self.assertEqual(chan1 @ chan1, targ) # Random superoperator mat1 = self.rand_matrix(4, 4) mat2 = self.rand_matrix(4, 4) chan1 = SuperOp(mat1) chan2 = SuperOp(mat2) targ = SuperOp(np.dot(mat2, mat1)) self.assertEqual(chan2.dot(chan1), targ) targ = SuperOp(np.dot(mat1, mat2)) # Compose different dimensions chan1 = SuperOp(self.rand_matrix(16, 4)) chan2 = SuperOp(self.rand_matrix(4, 16)) chan = chan1.dot(chan2) self.assertEqual(chan.dim, (4, 4)) chan = chan1 @ chan2 self.assertEqual(chan.dim, (4, 4)) chan = chan2.dot(chan1) self.assertEqual(chan.dim, (2, 2)) chan = chan2 @ chan1 self.assertEqual(chan.dim, (2, 2)) def test_compose_front(self): """Test front compose method.""" # DEPRECATED # UnitaryChannel evolution chan1 = SuperOp(self.sopX) chan2 = SuperOp(self.sopY) chan = chan1.compose(chan2, front=True) targ = SuperOp(self.sopZ) self.assertEqual(chan, targ) # 50% depolarizing channel chan1 = SuperOp(self.depol_sop(0.5)) chan = chan1.compose(chan1, front=True) targ = SuperOp(self.depol_sop(0.75)) self.assertEqual(chan, targ) # Random superoperator mat1 = self.rand_matrix(4, 4) mat2 = self.rand_matrix(4, 4) chan1 = SuperOp(mat1) chan2 = SuperOp(mat2) targ = SuperOp(np.dot(mat2, mat1)) self.assertEqual(chan2.compose(chan1, front=True), targ) targ = SuperOp(np.dot(mat1, mat2)) self.assertEqual(chan1.compose(chan2, front=True), targ) # Compose different dimensions chan1 = SuperOp(self.rand_matrix(16, 4)) chan2 = SuperOp(self.rand_matrix(4, 16)) chan = chan1.compose(chan2, front=True) self.assertEqual(chan.dim, (4, 4)) chan = chan2.compose(chan1, front=True) self.assertEqual(chan.dim, (2, 2)) def test_compose_subsystem(self): """Test subsystem compose method.""" # 3-qubit superoperator mat = self.rand_matrix(64, 64) mat_a = self.rand_matrix(4, 4) mat_b = self.rand_matrix(4, 4) mat_c = self.rand_matrix(4, 4) iden = SuperOp(np.eye(4)) op = SuperOp(mat) op1 = SuperOp(mat_a) op2 = SuperOp(mat_b).tensor(SuperOp(mat_a)) op3 = SuperOp(mat_c).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a)) # op3 qargs=[0, 1, 2] full_op = SuperOp(mat_c).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a)) targ = np.dot(full_op.data, mat) self.assertEqual(op.compose(op3, qargs=[0, 1, 2]), SuperOp(targ)) self.assertEqual(op & op3([0, 1, 2]), SuperOp(targ)) # op3 qargs=[2, 1, 0] full_op = SuperOp(mat_a).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_c)) targ = np.dot(full_op.data, mat) self.assertEqual(op.compose(op3, qargs=[2, 1, 0]), SuperOp(targ)) self.assertEqual(op & op3([2, 1, 0]), SuperOp(targ)) # op2 qargs=[0, 1] full_op = iden.tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a)) targ = np.dot(full_op.data, mat) self.assertEqual(op.compose(op2, qargs=[0, 1]), SuperOp(targ)) self.assertEqual(op & op2([0, 1]), SuperOp(targ)) # op2 qargs=[2, 0] full_op = SuperOp(mat_a).tensor(iden).tensor(SuperOp(mat_b)) targ = np.dot(full_op.data, mat) self.assertEqual(op.compose(op2, qargs=[2, 0]), SuperOp(targ)) self.assertEqual(op & op2([2, 0]), SuperOp(targ)) # op1 qargs=[0] full_op = iden.tensor(iden).tensor(SuperOp(mat_a)) targ = np.dot(full_op.data, mat) self.assertEqual(op.compose(op1, qargs=[0]), SuperOp(targ)) self.assertEqual(op & op1([0]), SuperOp(targ)) # op1 qargs=[1] full_op = iden.tensor(SuperOp(mat_a)).tensor(iden) targ = np.dot(full_op.data, mat) self.assertEqual(op.compose(op1, qargs=[1]), SuperOp(targ)) self.assertEqual(op & op1([1]), SuperOp(targ)) # op1 qargs=[2] full_op = SuperOp(mat_a).tensor(iden).tensor(iden) targ = np.dot(full_op.data, mat) self.assertEqual(op.compose(op1, qargs=[2]), SuperOp(targ)) self.assertEqual(op & op1([2]), SuperOp(targ)) def test_dot_subsystem(self): """Test subsystem dot method.""" # 3-qubit operator mat = self.rand_matrix(64, 64) mat_a = self.rand_matrix(4, 4) mat_b = self.rand_matrix(4, 4) mat_c = self.rand_matrix(4, 4) iden = SuperOp(np.eye(4)) op = SuperOp(mat) op1 = SuperOp(mat_a) op2 = SuperOp(mat_b).tensor(SuperOp(mat_a)) op3 = SuperOp(mat_c).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a)) # op3 qargs=[0, 1, 2] full_op = SuperOp(mat_c).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a)) targ = np.dot(mat, full_op.data) self.assertEqual(op.dot(op3, qargs=[0, 1, 2]), SuperOp(targ)) # op3 qargs=[2, 1, 0] full_op = SuperOp(mat_a).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_c)) targ = np.dot(mat, full_op.data) self.assertEqual(op.dot(op3, qargs=[2, 1, 0]), SuperOp(targ)) # op2 qargs=[0, 1] full_op = iden.tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a)) targ = np.dot(mat, full_op.data) self.assertEqual(op.dot(op2, qargs=[0, 1]), SuperOp(targ)) # op2 qargs=[2, 0] full_op = SuperOp(mat_a).tensor(iden).tensor(SuperOp(mat_b)) targ = np.dot(mat, full_op.data) self.assertEqual(op.dot(op2, qargs=[2, 0]), SuperOp(targ)) # op1 qargs=[0] full_op = iden.tensor(iden).tensor(SuperOp(mat_a)) targ = np.dot(mat, full_op.data) self.assertEqual(op.dot(op1, qargs=[0]), SuperOp(targ)) # op1 qargs=[1] full_op = iden.tensor(SuperOp(mat_a)).tensor(iden) targ = np.dot(mat, full_op.data) self.assertEqual(op.dot(op1, qargs=[1]), SuperOp(targ)) # op1 qargs=[2] full_op = SuperOp(mat_a).tensor(iden).tensor(iden) targ = np.dot(mat, full_op.data) self.assertEqual(op.dot(op1, qargs=[2]), SuperOp(targ)) def test_compose_front_subsystem(self): """Test subsystem front compose method.""" # 3-qubit operator mat = self.rand_matrix(64, 64) mat_a = self.rand_matrix(4, 4) mat_b = self.rand_matrix(4, 4) mat_c = self.rand_matrix(4, 4) iden = SuperOp(np.eye(4)) op = SuperOp(mat) op1 = SuperOp(mat_a) op2 = SuperOp(mat_b).tensor(SuperOp(mat_a)) op3 = SuperOp(mat_c).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a)) # op3 qargs=[0, 1, 2] full_op = SuperOp(mat_c).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a)) targ = np.dot(mat, full_op.data) self.assertEqual(op.compose(op3, qargs=[0, 1, 2], front=True), SuperOp(targ)) # op3 qargs=[2, 1, 0] full_op = SuperOp(mat_a).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_c)) targ = np.dot(mat, full_op.data) self.assertEqual(op.compose(op3, qargs=[2, 1, 0], front=True), SuperOp(targ)) # op2 qargs=[0, 1] full_op = iden.tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a)) targ = np.dot(mat, full_op.data) self.assertEqual(op.compose(op2, qargs=[0, 1], front=True), SuperOp(targ)) # op2 qargs=[2, 0] full_op = SuperOp(mat_a).tensor(iden).tensor(SuperOp(mat_b)) targ = np.dot(mat, full_op.data) self.assertEqual(op.compose(op2, qargs=[2, 0], front=True), SuperOp(targ)) # op1 qargs=[0] full_op = iden.tensor(iden).tensor(SuperOp(mat_a)) targ = np.dot(mat, full_op.data) self.assertEqual(op.compose(op1, qargs=[0], front=True), SuperOp(targ)) # op1 qargs=[1] full_op = iden.tensor(SuperOp(mat_a)).tensor(iden) targ = np.dot(mat, full_op.data) self.assertEqual(op.compose(op1, qargs=[1], front=True), SuperOp(targ)) # op1 qargs=[2] full_op = SuperOp(mat_a).tensor(iden).tensor(iden) targ = np.dot(mat, full_op.data) self.assertEqual(op.compose(op1, qargs=[2], front=True), SuperOp(targ)) def test_expand(self): """Test expand method.""" rho0, rho1 = np.diag([1, 0]), np.diag([0, 1]) rho_init = DensityMatrix(np.kron(rho0, rho0)) chan1 = SuperOp(self.sopI) chan2 = SuperOp(self.sopX) # X \otimes I chan = chan1.expand(chan2) rho_targ = DensityMatrix(np.kron(rho1, rho0)) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) # I \otimes X chan = chan2.expand(chan1) rho_targ = DensityMatrix(np.kron(rho0, rho1)) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) def test_tensor(self): """Test tensor method.""" rho0, rho1 = np.diag([1, 0]), np.diag([0, 1]) rho_init = DensityMatrix(np.kron(rho0, rho0)) chan1 = SuperOp(self.sopI) chan2 = SuperOp(self.sopX) # X \otimes I chan = chan2.tensor(chan1) rho_targ = DensityMatrix(np.kron(rho1, rho0)) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) chan = chan2 ^ chan1 self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) # I \otimes X chan = chan1.tensor(chan2) rho_targ = DensityMatrix(np.kron(rho0, rho1)) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) chan = chan1 ^ chan2 self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) def test_power(self): """Test power method.""" # 10% depolarizing channel p_id = 0.9 depol = SuperOp(self.depol_sop(1 - p_id)) # Compose 3 times p_id3 = p_id**3 chan3 = depol.power(3) targ3 = SuperOp(self.depol_sop(1 - p_id3)) self.assertEqual(chan3, targ3) def test_add(self): """Test add method.""" mat1 = 0.5 * self.sopI mat2 = 0.5 * self.depol_sop(1) chan1 = SuperOp(mat1) chan2 = SuperOp(mat2) targ = SuperOp(mat1 + mat2) self.assertEqual(chan1._add(chan2), targ) self.assertEqual(chan1 + chan2, targ) targ = SuperOp(mat1 - mat2) self.assertEqual(chan1 - chan2, targ) def test_add_qargs(self): """Test add method with qargs.""" mat = self.rand_matrix(8**2, 8**2) mat0 = self.rand_matrix(4, 4) mat1 = self.rand_matrix(4, 4) op = SuperOp(mat) op0 = SuperOp(mat0) op1 = SuperOp(mat1) op01 = op1.tensor(op0) eye = SuperOp(self.sopI) with self.subTest(msg="qargs=[0]"): value = op + op0([0]) target = op + eye.tensor(eye).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[1]"): value = op + op0([1]) target = op + eye.tensor(op0).tensor(eye) self.assertEqual(value, target) with self.subTest(msg="qargs=[2]"): value = op + op0([2]) target = op + op0.tensor(eye).tensor(eye) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 1]"): value = op + op01([0, 1]) target = op + eye.tensor(op1).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[1, 0]"): value = op + op01([1, 0]) target = op + eye.tensor(op0).tensor(op1) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 2]"): value = op + op01([0, 2]) target = op + op1.tensor(eye).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[2, 0]"): value = op + op01([2, 0]) target = op + op0.tensor(eye).tensor(op1) self.assertEqual(value, target) def test_sub_qargs(self): """Test subtract method with qargs.""" mat = self.rand_matrix(8**2, 8**2) mat0 = self.rand_matrix(4, 4) mat1 = self.rand_matrix(4, 4) op = SuperOp(mat) op0 = SuperOp(mat0) op1 = SuperOp(mat1) op01 = op1.tensor(op0) eye = SuperOp(self.sopI) with self.subTest(msg="qargs=[0]"): value = op - op0([0]) target = op - eye.tensor(eye).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[1]"): value = op - op0([1]) target = op - eye.tensor(op0).tensor(eye) self.assertEqual(value, target) with self.subTest(msg="qargs=[2]"): value = op - op0([2]) target = op - op0.tensor(eye).tensor(eye) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 1]"): value = op - op01([0, 1]) target = op - eye.tensor(op1).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[1, 0]"): value = op - op01([1, 0]) target = op - eye.tensor(op0).tensor(op1) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 2]"): value = op - op01([0, 2]) target = op - op1.tensor(eye).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[2, 0]"): value = op - op01([2, 0]) target = op - op0.tensor(eye).tensor(op1) self.assertEqual(value, target) def test_add_except(self): """Test add method raises exceptions.""" chan1 = SuperOp(self.sopI) chan2 = SuperOp(np.eye(16)) self.assertRaises(QiskitError, chan1._add, chan2) self.assertRaises(QiskitError, chan1._add, 5) def test_multiply(self): """Test multiply method.""" chan = SuperOp(self.sopI) val = 0.5 targ = SuperOp(val * self.sopI) self.assertEqual(chan._multiply(val), targ) self.assertEqual(val * chan, targ) targ = SuperOp(self.sopI * val) self.assertEqual(chan * val, targ) def test_multiply_except(self): """Test multiply method raises exceptions.""" chan = SuperOp(self.sopI) self.assertRaises(QiskitError, chan._multiply, "s") self.assertRaises(QiskitError, chan.__rmul__, "s") self.assertRaises(QiskitError, chan._multiply, chan) self.assertRaises(QiskitError, chan.__rmul__, chan) def test_negate(self): """Test negate method""" chan = SuperOp(self.sopI) targ = SuperOp(-self.sopI) self.assertEqual(-chan, targ) if __name__ == "__main__": unittest.main()
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# 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 quantum channel representation transformations.""" import unittest import numpy as np from qiskit import QiskitError from qiskit.quantum_info.states import DensityMatrix from qiskit.quantum_info.operators.predicates import matrix_equal from qiskit.quantum_info.operators.operator import Operator from qiskit.quantum_info.operators.channel.choi import Choi from qiskit.quantum_info.operators.channel.superop import SuperOp from qiskit.quantum_info.operators.channel.kraus import Kraus from qiskit.quantum_info.operators.channel.stinespring import Stinespring from qiskit.quantum_info.operators.channel.ptm import PTM from qiskit.quantum_info.operators.channel.chi import Chi from .channel_test_case import ChannelTestCase class TestTransformations(ChannelTestCase): """Tests for Operator channel representation.""" unitary_mat = [ ChannelTestCase.UI, ChannelTestCase.UX, ChannelTestCase.UY, ChannelTestCase.UZ, ChannelTestCase.UH, ] unitary_choi = [ ChannelTestCase.choiI, ChannelTestCase.choiX, ChannelTestCase.choiY, ChannelTestCase.choiZ, ChannelTestCase.choiH, ] unitary_chi = [ ChannelTestCase.chiI, ChannelTestCase.chiX, ChannelTestCase.chiY, ChannelTestCase.chiZ, ChannelTestCase.chiH, ] unitary_sop = [ ChannelTestCase.sopI, ChannelTestCase.sopX, ChannelTestCase.sopY, ChannelTestCase.sopZ, ChannelTestCase.sopH, ] unitary_ptm = [ ChannelTestCase.ptmI, ChannelTestCase.ptmX, ChannelTestCase.ptmY, ChannelTestCase.ptmZ, ChannelTestCase.ptmH, ] def test_operator_to_operator(self): """Test Operator to Operator transformation.""" # Test unitary channels for mat in self.unitary_mat: chan1 = Operator(mat) chan2 = Operator(chan1) self.assertEqual(chan1, chan2) def test_operator_to_choi(self): """Test Operator to Choi transformation.""" # Test unitary channels for mat, choi in zip(self.unitary_mat, self.unitary_choi): chan1 = Choi(choi) chan2 = Choi(Operator(mat)) self.assertEqual(chan1, chan2) def test_operator_to_superop(self): """Test Operator to SuperOp transformation.""" # Test unitary channels for mat, sop in zip(self.unitary_mat, self.unitary_sop): chan1 = SuperOp(sop) chan2 = SuperOp(Operator(mat)) self.assertEqual(chan1, chan2) def test_operator_to_kraus(self): """Test Operator to Kraus transformation.""" # Test unitary channels for mat in self.unitary_mat: chan1 = Kraus(mat) chan2 = Kraus(Operator(mat)) self.assertEqual(chan1, chan2) def test_operator_to_stinespring(self): """Test Operator to Stinespring transformation.""" # Test unitary channels for mat in self.unitary_mat: chan1 = Stinespring(mat) chan2 = Stinespring(Operator(chan1)) self.assertEqual(chan1, chan2) def test_operator_to_chi(self): """Test Operator to Chi transformation.""" # Test unitary channels for mat, chi in zip(self.unitary_mat, self.unitary_chi): chan1 = Chi(chi) chan2 = Chi(Operator(mat)) self.assertEqual(chan1, chan2) def test_operator_to_ptm(self): """Test Operator to PTM transformation.""" # Test unitary channels for mat, ptm in zip(self.unitary_mat, self.unitary_ptm): chan1 = PTM(ptm) chan2 = PTM(Operator(mat)) self.assertEqual(chan1, chan2) def test_choi_to_operator(self): """Test Choi to Operator transformation.""" # Test unitary channels for mat, choi in zip(self.unitary_mat, self.unitary_choi): chan1 = Operator(mat) chan2 = Operator(Choi(choi)) self.assertTrue(matrix_equal(chan2.data, chan1.data, ignore_phase=True)) def test_choi_to_choi(self): """Test Choi to Choi transformation.""" # Test unitary channels for choi in self.unitary_choi: chan1 = Choi(choi) chan2 = Choi(chan1) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = Choi(self.depol_choi(p)) chan2 = Choi(chan1) self.assertEqual(chan1, chan2) def test_choi_to_superop(self): """Test Choi to SuperOp transformation.""" # Test unitary channels for choi, sop in zip(self.unitary_choi, self.unitary_sop): chan1 = SuperOp(sop) chan2 = SuperOp(Choi(choi)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = SuperOp(self.depol_sop(p)) chan2 = SuperOp(Choi(self.depol_choi(p))) self.assertEqual(chan1, chan2) def test_choi_to_kraus(self): """Test Choi to Kraus transformation.""" # Test unitary channels for mat, choi in zip(self.unitary_mat, self.unitary_choi): chan1 = Kraus(mat) chan2 = Kraus(Choi(choi)) self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True)) # Test depolarizing channels rho = DensityMatrix(np.diag([1, 0])) for p in [0.25, 0.5, 0.75, 1]: target = rho.evolve(Kraus(self.depol_kraus(p))) output = rho.evolve(Kraus(Choi(self.depol_choi(p)))) self.assertEqual(output, target) def test_choi_to_stinespring(self): """Test Choi to Stinespring transformation.""" # Test unitary channels for mat, choi in zip(self.unitary_mat, self.unitary_choi): chan1 = Kraus(mat) chan2 = Kraus(Choi(choi)) self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True)) # Test depolarizing channels rho = DensityMatrix(np.diag([1, 0])) for p in [0.25, 0.5, 0.75, 1]: target = rho.evolve(Stinespring(self.depol_stine(p))) output = rho.evolve(Stinespring(Choi(self.depol_choi(p)))) self.assertEqual(output, target) def test_choi_to_chi(self): """Test Choi to Chi transformation.""" # Test unitary channels for choi, chi in zip(self.unitary_choi, self.unitary_chi): chan1 = Chi(chi) chan2 = Chi(Choi(choi)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = Chi(self.depol_chi(p)) chan2 = Chi(Choi(self.depol_choi(p))) self.assertEqual(chan1, chan2) def test_choi_to_ptm(self): """Test Choi to PTM transformation.""" # Test unitary channels for choi, ptm in zip(self.unitary_choi, self.unitary_ptm): chan1 = PTM(ptm) chan2 = PTM(Choi(choi)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = PTM(self.depol_ptm(p)) chan2 = PTM(Choi(self.depol_choi(p))) self.assertEqual(chan1, chan2) def test_superop_to_operator(self): """Test SuperOp to Operator transformation.""" for mat, sop in zip(self.unitary_mat, self.unitary_sop): chan1 = Operator(mat) chan2 = Operator(SuperOp(sop)) self.assertTrue(matrix_equal(chan2.data, chan1.data, ignore_phase=True)) self.assertRaises(QiskitError, Operator, SuperOp(self.depol_sop(0.5))) def test_superop_to_choi(self): """Test SuperOp to Choi transformation.""" # Test unitary channels for choi, sop in zip(self.unitary_choi, self.unitary_sop): chan1 = Choi(choi) chan2 = Choi(SuperOp(sop)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0, 0.25, 0.5, 0.75, 1]: chan1 = Choi(self.depol_choi(p)) chan2 = Choi(SuperOp(self.depol_sop(p))) self.assertEqual(chan1, chan2) def test_superop_to_superop(self): """Test SuperOp to SuperOp transformation.""" # Test unitary channels for sop in self.unitary_sop: chan1 = SuperOp(sop) chan2 = SuperOp(chan1) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0, 0.25, 0.5, 0.75, 1]: chan1 = SuperOp(self.depol_sop(p)) chan2 = SuperOp(chan1) self.assertEqual(chan1, chan2) def test_superop_to_kraus(self): """Test SuperOp to Kraus transformation.""" # Test unitary channels for mat, sop in zip(self.unitary_mat, self.unitary_sop): chan1 = Kraus(mat) chan2 = Kraus(SuperOp(sop)) self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True)) # Test depolarizing channels rho = DensityMatrix(np.diag([1, 0])) for p in [0.25, 0.5, 0.75, 1]: target = rho.evolve(Kraus(self.depol_kraus(p))) output = rho.evolve(Kraus(SuperOp(self.depol_sop(p)))) self.assertEqual(output, target) def test_superop_to_stinespring(self): """Test SuperOp to Stinespring transformation.""" # Test unitary channels for mat, sop in zip(self.unitary_mat, self.unitary_sop): chan1 = Stinespring(mat) chan2 = Stinespring(SuperOp(sop)) self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True)) # Test depolarizing channels rho = DensityMatrix(np.diag([1, 0])) for p in [0.25, 0.5, 0.75, 1]: target = rho.evolve(Stinespring(self.depol_stine(p))) output = rho.evolve(Stinespring(SuperOp(self.depol_sop(p)))) self.assertEqual(output, target) def test_superop_to_chi(self): """Test SuperOp to Chi transformation.""" # Test unitary channels for sop, ptm in zip(self.unitary_sop, self.unitary_ptm): chan1 = PTM(ptm) chan2 = PTM(SuperOp(sop)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = Chi(self.depol_chi(p)) chan2 = Chi(SuperOp(self.depol_sop(p))) self.assertEqual(chan1, chan2) def test_superop_to_ptm(self): """Test SuperOp to PTM transformation.""" # Test unitary channels for sop, ptm in zip(self.unitary_sop, self.unitary_ptm): chan1 = PTM(ptm) chan2 = PTM(SuperOp(sop)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = PTM(self.depol_ptm(p)) chan2 = PTM(SuperOp(self.depol_sop(p))) self.assertEqual(chan1, chan2) def test_kraus_to_operator(self): """Test Kraus to Operator transformation.""" for mat in self.unitary_mat: chan1 = Operator(mat) chan2 = Operator(Kraus(mat)) self.assertTrue(matrix_equal(chan2.data, chan1.data, ignore_phase=True)) self.assertRaises(QiskitError, Operator, Kraus(self.depol_kraus(0.5))) def test_kraus_to_choi(self): """Test Kraus to Choi transformation.""" # Test unitary channels for mat, choi in zip(self.unitary_mat, self.unitary_choi): chan1 = Choi(choi) chan2 = Choi(Kraus(mat)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = Choi(self.depol_choi(p)) chan2 = Choi(Kraus(self.depol_kraus(p))) self.assertEqual(chan1, chan2) def test_kraus_to_superop(self): """Test Kraus to SuperOp transformation.""" # Test unitary channels for mat, sop in zip(self.unitary_mat, self.unitary_sop): chan1 = SuperOp(sop) chan2 = SuperOp(Kraus(mat)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = SuperOp(self.depol_sop(p)) chan2 = SuperOp(Kraus(self.depol_kraus(p))) self.assertEqual(chan1, chan2) def test_kraus_to_kraus(self): """Test Kraus to Kraus transformation.""" # Test unitary channels for mat in self.unitary_mat: chan1 = Kraus(mat) chan2 = Kraus(chan1) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = Kraus(self.depol_kraus(p)) chan2 = Kraus(chan1) self.assertEqual(chan1, chan2) def test_kraus_to_stinespring(self): """Test Kraus to Stinespring transformation.""" # Test unitary channels for mat in self.unitary_mat: chan1 = Stinespring(mat) chan2 = Stinespring(Kraus(mat)) self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True)) # Test depolarizing channels rho = DensityMatrix(np.diag([1, 0])) for p in [0.25, 0.5, 0.75, 1]: target = rho.evolve(Stinespring(self.depol_stine(p))) output = rho.evolve(Stinespring(Kraus(self.depol_kraus(p)))) self.assertEqual(output, target) def test_kraus_to_chi(self): """Test Kraus to Chi transformation.""" # Test unitary channels for mat, chi in zip(self.unitary_mat, self.unitary_chi): chan1 = Chi(chi) chan2 = Chi(Kraus(mat)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = Chi(self.depol_chi(p)) chan2 = Chi(Kraus(self.depol_kraus(p))) self.assertEqual(chan1, chan2) def test_kraus_to_ptm(self): """Test Kraus to PTM transformation.""" # Test unitary channels for mat, ptm in zip(self.unitary_mat, self.unitary_ptm): chan1 = PTM(ptm) chan2 = PTM(Kraus(mat)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = PTM(self.depol_ptm(p)) chan2 = PTM(Kraus(self.depol_kraus(p))) self.assertEqual(chan1, chan2) def test_stinespring_to_operator(self): """Test Stinespring to Operator transformation.""" for mat in self.unitary_mat: chan1 = Operator(mat) chan2 = Operator(Stinespring(mat)) self.assertTrue(matrix_equal(chan2.data, chan1.data, ignore_phase=True)) self.assertRaises(QiskitError, Operator, Stinespring(self.depol_stine(0.5))) def test_stinespring_to_choi(self): """Test Stinespring to Choi transformation.""" # Test unitary channels for mat, choi in zip(self.unitary_mat, self.unitary_choi): chan1 = Choi(choi) chan2 = Choi(Stinespring(mat)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = Choi(self.depol_choi(p)) chan2 = Choi(Stinespring(self.depol_stine(p))) self.assertEqual(chan1, chan2) def test_stinespring_to_superop(self): """Test Stinespring to SuperOp transformation.""" # Test unitary channels for mat, sop in zip(self.unitary_mat, self.unitary_sop): chan1 = SuperOp(sop) chan2 = SuperOp(Kraus(mat)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = SuperOp(self.depol_sop(p)) chan2 = SuperOp(Stinespring(self.depol_stine(p))) self.assertEqual(chan1, chan2) def test_stinespring_to_kraus(self): """Test Stinespring to Kraus transformation.""" # Test unitary channels for mat in self.unitary_mat: chan1 = Kraus(mat) chan2 = Kraus(Stinespring(mat)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = Kraus(self.depol_kraus(p)) chan2 = Kraus(Stinespring(self.depol_stine(p))) self.assertEqual(chan1, chan2) def test_stinespring_to_stinespring(self): """Test Stinespring to Stinespring transformation.""" # Test unitary channels for mat in self.unitary_mat: chan1 = Stinespring(mat) chan2 = Stinespring(chan1) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = Stinespring(self.depol_stine(p)) chan2 = Stinespring(chan1) self.assertEqual(chan1, chan2) def test_stinespring_to_chi(self): """Test Stinespring to Chi transformation.""" # Test unitary channels for mat, chi in zip(self.unitary_mat, self.unitary_chi): chan1 = Chi(chi) chan2 = Chi(Stinespring(mat)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = Chi(self.depol_chi(p)) chan2 = Chi(Stinespring(self.depol_stine(p))) self.assertEqual(chan1, chan2) def test_stinespring_to_ptm(self): """Test Stinespring to PTM transformation.""" # Test unitary channels for mat, ptm in zip(self.unitary_mat, self.unitary_ptm): chan1 = PTM(ptm) chan2 = PTM(Stinespring(mat)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = PTM(self.depol_ptm(p)) chan2 = PTM(Stinespring(self.depol_stine(p))) self.assertEqual(chan1, chan2) def test_chi_to_operator(self): """Test Chi to Operator transformation.""" for mat, chi in zip(self.unitary_mat, self.unitary_chi): chan1 = Operator(mat) chan2 = Operator(Chi(chi)) self.assertTrue(matrix_equal(chan2.data, chan1.data, ignore_phase=True)) self.assertRaises(QiskitError, Operator, Chi(self.depol_chi(0.5))) def test_chi_to_choi(self): """Test Chi to Choi transformation.""" # Test unitary channels for chi, choi in zip(self.unitary_chi, self.unitary_choi): chan1 = Choi(choi) chan2 = Choi(Chi(chi)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = Choi(self.depol_choi(p)) chan2 = Choi(Chi(self.depol_chi(p))) self.assertEqual(chan1, chan2) def test_chi_to_superop(self): """Test Chi to SuperOp transformation.""" # Test unitary channels for chi, sop in zip(self.unitary_chi, self.unitary_sop): chan1 = SuperOp(sop) chan2 = SuperOp(Chi(chi)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = SuperOp(self.depol_sop(p)) chan2 = SuperOp(Chi(self.depol_chi(p))) self.assertEqual(chan1, chan2) def test_chi_to_kraus(self): """Test Chi to Kraus transformation.""" # Test unitary channels for mat, chi in zip(self.unitary_mat, self.unitary_chi): chan1 = Kraus(mat) chan2 = Kraus(Chi(chi)) self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True)) # Test depolarizing channels rho = DensityMatrix(np.diag([1, 0])) for p in [0.25, 0.5, 0.75, 1]: target = rho.evolve(Kraus(self.depol_kraus(p))) output = rho.evolve(Kraus(Chi(self.depol_chi(p)))) self.assertEqual(output, target) def test_chi_to_stinespring(self): """Test Chi to Stinespring transformation.""" # Test unitary channels for mat, chi in zip(self.unitary_mat, self.unitary_chi): chan1 = Kraus(mat) chan2 = Kraus(Chi(chi)) self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True)) # Test depolarizing channels rho = DensityMatrix(np.diag([1, 0])) for p in [0.25, 0.5, 0.75, 1]: target = rho.evolve(Stinespring(self.depol_stine(p))) output = rho.evolve(Stinespring(Chi(self.depol_chi(p)))) self.assertEqual(output, target) def test_chi_to_chi(self): """Test Chi to Chi transformation.""" # Test unitary channels for chi in self.unitary_chi: chan1 = Chi(chi) chan2 = Chi(chan1) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = Chi(self.depol_chi(p)) chan2 = Chi(chan1) self.assertEqual(chan1, chan2) def test_chi_to_ptm(self): """Test Chi to PTM transformation.""" # Test unitary channels for chi, ptm in zip(self.unitary_chi, self.unitary_ptm): chan1 = PTM(ptm) chan2 = PTM(Chi(chi)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = PTM(self.depol_ptm(p)) chan2 = PTM(Chi(self.depol_chi(p))) self.assertEqual(chan1, chan2) def test_ptm_to_operator(self): """Test PTM to Operator transformation.""" for mat, ptm in zip(self.unitary_mat, self.unitary_ptm): chan1 = Operator(mat) chan2 = Operator(PTM(ptm)) self.assertTrue(matrix_equal(chan2.data, chan1.data, ignore_phase=True)) self.assertRaises(QiskitError, Operator, PTM(self.depol_ptm(0.5))) def test_ptm_to_choi(self): """Test PTM to Choi transformation.""" # Test unitary channels for ptm, choi in zip(self.unitary_ptm, self.unitary_choi): chan1 = Choi(choi) chan2 = Choi(PTM(ptm)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = Choi(self.depol_choi(p)) chan2 = Choi(PTM(self.depol_ptm(p))) self.assertEqual(chan1, chan2) def test_ptm_to_superop(self): """Test PTM to SuperOp transformation.""" # Test unitary channels for ptm, sop in zip(self.unitary_ptm, self.unitary_sop): chan1 = SuperOp(sop) chan2 = SuperOp(PTM(ptm)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = SuperOp(self.depol_sop(p)) chan2 = SuperOp(PTM(self.depol_ptm(p))) self.assertEqual(chan1, chan2) def test_ptm_to_kraus(self): """Test PTM to Kraus transformation.""" # Test unitary channels for mat, ptm in zip(self.unitary_mat, self.unitary_ptm): chan1 = Kraus(mat) chan2 = Kraus(PTM(ptm)) self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True)) # Test depolarizing channels rho = DensityMatrix(np.diag([1, 0])) for p in [0.25, 0.5, 0.75, 1]: target = rho.evolve(Kraus(self.depol_kraus(p))) output = rho.evolve(Kraus(PTM(self.depol_ptm(p)))) self.assertEqual(output, target) def test_ptm_to_stinespring(self): """Test PTM to Stinespring transformation.""" # Test unitary channels for mat, ptm in zip(self.unitary_mat, self.unitary_ptm): chan1 = Kraus(mat) chan2 = Kraus(PTM(ptm)) self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True)) # Test depolarizing channels rho = DensityMatrix(np.diag([1, 0])) for p in [0.25, 0.5, 0.75, 1]: target = rho.evolve(Stinespring(self.depol_stine(p))) output = rho.evolve(Stinespring(PTM(self.depol_ptm(p)))) self.assertEqual(output, target) def test_ptm_to_chi(self): """Test PTM to Chi transformation.""" # Test unitary channels for chi, ptm in zip(self.unitary_chi, self.unitary_ptm): chan1 = Chi(chi) chan2 = Chi(PTM(ptm)) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = Chi(self.depol_chi(p)) chan2 = Chi(PTM(self.depol_ptm(p))) self.assertEqual(chan1, chan2) def test_ptm_to_ptm(self): """Test PTM to PTM transformation.""" # Test unitary channels for ptm in self.unitary_ptm: chan1 = PTM(ptm) chan2 = PTM(chan1) self.assertEqual(chan1, chan2) # Test depolarizing channels for p in [0.25, 0.5, 0.75, 1]: chan1 = PTM(self.depol_ptm(p)) chan2 = PTM(chan1) self.assertEqual(chan1, chan2) if __name__ == "__main__": unittest.main()
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# 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. # pylint: disable=invalid-name """Tests for Pauli operator class.""" import re import unittest import itertools as it from functools import lru_cache import numpy as np from ddt import ddt, data, unpack from qiskit import QuantumCircuit from qiskit.exceptions import QiskitError from qiskit.circuit.library import ( IGate, XGate, YGate, ZGate, HGate, SGate, SdgGate, CXGate, CZGate, CYGate, SwapGate, ) from qiskit.circuit.library.generalized_gates import PauliGate from qiskit.test import QiskitTestCase from qiskit.quantum_info.random import random_clifford, random_pauli from qiskit.quantum_info.operators import Pauli, Operator LABEL_REGEX = re.compile(r"(?P<coeff>[+-]?1?[ij]?)(?P<pauli>[IXYZ]*)") PHASE_MAP = {"": 0, "-i": 1, "-": 2, "i": 3} def _split_pauli_label(label): match_ = LABEL_REGEX.fullmatch(label) return match_["pauli"], match_["coeff"] def _phase_from_label(label): coeff = LABEL_REGEX.fullmatch(label)["coeff"] or "" return PHASE_MAP[coeff.replace("+", "").replace("1", "").replace("j", "i")] @lru_cache(maxsize=8) def pauli_group_labels(nq, full_group=True): """Generate list of the N-qubit pauli group string labels""" labels = ["".join(i) for i in it.product(("I", "X", "Y", "Z"), repeat=nq)] if full_group: labels = ["".join(i) for i in it.product(("", "-i", "-", "i"), labels)] return labels def operator_from_label(label): """Construct operator from full Pauli group label""" pauli, coeff = _split_pauli_label(label) coeff = (-1j) ** _phase_from_label(coeff) return coeff * Operator.from_label(pauli) @ddt class TestPauliConversions(QiskitTestCase): """Test representation conversions of Pauli""" @data(*pauli_group_labels(1), *pauli_group_labels(2)) def test_labels(self, label): """Test round trip label conversion""" pauli = Pauli(label) self.assertEqual(Pauli(str(pauli)), pauli) @data("S", "XX-") def test_invalid_labels(self, label): """Test raise if invalid labels are supplied""" with self.assertRaises(QiskitError): Pauli(label) @data(*pauli_group_labels(1), *pauli_group_labels(2)) def test_to_operator(self, label): """Test Pauli operator conversion""" value = Operator(Pauli(label)) target = operator_from_label(label) self.assertEqual(value, target) @data(*pauli_group_labels(1), *pauli_group_labels(2)) def test_to_matrix_sparse(self, label): """Test Pauli operator conversion""" spmat = Pauli(label).to_matrix(sparse=True) value = Operator(spmat.todense()) target = operator_from_label(label) self.assertEqual(value, target) @data(*pauli_group_labels(1), *pauli_group_labels(2)) def test_to_instruction(self, label): """Test Pauli to instruction""" pauli = Pauli(label) value = Operator(pauli.to_instruction()) target = Operator(pauli) self.assertEqual(value, target) @data((IGate(), "I"), (XGate(), "X"), (YGate(), "Y"), (ZGate(), "Z")) @unpack def test_init_single_pauli_gate(self, gate, label): """Test initialization from Pauli basis gates""" self.assertEqual(str(Pauli(gate)), label) @data("IXYZ", "XXY", "ZYX", "ZI", "Y") def test_init_pauli_gate(self, label): """Test initialization from Pauli basis gates""" pauli = Pauli(PauliGate(label)) self.assertEqual(str(pauli), label) @ddt class TestPauliProperties(QiskitTestCase): """Test Pauli properties""" @data("I", "XY", "XYZ", "IXYZ", "IXYZX") def test_len(self, label): """Test __len__ method""" self.assertEqual(len(Pauli(label)), len(label)) @data(*it.product(pauli_group_labels(1, full_group=False), pauli_group_labels(1))) @unpack def test_equal(self, label1, label2): """Test __eq__ method""" pauli1 = Pauli(label1) pauli2 = Pauli(label2) target = ( np.all(pauli1.z == pauli2.z) and np.all(pauli1.x == pauli2.x) and pauli1.phase == pauli2.phase ) self.assertEqual(pauli1 == pauli2, target) @data(*it.product(pauli_group_labels(1, full_group=False), pauli_group_labels(1))) @unpack def test_equiv(self, label1, label2): """Test equiv method""" pauli1 = Pauli(label1) pauli2 = Pauli(label2) target = np.all(pauli1.z == pauli2.z) and np.all(pauli1.x == pauli2.x) self.assertEqual(pauli1.equiv(pauli2), target) @data(*pauli_group_labels(1)) def test_phase(self, label): """Test phase attribute""" pauli = Pauli(label) _, coeff = _split_pauli_label(str(pauli)) target = _phase_from_label(coeff) self.assertEqual(pauli.phase, target) @data(*((p, q) for p in ["I", "X", "Y", "Z"] for q in range(4))) @unpack def test_phase_setter(self, pauli, phase): """Test phase setter""" pauli = Pauli(pauli) pauli.phase = phase _, coeff = _split_pauli_label(str(pauli)) value = _phase_from_label(coeff) self.assertEqual(value, phase) def test_x_setter(self): """Test phase attribute""" pauli = Pauli("II") pauli.x = True self.assertEqual(pauli, Pauli("XX")) def test_z_setter(self): """Test phase attribute""" pauli = Pauli("II") pauli.z = True self.assertEqual(pauli, Pauli("ZZ")) @data( *( ("IXYZ", i) for i in [0, 1, 2, 3, slice(None, None, None), slice(None, 2, None), [0, 3], [2, 1, 3]] ) ) @unpack def test_getitem(self, label, qubits): """Test __getitem__""" pauli = Pauli(label) value = str(pauli[qubits]) val_array = np.array(list(reversed(label)))[qubits] target = "".join(reversed(val_array.tolist())) self.assertEqual(value, target, msg=f"indices = {qubits}") @data( (0, "iY", "iIIY"), ([1, 0], "XZ", "IZX"), (slice(None, None, None), "XYZ", "XYZ"), (slice(None, None, -1), "XYZ", "ZYX"), ) @unpack def test_setitem(self, qubits, value, target): """Test __setitem__""" pauli = Pauli("III") pauli[qubits] = value self.assertEqual(str(pauli), target) def test_insert(self): """Test insert method""" pauli = Pauli("III") pauli = pauli.insert([2, 0, 4], "XYZ") self.assertEqual(str(pauli), "IXIZIY") def test_delete(self): """Test delete method""" pauli = Pauli("IXYZ") pauli = pauli.delete([0, 2]) self.assertEqual(str(pauli), "IY") @ddt class TestPauli(QiskitTestCase): """Tests for Pauli operator class.""" @data(*pauli_group_labels(2)) def test_conjugate(self, label): """Test conjugate method.""" value = Pauli(label).conjugate() target = operator_from_label(label).conjugate() self.assertEqual(Operator(value), target) @data(*pauli_group_labels(2)) def test_transpose(self, label): """Test transpose method.""" value = Pauli(label).transpose() target = operator_from_label(label).transpose() self.assertEqual(Operator(value), target) @data(*pauli_group_labels(2)) def test_adjoint(self, label): """Test adjoint method.""" value = Pauli(label).adjoint() target = operator_from_label(label).adjoint() self.assertEqual(Operator(value), target) @data(*pauli_group_labels(2)) def test_inverse(self, label): """Test inverse method.""" pauli = Pauli(label) value = pauli.inverse() target = pauli.adjoint() self.assertEqual(value, target) @data(*it.product(pauli_group_labels(2, full_group=False), repeat=2)) @unpack def test_dot(self, label1, label2): """Test dot method.""" p1 = Pauli(label1) p2 = Pauli(label2) value = Operator(p1.dot(p2)) op1 = operator_from_label(label1) op2 = operator_from_label(label2) target = op1.dot(op2) self.assertEqual(value, target) target = op1 @ op2 self.assertEqual(value, target) @data(*pauli_group_labels(1)) def test_dot_qargs(self, label2): """Test dot method with qargs.""" label1 = "-iXYZ" p1 = Pauli(label1) p2 = Pauli(label2) qargs = [0] value = Operator(p1.dot(p2, qargs=qargs)) op1 = operator_from_label(label1) op2 = operator_from_label(label2) target = op1.dot(op2, qargs=qargs) self.assertEqual(value, target) @data(*it.product(pauli_group_labels(2, full_group=False), repeat=2)) @unpack def test_compose(self, label1, label2): """Test compose method.""" p1 = Pauli(label1) p2 = Pauli(label2) value = Operator(p1.compose(p2)) op1 = operator_from_label(label1) op2 = operator_from_label(label2) target = op1.compose(op2) self.assertEqual(value, target) @data(*pauli_group_labels(1)) def test_compose_qargs(self, label2): """Test compose method with qargs.""" label1 = "-XYZ" p1 = Pauli(label1) p2 = Pauli(label2) qargs = [0] value = Operator(p1.compose(p2, qargs=qargs)) op1 = operator_from_label(label1) op2 = operator_from_label(label2) target = op1.compose(op2, qargs=qargs) self.assertEqual(value, target) @data(*it.product(pauli_group_labels(1, full_group=False), repeat=2)) @unpack def test_tensor(self, label1, label2): """Test tensor method.""" p1 = Pauli(label1) p2 = Pauli(label2) value = Operator(p1.tensor(p2)) op1 = operator_from_label(label1) op2 = operator_from_label(label2) target = op1.tensor(op2) self.assertEqual(value, target) @data(*it.product(pauli_group_labels(1, full_group=False), repeat=2)) @unpack def test_expand(self, label1, label2): """Test expand method.""" p1 = Pauli(label1) p2 = Pauli(label2) value = Operator(p1.expand(p2)) op1 = operator_from_label(label1) op2 = operator_from_label(label2) target = op1.expand(op2) self.assertEqual(value, target) @data("II", "XI", "YX", "ZZ", "YZ") def test_power(self, label): """Test power method.""" iden = Pauli("II") op = Pauli(label) self.assertTrue(op**2, iden) @data(1, 1.0, -1, -1.0, 1j, -1j) def test_multiply(self, val): """Test multiply method.""" op = val * Pauli(([True, True], [False, False], 0)) phase = (-1j) ** op.phase self.assertEqual(phase, val) op = Pauli(([True, True], [False, False], 0)) * val phase = (-1j) ** op.phase self.assertEqual(phase, val) def test_multiply_except(self): """Test multiply method raises exceptions.""" op = Pauli("XYZ") self.assertRaises(QiskitError, op._multiply, 2) @data(0, 1, 2, 3) def test_negate(self, phase): """Test negate method""" op = Pauli(([False], [True], phase)) neg = -op self.assertTrue(op.equiv(neg)) self.assertEqual(neg.phase, (op.phase + 2) % 4) @data(*it.product(pauli_group_labels(1, False), repeat=2)) @unpack def test_commutes(self, p1, p2): """Test commutes method""" P1 = Pauli(p1) P2 = Pauli(p2) self.assertEqual(P1.commutes(P2), P1.dot(P2) == P2.dot(P1)) @data(*it.product(pauli_group_labels(1, False), repeat=2)) @unpack def test_anticommutes(self, p1, p2): """Test anticommutes method""" P1 = Pauli(p1) P2 = Pauli(p2) self.assertEqual(P1.anticommutes(P2), P1.dot(P2) == -P2.dot(P1)) @data( *it.product( (IGate(), XGate(), YGate(), ZGate(), HGate(), SGate(), SdgGate()), pauli_group_labels(1, False), ) ) @unpack def test_evolve_clifford1(self, gate, label): """Test evolve method for 1-qubit Clifford gates.""" op = Operator(gate) pauli = Pauli(label) value = Operator(pauli.evolve(gate)) value_h = Operator(pauli.evolve(gate, frame="h")) value_s = Operator(pauli.evolve(gate, frame="s")) value_inv = Operator(pauli.evolve(gate.inverse())) target = op.adjoint().dot(pauli).dot(op) self.assertEqual(value, target) self.assertEqual(value, value_h) self.assertEqual(value_inv, value_s) @data(*it.product((CXGate(), CYGate(), CZGate(), SwapGate()), pauli_group_labels(2, False))) @unpack def test_evolve_clifford2(self, gate, label): """Test evolve method for 2-qubit Clifford gates.""" op = Operator(gate) pauli = Pauli(label) value = Operator(pauli.evolve(gate)) value_h = Operator(pauli.evolve(gate, frame="h")) value_s = Operator(pauli.evolve(gate, frame="s")) value_inv = Operator(pauli.evolve(gate.inverse())) target = op.adjoint().dot(pauli).dot(op) self.assertEqual(value, target) self.assertEqual(value, value_h) self.assertEqual(value_inv, value_s) @data( *it.product( ( IGate(), XGate(), YGate(), ZGate(), HGate(), SGate(), SdgGate(), CXGate(), CYGate(), CZGate(), SwapGate(), ), [int, np.int8, np.uint8, np.int16, np.uint16, np.int32, np.uint32, np.int64, np.uint64], ) ) @unpack def test_phase_dtype_evolve_clifford(self, gate, dtype): """Test phase dtype for evolve method for Clifford gates.""" z = np.ones(gate.num_qubits, dtype=bool) x = np.ones(gate.num_qubits, dtype=bool) phase = (np.sum(z & x) % 4).astype(dtype) paulis = Pauli((z, x, phase)) evo = paulis.evolve(gate) self.assertEqual(evo.phase.dtype, dtype) def test_evolve_clifford_qargs(self): """Test evolve method for random Clifford""" cliff = random_clifford(3, seed=10) op = Operator(cliff) pauli = random_pauli(5, seed=10) qargs = [3, 0, 1] value = Operator(pauli.evolve(cliff, qargs=qargs)) value_h = Operator(pauli.evolve(cliff, qargs=qargs, frame="h")) value_s = Operator(pauli.evolve(cliff, qargs=qargs, frame="s")) value_inv = Operator(pauli.evolve(cliff.adjoint(), qargs=qargs)) target = Operator(pauli).compose(op.adjoint(), qargs=qargs).dot(op, qargs=qargs) self.assertEqual(value, target) self.assertEqual(value, value_h) self.assertEqual(value_inv, value_s) def test_barrier_delay_sim(self): """Test barrier and delay instructions can be simulated""" target_circ = QuantumCircuit(2) target_circ.x(0) target_circ.y(1) target = Pauli(target_circ) circ = QuantumCircuit(2) circ.x(0) circ.delay(100, 0) circ.barrier([0, 1]) circ.y(1) value = Pauli(circ) self.assertEqual(value, target) @data(("", 0), ("-", 2), ("i", 3), ("-1j", 1)) @unpack def test_zero_qubit_pauli_construction(self, label, phase): """Test that Paulis of zero qubits can be constructed.""" expected = Pauli(label + "X")[0:0] # Empty slice from a 1q Pauli, which becomes phaseless expected.phase = phase test = Pauli(label) self.assertEqual(expected, test) if __name__ == "__main__": unittest.main()
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 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. """Tests for PauliList class.""" import itertools import unittest from test import combine import numpy as np from ddt import ddt from scipy.sparse import csr_matrix from qiskit import QiskitError from qiskit.circuit.library import ( CXGate, CYGate, CZGate, HGate, IGate, SdgGate, SGate, SwapGate, XGate, YGate, ZGate, ) from qiskit.quantum_info.operators import ( Clifford, Operator, Pauli, PauliList, PauliTable, StabilizerTable, ) from qiskit.quantum_info.random import random_clifford, random_pauli_list from qiskit.test import QiskitTestCase from .test_pauli import pauli_group_labels def pauli_mat(label): """Return Pauli matrix from a Pauli label""" mat = np.eye(1, dtype=complex) if label[0:2] == "-i": mat *= -1j label = label[2:] elif label[0] == "-": mat *= -1 label = label[1:] elif label[0] == "i": mat *= 1j label = label[1:] for i in label: if i == "I": mat = np.kron(mat, np.eye(2, dtype=complex)) elif i == "X": mat = np.kron(mat, np.array([[0, 1], [1, 0]], dtype=complex)) elif i == "Y": mat = np.kron(mat, np.array([[0, -1j], [1j, 0]], dtype=complex)) elif i == "Z": mat = np.kron(mat, np.array([[1, 0], [0, -1]], dtype=complex)) else: raise QiskitError(f"Invalid Pauli string {i}") return mat class TestPauliListInit(QiskitTestCase): """Tests for PauliList initialization.""" def test_array_init(self): """Test array initialization.""" # Matrix array initialization with self.subTest(msg="Empty array"): x = np.array([], dtype=bool).reshape((1, 0)) z = np.array([], dtype=bool).reshape((1, 0)) pauli_list = PauliList.from_symplectic(x, z) np.testing.assert_equal(pauli_list.z, z) np.testing.assert_equal(pauli_list.x, x) with self.subTest(msg="bool array"): z = np.array([[False], [True]]) x = np.array([[False], [True]]) pauli_list = PauliList.from_symplectic(z, x) np.testing.assert_equal(pauli_list.z, z) np.testing.assert_equal(pauli_list.x, x) with self.subTest(msg="bool array no copy"): z = np.array([[False], [True]]) x = np.array([[True], [True]]) pauli_list = PauliList.from_symplectic(z, x) z[0, 0] = not z[0, 0] np.testing.assert_equal(pauli_list.z, z) np.testing.assert_equal(pauli_list.x, x) def test_string_init(self): """Test string initialization.""" # String initialization with self.subTest(msg='str init "I"'): pauli_list = PauliList("I") z = np.array([[False]]) x = np.array([[False]]) np.testing.assert_equal(pauli_list.z, z) np.testing.assert_equal(pauli_list.x, x) with self.subTest(msg='str init "X"'): pauli_list = PauliList("X") z = np.array([[False]]) x = np.array([[True]]) np.testing.assert_equal(pauli_list.z, z) np.testing.assert_equal(pauli_list.x, x) with self.subTest(msg='str init "Y"'): pauli_list = PauliList("Y") z = np.array([[True]]) x = np.array([[True]]) np.testing.assert_equal(pauli_list.z, z) np.testing.assert_equal(pauli_list.x, x) with self.subTest(msg='str init "Z"'): pauli_list = PauliList("Z") z = np.array([[True]]) x = np.array([[False]]) np.testing.assert_equal(pauli_list.z, z) np.testing.assert_equal(pauli_list.x, x) with self.subTest(msg='str init "iZ"'): pauli_list = PauliList("iZ") z = np.array([[True]]) x = np.array([[False]]) phase = np.array([3]) np.testing.assert_equal(pauli_list.z, z) np.testing.assert_equal(pauli_list.x, x) np.testing.assert_equal(pauli_list.phase, phase) with self.subTest(msg='str init "-Z"'): pauli_list = PauliList("-Z") z = np.array([[True]]) x = np.array([[False]]) phase = np.array([2]) np.testing.assert_equal(pauli_list.z, z) np.testing.assert_equal(pauli_list.x, x) np.testing.assert_equal(pauli_list.phase, phase) with self.subTest(msg='str init "-iZ"'): pauli_list = PauliList("-iZ") z = np.array([[True]]) x = np.array([[False]]) phase = np.array([1]) np.testing.assert_equal(pauli_list.z, z) np.testing.assert_equal(pauli_list.x, x) np.testing.assert_equal(pauli_list.phase, phase) with self.subTest(msg='str init "IX"'): pauli_list = PauliList("IX") z = np.array([[False, False]]) x = np.array([[True, False]]) np.testing.assert_equal(pauli_list.z, z) np.testing.assert_equal(pauli_list.x, x) with self.subTest(msg='str init "XI"'): pauli_list = PauliList("XI") z = np.array([[False, False]]) x = np.array([[False, True]]) np.testing.assert_equal(pauli_list.z, z) np.testing.assert_equal(pauli_list.x, x) with self.subTest(msg='str init "YZ"'): pauli_list = PauliList("YZ") z = np.array([[True, True]]) x = np.array([[False, True]]) np.testing.assert_equal(pauli_list.z, z) np.testing.assert_equal(pauli_list.x, x) with self.subTest(msg='str init "iZY"'): pauli_list = PauliList("iZY") z = np.array([[True, True]]) x = np.array([[True, False]]) phase = np.array([3]) np.testing.assert_equal(pauli_list.z, z) np.testing.assert_equal(pauli_list.x, x) np.testing.assert_equal(pauli_list.phase, phase) with self.subTest(msg='str init "XIZ"'): pauli_list = PauliList("XIZ") z = np.array([[True, False, False]]) x = np.array([[False, False, True]]) np.testing.assert_equal(pauli_list.z, z) np.testing.assert_equal(pauli_list.x, x) with self.subTest(msg="str init prevent broadcasting"): with self.assertRaises(ValueError): PauliList(["XYZ", "I"]) def test_list_init(self): """Test list initialization.""" with self.subTest(msg="PauliList"): target = PauliList(["iXI", "IX", "IZ"]) value = PauliList(target) self.assertEqual(value, target) with self.subTest(msg="PauliList no copy"): target = PauliList(["iXI", "IX", "IZ"]) value = PauliList(target) value[0] = "-iII" self.assertEqual(value, target) def test_pauli_table_init(self): """Test table initialization.""" with self.subTest(msg="PauliTable"): target = PauliTable.from_labels(["XI", "IX", "IZ"]) value = PauliList(target) self.assertEqual(value, target) with self.subTest(msg="PauliTable no copy"): target = PauliTable.from_labels(["XI", "IX", "IZ"]) value = PauliList(target) value[0] = "II" self.assertEqual(value, target) def test_stabilizer_table_init(self): """Test table initialization.""" with self.subTest(msg="PauliTable"): with self.assertWarns(DeprecationWarning): target = StabilizerTable.from_labels(["+II", "-XZ"]) value = PauliList(target) self.assertEqual(value, target) with self.subTest(msg="PauliTable no copy"): with self.assertWarns(DeprecationWarning): target = StabilizerTable.from_labels(["+YY", "-XZ", "XI"]) value = PauliList(target) value[0] = "II" self.assertEqual(value, target) def test_init_from_settings(self): """Test initializing from the settings dictionary.""" pauli_list = PauliList(["IX", "-iYZ", "YY"]) from_settings = PauliList(**pauli_list.settings) self.assertEqual(pauli_list, from_settings) @ddt class TestPauliListProperties(QiskitTestCase): """Tests for PauliList properties.""" def test_x_property(self): """Test X property""" with self.subTest(msg="X"): pauli = PauliList(["XI", "IZ", "YY"]) array = np.array([[False, True], [False, False], [True, True]], dtype=bool) self.assertTrue(np.all(pauli.x == array)) with self.subTest(msg="set X"): pauli = PauliList(["XI", "IZ"]) val = np.array([[False, False], [True, True]], dtype=bool) pauli.x = val self.assertEqual(pauli, PauliList(["II", "iXY"])) with self.subTest(msg="set X raises"): with self.assertRaises(Exception): pauli = PauliList(["XI", "IZ"]) val = np.array([[False, False, False], [True, True, True]], dtype=bool) pauli.x = val def test_z_property(self): """Test Z property""" with self.subTest(msg="Z"): pauli = PauliList(["XI", "IZ", "YY"]) array = np.array([[False, False], [True, False], [True, True]], dtype=bool) self.assertTrue(np.all(pauli.z == array)) with self.subTest(msg="set Z"): pauli = PauliList(["XI", "IZ"]) val = np.array([[False, False], [True, True]], dtype=bool) pauli.z = val self.assertEqual(pauli, PauliList(["XI", "ZZ"])) with self.subTest(msg="set Z raises"): with self.assertRaises(Exception): pauli = PauliList(["XI", "IZ"]) val = np.array([[False, False, False], [True, True, True]], dtype=bool) pauli.z = val def test_phase_property(self): """Test phase property""" with self.subTest(msg="phase"): pauli = PauliList(["XI", "IZ", "YY", "YI"]) array = np.array([0, 0, 0, 0], dtype=int) np.testing.assert_equal(pauli.phase, array) with self.subTest(msg="set phase"): pauli = PauliList(["XI", "IZ"]) val = np.array([2, 3], dtype=int) pauli.phase = val self.assertEqual(pauli, PauliList(["-XI", "iIZ"])) with self.subTest(msg="set Z raises"): with self.assertRaises(Exception): pauli = PauliList(["XI", "IZ"]) val = np.array([1, 2, 3], dtype=int) pauli.phase = val def test_shape_property(self): """Test shape property""" shape = (3, 4) pauli = PauliList.from_symplectic(np.zeros(shape), np.zeros(shape)) self.assertEqual(pauli.shape, shape) @combine(j=range(1, 10)) def test_size_property(self, j): """Test size property""" shape = (j, 4) pauli = PauliList.from_symplectic(np.zeros(shape), np.zeros(shape)) self.assertEqual(len(pauli), j) @combine(j=range(1, 10)) def test_n_qubit_property(self, j): """Test n_qubit property""" shape = (5, j) pauli = PauliList.from_symplectic(np.zeros(shape), np.zeros(shape)) self.assertEqual(pauli.num_qubits, j) def test_eq(self): """Test __eq__ method.""" pauli1 = PauliList(["II", "XI"]) pauli2 = PauliList(["XI", "II"]) self.assertEqual(pauli1, pauli1) self.assertNotEqual(pauli1, pauli2) def test_len_methods(self): """Test __len__ method.""" for j in range(1, 10): labels = j * ["XX"] pauli = PauliList(labels) self.assertEqual(len(pauli), j) def test_add_methods(self): """Test __add__ method.""" labels1 = ["XXI", "IXX"] labels2 = ["XXI", "ZZI", "ZYZ"] pauli1 = PauliList(labels1) pauli2 = PauliList(labels2) target = PauliList(labels1 + labels2) self.assertEqual(target, pauli1 + pauli2) def test_add_qargs(self): """Test add method with qargs.""" pauli1 = PauliList(["IIII", "YYYY"]) pauli2 = PauliList(["XY", "YZ"]) pauli3 = PauliList(["X", "Y", "Z"]) with self.subTest(msg="qargs=[0, 1]"): target = PauliList(["IIII", "YYYY", "IIXY", "IIYZ"]) self.assertEqual(pauli1 + pauli2([0, 1]), target) with self.subTest(msg="qargs=[0, 3]"): target = PauliList(["IIII", "YYYY", "XIIY", "YIIZ"]) self.assertEqual(pauli1 + pauli2([0, 3]), target) with self.subTest(msg="qargs=[2, 1]"): target = PauliList(["IIII", "YYYY", "IYXI", "IZYI"]) self.assertEqual(pauli1 + pauli2([2, 1]), target) with self.subTest(msg="qargs=[3, 1]"): target = PauliList(["IIII", "YYYY", "YIXI", "ZIYI"]) self.assertEqual(pauli1 + pauli2([3, 1]), target) with self.subTest(msg="qargs=[0]"): target = PauliList(["IIII", "YYYY", "IIIX", "IIIY", "IIIZ"]) self.assertEqual(pauli1 + pauli3([0]), target) with self.subTest(msg="qargs=[1]"): target = PauliList(["IIII", "YYYY", "IIXI", "IIYI", "IIZI"]) self.assertEqual(pauli1 + pauli3([1]), target) with self.subTest(msg="qargs=[2]"): target = PauliList(["IIII", "YYYY", "IXII", "IYII", "IZII"]) self.assertEqual(pauli1 + pauli3([2]), target) with self.subTest(msg="qargs=[3]"): target = PauliList(["IIII", "YYYY", "XIII", "YIII", "ZIII"]) self.assertEqual(pauli1 + pauli3([3]), target) def test_getitem_methods(self): """Test __getitem__ method.""" with self.subTest(msg="__getitem__ single"): labels = ["XI", "IY"] pauli = PauliList(labels) self.assertEqual(pauli[0], PauliList(labels[0])) self.assertEqual(pauli[1], PauliList(labels[1])) with self.subTest(msg="__getitem__ array"): labels = np.array(["XI", "IY", "IZ", "XY", "ZX"]) pauli = PauliList(labels) inds = [0, 3] self.assertEqual(pauli[inds], PauliList(labels[inds])) inds = np.array([4, 1]) self.assertEqual(pauli[inds], PauliList(labels[inds])) with self.subTest(msg="__getitem__ slice"): labels = np.array(["XI", "IY", "IZ", "XY", "ZX"]) pauli = PauliList(labels) self.assertEqual(pauli[:], pauli) self.assertEqual(pauli[1:3], PauliList(labels[1:3])) def test_setitem_methods(self): """Test __setitem__ method.""" with self.subTest(msg="__setitem__ single"): labels = ["XI", "IY"] pauli = PauliList(["XI", "IY"]) pauli[0] = "II" self.assertEqual(pauli[0], PauliList("II")) pauli[1] = "-iXX" self.assertEqual(pauli[1], PauliList("-iXX")) with self.assertRaises(Exception): # Wrong size Pauli pauli[0] = "XXX" with self.subTest(msg="__setitem__ array"): labels = np.array(["XI", "IY", "IZ"]) pauli = PauliList(labels) target = PauliList(["II", "ZZ"]) inds = [2, 0] pauli[inds] = target self.assertEqual(pauli[inds], target) with self.assertRaises(Exception): pauli[inds] = PauliList(["YY", "ZZ", "XX"]) with self.subTest(msg="__setitem__ slice"): labels = np.array(5 * ["III"]) pauli = PauliList(labels) target = PauliList(5 * ["XXX"]) pauli[:] = target self.assertEqual(pauli[:], target) target = PauliList(2 * ["ZZZ"]) pauli[1:3] = target self.assertEqual(pauli[1:3], target) class TestPauliListLabels(QiskitTestCase): """Tests PauliList label representation conversions.""" def test_from_labels_1q(self): """Test 1-qubit from_labels method.""" labels = ["I", "Z", "Z", "X", "Y"] target = PauliList.from_symplectic( np.array([[False], [True], [True], [False], [True]]), np.array([[False], [False], [False], [True], [True]]), ) value = PauliList(labels) self.assertEqual(target, value) def test_from_labels_1q_with_phase(self): """Test 1-qubit from_labels method with phase.""" labels = ["-I", "iZ", "iZ", "X", "-iY"] target = PauliList.from_symplectic( np.array([[False], [True], [True], [False], [True]]), np.array([[False], [False], [False], [True], [True]]), np.array([2, 3, 3, 0, 1]), ) value = PauliList(labels) self.assertEqual(target, value) def test_from_labels_2q(self): """Test 2-qubit from_labels method.""" labels = ["II", "YY", "XZ"] target = PauliList.from_symplectic( np.array([[False, False], [True, True], [True, False]]), np.array([[False, False], [True, True], [False, True]]), ) value = PauliList(labels) self.assertEqual(target, value) def test_from_labels_2q_with_phase(self): """Test 2-qubit from_labels method.""" labels = ["iII", "iYY", "-iXZ"] target = PauliList.from_symplectic( np.array([[False, False], [True, True], [True, False]]), np.array([[False, False], [True, True], [False, True]]), np.array([3, 3, 1]), ) value = PauliList(labels) self.assertEqual(target, value) def test_from_labels_5q(self): """Test 5-qubit from_labels method.""" labels = [5 * "I", 5 * "X", 5 * "Y", 5 * "Z"] target = PauliList.from_symplectic( np.array([[False] * 5, [False] * 5, [True] * 5, [True] * 5]), np.array([[False] * 5, [True] * 5, [True] * 5, [False] * 5]), ) value = PauliList(labels) self.assertEqual(target, value) def test_to_labels_1q(self): """Test 1-qubit to_labels method.""" pauli = PauliList.from_symplectic( np.array([[False], [True], [True], [False], [True]]), np.array([[False], [False], [False], [True], [True]]), ) target = ["I", "Z", "Z", "X", "Y"] value = pauli.to_labels() self.assertEqual(value, target) def test_to_labels_1q_with_phase(self): """Test 1-qubit to_labels method with phase.""" pauli = PauliList.from_symplectic( np.array([[False], [True], [True], [False], [True]]), np.array([[False], [False], [False], [True], [True]]), np.array([1, 3, 2, 3, 1]), ) target = ["-iI", "iZ", "-Z", "iX", "-iY"] value = pauli.to_labels() self.assertEqual(value, target) def test_to_labels_1q_array(self): """Test 1-qubit to_labels method w/ array=True.""" pauli = PauliList.from_symplectic( np.array([[False], [True], [True], [False], [True]]), np.array([[False], [False], [False], [True], [True]]), ) target = np.array(["I", "Z", "Z", "X", "Y"]) value = pauli.to_labels(array=True) self.assertTrue(np.all(value == target)) def test_to_labels_1q_array_with_phase(self): """Test 1-qubit to_labels method w/ array=True.""" pauli = PauliList.from_symplectic( np.array([[False], [True], [True], [False], [True]]), np.array([[False], [False], [False], [True], [True]]), np.array([2, 3, 0, 1, 0]), ) target = np.array(["-I", "iZ", "Z", "-iX", "Y"]) value = pauli.to_labels(array=True) self.assertTrue(np.all(value == target)) def test_labels_round_trip(self): """Test from_labels and to_labels round trip.""" target = ["III", "IXZ", "XYI", "ZZZ", "-iZIX", "-IYX"] value = PauliList(target).to_labels() self.assertEqual(value, target) def test_labels_round_trip_array(self): """Test from_labels and to_labels round trip w/ array=True.""" labels = ["III", "IXZ", "XYI", "ZZZ", "-iZIX", "-IYX"] target = np.array(labels) value = PauliList(labels).to_labels(array=True) self.assertTrue(np.all(value == target)) class TestPauliListMatrix(QiskitTestCase): """Tests PauliList matrix representation conversions.""" def test_to_matrix_1q(self): """Test 1-qubit to_matrix method.""" labels = ["X", "I", "Z", "Y"] targets = [pauli_mat(i) for i in labels] values = PauliList(labels).to_matrix() self.assertTrue(isinstance(values, list)) for target, value in zip(targets, values): self.assertTrue(np.all(value == target)) def test_to_matrix_1q_array(self): """Test 1-qubit to_matrix method w/ array=True.""" labels = ["Z", "I", "Y", "X"] target = np.array([pauli_mat(i) for i in labels]) value = PauliList(labels).to_matrix(array=True) self.assertTrue(isinstance(value, np.ndarray)) self.assertTrue(np.all(value == target)) def test_to_matrix_1q_sparse(self): """Test 1-qubit to_matrix method w/ sparse=True.""" labels = ["X", "I", "Z", "Y"] targets = [pauli_mat(i) for i in labels] values = PauliList(labels).to_matrix(sparse=True) for mat, targ in zip(values, targets): self.assertTrue(isinstance(mat, csr_matrix)) self.assertTrue(np.all(targ == mat.toarray())) def test_to_matrix_2q(self): """Test 2-qubit to_matrix method.""" labels = ["IX", "YI", "II", "ZZ"] targets = [pauli_mat(i) for i in labels] values = PauliList(labels).to_matrix() self.assertTrue(isinstance(values, list)) for target, value in zip(targets, values): self.assertTrue(np.all(value == target)) def test_to_matrix_2q_array(self): """Test 2-qubit to_matrix method w/ array=True.""" labels = ["ZZ", "XY", "YX", "IZ"] target = np.array([pauli_mat(i) for i in labels]) value = PauliList(labels).to_matrix(array=True) self.assertTrue(isinstance(value, np.ndarray)) self.assertTrue(np.all(value == target)) def test_to_matrix_2q_sparse(self): """Test 2-qubit to_matrix method w/ sparse=True.""" labels = ["IX", "II", "ZY", "YZ"] targets = [pauli_mat(i) for i in labels] values = PauliList(labels).to_matrix(sparse=True) for mat, targ in zip(values, targets): self.assertTrue(isinstance(mat, csr_matrix)) self.assertTrue(np.all(targ == mat.toarray())) def test_to_matrix_5q(self): """Test 5-qubit to_matrix method.""" labels = ["IXIXI", "YZIXI", "IIXYZ"] targets = [pauli_mat(i) for i in labels] values = PauliList(labels).to_matrix() self.assertTrue(isinstance(values, list)) for target, value in zip(targets, values): self.assertTrue(np.all(value == target)) def test_to_matrix_5q_sparse(self): """Test 5-qubit to_matrix method w/ sparse=True.""" labels = ["XXXYY", "IXIZY", "ZYXIX"] targets = [pauli_mat(i) for i in labels] values = PauliList(labels).to_matrix(sparse=True) for mat, targ in zip(values, targets): self.assertTrue(isinstance(mat, csr_matrix)) self.assertTrue(np.all(targ == mat.toarray())) def test_to_matrix_5q_with_phase(self): """Test 5-qubit to_matrix method with phase.""" labels = ["iIXIXI", "-YZIXI", "-iIIXYZ"] targets = [pauli_mat(i) for i in labels] values = PauliList(labels).to_matrix() self.assertTrue(isinstance(values, list)) for target, value in zip(targets, values): self.assertTrue(np.all(value == target)) def test_to_matrix_5q_sparse_with_phase(self): """Test 5-qubit to_matrix method w/ sparse=True with phase.""" labels = ["iXXXYY", "-IXIZY", "-iZYXIX"] targets = [pauli_mat(i) for i in labels] values = PauliList(labels).to_matrix(sparse=True) for mat, targ in zip(values, targets): self.assertTrue(isinstance(mat, csr_matrix)) self.assertTrue(np.all(targ == mat.toarray())) class TestPauliListIteration(QiskitTestCase): """Tests for PauliList iterators class.""" def test_enumerate(self): """Test enumerate with PauliList.""" labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"] pauli = PauliList(labels) for idx, i in enumerate(pauli): self.assertEqual(i, PauliList(labels[idx])) def test_iter(self): """Test iter with PauliList.""" labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"] pauli = PauliList(labels) for idx, i in enumerate(iter(pauli)): self.assertEqual(i, PauliList(labels[idx])) def test_zip(self): """Test zip with PauliList.""" labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"] pauli = PauliList(labels) for label, i in zip(labels, pauli): self.assertEqual(i, PauliList(label)) def test_label_iter(self): """Test PauliList label_iter method.""" labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"] pauli = PauliList(labels) for idx, i in enumerate(pauli.label_iter()): self.assertEqual(i, labels[idx]) def test_matrix_iter(self): """Test PauliList dense matrix_iter method.""" labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"] pauli = PauliList(labels) for idx, i in enumerate(pauli.matrix_iter()): self.assertTrue(np.all(i == pauli_mat(labels[idx]))) def test_matrix_iter_sparse(self): """Test PauliList sparse matrix_iter method.""" labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"] pauli = PauliList(labels) for idx, i in enumerate(pauli.matrix_iter(sparse=True)): self.assertTrue(isinstance(i, csr_matrix)) self.assertTrue(np.all(i.toarray() == pauli_mat(labels[idx]))) @ddt class TestPauliListOperator(QiskitTestCase): """Tests for PauliList base operator methods.""" @combine(j=range(1, 10)) def test_tensor(self, j): """Test tensor method j={j}.""" labels1 = ["XX", "YY"] labels2 = [j * "I", j * "Z"] pauli1 = PauliList(labels1) pauli2 = PauliList(labels2) value = pauli1.tensor(pauli2) target = PauliList([l1 + l2 for l1 in labels1 for l2 in labels2]) self.assertEqual(value, target) @combine(j=range(1, 10)) def test_tensor_with_phase(self, j): """Test tensor method j={j} with phase.""" labels1 = ["XX", "iYY"] labels2 = [j * "I", "i" + j * "Z"] pauli1 = PauliList(labels1) pauli2 = PauliList(labels2) value = pauli1.tensor(pauli2) target = PauliList(["XX" + "I" * j, "iXX" + "Z" * j, "iYY" + "I" * j, "-YY" + "Z" * j]) self.assertEqual(value, target) @combine(j=range(1, 10)) def test_expand(self, j): """Test expand method j={j}.""" labels1 = ["XX", "YY"] labels2 = [j * "I", j * "Z"] pauli1 = PauliList(labels1) pauli2 = PauliList(labels2) value = pauli1.expand(pauli2) target = PauliList([j + i for j in labels2 for i in labels1]) self.assertEqual(value, target) @combine(j=range(1, 10)) def test_expand_with_phase(self, j): """Test expand method j={j}.""" labels1 = ["-XX", "iYY"] labels2 = ["i" + j * "I", "-i" + j * "Z"] pauli1 = PauliList(labels1) pauli2 = PauliList(labels2) value = pauli1.expand(pauli2) target = PauliList( ["-i" + "I" * j + "XX", "-" + "I" * j + "YY", "i" + "Z" * j + "XX", "Z" * j + "YY"] ) self.assertEqual(value, target) def test_compose_1q(self): """Test 1-qubit compose methods.""" # Test single qubit Pauli dot products pauli = PauliList(["I", "X", "Y", "Z"]) with self.subTest(msg="compose single I"): target = PauliList(["I", "X", "Y", "Z"]) value = pauli.compose("I") self.assertEqual(target, value) with self.subTest(msg="compose single X"): target = PauliList(["X", "I", "iZ", "-iY"]) value = pauli.compose("X") self.assertEqual(target, value) with self.subTest(msg="compose single Y"): target = PauliList(["Y", "-iZ", "I", "iX"]) value = pauli.compose("Y") self.assertEqual(target, value) with self.subTest(msg="compose single Z"): target = PauliList(["Z", "iY", "-iX", "I"]) value = pauli.compose("Z") self.assertEqual(target, value) def test_dot_1q(self): """Test 1-qubit dot method.""" # Test single qubit Pauli dot products pauli = PauliList(["I", "X", "Y", "Z"]) with self.subTest(msg="dot single I"): target = PauliList(["I", "X", "Y", "Z"]) value = pauli.dot("I") self.assertEqual(target, value) with self.subTest(msg="dot single X"): target = PauliList(["X", "I", "-iZ", "iY"]) value = pauli.dot("X") self.assertEqual(target, value) with self.subTest(msg="dot single Y"): target = PauliList(["Y", "iZ", "I", "-iX"]) value = pauli.dot("Y") self.assertEqual(target, value) with self.subTest(msg="dot single Z"): target = PauliList(["Z", "-iY", "iX", "I"]) value = pauli.dot("Z") self.assertEqual(target, value) def test_qargs_compose_1q(self): """Test 1-qubit compose method with qargs.""" pauli1 = PauliList(["III", "XXX"]) pauli2 = PauliList("Z") with self.subTest(msg="compose 1-qubit qargs=[0]"): target = PauliList(["IIZ", "iXXY"]) value = pauli1.compose(pauli2, qargs=[0]) self.assertEqual(value, target) with self.subTest(msg="compose 1-qubit qargs=[1]"): target = PauliList(["IZI", "iXYX"]) value = pauli1.compose(pauli2, qargs=[1]) self.assertEqual(value, target) with self.subTest(msg="compose 1-qubit qargs=[2]"): target = PauliList(["ZII", "iYXX"]) value = pauli1.compose(pauli2, qargs=[2]) self.assertEqual(value, target) def test_qargs_dot_1q(self): """Test 1-qubit dot method with qargs.""" pauli1 = PauliList(["III", "XXX"]) pauli2 = PauliList("Z") with self.subTest(msg="dot 1-qubit qargs=[0]"): target = PauliList(["IIZ", "-iXXY"]) value = pauli1.dot(pauli2, qargs=[0]) self.assertEqual(value, target) with self.subTest(msg="dot 1-qubit qargs=[1]"): target = PauliList(["IZI", "-iXYX"]) value = pauli1.dot(pauli2, qargs=[1]) self.assertEqual(value, target) with self.subTest(msg="dot 1-qubit qargs=[2]"): target = PauliList(["ZII", "-iYXX"]) value = pauli1.dot(pauli2, qargs=[2]) self.assertEqual(value, target) def test_qargs_compose_2q(self): """Test 2-qubit compose method with qargs.""" pauli1 = PauliList(["III", "XXX"]) pauli2 = PauliList("ZY") with self.subTest(msg="compose 2-qubit qargs=[0, 1]"): target = PauliList(["IZY", "XYZ"]) value = pauli1.compose(pauli2, qargs=[0, 1]) self.assertEqual(value, target) with self.subTest(msg="compose 2-qubit qargs=[1, 0]"): target = PauliList(["IYZ", "XZY"]) value = pauli1.compose(pauli2, qargs=[1, 0]) self.assertEqual(value, target) with self.subTest(msg="compose 2-qubit qargs=[0, 2]"): target = PauliList(["ZIY", "YXZ"]) value = pauli1.compose(pauli2, qargs=[0, 2]) self.assertEqual(value, target) with self.subTest(msg="compose 2-qubit qargs=[2, 0]"): target = PauliList(["YIZ", "ZXY"]) value = pauli1.compose(pauli2, qargs=[2, 0]) self.assertEqual(value, target) def test_qargs_dot_2q(self): """Test 2-qubit dot method with qargs.""" pauli1 = PauliList(["III", "XXX"]) pauli2 = PauliList("ZY") with self.subTest(msg="dot 2-qubit qargs=[0, 1]"): target = PauliList(["IZY", "XYZ"]) value = pauli1.dot(pauli2, qargs=[0, 1]) self.assertEqual(value, target) with self.subTest(msg="dot 2-qubit qargs=[1, 0]"): target = PauliList(["IYZ", "XZY"]) value = pauli1.dot(pauli2, qargs=[1, 0]) self.assertEqual(value, target) with self.subTest(msg="dot 2-qubit qargs=[0, 2]"): target = PauliList(["ZIY", "YXZ"]) value = pauli1.dot(pauli2, qargs=[0, 2]) self.assertEqual(value, target) with self.subTest(msg="dot 2-qubit qargs=[2, 0]"): target = PauliList(["YIZ", "ZXY"]) value = pauli1.dot(pauli2, qargs=[2, 0]) self.assertEqual(value, target) def test_qargs_compose_3q(self): """Test 3-qubit compose method with qargs.""" pauli1 = PauliList(["III", "XXX"]) pauli2 = PauliList("XYZ") with self.subTest(msg="compose 3-qubit qargs=None"): target = PauliList(["XYZ", "IZY"]) value = pauli1.compose(pauli2) self.assertEqual(value, target) with self.subTest(msg="compose 3-qubit qargs=[0, 1, 2]"): target = PauliList(["XYZ", "IZY"]) value = pauli1.compose(pauli2, qargs=[0, 1, 2]) self.assertEqual(value, target) with self.subTest(msg="compose 3-qubit qargs=[2, 1, 0]"): target = PauliList(["ZYX", "YZI"]) value = pauli1.compose(pauli2, qargs=[2, 1, 0]) self.assertEqual(value, target) with self.subTest(msg="compose 3-qubit qargs=[1, 0, 2]"): target = PauliList(["XZY", "IYZ"]) value = pauli1.compose(pauli2, qargs=[1, 0, 2]) self.assertEqual(value, target) def test_qargs_dot_3q(self): """Test 3-qubit dot method with qargs.""" pauli1 = PauliList(["III", "XXX"]) pauli2 = PauliList("XYZ") with self.subTest(msg="dot 3-qubit qargs=None"): target = PauliList(["XYZ", "IZY"]) value = pauli1.dot(pauli2, qargs=[0, 1, 2]) self.assertEqual(value, target) with self.subTest(msg="dot 3-qubit qargs=[0, 1, 2]"): target = PauliList(["XYZ", "IZY"]) value = pauli1.dot(pauli2, qargs=[0, 1, 2]) self.assertEqual(value, target) with self.subTest(msg="dot 3-qubit qargs=[2, 1, 0]"): target = PauliList(["ZYX", "YZI"]) value = pauli1.dot(pauli2, qargs=[2, 1, 0]) self.assertEqual(value, target) with self.subTest(msg="dot 3-qubit qargs=[1, 0, 2]"): target = PauliList(["XZY", "IYZ"]) value = pauli1.dot(pauli2, qargs=[1, 0, 2]) self.assertEqual(value, target) @ddt class TestPauliListMethods(QiskitTestCase): """Tests for PauliList utility methods class.""" def test_sort(self): """Test sort method.""" with self.subTest(msg="1 qubit standard order"): unsrt = ["X", "Z", "I", "Y", "-iI", "X", "Z", "iI", "-I", "-iY"] srt = ["I", "-iI", "-I", "iI", "X", "X", "Y", "-iY", "Z", "Z"] target = PauliList(srt) value = PauliList(unsrt).sort() self.assertEqual(target, value) with self.subTest(msg="1 qubit weight order"): unsrt = ["X", "Z", "I", "Y", "-iI", "X", "Z", "iI", "-I", "-iY"] srt = ["I", "-iI", "-I", "iI", "X", "X", "Y", "-iY", "Z", "Z"] target = PauliList(srt) value = PauliList(unsrt).sort(weight=True) self.assertEqual(target, value) with self.subTest(msg="1 qubit phase order"): unsrt = ["X", "Z", "I", "Y", "-iI", "X", "Z", "iI", "-I", "-iY"] srt = ["I", "X", "X", "Y", "Z", "Z", "-iI", "-iY", "-I", "iI"] target = PauliList(srt) value = PauliList(unsrt).sort(phase=True) self.assertEqual(target, value) with self.subTest(msg="1 qubit weight & phase order"): unsrt = ["X", "Z", "I", "Y", "-iI", "X", "Z", "iI", "-I", "-iY"] srt = ["I", "X", "X", "Y", "Z", "Z", "-iI", "-iY", "-I", "iI"] target = PauliList(srt) value = PauliList(unsrt).sort(weight=True, phase=True) self.assertEqual(target, value) with self.subTest(msg="2 qubit standard order"): srt = [ "II", "IX", "IX", "IY", "IZ", "iIZ", "XI", "XX", "XX", "iXX", "XY", "XZ", "iXZ", "YI", "YI", "-YI", "YX", "-iYX", "YY", "-iYY", "-YY", "iYY", "YZ", "ZI", "ZX", "ZX", "ZY", "ZZ", ] unsrt = srt.copy() np.random.shuffle(unsrt) target = PauliList(srt) value = PauliList(unsrt).sort() self.assertEqual(target, value) with self.subTest(msg="2 qubit weight order"): srt = [ "II", "IX", "IX", "IY", "IZ", "iIZ", "XI", "YI", "YI", "-YI", "ZI", "XX", "XX", "iXX", "XY", "XZ", "iXZ", "YX", "-iYX", "YY", "YY", "-YY", "YZ", "ZX", "ZX", "ZY", "ZZ", ] unsrt = srt.copy() np.random.shuffle(unsrt) target = PauliList(srt) value = PauliList(unsrt).sort(weight=True) self.assertEqual(target, value) with self.subTest(msg="2 qubit phase order"): srt = [ "II", "IX", "IX", "IY", "IZ", "XI", "XX", "XX", "XY", "XZ", "YI", "YI", "YX", "YY", "YY", "YZ", "ZI", "ZX", "ZX", "ZY", "ZZ", "-iYX", "-YI", "-YY", "iIZ", "iXX", "iXZ", ] unsrt = srt.copy() np.random.shuffle(unsrt) target = PauliList(srt) value = PauliList(unsrt).sort(phase=True) self.assertEqual(target, value) with self.subTest(msg="2 qubit weight & phase order"): srt = [ "II", "IX", "IX", "IY", "IZ", "XI", "YI", "YI", "ZI", "XX", "XX", "XY", "XZ", "YX", "YY", "YY", "YZ", "ZX", "ZX", "ZY", "ZZ", "-iYX", "-YI", "-YY", "iIZ", "iXX", "iXZ", ] unsrt = srt.copy() np.random.shuffle(unsrt) target = PauliList(srt) value = PauliList(unsrt).sort(weight=True, phase=True) self.assertEqual(target, value) with self.subTest(msg="3 qubit standard order"): srt = [ "III", "III", "IIX", "IIY", "-IIY", "IIZ", "IXI", "IXX", "IXY", "iIXY", "IXZ", "IYI", "IYX", "IYY", "IYZ", "IZI", "IZX", "IZY", "IZY", "IZZ", "XII", "XII", "XIX", "XIY", "XIZ", "XXI", "XXX", "-iXXX", "XXY", "XXZ", "XYI", "XYX", "iXYX", "XYY", "XYZ", "XYZ", "XZI", "XZX", "XZY", "XZZ", "YII", "YIX", "YIY", "YIZ", "YXI", "YXX", "YXY", "YXZ", "YXZ", "YYI", "YYX", "YYX", "YYY", "YYZ", "YZI", "YZX", "YZY", "YZZ", "ZII", "ZIX", "ZIY", "ZIZ", "ZXI", "ZXX", "iZXX", "ZXY", "ZXZ", "ZYI", "ZYI", "ZYX", "ZYY", "ZYZ", "ZZI", "ZZX", "ZZY", "ZZZ", ] unsrt = srt.copy() np.random.shuffle(unsrt) target = PauliList(srt) value = PauliList(unsrt).sort() self.assertEqual(target, value) with self.subTest(msg="3 qubit weight order"): srt = [ "III", "III", "IIX", "IIY", "-IIY", "IIZ", "IXI", "IYI", "IZI", "XII", "XII", "YII", "ZII", "IXX", "IXY", "iIXY", "IXZ", "IYX", "IYY", "IYZ", "IZX", "IZY", "IZY", "IZZ", "XIX", "XIY", "XIZ", "XXI", "XYI", "XZI", "YIX", "YIY", "YIZ", "YXI", "YYI", "YZI", "ZIX", "ZIY", "ZIZ", "ZXI", "ZYI", "ZYI", "ZZI", "XXX", "-iXXX", "XXY", "XXZ", "XYX", "iXYX", "XYY", "XYZ", "XYZ", "XZX", "XZY", "XZZ", "YXX", "YXY", "YXZ", "YXZ", "YYX", "YYX", "YYY", "YYZ", "YZX", "YZY", "YZZ", "ZXX", "iZXX", "ZXY", "ZXZ", "ZYX", "ZYY", "ZYZ", "ZZX", "ZZY", "ZZZ", ] unsrt = srt.copy() np.random.shuffle(unsrt) target = PauliList(srt) value = PauliList(unsrt).sort(weight=True) self.assertEqual(target, value) with self.subTest(msg="3 qubit phase order"): srt = [ "III", "III", "IIX", "IIY", "IIZ", "IXI", "IXX", "IXY", "IXZ", "IYI", "IYX", "IYY", "IYZ", "IZI", "IZX", "IZY", "IZY", "IZZ", "XII", "XII", "XIX", "XIY", "XIZ", "XXI", "XXX", "XXY", "XXZ", "XYI", "XYX", "XYY", "XYZ", "XYZ", "XZI", "XZX", "XZY", "XZZ", "YII", "YIX", "YIY", "YIZ", "YXI", "YXX", "YXY", "YXZ", "YXZ", "YYI", "YYX", "YYX", "YYY", "YYZ", "YZI", "YZX", "YZY", "YZZ", "ZII", "ZIX", "ZIY", "ZIZ", "ZXI", "ZXX", "ZXY", "ZXZ", "ZYI", "ZYI", "ZYX", "ZYY", "ZYZ", "ZZI", "ZZX", "ZZY", "ZZZ", "-iXXX", "-IIY", "iIXY", "iXYX", "iZXX", ] unsrt = srt.copy() np.random.shuffle(unsrt) target = PauliList(srt) value = PauliList(unsrt).sort(phase=True) self.assertEqual(target, value) with self.subTest(msg="3 qubit weight & phase order"): srt = [ "III", "III", "IIX", "IIY", "IYI", "IZI", "XII", "XII", "YII", "ZII", "IXX", "IXY", "IXZ", "IYX", "IYY", "IYZ", "IZX", "IZY", "IZY", "IZZ", "XIX", "XIY", "XIZ", "XXI", "XYI", "XZI", "YIX", "YIY", "YIZ", "YYI", "YZI", "ZIX", "ZIY", "ZIZ", "ZXI", "ZYI", "ZYI", "ZZI", "XXX", "XXY", "XXZ", "XYX", "XYY", "XYZ", "XZX", "XZY", "XZZ", "YXX", "YXY", "YXZ", "YXZ", "YYX", "YYX", "YYY", "YYZ", "YZX", "YZY", "YZZ", "ZXX", "ZXY", "ZXZ", "ZYX", "ZYY", "ZYZ", "ZZX", "ZZY", "ZZZ", "-iZIZ", "-iXXX", "-IIY", "iIXI", "iIXY", "iYXI", "iXYX", "iXYZ", "iZXX", ] unsrt = srt.copy() np.random.shuffle(unsrt) target = PauliList(srt) value = PauliList(unsrt).sort(weight=True, phase=True) self.assertEqual(target, value) def test_unique(self): """Test unique method.""" with self.subTest(msg="1 qubit"): labels = ["X", "Z", "X", "X", "I", "Y", "I", "X", "Z", "Z", "X", "I"] unique = ["X", "Z", "I", "Y"] target = PauliList(unique) value = PauliList(labels).unique() self.assertEqual(target, value) with self.subTest(msg="2 qubit"): labels = ["XX", "IX", "XX", "II", "IZ", "ZI", "YX", "YX", "ZZ", "IX", "XI"] unique = ["XX", "IX", "II", "IZ", "ZI", "YX", "ZZ", "XI"] target = PauliList(unique) value = PauliList(labels).unique() self.assertEqual(target, value) with self.subTest(msg="10 qubit"): labels = [10 * "X", 10 * "I", 10 * "X"] unique = [10 * "X", 10 * "I"] target = PauliList(unique) value = PauliList(labels).unique() self.assertEqual(target, value) def test_delete(self): """Test delete method.""" with self.subTest(msg="single row"): for j in range(1, 6): pauli = PauliList([j * "X", j * "Y"]) self.assertEqual(pauli.delete(0), PauliList(j * "Y")) self.assertEqual(pauli.delete(1), PauliList(j * "X")) with self.subTest(msg="multiple rows"): for j in range(1, 6): pauli = PauliList([j * "X", "-i" + j * "Y", j * "Z"]) self.assertEqual(pauli.delete([0, 2]), PauliList("-i" + j * "Y")) self.assertEqual(pauli.delete([1, 2]), PauliList(j * "X")) self.assertEqual(pauli.delete([0, 1]), PauliList(j * "Z")) with self.subTest(msg="single qubit"): pauli = PauliList(["IIX", "iIYI", "ZII"]) value = pauli.delete(0, qubit=True) target = PauliList(["II", "iIY", "ZI"]) self.assertEqual(value, target) value = pauli.delete(1, qubit=True) target = PauliList(["IX", "iII", "ZI"]) self.assertEqual(value, target) value = pauli.delete(2, qubit=True) target = PauliList(["IX", "iYI", "II"]) self.assertEqual(value, target) with self.subTest(msg="multiple qubits"): pauli = PauliList(["IIX", "IYI", "-ZII"]) value = pauli.delete([0, 1], qubit=True) target = PauliList(["I", "I", "-Z"]) self.assertEqual(value, target) value = pauli.delete([1, 2], qubit=True) target = PauliList(["X", "I", "-I"]) self.assertEqual(value, target) value = pauli.delete([0, 2], qubit=True) target = PauliList(["I", "Y", "-I"]) self.assertEqual(value, target) def test_insert(self): """Test insert method.""" # Insert single row for j in range(1, 10): pauli = PauliList(j * "X") target0 = PauliList([j * "I", j * "X"]) target1 = PauliList([j * "X", j * "I"]) with self.subTest(msg=f"single row from str ({j})"): value0 = pauli.insert(0, j * "I") self.assertEqual(value0, target0) value1 = pauli.insert(1, j * "I") self.assertEqual(value1, target1) with self.subTest(msg=f"single row from PauliList ({j})"): value0 = pauli.insert(0, PauliList(j * "I")) self.assertEqual(value0, target0) value1 = pauli.insert(1, PauliList(j * "I")) self.assertEqual(value1, target1) target0 = PauliList(["i" + j * "I", j * "X"]) target1 = PauliList([j * "X", "i" + j * "I"]) with self.subTest(msg=f"single row with phase from str ({j})"): value0 = pauli.insert(0, "i" + j * "I") self.assertEqual(value0, target0) value1 = pauli.insert(1, "i" + j * "I") self.assertEqual(value1, target1) with self.subTest(msg=f"single row with phase from PauliList ({j})"): value0 = pauli.insert(0, PauliList("i" + j * "I")) self.assertEqual(value0, target0) value1 = pauli.insert(1, PauliList("i" + j * "I")) self.assertEqual(value1, target1) # Insert multiple rows for j in range(1, 10): pauli = PauliList("i" + j * "X") insert = PauliList([j * "I", j * "Y", j * "Z", "-i" + j * "X"]) target0 = insert + pauli target1 = pauli + insert with self.subTest(msg=f"multiple-rows from PauliList ({j})"): value0 = pauli.insert(0, insert) self.assertEqual(value0, target0) value1 = pauli.insert(1, insert) self.assertEqual(value1, target1) # Insert single column pauli = PauliList(["X", "Y", "Z", "-iI"]) for i in ["I", "X", "Y", "Z", "iY"]: phase = "" if len(i) == 1 else i[0] p = i if len(i) == 1 else i[1] target0 = PauliList( [ phase + "X" + p, phase + "Y" + p, phase + "Z" + p, ("" if phase else "-i") + "I" + p, ] ) target1 = PauliList( [ i + "X", i + "Y", i + "Z", ("" if phase else "-i") + p + "I", ] ) with self.subTest(msg="single-column single-val from str"): value = pauli.insert(0, i, qubit=True) self.assertEqual(value, target0) value = pauli.insert(1, i, qubit=True) self.assertEqual(value, target1) with self.subTest(msg="single-column single-val from PauliList"): value = pauli.insert(0, PauliList(i), qubit=True) self.assertEqual(value, target0) value = pauli.insert(1, PauliList(i), qubit=True) self.assertEqual(value, target1) # Insert single column with multiple values pauli = PauliList(["X", "Y", "iZ"]) for i in [["I", "X", "Y"], ["X", "iY", "Z"], ["Y", "Z", "I"]]: target0 = PauliList( ["X" + i[0], "Y" + i[1] if len(i[1]) == 1 else i[1][0] + "Y" + i[1][1], "iZ" + i[2]] ) target1 = PauliList([i[0] + "X", i[1] + "Y", "i" + i[2] + "Z"]) with self.subTest(msg="single-column multiple-vals from PauliList"): value = pauli.insert(0, PauliList(i), qubit=True) self.assertEqual(value, target0) value = pauli.insert(1, PauliList(i), qubit=True) self.assertEqual(value, target1) # Insert multiple columns from single pauli = PauliList(["X", "iY", "Z"]) for j in range(1, 5): for i in [j * "I", j * "X", j * "Y", "i" + j * "Z"]: phase = "" if len(i) == j else i[0] p = i if len(i) == j else i[1:] target0 = PauliList( [ phase + "X" + p, ("-" if phase else "i") + "Y" + p, phase + "Z" + p, ] ) target1 = PauliList([i + "X", ("-" if phase else "i") + p + "Y", i + "Z"]) with self.subTest(msg="multiple-columns single-val from str"): value = pauli.insert(0, i, qubit=True) self.assertEqual(value, target0) value = pauli.insert(1, i, qubit=True) self.assertEqual(value, target1) with self.subTest(msg="multiple-columns single-val from PauliList"): value = pauli.insert(0, PauliList(i), qubit=True) self.assertEqual(value, target0) value = pauli.insert(1, PauliList(i), qubit=True) self.assertEqual(value, target1) # Insert multiple columns multiple row values pauli = PauliList(["X", "Y", "-iZ"]) for j in range(1, 5): for i in [ [j * "I", j * "X", j * "Y"], [j * "X", j * "Z", "i" + j * "Y"], [j * "Y", j * "Z", j * "I"], ]: target0 = PauliList( [ "X" + i[0], "Y" + i[1], ("-i" if len(i[2]) == j else "") + "Z" + i[2][-j:], ] ) target1 = PauliList( [ i[0] + "X", i[1] + "Y", ("-i" if len(i[2]) == j else "") + i[2][-j:] + "Z", ] ) with self.subTest(msg="multiple-column multiple-vals from PauliList"): value = pauli.insert(0, PauliList(i), qubit=True) self.assertEqual(value, target0) value = pauli.insert(1, PauliList(i), qubit=True) self.assertEqual(value, target1) def test_commutes(self): """Test commutes method.""" # Single qubit Pauli pauli = PauliList(["I", "X", "Y", "Z", "-iY"]) with self.subTest(msg="commutes single-Pauli I"): value = list(pauli.commutes("I")) target = [True, True, True, True, True] self.assertEqual(value, target) with self.subTest(msg="commutes single-Pauli X"): value = list(pauli.commutes("X")) target = [True, True, False, False, False] self.assertEqual(value, target) with self.subTest(msg="commutes single-Pauli Y"): value = list(pauli.commutes("Y")) target = [True, False, True, False, True] self.assertEqual(value, target) with self.subTest(msg="commutes single-Pauli Z"): value = list(pauli.commutes("Z")) target = [True, False, False, True, False] self.assertEqual(value, target) with self.subTest(msg="commutes single-Pauli iZ"): value = list(pauli.commutes("iZ")) target = [True, False, False, True, False] self.assertEqual(value, target) # 2-qubit Pauli pauli = PauliList(["II", "IX", "YI", "XY", "ZZ", "-iYY"]) with self.subTest(msg="commutes single-Pauli II"): value = list(pauli.commutes("II")) target = [True, True, True, True, True, True] self.assertEqual(value, target) with self.subTest(msg="commutes single-Pauli IX"): value = list(pauli.commutes("IX")) target = [True, True, True, False, False, False] self.assertEqual(value, target) with self.subTest(msg="commutes single-Pauli XI"): value = list(pauli.commutes("XI")) target = [True, True, False, True, False, False] self.assertEqual(value, target) with self.subTest(msg="commutes single-Pauli YI"): value = list(pauli.commutes("YI")) target = [True, True, True, False, False, True] self.assertEqual(value, target) with self.subTest(msg="commutes single-Pauli IY"): value = list(pauli.commutes("IY")) target = [True, False, True, True, False, True] self.assertEqual(value, target) with self.subTest(msg="commutes single-Pauli XY"): value = list(pauli.commutes("XY")) target = [True, False, False, True, True, False] self.assertEqual(value, target) with self.subTest(msg="commutes single-Pauli YX"): value = list(pauli.commutes("YX")) target = [True, True, True, True, True, False] self.assertEqual(value, target) with self.subTest(msg="commutes single-Pauli ZZ"): value = list(pauli.commutes("ZZ")) target = [True, False, False, True, True, True] self.assertEqual(value, target) with self.subTest(msg="commutes single-Pauli iYX"): value = list(pauli.commutes("iYX")) target = [True, True, True, True, True, False] self.assertEqual(value, target) def test_anticommutes(self): """Test anticommutes method.""" # Single qubit Pauli pauli = PauliList(["I", "X", "Y", "Z", "-iY"]) with self.subTest(msg="anticommutes single-Pauli I"): value = list(pauli.anticommutes("I")) target = [False, False, False, False, False] self.assertEqual(value, target) with self.subTest(msg="anticommutes single-Pauli X"): value = list(pauli.anticommutes("X")) target = [False, False, True, True, True] self.assertEqual(value, target) with self.subTest(msg="anticommutes single-Pauli Y"): value = list(pauli.anticommutes("Y")) target = [False, True, False, True, False] self.assertEqual(value, target) with self.subTest(msg="anticommutes single-Pauli Z"): value = list(pauli.anticommutes("Z")) target = [False, True, True, False, True] self.assertEqual(value, target) with self.subTest(msg="anticommutes single-Pauli iZ"): value = list(pauli.anticommutes("iZ")) target = [False, True, True, False, True] self.assertEqual(value, target) # 2-qubit Pauli pauli = PauliList(["II", "IX", "YI", "XY", "ZZ", "iZX"]) with self.subTest(msg="anticommutes single-Pauli II"): value = list(pauli.anticommutes("II")) target = [False, False, False, False, False, False] self.assertEqual(value, target) with self.subTest(msg="anticommutes single-Pauli IX"): value = list(pauli.anticommutes("IX")) target = [False, False, False, True, True, False] self.assertEqual(value, target) with self.subTest(msg="anticommutes single-Pauli XI"): value = list(pauli.anticommutes("XI")) target = [False, False, True, False, True, True] self.assertEqual(value, target) with self.subTest(msg="anticommutes single-Pauli YI"): value = list(pauli.anticommutes("YI")) target = [False, False, False, True, True, True] self.assertEqual(value, target) with self.subTest(msg="anticommutes single-Pauli IY"): value = list(pauli.anticommutes("IY")) target = [False, True, False, False, True, True] self.assertEqual(value, target) with self.subTest(msg="anticommutes single-Pauli XY"): value = list(pauli.anticommutes("XY")) target = [False, True, True, False, False, False] self.assertEqual(value, target) with self.subTest(msg="anticommutes single-Pauli YX"): value = list(pauli.anticommutes("YX")) target = [False, False, False, False, False, True] self.assertEqual(value, target) with self.subTest(msg="anticommutes single-Pauli ZZ"): value = list(pauli.anticommutes("ZZ")) target = [False, True, True, False, False, True] self.assertEqual(value, target) with self.subTest(msg="anticommutes single-Pauli iXY"): value = list(pauli.anticommutes("iXY")) target = [False, True, True, False, False, False] self.assertEqual(value, target) def test_commutes_with_all(self): """Test commutes_with_all method.""" # 1-qubit pauli = PauliList(["I", "X", "Y", "Z", "-iY"]) with self.subTest(msg="commutes_with_all [I]"): value = list(pauli.commutes_with_all("I")) target = [0, 1, 2, 3, 4] self.assertEqual(value, target) with self.subTest(msg="commutes_with_all [X]"): value = list(pauli.commutes_with_all("X")) target = [0, 1] self.assertEqual(value, target) with self.subTest(msg="commutes_with_all [Y]"): value = list(pauli.commutes_with_all("Y")) target = [0, 2, 4] self.assertEqual(value, target) with self.subTest(msg="commutes_with_all [Z]"): value = list(pauli.commutes_with_all("Z")) target = [0, 3] self.assertEqual(value, target) with self.subTest(msg="commutes_with_all [iY]"): value = list(pauli.commutes_with_all("iY")) target = [0, 2, 4] self.assertEqual(value, target) # 2-qubit Pauli pauli = PauliList(["II", "IX", "YI", "XY", "ZZ", "iXY"]) with self.subTest(msg="commutes_with_all [IX, YI]"): other = PauliList(["IX", "YI"]) value = list(pauli.commutes_with_all(other)) target = [0, 1, 2] self.assertEqual(value, target) with self.subTest(msg="commutes_with_all [XY, ZZ]"): other = PauliList(["XY", "ZZ"]) value = list(pauli.commutes_with_all(other)) target = [0, 3, 4, 5] self.assertEqual(value, target) with self.subTest(msg="commutes_with_all [YX, ZZ]"): other = PauliList(["YX", "ZZ"]) value = list(pauli.commutes_with_all(other)) target = [0, 3, 4, 5] self.assertEqual(value, target) with self.subTest(msg="commutes_with_all [XY, YX]"): other = PauliList(["XY", "YX"]) value = list(pauli.commutes_with_all(other)) target = [0, 3, 4, 5] self.assertEqual(value, target) with self.subTest(msg="commutes_with_all [XY, IX]"): other = PauliList(["XY", "IX"]) value = list(pauli.commutes_with_all(other)) target = [0] self.assertEqual(value, target) with self.subTest(msg="commutes_with_all [YX, IX]"): other = PauliList(["YX", "IX"]) value = list(pauli.commutes_with_all(other)) target = [0, 1, 2] self.assertEqual(value, target) with self.subTest(msg="commutes_with_all [-iYX, iZZ]"): other = PauliList(["-iYX", "iZZ"]) value = list(pauli.commutes_with_all(other)) target = [0, 3, 4, 5] self.assertEqual(value, target) def test_anticommutes_with_all(self): """Test anticommutes_with_all method.""" # 1-qubit pauli = PauliList(["I", "X", "Y", "Z", "-iY"]) with self.subTest(msg="anticommutes_with_all [I]"): value = list(pauli.anticommutes_with_all("I")) target = [] self.assertEqual(value, target) with self.subTest(msg="antianticommutes_with_all [X]"): value = list(pauli.anticommutes_with_all("X")) target = [2, 3, 4] self.assertEqual(value, target) with self.subTest(msg="anticommutes_with_all [Y]"): value = list(pauli.anticommutes_with_all("Y")) target = [1, 3] self.assertEqual(value, target) with self.subTest(msg="anticommutes_with_all [Z]"): value = list(pauli.anticommutes_with_all("Z")) target = [1, 2, 4] self.assertEqual(value, target) with self.subTest(msg="anticommutes_with_all [iY]"): value = list(pauli.anticommutes_with_all("iY")) target = [1, 3] self.assertEqual(value, target) # 2-qubit Pauli pauli = PauliList(["II", "IX", "YI", "XY", "ZZ", "iZX"]) with self.subTest(msg="anticommutes_with_all [IX, YI]"): other = PauliList(["IX", "YI"]) value = list(pauli.anticommutes_with_all(other)) target = [3, 4] self.assertEqual(value, target) with self.subTest(msg="anticommutes_with_all [XY, ZZ]"): other = PauliList(["XY", "ZZ"]) value = list(pauli.anticommutes_with_all(other)) target = [1, 2] self.assertEqual(value, target) with self.subTest(msg="anticommutes_with_all [YX, ZZ]"): other = PauliList(["YX", "ZZ"]) value = list(pauli.anticommutes_with_all(other)) target = [5] self.assertEqual(value, target) with self.subTest(msg="anticommutes_with_all [XY, YX]"): other = PauliList(["XY", "YX"]) value = list(pauli.anticommutes_with_all(other)) target = [] self.assertEqual(value, target) with self.subTest(msg="anticommutes_with_all [XY, IX]"): other = PauliList(["XY", "IX"]) value = list(pauli.anticommutes_with_all(other)) target = [] self.assertEqual(value, target) with self.subTest(msg="anticommutes_with_all [YX, IX]"): other = PauliList(["YX", "IX"]) value = list(pauli.anticommutes_with_all(other)) target = [] self.assertEqual(value, target) @combine( gate=( IGate(), XGate(), YGate(), ZGate(), HGate(), SGate(), SdgGate(), Clifford(IGate()), Clifford(XGate()), Clifford(YGate()), Clifford(ZGate()), Clifford(HGate()), Clifford(SGate()), Clifford(SdgGate()), ) ) def test_evolve_clifford1(self, gate): """Test evolve method for 1-qubit Clifford gates.""" op = Operator(gate) pauli_list = PauliList(pauli_group_labels(1, True)) value = [Operator(pauli) for pauli in pauli_list.evolve(gate)] value_h = [Operator(pauli) for pauli in pauli_list.evolve(gate, frame="h")] value_s = [Operator(pauli) for pauli in pauli_list.evolve(gate, frame="s")] if isinstance(gate, Clifford): value_inv = [Operator(pauli) for pauli in pauli_list.evolve(gate.adjoint())] else: value_inv = [Operator(pauli) for pauli in pauli_list.evolve(gate.inverse())] target = [op.adjoint().dot(pauli).dot(op) for pauli in pauli_list] self.assertListEqual(value, target) self.assertListEqual(value, value_h) self.assertListEqual(value_inv, value_s) @combine( gate=( CXGate(), CYGate(), CZGate(), SwapGate(), Clifford(CXGate()), Clifford(CYGate()), Clifford(CZGate()), Clifford(SwapGate()), ) ) def test_evolve_clifford2(self, gate): """Test evolve method for 2-qubit Clifford gates.""" op = Operator(gate) pauli_list = PauliList(pauli_group_labels(2, True)) value = [Operator(pauli) for pauli in pauli_list.evolve(gate)] value_h = [Operator(pauli) for pauli in pauli_list.evolve(gate, frame="h")] value_s = [Operator(pauli) for pauli in pauli_list.evolve(gate, frame="s")] if isinstance(gate, Clifford): value_inv = [Operator(pauli) for pauli in pauli_list.evolve(gate.adjoint())] else: value_inv = [Operator(pauli) for pauli in pauli_list.evolve(gate.inverse())] target = [op.adjoint().dot(pauli).dot(op) for pauli in pauli_list] self.assertListEqual(value, target) self.assertListEqual(value, value_h) self.assertListEqual(value_inv, value_s) def test_phase_dtype_evolve_clifford(self): """Test phase dtype during evolve method for Clifford gates.""" gates = ( IGate(), XGate(), YGate(), ZGate(), HGate(), SGate(), SdgGate(), CXGate(), CYGate(), CZGate(), SwapGate(), ) dtypes = [ int, np.int8, np.uint8, np.int16, np.uint16, np.int32, np.uint32, np.int64, np.uint64, ] for gate, dtype in itertools.product(gates, dtypes): z = np.ones(gate.num_qubits, dtype=bool) x = np.ones(gate.num_qubits, dtype=bool) phase = (np.sum(z & x) % 4).astype(dtype) paulis = Pauli((z, x, phase)) evo = paulis.evolve(gate) self.assertEqual(evo.phase.dtype, dtype) @combine(phase=(True, False)) def test_evolve_clifford_qargs(self, phase): """Test evolve method for random Clifford""" cliff = random_clifford(3, seed=10) op = Operator(cliff) pauli_list = random_pauli_list(5, 3, seed=10, phase=phase) qargs = [3, 0, 1] value = [Operator(pauli) for pauli in pauli_list.evolve(cliff, qargs=qargs)] value_inv = [Operator(pauli) for pauli in pauli_list.evolve(cliff.adjoint(), qargs=qargs)] value_h = [Operator(pauli) for pauli in pauli_list.evolve(cliff, qargs=qargs, frame="h")] value_s = [Operator(pauli) for pauli in pauli_list.evolve(cliff, qargs=qargs, frame="s")] target = [ Operator(pauli).compose(op.adjoint(), qargs=qargs).dot(op, qargs=qargs) for pauli in pauli_list ] self.assertListEqual(value, target) self.assertListEqual(value, value_h) self.assertListEqual(value_inv, value_s) def test_group_qubit_wise_commuting(self): """Test grouping qubit-wise commuting operators""" def qubitwise_commutes(left: Pauli, right: Pauli) -> bool: return len(left) == len(right) and all(a.commutes(b) for a, b in zip(left, right)) input_labels = ["IY", "ZX", "XZ", "YI", "YX", "YY", "YZ", "ZI", "ZX", "ZY", "iZZ", "II"] np.random.shuffle(input_labels) pauli_list = PauliList(input_labels) groups = pauli_list.group_qubit_wise_commuting() # checking that every input Pauli in pauli_list is in a group in the ouput output_labels = [pauli.to_label() for group in groups for pauli in group] self.assertListEqual(sorted(output_labels), sorted(input_labels)) # Within each group, every operator qubit-wise commutes with every other operator. for group in groups: self.assertTrue( all( qubitwise_commutes(pauli1, pauli2) for pauli1, pauli2 in itertools.combinations(group, 2) ) ) # For every pair of groups, at least one element from one does not qubit-wise commute with # at least one element of the other. for group1, group2 in itertools.combinations(groups, 2): self.assertFalse( all( qubitwise_commutes(group1_pauli, group2_pauli) for group1_pauli, group2_pauli in itertools.product(group1, group2) ) ) def test_group_commuting(self): """Test general grouping commuting operators""" def commutes(left: Pauli, right: Pauli) -> bool: return len(left) == len(right) and left.commutes(right) input_labels = ["IY", "ZX", "XZ", "YI", "YX", "YY", "YZ", "ZI", "ZX", "ZY", "iZZ", "II"] np.random.shuffle(input_labels) pauli_list = PauliList(input_labels) # if qubit_wise=True, equivalent to test_group_qubit_wise_commuting groups = pauli_list.group_commuting(qubit_wise=False) # checking that every input Pauli in pauli_list is in a group in the ouput output_labels = [pauli.to_label() for group in groups for pauli in group] self.assertListEqual(sorted(output_labels), sorted(input_labels)) # Within each group, every operator commutes with every other operator. for group in groups: self.assertTrue( all(commutes(pauli1, pauli2) for pauli1, pauli2 in itertools.combinations(group, 2)) ) # For every pair of groups, at least one element from one group does not commute with # at least one element of the other. for group1, group2 in itertools.combinations(groups, 2): self.assertFalse( all( commutes(group1_pauli, group2_pauli) for group1_pauli, group2_pauli in itertools.product(group1, group2) ) ) if __name__ == "__main__": unittest.main()
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 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. """Tests for SparsePauliOp class.""" import itertools as it import unittest from test import combine import numpy as np from ddt import ddt from qiskit import QiskitError from qiskit.circuit import ParameterExpression, Parameter, ParameterVector from qiskit.circuit.parametertable import ParameterView from qiskit.quantum_info.operators import Operator, Pauli, PauliList, PauliTable, SparsePauliOp from qiskit.test import QiskitTestCase def pauli_mat(label): """Return Pauli matrix from a Pauli label""" mat = np.eye(1, dtype=complex) for i in label: if i == "I": mat = np.kron(mat, np.eye(2, dtype=complex)) elif i == "X": mat = np.kron(mat, np.array([[0, 1], [1, 0]], dtype=complex)) elif i == "Y": mat = np.kron(mat, np.array([[0, -1j], [1j, 0]], dtype=complex)) elif i == "Z": mat = np.kron(mat, np.array([[1, 0], [0, -1]], dtype=complex)) else: raise QiskitError(f"Invalid Pauli string {i}") return mat class TestSparsePauliOpInit(QiskitTestCase): """Tests for SparsePauliOp initialization.""" def test_pauli_table_init(self): """Test PauliTable initialization.""" labels = ["I", "X", "Y", "Z"] table = PauliTable.from_labels(labels) paulis = PauliList(labels) with self.subTest(msg="no coeffs"): spp_op = SparsePauliOp(table) np.testing.assert_array_equal(spp_op.coeffs, np.ones(len(labels))) self.assertEqual(spp_op.paulis, paulis) with self.subTest(msg="no coeffs"): coeffs = [1, 2, 3, 4] spp_op = SparsePauliOp(table, coeffs) np.testing.assert_array_equal(spp_op.coeffs, coeffs) self.assertEqual(spp_op.paulis, paulis) def test_str_init(self): """Test str initialization.""" for label in ["IZ", "XI", "YX", "ZZ"]: pauli_list = PauliList(label) spp_op = SparsePauliOp(label) self.assertEqual(spp_op.paulis, pauli_list) np.testing.assert_array_equal(spp_op.coeffs, [1]) def test_pauli_list_init(self): """Test PauliList initialization.""" labels = ["I", "X", "Y", "-Z", "iZ", "-iX"] paulis = PauliList(labels) with self.subTest(msg="no coeffs"): spp_op = SparsePauliOp(paulis) np.testing.assert_array_equal(spp_op.coeffs, [1, 1, 1, -1, 1j, -1j]) paulis.phase = 0 self.assertEqual(spp_op.paulis, paulis) paulis = PauliList(labels) with self.subTest(msg="with coeffs"): coeffs = [1, 2, 3, 4, 5, 6] spp_op = SparsePauliOp(paulis, coeffs) np.testing.assert_array_equal(spp_op.coeffs, [1, 2, 3, -4, 5j, -6j]) paulis.phase = 0 self.assertEqual(spp_op.paulis, paulis) paulis = PauliList(labels) with self.subTest(msg="with Parameterized coeffs"): params = ParameterVector("params", 6) coeffs = np.array(params) spp_op = SparsePauliOp(paulis, coeffs) target = coeffs.copy() target[3] *= -1 target[4] *= 1j target[5] *= -1j np.testing.assert_array_equal(spp_op.coeffs, target) paulis.phase = 0 self.assertEqual(spp_op.paulis, paulis) def test_sparse_pauli_op_init(self): """Test SparsePauliOp initialization.""" labels = ["I", "X", "Y", "-Z", "iZ", "-iX"] with self.subTest(msg="make SparsePauliOp from SparsePauliOp"): op = SparsePauliOp(labels) ref_op = op.copy() spp_op = SparsePauliOp(op) self.assertEqual(spp_op, ref_op) np.testing.assert_array_equal(ref_op.paulis.phase, np.zeros(ref_op.size)) np.testing.assert_array_equal(spp_op.paulis.phase, np.zeros(spp_op.size)) # make sure the changes of `op` do not propagate through to `spp_op` op.paulis.z[:] = False op.coeffs *= 2 self.assertNotEqual(spp_op, op) self.assertEqual(spp_op, ref_op) with self.subTest(msg="make SparsePauliOp from SparsePauliOp and ndarray"): op = SparsePauliOp(labels) coeffs = np.array([1, 2, 3, 4, 5, 6]) spp_op = SparsePauliOp(op, coeffs) ref_op = SparsePauliOp(op.paulis.copy(), coeffs.copy()) self.assertEqual(spp_op, ref_op) np.testing.assert_array_equal(ref_op.paulis.phase, np.zeros(ref_op.size)) np.testing.assert_array_equal(spp_op.paulis.phase, np.zeros(spp_op.size)) # make sure the changes of `op` and `coeffs` do not propagate through to `spp_op` op.paulis.z[:] = False coeffs *= 2 self.assertNotEqual(spp_op, op) self.assertEqual(spp_op, ref_op) with self.subTest(msg="make SparsePauliOp from PauliList"): paulis = PauliList(labels) spp_op = SparsePauliOp(paulis) ref_op = SparsePauliOp(labels) self.assertEqual(spp_op, ref_op) np.testing.assert_array_equal(ref_op.paulis.phase, np.zeros(ref_op.size)) np.testing.assert_array_equal(spp_op.paulis.phase, np.zeros(spp_op.size)) # make sure the change of `paulis` does not propagate through to `spp_op` paulis.z[:] = False self.assertEqual(spp_op, ref_op) with self.subTest(msg="make SparsePauliOp from PauliList and ndarray"): paulis = PauliList(labels) coeffs = np.array([1, 2, 3, 4, 5, 6]) spp_op = SparsePauliOp(paulis, coeffs) ref_op = SparsePauliOp(labels, coeffs.copy()) self.assertEqual(spp_op, ref_op) np.testing.assert_array_equal(ref_op.paulis.phase, np.zeros(ref_op.size)) np.testing.assert_array_equal(spp_op.paulis.phase, np.zeros(spp_op.size)) # make sure the changes of `paulis` and `coeffs` do not propagate through to `spp_op` paulis.z[:] = False coeffs[:] = 0 self.assertEqual(spp_op, ref_op) class TestSparsePauliOpConversions(QiskitTestCase): """Tests SparsePauliOp representation conversions.""" def test_from_operator(self): """Test from_operator methods.""" for tup in it.product(["I", "X", "Y", "Z"], repeat=2): label = "".join(tup) with self.subTest(msg=label): spp_op = SparsePauliOp.from_operator(Operator(pauli_mat(label))) np.testing.assert_array_equal(spp_op.coeffs, [1]) self.assertEqual(spp_op.paulis, PauliList(label)) def test_from_list(self): """Test from_list method.""" labels = ["XXZ", "IXI", "YZZ", "III"] coeffs = [3.0, 5.5, -1j, 23.3333] spp_op = SparsePauliOp.from_list(zip(labels, coeffs)) np.testing.assert_array_equal(spp_op.coeffs, coeffs) self.assertEqual(spp_op.paulis, PauliList(labels)) def test_from_list_parameters(self): """Test from_list method with parameters.""" labels = ["XXZ", "IXI", "YZZ", "III"] coeffs = ParameterVector("a", 4) spp_op = SparsePauliOp.from_list(zip(labels, coeffs), dtype=object) np.testing.assert_array_equal(spp_op.coeffs, coeffs) self.assertEqual(spp_op.paulis, PauliList(labels)) def test_from_index_list(self): """Test from_list method specifying the Paulis via indices.""" expected_labels = ["XXZ", "IXI", "YIZ", "III"] paulis = ["XXZ", "X", "YZ", ""] indices = [[2, 1, 0], [1], [2, 0], []] coeffs = [3.0, 5.5, -1j, 23.3333] spp_op = SparsePauliOp.from_sparse_list(zip(paulis, indices, coeffs), num_qubits=3) np.testing.assert_array_equal(spp_op.coeffs, coeffs) self.assertEqual(spp_op.paulis, PauliList(expected_labels)) def test_from_index_list_parameters(self): """Test from_list method specifying the Paulis via indices with paramteres.""" expected_labels = ["XXZ", "IXI", "YIZ", "III"] paulis = ["XXZ", "X", "YZ", ""] indices = [[2, 1, 0], [1], [2, 0], []] coeffs = ParameterVector("a", 4) spp_op = SparsePauliOp.from_sparse_list( zip(paulis, indices, coeffs), num_qubits=3, dtype=object ) np.testing.assert_array_equal(spp_op.coeffs, coeffs) self.assertEqual(spp_op.paulis, PauliList(expected_labels)) def test_from_index_list_endianness(self): """Test the construction from index list has the right endianness.""" spp_op = SparsePauliOp.from_sparse_list([("ZX", [1, 4], 1)], num_qubits=5) expected = Pauli("XIIZI") self.assertEqual(spp_op.paulis[0], expected) def test_from_index_list_raises(self): """Test from_list via Pauli + indices raises correctly, if number of qubits invalid.""" with self.assertRaises(QiskitError): _ = SparsePauliOp.from_sparse_list([("Z", [2], 1)], 1) def test_from_index_list_same_index(self): """Test from_list via Pauli + number of qubits raises correctly, if indices duplicate.""" with self.assertRaises(QiskitError): _ = SparsePauliOp.from_sparse_list([("ZZ", [0, 0], 1)], 2) with self.assertRaises(QiskitError): _ = SparsePauliOp.from_sparse_list([("ZI", [0, 0], 1)], 2) with self.assertRaises(QiskitError): _ = SparsePauliOp.from_sparse_list([("IZ", [0, 0], 1)], 2) def test_from_zip(self): """Test from_list method for zipped input.""" labels = ["XXZ", "IXI", "YZZ", "III"] coeffs = [3.0, 5.5, -1j, 23.3333] spp_op = SparsePauliOp.from_list(zip(labels, coeffs)) np.testing.assert_array_equal(spp_op.coeffs, coeffs) self.assertEqual(spp_op.paulis, PauliList(labels)) def test_to_matrix(self): """Test to_matrix method.""" labels = ["XI", "YZ", "YY", "ZZ"] coeffs = [-3, 4.4j, 0.2 - 0.1j, 66.12] spp_op = SparsePauliOp(labels, coeffs) target = np.zeros((4, 4), dtype=complex) for coeff, label in zip(coeffs, labels): target += coeff * pauli_mat(label) np.testing.assert_array_equal(spp_op.to_matrix(), target) np.testing.assert_array_equal(spp_op.to_matrix(sparse=True).toarray(), target) def test_to_matrix_large(self): """Test to_matrix method with a large number of qubits.""" reps = 5 labels = ["XI" * reps, "YZ" * reps, "YY" * reps, "ZZ" * reps] coeffs = [-3, 4.4j, 0.2 - 0.1j, 66.12] spp_op = SparsePauliOp(labels, coeffs) size = 1 << 2 * reps target = np.zeros((size, size), dtype=complex) for coeff, label in zip(coeffs, labels): target += coeff * pauli_mat(label) np.testing.assert_array_equal(spp_op.to_matrix(), target) np.testing.assert_array_equal(spp_op.to_matrix(sparse=True).toarray(), target) def test_to_matrix_parameters(self): """Test to_matrix method for parameterized SparsePauliOp.""" labels = ["XI", "YZ", "YY", "ZZ"] coeffs = np.array(ParameterVector("a", 4)) spp_op = SparsePauliOp(labels, coeffs) target = np.zeros((4, 4), dtype=object) for coeff, label in zip(coeffs, labels): target += coeff * pauli_mat(label) np.testing.assert_array_equal(spp_op.to_matrix(), target) def test_to_operator(self): """Test to_operator method.""" labels = ["XI", "YZ", "YY", "ZZ"] coeffs = [-3, 4.4j, 0.2 - 0.1j, 66.12] spp_op = SparsePauliOp(labels, coeffs) target = Operator(np.zeros((4, 4), dtype=complex)) for coeff, label in zip(coeffs, labels): target = target + Operator(coeff * pauli_mat(label)) self.assertEqual(spp_op.to_operator(), target) def test_to_list(self): """Test to_operator method.""" labels = ["XI", "YZ", "YY", "ZZ"] coeffs = [-3, 4.4j, 0.2 - 0.1j, 66.12] op = SparsePauliOp(labels, coeffs) target = list(zip(labels, coeffs)) self.assertEqual(op.to_list(), target) def test_to_list_parameters(self): """Test to_operator method with paramters.""" labels = ["XI", "YZ", "YY", "ZZ"] coeffs = np.array(ParameterVector("a", 4)) op = SparsePauliOp(labels, coeffs) target = list(zip(labels, coeffs)) self.assertEqual(op.to_list(), target) class TestSparsePauliOpIteration(QiskitTestCase): """Tests for SparsePauliOp iterators class.""" def test_enumerate(self): """Test enumerate with SparsePauliOp.""" labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"] coeffs = np.array([1, 2, 3, 4, 5, 6]) op = SparsePauliOp(labels, coeffs) for idx, i in enumerate(op): self.assertEqual(i, SparsePauliOp(labels[idx], coeffs[[idx]])) def test_enumerate_parameters(self): """Test enumerate with SparsePauliOp with parameters.""" labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"] coeffs = np.array(ParameterVector("a", 6)) op = SparsePauliOp(labels, coeffs) for idx, i in enumerate(op): self.assertEqual(i, SparsePauliOp(labels[idx], coeffs[[idx]])) def test_iter(self): """Test iter with SparsePauliOp.""" labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"] coeffs = np.array([1, 2, 3, 4, 5, 6]) op = SparsePauliOp(labels, coeffs) for idx, i in enumerate(iter(op)): self.assertEqual(i, SparsePauliOp(labels[idx], coeffs[[idx]])) def test_iter_parameters(self): """Test iter with SparsePauliOp with parameters.""" labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"] coeffs = np.array(ParameterVector("a", 6)) op = SparsePauliOp(labels, coeffs) for idx, i in enumerate(iter(op)): self.assertEqual(i, SparsePauliOp(labels[idx], coeffs[[idx]])) def test_label_iter(self): """Test SparsePauliOp label_iter method.""" labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"] coeffs = np.array([1, 2, 3, 4, 5, 6]) op = SparsePauliOp(labels, coeffs) for idx, i in enumerate(op.label_iter()): self.assertEqual(i, (labels[idx], coeffs[idx])) def test_label_iter_parameters(self): """Test SparsePauliOp label_iter method with parameters.""" labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"] coeffs = np.array(ParameterVector("a", 6)) op = SparsePauliOp(labels, coeffs) for idx, i in enumerate(op.label_iter()): self.assertEqual(i, (labels[idx], coeffs[idx])) def test_matrix_iter(self): """Test SparsePauliOp dense matrix_iter method.""" labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"] coeffs = np.array([1, 2, 3, 4, 5, 6]) op = SparsePauliOp(labels, coeffs) for idx, i in enumerate(op.matrix_iter()): np.testing.assert_array_equal(i, coeffs[idx] * pauli_mat(labels[idx])) def test_matrix_iter_parameters(self): """Test SparsePauliOp dense matrix_iter method. with parameters""" labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"] coeffs = np.array(ParameterVector("a", 6)) op = SparsePauliOp(labels, coeffs) for idx, i in enumerate(op.matrix_iter()): np.testing.assert_array_equal(i, coeffs[idx] * pauli_mat(labels[idx])) def test_matrix_iter_sparse(self): """Test SparsePauliOp sparse matrix_iter method.""" labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"] coeffs = np.array([1, 2, 3, 4, 5, 6]) op = SparsePauliOp(labels, coeffs) for idx, i in enumerate(op.matrix_iter(sparse=True)): np.testing.assert_array_equal(i.toarray(), coeffs[idx] * pauli_mat(labels[idx])) def bind_parameters_to_one(array): """Bind parameters to one. The purpose of using this method is to bind some value and use ``assert_allclose``, since it is impossible to verify equivalence in the case of numerical errors with parameters existing. """ def bind_one(a): parameters = a.parameters return complex(a.bind(dict(zip(parameters, [1] * len(parameters))))) return np.vectorize(bind_one, otypes=[complex])(array) @ddt class TestSparsePauliOpMethods(QiskitTestCase): """Tests for SparsePauliOp operator methods.""" RNG = np.random.default_rng(1994) def setUp(self): super().setUp() self.parameter_names = (f"param_{x}" for x in it.count()) def random_spp_op(self, num_qubits, num_terms, use_parameters=False): """Generate a pseudo-random SparsePauliOp""" if use_parameters: coeffs = np.array(ParameterVector(next(self.parameter_names), num_terms)) else: coeffs = self.RNG.uniform(-1, 1, size=num_terms) + 1j * self.RNG.uniform( -1, 1, size=num_terms ) labels = [ "".join(self.RNG.choice(["I", "X", "Y", "Z"], size=num_qubits)) for _ in range(num_terms) ] return SparsePauliOp(labels, coeffs) @combine(num_qubits=[1, 2, 3, 4], use_parameters=[True, False]) def test_conjugate(self, num_qubits, use_parameters): """Test conjugate method for {num_qubits}-qubits.""" spp_op = self.random_spp_op(num_qubits, 2**num_qubits, use_parameters) target = spp_op.to_matrix().conjugate() op = spp_op.conjugate() value = op.to_matrix() np.testing.assert_array_equal(value, target) np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size)) @combine(num_qubits=[1, 2, 3, 4], use_parameters=[True, False]) def test_transpose(self, num_qubits, use_parameters): """Test transpose method for {num_qubits}-qubits.""" spp_op = self.random_spp_op(num_qubits, 2**num_qubits, use_parameters) target = spp_op.to_matrix().transpose() op = spp_op.transpose() value = op.to_matrix() np.testing.assert_array_equal(value, target) np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size)) @combine(num_qubits=[1, 2, 3, 4], use_parameters=[True, False]) def test_adjoint(self, num_qubits, use_parameters): """Test adjoint method for {num_qubits}-qubits.""" spp_op = self.random_spp_op(num_qubits, 2**num_qubits, use_parameters) target = spp_op.to_matrix().transpose().conjugate() op = spp_op.adjoint() value = op.to_matrix() np.testing.assert_array_equal(value, target) np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size)) @combine(num_qubits=[1, 2, 3, 4], use_parameters=[True, False]) def test_compose(self, num_qubits, use_parameters): """Test {num_qubits}-qubit compose methods.""" spp_op1 = self.random_spp_op(num_qubits, 2**num_qubits, use_parameters) spp_op2 = self.random_spp_op(num_qubits, 2**num_qubits, use_parameters) target = spp_op2.to_matrix() @ spp_op1.to_matrix() op = spp_op1.compose(spp_op2) value = op.to_matrix() if use_parameters: value = bind_parameters_to_one(value) target = bind_parameters_to_one(target) np.testing.assert_allclose(value, target, atol=1e-8) np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size)) op = spp_op1 & spp_op2 value = op.to_matrix() if use_parameters: value = bind_parameters_to_one(value) np.testing.assert_allclose(value, target, atol=1e-8) np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size)) @combine(num_qubits=[1, 2, 3, 4], use_parameters=[True, False]) def test_dot(self, num_qubits, use_parameters): """Test {num_qubits}-qubit dot methods.""" spp_op1 = self.random_spp_op(num_qubits, 2**num_qubits, use_parameters) spp_op2 = self.random_spp_op(num_qubits, 2**num_qubits, use_parameters) target = spp_op1.to_matrix() @ spp_op2.to_matrix() op = spp_op1.dot(spp_op2) value = op.to_matrix() if use_parameters: value = bind_parameters_to_one(value) target = bind_parameters_to_one(target) np.testing.assert_allclose(value, target, atol=1e-8) np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size)) op = spp_op1 @ spp_op2 value = op.to_matrix() if use_parameters: value = bind_parameters_to_one(value) np.testing.assert_allclose(value, target, atol=1e-8) np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size)) @combine(num_qubits=[1, 2, 3]) def test_qargs_compose(self, num_qubits): """Test 3-qubit compose method with {num_qubits}-qubit qargs.""" spp_op1 = self.random_spp_op(3, 2**3) spp_op2 = self.random_spp_op(num_qubits, 2**num_qubits) qargs = self.RNG.choice(3, size=num_qubits, replace=False).tolist() target = Operator(spp_op1).compose(Operator(spp_op2), qargs=qargs) op = spp_op1.compose(spp_op2, qargs=qargs) value = op.to_operator() self.assertEqual(value, target) np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size)) op = spp_op1 & spp_op2(qargs) value = op.to_operator() self.assertEqual(value, target) np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size)) @combine(num_qubits=[1, 2, 3]) def test_qargs_dot(self, num_qubits): """Test 3-qubit dot method with {num_qubits}-qubit qargs.""" spp_op1 = self.random_spp_op(3, 2**3) spp_op2 = self.random_spp_op(num_qubits, 2**num_qubits) qargs = self.RNG.choice(3, size=num_qubits, replace=False).tolist() target = Operator(spp_op1).dot(Operator(spp_op2), qargs=qargs) op = spp_op1.dot(spp_op2, qargs=qargs) value = op.to_operator() self.assertEqual(value, target) np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size)) @combine(num_qubits1=[1, 2, 3], num_qubits2=[1, 2, 3], use_parameters=[True, False]) def test_tensor(self, num_qubits1, num_qubits2, use_parameters): """Test tensor method for {num_qubits1} and {num_qubits2} qubits.""" spp_op1 = self.random_spp_op(num_qubits1, 2**num_qubits1, use_parameters) spp_op2 = self.random_spp_op(num_qubits2, 2**num_qubits2, use_parameters) target = np.kron(spp_op1.to_matrix(), spp_op2.to_matrix()) op = spp_op1.tensor(spp_op2) value = op.to_matrix() if use_parameters: value = bind_parameters_to_one(value) target = bind_parameters_to_one(target) np.testing.assert_allclose(value, target, atol=1e-8) np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size)) @combine(num_qubits1=[1, 2, 3], num_qubits2=[1, 2, 3], use_parameters=[True, False]) def test_expand(self, num_qubits1, num_qubits2, use_parameters): """Test expand method for {num_qubits1} and {num_qubits2} qubits.""" spp_op1 = self.random_spp_op(num_qubits1, 2**num_qubits1, use_parameters) spp_op2 = self.random_spp_op(num_qubits2, 2**num_qubits2, use_parameters) target = np.kron(spp_op2.to_matrix(), spp_op1.to_matrix()) op = spp_op1.expand(spp_op2) value = op.to_matrix() if use_parameters: value = bind_parameters_to_one(value) target = bind_parameters_to_one(target) np.testing.assert_allclose(value, target, atol=1e-8) np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size)) @combine(num_qubits=[1, 2, 3, 4], use_parameters=[True, False]) def test_add(self, num_qubits, use_parameters): """Test + method for {num_qubits} qubits.""" spp_op1 = self.random_spp_op(num_qubits, 2**num_qubits, use_parameters) spp_op2 = self.random_spp_op(num_qubits, 2**num_qubits, use_parameters) target = spp_op1.to_matrix() + spp_op2.to_matrix() op = spp_op1 + spp_op2 value = op.to_matrix() if use_parameters: value = bind_parameters_to_one(value) target = bind_parameters_to_one(target) np.testing.assert_allclose(value, target, atol=1e-8) np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size)) @combine(num_qubits=[1, 2, 3, 4], use_parameters=[True, False]) def test_sub(self, num_qubits, use_parameters): """Test + method for {num_qubits} qubits.""" spp_op1 = self.random_spp_op(num_qubits, 2**num_qubits, use_parameters) spp_op2 = self.random_spp_op(num_qubits, 2**num_qubits, use_parameters) target = spp_op1.to_matrix() - spp_op2.to_matrix() op = spp_op1 - spp_op2 value = op.to_matrix() if use_parameters: value = bind_parameters_to_one(value) target = bind_parameters_to_one(target) np.testing.assert_allclose(value, target, atol=1e-8) np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size)) @combine(num_qubits=[1, 2, 3]) def test_add_qargs(self, num_qubits): """Test + method for 3 qubits with {num_qubits} qubit qargs.""" spp_op1 = self.random_spp_op(3, 2**3) spp_op2 = self.random_spp_op(num_qubits, 2**num_qubits) qargs = self.RNG.choice(3, size=num_qubits, replace=False).tolist() target = Operator(spp_op1) + Operator(spp_op2)(qargs) op = spp_op1 + spp_op2(qargs) value = op.to_operator() self.assertEqual(value, target) np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size)) @combine(num_qubits=[1, 2, 3]) def test_sub_qargs(self, num_qubits): """Test - method for 3 qubits with {num_qubits} qubit qargs.""" spp_op1 = self.random_spp_op(3, 2**3) spp_op2 = self.random_spp_op(num_qubits, 2**num_qubits) qargs = self.RNG.choice(3, size=num_qubits, replace=False).tolist() target = Operator(spp_op1) - Operator(spp_op2)(qargs) op = spp_op1 - spp_op2(qargs) value = op.to_operator() self.assertEqual(value, target) np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size)) @combine( num_qubits=[1, 2, 3], value=[ 0, 1, 1j, -3 + 4.4j, np.int64(2), Parameter("x"), 0 * Parameter("x"), (-2 + 1.7j) * Parameter("x"), ], param=[None, "a"], ) def test_mul(self, num_qubits, value, param): """Test * method for {num_qubits} qubits and value {value}.""" spp_op = self.random_spp_op(num_qubits, 2**num_qubits, param) target = value * spp_op.to_matrix() op = value * spp_op value_mat = op.to_matrix() has_parameters = isinstance(value, ParameterExpression) or param is not None if value != 0 and has_parameters: value_mat = bind_parameters_to_one(value_mat) target = bind_parameters_to_one(target) if value == 0: np.testing.assert_array_equal(value_mat, target.astype(complex)) else: np.testing.assert_allclose(value_mat, target, atol=1e-8) np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size)) target = spp_op.to_matrix() * value op = spp_op * value value_mat = op.to_matrix() if value != 0 and has_parameters: value_mat = bind_parameters_to_one(value_mat) target = bind_parameters_to_one(target) if value == 0: np.testing.assert_array_equal(value_mat, target.astype(complex)) else: np.testing.assert_allclose(value_mat, target, atol=1e-8) np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size)) @combine(num_qubits=[1, 2, 3], value=[1, 1j, -3 + 4.4j], param=[None, "a"]) def test_div(self, num_qubits, value, param): """Test / method for {num_qubits} qubits and value {value}.""" spp_op = self.random_spp_op(num_qubits, 2**num_qubits, param) target = spp_op.to_matrix() / value op = spp_op / value value_mat = op.to_matrix() if param is not None: value_mat = bind_parameters_to_one(value_mat) target = bind_parameters_to_one(target) np.testing.assert_allclose(value_mat, target, atol=1e-8) np.testing.assert_array_equal(op.paulis.phase, np.zeros(op.size)) def test_simplify(self): """Test simplify method""" coeffs = [3 + 1j, -3 - 1j, 0, 4, -5, 2.2, -1.1j] labels = ["IXI", "IXI", "ZZZ", "III", "III", "XXX", "XXX"] spp_op = SparsePauliOp.from_list(zip(labels, coeffs)) simplified_op = spp_op.simplify() target_coeffs = [-1, 2.2 - 1.1j] target_labels = ["III", "XXX"] target_op = SparsePauliOp.from_list(zip(target_labels, target_coeffs)) self.assertEqual(simplified_op, target_op) np.testing.assert_array_equal(simplified_op.paulis.phase, np.zeros(simplified_op.size)) @combine(num_qubits=[1, 2, 3, 4], num_adds=[0, 1, 2, 3]) def test_simplify2(self, num_qubits, num_adds): """Test simplify method for {num_qubits} qubits with {num_adds} `add` calls.""" spp_op = self.random_spp_op(num_qubits, 2**num_qubits) for _ in range(num_adds): spp_op += spp_op simplified_op = spp_op.simplify() value = Operator(simplified_op) target = Operator(spp_op) self.assertEqual(value, target) np.testing.assert_array_equal(spp_op.paulis.phase, np.zeros(spp_op.size)) np.testing.assert_array_equal(simplified_op.paulis.phase, np.zeros(simplified_op.size)) @combine(num_qubits=[1, 2, 3, 4]) def test_simplify_zero(self, num_qubits): """Test simplify method for {num_qubits} qubits with zero operators.""" spp_op = self.random_spp_op(num_qubits, 2**num_qubits) zero_op = spp_op - spp_op simplified_op = zero_op.simplify() value = Operator(simplified_op) target = Operator(zero_op) self.assertEqual(value, target) np.testing.assert_array_equal(simplified_op.coeffs, [0]) np.testing.assert_array_equal(zero_op.paulis.phase, np.zeros(zero_op.size)) np.testing.assert_array_equal(simplified_op.paulis.phase, np.zeros(simplified_op.size)) def test_simplify_parameters(self): """Test simplify methods for parameterized SparsePauliOp.""" a = Parameter("a") coeffs = np.array([a, -a, 0, a, a, a, 2 * a]) labels = ["IXI", "IXI", "ZZZ", "III", "III", "XXX", "XXX"] spp_op = SparsePauliOp(labels, coeffs) simplified_op = spp_op.simplify() target_coeffs = np.array([2 * a, 3 * a]) target_labels = ["III", "XXX"] target_op = SparsePauliOp(target_labels, target_coeffs) self.assertEqual(simplified_op, target_op) np.testing.assert_array_equal(simplified_op.paulis.phase, np.zeros(simplified_op.size)) def test_sort(self): """Test sort method.""" with self.assertRaises(QiskitError): target = SparsePauliOp([], []) with self.subTest(msg="1 qubit real number"): target = SparsePauliOp( ["I", "I", "I", "I"], [-3.0 + 0.0j, 1.0 + 0.0j, 2.0 + 0.0j, 4.0 + 0.0j] ) value = SparsePauliOp(["I", "I", "I", "I"], [1, 2, -3, 4]).sort() self.assertEqual(target, value) with self.subTest(msg="1 qubit complex"): target = SparsePauliOp( ["I", "I", "I", "I"], [-1.0 + 0.0j, 0.0 - 1.0j, 0.0 + 1.0j, 1.0 + 0.0j] ) value = SparsePauliOp( ["I", "I", "I", "I"], [1.0 + 0.0j, 0.0 + 1.0j, 0.0 - 1.0j, -1.0 + 0.0j] ).sort() self.assertEqual(target, value) with self.subTest(msg="1 qubit Pauli I, X, Y, Z"): target = SparsePauliOp( ["I", "X", "Y", "Z"], [-1.0 + 2.0j, 1.0 + 0.0j, 2.0 + 0.0j, 3.0 - 4.0j] ) value = SparsePauliOp( ["Y", "X", "Z", "I"], [2.0 + 0.0j, 1.0 + 0.0j, 3.0 - 4.0j, -1.0 + 2.0j] ).sort() self.assertEqual(target, value) with self.subTest(msg="1 qubit weight order"): target = SparsePauliOp( ["I", "X", "Y", "Z"], [-1.0 + 2.0j, 1.0 + 0.0j, 2.0 + 0.0j, 3.0 - 4.0j] ) value = SparsePauliOp( ["Y", "X", "Z", "I"], [2.0 + 0.0j, 1.0 + 0.0j, 3.0 - 4.0j, -1.0 + 2.0j] ).sort(weight=True) self.assertEqual(target, value) with self.subTest(msg="1 qubit multi Pauli"): target = SparsePauliOp( ["I", "I", "I", "I", "X", "X", "Y", "Z"], [ -1.0 + 2.0j, 1.0 + 0.0j, 2.0 + 0.0j, 3.0 - 4.0j, -1.0 + 4.0j, -1.0 + 5.0j, -1.0 + 3.0j, -1.0 + 2.0j, ], ) value = SparsePauliOp( ["I", "I", "I", "I", "X", "Z", "Y", "X"], [ 2.0 + 0.0j, 1.0 + 0.0j, 3.0 - 4.0j, -1.0 + 2.0j, -1.0 + 5.0j, -1.0 + 2.0j, -1.0 + 3.0j, -1.0 + 4.0j, ], ).sort() self.assertEqual(target, value) with self.subTest(msg="2 qubit standard order"): target = SparsePauliOp( ["II", "XI", "XX", "XX", "XX", "XY", "XZ", "YI"], [ 4.0 + 0.0j, 7.0 + 0.0j, 2.0 + 1.0j, 2.0 + 2.0j, 3.0 + 0.0j, 6.0 + 0.0j, 5.0 + 0.0j, 3.0 + 0.0j, ], ) value = SparsePauliOp( ["XX", "XX", "XX", "YI", "II", "XZ", "XY", "XI"], [ 2.0 + 1.0j, 2.0 + 2.0j, 3.0 + 0.0j, 3.0 + 0.0j, 4.0 + 0.0j, 5.0 + 0.0j, 6.0 + 0.0j, 7.0 + 0.0j, ], ).sort() self.assertEqual(target, value) with self.subTest(msg="2 qubit weight order"): target = SparsePauliOp( ["II", "XI", "YI", "XX", "XX", "XX", "XY", "XZ"], [ 4.0 + 0.0j, 7.0 + 0.0j, 3.0 + 0.0j, 2.0 + 1.0j, 2.0 + 2.0j, 3.0 + 0.0j, 6.0 + 0.0j, 5.0 + 0.0j, ], ) value = SparsePauliOp( ["XX", "XX", "XX", "YI", "II", "XZ", "XY", "XI"], [ 2.0 + 1.0j, 2.0 + 2.0j, 3.0 + 0.0j, 3.0 + 0.0j, 4.0 + 0.0j, 5.0 + 0.0j, 6.0 + 0.0j, 7.0 + 0.0j, ], ).sort(weight=True) self.assertEqual(target, value) def test_chop(self): """Test chop, which individually truncates real and imaginary parts of the coeffs.""" eps = 1e-10 op = SparsePauliOp( ["XYZ", "ZII", "ZII", "YZY"], coeffs=[eps + 1j * eps, 1 + 1j * eps, eps + 1j, 1 + 1j] ) simplified = op.chop(tol=eps) expected_coeffs = [1, 1j, 1 + 1j] expected_paulis = ["ZII", "ZII", "YZY"] self.assertListEqual(simplified.coeffs.tolist(), expected_coeffs) self.assertListEqual(simplified.paulis.to_labels(), expected_paulis) def test_chop_all(self): """Test that chop returns an identity operator with coeff 0 if all coeffs are chopped.""" eps = 1e-10 op = SparsePauliOp(["X", "Z"], coeffs=[eps, eps]) simplified = op.chop(tol=eps) expected = SparsePauliOp(["I"], coeffs=[0.0]) self.assertEqual(simplified, expected) @combine(num_qubits=[1, 2, 3, 4], num_ops=[1, 2, 3, 4], param=[None, "a"]) def test_sum(self, num_qubits, num_ops, param): """Test sum method for {num_qubits} qubits with {num_ops} operators.""" ops = [ self.random_spp_op( num_qubits, 2**num_qubits, param if param is None else f"{param}_{i}" ) for i in range(num_ops) ] sum_op = SparsePauliOp.sum(ops) value = sum_op.to_matrix() target_operator = sum((op.to_matrix() for op in ops[1:]), ops[0].to_matrix()) if param is not None: value = bind_parameters_to_one(value) target_operator = bind_parameters_to_one(target_operator) np.testing.assert_allclose(value, target_operator, atol=1e-8) target_spp_op = sum((op for op in ops[1:]), ops[0]) self.assertEqual(sum_op, target_spp_op) np.testing.assert_array_equal(sum_op.paulis.phase, np.zeros(sum_op.size)) def test_sum_error(self): """Test sum method with invalid cases.""" with self.assertRaises(QiskitError): SparsePauliOp.sum([]) with self.assertRaises(QiskitError): ops = [self.random_spp_op(num_qubits, 2**num_qubits) for num_qubits in [1, 2]] SparsePauliOp.sum(ops) with self.assertRaises(QiskitError): SparsePauliOp.sum([1, 2]) @combine(num_qubits=[1, 2, 3, 4], use_parameters=[True, False]) def test_eq(self, num_qubits, use_parameters): """Test __eq__ method for {num_qubits} qubits.""" spp_op1 = self.random_spp_op(num_qubits, 2**num_qubits, use_parameters) spp_op2 = self.random_spp_op(num_qubits, 2**num_qubits, use_parameters) spp_op3 = self.random_spp_op(num_qubits, 2**num_qubits, use_parameters) zero = spp_op3 - spp_op3 self.assertEqual(spp_op1, spp_op1) self.assertEqual(spp_op2, spp_op2) self.assertNotEqual(spp_op1, spp_op1 + zero) self.assertNotEqual(spp_op2, spp_op2 + zero) if spp_op1 != spp_op2: self.assertNotEqual(spp_op1 + spp_op2, spp_op2 + spp_op1) @combine(num_qubits=[1, 2, 3, 4]) def test_equiv(self, num_qubits): """Test equiv method for {num_qubits} qubits.""" spp_op1 = self.random_spp_op(num_qubits, 2**num_qubits) spp_op2 = self.random_spp_op(num_qubits, 2**num_qubits) spp_op3 = self.random_spp_op(num_qubits, 2**num_qubits) spp_op4 = self.random_spp_op(num_qubits, 2**num_qubits) zero = spp_op3 - spp_op3 zero2 = spp_op4 - spp_op4 self.assertTrue(spp_op1.equiv(spp_op1)) self.assertTrue(spp_op1.equiv(spp_op1 + zero)) self.assertTrue(spp_op2.equiv(spp_op2)) self.assertTrue(spp_op2.equiv(spp_op2 + zero)) self.assertTrue(zero.equiv(zero2)) self.assertTrue((zero + zero2).equiv(zero2 + zero)) self.assertTrue((zero2 + zero).equiv(zero + zero2)) self.assertTrue((spp_op1 + spp_op2).equiv(spp_op2 + spp_op1)) self.assertTrue((spp_op2 + spp_op1).equiv(spp_op1 + spp_op2)) self.assertTrue((spp_op1 - spp_op1).equiv(spp_op2 - spp_op2)) self.assertTrue((2 * spp_op1).equiv(spp_op1 + spp_op1)) self.assertTrue((2 * spp_op2).equiv(spp_op2 + spp_op2)) if not spp_op1.equiv(zero): self.assertFalse(spp_op1.equiv(spp_op1 + spp_op1)) if not spp_op2.equiv(zero): self.assertFalse(spp_op2.equiv(spp_op2 + spp_op2)) def test_equiv_atol(self): """Test equiv method with atol.""" op1 = SparsePauliOp.from_list([("X", 1), ("Y", 2)]) op2 = op1 + 1e-7 * SparsePauliOp.from_list([("I", 1)]) self.assertFalse(op1.equiv(op2)) self.assertTrue(op1.equiv(op2, atol=1e-7)) def test_eq_equiv(self): """Test __eq__ and equiv methods with some specific cases.""" with self.subTest("shuffled"): spp_op1 = SparsePauliOp.from_list([("X", 1), ("Y", 2)]) spp_op2 = SparsePauliOp.from_list([("Y", 2), ("X", 1)]) self.assertNotEqual(spp_op1, spp_op2) self.assertTrue(spp_op1.equiv(spp_op2)) with self.subTest("w/ zero"): spp_op1 = SparsePauliOp.from_list([("X", 1), ("Y", 1)]) spp_op2 = SparsePauliOp.from_list([("X", 1), ("Y", 1), ("Z", 0)]) self.assertNotEqual(spp_op1, spp_op2) self.assertTrue(spp_op1.equiv(spp_op2)) @combine(parameterized=[True, False], qubit_wise=[True, False]) def test_group_commuting(self, parameterized, qubit_wise): """Test general grouping commuting operators""" def commutes(left: Pauli, right: Pauli, qubit_wise: bool) -> bool: if len(left) != len(right): return False if not qubit_wise: return left.commutes(right) else: # qubit-wise commuting check vec_l = left.z + 2 * left.x vec_r = right.z + 2 * right.x qubit_wise_comparison = (vec_l * vec_r) * (vec_l - vec_r) return np.all(qubit_wise_comparison == 0) input_labels = ["IX", "IY", "IZ", "XX", "YY", "ZZ", "XY", "YX", "ZX", "ZY", "XZ", "YZ"] np.random.shuffle(input_labels) if parameterized: coeffs = np.array(ParameterVector("a", len(input_labels))) else: coeffs = np.random.random(len(input_labels)) + np.random.random(len(input_labels)) * 1j sparse_pauli_list = SparsePauliOp(input_labels, coeffs) groups = sparse_pauli_list.group_commuting(qubit_wise) # checking that every input Pauli in sparse_pauli_list is in a group in the ouput output_labels = [pauli.to_label() for group in groups for pauli in group.paulis] self.assertListEqual(sorted(output_labels), sorted(input_labels)) # checking that every coeffs are grouped according to sparse_pauli_list group paulis_coeff_dict = dict( sum([list(zip(group.paulis.to_labels(), group.coeffs)) for group in groups], []) ) self.assertDictEqual(dict(zip(input_labels, coeffs)), paulis_coeff_dict) # Within each group, every operator commutes with every other operator. for group in groups: self.assertTrue( all( commutes(pauli1, pauli2, qubit_wise) for pauli1, pauli2 in it.combinations(group.paulis, 2) ) ) # For every pair of groups, at least one element from one group does not commute with # at least one element of the other. for group1, group2 in it.combinations(groups, 2): self.assertFalse( all( commutes(group1_pauli, group2_pauli, qubit_wise) for group1_pauli, group2_pauli in it.product(group1.paulis, group2.paulis) ) ) def test_dot_real(self): """Test dot for real coefficiets.""" x = SparsePauliOp("X", np.array([1])) y = SparsePauliOp("Y", np.array([1])) iz = SparsePauliOp("Z", 1j) self.assertEqual(x.dot(y), iz) def test_get_parameters(self): """Test getting the parameters.""" x, y = Parameter("x"), Parameter("y") op = SparsePauliOp(["X", "Y", "Z"], coeffs=[1, x, x * y]) with self.subTest(msg="all parameters"): self.assertEqual(ParameterView([x, y]), op.parameters) op.assign_parameters({y: 2}, inplace=True) with self.subTest(msg="after partial binding"): self.assertEqual(ParameterView([x]), op.parameters) def test_assign_parameters(self): """Test assign parameters.""" x, y = Parameter("x"), Parameter("y") op = SparsePauliOp(["X", "Y", "Z"], coeffs=[1, x, x * y]) # partial binding inplace op.assign_parameters({y: 2}, inplace=True) with self.subTest(msg="partial binding"): self.assertListEqual(op.coeffs.tolist(), [1, x, 2 * x]) # bind via array bound = op.assign_parameters([3]) with self.subTest(msg="fully bound"): self.assertTrue(np.allclose(bound.coeffs.astype(complex), [1, 3, 6])) def test_paulis_setter_rejects_bad_inputs(self): """Test that the setter for `paulis` rejects different-sized inputs.""" op = SparsePauliOp(["XY", "ZX"], coeffs=[1, 1j]) with self.assertRaisesRegex(ValueError, "incorrect number of qubits"): op.paulis = PauliList([Pauli("X"), Pauli("Y")]) with self.assertRaisesRegex(ValueError, "incorrect number of operators"): op.paulis = PauliList([Pauli("XY"), Pauli("ZX"), Pauli("YZ")]) if __name__ == "__main__": unittest.main()
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# 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 DensityMatrix quantum state class.""" import logging import unittest import numpy as np from ddt import data, ddt from numpy.testing import assert_allclose from qiskit import QiskitError, QuantumCircuit, QuantumRegister from qiskit.circuit.library import QFT, HGate from qiskit.quantum_info.operators.operator import Operator from qiskit.quantum_info.operators.symplectic import Pauli, SparsePauliOp from qiskit.quantum_info.random import random_density_matrix, random_pauli, random_unitary from qiskit.quantum_info.states import DensityMatrix, Statevector from qiskit.test import QiskitTestCase from qiskit.utils import optionals logger = logging.getLogger(__name__) @ddt class TestDensityMatrix(QiskitTestCase): """Tests for DensityMatrix class.""" @classmethod def rand_vec(cls, n, normalize=False): """Return complex vector or statevector""" seed = np.random.randint(0, np.iinfo(np.int32).max) logger.debug("rand_vec default_rng seeded with seed=%s", seed) rng = np.random.default_rng(seed) vec = rng.random(n) + 1j * rng.random(n) if normalize: vec /= np.sqrt(np.dot(vec, np.conj(vec))) return vec @classmethod def rand_rho(cls, n): """Return random pure state density matrix""" rho = cls.rand_vec(n, normalize=True) return np.outer(rho, np.conjugate(rho)) def test_init_array_qubit(self): """Test subsystem initialization from N-qubit array.""" # Test automatic inference of qubit subsystems rho = self.rand_rho(8) for dims in [None, 8]: state = DensityMatrix(rho, dims=dims) assert_allclose(state.data, rho) self.assertEqual(state.dim, 8) self.assertEqual(state.dims(), (2, 2, 2)) self.assertEqual(state.num_qubits, 3) def test_init_array(self): """Test initialization from array.""" rho = self.rand_rho(3) state = DensityMatrix(rho) assert_allclose(state.data, rho) self.assertEqual(state.dim, 3) self.assertEqual(state.dims(), (3,)) self.assertIsNone(state.num_qubits) rho = self.rand_rho(2 * 3 * 4) state = DensityMatrix(rho, dims=[2, 3, 4]) assert_allclose(state.data, rho) self.assertEqual(state.dim, 2 * 3 * 4) self.assertEqual(state.dims(), (2, 3, 4)) self.assertIsNone(state.num_qubits) def test_init_array_except(self): """Test initialization exception from array.""" rho = self.rand_rho(4) self.assertRaises(QiskitError, DensityMatrix, rho, dims=[4, 2]) self.assertRaises(QiskitError, DensityMatrix, rho, dims=[2, 4]) self.assertRaises(QiskitError, DensityMatrix, rho, dims=5) def test_init_densitymatrix(self): """Test initialization from DensityMatrix.""" rho1 = DensityMatrix(self.rand_rho(4)) rho2 = DensityMatrix(rho1) self.assertEqual(rho1, rho2) def test_init_statevector(self): """Test initialization from DensityMatrix.""" vec = self.rand_vec(4) target = DensityMatrix(np.outer(vec, np.conjugate(vec))) rho = DensityMatrix(Statevector(vec)) self.assertEqual(rho, target) def test_init_circuit(self): """Test initialization from a circuit.""" # random unitaries u0 = random_unitary(2).data u1 = random_unitary(2).data # add to circuit qr = QuantumRegister(2) circ = QuantumCircuit(qr) circ.unitary(u0, [qr[0]]) circ.unitary(u1, [qr[1]]) target_vec = Statevector(np.kron(u1, u0).dot([1, 0, 0, 0])) target = DensityMatrix(target_vec) rho = DensityMatrix(circ) self.assertEqual(rho, target) # Test tensor product of 1-qubit gates circuit = QuantumCircuit(3) circuit.h(0) circuit.x(1) circuit.ry(np.pi / 2, 2) target = DensityMatrix.from_label("000").evolve(Operator(circuit)) rho = DensityMatrix(circuit) self.assertEqual(rho, target) # Test decomposition of Controlled-Phase gate lam = np.pi / 4 circuit = QuantumCircuit(2) circuit.h(0) circuit.h(1) circuit.cp(lam, 0, 1) target = DensityMatrix.from_label("00").evolve(Operator(circuit)) rho = DensityMatrix(circuit) self.assertEqual(rho, target) def test_from_circuit(self): """Test initialization from a circuit.""" # random unitaries u0 = random_unitary(2).data u1 = random_unitary(2).data # add to circuit qr = QuantumRegister(2) circ = QuantumCircuit(qr) circ.unitary(u0, [qr[0]]) circ.unitary(u1, [qr[1]]) # Test decomposition of controlled-H gate circuit = QuantumCircuit(2) circ.x(0) circuit.ch(0, 1) target = DensityMatrix.from_label("00").evolve(Operator(circuit)) rho = DensityMatrix.from_instruction(circuit) self.assertEqual(rho, target) # Test initialize instruction init = Statevector([1, 0, 0, 1j]) / np.sqrt(2) target = DensityMatrix(init) circuit = QuantumCircuit(2) circuit.initialize(init.data, [0, 1]) rho = DensityMatrix.from_instruction(circuit) self.assertEqual(rho, target) # Test reset instruction target = DensityMatrix([1, 0]) circuit = QuantumCircuit(1) circuit.h(0) circuit.reset(0) rho = DensityMatrix.from_instruction(circuit) self.assertEqual(rho, target) def test_from_instruction(self): """Test initialization from an instruction.""" target_vec = Statevector(np.dot(HGate().to_matrix(), [1, 0])) target = DensityMatrix(target_vec) rho = DensityMatrix.from_instruction(HGate()) self.assertEqual(rho, target) def test_from_label(self): """Test initialization from a label""" x_p = DensityMatrix(np.array([[0.5, 0.5], [0.5, 0.5]])) x_m = DensityMatrix(np.array([[0.5, -0.5], [-0.5, 0.5]])) y_p = DensityMatrix(np.array([[0.5, -0.5j], [0.5j, 0.5]])) y_m = DensityMatrix(np.array([[0.5, 0.5j], [-0.5j, 0.5]])) z_p = DensityMatrix(np.diag([1, 0])) z_m = DensityMatrix(np.diag([0, 1])) label = "0+r" target = z_p.tensor(x_p).tensor(y_p) self.assertEqual(target, DensityMatrix.from_label(label)) label = "-l1" target = x_m.tensor(y_m).tensor(z_m) self.assertEqual(target, DensityMatrix.from_label(label)) def test_equal(self): """Test __eq__ method""" for _ in range(10): rho = self.rand_rho(4) self.assertEqual(DensityMatrix(rho), DensityMatrix(rho.tolist())) def test_copy(self): """Test DensityMatrix copy method""" for _ in range(5): rho = self.rand_rho(4) orig = DensityMatrix(rho) cpy = orig.copy() cpy._data[0] += 1.0 self.assertFalse(cpy == orig) def test_is_valid(self): """Test is_valid method.""" state = DensityMatrix(np.eye(2)) self.assertFalse(state.is_valid()) for _ in range(10): state = DensityMatrix(self.rand_rho(4)) self.assertTrue(state.is_valid()) def test_to_operator(self): """Test to_operator method for returning projector.""" for _ in range(10): rho = self.rand_rho(4) target = Operator(rho) op = DensityMatrix(rho).to_operator() self.assertEqual(op, target) def test_evolve(self): """Test evolve method for operators.""" for _ in range(10): op = random_unitary(4) rho = self.rand_rho(4) target = DensityMatrix(np.dot(op.data, rho).dot(op.adjoint().data)) evolved = DensityMatrix(rho).evolve(op) self.assertEqual(target, evolved) def test_evolve_subsystem(self): """Test subsystem evolve method for operators.""" # Test evolving single-qubit of 3-qubit system for _ in range(5): rho = self.rand_rho(8) state = DensityMatrix(rho) op0 = random_unitary(2) op1 = random_unitary(2) op2 = random_unitary(2) # Test evolve on 1-qubit op = op0 op_full = Operator(np.eye(4)).tensor(op) target = DensityMatrix(np.dot(op_full.data, rho).dot(op_full.adjoint().data)) self.assertEqual(state.evolve(op, qargs=[0]), target) # Evolve on qubit 1 op_full = Operator(np.eye(2)).tensor(op).tensor(np.eye(2)) target = DensityMatrix(np.dot(op_full.data, rho).dot(op_full.adjoint().data)) self.assertEqual(state.evolve(op, qargs=[1]), target) # Evolve on qubit 2 op_full = op.tensor(np.eye(4)) target = DensityMatrix(np.dot(op_full.data, rho).dot(op_full.adjoint().data)) self.assertEqual(state.evolve(op, qargs=[2]), target) # Test evolve on 2-qubits op = op1.tensor(op0) # Evolve on qubits [0, 2] op_full = op1.tensor(np.eye(2)).tensor(op0) target = DensityMatrix(np.dot(op_full.data, rho).dot(op_full.adjoint().data)) self.assertEqual(state.evolve(op, qargs=[0, 2]), target) # Evolve on qubits [2, 0] op_full = op0.tensor(np.eye(2)).tensor(op1) target = DensityMatrix(np.dot(op_full.data, rho).dot(op_full.adjoint().data)) self.assertEqual(state.evolve(op, qargs=[2, 0]), target) # Test evolve on 3-qubits op = op2.tensor(op1).tensor(op0) # Evolve on qubits [0, 1, 2] op_full = op target = DensityMatrix(np.dot(op_full.data, rho).dot(op_full.adjoint().data)) self.assertEqual(state.evolve(op, qargs=[0, 1, 2]), target) # Evolve on qubits [2, 1, 0] op_full = op0.tensor(op1).tensor(op2) target = DensityMatrix(np.dot(op_full.data, rho).dot(op_full.adjoint().data)) self.assertEqual(state.evolve(op, qargs=[2, 1, 0]), target) def test_evolve_qudit_subsystems(self): """Test nested evolve calls on qudit subsystems.""" dims = (3, 4, 5) init = self.rand_rho(np.prod(dims)) ops = [random_unitary((dim,)) for dim in dims] state = DensityMatrix(init, dims) for i, op in enumerate(ops): state = state.evolve(op, [i]) target_op = np.eye(1) for op in ops: target_op = np.kron(op.data, target_op) target = DensityMatrix(np.dot(target_op, init).dot(target_op.conj().T), dims) self.assertEqual(state, target) def test_conjugate(self): """Test conjugate method.""" for _ in range(10): rho = self.rand_rho(4) target = DensityMatrix(np.conj(rho)) state = DensityMatrix(rho).conjugate() self.assertEqual(state, target) def test_expand(self): """Test expand method.""" for _ in range(10): rho0 = self.rand_rho(2) rho1 = self.rand_rho(3) target = np.kron(rho1, rho0) state = DensityMatrix(rho0).expand(DensityMatrix(rho1)) self.assertEqual(state.dim, 6) self.assertEqual(state.dims(), (2, 3)) assert_allclose(state.data, target) def test_tensor(self): """Test tensor method.""" for _ in range(10): rho0 = self.rand_rho(2) rho1 = self.rand_rho(3) target = np.kron(rho0, rho1) state = DensityMatrix(rho0).tensor(DensityMatrix(rho1)) self.assertEqual(state.dim, 6) self.assertEqual(state.dims(), (3, 2)) assert_allclose(state.data, target) def test_add(self): """Test add method.""" for _ in range(10): rho0 = self.rand_rho(4) rho1 = self.rand_rho(4) state0 = DensityMatrix(rho0) state1 = DensityMatrix(rho1) self.assertEqual(state0 + state1, DensityMatrix(rho0 + rho1)) def test_add_except(self): """Test add method raises exceptions.""" state1 = DensityMatrix(self.rand_rho(2)) state2 = DensityMatrix(self.rand_rho(3)) self.assertRaises(QiskitError, state1.__add__, state2) def test_subtract(self): """Test subtract method.""" for _ in range(10): rho0 = self.rand_rho(4) rho1 = self.rand_rho(4) state0 = DensityMatrix(rho0) state1 = DensityMatrix(rho1) self.assertEqual(state0 - state1, DensityMatrix(rho0 - rho1)) def test_multiply(self): """Test multiply method.""" for _ in range(10): rho = self.rand_rho(4) state = DensityMatrix(rho) val = np.random.rand() + 1j * np.random.rand() self.assertEqual(val * state, DensityMatrix(val * state)) def test_negate(self): """Test negate method""" for _ in range(10): rho = self.rand_rho(4) state = DensityMatrix(rho) self.assertEqual(-state, DensityMatrix(-1 * rho)) def test_to_dict(self): """Test to_dict method""" with self.subTest(msg="dims = (2, 2)"): rho = DensityMatrix(np.arange(1, 17).reshape(4, 4)) target = { "00|00": 1, "01|00": 2, "10|00": 3, "11|00": 4, "00|01": 5, "01|01": 6, "10|01": 7, "11|01": 8, "00|10": 9, "01|10": 10, "10|10": 11, "11|10": 12, "00|11": 13, "01|11": 14, "10|11": 15, "11|11": 16, } self.assertDictAlmostEqual(target, rho.to_dict()) with self.subTest(msg="dims = (2, 3)"): rho = DensityMatrix(np.diag(np.arange(1, 7)), dims=(2, 3)) target = {} for i in range(2): for j in range(3): key = "{1}{0}|{1}{0}".format(i, j) target[key] = 2 * j + i + 1 self.assertDictAlmostEqual(target, rho.to_dict()) with self.subTest(msg="dims = (2, 11)"): vec = DensityMatrix(np.diag(np.arange(1, 23)), dims=(2, 11)) target = {} for i in range(2): for j in range(11): key = "{1},{0}|{1},{0}".format(i, j) target[key] = 2 * j + i + 1 self.assertDictAlmostEqual(target, vec.to_dict()) def test_densitymatrix_to_statevector_pure(self): """Test converting a pure density matrix to statevector.""" state = 1 / np.sqrt(2) * (np.array([1, 0, 0, 0, 0, 0, 0, 1])) psi = Statevector(state) rho = DensityMatrix(psi) phi = rho.to_statevector() self.assertTrue(psi.equiv(phi)) def test_densitymatrix_to_statevector_mixed(self): """Test converting a pure density matrix to statevector.""" state_1 = 1 / np.sqrt(2) * (np.array([1, 0, 0, 0, 0, 0, 0, 1])) state_2 = 1 / np.sqrt(2) * (np.array([0, 0, 0, 0, 0, 0, 1, 1])) psi = 0.5 * (Statevector(state_1) + Statevector(state_2)) rho = DensityMatrix(psi) self.assertRaises(QiskitError, rho.to_statevector) def test_probabilities_product(self): """Test probabilities method for product state""" state = DensityMatrix.from_label("+0") # 2-qubit qargs with self.subTest(msg="P(None)"): probs = state.probabilities() target = np.array([0.5, 0, 0.5, 0]) self.assertTrue(np.allclose(probs, target)) with self.subTest(msg="P([0, 1])"): probs = state.probabilities([0, 1]) target = np.array([0.5, 0, 0.5, 0]) self.assertTrue(np.allclose(probs, target)) with self.subTest(msg="P([1, 0]"): probs = state.probabilities([1, 0]) target = np.array([0.5, 0.5, 0, 0]) self.assertTrue(np.allclose(probs, target)) # 1-qubit qargs with self.subTest(msg="P([0])"): probs = state.probabilities([0]) target = np.array([1, 0]) self.assertTrue(np.allclose(probs, target)) with self.subTest(msg="P([1])"): probs = state.probabilities([1]) target = np.array([0.5, 0.5]) self.assertTrue(np.allclose(probs, target)) def test_probabilities_ghz(self): """Test probabilities method for GHZ state""" psi = (Statevector.from_label("000") + Statevector.from_label("111")) / np.sqrt(2) state = DensityMatrix(psi) # 3-qubit qargs target = np.array([0.5, 0, 0, 0, 0, 0, 0, 0.5]) for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities(qargs) self.assertTrue(np.allclose(probs, target)) # 2-qubit qargs target = np.array([0.5, 0, 0, 0.5]) for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities(qargs) self.assertTrue(np.allclose(probs, target)) # 1-qubit qargs target = np.array([0.5, 0.5]) for qargs in [[0], [1], [2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities(qargs) self.assertTrue(np.allclose(probs, target)) def test_probabilities_w(self): """Test probabilities method with W state""" psi = ( Statevector.from_label("001") + Statevector.from_label("010") + Statevector.from_label("100") ) / np.sqrt(3) state = DensityMatrix(psi) # 3-qubit qargs target = np.array([0, 1 / 3, 1 / 3, 0, 1 / 3, 0, 0, 0]) for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities(qargs) self.assertTrue(np.allclose(probs, target)) # 2-qubit qargs target = np.array([1 / 3, 1 / 3, 1 / 3, 0]) for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities(qargs) self.assertTrue(np.allclose(probs, target)) # 1-qubit qargs target = np.array([2 / 3, 1 / 3]) for qargs in [[0], [1], [2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities(qargs) self.assertTrue(np.allclose(probs, target)) def test_probabilities_dict_product(self): """Test probabilities_dict method for product state""" state = DensityMatrix.from_label("+0") # 2-qubit qargs with self.subTest(msg="P(None)"): probs = state.probabilities_dict() target = {"00": 0.5, "10": 0.5} self.assertDictAlmostEqual(probs, target) with self.subTest(msg="P([0, 1])"): probs = state.probabilities_dict([0, 1]) target = {"00": 0.5, "10": 0.5} self.assertDictAlmostEqual(probs, target) with self.subTest(msg="P([1, 0]"): probs = state.probabilities_dict([1, 0]) target = {"00": 0.5, "01": 0.5} self.assertDictAlmostEqual(probs, target) # 1-qubit qargs with self.subTest(msg="P([0])"): probs = state.probabilities_dict([0]) target = {"0": 1} self.assertDictAlmostEqual(probs, target) with self.subTest(msg="P([1])"): probs = state.probabilities_dict([1]) target = {"0": 0.5, "1": 0.5} self.assertDictAlmostEqual(probs, target) def test_probabilities_dict_ghz(self): """Test probabilities_dict method for GHZ state""" psi = (Statevector.from_label("000") + Statevector.from_label("111")) / np.sqrt(2) state = DensityMatrix(psi) # 3-qubit qargs target = {"000": 0.5, "111": 0.5} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities_dict(qargs) self.assertDictAlmostEqual(probs, target) # 2-qubit qargs target = {"00": 0.5, "11": 0.5} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities_dict(qargs) self.assertDictAlmostEqual(probs, target) # 1-qubit qargs target = {"0": 0.5, "1": 0.5} for qargs in [[0], [1], [2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities_dict(qargs) self.assertDictAlmostEqual(probs, target) def test_probabilities_dict_w(self): """Test probabilities_dict method with W state""" psi = ( Statevector.from_label("001") + Statevector.from_label("010") + Statevector.from_label("100") ) / np.sqrt(3) state = DensityMatrix(psi) # 3-qubit qargs target = np.array([0, 1 / 3, 1 / 3, 0, 1 / 3, 0, 0, 0]) target = {"001": 1 / 3, "010": 1 / 3, "100": 1 / 3} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities_dict(qargs) self.assertDictAlmostEqual(probs, target) # 2-qubit qargs target = {"00": 1 / 3, "01": 1 / 3, "10": 1 / 3} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities_dict(qargs) self.assertDictAlmostEqual(probs, target) # 1-qubit qargs target = {"0": 2 / 3, "1": 1 / 3} for qargs in [[0], [1], [2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities_dict(qargs) self.assertDictAlmostEqual(probs, target) def test_sample_counts_ghz(self): """Test sample_counts method for GHZ state""" shots = 2000 threshold = 0.02 * shots state = DensityMatrix( (Statevector.from_label("000") + Statevector.from_label("111")) / np.sqrt(2) ) state.seed(100) # 3-qubit qargs target = {"000": shots / 2, "111": shots / 2} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"counts (qargs={qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) # 2-qubit qargs target = {"00": shots / 2, "11": shots / 2} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: with self.subTest(msg=f"counts (qargs={qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) # 1-qubit qargs target = {"0": shots / 2, "1": shots / 2} for qargs in [[0], [1], [2]]: with self.subTest(msg=f"counts (qargs={qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) def test_sample_counts_w(self): """Test sample_counts method for W state""" shots = 3000 threshold = 0.02 * shots state = DensityMatrix( ( Statevector.from_label("001") + Statevector.from_label("010") + Statevector.from_label("100") ) / np.sqrt(3) ) state.seed(100) target = {"001": shots / 3, "010": shots / 3, "100": shots / 3} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"P({qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) # 2-qubit qargs target = {"00": shots / 3, "01": shots / 3, "10": shots / 3} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: with self.subTest(msg=f"P({qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) # 1-qubit qargs target = {"0": 2 * shots / 3, "1": shots / 3} for qargs in [[0], [1], [2]]: with self.subTest(msg=f"P({qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) def test_probabilities_dict_unequal_dims(self): """Test probabilities_dict for a state with unequal subsystem dimensions.""" vec = np.zeros(60, dtype=float) vec[15:20] = np.ones(5) vec[40:46] = np.ones(6) state = DensityMatrix(vec / np.sqrt(11.0), dims=[3, 4, 5]) p = 1.0 / 11.0 self.assertDictEqual( state.probabilities_dict(), { s: p for s in [ "110", "111", "112", "120", "121", "311", "312", "320", "321", "322", "330", ] }, ) # differences due to rounding self.assertDictAlmostEqual( state.probabilities_dict(qargs=[0]), {"0": 4 * p, "1": 4 * p, "2": 3 * p}, delta=1e-10 ) self.assertDictAlmostEqual( state.probabilities_dict(qargs=[1]), {"1": 5 * p, "2": 5 * p, "3": p}, delta=1e-10 ) self.assertDictAlmostEqual( state.probabilities_dict(qargs=[2]), {"1": 5 * p, "3": 6 * p}, delta=1e-10 ) self.assertDictAlmostEqual( state.probabilities_dict(qargs=[0, 1]), {"10": p, "11": 2 * p, "12": 2 * p, "20": 2 * p, "21": 2 * p, "22": p, "30": p}, delta=1e-10, ) self.assertDictAlmostEqual( state.probabilities_dict(qargs=[1, 0]), {"01": p, "11": 2 * p, "21": 2 * p, "02": 2 * p, "12": 2 * p, "22": p, "03": p}, delta=1e-10, ) self.assertDictAlmostEqual( state.probabilities_dict(qargs=[0, 2]), {"10": 2 * p, "11": 2 * p, "12": p, "31": 2 * p, "32": 2 * p, "30": 2 * p}, delta=1e-10, ) def test_sample_counts_qutrit(self): """Test sample_counts method for qutrit state""" p = 0.3 shots = 1000 threshold = 0.03 * shots state = DensityMatrix(np.diag([p, 0, 1 - p])) state.seed(100) with self.subTest(msg="counts"): target = {"0": shots * p, "2": shots * (1 - p)} counts = state.sample_counts(shots=shots) self.assertDictAlmostEqual(counts, target, threshold) def test_sample_memory_ghz(self): """Test sample_memory method for GHZ state""" shots = 2000 state = DensityMatrix( (Statevector.from_label("000") + Statevector.from_label("111")) / np.sqrt(2) ) state.seed(100) # 3-qubit qargs target = {"000": shots / 2, "111": shots / 2} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) self.assertEqual(set(memory), set(target)) # 2-qubit qargs target = {"00": shots / 2, "11": shots / 2} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) self.assertEqual(set(memory), set(target)) # 1-qubit qargs target = {"0": shots / 2, "1": shots / 2} for qargs in [[0], [1], [2]]: with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) self.assertEqual(set(memory), set(target)) def test_sample_memory_w(self): """Test sample_memory method for W state""" shots = 3000 state = DensityMatrix( ( Statevector.from_label("001") + Statevector.from_label("010") + Statevector.from_label("100") ) / np.sqrt(3) ) state.seed(100) target = {"001": shots / 3, "010": shots / 3, "100": shots / 3} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) self.assertEqual(set(memory), set(target)) # 2-qubit qargs target = {"00": shots / 3, "01": shots / 3, "10": shots / 3} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) self.assertEqual(set(memory), set(target)) # 1-qubit qargs target = {"0": 2 * shots / 3, "1": shots / 3} for qargs in [[0], [1], [2]]: with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) self.assertEqual(set(memory), set(target)) def test_sample_memory_qutrit(self): """Test sample_memory method for qutrit state""" p = 0.3 shots = 1000 state = DensityMatrix(np.diag([p, 0, 1 - p])) state.seed(100) with self.subTest(msg="memory"): memory = state.sample_memory(shots) self.assertEqual(len(memory), shots) self.assertEqual(set(memory), {"0", "2"}) def test_reset_2qubit(self): """Test reset method for 2-qubit state""" state = DensityMatrix(np.diag([0.5, 0, 0, 0.5])) with self.subTest(msg="reset"): rho = state.copy() value = rho.reset() target = DensityMatrix(np.diag([1, 0, 0, 0])) self.assertEqual(value, target) with self.subTest(msg="reset"): rho = state.copy() value = rho.reset([0, 1]) target = DensityMatrix(np.diag([1, 0, 0, 0])) self.assertEqual(value, target) with self.subTest(msg="reset [0]"): rho = state.copy() value = rho.reset([0]) target = DensityMatrix(np.diag([0.5, 0, 0.5, 0])) self.assertEqual(value, target) with self.subTest(msg="reset [0]"): rho = state.copy() value = rho.reset([1]) target = DensityMatrix(np.diag([0.5, 0.5, 0, 0])) self.assertEqual(value, target) def test_reset_qutrit(self): """Test reset method for qutrit""" state = DensityMatrix(np.diag([1, 1, 1]) / 3) state.seed(200) value = state.reset() target = DensityMatrix(np.diag([1, 0, 0])) self.assertEqual(value, target) def test_measure_2qubit(self): """Test measure method for 2-qubit state""" state = DensityMatrix.from_label("+0") seed = 200 shots = 100 with self.subTest(msg="measure"): for i in range(shots): rho = state.copy() rho.seed(seed + i) outcome, value = rho.measure() self.assertIn(outcome, ["00", "10"]) if outcome == "00": target = DensityMatrix.from_label("00") self.assertEqual(value, target) else: target = DensityMatrix.from_label("10") self.assertEqual(value, target) with self.subTest(msg="measure [0, 1]"): for i in range(shots): rho = state.copy() outcome, value = rho.measure([0, 1]) self.assertIn(outcome, ["00", "10"]) if outcome == "00": target = DensityMatrix.from_label("00") self.assertEqual(value, target) else: target = DensityMatrix.from_label("10") self.assertEqual(value, target) with self.subTest(msg="measure [1, 0]"): for i in range(shots): rho = state.copy() outcome, value = rho.measure([1, 0]) self.assertIn(outcome, ["00", "01"]) if outcome == "00": target = DensityMatrix.from_label("00") self.assertEqual(value, target) else: target = DensityMatrix.from_label("10") self.assertEqual(value, target) with self.subTest(msg="measure [0]"): for i in range(shots): rho = state.copy() outcome, value = rho.measure([0]) self.assertEqual(outcome, "0") target = DensityMatrix.from_label("+0") self.assertEqual(value, target) with self.subTest(msg="measure [1]"): for i in range(shots): rho = state.copy() outcome, value = rho.measure([1]) self.assertIn(outcome, ["0", "1"]) if outcome == "0": target = DensityMatrix.from_label("00") self.assertEqual(value, target) else: target = DensityMatrix.from_label("10") self.assertEqual(value, target) def test_measure_qutrit(self): """Test measure method for qutrit""" state = DensityMatrix(np.diag([1, 1, 1]) / 3) seed = 200 shots = 100 for i in range(shots): rho = state.copy() rho.seed(seed + i) outcome, value = rho.measure() self.assertIn(outcome, ["0", "1", "2"]) if outcome == "0": target = DensityMatrix(np.diag([1, 0, 0])) self.assertEqual(value, target) elif outcome == "1": target = DensityMatrix(np.diag([0, 1, 0])) self.assertEqual(value, target) else: target = DensityMatrix(np.diag([0, 0, 1])) self.assertEqual(value, target) def test_from_int(self): """Test from_int method""" with self.subTest(msg="from_int(0, 4)"): target = DensityMatrix([1, 0, 0, 0]) value = DensityMatrix.from_int(0, 4) self.assertEqual(target, value) with self.subTest(msg="from_int(3, 4)"): target = DensityMatrix([0, 0, 0, 1]) value = DensityMatrix.from_int(3, 4) self.assertEqual(target, value) with self.subTest(msg="from_int(8, (3, 3))"): target = DensityMatrix([0, 0, 0, 0, 0, 0, 0, 0, 1], dims=(3, 3)) value = DensityMatrix.from_int(8, (3, 3)) self.assertEqual(target, value) def test_expval(self): """Test expectation_value method""" psi = Statevector([1, 0, 0, 1]) / np.sqrt(2) rho = DensityMatrix(psi) for label, target in [ ("II", 1), ("XX", 1), ("YY", -1), ("ZZ", 1), ("IX", 0), ("YZ", 0), ("ZX", 0), ("YI", 0), ]: with self.subTest(msg=f"<{label}>"): op = Pauli(label) expval = rho.expectation_value(op) self.assertAlmostEqual(expval, target) psi = Statevector([np.sqrt(2), 0, 0, 0, 0, 0, 0, 1 + 1j]) / 2 rho = DensityMatrix(psi) for label, target in [ ("XXX", np.sqrt(2) / 2), ("YYY", -np.sqrt(2) / 2), ("ZZZ", 0), ("XYZ", 0), ("YIY", 0), ]: with self.subTest(msg=f"<{label}>"): op = Pauli(label) expval = rho.expectation_value(op) self.assertAlmostEqual(expval, target) labels = ["XXX", "IXI", "YYY", "III"] coeffs = [3.0, 5.5, -1j, 23] spp_op = SparsePauliOp.from_list(list(zip(labels, coeffs))) expval = rho.expectation_value(spp_op) target = 25.121320343559642 + 0.7071067811865476j self.assertAlmostEqual(expval, target) @data( "II", "IX", "IY", "IZ", "XI", "XX", "XY", "XZ", "YI", "YX", "YY", "YZ", "ZI", "ZX", "ZY", "ZZ", "-II", "-IX", "-IY", "-IZ", "-XI", "-XX", "-XY", "-XZ", "-YI", "-YX", "-YY", "-YZ", "-ZI", "-ZX", "-ZY", "-ZZ", "iII", "iIX", "iIY", "iIZ", "iXI", "iXX", "iXY", "iXZ", "iYI", "iYX", "iYY", "iYZ", "iZI", "iZX", "iZY", "iZZ", "-iII", "-iIX", "-iIY", "-iIZ", "-iXI", "-iXX", "-iXY", "-iXZ", "-iYI", "-iYX", "-iYY", "-iYZ", "-iZI", "-iZX", "-iZY", "-iZZ", ) def test_expval_pauli_f_contiguous(self, pauli): """Test expectation_value method for Pauli op""" seed = 1020 op = Pauli(pauli) rho = random_density_matrix(2**op.num_qubits, seed=seed) rho._data = np.reshape(rho.data.flatten(order="F"), rho.data.shape, order="F") target = rho.expectation_value(op.to_matrix()) expval = rho.expectation_value(op) self.assertAlmostEqual(expval, target) @data( "II", "IX", "IY", "IZ", "XI", "XX", "XY", "XZ", "YI", "YX", "YY", "YZ", "ZI", "ZX", "ZY", "ZZ", "-II", "-IX", "-IY", "-IZ", "-XI", "-XX", "-XY", "-XZ", "-YI", "-YX", "-YY", "-YZ", "-ZI", "-ZX", "-ZY", "-ZZ", "iII", "iIX", "iIY", "iIZ", "iXI", "iXX", "iXY", "iXZ", "iYI", "iYX", "iYY", "iYZ", "iZI", "iZX", "iZY", "iZZ", "-iII", "-iIX", "-iIY", "-iIZ", "-iXI", "-iXX", "-iXY", "-iXZ", "-iYI", "-iYX", "-iYY", "-iYZ", "-iZI", "-iZX", "-iZY", "-iZZ", ) def test_expval_pauli_c_contiguous(self, pauli): """Test expectation_value method for Pauli op""" seed = 1020 op = Pauli(pauli) rho = random_density_matrix(2**op.num_qubits, seed=seed) rho._data = np.reshape(rho.data.flatten(order="C"), rho.data.shape, order="C") target = rho.expectation_value(op.to_matrix()) expval = rho.expectation_value(op) self.assertAlmostEqual(expval, target) @data([0, 1], [0, 2], [1, 0], [1, 2], [2, 0], [2, 1]) def test_expval_pauli_qargs(self, qubits): """Test expectation_value method for Pauli op""" seed = 1020 op = random_pauli(2, seed=seed) state = random_density_matrix(2**3, seed=seed) target = state.expectation_value(op.to_matrix(), qubits) expval = state.expectation_value(op, qubits) self.assertAlmostEqual(expval, target) def test_reverse_qargs(self): """Test reverse_qargs method""" circ1 = QFT(5) circ2 = circ1.reverse_bits() state1 = DensityMatrix.from_instruction(circ1) state2 = DensityMatrix.from_instruction(circ2) self.assertEqual(state1.reverse_qargs(), state2) @unittest.skipUnless(optionals.HAS_MATPLOTLIB, "requires matplotlib") @unittest.skipUnless(optionals.HAS_PYLATEX, "requires pylatexenc") def test_drawings(self): """Test draw method""" qc1 = QFT(5) dm = DensityMatrix.from_instruction(qc1) with self.subTest(msg="str(density_matrix)"): str(dm) for drawtype in ["repr", "text", "latex", "latex_source", "qsphere", "hinton", "bloch"]: with self.subTest(msg=f"draw('{drawtype}')"): dm.draw(drawtype) def test_density_matrix_partial_transpose(self): """Test partial_transpose function on density matrices""" with self.subTest(msg="separable"): rho = DensityMatrix.from_label("10+") rho1 = np.zeros((8, 8), complex) rho1[4, 4] = 0.5 rho1[4, 5] = 0.5 rho1[5, 4] = 0.5 rho1[5, 5] = 0.5 self.assertEqual(rho.partial_transpose([0, 1]), DensityMatrix(rho1)) self.assertEqual(rho.partial_transpose([0, 2]), DensityMatrix(rho1)) with self.subTest(msg="entangled"): rho = DensityMatrix([[0, 0, 0, 0], [0, 0.5, -0.5, 0], [0, -0.5, 0.5, 0], [0, 0, 0, 0]]) rho1 = DensityMatrix([[0, 0, 0, -0.5], [0, 0.5, 0, 0], [0, 0, 0.5, 0], [-0.5, 0, 0, 0]]) self.assertEqual(rho.partial_transpose([0]), DensityMatrix(rho1)) self.assertEqual(rho.partial_transpose([1]), DensityMatrix(rho1)) with self.subTest(msg="dims(3,3)"): mat = np.zeros((9, 9)) mat1 = np.zeros((9, 9)) mat[8, 0] = 1 mat1[0, 8] = 1 rho = DensityMatrix(mat, dims=(3, 3)) rho1 = DensityMatrix(mat1, dims=(3, 3)) self.assertEqual(rho.partial_transpose([0, 1]), rho1) def test_clip_probabilities(self): """Test probabilities are clipped to [0, 1].""" dm = DensityMatrix([[1.1, 0], [0, 0]]) self.assertEqual(list(dm.probabilities()), [1.0, 0.0]) # The "1" key should be exactly zero and therefore omitted. self.assertEqual(dm.probabilities_dict(), {"0": 1.0}) def test_round_probabilities(self): """Test probabilities are correctly rounded. This is good to test to ensure clipping, renormalizing and rounding work together. """ p = np.sqrt(1 / 3) amplitudes = [p, p, p, 0] dm = DensityMatrix(np.outer(amplitudes, amplitudes)) expected = [0.33, 0.33, 0.33, 0] # Exact floating-point check because fixing the rounding should ensure this is exact. self.assertEqual(list(dm.probabilities(decimals=2)), expected) if __name__ == "__main__": unittest.main()
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# 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. """Quick program to test the quantum information states modules.""" import unittest import numpy as np from qiskit import QiskitError from qiskit.test import QiskitTestCase from qiskit.quantum_info.states import DensityMatrix, Statevector from qiskit.quantum_info import state_fidelity from qiskit.quantum_info import purity from qiskit.quantum_info import entropy from qiskit.quantum_info import concurrence from qiskit.quantum_info import entanglement_of_formation from qiskit.quantum_info import mutual_information from qiskit.quantum_info.states import shannon_entropy from qiskit.quantum_info import negativity class TestStateMeasures(QiskitTestCase): """Tests state measure functions""" def test_state_fidelity_statevector(self): """Test state_fidelity function for statevector inputs""" psi1 = [0.70710678118654746, 0, 0, 0.70710678118654746] psi2 = [0.0, 0.70710678118654746, 0.70710678118654746, 0.0] self.assertAlmostEqual(state_fidelity(psi1, psi1), 1.0, places=7, msg="vector-vector input") self.assertAlmostEqual(state_fidelity(psi2, psi2), 1.0, places=7, msg="vector-vector input") self.assertAlmostEqual(state_fidelity(psi1, psi2), 0.0, places=7, msg="vector-vector input") psi1 = Statevector([0.70710678118654746, 0, 0, 0.70710678118654746]) psi2 = Statevector([0.0, 0.70710678118654746, 0.70710678118654746, 0.0]) self.assertAlmostEqual(state_fidelity(psi1, psi1), 1.0, places=7, msg="vector-vector input") self.assertAlmostEqual(state_fidelity(psi2, psi2), 1.0, places=7, msg="vector-vector input") self.assertAlmostEqual(state_fidelity(psi1, psi2), 0.0, places=7, msg="vector-vector input") psi1 = Statevector([1, 0, 0, 1]) # invalid state psi2 = Statevector([1, 0, 0, 0]) self.assertRaises(QiskitError, state_fidelity, psi1, psi2) self.assertRaises(QiskitError, state_fidelity, psi1, psi2, validate=True) self.assertEqual(state_fidelity(psi1, psi2, validate=False), 1) def test_state_fidelity_density_matrix(self): """Test state_fidelity function for density matrix inputs""" rho1 = [[0.5, 0, 0, 0.5], [0, 0, 0, 0], [0, 0, 0, 0], [0.5, 0, 0, 0.5]] mix = [[0.25, 0, 0, 0], [0, 0.25, 0, 0], [0, 0, 0.25, 0], [0, 0, 0, 0.25]] self.assertAlmostEqual(state_fidelity(rho1, rho1), 1.0, places=7, msg="matrix-matrix input") self.assertAlmostEqual(state_fidelity(mix, mix), 1.0, places=7, msg="matrix-matrix input") self.assertAlmostEqual(state_fidelity(rho1, mix), 0.25, places=7, msg="matrix-matrix input") rho1 = DensityMatrix(rho1) mix = DensityMatrix(mix) self.assertAlmostEqual(state_fidelity(rho1, rho1), 1.0, places=7, msg="matrix-matrix input") self.assertAlmostEqual(state_fidelity(mix, mix), 1.0, places=7, msg="matrix-matrix input") self.assertAlmostEqual(state_fidelity(rho1, mix), 0.25, places=7, msg="matrix-matrix input") rho1 = DensityMatrix([1, 0, 0, 0]) mix = DensityMatrix(np.diag([1, 0, 0, 1])) self.assertRaises(QiskitError, state_fidelity, rho1, mix) self.assertRaises(QiskitError, state_fidelity, rho1, mix, validate=True) self.assertEqual(state_fidelity(rho1, mix, validate=False), 1) def test_state_fidelity_mixed(self): """Test state_fidelity function for statevector and density matrix inputs""" psi1 = Statevector([0.70710678118654746, 0, 0, 0.70710678118654746]) rho1 = DensityMatrix([[0.5, 0, 0, 0.5], [0, 0, 0, 0], [0, 0, 0, 0], [0.5, 0, 0, 0.5]]) mix = DensityMatrix([[0.25, 0, 0, 0], [0, 0.25, 0, 0], [0, 0, 0.25, 0], [0, 0, 0, 0.25]]) self.assertAlmostEqual(state_fidelity(psi1, rho1), 1.0, places=7, msg="vector-matrix input") self.assertAlmostEqual(state_fidelity(psi1, mix), 0.25, places=7, msg="vector-matrix input") self.assertAlmostEqual(state_fidelity(rho1, psi1), 1.0, places=7, msg="matrix-vector input") def test_purity_statevector(self): """Test purity function on statevector inputs""" psi = Statevector([1, 0, 0, 0]) self.assertEqual(purity(psi), 1) self.assertEqual(purity(psi, validate=True), 1) self.assertEqual(purity(psi, validate=False), 1) psi = [0.70710678118654746, 0.70710678118654746] self.assertAlmostEqual(purity(psi), 1) self.assertAlmostEqual(purity(psi, validate=True), 1) self.assertAlmostEqual(purity(psi, validate=False), 1) psi = np.array([0.5, 0.5j, -0.5j, -0.5]) self.assertAlmostEqual(purity(psi), 1) self.assertAlmostEqual(purity(psi, validate=True), 1) self.assertAlmostEqual(purity(psi, validate=False), 1) psi = Statevector([1, 0, 0, 1]) self.assertRaises(QiskitError, purity, psi) self.assertRaises(QiskitError, purity, psi, validate=True) self.assertEqual(purity(psi, validate=False), 4) def test_purity_density_matrix(self): """Test purity function on density matrix inputs""" rho = DensityMatrix(np.diag([1, 0, 0, 0])) self.assertEqual(purity(rho), 1) self.assertEqual(purity(rho, validate=True), 1) self.assertEqual(purity(rho, validate=False), 1) rho = np.diag([0.25, 0.25, 0.25, 0.25]) self.assertEqual(purity(rho), 0.25) self.assertEqual(purity(rho, validate=True), 0.25) self.assertEqual(purity(rho, validate=False), 0.25) rho = [[0.5, 0, 0, 0.5], [0, 0, 0, 0], [0, 0, 0, 0], [0.5, 0, 0, 0.5]] self.assertEqual(purity(rho), 1) self.assertEqual(purity(rho, validate=True), 1) self.assertEqual(purity(rho, validate=False), 1) rho = np.diag([1, 0, 0, 1]) self.assertRaises(QiskitError, purity, rho) self.assertRaises(QiskitError, purity, rho, validate=True) self.assertEqual(purity(rho, validate=False), 2) def test_purity_equivalence(self): """Test purity is same for equivalent inputs""" for alpha, beta in [ (0, 0), (0, 0.25), (0.25, 0), (0.33, 0.33), (0.5, 0.5), (0.75, 0.25), (0, 0.75), ]: psi = Statevector([alpha, beta, 0, 1j * np.sqrt(1 - alpha**2 - beta**2)]) rho = DensityMatrix(psi) self.assertAlmostEqual(purity(psi), purity(rho)) def test_entropy_statevector(self): """Test entropy function on statevector inputs""" test_psis = [ [1, 0], [0, 1, 0, 0], [0.5, 0.5, 0.5, 0.5], [0.5, 0.5j, -0.5j, 0.5], [0.70710678118654746, 0, 0, -0.70710678118654746j], [0.70710678118654746] + (14 * [0]) + [0.70710678118654746j], ] for psi_ls in test_psis: self.assertEqual(entropy(psi_ls), 0) self.assertEqual(entropy(np.array(psi_ls)), 0) def test_entropy_density_matrix(self): """Test entropy function on density matrix inputs""" # Density matrix input rhos = [DensityMatrix(np.diag([0.5] + (n * [0]) + [0.5])) for n in range(1, 5)] for rho in rhos: self.assertAlmostEqual(entropy(rho), 1) self.assertAlmostEqual(entropy(rho, base=2), 1) self.assertAlmostEqual(entropy(rho, base=np.e), -1 * np.log(0.5)) # Array input for prob in [0.001, 0.3, 0.7, 0.999]: rho = np.diag([prob, 1 - prob]) self.assertAlmostEqual(entropy(rho), shannon_entropy([prob, 1 - prob])) self.assertAlmostEqual( entropy(rho, base=np.e), shannon_entropy([prob, 1 - prob], base=np.e) ) self.assertAlmostEqual(entropy(rho, base=2), shannon_entropy([prob, 1 - prob], base=2)) # List input rho = [[0.5, 0], [0, 0.5]] self.assertAlmostEqual(entropy(rho), 1) def test_entropy_equivalence(self): """Test entropy is same for equivalent inputs""" for alpha, beta in [ (0, 0), (0, 0.25), (0.25, 0), (0.33, 0.33), (0.5, 0.5), (0.75, 0.25), (0, 0.75), ]: psi = Statevector([alpha, beta, 0, 1j * np.sqrt(1 - alpha**2 - beta**2)]) rho = DensityMatrix(psi) self.assertAlmostEqual(entropy(psi), entropy(rho)) def test_concurrence_statevector(self): """Test concurrence function on statevector inputs""" # Statevector input psi = Statevector([0.70710678118654746, 0, 0, -0.70710678118654746j]) self.assertAlmostEqual(concurrence(psi), 1) # List input psi = [1, 0, 0, 0] self.assertAlmostEqual(concurrence(psi), 0) # Array input psi = np.array([0.5, 0.5, 0.5, 0.5]) self.assertAlmostEqual(concurrence(psi), 0) # Larger than 2 qubit input psi_ls = [0.70710678118654746] + (14 * [0]) + [0.70710678118654746j] psi = Statevector(psi_ls, dims=(2, 8)) self.assertAlmostEqual(concurrence(psi), 1) psi = Statevector(psi_ls, dims=(4, 4)) self.assertAlmostEqual(concurrence(psi), 1) psi = Statevector(psi_ls, dims=(8, 2)) self.assertAlmostEqual(concurrence(psi), 1) def test_concurrence_density_matrix(self): """Test concurrence function on density matrix inputs""" # Density matrix input rho1 = DensityMatrix([[0.5, 0, 0, 0.5], [0, 0, 0, 0], [0, 0, 0, 0], [0.5, 0, 0, 0.5]]) rho2 = DensityMatrix([[0, 0, 0, 0], [0, 0.5, -0.5j, 0], [0, 0.5j, 0.5, 0], [0, 0, 0, 0]]) self.assertAlmostEqual(concurrence(rho1), 1) self.assertAlmostEqual(concurrence(rho2), 1) self.assertAlmostEqual(concurrence(0.5 * rho1 + 0.5 * rho2), 0) self.assertAlmostEqual(concurrence(0.75 * rho1 + 0.25 * rho2), 0.5) # List input rho = [[0.5, 0.5, 0, 0], [0.5, 0.5, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] self.assertEqual(concurrence(rho), 0) # Array input rho = np.diag([0.25, 0.25, 0.25, 0.25]) self.assertEqual(concurrence(rho), 0) def test_concurrence_equivalence(self): """Test concurrence is same for equivalent inputs""" for alpha, beta in [ (0, 0), (0, 0.25), (0.25, 0), (0.33, 0.33), (0.5, 0.5), (0.75, 0.25), (0, 0.75), ]: psi = Statevector([alpha, beta, 0, 1j * np.sqrt(1 - alpha**2 - beta**2)]) rho = DensityMatrix(psi) self.assertAlmostEqual(concurrence(psi), concurrence(rho)) def test_entanglement_of_formation_statevector(self): """Test entanglement of formation function on statevector inputs""" # Statevector input psi = Statevector([0.70710678118654746, 0, 0, -0.70710678118654746j]) self.assertAlmostEqual(entanglement_of_formation(psi), 1) # List input psi = [1, 0, 0, 0] self.assertAlmostEqual(entanglement_of_formation(psi), 0) # Array input psi = np.array([0.5, 0.5, 0.5, 0.5]) self.assertAlmostEqual(entanglement_of_formation(psi), 0) # Larger than 2 qubit input psi_ls = [0.70710678118654746] + (14 * [0]) + [0.70710678118654746j] psi = Statevector(psi_ls, dims=(2, 8)) self.assertAlmostEqual(entanglement_of_formation(psi), 1) psi = Statevector(psi_ls, dims=(4, 4)) self.assertAlmostEqual(entanglement_of_formation(psi), 1) psi = Statevector(psi_ls, dims=(8, 2)) self.assertAlmostEqual(entanglement_of_formation(psi), 1) def test_entanglement_of_formation_density_matrix(self): """Test entanglement of formation function on density matrix inputs""" # Density matrix input rho1 = DensityMatrix([[0.5, 0, 0, 0.5], [0, 0, 0, 0], [0, 0, 0, 0], [0.5, 0, 0, 0.5]]) rho2 = DensityMatrix([[0, 0, 0, 0], [0, 0.5, -0.5j, 0], [0, 0.5j, 0.5, 0], [0, 0, 0, 0]]) self.assertAlmostEqual(entanglement_of_formation(rho1), 1) self.assertAlmostEqual(entanglement_of_formation(rho2), 1) self.assertAlmostEqual(entanglement_of_formation(0.5 * rho1 + 0.5 * rho2), 0) self.assertAlmostEqual( entanglement_of_formation(0.75 * rho1 + 0.25 * rho2), 0.35457890266527003 ) # List input rho = [[0.5, 0.5, 0, 0], [0.5, 0.5, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] self.assertEqual(entanglement_of_formation(rho), 0) # Array input rho = np.diag([0.25, 0.25, 0.25, 0.25]) self.assertEqual(entanglement_of_formation(rho), 0) def test_entanglement_of_formation_equivalence(self): """Test entanglement of formation is same for equivalent inputs""" for alpha, beta in [ (0, 0), (0, 0.25), (0.25, 0), (0.33, 0.33), (0.5, 0.5), (0.75, 0.25), (0, 0.75), ]: psi = Statevector([alpha, beta, 0, 1j * np.sqrt(1 - alpha**2 - beta**2)]) rho = DensityMatrix(psi) self.assertAlmostEqual(entanglement_of_formation(psi), entanglement_of_formation(rho)) def test_mutual_information_statevector(self): """Test mutual_information function on statevector inputs""" # Statevector input psi = Statevector([0.70710678118654746, 0, 0, -0.70710678118654746j]) self.assertAlmostEqual(mutual_information(psi), 2) # List input psi = [1, 0, 0, 0] self.assertAlmostEqual(mutual_information(psi), 0) # Array input psi = np.array([0.5, 0.5, 0.5, 0.5]) self.assertAlmostEqual(mutual_information(psi), 0) # Larger than 2 qubit input psi_ls = [0.70710678118654746] + (14 * [0]) + [0.70710678118654746j] psi = Statevector(psi_ls, dims=(2, 8)) self.assertAlmostEqual(mutual_information(psi), 2) psi = Statevector(psi_ls, dims=(4, 4)) self.assertAlmostEqual(mutual_information(psi), 2) psi = Statevector(psi_ls, dims=(8, 2)) self.assertAlmostEqual(mutual_information(psi), 2) def test_mutual_information_density_matrix(self): """Test mutual_information function on density matrix inputs""" # Density matrix input rho1 = DensityMatrix([[0.5, 0, 0, 0.5], [0, 0, 0, 0], [0, 0, 0, 0], [0.5, 0, 0, 0.5]]) rho2 = DensityMatrix([[0, 0, 0, 0], [0, 0.5, -0.5j, 0], [0, 0.5j, 0.5, 0], [0, 0, 0, 0]]) self.assertAlmostEqual(mutual_information(rho1), 2) self.assertAlmostEqual(mutual_information(rho2), 2) # List input rho = [[0.5, 0.5, 0, 0], [0.5, 0.5, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] self.assertEqual(mutual_information(rho), 0) # Array input rho = np.diag([0.25, 0.25, 0.25, 0.25]) self.assertEqual(mutual_information(rho), 0) def test_mutual_information_equivalence(self): """Test mutual_information is same for equivalent inputs""" for alpha, beta in [ (0, 0), (0, 0.25), (0.25, 0), (0.33, 0.33), (0.5, 0.5), (0.75, 0.25), (0, 0.75), ]: psi = Statevector([alpha, beta, 0, 1j * np.sqrt(1 - alpha**2 - beta**2)]) rho = DensityMatrix(psi) self.assertAlmostEqual(mutual_information(psi), mutual_information(rho)) def test_negativity_statevector(self): """Test negativity function on statevector inputs""" # Constructing separable quantum statevector state = Statevector([1 / np.sqrt(2), 1 / np.sqrt(2), 0, 0]) negv = negativity(state, [0]) self.assertAlmostEqual(negv, 0, places=7) # Constructing entangled quantum statevector state = Statevector([0, 1 / np.sqrt(2), -1 / np.sqrt(2), 0]) negv = negativity(state, [1]) self.assertAlmostEqual(negv, 0.5, places=7) def test_negativity_density_matrix(self): """Test negativity function on density matrix inputs""" # Constructing separable quantum state rho = DensityMatrix.from_label("10+") negv = negativity(rho, [0, 1]) self.assertAlmostEqual(negv, 0, places=7) negv = negativity(rho, [0, 2]) self.assertAlmostEqual(negv, 0, places=7) # Constructing entangled quantum state rho = DensityMatrix([[0, 0, 0, 0], [0, 0.5, -0.5, 0], [0, -0.5, 0.5, 0], [0, 0, 0, 0]]) negv = negativity(rho, [0]) self.assertAlmostEqual(negv, 0.5, places=7) negv = negativity(rho, [1]) self.assertAlmostEqual(negv, 0.5, places=7) if __name__ == "__main__": unittest.main()
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# 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. """Tests for Stabilizerstate quantum state class.""" import unittest from test import combine import logging from ddt import ddt, data, unpack import numpy as np from qiskit.test import QiskitTestCase from qiskit import QuantumCircuit from qiskit.quantum_info.random import random_clifford, random_pauli from qiskit.quantum_info.states import StabilizerState, Statevector from qiskit.circuit.library import IGate, XGate, HGate from qiskit.quantum_info.operators import Clifford, Pauli, Operator logger = logging.getLogger(__name__) @ddt class TestStabilizerState(QiskitTestCase): """Tests for StabilizerState class.""" rng = np.random.default_rng(12345) samples = 10 shots = 1000 threshold = 0.1 * shots @combine(num_qubits=[2, 3, 4, 5]) def test_init_clifford(self, num_qubits): """Test initialization from Clifford.""" stab1 = StabilizerState(random_clifford(num_qubits, seed=self.rng)) stab2 = StabilizerState(stab1) self.assertEqual(stab1, stab2) @combine(num_qubits=[2, 3, 4, 5]) def test_init_circuit(self, num_qubits): """Test initialization from a Clifford circuit.""" cliff = random_clifford(num_qubits, seed=self.rng) stab1 = StabilizerState(cliff.to_circuit()) stab2 = StabilizerState(cliff) self.assertEqual(stab1, stab2) @combine(num_qubits=[2, 3, 4, 5]) def test_init_instruction(self, num_qubits): """Test initialization from a Clifford instruction.""" cliff = random_clifford(num_qubits, seed=self.rng) stab1 = StabilizerState(cliff.to_instruction()) stab2 = StabilizerState(cliff) self.assertEqual(stab1, stab2) @combine(num_qubits=[2, 3, 4, 5]) def test_init_pauli(self, num_qubits): """Test initialization from pauli.""" pauli = random_pauli(num_qubits, seed=self.rng) stab1 = StabilizerState(pauli) stab2 = StabilizerState(stab1) self.assertEqual(stab1, stab2) @combine(num_qubits=[2, 3, 4, 5]) def test_to_operator(self, num_qubits): """Test to_operator method for returning projector.""" for _ in range(self.samples): stab = StabilizerState(random_clifford(num_qubits, seed=self.rng)) target = Operator(stab) op = StabilizerState(stab).to_operator() self.assertEqual(op, target) @combine(num_qubits=[2, 3, 4]) def test_trace(self, num_qubits): """Test trace methods""" stab = StabilizerState(random_clifford(num_qubits, seed=self.rng)) trace = stab.trace() self.assertEqual(trace, 1.0) @combine(num_qubits=[2, 3, 4]) def test_purity(self, num_qubits): """Test purity methods""" stab = StabilizerState(random_clifford(num_qubits, seed=self.rng)) purity = stab.purity() self.assertEqual(purity, 1.0) @combine(num_qubits=[2, 3]) def test_conjugate(self, num_qubits): """Test conjugate method.""" for _ in range(self.samples): cliff = random_clifford(num_qubits, seed=self.rng) target = StabilizerState(cliff.conjugate()) state = StabilizerState(cliff).conjugate() self.assertEqual(state, target) def test_tensor(self): """Test tensor method.""" for _ in range(self.samples): cliff1 = random_clifford(2, seed=self.rng) cliff2 = random_clifford(3, seed=self.rng) stab1 = StabilizerState(cliff1) stab2 = StabilizerState(cliff2) target = StabilizerState(cliff1.tensor(cliff2)) state = stab1.tensor(stab2) self.assertEqual(state, target) def test_expand(self): """Test expand method.""" for _ in range(self.samples): cliff1 = random_clifford(2, seed=self.rng) cliff2 = random_clifford(3, seed=self.rng) stab1 = StabilizerState(cliff1) stab2 = StabilizerState(cliff2) target = StabilizerState(cliff1.expand(cliff2)) state = stab1.expand(stab2) self.assertEqual(state, target) @combine(num_qubits=[2, 3, 4]) def test_evolve(self, num_qubits): """Test evolve method.""" for _ in range(self.samples): cliff1 = random_clifford(num_qubits, seed=self.rng) cliff2 = random_clifford(num_qubits, seed=self.rng) stab1 = StabilizerState(cliff1) stab2 = StabilizerState(cliff2) target = StabilizerState(cliff1.compose(cliff2)) state = stab1.evolve(stab2) self.assertEqual(state, target) @combine(num_qubits_1=[4, 5, 6], num_qubits_2=[1, 2, 3]) def test_evolve_subsystem(self, num_qubits_1, num_qubits_2): """Test subsystem evolve method.""" for _ in range(self.samples): cliff1 = random_clifford(num_qubits_1, seed=self.rng) cliff2 = random_clifford(num_qubits_2, seed=self.rng) stab1 = StabilizerState(cliff1) stab2 = StabilizerState(cliff2) qargs = sorted(np.random.choice(range(num_qubits_1), num_qubits_2, replace=False)) target = StabilizerState(cliff1.compose(cliff2, qargs)) state = stab1.evolve(stab2, qargs) self.assertEqual(state, target) def test_measure_single_qubit(self): """Test a measurement of a single qubit""" for _ in range(self.samples): cliff = Clifford(XGate()) stab = StabilizerState(cliff) value = stab.measure()[0] self.assertEqual(value, "1") cliff = Clifford(IGate()) stab = StabilizerState(cliff) value = stab.measure()[0] self.assertEqual(value, "0") cliff = Clifford(HGate()) stab = StabilizerState(cliff) value = stab.measure()[0] self.assertIn(value, ["0", "1"]) def test_measure_qubits(self): """Test a measurement of a subsystem of qubits""" for _ in range(self.samples): num_qubits = 4 qc = QuantumCircuit(num_qubits) stab = StabilizerState(qc) value = stab.measure()[0] self.assertEqual(value, "0000") value = stab.measure([0, 2])[0] self.assertEqual(value, "00") value = stab.measure([1])[0] self.assertEqual(value, "0") for i in range(num_qubits): qc.x(i) stab = StabilizerState(qc) value = stab.measure()[0] self.assertEqual(value, "1111") value = stab.measure([2, 0])[0] self.assertEqual(value, "11") value = stab.measure([1])[0] self.assertEqual(value, "1") qc = QuantumCircuit(num_qubits) qc.h(0) stab = StabilizerState(qc) value = stab.measure()[0] self.assertIn(value, ["0000", "0001"]) value = stab.measure([0, 1])[0] self.assertIn(value, ["00", "01"]) value = stab.measure([2])[0] self.assertEqual(value, "0") qc = QuantumCircuit(num_qubits) qc.h(0) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) stab = StabilizerState(qc) value = stab.measure()[0] self.assertIn(value, ["0000", "1111"]) value = stab.measure([3, 1])[0] self.assertIn(value, ["00", "11"]) value = stab.measure([2])[0] self.assertIn(value, ["0", "1"]) def test_reset_single_qubit(self): """Test reset method of a single qubit""" empty_qc = QuantumCircuit(1) for _ in range(self.samples): cliff = Clifford(XGate()) stab = StabilizerState(cliff) value = stab.reset([0]) target = StabilizerState(empty_qc) self.assertEqual(value, target) cliff = Clifford(HGate()) stab = StabilizerState(cliff) value = stab.reset([0]) target = StabilizerState(empty_qc) self.assertEqual(value, target) def test_reset_qubits(self): """Test reset method of a subsystem of qubits""" num_qubits = 3 qc = QuantumCircuit(num_qubits) qc.h(0) qc.cx(0, 1) qc.cx(0, 2) for _ in range(self.samples): with self.subTest(msg="reset (None)"): stab = StabilizerState(qc) res = stab.reset() value = res.measure()[0] self.assertEqual(value, "000") for _ in range(self.samples): for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"reset (qargs={qargs})"): stab = StabilizerState(qc) res = stab.reset(qargs) value = res.measure()[0] self.assertEqual(value, "000") for _ in range(self.samples): with self.subTest(msg="reset ([0])"): stab = StabilizerState(qc) res = stab.reset([0]) value = res.measure()[0] self.assertIn(value, ["000", "110"]) for _ in range(self.samples): with self.subTest(msg="reset ([1])"): stab = StabilizerState(qc) res = stab.reset([1]) value = res.measure()[0] self.assertIn(value, ["000", "101"]) for _ in range(self.samples): with self.subTest(msg="reset ([2])"): stab = StabilizerState(qc) res = stab.reset([2]) value = res.measure()[0] self.assertIn(value, ["000", "011"]) for _ in range(self.samples): for qargs in [[0, 1], [1, 0]]: with self.subTest(msg=f"reset (qargs={qargs})"): stab = StabilizerState(qc) res = stab.reset(qargs) value = res.measure()[0] self.assertIn(value, ["000", "100"]) for _ in range(self.samples): for qargs in [[0, 2], [2, 0]]: with self.subTest(msg=f"reset (qargs={qargs})"): stab = StabilizerState(qc) res = stab.reset(qargs) value = res.measure()[0] self.assertIn(value, ["000", "010"]) for _ in range(self.samples): for qargs in [[1, 2], [2, 1]]: with self.subTest(msg=f"reset (qargs={qargs})"): stab = StabilizerState(qc) res = stab.reset(qargs) value = res.measure()[0] self.assertIn(value, ["000", "001"]) def test_probablities_dict_single_qubit(self): """Test probabilities and probabilities_dict methods of a single qubit""" num_qubits = 1 qc = QuantumCircuit(num_qubits) for _ in range(self.samples): with self.subTest(msg="P(id(0))"): stab = StabilizerState(qc) value = stab.probabilities_dict() target = {"0": 1} self.assertEqual(value, target) probs = stab.probabilities() target = np.array([1, 0]) self.assertTrue(np.allclose(probs, target)) qc.x(0) for _ in range(self.samples): with self.subTest(msg="P(x(0))"): stab = StabilizerState(qc) value = stab.probabilities_dict() target = {"1": 1} self.assertEqual(value, target) probs = stab.probabilities() target = np.array([0, 1]) self.assertTrue(np.allclose(probs, target)) qc = QuantumCircuit(num_qubits) qc.h(0) for _ in range(self.samples): with self.subTest(msg="P(h(0))"): stab = StabilizerState(qc) value = stab.probabilities_dict() target = {"0": 0.5, "1": 0.5} self.assertEqual(value, target) probs = stab.probabilities() target = np.array([0.5, 0.5]) self.assertTrue(np.allclose(probs, target)) def test_probablities_dict_two_qubits(self): """Test probabilities and probabilities_dict methods of two qubits""" num_qubits = 2 qc = QuantumCircuit(num_qubits) qc.h(0) stab = StabilizerState(qc) for _ in range(self.samples): with self.subTest(msg="P(None)"): value = stab.probabilities_dict() target = {"00": 0.5, "01": 0.5} self.assertEqual(value, target) probs = stab.probabilities() target = np.array([0.5, 0.5, 0, 0]) self.assertTrue(np.allclose(probs, target)) for _ in range(self.samples): with self.subTest(msg="P([0, 1])"): value = stab.probabilities_dict([0, 1]) target = {"00": 0.5, "01": 0.5} self.assertEqual(value, target) probs = stab.probabilities([0, 1]) target = np.array([0.5, 0.5, 0, 0]) self.assertTrue(np.allclose(probs, target)) for _ in range(self.samples): with self.subTest(msg="P([1, 0])"): value = stab.probabilities_dict([1, 0]) target = {"00": 0.5, "10": 0.5} self.assertEqual(value, target) probs = stab.probabilities([1, 0]) target = np.array([0.5, 0, 0.5, 0]) self.assertTrue(np.allclose(probs, target)) for _ in range(self.samples): with self.subTest(msg="P[0]"): value = stab.probabilities_dict([0]) target = {"0": 0.5, "1": 0.5} self.assertEqual(value, target) probs = stab.probabilities([0]) target = np.array([0.5, 0.5]) self.assertTrue(np.allclose(probs, target)) for _ in range(self.samples): with self.subTest(msg="P([1])"): value = stab.probabilities_dict([1]) target = {"0": 1.0} self.assertEqual(value, target) probs = stab.probabilities([1]) target = np.array([1, 0]) self.assertTrue(np.allclose(probs, target)) def test_probablities_dict_qubits(self): """Test probabilities and probabilities_dict methods of a subsystem of qubits""" num_qubits = 3 qc = QuantumCircuit(num_qubits) qc.h(0) qc.h(1) qc.h(2) stab = StabilizerState(qc) for _ in range(self.samples): with self.subTest(msg="P(None), decimals=1"): value = stab.probabilities_dict(decimals=1) target = { "000": 0.1, "001": 0.1, "010": 0.1, "011": 0.1, "100": 0.1, "101": 0.1, "110": 0.1, "111": 0.1, } self.assertEqual(value, target) probs = stab.probabilities(decimals=1) target = np.array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]) self.assertTrue(np.allclose(probs, target)) for _ in range(self.samples): with self.subTest(msg="P(None), decimals=2"): value = stab.probabilities_dict(decimals=2) target = { "000": 0.12, "001": 0.12, "010": 0.12, "011": 0.12, "100": 0.12, "101": 0.12, "110": 0.12, "111": 0.12, } self.assertEqual(value, target) probs = stab.probabilities(decimals=2) target = np.array([0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12]) self.assertTrue(np.allclose(probs, target)) for _ in range(self.samples): with self.subTest(msg="P(None), decimals=3"): value = stab.probabilities_dict(decimals=3) target = { "000": 0.125, "001": 0.125, "010": 0.125, "011": 0.125, "100": 0.125, "101": 0.125, "110": 0.125, "111": 0.125, } self.assertEqual(value, target) probs = stab.probabilities(decimals=3) target = np.array([0.125, 0.125, 0.125, 0.125, 0.125, 0.125, 0.125, 0.125]) self.assertTrue(np.allclose(probs, target)) def test_probablities_dict_ghz(self): """Test probabilities and probabilities_dict method of a subsystem of qubits""" num_qubits = 3 qc = QuantumCircuit(num_qubits) qc.h(0) qc.cx(0, 1) qc.cx(0, 2) with self.subTest(msg="P(None)"): stab = StabilizerState(qc) value = stab.probabilities_dict() target = {"000": 0.5, "111": 0.5} self.assertEqual(value, target) probs = stab.probabilities() target = np.array([0.5, 0, 0, 0, 0, 0, 0, 0.5]) self.assertTrue(np.allclose(probs, target)) # 3-qubit qargs for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"P({qargs})"): probs = stab.probabilities_dict(qargs) target = {"000": 0.5, "111": 0.5} self.assertDictAlmostEqual(probs, target) probs = stab.probabilities(qargs) target = np.array([0.5, 0, 0, 0, 0, 0, 0, 0.5]) self.assertTrue(np.allclose(probs, target)) # 2-qubit qargs for qargs in [[0, 1], [2, 1], [1, 0], [1, 2]]: with self.subTest(msg=f"P({qargs})"): probs = stab.probabilities_dict(qargs) target = {"00": 0.5, "11": 0.5} self.assertDictAlmostEqual(probs, target) probs = stab.probabilities(qargs) target = np.array([0.5, 0, 0, 0.5]) self.assertTrue(np.allclose(probs, target)) # 1-qubit qargs for qargs in [[0], [1], [2]]: with self.subTest(msg=f"P({qargs})"): probs = stab.probabilities_dict(qargs) target = {"0": 0.5, "1": 0.5} self.assertDictAlmostEqual(probs, target) probs = stab.probabilities(qargs) target = np.array([0.5, 0.5]) self.assertTrue(np.allclose(probs, target)) @combine(num_qubits=[2, 3, 4]) def test_probs_random_subsystem(self, num_qubits): """Test probabilities and probabilities_dict methods of random cliffords for a subsystem of qubits""" for _ in range(self.samples): for subsystem_size in range(1, num_qubits): cliff = random_clifford(num_qubits, seed=self.rng) qargs = np.random.choice(num_qubits, size=subsystem_size, replace=False) qc = cliff.to_circuit() stab = StabilizerState(cliff) probs = stab.probabilities(qargs) probs_dict = stab.probabilities_dict(qargs) target = Statevector(qc).probabilities(qargs) target_dict = Statevector(qc).probabilities_dict(qargs) self.assertTrue(np.allclose(probs, target)) self.assertDictAlmostEqual(probs_dict, target_dict) @combine(num_qubits=[2, 3, 4, 5]) def test_expval_from_random_clifford(self, num_qubits): """Test that the expectation values for a random Clifford, where the Pauli operators are all its stabilizers, are equal to 1.""" for _ in range(self.samples): cliff = random_clifford(num_qubits, seed=self.rng) qc = cliff.to_circuit() stab = StabilizerState(qc) stab_gen = stab.clifford.to_dict()["stabilizer"] for i in range(num_qubits): op = Pauli(stab_gen[i]) exp_val = stab.expectation_value(op) self.assertEqual(exp_val, 1) def test_sample_counts_reset_bell(self): """Test sample_counts after reset for Bell state""" num_qubits = 2 qc = QuantumCircuit(num_qubits) qc.h(0) qc.cx(0, 1) stab = StabilizerState(qc) target = {"00": self.shots / 2, "10": self.shots / 2} counts = {"00": 0, "10": 0} for _ in range(self.shots): res = stab.reset([0]) value = res.measure()[0] counts[value] += 1 self.assertDictAlmostEqual(counts, target, self.threshold) target = {"00": self.shots / 2, "01": self.shots / 2} counts = {"00": 0, "01": 0} for _ in range(self.shots): res = stab.reset([1]) value = res.measure()[0] counts[value] += 1 self.assertDictAlmostEqual(counts, target, self.threshold) def test_sample_counts_memory_ghz(self): """Test sample_counts and sample_memory method for GHZ state""" num_qubits = 3 qc = QuantumCircuit(num_qubits) qc.h(0) qc.cx(0, 1) qc.cx(0, 2) stab = StabilizerState(qc) # 3-qubit qargs target = {"000": self.shots / 2, "111": self.shots / 2} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"counts (qargs={qargs})"): counts = stab.sample_counts(self.shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, self.threshold) with self.subTest(msg=f"memory (qargs={qargs})"): memory = stab.sample_memory(self.shots, qargs=qargs) self.assertEqual(len(memory), self.shots) self.assertEqual(set(memory), set(target)) # 2-qubit qargs target = {"00": self.shots / 2, "11": self.shots / 2} for qargs in [[0, 1], [2, 1], [1, 2], [1, 0]]: with self.subTest(msg=f"counts (qargs={qargs})"): counts = stab.sample_counts(self.shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, self.threshold) with self.subTest(msg=f"memory (qargs={qargs})"): memory = stab.sample_memory(self.shots, qargs=qargs) self.assertEqual(len(memory), self.shots) self.assertEqual(set(memory), set(target)) # 1-qubit qargs target = {"0": self.shots / 2, "1": self.shots / 2} for qargs in [[0], [1], [2]]: with self.subTest(msg=f"counts (qargs={qargs})"): counts = stab.sample_counts(self.shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, self.threshold) with self.subTest(msg=f"memory (qargs={qargs})"): memory = stab.sample_memory(self.shots, qargs=qargs) self.assertEqual(len(memory), self.shots) self.assertEqual(set(memory), set(target)) def test_sample_counts_memory_superposition(self): """Test sample_counts and sample_memory method of a 3-qubit superposition""" num_qubits = 3 qc = QuantumCircuit(num_qubits) qc.h(0) qc.h(1) qc.h(2) stab = StabilizerState(qc) # 3-qubit qargs target = { "000": self.shots / 8, "001": self.shots / 8, "010": self.shots / 8, "011": self.shots / 8, "100": self.shots / 8, "101": self.shots / 8, "110": self.shots / 8, "111": self.shots / 8, } for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"counts (qargs={qargs})"): counts = stab.sample_counts(self.shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, self.threshold) with self.subTest(msg=f"memory (qargs={qargs})"): memory = stab.sample_memory(self.shots, qargs=qargs) self.assertEqual(len(memory), self.shots) self.assertEqual(set(memory), set(target)) # 2-qubit qargs target = { "00": self.shots / 4, "01": self.shots / 4, "10": self.shots / 4, "11": self.shots / 4, } for qargs in [[0, 1], [2, 1], [1, 2], [1, 0]]: with self.subTest(msg=f"counts (qargs={qargs})"): counts = stab.sample_counts(self.shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, self.threshold) with self.subTest(msg=f"memory (qargs={qargs})"): memory = stab.sample_memory(self.shots, qargs=qargs) self.assertEqual(len(memory), self.shots) self.assertEqual(set(memory), set(target)) # 1-qubit qargs target = {"0": self.shots / 2, "1": self.shots / 2} for qargs in [[0], [1], [2]]: with self.subTest(msg=f"counts (qargs={qargs})"): counts = stab.sample_counts(self.shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, self.threshold) with self.subTest(msg=f"memory (qargs={qargs})"): memory = stab.sample_memory(self.shots, qargs=qargs) self.assertEqual(len(memory), self.shots) self.assertEqual(set(memory), set(target)) @ddt class TestStabilizerStateExpectationValue(QiskitTestCase): """Tests for StabilizerState.expectation_value method.""" rng = np.random.default_rng(12345) samples = 10 shots = 1000 threshold = 0.1 * shots @data(("Z", 1), ("X", 0), ("Y", 0), ("I", 1), ("Z", 1), ("-Z", -1), ("iZ", 1j), ("-iZ", -1j)) @unpack def test_expval_single_qubit_0(self, label, target): """Test expectation_value method of a single qubit on |0>""" qc = QuantumCircuit(1) stab = StabilizerState(qc) op = Pauli(label) expval = stab.expectation_value(op) self.assertEqual(expval, target) @data(("Z", -1), ("X", 0), ("Y", 0), ("I", 1)) @unpack def test_expval_single_qubit_1(self, label, target): """Test expectation_value method of a single qubit on |1>""" qc = QuantumCircuit(1) qc.x(0) stab = StabilizerState(qc) op = Pauli(label) expval = stab.expectation_value(op) self.assertEqual(expval, target) @data(("Z", 0), ("X", 1), ("Y", 0), ("I", 1), ("X", 1), ("-X", -1), ("iX", 1j), ("-iX", -1j)) @unpack def test_expval_single_qubit_plus(self, label, target): """Test expectation_value method of a single qubit on |+>""" qc = QuantumCircuit(1) qc.h(0) stab = StabilizerState(qc) op = Pauli(label) expval = stab.expectation_value(op) self.assertEqual(expval, target) @data( ("II", 1), ("XX", 0), ("YY", 0), ("ZZ", 1), ("IX", 0), ("IY", 0), ("IZ", 1), ("XY", 0), ("XZ", 0), ("YZ", 0), ("-ZZ", -1), ("iZZ", 1j), ("-iZZ", -1j), ) @unpack def test_expval_two_qubits_00(self, label, target): """Test expectation_value method of two qubits in |00>""" num_qubits = 2 qc = QuantumCircuit(num_qubits) stab = StabilizerState(qc) op = Pauli(label) expval = stab.expectation_value(op) self.assertEqual(expval, target) @data( ("II", 1), ("XX", 0), ("YY", 0), ("ZZ", 1), ("IX", 0), ("IY", 0), ("IZ", -1), ("XY", 0), ("XZ", 0), ("YZ", 0), ) @unpack def test_expval_two_qubits_11(self, label, target): """Test expectation_value method of two qubits in |11>""" qc = QuantumCircuit(2) qc.x(0) qc.x(1) stab = StabilizerState(qc) op = Pauli(label) expval = stab.expectation_value(op) self.assertEqual(expval, target) @data( ("II", 1), ("XX", 1), ("YY", 0), ("ZZ", 0), ("IX", 1), ("IY", 0), ("IZ", 0), ("XY", 0), ("XZ", 0), ("YZ", 0), ("-XX", -1), ("iXX", 1j), ("-iXX", -1j), ) @unpack def test_expval_two_qubits_plusplus(self, label, target): """Test expectation_value method of two qubits in |++>""" qc = QuantumCircuit(2) qc.h(0) qc.h(1) stab = StabilizerState(qc) op = Pauli(label) expval = stab.expectation_value(op) self.assertEqual(expval, target) @data( ("II", 1), ("XX", 0), ("YY", 0), ("ZZ", 0), ("IX", 0), ("IY", 0), ("IZ", -1), ("XY", 0), ("XZ", -1), ("YZ", 0), ) @unpack def test_expval_two_qubits_plus1(self, label, target): """Test expectation_value method of two qubits in |+1>""" qc = QuantumCircuit(2) qc.x(0) qc.h(1) stab = StabilizerState(qc) op = Pauli(label) expval = stab.expectation_value(op) self.assertEqual(expval, target) @data( ("II", 1), ("XX", 1), ("YY", -1), ("ZZ", 1), ("IX", 0), ("IY", 0), ("IZ", 0), ("XY", 0), ("XZ", 0), ("YZ", 0), ("-YY", 1), ("iYY", -1j), ("-iYY", 1j), ) @unpack def test_expval_two_qubits_bell_phi_plus(self, label, target): """Test expectation_value method of two qubits in bell phi plus""" qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) stab = StabilizerState(qc) op = Pauli(label) expval = stab.expectation_value(op) self.assertEqual(expval, target) @data( ("II", 1), ("XX", 1), ("YY", 1), ("ZZ", -1), ("IX", 0), ("IY", 0), ("IZ", 0), ("XY", 0), ("XZ", 0), ("YZ", 0), ("-XX", -1), ("-YY", -1), ("iXX", 1j), ("iYY", 1j), ("-iXX", -1j), ("-iYY", -1j), ) @unpack def test_expval_two_qubits_bell_phi_minus(self, label, target): """Test expectation_value method of two qubits in bell phi minus""" qc = QuantumCircuit(2) qc.h(0) qc.x(1) qc.cx(0, 1) stab = StabilizerState(qc) op = Pauli(label) expval = stab.expectation_value(op) self.assertEqual(expval, target) @data( ("II", 1), ("XX", 1), ("YY", 1), ("ZZ", -1), ("IX", 0), ("IY", 0), ("IZ", 0), ("XY", 0), ("XZ", 0), ("YZ", 0), ("-XX", -1), ("-YY", -1), ("iXX", 1j), ("iYY", 1j), ("-iXX", -1j), ("-iYY", -1j), ) @unpack def test_expval_two_qubits_bell_sdg_h(self, label, target): """Test expectation_value method of two qubits in bell followed by sdg and h""" qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc.sdg(0) qc.sdg(1) qc.h(0) qc.h(1) stab = StabilizerState(qc) op = Pauli(label) expval = stab.expectation_value(op) self.assertEqual(expval, target) @combine(num_qubits=[2, 3, 4, 5]) def test_expval_random(self, num_qubits): """Test expectation_value method of random Cliffords""" for _ in range(self.samples): cliff = random_clifford(num_qubits, seed=self.rng) op = random_pauli(num_qubits, group_phase=True, seed=self.rng) qc = cliff.to_circuit() stab = StabilizerState(cliff) exp_val = stab.expectation_value(op) target = Statevector(qc).expectation_value(op) self.assertAlmostEqual(exp_val, target) @combine(num_qubits=[2, 3, 4, 5]) def test_expval_random_subsystem(self, num_qubits): """Test expectation_value method of random Cliffords and a subsystem""" for _ in range(self.samples): cliff = random_clifford(num_qubits, seed=self.rng) op = random_pauli(2, group_phase=True, seed=self.rng) qargs = np.random.choice(num_qubits, size=2, replace=False) qc = cliff.to_circuit() stab = StabilizerState(cliff) exp_val = stab.expectation_value(op, qargs) target = Statevector(qc).expectation_value(op, qargs) self.assertAlmostEqual(exp_val, target) def test_stabilizer_bell_equiv(self): """Test that two circuits produce the same stabilizer group.""" qc1 = QuantumCircuit(2) qc1.h(0) qc1.x(1) qc1.cx(0, 1) qc2 = QuantumCircuit(2) qc2.h(0) qc2.cx(0, 1) qc2.sdg(0) qc2.sdg(1) qc2.h(0) qc2.h(1) qc3 = QuantumCircuit(2) qc3.h(0) qc3.cx(0, 1) qc4 = QuantumCircuit(2) qc4.h(0) qc4.cx(0, 1) qc4.s(0) qc4.sdg(1) qc4.h(0) qc4.h(1) cliff1 = StabilizerState(qc1) # ['+XX', '-ZZ'] cliff2 = StabilizerState(qc2) # ['+YY', '+XX'] cliff3 = StabilizerState(qc3) # ['+XX', '+ZZ'] cliff4 = StabilizerState(qc4) # ['-YY', '+XX'] # [XX, -ZZ] and [XX, YY] both generate the stabilizer group {II, XX, YY, -ZZ} self.assertTrue(cliff1.equiv(cliff2)) self.assertEqual(cliff1.probabilities_dict(), cliff2.probabilities_dict()) # [XX, ZZ] and [XX, -YY] both generate the stabilizer group {II, XX, -YY, ZZ} self.assertTrue(cliff3.equiv(cliff4)) self.assertEqual(cliff3.probabilities_dict(), cliff4.probabilities_dict()) self.assertFalse(cliff1.equiv(cliff3)) self.assertFalse(cliff2.equiv(cliff4)) if __name__ == "__main__": unittest.main()
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# 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 Statevector quantum state class.""" import unittest import logging from itertools import permutations from ddt import ddt, data import numpy as np from numpy.testing import assert_allclose from qiskit.test import QiskitTestCase from qiskit import QiskitError from qiskit import QuantumRegister, QuantumCircuit from qiskit import transpile from qiskit.circuit.library import HGate, QFT, GlobalPhaseGate from qiskit.providers.basicaer import QasmSimulatorPy from qiskit.utils import optionals from qiskit.quantum_info.random import random_unitary, random_statevector, random_pauli from qiskit.quantum_info.states import Statevector from qiskit.quantum_info.operators.operator import Operator from qiskit.quantum_info.operators.symplectic import Pauli, SparsePauliOp from qiskit.quantum_info.operators.predicates import matrix_equal from qiskit.visualization.state_visualization import numbers_to_latex_terms, state_to_latex logger = logging.getLogger(__name__) @ddt class TestStatevector(QiskitTestCase): """Tests for Statevector class.""" @classmethod def rand_vec(cls, n, normalize=False): """Return complex vector or statevector""" seed = np.random.randint(0, np.iinfo(np.int32).max) logger.debug("rand_vec default_rng seeded with seed=%s", seed) rng = np.random.default_rng(seed) vec = rng.random(n) + 1j * rng.random(n) if normalize: vec /= np.sqrt(np.dot(vec, np.conj(vec))) return vec def test_init_array_qubit(self): """Test subsystem initialization from N-qubit array.""" # Test automatic inference of qubit subsystems vec = self.rand_vec(8) for dims in [None, 8]: state = Statevector(vec, dims=dims) assert_allclose(state.data, vec) self.assertEqual(state.dim, 8) self.assertEqual(state.dims(), (2, 2, 2)) self.assertEqual(state.num_qubits, 3) def test_init_array(self): """Test initialization from array.""" vec = self.rand_vec(3) state = Statevector(vec) assert_allclose(state.data, vec) self.assertEqual(state.dim, 3) self.assertEqual(state.dims(), (3,)) self.assertIsNone(state.num_qubits) vec = self.rand_vec(2 * 3 * 4) state = Statevector(vec, dims=[2, 3, 4]) assert_allclose(state.data, vec) self.assertEqual(state.dim, 2 * 3 * 4) self.assertEqual(state.dims(), (2, 3, 4)) self.assertIsNone(state.num_qubits) def test_init_circuit(self): """Test initialization from circuit.""" circuit = QuantumCircuit(3) circuit.x(0) state = Statevector(circuit) self.assertEqual(state.dim, 8) self.assertEqual(state.dims(), (2, 2, 2)) self.assertTrue(all(state.data == np.array([0, 1, 0, 0, 0, 0, 0, 0], dtype=complex))) self.assertEqual(state.num_qubits, 3) def test_init_array_except(self): """Test initialization exception from array.""" vec = self.rand_vec(4) self.assertRaises(QiskitError, Statevector, vec, dims=[4, 2]) self.assertRaises(QiskitError, Statevector, vec, dims=[2, 4]) self.assertRaises(QiskitError, Statevector, vec, dims=5) def test_init_statevector(self): """Test initialization from Statevector.""" vec1 = Statevector(self.rand_vec(4)) vec2 = Statevector(vec1) self.assertEqual(vec1, vec2) def test_from_circuit(self): """Test initialization from a circuit.""" # random unitaries u0 = random_unitary(2).data u1 = random_unitary(2).data # add to circuit qr = QuantumRegister(2) circ = QuantumCircuit(qr) circ.unitary(u0, [qr[0]]) circ.unitary(u1, [qr[1]]) target = Statevector(np.kron(u1, u0).dot([1, 0, 0, 0])) vec = Statevector.from_instruction(circ) self.assertEqual(vec, target) # Test tensor product of 1-qubit gates circuit = QuantumCircuit(3) circuit.h(0) circuit.x(1) circuit.ry(np.pi / 2, 2) target = Statevector.from_label("000").evolve(Operator(circuit)) psi = Statevector.from_instruction(circuit) self.assertEqual(psi, target) # Test decomposition of Controlled-Phase gate lam = np.pi / 4 circuit = QuantumCircuit(2) circuit.h(0) circuit.h(1) circuit.cp(lam, 0, 1) target = Statevector.from_label("00").evolve(Operator(circuit)) psi = Statevector.from_instruction(circuit) self.assertEqual(psi, target) # Test decomposition of controlled-H gate circuit = QuantumCircuit(2) circ.x(0) circuit.ch(0, 1) target = Statevector.from_label("00").evolve(Operator(circuit)) psi = Statevector.from_instruction(circuit) self.assertEqual(psi, target) # Test custom controlled gate qc = QuantumCircuit(2) qc.x(0) qc.h(1) gate = qc.to_gate() gate_ctrl = gate.control() circuit = QuantumCircuit(3) circuit.x(0) circuit.append(gate_ctrl, range(3)) target = Statevector.from_label("000").evolve(Operator(circuit)) psi = Statevector.from_instruction(circuit) self.assertEqual(psi, target) # Test initialize instruction target = Statevector([1, 0, 0, 1j]) / np.sqrt(2) circuit = QuantumCircuit(2) circuit.initialize(target.data, [0, 1]) psi = Statevector.from_instruction(circuit) self.assertEqual(psi, target) target = Statevector([1, 0, 1, 0]) / np.sqrt(2) circuit = QuantumCircuit(2) circuit.initialize("+", [1]) psi = Statevector.from_instruction(circuit) self.assertEqual(psi, target) target = Statevector([1, 0, 0, 0]) circuit = QuantumCircuit(2) circuit.initialize(0, [0, 1]) # initialize from int psi = Statevector.from_instruction(circuit) self.assertEqual(psi, target) # Test reset instruction target = Statevector([1, 0]) circuit = QuantumCircuit(1) circuit.h(0) circuit.reset(0) psi = Statevector.from_instruction(circuit) self.assertEqual(psi, target) # Test 0q instruction target = Statevector([1j, 0]) circuit = QuantumCircuit(1) circuit.append(GlobalPhaseGate(np.pi / 2), [], []) psi = Statevector.from_instruction(circuit) self.assertEqual(psi, target) def test_from_instruction(self): """Test initialization from an instruction.""" target = np.dot(HGate().to_matrix(), [1, 0]) vec = Statevector.from_instruction(HGate()).data global_phase_equivalent = matrix_equal(vec, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) def test_from_label(self): """Test initialization from a label""" x_p = Statevector(np.array([1, 1]) / np.sqrt(2)) x_m = Statevector(np.array([1, -1]) / np.sqrt(2)) y_p = Statevector(np.array([1, 1j]) / np.sqrt(2)) y_m = Statevector(np.array([1, -1j]) / np.sqrt(2)) z_p = Statevector(np.array([1, 0])) z_m = Statevector(np.array([0, 1])) label = "01" target = z_p.tensor(z_m) self.assertEqual(target, Statevector.from_label(label)) label = "+-" target = x_p.tensor(x_m) self.assertEqual(target, Statevector.from_label(label)) label = "rl" target = y_p.tensor(y_m) self.assertEqual(target, Statevector.from_label(label)) def test_equal(self): """Test __eq__ method""" for _ in range(10): vec = self.rand_vec(4) self.assertEqual(Statevector(vec), Statevector(vec.tolist())) def test_getitem(self): """Test __getitem__ method""" for _ in range(10): vec = self.rand_vec(4) state = Statevector(vec) for i in range(4): self.assertEqual(state[i], vec[i]) self.assertEqual(state[format(i, "b")], vec[i]) def test_getitem_except(self): """Test __getitem__ method raises exceptions.""" for i in range(1, 4): state = Statevector(self.rand_vec(2**i)) self.assertRaises(QiskitError, state.__getitem__, 2**i) self.assertRaises(QiskitError, state.__getitem__, -1) def test_copy(self): """Test Statevector copy method""" for _ in range(5): vec = self.rand_vec(4) orig = Statevector(vec) cpy = orig.copy() cpy._data[0] += 1.0 self.assertFalse(cpy == orig) def test_is_valid(self): """Test is_valid method.""" state = Statevector([1, 1]) self.assertFalse(state.is_valid()) for _ in range(10): state = Statevector(self.rand_vec(4, normalize=True)) self.assertTrue(state.is_valid()) def test_to_operator(self): """Test to_operator method for returning projector.""" for _ in range(10): vec = self.rand_vec(4) target = Operator(np.outer(vec, np.conj(vec))) op = Statevector(vec).to_operator() self.assertEqual(op, target) def test_evolve(self): """Test _evolve method.""" for _ in range(10): op = random_unitary(4) vec = self.rand_vec(4) target = Statevector(np.dot(op.data, vec)) evolved = Statevector(vec).evolve(op) self.assertEqual(target, evolved) def test_evolve_subsystem(self): """Test subsystem _evolve method.""" # Test evolving single-qubit of 3-qubit system for _ in range(5): vec = self.rand_vec(8) state = Statevector(vec) op0 = random_unitary(2) op1 = random_unitary(2) op2 = random_unitary(2) # Test evolve on 1-qubit op = op0 op_full = Operator(np.eye(4)).tensor(op) target = Statevector(np.dot(op_full.data, vec)) self.assertEqual(state.evolve(op, qargs=[0]), target) # Evolve on qubit 1 op_full = Operator(np.eye(2)).tensor(op).tensor(np.eye(2)) target = Statevector(np.dot(op_full.data, vec)) self.assertEqual(state.evolve(op, qargs=[1]), target) # Evolve on qubit 2 op_full = op.tensor(np.eye(4)) target = Statevector(np.dot(op_full.data, vec)) self.assertEqual(state.evolve(op, qargs=[2]), target) # Test evolve on 2-qubits op = op1.tensor(op0) # Evolve on qubits [0, 2] op_full = op1.tensor(np.eye(2)).tensor(op0) target = Statevector(np.dot(op_full.data, vec)) self.assertEqual(state.evolve(op, qargs=[0, 2]), target) # Evolve on qubits [2, 0] op_full = op0.tensor(np.eye(2)).tensor(op1) target = Statevector(np.dot(op_full.data, vec)) self.assertEqual(state.evolve(op, qargs=[2, 0]), target) # Test evolve on 3-qubits op = op2.tensor(op1).tensor(op0) # Evolve on qubits [0, 1, 2] op_full = op target = Statevector(np.dot(op_full.data, vec)) self.assertEqual(state.evolve(op, qargs=[0, 1, 2]), target) # Evolve on qubits [2, 1, 0] op_full = op0.tensor(op1).tensor(op2) target = Statevector(np.dot(op_full.data, vec)) self.assertEqual(state.evolve(op, qargs=[2, 1, 0]), target) def test_evolve_qudit_subsystems(self): """Test nested evolve calls on qudit subsystems.""" dims = (3, 4, 5) init = self.rand_vec(np.prod(dims)) ops = [random_unitary((dim,)) for dim in dims] state = Statevector(init, dims) for i, op in enumerate(ops): state = state.evolve(op, [i]) target_op = np.eye(1) for op in ops: target_op = np.kron(op.data, target_op) target = Statevector(np.dot(target_op, init), dims) self.assertEqual(state, target) def test_evolve_global_phase(self): """Test evolve circuit with global phase.""" state_i = Statevector([1, 0]) qr = QuantumRegister(2) phase = np.pi / 4 circ = QuantumCircuit(qr, global_phase=phase) circ.x(0) state_f = state_i.evolve(circ, qargs=[0]) target = Statevector([0, 1]) * np.exp(1j * phase) self.assertEqual(state_f, target) def test_conjugate(self): """Test conjugate method.""" for _ in range(10): vec = self.rand_vec(4) target = Statevector(np.conj(vec)) state = Statevector(vec).conjugate() self.assertEqual(state, target) def test_expand(self): """Test expand method.""" for _ in range(10): vec0 = self.rand_vec(2) vec1 = self.rand_vec(3) target = np.kron(vec1, vec0) state = Statevector(vec0).expand(Statevector(vec1)) self.assertEqual(state.dim, 6) self.assertEqual(state.dims(), (2, 3)) assert_allclose(state.data, target) def test_tensor(self): """Test tensor method.""" for _ in range(10): vec0 = self.rand_vec(2) vec1 = self.rand_vec(3) target = np.kron(vec0, vec1) state = Statevector(vec0).tensor(Statevector(vec1)) self.assertEqual(state.dim, 6) self.assertEqual(state.dims(), (3, 2)) assert_allclose(state.data, target) def test_inner(self): """Test inner method.""" for _ in range(10): vec0 = Statevector(self.rand_vec(4)) vec1 = Statevector(self.rand_vec(4)) target = np.vdot(vec0.data, vec1.data) result = vec0.inner(vec1) self.assertAlmostEqual(result, target) vec0 = Statevector(self.rand_vec(6), dims=(2, 3)) vec1 = Statevector(self.rand_vec(6), dims=(2, 3)) target = np.vdot(vec0.data, vec1.data) result = vec0.inner(vec1) self.assertAlmostEqual(result, target) def test_inner_except(self): """Test inner method raises exceptions.""" vec0 = Statevector(self.rand_vec(4)) vec1 = Statevector(self.rand_vec(3)) self.assertRaises(QiskitError, vec0.inner, vec1) vec0 = Statevector(self.rand_vec(6), dims=(2, 3)) vec1 = Statevector(self.rand_vec(6), dims=(3, 2)) self.assertRaises(QiskitError, vec0.inner, vec1) def test_add(self): """Test add method.""" for _ in range(10): vec0 = self.rand_vec(4) vec1 = self.rand_vec(4) state0 = Statevector(vec0) state1 = Statevector(vec1) self.assertEqual(state0 + state1, Statevector(vec0 + vec1)) def test_add_except(self): """Test add method raises exceptions.""" state1 = Statevector(self.rand_vec(2)) state2 = Statevector(self.rand_vec(3)) self.assertRaises(QiskitError, state1.__add__, state2) def test_subtract(self): """Test subtract method.""" for _ in range(10): vec0 = self.rand_vec(4) vec1 = self.rand_vec(4) state0 = Statevector(vec0) state1 = Statevector(vec1) self.assertEqual(state0 - state1, Statevector(vec0 - vec1)) def test_multiply(self): """Test multiply method.""" for _ in range(10): vec = self.rand_vec(4) state = Statevector(vec) val = np.random.rand() + 1j * np.random.rand() self.assertEqual(val * state, Statevector(val * state)) def test_negate(self): """Test negate method""" for _ in range(10): vec = self.rand_vec(4) state = Statevector(vec) self.assertEqual(-state, Statevector(-1 * vec)) def test_equiv(self): """Test equiv method""" vec = np.array([1, 0, 0, -1j]) / np.sqrt(2) phase = np.exp(-1j * np.pi / 4) statevec = Statevector(vec) self.assertTrue(statevec.equiv(phase * vec)) self.assertTrue(statevec.equiv(Statevector(phase * vec))) self.assertFalse(statevec.equiv(2 * vec)) def test_equiv_on_circuit(self): """Test the equiv method on different types of input.""" statevec = Statevector([1, 0]) qc = QuantumCircuit(1) self.assertTrue(statevec.equiv(qc)) qc.x(0) self.assertFalse(statevec.equiv(qc)) def test_to_dict(self): """Test to_dict method""" with self.subTest(msg="dims = (2, 3)"): vec = Statevector(np.arange(1, 7), dims=(2, 3)) target = {"00": 1, "01": 2, "10": 3, "11": 4, "20": 5, "21": 6} self.assertDictAlmostEqual(target, vec.to_dict()) with self.subTest(msg="dims = (11, )"): vec = Statevector(np.arange(1, 12), dims=(11,)) target = {str(i): i + 1 for i in range(11)} self.assertDictAlmostEqual(target, vec.to_dict()) with self.subTest(msg="dims = (2, 11)"): vec = Statevector(np.arange(1, 23), dims=(2, 11)) target = {} for i in range(11): for j in range(2): key = f"{i},{j}" target[key] = 2 * i + j + 1 self.assertDictAlmostEqual(target, vec.to_dict()) def test_probabilities_product(self): """Test probabilities method for product state""" state = Statevector.from_label("+0") # 2-qubit qargs with self.subTest(msg="P(None)"): probs = state.probabilities() target = np.array([0.5, 0, 0.5, 0]) self.assertTrue(np.allclose(probs, target)) with self.subTest(msg="P([0, 1])"): probs = state.probabilities([0, 1]) target = np.array([0.5, 0, 0.5, 0]) self.assertTrue(np.allclose(probs, target)) with self.subTest(msg="P([1, 0]"): probs = state.probabilities([1, 0]) target = np.array([0.5, 0.5, 0, 0]) self.assertTrue(np.allclose(probs, target)) # 1-qubit qargs with self.subTest(msg="P([0])"): probs = state.probabilities([0]) target = np.array([1, 0]) self.assertTrue(np.allclose(probs, target)) with self.subTest(msg="P([1])"): probs = state.probabilities([1]) target = np.array([0.5, 0.5]) self.assertTrue(np.allclose(probs, target)) def test_probabilities_ghz(self): """Test probabilities method for GHZ state""" state = (Statevector.from_label("000") + Statevector.from_label("111")) / np.sqrt(2) # 3-qubit qargs target = np.array([0.5, 0, 0, 0, 0, 0, 0, 0.5]) for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities(qargs) self.assertTrue(np.allclose(probs, target)) # 2-qubit qargs target = np.array([0.5, 0, 0, 0.5]) for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities(qargs) self.assertTrue(np.allclose(probs, target)) # 1-qubit qargs target = np.array([0.5, 0.5]) for qargs in [[0], [1], [2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities(qargs) self.assertTrue(np.allclose(probs, target)) def test_probabilities_w(self): """Test probabilities method with W state""" state = ( Statevector.from_label("001") + Statevector.from_label("010") + Statevector.from_label("100") ) / np.sqrt(3) # 3-qubit qargs target = np.array([0, 1 / 3, 1 / 3, 0, 1 / 3, 0, 0, 0]) for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities(qargs) self.assertTrue(np.allclose(probs, target)) # 2-qubit qargs target = np.array([1 / 3, 1 / 3, 1 / 3, 0]) for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities(qargs) self.assertTrue(np.allclose(probs, target)) # 1-qubit qargs target = np.array([2 / 3, 1 / 3]) for qargs in [[0], [1], [2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities(qargs) self.assertTrue(np.allclose(probs, target)) def test_probabilities_dict_product(self): """Test probabilities_dict method for product state""" state = Statevector.from_label("+0") # 2-qubit qargs with self.subTest(msg="P(None)"): probs = state.probabilities_dict() target = {"00": 0.5, "10": 0.5} self.assertDictAlmostEqual(probs, target) with self.subTest(msg="P([0, 1])"): probs = state.probabilities_dict([0, 1]) target = {"00": 0.5, "10": 0.5} self.assertDictAlmostEqual(probs, target) with self.subTest(msg="P([1, 0]"): probs = state.probabilities_dict([1, 0]) target = {"00": 0.5, "01": 0.5} self.assertDictAlmostEqual(probs, target) # 1-qubit qargs with self.subTest(msg="P([0])"): probs = state.probabilities_dict([0]) target = {"0": 1} self.assertDictAlmostEqual(probs, target) with self.subTest(msg="P([1])"): probs = state.probabilities_dict([1]) target = {"0": 0.5, "1": 0.5} self.assertDictAlmostEqual(probs, target) def test_probabilities_dict_ghz(self): """Test probabilities_dict method for GHZ state""" state = (Statevector.from_label("000") + Statevector.from_label("111")) / np.sqrt(2) # 3-qubit qargs target = {"000": 0.5, "111": 0.5} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities_dict(qargs) self.assertDictAlmostEqual(probs, target) # 2-qubit qargs target = {"00": 0.5, "11": 0.5} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities_dict(qargs) self.assertDictAlmostEqual(probs, target) # 1-qubit qargs target = {"0": 0.5, "1": 0.5} for qargs in [[0], [1], [2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities_dict(qargs) self.assertDictAlmostEqual(probs, target) def test_probabilities_dict_w(self): """Test probabilities_dict method with W state""" state = ( Statevector.from_label("001") + Statevector.from_label("010") + Statevector.from_label("100") ) / np.sqrt(3) # 3-qubit qargs target = np.array([0, 1 / 3, 1 / 3, 0, 1 / 3, 0, 0, 0]) target = {"001": 1 / 3, "010": 1 / 3, "100": 1 / 3} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities_dict(qargs) self.assertDictAlmostEqual(probs, target) # 2-qubit qargs target = {"00": 1 / 3, "01": 1 / 3, "10": 1 / 3} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities_dict(qargs) self.assertDictAlmostEqual(probs, target) # 1-qubit qargs target = {"0": 2 / 3, "1": 1 / 3} for qargs in [[0], [1], [2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities_dict(qargs) self.assertDictAlmostEqual(probs, target) def test_sample_counts_ghz(self): """Test sample_counts method for GHZ state""" shots = 2000 threshold = 0.02 * shots state = (Statevector.from_label("000") + Statevector.from_label("111")) / np.sqrt(2) state.seed(100) # 3-qubit qargs target = {"000": shots / 2, "111": shots / 2} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"counts (qargs={qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) # 2-qubit qargs target = {"00": shots / 2, "11": shots / 2} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: with self.subTest(msg=f"counts (qargs={qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) # 1-qubit qargs target = {"0": shots / 2, "1": shots / 2} for qargs in [[0], [1], [2]]: with self.subTest(msg=f"counts (qargs={qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) def test_sample_counts_w(self): """Test sample_counts method for W state""" shots = 3000 threshold = 0.02 * shots state = ( Statevector.from_label("001") + Statevector.from_label("010") + Statevector.from_label("100") ) / np.sqrt(3) state.seed(100) target = {"001": shots / 3, "010": shots / 3, "100": shots / 3} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"P({qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) # 2-qubit qargs target = {"00": shots / 3, "01": shots / 3, "10": shots / 3} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: with self.subTest(msg=f"P({qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) # 1-qubit qargs target = {"0": 2 * shots / 3, "1": shots / 3} for qargs in [[0], [1], [2]]: with self.subTest(msg=f"P({qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) def test_probabilities_dict_unequal_dims(self): """Test probabilities_dict for a state with unequal subsystem dimensions.""" vec = np.zeros(60, dtype=float) vec[15:20] = np.ones(5) vec[40:46] = np.ones(6) state = Statevector(vec / np.sqrt(11.0), dims=[3, 4, 5]) p = 1.0 / 11.0 self.assertDictEqual( state.probabilities_dict(), { s: p for s in [ "110", "111", "112", "120", "121", "311", "312", "320", "321", "322", "330", ] }, ) # differences due to rounding self.assertDictAlmostEqual( state.probabilities_dict(qargs=[0]), {"0": 4 * p, "1": 4 * p, "2": 3 * p}, delta=1e-10 ) self.assertDictAlmostEqual( state.probabilities_dict(qargs=[1]), {"1": 5 * p, "2": 5 * p, "3": p}, delta=1e-10 ) self.assertDictAlmostEqual( state.probabilities_dict(qargs=[2]), {"1": 5 * p, "3": 6 * p}, delta=1e-10 ) self.assertDictAlmostEqual( state.probabilities_dict(qargs=[0, 1]), {"10": p, "11": 2 * p, "12": 2 * p, "20": 2 * p, "21": 2 * p, "22": p, "30": p}, delta=1e-10, ) self.assertDictAlmostEqual( state.probabilities_dict(qargs=[1, 0]), {"01": p, "11": 2 * p, "21": 2 * p, "02": 2 * p, "12": 2 * p, "22": p, "03": p}, delta=1e-10, ) self.assertDictAlmostEqual( state.probabilities_dict(qargs=[0, 2]), {"10": 2 * p, "11": 2 * p, "12": p, "31": 2 * p, "32": 2 * p, "30": 2 * p}, delta=1e-10, ) def test_sample_counts_qutrit(self): """Test sample_counts method for qutrit state""" p = 0.3 shots = 1000 threshold = 0.03 * shots state = Statevector([np.sqrt(p), 0, np.sqrt(1 - p)]) state.seed(100) with self.subTest(msg="counts"): target = {"0": shots * p, "2": shots * (1 - p)} counts = state.sample_counts(shots=shots) self.assertDictAlmostEqual(counts, target, threshold) def test_sample_memory_ghz(self): """Test sample_memory method for GHZ state""" shots = 2000 state = (Statevector.from_label("000") + Statevector.from_label("111")) / np.sqrt(2) state.seed(100) # 3-qubit qargs target = {"000": shots / 2, "111": shots / 2} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) self.assertEqual(set(memory), set(target)) # 2-qubit qargs target = {"00": shots / 2, "11": shots / 2} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) self.assertEqual(set(memory), set(target)) # 1-qubit qargs target = {"0": shots / 2, "1": shots / 2} for qargs in [[0], [1], [2]]: with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) self.assertEqual(set(memory), set(target)) def test_sample_memory_w(self): """Test sample_memory method for W state""" shots = 3000 state = ( Statevector.from_label("001") + Statevector.from_label("010") + Statevector.from_label("100") ) / np.sqrt(3) state.seed(100) target = {"001": shots / 3, "010": shots / 3, "100": shots / 3} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) self.assertEqual(set(memory), set(target)) # 2-qubit qargs target = {"00": shots / 3, "01": shots / 3, "10": shots / 3} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) self.assertEqual(set(memory), set(target)) # 1-qubit qargs target = {"0": 2 * shots / 3, "1": shots / 3} for qargs in [[0], [1], [2]]: with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) self.assertEqual(set(memory), set(target)) def test_sample_memory_qutrit(self): """Test sample_memory method for qutrit state""" p = 0.3 shots = 1000 state = Statevector([np.sqrt(p), 0, np.sqrt(1 - p)]) state.seed(100) with self.subTest(msg="memory"): memory = state.sample_memory(shots) self.assertEqual(len(memory), shots) self.assertEqual(set(memory), {"0", "2"}) def test_reset_2qubit(self): """Test reset method for 2-qubit state""" state = Statevector(np.array([1, 0, 0, 1]) / np.sqrt(2)) state.seed(100) with self.subTest(msg="reset"): psi = state.copy() value = psi.reset() target = Statevector(np.array([1, 0, 0, 0])) self.assertEqual(value, target) with self.subTest(msg="reset"): psi = state.copy() value = psi.reset([0, 1]) target = Statevector(np.array([1, 0, 0, 0])) self.assertEqual(value, target) with self.subTest(msg="reset [0]"): psi = state.copy() value = psi.reset([0]) targets = [Statevector(np.array([1, 0, 0, 0])), Statevector(np.array([0, 0, 1, 0]))] self.assertIn(value, targets) with self.subTest(msg="reset [0]"): psi = state.copy() value = psi.reset([1]) targets = [Statevector(np.array([1, 0, 0, 0])), Statevector(np.array([0, 1, 0, 0]))] self.assertIn(value, targets) def test_reset_qutrit(self): """Test reset method for qutrit""" state = Statevector(np.array([1, 1, 1]) / np.sqrt(3)) state.seed(200) value = state.reset() target = Statevector(np.array([1, 0, 0])) self.assertEqual(value, target) def test_measure_2qubit(self): """Test measure method for 2-qubit state""" state = Statevector.from_label("+0") seed = 200 shots = 100 with self.subTest(msg="measure"): for i in range(shots): psi = state.copy() psi.seed(seed + i) outcome, value = psi.measure() self.assertIn(outcome, ["00", "10"]) if outcome == "00": target = Statevector.from_label("00") self.assertEqual(value, target) else: target = Statevector.from_label("10") self.assertEqual(value, target) with self.subTest(msg="measure [0, 1]"): for i in range(shots): psi = state.copy() outcome, value = psi.measure([0, 1]) self.assertIn(outcome, ["00", "10"]) if outcome == "00": target = Statevector.from_label("00") self.assertEqual(value, target) else: target = Statevector.from_label("10") self.assertEqual(value, target) with self.subTest(msg="measure [1, 0]"): for i in range(shots): psi = state.copy() outcome, value = psi.measure([1, 0]) self.assertIn(outcome, ["00", "01"]) if outcome == "00": target = Statevector.from_label("00") self.assertEqual(value, target) else: target = Statevector.from_label("10") self.assertEqual(value, target) with self.subTest(msg="measure [0]"): for i in range(shots): psi = state.copy() outcome, value = psi.measure([0]) self.assertEqual(outcome, "0") target = Statevector(np.array([1, 0, 1, 0]) / np.sqrt(2)) self.assertEqual(value, target) with self.subTest(msg="measure [1]"): for i in range(shots): psi = state.copy() outcome, value = psi.measure([1]) self.assertIn(outcome, ["0", "1"]) if outcome == "0": target = Statevector.from_label("00") self.assertEqual(value, target) else: target = Statevector.from_label("10") self.assertEqual(value, target) def test_measure_qutrit(self): """Test measure method for qutrit""" state = Statevector(np.array([1, 1, 1]) / np.sqrt(3)) seed = 200 shots = 100 for i in range(shots): psi = state.copy() psi.seed(seed + i) outcome, value = psi.measure() self.assertIn(outcome, ["0", "1", "2"]) if outcome == "0": target = Statevector([1, 0, 0]) self.assertEqual(value, target) elif outcome == "1": target = Statevector([0, 1, 0]) self.assertEqual(value, target) else: target = Statevector([0, 0, 1]) self.assertEqual(value, target) def test_from_int(self): """Test from_int method""" with self.subTest(msg="from_int(0, 4)"): target = Statevector([1, 0, 0, 0]) value = Statevector.from_int(0, 4) self.assertEqual(target, value) with self.subTest(msg="from_int(3, 4)"): target = Statevector([0, 0, 0, 1]) value = Statevector.from_int(3, 4) self.assertEqual(target, value) with self.subTest(msg="from_int(8, (3, 3))"): target = Statevector([0, 0, 0, 0, 0, 0, 0, 0, 1], dims=(3, 3)) value = Statevector.from_int(8, (3, 3)) self.assertEqual(target, value) def test_expval(self): """Test expectation_value method""" psi = Statevector([1, 0, 0, 1]) / np.sqrt(2) for label, target in [ ("II", 1), ("XX", 1), ("YY", -1), ("ZZ", 1), ("IX", 0), ("YZ", 0), ("ZX", 0), ("YI", 0), ]: with self.subTest(msg=f"<{label}>"): op = Pauli(label) expval = psi.expectation_value(op) self.assertAlmostEqual(expval, target) psi = Statevector([np.sqrt(2), 0, 0, 0, 0, 0, 0, 1 + 1j]) / 2 for label, target in [ ("XXX", np.sqrt(2) / 2), ("YYY", -np.sqrt(2) / 2), ("ZZZ", 0), ("XYZ", 0), ("YIY", 0), ]: with self.subTest(msg=f"<{label}>"): op = Pauli(label) expval = psi.expectation_value(op) self.assertAlmostEqual(expval, target) labels = ["XXX", "IXI", "YYY", "III"] coeffs = [3.0, 5.5, -1j, 23] spp_op = SparsePauliOp.from_list(list(zip(labels, coeffs))) expval = psi.expectation_value(spp_op) target = 25.121320343559642 + 0.7071067811865476j self.assertAlmostEqual(expval, target) @data( "II", "IX", "IY", "IZ", "XI", "XX", "XY", "XZ", "YI", "YX", "YY", "YZ", "ZI", "ZX", "ZY", "ZZ", "-II", "-IX", "-IY", "-IZ", "-XI", "-XX", "-XY", "-XZ", "-YI", "-YX", "-YY", "-YZ", "-ZI", "-ZX", "-ZY", "-ZZ", "iII", "iIX", "iIY", "iIZ", "iXI", "iXX", "iXY", "iXZ", "iYI", "iYX", "iYY", "iYZ", "iZI", "iZX", "iZY", "iZZ", "-iII", "-iIX", "-iIY", "-iIZ", "-iXI", "-iXX", "-iXY", "-iXZ", "-iYI", "-iYX", "-iYY", "-iYZ", "-iZI", "-iZX", "-iZY", "-iZZ", ) def test_expval_pauli(self, pauli): """Test expectation_value method for Pauli op""" seed = 1020 op = Pauli(pauli) state = random_statevector(2**op.num_qubits, seed=seed) target = state.expectation_value(op.to_matrix()) expval = state.expectation_value(op) self.assertAlmostEqual(expval, target) @data([0, 1], [0, 2], [1, 0], [1, 2], [2, 0], [2, 1]) def test_expval_pauli_qargs(self, qubits): """Test expectation_value method for Pauli op""" seed = 1020 op = random_pauli(2, seed=seed) state = random_statevector(2**3, seed=seed) target = state.expectation_value(op.to_matrix(), qubits) expval = state.expectation_value(op, qubits) self.assertAlmostEqual(expval, target) @data(*(qargs for i in range(4) for qargs in permutations(range(4), r=i + 1))) def test_probabilities_qargs(self, qargs): """Test probabilities method with qargs""" # Get initial state nq = 4 nc = len(qargs) state_circ = QuantumCircuit(nq, nc) for i in range(nq): state_circ.ry((i + 1) * np.pi / (nq + 1), i) # Get probabilities state = Statevector(state_circ) probs = state.probabilities(qargs) # Estimate target probs from simulator measurement sim = QasmSimulatorPy() shots = 5000 seed = 100 circ = transpile(state_circ, sim) circ.measure(qargs, range(nc)) result = sim.run(circ, shots=shots, seed_simulator=seed).result() target = np.zeros(2**nc, dtype=float) for i, p in result.get_counts(0).int_outcomes().items(): target[i] = p / shots # Compare delta = np.linalg.norm(probs - target) self.assertLess(delta, 0.05) def test_global_phase(self): """Test global phase is handled correctly when evolving statevector.""" qc = QuantumCircuit(1) qc.rz(0.5, 0) qc2 = transpile(qc, basis_gates=["p"]) sv = Statevector.from_instruction(qc2) expected = np.array([0.96891242 - 0.24740396j, 0]) self.assertEqual(float(qc2.global_phase), 2 * np.pi - 0.25) self.assertEqual(sv, Statevector(expected)) def test_reverse_qargs(self): """Test reverse_qargs method""" circ1 = QFT(5) circ2 = circ1.reverse_bits() state1 = Statevector.from_instruction(circ1) state2 = Statevector.from_instruction(circ2) self.assertEqual(state1.reverse_qargs(), state2) @unittest.skipUnless(optionals.HAS_MATPLOTLIB, "requires matplotlib") @unittest.skipUnless(optionals.HAS_PYLATEX, "requires pylatexenc") def test_drawings(self): """Test draw method""" qc1 = QFT(5) sv = Statevector.from_instruction(qc1) with self.subTest(msg="str(statevector)"): str(sv) for drawtype in ["repr", "text", "latex", "latex_source", "qsphere", "hinton", "bloch"]: with self.subTest(msg=f"draw('{drawtype}')"): sv.draw(drawtype) with self.subTest(msg=" draw('latex', convention='vector')"): sv.draw("latex", convention="vector") def test_state_to_latex_for_none(self): """ Test for `\rangleNone` output in latex representation See https://github.com/Qiskit/qiskit-terra/issues/8169 """ sv = Statevector( [ 7.07106781e-01 - 8.65956056e-17j, -5.55111512e-17 - 8.65956056e-17j, 7.85046229e-17 + 8.65956056e-17j, -7.07106781e-01 + 8.65956056e-17j, 0.00000000e00 + 0.00000000e00j, -0.00000000e00 + 0.00000000e00j, -0.00000000e00 + 0.00000000e00j, 0.00000000e00 - 0.00000000e00j, ], dims=(2, 2, 2), ) latex_representation = state_to_latex(sv) self.assertEqual( latex_representation, "\\frac{\\sqrt{2}}{2} |000\\rangle- \\frac{\\sqrt{2}}{2} |011\\rangle", ) def test_state_to_latex_for_large_statevector(self): """Test conversion of large dense state vector""" sv = Statevector(np.ones((2**15, 1))) latex_representation = state_to_latex(sv) self.assertEqual( latex_representation, " |000000000000000\\rangle+ |000000000000001\\rangle+ |000000000000010\\rangle+" " |000000000000011\\rangle+ |000000000000100\\rangle+ |000000000000101\\rangle +" " \\ldots + |111111111111011\\rangle+ |111111111111100\\rangle+" " |111111111111101\\rangle+ |111111111111110\\rangle+ |111111111111111\\rangle", ) def test_state_to_latex_with_prefix(self): """Test adding prefix to state vector latex output""" psi = Statevector(np.array([np.sqrt(1 / 2), 0, 0, np.sqrt(1 / 2)])) prefix = "|\\psi_{AB}\\rangle = " latex_sv = state_to_latex(psi) latex_expected = prefix + latex_sv latex_representation = state_to_latex(psi, prefix=prefix) self.assertEqual(latex_representation, latex_expected) def test_state_to_latex_for_large_sparse_statevector(self): """Test conversion of large sparse state vector""" sv = Statevector(np.eye(2**15, 1)) latex_representation = state_to_latex(sv) self.assertEqual(latex_representation, " |000000000000000\\rangle") def test_state_to_latex_with_max_size_limit(self): """Test limit the maximum number of non-zero terms in the expression""" sv = Statevector( [ 0.35355339 + 0.0j, 0.35355339 + 0.0j, 0.35355339 + 0.0j, 0.35355339 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 - 0.35355339j, 0.0 + 0.35355339j, 0.0 + 0.35355339j, 0.0 - 0.35355339j, ], dims=(2, 2, 2, 2), ) latex_representation = state_to_latex(sv, max_size=5) self.assertEqual( latex_representation, "\\frac{\\sqrt{2}}{4} |0000\\rangle+" "\\frac{\\sqrt{2}}{4} |0001\\rangle + " "\\ldots +" "\\frac{\\sqrt{2} i}{4} |1110\\rangle- " "\\frac{\\sqrt{2} i}{4} |1111\\rangle", ) def test_state_to_latex_with_decimals_round(self): """Test rounding of decimal places in the expression""" sv = Statevector( [ 0.35355339 + 0.0j, 0.35355339 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 - 0.35355339j, 0.0 + 0.35355339j, ], dims=(2, 2, 2), ) latex_representation = state_to_latex(sv, decimals=3) self.assertEqual( latex_representation, "0.354 |000\\rangle+0.354 |001\\rangle- 0.354 i |110\\rangle+0.354 i |111\\rangle", ) def test_number_to_latex_terms(self): """Test conversions of complex numbers to latex terms""" cases = [ ([1 - 8e-17, 0], ["", None]), ([0, -1], [None, "-"]), ([0, 1], [None, ""]), ([0, 1j], [None, "i"]), ([-1, 1], ["-", "+"]), ([0, 1j], [None, "i"]), ([-1, 1j], ["-", "+i"]), ([1e-16 + 1j], ["i"]), ([-1 + 1e-16 * 1j], ["-"]), ([-1, -1 - 1j], ["-", "+(-1 - i)"]), ([np.sqrt(2) / 2, np.sqrt(2) / 2], ["\\frac{\\sqrt{2}}{2}", "+\\frac{\\sqrt{2}}{2}"]), ([1 + np.sqrt(2)], ["(1 + \\sqrt{2})"]), ] with self.assertWarns(DeprecationWarning): for numbers, latex_terms in cases: terms = numbers_to_latex_terms(numbers, 15) self.assertListEqual(terms, latex_terms) def test_statevector_draw_latex_regression(self): """Test numerical rounding errors are not printed""" sv = Statevector(np.array([1 - 8e-17, 8.32667268e-17j])) latex_string = sv.draw(output="latex_source") self.assertTrue(latex_string.startswith(" |0\\rangle")) self.assertNotIn("|1\\rangle", latex_string) def test_statevctor_iter(self): """Test iteration over a state vector""" empty_vector = [] dummy_vector = [1, 2, 3] empty_sv = Statevector([]) sv = Statevector(dummy_vector) # Assert that successive iterations behave as expected, i.e., the # iterator is reset upon each exhaustion of the corresponding # collection of elements. for _ in range(2): self.assertEqual(empty_vector, list(empty_sv)) self.assertEqual(dummy_vector, list(sv)) def test_statevector_len(self): """Test state vector length""" empty_vector = [] dummy_vector = [1, 2, 3] empty_sv = Statevector([]) sv = Statevector(dummy_vector) self.assertEqual(len(empty_vector), len(empty_sv)) self.assertEqual(len(dummy_vector), len(sv)) def test_clip_probabilities(self): """Test probabilities are clipped to [0, 1].""" sv = Statevector([1.1, 0]) self.assertEqual(list(sv.probabilities()), [1.0, 0.0]) # The "1" key should be zero and therefore omitted. self.assertEqual(sv.probabilities_dict(), {"0": 1.0}) def test_round_probabilities(self): """Test probabilities are correctly rounded. This is good to test to ensure clipping, renormalizing and rounding work together. """ p = np.sqrt(1 / 3) sv = Statevector([p, p, p, 0]) expected = [0.33, 0.33, 0.33, 0] self.assertEqual(list(sv.probabilities(decimals=2)), expected) if __name__ == "__main__": unittest.main()
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# 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-class-docstring,missing-function-docstring """Test Counts class.""" import unittest import numpy as np from qiskit.result import counts from qiskit import exceptions from qiskit.result import utils class TestCounts(unittest.TestCase): def test_just_counts(self): raw_counts = {"0x0": 21, "0x2": 12} expected = {"0": 21, "10": 12} result = counts.Counts(raw_counts) self.assertEqual(expected, result) def test_counts_with_exta_formatting_data(self): raw_counts = {"0x0": 4, "0x2": 10} expected = {"0 0 00": 4, "0 0 10": 10} result = counts.Counts( raw_counts, "test_counts", creg_sizes=[["c0", 2], ["c0", 1], ["c1", 1]], memory_slots=4 ) self.assertEqual(result, expected) def test_marginal_counts(self): raw_counts = {"0x0": 4, "0x1": 7, "0x2": 10, "0x6": 5, "0x9": 11, "0xD": 9, "0xE": 8} expected = {"00": 4, "01": 27, "10": 23} counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4) result = utils.marginal_counts(counts_obj, [0, 1]) self.assertEqual(expected, result) def test_marginal_distribution(self): raw_counts = {"0x0": 4, "0x1": 7, "0x2": 10, "0x6": 5, "0x9": 11, "0xD": 9, "0xE": 8} expected = {"00": 4, "01": 27, "10": 23} counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4) result = utils.marginal_distribution(counts_obj, [0, 1]) self.assertEqual(expected, result) def test_marginal_distribution_numpy_indices(self): raw_counts = {"0x0": 4, "0x1": 7, "0x2": 10, "0x6": 5, "0x9": 11, "0xD": 9, "0xE": 8} expected = {"00": 4, "01": 27, "10": 23} indices = np.asarray([0, 1]) counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4) result = utils.marginal_distribution(counts_obj, indices) self.assertEqual(expected, result) def test_int_outcomes(self): raw_counts = {"0x0": 21, "0x2": 12, "0x3": 5, "0x2E": 265} expected = {0: 21, 2: 12, 3: 5, 46: 265} counts_obj = counts.Counts(raw_counts) result = counts_obj.int_outcomes() self.assertEqual(expected, result) def test_most_frequent(self): raw_counts = {"0x0": 21, "0x2": 12, "0x3": 5, "0x2E": 265} expected = "101110" counts_obj = counts.Counts(raw_counts) result = counts_obj.most_frequent() self.assertEqual(expected, result) def test_most_frequent_duplicate(self): raw_counts = {"0x0": 265, "0x2": 12, "0x3": 5, "0x2E": 265} counts_obj = counts.Counts(raw_counts) self.assertRaises(exceptions.QiskitError, counts_obj.most_frequent) def test_hex_outcomes(self): raw_counts = {"0x0": 21, "0x2": 12, "0x3": 5, "0x2E": 265} expected = {"0x0": 21, "0x2": 12, "0x3": 5, "0x2e": 265} counts_obj = counts.Counts(raw_counts) result = counts_obj.hex_outcomes() self.assertEqual(expected, result) def test_just_int_counts(self): raw_counts = {0: 21, 2: 12} expected = {"0": 21, "10": 12} result = counts.Counts(raw_counts) self.assertEqual(expected, result) def test_int_counts_with_exta_formatting_data(self): raw_counts = {0: 4, 2: 10} expected = {"0 0 00": 4, "0 0 10": 10} result = counts.Counts( raw_counts, "test_counts", creg_sizes=[["c0", 2], ["c0", 1], ["c1", 1]], memory_slots=4 ) self.assertEqual(result, expected) def test_marginal_int_counts(self): raw_counts = {0: 4, 1: 7, 2: 10, 6: 5, 9: 11, 13: 9, 14: 8} expected = {"00": 4, "01": 27, "10": 23} counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4) result = utils.marginal_counts(counts_obj, [0, 1]) self.assertEqual(expected, result) def test_marginal_distribution_int_counts(self): raw_counts = {0: 4, 1: 7, 2: 10, 6: 5, 9: 11, 13: 9, 14: 8} expected = {"00": 4, "01": 27, "10": 23} counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4) result = utils.marginal_distribution(counts_obj, [0, 1]) self.assertEqual(expected, result) def test_marginal_distribution_int_counts_numpy_64_bit(self): raw_counts = { 0: np.int64(4), 1: np.int64(7), 2: np.int64(10), 6: np.int64(5), 9: np.int64(11), 13: np.int64(9), 14: np.int64(8), } expected = {"00": 4, "01": 27, "10": 23} counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4) result = utils.marginal_distribution(counts_obj, [0, 1]) self.assertEqual(expected, result) def test_marginal_distribution_int_counts_numpy_8_bit(self): raw_counts = { 0: np.int8(4), 1: np.int8(7), 2: np.int8(10), 6: np.int8(5), 9: np.int8(11), 13: np.int8(9), 14: np.int8(8), } expected = {"00": 4, "01": 27, "10": 23} counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4) result = utils.marginal_distribution(counts_obj, [0, 1]) self.assertEqual(expected, result) def test_int_outcomes_with_int_counts(self): raw_counts = {0: 21, 2: 12, 3: 5, 46: 265} counts_obj = counts.Counts(raw_counts) result = counts_obj.int_outcomes() self.assertEqual(raw_counts, result) def test_most_frequent_int_counts(self): raw_counts = {0: 21, 2: 12, 3: 5, 46: 265} expected = "101110" counts_obj = counts.Counts(raw_counts) result = counts_obj.most_frequent() self.assertEqual(expected, result) def test_most_frequent_duplicate_int_counts(self): raw_counts = {0: 265, 2: 12, 3: 5, 46: 265} counts_obj = counts.Counts(raw_counts) self.assertRaises(exceptions.QiskitError, counts_obj.most_frequent) def test_hex_outcomes_int_counts(self): raw_counts = {0: 265, 2: 12, 3: 5, 46: 265} expected = {"0x0": 265, "0x2": 12, "0x3": 5, "0x2e": 265} counts_obj = counts.Counts(raw_counts) result = counts_obj.hex_outcomes() self.assertEqual(expected, result) def test_invalid_input_type(self): self.assertRaises(TypeError, counts.Counts, {2.4: 1024}) def test_just_bitstring_counts(self): raw_counts = {"0": 21, "10": 12} expected = {"0": 21, "10": 12} result = counts.Counts(raw_counts) self.assertEqual(expected, result) def test_bistring_counts_with_exta_formatting_data(self): raw_counts = {"0": 4, "10": 10} expected = {"0 0 00": 4, "0 0 10": 10} result = counts.Counts( raw_counts, "test_counts", creg_sizes=[["c0", 2], ["c0", 1], ["c1", 1]], memory_slots=4 ) self.assertEqual(result, expected) def test_marginal_bitstring_counts(self): raw_counts = {"0": 4, "1": 7, "10": 10, "110": 5, "1001": 11, "1101": 9, "1110": 8} expected = {"00": 4, "01": 27, "10": 23} counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4) result = utils.marginal_counts(counts_obj, [0, 1]) self.assertEqual(expected, result) def test_marginal_distribution_bitstring_counts(self): raw_counts = {"0": 4, "1": 7, "10": 10, "110": 5, "1001": 11, "1101": 9, "1110": 8} expected = {"00": 4, "01": 27, "10": 23} counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4) result = utils.marginal_distribution(counts_obj, [0, 1]) self.assertEqual(expected, result) def test_int_outcomes_with_bitstring_counts(self): raw_counts = {"0": 21, "10": 12, "11": 5, "101110": 265} expected = {0: 21, 2: 12, 3: 5, 46: 265} counts_obj = counts.Counts(raw_counts) result = counts_obj.int_outcomes() self.assertEqual(expected, result) def test_most_frequent_bitstring_counts(self): raw_counts = {"0": 21, "10": 12, "11": 5, "101110": 265} expected = "101110" counts_obj = counts.Counts(raw_counts) result = counts_obj.most_frequent() self.assertEqual(expected, result) def test_most_frequent_duplicate_bitstring_counts(self): raw_counts = {"0": 265, "10": 12, "11": 5, "101110": 265} counts_obj = counts.Counts(raw_counts) self.assertRaises(exceptions.QiskitError, counts_obj.most_frequent) def test_hex_outcomes_bitstring_counts(self): raw_counts = {"0": 265, "10": 12, "11": 5, "101110": 265} expected = {"0x0": 265, "0x2": 12, "0x3": 5, "0x2e": 265} counts_obj = counts.Counts(raw_counts) result = counts_obj.hex_outcomes() self.assertEqual(expected, result) def test_qudit_counts(self): raw_counts = { "00": 121, "01": 109, "02": 114, "10": 113, "11": 106, "12": 114, "20": 117, "21": 104, "22": 102, } result = counts.Counts(raw_counts) self.assertEqual(raw_counts, result) def test_qudit_counts_raises_with_format(self): raw_counts = { "00": 121, "01": 109, "02": 114, "10": 113, "11": 106, "12": 114, "20": 117, "21": 104, "22": 102, } self.assertRaises(exceptions.QiskitError, counts.Counts, raw_counts, creg_sizes=[["c0", 4]]) def test_qudit_counts_hex_outcome(self): raw_counts = { "00": 121, "01": 109, "02": 114, "10": 113, "11": 106, "12": 114, "20": 117, "21": 104, "22": 102, } counts_obj = counts.Counts(raw_counts) self.assertRaises(exceptions.QiskitError, counts_obj.hex_outcomes) def test_qudit_counts_int_outcome(self): raw_counts = { "00": 121, "01": 109, "02": 114, "10": 113, "11": 106, "12": 114, "20": 117, "21": 104, "22": 102, } counts_obj = counts.Counts(raw_counts) self.assertRaises(exceptions.QiskitError, counts_obj.int_outcomes) def test_qudit_counts_most_frequent(self): raw_counts = { "00": 121, "01": 109, "02": 114, "10": 113, "11": 106, "12": 114, "20": 117, "21": 104, "22": 102, } counts_obj = counts.Counts(raw_counts) self.assertEqual("00", counts_obj.most_frequent()) def test_just_0b_bitstring_counts(self): raw_counts = {"0b0": 21, "0b10": 12} expected = {"0": 21, "10": 12} result = counts.Counts(raw_counts) self.assertEqual(expected, result) def test_0b_bistring_counts_with_exta_formatting_data(self): raw_counts = {"0b0": 4, "0b10": 10} expected = {"0 0 00": 4, "0 0 10": 10} result = counts.Counts( raw_counts, "test_counts", creg_sizes=[["c0", 2], ["c0", 1], ["c1", 1]], memory_slots=4 ) self.assertEqual(result, expected) def test_marginal_0b_string_counts(self): raw_counts = { "0b0": 4, "0b1": 7, "0b10": 10, "0b110": 5, "0b1001": 11, "0b1101": 9, "0b1110": 8, } expected = {"00": 4, "01": 27, "10": 23} counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4) result = utils.marginal_counts(counts_obj, [0, 1]) self.assertEqual(expected, result) def test_marginal_distribution_0b_string_counts(self): raw_counts = { "0b0": 4, "0b1": 7, "0b10": 10, "0b110": 5, "0b1001": 11, "0b1101": 9, "0b1110": 8, } expected = {"00": 4, "01": 27, "10": 23} counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4) result = utils.marginal_distribution(counts_obj, [0, 1]) self.assertEqual(expected, result) def test_int_outcomes_with_0b_bitstring_counts(self): raw_counts = {"0b0": 21, "0b10": 12, "0b11": 5, "0b101110": 265} expected = {0: 21, 2: 12, 3: 5, 46: 265} counts_obj = counts.Counts(raw_counts) result = counts_obj.int_outcomes() self.assertEqual(expected, result) def test_most_frequent_0b_bitstring_counts(self): raw_counts = {"0b0": 21, "0b10": 12, "0b11": 5, "0b101110": 265} expected = "101110" counts_obj = counts.Counts(raw_counts) result = counts_obj.most_frequent() self.assertEqual(expected, result) def test_most_frequent_duplicate_0b_bitstring_counts(self): raw_counts = {"0b0": 265, "0b10": 12, "0b11": 5, "0b101110": 265} counts_obj = counts.Counts(raw_counts) self.assertRaises(exceptions.QiskitError, counts_obj.most_frequent) def test_hex_outcomes_0b_bitstring_counts(self): raw_counts = {"0b0": 265, "0b10": 12, "0b11": 5, "0b101110": 265} expected = {"0x0": 265, "0x2": 12, "0x3": 5, "0x2e": 265} counts_obj = counts.Counts(raw_counts) result = counts_obj.hex_outcomes() self.assertEqual(expected, result) def test_empty_bitstring_counts(self): raw_counts = {} expected = {} result = counts.Counts(raw_counts) self.assertEqual(expected, result) def test_empty_bistring_counts_with_exta_formatting_data(self): raw_counts = {} expected = {} result = counts.Counts( raw_counts, "test_counts", creg_sizes=[["c0", 2], ["c0", 1], ["c1", 1]], memory_slots=4 ) self.assertEqual(result, expected) def test_int_outcomes_with_empty_counts(self): raw_counts = {} expected = {} counts_obj = counts.Counts(raw_counts) result = counts_obj.int_outcomes() self.assertEqual(expected, result) def test_most_frequent_empty_bitstring_counts(self): raw_counts = {} counts_obj = counts.Counts(raw_counts) self.assertRaises(exceptions.QiskitError, counts_obj.most_frequent) def test_hex_outcomes_empty_bitstring_counts(self): raw_counts = {} expected = {} counts_obj = counts.Counts(raw_counts) result = counts_obj.hex_outcomes() self.assertEqual(expected, result)
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# 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. # pylint: disable=invalid-name """Tests for error mitigation routines.""" import unittest from collections import Counter import numpy as np from qiskit import QiskitError, QuantumCircuit from qiskit.quantum_info import Statevector from qiskit.quantum_info.operators.predicates import matrix_equal from qiskit.result import ( CorrelatedReadoutMitigator, Counts, LocalReadoutMitigator, ) from qiskit.result.mitigation.utils import ( counts_probability_vector, expval_with_stddev, stddev, str2diag, ) from qiskit.result.utils import marginal_counts from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider import FakeYorktown class TestReadoutMitigation(QiskitTestCase): """Tests for correlated and local readout mitigation.""" @classmethod def setUpClass(cls): super().setUpClass() cls.rng = np.random.default_rng(42) @staticmethod def compare_results(res1, res2): """Compare the results between two runs""" res1_total_shots = sum(res1.values()) res2_total_shots = sum(res2.values()) keys = set(res1.keys()).union(set(res2.keys())) total = 0 for key in keys: val1 = res1.get(key, 0) / res1_total_shots val2 = res2.get(key, 0) / res2_total_shots total += abs(val1 - val2) ** 2 return total @staticmethod def mitigators(assignment_matrices, qubits=None): """Generates the mitigators to test for given assignment matrices""" full_assignment_matrix = assignment_matrices[0] for m in assignment_matrices[1:]: full_assignment_matrix = np.kron(full_assignment_matrix, m) CRM = CorrelatedReadoutMitigator(full_assignment_matrix, qubits) LRM = LocalReadoutMitigator(assignment_matrices, qubits) mitigators = [CRM, LRM] return mitigators @staticmethod def simulate_circuit(circuit, assignment_matrix, num_qubits, shots=1024): """Simulates the given circuit under the given readout noise""" probs = Statevector.from_instruction(circuit).probabilities() noisy_probs = assignment_matrix @ probs labels = [bin(a)[2:].zfill(num_qubits) for a in range(2**num_qubits)] results = TestReadoutMitigation.rng.choice(labels, size=shots, p=noisy_probs) return Counts(dict(Counter(results))) @staticmethod def ghz_3_circuit(): """A 3-qubit circuit generating |000>+|111>""" c = QuantumCircuit(3) c.h(0) c.cx(0, 1) c.cx(1, 2) return (c, "ghz_3_ciruit", 3) @staticmethod def first_qubit_h_3_circuit(): """A 3-qubit circuit generating |000>+|001>""" c = QuantumCircuit(3) c.h(0) return (c, "first_qubit_h_3_circuit", 3) @staticmethod def assignment_matrices(): """A 3-qubit readout noise assignment matrices""" return LocalReadoutMitigator(backend=FakeYorktown())._assignment_mats[0:3] @staticmethod def counts_data(circuit, assignment_matrices, shots=1024): """Generates count data for the noisy and noiseless versions of the circuit simulation""" full_assignment_matrix = assignment_matrices[0] for m in assignment_matrices[1:]: full_assignment_matrix = np.kron(full_assignment_matrix, m) num_qubits = len(assignment_matrices) ideal_assignment_matrix = np.eye(2**num_qubits) counts_ideal = TestReadoutMitigation.simulate_circuit( circuit, ideal_assignment_matrix, num_qubits, shots ) counts_noise = TestReadoutMitigation.simulate_circuit( circuit, full_assignment_matrix, num_qubits, shots ) probs_noise = {key: value / shots for key, value in counts_noise.items()} return counts_ideal, counts_noise, probs_noise def test_mitigation_improvement(self): """Test whether readout mitigation led to more accurate results""" shots = 1024 assignment_matrices = self.assignment_matrices() num_qubits = len(assignment_matrices) mitigators = self.mitigators(assignment_matrices) circuit, circuit_name, num_qubits = self.ghz_3_circuit() counts_ideal, counts_noise, probs_noise = self.counts_data( circuit, assignment_matrices, shots ) unmitigated_error = self.compare_results(counts_ideal, counts_noise) unmitigated_stddev = stddev(probs_noise, shots) for mitigator in mitigators: mitigated_quasi_probs = mitigator.quasi_probabilities(counts_noise) mitigated_probs = ( mitigated_quasi_probs.nearest_probability_distribution().binary_probabilities( num_bits=num_qubits ) ) mitigated_error = self.compare_results(counts_ideal, mitigated_probs) self.assertLess( mitigated_error, unmitigated_error * 0.8, "Mitigator {} did not improve circuit {} measurements".format( mitigator, circuit_name ), ) mitigated_stddev_upper_bound = mitigated_quasi_probs._stddev_upper_bound max_unmitigated_stddev = max(unmitigated_stddev.values()) self.assertGreaterEqual( mitigated_stddev_upper_bound, max_unmitigated_stddev, "Mitigator {} on circuit {} gave stddev upper bound {} " "while unmitigated stddev maximum is {}".format( mitigator, circuit_name, mitigated_stddev_upper_bound, max_unmitigated_stddev, ), ) def test_expectation_improvement(self): """Test whether readout mitigation led to more accurate results and that its standard deviation is increased""" shots = 1024 assignment_matrices = self.assignment_matrices() mitigators = self.mitigators(assignment_matrices) num_qubits = len(assignment_matrices) diagonals = [] diagonals.append("IZ0") diagonals.append("101") diagonals.append("IZZ") qubit_index = {i: i for i in range(num_qubits)} circuit, circuit_name, num_qubits = self.ghz_3_circuit() counts_ideal, counts_noise, _ = self.counts_data(circuit, assignment_matrices, shots) probs_ideal, _ = counts_probability_vector(counts_ideal, qubit_index=qubit_index) probs_noise, _ = counts_probability_vector(counts_noise, qubit_index=qubit_index) for diagonal in diagonals: if isinstance(diagonal, str): diagonal = str2diag(diagonal) unmitigated_expectation, unmitigated_stddev = expval_with_stddev( diagonal, probs_noise, shots=counts_noise.shots() ) ideal_expectation = np.dot(probs_ideal, diagonal) unmitigated_error = np.abs(ideal_expectation - unmitigated_expectation) for mitigator in mitigators: mitigated_expectation, mitigated_stddev = mitigator.expectation_value( counts_noise, diagonal ) mitigated_error = np.abs(ideal_expectation - mitigated_expectation) self.assertLess( mitigated_error, unmitigated_error, "Mitigator {} did not improve circuit {} expectation computation for diagonal {} " "ideal: {}, unmitigated: {} mitigated: {}".format( mitigator, circuit_name, diagonal, ideal_expectation, unmitigated_expectation, mitigated_expectation, ), ) self.assertGreaterEqual( mitigated_stddev, unmitigated_stddev, "Mitigator {} did not increase circuit {} the standard deviation".format( mitigator, circuit_name ), ) def test_clbits_parameter(self): """Test whether the clbits parameter is handled correctly""" shots = 10000 assignment_matrices = self.assignment_matrices() mitigators = self.mitigators(assignment_matrices) circuit, _, _ = self.first_qubit_h_3_circuit() counts_ideal, counts_noise, _ = self.counts_data(circuit, assignment_matrices, shots) counts_ideal_12 = marginal_counts(counts_ideal, [1, 2]) counts_ideal_02 = marginal_counts(counts_ideal, [0, 2]) for mitigator in mitigators: mitigated_probs_12 = ( mitigator.quasi_probabilities(counts_noise, qubits=[1, 2], clbits=[1, 2]) .nearest_probability_distribution() .binary_probabilities(num_bits=2) ) mitigated_error = self.compare_results(counts_ideal_12, mitigated_probs_12) self.assertLess( mitigated_error, 0.001, "Mitigator {} did not correctly marganalize for qubits 1,2".format(mitigator), ) mitigated_probs_02 = ( mitigator.quasi_probabilities(counts_noise, qubits=[0, 2], clbits=[0, 2]) .nearest_probability_distribution() .binary_probabilities(num_bits=2) ) mitigated_error = self.compare_results(counts_ideal_02, mitigated_probs_02) self.assertLess( mitigated_error, 0.001, "Mitigator {} did not correctly marganalize for qubits 0,2".format(mitigator), ) def test_qubits_parameter(self): """Test whether the qubits parameter is handled correctly""" shots = 10000 assignment_matrices = self.assignment_matrices() mitigators = self.mitigators(assignment_matrices) circuit, _, _ = self.first_qubit_h_3_circuit() counts_ideal, counts_noise, _ = self.counts_data(circuit, assignment_matrices, shots) counts_ideal_012 = counts_ideal counts_ideal_210 = Counts({"000": counts_ideal["000"], "100": counts_ideal["001"]}) counts_ideal_102 = Counts({"000": counts_ideal["000"], "010": counts_ideal["001"]}) for mitigator in mitigators: mitigated_probs_012 = ( mitigator.quasi_probabilities(counts_noise, qubits=[0, 1, 2]) .nearest_probability_distribution() .binary_probabilities(num_bits=3) ) mitigated_error = self.compare_results(counts_ideal_012, mitigated_probs_012) self.assertLess( mitigated_error, 0.001, "Mitigator {} did not correctly handle qubit order 0, 1, 2".format(mitigator), ) mitigated_probs_210 = ( mitigator.quasi_probabilities(counts_noise, qubits=[2, 1, 0]) .nearest_probability_distribution() .binary_probabilities(num_bits=3) ) mitigated_error = self.compare_results(counts_ideal_210, mitigated_probs_210) self.assertLess( mitigated_error, 0.001, "Mitigator {} did not correctly handle qubit order 2, 1, 0".format(mitigator), ) mitigated_probs_102 = ( mitigator.quasi_probabilities(counts_noise, qubits=[1, 0, 2]) .nearest_probability_distribution() .binary_probabilities(num_bits=3) ) mitigated_error = self.compare_results(counts_ideal_102, mitigated_probs_102) self.assertLess( mitigated_error, 0.001, "Mitigator {} did not correctly handle qubit order 1, 0, 2".format(mitigator), ) def test_repeated_qubits_parameter(self): """Tests the order of mitigated qubits.""" shots = 10000 assignment_matrices = self.assignment_matrices() mitigators = self.mitigators(assignment_matrices, qubits=[0, 1, 2]) circuit, _, _ = self.first_qubit_h_3_circuit() counts_ideal, counts_noise, _ = self.counts_data(circuit, assignment_matrices, shots) counts_ideal_012 = counts_ideal counts_ideal_210 = Counts({"000": counts_ideal["000"], "100": counts_ideal["001"]}) for mitigator in mitigators: mitigated_probs_210 = ( mitigator.quasi_probabilities(counts_noise, qubits=[2, 1, 0]) .nearest_probability_distribution() .binary_probabilities(num_bits=3) ) mitigated_error = self.compare_results(counts_ideal_210, mitigated_probs_210) self.assertLess( mitigated_error, 0.001, "Mitigator {} did not correctly handle qubit order 2,1,0".format(mitigator), ) # checking qubit order 2,1,0 should not "overwrite" the default 0,1,2 mitigated_probs_012 = ( mitigator.quasi_probabilities(counts_noise) .nearest_probability_distribution() .binary_probabilities(num_bits=3) ) mitigated_error = self.compare_results(counts_ideal_012, mitigated_probs_012) self.assertLess( mitigated_error, 0.001, "Mitigator {} did not correctly handle qubit order 0,1,2 (the expected default)".format( mitigator ), ) def test_qubits_subset_parameter(self): """Tests mitigation on a subset of the initial set of qubits.""" shots = 10000 assignment_matrices = self.assignment_matrices() mitigators = self.mitigators(assignment_matrices, qubits=[2, 4, 6]) circuit, _, _ = self.first_qubit_h_3_circuit() counts_ideal, counts_noise, _ = self.counts_data(circuit, assignment_matrices, shots) counts_ideal_2 = marginal_counts(counts_ideal, [0]) counts_ideal_6 = marginal_counts(counts_ideal, [2]) for mitigator in mitigators: mitigated_probs_2 = ( mitigator.quasi_probabilities(counts_noise, qubits=[2]) .nearest_probability_distribution() .binary_probabilities(num_bits=1) ) mitigated_error = self.compare_results(counts_ideal_2, mitigated_probs_2) self.assertLess( mitigated_error, 0.001, "Mitigator {} did not correctly handle qubit subset".format(mitigator), ) mitigated_probs_6 = ( mitigator.quasi_probabilities(counts_noise, qubits=[6]) .nearest_probability_distribution() .binary_probabilities(num_bits=1) ) mitigated_error = self.compare_results(counts_ideal_6, mitigated_probs_6) self.assertLess( mitigated_error, 0.001, "Mitigator {} did not correctly handle qubit subset".format(mitigator), ) diagonal = str2diag("ZZ") ideal_expectation = 0 mitigated_expectation, _ = mitigator.expectation_value( counts_noise, diagonal, qubits=[2, 6] ) mitigated_error = np.abs(ideal_expectation - mitigated_expectation) self.assertLess( mitigated_error, 0.1, "Mitigator {} did not improve circuit expectation".format(mitigator), ) def test_from_backend(self): """Test whether a local mitigator can be created directly from backend properties""" backend = FakeYorktown() num_qubits = len(backend.properties().qubits) probs = TestReadoutMitigation.rng.random((num_qubits, 2)) for qubit_idx, qubit_prop in enumerate(backend.properties().qubits): for prop in qubit_prop: if prop.name == "prob_meas1_prep0": prop.value = probs[qubit_idx][0] if prop.name == "prob_meas0_prep1": prop.value = probs[qubit_idx][1] LRM_from_backend = LocalReadoutMitigator(backend=backend) mats = [] for qubit_idx in range(num_qubits): mat = np.array( [ [1 - probs[qubit_idx][0], probs[qubit_idx][1]], [probs[qubit_idx][0], 1 - probs[qubit_idx][1]], ] ) mats.append(mat) LRM_from_matrices = LocalReadoutMitigator(assignment_matrices=mats) self.assertTrue( matrix_equal( LRM_from_backend.assignment_matrix(), LRM_from_matrices.assignment_matrix() ) ) def test_error_handling(self): """Test that the assignment matrices are valid.""" bad_matrix_A = np.array([[-0.3, 1], [1.3, 0]]) # negative indices bad_matrix_B = np.array([[0.2, 1], [0.7, 0]]) # columns not summing to 1 good_matrix_A = np.array([[0.2, 1], [0.8, 0]]) for bad_matrix in [bad_matrix_A, bad_matrix_B]: with self.assertRaises(QiskitError) as cm: CorrelatedReadoutMitigator(bad_matrix) self.assertEqual( cm.exception.message, "Assignment matrix columns must be valid probability distributions", ) with self.assertRaises(QiskitError) as cm: amats = [good_matrix_A, bad_matrix_A] LocalReadoutMitigator(amats) self.assertEqual( cm.exception.message, "Assignment matrix columns must be valid probability distributions", ) with self.assertRaises(QiskitError) as cm: amats = [bad_matrix_B, good_matrix_A] LocalReadoutMitigator(amats) self.assertEqual( cm.exception.message, "Assignment matrix columns must be valid probability distributions", ) def test_expectation_value_endian(self): """Test that endian for expval is little.""" mitigators = self.mitigators(self.assignment_matrices()) counts = Counts({"10": 3, "11": 24, "00": 74, "01": 923}) for mitigator in mitigators: expval, _ = mitigator.expectation_value(counts, diagonal="IZ", qubits=[0, 1]) self.assertAlmostEqual(expval, -1.0, places=0) def test_quasi_probabilities_shots_passing(self): """Test output of LocalReadoutMitigator.quasi_probabilities We require the number of shots to be set in the output. """ mitigator = LocalReadoutMitigator([np.array([[0.9, 0.1], [0.1, 0.9]])], qubits=[0]) counts = Counts({"10": 3, "11": 24, "00": 74, "01": 923}) quasi_dist = mitigator.quasi_probabilities(counts) self.assertEqual(quasi_dist.shots, sum(counts.values())) # custom number of shots quasi_dist = mitigator.quasi_probabilities(counts, shots=1025) self.assertEqual(quasi_dist.shots, 1025) class TestLocalReadoutMitigation(QiskitTestCase): """Tests specific to the local readout mitigator""" def test_assignment_matrix(self): """Tests that the local mitigator generates the full assignment matrix correctly""" qubits = [7, 2, 3] assignment_matrices = LocalReadoutMitigator(backend=FakeYorktown())._assignment_mats[0:3] expected_assignment_matrix = np.kron( np.kron(assignment_matrices[2], assignment_matrices[1]), assignment_matrices[0] ) expected_mitigation_matrix = np.linalg.inv(expected_assignment_matrix) LRM = LocalReadoutMitigator(assignment_matrices, qubits) self.assertTrue(matrix_equal(expected_mitigation_matrix, LRM.mitigation_matrix())) self.assertTrue(matrix_equal(expected_assignment_matrix, LRM.assignment_matrix())) if __name__ == "__main__": unittest.main()
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# 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 cases for the pulse scheduler passes.""" from numpy import pi from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, schedule from qiskit.circuit import Gate, Parameter from qiskit.circuit.library import U1Gate, U2Gate, U3Gate from qiskit.exceptions import QiskitError from qiskit.pulse import ( Schedule, DriveChannel, AcquireChannel, Acquire, MeasureChannel, MemorySlot, Gaussian, Play, transforms, ) from qiskit.pulse import build, macros, play, InstructionScheduleMap from qiskit.providers.fake_provider import FakeBackend, FakeOpenPulse2Q, FakeOpenPulse3Q from qiskit.test import QiskitTestCase class TestBasicSchedule(QiskitTestCase): """Scheduling tests.""" def setUp(self): super().setUp() self.backend = FakeOpenPulse2Q() self.inst_map = self.backend.defaults().instruction_schedule_map def test_unavailable_defaults(self): """Test backend with unavailable defaults.""" qr = QuantumRegister(1) qc = QuantumCircuit(qr) backend = FakeBackend(None) backend.defaults = backend.configuration self.assertRaises(QiskitError, lambda: schedule(qc, backend)) def test_alap_pass(self): """Test ALAP scheduling.""" # β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β–‘ β”Œβ”€β” # q0_0: ─ U2(3.14,1.57) β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–‘β”€β”€β”€β– β”€β”€β”€Mβ”œβ”€β”€β”€ # └┬─────────────── β–‘ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β–‘ β”Œβ”€β”΄β”€β”β””β•₯β”˜β”Œβ”€β” # q0_1: ── U2(0.5,0.25) β”œβ”€β–‘β”€β”€ U2(0.5,0.25) β”œβ”€β–‘β”€β”€ X β”œβ”€β•«β”€β”€Mβ”œ # β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β–‘ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β–‘ β””β”€β”€β”€β”˜ β•‘ β””β•₯β”˜ # c0: 2/═════════════════════════════════════════════╩══╩═ # 0 1 q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.append(U2Gate(3.14, 1.57), [q[0]]) qc.append(U2Gate(0.5, 0.25), [q[1]]) qc.barrier(q[1]) qc.append(U2Gate(0.5, 0.25), [q[1]]) qc.barrier(q[0], [q[1]]) qc.cx(q[0], q[1]) qc.measure(q, c) sched = schedule(qc, self.backend) # X pulse on q0 should end at the start of the CNOT expected = Schedule( (2, self.inst_map.get("u2", [0], 3.14, 1.57)), self.inst_map.get("u2", [1], 0.5, 0.25), (2, self.inst_map.get("u2", [1], 0.5, 0.25)), (4, self.inst_map.get("cx", [0, 1])), (26, self.inst_map.get("measure", [0, 1])), ) for actual, expected in zip(sched.instructions, expected.instructions): self.assertEqual(actual[0], expected[0]) self.assertEqual(actual[1], expected[1]) def test_single_circuit_list_schedule(self): """Test that passing a single circuit list to schedule() returns a list.""" q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) sched = schedule([qc], self.backend, method="alap") expected = Schedule() self.assertIsInstance(sched, list) self.assertEqual(sched[0].instructions, expected.instructions) def test_alap_with_barriers(self): """Test that ALAP respects barriers on new qubits.""" q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.append(U2Gate(0, 0), [q[0]]) qc.barrier(q[0], q[1]) qc.append(U2Gate(0, 0), [q[1]]) sched = schedule(qc, self.backend, method="alap") expected = Schedule( self.inst_map.get("u2", [0], 0, 0), (2, self.inst_map.get("u2", [1], 0, 0)) ) for actual, expected in zip(sched.instructions, expected.instructions): self.assertEqual(actual[0], expected[0]) self.assertEqual(actual[1], expected[1]) def test_empty_circuit_schedule(self): """Test empty circuit being scheduled.""" q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) sched = schedule(qc, self.backend, method="alap") expected = Schedule() self.assertEqual(sched.instructions, expected.instructions) def test_alap_aligns_end(self): """Test that ALAP always acts as though there is a final global barrier.""" q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.append(U3Gate(0, 0, 0), [q[0]]) qc.append(U2Gate(0, 0), [q[1]]) sched = schedule(qc, self.backend, method="alap") expected_sched = Schedule( (2, self.inst_map.get("u2", [1], 0, 0)), self.inst_map.get("u3", [0], 0, 0, 0) ) for actual, expected in zip(sched.instructions, expected_sched.instructions): self.assertEqual(actual[0], expected[0]) self.assertEqual(actual[1], expected[1]) self.assertEqual( sched.ch_duration(DriveChannel(0)), expected_sched.ch_duration(DriveChannel(1)) ) def test_asap_pass(self): """Test ASAP scheduling.""" # β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β–‘ β”Œβ”€β” # q0_0: ─ U2(3.14,1.57) β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–‘β”€β”€β”€β– β”€β”€β”€Mβ”œβ”€β”€β”€ # └┬─────────────── β–‘ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β–‘ β”Œβ”€β”΄β”€β”β””β•₯β”˜β”Œβ”€β” # q0_1: ── U2(0.5,0.25) β”œβ”€β–‘β”€β”€ U2(0.5,0.25) β”œβ”€β–‘β”€β”€ X β”œβ”€β•«β”€β”€Mβ”œ # β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β–‘ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β–‘ β””β”€β”€β”€β”˜ β•‘ β””β•₯β”˜ # c0: 2/═════════════════════════════════════════════╩══╩═ # 0 1 q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.append(U2Gate(3.14, 1.57), [q[0]]) qc.append(U2Gate(0.5, 0.25), [q[1]]) qc.barrier(q[1]) qc.append(U2Gate(0.5, 0.25), [q[1]]) qc.barrier(q[0], q[1]) qc.cx(q[0], q[1]) qc.measure(q, c) sched = schedule(qc, self.backend, method="as_soon_as_possible") # X pulse on q0 should start at t=0 expected = Schedule( self.inst_map.get("u2", [0], 3.14, 1.57), self.inst_map.get("u2", [1], 0.5, 0.25), (2, self.inst_map.get("u2", [1], 0.5, 0.25)), (4, self.inst_map.get("cx", [0, 1])), (26, self.inst_map.get("measure", [0, 1])), ) for actual, expected in zip(sched.instructions, expected.instructions): self.assertEqual(actual[0], expected[0]) self.assertEqual(actual[1], expected[1]) def test_alap_resource_respecting(self): """Test that the ALAP pass properly respects busy resources when backwards scheduling. For instance, a CX on 0 and 1 followed by an X on only 1 must respect both qubits' timeline.""" q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.cx(q[0], q[1]) qc.append(U2Gate(0.5, 0.25), [q[1]]) sched = schedule(qc, self.backend, method="as_late_as_possible") insts = sched.instructions self.assertEqual(insts[0][0], 0) self.assertEqual(insts[6][0], 22) qc = QuantumCircuit(q, c) qc.cx(q[0], q[1]) qc.append(U2Gate(0.5, 0.25), [q[1]]) qc.measure(q, c) sched = schedule(qc, self.backend, method="as_late_as_possible") self.assertEqual(sched.instructions[-1][0], 24) def test_inst_map_schedules_unaltered(self): """Test that forward scheduling doesn't change relative timing with a command.""" q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.cx(q[0], q[1]) sched1 = schedule(qc, self.backend, method="as_soon_as_possible") sched2 = schedule(qc, self.backend, method="as_late_as_possible") for asap, alap in zip(sched1.instructions, sched2.instructions): self.assertEqual(asap[0], alap[0]) self.assertEqual(asap[1], alap[1]) insts = sched1.instructions self.assertEqual(insts[0][0], 0) # shift phase self.assertEqual(insts[1][0], 0) # ym_d0 self.assertEqual(insts[2][0], 0) # x90p_d1 self.assertEqual(insts[3][0], 2) # cr90p_u0 self.assertEqual(insts[4][0], 11) # xp_d0 self.assertEqual(insts[5][0], 13) # cr90m_u0 def test_measure_combined(self): """ Test to check for measure on the same qubit which generated another measure schedule. The measures on different qubits are combined, but measures on the same qubit adds another measure to the schedule. """ q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.append(U2Gate(3.14, 1.57), [q[0]]) qc.cx(q[0], q[1]) qc.measure(q[0], c[0]) qc.measure(q[1], c[1]) qc.measure(q[1], c[1]) sched = schedule(qc, self.backend, method="as_soon_as_possible") expected = Schedule( self.inst_map.get("u2", [0], 3.14, 1.57), (2, self.inst_map.get("cx", [0, 1])), (24, self.inst_map.get("measure", [0, 1])), (34, self.inst_map.get("measure", [0, 1]).filter(channels=[MeasureChannel(1)])), (34, Acquire(10, AcquireChannel(1), MemorySlot(1))), ) self.assertEqual(sched.instructions, expected.instructions) def test_3q_schedule(self): """Test a schedule that was recommended by David McKay :D""" # β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” # q0_0: ─────────■────────── U3(3.14,1.57,0) β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ # β”Œβ”€β”΄β”€β” β””β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”˜ # q0_1: ──────── X β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€ U2(3.14,1.57) β”œβ”€β”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ # β”Œβ”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β” β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”Œβ”€β”΄β”€β”β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” # q0_2: ─ U2(0.778,0.122) β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ X β”œβ”€ U2(0.778,0.122) β”œ # β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ backend = FakeOpenPulse3Q() inst_map = backend.defaults().instruction_schedule_map q = QuantumRegister(3) c = ClassicalRegister(3) qc = QuantumCircuit(q, c) qc.cx(q[0], q[1]) qc.append(U2Gate(0.778, 0.122), [q[2]]) qc.append(U3Gate(3.14, 1.57, 0), [q[0]]) qc.append(U2Gate(3.14, 1.57), [q[1]]) qc.cx(q[1], q[2]) qc.append(U2Gate(0.778, 0.122), [q[2]]) sched = schedule(qc, backend) expected = Schedule( inst_map.get("cx", [0, 1]), (22, inst_map.get("u2", [1], 3.14, 1.57)), (22, inst_map.get("u2", [2], 0.778, 0.122)), (24, inst_map.get("cx", [1, 2])), (44, inst_map.get("u3", [0], 3.14, 1.57, 0)), (46, inst_map.get("u2", [2], 0.778, 0.122)), ) for actual, expected in zip(sched.instructions, expected.instructions): self.assertEqual(actual[0], expected[0]) self.assertEqual(actual[1], expected[1]) def test_schedule_multi(self): """Test scheduling multiple circuits at once.""" q = QuantumRegister(2) c = ClassicalRegister(2) qc0 = QuantumCircuit(q, c) qc0.cx(q[0], q[1]) qc1 = QuantumCircuit(q, c) qc1.cx(q[0], q[1]) schedules = schedule([qc0, qc1], self.backend) expected_insts = schedule(qc0, self.backend).instructions for actual, expected in zip(schedules[0].instructions, expected_insts): self.assertEqual(actual[0], expected[0]) self.assertEqual(actual[1], expected[1]) def test_circuit_name_kept(self): """Test that the new schedule gets its name from the circuit.""" q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c, name="CIRCNAME") qc.cx(q[0], q[1]) sched = schedule(qc, self.backend, method="asap") self.assertEqual(sched.name, qc.name) sched = schedule(qc, self.backend, method="alap") self.assertEqual(sched.name, qc.name) def test_can_add_gates_into_free_space(self): """The scheduler does some time bookkeeping to know when qubits are free to be scheduled. Make sure this works for qubits that are used in the future. This was a bug, uncovered by this example: q0 = - - - - |X| q1 = |X| |u2| |X| In ALAP scheduling, the next operation on qubit 0 would be added at t=0 rather than immediately before the X gate. """ qr = QuantumRegister(2) qc = QuantumCircuit(qr) for i in range(2): qc.append(U2Gate(0, 0), [qr[i]]) qc.append(U1Gate(3.14), [qr[i]]) qc.append(U2Gate(0, 0), [qr[i]]) sched = schedule(qc, self.backend, method="alap") expected = Schedule( self.inst_map.get("u2", [0], 0, 0), self.inst_map.get("u2", [1], 0, 0), (2, self.inst_map.get("u1", [0], 3.14)), (2, self.inst_map.get("u1", [1], 3.14)), (2, self.inst_map.get("u2", [0], 0, 0)), (2, self.inst_map.get("u2", [1], 0, 0)), ) for actual, expected in zip(sched.instructions, expected.instructions): self.assertEqual(actual[0], expected[0]) self.assertEqual(actual[1], expected[1]) def test_barriers_in_middle(self): """As a follow on to `test_can_add_gates_into_free_space`, similar issues arose for barriers, specifically. """ qr = QuantumRegister(2) qc = QuantumCircuit(qr) for i in range(2): qc.append(U2Gate(0, 0), [qr[i]]) qc.barrier(qr[i]) qc.append(U1Gate(3.14), [qr[i]]) qc.barrier(qr[i]) qc.append(U2Gate(0, 0), [qr[i]]) sched = schedule(qc, self.backend, method="alap") expected = Schedule( self.inst_map.get("u2", [0], 0, 0), self.inst_map.get("u2", [1], 0, 0), (2, self.inst_map.get("u1", [0], 3.14)), (2, self.inst_map.get("u1", [1], 3.14)), (2, self.inst_map.get("u2", [0], 0, 0)), (2, self.inst_map.get("u2", [1], 0, 0)), ) for actual, expected in zip(sched.instructions, expected.instructions): self.assertEqual(actual[0], expected[0]) self.assertEqual(actual[1], expected[1]) def test_parametric_input(self): """Test that scheduling works with parametric pulses as input.""" qr = QuantumRegister(1) qc = QuantumCircuit(qr) qc.append(Gate("gauss", 1, []), qargs=[qr[0]]) custom_gauss = Schedule( Play(Gaussian(duration=25, sigma=4, amp=0.5, angle=pi / 2), DriveChannel(0)) ) self.inst_map.add("gauss", [0], custom_gauss) sched = schedule(qc, self.backend, inst_map=self.inst_map) self.assertEqual(sched.instructions[0], custom_gauss.instructions[0]) def test_pulse_gates(self): """Test scheduling calibrated pulse gates.""" q = QuantumRegister(2) qc = QuantumCircuit(q) qc.append(U2Gate(0, 0), [q[0]]) qc.barrier(q[0], q[1]) qc.append(U2Gate(0, 0), [q[1]]) qc.add_calibration("u2", [0], Schedule(Play(Gaussian(28, 0.2, 4), DriveChannel(0))), [0, 0]) qc.add_calibration("u2", [1], Schedule(Play(Gaussian(28, 0.2, 4), DriveChannel(1))), [0, 0]) sched = schedule(qc, self.backend) expected = Schedule( Play(Gaussian(28, 0.2, 4), DriveChannel(0)), (28, Schedule(Play(Gaussian(28, 0.2, 4), DriveChannel(1)))), ) self.assertEqual(sched.instructions, expected.instructions) def test_calibrated_measurements(self): """Test scheduling calibrated measurements.""" q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.append(U2Gate(0, 0), [q[0]]) qc.measure(q[0], c[0]) meas_sched = Play(Gaussian(1200, 0.2, 4), MeasureChannel(0)) meas_sched |= Acquire(1200, AcquireChannel(0), MemorySlot(0)) qc.add_calibration("measure", [0], meas_sched) sched = schedule(qc, self.backend) expected = Schedule(self.inst_map.get("u2", [0], 0, 0), (2, meas_sched)) self.assertEqual(sched.instructions, expected.instructions) def test_subset_calibrated_measurements(self): """Test that measurement calibrations can be added and used for some qubits, even if the other qubits do not also have calibrated measurements.""" qc = QuantumCircuit(3, 3) qc.measure(0, 0) qc.measure(1, 1) qc.measure(2, 2) meas_scheds = [] for qubit in [0, 2]: meas = Play(Gaussian(1200, 0.2, 4), MeasureChannel(qubit)) + Acquire( 1200, AcquireChannel(qubit), MemorySlot(qubit) ) meas_scheds.append(meas) qc.add_calibration("measure", [qubit], meas) meas = macros.measure([1], FakeOpenPulse3Q()) meas = meas.exclude(channels=[AcquireChannel(0), AcquireChannel(2)]) sched = schedule(qc, FakeOpenPulse3Q()) expected = Schedule(meas_scheds[0], meas_scheds[1], meas) self.assertEqual(sched.instructions, expected.instructions) def test_clbits_of_calibrated_measurements(self): """Test that calibrated measurements are only used when the classical bits also match.""" q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.measure(q[0], c[1]) meas_sched = Play(Gaussian(1200, 0.2, 4), MeasureChannel(0)) meas_sched |= Acquire(1200, AcquireChannel(0), MemorySlot(0)) qc.add_calibration("measure", [0], meas_sched) sched = schedule(qc, self.backend) # Doesn't use the calibrated schedule because the classical memory slots do not match expected = Schedule(macros.measure([0], self.backend, qubit_mem_slots={0: 1})) self.assertEqual(sched.instructions, expected.instructions) def test_metadata_is_preserved_alap(self): """Test that circuit metadata is preserved in output schedule with alap.""" q = QuantumRegister(2) qc = QuantumCircuit(q) qc.append(U2Gate(0, 0), [q[0]]) qc.barrier(q[0], q[1]) qc.append(U2Gate(0, 0), [q[1]]) qc.metadata = {"experiment_type": "gst", "execution_number": "1234"} sched = schedule(qc, self.backend, method="alap") self.assertEqual({"experiment_type": "gst", "execution_number": "1234"}, sched.metadata) def test_metadata_is_preserved_asap(self): """Test that circuit metadata is preserved in output schedule with asap.""" q = QuantumRegister(2) qc = QuantumCircuit(q) qc.append(U2Gate(0, 0), [q[0]]) qc.barrier(q[0], q[1]) qc.append(U2Gate(0, 0), [q[1]]) qc.metadata = {"experiment_type": "gst", "execution_number": "1234"} sched = schedule(qc, self.backend, method="asap") self.assertEqual({"experiment_type": "gst", "execution_number": "1234"}, sched.metadata) def test_scheduler_with_params_bound(self): """Test scheduler with parameters defined and bound""" x = Parameter("x") qc = QuantumCircuit(2) qc.append(Gate("pulse_gate", 1, [x]), [0]) expected_schedule = Schedule() qc.add_calibration(gate="pulse_gate", qubits=[0], schedule=expected_schedule, params=[x]) qc = qc.assign_parameters({x: 1}) sched = schedule(qc, self.backend) self.assertEqual(sched, expected_schedule) def test_scheduler_with_params_not_bound(self): """Test scheduler with parameters defined but not bound""" x = Parameter("amp") qc = QuantumCircuit(2) qc.append(Gate("pulse_gate", 1, [x]), [0]) with build() as expected_schedule: play(Gaussian(duration=160, amp=x, sigma=40), DriveChannel(0)) qc.add_calibration(gate="pulse_gate", qubits=[0], schedule=expected_schedule, params=[x]) sched = schedule(qc, self.backend) self.assertEqual(sched, transforms.target_qobj_transform(expected_schedule)) def test_schedule_block_in_instmap(self): """Test schedule block in instmap can be scheduled.""" duration = Parameter("duration") with build() as pulse_prog: play(Gaussian(duration, 0.1, 10), DriveChannel(0)) instmap = InstructionScheduleMap() instmap.add("block_gate", (0,), pulse_prog, ["duration"]) qc = QuantumCircuit(1) qc.append(Gate("block_gate", 1, [duration]), [0]) qc.assign_parameters({duration: 100}, inplace=True) sched = schedule(qc, self.backend, inst_map=instmap) ref_sched = Schedule() ref_sched += Play(Gaussian(100, 0.1, 10), DriveChannel(0)) self.assertEqual(sched, ref_sched)
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# 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 -CZ-CX- joint synthesis function.""" import unittest from test import combine import numpy as np from ddt import ddt from qiskit import QuantumCircuit from qiskit.quantum_info import Clifford from qiskit.synthesis.linear_phase.cx_cz_depth_lnn import synth_cx_cz_depth_line_my from qiskit.synthesis.linear import ( synth_cnot_depth_line_kms, random_invertible_binary_matrix, ) from qiskit.synthesis.linear.linear_circuits_utils import check_lnn_connectivity from qiskit.test import QiskitTestCase @ddt class TestCXCZSynth(QiskitTestCase): """Test the linear reversible circuit synthesis functions.""" @combine(num_qubits=[3, 4, 5, 6, 7, 8, 9, 10]) def test_cx_cz_synth_lnn(self, num_qubits): """Test the CXCZ synthesis code for linear nearest neighbour connectivity.""" seed = 1234 rng = np.random.default_rng(seed) num_gates = 10 num_trials = 8 for _ in range(num_trials): # Generate a random CZ circuit mat_z = np.zeros((num_qubits, num_qubits)) cir_z = QuantumCircuit(num_qubits) for _ in range(num_gates): i = rng.integers(num_qubits) j = rng.integers(num_qubits) if i != j: cir_z.cz(i, j) if j > i: mat_z[i][j] = (mat_z[i][j] + 1) % 2 else: mat_z[j][i] = (mat_z[j][i] + 1) % 2 # Generate a random CX circuit mat_x = random_invertible_binary_matrix(num_qubits, seed=rng) mat_x = np.array(mat_x, dtype=bool) cir_x = synth_cnot_depth_line_kms(mat_x) # Joint Synthesis cir_zx_test = QuantumCircuit.compose(cir_z, cir_x) cir_zx = synth_cx_cz_depth_line_my(mat_x, mat_z) # Check that the output circuit 2-qubit depth is at most 5n depth2q = cir_zx.depth(filter_function=lambda x: x.operation.num_qubits == 2) self.assertTrue(depth2q <= 5 * num_qubits) # Check that the output circuit has LNN connectivity self.assertTrue(check_lnn_connectivity(cir_zx)) # Assert that we get the same elements as other methods self.assertEqual(Clifford(cir_zx), Clifford(cir_zx_test)) if __name__ == "__main__": unittest.main()
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# 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 CZ circuits synthesis functions.""" import unittest from test import combine import numpy as np from ddt import ddt from qiskit import QuantumCircuit from qiskit.circuit.library import Permutation from qiskit.synthesis.linear_phase import synth_cz_depth_line_mr from qiskit.synthesis.linear.linear_circuits_utils import check_lnn_connectivity from qiskit.quantum_info import Clifford from qiskit.test import QiskitTestCase @ddt class TestCZSynth(QiskitTestCase): """Test the linear reversible circuit synthesis functions.""" @combine(num_qubits=[3, 4, 5, 6, 7]) def test_cz_synth_lnn(self, num_qubits): """Test the CZ synthesis code for linear nearest neighbour connectivity.""" seed = 1234 rng = np.random.default_rng(seed) num_gates = 10 num_trials = 5 for _ in range(num_trials): mat = np.zeros((num_qubits, num_qubits)) qctest = QuantumCircuit(num_qubits) # Generate a random CZ circuit for _ in range(num_gates): i = rng.integers(num_qubits) j = rng.integers(num_qubits) if i != j: qctest.cz(i, j) if j > i: mat[i][j] = (mat[i][j] + 1) % 2 else: mat[j][i] = (mat[j][i] + 1) % 2 qc = synth_cz_depth_line_mr(mat) # Check that the output circuit 2-qubit depth equals to 2*n+2 depth2q = qc.depth(filter_function=lambda x: x.operation.num_qubits == 2) self.assertTrue(depth2q == 2 * num_qubits + 2) # Check that the output circuit has LNN connectivity self.assertTrue(check_lnn_connectivity(qc)) # Assert that we get the same element, up to reverse order of qubits perm = Permutation(num_qubits=num_qubits, pattern=range(num_qubits)[::-1]) qctest = qctest.compose(perm) self.assertEqual(Clifford(qc), Clifford(qctest)) if __name__ == "__main__": unittest.main()
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 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 linear reversible circuits synthesis functions.""" import unittest import numpy as np from ddt import ddt, data from qiskit import QuantumCircuit from qiskit.circuit.library import LinearFunction from qiskit.synthesis.linear import ( synth_cnot_count_full_pmh, synth_cnot_depth_line_kms, random_invertible_binary_matrix, check_invertible_binary_matrix, calc_inverse_matrix, ) from qiskit.synthesis.linear.linear_circuits_utils import transpose_cx_circ, optimize_cx_4_options from qiskit.test import QiskitTestCase @ddt class TestLinearSynth(QiskitTestCase): """Test the linear reversible circuit synthesis functions.""" def test_lnn_circuit(self): """Test the synthesis of a CX circuit with LNN connectivity.""" n = 5 qc = QuantumCircuit(n) for i in range(n - 1): qc.cx(i, i + 1) mat = LinearFunction(qc).linear for optimized in [True, False]: optimized_qc = optimize_cx_4_options( synth_cnot_count_full_pmh, mat, optimize_count=optimized ) self.assertEqual(optimized_qc.depth(), 4) self.assertEqual(optimized_qc.count_ops()["cx"], 4) def test_full_circuit(self): """Test the synthesis of a CX circuit with full connectivity.""" n = 5 qc = QuantumCircuit(n) for i in range(n): for j in range(i + 1, n): qc.cx(i, j) mat = LinearFunction(qc).linear for optimized in [True, False]: optimized_qc = optimize_cx_4_options( synth_cnot_count_full_pmh, mat, optimize_count=optimized ) self.assertEqual(optimized_qc.depth(), 4) self.assertEqual(optimized_qc.count_ops()["cx"], 4) def test_transpose_circ(self): """Test the transpose_cx_circ() function.""" n = 5 mat = random_invertible_binary_matrix(n, seed=1234) qc = synth_cnot_count_full_pmh(mat) transposed_qc = transpose_cx_circ(qc) transposed_mat = LinearFunction(transposed_qc).linear.astype(int) self.assertTrue((mat.transpose() == transposed_mat).all()) def test_example_circuit(self): """Test the synthesis of an example CX circuit which provides different CX count and depth for different optimization methods.""" qc = QuantumCircuit(9) qc.swap(8, 7) qc.swap(7, 6) qc.cx(5, 6) qc.cx(6, 5) qc.swap(4, 5) qc.cx(3, 4) qc.cx(4, 3) qc.swap(2, 3) qc.cx(1, 2) qc.cx(2, 1) qc.cx(0, 1) qc.cx(1, 0) mat = LinearFunction(qc).linear optimized_qc = optimize_cx_4_options(synth_cnot_count_full_pmh, mat, optimize_count=True) self.assertEqual(optimized_qc.depth(), 17) self.assertEqual(optimized_qc.count_ops()["cx"], 20) optimized_qc = optimize_cx_4_options(synth_cnot_count_full_pmh, mat, optimize_count=False) self.assertEqual(optimized_qc.depth(), 15) self.assertEqual(optimized_qc.count_ops()["cx"], 23) @data(5, 6) def test_invertible_matrix(self, n): """Test the functions for generating a random invertible matrix and inverting it.""" mat = random_invertible_binary_matrix(n, seed=1234) out = check_invertible_binary_matrix(mat) mat_inv = calc_inverse_matrix(mat, verify=True) mat_out = np.dot(mat, mat_inv) % 2 self.assertTrue(np.array_equal(mat_out, np.eye(n))) self.assertTrue(out) @data(5, 6) def test_synth_lnn_kms(self, num_qubits): """Test that synth_cnot_depth_line_kms produces the correct synthesis.""" rng = np.random.default_rng(1234) num_trials = 10 for _ in range(num_trials): mat = random_invertible_binary_matrix(num_qubits, seed=rng) mat = np.array(mat, dtype=bool) qc = synth_cnot_depth_line_kms(mat) mat1 = LinearFunction(qc).linear self.assertTrue((mat == mat1).all()) # Check that the circuit depth is bounded by 5*num_qubits depth = qc.depth() self.assertTrue(depth <= 5 * num_qubits) # Check that the synthesized circuit qc fits LNN connectivity for inst in qc.data: self.assertEqual(inst.operation.name, "cx") q0 = qc.find_bit(inst.qubits[0]).index q1 = qc.find_bit(inst.qubits[1]).index dist = abs(q0 - q1) self.assertEqual(dist, 1) if __name__ == "__main__": unittest.main()
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 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 """Tests for local invariance routines.""" import unittest from numpy.testing import assert_allclose from qiskit import QuantumCircuit, QuantumRegister from qiskit.synthesis.two_qubit.local_invariance import two_qubit_local_invariants from qiskit.quantum_info import Operator from test import QiskitTestCase # pylint: disable=wrong-import-order class TestLocalInvariance(QiskitTestCase): """Test local invariance routines""" def test_2q_local_invariance_simple(self): """Check the local invariance parameters for known simple cases. """ qr = QuantumRegister(2, name="q") qc = QuantumCircuit(qr) U = Operator(qc) vec = two_qubit_local_invariants(U) assert_allclose(vec, [1, 0, 3]) qr = QuantumRegister(2, name="q") qc = QuantumCircuit(qr) qc.cx(qr[1], qr[0]) U = Operator(qc) vec = two_qubit_local_invariants(U) assert_allclose(vec, [0, 0, 1]) qr = QuantumRegister(2, name="q") qc = QuantumCircuit(qr) qc.cx(qr[1], qr[0]) qc.cx(qr[0], qr[1]) U = Operator(qc) vec = two_qubit_local_invariants(U) assert_allclose(vec, [0, 0, -1]) qr = QuantumRegister(2, name="q") qc = QuantumCircuit(qr) qc.swap(qr[1], qr[0]) U = Operator(qc) vec = two_qubit_local_invariants(U) assert_allclose(vec, [-1, 0, -3]) if __name__ == "__main__": unittest.main()
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
import numpy as np from qiskit import QuantumCircuit, transpile from qiskit.providers.aer import QasmSimulator from qiskit.visualization import plot_histogram # Use Aer's qasm_simulator simulator = QasmSimulator() # Create a Quantum Circuit acting on the q register circuit = QuantumCircuit(2, 2) # Add a H gate on qubit 0 circuit.h(0) # Add a CX (CNOT) gate on control qubit 0 and target qubit 1 circuit.cx(0, 1) # Map the quantum measurement to the classical bits circuit.measure([0,1], [0,1]) # compile the circuit down to low-level QASM instructions # supported by the backend (not needed for simple circuits) compiled_circuit = transpile(circuit, simulator) # Execute the circuit on the qasm simulator job = simulator.run(compiled_circuit, shots=1000) # Grab results from the job result = job.result() # Returns counts counts = result.get_counts(compiled_circuit) # print("\nTotal count for 00 and 11 are:",counts) # Draw the ci circuit.draw(output="latex", filename="printing.png")
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# 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 for qiskit-terra/qiskit/quantum_info/synthesis/xx_decompose/qiskit.py . """ from statistics import mean import unittest import ddt import numpy as np from scipy.stats import unitary_group import qiskit from qiskit.circuit.quantumcircuit import QuantumCircuit from qiskit.quantum_info.operators import Operator from qiskit.quantum_info.synthesis.xx_decompose.decomposer import ( XXDecomposer, TwoQubitWeylDecomposition, ) from .utilities import canonical_matrix EPSILON = 1e-8 @ddt.ddt class TestXXDecomposer(unittest.TestCase): """Tests for decomposition of two-qubit unitaries over discrete gates from XX family.""" decomposer = XXDecomposer(euler_basis="PSX") def __init__(self, *args, seed=42, **kwargs): super().__init__(*args, **kwargs) self._random_state = np.random.Generator(np.random.PCG64(seed)) def test_random_compilation(self): """Test that compilation gives correct results.""" for _ in range(100): unitary = unitary_group.rvs(4, random_state=self._random_state) unitary /= np.linalg.det(unitary) ** (1 / 4) # decompose into CX, CX/2, and CX/3 circuit = self.decomposer(unitary, approximate=False) decomposed_unitary = Operator(circuit).data self.assertTrue(np.all(unitary - decomposed_unitary < EPSILON)) def test_compilation_determinism(self): """Test that compilation is stable under multiple calls.""" for _ in range(10): unitary = unitary_group.rvs(4, random_state=self._random_state) unitary /= np.linalg.det(unitary) ** (1 / 4) # decompose into CX, CX/2, and CX/3 circuit1 = self.decomposer(unitary, approximate=False) circuit2 = self.decomposer(unitary, approximate=False) self.assertEqual(circuit1, circuit2) @ddt.data(np.pi / 3, np.pi / 5, np.pi / 2) def test_default_embodiment(self, angle): """Test that _default_embodiment actually does yield XX gates.""" embodiment = self.decomposer._default_embodiment(angle) embodiment_matrix = Operator(embodiment).data self.assertTrue(np.all(canonical_matrix(angle, 0, 0) - embodiment_matrix < EPSILON)) def test_check_embodiment(self): """Test that XXDecomposer._check_embodiments correctly diagnoses il/legal embodiments.""" # build the member of the XX family corresponding to a single CX good_angle = np.pi / 2 good_embodiment = qiskit.QuantumCircuit(2) good_embodiment.h(0) good_embodiment.cx(0, 1) good_embodiment.h(1) good_embodiment.rz(np.pi / 2, 0) good_embodiment.rz(np.pi / 2, 1) good_embodiment.h(1) good_embodiment.h(0) good_embodiment.global_phase += np.pi / 4 # mismatch two members of the XX family bad_angle = np.pi / 10 bad_embodiment = qiskit.QuantumCircuit(2) # "self.assertDoesNotRaise" XXDecomposer(embodiments={good_angle: good_embodiment}) self.assertRaises( qiskit.exceptions.QiskitError, XXDecomposer, embodiments={bad_angle: bad_embodiment} ) def test_compilation_improvement(self): """Test that compilation to CX, CX/2, CX/3 improves over CX alone.""" slope, offset = (64 * 90) / 1000000, 909 / 1000000 + 1 / 1000 strength_table = self.decomposer._strength_to_infidelity( basis_fidelity={ strength: 1 - (slope * strength / (np.pi / 2) + offset) for strength in [np.pi / 2, np.pi / 4, np.pi / 6] }, approximate=True, ) limited_strength_table = {np.pi / 2: strength_table[np.pi / 2]} clever_costs = [] naive_costs = [] for _ in range(200): unitary = unitary_group.rvs(4, random_state=self._random_state) unitary /= np.linalg.det(unitary) ** (1 / 4) weyl_decomposition = TwoQubitWeylDecomposition(unitary) target = [getattr(weyl_decomposition, x) for x in ("a", "b", "c")] if target[-1] < -EPSILON: target = [np.pi / 2 - target[0], target[1], -target[2]] # decompose into CX, CX/2, and CX/3 clever_costs.append(self.decomposer._best_decomposition(target, strength_table)["cost"]) naive_costs.append( self.decomposer._best_decomposition(target, limited_strength_table)["cost"] ) # the following are taken from Fig 14 of the XX synthesis paper self.assertAlmostEqual(mean(clever_costs), 1.445e-2, delta=5e-3) self.assertAlmostEqual(mean(naive_costs), 2.058e-2, delta=5e-3) def test_error_on_empty_basis_fidelity(self): """Test synthesizing entangling gate with no entangling basis fails.""" decomposer = XXDecomposer(basis_fidelity={}) qc = QuantumCircuit(2) qc.cx(0, 1) mat = Operator(qc).to_matrix() with self.assertRaisesRegex( qiskit.exceptions.QiskitError, "Attempting to synthesize entangling gate with no controlled gates in basis set.", ): decomposer(mat) def test_no_error_on_empty_basis_fidelity_trivial_target(self): """Test synthesizing non-entangling gate with no entangling basis succeeds.""" decomposer = XXDecomposer(basis_fidelity={}) qc = QuantumCircuit(2) qc.x(0) qc.y(1) mat = Operator(qc).to_matrix() dqc = decomposer(mat) self.assertTrue(np.allclose(mat, Operator(dqc).to_matrix()))
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# 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 preset pass managers with 1Q backend""" from test import combine from ddt import ddt from qiskit import QuantumCircuit from qiskit.compiler import transpile from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider import Fake1Q from qiskit.transpiler import TranspilerError def emptycircuit(): """Empty circuit""" return QuantumCircuit() def circuit_3516(): """Circuit from https://github.com/Qiskit/qiskit-terra/issues/3516 should fail""" circuit = QuantumCircuit(2, 1) circuit.h(0) circuit.ry(0.11, 1) circuit.measure([0], [0]) return circuit @ddt class Test1QFailing(QiskitTestCase): """1Q tests that should fail.""" @combine( circuit=[circuit_3516], level=[0, 1, 2, 3], dsc="Transpiling {circuit.__name__} at level {level} should fail", name="{circuit.__name__}_level{level}_fail", ) def test(self, circuit, level): """All the levels with all the 1Q backend""" with self.assertRaises(TranspilerError): transpile(circuit(), backend=Fake1Q(), optimization_level=level, seed_transpiler=42) @ddt class Test1QWorking(QiskitTestCase): """1Q tests that should work.""" @combine( circuit=[emptycircuit], level=[0, 1, 2, 3], dsc="Transpiling {circuit.__name__} at level {level} should work", name="{circuit.__name__}_level{level}_valid", ) def test_device(self, circuit, level): """All the levels with all the 1Q backend""" result = transpile( circuit(), backend=Fake1Q(), optimization_level=level, seed_transpiler=42 ) self.assertIsInstance(result, QuantumCircuit) @combine( circuit=[circuit_3516], level=[0, 1, 2, 3], dsc="Transpiling {circuit.__name__} at level {level} should work for simulator", name="{circuit.__name__}_level{level}_valid", ) def test_simulator(self, circuit, level): """All the levels with all the 1Q simulator backend""" # Set fake backend config to simulator backend = Fake1Q() backend._configuration.simulator = True result = transpile(circuit(), backend=backend, optimization_level=level, seed_transpiler=42) self.assertIsInstance(result, QuantumCircuit)
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# 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 MergeAdjacentBarriers pass""" import random import unittest from qiskit.transpiler.passes import MergeAdjacentBarriers from qiskit.converters import circuit_to_dag from qiskit import QuantumRegister, QuantumCircuit from qiskit.test import QiskitTestCase class TestMergeAdjacentBarriers(QiskitTestCase): """Test the MergeAdjacentBarriers pass""" def test_two_identical_barriers(self): """Merges two barriers that are identical into one β–‘ β–‘ β–‘ q_0: |0>─░──░─ -> q_0: |0>─░─ β–‘ β–‘ β–‘ """ qr = QuantumRegister(1, "q") circuit = QuantumCircuit(qr) circuit.barrier(qr) circuit.barrier(qr) expected = QuantumCircuit(qr) expected.barrier(qr) pass_ = MergeAdjacentBarriers() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_numerous_identical_barriers(self): """Merges 5 identical barriers in a row into one β–‘ β–‘ β–‘ β–‘ β–‘ β–‘ β–‘ q_0: |0>─░──░──░──░──░──░─ -> q_0: |0>─░─ β–‘ β–‘ β–‘ β–‘ β–‘ β–‘ β–‘ """ qr = QuantumRegister(1, "q") circuit = QuantumCircuit(qr) circuit.barrier(qr) circuit.barrier(qr) circuit.barrier(qr) circuit.barrier(qr) circuit.barrier(qr) circuit.barrier(qr) expected = QuantumCircuit(qr) expected.barrier(qr) expected = QuantumCircuit(qr) expected.barrier(qr) pass_ = MergeAdjacentBarriers() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_barriers_of_different_sizes(self): """Test two barriers of different sizes are merged into one β–‘ β–‘ β–‘ q_0: |0>─░──░─ q_0: |0>─░─ β–‘ β–‘ -> β–‘ q_1: |0>────░─ q_1: |0>─░─ β–‘ β–‘ """ qr = QuantumRegister(2, "q") circuit = QuantumCircuit(qr) circuit.barrier(qr[0]) circuit.barrier(qr) expected = QuantumCircuit(qr) expected.barrier(qr) pass_ = MergeAdjacentBarriers() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_not_overlapping_barriers(self): """Test two barriers with no overlap are not merged (NB in these pictures they look like 1 barrier but they are actually 2 distinct barriers, this is just how the text drawer draws them) β–‘ β–‘ q_0: |0>─░─ q_0: |0>─░─ β–‘ -> β–‘ q_1: |0>─░─ q_1: |0>─░─ β–‘ β–‘ """ qr = QuantumRegister(2, "q") circuit = QuantumCircuit(qr) circuit.barrier(qr[0]) circuit.barrier(qr[1]) expected = QuantumCircuit(qr) expected.barrier(qr[0]) expected.barrier(qr[1]) pass_ = MergeAdjacentBarriers() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_barriers_with_obstacle_before(self): """Test with an obstacle before the larger barrier β–‘ β–‘ β–‘ q_0: |0>──░───░─ q_0: |0>──────░─ β”Œβ”€β”€β”€β” β–‘ -> β”Œβ”€β”€β”€β” β–‘ q_1: |0>─ H β”œβ”€β–‘β”€ q_1: |0>─ H β”œβ”€β–‘β”€ β””β”€β”€β”€β”˜ β–‘ β””β”€β”€β”€β”˜ β–‘ """ qr = QuantumRegister(2, "q") circuit = QuantumCircuit(qr) circuit.barrier(qr[0]) circuit.h(qr[1]) circuit.barrier(qr) expected = QuantumCircuit(qr) expected.h(qr[1]) expected.barrier(qr) pass_ = MergeAdjacentBarriers() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_barriers_with_obstacle_after(self): """Test with an obstacle after the larger barrier β–‘ β–‘ β–‘ q_0: |0>─░───░── q_0: |0>─░────── β–‘ β”Œβ”€β”€β”€β” -> β–‘ β”Œβ”€β”€β”€β” q_1: |0>─░── H β”œ q_1: |0>─░── H β”œ β–‘ β””β”€β”€β”€β”˜ β–‘ β””β”€β”€β”€β”˜ """ qr = QuantumRegister(2, "q") circuit = QuantumCircuit(qr) circuit.barrier(qr) circuit.barrier(qr[0]) circuit.h(qr[1]) expected = QuantumCircuit(qr) expected.barrier(qr) expected.h(qr[1]) pass_ = MergeAdjacentBarriers() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_barriers_with_blocking_obstacle(self): """Test that barriers don't merge if there is an obstacle that is blocking β–‘ β”Œβ”€β”€β”€β” β–‘ β–‘ β”Œβ”€β”€β”€β” β–‘ q_0: |0>─░── H β”œβ”€β–‘β”€ -> q_0: |0>─░── H β”œβ”€β–‘β”€ β–‘ β””β”€β”€β”€β”˜ β–‘ β–‘ β””β”€β”€β”€β”˜ β–‘ """ qr = QuantumRegister(1, "q") circuit = QuantumCircuit(qr) circuit.barrier(qr) circuit.h(qr) circuit.barrier(qr) expected = QuantumCircuit(qr) expected.barrier(qr) expected.h(qr) expected.barrier(qr) pass_ = MergeAdjacentBarriers() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_barriers_with_blocking_obstacle_long(self): """Test that barriers don't merge if there is an obstacle that is blocking β–‘ β”Œβ”€β”€β”€β” β–‘ β–‘ β”Œβ”€β”€β”€β” β–‘ q_0: |0>─░── H β”œβ”€β–‘β”€ q_0: |0>─░── H β”œβ”€β–‘β”€ β–‘ β””β”€β”€β”€β”˜ β–‘ -> β–‘ β””β”€β”€β”€β”˜ β–‘ q_1: |0>─────────░─ q_1: |0>─────────░─ β–‘ β–‘ """ qr = QuantumRegister(2, "q") circuit = QuantumCircuit(qr) circuit.barrier(qr[0]) circuit.h(qr[0]) circuit.barrier(qr) expected = QuantumCircuit(qr) expected.barrier(qr[0]) expected.h(qr[0]) expected.barrier(qr) pass_ = MergeAdjacentBarriers() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_barriers_with_blocking_obstacle_narrow(self): """Test that barriers don't merge if there is an obstacle that is blocking β–‘ β”Œβ”€β”€β”€β” β–‘ β–‘ β”Œβ”€β”€β”€β” β–‘ q_0: |0>─░── H β”œβ”€β–‘β”€ q_0: |0>─░── H β”œβ”€β–‘β”€ β–‘ β””β”€β”€β”€β”˜ β–‘ -> β–‘ β””β”€β”€β”€β”˜ β–‘ q_1: |0>─░───────░─ q_1: |0>─░───────░─ β–‘ β–‘ β–‘ β–‘ """ qr = QuantumRegister(2, "q") circuit = QuantumCircuit(qr) circuit.barrier(qr) circuit.h(qr[0]) circuit.barrier(qr) expected = QuantumCircuit(qr) expected.barrier(qr) expected.h(qr[0]) expected.barrier(qr) pass_ = MergeAdjacentBarriers() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_barriers_with_blocking_obstacle_twoQ(self): """Test that barriers don't merge if there is an obstacle that is blocking β–‘ β–‘ β–‘ β–‘ q_0: |0>─░───────░─ q_0: |0>─░───────░─ β–‘ β–‘ β–‘ β–‘ q_1: |0>─░───■───── -> q_1: |0>─░───■───── β–‘ β”Œβ”€β”΄β”€β” β–‘ β–‘ β”Œβ”€β”΄β”€β” β–‘ q_2: |0>──── X β”œβ”€β–‘β”€ q_2: |0>──── X β”œβ”€β–‘β”€ β””β”€β”€β”€β”˜ β–‘ β””β”€β”€β”€β”˜ β–‘ """ qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.barrier(0, 1) circuit.cx(1, 2) circuit.barrier(0, 2) expected = QuantumCircuit(qr) expected.barrier(0, 1) expected.cx(1, 2) expected.barrier(0, 2) pass_ = MergeAdjacentBarriers() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_output_deterministic(self): """Test that the output barriers have a deterministic ordering (independent of PYTHONHASHSEED). This is important to guarantee that any subsequent topological iterations through the circuit are also deterministic; it's in general not possible for all transpiler passes to produce identical outputs across all valid topological orderings, especially if those passes have some stochastic element.""" order = list(range(20)) random.Random(2023_02_10).shuffle(order) circuit = QuantumCircuit(20) circuit.barrier([5, 2, 3]) circuit.barrier([7, 11, 14, 2, 4]) circuit.barrier(order) # All the barriers should get merged together. expected = QuantumCircuit(20) expected.barrier(range(20)) output = MergeAdjacentBarriers()(circuit) self.assertEqual(expected, output) # This assertion is that the ordering of the arguments in the barrier is fixed. self.assertEqual(list(output.data[0].qubits), list(output.qubits)) if __name__ == "__main__": unittest.main()
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# 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 BasicSwap pass""" import unittest from qiskit.transpiler.passes import BasicSwap from qiskit.transpiler.passmanager import PassManager from qiskit.transpiler.layout import Layout from qiskit.transpiler import CouplingMap, Target from qiskit.circuit.library import CXGate from qiskit.converters import circuit_to_dag from qiskit import QuantumRegister, QuantumCircuit from qiskit.test import QiskitTestCase class TestBasicSwap(QiskitTestCase): """Tests the BasicSwap pass.""" def test_trivial_case(self): """No need to have any swap, the CX are distance 1 to each other q0:--(+)-[U]-(+)- | | q1:---.-------|-- | q2:-----------.-- CouplingMap 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_ = BasicSwap(coupling) after = pass_.run(dag) self.assertEqual(dag, after) def test_trivial_in_same_layer(self): """No need to have any swap, two CXs distance 1 to each other, in the same layer q0:--(+)-- | q1:---.--- q2:--(+)-- | q3:---.--- CouplingMap 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_ = BasicSwap(coupling) after = pass_.run(dag) self.assertEqual(dag, after) def test_a_single_swap(self): """Adding a swap q0:------- q1:--(+)-- | q2:---.--- CouplingMap map: [1]--[0]--[2] q0:--X---.--- | | q1:--X---|--- | q2:-----(+)-- """ coupling = CouplingMap([[0, 1], [0, 2]]) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[2]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr) expected.swap(qr[1], qr[0]) expected.cx(qr[0], qr[2]) pass_ = BasicSwap(coupling) after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_a_single_swap_with_target(self): """Adding a swap q0:------- q1:--(+)-- | q2:---.--- CouplingMap map: [1]--[0]--[2] q0:--X---.--- | | q1:--X---|--- | q2:-----(+)-- """ target = Target() target.add_instruction(CXGate(), {(0, 1): None, (0, 2): None}) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[2]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr) expected.swap(qr[1], qr[0]) expected.cx(qr[0], qr[2]) pass_ = BasicSwap(target) after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_a_single_swap_bigger_cm(self): """Swapper in a bigger coupling map q0:------- q1:---.--- | q2:--(+)-- CouplingMap map: [1]--[0]--[2]--[3] q0:--X---.--- | | q1:--X---|--- | q2:-----(+)-- """ coupling = CouplingMap([[0, 1], [0, 2], [2, 3]]) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[2]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr) expected.swap(qr[1], qr[0]) expected.cx(qr[0], qr[2]) pass_ = BasicSwap(coupling) after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_keep_layout(self): """After a swap, the following gates also change the wires. qr0:---.---[H]-- | qr1:---|-------- | qr2:--(+)------- CouplingMap map: [0]--[1]--[2] qr0:--X----------- | qr1:--X---.--[H]-- | qr2:-----(+)------ """ 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) expected = QuantumCircuit(qr) expected.swap(qr[0], qr[1]) expected.cx(qr[1], qr[2]) expected.h(qr[1]) pass_ = BasicSwap(coupling) after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_far_swap(self): """A far swap that affects coming CXs. qr0:--(+)---.-- | | qr1:---|----|-- | | qr2:---|----|-- | | qr3:---.---(+)- CouplingMap map: [0]--[1]--[2]--[3] qr0:--X-------------- | qr1:--X--X----------- | qr2:-----X--(+)---.-- | | qr3:---------.---(+)- """ 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) expected = QuantumCircuit(qr) expected.swap(qr[0], qr[1]) expected.swap(qr[1], qr[2]) expected.cx(qr[2], qr[3]) expected.cx(qr[3], qr[2]) pass_ = BasicSwap(coupling) after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_far_swap_with_gate_the_front(self): """A far swap with a gate in the front. q0:------(+)-- | q1:-------|--- | q2:-------|--- | q3:--[H]--.--- CouplingMap map: [0]--[1]--[2]--[3] q0:-----------(+)-- | q1:---------X--.--- | q2:------X--X------ | q3:-[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) expected = QuantumCircuit(qr) expected.h(qr[3]) expected.swap(qr[3], qr[2]) expected.swap(qr[2], qr[1]) expected.cx(qr[1], qr[0]) pass_ = BasicSwap(coupling) after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_far_swap_with_gate_the_back(self): """A far swap with a gate in the back. q0:--(+)------ | q1:---|------- | q2:---|------- | q3:---.--[H]-- CouplingMap map: [0]--[1]--[2]--[3] q0:-------(+)------ | q1:-----X--.--[H]-- | q2:--X--X---------- | q3:--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) expected = QuantumCircuit(qr) expected.swap(qr[3], qr[2]) expected.swap(qr[2], qr[1]) expected.cx(qr[1], qr[0]) expected.h(qr[1]) pass_ = BasicSwap(coupling) after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_far_swap_with_gate_the_middle(self): """A far swap with a gate in the middle. q0:--(+)-------.-- | | q1:---|--------|-- | q2:---|--------|-- | | q3:---.--[H]--(+)- CouplingMap map: [0]--[1]--[2]--[3] q0:-------(+)-------.--- | | q1:-----X--.--[H]--(+)-- | q2:--X--X--------------- | q3:--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]) circuit.cx(qr[0], qr[3]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr) expected.swap(qr[3], qr[2]) expected.swap(qr[2], qr[1]) expected.cx(qr[1], qr[0]) expected.h(qr[1]) expected.cx(qr[0], qr[1]) pass_ = BasicSwap(coupling) after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_fake_run(self): """A fake run, doesn't change dag q0:--(+)-------.-- | | q1:---|--------|-- | q2:---|--------|-- | | q3:---.--[H]--(+)- CouplingMap map: [0]--[1]--[2]--[3] q0:-------(+)-------.--- | | q1:-----X--.--[H]--(+)-- | q2:--X--X--------------- | q3:--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]) circuit.cx(qr[0], qr[3]) fake_pm = PassManager([BasicSwap(coupling, fake_run=True)]) real_pm = PassManager([BasicSwap(coupling, fake_run=False)]) self.assertEqual(circuit, fake_pm.run(circuit)) self.assertNotEqual(circuit, real_pm.run(circuit)) self.assertIsInstance(fake_pm.property_set["final_layout"], Layout) self.assertEqual(fake_pm.property_set["final_layout"], real_pm.property_set["final_layout"]) if __name__ == "__main__": unittest.main()
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# 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 BasisTranslator pass""" import os from numpy import pi from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import transpile from qiskit.test import QiskitTestCase from qiskit.circuit import Gate, Parameter, EquivalenceLibrary, Qubit, Clbit from qiskit.circuit.library import ( U1Gate, U2Gate, U3Gate, CU1Gate, CU3Gate, UGate, RZGate, XGate, SXGate, CXGate, ) from qiskit.converters import circuit_to_dag, dag_to_circuit, circuit_to_instruction from qiskit.exceptions import QiskitError from qiskit.quantum_info import Operator from qiskit.transpiler.target import Target, InstructionProperties from qiskit.transpiler.exceptions import TranspilerError from qiskit.transpiler.passes.basis import BasisTranslator, UnrollCustomDefinitions from qiskit.circuit.library.standard_gates.equivalence_library import ( StandardEquivalenceLibrary as std_eqlib, ) class OneQubitZeroParamGate(Gate): """Mock one qubit zero param gate.""" def __init__(self, name="1q0p"): super().__init__(name, 1, []) class OneQubitOneParamGate(Gate): """Mock one qubit one param gate.""" def __init__(self, theta, name="1q1p"): super().__init__(name, 1, [theta]) class OneQubitOneParamPrimeGate(Gate): """Mock one qubit one param gate.""" def __init__(self, alpha): super().__init__("1q1p_prime", 1, [alpha]) class OneQubitTwoParamGate(Gate): """Mock one qubit two param gate.""" def __init__(self, phi, lam, name="1q2p"): super().__init__(name, 1, [phi, lam]) class TwoQubitZeroParamGate(Gate): """Mock one qubit zero param gate.""" def __init__(self, name="2q0p"): super().__init__(name, 2, []) class VariadicZeroParamGate(Gate): """Mock variadic zero param gate.""" def __init__(self, num_qubits, name="vq0p"): super().__init__(name, num_qubits, []) class TestBasisTranslator(QiskitTestCase): """Test the BasisTranslator pass.""" def test_circ_in_basis_no_op(self): """Verify we don't change a circuit already in the target basis.""" eq_lib = EquivalenceLibrary() qc = QuantumCircuit(1) qc.append(OneQubitZeroParamGate(), [0]) dag = circuit_to_dag(qc) expected = circuit_to_dag(qc) pass_ = BasisTranslator(eq_lib, ["1q0p"]) actual = pass_.run(dag) self.assertEqual(actual, expected) def test_raise_if_target_basis_unreachable(self): """Verify we raise if the circuit cannot be transformed to the target.""" eq_lib = EquivalenceLibrary() qc = QuantumCircuit(1) qc.append(OneQubitZeroParamGate(), [0]) dag = circuit_to_dag(qc) pass_ = BasisTranslator(eq_lib, ["1q1p"]) with self.assertRaises(TranspilerError): pass_.run(dag) def test_single_substitution(self): """Verify we correctly unroll gates through a single equivalence.""" eq_lib = EquivalenceLibrary() gate = OneQubitZeroParamGate() equiv = QuantumCircuit(1) equiv.append(OneQubitOneParamGate(pi), [0]) eq_lib.add_equivalence(gate, equiv) qc = QuantumCircuit(1) qc.append(OneQubitZeroParamGate(), [0]) dag = circuit_to_dag(qc) expected = QuantumCircuit(1) expected.append(OneQubitOneParamGate(pi), [0]) expected_dag = circuit_to_dag(expected) pass_ = BasisTranslator(eq_lib, ["1q1p"]) actual = pass_.run(dag) self.assertEqual(actual, expected_dag) def test_double_substitution(self): """Verify we correctly unroll gates through multiple equivalences.""" eq_lib = EquivalenceLibrary() gate = OneQubitZeroParamGate() equiv = QuantumCircuit(1) equiv.append(OneQubitOneParamGate(pi), [0]) eq_lib.add_equivalence(gate, equiv) theta = Parameter("theta") gate = OneQubitOneParamGate(theta) equiv = QuantumCircuit(1) equiv.append(OneQubitTwoParamGate(theta, pi / 2), [0]) eq_lib.add_equivalence(gate, equiv) qc = QuantumCircuit(1) qc.append(OneQubitZeroParamGate(), [0]) dag = circuit_to_dag(qc) expected = QuantumCircuit(1) expected.append(OneQubitTwoParamGate(pi, pi / 2), [0]) expected_dag = circuit_to_dag(expected) pass_ = BasisTranslator(eq_lib, ["1q2p"]) actual = pass_.run(dag) self.assertEqual(actual, expected_dag) def test_single_substitution_with_global_phase(self): """Verify we correctly unroll gates through a single equivalence with global phase.""" eq_lib = EquivalenceLibrary() gate = OneQubitZeroParamGate() equiv = QuantumCircuit(1, global_phase=0.2) equiv.append(OneQubitOneParamGate(pi), [0]) eq_lib.add_equivalence(gate, equiv) qc = QuantumCircuit(1, global_phase=0.1) qc.append(OneQubitZeroParamGate(), [0]) dag = circuit_to_dag(qc) expected = QuantumCircuit(1, global_phase=0.1 + 0.2) expected.append(OneQubitOneParamGate(pi), [0]) expected_dag = circuit_to_dag(expected) pass_ = BasisTranslator(eq_lib, ["1q1p"]) actual = pass_.run(dag) self.assertEqual(actual, expected_dag) def test_single_two_gate_substitution_with_global_phase(self): """Verify we correctly unroll gates through a single equivalence with global phase.""" eq_lib = EquivalenceLibrary() gate = OneQubitZeroParamGate() equiv = QuantumCircuit(1, global_phase=0.2) equiv.append(OneQubitOneParamGate(pi), [0]) equiv.append(OneQubitOneParamGate(pi), [0]) eq_lib.add_equivalence(gate, equiv) qc = QuantumCircuit(1, global_phase=0.1) qc.append(OneQubitZeroParamGate(), [0]) dag = circuit_to_dag(qc) expected = QuantumCircuit(1, global_phase=0.1 + 0.2) expected.append(OneQubitOneParamGate(pi), [0]) expected.append(OneQubitOneParamGate(pi), [0]) expected_dag = circuit_to_dag(expected) pass_ = BasisTranslator(eq_lib, ["1q1p"]) actual = pass_.run(dag) self.assertEqual(actual, expected_dag) def test_two_substitutions_with_global_phase(self): """Verify we correctly unroll gates through a single equivalences with global phase.""" eq_lib = EquivalenceLibrary() gate = OneQubitZeroParamGate() equiv = QuantumCircuit(1, global_phase=0.2) equiv.append(OneQubitOneParamGate(pi), [0]) eq_lib.add_equivalence(gate, equiv) qc = QuantumCircuit(1, global_phase=0.1) qc.append(OneQubitZeroParamGate(), [0]) qc.append(OneQubitZeroParamGate(), [0]) dag = circuit_to_dag(qc) expected = QuantumCircuit(1, global_phase=0.1 + 2 * 0.2) expected.append(OneQubitOneParamGate(pi), [0]) expected.append(OneQubitOneParamGate(pi), [0]) expected_dag = circuit_to_dag(expected) pass_ = BasisTranslator(eq_lib, ["1q1p"]) actual = pass_.run(dag) self.assertEqual(actual, expected_dag) def test_two_single_two_gate_substitutions_with_global_phase(self): """Verify we correctly unroll gates through a single equivalence with global phase.""" eq_lib = EquivalenceLibrary() gate = OneQubitZeroParamGate() equiv = QuantumCircuit(1, global_phase=0.2) equiv.append(OneQubitOneParamGate(pi), [0]) equiv.append(OneQubitOneParamGate(pi), [0]) eq_lib.add_equivalence(gate, equiv) qc = QuantumCircuit(1, global_phase=0.1) qc.append(OneQubitZeroParamGate(), [0]) qc.append(OneQubitZeroParamGate(), [0]) dag = circuit_to_dag(qc) expected = QuantumCircuit(1, global_phase=0.1 + 2 * 0.2) expected.append(OneQubitOneParamGate(pi), [0]) expected.append(OneQubitOneParamGate(pi), [0]) expected.append(OneQubitOneParamGate(pi), [0]) expected.append(OneQubitOneParamGate(pi), [0]) expected_dag = circuit_to_dag(expected) pass_ = BasisTranslator(eq_lib, ["1q1p"]) actual = pass_.run(dag) self.assertEqual(actual, expected_dag) def test_double_substitution_with_global_phase(self): """Verify we correctly unroll gates through multiple equivalences with global phase.""" eq_lib = EquivalenceLibrary() gate = OneQubitZeroParamGate() equiv = QuantumCircuit(1, global_phase=0.2) equiv.append(OneQubitOneParamGate(pi), [0]) eq_lib.add_equivalence(gate, equiv) theta = Parameter("theta") gate = OneQubitOneParamGate(theta) equiv = QuantumCircuit(1, global_phase=0.4) equiv.append(OneQubitTwoParamGate(theta, pi / 2), [0]) eq_lib.add_equivalence(gate, equiv) qc = QuantumCircuit(1, global_phase=0.1) qc.append(OneQubitZeroParamGate(), [0]) dag = circuit_to_dag(qc) expected = QuantumCircuit(1, global_phase=0.1 + 0.2 + 0.4) expected.append(OneQubitTwoParamGate(pi, pi / 2), [0]) expected_dag = circuit_to_dag(expected) pass_ = BasisTranslator(eq_lib, ["1q2p"]) actual = pass_.run(dag) self.assertEqual(actual, expected_dag) def test_multiple_variadic(self): """Verify circuit with multiple instances of variadic gate.""" eq_lib = EquivalenceLibrary() # e.g. MSGate oneq_gate = VariadicZeroParamGate(1) equiv = QuantumCircuit(1) equiv.append(OneQubitZeroParamGate(), [0]) eq_lib.add_equivalence(oneq_gate, equiv) twoq_gate = VariadicZeroParamGate(2) equiv = QuantumCircuit(2) equiv.append(TwoQubitZeroParamGate(), [0, 1]) eq_lib.add_equivalence(twoq_gate, equiv) qc = QuantumCircuit(2) qc.append(VariadicZeroParamGate(1), [0]) qc.append(VariadicZeroParamGate(2), [0, 1]) dag = circuit_to_dag(qc) expected = QuantumCircuit(2) expected.append(OneQubitZeroParamGate(), [0]) expected.append(TwoQubitZeroParamGate(), [0, 1]) expected_dag = circuit_to_dag(expected) pass_ = BasisTranslator(eq_lib, ["1q0p", "2q0p"]) actual = pass_.run(dag) self.assertEqual(actual, expected_dag) def test_diamond_path(self): """Verify we find a path when there are multiple paths to the target basis.""" eq_lib = EquivalenceLibrary() # Path 1: 1q0p -> 1q1p(pi) -> 1q2p(pi, pi/2) gate = OneQubitZeroParamGate() equiv = QuantumCircuit(1) equiv.append(OneQubitOneParamGate(pi), [0]) eq_lib.add_equivalence(gate, equiv) theta = Parameter("theta") gate = OneQubitOneParamGate(theta) equiv = QuantumCircuit(1) equiv.append(OneQubitTwoParamGate(theta, pi / 2), [0]) eq_lib.add_equivalence(gate, equiv) # Path 2: 1q0p -> 1q1p_prime(pi/2) -> 1q2p(2 * pi/2, pi/2) gate = OneQubitZeroParamGate() equiv = QuantumCircuit(1) equiv.append(OneQubitOneParamPrimeGate(pi / 2), [0]) eq_lib.add_equivalence(gate, equiv) alpha = Parameter("alpha") gate = OneQubitOneParamPrimeGate(alpha) equiv = QuantumCircuit(1) equiv.append(OneQubitTwoParamGate(2 * alpha, pi / 2), [0]) eq_lib.add_equivalence(gate, equiv) qc = QuantumCircuit(1) qc.append(OneQubitZeroParamGate(), [0]) dag = circuit_to_dag(qc) expected = QuantumCircuit(1) expected.append(OneQubitTwoParamGate(pi, pi / 2), [0]) expected_dag = circuit_to_dag(expected) pass_ = BasisTranslator(eq_lib, ["1q2p"]) actual = pass_.run(dag) self.assertEqual(actual, expected_dag) def test_if_else(self): """Test a simple if-else with parameters.""" qubits = [Qubit(), Qubit()] clbits = [Clbit(), Clbit()] alpha = Parameter("alpha") beta = Parameter("beta") gate = OneQubitOneParamGate(alpha) equiv = QuantumCircuit([qubits[0]]) equiv.append(OneQubitZeroParamGate(name="1q0p_2"), [qubits[0]]) equiv.append(OneQubitOneParamGate(alpha, name="1q1p_2"), [qubits[0]]) eq_lib = EquivalenceLibrary() eq_lib.add_equivalence(gate, equiv) circ = QuantumCircuit(qubits, clbits) circ.append(OneQubitOneParamGate(beta), [qubits[0]]) circ.measure(qubits[0], clbits[1]) with circ.if_test((clbits[1], 0)) as else_: circ.append(OneQubitOneParamGate(alpha), [qubits[0]]) circ.append(TwoQubitZeroParamGate(), qubits) with else_: circ.append(TwoQubitZeroParamGate(), [qubits[1], qubits[0]]) dag = circuit_to_dag(circ) dag_translated = BasisTranslator(eq_lib, ["if_else", "1q0p_2", "1q1p_2", "2q0p"]).run(dag) expected = QuantumCircuit(qubits, clbits) expected.append(OneQubitZeroParamGate(name="1q0p_2"), [qubits[0]]) expected.append(OneQubitOneParamGate(beta, name="1q1p_2"), [qubits[0]]) expected.measure(qubits[0], clbits[1]) with expected.if_test((clbits[1], 0)) as else_: expected.append(OneQubitZeroParamGate(name="1q0p_2"), [qubits[0]]) expected.append(OneQubitOneParamGate(alpha, name="1q1p_2"), [qubits[0]]) expected.append(TwoQubitZeroParamGate(), qubits) with else_: expected.append(TwoQubitZeroParamGate(), [qubits[1], qubits[0]]) dag_expected = circuit_to_dag(expected) self.assertEqual(dag_translated, dag_expected) def test_nested_loop(self): """Test a simple if-else with parameters.""" qubits = [Qubit(), Qubit()] clbits = [Clbit(), Clbit()] cr = ClassicalRegister(bits=clbits) index1 = Parameter("index1") alpha = Parameter("alpha") gate = OneQubitOneParamGate(alpha) equiv = QuantumCircuit([qubits[0]]) equiv.append(OneQubitZeroParamGate(name="1q0p_2"), [qubits[0]]) equiv.append(OneQubitOneParamGate(alpha, name="1q1p_2"), [qubits[0]]) eq_lib = EquivalenceLibrary() eq_lib.add_equivalence(gate, equiv) circ = QuantumCircuit(qubits, cr) with circ.for_loop(range(3), loop_parameter=index1) as ind: with circ.while_loop((cr, 0)): circ.append(OneQubitOneParamGate(alpha * ind), [qubits[0]]) dag = circuit_to_dag(circ) dag_translated = BasisTranslator( eq_lib, ["if_else", "for_loop", "while_loop", "1q0p_2", "1q1p_2"] ).run(dag) expected = QuantumCircuit(qubits, cr) with expected.for_loop(range(3), loop_parameter=index1) as ind: with expected.while_loop((cr, 0)): expected.append(OneQubitZeroParamGate(name="1q0p_2"), [qubits[0]]) expected.append(OneQubitOneParamGate(alpha * ind, name="1q1p_2"), [qubits[0]]) dag_expected = circuit_to_dag(expected) self.assertEqual(dag_translated, dag_expected) def test_different_bits(self): """Test that the basis translator correctly works when the inner blocks of control-flow operations are not over the same bits as the outer blocks.""" base = QuantumCircuit([Qubit() for _ in [None] * 4], [Clbit()]) for_body = QuantumCircuit([Qubit(), Qubit()]) for_body.h(0) for_body.cz(0, 1) base.for_loop((1,), None, for_body, [1, 2], []) while_body = QuantumCircuit([Qubit(), Qubit(), Clbit()]) while_body.cz(0, 1) true_body = QuantumCircuit([Qubit(), Qubit(), Clbit()]) true_body.measure(0, 0) true_body.while_loop((0, True), while_body, [0, 1], [0]) false_body = QuantumCircuit([Qubit(), Qubit(), Clbit()]) false_body.cz(0, 1) base.if_else((0, True), true_body, false_body, [0, 3], [0]) basis = {"rz", "sx", "cx", "for_loop", "if_else", "while_loop", "measure"} out = BasisTranslator(std_eqlib, basis).run(circuit_to_dag(base)) self.assertEqual(set(out.count_ops(recurse=True)), basis) class TestUnrollerCompatability(QiskitTestCase): """Tests backward compatability with the Unroller pass. Duplicate of TestUnroller from test.python.transpiler.test_unroller with Unroller replaced by UnrollCustomDefinitions -> BasisTranslator. """ 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_ = UnrollCustomDefinitions(std_eqlib, ["u2"]) dag = pass_.run(dag) pass_ = BasisTranslator(std_eqlib, ["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_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_ = UnrollCustomDefinitions(std_eqlib, ["h", "t", "tdg", "cx"]) dag = pass_.run(dag) pass_ = BasisTranslator(std_eqlib, ["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: ─ H β”œβ”€ Tdg β”œβ”€ Z β”œβ”€ T β”œβ”€ Ry(0.5) β”œβ”€ Rz(0.3) β”œβ”€ Rx(0.1) β”œβ”€Mβ”œβ”€β”€ X β”œβ”€β”€β”€ Y β”œβ”€Β» # β””β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”˜β””β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β””β•₯β”˜ └─β•₯β”€β”˜ └─β•₯β”€β”˜ Β» # β•‘ β”Œβ”€β”€β•¨β”€β”€β”β”Œβ”€β”€β•¨β”€β”€β”Β» # cr: 1/══════════════════════════════════════════════════════╩═║ 0x1 β•žβ•‘ 0x1 β•žΒ» # 0 β””β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”˜Β» # Β« β”Œβ”€β”€β”€β” # Β« qr: ── Z β”œβ”€ # Β« └─β•₯β”€β”˜ # Β« β”Œβ”€β”€β•¨β”€β”€β” # Β«cr: 1/β•‘ 0x1 β•ž # Β« β””β”€β”€β”€β”€β”€β”˜ 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_ = UnrollCustomDefinitions(std_eqlib, ["u1", "u2", "u3"]) dag = pass_.run(dag) pass_ = BasisTranslator(std_eqlib, ["u1", "u2", "u3"]) unrolled_dag = pass_.run(dag) # Pick up -1 * 0.3 / 2 global phase for one RZ -> U1. # # global phase: 6.1332 # β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β”Œβ”€β”€β”€β”€β”€β”€β”€β”β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”Β» # qr: ─ U2(0,Ο€) β”œβ”€ U1(-Ο€/4) β”œβ”€ U1(Ο€) β”œβ”€ U1(Ο€/4) β”œβ”€ U3(0.5,0,0) β”œβ”€ U1(0.3) β”œΒ» # β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜Β» # cr: 1/═══════════════════════════════════════════════════════════════════» # Β» # Β« β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β”Œβ”€β”β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β”Œβ”€β”€β”€β”€β”€β”€β”€β” # Β« qr: ─ U3(0.1,-Ο€/2,Ο€/2) β”œβ”€Mβ”œβ”€ U3(Ο€,0,Ο€) β”œβ”€ U3(Ο€,Ο€/2,Ο€/2) β”œβ”€ U1(Ο€) β”œ # Β« β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β””β•₯β”˜β””β”€β”€β”€β”€β”€β•₯β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”€β”€β•₯β”€β”€β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β•₯β”€β”€β”€β”˜ # Β« β•‘ β”Œβ”€β”€β•¨β”€β”€β” β”Œβ”€β”€β•¨β”€β”€β” β”Œβ”€β”€β•¨β”€β”€β” # Β«cr: 1/═════════════════════╩════║ 0x1 β•žβ•β•β•β•β•β•β•β•β•‘ 0x1 β•žβ•β•β•β•β•β•β•‘ 0x1 β•žβ• # Β« 0 β””β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”˜ 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_ = UnrollCustomDefinitions(std_eqlib, []) dag = pass_.run(dag) pass_ = BasisTranslator(std_eqlib, []) with self.assertRaises(QiskitError): pass_.run(dag) def test_unroll_all_instructions(self): """Test unrolling a circuit containing all standard instructions.""" qr = QuantumRegister(3, "qr") cr = ClassicalRegister(3, "cr") circuit = QuantumCircuit(qr, cr) circuit.crx(0.5, qr[1], qr[2]) circuit.cry(0.5, qr[1], qr[2]) circuit.ccx(qr[0], qr[1], qr[2]) circuit.ch(qr[0], qr[2]) circuit.crz(0.5, qr[1], qr[2]) circuit.cswap(qr[1], qr[0], qr[2]) circuit.append(CU1Gate(0.1), [qr[0], qr[2]]) circuit.append(CU3Gate(0.2, 0.1, 0.0), [qr[1], qr[2]]) circuit.cx(qr[1], qr[0]) circuit.cy(qr[1], qr[2]) circuit.cz(qr[2], qr[0]) circuit.h(qr[1]) circuit.i(qr[0]) circuit.rx(0.1, qr[0]) circuit.ry(0.2, qr[1]) circuit.rz(0.3, qr[2]) circuit.rzz(0.6, qr[1], qr[0]) circuit.s(qr[0]) circuit.sdg(qr[1]) circuit.swap(qr[1], qr[2]) circuit.t(qr[2]) circuit.tdg(qr[0]) circuit.append(U1Gate(0.1), [qr[1]]) circuit.append(U2Gate(0.2, -0.1), [qr[0]]) circuit.append(U3Gate(0.3, 0.0, -0.1), [qr[2]]) circuit.x(qr[2]) circuit.y(qr[1]) circuit.z(qr[0]) # circuit.snapshot('0') # circuit.measure(qr, cr) dag = circuit_to_dag(circuit) pass_ = UnrollCustomDefinitions(std_eqlib, ["u3", "cx", "id"]) dag = pass_.run(dag) pass_ = BasisTranslator(std_eqlib, ["u3", "cx", "id"]) unrolled_dag = pass_.run(dag) ref_circuit = QuantumCircuit(qr, cr) ref_circuit.append(U3Gate(0, 0, pi / 2), [qr[2]]) ref_circuit.cx(qr[1], qr[2]) ref_circuit.append(U3Gate(-0.25, 0, 0), [qr[2]]) ref_circuit.cx(qr[1], qr[2]) ref_circuit.append(U3Gate(0.25, -pi / 2, 0), [qr[2]]) ref_circuit.append(U3Gate(0.25, 0, 0), [qr[2]]) ref_circuit.cx(qr[1], qr[2]) ref_circuit.append(U3Gate(-0.25, 0, 0), [qr[2]]) ref_circuit.cx(qr[1], qr[2]) ref_circuit.append(U3Gate(pi / 2, 0, pi), [qr[2]]) ref_circuit.cx(qr[1], qr[2]) ref_circuit.append(U3Gate(0, 0, -pi / 4), [qr[2]]) ref_circuit.cx(qr[0], qr[2]) ref_circuit.append(U3Gate(0, 0, pi / 4), [qr[2]]) ref_circuit.cx(qr[1], qr[2]) ref_circuit.append(U3Gate(0, 0, pi / 4), [qr[1]]) ref_circuit.append(U3Gate(0, 0, -pi / 4), [qr[2]]) ref_circuit.cx(qr[0], qr[2]) ref_circuit.cx(qr[0], qr[1]) ref_circuit.append(U3Gate(0, 0, pi / 4), [qr[0]]) ref_circuit.append(U3Gate(0, 0, -pi / 4), [qr[1]]) ref_circuit.cx(qr[0], qr[1]) ref_circuit.append(U3Gate(0, 0, pi / 4), [qr[2]]) ref_circuit.append(U3Gate(pi / 2, 0, pi), [qr[2]]) ref_circuit.append(U3Gate(0, 0, pi / 2), [qr[2]]) ref_circuit.append(U3Gate(pi / 2, 0, pi), [qr[2]]) ref_circuit.append(U3Gate(0, 0, pi / 4), [qr[2]]) ref_circuit.cx(qr[0], qr[2]) ref_circuit.append(U3Gate(0, 0, -pi / 4), [qr[2]]) ref_circuit.append(U3Gate(pi / 2, 0, pi), [qr[2]]) ref_circuit.append(U3Gate(0, 0, -pi / 2), [qr[2]]) ref_circuit.append(U3Gate(0, 0, 0.25), [qr[2]]) ref_circuit.cx(qr[1], qr[2]) ref_circuit.append(U3Gate(0, 0, -0.25), [qr[2]]) ref_circuit.cx(qr[1], qr[2]) ref_circuit.cx(qr[2], qr[0]) ref_circuit.append(U3Gate(pi / 2, 0, pi), [qr[2]]) ref_circuit.cx(qr[0], qr[2]) ref_circuit.append(U3Gate(0, 0, -pi / 4), [qr[2]]) ref_circuit.cx(qr[1], qr[2]) ref_circuit.append(U3Gate(0, 0, pi / 4), [qr[2]]) ref_circuit.cx(qr[0], qr[2]) ref_circuit.append(U3Gate(0, 0, pi / 4), [qr[0]]) ref_circuit.append(U3Gate(0, 0, -pi / 4), [qr[2]]) ref_circuit.cx(qr[1], qr[2]) ref_circuit.cx(qr[1], qr[0]) ref_circuit.append(U3Gate(0, 0, -pi / 4), [qr[0]]) ref_circuit.append(U3Gate(0, 0, pi / 4), [qr[1]]) ref_circuit.cx(qr[1], qr[0]) ref_circuit.append(U3Gate(0, 0, 0.05), [qr[1]]) ref_circuit.append(U3Gate(0, 0, pi / 4), [qr[2]]) ref_circuit.append(U3Gate(pi / 2, 0, pi), [qr[2]]) ref_circuit.cx(qr[2], qr[0]) ref_circuit.append(U3Gate(0, 0, 0.05), [qr[0]]) ref_circuit.cx(qr[0], qr[2]) ref_circuit.append(U3Gate(0, 0, -0.05), [qr[2]]) ref_circuit.cx(qr[0], qr[2]) ref_circuit.append(U3Gate(0, 0, 0.05), [qr[2]]) ref_circuit.append(U3Gate(0, 0, -0.05), [qr[2]]) ref_circuit.cx(qr[1], qr[2]) ref_circuit.append(U3Gate(-0.1, 0, -0.05), [qr[2]]) ref_circuit.cx(qr[1], qr[2]) ref_circuit.cx(qr[1], qr[0]) ref_circuit.append(U3Gate(pi / 2, 0, pi), [qr[0]]) ref_circuit.append(U3Gate(0.1, 0.1, 0), [qr[2]]) ref_circuit.append(U3Gate(0, 0, -pi / 2), [qr[2]]) ref_circuit.cx(qr[1], qr[2]) ref_circuit.append(U3Gate(pi / 2, 0, pi), [qr[1]]) ref_circuit.append(U3Gate(0.2, 0, 0), [qr[1]]) ref_circuit.append(U3Gate(0, 0, pi / 2), [qr[2]]) ref_circuit.cx(qr[2], qr[0]) ref_circuit.append(U3Gate(pi / 2, 0, pi), [qr[0]]) ref_circuit.i(qr[0]) ref_circuit.append(U3Gate(0.1, -pi / 2, pi / 2), [qr[0]]) ref_circuit.cx(qr[1], qr[0]) ref_circuit.append(U3Gate(0, 0, 0.6), [qr[0]]) ref_circuit.cx(qr[1], qr[0]) ref_circuit.append(U3Gate(0, 0, pi / 2), [qr[0]]) ref_circuit.append(U3Gate(0, 0, -pi / 4), [qr[0]]) ref_circuit.append(U3Gate(pi / 2, 0.2, -0.1), [qr[0]]) ref_circuit.append(U3Gate(0, 0, pi), [qr[0]]) ref_circuit.append(U3Gate(0, 0, -pi / 2), [qr[1]]) ref_circuit.append(U3Gate(0, 0, 0.3), [qr[2]]) ref_circuit.cx(qr[1], qr[2]) ref_circuit.cx(qr[2], qr[1]) ref_circuit.cx(qr[1], qr[2]) ref_circuit.append(U3Gate(0, 0, 0.1), [qr[1]]) ref_circuit.append(U3Gate(pi, pi / 2, pi / 2), [qr[1]]) ref_circuit.append(U3Gate(0, 0, pi / 4), [qr[2]]) ref_circuit.append(U3Gate(0.3, 0.0, -0.1), [qr[2]]) ref_circuit.append(U3Gate(pi, 0, pi), [qr[2]]) # ref_circuit.snapshot('0') # ref_circuit.measure(qr, cr) # ref_dag = circuit_to_dag(ref_circuit) self.assertTrue(Operator(dag_to_circuit(unrolled_dag)).equiv(ref_circuit)) 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) pass_ = UnrollCustomDefinitions(std_eqlib, ["u1", "cx"]) dag = pass_.run(dag) unrolled_dag = BasisTranslator(std_eqlib, ["u1", "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) pass_ = UnrollCustomDefinitions(std_eqlib, ["p", "cx"]) dag = pass_.run(dag) unrolled_dag = BasisTranslator(std_eqlib, ["p", "cx"]).run(dag) expected = QuantumCircuit(qr, global_phase=-sum_ / 2) expected.p(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.cp(theta, qr[1], qr[0]) qc.cp(theta * theta, qr[0], qr[1]) dag = circuit_to_dag(qc) pass_ = UnrollCustomDefinitions(std_eqlib, ["p", "cx"]) dag = pass_.run(dag) out_dag = BasisTranslator(std_eqlib, ["p", "cx"]).run(dag) self.assertEqual(out_dag.count_ops(), {"p": 6, "cx": 4}) def test_unrolling_parameterized_composite_gates(self): """Verify unrolling circuits with parameterized composite gates.""" mock_sel = EquivalenceLibrary(base=std_eqlib) 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) sub_instr = circuit_to_instruction(subqc, equivalence_library=mock_sel) qc.append(sub_instr, [qr2[0], qr2[1]]) qc.append(sub_instr, [qr2[2], qr2[3]]) dag = circuit_to_dag(qc) pass_ = UnrollCustomDefinitions(mock_sel, ["p", "cx"]) dag = pass_.run(dag) out_dag = BasisTranslator(mock_sel, ["p", "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.p(theta, qr2[0]) expected.p(theta, qr2[2]) expected.cx(qr2[0], qr2[1]) expected.cx(qr2[2], qr2[3]) expected.p(theta, qr2[1]) expected.p(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") sub_instr = circuit_to_instruction(subqc, {theta: phi}, mock_sel) qc.append(sub_instr, [qr2[0], qr2[1]]) sub_instr = circuit_to_instruction(subqc, {theta: gamma}, mock_sel) qc.append(sub_instr, [qr2[2], qr2[3]]) dag = circuit_to_dag(qc) pass_ = UnrollCustomDefinitions(mock_sel, ["p", "cx"]) dag = pass_.run(dag) out_dag = BasisTranslator(mock_sel, ["p", "cx"]).run(dag) expected = QuantumCircuit(qr2, global_phase=-1 * (2 * phi + 2 * gamma) / 2.0) expected.p(phi, qr2[0]) expected.p(gamma, qr2[2]) expected.cx(qr2[0], qr2[1]) expected.cx(qr2[2], qr2[3]) expected.p(phi, qr2[1]) expected.p(gamma, qr2[3]) self.assertEqual(circuit_to_dag(expected), out_dag) class TestBasisExamples(QiskitTestCase): """Test example circuits targeting example bases over the StandardEquivalenceLibrary.""" def test_cx_bell_to_cz(self): """Verify we can translate a CX bell circuit to CZ,RX,RZ.""" bell = QuantumCircuit(2) bell.h(0) bell.cx(0, 1) in_dag = circuit_to_dag(bell) out_dag = BasisTranslator(std_eqlib, ["cz", "rx", "rz"]).run(in_dag) self.assertTrue(set(out_dag.count_ops()).issubset(["cz", "rx", "rz"])) self.assertEqual(Operator(bell), Operator(dag_to_circuit(out_dag))) def test_cx_bell_to_iswap(self): """Verify we can translate a CX bell to iSwap,U3.""" bell = QuantumCircuit(2) bell.h(0) bell.cx(0, 1) in_dag = circuit_to_dag(bell) out_dag = BasisTranslator(std_eqlib, ["iswap", "u"]).run(in_dag) self.assertTrue(set(out_dag.count_ops()).issubset(["iswap", "u"])) self.assertEqual(Operator(bell), Operator(dag_to_circuit(out_dag))) def test_cx_bell_to_ecr(self): """Verify we can translate a CX bell to ECR,U.""" bell = QuantumCircuit(2) bell.h(0) bell.cx(0, 1) in_dag = circuit_to_dag(bell) out_dag = BasisTranslator(std_eqlib, ["ecr", "u"]).run(in_dag) # β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β”Œβ”€β”€β”€β”€β”€β”€β”β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” # q_0: ──── U(Ο€/2,0,Ο€) β”œβ”€β”€β”€β”€ U(0,0,-Ο€/2) β”œβ”€0 β”œβ”€ U(Ο€,0,Ο€) β”œ # β”Œβ”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β”‚ Ecr β”‚β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ # q_1: ─ U(-Ο€/2,-Ο€/2,Ο€/2) β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€1 β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ # β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”˜ qr = QuantumRegister(2, "q") expected = QuantumCircuit(2) expected.u(pi / 2, 0, pi, qr[0]) expected.u(0, 0, -pi / 2, qr[0]) expected.u(-pi / 2, -pi / 2, pi / 2, qr[1]) expected.ecr(0, 1) expected.u(pi, 0, pi, qr[0]) expected_dag = circuit_to_dag(expected) self.assertEqual(out_dag, expected_dag) def test_cx_bell_to_cp(self): """Verify we can translate a CX bell to CP,U.""" bell = QuantumCircuit(2) bell.h(0) bell.cx(0, 1) in_dag = circuit_to_dag(bell) out_dag = BasisTranslator(std_eqlib, ["cp", "u"]).run(in_dag) self.assertTrue(set(out_dag.count_ops()).issubset(["cp", "u"])) self.assertEqual(Operator(bell), Operator(dag_to_circuit(out_dag))) qr = QuantumRegister(2, "q") expected = QuantumCircuit(qr) expected.u(pi / 2, 0, pi, 0) expected.u(pi / 2, 0, pi, 1) expected.cp(pi, 0, 1) expected.u(pi / 2, 0, pi, 1) expected_dag = circuit_to_dag(expected) self.assertEqual(out_dag, expected_dag) def test_cx_bell_to_crz(self): """Verify we can translate a CX bell to CRZ,U.""" bell = QuantumCircuit(2) bell.h(0) bell.cx(0, 1) in_dag = circuit_to_dag(bell) out_dag = BasisTranslator(std_eqlib, ["crz", "u"]).run(in_dag) self.assertTrue(set(out_dag.count_ops()).issubset(["crz", "u"])) self.assertEqual(Operator(bell), Operator(dag_to_circuit(out_dag))) qr = QuantumRegister(2, "q") expected = QuantumCircuit(qr) expected.u(pi / 2, 0, pi, 0) expected.u(0, 0, pi / 2, 0) expected.u(pi / 2, 0, pi, 1) expected.crz(pi, 0, 1) expected.u(pi / 2, 0, pi, 1) expected_dag = circuit_to_dag(expected) self.assertEqual(out_dag, expected_dag) def test_global_phase(self): """Verify global phase preserved in basis translation""" circ = QuantumCircuit(1) gate_angle = pi / 5 circ_angle = pi / 3 circ.rz(gate_angle, 0) circ.global_phase = circ_angle in_dag = circuit_to_dag(circ) out_dag = BasisTranslator(std_eqlib, ["p"]).run(in_dag) qr = QuantumRegister(1, "q") expected = QuantumCircuit(qr) expected.p(gate_angle, qr) expected.global_phase = circ_angle - gate_angle / 2 expected_dag = circuit_to_dag(expected) self.assertEqual(out_dag, expected_dag) self.assertAlmostEqual( float(out_dag.global_phase), float(expected_dag.global_phase), places=14 ) self.assertEqual(Operator(dag_to_circuit(out_dag)), Operator(expected)) def test_condition_set_substitute_node(self): """Verify condition is set in BasisTranslator on substitute_node""" # β”Œβ”€β”€β”€β” β”Œβ”€β”€β”€β” # q_0: ─ H β”œβ”€β”€β– β”€β”€β”€β”€β”€β”€β”€ H β”œβ”€ # β””β”€β”€β”€β”˜β”Œβ”€β”΄β”€β”β”Œβ”€β” └─β•₯β”€β”˜ # q_1: ────── X β”œβ”€Mβ”œβ”€β”€β”€β•«β”€β”€β”€ # β””β”€β”€β”€β”˜β””β•₯β”˜β”Œβ”€β”€β•¨β”€β”€β” # c: 2/═══════════╩═║ 0x1 β•ž # 1 β””β”€β”€β”€β”€β”€β”˜ qr = QuantumRegister(2, "q") cr = ClassicalRegister(2, "c") circ = QuantumCircuit(qr, cr) circ.h(0) circ.cx(0, 1) circ.measure(1, 1) circ.h(0).c_if(cr, 1) circ_transpiled = transpile(circ, optimization_level=3, basis_gates=["cx", "id", "u"]) # β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” # q_0: ─ U(Ο€/2,0,Ο€) β”œβ”€β”€β– β”€β”€β”€β”€β”€β”€ U(Ο€/2,0,Ο€) β”œ # β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β”Œβ”€β”΄β”€β”β”Œβ”€β”β””β”€β”€β”€β”€β”€β•₯β”€β”€β”€β”€β”€β”€β”˜ # q_1: ─────────────── X β”œβ”€Mβ”œβ”€β”€β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€β”€β”€ # β””β”€β”€β”€β”˜β””β•₯β”˜ β”Œβ”€β”€β•¨β”€β”€β” # c: 2/════════════════════╩════║ 0x1 β•žβ•β•β•β• # 1 β””β”€β”€β”€β”€β”€β”˜ qr = QuantumRegister(2, "q") cr = ClassicalRegister(2, "c") expected = QuantumCircuit(qr, cr) expected.u(pi / 2, 0, pi, 0) expected.cx(0, 1) expected.measure(1, 1) expected.u(pi / 2, 0, pi, 0).c_if(cr, 1) self.assertEqual(circ_transpiled, expected) def test_skip_target_basis_equivalences_1(self): """Test that BasisTranslator skips gates in the target_basis - #6085""" circ = QuantumCircuit() qasm_file = os.path.join( os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm", "TestBasisTranslator_skip_target.qasm", ) circ = circ.from_qasm_file(qasm_file) circ_transpiled = transpile( circ, basis_gates=["id", "rz", "sx", "x", "cx"], seed_transpiler=42, ) self.assertEqual(circ_transpiled.count_ops(), {"cx": 91, "rz": 66, "sx": 22}) class TestBasisTranslatorWithTarget(QiskitTestCase): """Test the basis translator when running with a Target.""" def setUp(self): super().setUp() self.target = Target() # U gate in qubit 0. self.theta = Parameter("theta") self.phi = Parameter("phi") self.lam = Parameter("lambda") u_props = { (0,): InstructionProperties(duration=5.23e-8, error=0.00038115), } self.target.add_instruction(UGate(self.theta, self.phi, self.lam), u_props) # Rz gate in qubit 1. rz_props = { (1,): InstructionProperties(duration=0.0, error=0), } self.target.add_instruction(RZGate(self.phi), rz_props) # X gate in qubit 1. x_props = { (1,): InstructionProperties( duration=3.5555555555555554e-08, error=0.00020056469709026198 ), } self.target.add_instruction(XGate(), x_props) # SX gate in qubit 1. sx_props = { (1,): InstructionProperties( duration=3.5555555555555554e-08, error=0.00020056469709026198 ), } self.target.add_instruction(SXGate(), sx_props) cx_props = { (0, 1): InstructionProperties(duration=5.23e-7, error=0.00098115), (1, 0): InstructionProperties(duration=4.52e-7, error=0.00132115), } self.target.add_instruction(CXGate(), cx_props) def test_2q_with_non_global_1q(self): """Test translation works with a 2q gate on an non-global 1q basis.""" qc = QuantumCircuit(2) qc.cz(0, 1) bt_pass = BasisTranslator(std_eqlib, target_basis=None, target=self.target) output = bt_pass(qc) # We need a second run of BasisTranslator to correct gates outside of # the target basis. This is a known isssue, see: # https://qiskit.org/documentation/release_notes.html#release-notes-0-19-0-known-issues output = bt_pass(output) expected = QuantumCircuit(2) expected.rz(pi, 1) expected.sx(1) expected.rz(3 * pi / 2, 1) expected.sx(1) expected.rz(3 * pi, 1) expected.cx(0, 1) expected.rz(pi, 1) expected.sx(1) expected.rz(3 * pi / 2, 1) expected.sx(1) expected.rz(3 * pi, 1) self.assertEqual(output, expected)
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# 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 RZXCalibrationBuilderNoEcho.""" from math import pi, erf import numpy as np from ddt import data, ddt from qiskit.converters import circuit_to_dag from qiskit import circuit, schedule, QiskitError from qiskit.circuit.library.standard_gates import SXGate, RZGate from qiskit.providers.fake_provider import FakeHanoi # TODO - include FakeHanoiV2, FakeSherbrooke from qiskit.providers.fake_provider import FakeArmonk from qiskit.pulse import ( ControlChannel, DriveChannel, GaussianSquare, Waveform, Play, InstructionScheduleMap, Schedule, ) from qiskit.pulse import builder from qiskit.pulse.transforms import target_qobj_transform from qiskit.test import QiskitTestCase from qiskit.transpiler import PassManager from qiskit.transpiler.passes.calibration.builders import ( RZXCalibrationBuilder, RZXCalibrationBuilderNoEcho, ) class TestCalibrationBuilder(QiskitTestCase): """Test the Calibration Builder.""" # CR parameters __risefall = 4 __angle = np.pi / 2 __granularity = 16 @staticmethod def get_cr_play(cr_schedule, name): """A helper function to filter CR pulses.""" def _filter_func(time_inst): return isinstance(time_inst[1], Play) and time_inst[1].pulse.name.startswith(name) return cr_schedule.filter(_filter_func).instructions[0][1] def compute_stretch_duration(self, play_gaussian_square_pulse, theta): """Compute duration of stretched Gaussian Square pulse.""" pulse = play_gaussian_square_pulse.pulse sigma = pulse.sigma width = self.compute_stretch_width(play_gaussian_square_pulse, theta) duration = width + sigma * self.__risefall return round(duration / self.__granularity) * self.__granularity def compute_stretch_width(self, play_gaussian_square_pulse, theta): """Compute width of stretched Gaussian Square pulse.""" pulse = play_gaussian_square_pulse.pulse sigma = pulse.sigma width = pulse.width risefall_area = sigma * np.sqrt(2 * np.pi) * erf(self.__risefall) full_area = risefall_area + width target_area = abs(theta) / self.__angle * full_area return max(0, target_area - risefall_area) def u0p_play(self, cr_schedule): """Returns the positive CR pulse from cr_schedule.""" return self.get_cr_play(cr_schedule, "CR90p_u") def u0m_play(self, cr_schedule): """Returns the negative CR pulse from cr_schedule.""" return self.get_cr_play(cr_schedule, "CR90m_u") def d1p_play(self, cr_schedule): """Returns the positive rotary echo pulse from cr_schedule.""" return self.get_cr_play(cr_schedule, "CR90p_d") def d1m_play(self, cr_schedule): """Returns the negative rotary echo pulse from cr_schedule.""" return self.get_cr_play(cr_schedule, "CR90m_d") @ddt class TestRZXCalibrationBuilder(TestCalibrationBuilder): """Test RZXCalibrationBuilder.""" def build_forward( self, backend, theta, u0p_play, d1p_play, u0m_play, d1m_play, ): """A helper function to generate reference pulse schedule for forward direction.""" duration = self.compute_stretch_duration(u0p_play, theta) width = self.compute_stretch_width(u0p_play, theta) with builder.build( backend, default_alignment="sequential", default_transpiler_settings={"optimization_level": 0}, ) as ref_sched: with builder.align_left(): # Positive CRs u0p_params = u0p_play.pulse.parameters u0p_params["duration"] = duration u0p_params["width"] = width builder.play( GaussianSquare(**u0p_params), ControlChannel(0), ) d1p_params = d1p_play.pulse.parameters d1p_params["duration"] = duration d1p_params["width"] = width builder.play( GaussianSquare(**d1p_params), DriveChannel(1), ) builder.x(0) with builder.align_left(): # Negative CRs u0m_params = u0m_play.pulse.parameters u0m_params["duration"] = duration u0m_params["width"] = width builder.play( GaussianSquare(**u0m_params), ControlChannel(0), ) d1m_params = d1m_play.pulse.parameters d1m_params["duration"] = duration d1m_params["width"] = width builder.play( GaussianSquare(**d1m_params), DriveChannel(1), ) builder.x(0) return ref_sched def build_reverse( self, backend, theta, u0p_play, d1p_play, u0m_play, d1m_play, ): """A helper function to generate reference pulse schedule for backward direction.""" duration = self.compute_stretch_duration(u0p_play, theta) width = self.compute_stretch_width(u0p_play, theta) with builder.build( backend, default_alignment="sequential", default_transpiler_settings={"optimization_level": 0}, ) as ref_sched: # Hadamard gates builder.call_gate(RZGate(np.pi / 2), qubits=(0,)) builder.call_gate(SXGate(), qubits=(0,)) builder.call_gate(RZGate(np.pi / 2), qubits=(0,)) builder.call_gate(RZGate(np.pi / 2), qubits=(1,)) builder.call_gate(SXGate(), qubits=(1,)) builder.call_gate(RZGate(np.pi / 2), qubits=(1,)) with builder.align_left(): # Positive CRs u0p_params = u0p_play.pulse.parameters u0p_params["duration"] = duration u0p_params["width"] = width builder.play( GaussianSquare(**u0p_params), ControlChannel(0), ) d1p_params = d1p_play.pulse.parameters d1p_params["duration"] = duration d1p_params["width"] = width builder.play( GaussianSquare(**d1p_params), DriveChannel(1), ) builder.x(0) with builder.align_left(): # Negative CRs u0m_params = u0m_play.pulse.parameters u0m_params["duration"] = duration u0m_params["width"] = width builder.play( GaussianSquare(**u0m_params), ControlChannel(0), ) d1m_params = d1m_play.pulse.parameters d1m_params["duration"] = duration d1m_params["width"] = width builder.play( GaussianSquare(**d1m_params), DriveChannel(1), ) builder.x(0) # Hadamard gates builder.call_gate(RZGate(np.pi / 2), qubits=(0,)) builder.call_gate(SXGate(), qubits=(0,)) builder.call_gate(RZGate(np.pi / 2), qubits=(0,)) builder.call_gate(RZGate(np.pi / 2), qubits=(1,)) builder.call_gate(SXGate(), qubits=(1,)) builder.call_gate(RZGate(np.pi / 2), qubits=(1,)) return ref_sched @data(-np.pi / 4, 0.1, np.pi / 4, np.pi / 2, np.pi) def test_rzx_calibration_cr_pulse_stretch(self, theta: float): """Test that cross resonance pulse durations are computed correctly.""" backend = FakeHanoi() inst_map = backend.defaults().instruction_schedule_map cr_schedule = inst_map.get("cx", (0, 1)) with builder.build() as test_sched: RZXCalibrationBuilder.rescale_cr_inst(self.u0p_play(cr_schedule), theta) self.assertEqual( test_sched.duration, self.compute_stretch_duration(self.u0p_play(cr_schedule), theta) ) @data(-np.pi / 4, 0.1, np.pi / 4, np.pi / 2, np.pi) def test_rzx_calibration_rotary_pulse_stretch(self, theta: float): """Test that rotary pulse durations are computed correctly.""" backend = FakeHanoi() inst_map = backend.defaults().instruction_schedule_map cr_schedule = inst_map.get("cx", (0, 1)) with builder.build() as test_sched: RZXCalibrationBuilder.rescale_cr_inst(self.d1p_play(cr_schedule), theta) self.assertEqual( test_sched.duration, self.compute_stretch_duration(self.d1p_play(cr_schedule), theta) ) def test_raise(self): """Test that the correct error is raised.""" theta = np.pi / 4 qc = circuit.QuantumCircuit(2) qc.rzx(theta, 0, 1) dag = circuit_to_dag(qc) backend = FakeArmonk() inst_map = backend.defaults().instruction_schedule_map _pass = RZXCalibrationBuilder(inst_map) qubit_map = {qubit: i for i, qubit in enumerate(dag.qubits)} with self.assertRaises(QiskitError): for node in dag.gate_nodes(): qubits = [qubit_map[q] for q in node.qargs] _pass.get_calibration(node.op, qubits) def test_ecr_cx_forward(self): """Test that correct pulse sequence is generated for native CR pair.""" # Sufficiently large angle to avoid minimum duration, i.e. amplitude rescaling theta = np.pi / 4 qc = circuit.QuantumCircuit(2) qc.rzx(theta, 0, 1) backend = FakeHanoi() inst_map = backend.defaults().instruction_schedule_map _pass = RZXCalibrationBuilder(inst_map) test_qc = PassManager(_pass).run(qc) cr_schedule = inst_map.get("cx", (0, 1)) ref_sched = self.build_forward( backend, theta, self.u0p_play(cr_schedule), self.d1p_play(cr_schedule), self.u0m_play(cr_schedule), self.d1m_play(cr_schedule), ) self.assertEqual(schedule(test_qc, backend), target_qobj_transform(ref_sched)) def test_ecr_cx_reverse(self): """Test that correct pulse sequence is generated for non-native CR pair.""" # Sufficiently large angle to avoid minimum duration, i.e. amplitude rescaling theta = np.pi / 4 qc = circuit.QuantumCircuit(2) qc.rzx(theta, 1, 0) backend = FakeHanoi() inst_map = backend.defaults().instruction_schedule_map _pass = RZXCalibrationBuilder(inst_map) test_qc = PassManager(_pass).run(qc) cr_schedule = inst_map.get("cx", (0, 1)) ref_sched = self.build_reverse( backend, theta, self.u0p_play(cr_schedule), self.d1p_play(cr_schedule), self.u0m_play(cr_schedule), self.d1m_play(cr_schedule), ) self.assertEqual(schedule(test_qc, backend), target_qobj_transform(ref_sched)) def test_pass_alive_with_dcx_ish(self): """Test if the pass is not terminated by error with direct CX input.""" cx_sched = Schedule() # Fake direct cr cx_sched.insert(0, Play(GaussianSquare(800, 0.2, 64, 544), ControlChannel(1)), inplace=True) # Fake direct compensation tone # Compensation tone doesn't have dedicated pulse class. # So it's reported as a waveform now. compensation_tone = Waveform(0.1 * np.ones(800, dtype=complex)) cx_sched.insert(0, Play(compensation_tone, DriveChannel(0)), inplace=True) inst_map = InstructionScheduleMap() inst_map.add("cx", (1, 0), schedule=cx_sched) theta = pi / 3 rzx_qc = circuit.QuantumCircuit(2) rzx_qc.rzx(theta, 1, 0) pass_ = RZXCalibrationBuilder(instruction_schedule_map=inst_map) with self.assertWarns(UserWarning): # User warning that says q0 q1 is invalid cal_qc = PassManager(pass_).run(rzx_qc) self.assertEqual(cal_qc, rzx_qc) class TestRZXCalibrationBuilderNoEcho(TestCalibrationBuilder): """Test RZXCalibrationBuilderNoEcho.""" def build_forward( self, theta, u0p_play, d1p_play, ): """A helper function to generate reference pulse schedule for forward direction.""" duration = self.compute_stretch_duration(u0p_play, 2.0 * theta) width = self.compute_stretch_width(u0p_play, 2.0 * theta) with builder.build() as ref_sched: # Positive CRs u0p_params = u0p_play.pulse.parameters u0p_params["duration"] = duration u0p_params["width"] = width builder.play( GaussianSquare(**u0p_params), ControlChannel(0), ) d1p_params = d1p_play.pulse.parameters d1p_params["duration"] = duration d1p_params["width"] = width builder.play( GaussianSquare(**d1p_params), DriveChannel(1), ) builder.delay(duration, DriveChannel(0)) return ref_sched def test_ecr_cx_forward(self): """Test that correct pulse sequence is generated for native CR pair. .. notes:: No echo builder only supports native direction. """ # Sufficiently large angle to avoid minimum duration, i.e. amplitude rescaling theta = np.pi / 4 qc = circuit.QuantumCircuit(2) qc.rzx(theta, 0, 1) backend = FakeHanoi() inst_map = backend.defaults().instruction_schedule_map _pass = RZXCalibrationBuilderNoEcho(inst_map) test_qc = PassManager(_pass).run(qc) cr_schedule = inst_map.get("cx", (0, 1)) ref_sched = self.build_forward( theta, self.u0p_play(cr_schedule), self.d1p_play(cr_schedule), ) self.assertEqual(schedule(test_qc, backend), target_qobj_transform(ref_sched)) # # TODO - write test for forward ECR native pulse # def test_ecr_forward(self): def test_pass_alive_with_dcx_ish(self): """Test if the pass is not terminated by error with direct CX input.""" cx_sched = Schedule() # Fake direct cr cx_sched.insert(0, Play(GaussianSquare(800, 0.2, 64, 544), ControlChannel(1)), inplace=True) # Fake direct compensation tone # Compensation tone doesn't have dedicated pulse class. # So it's reported as a waveform now. compensation_tone = Waveform(0.1 * np.ones(800, dtype=complex)) cx_sched.insert(0, Play(compensation_tone, DriveChannel(0)), inplace=True) inst_map = InstructionScheduleMap() inst_map.add("cx", (1, 0), schedule=cx_sched) theta = pi / 3 rzx_qc = circuit.QuantumCircuit(2) rzx_qc.rzx(theta, 1, 0) pass_ = RZXCalibrationBuilderNoEcho(instruction_schedule_map=inst_map) with self.assertWarns(UserWarning): # User warning that says q0 q1 is invalid cal_qc = PassManager(pass_).run(rzx_qc) self.assertEqual(cal_qc, rzx_qc)
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# 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 CNOT direction pass""" import unittest import ddt from qiskit import QuantumRegister, QuantumCircuit from qiskit.circuit.library import CXGate, CZGate, ECRGate from qiskit.transpiler.passes import CheckGateDirection from qiskit.transpiler import CouplingMap, Target from qiskit.converters import circuit_to_dag from qiskit.test import QiskitTestCase @ddt.ddt class TestCheckGateDirection(QiskitTestCase): """Tests the CheckGateDirection pass""" def test_trivial_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_ = CheckGateDirection(coupling) pass_.run(dag) self.assertTrue(pass_.property_set["is_direction_mapped"]) def test_true_direction(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_ = CheckGateDirection(coupling) pass_.run(dag) self.assertTrue(pass_.property_set["is_direction_mapped"]) def test_true_direction_in_same_layer(self): """Two CXs distance_qubits 1 to each other, in the same layer qr0:--(+)-- | qr1:---.--- qr2:--(+)-- | qr3:---.--- CouplingMap map: [0]->[1]->[2]->[3] """ qr = QuantumRegister(4, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.cx(qr[2], qr[3]) coupling = CouplingMap([[0, 1], [1, 2], [2, 3]]) dag = circuit_to_dag(circuit) pass_ = CheckGateDirection(coupling) pass_.run(dag) self.assertTrue(pass_.property_set["is_direction_mapped"]) def test_wrongly_mapped(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_ = CheckGateDirection(coupling) pass_.run(dag) self.assertFalse(pass_.property_set["is_direction_mapped"]) def test_true_direction_undirected(self): """Mapped but with wrong direction 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[2], qr[0]) coupling = CouplingMap([[0, 1], [0, 2]]) dag = circuit_to_dag(circuit) pass_ = CheckGateDirection(coupling) pass_.run(dag) self.assertFalse(pass_.property_set["is_direction_mapped"]) def test_false_direction_in_same_layer_undirected(self): """Two CXs in the same layer, but one is wrongly directed qr0:--(+)-- | qr1:---.--- qr2:---.--- | qr3:--(+)-- CouplingMap map: [0]->[1]->[2]->[3] """ qr = QuantumRegister(4, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.cx(qr[3], qr[2]) coupling = CouplingMap([[0, 1], [1, 2], [2, 3]]) dag = circuit_to_dag(circuit) pass_ = CheckGateDirection(coupling) pass_.run(dag) self.assertFalse(pass_.property_set["is_direction_mapped"]) def test_2q_barrier(self): """A 2q barrier should be ignored qr0:--|-- | qr1:--|-- CouplingMap map: None """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.barrier(qr[0], qr[1]) coupling = CouplingMap() dag = circuit_to_dag(circuit) pass_ = CheckGateDirection(coupling) pass_.run(dag) self.assertTrue(pass_.property_set["is_direction_mapped"]) def test_ecr_gate(self): """A directional ECR gate is detected. β”Œβ”€β”€β”€β”€β”€β”€β” 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() dag = circuit_to_dag(circuit) pass_ = CheckGateDirection(coupling) pass_.run(dag) self.assertFalse(pass_.property_set["is_direction_mapped"]) @ddt.data(CXGate(), CZGate(), ECRGate()) def test_target_static(self, gate): """Test that static 2q gates are detected 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}) pass_ = CheckGateDirection(None, target=matching) pass_(circuit) self.assertTrue(pass_.property_set["is_direction_mapped"]) swapped = Target(num_qubits=2) swapped.add_instruction(gate, {(1, 0): None}) pass_ = CheckGateDirection(None, target=swapped) pass_(circuit) self.assertFalse(pass_.property_set["is_direction_mapped"]) def test_coupling_map_control_flow(self): """Test recursing into control-flow operations with a coupling map.""" matching = CouplingMap.from_line(5, bidirectional=True) swapped = CouplingMap.from_line(5, bidirectional=False) circuit = QuantumCircuit(5, 1) circuit.h(0) circuit.measure(0, 0) with circuit.for_loop((2,)): circuit.cx(1, 0) pass_ = CheckGateDirection(matching) pass_(circuit) self.assertTrue(pass_.property_set["is_direction_mapped"]) pass_ = CheckGateDirection(swapped) pass_(circuit) self.assertFalse(pass_.property_set["is_direction_mapped"]) circuit = QuantumCircuit(5, 1) circuit.h(0) circuit.measure(0, 0) with circuit.for_loop((2,)): with circuit.if_test((circuit.clbits[0], True)) as else_: circuit.cz(3, 2) with else_: with circuit.while_loop((circuit.clbits[0], True)): circuit.ecr(4, 3) pass_ = CheckGateDirection(matching) pass_(circuit) self.assertTrue(pass_.property_set["is_direction_mapped"]) pass_ = CheckGateDirection(swapped) pass_(circuit) self.assertFalse(pass_.property_set["is_direction_mapped"]) def test_target_control_flow(self): """Test recursing into control-flow operations with a coupling map.""" swapped = Target(num_qubits=5) for gate in (CXGate(), CZGate(), ECRGate()): swapped.add_instruction(gate, {qargs: None for qargs in zip(range(4), range(1, 5))}) matching = Target(num_qubits=5) for gate in (CXGate(), CZGate(), ECRGate()): matching.add_instruction(gate, {None: None}) circuit = QuantumCircuit(5, 1) circuit.h(0) circuit.measure(0, 0) with circuit.for_loop((2,)): circuit.cx(1, 0) pass_ = CheckGateDirection(None, target=matching) pass_(circuit) self.assertTrue(pass_.property_set["is_direction_mapped"]) pass_ = CheckGateDirection(None, target=swapped) pass_(circuit) self.assertFalse(pass_.property_set["is_direction_mapped"]) circuit = QuantumCircuit(5, 1) circuit.h(0) circuit.measure(0, 0) with circuit.for_loop((2,)): with circuit.if_test((circuit.clbits[0], True)) as else_: circuit.cz(3, 2) with else_: with circuit.while_loop((circuit.clbits[0], True)): circuit.ecr(4, 3) pass_ = CheckGateDirection(None, target=matching) pass_(circuit) self.assertTrue(pass_.property_set["is_direction_mapped"]) pass_ = CheckGateDirection(None, target=swapped) pass_(circuit) self.assertFalse(pass_.property_set["is_direction_mapped"]) if __name__ == "__main__": unittest.main()
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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. """FilterOpNodes pass testing""" from qiskit import QuantumCircuit from qiskit.transpiler.passes import FilterOpNodes from test import QiskitTestCase # pylint: disable=wrong-import-order class TestFilterOpNodes(QiskitTestCase): """Tests for FilterOpNodes transformation pass.""" def test_empty_circuit(self): """Empty DAG has does nothing.""" circuit = QuantumCircuit() self.assertEqual(FilterOpNodes(lambda x: False)(circuit), circuit) def test_remove_x_gate(self): """Test filter removes matching gates.""" circuit = QuantumCircuit(2) circuit.x(0) circuit.x(1) circuit.cx(0, 1) circuit.cx(1, 0) circuit.cx(0, 1) circuit.measure_all() filter_pass = FilterOpNodes(lambda node: node.op.name != "x") expected = QuantumCircuit(2) expected.cx(0, 1) expected.cx(1, 0) expected.cx(0, 1) expected.measure_all() self.assertEqual(filter_pass(circuit), expected) def test_filter_exception(self): """Test a filter function exception passes through.""" circuit = QuantumCircuit(2) circuit.x(0) circuit.x(1) circuit.cx(0, 1) circuit.cx(1, 0) circuit.cx(0, 1) circuit.measure_all() def filter_fn(node): raise TypeError("Failure") filter_pass = FilterOpNodes(filter_fn) with self.assertRaises(TypeError): filter_pass(circuit) def test_no_matches(self): """Test the pass does nothing if there are no filter matches.""" circuit = QuantumCircuit(2) circuit.x(0) circuit.x(1) circuit.cx(0, 1) circuit.cx(1, 0) circuit.cx(0, 1) circuit.measure_all() filter_pass = FilterOpNodes(lambda node: node.op.name != "cz") self.assertEqual(filter_pass(circuit), circuit)
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2023, 2024. # # 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 NormalizeRXAngle pass""" import unittest import numpy as np from ddt import ddt, named_data from qiskit import QuantumCircuit from qiskit.transpiler.passes.optimization.normalize_rx_angle import ( NormalizeRXAngle, ) from qiskit.providers.fake_provider import GenericBackendV2 from qiskit.transpiler import Target from qiskit.circuit.library.standard_gates import SXGate from test import QiskitTestCase # pylint: disable=wrong-import-order @ddt class TestNormalizeRXAngle(QiskitTestCase): """Tests the NormalizeRXAngle pass.""" def test_not_convert_to_x_if_no_calib_in_target(self): """Check that RX(pi) is NOT converted to X, if X calibration is not present in the target""" empty_target = Target() tp = NormalizeRXAngle(target=empty_target) qc = QuantumCircuit(1) qc.rx(90, 0) transpiled_circ = tp(qc) self.assertEqual(transpiled_circ.count_ops().get("x", 0), 0) def test_sx_conversion_works(self): """Check that RX(pi/2) is converted to SX, if SX calibration is present in the target""" target = Target() target.add_instruction(SXGate(), properties={(0,): None}) tp = NormalizeRXAngle(target=target) qc = QuantumCircuit(1) qc.rx(np.pi / 2, 0) transpiled_circ = tp(qc) self.assertEqual(transpiled_circ.count_ops().get("sx", 0), 1) def test_rz_added_for_negative_rotation_angles(self): """Check that RZ is added before and after RX, if RX rotation angle is negative""" backend = GenericBackendV2(num_qubits=5) tp = NormalizeRXAngle(target=backend.target) # circuit to transpile and test qc = QuantumCircuit(1) qc.rx((-1 / 3) * np.pi, 0) transpiled_circ = tp(qc) # circuit to show the correct answer qc_ref = QuantumCircuit(1) qc_ref.rz(np.pi, 0) qc_ref.rx(np.pi / 3, 0) qc_ref.rz(-np.pi, 0) self.assertQuantumCircuitEqual(transpiled_circ, qc_ref) @named_data( {"name": "-0.3pi", "raw_theta": -0.3 * np.pi, "correct_wrapped_theta": 0.3 * np.pi}, {"name": "1.7pi", "raw_theta": 1.7 * np.pi, "correct_wrapped_theta": 0.3 * np.pi}, {"name": "2.2pi", "raw_theta": 2.2 * np.pi, "correct_wrapped_theta": 0.2 * np.pi}, ) def test_angle_wrapping_works(self, raw_theta, correct_wrapped_theta): """Check that RX rotation angles are correctly wrapped to [0, pi]""" backend = GenericBackendV2(num_qubits=5) tp = NormalizeRXAngle(target=backend.target) # circuit to transpile and test qc = QuantumCircuit(1) qc.rx(raw_theta, 0) transpiled_circuit = tp(qc) wrapped_theta = transpiled_circuit.get_instructions("rx")[0].operation.params[0] self.assertAlmostEqual(wrapped_theta, correct_wrapped_theta) @named_data( { "name": "angles are within resolution", "resolution": 0.1, "rx_angles": [0.3, 0.303], "correct_num_of_cals": 1, }, { "name": "angles are not within resolution", "resolution": 0.1, "rx_angles": [0.2, 0.4], "correct_num_of_cals": 2, }, { "name": "same angle three times", "resolution": 0.1, "rx_angles": [0.2, 0.2, 0.2], "correct_num_of_cals": 1, }, ) def test_quantize_angles(self, resolution, rx_angles, correct_num_of_cals): """Test that quantize_angles() adds a new calibration only if the requested angle is not in the vicinity of the already generated angles. """ backend = GenericBackendV2(num_qubits=5) tp = NormalizeRXAngle(backend.target, resolution_in_radian=resolution) qc = QuantumCircuit(1) for rx_angle in rx_angles: qc.rx(rx_angle, 0) transpiled_circuit = tp(qc) angles = [ inst.operation.params[0] for inst in transpiled_circuit.data if inst.operation.name == "rx" ] angles_without_duplicate = list(dict.fromkeys(angles)) self.assertEqual(len(angles_without_duplicate), correct_num_of_cals) if __name__ == "__main__": unittest.main()
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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 qiskit/tools/parallel""" import os import time from unittest.mock import patch from qiskit.tools.parallel import get_platform_parallel_default, parallel_map from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.pulse import Schedule from qiskit.test import QiskitTestCase def _parfunc(x): """Function for testing parallel_map""" time.sleep(1) return x def _build_simple_circuit(_): qreg = QuantumRegister(2) creg = ClassicalRegister(2) qc = QuantumCircuit(qreg, creg) return qc def _build_simple_schedule(_): return Schedule() class TestGetPlatformParallelDefault(QiskitTestCase): """Tests get_parallel_default_for_platform.""" def test_windows_parallel_default(self): """Verifies the parallel default for Windows.""" with patch("sys.platform", "win32"): parallel_default = get_platform_parallel_default() self.assertEqual(parallel_default, False) def test_mac_os_unsupported_version_parallel_default(self): """Verifies the parallel default for macOS.""" with patch("sys.platform", "darwin"): with patch("sys.version_info", (3, 8, 0, "final", 0)): parallel_default = get_platform_parallel_default() self.assertEqual(parallel_default, False) def test_other_os_parallel_default(self): """Verifies the parallel default for Linux and other OSes.""" with patch("sys.platform", "linux"): parallel_default = get_platform_parallel_default() self.assertEqual(parallel_default, True) class TestParallel(QiskitTestCase): """A class for testing parallel_map functionality.""" def test_parallel_env_flag(self): """Verify parallel env flag is set""" self.assertEqual(os.getenv("QISKIT_IN_PARALLEL", None), "FALSE") def test_parallel(self): """Test parallel_map""" ans = parallel_map(_parfunc, list(range(10))) self.assertEqual(ans, list(range(10))) def test_parallel_circuit_names(self): """Verify unique circuit names in parallel""" out_circs = parallel_map(_build_simple_circuit, list(range(10))) names = [circ.name for circ in out_circs] self.assertEqual(len(names), len(set(names))) def test_parallel_schedule_names(self): """Verify unique schedule names in parallel""" out_schedules = parallel_map(_build_simple_schedule, list(range(10))) names = [schedule.name for schedule in out_schedules] self.assertEqual(len(names), len(set(names)))
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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/2lambda123/Qiskit-qiskit
2lambda123
# 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: &quot;Courier New&quot;,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()