repo
stringclasses
900 values
file
stringclasses
754 values
content
stringlengths
4
215k
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the NoiseAdaptiveLayout pass""" from datetime import datetime import unittest from qiskit.transpiler.passes import NoiseAdaptiveLayout from qiskit.converters import circuit_to_dag from qiskit import QuantumRegister, QuantumCircuit from qiskit.test import QiskitTestCase from qiskit.providers.models import BackendProperties from qiskit.providers.models.backendproperties import Nduv, Gate def make_qubit_with_error(readout_error): """Create a qubit for BackendProperties""" calib_time = datetime(year=2019, month=2, day=1, hour=0, minute=0, second=0) return [ Nduv(name="T1", date=calib_time, unit="µs", value=100.0), Nduv(name="T2", date=calib_time, unit="µs", value=100.0), Nduv(name="frequency", date=calib_time, unit="GHz", value=5.0), Nduv(name="readout_error", date=calib_time, unit="", value=readout_error), ] class TestNoiseAdaptiveLayout(QiskitTestCase): """Tests the NoiseAdaptiveLayout pass.""" def test_on_linear_topology(self): """ Test that the mapper identifies the correct gate in a linear topology """ calib_time = datetime(year=2019, month=2, day=1, hour=0, minute=0, second=0) qr = QuantumRegister(2, name="q") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) dag = circuit_to_dag(circuit) qubit_list = [] ro_errors = [0.01, 0.01, 0.01] for ro_error in ro_errors: qubit_list.append(make_qubit_with_error(ro_error)) p01 = [Nduv(date=calib_time, name="gate_error", unit="", value=0.9)] g01 = Gate(name="CX0_1", gate="cx", parameters=p01, qubits=[0, 1]) p12 = [Nduv(date=calib_time, name="gate_error", unit="", value=0.1)] g12 = Gate(name="CX1_2", gate="cx", parameters=p12, qubits=[1, 2]) gate_list = [g01, g12] bprop = BackendProperties( last_update_date=calib_time, backend_name="test_backend", qubits=qubit_list, backend_version="1.0.0", gates=gate_list, general=[], ) nalayout = NoiseAdaptiveLayout(bprop) nalayout.run(dag) initial_layout = nalayout.property_set["layout"] self.assertNotEqual(initial_layout[qr[0]], 0) self.assertNotEqual(initial_layout[qr[1]], 0) def test_bad_readout(self): """Test that the mapper avoids bad readout unit""" calib_time = datetime(year=2019, month=2, day=1, hour=0, minute=0, second=0) qr = QuantumRegister(2, name="q") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) dag = circuit_to_dag(circuit) qubit_list = [] ro_errors = [0.01, 0.01, 0.8] for ro_error in ro_errors: qubit_list.append(make_qubit_with_error(ro_error)) p01 = [Nduv(date=calib_time, name="gate_error", unit="", value=0.1)] g01 = Gate(name="CX0_1", gate="cx", parameters=p01, qubits=[0, 1]) p12 = [Nduv(date=calib_time, name="gate_error", unit="", value=0.1)] g12 = Gate(name="CX1_2", gate="cx", parameters=p12, qubits=[1, 2]) gate_list = [g01, g12] bprop = BackendProperties( last_update_date=calib_time, backend_name="test_backend", qubits=qubit_list, backend_version="1.0.0", gates=gate_list, general=[], ) nalayout = NoiseAdaptiveLayout(bprop) nalayout.run(dag) initial_layout = nalayout.property_set["layout"] self.assertNotEqual(initial_layout[qr[0]], 2) self.assertNotEqual(initial_layout[qr[1]], 2) def test_grid_layout(self): """ Test that the mapper identifies best location for a star-like program graph Machine row1: (0, 1, 2) Machine row2: (3, 4, 5) """ calib_time = datetime(year=2019, month=2, day=1, hour=0, minute=0, second=0) qr = QuantumRegister(4, name="q") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[3]) circuit.cx(qr[1], qr[3]) circuit.cx(qr[2], qr[3]) dag = circuit_to_dag(circuit) qubit_list = [] ro_errors = [0.01] * 6 for ro_error in ro_errors: qubit_list.append(make_qubit_with_error(ro_error)) p01 = [Nduv(date=calib_time, name="gate_error", unit="", value=0.3)] p03 = [Nduv(date=calib_time, name="gate_error", unit="", value=0.3)] p12 = [Nduv(date=calib_time, name="gate_error", unit="", value=0.3)] p14 = [Nduv(date=calib_time, name="gate_error", unit="", value=0.1)] p34 = [Nduv(date=calib_time, name="gate_error", unit="", value=0.1)] p45 = [Nduv(date=calib_time, name="gate_error", unit="", value=0.1)] p25 = [Nduv(date=calib_time, name="gate_error", unit="", value=0.3)] g01 = Gate(name="CX0_1", gate="cx", parameters=p01, qubits=[0, 1]) g03 = Gate(name="CX0_3", gate="cx", parameters=p03, qubits=[0, 3]) g12 = Gate(name="CX1_2", gate="cx", parameters=p12, qubits=[1, 2]) g14 = Gate(name="CX1_4", gate="cx", parameters=p14, qubits=[1, 4]) g34 = Gate(name="CX3_4", gate="cx", parameters=p34, qubits=[3, 4]) g45 = Gate(name="CX4_5", gate="cx", parameters=p45, qubits=[4, 5]) g25 = Gate(name="CX2_5", gate="cx", parameters=p25, qubits=[2, 5]) gate_list = [g01, g03, g12, g14, g34, g45, g25] bprop = BackendProperties( last_update_date=calib_time, backend_name="test_backend", qubits=qubit_list, backend_version="1.0.0", gates=gate_list, general=[], ) nalayout = NoiseAdaptiveLayout(bprop) nalayout.run(dag) initial_layout = nalayout.property_set["layout"] for qid in range(4): for qloc in [0, 2]: self.assertNotEqual(initial_layout[qr[qid]], qloc) if __name__ == "__main__": unittest.main()
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# 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/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# 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/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# 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/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# 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/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# 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/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# 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/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# 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/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# 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/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# 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/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# 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/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the Unroller pass""" from numpy import pi from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.extensions.simulator import Snapshot from qiskit.transpiler.passes import Unroller from qiskit.converters import circuit_to_dag, dag_to_circuit from qiskit.quantum_info import Operator from qiskit.test import QiskitTestCase from qiskit.exceptions import QiskitError from qiskit.circuit import Parameter, Qubit, Clbit from qiskit.circuit.library import U1Gate, U2Gate, U3Gate, CU1Gate, CU3Gate from qiskit.transpiler.target import Target class TestUnroller(QiskitTestCase): """Tests the Unroller pass.""" def test_basic_unroll(self): """Test decompose a single H into u2.""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.h(qr[0]) dag = circuit_to_dag(circuit) pass_ = Unroller(["u2"]) unrolled_dag = pass_.run(dag) op_nodes = unrolled_dag.op_nodes() self.assertEqual(len(op_nodes), 1) self.assertEqual(op_nodes[0].name, "u2") def test_basic_unroll_target(self): """Test decompose a single H into U2 from target.""" qc = QuantumCircuit(1) qc.h(0) target = Target(num_qubits=1) phi = Parameter("phi") lam = Parameter("lam") target.add_instruction(U2Gate(phi, lam)) dag = circuit_to_dag(qc) pass_ = Unroller(target=target) unrolled_dag = pass_.run(dag) op_nodes = unrolled_dag.op_nodes() self.assertEqual(len(op_nodes), 1) self.assertEqual(op_nodes[0].name, "u2") def test_unroll_toffoli(self): """Test unroll toffoli on multi regs to h, t, tdg, cx.""" qr1 = QuantumRegister(2, "qr1") qr2 = QuantumRegister(1, "qr2") circuit = QuantumCircuit(qr1, qr2) circuit.ccx(qr1[0], qr1[1], qr2[0]) dag = circuit_to_dag(circuit) pass_ = Unroller(["h", "t", "tdg", "cx"]) unrolled_dag = pass_.run(dag) op_nodes = unrolled_dag.op_nodes() self.assertEqual(len(op_nodes), 15) for node in op_nodes: self.assertIn(node.name, ["h", "t", "tdg", "cx"]) def test_unroll_1q_chain_conditional(self): """Test unroll chain of 1-qubit gates interrupted by conditional.""" qr = QuantumRegister(1, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.h(qr) circuit.tdg(qr) circuit.z(qr) circuit.t(qr) circuit.ry(0.5, qr) circuit.rz(0.3, qr) circuit.rx(0.1, qr) circuit.measure(qr, cr) circuit.x(qr).c_if(cr, 1) circuit.y(qr).c_if(cr, 1) circuit.z(qr).c_if(cr, 1) dag = circuit_to_dag(circuit) pass_ = Unroller(["u1", "u2", "u3"]) unrolled_dag = pass_.run(dag) # Pick up -1 * 0.3 / 2 global phase for one RZ -> U1. ref_circuit = QuantumCircuit(qr, cr, global_phase=-0.3 / 2) ref_circuit.append(U2Gate(0, pi), [qr[0]]) ref_circuit.append(U1Gate(-pi / 4), [qr[0]]) ref_circuit.append(U1Gate(pi), [qr[0]]) ref_circuit.append(U1Gate(pi / 4), [qr[0]]) ref_circuit.append(U3Gate(0.5, 0, 0), [qr[0]]) ref_circuit.append(U1Gate(0.3), [qr[0]]) ref_circuit.append(U3Gate(0.1, -pi / 2, pi / 2), [qr[0]]) ref_circuit.measure(qr[0], cr[0]) ref_circuit.append(U3Gate(pi, 0, pi), [qr[0]]).c_if(cr, 1) ref_circuit.append(U3Gate(pi, pi / 2, pi / 2), [qr[0]]).c_if(cr, 1) ref_circuit.append(U1Gate(pi), [qr[0]]).c_if(cr, 1) ref_dag = circuit_to_dag(ref_circuit) self.assertEqual(unrolled_dag, ref_dag) def test_unroll_no_basis(self): """Test when a given gate has no decompositions.""" qr = QuantumRegister(1, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.h(qr) dag = circuit_to_dag(circuit) pass_ = Unroller(basis=[]) with self.assertRaises(QiskitError): pass_.run(dag) def test_simple_unroll_parameterized_without_expressions(self): """Verify unrolling parameterized gates without expressions.""" qr = QuantumRegister(1) qc = QuantumCircuit(qr) theta = Parameter("theta") qc.rz(theta, qr[0]) dag = circuit_to_dag(qc) unrolled_dag = Unroller(["u1", "u3", "cx"]).run(dag) expected = QuantumCircuit(qr, global_phase=-theta / 2) expected.append(U1Gate(theta), [qr[0]]) self.assertEqual(circuit_to_dag(expected), unrolled_dag) def test_simple_unroll_parameterized_with_expressions(self): """Verify unrolling parameterized gates with expressions.""" qr = QuantumRegister(1) qc = QuantumCircuit(qr) theta = Parameter("theta") phi = Parameter("phi") sum_ = theta + phi qc.rz(sum_, qr[0]) dag = circuit_to_dag(qc) unrolled_dag = Unroller(["u1", "u3", "cx"]).run(dag) expected = QuantumCircuit(qr, global_phase=-sum_ / 2) expected.append(U1Gate(sum_), [qr[0]]) self.assertEqual(circuit_to_dag(expected), unrolled_dag) def test_definition_unroll_parameterized(self): """Verify that unrolling complex gates with parameters does not raise.""" qr = QuantumRegister(2) qc = QuantumCircuit(qr) theta = Parameter("theta") qc.append(CU1Gate(theta), [qr[1], qr[0]]) qc.append(CU1Gate(theta * theta), [qr[0], qr[1]]) dag = circuit_to_dag(qc) out_dag = Unroller(["u1", "cx"]).run(dag) self.assertEqual(out_dag.count_ops(), {"u1": 6, "cx": 4}) def test_unrolling_parameterized_composite_gates(self): """Verify unrolling circuits with parameterized composite gates.""" qr1 = QuantumRegister(2) subqc = QuantumCircuit(qr1) theta = Parameter("theta") subqc.rz(theta, qr1[0]) subqc.cx(qr1[0], qr1[1]) subqc.rz(theta, qr1[1]) # Expanding across register with shared parameter qr2 = QuantumRegister(4) qc = QuantumCircuit(qr2) qc.append(subqc.to_instruction(), [qr2[0], qr2[1]]) qc.append(subqc.to_instruction(), [qr2[2], qr2[3]]) dag = circuit_to_dag(qc) out_dag = Unroller(["u1", "u3", "cx"]).run(dag) # Pick up -1 * theta / 2 global phase four twice (once for each RZ -> P # in each of the two sub_instr instructions). expected = QuantumCircuit(qr2, global_phase=-1 * 4 * theta / 2.0) expected.append(U1Gate(theta), [qr2[0]]) expected.cx(qr2[0], qr2[1]) expected.append(U1Gate(theta), [qr2[1]]) expected.append(U1Gate(theta), [qr2[2]]) expected.cx(qr2[2], qr2[3]) expected.append(U1Gate(theta), [qr2[3]]) self.assertEqual(circuit_to_dag(expected), out_dag) # Expanding across register with shared parameter qc = QuantumCircuit(qr2) phi = Parameter("phi") gamma = Parameter("gamma") qc.append(subqc.to_instruction({theta: phi}), [qr2[0], qr2[1]]) qc.append(subqc.to_instruction({theta: gamma}), [qr2[2], qr2[3]]) dag = circuit_to_dag(qc) out_dag = Unroller(["u1", "u3", "cx"]).run(dag) expected = QuantumCircuit(qr2, global_phase=-1 * (2 * phi + 2 * gamma) / 2.0) expected.append(U1Gate(phi), [qr2[0]]) expected.cx(qr2[0], qr2[1]) expected.append(U1Gate(phi), [qr2[1]]) expected.append(U1Gate(gamma), [qr2[2]]) expected.cx(qr2[2], qr2[3]) expected.append(U1Gate(gamma), [qr2[3]]) self.assertEqual(circuit_to_dag(expected), out_dag) def test_unrolling_preserves_qregs_order(self): """Test unrolling a gate preseveres it's definition registers order""" qr = QuantumRegister(2, "qr1") qc = QuantumCircuit(qr) qc.cx(1, 0) gate = qc.to_gate() qr2 = QuantumRegister(2, "qr2") qc2 = QuantumCircuit(qr2) qc2.append(gate, qr2) dag = circuit_to_dag(qc2) out_dag = Unroller(["cx"]).run(dag) expected = QuantumCircuit(qr2) expected.cx(1, 0) self.assertEqual(circuit_to_dag(expected), out_dag) def test_unrolling_nested_gates_preserves_qregs_order(self): """Test unrolling a nested gate preseveres it's definition registers order.""" qr = QuantumRegister(2, "qr1") qc = QuantumCircuit(qr) qc.cx(1, 0) gate_level_1 = qc.to_gate() qr2 = QuantumRegister(2, "qr2") qc2 = QuantumCircuit(qr2) qc2.append(gate_level_1, [1, 0]) qc2.cp(pi, 1, 0) gate_level_2 = qc2.to_gate() qr3 = QuantumRegister(2, "qr3") qc3 = QuantumCircuit(qr3) qc3.append(gate_level_2, [1, 0]) qc3.cu(pi, pi, pi, 0, 1, 0) gate_level_3 = qc3.to_gate() qr4 = QuantumRegister(2, "qr4") qc4 = QuantumCircuit(qr4) qc4.append(gate_level_3, [0, 1]) dag = circuit_to_dag(qc4) out_dag = Unroller(["cx", "cp", "cu"]).run(dag) expected = QuantumCircuit(qr4) expected.cx(1, 0) expected.cp(pi, 0, 1) expected.cu(pi, pi, pi, 0, 1, 0) self.assertEqual(circuit_to_dag(expected), out_dag) def test_unrolling_global_phase_1q(self): """Test unrolling a circuit with global phase in a composite gate.""" circ = QuantumCircuit(1, global_phase=pi / 2) circ.x(0) circ.h(0) v = circ.to_gate() qc = QuantumCircuit(1) qc.append(v, [0]) dag = circuit_to_dag(qc) out_dag = Unroller(["cx", "x", "h"]).run(dag) qcd = dag_to_circuit(out_dag) self.assertEqual(Operator(qc), Operator(qcd)) def test_unrolling_global_phase_nested_gates(self): """Test unrolling a nested gate preseveres global phase.""" qc = QuantumCircuit(1, global_phase=pi) qc.x(0) gate = qc.to_gate() qc = QuantumCircuit(1) qc.append(gate, [0]) gate = qc.to_gate() qc = QuantumCircuit(1) qc.append(gate, [0]) dag = circuit_to_dag(qc) out_dag = Unroller(["x", "u"]).run(dag) qcd = dag_to_circuit(out_dag) self.assertEqual(Operator(qc), Operator(qcd)) def test_if_simple(self): """Test a simple if statement unrolls correctly.""" qubits = [Qubit(), Qubit()] clbits = [Clbit(), Clbit()] qc = QuantumCircuit(qubits, clbits) qc.h(0) qc.measure(0, 0) with qc.if_test((clbits[0], 0)): qc.x(0) qc.h(0) qc.measure(0, 1) with qc.if_test((clbits[1], 0)): qc.h(1) qc.cx(1, 0) dag = circuit_to_dag(qc) unrolled_dag = Unroller(["u", "cx"]).run(dag) expected = QuantumCircuit(qubits, clbits) expected.u(pi / 2, 0, pi, 0) expected.measure(0, 0) with expected.if_test((clbits[0], 0)): expected.u(pi, 0, pi, 0) expected.u(pi / 2, 0, pi, 0) expected.measure(0, 1) with expected.if_test((clbits[1], 0)): expected.u(pi / 2, 0, pi, 1) expected.cx(1, 0) expected_dag = circuit_to_dag(expected) self.assertEqual(unrolled_dag, expected_dag) def test_if_else_simple(self): """Test a simple if-else statement unrolls correctly.""" qubits = [Qubit(), Qubit()] clbits = [Clbit(), Clbit()] qc = QuantumCircuit(qubits, clbits) qc.h(0) qc.measure(0, 0) with qc.if_test((clbits[0], 0)) as else_: qc.x(0) with else_: qc.z(0) qc.h(0) qc.measure(0, 1) with qc.if_test((clbits[1], 0)) as else_: qc.h(1) qc.cx(1, 0) with else_: qc.h(0) qc.cx(0, 1) dag = circuit_to_dag(qc) unrolled_dag = Unroller(["u", "cx"]).run(dag) expected = QuantumCircuit(qubits, clbits) expected.u(pi / 2, 0, pi, 0) expected.measure(0, 0) with expected.if_test((clbits[0], 0)) as else_: expected.u(pi, 0, pi, 0) with else_: expected.u(0, 0, pi, 0) expected.u(pi / 2, 0, pi, 0) expected.measure(0, 1) with expected.if_test((clbits[1], 0)) as else_: expected.u(pi / 2, 0, pi, 1) expected.cx(1, 0) with else_: expected.u(pi / 2, 0, pi, 0) expected.cx(0, 1) expected_dag = circuit_to_dag(expected) self.assertEqual(unrolled_dag, expected_dag) def test_nested_control_flow(self): """Test unrolling nested control flow blocks.""" qr = QuantumRegister(2) cr1 = ClassicalRegister(1) cr2 = ClassicalRegister(1) cr3 = ClassicalRegister(1) qc = QuantumCircuit(qr, cr1, cr2, cr3) with qc.for_loop(range(3)): with qc.while_loop((cr1, 0)): qc.x(0) with qc.while_loop((cr2, 0)): qc.y(0) with qc.while_loop((cr3, 0)): qc.z(0) dag = circuit_to_dag(qc) unrolled_dag = Unroller(["u", "cx"]).run(dag) expected = QuantumCircuit(qr, cr1, cr2, cr3) with expected.for_loop(range(3)): with expected.while_loop((cr1, 0)): expected.u(pi, 0, pi, 0) with expected.while_loop((cr2, 0)): expected.u(pi, pi / 2, pi / 2, 0) with expected.while_loop((cr3, 0)): expected.u(0, 0, pi, 0) expected_dag = circuit_to_dag(expected) self.assertEqual(unrolled_dag, expected_dag) def test_parameterized_angle(self): """Test unrolling with parameterized angle""" qc = QuantumCircuit(1) index = Parameter("index") with qc.for_loop((0, 0.5 * pi), index) as param: qc.rx(param, 0) dag = circuit_to_dag(qc) unrolled_dag = Unroller(["u", "cx"]).run(dag) expected = QuantumCircuit(1) with expected.for_loop((0, 0.5 * pi), index) as param: expected.u(param, -pi / 2, pi / 2, 0) expected_dag = circuit_to_dag(expected) self.assertEqual(unrolled_dag, expected_dag) class TestUnrollAllInstructions(QiskitTestCase): """Test unrolling a circuit containing all standard instructions.""" def setUp(self): super().setUp() qr = self.qr = QuantumRegister(3, "qr") cr = self.cr = ClassicalRegister(3, "cr") self.circuit = QuantumCircuit(qr, cr) self.ref_circuit = QuantumCircuit(qr, cr) self.pass_ = Unroller(basis=["u3", "cx", "id"]) def compare_dags(self): """compare dags in class tests""" dag = circuit_to_dag(self.circuit) unrolled_dag = self.pass_.run(dag) ref_dag = circuit_to_dag(self.ref_circuit) self.assertEqual(unrolled_dag, ref_dag) def test_unroll_crx(self): """test unroll crx""" # qr_1: ─────■───── qr_1: ─────────────────■─────────────────────■───────────────────── # ┌────┴────┐ = ┌─────────────┐┌─┴─┐┌───────────────┐┌─┴─┐┌─────────────────┐ # qr_2: ┤ Rx(0.5) ├ qr_2: ┤ U3(0,0,π/2) ├┤ X ├┤ U3(-0.25,0,0) ├┤ X ├┤ U3(0.25,-π/2,0) ├ # └─────────┘ └─────────────┘└───┘└───────────────┘└───┘└─────────────────┘ self.circuit.crx(0.5, 1, 2) self.ref_circuit.append(U3Gate(0, 0, pi / 2), [2]) self.ref_circuit.cx(1, 2) self.ref_circuit.append(U3Gate(-0.25, 0, 0), [2]) self.ref_circuit.cx(1, 2) self.ref_circuit.append(U3Gate(0.25, -pi / 2, 0), [2]) self.compare_dags() def test_unroll_cry(self): """test unroll cry""" # qr_1: ─────■───── qr_1: ──────────────────■─────────────────────■── # ┌────┴────┐ = ┌──────────────┐┌─┴─┐┌───────────────┐┌─┴─┐ # qr_2: ┤ Ry(0.5) ├ qr_2: ┤ U3(0.25,0,0) ├┤ X ├┤ U3(-0.25,0,0) ├┤ X ├ # └─────────┘ └──────────────┘└───┘└───────────────┘└───┘ self.circuit.cry(0.5, 1, 2) self.ref_circuit.append(U3Gate(0.25, 0, 0), [2]) self.ref_circuit.cx(1, 2) self.ref_circuit.append(U3Gate(-0.25, 0, 0), [2]) self.ref_circuit.cx(1, 2) self.compare_dags() def test_unroll_ccx(self): """test unroll ccx""" # qr_0: ──■── qr_0: ──────────────────────────────────────■──────────────────────» # │ │ » # qr_1: ──■── = qr_1: ─────────────────■────────────────────┼───────────────────■──» # ┌─┴─┐ ┌─────────────┐┌─┴─┐┌──────────────┐┌─┴─┐┌─────────────┐┌─┴─┐» # qr_2: ┤ X ├ qr_2: ┤ U3(π/2,0,π) ├┤ X ├┤ U3(0,0,-π/4) ├┤ X ├┤ U3(0,0,π/4) ├┤ X ├» # └───┘ └─────────────┘└───┘└──────────────┘└───┘└─────────────┘└───┘» # « ┌─────────────┐ # «qr_0: ──────────────────■─────────■───────┤ U3(0,0,π/4) ├───■── # « ┌─────────────┐ │ ┌─┴─┐ ├─────────────┴┐┌─┴─┐ # «qr_1: ┤ U3(0,0,π/4) ├───┼───────┤ X ├─────┤ U3(0,0,-π/4) ├┤ X ├ # « ├─────────────┴┐┌─┴─┐┌────┴───┴────┐├─────────────┬┘└───┘ # «qr_2: ┤ U3(0,0,-π/4) ├┤ X ├┤ U3(0,0,π/4) ├┤ U3(π/2,0,π) ├────── # « └──────────────┘└───┘└─────────────┘└─────────────┘ self.circuit.ccx(0, 1, 2) self.ref_circuit.append(U3Gate(pi / 2, 0, pi), [2]) self.ref_circuit.cx(1, 2) self.ref_circuit.append(U3Gate(0, 0, -pi / 4), [2]) self.ref_circuit.cx(0, 2) self.ref_circuit.append(U3Gate(0, 0, pi / 4), [2]) self.ref_circuit.cx(1, 2) self.ref_circuit.append(U3Gate(0, 0, pi / 4), [1]) self.ref_circuit.append(U3Gate(0, 0, -pi / 4), [2]) self.ref_circuit.cx(0, 2) self.ref_circuit.cx(0, 1) self.ref_circuit.append(U3Gate(0, 0, pi / 4), [0]) self.ref_circuit.append(U3Gate(0, 0, -pi / 4), [1]) self.ref_circuit.cx(0, 1) self.ref_circuit.append(U3Gate(0, 0, pi / 4), [2]) self.ref_circuit.append(U3Gate(pi / 2, 0, pi), [2]) self.compare_dags() def test_unroll_ch(self): """test unroll ch""" # qr_0: ──■── qr_0: ───────────────────────────────────────────────■──────────────────» # ┌─┴─┐ = ┌─────────────┐┌─────────────┐┌─────────────┐┌─┴─┐┌──────────────┐» # qr_2: ┤ H ├ qr_2: ┤ U3(0,0,π/2) ├┤ U3(π/2,0,π) ├┤ U3(0,0,π/4) ├┤ X ├┤ U3(0,0,-π/4) ├» # └───┘ └─────────────┘└─────────────┘└─────────────┘└───┘└──────────────┘» # « # «qr_0: ─────────────────────────────── # « ┌─────────────┐┌──────────────┐ # «qr_2: ┤ U3(π/2,0,π) ├┤ U3(0,0,-π/2) ├ # « └─────────────┘└──────────────┘ self.circuit.ch(0, 2) self.ref_circuit.append(U3Gate(0, 0, pi / 2), [2]) self.ref_circuit.append(U3Gate(pi / 2, 0, pi), [2]) self.ref_circuit.append(U3Gate(0, 0, pi / 4), [2]) self.ref_circuit.cx(0, 2) self.ref_circuit.append(U3Gate(0, 0, -pi / 4), [2]) self.ref_circuit.append(U3Gate(pi / 2, 0, pi), [2]) self.ref_circuit.append(U3Gate(0, 0, -pi / 2), [2]) self.compare_dags() def test_unroll_crz(self): """test unroll crz""" # qr_1: ─────■───── qr_1: ──────────────────■─────────────────────■── # ┌────┴────┐ = ┌──────────────┐┌─┴─┐┌───────────────┐┌─┴─┐ # qr_2: ┤ Rz(0.5) ├ qr_2: ┤ U3(0,0,0.25) ├┤ X ├┤ U3(0,0,-0.25) ├┤ X ├ # └─────────┘ └──────────────┘└───┘└───────────────┘└───┘ self.circuit.crz(0.5, 1, 2) self.ref_circuit.append(U3Gate(0, 0, 0.25), [2]) self.ref_circuit.cx(1, 2) self.ref_circuit.append(U3Gate(0, 0, -0.25), [2]) self.ref_circuit.cx(1, 2) def test_unroll_cswap(self): """test unroll cswap""" # ┌───┐ » # qr_0: ─X─ qr_0: ┤ X ├─────────────────■────────────────────────────────────────■──» # │ └─┬─┘ │ │ » # qr_1: ─■─ = qr_1: ──┼───────────────────┼────────────────────■───────────────────┼──» # │ │ ┌─────────────┐┌─┴─┐┌──────────────┐┌─┴─┐┌─────────────┐┌─┴─┐» # qr_2: ─X─ qr_2: ──■──┤ U3(π/2,0,π) ├┤ X ├┤ U3(0,0,-π/4) ├┤ X ├┤ U3(0,0,π/4) ├┤ X ├» # └─────────────┘└───┘└──────────────┘└───┘└─────────────┘└───┘» # « ┌─────────────┐ ┌───┐ ┌──────────────┐┌───┐┌───┐ # «qr_0: ┤ U3(0,0,π/4) ├───────────┤ X ├─────┤ U3(0,0,-π/4) ├┤ X ├┤ X ├ # « └─────────────┘ └─┬─┘ ├─────────────┬┘└─┬─┘└─┬─┘ # «qr_1: ──────────────────■─────────■───────┤ U3(0,0,π/4) ├───■────┼── # « ┌──────────────┐┌─┴─┐┌─────────────┐├─────────────┤ │ # «qr_2: ┤ U3(0,0,-π/4) ├┤ X ├┤ U3(0,0,π/4) ├┤ U3(π/2,0,π) ├────────■── # « └──────────────┘└───┘└─────────────┘└─────────────┘ self.circuit.cswap(1, 0, 2) self.ref_circuit.cx(2, 0) self.ref_circuit.append(U3Gate(pi / 2, 0, pi), [2]) self.ref_circuit.cx(0, 2) self.ref_circuit.append(U3Gate(0, 0, -pi / 4), [2]) self.ref_circuit.cx(1, 2) self.ref_circuit.append(U3Gate(0, 0, pi / 4), [2]) self.ref_circuit.cx(0, 2) self.ref_circuit.append(U3Gate(0, 0, pi / 4), [0]) self.ref_circuit.append(U3Gate(0, 0, -pi / 4), [2]) self.ref_circuit.cx(1, 2) self.ref_circuit.cx(1, 0) self.ref_circuit.append(U3Gate(0, 0, -pi / 4), [0]) self.ref_circuit.append(U3Gate(0, 0, pi / 4), [1]) self.ref_circuit.cx(1, 0) self.ref_circuit.append(U3Gate(0, 0, pi / 4), [2]) self.ref_circuit.append(U3Gate(pi / 2, 0, pi), [2]) self.ref_circuit.cx(2, 0) self.compare_dags() def test_unroll_cu1(self): """test unroll cu1""" # ┌──────────────┐ # qr_0: ─■──────── qr_0: ┤ U3(0,0,0.05) ├──■─────────────────────■────────────────── # │U1(0.1) = └──────────────┘┌─┴─┐┌───────────────┐┌─┴─┐┌──────────────┐ # qr_2: ─■──────── qr_2: ────────────────┤ X ├┤ U3(0,0,-0.05) ├┤ X ├┤ U3(0,0,0.05) ├ # └───┘└───────────────┘└───┘└──────────────┘ self.circuit.append(CU1Gate(0.1), [0, 2]) self.ref_circuit.append(U3Gate(0, 0, 0.05), [0]) self.ref_circuit.cx(0, 2) self.ref_circuit.append(U3Gate(0, 0, -0.05), [2]) self.ref_circuit.cx(0, 2) self.ref_circuit.append(U3Gate(0, 0, 0.05), [2]) self.compare_dags() def test_unroll_cu3(self): """test unroll cu3""" # ┌──────────────┐ # q_1: ────────■──────── q_1: ─┤ U3(0,0,0.05) ├──■────────────────────────■─────────────────── # ┌───────┴───────┐ = ┌┴──────────────┤┌─┴─┐┌──────────────────┐┌─┴─┐┌───────────────┐ # q_2: ┤ U3(0.2,0.1,0) ├ q_2: ┤ U3(0,0,-0.05) ├┤ X ├┤ U3(-0.1,0,-0.05) ├┤ X ├┤ U3(0.1,0.1,0) ├ # └───────────────┘ └───────────────┘└───┘└──────────────────┘└───┘└───────────────┘ self.circuit.append(CU3Gate(0.2, 0.1, 0.0), [1, 2]) self.ref_circuit.append(U3Gate(0, 0, 0.05), [1]) self.ref_circuit.append(U3Gate(0, 0, -0.05), [2]) self.ref_circuit.cx(1, 2) self.ref_circuit.append(U3Gate(-0.1, 0, -0.05), [2]) self.ref_circuit.cx(1, 2) self.ref_circuit.append(U3Gate(0.1, 0.1, 0), [2]) self.compare_dags() def test_unroll_cx(self): """test unroll cx""" self.circuit.cx(1, 0) self.ref_circuit.cx(1, 0) self.compare_dags() def test_unroll_cy(self): """test unroll cy""" # qr_1: ──■── qr_1: ──────────────────■───────────────── # ┌─┴─┐ = ┌──────────────┐┌─┴─┐┌─────────────┐ # qr_2: ┤ Y ├ qr_2: ┤ U3(0,0,-π/2) ├┤ X ├┤ U3(0,0,π/2) ├ # └───┘ └──────────────┘└───┘└─────────────┘ self.circuit.cy(1, 2) self.ref_circuit.append(U3Gate(0, 0, -pi / 2), [2]) self.ref_circuit.cx(1, 2) self.ref_circuit.append(U3Gate(0, 0, pi / 2), [2]) self.compare_dags() def test_unroll_cz(self): """test unroll cz""" # ┌─────────────┐┌───┐┌─────────────┐ # qr_0: ─■─ qr_0: ┤ U3(π/2,0,π) ├┤ X ├┤ U3(π/2,0,π) ├ # │ = └─────────────┘└─┬─┘└─────────────┘ # qr_2: ─■─ qr_2: ─────────────────■───────────────── self.circuit.cz(2, 0) self.ref_circuit.append(U3Gate(pi / 2, 0, pi), [0]) self.ref_circuit.cx(2, 0) self.ref_circuit.append(U3Gate(pi / 2, 0, pi), [0]) self.compare_dags() def test_unroll_h(self): """test unroll h""" self.circuit.h(1) self.ref_circuit.append(U3Gate(pi / 2, 0, pi), [1]) self.compare_dags() def test_unroll_i(self): """test unroll i""" self.circuit.i(0) self.ref_circuit.i(0) self.compare_dags() def test_unroll_rx(self): """test unroll rx""" self.circuit.rx(0.1, 0) self.ref_circuit.append(U3Gate(0.1, -pi / 2, pi / 2), [0]) self.compare_dags() def test_unroll_ry(self): """test unroll ry""" self.circuit.ry(0.2, 1) self.ref_circuit.append(U3Gate(0.2, 0, 0), [1]) self.compare_dags() def test_unroll_rz(self): """test unroll rz""" self.circuit.rz(0.3, 2) self.ref_circuit.global_phase = -1 * 0.3 / 2 self.ref_circuit.append(U3Gate(0, 0, 0.3), [2]) self.compare_dags() def test_unroll_rzz(self): """test unroll rzz""" # global phase: 5.9832 # ┌───┐┌─────────────┐┌───┐ # qr_0: ─■──────── qr_0: ┤ X ├┤ U3(0,0,0.6) ├┤ X ├ # │ZZ(0.6) = └─┬─┘└─────────────┘└─┬─┘ # qr_1: ─■──────── qr_1: ──■───────────────────■── self.circuit.rzz(0.6, 1, 0) self.ref_circuit.global_phase = -1 * 0.6 / 2 self.ref_circuit.cx(1, 0) self.ref_circuit.append(U3Gate(0, 0, 0.6), [0]) self.ref_circuit.cx(1, 0) self.compare_dags() def test_unroll_s(self): """test unroll s""" self.circuit.s(0) self.ref_circuit.append(U3Gate(0, 0, pi / 2), [0]) self.compare_dags() def test_unroll_sdg(self): """test unroll sdg""" self.circuit.sdg(1) self.ref_circuit.append(U3Gate(0, 0, -pi / 2), [1]) self.compare_dags() def test_unroll_swap(self): """test unroll swap""" # ┌───┐ # qr_1: ─X─ qr_1: ──■──┤ X ├──■── # │ = ┌─┴─┐└─┬─┘┌─┴─┐ # qr_2: ─X─ qr_2: ┤ X ├──■──┤ X ├ # └───┘ └───┘ self.circuit.swap(1, 2) self.ref_circuit.cx(1, 2) self.ref_circuit.cx(2, 1) self.ref_circuit.cx(1, 2) self.compare_dags() def test_unroll_t(self): """test unroll t""" self.circuit.t(2) self.ref_circuit.append(U3Gate(0, 0, pi / 4), [2]) self.compare_dags() def test_unroll_tdg(self): """test unroll tdg""" self.circuit.tdg(0) self.ref_circuit.append(U3Gate(0, 0, -pi / 4), [0]) self.compare_dags() def test_unroll_u1(self): """test unroll u1""" self.circuit.append(U1Gate(0.1), [1]) self.ref_circuit.append(U3Gate(0, 0, 0.1), [1]) self.compare_dags() def test_unroll_u2(self): """test unroll u2""" self.circuit.append(U2Gate(0.2, -0.1), [0]) self.ref_circuit.append(U3Gate(pi / 2, 0.2, -0.1), [0]) self.compare_dags() def test_unroll_u3(self): """test unroll u3""" self.circuit.append(U3Gate(0.3, 0.0, -0.1), [2]) self.ref_circuit.append(U3Gate(0.3, 0.0, -0.1), [2]) self.compare_dags() def test_unroll_x(self): """test unroll x""" self.circuit.x(2) self.ref_circuit.append(U3Gate(pi, 0, pi), [2]) self.compare_dags() def test_unroll_y(self): """test unroll y""" self.circuit.y(1) self.ref_circuit.append(U3Gate(pi, pi / 2, pi / 2), [1]) self.compare_dags() def test_unroll_z(self): """test unroll z""" self.circuit.z(0) self.ref_circuit.append(U3Gate(0, 0, pi), [0]) self.compare_dags() def test_unroll_snapshot(self): """test unroll snapshot""" num_qubits = self.circuit.num_qubits instr = Snapshot("0", num_qubits=num_qubits) self.circuit.append(instr, range(num_qubits)) self.ref_circuit.append(instr, range(num_qubits)) self.compare_dags() def test_unroll_measure(self): """test unroll measure""" self.circuit.measure(self.qr, self.cr) self.ref_circuit.measure(self.qr, self.cr) self.compare_dags()
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# 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/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# 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/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# 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/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for circuit MPL drawer""" import unittest import os import math from test.visual import VisualTestUtilities from pathlib import Path import numpy as np from numpy import pi from qiskit.test import QiskitTestCase from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, transpile from qiskit.providers.fake_provider import FakeTenerife from qiskit.visualization.circuit.circuit_visualization import _matplotlib_circuit_drawer from qiskit.circuit.library import ( XGate, MCXGate, HGate, RZZGate, SwapGate, DCXGate, ZGate, SGate, U1Gate, CPhaseGate, ) from qiskit.circuit.library import MCXVChain from qiskit.extensions import HamiltonianGate from qiskit.circuit import Parameter, Qubit, Clbit from qiskit.circuit.library import IQP from qiskit.quantum_info.random import random_unitary from qiskit.utils import optionals if optionals.HAS_MATPLOTLIB: from matplotlib.pyplot import close as mpl_close else: raise ImportError('Must have Matplotlib installed. To install, run "pip install matplotlib".') BASE_DIR = Path(__file__).parent RESULT_DIR = Path(BASE_DIR) / "circuit_results" TEST_REFERENCE_DIR = Path(BASE_DIR) / "references" FAILURE_DIFF_DIR = Path(BASE_DIR).parent / "visual_test_failures" FAILURE_PREFIX = "circuit_failure_" class TestCircuitMatplotlibDrawer(QiskitTestCase): """Circuit MPL visualization""" def setUp(self): super().setUp() self.circuit_drawer = VisualTestUtilities.save_data_wrap( _matplotlib_circuit_drawer, str(self), RESULT_DIR ) if not os.path.exists(FAILURE_DIFF_DIR): os.makedirs(FAILURE_DIFF_DIR) if not os.path.exists(RESULT_DIR): os.makedirs(RESULT_DIR) def tearDown(self): super().tearDown() mpl_close("all") @staticmethod def _image_path(image_name): return os.path.join(RESULT_DIR, image_name) @staticmethod def _reference_path(image_name): return os.path.join(TEST_REFERENCE_DIR, image_name) def test_empty_circuit(self): """Test empty circuit""" circuit = QuantumCircuit() fname = "empty_circut.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_calibrations(self): """Test calibrations annotations See https://github.com/Qiskit/qiskit-terra/issues/5920 """ circuit = QuantumCircuit(2, 2) circuit.h(0) from qiskit import pulse with pulse.build(name="hadamard") as h_q0: pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(0) ) circuit.add_calibration("h", [0], h_q0) fname = "calibrations.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_calibrations_with_control_gates(self): """Test calibrations annotations See https://github.com/Qiskit/qiskit-terra/issues/5920 """ circuit = QuantumCircuit(2, 2) circuit.cx(0, 1) circuit.ch(0, 1) from qiskit import pulse with pulse.build(name="cnot") as cx_q01: pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(1) ) circuit.add_calibration("cx", [0, 1], cx_q01) with pulse.build(name="ch") as ch_q01: pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(1) ) circuit.add_calibration("ch", [0, 1], ch_q01) fname = "calibrations_with_control_gates.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_calibrations_with_swap_and_reset(self): """Test calibrations annotations See https://github.com/Qiskit/qiskit-terra/issues/5920 """ circuit = QuantumCircuit(2, 2) circuit.swap(0, 1) circuit.reset(0) from qiskit import pulse with pulse.build(name="swap") as swap_q01: pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(1) ) circuit.add_calibration("swap", [0, 1], swap_q01) with pulse.build(name="reset") as reset_q0: pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(1) ) circuit.add_calibration("reset", [0], reset_q0) fname = "calibrations_with_swap_and_reset.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_calibrations_with_rzz_and_rxx(self): """Test calibrations annotations See https://github.com/Qiskit/qiskit-terra/issues/5920 """ circuit = QuantumCircuit(2, 2) circuit.rzz(pi, 0, 1) circuit.rxx(pi, 0, 1) from qiskit import pulse with pulse.build(name="rzz") as rzz_q01: pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(1) ) circuit.add_calibration("rzz", [0, 1], rzz_q01) with pulse.build(name="rxx") as rxx_q01: pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(1) ) circuit.add_calibration("rxx", [0, 1], rxx_q01) fname = "calibrations_with_rzz_and_rxx.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_no_ops(self): """Test circuit with no ops. See https://github.com/Qiskit/qiskit-terra/issues/5393""" circuit = QuantumCircuit(2, 3) fname = "no_op_circut.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_long_name(self): """Test to see that long register names can be seen completely As reported in #2605 """ # add a register with a very long name qr = QuantumRegister(4, "veryLongQuantumRegisterName") # add another to make sure adjustments are made based on longest qrr = QuantumRegister(1, "q0") circuit = QuantumCircuit(qr, qrr) # check gates are shifted over accordingly circuit.h(qr) circuit.h(qr) circuit.h(qr) fname = "long_name.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_multi_underscore_reg_names(self): """Test that multi-underscores in register names display properly""" q_reg1 = QuantumRegister(1, "q1_re__g__g") q_reg3 = QuantumRegister(3, "q3_re_g__g") c_reg1 = ClassicalRegister(1, "c1_re_g__g") c_reg3 = ClassicalRegister(3, "c3_re_g__g") circuit = QuantumCircuit(q_reg1, q_reg3, c_reg1, c_reg3) fname = "multi_underscore_true.png" self.circuit_drawer(circuit, cregbundle=True, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) fname2 = "multi_underscore_false.png" self.circuit_drawer(circuit, cregbundle=False, filename=fname2) ratio2 = VisualTestUtilities._save_diff( self._image_path(fname2), self._reference_path(fname2), fname2, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) self.assertGreaterEqual(ratio2, 0.9999) def test_conditional(self): """Test that circuits with conditionals draw correctly""" qr = QuantumRegister(2, "q") cr = ClassicalRegister(2, "c") circuit = QuantumCircuit(qr, cr) # check gates are shifted over accordingly circuit.h(qr) circuit.measure(qr, cr) circuit.h(qr[0]).c_if(cr, 2) fname = "reg_conditional.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_bit_conditional_with_cregbundle(self): """Test that circuits with single bit conditionals draw correctly with cregbundle=True.""" qr = QuantumRegister(2, "q") cr = ClassicalRegister(2, "c") circuit = QuantumCircuit(qr, cr) circuit.x(qr[0]) circuit.measure(qr, cr) circuit.h(qr[0]).c_if(cr[0], 1) circuit.x(qr[1]).c_if(cr[1], 0) fname = "bit_conditional_bundle.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_bit_conditional_no_cregbundle(self): """Test that circuits with single bit conditionals draw correctly with cregbundle=False.""" qr = QuantumRegister(2, "q") cr = ClassicalRegister(2, "c") circuit = QuantumCircuit(qr, cr) circuit.x(qr[0]) circuit.measure(qr, cr) circuit.h(qr[0]).c_if(cr[0], 1) circuit.x(qr[1]).c_if(cr[1], 0) fname = "bit_conditional_no_bundle.png" self.circuit_drawer(circuit, filename=fname, cregbundle=False) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_plot_partial_barrier(self): """Test plotting of partial barriers.""" # generate a circuit with barrier and other barrier like instructions in q = QuantumRegister(2, "q") c = ClassicalRegister(2, "c") circuit = QuantumCircuit(q, c) # check for barriers circuit.h(q[0]) circuit.barrier(0) circuit.h(q[0]) fname = "plot_partial_barrier.png" self.circuit_drawer(circuit, filename=fname, plot_barriers=True) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_plot_barriers(self): """Test to see that plotting barriers works. If it is set to False, no blank columns are introduced""" # generate a circuit with barriers and other barrier like instructions in q = QuantumRegister(2, "q") c = ClassicalRegister(2, "c") circuit = QuantumCircuit(q, c) # check for barriers circuit.h(q[0]) circuit.barrier() # check for other barrier like commands circuit.h(q[1]) # this import appears to be unused, but is actually needed to get snapshot instruction import qiskit.extensions.simulator # pylint: disable=unused-import circuit.snapshot("1") # check the barriers plot properly when plot_barriers= True fname = "plot_barriers_true.png" self.circuit_drawer(circuit, filename=fname, plot_barriers=True) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) fname2 = "plot_barriers_false.png" self.circuit_drawer(circuit, filename=fname2, plot_barriers=False) ratio2 = VisualTestUtilities._save_diff( self._image_path(fname2), self._reference_path(fname2), fname2, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) self.assertGreaterEqual(ratio2, 0.9999) def test_no_barriers_false(self): """Generate the same circuit as test_plot_barriers but without the barrier commands as this is what the circuit should look like when displayed with plot barriers false""" q1 = QuantumRegister(2, "q") c1 = ClassicalRegister(2, "c") circuit = QuantumCircuit(q1, c1) circuit.h(q1[0]) circuit.h(q1[1]) fname = "no_barriers.png" self.circuit_drawer(circuit, filename=fname, plot_barriers=False) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_fold_minus1(self): """Test to see that fold=-1 is no folding""" qr = QuantumRegister(2, "q") cr = ClassicalRegister(1, "c") circuit = QuantumCircuit(qr, cr) for _ in range(3): circuit.h(0) circuit.x(0) fname = "fold_minus1.png" self.circuit_drawer(circuit, fold=-1, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_fold_4(self): """Test to see that fold=4 is folding""" qr = QuantumRegister(2, "q") cr = ClassicalRegister(1, "c") circuit = QuantumCircuit(qr, cr) for _ in range(3): circuit.h(0) circuit.x(0) fname = "fold_4.png" self.circuit_drawer(circuit, fold=4, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_big_gates(self): """Test large gates with params""" qr = QuantumRegister(6, "q") circuit = QuantumCircuit(qr) circuit.append(IQP([[6, 5, 3], [5, 4, 5], [3, 5, 1]]), [0, 1, 2]) desired_vector = [ 1 / math.sqrt(16) * complex(0, 1), 1 / math.sqrt(8) * complex(1, 0), 1 / math.sqrt(16) * complex(1, 1), 0, 0, 1 / math.sqrt(8) * complex(1, 2), 1 / math.sqrt(16) * complex(1, 0), 0, ] circuit.initialize(desired_vector, [qr[3], qr[4], qr[5]]) circuit.unitary([[1, 0], [0, 1]], [qr[0]]) matrix = np.zeros((4, 4)) theta = Parameter("theta") circuit.append(HamiltonianGate(matrix, theta), [qr[1], qr[2]]) circuit = circuit.bind_parameters({theta: 1}) circuit.isometry(np.eye(4, 4), list(range(3, 5)), []) fname = "big_gates.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_cnot(self): """Test different cnot gates (ccnot, mcx, etc)""" qr = QuantumRegister(6, "q") circuit = QuantumCircuit(qr) circuit.x(0) circuit.cx(0, 1) circuit.ccx(0, 1, 2) circuit.append(XGate().control(3, ctrl_state="010"), [qr[2], qr[3], qr[0], qr[1]]) circuit.append(MCXGate(num_ctrl_qubits=3, ctrl_state="101"), [qr[0], qr[1], qr[2], qr[4]]) circuit.append(MCXVChain(3, dirty_ancillas=True), [qr[0], qr[1], qr[2], qr[3], qr[5]]) fname = "cnot.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_cz(self): """Test Z and Controlled-Z Gates""" qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.z(0) circuit.cz(0, 1) circuit.append(ZGate().control(3, ctrl_state="101"), [0, 1, 2, 3]) circuit.append(ZGate().control(2), [1, 2, 3]) circuit.append(ZGate().control(1, ctrl_state="0", label="CZ Gate"), [2, 3]) fname = "cz.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_pauli_clifford(self): """Test Pauli(green) and Clifford(blue) gates""" qr = QuantumRegister(5, "q") circuit = QuantumCircuit(qr) circuit.x(0) circuit.y(0) circuit.z(0) circuit.id(0) circuit.h(1) circuit.cx(1, 2) circuit.cy(1, 2) circuit.cz(1, 2) circuit.swap(3, 4) circuit.s(3) circuit.sdg(3) circuit.iswap(3, 4) circuit.dcx(3, 4) fname = "pauli_clifford.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_creg_initial(self): """Test cregbundle and initial state options""" qr = QuantumRegister(2, "q") cr = ClassicalRegister(2, "c") circuit = QuantumCircuit(qr, cr) circuit.x(0) circuit.h(0) circuit.x(1) fname = "creg_initial_true.png" self.circuit_drawer(circuit, filename=fname, cregbundle=True, initial_state=True) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) fname2 = "creg_initial_false.png" self.circuit_drawer(circuit, filename=fname2, cregbundle=False, initial_state=False) ratio2 = VisualTestUtilities._save_diff( self._image_path(fname2), self._reference_path(fname2), fname2, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) self.assertGreaterEqual(ratio2, 0.9999) def test_r_gates(self): """Test all R gates""" qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.r(3 * pi / 4, 3 * pi / 8, 0) circuit.rx(pi / 2, 1) circuit.ry(-pi / 2, 2) circuit.rz(3 * pi / 4, 3) circuit.rxx(pi / 2, 0, 1) circuit.ryy(3 * pi / 4, 2, 3) circuit.rzx(-pi / 2, 0, 1) circuit.rzz(pi / 2, 2, 3) fname = "r_gates.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_ctrl_labels(self): """Test control labels""" qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.cy(1, 0, label="Bottom Y label") circuit.cu(pi / 2, pi / 2, pi / 2, 0, 2, 3, label="Top U label") circuit.ch(0, 1, label="Top H label") circuit.append( HGate(label="H gate label").control(3, label="H control label", ctrl_state="010"), [qr[1], qr[2], qr[3], qr[0]], ) fname = "ctrl_labels.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_cswap_rzz(self): """Test controlled swap and rzz gates""" qr = QuantumRegister(5, "q") circuit = QuantumCircuit(qr) circuit.cswap(0, 1, 2) circuit.append(RZZGate(3 * pi / 4).control(3, ctrl_state="010"), [2, 1, 4, 3, 0]) fname = "cswap_rzz.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_ghz_to_gate(self): """Test controlled GHZ to_gate circuit""" qr = QuantumRegister(5, "q") circuit = QuantumCircuit(qr) ghz_circuit = QuantumCircuit(3, name="this is a WWWWWWWWWWWide name Ctrl-GHZ Circuit") ghz_circuit.h(0) ghz_circuit.cx(0, 1) ghz_circuit.cx(1, 2) ghz = ghz_circuit.to_gate() ccghz = ghz.control(2, ctrl_state="10") circuit.append(ccghz, [4, 0, 1, 3, 2]) fname = "ghz_to_gate.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_scale(self): """Tests scale See: https://github.com/Qiskit/qiskit-terra/issues/4179""" circuit = QuantumCircuit(5) circuit.unitary(random_unitary(2**5), circuit.qubits) fname = "scale_default.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) fname2 = "scale_half.png" self.circuit_drawer(circuit, filename=fname2, scale=0.5) ratio2 = VisualTestUtilities._save_diff( self._image_path(fname2), self._reference_path(fname2), fname2, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) fname3 = "scale_double.png" self.circuit_drawer(circuit, filename=fname3, scale=2) ratio3 = VisualTestUtilities._save_diff( self._image_path(fname3), self._reference_path(fname3), fname3, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) self.assertGreaterEqual(ratio2, 0.9999) self.assertGreaterEqual(ratio3, 0.9999) def test_pi_param_expr(self): """Test pi in circuit with parameter expression.""" x, y = Parameter("x"), Parameter("y") circuit = QuantumCircuit(1) circuit.rx((pi - x) * (pi - y), 0) fname = "pi_in_param_expr.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_partial_layout(self): """Tests partial_layout See: https://github.com/Qiskit/qiskit-terra/issues/4757""" circuit = QuantumCircuit(3) circuit.h(1) transpiled = transpile( circuit, backend=FakeTenerife(), basis_gates=["id", "cx", "rz", "sx", "x"], optimization_level=0, initial_layout=[1, 2, 0], seed_transpiler=0, ) fname = "partial_layout.png" self.circuit_drawer(transpiled, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_init_reset(self): """Test reset and initialize with 1 and 2 qubits""" circuit = QuantumCircuit(2) circuit.initialize([0, 1], 0) circuit.reset(1) circuit.initialize([0, 1, 0, 0], [0, 1]) fname = "init_reset.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_with_global_phase(self): """Tests with global phase""" circuit = QuantumCircuit(3, global_phase=1.57079632679) circuit.h(range(3)) fname = "global_phase.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_alternative_colors(self): """Tests alternative color schemes""" ratios = [] for style in ["iqx", "iqx-dark", "textbook"]: with self.subTest(style=style): circuit = QuantumCircuit(7) circuit.h(0) circuit.x(0) circuit.cx(0, 1) circuit.ccx(0, 1, 2) circuit.swap(0, 1) circuit.cswap(0, 1, 2) circuit.append(SwapGate().control(2), [0, 1, 2, 3]) circuit.dcx(0, 1) circuit.append(DCXGate().control(1), [0, 1, 2]) circuit.append(DCXGate().control(2), [0, 1, 2, 3]) circuit.z(4) circuit.s(4) circuit.sdg(4) circuit.t(4) circuit.tdg(4) circuit.p(pi / 2, 4) circuit.cz(5, 6) circuit.cp(pi / 2, 5, 6) circuit.y(5) circuit.rx(pi / 3, 5) circuit.rzx(pi / 2, 5, 6) circuit.u(pi / 2, pi / 2, pi / 2, 5) circuit.barrier(5, 6) circuit.reset(5) fname = f"{style}_color.png" self.circuit_drawer(circuit, style={"name": style}, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) ratios.append(ratio) for ratio in ratios: self.assertGreaterEqual(ratio, 0.9999) def test_reverse_bits(self): """Tests reverse_bits parameter""" circuit = QuantumCircuit(3) circuit.h(0) circuit.cx(0, 1) circuit.ccx(2, 1, 0) fname = "reverse_bits.png" self.circuit_drawer(circuit, reverse_bits=True, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_bw(self): """Tests black and white style parameter""" circuit = QuantumCircuit(3, 3) circuit.h(0) circuit.x(1) circuit.sdg(2) circuit.cx(0, 1) circuit.ccx(2, 1, 0) circuit.swap(1, 2) circuit.measure_all() fname = "bw.png" self.circuit_drawer(circuit, style={"name": "bw"}, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_user_style(self): """Tests loading a user style""" circuit = QuantumCircuit(7) circuit.h(0) circuit.append(HGate(label="H2"), [1]) circuit.x(0) circuit.cx(0, 1) circuit.ccx(0, 1, 2) circuit.swap(0, 1) circuit.cswap(0, 1, 2) circuit.append(SwapGate().control(2), [0, 1, 2, 3]) circuit.dcx(0, 1) circuit.append(DCXGate().control(1), [0, 1, 2]) circuit.append(DCXGate().control(2), [0, 1, 2, 3]) circuit.z(4) circuit.append(SGate(label="S1"), [4]) circuit.sdg(4) circuit.t(4) circuit.tdg(4) circuit.p(pi / 2, 4) circuit.cz(5, 6) circuit.cp(pi / 2, 5, 6) circuit.y(5) circuit.rx(pi / 3, 5) circuit.rzx(pi / 2, 5, 6) circuit.u(pi / 2, pi / 2, pi / 2, 5) circuit.barrier(5, 6) circuit.reset(5) fname = "user_style.png" self.circuit_drawer( circuit, style={ "name": "user_style", "displaytext": {"H2": "H_2"}, "displaycolor": {"H2": ("#EEDD00", "#FF0000")}, }, filename=fname, ) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_subfont_change(self): """Tests changing the subfont size""" circuit = QuantumCircuit(3) circuit.h(0) circuit.x(0) circuit.u(pi / 2, pi / 2, pi / 2, 1) circuit.p(pi / 2, 2) style = {"name": "iqx", "subfontsize": 11} fname = "subfont.png" self.circuit_drawer(circuit, style=style, filename=fname) self.assertEqual(style, {"name": "iqx", "subfontsize": 11}) # check does not change style ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_meas_condition(self): """Tests measure with a condition""" qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") circuit = QuantumCircuit(qr, cr) circuit.h(qr[0]) circuit.measure(qr[0], cr[0]) circuit.h(qr[1]).c_if(cr, 1) fname = "meas_condition.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_reverse_bits_condition(self): """Tests reverse_bits with a condition and gate above""" cr = ClassicalRegister(2, "cr") cr2 = ClassicalRegister(1, "cr2") qr = QuantumRegister(3, "qr") circuit = QuantumCircuit(qr, cr, cr2) circuit.h(0) circuit.h(1) circuit.h(2) circuit.x(0) circuit.x(0) circuit.measure(2, 1) circuit.x(2).c_if(cr, 2) fname = "reverse_bits_cond_true.png" self.circuit_drawer(circuit, cregbundle=False, reverse_bits=True, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) fname2 = "reverse_bits_cond_false.png" self.circuit_drawer(circuit, cregbundle=False, reverse_bits=False, filename=fname2) ratio2 = VisualTestUtilities._save_diff( self._image_path(fname2), self._reference_path(fname2), fname2, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) self.assertGreaterEqual(ratio2, 0.9999) def test_style_custom_gates(self): """Tests style for custom gates""" def cnotnot(gate_label): gate_circuit = QuantumCircuit(3, name=gate_label) gate_circuit.cnot(0, 1) gate_circuit.cnot(0, 2) gate = gate_circuit.to_gate() return gate q = QuantumRegister(3, name="q") circuit = QuantumCircuit(q) circuit.append(cnotnot("CNOTNOT"), [q[0], q[1], q[2]]) circuit.append(cnotnot("CNOTNOT_PRIME"), [q[0], q[1], q[2]]) circuit.h(q[0]) fname = "style_custom_gates.png" self.circuit_drawer( circuit, style={ "displaycolor": {"CNOTNOT": ("#000000", "#FFFFFF"), "h": ("#A1A1A1", "#043812")}, "displaytext": {"CNOTNOT_PRIME": "$\\mathrm{CNOTNOT}'$"}, }, filename=fname, ) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_6095(self): """Tests controlled-phase gate style See https://github.com/Qiskit/qiskit-terra/issues/6095""" circuit = QuantumCircuit(2) circuit.cp(1.0, 0, 1) circuit.h(1) fname = "6095.png" self.circuit_drawer( circuit, style={"displaycolor": {"cp": ("#A27486", "#000000"), "h": ("#A27486", "#000000")}}, filename=fname, ) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_instruction_1q_1c(self): """Tests q0-cr0 instruction on a circuit""" qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") circuit = QuantumCircuit(qr, cr) inst = QuantumCircuit(1, 1, name="Inst").to_instruction() circuit.append(inst, [qr[0]], [cr[0]]) fname = "instruction_1q_1c.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_instruction_3q_3c_circ1(self): """Tests q0-q1-q2-cr_20-cr0-cr1 instruction on a circuit""" qr = QuantumRegister(4, "qr") cr = ClassicalRegister(2, "cr") cr2 = ClassicalRegister(2, "cr2") circuit = QuantumCircuit(qr, cr, cr2) inst = QuantumCircuit(3, 3, name="Inst").to_instruction() circuit.append(inst, [qr[0], qr[1], qr[2]], [cr2[0], cr[0], cr[1]]) fname = "instruction_3q_3c_circ1.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_instruction_3q_3c_circ2(self): """Tests q3-q0-q2-cr0-cr1-cr_20 instruction on a circuit""" qr = QuantumRegister(4, "qr") cr = ClassicalRegister(2, "cr") cr2 = ClassicalRegister(2, "cr2") circuit = QuantumCircuit(qr, cr, cr2) inst = QuantumCircuit(3, 3, name="Inst").to_instruction() circuit.append(inst, [qr[3], qr[0], qr[2]], [cr[0], cr[1], cr2[0]]) fname = "instruction_3q_3c_circ2.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_instruction_3q_3c_circ3(self): """Tests q3-q1-q2-cr_31-cr1-cr_30 instruction on a circuit""" qr = QuantumRegister(4, "qr") cr = ClassicalRegister(2, "cr") cr2 = ClassicalRegister(1, "cr2") cr3 = ClassicalRegister(2, "cr3") circuit = QuantumCircuit(qr, cr, cr2, cr3) inst = QuantumCircuit(3, 3, name="Inst").to_instruction() circuit.append(inst, [qr[3], qr[1], qr[2]], [cr3[1], cr[1], cr3[0]]) fname = "instruction_3q_3c_circ3.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_overwide_gates(self): """Test gates don't exceed width of default fold""" circuit = QuantumCircuit(5) initial_state = np.zeros(2**5) initial_state[5] = 1 circuit.initialize(initial_state) fname = "wide_params.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_one_bit_regs(self): """Test registers with only one bit display without number""" qr1 = QuantumRegister(1, "qr1") qr2 = QuantumRegister(2, "qr2") cr1 = ClassicalRegister(1, "cr1") cr2 = ClassicalRegister(2, "cr2") circuit = QuantumCircuit(qr1, qr2, cr1, cr2) circuit.h(0) circuit.measure(0, 0) fname = "one_bit_regs.png" self.circuit_drawer(circuit, cregbundle=False, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_user_ax_subplot(self): """Test for when user supplies ax for a subplot""" import matplotlib.pyplot as plt fig = plt.figure(1, figsize=(6, 4)) fig.patch.set_facecolor("white") ax1 = fig.add_subplot(1, 2, 1) ax2 = fig.add_subplot(1, 2, 2) ax1.plot([1, 2, 3]) circuit = QuantumCircuit(4) circuit.h(0) circuit.cx(0, 1) circuit.h(1) circuit.cx(1, 2) plt.close(fig) fname = "user_ax.png" self.circuit_drawer(circuit, ax=ax2, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_figwidth(self): """Test style dict 'figwidth'""" circuit = QuantumCircuit(3) circuit.h(0) circuit.cx(0, 1) circuit.x(1) circuit.cx(1, 2) circuit.x(2) fname = "figwidth.png" self.circuit_drawer(circuit, style={"figwidth": 5}, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_registerless_one_bit(self): """Test circuit with one-bit registers and registerless bits.""" qrx = QuantumRegister(2, "qrx") qry = QuantumRegister(1, "qry") crx = ClassicalRegister(2, "crx") circuit = QuantumCircuit(qrx, [Qubit(), Qubit()], qry, [Clbit(), Clbit()], crx) fname = "registerless_one_bit.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_measures_with_conditions(self): """Test that a measure containing a condition displays""" qr = QuantumRegister(2, "qr") cr1 = ClassicalRegister(2, "cr1") cr2 = ClassicalRegister(2, "cr2") circuit = QuantumCircuit(qr, cr1, cr2) circuit.h(0) circuit.h(1) circuit.measure(0, cr1[1]) circuit.measure(1, cr2[0]).c_if(cr1, 1) circuit.h(0).c_if(cr2, 3) fname = "measure_cond_false.png" self.circuit_drawer(circuit, cregbundle=False, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) fname2 = "measure_cond_true.png" self.circuit_drawer(circuit, cregbundle=True, filename=fname2) ratio2 = VisualTestUtilities._save_diff( self._image_path(fname2), self._reference_path(fname2), fname2, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) self.assertGreaterEqual(ratio2, 0.9999) def test_conditions_measures_with_bits(self): """Test that gates with conditions and measures work with bits""" bits = [Qubit(), Qubit(), Clbit(), Clbit()] cr = ClassicalRegister(2, "cr") crx = ClassicalRegister(3, "cs") circuit = QuantumCircuit(bits, cr, [Clbit()], crx) circuit.x(0).c_if(crx[1], 0) circuit.measure(0, bits[3]) fname = "measure_cond_bits_false.png" self.circuit_drawer(circuit, cregbundle=False, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) fname2 = "measure_cond_bits_true.png" self.circuit_drawer(circuit, cregbundle=True, filename=fname2) ratio2 = VisualTestUtilities._save_diff( self._image_path(fname2), self._reference_path(fname2), fname2, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) self.assertGreaterEqual(ratio2, 0.9999) def test_conditional_gates_right_of_measures_with_bits(self): """Test that gates with conditions draw to right of measures when same bit""" qr = QuantumRegister(3, "qr") cr = ClassicalRegister(2, "cr") circuit = QuantumCircuit(qr, cr) circuit.h(qr[0]) circuit.measure(qr[0], cr[1]) circuit.h(qr[1]).c_if(cr[1], 0) circuit.h(qr[2]).c_if(cr[0], 0) fname = "measure_cond_bits_right.png" self.circuit_drawer(circuit, cregbundle=False, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_conditions_with_bits_reverse(self): """Test that gates with conditions work with bits reversed""" bits = [Qubit(), Qubit(), Clbit(), Clbit()] cr = ClassicalRegister(2, "cr") crx = ClassicalRegister(2, "cs") circuit = QuantumCircuit(bits, cr, [Clbit()], crx) circuit.x(0).c_if(bits[3], 0) fname = "cond_bits_reverse.png" self.circuit_drawer(circuit, cregbundle=False, reverse_bits=True, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_sidetext_with_condition(self): """Test that sidetext gates align properly with conditions""" qr = QuantumRegister(2, "q") cr = ClassicalRegister(2, "c") circuit = QuantumCircuit(qr, cr) circuit.append(CPhaseGate(pi / 2), [qr[0], qr[1]]).c_if(cr[1], 1) fname = "sidetext_condition.png" self.circuit_drawer(circuit, cregbundle=False, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_fold_with_conditions(self): """Test that gates with conditions draw correctly when folding""" qr = QuantumRegister(3) cr = ClassicalRegister(5) circuit = QuantumCircuit(qr, cr) circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 1) circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 3) circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 5) circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 7) circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 9) circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 11) circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 13) circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 15) circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 17) circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 19) circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 21) circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 23) circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 25) circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 27) circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 29) circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 31) fname = "fold_with_conditions.png" self.circuit_drawer(circuit, cregbundle=False, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_idle_wires_barrier(self): """Test that idle_wires False works with barrier""" circuit = QuantumCircuit(4, 4) circuit.x(2) circuit.barrier() fname = "idle_wires_barrier.png" self.circuit_drawer(circuit, cregbundle=False, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_wire_order(self): """Test the wire_order option""" qr = QuantumRegister(4, "q") cr = ClassicalRegister(4, "c") cr2 = ClassicalRegister(2, "cx") circuit = QuantumCircuit(qr, cr, cr2) circuit.h(0) circuit.h(3) circuit.x(1) circuit.x(3).c_if(cr, 10) fname = "wire_order.png" self.circuit_drawer( circuit, cregbundle=False, wire_order=[2, 1, 3, 0, 6, 8, 9, 5, 4, 7], filename=fname, ) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_barrier_label(self): """Test the barrier label""" circuit = QuantumCircuit(2) circuit.x(0) circuit.y(1) circuit.barrier() circuit.y(0) circuit.x(1) circuit.barrier(label="End Y/X") fname = "barrier_label.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_if_op(self): """Test the IfElseOp with if only""" qr = QuantumRegister(4, "q") cr = ClassicalRegister(2, "cr") circuit = QuantumCircuit(qr, cr) with circuit.if_test((cr[1], 1)): circuit.h(0) circuit.cx(0, 1) fname = "if_op.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_if_else_op(self): """Test the IfElseOp with else""" qr = QuantumRegister(4, "q") cr = ClassicalRegister(2, "cr") circuit = QuantumCircuit(qr, cr) with circuit.if_test((cr[1], 1)) as _else: circuit.h(0) circuit.cx(0, 1) with _else: circuit.cx(0, 1) fname = "if_else_op.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_if_else_op_textbook_style(self): """Test the IfElseOp with else in textbook style""" qr = QuantumRegister(4, "q") cr = ClassicalRegister(2, "cr") circuit = QuantumCircuit(qr, cr) with circuit.if_test((cr[1], 1)) as _else: circuit.h(0) circuit.cx(0, 1) with _else: circuit.cx(0, 1) fname = "if_else_op_textbook.png" self.circuit_drawer(circuit, style="textbook", filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_if_else_with_body(self): """Test the IfElseOp with adding a body manually""" qr = QuantumRegister(4, "q") cr = ClassicalRegister(3, "cr") circuit = QuantumCircuit(qr, cr) circuit.h(0) circuit.h(1) circuit.measure(0, 1) circuit.measure(1, 2) circuit.x(2) circuit.x(2, label="XLabel").c_if(cr, 2) qr2 = QuantumRegister(3, "qr2") qc2 = QuantumCircuit(qr2, cr) qc2.x(1) qc2.y(1) qc2.z(0) qc2.x(0, label="X1i").c_if(cr, 4) circuit.if_else((cr[1], 1), qc2, None, [0, 1, 2], [0, 1, 2]) circuit.x(0, label="X1i") fname = "if_else_body.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_if_else_op_nested(self): """Test the IfElseOp with complex nested if/else""" qr = QuantumRegister(4, "q") cr = ClassicalRegister(3, "cr") circuit = QuantumCircuit(qr, cr) circuit.h(0) with circuit.if_test((cr[1], 1)) as _else: circuit.x(0, label="X c_if").c_if(cr, 4) with circuit.if_test((cr[2], 1)): circuit.z(0) circuit.y(1) with circuit.if_test((cr[1], 1)): circuit.y(1) circuit.z(2) with circuit.if_test((cr[2], 1)): circuit.cx(0, 1) with circuit.if_test((cr[1], 1)): circuit.h(0) circuit.x(1) with _else: circuit.y(1) with circuit.if_test((cr[2], 1)): circuit.x(0) circuit.x(1) inst = QuantumCircuit(2, 2, name="Inst").to_instruction() circuit.append(inst, [qr[0], qr[1]], [cr[0], cr[1]]) circuit.x(0) fname = "if_else_op_nested.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_if_else_op_wire_order(self): """Test the IfElseOp with complex nested if/else and wire_order""" qr = QuantumRegister(4, "q") cr = ClassicalRegister(3, "cr") circuit = QuantumCircuit(qr, cr) circuit.h(0) with circuit.if_test((cr[1], 1)) as _else: circuit.x(0, label="X c_if").c_if(cr, 4) with circuit.if_test((cr[2], 1)): circuit.z(0) circuit.y(1) with circuit.if_test((cr[1], 1)): circuit.y(1) circuit.z(2) with circuit.if_test((cr[2], 1)): circuit.cx(0, 1) with circuit.if_test((cr[1], 1)): circuit.h(0) circuit.x(1) with _else: circuit.y(1) with circuit.if_test((cr[2], 1)): circuit.x(0) circuit.x(1) inst = QuantumCircuit(2, 2, name="Inst").to_instruction() circuit.append(inst, [qr[0], qr[1]], [cr[0], cr[1]]) circuit.x(0) fname = "if_else_op_wire_order.png" self.circuit_drawer(circuit, wire_order=[2, 0, 3, 1, 4, 5, 6], filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_if_else_op_fold(self): """Test the IfElseOp with complex nested if/else and fold""" qr = QuantumRegister(4, "q") cr = ClassicalRegister(3, "cr") circuit = QuantumCircuit(qr, cr) circuit.h(0) with circuit.if_test((cr[1], 1)) as _else: circuit.x(0, label="X c_if").c_if(cr, 4) with circuit.if_test((cr[2], 1)): circuit.z(0) circuit.y(1) with circuit.if_test((cr[1], 1)): circuit.y(1) circuit.z(2) with circuit.if_test((cr[2], 1)): circuit.cx(0, 1) with circuit.if_test((cr[1], 1)): circuit.h(0) circuit.x(1) with _else: circuit.y(1) with circuit.if_test((cr[2], 1)): circuit.x(0) circuit.x(1) inst = QuantumCircuit(2, 2, name="Inst").to_instruction() circuit.append(inst, [qr[0], qr[1]], [cr[0], cr[1]]) circuit.x(0) fname = "if_else_op_fold.png" self.circuit_drawer(circuit, fold=7, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_while_loop_op(self): """Test the WhileLoopOp""" qr = QuantumRegister(4, "q") cr = ClassicalRegister(3, "cr") circuit = QuantumCircuit(qr, cr) circuit.h(0) circuit.measure(0, 2) with circuit.while_loop((cr[0], 0)): circuit.h(0) circuit.cx(0, 1) circuit.measure(0, 0) with circuit.if_test((cr[2], 1)): circuit.x(0) fname = "while_loop.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_for_loop_op(self): """Test the ForLoopOp""" qr = QuantumRegister(4, "q") cr = ClassicalRegister(3, "cr") circuit = QuantumCircuit(qr, cr) a = Parameter("a") circuit.h(0) circuit.measure(0, 2) with circuit.for_loop((2, 4, 8, 16), loop_parameter=a): circuit.h(0) circuit.cx(0, 1) circuit.rx(pi / a, 1) circuit.measure(0, 0) with circuit.if_test((cr[2], 1)): circuit.z(0) fname = "for_loop.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_switch_case_op(self): """Test the SwitchCaseOp""" qreg = QuantumRegister(3, "q") creg = ClassicalRegister(3, "cr") circuit = QuantumCircuit(qreg, creg) circuit.h([0, 1, 2]) circuit.measure([0, 1, 2], [0, 1, 2]) with circuit.switch(creg) as case: with case(0, 1, 2): circuit.x(0) with case(3, 4, 5): circuit.y(1) circuit.y(0) circuit.y(0) with case(case.DEFAULT): circuit.cx(0, 1) circuit.h(0) fname = "switch_case.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) if __name__ == "__main__": unittest.main(verbosity=1)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# 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()
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# -*- coding: utf-8 -*- # 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. # pylint: disable=missing-docstring """Tests for comparing the outputs of circuit drawer with expected ones.""" import os import unittest from codecs import encode from math import pi from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.tools.visualization import HAS_MATPLOTLIB, circuit_drawer from .visualization import QiskitVisualizationTestCase, path_to_diagram_reference class TestCircuitVisualizationImplementation(QiskitVisualizationTestCase): """Visual accuracy of visualization tools outputs tests.""" latex_reference = path_to_diagram_reference('circuit_latex_ref.png') matplotlib_reference = path_to_diagram_reference('circuit_matplotlib_ref.png') text_reference = path_to_diagram_reference('circuit_text_ref.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.iden(qr[0]) circuit.reset(qr[0]) circuit.rx(pi, qr[0]) circuit.ry(pi, qr[0]) circuit.rz(pi, qr[0]) circuit.u0(pi, qr[0]) circuit.u1(pi, qr[0]) circuit.u2(pi, pi, qr[0]) circuit.u3(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.cu1(pi, qr[0], qr[1]) circuit.cu3(pi, pi, pi, qr[0], qr[1]) circuit.crz(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 # TODO: Enable for refactoring purposes and enable by default when we can # decide if the backend is available or not. @unittest.skip('Useful for refactoring purposes, skipping by default.') def test_latex_drawer(self): filename = self._get_resource_path('current_latex.png') qc = self.sample_circuit() circuit_drawer(qc, filename=filename, output='latex') self.assertImagesAreEqual(filename, self.latex_reference) os.remove(filename) # TODO: Enable for refactoring purposes and enable by default when we can # decide if the backend is available or not. @unittest.skipIf(not HAS_MATPLOTLIB, 'matplotlib not available.') @unittest.skip('Useful for refactoring purposes, skipping by default.') def test_matplotlib_drawer(self): filename = self._get_resource_path('current_matplot.png') qc = self.sample_circuit() circuit_drawer(qc, filename=filename, output='mpl') self.assertImagesAreEqual(filename, self.matplotlib_reference) os.remove(filename) def test_text_drawer(self): filename = self._get_resource_path('current_textplot.txt') qc = self.sample_circuit() output = circuit_drawer(qc, filename=filename, output="text", line_length=-1) self.assertFilesAreEqual(filename, self.text_reference) os.remove(filename) try: encode(str(output), encoding='cp437') except UnicodeEncodeError: self.fail("_text_circuit_drawer() should only use extended ascii (aka code page 437).") if __name__ == '__main__': unittest.main(verbosity=2)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for DAG visualization tool.""" import unittest from qiskit import QuantumRegister, QuantumCircuit from qiskit.test import QiskitTestCase from qiskit.tools.visualization import dag_drawer from qiskit.visualization.exceptions import VisualizationError from qiskit.converters import circuit_to_dag class TestDagDrawer(QiskitTestCase): """Qiskit DAG drawer tests.""" def setUp(self): qr = QuantumRegister(2, 'qr') circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) self.dag = circuit_to_dag(circuit) def test_dag_drawer_no_graphviz(self): """Test dag draw with no graphviz.""" with unittest.mock.patch('nxpd.pydot.find_graphviz', return_value=None) as _: self.assertRaises(VisualizationError, dag_drawer, self.dag) if __name__ == '__main__': unittest.main(verbosity=2)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# -*- coding: utf-8 -*- # 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 tools.""" import os import logging import unittest from inspect import signature import numpy as np from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.visualization import utils from qiskit.visualization import circuit_drawer from qiskit.test import QiskitTestCase logger = logging.getLogger(__name__) class TestLatexSourceGenerator(QiskitTestCase): """Qiskit latex source generator tests.""" def random_circuit(self, width=3, depth=3, max_operands=3): """Generate random circuit of arbitrary size. Note: the depth is the layers of independent operation. true depth in the image may be more for visualization purposes, if gates overlap. Args: width (int): number of quantum wires depth (int): layers of operations max_operands (int): maximum operands of each gate Returns: QuantumCircuit: constructed circuit """ qr = QuantumRegister(width, "q") qc = QuantumCircuit(qr) one_q_ops = "iden,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz" two_q_ops = "cx,cy,cz,ch,crz,cu1,cu3,swap" three_q_ops = "ccx" seed = np.random.randint(0, np.iinfo(np.int32).max) logger.debug("random_circuit RandomState seeded with seed=%s", seed) rng = np.random.RandomState(seed) # apply arbitrary random operations at every depth for _ in range(depth): # choose either 1, 2, or 3 qubits for the operation remaining_qubits = list(range(width)) while remaining_qubits: max_possible_operands = min(len(remaining_qubits), max_operands) num_operands = rng.choice(range(max_possible_operands)) + 1 rng.shuffle(remaining_qubits) operands = remaining_qubits[:num_operands] remaining_qubits = [q for q in remaining_qubits if q not in operands] if num_operands == 1: operation = rng.choice(one_q_ops.split(',')) elif num_operands == 2: operation = rng.choice(two_q_ops.split(',')) elif num_operands == 3: operation = rng.choice(three_q_ops.split(',')) # every gate is defined as a method of the QuantumCircuit class # the code below is so we can call a gate by its name gate = getattr(QuantumCircuit, operation) op_args = list(signature(gate).parameters.keys()) num_angles = len(op_args) - num_operands - 1 # -1 for the 'self' arg angles = [rng.uniform(0, 3.14) for x in range(num_angles)] register_operands = [qr[i] for i in operands] gate(qc, *angles, *register_operands) return qc def test_tiny_circuit(self): """Test draw tiny circuit.""" filename = self._get_resource_path('test_tiny.tex') qc = self.random_circuit(1, 1, 1) try: circuit_drawer(qc, filename=filename, output='latex_source') self.assertNotEqual(os.path.exists(filename), False) finally: if os.path.exists(filename): os.remove(filename) def test_normal_circuit(self): """Test draw normal size circuit.""" filename = self._get_resource_path('test_normal.tex') qc = self.random_circuit(5, 5, 3) try: circuit_drawer(qc, filename=filename, output='latex_source') self.assertNotEqual(os.path.exists(filename), False) finally: if os.path.exists(filename): os.remove(filename) def test_wide_circuit(self): """Test draw wide circuit.""" filename = self._get_resource_path('test_wide.tex') qc = self.random_circuit(100, 1, 1) try: circuit_drawer(qc, filename=filename, output='latex_source') self.assertNotEqual(os.path.exists(filename), False) finally: if os.path.exists(filename): os.remove(filename) def test_deep_circuit(self): """Test draw deep circuit.""" filename = self._get_resource_path('test_deep.tex') qc = self.random_circuit(1, 100, 1) try: circuit_drawer(qc, filename=filename, output='latex_source') self.assertNotEqual(os.path.exists(filename), False) finally: if os.path.exists(filename): os.remove(filename) def test_huge_circuit(self): """Test draw huge circuit.""" filename = self._get_resource_path('test_huge.tex') qc = self.random_circuit(40, 40, 1) try: circuit_drawer(qc, filename=filename, output='latex_source') self.assertNotEqual(os.path.exists(filename), False) finally: if os.path.exists(filename): os.remove(filename) def test_teleport(self): """Test draw teleport circuit.""" filename = self._get_resource_path('test_teleport.tex') qr = QuantumRegister(3, 'q') cr = ClassicalRegister(3, 'c') qc = QuantumCircuit(qr, cr) # Prepare an initial state qc.u3(0.3, 0.2, 0.1, qr[0]) # Prepare a Bell pair qc.h(qr[1]) qc.cx(qr[1], qr[2]) # Barrier following state preparation qc.barrier(qr) # Measure in the Bell basis qc.cx(qr[0], qr[1]) qc.h(qr[0]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) # Apply a correction qc.z(qr[2]).c_if(cr, 1) qc.x(qr[2]).c_if(cr, 2) qc.measure(qr[2], cr[2]) try: circuit_drawer(qc, filename=filename, output='latex_source') self.assertNotEqual(os.path.exists(filename), False) finally: if os.path.exists(filename): os.remove(filename) class TestVisualizationUtils(QiskitTestCase): """ Tests for visualizer utilities. Since the utilities in qiskit/tools/visualization/_utils.py are used by several visualizers the need to be check if the interface or their result changes.""" def setUp(self): 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', [(QuantumRegister(2, 'qr2'), 0), (QuantumRegister(2, 'qr2'), 1)], []), ('cx', [(QuantumRegister(2, 'qr1'), 0), (QuantumRegister(2, 'qr1'), 1)], [])], [('measure', [(QuantumRegister(2, 'qr2'), 0)], [(ClassicalRegister(2, 'cr2'), 0)])], [('measure', [(QuantumRegister(2, 'qr1'), 0)], [(ClassicalRegister(2, 'cr1'), 0)])], [('cx', [(QuantumRegister(2, 'qr2'), 1), (QuantumRegister(2, 'qr2'), 0)], []), ('cx', [(QuantumRegister(2, 'qr1'), 1), (QuantumRegister(2, 'qr1'), 0)], [])], [('measure', [(QuantumRegister(2, 'qr2'), 1)], [(ClassicalRegister(2, 'cr2'), 1)])], [('measure', [(QuantumRegister(2, 'qr1'), 1)], [(ClassicalRegister(2, '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', [(QuantumRegister(2, 'qr2'), 0), (QuantumRegister(2, 'qr2'), 1)], []), ('cx', [(QuantumRegister(2, 'qr1'), 0), (QuantumRegister(2, 'qr1'), 1)], [])], [('measure', [(QuantumRegister(2, 'qr2'), 0)], [(ClassicalRegister(2, 'cr2'), 0)])], [('measure', [(QuantumRegister(2, 'qr1'), 0)], [(ClassicalRegister(2, 'cr1'), 0)])], [('cx', [(QuantumRegister(2, 'qr2'), 1), (QuantumRegister(2, 'qr2'), 0)], []), ('cx', [(QuantumRegister(2, 'qr1'), 1), (QuantumRegister(2, 'qr1'), 0)], [])], [('measure', [(QuantumRegister(2, 'qr2'), 1)], [(ClassicalRegister(2, 'cr2'), 1)])], [('measure', [(QuantumRegister(2, 'qr1'), 1)], [(ClassicalRegister(2, '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]) if __name__ == '__main__': unittest.main(verbosity=2)
https://github.com/yh08037/quantum-neural-network
yh08037
import numpy as np import matplotlib.pyplot as plt import torch from torch.autograd import Function from torchvision import datasets, transforms import torch.optim as optim import torch.nn as nn import torch.nn.functional as F from torchsummary import summary import qiskit from qiskit.visualization import * class QuantumCircuit: """ This class provides a simple interface for interaction with the quantum circuit """ def __init__(self, n_qubits, backend, shots): # --- Circuit definition --- self._circuit = qiskit.QuantumCircuit(n_qubits) all_qubits = [i for i in range(n_qubits)] self.theta = qiskit.circuit.Parameter('theta') self._circuit.h(all_qubits) self._circuit.barrier() self._circuit.ry(self.theta, all_qubits) self._circuit.measure_all() # --------------------------- self.backend = backend self.shots = shots def run(self, thetas): job = qiskit.execute(self._circuit, self.backend, shots = self.shots, parameter_binds = [{self.theta: theta} for theta in thetas]) result = job.result().get_counts(self._circuit) counts = np.array(list(result.values())) states = np.array(list(result.keys())).astype(float) # Compute probabilities for each state probabilities = counts / self.shots # Get state expectation expectation = np.sum(states * probabilities) return np.array([expectation]) simulator = qiskit.Aer.get_backend('qasm_simulator') circuit = QuantumCircuit(1, simulator, 100) print('Expected value for rotation pi {}'.format(circuit.run([np.pi])[0])) circuit._circuit.draw('mpl') class HybridFunction(Function): """ Hybrid quantum - classical function definition """ @staticmethod def forward(ctx, inputs, quantum_circuit, shift): """ Forward pass computation """ ctx.shift = shift ctx.quantum_circuit = quantum_circuit expectation_z = [] for input in inputs: expectation_z.append(ctx.quantum_circuit.run(input.tolist())) result = torch.tensor(expectation_z) ctx.save_for_backward(inputs, result) return result @staticmethod def backward(ctx, grad_output): """ Backward pass computation """ input, expectation_z = ctx.saved_tensors input_list = np.array(input.tolist()) shift_right = input_list + np.ones(input_list.shape) * ctx.shift shift_left = input_list - np.ones(input_list.shape) * ctx.shift gradients = [] for i in range(len(input_list)): expectation_right = ctx.quantum_circuit.run(shift_right[i]) expectation_left = ctx.quantum_circuit.run(shift_left[i]) gradient = torch.tensor([expectation_right]) - torch.tensor([expectation_left]) gradients.append(gradient) gradients = np.array([gradients]).T return torch.tensor([gradients]).float() * grad_output.float(), None, None class Hybrid(nn.Module): """ Hybrid quantum - classical layer definition """ def __init__(self, backend, shots, shift): super(Hybrid, self).__init__() self.quantum_circuit = QuantumCircuit(1, backend, shots) self.shift = shift def forward(self, input): return HybridFunction.apply(input, self.quantum_circuit, self.shift) # Concentrating on the first 100 samples n_samples = 128 batch_size = 32 X_train = datasets.MNIST(root='./data', train=True, download=True, transform=transforms.Compose([transforms.ToTensor()])) X_train.data = X_train.data[:n_samples] X_train.targets = X_train.targets[:n_samples] train_loader = torch.utils.data.DataLoader(X_train, batch_size=batch_size, shuffle=True) # n_samples_show = 6 # data_iter = iter(train_loader) # fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3)) # while n_samples_show > 0: # images, targets = data_iter.__next__() # axes[n_samples_show - 1].imshow(images[0].numpy().squeeze(), cmap='gray') # axes[n_samples_show - 1].set_xticks([]) # axes[n_samples_show - 1].set_yticks([]) # axes[n_samples_show - 1].set_title("Labeled: {}".format(targets.item())) # n_samples_show -= 1 n_samples = 256 X_test = datasets.MNIST(root='./data', train=False, download=True, transform=transforms.Compose([transforms.ToTensor()])) # idx = np.append(np.where(X_test.targets == 0)[0][:n_samples], # np.where(X_test.targets == 1)[0][:n_samples]) X_test.data = X_test.data[:n_samples] X_test.targets = X_test.targets[:n_samples] test_loader = torch.utils.data.DataLoader(X_test, batch_size=batch_size, shuffle=True) class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 6, kernel_size=5) self.conv2 = nn.Conv2d(6, 16, kernel_size=5) self.dropout = nn.Dropout2d() self.fc1 = nn.Linear(256, 64) self.fc2 = nn.Linear(64, 10) # self.hybrid = Hybrid(qiskit.Aer.get_backend('qasm_simulator'), 100, np.pi / 2) self.hybrid = [Hybrid(qiskit.Aer.get_backend('qasm_simulator'), 100, np.pi / 2) for i in range(10)] def forward(self, x): x = F.relu(self.conv1(x)) x = F.max_pool2d(x, 2) x = F.relu(self.conv2(x)) x = F.max_pool2d(x, 2) x = self.dropout(x) # x = x.view(-1, 256) x = torch.flatten(x, start_dim=1) x = F.relu(self.fc1(x)) x = self.fc2(x) x = torch.chunk(x, 10, dim=1) # x = self.hybrid(x) x = tuple([hy(x_) for hy, x_ in zip(self.hybrid, x)]) return torch.cat(x, -1) model = Net() summary(model, (1, 28, 28), device='cpu') optimizer = optim.Adam(model.parameters(), lr=0.001) # loss_func = nn.NLLLoss() loss_func = nn.CrossEntropyLoss() epochs = 20 loss_list = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # print("data ", data.size()) # print("output", output.size()) # print("target", target.size()) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_list.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format( 100. * (epoch + 1) / epochs, loss_list[-1])) plt.plot(loss_list) plt.title('Hybrid NN Training Convergence') plt.xlabel('Training Iterations') plt.ylabel('Neg Log Likelihood Loss') model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100 / batch_size) ) # n_samples_show = 6 # count = 0 # fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3)) # model.eval() # with torch.no_grad(): # for batch_idx, (data, target) in enumerate(test_loader): # if count == n_samples_show: # break # output = model(data) # pred = output.argmax(dim=1, keepdim=True) # axes[count].imshow(data[0].numpy().squeeze(), cmap='gray') # axes[count].set_xticks([]) # axes[count].set_yticks([]) # axes[count].set_title('Predicted {}'.format(pred.item())) # count += 1
https://github.com/yh08037/quantum-neural-network
yh08037
import numpy as np import matplotlib.pyplot as plt import torch from torch.autograd import Function from torchvision import datasets, transforms import torch.optim as optim import torch.nn as nn import torch.nn.functional as F from torchsummary import summary import qiskit from qiskit.visualization import * use_cuda = torch.cuda.is_available() print('CUDA available:', use_cuda) if use_cuda: device = torch.device('cuda') print('Training on GPU...') else: device = torch.device('cpu') print('Training on CPU...') class QuantumCircuit: """ This class provides a simple interface for interaction with the quantum circuit """ def __init__(self, n_qubits, backend, shots): # --- Circuit definition --- self._circuit = qiskit.QuantumCircuit(n_qubits) all_qubits = [i for i in range(n_qubits)] self.theta = qiskit.circuit.Parameter('theta') self._circuit.h(all_qubits) self._circuit.barrier() self._circuit.ry(self.theta, all_qubits) self._circuit.measure_all() # --------------------------- self.backend = backend self.shots = shots def run(self, thetas): job = qiskit.execute(self._circuit, self.backend, shots = self.shots, parameter_binds = [{self.theta: theta} for theta in thetas]) result = job.result().get_counts(self._circuit) counts = np.array(list(result.values())) states = np.array(list(result.keys())).astype(float) # Compute probabilities for each state probabilities = counts / self.shots # Get state expectation expectation = np.sum(states * probabilities) return np.array([expectation]) simulator = qiskit.Aer.get_backend('qasm_simulator') circuit = QuantumCircuit(1, simulator, 100) print('Expected value for rotation pi {}'.format(circuit.run([np.pi])[0])) circuit._circuit.draw('mpl') class HybridFunction(Function): """ Hybrid quantum - classical function definition """ @staticmethod def forward(ctx, inputs, quantum_circuit, shift): """ Forward pass computation """ ctx.shift = shift ctx.quantum_circuit = quantum_circuit expectation_z = [] for input in inputs: expectation_z.append(ctx.quantum_circuit.run(input.tolist())) result = torch.tensor(expectation_z).cuda() ctx.save_for_backward(inputs, result) return result @staticmethod def backward(ctx, grad_output): """ Backward pass computation """ input, expectation_z = ctx.saved_tensors input_list = np.array(input.tolist()) shift_right = input_list + np.ones(input_list.shape) * ctx.shift shift_left = input_list - np.ones(input_list.shape) * ctx.shift gradients = [] for i in range(len(input_list)): expectation_right = ctx.quantum_circuit.run(shift_right[i]) expectation_left = ctx.quantum_circuit.run(shift_left[i]) gradient = torch.tensor([expectation_right]).cuda() - torch.tensor([expectation_left]).cuda() gradients.append(gradient) # gradients = np.array([gradients]).T gradients = torch.tensor([gradients]).cuda() gradients = torch.transpose(gradients, 0, 1) # return torch.tensor([gradients]).float() * grad_output.float(), None, None return gradients.float() * grad_output.float(), None, None class Hybrid(nn.Module): """ Hybrid quantum - classical layer definition """ def __init__(self, backend, shots, shift): super(Hybrid, self).__init__() self.quantum_circuit = QuantumCircuit(1, backend, shots) self.shift = shift def forward(self, input): return HybridFunction.apply(input, self.quantum_circuit, self.shift) n_samples = 512 batch_size = 256 X_train = datasets.MNIST(root='./data', train=True, download=True, transform=transforms.Compose([transforms.ToTensor()])) X_train.data = X_train.data[:n_samples] X_train.targets = X_train.targets[:n_samples] train_loader = torch.utils.data.DataLoader(X_train, batch_size=batch_size, shuffle=True) # check MNIST data n_samples_show = 6 data_iter = iter(train_loader) fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3)) images, targets = data_iter.__next__() while n_samples_show > 0: axes[n_samples_show - 1].imshow(images[n_samples_show].numpy().squeeze(), cmap='gray') axes[n_samples_show - 1].set_xticks([]) axes[n_samples_show - 1].set_yticks([]) axes[n_samples_show - 1].set_title("Labeled: {}".format(int(targets[n_samples_show]))) n_samples_show -= 1 n_samples = 2048 X_test = datasets.MNIST(root='./data', train=False, download=True, transform=transforms.Compose([transforms.ToTensor()])) # idx = np.append(np.where(X_test.targets == 0)[0][:n_samples], # np.where(X_test.targets == 1)[0][:n_samples]) X_test.data = X_test.data[:n_samples] X_test.targets = X_test.targets[:n_samples] test_loader = torch.utils.data.DataLoader(X_test, batch_size=batch_size, shuffle=True) class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 6, kernel_size=5) self.conv2 = nn.Conv2d(6, 16, kernel_size=5) self.dropout = nn.Dropout2d() self.fc1 = nn.Linear(256, 64) self.fc2 = nn.Linear(64, 10) # self.hybrid = Hybrid(qiskit.Aer.get_backend('qasm_simulator'), 100, np.pi / 2) self.hybrid = [Hybrid(qiskit.Aer.get_backend('qasm_simulator'), 100, np.pi / 2) for i in range(10)] def forward(self, x): x = F.relu(self.conv1(x)) x = F.max_pool2d(x, 2) x = F.relu(self.conv2(x)) x = F.max_pool2d(x, 2) x = self.dropout(x) # x = x.view(-1, 256) x = torch.flatten(x, start_dim=1) x = F.relu(self.fc1(x)) x = self.fc2(x) x = torch.chunk(x, 10, dim=1) # x = self.hybrid(x) x = tuple([hy(x_) for hy, x_ in zip(self.hybrid, x)]) return torch.cat(x, -1) model = Net().cuda() summary(model, (1, 28, 28)) optimizer = optim.Adam(model.parameters(), lr=0.001) # loss_func = nn.NLLLoss() loss_func = nn.CrossEntropyLoss().cuda() epochs = 50 loss_list = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() data = data.cuda() target = target.cuda() # Forward pass output = model(data).cuda() # print("data ", data.size()) # print("output", output.size()) # print("target", target.size()) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_list.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format( 100. * (epoch + 1) / epochs, loss_list[-1])) plt.plot(loss_list) plt.title('Hybrid NN Training Convergence') plt.xlabel('Training Iterations') plt.ylabel('Neg Log Likelihood Loss') model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): data = data.cuda() target = target.cuda() output = model(data).cuda() pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100 / batch_size) ) n_samples_show = 8 count = 0 fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3)) model.eval() with torch.no_grad(): for batch_idx, (data, target) in enumerate(test_loader): if count == n_samples_show: break data_cuda = data.cuda() target_cuda = target.cuda() output_cuda = model(data_cuda).cuda() pred = output_cuda.argmax(dim=1, keepdim=True) axes[count].imshow(data[count].numpy().squeeze(), cmap='gray') axes[count].set_xticks([]) axes[count].set_yticks([]) axes[count].set_title('Predicted {}'.format(pred[count].item())) count += 1
https://github.com/yh08037/quantum-neural-network
yh08037
# !pip install qiskit-aer-gpu import numpy as np import matplotlib.pyplot as plt %matplotlib inline import torch from torch.autograd import Function from torchvision import datasets, transforms import torch.optim as optim import torch.nn as nn import torch.nn.functional as F # from torchsummary import summary import qiskit from qiskit.visualization import * from qiskit.circuit.random import random_circuit from itertools import combinations if torch.cuda.is_available(): DEVICE = torch.device('cuda') else: DEVICE = torch.device('cpu') print('Using PyTorch version:', torch.__version__, ' Device:', DEVICE) print('cuda index:', torch.cuda.current_device()) print('GPU 이름:', torch.cuda.get_device_name()) BATCH_SIZE = 10 EPOCHS = 10 # Number of optimization epochs n_layers = 1 # Number of random layers n_train = 50 # Size of the train dataset n_test = 30 # Size of the test dataset SAVE_PATH = "quanvolution/" # Data saving folder PREPROCESS = True # If False, skip quantum processing and load data from SAVE_PATH seed = 47 np.random.seed(seed) # Seed for NumPy random number generator torch.manual_seed(seed) # Seed for TensorFlow random number generator train_dataset = datasets.MNIST(root = "./data", train = True, download = True, transform = transforms.ToTensor()) train_dataset.data = train_dataset.data[:n_train] train_dataset.targets = train_dataset.targets[:n_train] test_dataset = datasets.MNIST(root = "./data", train = False, transform = transforms.ToTensor()) test_dataset.data = test_dataset.data[:n_test] test_dataset.targets = test_dataset.targets[:n_test] train_loader = torch.utils.data.DataLoader(dataset = train_dataset, batch_size = BATCH_SIZE, shuffle = True) test_loader = torch.utils.data.DataLoader(dataset = test_dataset, batch_size = BATCH_SIZE, shuffle = False) for (X_train, y_train) in train_loader: print('X_train:', X_train.size(), 'type:', X_train.type()) print('y_train:', y_train.size(), 'type:', y_train.type()) break pltsize = 1 plt.figure(figsize=(10 * pltsize, pltsize)) for i in range(10): plt.subplot(1, 10, i + 1) plt.axis('off') plt.imshow(X_train[i, :, :, :].numpy().reshape(28, 28), cmap = "gray_r") plt.title('Class: ' + str(y_train[i].item())) class QuanvCircuit: """ This class defines filter circuit of Quanvolution layer """ def __init__(self, kernel_size, backend, shots, threshold): # --- Circuit definition start --- self.n_qubits = kernel_size ** 2 self._circuit = qiskit.QuantumCircuit(self.n_qubits) self.theta = [qiskit.circuit.Parameter('theta{}'.format(i)) for i in range(self.n_qubits)] for i in range(self.n_qubits): self._circuit.rx(self.theta[i], i) self._circuit.barrier() self._circuit += random_circuit(self.n_qubits, 2) self._circuit.measure_all() # ---- Circuit definition end ---- self.backend = backend self.shots = shots self.threshold = threshold def run(self, data): # data shape: tensor (1, 5, 5) # val > self.threshold : |1> - rx(pi) # val <= self.threshold : |0> - rx(0) # reshape input data # [1, kernel_size, kernel_size] -> [1, self.n_qubits] data = torch.reshape(data, (1, self.n_qubits)) # encoding data to parameters thetas = [] for dat in data: theta = [] for val in dat: if val > self.threshold: theta.append(np.pi) else: theta.append(0) thetas.append(theta) param_dict = dict() for theta in thetas: for i in range(self.n_qubits): param_dict[self.theta[i]] = theta[i] param_binds = [param_dict] # execute random quantum circuit job = qiskit.execute(self._circuit, self.backend, shots = self.shots, parameter_binds = param_binds) result = job.result().get_counts(self._circuit) # decoding the result counts = 0 for key, val in result.items(): cnt = sum([int(char) for char in key]) counts += cnt * val # Compute probabilities for each state probabilities = counts / (self.shots * self.n_qubits) # probabilities = counts / self.shots return probabilities # backend = qiskit.Aer.get_backend('qasm_simulator') backend = qiskit.providers.aer.QasmSimulator(method = "statevector_gpu") filter_size = 2 circ = QuanvCircuit(filter_size, backend, 100, 127) data = torch.tensor([[0, 200], [100, 255]]) # data = torch.tensor([[0, 200, 128, 192,168], [100, 255,53,47,29],[100, 255,53,47,29],[0, 200, 128, 192,168],[0, 200, 128, 192,168]]) print(data.size()) print(circ.run(data)) circ._circuit.draw(output='mpl') ''' def quanv_feed(image): """ Convolves the input image with many applications of the same quantum circuit. In the standard language of CNN, this would correspond to a convolution with a 5×5 kernel and a stride equal to 1. """ out = np.zeros((24, 24, 25)) # Loop over the coordinates of the top-left pixel of 5X5 squares for j in range(24): for k in range(24): # Process a squared 5x5 region of the image with a quantum circuit circuit_input = [] for a in range(5): for b in range(5): circuit_input.append(image[j + a, k + b, 0]) q_results = circuit(circuit_input) # Assign expectation values to different channels of the output pixel (j/2, k/2) for c in range(25): out[24, 24, c] = q_results[c] return out ''' class QuanvFunction(Function): """ Quanv function definition """ @staticmethod def forward(ctx, inputs, in_channels, out_channels, kernel_size, quantum_circuits, shift): """ Forward pass computation """ # input shape : (-1, 1, 28, 28) # otuput shape : (-1, 6, 24, 24) ctx.in_channels = in_channels ctx.out_channels = out_channels ctx.kernel_size = kernel_size ctx.quantum_circuits = quantum_circuits ctx.shift = shift _, _, len_x, len_y = inputs.size() len_x = len_x - kernel_size + 1 len_y = len_y - kernel_size + 1 outputs = torch.zeros((len(inputs), len(quantum_circuits), len_x, len_y)).to(DEVICE) for i in range(len(inputs)): print(f"batch{i}") input = inputs[i] for c in range(len(quantum_circuits)): circuit = quantum_circuits[c] print(f"channel{c}") for h in range(len_y): for w in range(len_x): data = input[0, h:h+kernel_size, w:w+kernel_size] outputs[i, c, h, w] = circuit.run(data) # print(f"({h},{w})") ctx.save_for_backward(inputs, outputs) return outputs ''' features = [] for input in inputs: feature = [] for circuit in quantum_circuits: xys = [] for x in range(len_x): ys = [] for y in range(len_y): data = input[0, x:x+kernel_size, y:y+kernel_size] ys.append(circuit.run(data)) xys.append(ys) feature.append(xys) features.append(feature) result = torch.tensor(features) ctx.save_for_backward(inputs, result) return result ''' @staticmethod def backward(ctx, grad_output): # 확인 필요(검증 x) """ Backward pass computation """ input, expectation_z = ctx.saved_tensors input_list = np.array(input.tolist()) shift_right = input_list + np.ones(input_list.shape) * ctx.shift shift_left = input_list - np.ones(input_list.shape) * ctx.shift gradients = [] for i in range(len(input_list)): expectation_right = ctx.quantum_circuit.run(shift_right[i]) expectation_left = ctx.quantum_circuit.run(shift_left[i]) gradient = torch.tensor([expectation_right]) - torch.tensor([expectation_left]) gradients.append(gradient) gradients = np.array([gradients]).T return torch.tensor([gradients]).float() * grad_output.float(), None, None class Quanv(nn.Module): """ Quanvolution(Quantum convolution) layer definition """ def __init__(self, in_channels, out_channels, kernel_size, backend=qiskit.providers.aer.QasmSimulator(method="statevector_gpu"), shots=100, shift=np.pi/2): super(Quanv, self).__init__() self.quantum_circuits = [QuanvCircuit(kernel_size=kernel_size, backend=backend, shots=shots, threshold=127) for i in range(out_channels)] self.in_channels = in_channels self.out_channels = out_channels self.kernel_size = kernel_size self.shift = shift def forward(self, inputs): return QuanvFunction.apply(inputs, self.in_channels, self.out_channels, self.kernel_size, self.quantum_circuits, self.shift) class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.quanv = Quanv(in_channels=1, out_channels=1, kernel_size = 3) # <- Quanv!!!! self.conv = nn.Conv2d(1, 16, kernel_size=5) self.dropout = nn.Dropout2d() self.fc1 = nn.Linear(256, 64) self.fc2 = nn.Linear(64, 10) def forward(self, x): x = F.relu(self.quanv(x)) x = F.max_pool2d(x, 2) x = F.relu(self.conv(x)) x = F.max_pool2d(x, 2) x = self.dropout(x) # x = x.view(-1, 256) x = torch.flatten(x, start_dim=1) x = F.relu(self.fc1(x)) x = self.fc2(x) return F.softmax(x) model = Net().to(DEVICE) optimizer = optim.Adam(model.parameters(), lr=0.001) loss_func = nn.CrossEntropyLoss() epochs = 20 loss_list = [] model.train().to(DEVICE) for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): target = target.to(DEVICE) optimizer.zero_grad() # Forward pass output = model(data).to(DEVICE) # Calculating loss loss = loss_func(output, target).to(DEVICE) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_list.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format( 100. * (epoch + 1) / epochs, loss_list[-1])) model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): data = data.cuda() target = target.cuda() output = model(data).cuda() pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100 / batch_size) )
https://github.com/yh08037/quantum-neural-network
yh08037
import numpy as np import matplotlib.pyplot as plt %matplotlib inline import torch from torch.autograd import Function from torchvision import datasets, transforms import torch.optim as optim import torch.nn as nn import torch.nn.functional as F # from torchsummary import summary import qiskit from qiskit.visualization import * from qiskit.circuit.random import random_circuit from itertools import combinations if torch.cuda.is_available(): DEVICE = torch.device('cuda') else: DEVICE = torch.device('cpu') print('Using PyTorch version:', torch.__version__, ' Device:', DEVICE) print('cuda index:', torch.cuda.current_device()) print('GPU 이름:', torch.cuda.get_device_name()) BATCH_SIZE = 256 EPOCHS = 10 # Number of optimization epochs n_layers = 1 # Number of random layers n_train = 50 # Size of the train dataset n_test = 30 # Size of the test dataset SAVE_PATH = "quanvolution/" # Data saving folder PREPROCESS = True # If False, skip quantum processing and load data from SAVE_PATH seed = 47 np.random.seed(seed) # Seed for NumPy random number generator torch.manual_seed(seed) # Seed for TensorFlow random number generator train_dataset = datasets.MNIST(root = "./data", train = True, download = True, transform = transforms.ToTensor()) test_dataset = datasets.MNIST(root = "./data", train = False, transform = transforms.ToTensor()) train_loader = torch.utils.data.DataLoader(dataset = train_dataset, batch_size = BATCH_SIZE, shuffle = True) test_loader = torch.utils.data.DataLoader(dataset = test_dataset, batch_size = BATCH_SIZE, shuffle = False) for (X_train, y_train) in train_loader: print('X_train:', X_train.size(), 'type:', X_train.type()) print('y_train:', y_train.size(), 'type:', y_train.type()) break pltsize = 1 plt.figure(figsize=(10 * pltsize, pltsize)) for i in range(10): plt.subplot(1, 10, i + 1) plt.axis('off') plt.imshow(X_train[i, :, :, :].numpy().reshape(28, 28), cmap = "gray_r") plt.title('Class: ' + str(y_train[i].item())) class QuanvCircuit: """ This class defines filter circuit of Quanvolution layer """ def __init__(self, kernel_size, backend, shots, threshold): # --- Circuit definition start --- self.n_qubits = kernel_size ** 2 self._circuit = qiskit.QuantumCircuit(self.n_qubits) self.theta = [qiskit.circuit.Parameter('theta{}'.format(i)) for i in range(self.n_qubits)] for i in range(self.n_qubits): self._circuit.rx(self.theta[i], i) self._circuit.barrier() self._circuit += random_circuit(self.n_qubits, 2) self._circuit.measure_all() # ---- Circuit definition end ---- self.backend = backend self.shots = shots self.threshold = threshold def run(self, data): # data shape: tensor (1, 5, 5) # val > self.threshold : |1> - rx(pi) # val <= self.threshold : |0> - rx(0) # reshape input data # [1, kernel_size, kernel_size] -> [1, self.n_qubits] data = torch.reshape(data, (1, self.n_qubits)) # encoding data to parameters thetas = [] for dat in data: theta = [] for val in dat: if val > self.threshold: theta.append(np.pi) else: theta.append(0) thetas.append(theta) param_dict = dict() for theta in thetas: for i in range(self.n_qubits): param_dict[self.theta[i]] = theta[i] param_binds = [param_dict] # execute random quantum circuit job = qiskit.execute(self._circuit, self.backend, shots = self.shots, parameter_binds = param_binds) result = job.result().get_counts(self._circuit) # decoding the result counts = 0 for key, val in result.items(): cnt = sum([int(char) for char in key]) counts += cnt * val # Compute probabilities for each state probabilities = counts / (self.shots * self.n_qubits) # probabilities = counts / self.shots return probabilities backend = qiskit.Aer.get_backend('qasm_simulator') filter_size = 2 circ = QuanvCircuit(filter_size, backend, 100, 127) data = torch.tensor([[0, 200], [100, 255]]) print(data.size()) print(circ.run(data)) circ._circuit.draw(output='mpl') # def quanv_feed(image): # """ # Convolves the input image with many applications # of the same quantum circuit. # In the standard language of CNN, this would correspond to # a convolution with a 5×5 kernel and a stride equal to 1. # """ # out = np.zeros((24, 24, 25)) # # Loop over the coordinates of the top-left pixel of 5X5 squares # for j in range(24): # for k in range(24): # # Process a squared 5x5 region of the image with a quantum circuit # circuit_input = [] # for a in range(5): # for b in range(5): # circuit_input.append(image[j + a, k + b, 0]) # q_results = circuit(circuit_input) # # Assign expectation values to different channels of the output pixel (j/2, k/2) # for c in range(25): # out[24, 24, c] = q_results[c] # return out class QuanvFunction(Function): """ Quanv function definition """ @staticmethod def forward(ctx, inputs, in_channels, out_channels, kernel_size, quantum_circuits, shift): """ Forward pass computation """ # input shape : (-1, 1, 28, 28) # otuput shape : (-1, 6, 24, 24) ctx.in_channels = in_channels ctx.out_channels = out_channels ctx.kernel_size = kernel_size ctx.quantum_circuits = quantum_circuits ctx.shift = shift _, _, len_x, len_y = inputs.size() len_x = len_x - kernel_size + 1 len_y = len_y - kernel_size + 1 features = [] for input in inputs: feature = [] for circuit in quantum_circuits: xys = [] for x in range(len_x): ys = [] for y in range(len_y): data = input[0, x:x+kernel_size, y:y+kernel_size] ys.append(circuit.run(data)) xys.append(ys) feature.append(xys) features.append(feature) result = torch.tensor(features) ctx.save_for_backward(inputs, result) return result @staticmethod def backward(ctx, grad_output): # 확인 필요(검증 x) """ Backward pass computation """ input, expectation_z = ctx.saved_tensors input_list = np.array(input.tolist()) shift_right = input_list + np.ones(input_list.shape) * ctx.shift shift_left = input_list - np.ones(input_list.shape) * ctx.shift gradients = [] for i in range(len(input_list)): expectation_right = ctx.quantum_circuit.run(shift_right[i]) expectation_left = ctx.quantum_circuit.run(shift_left[i]) gradient = torch.tensor([expectation_right]) - torch.tensor([expectation_left]) gradients.append(gradient) gradients = np.array([gradients]).T return torch.tensor([gradients]).float() * grad_output.float(), None, None class Quanv(nn.Module): """ Quanvolution(Quantum convolution) layer definition """ def __init__(self, in_channels, out_channels, kernel_size, backend=qiskit.Aer.get_backend('qasm_simulator'), shots=100, shift=np.pi/2): super(Quanv, self).__init__() self.quantum_circuits = [QuanvCircuit(kernel_size=kernel_size, backend=backend, shots=shots, threshold=127) for i in range(out_channels)] self.in_channels = in_channels self.out_channels = out_channels self.kernel_size = kernel_size self.shift = shift def forward(self, inputs): return QuanvFunction.apply(inputs, self.in_channels, self.out_channels, self.kernel_size, self.quantum_circuits, self.shift) class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.quanv = Quanv(1, 6, kernel_size=5) self.conv = nn.Conv2d(6, 16, kernel_size=5) self.dropout = nn.Dropout2d() self.fc1 = nn.Linear(256, 64) self.fc2 = nn.Linear(64, 10) def forward(self, x): x = F.relu(self.quanv(x)) x = F.max_pool2d(x, 2) x = F.relu(self.conv(x)) x = F.max_pool2d(x, 2) x = self.dropout(x) x = torch.flatten(x, start_dim=1) x = F.relu(self.fc1(x)) x = self.fc2(x) return F.softmax(x) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.001) loss_func = nn.CrossEntropyLoss() epochs = 20 loss_list = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_list.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format( 100. * (epoch + 1) / epochs, loss_list[-1])) model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): data = data.cuda() target = target.cuda() output = model(data).cuda() pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100 / batch_size) )
https://github.com/yh08037/quantum-neural-network
yh08037
import numpy as np import matplotlib.pyplot as plt %matplotlib inline import torch from torch.autograd import Function from torchvision import datasets, transforms import torch.optim as optim import torch.nn as nn import torch.nn.functional as F # from torchsummary import summary import qiskit from qiskit.visualization import * from qiskit.circuit.random import random_circuit from itertools import combinations if torch.cuda.is_available(): DEVICE = torch.device('cuda') else: DEVICE = torch.device('cpu') print('Using PyTorch version:', torch.__version__, ' Device:', DEVICE) print('cuda index:', torch.cuda.current_device()) print('GPU 이름:', torch.cuda.get_device_name()) BATCH_SIZE = 256 EPOCHS = 10 # Number of optimization epochs n_layers = 1 # Number of random layers n_train = 50 # Size of the train dataset n_test = 30 # Size of the test dataset SAVE_PATH = "quanvolution/" # Data saving folder PREPROCESS = True # If False, skip quantum processing and load data from SAVE_PATH seed = 47 np.random.seed(seed) # Seed for NumPy random number generator torch.manual_seed(seed) # Seed for TensorFlow random number generator train_dataset = datasets.MNIST(root = "./data", train = True, download = True, transform = transforms.ToTensor()) test_dataset = datasets.MNIST(root = "./data", train = False, transform = transforms.ToTensor()) train_loader = torch.utils.data.DataLoader(dataset = train_dataset, batch_size = BATCH_SIZE, shuffle = True) test_loader = torch.utils.data.DataLoader(dataset = test_dataset, batch_size = BATCH_SIZE, shuffle = False) for (X_train, y_train) in train_loader: print('X_train:', X_train.size(), 'type:', X_train.type()) print('y_train:', y_train.size(), 'type:', y_train.type()) break pltsize = 1 plt.figure(figsize=(10 * pltsize, pltsize)) for i in range(10): plt.subplot(1, 10, i + 1) plt.axis('off') plt.imshow(X_train[i, :, :, :].numpy().reshape(28, 28), cmap = "gray_r") plt.title('Class: ' + str(y_train[i].item())) class QuanvCircuit: """ This class defines filter circuit of Quanvolution layer """ def __init__(self, kernel_size, backend, shots, threshold): # --- Circuit definition start --- self.n_qubits = kernel_size ** 2 self._circuit = qiskit.QuantumCircuit(self.n_qubits) self.theta = [qiskit.circuit.Parameter('theta{}'.format(i)) for i in range(self.n_qubits)] for i in range(self.n_qubits): self._circuit.rx(self.theta[i], i) self._circuit.barrier() self._circuit += random_circuit(self.n_qubits, 2) self._circuit.measure_all() # ---- Circuit definition end ---- self.backend = backend self.shots = shots self.threshold = threshold def run(self, data): # data shape: tensor (1, 5, 5) # val > self.threshold : |1> - rx(pi) # val <= self.threshold : |0> - rx(0) # reshape input data # [1, kernel_size, kernel_size] -> [1, self.n_qubits] data = torch.reshape(data, (1, self.n_qubits)) # encoding data to parameters thetas = [] for dat in data: theta = [] for val in dat: if val > self.threshold: theta.append(np.pi) else: theta.append(0) thetas.append(theta) param_dict = dict() for theta in thetas: for i in range(self.n_qubits): param_dict[self.theta[i]] = theta[i] param_binds = [param_dict] # execute random quantum circuit job = qiskit.execute(self._circuit, self.backend, shots = self.shots, parameter_binds = param_binds) result = job.result().get_counts(self._circuit) # decoding the result counts = 0 for key, val in result.items(): cnt = sum([int(char) for char in key]) counts += cnt * val # Compute probabilities for each state probabilities = counts / (self.shots * self.n_qubits) # probabilities = counts / self.shots return probabilities backend = qiskit.Aer.get_backend('qasm_simulator') filter_size = 2 circ = QuanvCircuit(filter_size, backend, 100, 127) data = torch.tensor([[0, 200], [100, 255]]) print(data.size()) print(circ.run(data)) circ._circuit.draw(output='mpl') # def quanv_feed(image): # """ # Convolves the input image with many applications # of the same quantum circuit. # In the standard language of CNN, this would correspond to # a convolution with a 5×5 kernel and a stride equal to 1. # """ # out = np.zeros((24, 24, 25)) # # Loop over the coordinates of the top-left pixel of 5X5 squares # for j in range(24): # for k in range(24): # # Process a squared 5x5 region of the image with a quantum circuit # circuit_input = [] # for a in range(5): # for b in range(5): # circuit_input.append(image[j + a, k + b, 0]) # q_results = circuit(circuit_input) # # Assign expectation values to different channels of the output pixel (j/2, k/2) # for c in range(25): # out[24, 24, c] = q_results[c] # return out class QuanvFunction(Function): """ Quanv function definition """ @staticmethod def forward(ctx, inputs, in_channels, out_channels, kernel_size, quantum_circuits, shift): """ Forward pass computation """ # input shape : (-1, 1, 28, 28) # otuput shape : (-1, 6, 24, 24) ctx.in_channels = in_channels ctx.out_channels = out_channels ctx.kernel_size = kernel_size ctx.quantum_circuits = quantum_circuits ctx.shift = shift _, _, len_x, len_y = inputs.size() len_x = len_x - kernel_size + 1 len_y = len_y - kernel_size + 1 features = [] for input in inputs: feature = [] for circuit in quantum_circuits: xys = [] for x in range(len_x): ys = [] for y in range(len_y): data = input[0, x:x+kernel_size, y:y+kernel_size] ys.append(circuit.run(data)) xys.append(ys) feature.append(xys) features.append(feature) result = torch.tensor(features) ctx.save_for_backward(inputs, result) return result @staticmethod def backward(ctx, grad_output): # 확인 필요(검증 x) """ Backward pass computation """ input, expectation_z = ctx.saved_tensors input_list = np.array(input.tolist()) shift_right = input_list + np.ones(input_list.shape) * ctx.shift shift_left = input_list - np.ones(input_list.shape) * ctx.shift gradients = [] for i in range(len(input_list)): expectation_right = ctx.quantum_circuit.run(shift_right[i]) expectation_left = ctx.quantum_circuit.run(shift_left[i]) gradient = torch.tensor([expectation_right]) - torch.tensor([expectation_left]) gradients.append(gradient) gradients = np.array([gradients]).T return torch.tensor([gradients]).float() * grad_output.float(), None, None class Quanv(nn.Module): """ Quanvolution(Quantum convolution) layer definition """ def __init__(self, in_channels, out_channels, kernel_size, backend=qiskit.Aer.get_backend('qasm_simulator'), shots=100, shift=np.pi/2): super(Quanv, self).__init__() self.quantum_circuits = [QuanvCircuit(kernel_size=kernel_size, backend=backend, shots=shots, threshold=127) for i in range(out_channels)] self.in_channels = in_channels self.out_channels = out_channels self.kernel_size = kernel_size self.shift = shift def forward(self, inputs): return QuanvFunction.apply(inputs, self.in_channels, self.out_channels, self.kernel_size, self.quantum_circuits, self.shift) class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.quanv = Quanv(1, 6, kernel_size=5) self.conv = nn.Conv2d(6, 16, kernel_size=5) self.dropout = nn.Dropout2d() self.fc1 = nn.Linear(256, 64) self.fc2 = nn.Linear(64, 10) def forward(self, x): x = F.relu(self.quanv(x)) x = F.max_pool2d(x, 2) x = F.relu(self.conv(x)) x = F.max_pool2d(x, 2) x = self.dropout(x) x = torch.flatten(x, start_dim=1) x = F.relu(self.fc1(x)) x = self.fc2(x) return F.softmax(x) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.001) loss_func = nn.CrossEntropyLoss() epochs = 20 loss_list = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_list.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format( 100. * (epoch + 1) / epochs, loss_list[-1])) model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): data = data.cuda() target = target.cuda() output = model(data).cuda() pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100 / batch_size) )
https://github.com/ttlion/ShorAlgQiskit
ttlion
""" This is the final implementation of Shor's Algorithm using the circuit presented in section 2.3 of the report about the first simplification introduced by the base paper used. As the circuit is completely general, it is a rather long circuit, with a lot of QASM instructions in the generated Assembly code, which makes that for high values of N the code is not able to run in IBM Q Experience because IBM has a very low restriction on the number os QASM instructions it can run. For N=15, it can run on IBM. But, for example, for N=21 it already may not, because it exceeds the restriction of QASM instructions. The user can try to use n qubits on top register instead of 2n to get more cases working on IBM. This will, however and naturally, diminish the probabilty of success. For a small number of qubits (about until 20), the code can be run on a local simulator. This makes it to be a little slow even for the factorization of small numbers N. Because of this, although all is general and we ask the user to introduce the number N and if he agrees with the 'a' value selected or not, we after doing that force N=15 and a=4, because that is a case where the simulation, although slow, can be run in local simulator and does not last 'forever' to end. If the user wants he can just remove the 2 lines of code where that is done, and put bigger N (that will be slow) or can try to run on the ibm simulator (for that, the user should introduce its IBM Q Experience Token and be aware that for high values of N it will just receive a message saying the size of the circuit is too big) """ """ Imports from qiskit""" from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute, IBMQ from qiskit import BasicAer import sys """ Imports to Python functions """ import math import array import fractions import numpy as np import time """ Local Imports """ from cfunctions import check_if_power, get_value_a from cfunctions import get_factors from qfunctions import create_QFT, create_inverse_QFT from qfunctions import cMULTmodN """ Main program """ if __name__ == '__main__': """ Ask for analysis number N """ N = int(input('Please insert integer number N: ')) print('input number was: {0}\n'.format(N)) """ Check if N==1 or N==0""" if N==1 or N==0: print('Please put an N different from 0 and from 1') exit() """ Check if N is even """ if (N%2)==0: print('N is even, so does not make sense!') exit() """ Check if N can be put in N=p^q, p>1, q>=2 """ """ Try all numbers for p: from 2 to sqrt(N) """ if check_if_power(N)==True: exit() print('Not an easy case, using the quantum circuit is necessary\n') """ To login to IBM Q experience the following functions should be called """ """ IBMQ.delete_accounts() IBMQ.save_account('insert token here') IBMQ.load_accounts() """ """ Get an integer a that is coprime with N """ a = get_value_a(N) """ If user wants to force some values, he can do that here, please make sure to update the print and that N and a are coprime""" print('Forcing N=15 and a=4 because its the fastest case, please read top of source file for more info') N=15 a=4 """ Get n value used in Shor's algorithm, to know how many qubits are used """ n = math.ceil(math.log(N,2)) print('Total number of qubits used: {0}\n'.format(4*n+2)) ts = time.time() """ Create quantum and classical registers """ """auxilliary quantum register used in addition and multiplication""" aux = QuantumRegister(n+2) """quantum register where the sequential QFT is performed""" up_reg = QuantumRegister(2*n) """quantum register where the multiplications are made""" down_reg = QuantumRegister(n) """classical register where the measured values of the QFT are stored""" up_classic = ClassicalRegister(2*n) """ Create Quantum Circuit """ circuit = QuantumCircuit(down_reg , up_reg , aux, up_classic) """ Initialize down register to 1 and create maximal superposition in top register """ circuit.h(up_reg) circuit.x(down_reg[0]) """ Apply the multiplication gates as showed in the report in order to create the exponentiation """ for i in range(0, 2*n): cMULTmodN(circuit, up_reg[i], down_reg, aux, int(pow(a, pow(2, i))), N, n) """ Apply inverse QFT """ create_inverse_QFT(circuit, up_reg, 2*n ,1) """ Measure the top qubits, to get x value""" circuit.measure(up_reg,up_classic) """ show results of circuit creation """ create_time = round(time.time()-ts, 3) #if n < 8: print(circuit) print(f"... circuit creation time = {create_time}") ts = time.time() """ Select how many times the circuit runs""" number_shots=int(input('Number of times to run the circuit: ')) if number_shots < 1: print('Please run the circuit at least one time...') exit() if number_shots > 1: print('\nIf the circuit takes too long to run, consider running it less times\n') """ Print info to user """ print('Executing the circuit {0} times for N={1} and a={2}\n'.format(number_shots,N,a)) """ Simulate the created Quantum Circuit """ simulation = execute(circuit, backend=BasicAer.get_backend('qasm_simulator'),shots=number_shots) """ to run on IBM, use backend=IBMQ.get_backend('ibmq_qasm_simulator') in execute() function """ """ to run locally, use backend=BasicAer.get_backend('qasm_simulator') in execute() function """ """ Get the results of the simulation in proper structure """ sim_result=simulation.result() counts_result = sim_result.get_counts(circuit) """ show execution time """ exec_time = round(time.time()-ts, 3) print(f"... circuit execute time = {exec_time}") """ Print info to user from the simulation results """ print('Printing the various results followed by how many times they happened (out of the {} cases):\n'.format(number_shots)) i=0 while i < len(counts_result): print('Result \"{0}\" happened {1} times out of {2}'.format(list(sim_result.get_counts().keys())[i],list(sim_result.get_counts().values())[i],number_shots)) i=i+1 """ An empty print just to have a good display in terminal """ print(' ') """ Initialize this variable """ prob_success=0 """ For each simulation result, print proper info to user and try to calculate the factors of N""" i=0 while i < len(counts_result): """ Get the x_value from the final state qubits """ output_desired = list(sim_result.get_counts().keys())[i] x_value = int(output_desired, 2) prob_this_result = 100 * ( int( list(sim_result.get_counts().values())[i] ) ) / (number_shots) print("------> Analysing result {0}. This result happened in {1:.4f} % of all cases\n".format(output_desired,prob_this_result)) """ Print the final x_value to user """ print('In decimal, x_final value for this result is: {0}\n'.format(x_value)) """ Get the factors using the x value obtained """ success=get_factors(int(x_value),int(2*n),int(N),int(a)) if success==True: prob_success = prob_success + prob_this_result i=i+1 print("\nUsing a={0}, found the factors of N={1} in {2:.4f} % of the cases\n".format(a,N,prob_success))
https://github.com/ttlion/ShorAlgQiskit
ttlion
""" This is the final implementation of Shor's Algorithm using the circuit presented in section 2.3 of the report about the second simplification introduced by the base paper used. The circuit is general, so, in a good computer that can support simulations infinite qubits, it can factorize any number N. The only limitation is the capacity of the computer when running in local simulator and the limits on the IBM simulator (in the number of qubits and in the number of QASM instructions the simulations can have when sent to IBM simulator). The user may try N=21, which is an example that runs perfectly fine even just in local simulator because, as in explained in report, this circuit, because implements the QFT sequentially, uses less qubits then when using a "normal"n QFT. """ """ Imports from qiskit""" from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute, IBMQ from qiskit import BasicAer import sys """ Imports to Python functions """ import math import array import fractions import numpy as np import time """ Local Imports """ from cfunctions import check_if_power, get_value_a from cfunctions import get_factors from qfunctions import create_QFT, create_inverse_QFT from qfunctions import getAngle, cMULTmodN """ Main program """ if __name__ == '__main__': """ Ask for analysis number N """ N = int(input('Please insert integer number N: ')) print('input number was: {0}\n'.format(N)) """ Check if N==1 or N==0""" if N==1 or N==0: print('Please put an N different from 0 and from 1') exit() """ Check if N is even """ if (N%2)==0: print('N is even, so does not make sense!') exit() """ Check if N can be put in N=p^q, p>1, q>=2 """ """ Try all numbers for p: from 2 to sqrt(N) """ if check_if_power(N)==True: exit() print('Not an easy case, using the quantum circuit is necessary\n') """ To login to IBM Q experience the following functions should be called """ """ IBMQ.delete_accounts() IBMQ.save_account('insert token here') IBMQ.load_accounts()""" """ Get an integer a that is coprime with N """ a = get_value_a(N) """ If user wants to force some values, can do that here, please make sure to update print and that N and a are coprime""" """print('Forcing N=15 and a=4 because its the fastest case, please read top of source file for more info') N=15 a=2""" """ Get n value used in Shor's algorithm, to know how many qubits are used """ n = math.ceil(math.log(N,2)) print('Total number of qubits used: {0}\n'.format(2*n+3)) ts = time.time() """ Create quantum and classical registers """ """auxilliary quantum register used in addition and multiplication""" aux = QuantumRegister(n+2) """single qubit where the sequential QFT is performed""" up_reg = QuantumRegister(1) """quantum register where the multiplications are made""" down_reg = QuantumRegister(n) """classical register where the measured values of the sequential QFT are stored""" up_classic = ClassicalRegister(2*n) """classical bit used to reset the state of the top qubit to 0 if the previous measurement was 1""" c_aux = ClassicalRegister(1) """ Create Quantum Circuit """ circuit = QuantumCircuit(down_reg , up_reg , aux, up_classic, c_aux) """ Initialize down register to 1""" circuit.x(down_reg[0]) """ Cycle to create the Sequential QFT, measuring qubits and applying the right gates according to measurements """ for i in range(0, 2*n): """reset the top qubit to 0 if the previous measurement was 1""" circuit.x(up_reg).c_if(c_aux, 1) circuit.h(up_reg) cMULTmodN(circuit, up_reg[0], down_reg, aux, a**(2**(2*n-1-i)), N, n) """cycle through all possible values of the classical register and apply the corresponding conditional phase shift""" for j in range(0, 2**i): """the phase shift is applied if the value of the classical register matches j exactly""" circuit.u1(getAngle(j, i), up_reg[0]).c_if(up_classic, j) circuit.h(up_reg) circuit.measure(up_reg[0], up_classic[i]) circuit.measure(up_reg[0], c_aux[0]) """ show results of circuit creation """ create_time = round(time.time()-ts, 3) #if n < 8: print(circuit) print(f"... circuit creation time = {create_time}") ts = time.time() """ Select how many times the circuit runs""" number_shots=int(input('Number of times to run the circuit: ')) if number_shots < 1: print('Please run the circuit at least one time...') exit() """ Print info to user """ print('Executing the circuit {0} times for N={1} and a={2}\n'.format(number_shots,N,a)) """ Simulate the created Quantum Circuit """ simulation = execute(circuit, backend=BasicAer.get_backend('qasm_simulator'),shots=number_shots) """ to run on IBM, use backend=IBMQ.get_backend('ibmq_qasm_simulator') in execute() function """ """ to run locally, use backend=BasicAer.get_backend('qasm_simulator') in execute() function """ """ Get the results of the simulation in proper structure """ sim_result=simulation.result() counts_result = sim_result.get_counts(circuit) """ show execution time """ exec_time = round(time.time()-ts, 3) print(f"... circuit execute time = {exec_time}") """ Print info to user from the simulation results """ print('Printing the various results followed by how many times they happened (out of the {} cases):\n'.format(number_shots)) i=0 while i < len(counts_result): print('Result \"{0}\" happened {1} times out of {2}'.format(list(sim_result.get_counts().keys())[i],list(sim_result.get_counts().values())[i],number_shots)) i=i+1 """ An empty print just to have a good display in terminal """ print(' ') """ Initialize this variable """ prob_success=0 """ For each simulation result, print proper info to user and try to calculate the factors of N""" i=0 while i < len(counts_result): """ Get the x_value from the final state qubits """ all_registers_output = list(sim_result.get_counts().keys())[i] output_desired = all_registers_output.split(" ")[1] x_value = int(output_desired, 2) prob_this_result = 100 * ( int( list(sim_result.get_counts().values())[i] ) ) / (number_shots) print("------> Analysing result {0}. This result happened in {1:.4f} % of all cases\n".format(output_desired,prob_this_result)) """ Print the final x_value to user """ print('In decimal, x_final value for this result is: {0}\n'.format(x_value)) """ Get the factors using the x value obtained """ success = get_factors(int(x_value),int(2*n),int(N),int(a)) if success==True: prob_success = prob_success + prob_this_result i=i+1 print("\nUsing a={0}, found the factors of N={1} in {2:.4f} % of the cases\n".format(a,N,prob_success))
https://github.com/ttlion/ShorAlgQiskit
ttlion
""" This file allows to test the Multiplication blocks Ua. This blocks, when put together as explain in the report, do the exponentiation. The user can change N, n, a and the input state, to create the circuit: up_reg |+> ---------------------|----------------------- |+> | | | -------|--------- ------------ | | ------------ down_reg |x> ------------ | Mult | ------------ |(x*a) mod N> ------------ | | ------------ ----------------- Where |x> has n qubits and is the input state, the user can change it to whatever he wants This file uses as simulator the local simulator 'statevector_simulator' because this simulator saves the quantum state at the end of the circuit, which is exactly the goal of the test file. This simulator supports sufficient qubits to the size of the QFTs that are going to be used in Shor's Algorithm because the IBM simulator only supports up to 32 qubits """ """ Imports from qiskit""" from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute, IBMQ, BasicAer """ Imports to Python functions """ import math import time """ Local Imports """ from qfunctions import create_QFT, create_inverse_QFT from qfunctions import cMULTmodN """ Function to properly get the final state, it prints it to user """ """ This is only possible in this way because the program uses the statevector_simulator """ def get_final(results, number_aux, number_up, number_down): i=0 """ Get total number of qubits to go through all possibilities """ total_number = number_aux + number_up + number_down max = pow(2,total_number) print('|aux>|top_register>|bottom_register>\n') while i<max: binary = bin(i)[2:].zfill(total_number) number = results.item(i) number = round(number.real, 3) + round(number.imag, 3) * 1j """ If the respective state is not zero, then print it and store the state of the register where the result we are looking for is. This works because that state is the same for every case where number !=0 """ if number!=0: print('|{0}>|{1}>|{2}>'.format(binary[0:number_aux],binary[number_aux:(number_aux+number_up)],binary[(number_aux+number_up):(total_number)]),number) if binary[number_aux:(number_aux+number_up)]=='1': store = binary[(number_aux+number_up):(total_number)] i=i+1 print(' ') return int(store, 2) """ Main program """ if __name__ == '__main__': """ Select number N to do modN""" N = int(input('Please insert integer number N: ')) print(' ') """ Get n value used in QFT, to know how many qubits are used """ n = math.ceil(math.log(N,2)) """ Select the value for 'a' """ a = int(input('Please insert integer number a: ')) print(' ') """ Please make sure the a and N are coprime""" if math.gcd(a,N)!=1: print('Please make sure the a and N are coprime. Exiting program.') exit() print('Total number of qubits used: {0}\n'.format(2*n+3)) print('Please check source file to change input quantum state. By default is |2>.\n') ts = time.time() """ Create quantum and classical registers """ aux = QuantumRegister(n+2) up_reg = QuantumRegister(1) down_reg = QuantumRegister(n) aux_classic = ClassicalRegister(n+2) up_classic = ClassicalRegister(1) down_classic = ClassicalRegister(n) """ Create Quantum Circuit """ circuit = QuantumCircuit(down_reg , up_reg , aux, down_classic, up_classic, aux_classic) """ Initialize with |+> to also check if the control is working""" circuit.h(up_reg[0]) """ Put the desired input state in the down quantum register. By default we put |2> """ circuit.x(down_reg[1]) """ Apply multiplication""" cMULTmodN(circuit, up_reg[0], down_reg, aux, int(a), N, n) """ show results of circuit creation """ create_time = round(time.time()-ts, 3) if n < 8: print(circuit) print(f"... circuit creation time = {create_time}") ts = time.time() """ Simulate the created Quantum Circuit """ simulation = execute(circuit, backend=BasicAer.get_backend('statevector_simulator'),shots=1) """ Get the results of the simulation in proper structure """ sim_result=simulation.result() """ Get the statevector of the final quantum state """ outputstate = sim_result.get_statevector(circuit, decimals=3) """ Show the final state after the multiplication """ after_exp = get_final(outputstate, n+2, 1, n) """ show execution time """ exec_time = round(time.time()-ts, 3) print(f"... circuit execute time = {exec_time}") """ Print final quantum state to user """ print('When control=1, value after exponentiation is in bottom quantum register: |{0}>'.format(after_exp))
https://github.com/ttlion/ShorAlgQiskit
ttlion
""" This file allows to test the various QFT implemented. The user must specify: 1) The number of qubits it wants the QFT to be implemented on 2) The kind of QFT want to implement, among the options: -> Normal QFT with SWAP gates at the end -> Normal QFT without SWAP gates at the end -> Inverse QFT with SWAP gates at the end -> Inverse QFT without SWAP gates at the end The user must can also specify, in the main function, the input quantum state. By default is a maximal superposition state This file uses as simulator the local simulator 'statevector_simulator' because this simulator saves the quantum state at the end of the circuit, which is exactly the goal of the test file. This simulator supports sufficient qubits to the size of the QFTs that are going to be used in Shor's Algorithm because the IBM simulator only supports up to 32 qubits """ """ Imports from qiskit""" from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute, IBMQ, BasicAer """ Imports to Python functions """ import time """ Local Imports """ from qfunctions import create_QFT, create_inverse_QFT """ Function to properly print the final state of the simulation """ """ This is only possible in this way because the program uses the statevector_simulator """ def show_good_coef(results, n): i=0 max = pow(2,n) if max > 100: max = 100 """ Iterate to all possible states """ while i<max: binary = bin(i)[2:].zfill(n) number = results.item(i) number = round(number.real, 3) + round(number.imag, 3) * 1j """ Print the respective component of the state if it has a non-zero coefficient """ if number!=0: print('|{}>'.format(binary),number) i=i+1 """ Main program """ if __name__ == '__main__': """ Select how many qubits want to apply the QFT on """ n = int(input('\nPlease select how many qubits want to apply the QFT on: ')) """ Select the kind of QFT to apply using the variable what_to_test: what_to_test = 0: Apply normal QFT with the SWAP gates at the end what_to_test = 1: Apply normal QFT without the SWAP gates at the end what_to_test = 2: Apply inverse QFT with the SWAP gates at the end what_to_test = 3: Apply inverse QFT without the SWAP gates at the end """ print('\nSelect the kind of QFT to apply:') print('Select 0 to apply normal QFT with the SWAP gates at the end') print('Select 1 to apply normal QFT without the SWAP gates at the end') print('Select 2 to apply inverse QFT with the SWAP gates at the end') print('Select 3 to apply inverse QFT without the SWAP gates at the end\n') what_to_test = int(input('Select your option: ')) if what_to_test<0 or what_to_test>3: print('Please select one of the options') exit() print('\nTotal number of qubits used: {0}\n'.format(n)) print('Please check source file to change input quantum state. By default is a maximal superposition state with |+> in every qubit.\n') ts = time.time() """ Create quantum and classical registers """ quantum_reg = QuantumRegister(n) classic_reg = ClassicalRegister(n) """ Create Quantum Circuit """ circuit = QuantumCircuit(quantum_reg, classic_reg) """ Create the input state desired Please change this as you like, by default we put H gates in every qubit, initializing with a maximimal superposition state """ #circuit.h(quantum_reg) """ Test the right QFT according to the variable specified before""" if what_to_test == 0: create_QFT(circuit,quantum_reg,n,1) elif what_to_test == 1: create_QFT(circuit,quantum_reg,n,0) elif what_to_test == 2: create_inverse_QFT(circuit,quantum_reg,n,1) elif what_to_test == 3: create_inverse_QFT(circuit,quantum_reg,n,0) else: print('Noting to implement, exiting program') exit() """ show results of circuit creation """ create_time = round(time.time()-ts, 3) if n < 8: print(circuit) print(f"... circuit creation time = {create_time}") ts = time.time() """ Simulate the created Quantum Circuit """ simulation = execute(circuit, backend=BasicAer.get_backend('statevector_simulator'),shots=1) """ Get the results of the simulation in proper structure """ sim_result=simulation.result() """ Get the statevector of the final quantum state """ outputstate = sim_result.get_statevector(circuit, decimals=3) """ show execution time """ exec_time = round(time.time()-ts, 3) print(f"... circuit execute time = {exec_time}") """ Print final quantum state to user """ print('The final state after applying the QFT is:\n') show_good_coef(outputstate,n)
https://github.com/qiskit-community/qgss-2024
qiskit-community
# required imports: from qiskit.visualization import array_to_latex from qiskit.quantum_info import Statevector, random_statevector from qiskit.quantum_info.operators import Operator, Pauli from qiskit import QuantumCircuit from qiskit.circuit.library import HGate, CXGate import numpy as np ket0 = [[1],[0]] array_to_latex(ket0) bra0 = [1,0] array_to_latex(bra0) ket1 = # put your answer answer here for |1⟩ bra1 = # put answer here for ⟨1| from qc_grader.challenges.qgss_2023 import grade_lab1_ex1 grade_lab1_ex1([ket1, bra1]) sv_bra0 = Statevector(bra0) sv_bra0 sv_bra0.draw('latex') sv_eq = Statevector([1/2, 3/4, 4/5, 6/8]) sv_eq.draw('latex') sv_eq.is_valid() sv_valid = # create your statevector here from qc_grader.challenges.qgss_2023 import grade_lab1_ex2 grade_lab1_ex2(sv_valid) op_bra0 = Operator(bra0) op_bra0 op_ket0 = Operator(ket0) op_bra0.tensor(op_ket0) braket = np.dot(op_bra0,op_ket0) array_to_latex(braket) ketbra = np.outer(ket0,bra0) array_to_latex(ketbra) braket = np.dot(op_bra0,op_ket0) array_to_latex(braket) bra1ket0 = # put your answer for ⟨1|0⟩ here bra0ket1 = # put your answer for ⟨0|1⟩ here bra1ket1 = # put your answer for ⟨1|1⟩ here ket1bra0 = # put your answer for |1⟩⟨0| here ket0bra1 = # put your answer for |0⟩⟨1| here ket1bra1 = # put your answer for |1⟩⟨1| here from qc_grader.challenges.qgss_2023 import grade_lab1_ex3 grade_lab1_ex3([bra1ket0, bra0ket1, bra1ket1, ket1bra0, ket0bra1, ket1bra1]) # add or remove your answer from this list answer = ['a', 'b', 'c'] from qc_grader.challenges.qgss_2023 import grade_lab1_ex4 grade_lab1_ex4(answer) m1 = Operator([[1,1],[0,0]]) array_to_latex(m1) m3 = Operator([[0,1],[1,0]]) array_to_latex(m3) array_to_latex(m1@ket0) m2 = # create an operator for m2 here m4 = # create and operator for m4 here from qc_grader.challenges.qgss_2023 import grade_lab1_ex5 grade_lab1_ex5([m2, m4]) cnot = CXGate() array_to_latex(cnot) m3.is_unitary() random = Operator(np.array([[ 0.50778085-0.44607116j, -0.1523741 +0.14128434j, 0.44607116+0.50778085j, -0.14128434-0.1523741j ], [ 0.16855994+0.12151822j, 0.55868196+0.38038841j, -0.12151822+0.16855994j, -0.38038841+0.55868196j], [ 0.50778085-0.44607116j, -0.1523741 +0.14128434j, -0.44607116-0.50778085j, 0.14128434+0.1523741j ], [ 0.16855994+0.12151822j, 0.55868196+0.38038841j, 0.12151822-0.16855994j, 0.38038841-0.55868196j]])) random.is_unitary() non_unitary_op = # create your operator here from qc_grader.challenges.qgss_2023 import grade_lab1_ex6 grade_lab1_ex6(non_unitary_op) pauli_x = Pauli('X') array_to_latex(pauli_x) pauli_y = Pauli('Y') array_to_latex(pauli_y) pauli_z = Pauli('Z') array_to_latex(pauli_z) op_x = Operator(pauli_x) op_x op_new = np.dot(op_x,ket0) array_to_latex(op_new) result = # do your operations here from qc_grader.challenges.qgss_2023 import grade_lab1_ex7 grade_lab1_ex7(result) hadamard = HGate() array_to_latex(hadamard) hop = Operator(hadamard) hop.is_unitary() bell = QuantumCircuit(2) bell.h(0) # apply an H gate to the circuit bell.cx(0,1) # apply a CNOT gate to the circuit bell.draw(output="mpl") bell_op = Operator(bell) array_to_latex(bell_op) ghz = QuantumCircuit(3) ############################## # add gates to your circuit here ############################## ghz.draw(output='mpl') from qc_grader.challenges.qgss_2023 import grade_lab1_ex8 grade_lab1_ex8(ghz) plus_state = Statevector.from_label("+") plus_state.draw('latex') plus_state plus_state.probabilities_dict() # run this cell multiple times to show collapsing into one state or the other res = plus_state.measure() res qc = QuantumCircuit(1,1) qc.h(0) qc.measure(0, 0) qc.draw(output="mpl") sv_bell = Statevector([np.sqrt(1/2), 0, 0, np.sqrt(1/2)]) sv_bell.draw('latex') sv_bell.probabilities_dict() sv_psi_plus = # create a statevector for |𝜓+⟩ here prob_psi_plus = # find the measurement probabilities for |𝜓+⟩ here sv_psi_minus = # create a statevector for |𝜓−⟩ here prob_psi_minus = # find the measurement probabilities for |𝜓−⟩ here sv_phi_minus = # create a statevector for |𝜙−⟩ here prob_phi_minus = # find the measurement probabilities for |𝜙−⟩ here from qc_grader.challenges.qgss_2023 import grade_lab1_ex9 grade_lab1_ex9([prob_psi_plus, prob_psi_minus, prob_phi_minus]) qft = QuantumCircuit(2) ############################## # add gates to your circuit here ############################## qft.draw(output='mpl') from qc_grader.challenges.qgss_2023 import grade_lab1_ex10 grade_lab1_ex10(qft) U = Operator(qft) array_to_latex(U)
https://github.com/qiskit-community/qgss-2024
qiskit-community
from qiskit.circuit import QuantumCircuit from qiskit.primitives import Estimator, Sampler from qiskit.quantum_info import SparsePauliOp from qiskit.visualization import plot_histogram import numpy as np import matplotlib.pyplot as plt plt.style.use('dark_background') # optional # create excited |1> state qc_1 = QuantumCircuit(1) qc_1.x(0) qc_1.draw('mpl') # create superposition |+> state qc_plus = QuantumCircuit(1) qc_plus.h(0) qc_plus.draw('mpl') qc_1.measure_all() qc_plus.measure_all() sampler = Sampler() job_1 = sampler.run(qc_1) job_plus = sampler.run(qc_plus) job_1.result().quasi_dists job_plus.result().quasi_dists legend = ["Excited State", "Plus State"] # TODO: Excited State does not appear plot_histogram([job_1.result().quasi_dists[0], job_plus.result().quasi_dists[0]], legend=legend) qc_1.remove_final_measurements() qc_plus.remove_final_measurements() # rotate into the X-basis qc_1.h(0) qc_plus.h(0) qc_1.measure_all() qc_plus.measure_all() sampler = Sampler() job_1 = sampler.run(qc_1) job_plus = sampler.run(qc_plus) plot_histogram([job_1.result().quasi_dists[0], job_plus.result().quasi_dists[0]], legend=legend) qc2_1 = QuantumCircuit(1) qc2_1.x(0) qc2_plus = QuantumCircuit(1) qc2_plus.h(0) obsvs = list(SparsePauliOp(['Z', 'X'])) estimator = Estimator() job2_1 = estimator.run([qc2_1]*len(obsvs), observables=obsvs) job2_plus = estimator.run([qc2_plus]*len(obsvs), observables=obsvs) job2_1.result() # TODO: make this into module that outputs a nice table print(f' | <Z> | <X> ') print(f'----|------------------') print(f'|1> | {job2_1.result().values[0]} | {job2_1.result().values[1]}') print(f'|+> | {job2_plus.result().values[0]} | {job2_plus.result().values[1]}') obsv = # create operator for chsh witness from qc_grader.challenges.qgss_2023 import grade_lab2_ex1 grade_lab2_ex1(obsv) from qiskit.circuit import Parameter theta = Parameter('θ') qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc.ry(theta, 0) qc.draw('mpl') angles = # create a parameterization of angles that will violate the inequality estimator = Estimator() job = estimator.run([qc]*len(angles), observables=[obsv]*len(angles), parameter_values=angles) exps = job.result().values plt.plot(angles, exps, marker='x', ls='-', color='green') plt.plot(angles, [2]*len(angles), ls='--', color='red', label='Classical Bound') plt.plot(angles, [-2]*len(angles), ls='--', color='red') plt.xlabel('angle (rad)') plt.ylabel('CHSH Witness') plt.legend(loc=4) from qc_grader.challenges.qgss_2023 import grade_lab2_ex2 grade_lab2_ex2(obsv, angles) from qiskit.circuit import ClassicalRegister, QuantumRegister theta = Parameter('θ') qr = QuantumRegister(1, 'q') qc = QuantumCircuit(qr) qc.ry(theta, 0) qc.draw('mpl') tele_qc = qc.copy() bell = QuantumRegister(2, 'Bell') alice = ClassicalRegister(2, 'Alice') bob = ClassicalRegister(1, 'Bob') tele_qc.add_register(bell, alice, bob) tele_qc.draw('mpl') # create Bell state with other two qubits tele_qc.barrier() tele_qc.h(1) tele_qc.cx(1, 2) tele_qc.barrier() tele_qc.draw('mpl') # alice operates on her qubits tele_qc.cx(0, 1) tele_qc.h(0) tele_qc.barrier() tele_qc.draw('mpl') tele_qc.measure([qr[0], bell[0]], alice) tele_qc.draw('mpl') graded_qc = tele_qc.copy() ############################## # add gates to graded_qc here ############################## graded_qc.draw('mpl') graded_qc.barrier() graded_qc.measure(bell[1], bob) graded_qc.draw('mpl') from qc_grader.challenges.qgss_2023 import grade_lab2_ex3 grade_lab2_ex3(graded_qc, theta, 5*np.pi/7) from qiskit_aer.primitives import Sampler angle = 5*np.pi/7 sampler = Sampler() qc.measure_all() job_static = sampler.run(qc.bind_parameters({theta: angle})) job_dynamic = sampler.run(graded_qc.bind_parameters({theta: angle})) print(f"Original Dists: {job_static.result().quasi_dists[0].binary_probabilities()}") print(f"Teleported Dists: {job_dynamic.result().quasi_dists[0].binary_probabilities()}") from qiskit.result import marginal_counts tele_counts = # marginalize counts legend = ['Original State', 'Teleported State'] plot_histogram([job_static.result().quasi_dists[0].binary_probabilities(), tele_counts], legend=legend) from qc_grader.challenges.qgss_2023 import grade_lab2_ex4 grade_lab2_ex4(tele_counts, job_dynamic.result()) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/qiskit-community/qgss-2024
qiskit-community
from qiskit import QuantumCircuit, Aer, execute import numpy as np from qiskit.visualization import plot_histogram import matplotlib.pyplot as plt from math import gcd #QFT Circuit def qft(n): """Creates an n-qubit QFT circuit""" circuit = QuantumCircuit(n) def swap_registers(circuit, n): for qubit in range(n//2): circuit.swap(qubit, n-qubit-1) return circuit def qft_rotations(circuit, n): """Performs qft on the first n qubits in circuit (without swaps)""" if n == 0: return circuit n -= 1 circuit.h(n) for qubit in range(n): circuit.cp(np.pi/2**(n-qubit), qubit, n) qft_rotations(circuit, n) qft_rotations(circuit, n) swap_registers(circuit, n) return circuit #Inverse Quantum Fourier Transform def qft_dagger(qc, n): """n-qubit QFTdagger the first n qubits in circ""" # Don't forget the Swaps! for qubit in range(n//2): qc.swap(qubit, n-qubit-1) for j in range(n): for m in range(j): qc.cp(-np.pi/float(2**(j-m)), m, j) qc.h(j) return qc phase_register_size = 4 qpe4 = QuantumCircuit(phase_register_size+1, phase_register_size) ### Insert your code here ## Run this cell to simulate 'qpe4' and to plot the histogram of the result sim = Aer.get_backend('aer_simulator') shots = 2000 count_qpe4 = execute(qpe4, sim, shots=shots).result().get_counts() plot_histogram(count_qpe4, figsize=(9,5)) from qc_grader.challenges.qgss_2023 import grade_lab3_ex1 grade_lab3_ex1(count_qpe4) #Grab the highest probability measurement max_binary_counts = 0 max_binary_val = '' for key, item in count_qpe4.items(): if item > max_binary_counts: max_binary_counts = item max_binary_val = key ## Your function to convert a binary string to decimal goes here estimated_phase = # calculate the estimated phase phase_accuracy_window = # highest power of 2 (i.e. smallest decimal) this circuit can estimate from qc_grader.challenges.qgss_2023 import grade_lab3_ex2 grade_lab3_ex2([estimated_phase, phase_accuracy_window]) from qiskit_ibm_provider import IBMProvider from qiskit.compiler import transpile provider = IBMProvider() hub = "YOUR_HUB" group = "YOUR_GROUP" project = "YOUR_PROJECT" backend_name = "YOUR_BACKEND" backend = provider.get_backend(backend_name, instance=f"{hub}/{group}/{project}") # your code goes here from qc_grader.challenges.qgss_2023 import grade_lab3_ex3 grade_lab3_ex3([max_depth_qpe, min_depth_qpe]) shots = 2000 #OPTIONAL: Run the minimum depth qpe circuit job_min_qpe4 = backend.run(min_depth_qpe, sim, shots=shots) print(job_min_qpe4.job_id()) #Gather the count data count_min_qpe4 = job_min_qpe4.result().get_counts() plot_histogram(count_min_qpe4, figsize=(9,5)) #OPTIONAL: Run the maximum depth qpe circuit job_max_qpe4 = backend.run(max_depth_qpe, sim, shots=shots) print(job_max_qpe4.job_id()) #Gather the count data count_max_qpe4 = job_max_qpe4.result().get_counts() plot_histogram(count_max_qpe4, figsize=(9,5)) def qpe_circuit(register_size): # Your code goes here return qpe ## Run this cell to simulate 'qpe4' and to plot the histogram of the result reg_size = # Vary the register sizes qpe_check = qpe_circuit(reg_size) sim = Aer.get_backend('aer_simulator') shots = 10000 count_qpe4 = execute(qpe_check, sim, shots=shots).result().get_counts() plot_histogram(count_qpe4, figsize=(9,5)) # Process the count data to determine accuracy of the estimated phase required_register_size = #your answer here from qc_grader.challenges.qgss_2023 import grade_lab3_ex4 grade_lab3_ex4(required_register_size) ## Create 7mod15 gate N = 15 m = int(np.ceil(np.log2(N))) U_qc = QuantumCircuit(m) U_qc.x(range(m)) U_qc.swap(1, 2) U_qc.swap(2, 3) U_qc.swap(0, 3) U = U_qc.to_gate() U.name ='{}Mod{}'.format(7, N) ### your code goes here qcirc = QuantumCircuit(m) ## Run this cell to simulate 'qpe4' and to plot the histogram of the result sim = Aer.get_backend('aer_simulator') shots = 20000 input_1 = execute(qcirc, sim, shots=shots).result().get_counts() # save the count data for input 1 input_2 = # save the count data for input 2 input_5 = # save the count data for input 5 from qc_grader.challenges.qgss_2023 import grade_lab3_ex5 grade_lab3_ex5([input_1, input_2, input_5]) unitary_circ = QuantumCircuit(m) # Your code goes here sim = Aer.get_backend('unitary_simulator') unitary = execute(unitary_circ, sim).result().get_unitary() from qc_grader.challenges.qgss_2023 import grade_lab3_ex6 grade_lab3_ex6(unitary, unitary_circ) #This function will return a ControlledGate object which repeats the action # of U, 2^k times def cU_multi(k): sys_register_size = 4 circ = QuantumCircuit(sys_register_size) for _ in range(2**k): circ.append(U, range(sys_register_size)) U_multi = circ.to_gate() U_multi.name = '7Mod15_[2^{}]'.format(k) cU_multi = U_multi.control() return cU_multi # your code goes here shor_qpe = #Create the QuantumCircuit needed to run with 8 phase register qubits ## Run this cell to simulate 'shor_qpe' and to plot the histogram of the results sim = Aer.get_backend('aer_simulator') shots = 20000 shor_qpe_counts = execute(shor_qpe, sim, shots=shots).result().get_counts() plot_histogram(shor_qpe_counts, figsize=(9,5)) from qc_grader.challenges.qgss_2023 import grade_lab3_ex7 grade_lab3_ex7(shor_qpe_counts) from fractions import Fraction print(Fraction(0.666), '\n') print(Fraction(0.666).limit_denominator(15)) shor_qpe_fractions = # create a list of Fraction objects for each measurement outcome from qc_grader.challenges.qgss_2023 import grade_lab3_ex8 grade_lab3_ex8(shor_qpe_fractions) def shor_qpe(k): a = 7 #Step 1. Begin a while loop until a nontrivial guess is found ### Your code goes here ### #Step 2a. Construct a QPE circuit with m phase count qubits # to guess the phase phi = s/r using the function cU_multi() ### Your code goes here ### #Step 2b. Run the QPE circuit with a single shot, record the results # and convert the estimated phase bitstring to decimal ### Your code goes here ### #Step 3. Use the Fraction object to find the guess for r ### Your code goes here ### #Step 4. Now that r has been found, use the builtin greatest common deonominator # function to determine the guesses for a factor of N guesses = [gcd(a**(r//2)-1, N), gcd(a**(r//2)+1, N)] #Step 5. For each guess in guesses, check if at least one is a non-trivial factor # i.e. (guess != 1 or N) and (N % guess == 0) ### Your code goes here ### #Step 6. If a nontrivial factor is found return the list 'guesses', otherwise # continue the while loop ### Your code goes here ### return guesses from qc_grader.challenges.qgss_2023 import grade_lab3_ex9 grade_lab3_ex9(shor_qpe)
https://github.com/Qiskit-Extensions/circuit-knitting-toolbox
Qiskit-Extensions
# This code is a Qiskit project. # (C) Copyright IBM 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. """Helper functions that are used in the code.""" from __future__ import annotations from qiskit import QuantumCircuit from qiskit.circuit import Instruction, Gate from .optimization_settings import OptimizationSettings from typing import TYPE_CHECKING, cast, Callable if TYPE_CHECKING: from .cut_optimization import CutOptimizationFuncArgs # pragma: no cover from .disjoint_subcircuits_state import DisjointSubcircuitsState from .search_space_generator import SearchFunctions from .best_first_search import BestFirstSearch from .circuit_interface import CircuitElement, SimpleGateList from ..qpd import QPDBasis def qc_to_cco_circuit(circuit: QuantumCircuit) -> list[str | CircuitElement]: """Convert a :class:`qiskit.QuantumCircuit` instance into a circuit list that is compatible with the :class:`SimpleGateList`. To conform with the uniformity of the design, single qubit gates are assigned :math:`gamma=None`. In the converted list, a barrier across the entire circuit is represented by the string "barrier." Everything else is represented by an instance of :class:`CircuitElement`. Args: circuit: an instance of :class:`qiskit.QuantumCircuit` . Returns: circuit_list_rep: list of circuit instructions represented in a form that is compatible with :class:`SimpleGateList` and can therefore be ingested by the cut finder. TODO: Extend this function to allow for circuits with (mid-circuit or other) measurements, as needed. """ circuit_list_rep = [] for inst in circuit.data: if inst.operation.name == "barrier" and len(inst.qubits) == circuit.num_qubits: circuit_element: CircuitElement | str = "barrier" else: gamma = None if isinstance(inst.operation, Gate) and len(inst.qubits) == 2: gamma = QPDBasis.from_instruction(inst.operation).kappa name = inst.operation.name params = inst.operation.params circuit_element = CircuitElement( name=name, params=params, qubits=list(circuit.find_bit(q).index for q in inst.qubits), gamma=gamma, ) circuit_list_rep.append(circuit_element) return circuit_list_rep # currently not in use, written up for future use. def cco_to_qc_circuit(interface: SimpleGateList) -> QuantumCircuit: """Convert the cut circuit outputted by the cut finder into a :class:`qiskit.QuantumCircuit` instance. Args: interface: An instance of :class:`SimpleGateList` whose attributes carry information about the cut circuit. Returns: qc_cut: The SimpleGateList converted into a :class:`qiskit.QuantumCircuit` instance. TODO: This function only works for instances of LO gate cutting. Expand to cover the wire cutting case if or when needed. """ cut_circuit_list = interface.export_cut_circuit(name_mapping=None) num_qubits = interface.get_num_wires() cut_types = interface.cut_type qc_cut = QuantumCircuit(num_qubits) for k, op in enumerate([cut_circuit for cut_circuit in cut_circuit_list]): if cut_types[k] is None: # only append gates that are not cut. op_name = op.name op_qubits = op.qubits op_params = op.params inst = Instruction(op_name, len(op_qubits), 0, op_params) qc_cut.append(inst, op_qubits) return qc_cut def select_search_engine( stage_of_optimization: str, optimization_settings: OptimizationSettings, search_space_funcs: SearchFunctions, stop_at_first_min: bool = False, ) -> BestFirstSearch: """Select the search algorithm to use. In this release, the main search engine is always Dijkstra's best first search algorithm. Note however that there is also :func:``greedy_best_first_search``, which is used to warm start the search algorithm. It can also provide a solution should the main search engine fail to find a solution given the constraints on the computation it is allowed to perform. """ engine = optimization_settings.get_engine_selection(stage_of_optimization) if engine == "BestFirst": return BestFirstSearch( optimization_settings, search_space_funcs, stop_at_first_min=stop_at_first_min, ) else: raise ValueError(f"Search engine {engine} is not supported.") def greedy_best_first_search( state: DisjointSubcircuitsState, search_space_funcs: SearchFunctions, *args: CutOptimizationFuncArgs, ) -> None | DisjointSubcircuitsState: """Perform greedy best-first search using the input starting state and the input search-space functions. The resulting goal state is returned, or None if a deadend is reached. Any additional input argumnets are passed as additional arguments to the search-space functions. """ search_space_funcs.goal_state_func = cast( Callable, search_space_funcs.goal_state_func ) search_space_funcs.cost_func = cast(Callable, search_space_funcs.cost_func) search_space_funcs.next_state_func = cast( Callable, search_space_funcs.next_state_func ) while not search_space_funcs.goal_state_func(state, *args): best = min( [ (search_space_funcs.cost_func(next_state, *args), k, next_state) for k, next_state in enumerate( search_space_funcs.next_state_func(state, *args) ) ], default=(None, None, None), ) if best[-1] is None: # pragma: no cover # This covers a rare edge case. # We have so far found no circuit that triggers it. # Excluding from test coverage for now. return None state = best[-1] return state
https://github.com/Qiskit-Extensions/circuit-knitting-toolbox
Qiskit-Extensions
# 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. """Two-qubit instruction representing a swap + single-qubit reset.""" from __future__ import annotations from qiskit.circuit import QuantumCircuit, Instruction class Move(Instruction): """A two-qubit instruction representing a reset of the second qubit followed by a swap. **Circuit Symbol:** .. parsed-literal:: ┌───────┐ q_0: ┤0 ├ q_0: ──────X─ │ Move │ = │ q_1: ┤1 ├ q_1: ─|0>──X─ └───────┘ The desired effect of this instruction, typically, is to move the state of the first qubit to the second qubit. For this to work as expected, the second incoming qubit must share no entanglement with the remainder of the system. If this qubit *is* entangled, then performing the reset operation will in turn implement a quantum channel on the other qubit(s) with which it is entangled, resulting in the partial collapse of those qubits. The simplest way to ensure that the second (i.e., destination) qubit shares no entanglement with the remainder of the system is to use a fresh qubit which has not been used since initialization. Another valid way is to use, as a desination qubit, a qubit whose immediate prior use was as the source (i.e., first) qubit of a preceding :class:`Move` operation. The following circuit contains two :class:`Move` operations, corresponding to each of the aforementioned cases: .. plot:: :include-source: import numpy as np from qiskit import QuantumCircuit from circuit_knitting.cutting.instructions import Move qc = QuantumCircuit(4) qc.ryy(np.pi / 4, 0, 1) qc.rx(np.pi / 4, 3) qc.append(Move(), [1, 2]) qc.rz(np.pi / 4, 0) qc.ryy(np.pi / 4, 2, 3) qc.append(Move(), [2, 1]) qc.ryy(np.pi / 4, 0, 1) qc.rx(np.pi / 4, 3) qc.draw("mpl") A full demonstration of the :class:`Move` instruction is available in `the introductory tutorial on wire cutting <../circuit_cutting/tutorials/03_wire_cutting_via_move_instruction.ipynb>`__. """ def __init__(self, label: str | None = None): """Create a :class:`Move` instruction.""" super().__init__("move", 2, 0, [], label=label) def _define(self): """Set definition to equivalent circuit.""" qc = QuantumCircuit(2, name=self.name) qc.reset(1) qc.swap(0, 1) self.definition = qc
https://github.com/Qiskit-Extensions/circuit-knitting-toolbox
Qiskit-Extensions
from qiskit import QuantumCircuit from qiskit.quantum_info import SparsePauliOp from circuit_knitting.cutting import ( partition_problem, generate_cutting_experiments, ) circuit = QuantumCircuit(2) circuit.h(0) circuit.cx(0, 1) observable = SparsePauliOp(["ZZ"]) partitioned_problem = partition_problem( circuit=circuit, partition_labels="AB", observables=observable.paulis ) subcircuits = partitioned_problem.subcircuits subobservables = partitioned_problem.subobservables subexperiments, coefficients = generate_cutting_experiments( circuits=subcircuits, observables=subobservables, num_samples=1000, ) from circuit_knitting.utils.simulation import ExactSampler exact_sampler = ExactSampler() results = { label: exact_sampler.run(subexperiment).result() for label, subexperiment in subexperiments.items() }
https://github.com/Qiskit-Extensions/circuit-knitting-toolbox
Qiskit-Extensions
import numpy as np from qiskit.circuit.library import EfficientSU2 from qiskit.quantum_info import SparsePauliOp from circuit_knitting.cutting import ( partition_problem, generate_cutting_experiments, ) circuit = EfficientSU2(4, entanglement="linear", reps=2).decompose() circuit.assign_parameters([0.8] * len(circuit.parameters), inplace=True) observable = SparsePauliOp(["ZZZZ"]) circuit.draw("mpl", scale=0.8) partitioned_problem = partition_problem( circuit=circuit, partition_labels="AABB", observables=observable.paulis ) subcircuits = partitioned_problem.subcircuits bases = partitioned_problem.bases subobservables = partitioned_problem.subobservables subcircuits["A"].draw("mpl", scale=0.6) subcircuits["B"].draw("mpl", scale=0.6) subexperiments, coefficients = generate_cutting_experiments( circuits=subcircuits, observables=subobservables, num_samples=np.inf, ) coefficients print(f"Mapping probabilities for a CNOT decomposition: {bases[0].probabilities}") from circuit_knitting.cutting.qpd import QPDBasis from qiskit.circuit.library.standard_gates import CXGate qpd_basis_cx = QPDBasis.from_instruction(CXGate()) def _min_nonzero(seq, /): """Return the minimum value in a sequence, ignoring values near zero.""" return min(x for x in seq if not np.isclose(x, 0)) num_cx_cuts = 2 print( f"Number of samples needed to retrieve exact weights: {1 / _min_nonzero(qpd_basis_cx.probabilities)**num_cx_cuts}" ) subexperiments, coefficients = generate_cutting_experiments( circuits=subcircuits, observables=subobservables, num_samples=36, ) coefficients
https://github.com/Qiskit-Extensions/circuit-knitting-toolbox
Qiskit-Extensions
import numpy as np from qiskit import QuantumCircuit from qiskit.quantum_info import SparsePauliOp from qiskit_aer.primitives import EstimatorV2, SamplerV2 from circuit_knitting.cutting import ( partition_problem, generate_cutting_experiments, reconstruct_expectation_values, ) from circuit_knitting.cutting.instructions import CutWire from circuit_knitting.cutting import cut_wires, expand_observables qc_0 = QuantumCircuit(7) for i in range(7): qc_0.rx(np.pi / 4, i) qc_0.cx(0, 3) qc_0.cx(1, 3) qc_0.cx(2, 3) qc_0.append(CutWire(), [3]) qc_0.cx(3, 4) qc_0.cx(3, 5) qc_0.cx(3, 6) qc_0.append(CutWire(), [3]) qc_0.cx(0, 3) qc_0.cx(1, 3) qc_0.cx(2, 3) qc_0.draw("mpl") qc_0.decompose("cut_wire").draw("mpl") observable = SparsePauliOp(["ZIIIIII", "IIIZIII", "IIIIIIZ"]) qc_1 = cut_wires(qc_0) qc_1.draw("mpl") observable_expanded_paulis = expand_observables(observable.paulis, qc_0, qc_1) observable_expanded_paulis partitioned_problem = partition_problem( circuit=qc_1, observables=observable_expanded_paulis ) subcircuits = partitioned_problem.subcircuits subobservables = partitioned_problem.subobservables subobservables subcircuits[0].draw("mpl") subcircuits[1].draw("mpl") subexperiments, coefficients = generate_cutting_experiments( circuits=subcircuits, observables=subobservables, num_samples=np.inf, ) sampler = SamplerV2() results = { label: sampler.run(subexperiment, shots=2**12).result() for label, subexperiment in subexperiments.items() } reconstructed_expvals = reconstruct_expectation_values( results, coefficients, subobservables, ) final_expval = np.dot(reconstructed_expvals, observable.coeffs) estimator = EstimatorV2() exact_expval = ( estimator.run([(qc_0.decompose("cut_wire"), observable)]).result()[0].data.evs ) print(f"Reconstructed expectation value: {np.real(np.round(final_expval, 8))}") print(f"Exact expectation value: {np.round(exact_expval, 8)}") print(f"Error in estimation: {np.real(np.round(final_expval-exact_expval, 8))}") print( f"Relative error in estimation: {np.real(np.round((final_expval-exact_expval) / exact_expval, 8))}" )
https://github.com/Qiskit-Extensions/circuit-knitting-toolbox
Qiskit-Extensions
from qiskit.circuit.library import EfficientSU2 qc = EfficientSU2(4, entanglement="linear", reps=2).decompose() qc.assign_parameters([0.4] * len(qc.parameters), inplace=True) qc.draw("mpl", scale=0.8) from qiskit.quantum_info import SparsePauliOp observable = SparsePauliOp(["ZZII", "IZZI", "-IIZZ", "XIXI", "ZIZZ", "IXIX"]) from circuit_knitting.cutting import partition_problem partitioned_problem = partition_problem( circuit=qc, partition_labels="AABB", observables=observable.paulis ) subcircuits = partitioned_problem.subcircuits subobservables = partitioned_problem.subobservables bases = partitioned_problem.bases subobservables subcircuits["A"].draw("mpl", scale=0.8) subcircuits["B"].draw("mpl", scale=0.8) import numpy as np print(f"Sampling overhead: {np.prod([basis.overhead for basis in bases])}") from circuit_knitting.cutting import generate_cutting_experiments subexperiments, coefficients = generate_cutting_experiments( circuits=subcircuits, observables=subobservables, num_samples=np.inf ) from qiskit_ibm_runtime.fake_provider import FakeManilaV2 backend = FakeManilaV2() from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager # Transpile the subexperiments to ISA circuits pass_manager = generate_preset_pass_manager(optimization_level=1, backend=backend) isa_subexperiments = { label: pass_manager.run(partition_subexpts) for label, partition_subexpts in subexperiments.items() } from qiskit_ibm_runtime import SamplerV2, Batch # Submit each partition's subexperiments to the Qiskit Runtime Sampler # primitive, in a single batch so that the jobs will run back-to-back. with Batch(backend=backend) as batch: sampler = SamplerV2(mode=batch) jobs = { label: sampler.run(subsystem_subexpts, shots=2**12) for label, subsystem_subexpts in isa_subexperiments.items() } # Retrieve results results = {label: job.result() for label, job in jobs.items()} from circuit_knitting.cutting import reconstruct_expectation_values # Get expectation values for each observable term reconstructed_expvals = reconstruct_expectation_values( results, coefficients, subobservables, ) # Reconstruct final expectation value final_expval = np.dot(reconstructed_expvals, observable.coeffs) from qiskit_aer.primitives import EstimatorV2 estimator = EstimatorV2() exact_expval = estimator.run([(qc, observable)]).result()[0].data.evs print(f"Reconstructed expectation value: {np.real(np.round(final_expval, 8))}") print(f"Exact expectation value: {np.round(exact_expval, 8)}") print(f"Error in estimation: {np.real(np.round(final_expval-exact_expval, 8))}") print( f"Relative error in estimation: {np.real(np.round((final_expval-exact_expval) / exact_expval, 8))}" )
https://github.com/Qiskit-Extensions/circuit-knitting-toolbox
Qiskit-Extensions
from qiskit.circuit.library import EfficientSU2 circuit = EfficientSU2(num_qubits=4, entanglement="circular").decompose() circuit.assign_parameters([0.4] * len(circuit.parameters), inplace=True) circuit.draw("mpl", scale=0.8) from qiskit.quantum_info import SparsePauliOp observable = SparsePauliOp(["ZZII", "IZZI", "-IIZZ", "XIXI", "ZIZZ", "IXIX"]) from qiskit_ibm_runtime.fake_provider import FakeManilaV2 backend = FakeManilaV2() from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager pass_manager = generate_preset_pass_manager( optimization_level=1, backend=backend, initial_layout=[0, 1, 2, 3] ) transpiled_qc = pass_manager.run(circuit) print(f"Transpiled circuit depth: {transpiled_qc.depth(lambda x: len(x[1]) >= 2)}") transpiled_qc.draw("mpl", scale=0.4, idle_wires=False, fold=-1) from circuit_knitting.cutting import cut_gates # Find the indices of the distant gates cut_indices = [ i for i, instruction in enumerate(circuit.data) if {circuit.find_bit(q)[0] for q in instruction.qubits} == {0, 3} ] # Decompose distant CNOTs into TwoQubitQPDGate instances qpd_circuit, bases = cut_gates(circuit, cut_indices) qpd_circuit.draw("mpl", scale=0.8) import numpy as np from circuit_knitting.cutting import generate_cutting_experiments # Generate the subexperiments and sampling coefficients subexperiments, coefficients = generate_cutting_experiments( circuits=qpd_circuit, observables=observable.paulis, num_samples=np.inf ) print(f"Sampling overhead: {np.prod([basis.overhead for basis in bases])}") # Transpile the decomposed circuit to the same layout transpiled_qpd_circuit = pass_manager.run(subexperiments[100]) print( f"Original circuit depth after transpile: {transpiled_qc.depth(lambda x: len(x[1]) >= 2)}" ) print( f"QPD subexperiment depth after transpile: {transpiled_qpd_circuit.depth(lambda x: len(x[1]) >= 2)}" ) transpiled_qpd_circuit.draw("mpl", scale=0.8, idle_wires=False, fold=-1) from qiskit_ibm_runtime import SamplerV2 # Transpile the subeperiments to the backend's instruction set architecture (ISA) isa_subexperiments = pass_manager.run(subexperiments) # Set up the Qiskit Runtime Sampler primitive. For a fake backend, this will use a local simulator. sampler = SamplerV2(backend) # Submit the subexperiments job = sampler.run(isa_subexperiments) # Retrieve the results results = job.result() from circuit_knitting.cutting import reconstruct_expectation_values reconstructed_expvals = reconstruct_expectation_values( results, coefficients, observable.paulis, ) # Reconstruct final expectation value final_expval = np.dot(reconstructed_expvals, observable.coeffs) from qiskit_aer.primitives import EstimatorV2 estimator = EstimatorV2() exact_expval = estimator.run([(circuit, observable)]).result()[0].data.evs print(f"Reconstructed expectation value: {np.real(np.round(final_expval, 8))}") print(f"Exact expectation value: {np.round(exact_expval, 8)}") print(f"Error in estimation: {np.real(np.round(final_expval-exact_expval, 8))}") print( f"Relative error in estimation: {np.real(np.round((final_expval-exact_expval) / exact_expval, 8))}" )
https://github.com/Qiskit-Extensions/circuit-knitting-toolbox
Qiskit-Extensions
import numpy as np from qiskit import QuantumCircuit qc_0 = QuantumCircuit(7) for i in range(7): qc_0.rx(np.pi / 4, i) qc_0.cx(0, 3) qc_0.cx(1, 3) qc_0.cx(2, 3) qc_0.cx(3, 4) qc_0.cx(3, 5) qc_0.cx(3, 6) qc_0.cx(0, 3) qc_0.cx(1, 3) qc_0.cx(2, 3) qc_0.draw("mpl") from qiskit.quantum_info import SparsePauliOp observable = SparsePauliOp(["ZIIIIII", "IIIZIII", "IIIIIIZ"]) from circuit_knitting.cutting.instructions import Move qc_1 = QuantumCircuit(8) for i in [*range(4), *range(5, 8)]: qc_1.rx(np.pi / 4, i) qc_1.cx(0, 3) qc_1.cx(1, 3) qc_1.cx(2, 3) qc_1.append(Move(), [3, 4]) qc_1.cx(4, 5) qc_1.cx(4, 6) qc_1.cx(4, 7) qc_1.append(Move(), [4, 3]) qc_1.cx(0, 3) qc_1.cx(1, 3) qc_1.cx(2, 3) qc_1.draw("mpl") observable_expanded = SparsePauliOp(["ZIIIIIII", "IIIIZIII", "IIIIIIIZ"]) from circuit_knitting.cutting import partition_problem partitioned_problem = partition_problem( circuit=qc_1, partition_labels="AAAABBBB", observables=observable_expanded.paulis ) subcircuits = partitioned_problem.subcircuits subobservables = partitioned_problem.subobservables bases = partitioned_problem.bases subobservables subcircuits["A"].draw("mpl") subcircuits["B"].draw("mpl") print(f"Sampling overhead: {np.prod([basis.overhead for basis in bases])}") from circuit_knitting.cutting import generate_cutting_experiments subexperiments, coefficients = generate_cutting_experiments( circuits=subcircuits, observables=subobservables, num_samples=np.inf ) from qiskit_ibm_runtime.fake_provider import FakeManilaV2 backend = FakeManilaV2() from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager # Transpile the subexperiments to ISA circuits pass_manager = generate_preset_pass_manager(optimization_level=1, backend=backend) isa_subexperiments = { label: pass_manager.run(partition_subexpts) for label, partition_subexpts in subexperiments.items() } from qiskit_ibm_runtime import SamplerV2, Batch # Submit each partition's subexperiments to the Qiskit Runtime Sampler # primitive, in a single batch so that the jobs will run back-to-back. with Batch(backend=backend) as batch: sampler = SamplerV2(mode=batch) jobs = { label: sampler.run(subsystem_subexpts, shots=2**12) for label, subsystem_subexpts in isa_subexperiments.items() } # Retrieve results results = {label: job.result() for label, job in jobs.items()} from circuit_knitting.cutting import reconstruct_expectation_values reconstructed_expvals = reconstruct_expectation_values( results, coefficients, subobservables, ) final_expval = np.dot(reconstructed_expvals, observable.coeffs) from qiskit_aer.primitives import EstimatorV2 estimator = EstimatorV2() exact_expval = estimator.run([(qc_0, observable)]).result()[0].data.evs print(f"Reconstructed expectation value: {np.real(np.round(final_expval, 8))}") print(f"Exact expectation value: {np.round(exact_expval, 8)}") print(f"Error in estimation: {np.real(np.round(final_expval-exact_expval, 8))}") print( f"Relative error in estimation: {np.real(np.round((final_expval-exact_expval) / exact_expval, 8))}" )
https://github.com/Qiskit-Extensions/circuit-knitting-toolbox
Qiskit-Extensions
import numpy as np from qiskit.circuit.random import random_circuit from qiskit.quantum_info import SparsePauliOp circuit = random_circuit(7, 6, max_operands=2, seed=1242) observable = SparsePauliOp(["ZIIIIII", "IIIZIII", "IIIIIIZ"]) circuit.draw("mpl", scale=0.8) from circuit_knitting.cutting.automated_cut_finding import ( find_cuts, OptimizationParameters, DeviceConstraints, ) # Specify settings for the cut-finding optimizer optimization_settings = OptimizationParameters(seed=111) # Specify the size of the QPUs available device_constraints = DeviceConstraints(qubits_per_subcircuit=4) cut_circuit, metadata = find_cuts(circuit, optimization_settings, device_constraints) print( f'Found solution using {len(metadata["cuts"])} cuts with a sampling ' f'overhead of {metadata["sampling_overhead"]}.\n' f'Lowest cost solution found: {metadata["minimum_reached"]}.' ) for cut in metadata["cuts"]: print(f"{cut[0]} at circuit instruction index {cut[1]}") cut_circuit.draw("mpl", scale=0.8, fold=-1) from circuit_knitting.cutting import cut_wires, expand_observables qc_w_ancilla = cut_wires(cut_circuit) observables_expanded = expand_observables(observable.paulis, circuit, qc_w_ancilla) qc_w_ancilla.draw("mpl", scale=0.8, fold=-1) from circuit_knitting.cutting import partition_problem partitioned_problem = partition_problem( circuit=qc_w_ancilla, observables=observables_expanded ) subcircuits = partitioned_problem.subcircuits subobservables = partitioned_problem.subobservables print( f"Sampling overhead: {np.prod([basis.overhead for basis in partitioned_problem.bases])}" ) subobservables subcircuits[0].draw("mpl", style="iqp", scale=0.8) subcircuits[1].draw("mpl", style="iqp", scale=0.8) from circuit_knitting.cutting import generate_cutting_experiments subexperiments, coefficients = generate_cutting_experiments( circuits=subcircuits, observables=subobservables, num_samples=1_000 ) print( f"{len(subexperiments[0]) + len(subexperiments[1])} total subexperiments to run on backend." )
https://github.com/Qiskit-Extensions/circuit-knitting-toolbox
Qiskit-Extensions
# This code is a Qiskit project. # (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. """Tests for cutting_decomposition module.""" import unittest import pytest import numpy as np from qiskit import QuantumCircuit from qiskit.circuit import CircuitInstruction, Barrier, Clbit from qiskit.circuit.library import EfficientSU2, RXXGate from qiskit.circuit.library.standard_gates import CXGate from qiskit.quantum_info import PauliList from circuit_knitting.cutting import ( partition_circuit_qubits, partition_problem, cut_gates, ) from circuit_knitting.cutting.instructions import Move from circuit_knitting.cutting.qpd import ( QPDBasis, TwoQubitQPDGate, BaseQPDGate, ) class TestCuttingDecomposition(unittest.TestCase): def setUp(self): # Use HWEA for simplicity and easy visualization circuit = EfficientSU2(4, entanglement="linear", reps=2).decompose() qpd_circuit = EfficientSU2(4, entanglement="linear", reps=2).decompose() # We will instantiate 2 QPDBasis objects using from_instruction rxx_gate = RXXGate(np.pi / 3) rxx_decomp = QPDBasis.from_instruction(rxx_gate) # Create two QPDGates and specify each of their bases # Labels are only used for visualizations qpd_gate1 = TwoQubitQPDGate(rxx_decomp, label=f"cut_{rxx_gate.name}") qpd_gate2 = TwoQubitQPDGate(rxx_decomp, label=f"cut_{rxx_gate.name}") qpd_gate1.basis_id = 0 qpd_gate2.basis_id = 0 # Create the circuit instructions qpd_inst1 = CircuitInstruction(qpd_gate1, qubits=[1, 2]) qpd_inst2 = CircuitInstruction(qpd_gate2, qubits=[1, 2]) inst1 = CircuitInstruction(rxx_gate, qubits=[1, 2]) inst2 = CircuitInstruction(rxx_gate, qubits=[1, 2]) # Hard-coded overwrite of the two CNOTS with our decomposed RXX gates qpd_circuit.data[9] = qpd_inst1 qpd_circuit.data[20] = qpd_inst2 circuit.data[9] = inst1 circuit.data[20] = inst2 self.qpd_circuit = qpd_circuit self.circuit = circuit def test_partition_circuit_qubits(self): with self.subTest("Empty circuit"): compare_circuit = QuantumCircuit() partitioned_circuit = partition_circuit_qubits(compare_circuit, []) self.assertEqual(partitioned_circuit, compare_circuit) with self.subTest("Circuit with parameters"): # Split 4q HWEA in middle of qubits partition_labels = [0, 0, 1, 1] # Get a QPD circuit based on partitions, and set the basis for each gate # to match the basis_ids of self.qpd_circuit's QPDGates circuit = partition_circuit_qubits(self.circuit, partition_labels) for inst in circuit.data: if isinstance(inst.operation, TwoQubitQPDGate): inst.operation.basis_id = 0 # Terra doesn't consider params with same name to be equivalent, so # we need to copy the comparison circuit and bind parameters to test # equivalence. compare_circuit = self.qpd_circuit.copy() compare_qpd_circuit = partition_circuit_qubits( compare_circuit, partition_labels ) parameter_vals = [np.pi / 4] * len(circuit.parameters) circuit.assign_parameters(parameter_vals, inplace=True) compare_qpd_circuit.assign_parameters(parameter_vals, inplace=True) self.assertEqual(circuit, compare_qpd_circuit) with self.subTest("Circuit with barriers"): # Split 4q HWEA in middle of qubits partition_labels = [0, 0, 1, 1] bar1 = CircuitInstruction(Barrier(4), qubits=[0, 1, 2, 3]) bar2 = CircuitInstruction(Barrier(4), qubits=[0, 1, 2, 3]) bar_circuit = self.circuit.copy() bar_circuit.data.insert(10, bar1) bar_circuit.data.insert(22, bar2) # Get a QPD circuit based on partitions, and set the basis for each gate # to match the basis_ids of self.qpd_circuit's QPDGates circuit = partition_circuit_qubits(bar_circuit, partition_labels) for inst in circuit.data: if isinstance(inst.operation, TwoQubitQPDGate): inst.operation.basis_id = 0 # Terra doesn't consider params with same name to be equivalent, so # we need to copy the comparison circuit and bind parameters to test # equivalence. compare_circuit = self.qpd_circuit.copy() compare_qpd_circuit = partition_circuit_qubits( compare_circuit, partition_labels ) bar1 = CircuitInstruction(Barrier(4), qubits=[0, 1, 2, 3]) bar2 = CircuitInstruction(Barrier(4), qubits=[0, 1, 2, 3]) compare_qpd_circuit.data.insert(10, bar1) compare_qpd_circuit.data.insert(22, bar2) parameter_vals = [np.pi / 4] * len(circuit.parameters) circuit.assign_parameters(parameter_vals, inplace=True) compare_qpd_circuit.assign_parameters(parameter_vals, inplace=True) self.assertEqual(circuit, compare_qpd_circuit) with self.subTest("Partition IDs the wrong size"): compare_circuit = QuantumCircuit() with pytest.raises(ValueError) as e_info: partition_circuit_qubits(compare_circuit, [0]) assert ( e_info.value.args[0] == "Length of partition_labels (1) does not equal the number of qubits in the input circuit (0)." ) with self.subTest("Unsupported gate"): compare_circuit = QuantumCircuit(3) compare_circuit.ccx(0, 1, 2) partitions = [0, 1, 1] with pytest.raises(ValueError) as e_info: partition_circuit_qubits(compare_circuit, partitions) assert ( e_info.value.args[0] == "Decomposition is only supported for two-qubit gates. Cannot decompose (ccx)." ) with self.subTest("Toffoli gate in a single partition"): circuit = QuantumCircuit(4) circuit.ccx(0, 1, 2) circuit.rzz(np.pi / 7, 2, 3) partition_circuit_qubits(circuit, "AAAB") def test_partition_problem(self): with self.subTest("simple circuit and observable"): # Split 4q HWEA in middle of qubits partition_labels = "AABB" observable = PauliList(["ZZXX"]) subcircuits, _, subobservables = partition_problem( self.circuit, partition_labels, observables=observable ) for subcircuit in subcircuits.values(): parameter_vals = [np.pi / 4] * len(subcircuit.parameters) subcircuit.assign_parameters(parameter_vals, inplace=True) for inst in subcircuit.data: if isinstance(inst.operation, BaseQPDGate): inst.operation.basis_id = 0 compare_obs = {"A": PauliList(["XX"]), "B": PauliList(["ZZ"])} self.assertEqual(subobservables, compare_obs) with self.subTest("test mismatching inputs"): # Split 4q HWEA in middle of qubits partition_labels = "AB" with pytest.raises(ValueError) as e_info: subcircuits, _, subobservables = partition_problem( self.circuit, partition_labels ) assert ( e_info.value.args[0] == "The number of partition labels (2) must equal the number of qubits in the circuit (4)." ) partition_labels = "AABB" observable = PauliList(["ZZ"]) with pytest.raises(ValueError) as e_info: subcircuits, _, subobservables = partition_problem( self.circuit, partition_labels, observable ) assert ( e_info.value.args[0] == "An input observable acts on a different number of qubits than the input circuit." ) with self.subTest("Classical bit on input"): # Split 4q HWEA in middle of qubits partition_labels = "AABB" observable = PauliList(["ZZXX"]) # Add a clbit circuit = self.circuit.copy() circuit.add_bits([Clbit()]) with pytest.raises(ValueError) as e_info: partition_problem(circuit, partition_labels, observables=observable) assert ( e_info.value.args[0] == "Circuits input to partition_problem should contain no classical registers or bits." ) with self.subTest("Unsupported phase"): # Split 4q HWEA in middle of qubits partition_labels = "AABB" observable = PauliList(["-ZZXX"]) with pytest.raises(ValueError) as e_info: partition_problem( self.circuit, partition_labels, observables=observable ) assert ( e_info.value.args[0] == "An input observable has a phase not equal to 1." ) with self.subTest("Unlabeled TwoQubitQPDGates (smoke test)"): qc = QuantumCircuit(4) qc.rx(np.pi / 4, 0) qc.rx(np.pi / 4, 1) qc.rx(np.pi / 4, 3) qc.cx(0, 1) qc.append(TwoQubitQPDGate(QPDBasis.from_instruction(Move())), [1, 2]) qc.cx(2, 3) qc.append(TwoQubitQPDGate(QPDBasis.from_instruction(Move())), [2, 1]) qc.cx(0, 1) subcircuits, bases, subobservables = partition_problem( qc, "AABB", observables=PauliList(["IZIZ"]) ) assert len(subcircuits) == len(bases) == len(subobservables) == 2 with self.subTest("Automatic partition_labels"): qc = QuantumCircuit(4) qc.h(0) qc.cx(0, 2) qc.cx(0, 1) qc.s(3) # Add a TwoQubitQPDGate that, when cut, allows the circuit to # separate qc.append(TwoQubitQPDGate.from_instruction(CXGate()), [1, 3]) # Add a TwoQubitQPDGate that, when cut, does *not* allow the # circuit to separate qc.append(TwoQubitQPDGate.from_instruction(CXGate()), [2, 0]) subcircuit, *_ = partition_problem(qc) assert subcircuit.keys() == {0, 1} assert subcircuit[0].num_qubits == 3 assert subcircuit[1].num_qubits == 1 def test_cut_gates(self): with self.subTest("simple circuit"): compare_qc = QuantumCircuit(2) compare_qc.append(TwoQubitQPDGate.from_instruction(CXGate()), [0, 1]) qc = QuantumCircuit(2) qc.cx(0, 1) qpd_qc, _ = cut_gates(qc, [0]) self.assertEqual(qpd_qc, compare_qc) with self.subTest("classical bit on input"): qc = QuantumCircuit(2, 1) qc.cx(0, 1) with pytest.raises(ValueError) as e_info: cut_gates(qc, [0]) assert ( e_info.value.args[0] == "Circuits input to cut_gates should contain no classical registers or bits." ) def test_unused_qubits(self): """Issue #218""" qc = QuantumCircuit(2) subcircuits, _, subobservables = partition_problem( circuit=qc, partition_labels="AB", observables=PauliList(["XX"]) ) assert subcircuits.keys() == {"A", "B"} assert subobservables.keys() == {"A", "B"}
https://github.com/Qiskit-Extensions/circuit-knitting-toolbox
Qiskit-Extensions
# This code is a Qiskit project. # (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. from __future__ import annotations import pytest import logging import numpy as np from qiskit import QuantumCircuit from qiskit.circuit.library import UnitaryGate from qiskit.circuit.library.standard_gates import ( RXXGate, RYYGate, RZZGate, RZXGate, XXPlusYYGate, XXMinusYYGate, CHGate, CXGate, CYGate, CZGate, CSGate, CSdgGate, CSXGate, CRXGate, CRYGate, CRZGate, CPhaseGate, ECRGate, SwapGate, iSwapGate, DCXGate, ) from qiskit.quantum_info import PauliList, random_unitary from qiskit.primitives import Estimator from qiskit_ibm_runtime import SamplerV2 from qiskit_aer import AerSimulator from qiskit_aer.primitives import Sampler from circuit_knitting.utils.simulation import ExactSampler from circuit_knitting.cutting import ( partition_problem, generate_cutting_experiments, reconstruct_expectation_values, ) from circuit_knitting.cutting.instructions import Move logger = logging.getLogger(__name__) def append_random_unitary(circuit: QuantumCircuit, qubits): circuit.unitary(random_unitary(2 ** len(qubits)), qubits) @pytest.fixture( params=[ [SwapGate()], [iSwapGate()], [DCXGate()], [CXGate()], [CYGate()], [CZGate()], [CHGate()], [ECRGate()], [CSXGate()], [CSXGate().inverse()], [CSGate()], [CSdgGate()], [RYYGate(0.0)], [RZZGate(np.pi)], [RXXGate(np.pi / 3)], [RYYGate(np.pi / 7)], [RZZGate(np.pi / 11)], [CRXGate(0.0)], [CRYGate(np.pi)], [CRZGate(np.pi / 2)], [CRXGate(np.pi / 3)], [CRYGate(np.pi / 7)], [CRZGate(np.pi / 11)], [RXXGate(np.pi / 3), CRYGate(np.pi / 7)], [CPhaseGate(np.pi / 3)], [RXXGate(np.pi / 3), CPhaseGate(np.pi / 7)], [UnitaryGate(random_unitary(2**2))], [RZXGate(np.pi / 5)], # XXPlusYYGate, XXMinusYYGate, with some combinations: # beta == 0 or not; and # within |theta| < pi or not [XXPlusYYGate(7 * np.pi / 11)], [XXPlusYYGate(17 * np.pi / 11, beta=0.4)], [XXPlusYYGate(-19 * np.pi / 11, beta=0.3)], [XXMinusYYGate(11 * np.pi / 17)], [Move()], [Move(), Move()], ] ) def example_circuit(request) -> QuantumCircuit: """Fixture for an example circuit. Except for the parametrized gates, the system can be separated according to the partition labels "AAB". """ qc = QuantumCircuit(3) cut_indices = [] for instruction in request.param: if instruction.name == "move" and len(cut_indices) % 2 == 1: # We should not entangle qubit 1 with the remainder of the system. # In fact, we're also assuming that the previous operation here was # a move. append_random_unitary(qc, [0]) append_random_unitary(qc, [1]) else: append_random_unitary(qc, [0, 1]) append_random_unitary(qc, [2]) cut_indices.append(len(qc.data)) qubits = [1, 2] if len(cut_indices) % 2 == 0: qubits.reverse() qc.append(instruction, qubits) qc.barrier() append_random_unitary(qc, [0, 1]) qc.barrier() append_random_unitary(qc, [2]) return qc def test_cutting_exact_reconstruction(example_circuit): """Test gate-cut circuit vs original circuit on statevector simulator""" qc = example_circuit observables = PauliList(["III", "IIY", "XII", "XYZ", "iZZZ", "-XZI"]) phases = np.array([(-1j) ** obs.phase for obs in observables]) observables_nophase = PauliList(["III", "IIY", "XII", "XYZ", "ZZZ", "XZI"]) estimator = Estimator() exact_expvals = ( estimator.run([qc] * len(observables), list(observables)).result().values ) subcircuits, bases, subobservables = partition_problem( qc, "AAB", observables=observables_nophase ) subexperiments, coefficients = generate_cutting_experiments( subcircuits, subobservables, num_samples=np.inf ) if np.random.randint(2): # Re-use a single sampler sampler = ExactSampler() samplers = {label: sampler for label in subcircuits.keys()} else: # One sampler per partition samplers = {label: ExactSampler() for label in subcircuits.keys()} results = { label: sampler.run(subexperiments[label]).result() for label, sampler in samplers.items() } reconstructed_expvals = reconstruct_expectation_values( results, coefficients, subobservables ) reconstructed_expvals *= phases logger.info("Max error: %f", np.max(np.abs(exact_expvals - reconstructed_expvals))) assert np.allclose(exact_expvals, reconstructed_expvals, atol=1e-8) @pytest.mark.parametrize( "sampler,is_exact_sampler", [(Sampler(), False), (SamplerV2(AerSimulator()), False), (ExactSampler(), True)], ) def test_sampler_with_identity_subobservable(sampler, is_exact_sampler): """This test ensures that the sampler works for a subcircuit with no observable measurements. Specifically, that - ``Sampler`` does not blow up (Issue #422); and - ``ExactSampler`` returns correct results This is related to https://github.com/Qiskit-Extensions/circuit-knitting-toolbox/issues/422. """ # Create a circuit to cut qc = QuantumCircuit(3) append_random_unitary(qc, [0, 1]) append_random_unitary(qc, [2]) qc.rxx(np.pi / 3, 1, 2) append_random_unitary(qc, [0, 1]) append_random_unitary(qc, [2]) # Determine expectation value using cutting observables = PauliList( ["IIZ"] ) # Without the workaround to Issue #422, this observable causes a Sampler error. subcircuits, bases, subobservables = partition_problem( qc, "AAB", observables=observables ) subexperiments, coefficients = generate_cutting_experiments( subcircuits, subobservables, num_samples=np.inf ) samplers = {label: sampler for label in subexperiments.keys()} results = { label: sampler.run(subexperiments[label]).result() for label, sampler in samplers.items() } reconstructed_expvals = reconstruct_expectation_values( results, coefficients, subobservables ) if is_exact_sampler: # Determine exact expectation values estimator = Estimator() exact_expvals = ( estimator.run([qc] * len(observables), list(observables)).result().values ) logger.info( "Max error: %f", np.max(np.abs(exact_expvals - reconstructed_expvals)) ) # Ensure both methods yielded equivalent expectation values assert np.allclose(exact_expvals, reconstructed_expvals, atol=1e-8)
https://github.com/Qiskit-Extensions/circuit-knitting-toolbox
Qiskit-Extensions
# This code is a Qiskit project. # (C) Copyright IBM 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. """Tests for find_cuts module.""" import unittest import pytest import os import numpy as np from qiskit import QuantumCircuit from qiskit.circuit.library import EfficientSU2 from circuit_knitting.cutting.automated_cut_finding import ( find_cuts, OptimizationParameters, DeviceConstraints, ) class TestCuttingDecomposition(unittest.TestCase): def test_find_cuts(self): with self.subTest("simple circuit"): path_to_circuit = os.path.join( os.path.dirname(__file__), "..", "qasm_circuits", "circuit_find_cuts_test.qasm", ) circuit = QuantumCircuit.from_qasm_file(path_to_circuit) optimization = OptimizationParameters(seed=111) constraints = DeviceConstraints(qubits_per_subcircuit=4) _, metadata = find_cuts( circuit, optimization=optimization, constraints=constraints ) cut_types = {cut[0] for cut in metadata["cuts"]} assert len(metadata["cuts"]) == 2 assert {"Wire Cut", "Gate Cut"} == cut_types assert np.isclose(127.06026169, metadata["sampling_overhead"], atol=1e-8) assert metadata["minimum_reached"] is True with self.subTest("Cut both wires instance"): qc = EfficientSU2(4, entanglement="linear", reps=2).decompose() qc.assign_parameters([0.4] * len(qc.parameters), inplace=True) optimization = OptimizationParameters( seed=12345, gate_lo=False, wire_lo=True ) constraints = DeviceConstraints(qubits_per_subcircuit=2) _, metadata = find_cuts( qc, optimization=optimization, constraints=constraints ) cut_types = {cut[0] for cut in metadata["cuts"]} assert len(metadata["cuts"]) == 8 assert {"Wire Cut"} == cut_types assert np.isclose(65536.0**2, metadata["sampling_overhead"], atol=1e-8) with self.subTest("3-qubit gate"): circuit = QuantumCircuit(3) circuit.cswap(2, 1, 0) circuit.crx(3.57, 1, 0) circuit.z(2) with pytest.raises(ValueError) as e_info: _, metadata = find_cuts( circuit, optimization=optimization, constraints=constraints ) assert e_info.value.args[0] == ( "The input circuit must contain only single and two-qubits gates. " "Found 3-qubit gate: (cswap)." ) with self.subTest( "right-wire-cut" ): # tests resolution of https://github.com/Qiskit-Extensions/circuit-knitting-toolbox/issues/508 circuit = QuantumCircuit(5) circuit.cx(0, 3) circuit.cx(1, 3) circuit.cx(2, 3) circuit.h(4) circuit.cx(3, 4) constraints = DeviceConstraints(qubits_per_subcircuit=3) _, metadata = find_cuts( circuit, optimization=optimization, constraints=constraints ) cut_types = {cut[0] for cut in metadata["cuts"]} assert len(metadata["cuts"]) == 1 assert {"Wire Cut"} == cut_types assert metadata["sampling_overhead"] == 16 @pytest.mark.parametrize("qubits_per_subcircuit", [-1, 0]) def test_device_constraints(qubits_per_subcircuit: int): """Test device constraints for being valid data types.""" with pytest.raises(ValueError): _ = DeviceConstraints(qubits_per_subcircuit) @pytest.mark.parametrize("qubits_per_subcircuit", [2, 1]) def test_get_qpu_width(qubits_per_subcircuit: int): """Test that get_qpu_width returns number of qubits per qpu.""" assert ( DeviceConstraints(qubits_per_subcircuit).get_qpu_width() == qubits_per_subcircuit )
https://github.com/Qiskit-Extensions/circuit-knitting-toolbox
Qiskit-Extensions
# This code is a Qiskit project. # (C) Copyright IBM 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. """Tests for cco_utils module.""" from __future__ import annotations from typing import Callable import pytest from pytest import fixture from qiskit.circuit.library import EfficientSU2 from qiskit import QuantumCircuit, QuantumRegister from qiskit.circuit import Qubit, Instruction, CircuitInstruction from circuit_knitting.cutting.cut_finding.cco_utils import ( qc_to_cco_circuit, cco_to_qc_circuit, ) from circuit_knitting.cutting.cut_finding.circuit_interface import ( SimpleGateList, CircuitElement, ) def create_test_circuit_1(): tc_1 = QuantumCircuit(2) tc_1.h(1) tc_1.barrier(1) tc_1.s(0) tc_1.barrier() tc_1.cx(1, 0) return tc_1 def create_test_circuit_2(): tc_2 = EfficientSU2(2, entanglement="linear", reps=2).decompose() tc_2.assign_parameters([0.4] * len(tc_2.parameters), inplace=True) return tc_2 # test circuit 3 @fixture def internal_test_circuit(): circuit = [ CircuitElement(name="cx", params=[], qubits=[0, 1], gamma=3), CircuitElement(name="cx", params=[], qubits=[2, 3], gamma=3), CircuitElement(name="cx", params=[], qubits=[1, 2], gamma=3), CircuitElement(name="cx", params=[], qubits=[0, 1], gamma=3), CircuitElement(name="cx", params=[], qubits=[2, 3], gamma=3), CircuitElement(name="h", params=[], qubits=[0], gamma=None), CircuitElement(name="rx", params=[0.4], qubits=[0], gamma=None), ] interface = SimpleGateList(circuit) interface.insert_gate_cut(2, "LO") interface.define_subcircuits([[0, 1], [2, 3]]) return interface @pytest.mark.parametrize( "create_test_circuit, known_output", [ ( create_test_circuit_1, [ CircuitElement("h", [], [1], None), CircuitElement("barrier", [], [1], None), CircuitElement("s", [], [0], None), "barrier", CircuitElement("cx", [], [1, 0], 3), ], ), ( create_test_circuit_2, [ CircuitElement("ry", [0.4], [0], None), CircuitElement("rz", [0.4], [0], None), CircuitElement("ry", [0.4], [1], None), CircuitElement("rz", [0.4], [1], None), CircuitElement("cx", [], [0, 1], 3), CircuitElement("ry", [0.4], [0], None), CircuitElement("rz", [0.4], [0], None), CircuitElement("ry", [0.4], [1], None), CircuitElement("rz", [0.4], [1], None), CircuitElement("cx", [], [0, 1], 3), CircuitElement("ry", [0.4], [0], None), CircuitElement("rz", [0.4], [0], None), CircuitElement("ry", [0.4], [1], None), CircuitElement("rz", [0.4], [1], None), ], ), ], ) def test_qc_to_cco_circuit( create_test_circuit: Callable[[], QuantumCircuit], known_output: list[CircuitElement, str], ): test_circuit = create_test_circuit() test_circuit_internal = qc_to_cco_circuit(test_circuit) assert test_circuit_internal == known_output def test_cco_to_qc_circuit(internal_test_circuit: SimpleGateList): qc_cut = cco_to_qc_circuit(internal_test_circuit) assert qc_cut.data == [ CircuitInstruction( operation=Instruction(name="cx", num_qubits=2, num_clbits=0, params=[]), qubits=( Qubit(QuantumRegister(4, "q"), 0), Qubit(QuantumRegister(4, "q"), 1), ), clbits=(), ), CircuitInstruction( operation=Instruction(name="cx", num_qubits=2, num_clbits=0, params=[]), qubits=( Qubit(QuantumRegister(4, "q"), 2), Qubit(QuantumRegister(4, "q"), 3), ), clbits=(), ), CircuitInstruction( operation=Instruction(name="cx", num_qubits=2, num_clbits=0, params=[]), qubits=( Qubit(QuantumRegister(4, "q"), 0), Qubit(QuantumRegister(4, "q"), 1), ), clbits=(), ), CircuitInstruction( operation=Instruction(name="cx", num_qubits=2, num_clbits=0, params=[]), qubits=( Qubit(QuantumRegister(4, "q"), 2), Qubit(QuantumRegister(4, "q"), 3), ), clbits=(), ), CircuitInstruction( operation=Instruction(name="h", num_qubits=1, num_clbits=0, params=[]), qubits=(Qubit(QuantumRegister(4, "q"), 0),), clbits=(), ), CircuitInstruction( operation=Instruction(name="rx", num_qubits=1, num_clbits=0, params=[0.4]), qubits=(Qubit(QuantumRegister(4, "q"), 0),), clbits=(), ), ]
https://github.com/Qiskit-Extensions/circuit-knitting-toolbox
Qiskit-Extensions
# This code is a Qiskit project. # (C) Copyright IBM 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. """End to end tests for the cut finder workflow.""" from __future__ import annotations import numpy as np import unittest from pytest import raises from qiskit import QuantumCircuit from qiskit.circuit.library import EfficientSU2 from circuit_knitting.cutting.cut_finding.cco_utils import qc_to_cco_circuit from circuit_knitting.cutting.cut_finding.circuit_interface import ( SimpleGateList, ) from circuit_knitting.cutting.cut_finding.optimization_settings import ( OptimizationSettings, ) from circuit_knitting.cutting.automated_cut_finding import DeviceConstraints from circuit_knitting.cutting.cut_finding.disjoint_subcircuits_state import ( get_actions_list, SingleWireCutIdentifier, WireCutLocation, CutIdentifier, CutLocation, ) from circuit_knitting.cutting.cut_finding.lo_cuts_optimizer import ( LOCutsOptimizer, ) from circuit_knitting.cutting.cut_finding.cut_optimization import CutOptimization class TestCuttingFourQubitCircuit(unittest.TestCase): def setUp(self): qc = EfficientSU2(4, entanglement="linear", reps=2).decompose() qc.assign_parameters([0.4] * len(qc.parameters), inplace=True) self.circuit_internal = qc_to_cco_circuit(qc) def test_four_qubit_cutting_workflow(self): with self.subTest("No cuts needed"): qubits_per_subcircuit = 4 interface = SimpleGateList(self.circuit_internal) settings = OptimizationSettings(seed=12345, gate_lo=True, wire_lo=True) settings.set_engine_selection("CutOptimization", "BestFirst") constraint_obj = DeviceConstraints(qubits_per_subcircuit) optimization_pass = LOCutsOptimizer(interface, settings, constraint_obj) output = optimization_pass.optimize(interface, settings, constraint_obj) assert get_actions_list(output.actions) == [] # no cutting. assert ( interface.export_subcircuits_as_string(name_mapping="default") == "AAAA" ) with self.subTest("No cuts found when all flags set to False"): qubits_per_subcircuit = 3 interface = SimpleGateList(self.circuit_internal) settings = OptimizationSettings(seed=12345, gate_lo=False, wire_lo=False) settings.set_engine_selection("CutOptimization", "BestFirst") constraint_obj = DeviceConstraints(qubits_per_subcircuit) optimization_pass = LOCutsOptimizer(interface, settings, constraint_obj) with raises(ValueError) as e_info: optimization_pass.optimize(interface, settings, constraint_obj) assert ( e_info.value.args[0] == "None state encountered: no cut state satisfying the specified constraints and settings could be found." ) with self.subTest( "No separating cuts possible if one qubit per qpu and only wire cuts allowed" ): settings = OptimizationSettings(seed=12345, gate_lo=False, wire_lo=True) settings.set_engine_selection("CutOptimization", "BestFirst") interface = SimpleGateList(self.circuit_internal) qubits_per_subcircuit = 1 constraint_obj = DeviceConstraints(qubits_per_subcircuit) optimization_pass = LOCutsOptimizer(interface, settings, constraint_obj) with raises(ValueError) as e_info: optimization_pass.optimize(interface, settings, constraint_obj) assert ( e_info.value.args[0] == "None state encountered: no cut state satisfying the specified constraints and settings could be found." ) with self.subTest("Gate cuts to get three qubits per subcircuit"): # QPU with 3 qubits for a 4 qubit circuit enforces cutting. qubits_per_subcircuit = 3 interface = SimpleGateList(self.circuit_internal) settings = OptimizationSettings(seed=12345, gate_lo=True, wire_lo=True) settings.set_engine_selection("CutOptimization", "BestFirst") constraint_obj = DeviceConstraints(qubits_per_subcircuit) optimization_pass = LOCutsOptimizer(interface, settings, constraint_obj) output = optimization_pass.optimize() cut_actions_list = output.cut_actions_sublist() assert cut_actions_list == [ CutIdentifier( cut_action="CutTwoQubitGate", cut_location=CutLocation( instruction_id=17, gate_name="cx", qubits=[2, 3] ), ), CutIdentifier( cut_action="CutTwoQubitGate", cut_location=CutLocation( instruction_id=25, gate_name="cx", qubits=[2, 3] ), ), ] best_result = optimization_pass.get_results() assert ( output.upper_bound_gamma() == best_result.gamma_UB == 9 ) # 2 LO cnot cuts. assert ( optimization_pass.minimum_reached() is True ) # matches optimal solution. assert ( interface.export_subcircuits_as_string(name_mapping="default") == "AAAB" ) # circuit separated into 2 subcircuits. with self.subTest("Gate cuts to get two qubits per subcircuit"): qubits_per_subcircuit = 2 interface = SimpleGateList(self.circuit_internal) settings = OptimizationSettings(seed=12345, gate_lo=True, wire_lo=True) settings.set_engine_selection("CutOptimization", "BestFirst") constraint_obj = DeviceConstraints(qubits_per_subcircuit) optimization_pass = LOCutsOptimizer(interface, settings, constraint_obj) output = optimization_pass.optimize() cut_actions_list = output.cut_actions_sublist() assert cut_actions_list == [ CutIdentifier( cut_action="CutTwoQubitGate", cut_location=CutLocation( instruction_id=9, gate_name="cx", qubits=[1, 2] ), ), CutIdentifier( cut_action="CutTwoQubitGate", cut_location=CutLocation( instruction_id=20, gate_name="cx", qubits=[1, 2] ), ), ] best_result = optimization_pass.get_results() assert ( output.upper_bound_gamma() == best_result.gamma_UB == 9 ) # 2 LO cnot cuts. assert optimization_pass.minimum_reached() is True # matches optimal solution. assert ( interface.export_subcircuits_as_string(name_mapping="default") == "AABB" ) # circuit separated into 2 subcircuits. assert ( optimization_pass.get_stats()["CutOptimization"].backjumps <= settings.max_backjumps ) with self.subTest("Cut both wires instance"): qubits_per_subcircuit = 2 interface = SimpleGateList(self.circuit_internal) settings = OptimizationSettings(seed=12345, gate_lo=False, wire_lo=True) settings.set_engine_selection("CutOptimization", "BestFirst") constraint_obj = DeviceConstraints(qubits_per_subcircuit) optimization_pass = LOCutsOptimizer(interface, settings, constraint_obj) output = optimization_pass.optimize() cut_actions_list = output.cut_actions_sublist() assert cut_actions_list == [ SingleWireCutIdentifier( cut_action="CutLeftWire", wire_cut_location=WireCutLocation( instruction_id=9, gate_name="cx", qubits=[1, 2], input=1 ), ), CutIdentifier( cut_action="CutBothWires", cut_location=CutLocation( instruction_id=12, gate_name="cx", qubits=[0, 1] ), ), SingleWireCutIdentifier( cut_action="CutLeftWire", wire_cut_location=WireCutLocation( instruction_id=17, gate_name="cx", qubits=[2, 3], input=1 ), ), CutIdentifier( cut_action="CutBothWires", cut_location=CutLocation( instruction_id=20, gate_name="cx", qubits=[1, 2] ), ), CutIdentifier( cut_action="CutBothWires", cut_location=CutLocation( instruction_id=25, gate_name="cx", qubits=[2, 3] ), ), ] best_result = optimization_pass.get_results() assert output.upper_bound_gamma() == best_result.gamma_UB == 65536 assert ( interface.export_subcircuits_as_string(name_mapping="default") == "ADABDEBCEFCF" ) with self.subTest("Wire cuts to get to 3 qubits per subcircuit"): qubits_per_subcircuit = 3 interface = SimpleGateList(self.circuit_internal) settings = OptimizationSettings(seed=12345, gate_lo=False, wire_lo=True) settings.set_engine_selection("CutOptimization", "BestFirst") constraint_obj = DeviceConstraints(qubits_per_subcircuit) optimization_pass = LOCutsOptimizer(interface, settings, constraint_obj) output = optimization_pass.optimize() cut_actions_list = output.cut_actions_sublist() assert cut_actions_list == [ SingleWireCutIdentifier( cut_action="CutLeftWire", wire_cut_location=WireCutLocation( instruction_id=17, gate_name="cx", qubits=[2, 3], input=1 ), ), SingleWireCutIdentifier( cut_action="CutLeftWire", wire_cut_location=WireCutLocation( instruction_id=20, gate_name="cx", qubits=[1, 2], input=1 ), ), ] best_result = optimization_pass.get_results() assert ( output.upper_bound_gamma() == best_result.gamma_UB == 16 ) # 2 LO wire cuts. assert ( interface.export_subcircuits_as_string(name_mapping="default") == "AABABB" ) # circuit separated into 2 subcircuits. with self.subTest("Search engine not supported"): # Check if unspported search engine is flagged qubits_per_subcircuit = 4 interface = SimpleGateList(self.circuit_internal) settings = OptimizationSettings(seed=12345, gate_lo=True, wire_lo=True) settings.set_engine_selection("CutOptimization", "BeamSearch") search_engine = settings.get_engine_selection("CutOptimization") constraint_obj = DeviceConstraints(qubits_per_subcircuit) optimization_pass = LOCutsOptimizer(interface, settings, constraint_obj) with raises(ValueError) as e_info: _ = optimization_pass.optimize() assert ( e_info.value.args[0] == f"Search engine {search_engine} is not supported." ) with self.subTest("Greedy search gate cut warm start test"): # Even if the input cost bounds are too stringent, greedy_cut_optimization # is able to return a solution. qubits_per_subcircuit = 3 interface = SimpleGateList(self.circuit_internal) settings = OptimizationSettings(seed=12345, gate_lo=True, wire_lo=False) settings.set_engine_selection("CutOptimization", "BestFirst") constraint_obj = DeviceConstraints(qubits_per_subcircuit) # Impose a stringent cost upper bound, insist gamma <=2. cut_opt = CutOptimization(interface, settings, constraint_obj) cut_opt.update_upperbound_cost((2, 4)) state, cost = cut_opt.optimization_pass() # 2 cnot cuts are still found assert state is not None assert cost[0] == 9 with self.subTest("Greedy search wire cut warm start test"): # Even if the input cost bounds are too stringent, greedy_cut_optimization # is able to return a solution. qubits_per_subcircuit = 3 interface = SimpleGateList(self.circuit_internal) settings = OptimizationSettings(seed=12345, gate_lo=False, wire_lo=True) settings.set_engine_selection("CutOptimization", "BestFirst") constraint_obj = DeviceConstraints(qubits_per_subcircuit) # Impose a stringent cost upper bound, insist gamma <=2. cut_opt = CutOptimization(interface, settings, constraint_obj) cut_opt.update_upperbound_cost((2, 4)) state, cost = cut_opt.optimization_pass() # 2 LO wire cuts are still found assert state is not None assert cost[0] == 16 class TestCuttingSevenQubitCircuit(unittest.TestCase): def setUp(self): qc = QuantumCircuit(7) for i in range(7): qc.rx(np.pi / 4, i) qc.cx(0, 3) qc.cx(1, 3) qc.cx(2, 3) qc.cx(3, 4) qc.cx(3, 5) qc.cx(3, 6) self.circuit_internal = qc_to_cco_circuit(qc) def test_seven_qubit_workflow(self): with self.subTest("Two qubits per subcircuit"): qubits_per_subcircuit = 2 interface = SimpleGateList(self.circuit_internal) settings = OptimizationSettings(seed=12345, gate_lo=True, wire_lo=True) settings.set_engine_selection("CutOptimization", "BestFirst") constraint_obj = DeviceConstraints(qubits_per_subcircuit) optimization_pass = LOCutsOptimizer(interface, settings, constraint_obj) output = optimization_pass.optimize() cut_actions_list = output.cut_actions_sublist() assert cut_actions_list == [ CutIdentifier( cut_action="CutTwoQubitGate", cut_location=CutLocation( instruction_id=7, gate_name="cx", qubits=[0, 3] ), ), CutIdentifier( cut_action="CutTwoQubitGate", cut_location=CutLocation( instruction_id=8, gate_name="cx", qubits=[1, 3] ), ), CutIdentifier( cut_action="CutTwoQubitGate", cut_location=CutLocation( instruction_id=9, gate_name="cx", qubits=[2, 3] ), ), CutIdentifier( cut_action="CutTwoQubitGate", cut_location=CutLocation( instruction_id=11, gate_name="cx", qubits=[3, 5] ), ), CutIdentifier( cut_action="CutTwoQubitGate", cut_location=CutLocation( instruction_id=12, gate_name="cx", qubits=[3, 6] ), ), ] best_result = optimization_pass.get_results() assert ( output.upper_bound_gamma() == best_result.gamma_UB == 243 ) # 5 LO cnot cuts. assert ( optimization_pass.minimum_reached() is True ) # matches optimal solution. assert ( interface.export_subcircuits_as_string(name_mapping="default") == "ABCDDEF" ) # circuit separated into 2 subcircuits. with self.subTest("Single wire cut"): qubits_per_subcircuit = 4 interface = SimpleGateList(self.circuit_internal) settings = OptimizationSettings(seed=12345, gate_lo=True, wire_lo=True) settings.set_engine_selection("CutOptimization", "BestFirst") constraint_obj = DeviceConstraints(qubits_per_subcircuit) optimization_pass = LOCutsOptimizer(interface, settings, constraint_obj) output = optimization_pass.optimize() cut_actions_list = output.cut_actions_sublist() assert cut_actions_list == [ SingleWireCutIdentifier( cut_action="CutLeftWire", wire_cut_location=WireCutLocation( instruction_id=10, gate_name="cx", qubits=[3, 4], input=1 ), ) ] assert ( interface.export_subcircuits_as_string(name_mapping="default") == "AAAABBBB" ) # extra wires because of wire cuts # and no qubit reuse. best_result = optimization_pass.get_results() assert ( output.upper_bound_gamma() == best_result.gamma_UB == 4 ) # One LO wire cut. assert ( optimization_pass.minimum_reached() is True ) # matches optimal solution with self.subTest("Two single wire cuts"): qubits_per_subcircuit = 3 interface = SimpleGateList(self.circuit_internal) settings = OptimizationSettings(seed=12345, gate_lo=True, wire_lo=True) settings.set_engine_selection("CutOptimization", "BestFirst") constraint_obj = DeviceConstraints(qubits_per_subcircuit) optimization_pass = LOCutsOptimizer(interface, settings, constraint_obj) output = optimization_pass.optimize() cut_actions_list = output.cut_actions_sublist() assert cut_actions_list == [ SingleWireCutIdentifier( cut_action="CutRightWire", wire_cut_location=WireCutLocation( instruction_id=9, gate_name="cx", qubits=[2, 3], input=2 ), ), SingleWireCutIdentifier( cut_action="CutLeftWire", wire_cut_location=WireCutLocation( instruction_id=11, gate_name="cx", qubits=[3, 5], input=1 ), ), ] assert ( interface.export_subcircuits_as_string(name_mapping="default") == "AABABCBCC" ) # extra wires because of wire cuts # and no qubit reuse. In the string above, # {A: wire 0, A:wire 1, B:wire 2, A: wire 3, # B: first cut on wire 3, C: second cut on wire 3, # B: wire 4, C: wire 5, C: wire 6}. best_result = optimization_pass.get_results() assert ( output.upper_bound_gamma() == best_result.gamma_UB == 16 ) # Two LO wire cuts. assert optimization_pass.minimum_reached() is True # matches optimal solution class TestCuttingMultiQubitGates(unittest.TestCase): def setUp(self): qc = QuantumCircuit(3) qc.ccx(0, 1, 2) circuit_internal = qc_to_cco_circuit(qc) self.interface = SimpleGateList(circuit_internal) self.settings = OptimizationSettings(seed=12345) self.settings.set_engine_selection("CutOptimization", "BestFirst") def no_cutting_multiqubit_gates(self): # The cutting of multiqubit gates is not supported at present. qubits_per_subcircuit = 2 constraint_obj = DeviceConstraints(qubits_per_subcircuit) optimization_pass = LOCutsOptimizer( self.interface, self.settings, constraint_obj ) with raises(ValueError) as e_info: _ = optimization_pass.optimize() assert e_info.value.args[0] == ( "The input circuit must contain only single and two-qubits gates. " "Found 3-qubit gate: (ccx)." )
https://github.com/Qiskit-Extensions/circuit-knitting-toolbox
Qiskit-Extensions
# This code is a Qiskit project. # (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. """Tests for QPDGate classes.""" import unittest import copy import io import pytest from qiskit import QuantumCircuit, qpy from qiskit.circuit.library.standard_gates import CXGate, XGate, YGate, ZGate from circuit_knitting.cutting.qpd import ( QPDBasis, TwoQubitQPDGate, SingleQubitQPDGate, ) class TestTwoQubitQPDGate(unittest.TestCase): def test_qpd_gate_empty(self): empty_maps = [([], [])] empty_basis = QPDBasis(empty_maps, [1.0]) empty_gate = TwoQubitQPDGate(empty_basis) self.assertEqual(None, empty_gate.basis_id) def test_qpd_gate_bad_idx(self): empty_maps = [([], [])] empty_basis = QPDBasis(empty_maps, [1.0]) empty_gate = TwoQubitQPDGate(empty_basis) with pytest.raises(ValueError) as e_info: empty_gate.basis_id = 1 self.assertEqual("Basis ID out of range", e_info.value.args[0]) def test_qpd_gate_select_basis(self): qpd_maps = [ ([XGate()], [XGate()]), ([YGate()], [YGate()]), ([ZGate()], [ZGate()]), ] qpd_basis = QPDBasis(qpd_maps, [0.5, 0.25, 0.25]) qpd_gate = TwoQubitQPDGate(qpd_basis) qpd_gate.basis_id = 1 qpd_gate_copy1 = copy.copy(qpd_gate) qpd_gate_copy2 = copy.copy(qpd_gate) # These will be random if the basis_id isn't working correctly self.assertEqual( qpd_gate.definition.decompose(), qpd_gate_copy1.definition.decompose(), qpd_gate_copy2.definition.decompose(), ) def test_qpd_gate_mismatching_basis(self): single_qubit_map = [ ([XGate()],), ] single_qubit_basis = QPDBasis(single_qubit_map, [1.0]) with pytest.raises(ValueError) as e_info: TwoQubitQPDGate(single_qubit_basis) self.assertEqual( "TwoQubitQPDGate only supports QPDBasis which act on two qubits.", e_info.value.args[0], ) class TestSingleQubitQPDGate(unittest.TestCase): def test_qpd_gate_empty(self): empty_maps = [([],)] empty_basis = QPDBasis(empty_maps, [1.0]) empty_gate = SingleQubitQPDGate(empty_basis, qubit_id=0) self.assertEqual(None, empty_gate.basis_id) self.assertEqual(0, empty_gate.qubit_id) def test_qubit_id_out_of_range(self): maps = [([XGate()], [YGate()])] basis = QPDBasis(maps, [1.0]) with pytest.raises(ValueError) as e_info: SingleQubitQPDGate(basis, qubit_id=2) self.assertEqual( "'qubit_id' out of range. 'basis' acts on 2 qubits, but 'qubit_id' is 2.", e_info.value.args[0], ) def test_missing_basis_id(self): maps = [([XGate()], [YGate()])] basis = QPDBasis(maps, [1.0]) assert SingleQubitQPDGate(basis=basis, qubit_id=0).definition is None def test_compare_1q_and_2q(self): maps = [([XGate()], [YGate()])] basis = QPDBasis(maps, [1.0]) inst_2q = TwoQubitQPDGate(basis=basis) inst_1q = SingleQubitQPDGate(basis=basis, qubit_id=0) # Call both eq methods, since single qubit implements a slightly different equivalence self.assertFalse(inst_2q == inst_1q) self.assertFalse(inst_1q == inst_2q) def test_qpy_serialization(self): qc = QuantumCircuit(2) qc.append(TwoQubitQPDGate.from_instruction(CXGate()), [0, 1]) f = io.BytesIO() qpy.dump(qc, f)
https://github.com/Qiskit-Extensions/circuit-knitting-toolbox
Qiskit-Extensions
# This code is a Qiskit project. # (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. import unittest import pytest import numpy as np from qiskit import QuantumCircuit from circuit_knitting.utils.simulation import ( simulate_statevector_outcomes, ExactSampler, ) class TestSimulationFunctions(unittest.TestCase): def test_simulate_statevector_outcomes(self): with self.subTest("Normal circuit"): qc = QuantumCircuit(2, 1) qc.h(0) qc.t(0) qc.h(0) qc.cx(0, 1) qc.measure(0, 0) qc.h(0) r = simulate_statevector_outcomes(qc) assert r.keys() == {0, 1} assert r[0] == pytest.approx(np.cos(np.pi / 8) ** 2) assert r[1] == pytest.approx(1 - np.cos(np.pi / 8) ** 2) with self.subTest("Circuit without measurement"): qc = QuantumCircuit(2) qc.h(0) qc.t(0) qc.h(0) qc.cx(0, 1) qc.h(0) r = simulate_statevector_outcomes(qc) assert r.keys() == {0} assert r[0] == pytest.approx(1.0) with self.subTest("Overwriting clbits"): qc = QuantumCircuit(2, 1) qc.h(0) qc.measure(0, 0) qc.measure(1, 0) r = simulate_statevector_outcomes(qc) assert r.keys() == {0} assert r[0] == pytest.approx(1.0) with self.subTest("Bit has probability 1 of being set"): qc = QuantumCircuit(1, 1) qc.x(0) qc.measure(0, 0) r = simulate_statevector_outcomes(qc) assert r.keys() == {1} with self.subTest("Circuit with reset operation"): qc = QuantumCircuit(1, 2) qc.h(0) qc.measure(0, 0) qc.reset(0) qc.measure(0, 1) r = simulate_statevector_outcomes(qc) assert r.keys() == {0, 1} assert r[0] == pytest.approx(0.5) assert r[1] == pytest.approx(0.5) with self.subTest("Circuit with control flow"): qc = QuantumCircuit(2, 1) with qc.for_loop(range(5)): qc.h(0) qc.cx(0, 1) qc.measure(0, 0) qc.break_loop().c_if(0, True) with pytest.raises(ValueError) as e_info: simulate_statevector_outcomes(qc) assert ( e_info.value.args[0] == "Circuit cannot contain a non-measurement operation on classical bit(s)." ) with self.subTest("Circuit with condition bits"): qc = QuantumCircuit(2, 1) qc.h(0) qc.measure(0, 0) qc.x(1).c_if(0, True) with pytest.raises(ValueError) as e_info: simulate_statevector_outcomes(qc) assert ( e_info.value.args[0] == "Operations conditioned on classical bits are currently not supported." ) def test_exact_sampler(self): with self.subTest("Mid-circuit measurement, etc."): qc = QuantumCircuit(2, 2) qc.h(0) qc.cx(0, 1) qc.measure(0, 0) qc.reset(0) qc.measure(0, 1) quasi_dists = ExactSampler().run(qc).result().quasi_dists assert len(quasi_dists) == 1 r = quasi_dists[0] assert r.keys() == {0, 1} assert r[0] == pytest.approx(0.5) assert r[0] == pytest.approx(0.5) with self.subTest("Circuit with reset"): qc = QuantumCircuit(2, 2) qc.h(0) qc.cx(0, 1) qc.reset(0) qc.measure([0, 1], [0, 1]) quasi_dists = ExactSampler().run(qc).result().quasi_dists assert len(quasi_dists) == 1 r = quasi_dists[0] assert r.keys() == {0, 2} assert r[0] == pytest.approx(0.5) assert r[2] == pytest.approx(0.5)
https://github.com/Qiskit-Extensions/circuit-knitting-toolbox
Qiskit-Extensions
# This code is a Qiskit project. # (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. """Tests for CKT transpilation passes.""" import unittest from qiskit import QuantumRegister, QuantumCircuit from qiskit.transpiler import PassManager from qiskit.transpiler.passes import DAGFixedPoint from qiskit.passmanager.flow_controllers import DoWhileController from qiskit.converters import circuit_to_dag from circuit_knitting.utils.transpiler_passes import RemoveFinalReset, ConsolidateResets class TestRemoveFinalReset(unittest.TestCase): """Test remove-reset-in-zero-state optimizations.""" def test_optimize_single_reset(self): """Remove a single final reset qr0:--[H]--|0>-- ==> qr0:--[H]-- """ qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.h(0) circuit.reset(qr) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr) expected.h(0) pass_ = RemoveFinalReset() after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_dont_optimize_non_final_reset(self): """Do not remove reset if not final instruction qr0:--|0>--[H]-- ==> qr0:--|0>--[H]-- """ qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.reset(qr) circuit.h(qr) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr) expected.reset(qr) expected.h(qr) pass_ = RemoveFinalReset() after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_optimize_single_reset_in_diff_qubits(self): """Remove a single final reset in different qubits qr0:--[H]--|0>-- qr0:--[H]-- ==> qr1:--[X]--|0>-- qr1:--[X]---- """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.h(0) circuit.x(1) circuit.reset(qr) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr) expected.h(0) expected.x(1) pass_ = RemoveFinalReset() after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) class TestRemoveFinalResetFixedPoint(unittest.TestCase): """Test RemoveFinalReset in a transpiler, using fixed point.""" def test_two_resets(self): """Remove two final resets qr0:--[H]-|0>-|0>-- ==> qr0:--[H]-- """ qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.reset(qr[0]) circuit.reset(qr[0]) expected = QuantumCircuit(qr) expected.h(qr[0]) pass_manager = PassManager() passes = [RemoveFinalReset(), DAGFixedPoint()] pass_manager.append( DoWhileController( passes, do_while=lambda property_set: not property_set["dag_fixed_point"], ) ) after = pass_manager.run(circuit) self.assertEqual(expected, after) class TestConsolidateResets(unittest.TestCase): """Test consolidate-resets optimization.""" def test_consolidate_double_reset(self): """Consolidate a pair of resets. qr0:--|0>--|0>-- ==> qr0:--|0>-- """ qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.reset(qr) circuit.reset(qr) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr) expected.reset(qr) pass_ = ConsolidateResets() after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after)
https://github.com/QuantumBarcelona/Qiskit-Hackathon-BCN
QuantumBarcelona
from typing import List, Optional from qiskit import transpile, QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.result import marginal_counts import warnings warnings.filterwarnings("ignore") import math pi=math.pi from qiskit_ibm_provider import IBMProvider provider = IBMProvider() hub = "ibm-q-community" group = "digiq-icfo-hack" project = "main" backend_name = "ibmq_jakarta" # 7 qubits #backend_name = "ibmq_guadalupe " # 16 qubits backend = provider.get_backend(backend_name, instance=f"{hub}/{group}/{project}") shots: int = 1024 # Number of shots to run each circuit for print(len(backend.properties().qubits)) from qiskit import transpile initial_layout=[0,1,2,3,4] # optional qc_transpiled = transpile(your_circuit, backend, initial_layout=initial_layout) job = backend.run(qc_transpiled, shots=1024, job_tags=["team_name", "bcn_hackathon"]) counts = job.result().get_counts()
https://github.com/QuantumBarcelona/Qiskit-Hackathon-BCN
QuantumBarcelona
import numpy as np import matplotlib.pyplot as plt plt.rcParams.update({'font.size': 16}) # enlarge fonts # Import standard qiskit modules from qiskit import QuantumCircuit, QuantumRegister #For doing exact simulation you can use Statevector (feel free to use something else) from qiskit.quantum_info import Statevector #Your code here # loading IBMQ account from qiskit import IBMQ # IBMQ.save_account('Token') #you can replace TOKEN with your API token string (https://quantum-computing.ibm.com/lab/docs/iql/manage/account/ibmq) IBMQ.load_account() # Your answer here # Your code here # Your code here # Your code here
https://github.com/QuantumBarcelona/Qiskit-Hackathon-BCN
QuantumBarcelona
https://github.com/QuantumBarcelona/Qiskit-Hackathon-BCN
QuantumBarcelona
## Black scholes, simulation parameters and basic imports import matplotlib.pyplot as plt import numpy as np K = 100 # strike price sigma = 0.4 # volatility in % T = 1 r = 0 Smin = 50 Smax = 150 Nqubits = 4 #Define range of stock price S = np.arange(Smin,Smax,5) #Define the Payoff Function def call_payoff(S,K): # TO DO pass #Define the underlying strike price K = 100 #Calculate the payoff for the option payoff = call_payoff(S,K) #Plot the Payoff Graph fig, ax = plt.subplots() ax.spines['bottom'].set_position('zero') ax.plot(S, payoff, '--', color='g') plt.xlabel('x') plt.ylabel('Payoff') plt.title('Call Option Payoff') plt.show() ## PUT CODE HERE ## PUT CODE HERE ## PUT CODE HERE
https://github.com/qiskit-community/qiskit-aqt-provider
qiskit-community
# This code is part of Qiskit. # # (C) Copyright Alpine Quantum Technologies GmbH 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. """Basic example with the Qiskit AQT provider. Creates a 4-qubit GHZ state.""" import qiskit from qiskit import QuantumCircuit from qiskit_aqt_provider.aqt_provider import AQTProvider if __name__ == "__main__": # Ways to specify an access token (in precedence order): # - as argument to the AQTProvider initializer # - in the AQT_TOKEN environment variable # - if none of the above exists, default to an empty string, which restricts access # to the default workspace only. provider = AQTProvider("token") # The backends() method lists all available computing backends. Printing it # renders it as a table that shows each backend's containing workspace. print(provider.backends()) # Retrieve a backend by providing search criteria. The search must have a single # match. For example: backend = provider.get_backend("offline_simulator_no_noise", workspace="default") # Define a quantum circuit that produces a 4-qubit GHZ state. qc = QuantumCircuit(4) qc.h(0) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) qc.measure_all() # Transpile for the target backend. qc = qiskit.transpile(qc, backend) # Execute on the target backend. result = backend.run(qc, shots=200).result() if result.success: print(result.get_counts()) else: # pragma: no cover print(result.to_dict()["error"])
https://github.com/qiskit-community/qiskit-aqt-provider
qiskit-community
# This code is part of Qiskit. # # (C) Copyright Alpine Quantum Technologies GmbH 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. """Basic example with the Qiskit AQT provider and the noisy offline simulator. Creates a 2-qubit GHZ state. """ import qiskit from qiskit import QuantumCircuit from qiskit_aqt_provider.aqt_provider import AQTProvider if __name__ == "__main__": # Ways to specify an access token (in precedence order): # - as argument to the AQTProvider initializer # - in the AQT_TOKEN environment variable # - if none of the above exists, default to an empty string, which restricts access # to the default workspace only. provider = AQTProvider("token") # The backends() method lists all available computing backends. Printing it # renders it as a table that shows each backend's containing workspace. print(provider.backends()) # Retrieve a backend by providing search criteria. The search must have a single # match. For example: backend = provider.get_backend("offline_simulator_noise", workspace="default") # Define a quantum circuit that produces a 2-qubit GHZ state. qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc.measure_all() # Transpile for the target backend. qc = qiskit.transpile(qc, backend) # Execute on the target backend. result = backend.run(qc, shots=200).result() if result.success: # due to the noise, also the states '01' and '10' may be populated! print(result.get_counts()) else: # pragma: no cover print(result.to_dict()["error"])
https://github.com/qiskit-community/qiskit-aqt-provider
qiskit-community
# This code is part of Qiskit. # # (C) Copyright Alpine Quantum Technologies GmbH 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. """Simple number partition problem solving. This example shows how to solve problems covered by the application domains in the qiskit_optimization package. Number partition: given a set of positive integers, determine whether it can be split into two non-overlapping sets that have the same sum. """ from dataclasses import dataclass from typing import Final, Union import qiskit_algorithms from qiskit_algorithms.minimum_eigensolvers import QAOA from qiskit_algorithms.optimizers import COBYLA from qiskit_optimization.algorithms import MinimumEigenOptimizer, OptimizationResultStatus from qiskit_optimization.applications import NumberPartition from qiskit_aqt_provider import AQTProvider from qiskit_aqt_provider.primitives import AQTSampler RANDOM_SEED: Final = 0 @dataclass(frozen=True) class Success: """Solution of a partition problem.""" # type would be better as tuple[set[int], set[int]] but # NumberPartition.interpret returns list[list[int]]. partition: list[list[int]] def is_valid(self) -> bool: """Evaluate whether the stored partition is valid. A partition is valid if both sets have the same sum. """ a, b = self.partition return sum(a) == sum(b) class Infeasible: """Marker for unsolvable partition problems.""" def solve_partition_problem(num_set: set[int]) -> Union[Success, Infeasible]: """Solve a partition problem. Args: num_set: set of positive integers to partition into two distinct subsets with the same sum. Returns: Success: solutions to the problem exist and are returned Infeasible: the given set cannot be partitioned. """ problem = NumberPartition(list(num_set)) qp = problem.to_quadratic_program() meo = MinimumEigenOptimizer( min_eigen_solver=QAOA(sampler=AQTSampler(backend), optimizer=COBYLA()) ) result = meo.solve(qp) if result.status is OptimizationResultStatus.SUCCESS: return Success(partition=problem.interpret(result)) if result.status is OptimizationResultStatus.INFEASIBLE: return Infeasible() raise RuntimeError("Unexpected optimizer status") # pragma: no cover if __name__ == "__main__": backend = AQTProvider("token").get_backend("offline_simulator_no_noise") # fix the random seeds such that the example is reproducible qiskit_algorithms.utils.algorithm_globals.random_seed = RANDOM_SEED backend.simulator.options.seed_simulator = RANDOM_SEED num_set = {1, 3, 4} result = solve_partition_problem(num_set) assert isinstance(result, Success) # noqa: S101 assert result.is_valid() # noqa: S101 print(f"Partition for {num_set}:", result.partition) num_set = {1, 2} result = solve_partition_problem(num_set) assert isinstance(result, Infeasible) # noqa: S101 print(f"No partition possible for {num_set}.")
https://github.com/qiskit-community/qiskit-aqt-provider
qiskit-community
# This code is part of Qiskit. # # (C) Copyright Alpine Quantum Technologies GmbH 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. """Trivial minimization example using a quantum approximate optimization algorithm (QAOA). This is the same example as in vqe.py, but uses QAOA instead of VQE as solver. """ from typing import Final import qiskit_algorithms from qiskit.quantum_info import SparsePauliOp from qiskit_algorithms.minimum_eigensolvers import QAOA from qiskit_algorithms.optimizers import COBYLA from qiskit_aqt_provider import AQTProvider from qiskit_aqt_provider.primitives import AQTSampler RANDOM_SEED: Final = 0 if __name__ == "__main__": backend = AQTProvider("token").get_backend("offline_simulator_no_noise") sampler = AQTSampler(backend) # fix the random seeds such that the example is reproducible qiskit_algorithms.utils.algorithm_globals.random_seed = RANDOM_SEED backend.simulator.options.seed_simulator = RANDOM_SEED # Hamiltonian: Ising model on two spin 1/2 without external field J = 1.23456789 hamiltonian = SparsePauliOp.from_list([("ZZ", 3 * J)]) # Find the ground-state energy with QAOA optimizer = COBYLA(maxiter=100, tol=0.01) qaoa = QAOA(sampler, optimizer) result = qaoa.compute_minimum_eigenvalue(operator=hamiltonian) assert result.eigenvalue is not None # noqa: S101 print(f"Optimizer run time: {result.optimizer_time:.2f} s") print("Cost function evaluations:", result.cost_function_evals) print("Deviation from expected ground-state energy:", abs(result.eigenvalue - (-3 * J)))
https://github.com/qiskit-community/qiskit-aqt-provider
qiskit-community
# This code is part of Qiskit. # # (C) Copyright Alpine Quantum Technologies GmbH 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. # mypy: disable-error-code="no-untyped-def" """Quickstart example on using the Estimator primitive. This examples uses a variational quantum eigensolver (VQE) to find the ground state energy of a Hamiltonian. """ from collections.abc import Sequence from qiskit import QuantumCircuit from qiskit.circuit.library import TwoLocal from qiskit.primitives import BaseEstimator from qiskit.quantum_info import SparsePauliOp from qiskit.quantum_info.operators.base_operator import BaseOperator from scipy.optimize import minimize from qiskit_aqt_provider import AQTProvider from qiskit_aqt_provider.primitives import AQTEstimator # Select an execution backend provider = AQTProvider("ACCESS_TOKEN") backend = provider.get_backend("offline_simulator_no_noise") # Instantiate an estimator on the execution backend estimator = AQTEstimator(backend) # Set the transpiler's optimization level estimator.set_transpile_options(optimization_level=3) # Specify the problem Hamiltonian hamiltonian = SparsePauliOp.from_list( [ ("II", -1.052373245772859), ("IZ", 0.39793742484318045), ("ZI", -0.39793742484318045), ("ZZ", -0.01128010425623538), ("XX", 0.18093119978423156), ] ) # Define the VQE Ansatz, initial point, and cost function ansatz = TwoLocal(num_qubits=2, rotation_blocks="ry", entanglement_blocks="cz") initial_point = [0] * 8 def cost_function( params: Sequence[float], ansatz: QuantumCircuit, hamiltonian: BaseOperator, estimator: BaseEstimator, ) -> float: """Cost function for the VQE. Return the estimated expectation value of the Hamiltonian on the state prepared by the Ansatz circuit. """ return float(estimator.run(ansatz, hamiltonian, parameter_values=params).result().values[0]) # Run the VQE using the SciPy minimizer routine result = minimize( cost_function, initial_point, args=(ansatz, hamiltonian, estimator), method="cobyla" ) # Print the found minimum eigenvalue print(result.fun)
https://github.com/qiskit-community/qiskit-aqt-provider
qiskit-community
# This code is part of Qiskit. # # (C) Copyright Alpine Quantum Technologies GmbH 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. """Quickstart example on using the Sampler primitive. This example samples a 2-qubit Bell state. """ from qiskit import QuantumCircuit from qiskit_aqt_provider import AQTProvider from qiskit_aqt_provider.primitives import AQTSampler # Define a circuit circuit = QuantumCircuit(2) circuit.h(0) circuit.cx(0, 1) circuit.measure_all() # Select an execution backend provider = AQTProvider("ACCESS_TOKEN") backend = provider.get_backend("offline_simulator_no_noise") # Instantiate a sampler on the execution backend sampler = AQTSampler(backend) # Set the transpiler's optimization level sampler.set_transpile_options(optimization_level=3) # Sample the circuit on the execution backend result = sampler.run(circuit).result() quasi_dist = result.quasi_dists[0] print(quasi_dist)
https://github.com/qiskit-community/qiskit-aqt-provider
qiskit-community
# This code is part of Qiskit. # # (C) Copyright Alpine Quantum Technologies GmbH 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. """Quickstart example on transpiling and executing circuits.""" import qiskit from qiskit.circuit.library import QuantumVolume from qiskit_aqt_provider import AQTProvider # Define a circuit circuit = QuantumVolume(5) circuit.measure_all() # Select an execution backend provider = AQTProvider("ACCESS_TOKEN") backend = provider.get_backend("offline_simulator_no_noise") # Transpile the circuit to target the selected AQT backend transpiled_circuit = qiskit.transpile(circuit, backend, optimization_level=2) print(transpiled_circuit) # Execute the circuit on the selected AQT backend result = backend.run(transpiled_circuit, shots=50).result() if result.success: print(result.get_counts()) else: # pragma: no cover raise RuntimeError
https://github.com/qiskit-community/qiskit-aqt-provider
qiskit-community
# This code is part of Qiskit. # # (C) Copyright Alpine Quantum Technologies GmbH 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. """Trivial minimization example using a variational quantum eigensolver.""" from typing import Final import qiskit_algorithms from qiskit.circuit.library import TwoLocal from qiskit.quantum_info import SparsePauliOp from qiskit_algorithms.minimum_eigensolvers import VQE from qiskit_algorithms.optimizers import COBYLA from qiskit_aqt_provider import AQTProvider from qiskit_aqt_provider.aqt_resource import OfflineSimulatorResource from qiskit_aqt_provider.primitives import AQTEstimator RANDOM_SEED: Final = 0 if __name__ == "__main__": backend = AQTProvider("token").get_backend("offline_simulator_no_noise") assert isinstance(backend, OfflineSimulatorResource) # noqa: S101 estimator = AQTEstimator(backend) # fix the random seeds such that the example is reproducible qiskit_algorithms.utils.algorithm_globals.random_seed = RANDOM_SEED backend.simulator.options.seed_simulator = RANDOM_SEED # Hamiltonian: Ising model on two spin 1/2 without external field J = 1.2 hamiltonian = SparsePauliOp.from_list([("XX", J)]) # Find the ground-state energy with VQE ansatz = TwoLocal(num_qubits=2, rotation_blocks="ry", entanglement_blocks="rxx", reps=1) optimizer = COBYLA(maxiter=100, tol=0.01) vqe = VQE(estimator, ansatz, optimizer) result = vqe.compute_minimum_eigenvalue(operator=hamiltonian) assert result.eigenvalue is not None # noqa: S101 print(f"Optimizer run time: {result.optimizer_time:.2f} s") print("Cost function evaluations:", result.cost_function_evals) print("Deviation from expected ground-state energy:", abs(result.eigenvalue - (-J)))
https://github.com/qiskit-community/qiskit-aqt-provider
qiskit-community
# This code is part of Qiskit. # # (C) Copyright IBM 2019, Alpine Quantum Technologies GmbH 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. import uuid from collections import Counter, defaultdict from dataclasses import dataclass from pathlib import Path from types import TracebackType from typing import ( TYPE_CHECKING, Any, ClassVar, NoReturn, Optional, Union, ) import numpy as np from qiskit import QuantumCircuit from qiskit.providers import JobV1 from qiskit.providers.jobstatus import JobStatus from qiskit.result.result import Result from qiskit.utils.lazy_tester import contextlib from tqdm import tqdm from typing_extensions import Self, TypeAlias, assert_never from qiskit_aqt_provider import api_models_generated, persistence from qiskit_aqt_provider.api_models_direct import JobResultError from qiskit_aqt_provider.aqt_options import AQTOptions from qiskit_aqt_provider.circuit_to_aqt import circuits_to_aqt_job if TYPE_CHECKING: # pragma: no cover from qiskit_aqt_provider.aqt_resource import AQTDirectAccessResource, AQTResource # Tags for the status of AQT API jobs @dataclass class JobFinished: """The job finished successfully.""" status: ClassVar = JobStatus.DONE results: dict[int, list[list[int]]] @dataclass class JobFailed: """An error occurred during the job execution.""" status: ClassVar = JobStatus.ERROR error: str class JobQueued: """The job is queued.""" status: ClassVar = JobStatus.QUEUED @dataclass class JobOngoing: """The job is running.""" status: ClassVar = JobStatus.RUNNING finished_count: int class JobCancelled: """The job was cancelled.""" status = ClassVar = JobStatus.CANCELLED JobStatusPayload: TypeAlias = Union[JobQueued, JobOngoing, JobFinished, JobFailed, JobCancelled] @dataclass(frozen=True) class Progress: """Progress information of a job.""" finished_count: int """Number of completed circuits.""" total_count: int """Total number of circuits in the job.""" @dataclass class _MockProgressBar: """Minimal tqdm-compatible progress bar mock.""" total: int """Total number of items in the job.""" n: int = 0 """Number of processed items.""" def update(self, n: int = 1) -> None: """Update the number of processed items by `n`.""" self.n += n def __enter__(self) -> Self: return self def __exit__( self, exc_type: Optional[type[BaseException]], exc_value: Optional[BaseException], traceback: Optional[TracebackType], /, ) -> None: ... class AQTJob(JobV1): """Handle for quantum circuits jobs running on AQT cloud backends. Jobs contain one or more quantum circuits that are executed with a common set of options (see :class:`AQTOptions <qiskit_aqt_provider.aqt_options.AQTOptions>`). Job handles should be retrieved from calls to :meth:`AQTResource.run <qiskit_aqt_provider.aqt_resource.AQTResource.run>`, which immediately returns after submitting the job. The :meth:`result` method allows blocking until a job completes: >>> import qiskit >>> from qiskit.providers import JobStatus >>> from qiskit_aqt_provider import AQTProvider >>> >>> backend = AQTProvider("").get_backend("offline_simulator_no_noise") >>> >>> qc = qiskit.QuantumCircuit(1) >>> _ = qc.rx(3.14, 0) >>> _ = qc.measure_all() >>> qc = qiskit.transpile(qc, backend) >>> >>> job = backend.run(qc, shots=100) >>> result = job.result() >>> job.status() is JobStatus.DONE True >>> result.success True >>> result.get_counts() {'1': 100} """ _backend: "AQTResource" def __init__( self, backend: "AQTResource", circuits: list[QuantumCircuit], options: AQTOptions, ) -> None: """Initialize an :class:`AQTJob` instance. .. tip:: :class:`AQTJob` instances should not be created directly. Use :meth:`AQTResource.run <qiskit_aqt_provider.aqt_resource.AQTResource.run>` to submit circuits for execution and retrieve a job handle. Args: backend: backend to run the job on. circuits: list of circuits to execute. options: overridden resource options for this job. """ super().__init__(backend, "") self.circuits = circuits self.options = options self.api_submit_payload = circuits_to_aqt_job(circuits, options.shots) self.status_payload: JobStatusPayload = JobQueued() @classmethod def restore( cls, job_id: str, *, access_token: Optional[str] = None, store_path: Optional[Path] = None, remove_from_store: bool = True, ) -> Self: """Restore a job handle from local persistent storage. .. warning:: The default local storage path depends on the `qiskit_aqt_provider` package version. Job persisted with a different package version will therefore **not** be found! .. hint:: If the job's execution backend is an offline simulator, the job is re-submitted to the simulation backend and the new job ID differs from the one passed to this function. Args: job_id: identifier of the job to retrieve. access_token: access token for the AQT cloud. See :class:`AQTProvider <qiskit_aqt_provider.aqt_provider.AQTProvider>`. store_path: local persistent storage directory. By default, use a standard cache directory. remove_from_store: if :data:`True`, remove the retrieved job's data from persistent storage after a successful load. Returns: A job handle for the passed `job_id`. Raises: JobNotFoundError: the target job was not found in persistent storage. """ from qiskit_aqt_provider.aqt_provider import AQTProvider from qiskit_aqt_provider.aqt_resource import AQTResource, OfflineSimulatorResource store_path = persistence.get_store_path(store_path) data = persistence.Job.restore(job_id, store_path) # TODO: forward .env loading args? provider = AQTProvider(access_token) if data.resource.resource_type == "offline_simulator": # FIXME: persist with_noise_model and restore it resource = OfflineSimulatorResource(provider, data.resource, with_noise_model=False) else: resource = AQTResource(provider, data.resource) obj = cls(backend=resource, circuits=data.circuits.circuits, options=data.options) if data.resource.resource_type == "offline_simulator": # re-submit the job because we can't restore the backend state obj.submit() else: obj._job_id = job_id if remove_from_store: persistence.Job.remove_from_store(job_id, store_path) return obj def persist(self, *, store_path: Optional[Path] = None) -> Path: """Save this job to local persistent storage. .. warning:: Only jobs that have been submitted for execution can be persisted (a valid `job_id` is required). Args: store_path: local persistent storage directory. By default, use a standard cache directory. Returns: The path to the job data in local persistent storage. Raises: RuntimeError: the job was never submitted for execution. """ if not self.job_id(): raise RuntimeError("Can only persist submitted jobs.") store_path = persistence.get_store_path(store_path) data = persistence.Job( resource=self._backend.resource_id, circuits=persistence.Circuits(self.circuits), options=self.options, ) return data.persist(self.job_id(), store_path) def submit(self) -> None: """Submit this job for execution. This operation is not blocking. Use :meth:`result()` to block until the job completes. Raises: RuntimeError: this job was already submitted. """ if self.job_id(): raise RuntimeError(f"Job already submitted (ID: {self.job_id()})") job_id = self._backend.submit(self) self._job_id = str(job_id) def status(self) -> JobStatus: """Query the job's status. Returns: Aggregated job status for all the circuits in this job. """ payload = self._backend.result(uuid.UUID(self.job_id())) if isinstance(payload, api_models_generated.JobResponseRRQueued): self.status_payload = JobQueued() elif isinstance(payload, api_models_generated.JobResponseRROngoing): self.status_payload = JobOngoing(finished_count=payload.response.finished_count) elif isinstance(payload, api_models_generated.JobResponseRRFinished): self.status_payload = JobFinished( results={ int(circuit_index): [[sample.root for sample in shot] for shot in shots] for circuit_index, shots in payload.response.result.items() } ) elif isinstance(payload, api_models_generated.JobResponseRRError): self.status_payload = JobFailed(error=payload.response.message) elif isinstance(payload, api_models_generated.JobResponseRRCancelled): self.status_payload = JobCancelled() else: # pragma: no cover assert_never(payload) return self.status_payload.status def progress(self) -> Progress: """Progress information for this job.""" num_circuits = len(self.circuits) if isinstance(self.status_payload, JobQueued): return Progress(finished_count=0, total_count=num_circuits) if isinstance(self.status_payload, JobOngoing): return Progress( finished_count=self.status_payload.finished_count, total_count=num_circuits ) # if the circuit is finished, failed, or cancelled, it is completed return Progress(finished_count=num_circuits, total_count=num_circuits) @property def error_message(self) -> Optional[str]: """Error message for this job (if any).""" if isinstance(self.status_payload, JobFailed): return self.status_payload.error return None def result(self) -> Result: """Block until all circuits have been evaluated and return the combined result. Success or error is signalled by the `success` field in the returned Result instance. Returns: The combined result of all circuit evaluations. """ if self.options.with_progress_bar: context: Union[tqdm[NoReturn], _MockProgressBar] = tqdm(total=len(self.circuits)) else: context = _MockProgressBar(total=len(self.circuits)) with context as progress_bar: def callback( job_id: str, # noqa: ARG001 status: JobStatus, # noqa: ARG001 job: AQTJob, ) -> None: progress = job.progress() progress_bar.update(progress.finished_count - progress_bar.n) # one of DONE, CANCELLED, ERROR self.wait_for_final_state( timeout=self.options.query_timeout_seconds, wait=self.options.query_period_seconds, callback=callback, ) # make sure the progress bar completes progress_bar.update(self.progress().finished_count - progress_bar.n) results = [] if isinstance(self.status_payload, JobFinished): for circuit_index, circuit in enumerate(self.circuits): samples = self.status_payload.results[circuit_index] results.append( _partial_qiskit_result_dict( samples, circuit, shots=self.options.shots, memory=self.options.memory ) ) return Result.from_dict( { "backend_name": self._backend.name, "backend_version": self._backend.version, "qobj_id": id(self.circuits), "job_id": self.job_id(), "success": self.status_payload.status is JobStatus.DONE, "results": results, # Pass error message as metadata "error": self.error_message, } ) class AQTDirectAccessJob(JobV1): """Handle for quantum circuits jobs running on direct-access AQT backends. Use :meth:`AQTDirectAccessResource.run <qiskit_aqt_provider.aqt_resource.AQTDirectAccessResource.run>` to get a handle and evaluate circuits on a direct-access backend. """ _backend: "AQTDirectAccessResource" def __init__( self, backend: "AQTDirectAccessResource", circuits: list[QuantumCircuit], options: AQTOptions, ) -> None: """Initialize the :class:`AQTDirectAccessJob` instance. Args: backend: backend to run the job on. circuits: list of circuits to execute. options: overridden resource options for this job. """ super().__init__(backend, "") self.circuits = circuits self.options = options self.api_submit_payload = circuits_to_aqt_job(circuits, options.shots) self._job_id = uuid.uuid4() self._status = JobStatus.INITIALIZING def submit(self) -> None: """No-op on direct-access backends.""" def result(self) -> Result: """Iteratively submit all circuits and block until full completion. If an error occurs, the remaining circuits are not executed and the whole job is marked as failed. Returns: The combined result of all circuit evaluations. """ if self.options.with_progress_bar: context: Union[tqdm[NoReturn], _MockProgressBar] = tqdm(total=len(self.circuits)) else: context = _MockProgressBar(total=len(self.circuits)) result = { "backend_name": self._backend.name, "backend_version": self._backend.version, "qobj_id": id(self.circuits), "job_id": self.job_id(), "success": True, "results": [], } with context as progress_bar: for circuit_index, circuit in enumerate(self.circuits): api_circuit = self.api_submit_payload.payload.circuits[circuit_index] job_id = self._backend.submit(api_circuit) api_result = self._backend.result( job_id, timeout=self.options.query_timeout_seconds ) if isinstance(api_result.payload, JobResultError): break result["results"].append( _partial_qiskit_result_dict( api_result.payload.result, circuit, shots=self.options.shots, memory=self.options.memory, ) ) progress_bar.update(1) else: # no circuits in the job, or all executed successfully self._status = JobStatus.DONE return Result.from_dict(result) self._status = JobStatus.ERROR result["success"] = False return Result.from_dict(result) def status(self) -> JobStatus: """Query the job's status. Returns: Aggregated job status for all the circuits in this job. """ return self._status def _partial_qiskit_result_dict( samples: list[list[int]], circuit: QuantumCircuit, *, shots: int, memory: bool ) -> dict[str, Any]: """Build the Qiskit result dict for a single circuit evaluation. Args: samples: measurement outcome of the circuit evaluation. circuit: the evaluated circuit. shots: number of repetitions of the circuit evaluation. memory: whether to fill the classical memory dump field with the measurement results. Returns: Dict, suitable for Qiskit's `Result.from_dict` factory. """ meas_map = _build_memory_mapping(circuit) data: dict[str, Any] = {"counts": _format_counts(samples, meas_map)} if memory: data["memory"] = ["".join(str(x) for x in reversed(states)) for states in samples] return { "shots": shots, "success": True, "status": JobStatus.DONE, "data": data, "header": { "memory_slots": circuit.num_clbits, "creg_sizes": [[reg.name, reg.size] for reg in circuit.cregs], "qreg_sizes": [[reg.name, reg.size] for reg in circuit.qregs], "name": circuit.name, "metadata": circuit.metadata or {}, }, } def _build_memory_mapping(circuit: QuantumCircuit) -> dict[int, set[int]]: """Scan the circuit for measurement instructions and collect qubit to classical bits mappings. Qubits can be mapped to multiple classical bits, possibly in different classical registers. The returned map only maps qubits referenced in a `measure` operation in the passed circuit. Qubits not targeted by a `measure` operation will not appear in the returned result. Parameters: circuit: the `QuantumCircuit` to analyze. Returns: the translation map for all measurement operations in the circuit. Examples: >>> qc = QuantumCircuit(2) >>> qc.measure_all() >>> _build_memory_mapping(qc) {0: {0}, 1: {1}} >>> qc = QuantumCircuit(2, 2) >>> _ = qc.measure([0, 1], [1, 0]) >>> _build_memory_mapping(qc) {0: {1}, 1: {0}} >>> qc = QuantumCircuit(3, 2) >>> _ = qc.measure([0, 1], [0, 1]) >>> _build_memory_mapping(qc) {0: {0}, 1: {1}} >>> qc = QuantumCircuit(4, 6) >>> _ = qc.measure([0, 1, 2, 3], [2, 3, 4, 5]) >>> _build_memory_mapping(qc) {0: {2}, 1: {3}, 2: {4}, 3: {5}} >>> qc = QuantumCircuit(3, 4) >>> qc.measure_all(add_bits=False) >>> _build_memory_mapping(qc) {0: {0}, 1: {1}, 2: {2}} >>> qc = QuantumCircuit(3, 3) >>> _ = qc.x(0) >>> _ = qc.measure([0], [2]) >>> _ = qc.y(1) >>> _ = qc.measure([1], [1]) >>> _ = qc.x(2) >>> _ = qc.measure([2], [0]) >>> _build_memory_mapping(qc) {0: {2}, 1: {1}, 2: {0}} 5 qubits in two registers: >>> from qiskit import QuantumRegister, ClassicalRegister >>> qr0 = QuantumRegister(2) >>> qr1 = QuantumRegister(3) >>> cr = ClassicalRegister(2) >>> qc = QuantumCircuit(qr0, qr1, cr) >>> _ = qc.measure(qr0, cr) >>> _build_memory_mapping(qc) {0: {0}, 1: {1}} Multiple mapping of a qubit: >>> qc = QuantumCircuit(3, 3) >>> _ = qc.measure([0, 1], [0, 1]) >>> _ = qc.measure([0], [2]) >>> _build_memory_mapping(qc) {0: {0, 2}, 1: {1}} """ qu2cl: defaultdict[int, set[int]] = defaultdict(set) for instruction in circuit.data: if instruction.operation.name == "measure": for qubit, clbit in zip(instruction.qubits, instruction.clbits): qu2cl[circuit.find_bit(qubit).index].add(circuit.find_bit(clbit).index) return dict(qu2cl) def _shot_to_int( fluorescence_states: list[int], qubit_to_bit: Optional[dict[int, set[int]]] = None ) -> int: """Format the detected fluorescence states from a single shot as an integer. This follows the Qiskit ordering convention, where bit 0 in the classical register is mapped to bit 0 in the returned integer. The first classical register in the original circuit represents the least-significant bits in the integer representation. An optional translation map from the quantum to the classical register can be applied. If given, only the qubits registered in the translation map are present in the return value, at the index given by the translation map. Parameters: fluorescence_states: detected fluorescence states for this shot qubit_to_bit: optional translation map from quantum register to classical register positions Returns: integral representation of the shot result, with the translation map applied. Examples: Without a translation map, the natural mapping is used (n -> n): >>> _shot_to_int([1]) 1 >>> _shot_to_int([0, 0, 1]) 4 >>> _shot_to_int([0, 1, 1]) 6 Swap qubits 1 and 2 in the classical register: >>> _shot_to_int([1, 0, 1], {0: {0}, 1: {2}, 2: {1}}) 3 If the map is partial, only the mapped qubits are present in the output: >>> _shot_to_int([1, 0, 1], {1: {2}, 2: {1}}) 2 One can translate into a classical register larger than the qubit register. Warning: the classical register is always initialized to 0. >>> _shot_to_int([1], {0: {1}}) 2 >>> _shot_to_int([0, 1, 1], {0: {3}, 1: {4}, 2: {5}}) == (0b110 << 3) True or with a map larger than the qubit space: >>> _shot_to_int([1], {0: {0}, 1: {1}}) 1 Consider the typical example of two quantum registers (the second one contains ancilla qubits) and one classical register: >>> from qiskit import QuantumRegister, ClassicalRegister >>> qr_meas = QuantumRegister(2) >>> qr_ancilla = QuantumRegister(3) >>> cr = ClassicalRegister(2) >>> qc = QuantumCircuit(qr_meas, qr_ancilla, cr) >>> _ = qc.measure(qr_meas, cr) >>> tr_map = _build_memory_mapping(qc) We assume that a single shot gave the result: >>> ancillas = [1, 1, 0] >>> meas = [1, 0] Then the corresponding output is 0b01 (measurement qubits mapped straight to the classical register of length 2): >>> _shot_to_int(meas + ancillas, tr_map) == 0b01 True One can overwrite qr_meas[1] with qr_ancilla[0]: >>> _ = qc.measure(qr_ancilla[0], cr[1]) >>> tr_map = _build_memory_mapping(qc) >>> _shot_to_int(meas + ancillas, tr_map) == 0b11 True """ tr_map = qubit_to_bit or {} if tr_map: # allocate a zero-initialized classical register # TODO: support pre-initialized classical registers clbits = max(max(d) for d in tr_map.values()) + 1 creg = [0] * clbits for src_index, dest_indices in tr_map.items(): # the translation map could map more than just the measured qubits with contextlib.suppress(IndexError): for dest_index in dest_indices: creg[dest_index] = fluorescence_states[src_index] else: creg = fluorescence_states.copy() return int((np.left_shift(1, np.arange(len(creg))) * creg).sum()) def _format_counts( samples: list[list[int]], qubit_to_bit: Optional[dict[int, set[int]]] = None ) -> dict[str, int]: """Format all shots results from a circuit evaluation. The returned dictionary is compatible with Qiskit's `ExperimentResultData` `counts` field. Keys are hexadecimal string representations of the detected states, with the optional `QuantumRegister` to `ClassicalRegister` applied. Values are the occurrences of the keys. Parameters: samples: detected qubit fluorescence states for all shots qubit_to_bit: optional quantum to classical register translation map Returns: collected counts, for `ExperimentResultData`. Examples: >>> _format_counts([[1, 0, 0], [0, 1, 0], [1, 0, 0]]) {'0x1': 2, '0x2': 1} >>> _format_counts([[1, 0, 0], [0, 1, 0], [1, 0, 0]], {0: {2}, 1: {1}, 2: {0}}) {'0x4': 2, '0x2': 1} """ return dict(Counter(hex(_shot_to_int(shot, qubit_to_bit)) for shot in samples))
https://github.com/qiskit-community/qiskit-aqt-provider
qiskit-community
# This code is part of Qiskit. # # (C) Copyright Alpine Quantum Technologies GmbH 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. from collections.abc import Iterator, Mapping from typing import Any, Optional import annotated_types import pydantic as pdt from typing_extensions import Self, override class AQTOptions(pdt.BaseModel, Mapping[str, Any]): """Options for AQT resources. This is a typed drop-in replacement for :class:`qiskit.providers.Options`. Options can be set on a backend globally or on a per-job basis. To update an option globally, set the corresponding attribute in the backend's :attr:`options <qiskit_aqt_provider.aqt_resource._ResourceBase.options>` attribute: >>> import qiskit >>> from qiskit_aqt_provider import AQTProvider >>> >>> backend = AQTProvider("").get_backend("offline_simulator_no_noise") >>> >>> qc = qiskit.QuantumCircuit(1) >>> _ = qc.rx(3.14, 0) >>> _ = qc.measure_all() >>> qc = qiskit.transpile(qc, backend) >>> >>> backend.options.shots = 50 >>> result = backend.run(qc).result() >>> sum(result.get_counts().values()) 50 Option overrides can also be applied on a per-job basis, as keyword arguments to :meth:`AQTResource.run <qiskit_aqt_provider.aqt_resource.AQTResource.run>` or :meth:`AQTDirectAccessResource.run <qiskit_aqt_provider.aqt_resource.AQTDirectAccessResource.run>`: >>> backend.options.shots 50 >>> result = backend.run(qc, shots=100).result() >>> sum(result.get_counts().values()) 100 """ model_config = pdt.ConfigDict(extra="forbid", validate_assignment=True) # Qiskit generic: shots: int = pdt.Field(ge=1, le=2000, default=100) """Number of repetitions per circuit.""" memory: bool = False """Whether to return the sequence of memory states (readout) for each shot. See :meth:`qiskit.result.Result.get_memory` for details.""" # AQT-specific: query_period_seconds: float = pdt.Field(ge=0.1, default=1.0) """Elapsed time between queries to the cloud portal when waiting for results, in seconds.""" query_timeout_seconds: Optional[float] = None """Maximum time to wait for results of a single job, in seconds.""" with_progress_bar: bool = True """Whether to display a progress bar when waiting for results from a single job. When enabled, the progress bar is written to :data:`sys.stderr`. """ @pdt.field_validator("query_timeout_seconds") @classmethod def validate_timeout(cls, value: Optional[float], info: pdt.ValidationInfo) -> Optional[float]: """Enforce that the timeout, if set, is strictly positive.""" if value is not None and value <= 0.0: raise ValueError(f"{info.field_name} must be None or > 0.") return value def update_options(self, **kwargs: Any) -> Self: """Update options by name. .. tip:: This is exposed for compatibility with :class:`qiskit.providers.Options`. The preferred way of updating options is by direct (validated) assignment. """ update = self.model_dump() update.update(kwargs) for key, value in self.model_validate(update).model_dump().items(): setattr(self, key, value) return self # Mapping[str, Any] implementation, for compatibility with qiskit.providers.Options @override def __len__(self) -> int: """Number of options.""" return len(self.model_fields) @override def __iter__(self) -> Iterator[Any]: # type: ignore[override] """Iterate over option names.""" return iter(self.model_fields) @override def __getitem__(self, name: str) -> Any: """Get the value for a given option.""" return self.__dict__[name] # Convenience methods @classmethod def max_shots(cls) -> int: """Maximum number of repetitions per circuit.""" for metadata in cls.model_fields["shots"].metadata: if isinstance(metadata, annotated_types.Le): return int(str(metadata.le)) if isinstance(metadata, annotated_types.Lt): # pragma: no cover return int(str(metadata.lt)) - 1 raise ValueError("No upper bound found for 'shots'.") # pragma: no cover class AQTDirectAccessOptions(AQTOptions): """Options for AQT direct-access resources.""" shots: int = pdt.Field(ge=1, le=200, default=100) """Number of repetitions per circuit."""
https://github.com/qiskit-community/qiskit-aqt-provider
qiskit-community
# This code is part of Qiskit. # # (C) Copyright IBM 2019, Alpine Quantum Technologies GmbH 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. import typing import warnings from dataclasses import dataclass from typing import ( TYPE_CHECKING, Any, Generic, Optional, TypeVar, Union, ) from uuid import UUID import httpx from qiskit import QuantumCircuit from qiskit.circuit.library import RXGate, RXXGate, RZGate from qiskit.circuit.measure import Measure from qiskit.circuit.parameter import Parameter from qiskit.providers import BackendV2 as Backend from qiskit.providers import Options as QiskitOptions from qiskit.providers.models import BackendConfiguration from qiskit.transpiler import Target from qiskit_aer import AerJob, AerSimulator, noise from typing_extensions import override from qiskit_aqt_provider import api_models, api_models_direct from qiskit_aqt_provider.aqt_job import AQTDirectAccessJob, AQTJob from qiskit_aqt_provider.aqt_options import AQTDirectAccessOptions, AQTOptions from qiskit_aqt_provider.circuit_to_aqt import aqt_to_qiskit_circuit if TYPE_CHECKING: # pragma: no cover from qiskit_aqt_provider.aqt_provider import AQTProvider TargetT = TypeVar("TargetT", bound=Target) class UnknownOptionWarning(UserWarning): """An unknown option was passed to a backend's :meth:`run <AQTResource.run>` method.""" def make_transpiler_target(target_cls: type[TargetT], num_qubits: int) -> TargetT: """Factory for transpilation targets of AQT resources. Args: target_cls: base class to use for the returned instance. num_qubits: maximum number of qubits supported by the resource. Returns: A Qiskit transpilation target for an AQT resource. """ target: TargetT = target_cls(num_qubits=num_qubits) theta = Parameter("θ") lam = Parameter("λ") # configure the transpiler to use RX/RZ/RXX # the custom scheduling pass rewrites RX to R to comply to the Arnica API format. target.add_instruction(RZGate(lam)) target.add_instruction(RXGate(theta)) target.add_instruction(RXXGate(theta)) target.add_instruction(Measure()) return target _JobType = TypeVar("_JobType", AQTJob, AQTDirectAccessJob) _OptionsType = TypeVar("_OptionsType", bound=AQTOptions) """Resource options model.""" class _ResourceBase(Generic[_OptionsType], Backend): """Common setup for AQT backends.""" def __init__( self, provider: "AQTProvider", name: str, options_type: type[_OptionsType] ) -> None: """Initialize the Qiskit backend. Args: provider: Qiskit provider that owns this backend. name: name of the backend. options_type: options model. Must be default-initializable. """ super().__init__(name=name, provider=provider) num_qubits = 20 self._target = make_transpiler_target(Target, num_qubits) self._options = options_type() self._configuration = BackendConfiguration.from_dict( { "backend_name": name, "backend_version": 2, "url": provider.portal_url, "simulator": True, "local": False, "coupling_map": None, "description": "AQT trapped-ion device simulator", "basis_gates": ["r", "rz", "rxx"], # the actual basis gates "memory": True, "n_qubits": num_qubits, "conditional": False, "max_shots": self._options.max_shots(), "max_experiments": 1, "open_pulse": False, "gates": [ {"name": "rz", "parameters": ["theta"], "qasm_def": "TODO"}, {"name": "r", "parameters": ["theta", "phi"], "qasm_def": "TODO"}, {"name": "rxx", "parameters": ["theta"], "qasm_def": "TODO"}, ], } ) def configuration(self) -> BackendConfiguration: """Legacy Qiskit backend configuration.""" return self._configuration @property def max_circuits(self) -> int: """Maximum number of circuits per batch.""" return 2000 @property def target(self) -> Target: """Transpilation target for this backend.""" return self._target @classmethod def _default_options(cls) -> QiskitOptions: """Default backend options, in Qiskit format.""" options_type = typing.get_args(cls.__orig_bases__[0])[0] return QiskitOptions(**options_type()) @property def options(self) -> _OptionsType: """Configured backend options.""" return self._options def get_scheduling_stage_plugin(self) -> str: """Name of the custom scheduling stage plugin for the Qiskit transpiler.""" return "aqt" def get_translation_stage_plugin(self) -> str: """Name of the custom translation stage plugin for the Qiskit transpiler.""" return "aqt" def _create_job( self, job_type: type[_JobType], circuits: Union[QuantumCircuit, list[QuantumCircuit]], **options: Any, ) -> _JobType: """Initialize a job handle of a given type. Helper function for the ``run()`` method implementations. Args: job_type: type of the job handle to initialize. circuits: circuits to execute when the job is submitted. options: backend options overrides. """ if not isinstance(circuits, list): circuits = [circuits] valid_options = {key: value for key, value in options.items() if key in self.options} unknown_options = set(options) - set(valid_options) if unknown_options: for unknown_option in unknown_options: warnings.warn( f"Option {unknown_option} is not used by this backend", UnknownOptionWarning, stacklevel=2, ) options_copy = self.options.model_copy() options_copy.update_options(**valid_options) return job_type( self, circuits, options_copy, ) class AQTResource(_ResourceBase[AQTOptions]): """Qiskit backend for AQT cloud quantum computing resources. Use :meth:`AQTProvider.get_backend <qiskit_aqt_provider.aqt_provider.AQTProvider.get_backend>` to retrieve backend instances. """ def __init__( self, provider: "AQTProvider", resource_id: api_models.ResourceId, ) -> None: """Initialize the backend. Args: provider: Qiskit provider that owns this backend. resource_id: description of resource to target. """ super().__init__( name=resource_id.resource_id, provider=provider, options_type=AQTOptions, ) self._http_client: httpx.Client = provider._http_client self.resource_id = resource_id def run(self, circuits: Union[QuantumCircuit, list[QuantumCircuit]], **options: Any) -> AQTJob: """Submit circuits for execution on this resource. Args: circuits: circuits to execute options: overrides for this resource's options. Elements should be valid fields of the :class:`AQTOptions <qiskit_aqt_provider.aqt_options.AQTOptions>` model. Unknown fields are ignored with a :class:`UnknownOptionWarning`. Returns: A handle to the submitted job. """ job = self._create_job(AQTJob, circuits, **options) job.submit() return job def submit(self, job: AQTJob) -> UUID: """Submit a quantum circuits job to the AQT resource. .. tip:: This is a low-level method. Use the :meth:`run` method to submit a job and retrieve a :class:`AQTJob <qiskit_aqt_provider.aqt_job.AQTJob>` handle. Args: job: the quantum circuits job to submit to the resource for execution. Returns: The unique identifier of the submitted job. """ resp = self._http_client.post( f"/submit/{self.resource_id.workspace_id}/{self.resource_id.resource_id}", json=job.api_submit_payload.model_dump(), ) resp.raise_for_status() return api_models.Response.model_validate(resp.json()).job.job_id def result(self, job_id: UUID) -> api_models.JobResponse: """Query the result for a specific job. .. tip:: This is a low-level method. Use the :meth:`AQTJob.result <qiskit_aqt_provider.aqt_job.AQTJob.result>` method to retrieve the result of a job described by a :class:`AQTJob <qiskit_aqt_provider.aqt_job.AQTJob>` handle. Parameters: job_id: The unique identifier for the target job. Returns: AQT API payload with the job results. """ resp = self._http_client.get(f"/result/{job_id}") resp.raise_for_status() return api_models.Response.model_validate(resp.json()) class AQTDirectAccessResource(_ResourceBase[AQTDirectAccessOptions]): """Qiskit backend for AQT direct-access quantum computing resources. Use :meth:`AQTProvider.get_direct_access_backend <qiskit_aqt_provider.aqt_provider.AQTProvider.get_direct_access_backend>` to retrieve backend instances. """ def __init__( self, provider: "AQTProvider", base_url: str, ) -> None: """Initialize the backend. Args: provider: Qiskit provider that owns the backend. base_url: URL of the direct-access interface. """ super().__init__( provider=provider, name="direct-access", options_type=AQTDirectAccessOptions, ) self._http_client = api_models.http_client(base_url=base_url, token=provider.access_token) def run( self, circuits: Union[QuantumCircuit, list[QuantumCircuit]], **options: Any ) -> AQTDirectAccessJob: """Prepare circuits for execution on this resource. .. warning:: The circuits are only evaluated during the :meth:`AQTDirectAccessJob.result <qiskit_aqt_provider.aqt_job.AQTDirectAccessJob.result>` call. Args: circuits: circuits to execute options: overrides for this resource's options. Elements should be valid fields of the :class:`AQTOptions <qiskit_aqt_provider.aqt_options.AQTOptions>` model. Unknown fields are ignored with a :class:`UnknownOptionWarning`. Returns: A handle to the prepared job. """ return self._create_job(AQTDirectAccessJob, circuits, **options) def submit(self, circuit: api_models.QuantumCircuit) -> UUID: """Submit a quantum circuit job to the AQT resource. Args: circuit: circuit to evaluate, in API format. Returns: The unique identifier of the submitted job. """ resp = self._http_client.put("/circuit", json=circuit.model_dump()) resp.raise_for_status() return UUID(resp.json()) def result(self, job_id: UUID, *, timeout: Optional[float]) -> api_models_direct.JobResult: """Query the result of a specific job. Block until a result (success or error) is available. Args: job_id: unique identifier of the target job. timeout: query timeout, in seconds. Disabled if `None`. Returns: Job result, as API payload. """ resp = self._http_client.get(f"/circuit/result/{job_id}", timeout=timeout) resp.raise_for_status() return api_models_direct.JobResult.model_validate(resp.json()) def qubit_states_from_int(state: int, num_qubits: int) -> list[int]: """Convert the Qiskit state representation to the AQT states samples one. Args: state: Qiskit quantum register state representation num_qubits: number of qubits in the register. Returns: AQT qubit states representation. Raises: ValueError: the passed state is too large for the passed register size. Examples: >>> qubit_states_from_int(0, 3) [0, 0, 0] >>> qubit_states_from_int(0b11, 3) [1, 1, 0] >>> qubit_states_from_int(0b01, 3) [1, 0, 0] >>> qubit_states_from_int(123, 7) [1, 1, 0, 1, 1, 1, 1] >>> qubit_states_from_int(123, 3) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: Cannot represent state=123 on num_qubits=3. """ if state.bit_length() > num_qubits: raise ValueError(f"Cannot represent {state=} on {num_qubits=}.") return [(state >> qubit) & 1 for qubit in range(num_qubits)] @dataclass(frozen=True) class SimulatorJob: """Data for a job running on a local simulator.""" job: AerJob """Simulation backend job handle.""" circuits: list[QuantumCircuit] """Quantum circuits to evaluate.""" shots: int """Number of repetitions of each circuit.""" @property def job_id(self) -> UUID: """The job's unique identifier.""" return UUID(hex=self.job.job_id()) class OfflineSimulatorResource(AQTResource): """AQT-compatible offline simulator resource. Offline simulators expose the same interface and restrictions as hardware backends. If `with_noise_model` is true, a noise model approximating that of AQT hardware backends is used. .. tip:: The simulator backend is provided by `Qiskit Aer <https://qiskit.github.io/qiskit-aer/>`_. The Qiskit Aer resource is exposed for detailed detuning as the ``OfflineSimulatorResource.simulator`` attribute. """ def __init__( self, provider: "AQTProvider", resource_id: api_models.ResourceId, with_noise_model: bool, ) -> None: """Initialize an offline simulator resource. Args: provider: Qiskit provider that owns this backend. resource_id: identification of the offline simulator resource. with_noise_model: whether to configure a noise model in the simulator backend. """ assert resource_id.resource_type == "offline_simulator" # noqa: S101 super().__init__( provider, resource_id=resource_id, ) self.job: Optional[SimulatorJob] = None if not with_noise_model: noise_model = None else: # the transpiler lowers all operations to the gate set supported by the AQT API, # not to the resource target's one. noise_model = noise.NoiseModel(basis_gates=["r", "rz", "rxx"]) noise_model.add_all_qubit_quantum_error(noise.depolarizing_error(0.003, 1), ["r"]) noise_model.add_all_qubit_quantum_error(noise.depolarizing_error(0.01, 2), ["rxx"]) self.simulator = AerSimulator(method="statevector", noise_model=noise_model) @property def with_noise_model(self) -> bool: """Whether the simulator includes a noise model.""" return self.simulator.options.noise_model is not None @override def submit(self, job: AQTJob) -> UUID: """Submit a job for execution on the simulator. .. tip:: This is a low-level method. Use the :meth:`AQTResource.run()` method to submit a job and retrieve a :class:`AQTJob <qiskit_aqt_provider.aqt_job.AQTJob>` handle. Args: job: quantum circuits job to submit to the simulator. Returns: Unique identifier of the simulator job. """ # Use the API payload such that the memory map is the same as that # of the remote devices. circuits = [ aqt_to_qiskit_circuit(circuit.quantum_circuit, circuit.number_of_qubits) for circuit in job.api_submit_payload.payload.circuits ] self.job = SimulatorJob( job=self.simulator.run(circuits, shots=job.options.shots), circuits=job.circuits, shots=job.options.shots, ) return self.job.job_id @override def result(self, job_id: UUID) -> api_models.JobResponse: """Query results for a simulator job. .. tip:: This is a low-level method. Use :meth:`AQTJob.result() <qiskit_aqt_provider.aqt_job.AQTJob.result>` instead. Args: job_id: identifier of the job to retrieve results for. Returns: AQT API payload with the job results. Raises: UnknownJobError: ``job_id`` doesn't correspond to a simulator job on this resource. """ if self.job is None or job_id != self.job.job_id: raise api_models.UnknownJobError(str(job_id)) qiskit_result = self.job.job.result() results: dict[str, list[list[int]]] = {} for circuit_index, circuit in enumerate(self.job.circuits): samples: list[list[int]] = [] # Use data()["counts"] instead of get_counts() to access the raw counts # in hexadecimal format. counts: dict[str, int] = qiskit_result.data(circuit_index)["counts"] for hex_state, occurrences in counts.items(): samples.extend( [ qubit_states_from_int(int(hex_state, 16), circuit.num_qubits) for _ in range(occurrences) ] ) results[str(circuit_index)] = samples return api_models.Response.finished( job_id=job_id, workspace_id=self.resource_id.workspace_id, resource_id=self.resource_id.resource_id, results=results, )
https://github.com/qiskit-community/qiskit-aqt-provider
qiskit-community
# This code is part of Qiskit. # # (C) Copyright IBM 2019, Alpine Quantum Technologies GmbH 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. from numpy import pi from qiskit import QuantumCircuit from typing_extensions import assert_never from qiskit_aqt_provider import api_models, api_models_generated def qiskit_to_aqt_circuit(circuit: QuantumCircuit) -> api_models.Circuit: """Convert a Qiskit `QuantumCircuit` into a payload for AQT's quantum_circuit job type. Args: circuit: Qiskit circuit to convert. Returns: AQT API circuit payload. """ ops: list[api_models.OperationModel] = [] num_measurements = 0 for instruction in circuit.data: if instruction.operation.name != "measure" and num_measurements > 0: raise ValueError( "Measurement operations can only be located at the end of the circuit." ) if instruction.operation.name == "rz": (phi,) = instruction.operation.params (qubit,) = instruction.qubits ops.append( api_models.Operation.rz( phi=float(phi) / pi, qubit=circuit.find_bit(qubit).index, ) ) elif instruction.operation.name == "r": theta, phi = instruction.operation.params (qubit,) = instruction.qubits ops.append( api_models.Operation.r( phi=float(phi) / pi, theta=float(theta) / pi, qubit=circuit.find_bit(qubit).index, ) ) elif instruction.operation.name == "rxx": (theta,) = instruction.operation.params q0, q1 = instruction.qubits ops.append( api_models.Operation.rxx( theta=float(theta) / pi, qubits=[circuit.find_bit(q0).index, circuit.find_bit(q1).index], ) ) elif instruction.operation.name == "measure": num_measurements += 1 elif instruction.operation.name == "barrier": continue else: raise ValueError( f"Operation '{instruction.operation.name}' not in basis gate set: {{rz, r, rxx}}" ) if not num_measurements: raise ValueError("Circuit must have at least one measurement operation.") ops.append(api_models.Operation.measure()) return api_models.Circuit(root=ops) def aqt_to_qiskit_circuit(circuit: api_models.Circuit, number_of_qubits: int) -> QuantumCircuit: """Convert an AQT API quantum circuit payload to an equivalent Qiskit representation. Args: circuit: payload to convert number_of_qubits: size of the quantum register to use for the converted circuit. Returns: A :class:`QuantumCircuit <qiskit.circuit.quantumcircuit.QuantumCircuit>` equivalent to the passed circuit payload. """ qiskit_circuit = QuantumCircuit(number_of_qubits) for operation in circuit.root: if isinstance(operation.root, api_models_generated.GateRZ): qiskit_circuit.rz(operation.root.phi * pi, operation.root.qubit) elif isinstance(operation.root, api_models_generated.GateR): qiskit_circuit.r( operation.root.theta * pi, operation.root.phi * pi, operation.root.qubit, ) elif isinstance(operation.root, api_models_generated.GateRXX): qiskit_circuit.rxx( operation.root.theta * pi, *[mod.root for mod in operation.root.qubits] ) elif isinstance(operation.root, api_models_generated.Measure): qiskit_circuit.measure_all() else: assert_never(operation.root) # pragma: no cover return qiskit_circuit def circuits_to_aqt_job(circuits: list[QuantumCircuit], shots: int) -> api_models.SubmitJobRequest: """Convert a list of circuits to the corresponding AQT API job request payload. Args: circuits: circuits to execute shots: number of repetitions per circuit. Returns: JobSubmission: AQT API payload for submitting the quantum circuits job. """ return api_models.SubmitJobRequest( job_type="quantum_circuit", label="qiskit", payload=api_models.QuantumCircuits( circuits=[ api_models.QuantumCircuit( repetitions=shots, quantum_circuit=qiskit_to_aqt_circuit(circuit), number_of_qubits=circuit.num_qubits, ) for circuit in circuits ] ), )
https://github.com/qiskit-community/qiskit-aqt-provider
qiskit-community
# This code is part of Qiskit. # # (C) Copyright Alpine Quantum Technologies 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. import base64 import io import typing from pathlib import Path from typing import Any, Optional, Union import platformdirs import pydantic as pdt from pydantic import ConfigDict, GetCoreSchemaHandler from pydantic_core import CoreSchema, core_schema from qiskit import qpy from qiskit.circuit import QuantumCircuit from typing_extensions import Self from qiskit_aqt_provider.api_models import ResourceId from qiskit_aqt_provider.aqt_options import AQTOptions from qiskit_aqt_provider.utils import map_exceptions from qiskit_aqt_provider.versions import QISKIT_AQT_PROVIDER_VERSION class JobNotFoundError(Exception): """A job was not found in persistent storage.""" class Circuits: """Custom Pydantic type to persist and restore lists of Qiskit circuits. Serialization of :class:`QuantumCircuit <qiskit.circuit.QuantumCircuit>` instances is provided by :mod:`qiskit.qpy`. """ def __init__(self, circuits: list[QuantumCircuit]) -> None: """Initialize a container filled with the given circuits.""" self.circuits = circuits @classmethod def __get_pydantic_core_schema__( cls, source_type: Any, handler: GetCoreSchemaHandler ) -> CoreSchema: """Setup custom validator, to turn this class into a pydantic model.""" return core_schema.no_info_plain_validator_function(function=cls.validate) @classmethod def validate(cls, value: Union[Self, str]) -> Self: """Parse the base64-encoded :mod:`qiskit.qpy` representation of a list of quantum circuits. Because initializing a Pydantic model also triggers validation, this parser accepts already formed instances of this class and returns them unvalidated. """ if isinstance(value, Circuits): # self bypass return typing.cast(Self, value) if not isinstance(value, str): raise ValueError(f"Expected string, received {type(value)}") data = base64.b64decode(value.encode("ascii")) buf = io.BytesIO(data) obj = qpy.load(buf) if not isinstance(obj, list): obj = [obj] for n, qc in enumerate(obj): if not isinstance(qc, QuantumCircuit): raise ValueError(f"Object at position {n} is not a QuantumCircuit: {type(qc)}") return cls(circuits=obj) @classmethod def json_encoder(cls, value: Self) -> str: """Return a base64-encoded QPY representation of the held list of circuits.""" buf = io.BytesIO() qpy.dump(value.circuits, buf) return base64.b64encode(buf.getvalue()).decode("ascii") class Job(pdt.BaseModel): """Model for job persistence in local storage.""" model_config = ConfigDict(frozen=True, json_encoders={Circuits: Circuits.json_encoder}) resource: ResourceId circuits: Circuits options: AQTOptions @classmethod @map_exceptions(JobNotFoundError, source_exc=(FileNotFoundError,)) def restore(cls, job_id: str, store_path: Path) -> Self: """Load data for a job by ID from local storage. Args: job_id: identifier of the job to restore. store_path: path to the local storage directory. Raises: JobNotFoundError: no job with the given identifier is stored in the local storage. """ data = cls.filepath(job_id, store_path).read_text("utf-8") return cls.model_validate_json(data) def persist(self, job_id: str, store_path: Path) -> Path: """Persist the job data to the local storage. Args: job_id: storage key for this job data. store_path: path to the local storage directory. Returns: The path of the persisted data file. """ filepath = self.filepath(job_id, store_path) filepath.write_text(self.model_dump_json(), "utf-8") return filepath @classmethod def remove_from_store(cls, job_id: str, store_path: Path) -> None: """Remove persisted job data from the local storage. This function also succeeds if there is no data under `job_id`. Args: job_id: storage key for the data to delete. store_path: path to the local storage directory. """ cls.filepath(job_id, store_path).unlink(missing_ok=True) @classmethod def filepath(cls, job_id: str, store_path: Path) -> Path: """Path of the file to store data under a given key in local storage. Args: job_id: storage key for the data. store_path: path to the local storage directory. """ return store_path / job_id def get_store_path(override: Optional[Path] = None) -> Path: """Resolve the local persistence store path. By default, this is the user cache directory for this package. Different cache directories are used for different package versions. Args: override: if given, return this override instead of the default path. Returns: Path for the persistence store. Ensured to exist. """ if override is not None: override.mkdir(parents=True, exist_ok=True) return override return Path( platformdirs.user_cache_dir( "qiskit_aqt_provider", version=QISKIT_AQT_PROVIDER_VERSION, ensure_exists=True, ) )
https://github.com/qiskit-community/qiskit-aqt-provider
qiskit-community
# This code is part of Qiskit. # # (C) Copyright Alpine Quantum Technologies GmbH 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. import math from collections.abc import Sequence from dataclasses import dataclass from typing import Final, Optional import numpy as np from qiskit import QuantumCircuit from qiskit.circuit import Gate, Instruction from qiskit.circuit.library import RGate, RXGate, RXXGate, RZGate from qiskit.circuit.tools import pi_check from qiskit.dagcircuit import DAGCircuit from qiskit.transpiler import Target from qiskit.transpiler.basepasses import BasePass, TransformationPass from qiskit.transpiler.exceptions import TranspilerError from qiskit.transpiler.passes import Decompose, Optimize1qGatesDecomposition from qiskit.transpiler.passmanager import PassManager from qiskit.transpiler.passmanager_config import PassManagerConfig from qiskit.transpiler.preset_passmanagers import common from qiskit.transpiler.preset_passmanagers.plugin import PassManagerStagePlugin from qiskit_aqt_provider.utils import map_exceptions class UnboundParametersTarget(Target): """Marker class for transpilation targets to disable passes that require bound parameters.""" def bound_pass_manager(target: Target) -> PassManager: """Transpilation passes to apply on circuits after the parameters are bound. This assumes that a preset pass manager was applied to the unbound circuits (by setting the target to an instance of `UnboundParametersTarget`). Args: target: transpilation target. """ return PassManager( [ # wrap the Rxx angles WrapRxxAngles(), # decompose the substituted Rxx gates Decompose([f"{WrapRxxAngles.SUBSTITUTE_GATE_NAME}*"]), # collapse the single qubit runs as ZXZ Optimize1qGatesDecomposition(target=target), # wrap the Rx angles, rewrite as R RewriteRxAsR(), ] ) def rewrite_rx_as_r(theta: float) -> Instruction: """Instruction equivalent to Rx(θ) as R(θ, φ) with θ ∈ [0, π] and φ ∈ [0, 2π].""" theta = math.atan2(math.sin(theta), math.cos(theta)) phi = math.pi if theta < 0.0 else 0.0 return RGate(abs(theta), phi) class RewriteRxAsR(TransformationPass): """Rewrite Rx(θ) as R(θ, φ) with θ ∈ [0, π] and φ ∈ [0, 2π].""" @map_exceptions(TranspilerError) def run(self, dag: DAGCircuit) -> DAGCircuit: """Apply the transformation pass.""" for node in dag.gate_nodes(): if node.name == "rx": (theta,) = node.op.params dag.substitute_node(node, rewrite_rx_as_r(float(theta))) return dag class AQTSchedulingPlugin(PassManagerStagePlugin): """Scheduling stage plugin for the :mod:`qiskit.transpiler`. If the transpilation target is not :class:`UnboundParametersTarget`, register a :class:`RewriteRxAsR` pass irrespective of the optimization level. """ def pass_manager( self, pass_manager_config: PassManagerConfig, optimization_level: Optional[int] = None, # noqa: ARG002 ) -> PassManager: """Pass manager for the scheduling phase.""" if isinstance(pass_manager_config.target, UnboundParametersTarget): return PassManager([]) passes: list[BasePass] = [ # The Qiskit Target declares RX/RZ as basis gates. # This allows decomposing any run of rotations into the ZXZ form, taking # advantage of the free Z rotations. # Since the API expects R/RZ as single-qubit operations, # we rewrite all RX gates as R gates after optimizations have been performed. RewriteRxAsR(), ] return PassManager(passes) @dataclass(frozen=True) class CircuitInstruction: """Substitute for `qiskit.circuit.CircuitInstruction`. Contrary to its Qiskit counterpart, this type allows passing the qubits as integers. """ gate: Gate qubits: tuple[int, ...] def _rxx_positive_angle(theta: float) -> list[CircuitInstruction]: """List of instructions equivalent to RXX(θ) with θ >= 0.""" rxx = CircuitInstruction(RXXGate(abs(theta)), qubits=(0, 1)) if theta >= 0: return [rxx] return [ CircuitInstruction(RZGate(math.pi), (0,)), rxx, CircuitInstruction(RZGate(math.pi), (0,)), ] def _emit_rxx_instruction(theta: float, instructions: list[CircuitInstruction]) -> Instruction: """Collect the passed instructions into a single one labeled 'Rxx(θ)'.""" qc = QuantumCircuit(2, name=f"{WrapRxxAngles.SUBSTITUTE_GATE_NAME}({pi_check(theta)})") for instruction in instructions: qc.append(instruction.gate, instruction.qubits) return qc.to_instruction() def wrap_rxx_angle(theta: float) -> Instruction: """Instruction equivalent to RXX(θ) with θ ∈ [0, π/2].""" # fast path if -π/2 <= θ <= π/2 if abs(theta) <= math.pi / 2: operations = _rxx_positive_angle(theta) return _emit_rxx_instruction(theta, operations) # exploit 2-pi periodicity of Rxx theta %= 2 * math.pi if abs(theta) <= math.pi / 2: operations = _rxx_positive_angle(theta) elif abs(theta) <= 3 * math.pi / 2: corrected_angle = theta - np.sign(theta) * math.pi operations = [ CircuitInstruction(RXGate(math.pi), (0,)), CircuitInstruction(RXGate(math.pi), (1,)), ] operations.extend(_rxx_positive_angle(corrected_angle)) else: corrected_angle = theta - np.sign(theta) * 2 * math.pi operations = _rxx_positive_angle(corrected_angle) return _emit_rxx_instruction(theta, operations) class WrapRxxAngles(TransformationPass): """Wrap Rxx angles to [0, π/2].""" SUBSTITUTE_GATE_NAME: Final = "Rxx-wrapped" @map_exceptions(TranspilerError) def run(self, dag: DAGCircuit) -> DAGCircuit: """Apply the transformation pass.""" for node in dag.gate_nodes(): if node.name == "rxx": (theta,) = node.op.params if 0 <= float(theta) <= math.pi / 2: continue rxx = wrap_rxx_angle(float(theta)) dag.substitute_node(node, rxx) return dag class AQTTranslationPlugin(PassManagerStagePlugin): """Translation stage plugin for the :mod:`qiskit.transpiler`. If the transpilation target is not :class:`UnboundParametersTarget`, register a :class:`WrapRxxAngles` pass after the preset pass irrespective of the optimization level. """ def pass_manager( self, pass_manager_config: PassManagerConfig, optimization_level: Optional[int] = None, ) -> PassManager: """Pass manager for the translation stage.""" translation_pm = common.generate_translation_passmanager( target=pass_manager_config.target, basis_gates=pass_manager_config.basis_gates, approximation_degree=pass_manager_config.approximation_degree, coupling_map=pass_manager_config.coupling_map, backend_props=pass_manager_config.backend_properties, unitary_synthesis_method=pass_manager_config.unitary_synthesis_method, unitary_synthesis_plugin_config=pass_manager_config.unitary_synthesis_plugin_config, hls_config=pass_manager_config.hls_config, ) if isinstance(pass_manager_config.target, UnboundParametersTarget): return translation_pm passes: Sequence[BasePass] = [ WrapRxxAngles(), ] + ( [ Decompose([f"{WrapRxxAngles.SUBSTITUTE_GATE_NAME}*"]), ] if optimization_level is None or optimization_level == 0 else [] ) return translation_pm + PassManager(passes)
https://github.com/qiskit-community/qiskit-aqt-provider
qiskit-community
# This code is part of Qiskit. # # (C) Copyright Alpine Quantum Technologies GmbH 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. from copy import copy from typing import Any, Optional from qiskit.primitives import BackendSampler from qiskit_aqt_provider import transpiler_plugin from qiskit_aqt_provider.aqt_resource import AQTResource, make_transpiler_target class AQTSampler(BackendSampler): """:class:`BaseSamplerV1 <qiskit.primitives.BaseSamplerV1>` primitive for AQT backends.""" _backend: AQTResource def __init__( self, backend: AQTResource, options: Optional[dict[str, Any]] = None, skip_transpilation: bool = False, ) -> None: """Initialize a ``Sampler`` primitive using an AQT backend. Args: backend: AQT resource to evaluate circuits on. options: options passed through to the underlying :class:`BackendSampler <qiskit.primitives.BackendSampler>`. skip_transpilation: if :data:`True`, do not transpile circuits before passing them to the execution backend. Examples: Initialize a :class:`Sampler <qiskit.primitives.BaseSamplerV1>` primitive on a AQT offline simulator: >>> import qiskit >>> from qiskit_aqt_provider import AQTProvider >>> from qiskit_aqt_provider.primitives import AQTSampler >>> >>> backend = AQTProvider("").get_backend("offline_simulator_no_noise") >>> sampler = AQTSampler(backend) Configuring :class:`options <qiskit_aqt_provider.aqt_options.AQTOptions>` on the backend will affect all circuit evaluations triggered by the `Sampler` primitive: >>> qc = qiskit.QuantumCircuit(2) >>> _ = qc.cx(0, 1) >>> _ = qc.measure_all() >>> >>> sampler.run(qc).result().metadata[0]["shots"] 100 >>> backend.options.shots = 123 >>> sampler.run(qc).result().metadata[0]["shots"] 123 The same effect is achieved by passing options to the :class:`AQTSampler` initializer: >>> sampler = AQTSampler(backend, options={"shots": 120}) >>> sampler.run(qc).result().metadata[0]["shots"] 120 Passing the option in the :meth:`AQTSampler.run <qiskit.primitives.BaseSamplerV1.run>` call restricts the effect to a single evaluation: >>> sampler.run(qc, shots=130).result().metadata[0]["shots"] 130 >>> sampler.run(qc).result().metadata[0]["shots"] 120 """ # Signal the transpiler to disable passes that require bound # parameters. # This allows the underlying sampler to apply most of # the transpilation passes, and cache the results. mod_backend = copy(backend) mod_backend._target = make_transpiler_target( transpiler_plugin.UnboundParametersTarget, backend.num_qubits ) # if `with_progress_bar` is not explicitly set in the options, disable it options_copy = (options or {}).copy() options_copy.update(with_progress_bar=options_copy.get("with_progress_bar", False)) super().__init__( mod_backend, bound_pass_manager=transpiler_plugin.bound_pass_manager(mod_backend.target), options=options_copy, skip_transpilation=skip_transpilation, ) @property def backend(self) -> AQTResource: """Computing resource used for circuit evaluation.""" return self._backend
https://github.com/qiskit-community/qiskit-aqt-provider
qiskit-community
# This code is part of Qiskit. # # (C) Alpine Quantum Technologies GmbH 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 helpers for quantum circuits.""" import math import qiskit.circuit.random from qiskit import QuantumCircuit from qiskit.quantum_info.operators import Operator def assert_circuits_equal(result: QuantumCircuit, expected: QuantumCircuit) -> None: """Assert result == expected, pretty-printing the circuits if they don't match.""" msg = f"\nexpected:\n{expected}\nresult:\n{result}" assert result == expected, msg # noqa: S101 def assert_circuits_equal_ignore_global_phase( result: QuantumCircuit, expected: QuantumCircuit ) -> None: """Assert result == expected, ignoring the value of the global phase.""" result_copy = result.copy() result_copy.global_phase = 0.0 expected_copy = expected.copy() expected_copy.global_phase = 0.0 assert_circuits_equal(result_copy, expected_copy) def assert_circuits_equivalent(result: QuantumCircuit, expected: QuantumCircuit) -> None: """Assert that the passed circuits are equivalent up to a global phase.""" msg = f"\nexpected:\n{expected}\nresult:\n{result}" assert Operator(expected).equiv(Operator(result)), msg # noqa: S101 def empty_circuit(num_qubits: int, with_final_measurement: bool = True) -> QuantumCircuit: """An empty circuit, with the given number of qubits.""" qc = QuantumCircuit(num_qubits) if with_final_measurement: qc.measure_all() return qc def random_circuit( num_qubits: int, *, seed: int = 1234, with_final_measurement: bool = True ) -> QuantumCircuit: """A random circuit, with depth equal to the number of qubits.""" qc = qiskit.circuit.random.random_circuit( num_qubits, num_qubits, seed=seed, ) if with_final_measurement: qc.measure_all() return qc def qft_circuit(num_qubits: int) -> QuantumCircuit: """N-qubits quantum Fourier transform. Source: Nielsen & Chuang, Quantum Computation and Quantum Information. """ qc = QuantumCircuit(num_qubits) for qubit in range(num_qubits - 1, -1, -1): qc.h(qubit) for k in range(1, qubit + 1): qc.cp(math.pi / 2**k, qubit - k, qubit) for qubit in range(num_qubits // 2): qc.swap(qubit, (num_qubits - 1) - qubit) return qc
https://github.com/qiskit-community/qiskit-aqt-provider
qiskit-community
# This code is part of Qiskit. # # (C) Alpine Quantum Technologies GmbH 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. """Dummy resources for testing purposes.""" import enum import random import time import uuid from dataclasses import dataclass, field from typing import Optional from qiskit import QuantumCircuit from typing_extensions import assert_never, override from qiskit_aqt_provider import api_models from qiskit_aqt_provider.aqt_job import AQTJob from qiskit_aqt_provider.aqt_provider import AQTProvider from qiskit_aqt_provider.aqt_resource import AQTDirectAccessResource, AQTResource class JobStatus(enum.Enum): """AQT job lifecycle labels.""" QUEUED = enum.auto() ONGOING = enum.auto() FINISHED = enum.auto() ERROR = enum.auto() CANCELLED = enum.auto() @dataclass class TestJob: # pylint: disable=too-many-instance-attributes """Job state holder for the TestResource.""" circuits: list[QuantumCircuit] shots: int status: JobStatus = JobStatus.QUEUED job_id: uuid.UUID = field(default_factory=lambda: uuid.uuid4()) time_queued: float = field(default_factory=time.time) time_submitted: float = 0.0 time_finished: float = 0.0 error_message: str = "error" results: dict[str, list[list[int]]] = field(init=False) workspace: str = field(default="test-workspace", init=False) resource: str = field(default="test-resource", init=False) def __post_init__(self) -> None: """Calculate derived quantities.""" self.results = { str(circuit_index): [ random.choices([0, 1], k=circuit.num_clbits) for _ in range(self.shots) ] for circuit_index, circuit in enumerate(self.circuits) } def submit(self) -> None: """Submit the job for execution.""" self.time_submitted = time.time() self.status = JobStatus.ONGOING def finish(self) -> None: """The job execution finished successfully.""" self.time_finished = time.time() self.status = JobStatus.FINISHED def error(self) -> None: """The job execution triggered an error.""" self.time_finished = time.time() self.status = JobStatus.ERROR def cancel(self) -> None: """The job execution was cancelled.""" self.time_finished = time.time() self.status = JobStatus.CANCELLED def response_payload(self) -> api_models.JobResponse: """AQT API-compatible response for the current job status.""" if self.status is JobStatus.QUEUED: return api_models.Response.queued( job_id=self.job_id, workspace_id=self.workspace, resource_id=self.resource, ) if self.status is JobStatus.ONGOING: return api_models.Response.ongoing( job_id=self.job_id, workspace_id=self.workspace, resource_id=self.resource, finished_count=1, ) if self.status is JobStatus.FINISHED: return api_models.Response.finished( job_id=self.job_id, workspace_id=self.workspace, resource_id=self.resource, results=self.results, ) if self.status is JobStatus.ERROR: return api_models.Response.error( job_id=self.job_id, workspace_id=self.workspace, resource_id=self.resource, message=self.error_message, ) if self.status is JobStatus.CANCELLED: return api_models.Response.cancelled( job_id=self.job_id, workspace_id=self.workspace, resource_id=self.resource ) assert_never(self.status) # pragma: no cover class TestResource(AQTResource): # pylint: disable=too-many-instance-attributes """AQT computing resource with hooks for triggering different execution scenarios.""" __test__ = False # disable pytest collection def __init__( # noqa: PLR0913 self, *, min_queued_duration: float = 0.0, min_running_duration: float = 0.0, always_cancel: bool = False, always_error: bool = False, error_message: str = "", ) -> None: """Initialize the testing resource. Args: min_queued_duration: minimum time in seconds spent by all jobs in the QUEUED state min_running_duration: minimum time in seconds spent by all jobs in the ONGOING state always_cancel: always cancel the jobs directly after submission always_error: always finish execution with an error error_message: the error message returned by failed jobs. Implies `always_error`. """ super().__init__( AQTProvider(""), resource_id=api_models.ResourceId( workspace_id="test-workspace", resource_id="test", resource_name="test-resource", resource_type="simulator", ), ) self.job: Optional[TestJob] = None self.min_queued_duration = min_queued_duration self.min_running_duration = min_running_duration self.always_cancel = always_cancel self.always_error = always_error or error_message self.error_message = error_message or str(uuid.uuid4()) @override def submit(self, job: AQTJob) -> uuid.UUID: """Handle an execution request for a given job. If the backend always cancels job, the job is immediately cancelled. Otherwise, register the passed job as the active one on the backend. """ test_job = TestJob(job.circuits, job.options.shots, error_message=self.error_message) if self.always_cancel: test_job.cancel() self.job = test_job return test_job.job_id @override def result(self, job_id: uuid.UUID) -> api_models.JobResponse: """Handle a results request for a given job. Apply the logic configured when initializing the backend to build an API result payload. Raises: UnknownJobError: the given job ID doesn't correspond to the active job's ID. """ if self.job is None or self.job.job_id != job_id: # pragma: no cover raise api_models.UnknownJobError(str(job_id)) now = time.time() if ( self.job.status is JobStatus.QUEUED and (now - self.job.time_queued) > self.min_queued_duration ): self.job.submit() if ( self.job.status is JobStatus.ONGOING and (now - self.job.time_submitted) > self.min_running_duration ): if self.always_error: self.job.error() else: self.job.finish() return self.job.response_payload() class DummyResource(AQTResource): """A non-functional resource, for testing purposes.""" def __init__(self, token: str) -> None: """Initialize the dummy backend.""" super().__init__( AQTProvider(token), resource_id=api_models.ResourceId( workspace_id="dummy", resource_id="dummy", resource_name="dummy", resource_type="simulator", ), ) class DummyDirectAccessResource(AQTDirectAccessResource): """A non-functional direct-access resource, for testing purposes.""" def __init__(self, token: str) -> None: """Initialize the dummy backend.""" super().__init__( AQTProvider(token), base_url="direct-access-example.aqt.eu:6020", )
https://github.com/qiskit-community/qiskit-aqt-provider
qiskit-community
# This code is part of Qiskit. # # (C) Copyright IBM 2019, Alpine Quantum Technologies 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. from math import pi import pytest import qiskit from pydantic import ValidationError from qiskit import QuantumCircuit from qiskit_aqt_provider import api_models from qiskit_aqt_provider.aqt_resource import AQTResource from qiskit_aqt_provider.circuit_to_aqt import ( aqt_to_qiskit_circuit, circuits_to_aqt_job, qiskit_to_aqt_circuit, ) from qiskit_aqt_provider.test.circuits import ( assert_circuits_equal_ignore_global_phase, assert_circuits_equivalent, empty_circuit, qft_circuit, random_circuit, ) def test_no_circuit() -> None: """Cannot convert an empty list of circuits to an AQT job request.""" with pytest.raises(ValidationError): circuits_to_aqt_job([], shots=1) def test_empty_circuit() -> None: """Circuits need at least one measurement operation.""" qc = QuantumCircuit(1) with pytest.raises(ValueError): circuits_to_aqt_job([qc], shots=1) def test_just_measure_circuit() -> None: """Circuits with only measurement operations are valid.""" shots = 100 qc = QuantumCircuit(1) qc.measure_all() expected = api_models.SubmitJobRequest( job_type="quantum_circuit", label="qiskit", payload=api_models.QuantumCircuits( circuits=[ api_models.QuantumCircuit( repetitions=shots, number_of_qubits=1, quantum_circuit=api_models.Circuit(root=[api_models.Operation.measure()]), ), ] ), ) result = circuits_to_aqt_job([qc], shots=shots) assert result == expected def test_valid_circuit() -> None: """A valid circuit with all supported basis gates.""" qc = QuantumCircuit(2) qc.r(pi / 2, 0, 0) qc.rz(pi / 5, 1) qc.rxx(pi / 2, 0, 1) qc.measure_all() result = circuits_to_aqt_job([qc], shots=1) expected = api_models.SubmitJobRequest( job_type="quantum_circuit", label="qiskit", payload=api_models.QuantumCircuits( circuits=[ api_models.QuantumCircuit( number_of_qubits=2, repetitions=1, quantum_circuit=api_models.Circuit( root=[ api_models.Operation.r(theta=0.5, phi=0.0, qubit=0), api_models.Operation.rz(phi=0.2, qubit=1), api_models.Operation.rxx(theta=0.5, qubits=[0, 1]), api_models.Operation.measure(), ] ), ), ] ), ) assert result == expected def test_invalid_gates_in_circuit() -> None: """Circuits must already be in the target basis when they are converted to the AQT wire format. """ qc = QuantumCircuit(1) qc.h(0) # not an AQT-resource basis gate qc.measure_all() with pytest.raises(ValueError, match="not in basis gate set"): circuits_to_aqt_job([qc], shots=1) def test_invalid_measurements() -> None: """Measurement operations can only be located at the end of the circuit.""" qc_invalid = QuantumCircuit(2, 2) qc_invalid.r(pi / 2, 0.0, 0) qc_invalid.measure([0], [0]) qc_invalid.r(pi / 2, 0.0, 1) qc_invalid.measure([1], [1]) with pytest.raises(ValueError, match="at the end of the circuit"): circuits_to_aqt_job([qc_invalid], shots=1) # same circuit as above, but with the measurements at the end is valid qc = QuantumCircuit(2, 2) qc.r(pi / 2, 0.0, 0) qc.r(pi / 2, 0.0, 1) qc.measure([0], [0]) qc.measure([1], [1]) result = circuits_to_aqt_job([qc], shots=1) expected = api_models.SubmitJobRequest( job_type="quantum_circuit", label="qiskit", payload=api_models.QuantumCircuits( circuits=[ api_models.QuantumCircuit( number_of_qubits=2, repetitions=1, quantum_circuit=api_models.Circuit( root=[ api_models.Operation.r(theta=0.5, phi=0.0, qubit=0), api_models.Operation.r(theta=0.5, phi=0.0, qubit=1), api_models.Operation.measure(), ] ), ), ] ), ) assert result == expected def test_convert_multiple_circuits() -> None: """Convert multiple circuits. Check that the order is conserved.""" qc0 = QuantumCircuit(2) qc0.r(pi / 2, 0.0, 0) qc0.rxx(pi / 2, 0, 1) qc0.measure_all() qc1 = QuantumCircuit(1) qc1.r(pi / 4, 0.0, 0) qc1.measure_all() result = circuits_to_aqt_job([qc0, qc1], shots=1) expected = api_models.SubmitJobRequest( job_type="quantum_circuit", label="qiskit", payload=api_models.QuantumCircuits( circuits=[ api_models.QuantumCircuit( number_of_qubits=2, repetitions=1, quantum_circuit=api_models.Circuit( root=[ api_models.Operation.r(theta=0.5, phi=0.0, qubit=0), api_models.Operation.rxx(theta=0.5, qubits=[0, 1]), api_models.Operation.measure(), ] ), ), api_models.QuantumCircuit( number_of_qubits=1, repetitions=1, quantum_circuit=api_models.Circuit( root=[ api_models.Operation.r(theta=0.25, phi=0.0, qubit=0), api_models.Operation.measure(), ] ), ), ], ), ) assert result == expected @pytest.mark.parametrize( "circuit", [ pytest.param(empty_circuit(2, with_final_measurement=False), id="empty-2"), pytest.param(random_circuit(2, with_final_measurement=False), id="random-2"), pytest.param(random_circuit(3, with_final_measurement=False), id="random-3"), pytest.param(random_circuit(5, with_final_measurement=False), id="random-5"), pytest.param(qft_circuit(5), id="qft-5"), ], ) def test_convert_circuit_round_trip( circuit: QuantumCircuit, offline_simulator_no_noise: AQTResource ) -> None: """Check that transpiled qiskit circuits can be round-tripped through the API format.""" trans_qc = qiskit.transpile(circuit, offline_simulator_no_noise) # There's no measurement in the circuit, so unitary operator equality # can be used to check the transpilation result. assert_circuits_equivalent(trans_qc, circuit) # Add the measurement operation to allow conversion to the AQT API format. trans_qc.measure_all() aqt_circuit = qiskit_to_aqt_circuit(trans_qc) trans_qc_back = aqt_to_qiskit_circuit(aqt_circuit, trans_qc.num_qubits) # transpiled circuits can be exactly reconstructed, up to the global # phase which is irrelevant for execution assert_circuits_equal_ignore_global_phase(trans_qc_back, trans_qc)
https://github.com/qiskit-community/qiskit-aqt-provider
qiskit-community
# This code is part of Qiskit. # # (C) Alpine Quantum Technologies GmbH 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. """Run various circuits on an offline simulator controlled by an AQTResource. This tests whether the circuit pre-conditioning and results formatting works as expected. """ import re import typing from collections import Counter from math import pi from typing import Union import pytest import qiskit from qiskit import ClassicalRegister, QiskitError, QuantumCircuit, QuantumRegister, quantum_info from qiskit.providers import BackendV2 from qiskit.providers.jobstatus import JobStatus from qiskit.transpiler import TranspilerError from qiskit_aer import AerProvider, AerSimulator from qiskit_aqt_provider import AQTProvider from qiskit_aqt_provider.aqt_resource import AQTResource from qiskit_aqt_provider.test.circuits import assert_circuits_equivalent from qiskit_aqt_provider.test.fixtures import MockSimulator from qiskit_aqt_provider.test.resources import TestResource from qiskit_aqt_provider.test.timeout import timeout @pytest.mark.parametrize("shots", [200]) def test_empty_circuit(shots: int, any_offline_simulator_no_noise: BackendV2) -> None: """Run an empty circuit.""" qc = QuantumCircuit(1) qc.measure_all() job = any_offline_simulator_no_noise.run(qc, shots=shots) assert job.result().get_counts() == {"0": shots} def test_circuit_success_lifecycle() -> None: """Go through the lifecycle of a successful single-circuit job. Check that the job status visits the states QUEUED, RUNNING, and DONE. """ backend = TestResource(min_queued_duration=0.5, min_running_duration=0.5) backend.options.update_options(query_period_seconds=0.1) qc = QuantumCircuit(1) qc.measure_all() job = backend.run(qc) assert job.status() is JobStatus.QUEUED with timeout(2.0): while job.status() is JobStatus.QUEUED: continue assert job.status() is JobStatus.RUNNING with timeout(2.0): while job.status() is JobStatus.RUNNING: continue assert job.status() is JobStatus.DONE def test_error_circuit() -> None: """Check that errors in circuits are reported in the `errors` field of the Qiskit result metadata, where the keys are the circuit job ids. """ backend = TestResource(always_error=True) backend.options.update_options(query_period_seconds=0.1) qc = QuantumCircuit(1) qc.measure_all() result = backend.run(qc).result() assert result.success is False assert backend.error_message == result._metadata["error"] def test_cancelled_circuit() -> None: """Check that cancelled jobs return success = false.""" backend = TestResource(always_cancel=True) qc = QuantumCircuit(1) qc.measure_all() result = backend.run(qc).result() assert result.success is False @pytest.mark.parametrize("shots", [1, 100, 200]) def test_simple_backend_run(shots: int, any_offline_simulator_no_noise: BackendV2) -> None: """Run a simple circuit with `backend.run`.""" qc = QuantumCircuit(1) qc.rx(pi, 0) qc.measure_all() trans_qc = qiskit.transpile(qc, any_offline_simulator_no_noise) job = any_offline_simulator_no_noise.run(trans_qc, shots=shots) assert job.result().get_counts() == {"1": shots} @pytest.mark.parametrize("resource", [MockSimulator(noisy=False), MockSimulator(noisy=True)]) def test_simple_backend_execute_noisy(resource: MockSimulator) -> None: """Execute a simple circuit on a noisy and noiseless backend. Check that the noisy backend is indeed noisy. """ qc = QuantumCircuit(1) qc.rx(pi, 0) qc.measure_all() # the single qubit error is around 0.1% so to see at least one error, we need to do more than # 1000 shots. total_shots = 4000 # take some margin shots = 200 # maximum shots per submission assert total_shots % shots == 0 counts: typing.Counter[str] = Counter() for _ in range(total_shots // shots): job = resource.run(qiskit.transpile(qc, backend=resource), shots=shots) counts += Counter(job.result().get_counts()) assert sum(counts.values()) == total_shots if resource.with_noise_model: assert set(counts.keys()) == {"0", "1"} assert counts["0"] < 0.1 * counts["1"] # very crude else: assert set(counts.keys()) == {"1"} @pytest.mark.parametrize("shots", [100]) def test_ancilla_qubits_mapping(shots: int, any_offline_simulator_no_noise: BackendV2) -> None: """Run a circuit with two quantum registers, with only one mapped to the classical memory.""" qr = QuantumRegister(2) qr_aux = QuantumRegister(3) memory = ClassicalRegister(2) qc = QuantumCircuit(qr, qr_aux, memory) qc.rx(pi, qr[0]) qc.ry(pi, qr[1]) qc.rxx(pi / 2, qr_aux[0], qr_aux[1]) qc.measure(qr, memory) trans_qc = qiskit.transpile(qc, any_offline_simulator_no_noise) job = any_offline_simulator_no_noise.run(trans_qc, shots=shots) # only two bits in the counts dict because memory has two bits width assert job.result().get_counts() == {"11": shots} @pytest.mark.parametrize("shots", [100]) def test_multiple_classical_registers( shots: int, any_offline_simulator_no_noise: BackendV2 ) -> None: """Run a circuit with the final state mapped to multiple classical registers.""" qr = QuantumRegister(5) memory_a = ClassicalRegister(2) memory_b = ClassicalRegister(3) qc = QuantumCircuit(qr, memory_a, memory_b) qc.rx(pi, qr[0]) qc.rx(pi, qr[3]) qc.measure(qr[:2], memory_a) qc.measure(qr[2:], memory_b) trans_qc = qiskit.transpile(qc, any_offline_simulator_no_noise) job = any_offline_simulator_no_noise.run(trans_qc, shots=shots) # counts are returned as "memory_b memory_a", msb first assert job.result().get_counts() == {"010 01": shots} @pytest.mark.parametrize("shots", [123]) @pytest.mark.parametrize("memory_opt", [True, False]) def test_get_memory_simple( shots: int, memory_opt: bool, any_offline_simulator_no_noise: BackendV2 ) -> None: """Check that the raw bitstrings can be accessed for each shot via the get_memory() method in Qiskit's Result. The memory is only accessible if the `memory` option is set. """ qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc.measure_all() result = any_offline_simulator_no_noise.run( qiskit.transpile(qc, any_offline_simulator_no_noise), shots=shots, memory=memory_opt ).result() if memory_opt: memory = result.get_memory() assert set(memory) == {"11", "00"} assert len(memory) == shots else: with pytest.raises(QiskitError, match=re.compile("no memory", re.IGNORECASE)): result.get_memory() @pytest.mark.parametrize("shots", [123]) def test_get_memory_ancilla_qubits(shots: int, any_offline_simulator_no_noise: BackendV2) -> None: """Check that the raw bistrings returned by get_memory() in Qiskit's Result only contain the mapped classical bits. """ qr = QuantumRegister(2) qr_aux = QuantumRegister(3) memory = ClassicalRegister(2) qc = QuantumCircuit(qr, qr_aux, memory) qc.rx(pi, qr[0]) qc.ry(pi, qr[1]) qc.rxx(pi / 2, qr_aux[0], qr_aux[1]) qc.measure(qr, memory) job = any_offline_simulator_no_noise.run( qiskit.transpile(qc, any_offline_simulator_no_noise), shots=shots, memory=True ) memory = job.result().get_memory() assert set(memory) == {"11"} assert len(memory) == shots @pytest.mark.parametrize("shots", [123]) def test_get_memory_bit_ordering(shots: int, any_offline_simulator_no_noise: BackendV2) -> None: """Check that the bitstrings returned by the results produced by AQT jobs have the same bit order as the Qiskit Aer simulators. """ sim = AerSimulator(method="statevector") qc = QuantumCircuit(3) qc.rx(pi, 0) qc.rx(pi, 1) qc.measure_all() aqt_memory = ( any_offline_simulator_no_noise.run( qiskit.transpile(qc, any_offline_simulator_no_noise), shots=shots, memory=True ) .result() .get_memory() ) sim_memory = sim.run(qiskit.transpile(qc, sim), shots=shots, memory=True).result().get_memory() assert set(sim_memory) == set(aqt_memory) # sanity check: bitstrings are no palindromes assert not any(bitstring == bitstring[::-1] for bitstring in sim_memory) @pytest.mark.parametrize( "backend", [ pytest.param( AQTProvider("token").get_backend("offline_simulator_no_noise"), id="offline-simulator" ), pytest.param(AerProvider().get_backend("aer_simulator"), id="aer-simulator"), ], ) def test_regression_issue_85(backend: BackendV2) -> None: """Check that qubit and clbit permutations are properly handled by the offline simulators. This is a regression test for #85. Check that executing circuits with qubit/clbit permutations outputs the same bitstrings on noiseless offline simulators from this package and straight from Aer. """ empty_3 = QuantumCircuit(3) base = QuantumCircuit(3) base.h(0) base.cx(0, 2) base.measure_all() perm_qubits = empty_3.compose(base, qubits=[0, 2, 1]) perm_all = empty_3.compose(base, qubits=[0, 2, 1], clbits=[0, 2, 1]) base_bitstrings = set(backend.run(qiskit.transpile(base, backend)).result().get_counts()) assert base_bitstrings == {"000", "101"} perm_qubits_bitstrings = set( backend.run(qiskit.transpile(perm_qubits, backend)).result().get_counts() ) assert perm_qubits_bitstrings == {"000", "101"} perm_all_bitstrings = set( backend.run(qiskit.transpile(perm_all, backend)).result().get_counts() ) assert perm_all_bitstrings == {"000", "011"} @pytest.mark.parametrize(("shots", "qubits"), [(100, 5), (100, 8)]) def test_bell_states(shots: int, qubits: int, any_offline_simulator_no_noise: BackendV2) -> None: """Create a N qubits Bell state.""" qc = QuantumCircuit(qubits) qc.h(0) for qubit in range(1, qubits): qc.cx(0, qubit) qc.measure_all() job = any_offline_simulator_no_noise.run( qiskit.transpile(qc, any_offline_simulator_no_noise), shots=shots ) counts = job.result().get_counts() assert set(counts.keys()) == {"0" * qubits, "1" * qubits} assert sum(counts.values()) == shots @pytest.mark.parametrize( "target_state", [ quantum_info.Statevector.from_label("01"), "01", 1, [0, 1, 0, 0], ], ) @pytest.mark.parametrize("optimization_level", range(4)) def test_state_preparation( target_state: Union[int, str, quantum_info.Statevector, list[complex]], optimization_level: int, any_offline_simulator_no_noise: BackendV2, ) -> None: """Test the state preparation unitary factory. Prepare the state |01> using the different formats accepted by `QuantumCircuit.prepare_state`. """ qc = QuantumCircuit(2) qc.prepare_state(target_state) qc.measure_all() shots = 100 job = any_offline_simulator_no_noise.run( qiskit.transpile(qc, any_offline_simulator_no_noise, optimization_level=optimization_level), shots=shots, ) counts = job.result().get_counts() assert counts == {"01": shots} @pytest.mark.parametrize("optimization_level", range(4)) def test_state_preparation_single_qubit( optimization_level: int, any_offline_simulator_no_noise: BackendV2 ) -> None: """Test the state preparation unitary factory, targeting a single qubit in the register.""" qreg = QuantumRegister(4) qc = QuantumCircuit(qreg) qc.prepare_state(1, qreg[2]) qc.measure_all() shots = 100 job = any_offline_simulator_no_noise.run( qiskit.transpile(qc, any_offline_simulator_no_noise, optimization_level=optimization_level), shots=shots, ) counts = job.result().get_counts() assert counts == {"0100": shots} def test_initialize_not_supported(offline_simulator_no_noise: AQTResource) -> None: """Verify that `QuantumCircuit.initialize` is not supported. #112 adds a note to the user guide indicating that `QuantumCircuit.initialize` is not supported. Remove the note if this test fails. """ qc = QuantumCircuit(2) qc.x(0) qc.initialize("01") qc.measure_all() with pytest.raises( TranspilerError, match=re.compile( r"high\s?level\s?synthesis was unable to synthesize instruction", re.IGNORECASE ), ): qiskit.transpile(qc, offline_simulator_no_noise) @pytest.mark.parametrize("optimization_level", range(4)) def test_cswap(optimization_level: int, any_offline_simulator_no_noise: BackendV2) -> None: """Verify that CSWAP (Fredkin) gates can be transpiled and executed (in a trivial case).""" qc = QuantumCircuit(3) qc.prepare_state("101") qc.cswap(0, 1, 2) trans_qc = qiskit.transpile( qc, any_offline_simulator_no_noise, optimization_level=optimization_level ) assert_circuits_equivalent(qc, trans_qc) qc.measure_all() shots = 200 job = any_offline_simulator_no_noise.run( qiskit.transpile(qc, any_offline_simulator_no_noise, optimization_level=optimization_level), shots=shots, ) counts = job.result().get_counts() assert counts == {"011": shots}
https://github.com/qiskit-community/qiskit-aqt-provider
qiskit-community
# This code is part of Qiskit. # # (C) Alpine Quantum Technologies GmbH 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. import json import os import re import uuid from pathlib import Path from typing import NamedTuple, Optional import httpx import pytest import qiskit from pytest_httpx import HTTPXMock from pytest_mock import MockerFixture from qiskit.providers import JobStatus from qiskit_aqt_provider import api_models, api_models_generated, persistence from qiskit_aqt_provider.aqt_job import AQTJob from qiskit_aqt_provider.aqt_options import AQTOptions from qiskit_aqt_provider.aqt_provider import AQTProvider from qiskit_aqt_provider.aqt_resource import AQTResource, OfflineSimulatorResource from qiskit_aqt_provider.test.circuits import random_circuit from qiskit_aqt_provider.test.fixtures import MockSimulator @pytest.mark.parametrize( "backend_name", [ "offline_simulator_no_noise", pytest.param( "offline_simulator_noise", marks=pytest.mark.xfail(reason="Job persistence on noisy simulator not supported."), ), ], ) @pytest.mark.parametrize("remove_from_store", [True, False]) def test_job_persistence_transaction_offline_simulator( backend_name: str, remove_from_store: bool, tmp_path: Path ) -> None: """Persist and restore a job on offline simulators.""" token = str(uuid.uuid4()) provider = AQTProvider(token) backend = provider.get_backend(backend_name) assert isinstance(backend, OfflineSimulatorResource) circuits = [random_circuit(2), random_circuit(3)] job = backend.run(qiskit.transpile(circuits, backend)) path = job.persist(store_path=tmp_path) # sanity check assert str(path).startswith(str(tmp_path)) restored_job = AQTJob.restore( job.job_id(), access_token=token, store_path=tmp_path, remove_from_store=remove_from_store ) assert path.exists() is not remove_from_store assert isinstance(restored_job.backend(), OfflineSimulatorResource) restored_backend: OfflineSimulatorResource = restored_job.backend() assert restored_backend.provider.access_token == backend.provider.access_token assert restored_backend.with_noise_model == backend.with_noise_model assert restored_job.options == job.options assert restored_job.circuits == job.circuits assert restored_job.api_submit_payload == job.api_submit_payload # for offline simulators, the backend state is fully lost so the restored_job # is actually a new one assert restored_job.job_id() assert restored_job.job_id() != job.job_id() # we get a result for both jobs, but they in principle differ because the job was re-submitted assert restored_job.result().success assert len(restored_job.result().get_counts()) == len(circuits) assert job.result().success assert len(job.result().get_counts()) == len(circuits) def test_job_persistence_transaction_online_backend(httpx_mock: HTTPXMock, tmp_path: Path) -> None: """Persist and restore a job on mocked online resources.""" # Set up a fake online resource token = str(uuid.uuid4()) provider = AQTProvider(token) resource_id = api_models.ResourceId( workspace_id=str(uuid.uuid4()), resource_id=str(uuid.uuid4()), resource_name=str(uuid.uuid4()), resource_type="device", ) backend = AQTResource(provider, resource_id) class PortalJob(NamedTuple): """Mocked portal state: holds details of the submitted jobs.""" circuits: list[api_models_generated.QuantumCircuit] workspace_id: str resource_id: str error_msg: str portal_state: dict[uuid.UUID, PortalJob] = {} def handle_submit(request: httpx.Request) -> httpx.Response: """Mocked circuit submission endpoint. Create a job ID and a unique error message for the submitted job. Store the details in `portal_state`. """ assert request.headers["authorization"] == f"Bearer {token}" _, workspace_id, resource_id = request.url.path.rsplit("/", maxsplit=2) data = api_models.SubmitJobRequest.model_validate_json(request.content.decode("utf-8")) circuits = data.payload.circuits job_id = uuid.uuid4() assert job_id not in portal_state portal_state[job_id] = PortalJob( circuits=circuits, workspace_id=workspace_id, resource_id=resource_id, error_msg=str(uuid.uuid4()), ) return httpx.Response( status_code=httpx.codes.OK, json=json.loads( api_models.Response.queued( job_id=job_id, resource_id=resource_id, workspace_id=workspace_id ).model_dump_json() ), ) def handle_result(request: httpx.Request) -> httpx.Response: """Mocked circuit result endpoint. Check that the access token is valid. Return an error response, with the unique error message for the requested job ID. """ assert request.headers["authorization"] == f"Bearer {token}" _, job_id = request.url.path.rsplit("/", maxsplit=1) job = portal_state[uuid.UUID(job_id)] return httpx.Response( status_code=httpx.codes.OK, json=json.loads( api_models.Response.error( job_id=uuid.UUID(job_id), workspace_id=job.workspace_id, resource_id=job.resource_id, message=job.error_msg, ).model_dump_json() ), ) httpx_mock.add_callback( handle_submit, url=re.compile(r".+/submit/[0-9a-f-]+/[0-9a-f-]+$"), method="POST" ) httpx_mock.add_callback(handle_result, url=re.compile(r".+/result/[0-9a-f-]+$"), method="GET") # ---------- circuits = [random_circuit(2), random_circuit(3), random_circuit(4)] job = backend.run(qiskit.transpile(circuits, backend), shots=123) # sanity checks assert uuid.UUID(job.job_id()) in portal_state assert job.options != AQTOptions() # non-default options because shots=123 path = job.persist(store_path=tmp_path) restored_job = AQTJob.restore(job.job_id(), access_token=token, store_path=tmp_path) assert not path.exists() # remove_from_store is True by default assert restored_job.job_id() == job.job_id() assert restored_job.circuits == job.circuits assert restored_job.options == job.options # the mocked GET /result route always returns an error response with a unique error message assert job.status() is JobStatus.ERROR assert restored_job.status() is JobStatus.ERROR assert job.error_message assert job.error_message == restored_job.error_message assert job.result().success is False assert restored_job.result().success is False # both job and restored_job have already been submitted, so they can't be submitted again with pytest.raises(RuntimeError, match="Job already submitted"): job.submit() with pytest.raises(RuntimeError, match="Job already submitted"): restored_job.submit() def test_can_only_persist_submitted_jobs( offline_simulator_no_noise: MockSimulator, tmp_path: Path ) -> None: """Check that only jobs with a valid job_id can be persisted.""" circuit = qiskit.transpile(random_circuit(2), offline_simulator_no_noise) job = AQTJob(offline_simulator_no_noise, [circuit], AQTOptions()) assert not job.job_id() with pytest.raises(RuntimeError, match=r"Can only persist submitted jobs."): job.persist(store_path=tmp_path) def test_restore_unknown_job(tmp_path: Path) -> None: """Check that an attempt at restoring an unknown job raises JobNotFoundError.""" with pytest.raises(persistence.JobNotFoundError): AQTJob.restore(job_id="invalid", store_path=tmp_path) @pytest.mark.parametrize("override", [None, Path("foo/bar")]) def test_store_path_resolver( override: Optional[Path], tmp_path: Path, mocker: MockerFixture ) -> None: """Test the persistence store path resolver. The returned path must: - be the override, if passed - exist - be a directory. """ # do not pollute the test user's environment # this only works on unix mocker.patch.dict(os.environ, {"XDG_CACHE_HOME": str(tmp_path)}) if override is not None: override = tmp_path / override store_path = persistence.get_store_path(override) # sanity check: make sure the mock works assert str(store_path).startswith(str(tmp_path)) assert store_path.exists() assert store_path.is_dir() if override is not None: assert store_path == override
https://github.com/qiskit-community/qiskit-aqt-provider
qiskit-community
# This code is part of Qiskit. # # (C) Alpine Quantum Technologies GmbH 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. from math import isclose, pi from typing import Callable import pytest import qiskit from qiskit.circuit import Parameter, QuantumCircuit from qiskit.primitives import ( BackendEstimator, BackendSampler, BaseEstimatorV1, BaseSamplerV1, Sampler, ) from qiskit.providers import Backend, BackendV2 from qiskit.quantum_info import SparsePauliOp from qiskit.transpiler.exceptions import TranspilerError from qiskit_aqt_provider.primitives import AQTSampler from qiskit_aqt_provider.primitives.estimator import AQTEstimator from qiskit_aqt_provider.test.circuits import assert_circuits_equal from qiskit_aqt_provider.test.fixtures import MockSimulator @pytest.fixture(scope="module") def assert_all_responses_were_requested() -> bool: """Disable pytest-httpx check that all mocked responses are used for this module. Some tests in this module request the offline_simulator_no_noise_direct_access fixture without using it, thus not calling the mocked HTTP responses it contains. # TODO: use alternative HTTPXMock setup when available. # See: https://github.com/Colin-b/pytest_httpx/issues/137 """ return False def test_backend_primitives_are_v1() -> None: """Check that `BackendSampler` and `BackendEstimator` have primitives V1 interfaces. As of 2024-02-20, there are no backend primitives that provide V2 interfaces. If this test fails, the `AQTSampler` and `AQTEstimator` docs as well as the user guide must be updated. An interface mismatch may be detected at other spots. This makes the detection explicit. """ assert issubclass(BackendSampler, BaseSamplerV1) assert issubclass(BackendEstimator, BaseEstimatorV1) @pytest.mark.parametrize( "get_sampler", [ # Reference implementation lambda _: Sampler(), # The AQT transpilation plugin doesn't support transpiling unbound parametric circuits # and the BackendSampler doesn't fallback to transpiling the bound circuit if # transpiling the unbound circuit failed (like the opflow sampler does). # Sampling a parametric circuit with the generic BackendSampler is therefore not supported. pytest.param( lambda backend: BackendSampler(backend), marks=pytest.mark.xfail(raises=TranspilerError) ), # The specialized implementation of the Sampler primitive for AQT backends delays the # transpilation passes that require bound parameters. lambda backend: AQTSampler(backend), ], ) def test_circuit_sampling_primitive( get_sampler: Callable[[Backend], BaseSamplerV1], any_offline_simulator_no_noise: BackendV2 ) -> None: """Check that a `Sampler` primitive using an AQT backend can sample parametric circuits.""" theta = Parameter("θ") qc = QuantumCircuit(2) qc.rx(theta, 0) qc.ry(theta, 0) qc.rz(theta, 0) qc.rxx(theta, 0, 1) qc.measure_all() assert qc.num_parameters > 0 sampler = get_sampler(any_offline_simulator_no_noise) sampled = sampler.run(qc, [pi]).result().quasi_dists assert sampled == [{3: 1.0}] @pytest.mark.parametrize("theta", [0.0, pi]) def test_operator_estimator_primitive_trivial_pauli_x( theta: float, offline_simulator_no_noise: MockSimulator ) -> None: """Use the Estimator primitive to verify that <0|X|0> = <1|X|1> = 0. Define the parametrized circuit that consists of the single gate Rx(θ) with θ=0,π. Applied to |0>, this creates the states |0>,|1>. The Estimator primitive is then used to evaluate the expectation value of the Pauli X operator on the state produced by the circuit. """ offline_simulator_no_noise.simulator.options.seed_simulator = 0 estimator = AQTEstimator(offline_simulator_no_noise, options={"shots": 200}) qc = QuantumCircuit(1) qc.rx(theta, 0) op = SparsePauliOp("X") result = estimator.run(qc, op).result() assert abs(result.values[0]) < 0.1 def test_operator_estimator_primitive_trivial_pauli_z( offline_simulator_no_noise: MockSimulator, ) -> None: """Use the Estimator primitive to verify that: <0|Z|0> = 1 <1|Z|1> = -1 <ψ|Z|ψ> = 0 with |ψ> = (|0> + |1>)/√2. The sampled circuit is always Rx(θ) with θ=0,π,π/2 respectively. The θ values are passed into a single call to the estimator, thus also checking that the AQTEstimator can deal with parametrized circuits. """ offline_simulator_no_noise.simulator.options.seed_simulator = 0 estimator = AQTEstimator(offline_simulator_no_noise, options={"shots": 200}) theta = Parameter("θ") qc = QuantumCircuit(1) qc.rx(theta, 0) op = SparsePauliOp("Z") result = estimator.run([qc] * 3, [op] * 3, [[0], [pi], [pi / 2]]).result() z0, z1, z01 = result.values assert isclose(z0, 1.0) # <0|Z|0> assert isclose(z1, -1.0) # <1|Z|1> assert abs(z01) < 0.1 # <ψ|Z|ψ>, |ψ> = (|0> + |1>)/√2 @pytest.mark.parametrize( "theta", [ pi / 3, -pi / 3, pi / 2, -pi / 2, 3 * pi / 4, -3 * pi / 4, 15 * pi / 8, -15 * pi / 8, 33 * pi / 16, -33 * pi / 16, ], ) def test_aqt_sampler_transpilation(theta: float, offline_simulator_no_noise: MockSimulator) -> None: """Check that the AQTSampler passes the same circuit to the backend as a call to `backend.run` with the same transpiler call on the bound circuit would. """ theta_param = Parameter("θ") # define a circuit with unbound parameters qc = QuantumCircuit(2) qc.rx(pi / 3, 0) qc.rxx(theta_param, 0, 1) qc.measure_all() assert qc.num_parameters > 0 # sample the circuit, passing parameter assignments sampler = AQTSampler(offline_simulator_no_noise) sampler.run(qc, [theta]).result() # the sampler was only called once assert len(offline_simulator_no_noise.submitted_circuits) == 1 # get the circuit passed to the backend ((transpiled_circuit,),) = offline_simulator_no_noise.submitted_circuits # compare to the circuit obtained by binding the parameters and transpiling at once expected = qc.assign_parameters({theta_param: theta}) tr_expected = qiskit.transpile(expected, offline_simulator_no_noise) assert_circuits_equal(transpiled_circuit, tr_expected)
https://github.com/qiskit-community/qiskit-aqt-provider
qiskit-community
# This code is part of Qiskit. # # (C) Copyright IBM 2019, Alpine Quantum Technologies GmbH 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. import itertools import json import math import re import uuid from contextlib import AbstractContextManager, nullcontext from typing import Any from unittest import mock import httpx import pydantic as pdt import pytest import qiskit from polyfactory.factories.pydantic_factory import ModelFactory from pytest_httpx import HTTPXMock from qiskit import QuantumCircuit from qiskit.providers import JobStatus from qiskit.providers.exceptions import JobTimeoutError from typing_extensions import assert_type from qiskit_aqt_provider import api_models, api_models_direct from qiskit_aqt_provider.aqt_job import AQTJob from qiskit_aqt_provider.aqt_options import AQTDirectAccessOptions, AQTOptions from qiskit_aqt_provider.aqt_resource import AQTResource from qiskit_aqt_provider.circuit_to_aqt import circuits_to_aqt_job from qiskit_aqt_provider.test.circuits import assert_circuits_equal, empty_circuit, random_circuit from qiskit_aqt_provider.test.fixtures import MockSimulator from qiskit_aqt_provider.test.resources import ( DummyDirectAccessResource, DummyResource, TestResource, ) from qiskit_aqt_provider.versions import USER_AGENT class OptionsFactory(ModelFactory[AQTOptions]): """Factory of random but well-formed options data.""" __model__ = AQTOptions query_timeout_seconds = 10.0 def test_options_set_query_timeout(offline_simulator_no_noise: AQTResource) -> None: """Set the query timeout for job status queries with different values.""" backend = offline_simulator_no_noise # doesn't work with str with pytest.raises(pdt.ValidationError): backend.options.update_options(query_timeout_seconds="abc") # works with integers backend.options.update_options(query_timeout_seconds=123) assert backend.options.query_timeout_seconds == 123 # works with floats backend.options.update_options(query_timeout_seconds=123.45) assert backend.options.query_timeout_seconds == 123.45 # works with None (no timeout) backend.options.update_options(query_timeout_seconds=None) assert backend.options.query_timeout_seconds is None def test_options_set_query_period(offline_simulator_no_noise: AQTResource) -> None: """Set the query period for job status queries with different values.""" backend = offline_simulator_no_noise # works with integers backend.options.update_options(query_period_seconds=123) assert backend.options.query_period_seconds == 123 # works with floats backend.options.update_options(query_period_seconds=123.45) assert backend.options.query_period_seconds == 123.45 # doesn't work with None with pytest.raises(pdt.ValidationError): backend.options.update_options(query_period_seconds=None) # doesn't work with str with pytest.raises(pdt.ValidationError): backend.options.update_options(query_period_seconds="abc") def test_options_types_and_constraints_cloud_resource( offline_simulator_no_noise: AQTResource, ) -> None: """Check that the options models and constraints are as expected for cloud backends.""" assert_type(offline_simulator_no_noise.options, AQTOptions) assert isinstance(offline_simulator_no_noise.options, AQTOptions) assert offline_simulator_no_noise.options.max_shots() == 2000 # Check that the default options in Qiskit format match the Pydantic model. assert offline_simulator_no_noise.options.model_dump() == { **offline_simulator_no_noise.__class__._default_options() } def test_options_types_and_constraints_direct_access_resource() -> None: """Check that the options models and constraints are as expected for direct-access backends.""" backend = DummyDirectAccessResource("token") assert_type(backend.options, AQTDirectAccessOptions) assert isinstance(backend.options, AQTDirectAccessOptions) assert backend.options.max_shots() == 200 # Check that the default options in Qiskit format match the Pydantic model. assert backend.options.model_dump() == {**backend.__class__._default_options()} def test_query_timeout_propagation() -> None: """Check that the query timeout is properly propagated from the backend options to the job result polling loop. Acquire a resource with 10s processing time, but set the job result timeout to 1s. Check that calling `result()` on the job handle fails with a timeout error. """ response_delay = 10.0 timeout = 1.0 assert timeout < response_delay backend = TestResource(min_running_duration=response_delay) backend.options.update_options(query_timeout_seconds=timeout, query_period_seconds=0.5) qc = QuantumCircuit(1) qc.rx(3.14, 0) qc.measure_all() job = backend.run(qiskit.transpile(qc, backend)) with pytest.raises(JobTimeoutError): job.result() def test_query_period_propagation() -> None: """Check that the query wait duration is properly propagated from the backend options to the job result polling loop. Set the polling period (much) shorter than the backend's processing time. Check that the backend is polled the calculated number of times. """ response_delay = 2.0 period_seconds = 0.5 timeout_seconds = 3.0 assert timeout_seconds > response_delay # won't time out backend = TestResource(min_running_duration=response_delay) backend.options.update_options( query_timeout_seconds=timeout_seconds, query_period_seconds=period_seconds ) qc = QuantumCircuit(1) qc.rx(3.14, 0) qc.measure_all() job = backend.run(qiskit.transpile(qc, backend)) with mock.patch.object(AQTJob, "status", wraps=job.status) as mocked_status: job.result() lower_bound = math.floor(response_delay / period_seconds) upper_bound = math.ceil(response_delay / period_seconds) + 1 assert lower_bound <= mocked_status.call_count <= upper_bound def test_run_options_propagation(offline_simulator_no_noise: MockSimulator) -> None: """Check that options passed to AQTResource.run are propagated to the corresponding job.""" default = offline_simulator_no_noise.options.model_copy() while True: overrides = OptionsFactory.build() if overrides != default: break qc = QuantumCircuit(1) qc.measure_all() # don't submit the circuit to the simulator with mock.patch.object(AQTJob, "submit") as mocked_submit: job = offline_simulator_no_noise.run(qc, **overrides.model_dump()) assert job.options == overrides mocked_submit.assert_called_once() def test_run_options_unknown(offline_simulator_no_noise: MockSimulator) -> None: """Check that AQTResource.run accepts but warns about unknown options.""" default = offline_simulator_no_noise.options.model_copy() overrides = {"shots": 123, "unknown_option": True} assert set(overrides) - set(default) == {"unknown_option"} qc = QuantumCircuit(1) qc.measure_all() with mock.patch.object(AQTJob, "submit") as mocked_submit: with pytest.warns(UserWarning, match="not used"): job = offline_simulator_no_noise.run(qc, **overrides) assert job.options.shots == 123 mocked_submit.assert_called_once() def test_run_options_invalid(offline_simulator_no_noise: MockSimulator) -> None: """Check that AQTResource.run reject valid option names with invalid values.""" qc = QuantumCircuit(1) qc.measure_all() with pytest.raises(pdt.ValidationError, match="shots"): offline_simulator_no_noise.run(qc, shots=-123) def test_double_job_submission(offline_simulator_no_noise: MockSimulator) -> None: """Check that attempting to re-submit a job raises a RuntimeError.""" qc = QuantumCircuit(1) qc.r(3.14, 0.0, 0) qc.measure_all() # AQTResource.run submits the job job = offline_simulator_no_noise.run(qc) with pytest.raises(RuntimeError, match=f"{job.job_id()}"): job.submit() # Check that the job was actually submitted ((submitted_circuit,),) = offline_simulator_no_noise.submitted_circuits assert_circuits_equal(submitted_circuit, qc) def test_offline_simulator_invalid_job_id(offline_simulator_no_noise: MockSimulator) -> None: """Check that the offline simulator raises UnknownJobError if the job id passed to `result()` is invalid. """ qc = QuantumCircuit(1) qc.measure_all() job = offline_simulator_no_noise.run([qc], shots=1) job_id = uuid.UUID(hex=job.job_id()) invalid_job_id = uuid.uuid4() assert invalid_job_id != job_id with pytest.raises(api_models.UnknownJobError, match=str(invalid_job_id)): offline_simulator_no_noise.result(invalid_job_id) # querying the actual job is successful result = offline_simulator_no_noise.result(job_id) assert result.job.job_id == job_id def test_submit_valid_response(httpx_mock: HTTPXMock) -> None: """Check that AQTResource.submit passes the authorization token and extracts the correct job_id when the response payload is valid. """ token = str(uuid.uuid4()) backend = DummyResource(token) expected_job_id = uuid.uuid4() def handle_submit(request: httpx.Request) -> httpx.Response: assert request.headers["user-agent"] == USER_AGENT assert request.headers["authorization"] == f"Bearer {token}" return httpx.Response( status_code=httpx.codes.OK, json=json.loads( api_models.Response.queued( job_id=expected_job_id, resource_id=backend.resource_id.resource_id, workspace_id=backend.resource_id.workspace_id, ).model_dump_json() ), ) httpx_mock.add_callback(handle_submit, method="POST") job = AQTJob(backend, circuits=[empty_circuit(2)], options=AQTOptions(shots=10)) job.submit() assert job.job_id() == str(expected_job_id) def test_submit_payload_matches(httpx_mock: HTTPXMock) -> None: """Check that the quantum circuits jobs payload is correctly submitted to the API endpoint.""" backend = DummyResource("") shots = 123 qc = qiskit.transpile(random_circuit(2), backend) expected_job_payload = circuits_to_aqt_job([qc], shots=shots) expected_job_id = uuid.uuid4() def handle_submit(request: httpx.Request) -> httpx.Response: assert request.headers["user-agent"] == USER_AGENT assert request.url.path.endswith( f"submit/{backend.resource_id.workspace_id}/{backend.resource_id.resource_id}" ) data = api_models.SubmitJobRequest.model_validate_json(request.content.decode("utf-8")) assert data == expected_job_payload return httpx.Response( status_code=httpx.codes.OK, json=json.loads( api_models.Response.queued( job_id=expected_job_id, resource_id=backend.resource_id.resource_id, workspace_id=backend.resource_id.workspace_id, ).model_dump_json() ), ) httpx_mock.add_callback(handle_submit, method="POST") qc = qiskit.transpile(random_circuit(2), backend) job = AQTJob(backend, circuits=[qc], options=AQTOptions(shots=shots)) job.submit() assert job.job_id() == str(expected_job_id) def test_submit_bad_request(httpx_mock: HTTPXMock) -> None: """Check that AQTResource.submit raises an HTTPError if the request is flagged invalid by the server. """ backend = DummyResource("") httpx_mock.add_response(status_code=httpx.codes.BAD_REQUEST) job = AQTJob(backend, circuits=[empty_circuit(2)], options=AQTOptions(shots=10)) with pytest.raises(httpx.HTTPError): job.submit() def test_result_valid_response(httpx_mock: HTTPXMock) -> None: """Check that AQTResource.result passes the authorization token and returns the raw response payload. """ token = str(uuid.uuid4()) backend = DummyResource(token) job_id = uuid.uuid4() payload = api_models.Response.cancelled( job_id=job_id, resource_id=backend.resource_id.resource_id, workspace_id=backend.resource_id.workspace_id, ) def handle_result(request: httpx.Request) -> httpx.Response: assert request.headers["user-agent"] == USER_AGENT assert request.headers["authorization"] == f"Bearer {token}" assert request.url.path.endswith(f"result/{job_id}") return httpx.Response( status_code=httpx.codes.OK, json=json.loads(payload.model_dump_json()) ) httpx_mock.add_callback(handle_result, method="GET") response = backend.result(job_id) assert response == payload def test_result_bad_request(httpx_mock: HTTPXMock) -> None: """Check that AQTResource.result raises an HTTPError if the request is flagged invalid by the server. """ backend = DummyResource("") httpx_mock.add_response(status_code=httpx.codes.BAD_REQUEST) with pytest.raises(httpx.HTTPError): backend.result(uuid.uuid4()) def test_result_unknown_job(httpx_mock: HTTPXMock) -> None: """Check that AQTResource.result raises UnknownJobError if the API responds with an UnknownJob payload. """ backend = DummyResource("") job_id = uuid.uuid4() httpx_mock.add_response( json=json.loads(api_models.Response.unknown_job(job_id=job_id).model_dump_json()) ) with pytest.raises(api_models.UnknownJobError, match=str(job_id)): backend.result(job_id) def test_offline_simulator_detects_invalid_circuits( offline_simulator_no_noise: MockSimulator, ) -> None: """Pass a circuit that cannot be converted to the AQT API to the offline simulator. This must fail. """ qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc.measure_all() with pytest.raises(ValueError, match="^Operation 'h' not in basis gate set"): offline_simulator_no_noise.run(qc) def test_offline_simulator_propagate_shots_option( offline_simulator_no_noise: MockSimulator, ) -> None: """Check various ways of configuring the number of repetitions.""" qc = qiskit.transpile(random_circuit(2), offline_simulator_no_noise) default_shots = sum(offline_simulator_no_noise.run(qc).result().get_counts().values()) assert default_shots == AQTOptions().shots shots = min(default_shots + 40, AQTOptions.max_shots()) assert shots != default_shots # configure shots in AQTResource.run shots_run = sum(offline_simulator_no_noise.run(qc, shots=shots).result().get_counts().values()) assert shots_run == shots # configure shots in resource options offline_simulator_no_noise.options.shots = shots shots_options = sum(offline_simulator_no_noise.run(qc).result().get_counts().values()) assert shots_options == shots @pytest.mark.parametrize( ("memory", "context"), [(True, nullcontext()), (False, pytest.raises(qiskit.QiskitError, match="No memory"))], ) def test_offline_simulator_run_propagate_memory_option( memory: bool, context: AbstractContextManager[Any], offline_simulator_no_noise: MockSimulator, ) -> None: """Check that the memory option can be set on `AQTResource.run`.""" qc = qiskit.transpile(random_circuit(2), offline_simulator_no_noise) default_shots = AQTOptions().shots result = offline_simulator_no_noise.run(qc, memory=memory).result() with context: assert len(result.get_memory()) == default_shots @pytest.mark.parametrize( ("memory", "context"), [(True, nullcontext()), (False, pytest.raises(qiskit.QiskitError, match="No memory"))], ) def test_offline_simulator_resource_propagate_memory_option( memory: bool, context: AbstractContextManager[Any], offline_simulator_no_noise: MockSimulator ) -> None: """Check that the memory option can be set as resource option.""" qc = qiskit.transpile(random_circuit(2), offline_simulator_no_noise) default_shots = AQTOptions().shots offline_simulator_no_noise.options.memory = memory result = offline_simulator_no_noise.run(qc).result() with context: assert len(result.get_memory()) == default_shots def test_direct_access_bad_request(httpx_mock: HTTPXMock) -> None: """Check that direct-access resources raise a httpx.HTTPError on bad requests.""" backend = DummyDirectAccessResource("token") httpx_mock.add_response(status_code=httpx.codes.BAD_REQUEST) job = backend.run(empty_circuit(2)) with pytest.raises(httpx.HTTPError): job.result() @pytest.mark.parametrize("success", [False, True]) def test_direct_access_job_status(success: bool, httpx_mock: HTTPXMock) -> None: """Check the expected Qiskit job status on direct-access resources. Since the transactions are synchronous, there are only three possible statuses: 1. initializing: the job was created but is not executing 2. done: the job executed successfully 3. error: the job execution failed. """ shots = 100 def handle_submit(request: httpx.Request) -> httpx.Response: assert request.headers["user-agent"] == USER_AGENT return httpx.Response(status_code=httpx.codes.OK, text=f'"{uuid.uuid4()}"') def handle_result(request: httpx.Request) -> httpx.Response: assert request.headers["user-agent"] == USER_AGENT _, job_id = request.url.path.rsplit("/", maxsplit=1) return httpx.Response( status_code=httpx.codes.OK, json=json.loads( api_models_direct.JobResult.create_finished( job_id=uuid.UUID(job_id), result=[[0] for _ in range(shots)] ).model_dump_json() if success else api_models_direct.JobResult.create_error( job_id=uuid.UUID(job_id) ).model_dump_json() ), ) httpx_mock.add_callback(handle_submit, method="PUT", url=re.compile(".+/circuit/?$")) httpx_mock.add_callback( handle_result, method="GET", url=re.compile(".+/circuit/result/[0-9a-f-]+$") ) backend = DummyDirectAccessResource("token") job = backend.run(empty_circuit(1), shots=shots) assert job.status() is JobStatus.INITIALIZING result = job.result() assert result.success is success if success: assert job.status() is JobStatus.DONE else: assert job.status() is JobStatus.ERROR @pytest.mark.parametrize("token", [str(uuid.uuid4()), ""]) def test_direct_access_mocked_successful_transaction(token: str, httpx_mock: HTTPXMock) -> None: """Mock a successful single-circuit transaction on a direct-access resource.""" backend = DummyDirectAccessResource(token) backend.options.with_progress_bar = False shots = 122 qc = empty_circuit(2) expected_job_id = str(uuid.uuid4()) def assert_valid_token(headers: httpx.Headers) -> None: if token: assert headers["authorization"] == f"Bearer {token}" else: assert "authorization" not in headers def handle_submit(request: httpx.Request) -> httpx.Response: assert request.headers["user-agent"] == USER_AGENT assert_valid_token(request.headers) data = api_models.QuantumCircuit.model_validate_json(request.content.decode("utf-8")) assert data.repetitions == shots return httpx.Response( status_code=httpx.codes.OK, text=f'"{expected_job_id}"', ) def handle_result(request: httpx.Request) -> httpx.Response: assert request.headers["user-agent"] == USER_AGENT assert_valid_token(request.headers) _, job_id = request.url.path.rsplit("/", maxsplit=1) assert job_id == expected_job_id return httpx.Response( status_code=httpx.codes.OK, json=json.loads( api_models_direct.JobResult.create_finished( job_id=uuid.UUID(job_id), result=[[0, 0] if s % 2 == 0 else [1, 0] for s in range(shots)], ).model_dump_json() ), ) httpx_mock.add_callback(handle_submit, method="PUT", url=re.compile(".+/circuit/?$")) httpx_mock.add_callback( handle_result, method="GET", url=re.compile(".+/circuit/result/[0-9a-f-]+$") ) job = backend.run(qc, shots=shots) result = job.result() assert result.get_counts() == {"00": shots // 2, "01": shots // 2} def test_direct_access_mocked_failed_transaction(httpx_mock: HTTPXMock) -> None: """Mock a failed multi-circuit transaction on a direct-access resource. The first two circuits succeed, the third one not. The fourth circuit would succeed, but is never executed. """ token = str(uuid.uuid4()) backend = DummyDirectAccessResource(token) backend.options.with_progress_bar = False shots = 122 qc = empty_circuit(2) job_ids = [str(uuid.uuid4()) for _ in range(4)] # produce 2 times the same id before going to the next, one value # for handle_submit, the other one for handle result. job_ids_iter = itertools.chain.from_iterable(zip(job_ids, job_ids)) # circuit executions' planned success success = [True, True, False, True] success_iter = iter(success) circuit_submissions = 0 def handle_submit(request: httpx.Request) -> httpx.Response: assert request.headers["user-agent"] == USER_AGENT data = api_models.QuantumCircuit.model_validate_json(request.content.decode("utf-8")) assert data.repetitions == shots nonlocal circuit_submissions circuit_submissions += 1 return httpx.Response( status_code=httpx.codes.OK, text=f'"{next(job_ids_iter)}"', ) def handle_result(request: httpx.Request) -> httpx.Response: assert request.headers["user-agent"] == USER_AGENT _, job_id = request.url.path.rsplit("/", maxsplit=1) assert job_id == next(job_ids_iter) return httpx.Response( status_code=httpx.codes.OK, json=json.loads( api_models_direct.JobResult.create_finished( job_id=uuid.UUID(job_id), result=[[0, 1] for _ in range(shots)] ).model_dump_json() if next(success_iter) else api_models_direct.JobResult.create_error( job_id=uuid.UUID(job_id) ).model_dump_json() ), ) httpx_mock.add_callback(handle_submit, method="PUT", url=re.compile(".+/circuit/?$")) httpx_mock.add_callback( handle_result, method="GET", url=re.compile(".+/circuit/result/[0-9a-f-]+$") ) job = backend.run([qc, qc, qc, qc], shots=shots) result = job.result() assert not result.success # not all circuits executed successfully counts = result.get_counts() assert isinstance(counts, list) # multiple successful circuit executions assert len(counts) == 2 # the first two circuits executed successfully assert counts == [{"10": shots}, {"10": shots}] assert circuit_submissions == 3 # the last circuit was never submitted
https://github.com/qiskit-community/qiskit-aqt-provider
qiskit-community
# This code is part of Qiskit. # # (C) Alpine Quantum Technologies GmbH 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. from math import pi from typing import Union import pytest from hypothesis import assume, example, given from hypothesis import strategies as st from qiskit import QuantumCircuit, transpile from qiskit.circuit.library import RXGate, RYGate from qiskit_aqt_provider.aqt_resource import AQTResource from qiskit_aqt_provider.test.circuits import ( assert_circuits_equal, assert_circuits_equivalent, qft_circuit, ) from qiskit_aqt_provider.test.fixtures import MockSimulator from qiskit_aqt_provider.transpiler_plugin import rewrite_rx_as_r, wrap_rxx_angle @pytest.mark.parametrize( ("input_theta", "output_theta", "output_phi"), [ (pi / 3, pi / 3, 0.0), (-pi / 3, pi / 3, pi), (7 * pi / 5, 3 * pi / 5, pi), (25 * pi, pi, pi), (22 * pi / 3, 2 * pi / 3, pi), ], ) def test_rx_rewrite_example( input_theta: float, output_theta: float, output_phi: float, ) -> None: """Snapshot test for the Rx(θ) → R(θ, φ) rule.""" result = QuantumCircuit(1) result.append(rewrite_rx_as_r(input_theta), (0,)) expected = QuantumCircuit(1) expected.r(output_theta, output_phi, 0) reference = QuantumCircuit(1) reference.rx(input_theta, 0) assert_circuits_equal(result, expected) assert_circuits_equivalent(result, reference) @given(theta=st.floats(allow_nan=False, min_value=-1000 * pi, max_value=1000 * pi)) @pytest.mark.parametrize("optimization_level", [0, 1, 2, 3]) @pytest.mark.parametrize("test_gate", [RXGate, RYGate]) def test_rx_ry_rewrite_transpile( theta: float, optimization_level: int, test_gate: Union[RXGate, RYGate], ) -> None: """Test the rewrite rule: Rx(θ), Ry(θ) → R(θ, φ), θ ∈ [0, π], φ ∈ [0, 2π].""" assume(abs(theta) > pi / 200) # we only need the backend's transpiler target for this test backend = MockSimulator(noisy=False) qc = QuantumCircuit(1) qc.append(test_gate(theta), (0,)) trans_qc = transpile(qc, backend, optimization_level=optimization_level) assert isinstance(trans_qc, QuantumCircuit) assert_circuits_equivalent(trans_qc, qc) assert set(trans_qc.count_ops()) <= set(backend.configuration().basis_gates) num_r = trans_qc.count_ops().get("r") assume(num_r is not None) assert num_r == 1 for operation in trans_qc.data: instruction = operation[0] if instruction.name == "r": theta, phi = instruction.params assert 0 <= float(theta) <= pi assert 0 <= float(phi) <= 2 * pi break else: # pragma: no cover pytest.fail("No R gates in transpiled circuit.") def test_decompose_1q_rotations_example(offline_simulator_no_noise: AQTResource) -> None: """Snapshot test for the efficient rewrite of single-qubit rotation runs as ZXZ.""" qc = QuantumCircuit(1) qc.rx(pi / 2, 0) qc.ry(pi / 2, 0) expected = QuantumCircuit(1) expected.rz(-pi / 2, 0) expected.r(pi / 2, 0, 0) result = transpile(qc, offline_simulator_no_noise, optimization_level=3) assert isinstance(result, QuantumCircuit) # only got one circuit back assert_circuits_equal(result, expected) assert_circuits_equivalent(result, expected) def test_rxx_wrap_angle_case0() -> None: """Snapshot test for Rxx(θ) rewrite with 0 <= θ <= π/2.""" result = QuantumCircuit(2) result.append(wrap_rxx_angle(pi / 2), (0, 1)) expected = QuantumCircuit(2) expected.rxx(pi / 2, 0, 1) assert_circuits_equal(result.decompose(), expected) assert_circuits_equivalent(result.decompose(), expected) def test_rxx_wrap_angle_case0_negative() -> None: """Snapshot test for Rxx(θ) rewrite with -π/2 <= θ < 0.""" result = QuantumCircuit(2) result.append(wrap_rxx_angle(-pi / 2), (0, 1)) expected = QuantumCircuit(2) expected.rz(pi, 0) expected.rxx(pi / 2, 0, 1) expected.rz(pi, 0) assert_circuits_equal(result.decompose(), expected) assert_circuits_equivalent(result.decompose(), expected) def test_rxx_wrap_angle_case1() -> None: """Snapshot test for Rxx(θ) rewrite with π/2 < θ <= 3π/2.""" result = QuantumCircuit(2) result.append(wrap_rxx_angle(3 * pi / 2), (0, 1)) expected = QuantumCircuit(2) expected.rx(pi, 0) expected.rx(pi, 1) expected.rxx(pi / 2, 0, 1) assert_circuits_equal(result.decompose(), expected) assert_circuits_equivalent(result.decompose(), expected) def test_rxx_wrap_angle_case1_negative() -> None: """Snapshot test for Rxx(θ) rewrite with -3π/2 <= θ < -π/2.""" result = QuantumCircuit(2) result.append(wrap_rxx_angle(-3 * pi / 2), (0, 1)) expected = QuantumCircuit(2) expected.rxx(pi / 2, 0, 1) assert_circuits_equal(result.decompose(), expected) assert_circuits_equivalent(result.decompose(), expected) def test_rxx_wrap_angle_case2() -> None: """Snapshot test for Rxx(θ) rewrite with θ > 3*π/2.""" result = QuantumCircuit(2) result.append(wrap_rxx_angle(18 * pi / 10), (0, 1)) # mod 2π = 9π/5 → -π/5 expected = QuantumCircuit(2) expected.rz(pi, 0) expected.rxx(pi / 5, 0, 1) expected.rz(pi, 0) assert_circuits_equal(result.decompose(), expected) assert_circuits_equivalent(result.decompose(), expected) def test_rxx_wrap_angle_case2_negative() -> None: """Snapshot test for Rxx(θ) rewrite with θ < -3π/2.""" result = QuantumCircuit(2) result.append(wrap_rxx_angle(-18 * pi / 10), (0, 1)) # mod 2π = π/5 expected = QuantumCircuit(2) expected.rxx(pi / 5, 0, 1) assert_circuits_equal(result.decompose(), expected) assert_circuits_equivalent(result.decompose(), expected) @given( angle=st.floats( allow_nan=False, allow_infinity=False, min_value=-1000 * pi, max_value=1000 * pi, ) ) @pytest.mark.parametrize("qubits", [3]) @pytest.mark.parametrize("optimization_level", [0, 1, 2, 3]) def test_rxx_wrap_angle_transpile(angle: float, qubits: int, optimization_level: int) -> None: """Check that Rxx angles are wrapped by the transpiler.""" assume(abs(angle) > pi / 200) qc = QuantumCircuit(qubits) qc.rxx(angle, 0, 1) # we only need the backend's transpilation target for this test backend = MockSimulator(noisy=False) trans_qc = transpile(qc, backend, optimization_level=optimization_level) assert isinstance(trans_qc, QuantumCircuit) assert_circuits_equivalent(trans_qc, qc) assert set(trans_qc.count_ops()) <= set(backend.configuration().basis_gates) num_rxx = trans_qc.count_ops().get("rxx", 0) # Higher optimization levels can optimize e.g. Rxx(2n*π) = Identity away. assert num_rxx <= 1 # check that the Rxx gate has angle in [0, π/2] for operation in trans_qc.data: instruction = operation[0] if instruction.name == "rxx": (theta,) = instruction.params assert 0 <= float(theta) <= pi / 2 break else: # pragma: no cover if num_rxx > 0: pytest.fail("Transpiled circuit contains no Rxx gate.") @example(angles_pi=[-582.16 / pi]) @given( angles_pi=st.lists( st.floats(min_value=-1000.0, max_value=1000.0, allow_nan=False), min_size=1, max_size=4, ) ) @pytest.mark.parametrize("optimization_level", [0, 1, 2, 3]) def test_transpilation_preserves_or_decreases_number_of_rxx_gates( angles_pi: list[float], optimization_level: int ) -> None: """Check that transpilation at least preserves the number of RXX gates.""" if optimization_level > 1: # FIXME: remove once https://github.com/Qiskit/qiskit/issues/12051 is fixed. assume(len(angles_pi) == 1) qc = QuantumCircuit(2) for angle_pi in angles_pi: qc.rxx(angle_pi * pi, 0, 1) # we only need the backend's transpilation target for this test backend = MockSimulator(noisy=False) tr_qc = transpile(qc, backend, optimization_level=optimization_level) tr_qc_ops = tr_qc.count_ops() assert set(tr_qc_ops) <= set(backend.configuration().basis_gates) qc_rxx = qc.count_ops()["rxx"] assert qc_rxx == len(angles_pi) assert tr_qc_ops.get("rxx", 0) <= qc_rxx @pytest.mark.parametrize("qubits", [1, 5, 10]) @pytest.mark.parametrize("optimization_level", [0, 1, 2, 3]) def test_qft_circuit_transpilation( qubits: int, optimization_level: int, offline_simulator_no_noise: AQTResource ) -> None: """Transpile a N-qubit QFT circuit for an AQT backend. Check that the angles are properly wrapped. """ qc = qft_circuit(qubits) trans_qc = transpile(qc, offline_simulator_no_noise, optimization_level=optimization_level) assert isinstance(trans_qc, QuantumCircuit) assert set(trans_qc.count_ops()) <= set(offline_simulator_no_noise.configuration().basis_gates) rxx_count = 0 r_count = 0 for operation in trans_qc.data: instruction = operation[0] if instruction.name == "rxx": (theta,) = instruction.params assert 0 <= float(theta) <= pi / 2 rxx_count += 1 if instruction.name == "r": (theta, _) = instruction.params assert abs(theta) <= pi r_count += 1 assert r_count > 0 if qubits > 1: assert rxx_count > 0 if optimization_level < 2 and qubits < 6: assert_circuits_equivalent(qc, trans_qc)
https://github.com/JavaFXpert/qiskit4devs-workshop-notebooks
JavaFXpert
# !pip install qiskit==0.7.1 # Include the necessary imports for this program import numpy as np from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute # Create a Quantum Register with 2 qubits qr = QuantumRegister(2) # Create a Classical Register with 2 bits cr = ClassicalRegister(2) # Create a Quantum Circuit from the quantum and classical registers circ = QuantumCircuit(qr, cr) # Place Hadamard gate on the top wire, putting this qubit in a superposition. circ.h(qr[0]) # Add a CX (CNOT) gate across the top two wires, entangling the qubits. circ.cx(qr[0], qr[1]) # Create a barrier that separates the gates from the measurements circ.barrier(qr) # Measure the qubits into the classical registers circ.measure(qr, cr) # Draw the new circuit circ.draw(output='mpl') # Use the BasicAer statevector_simulator backend from qiskit import BasicAer backend_sv_sim = BasicAer.get_backend('statevector_simulator') # Execute the circuit on the state vector simulator job_sim = execute(circ, backend_sv_sim) # Grab the results from the job. result_sim = job_sim.result() # Obtain the state vector for the quantum circuit quantum_state = result_sim.get_statevector(circ, decimals=3) # Output the quantum state vector in a manner that contains a comma-delimited string. quantum_state # Plot the state vector on a Q-sphere from qiskit.tools.visualization import plot_state_qsphere plot_state_qsphere(quantum_state) # Use the BasicAer qasm_simulator backend from qiskit import BasicAer backend_sim = BasicAer.get_backend('qasm_simulator') # Execute the circuit on the qasm simulator, running it 1000 times. job_sim = execute(circ, backend_sim, shots=1000) # Grab the results from the job. result_sim = job_sim.result() # Print the counts, which are contained in a Python dictionary counts = result_sim.get_counts(circ) print(counts) # Plot the results on a histogram from qiskit.tools.visualization import plot_histogram plot_histogram(counts) # Include the necessary imports for this program # Create a Quantum Register with 2 qubits # Create a Classical Register with 2 bits # Create a Quantum Circuit from the quantum and classical registers # Place appropriate gates on the wires to achieve the desired Bell state # Create a barrier that separates the gates from the measurements # Measure the qubits into the classical registers # Draw the circuit # Use the BasicAer statevector_simulator backend # Execute the circuit on the state vector simulator # Grab the results from the job. # Obtain the state vector for the quantum circuit # Output the quantum state vector in a manner that contains a comma-delimited string. # Plot the state vector on a Q-sphere # Use the BasicAer qasm_simulator backend # Execute the circuit on the qasm simulator, running it 1000 times. # Grab the results from the job. # Print the counts, which are contained in a Python dictionary # Plot the results on a histogram
https://github.com/JavaFXpert/qiskit4devs-workshop-notebooks
JavaFXpert
# Do the necessary import for our program #!pip install qiskit-aqua from qiskit import BasicAer from qiskit.aqua.algorithms import Grover from qiskit.aqua.components.oracles import LogicalExpressionOracle from qiskit.tools.visualization import plot_histogram log_expr = '((A & B) | (C & D)) & ~(A & D)' algorithm = Grover(LogicalExpressionOracle(log_expr)) # Run the algorithm on a simulator, printing the most frequently occurring result backend = BasicAer.get_backend('qasm_simulator') result = algorithm.run(backend) print(result['top_measurement']) plot_histogram(result['measurement'])
https://github.com/JavaFXpert/qiskit4devs-workshop-notebooks
JavaFXpert
#!pip install qiskit # Include the necessary imports for this program import numpy as np from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute # Create a Quantum Register with 3 qubits qr = QuantumRegister(3) # Create a Quantum Circuit from the quantum register. Because we're going to use # the statevector_simulator, we won't measure the circuit or need classical registers. circ = QuantumCircuit(qr) # Place an X gate on the 2nd and 3rd wires. The topmost wire is index 0. circ.x(qr[1]) circ.x(qr[2]) # Draw the circuit circ.draw(output='mpl') # Use the BasicAer statevector_simulator backend from qiskit import BasicAer backend_sv_sim = BasicAer.get_backend('statevector_simulator') # Execute the circuit on the state vector simulator job_sim = execute(circ, backend_sv_sim) # Grab the results from the job. result_sim = job_sim.result() # Obtain the state vector for the quantum circuit quantum_state = result_sim.get_statevector(circ, decimals=3) # Output the quantum state vector in a manner that contains a comma-delimited string. quantum_state # Plot the state vector on a Q-sphere from qiskit.tools.visualization import plot_state_qsphere plot_state_qsphere(quantum_state) # Create a Classical Register with 3 bits cr = ClassicalRegister(3) # Create the measurement portion of a quantum circuit meas_circ = QuantumCircuit(qr, cr) # Create a barrier that separates the gates from the measurements meas_circ.barrier(qr) # Measure the qubits into the classical registers meas_circ.measure(qr, cr) # Add the measument circuit to the original circuit complete_circuit = circ + meas_circ # Draw the new circuit complete_circuit.draw(output='mpl') # Use the BasicAer qasm_simulator backend from qiskit import BasicAer backend_sim = BasicAer.get_backend('qasm_simulator') # Execute the circuit on the qasm simulator, running it 1000 times. job_sim = execute(complete_circuit, backend_sim, shots=1000) # Grab the results from the job. result_sim = job_sim.result() # Print the counts, which are contained in a Python dictionary counts = result_sim.get_counts(complete_circuit) print(counts) # Plot the results on a histogram from qiskit.tools.visualization import plot_histogram plot_histogram(counts) # Include the necessary imports for this program # Create a Quantum Register with 3 qubits # Create a Quantum Circuit from the quantum register. Because we're going to use # the statevector_simulator, we won't measure the circuit or need classical registers. # Place Hadamard gate on each of the wires. # Draw the circuit # Use the BasicAer statevector_simulator backend # Execute the circuit on the state vector simulator # Grab the results from the job. # Obtain the state vector for the quantum circuit # Output the quantum state vector in a manner that contains a comma-delimited string. # Plot the state vector on a Q-sphere # Create a Classical Register with 3 bits # Create the measurement portion of a quantum circuit # Create a barrier that separates the gates from the measurements # Measure the qubits into the classical registers # Add the measument circuit to the original circuit # Draw the new circuit # Use the BasicAer qasm_simulator backend # Execute the circuit on the qasm simulator, running it 1000 times. # Grab the results from the job. # Print the counts, which are contained in a Python dictionary # Plot the results on a histogram
https://github.com/JavaFXpert/qiskit4devs-workshop-notebooks
JavaFXpert
#!pip install qiskit # Include the necessary imports for this program import numpy as np from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute # Create a Quantum Register with 1 qubit (wire). qr = QuantumRegister(1) # Create a Classical Register with 1 bit (double wire). cr = ClassicalRegister(1) # Create a Quantum Circuit from the quantum and classical registers circ = QuantumCircuit(qr, cr) # Place an Hadamard gate on the qubit wire circ.h(qr[0]) # Measure the qubit into the classical register circ.measure(qr, cr) # Draw the circuit circ.draw(output='mpl') # Import BasicAer from qiskit import BasicAer # Use BasicAer's qasm_simulator backend_sim = BasicAer.get_backend('qasm_simulator') # Execute the circuit on the qasm simulator, running it 100 times. job_sim = execute(circ, backend_sim, shots=100) # Grab the results from the job. result_sim = job_sim.result() # Print the counts, which are contained in a Python dictionary counts = result_sim.get_counts(circ) print(counts) from qiskit.tools.visualization import plot_histogram # Plot the results on a bar chart plot_histogram(counts) # Include the necessary imports for this program # Create a Quantum Register with 1 qubit (wire). # Create a Classical Register with 1 bit (double wire). # Create a Quantum Circuit from the quantum and classical registers # Place an X gate followed by a Hadamard gate on the qubit wire. The registers are zero-indexed. # Measure the qubit into the classical register # Draw the circuit # Import BasicAer # Use BasicAer's qasm_simulator # Execute the circuit on the qasm simulator, running it 100 times. # Grab the results from the job. # Print the counts, which are contained in a Python dictionary # Plot the results on a bar chart
https://github.com/JavaFXpert/qiskit4devs-workshop-notebooks
JavaFXpert
#!pip install qiskit # Include the necessary imports for this program import numpy as np from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute # Create a Quantum Register with 1 qubit (wire). qr = QuantumRegister(1) # Create a Classical Register with 1 bit (double wire). cr = ClassicalRegister(1) # Create a Quantum Circuit from the quantum and classical registers circ = QuantumCircuit(qr, cr) # Place an X gate on the qubit wire. The registers are zero-indexed. circ.x(qr[0]) # Measure the qubit into the classical register circ.measure(qr, cr) # Draw the circuit circ.draw(output='mpl') # Import BasicAer from qiskit import BasicAer # Use BasicAer's qasm_simulator backend_sim = BasicAer.get_backend('qasm_simulator') # Execute the circuit on the qasm simulator, running it 100 times. job_sim = execute(circ, backend_sim, shots=100) # Grab the results from the job. result_sim = job_sim.result() # Print the counts, which are contained in a Python dictionary counts = result_sim.get_counts(circ) print(counts) from qiskit.tools.visualization import plot_histogram # Plot the results on a bar chart plot_histogram(counts) # Include the necessary imports for this program # Create a Quantum Register with 1 qubit (wire). # Create a Classical Register with 1 bit (double wire). # Create a Quantum Circuit from the quantum and classical registers # Place two X gates on the qubit wire. The registers are zero-indexed. # Measure the qubit into the classical register # Draw the circuit # Import BasicAer # Use BasicAer's qasm_simulator # Execute the circuit on the qasm simulator, running it 100 times. # Grab the results from the job. # Print the counts, which are contained in a Python dictionary # Plot the results on a bar chart
https://github.com/JavaFXpert/qiskit4devs-workshop-notebooks
JavaFXpert
#!pip install qiskit # Do the usual setup, but without classical registers or measurement import numpy as np from qiskit import QuantumCircuit, QuantumRegister, execute qr = QuantumRegister(1) circ = QuantumCircuit(qr) # Place an Ry gate with a −3π/4 rotation circ.ry(-3/4 * np.pi, qr[0]) # Draw the circuit circ.draw(output='mpl') # Use the BasicAer statevector_simulator backend from qiskit import BasicAer backend_sv_sim = BasicAer.get_backend('statevector_simulator') job_sim = execute(circ, backend_sv_sim) result_sim = job_sim.result() quantum_state = result_sim.get_statevector(circ, decimals=3) # Output the quantum state vector quantum_state # Plot the state vector on a Bloch sphere from qiskit.tools.visualization import plot_bloch_multivector plot_bloch_multivector(quantum_state) # Do the usual setup, but without classical registers or measurement import numpy as np from qiskit import QuantumCircuit, QuantumRegister, execute qr = QuantumRegister(1) circ = QuantumCircuit(qr) # Place gates that will achieve the desired state # Draw the circuit circ.draw(output='mpl') # Use the BasicAer statevector_simulator backend from qiskit import BasicAer backend_sv_sim = BasicAer.get_backend('statevector_simulator') job_sim = execute(circ, backend_sv_sim) result_sim = job_sim.result() quantum_state = result_sim.get_statevector(circ, decimals=3) # Output the quantum state vector quantum_state # Plot the state vector on a Bloch sphere from qiskit.tools.visualization import plot_bloch_multivector plot_bloch_multivector(quantum_state)
https://github.com/chunfuchen/qiskit-chemistry
chunfuchen
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2018, 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. import logging import numpy as np from qiskit import QuantumRegister, QuantumCircuit from qiskit.aqua.components.initial_states import InitialState logger = logging.getLogger(__name__) class HartreeFock(InitialState): """A Hartree-Fock initial state.""" CONFIGURATION = { 'name': 'HartreeFock', 'description': 'Hartree-Fock initial state', 'input_schema': { '$schema': 'http://json-schema.org/schema#', 'id': 'hf_state_schema', 'type': 'object', 'properties': { 'num_orbitals': { 'type': 'integer', 'default': 4, 'minimum': 1 }, 'num_particles': { 'type': 'integer', 'default': 2, 'minimum': 1 }, 'qubit_mapping': { 'type': 'string', 'default': 'parity', 'oneOf': [ {'enum': ['jordan_wigner', 'parity', 'bravyi_kitaev']} ] }, 'two_qubit_reduction': { 'type': 'boolean', 'default': True } }, 'additionalProperties': False } } def __init__(self, num_qubits, num_orbitals, num_particles, qubit_mapping='parity', two_qubit_reduction=True, sq_list=None): """Constructor. Args: num_qubits (int): number of qubits num_orbitals (int): number of spin orbitals qubit_mapping (str): mapping type for qubit operator two_qubit_reduction (bool): flag indicating whether or not two qubit is reduced num_particles (int): number of particles sq_list ([int]): position of the single-qubit operators that anticommute with the cliffords Raises: ValueError: wrong setting in num_particles and num_orbitals. ValueError: wrong setting for computed num_qubits and supplied num_qubits. """ self.validate(locals()) super().__init__() self._sq_list = sq_list self._qubit_tapering = False if self._sq_list is None else True self._qubit_mapping = qubit_mapping.lower() self._two_qubit_reduction = two_qubit_reduction if self._qubit_mapping != 'parity': if self._two_qubit_reduction: logger.warning("two_qubit_reduction only works with parity qubit mapping " "but you have {}. We switch two_qubit_reduction " "to False.".format(self._qubit_mapping)) self._two_qubit_reduction = False self._num_orbitals = num_orbitals self._num_particles = num_particles if self._num_particles > self._num_orbitals: raise ValueError("# of particles must be less than or equal to # of orbitals.") self._num_qubits = num_orbitals - 2 if self._two_qubit_reduction else self._num_orbitals self._num_qubits = self._num_qubits \ if not self._qubit_tapering else self._num_qubits - len(sq_list) if self._num_qubits != num_qubits: raise ValueError("Computed num qubits {} does not match " "actual {}".format(self._num_qubits, num_qubits)) self._bitstr = None def _build_bitstr(self): half_orbitals = self._num_orbitals // 2 bitstr = np.zeros(self._num_orbitals, np.bool) bitstr[-int(np.ceil(self._num_particles / 2)):] = True bitstr[-(half_orbitals + int(np.floor(self._num_particles / 2))):-half_orbitals] = True if self._qubit_mapping == 'parity': new_bitstr = bitstr.copy() t = np.triu(np.ones((self._num_orbitals, self._num_orbitals))) new_bitstr = t.dot(new_bitstr.astype(np.int)) % 2 bitstr = np.append(new_bitstr[1:half_orbitals], new_bitstr[half_orbitals + 1:]) \ if self._two_qubit_reduction else new_bitstr elif self._qubit_mapping == 'bravyi_kitaev': binary_superset_size = int(np.ceil(np.log2(self._num_orbitals))) beta = 1 basis = np.asarray([[1, 0], [0, 1]]) for i in range(binary_superset_size): beta = np.kron(basis, beta) beta[0, :] = 1 beta = beta[:self._num_orbitals, :self._num_orbitals] new_bitstr = beta.dot(bitstr.astype(int)) % 2 bitstr = new_bitstr.astype(np.bool) if self._qubit_tapering: sq_list = (len(bitstr) - 1) - np.asarray(self._sq_list) bitstr = np.delete(bitstr, sq_list) self._bitstr = bitstr.astype(np.bool) def construct_circuit(self, mode, register=None): """ Construct the statevector of desired initial state. Args: mode (string): `vector` or `circuit`. The `vector` mode produces the vector. While the `circuit` constructs the quantum circuit corresponding that vector. register (QuantumRegister): register for circuit construction. Returns: QuantumCircuit or numpy.ndarray: statevector. Raises: ValueError: when mode is not 'vector' or 'circuit'. """ if self._bitstr is None: self._build_bitstr() if mode == 'vector': state = 1.0 one = np.asarray([0.0, 1.0]) zero = np.asarray([1.0, 0.0]) for k in self._bitstr[::-1]: state = np.kron(one if k else zero, state) return state elif mode == 'circuit': if register is None: register = QuantumRegister(self._num_qubits, name='q') quantum_circuit = QuantumCircuit(register) for qubit_idx, bit in enumerate(self._bitstr[::-1]): if bit: quantum_circuit.u3(np.pi, 0.0, np.pi, register[qubit_idx]) return quantum_circuit else: raise ValueError('Mode should be either "vector" or "circuit"') @property def bitstr(self): """Getter of the bit string represented the statevector.""" if self._bitstr is None: self._build_bitstr() return self._bitstr
https://github.com/chunfuchen/qiskit-chemistry
chunfuchen
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2018, 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. """ This trial wavefunction is a Unitary Coupled-Cluster Single and Double excitations variational form. For more information, see https://arxiv.org/abs/1805.04340 """ import logging import sys import numpy as np from qiskit import QuantumRegister, QuantumCircuit from qiskit.tools import parallel_map from qiskit.tools.events import TextProgressBar from qiskit.aqua import Operator, aqua_globals from qiskit.aqua.components.variational_forms import VariationalForm from qiskit.chemistry.fermionic_operator import FermionicOperator from qiskit.chemistry import MP2Info from qiskit.chemistry import QMolecule as qm logger = logging.getLogger(__name__) class UCCSD(VariationalForm): """ This trial wavefunction is a Unitary Coupled-Cluster Single and Double excitations variational form. For more information, see https://arxiv.org/abs/1805.04340 """ CONFIGURATION = { 'name': 'UCCSD', 'description': 'UCCSD Variational Form', 'input_schema': { '$schema': 'http://json-schema.org/schema#', 'id': 'uccsd_schema', 'type': 'object', 'properties': { 'depth': { 'type': 'integer', 'default': 1, 'minimum': 1 }, 'num_orbitals': { 'type': 'integer', 'default': 4, 'minimum': 1 }, 'num_particles': { 'type': 'integer', 'default': 2, 'minimum': 1 }, 'active_occupied': { 'type': ['array', 'null'], 'default': None }, 'active_unoccupied': { 'type': ['array', 'null'], 'default': None }, 'qubit_mapping': { 'type': 'string', 'default': 'parity', 'oneOf': [ {'enum': ['jordan_wigner', 'parity', 'bravyi_kitaev']} ] }, 'two_qubit_reduction': { 'type': 'boolean', 'default': False }, 'mp2_reduction': { 'type': 'boolean', 'default': False }, 'num_time_slices': { 'type': 'integer', 'default': 1, 'minimum': 1 }, }, 'additionalProperties': False }, 'depends': [ { 'pluggable_type': 'initial_state', 'default': { 'name': 'HartreeFock', } }, ], } def __init__(self, num_qubits, depth, num_orbitals, num_particles, active_occupied=None, active_unoccupied=None, initial_state=None, qubit_mapping='parity', two_qubit_reduction=False, mp2_reduction=False, num_time_slices=1, cliffords=None, sq_list=None, tapering_values=None, symmetries=None, shallow_circuit_concat=True): """Constructor. Args: num_orbitals (int): number of spin orbitals depth (int): number of replica of basic module num_particles (int): number of particles active_occupied (list): list of occupied orbitals to consider as active space active_unoccupied (list): list of unoccupied orbitals to consider as active space initial_state (InitialState): An initial state object. qubit_mapping (str): qubit mapping type. two_qubit_reduction (bool): two qubit reduction is applied or not. num_time_slices (int): parameters for dynamics. cliffords ([Operator]): list of unitary Clifford transformation sq_list ([int]): position of the single-qubit operators that anticommute with the cliffords tapering_values ([int]): array of +/- 1 used to select the subspace. Length has to be equal to the length of cliffords and sq_list symmetries ([Pauli]): represent the Z2 symmetries shallow_circuit_concat (bool): indicate whether to use shallow (cheap) mode for circuit concatenation """ self.validate(locals()) super().__init__() self._cliffords = cliffords self._sq_list = sq_list self._tapering_values = tapering_values self._symmetries = symmetries if self._cliffords is not None and self._sq_list is not None and \ self._tapering_values is not None and self._symmetries is not None: self._qubit_tapering = True else: self._qubit_tapering = False self._num_qubits = num_orbitals if not two_qubit_reduction else num_orbitals - 2 self._num_qubits = self._num_qubits if not self._qubit_tapering else self._num_qubits - len(sq_list) if self._num_qubits != num_qubits: raise ValueError('Computed num qubits {} does not match actual {}' .format(self._num_qubits, num_qubits)) self._depth = depth self._num_orbitals = num_orbitals self._num_particles = num_particles if self._num_particles > self._num_orbitals: raise ValueError('# of particles must be less than or equal to # of orbitals.') self._initial_state = initial_state self._qubit_mapping = qubit_mapping self._two_qubit_reduction = two_qubit_reduction self._num_time_slices = num_time_slices self._shallow_circuit_concat = shallow_circuit_concat self._single_excitations, self._double_excitations = \ UCCSD.compute_excitation_lists(num_particles, num_orbitals, active_occupied, active_unoccupied) self._single_excitations = [] print('{} are the old doubles'.format(self._double_excitations)) print(mp2_reduction) if mp2_reduction: print('Getting new doubles') self._double_excitations = get_mp2_doubles(self._single_excitations,self._double_excitations) print('{} are the new doubles'.format(self._double_excitations)) self._hopping_ops, self._num_parameters = self._build_hopping_operators() self._bounds = [(-np.pi, np.pi) for _ in range(self._num_parameters)] self._logging_construct_circuit = True def _build_hopping_operators(self): from .uccsd import UCCSD hopping_ops = [] if logger.isEnabledFor(logging.DEBUG): TextProgressBar(sys.stderr) results = parallel_map(UCCSD._build_hopping_operator, self._single_excitations + self._double_excitations, task_args=(self._num_orbitals, self._num_particles, self._qubit_mapping, self._two_qubit_reduction, self._qubit_tapering, self._symmetries, self._cliffords, self._sq_list, self._tapering_values), num_processes=aqua_globals.num_processes) hopping_ops = [qubit_op for qubit_op in results if qubit_op is not None] num_parameters = len(hopping_ops) * self._depth return hopping_ops, num_parameters @staticmethod def _build_hopping_operator(index, num_orbitals, num_particles, qubit_mapping, two_qubit_reduction, qubit_tapering, symmetries, cliffords, sq_list, tapering_values): def check_commutativity(op_1, op_2): com = op_1 * op_2 - op_2 * op_1 com.zeros_coeff_elimination() return True if com.is_empty() else False h1 = np.zeros((num_orbitals, num_orbitals)) h2 = np.zeros((num_orbitals, num_orbitals, num_orbitals, num_orbitals)) if len(index) == 2: i, j = index h1[i, j] = 1.0 h1[j, i] = -1.0 elif len(index) == 4: i, j, k, m = index h2[i, j, k, m] = 1.0 h2[m, k, j, i] = -1.0 dummpy_fer_op = FermionicOperator(h1=h1, h2=h2) qubit_op = dummpy_fer_op.mapping(qubit_mapping) qubit_op = qubit_op.two_qubit_reduced_operator(num_particles) \ if two_qubit_reduction else qubit_op if qubit_tapering: for symmetry in symmetries: symmetry_op = Operator(paulis=[[1.0, symmetry]]) symm_commuting = check_commutativity(symmetry_op, qubit_op) if not symm_commuting: break if qubit_tapering: if symm_commuting: qubit_op = Operator.qubit_tapering(qubit_op, cliffords, sq_list, tapering_values) else: qubit_op = None if qubit_op is None: logger.debug('Excitation ({}) is skipped since it is not commuted ' 'with symmetries'.format(','.join([str(x) for x in index]))) return qubit_op def construct_circuit(self, parameters, q=None): """ Construct the variational form, given its parameters. Args: parameters (numpy.ndarray): circuit parameters q (QuantumRegister): Quantum Register for the circuit. Returns: QuantumCircuit: a quantum circuit with given `parameters` Raises: ValueError: the number of parameters is incorrect. """ from .uccsd import UCCSD if len(parameters) != self._num_parameters: raise ValueError('The number of parameters has to be {}'.format(self._num_parameters)) if q is None: q = QuantumRegister(self._num_qubits, name='q') if self._initial_state is not None: circuit = self._initial_state.construct_circuit('circuit', q) else: circuit = QuantumCircuit(q) if logger.isEnabledFor(logging.DEBUG) and self._logging_construct_circuit: logger.debug("Evolving hopping operators:") TextProgressBar(sys.stderr) self._logging_construct_circuit = False num_excitations = len(self._hopping_ops) results = parallel_map(UCCSD._construct_circuit_for_one_excited_operator, [(self._hopping_ops[index % num_excitations], parameters[index]) for index in range(self._depth * num_excitations)], task_args=(q, self._num_time_slices), num_processes=aqua_globals.num_processes) for qc in results: if self._shallow_circuit_concat: circuit.data += qc.data else: circuit += qc return circuit @staticmethod def _construct_circuit_for_one_excited_operator(qubit_op_and_param, qr, num_time_slices): qubit_op, param = qubit_op_and_param qc = qubit_op.evolve(None, param * -1j, 'circuit', num_time_slices, qr) return qc @property def preferred_init_points(self): """Getter of preferred initial points based on the given initial state.""" if self._initial_state is None: return None else: bitstr = self._initial_state.bitstr if bitstr is not None: return np.zeros(self._num_parameters, dtype=np.float) else: return None @staticmethod def compute_excitation_lists(num_particles, num_orbitals, active_occ_list=None, active_unocc_list=None, same_spin_doubles=True): """ Computes single and double excitation lists Args: num_particles: Total number of particles num_orbitals: Total number of spin orbitals active_occ_list: List of occupied orbitals to include, indices are 0 to n where n is num particles // 2 active_unocc_list: List of unoccupied orbitals to include, indices are 0 to m where m is (num_orbitals - num particles) // 2 same_spin_doubles: True to include alpha,alpha and beta,beta double excitations as well as alpha,beta pairings. False includes only alpha,beta Returns: Single and double excitation lists """ if num_particles < 2 or num_particles % 2 != 0: raise ValueError('Invalid number of particles {}'.format(num_particles)) if num_orbitals < 4 or num_orbitals % 2 != 0: raise ValueError('Invalid number of orbitals {}'.format(num_orbitals)) if num_orbitals <= num_particles: raise ValueError('No unoccupied orbitals') if active_occ_list is not None: active_occ_list = [i if i >= 0 else i + num_particles // 2 for i in active_occ_list] for i in active_occ_list: if i >= num_particles // 2: raise ValueError('Invalid index {} in active active_occ_list {}' .format(i, active_occ_list)) if active_unocc_list is not None: active_unocc_list = [i + num_particles // 2 if i >= 0 else i + num_orbitals // 2 for i in active_unocc_list] for i in active_unocc_list: if i < 0 or i >= num_orbitals // 2: raise ValueError('Invalid index {} in active active_unocc_list {}' .format(i, active_unocc_list)) if active_occ_list is None or len(active_occ_list) <= 0: active_occ_list = [i for i in range(0, num_particles // 2)] if active_unocc_list is None or len(active_unocc_list) <= 0: active_unocc_list = [i for i in range(num_particles // 2, num_orbitals // 2)] single_excitations = [] double_excitations = [] logger.debug('active_occ_list {}'.format(active_occ_list)) logger.debug('active_unocc_list {}'.format(active_unocc_list)) beta_idx = num_orbitals // 2 for occ_alpha in active_occ_list: for unocc_alpha in active_unocc_list: single_excitations.append([occ_alpha, unocc_alpha]) for occ_beta in [i + beta_idx for i in active_occ_list]: for unocc_beta in [i + beta_idx for i in active_unocc_list]: single_excitations.append([occ_beta, unocc_beta]) for occ_alpha in active_occ_list: for unocc_alpha in active_unocc_list: for occ_beta in [i + beta_idx for i in active_occ_list]: for unocc_beta in [i + beta_idx for i in active_unocc_list]: double_excitations.append([occ_alpha, unocc_alpha, occ_beta, unocc_beta]) if same_spin_doubles and len(active_occ_list) > 1 and len(active_unocc_list) > 1: for i, occ_alpha in enumerate(active_occ_list[:-1]): for j, unocc_alpha in enumerate(active_unocc_list[:-1]): for occ_alpha_1 in active_occ_list[i + 1:]: for unocc_alpha_1 in active_unocc_list[j + 1:]: double_excitations.append([occ_alpha, unocc_alpha, occ_alpha_1, unocc_alpha_1]) up_active_occ_list = [i + beta_idx for i in active_occ_list] up_active_unocc_list = [i + beta_idx for i in active_unocc_list] for i, occ_beta in enumerate(up_active_occ_list[:-1]): for j, unocc_beta in enumerate(up_active_unocc_list[:-1]): for occ_beta_1 in up_active_occ_list[i + 1:]: for unocc_beta_1 in up_active_unocc_list[j + 1:]: double_excitations.append([occ_beta, unocc_beta, occ_beta_1, unocc_beta_1]) logger.debug('single_excitations ({}) {}'.format(len(single_excitations), single_excitations)) logger.debug('double_excitations ({}) {}'.format(len(double_excitations), double_excitations)) return single_excitations, double_excitations def get_mp2_doubles(single_excitations, double_excitations): print('Is the class still populated with the correct info: ', qm.nuclear_repulsion_energy) mp2 = MP2Info(qm, single_excitations, double_excitations, threshold=1e-3) mp2_doubles = mp2._mp2_doubles return mp2_doubles
https://github.com/chunfuchen/qiskit-chemistry
chunfuchen
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2018, 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. import unittest from parameterized import parameterized import numpy as np import qiskit from qiskit.transpiler import PassManager from qiskit.aqua.utils import decimal_to_binary from qiskit.aqua import QuantumInstance from qiskit.aqua.algorithms.single_sample import IQPE from qiskit.aqua.algorithms.classical import ExactEigensolver from test.common import QiskitChemistryTestCase from qiskit.chemistry.drivers import PySCFDriver, UnitsType from qiskit.chemistry import FermionicOperator, QiskitChemistryError from qiskit.chemistry.aqua_extensions.components.initial_states import HartreeFock class TestIQPE(QiskitChemistryTestCase): """IQPE tests.""" @parameterized.expand([ [0.5], [0.735], [1], ]) def test_iqpe(self, distance): self.algorithm = 'IQPE' self.log.debug('Testing End-to-End with IQPE on H2 with ' 'inter-atomic distance {}.'.format(distance)) try: driver = PySCFDriver(atom='H .0 .0 .0; H .0 .0 {}'.format(distance), unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') except QiskitChemistryError: self.skipTest('PYSCF driver does not appear to be installed') self.molecule = driver.run() qubit_mapping = 'parity' fer_op = FermionicOperator(h1=self.molecule.one_body_integrals, h2=self.molecule.two_body_integrals) self.qubit_op = fer_op.mapping(map_type=qubit_mapping, threshold=1e-10).two_qubit_reduced_operator(2) exact_eigensolver = ExactEigensolver(self.qubit_op, k=1) results = exact_eigensolver.run() self.reference_energy = results['energy'] self.log.debug('The exact ground state energy is: {}'.format(results['energy'])) num_particles = self.molecule.num_alpha + self.molecule.num_beta two_qubit_reduction = True num_orbitals = self.qubit_op.num_qubits + (2 if two_qubit_reduction else 0) num_time_slices = 50 num_iterations = 12 state_in = HartreeFock(self.qubit_op.num_qubits, num_orbitals, num_particles, qubit_mapping, two_qubit_reduction) iqpe = IQPE(self.qubit_op, state_in, num_time_slices, num_iterations, expansion_mode='suzuki', expansion_order=2, shallow_circuit_concat=True) backend = qiskit.BasicAer.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend, shots=100, pass_manager=PassManager()) result = iqpe.run(quantum_instance) self.log.debug('top result str label: {}'.format(result['top_measurement_label'])) self.log.debug('top result in decimal: {}'.format(result['top_measurement_decimal'])) self.log.debug('stretch: {}'.format(result['stretch'])) self.log.debug('translation: {}'.format(result['translation'])) self.log.debug('final energy from QPE: {}'.format(result['energy'])) self.log.debug('reference energy: {}'.format(self.reference_energy)) self.log.debug('ref energy (transformed): {}'.format( (self.reference_energy + result['translation']) * result['stretch']) ) self.log.debug('ref binary str label: {}'.format(decimal_to_binary( (self.reference_energy + result['translation']) * result['stretch'], max_num_digits=num_iterations + 3, fractional_part_only=True ))) np.testing.assert_approx_equal(result['energy'], self.reference_energy, significant=2) if __name__ == '__main__': unittest.main()
https://github.com/chunfuchen/qiskit-chemistry
chunfuchen
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2018, 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. import unittest from parameterized import parameterized import numpy as np import qiskit from qiskit.transpiler import PassManager from qiskit.aqua.utils import decimal_to_binary from qiskit.aqua import QuantumInstance from qiskit.aqua.algorithms.single_sample import QPE from qiskit.aqua.algorithms.classical import ExactEigensolver from qiskit.aqua.components.iqfts import Standard from test.common import QiskitChemistryTestCase from qiskit.chemistry.drivers import PySCFDriver, UnitsType from qiskit.chemistry import FermionicOperator, QiskitChemistryError from qiskit.chemistry.aqua_extensions.components.initial_states import HartreeFock class TestEnd2EndWithQPE(QiskitChemistryTestCase): """QPE tests.""" @parameterized.expand([ [0.5], [0.735], [1], ]) def test_qpe(self, distance): self.algorithm = 'QPE' self.log.debug('Testing End-to-End with QPE on H2 with inter-atomic distance {}.'.format(distance)) try: driver = PySCFDriver(atom='H .0 .0 .0; H .0 .0 {}'.format(distance), unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') except QiskitChemistryError: self.skipTest('PYSCF driver does not appear to be installed') self.molecule = driver.run() qubit_mapping = 'parity' fer_op = FermionicOperator( h1=self.molecule.one_body_integrals, h2=self.molecule.two_body_integrals) self.qubit_op = fer_op.mapping(map_type=qubit_mapping, threshold=1e-10).two_qubit_reduced_operator(2) exact_eigensolver = ExactEigensolver(self.qubit_op, k=1) results = exact_eigensolver.run() self.reference_energy = results['energy'] self.log.debug( 'The exact ground state energy is: {}'.format(results['energy'])) num_particles = self.molecule.num_alpha + self.molecule.num_beta two_qubit_reduction = True num_orbitals = self.qubit_op.num_qubits + \ (2 if two_qubit_reduction else 0) num_time_slices = 50 n_ancillae = 9 state_in = HartreeFock(self.qubit_op.num_qubits, num_orbitals, num_particles, qubit_mapping, two_qubit_reduction) iqft = Standard(n_ancillae) qpe = QPE(self.qubit_op, state_in, iqft, num_time_slices, n_ancillae, expansion_mode='suzuki', expansion_order=2, shallow_circuit_concat=True) backend = qiskit.BasicAer.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend, shots=100, pass_manager=PassManager()) result = qpe.run(quantum_instance) self.log.debug('eigvals: {}'.format(result['eigvals'])) self.log.debug('top result str label: {}'.format(result['top_measurement_label'])) self.log.debug('top result in decimal: {}'.format(result['top_measurement_decimal'])) self.log.debug('stretch: {}'.format(result['stretch'])) self.log.debug('translation: {}'.format(result['translation'])) self.log.debug('final energy from QPE: {}'.format(result['energy'])) self.log.debug('reference energy: {}'.format(self.reference_energy)) self.log.debug('ref energy (transformed): {}'.format( (self.reference_energy + result['translation']) * result['stretch'])) self.log.debug('ref binary str label: {}'.format(decimal_to_binary((self.reference_energy + result['translation']) * result['stretch'], max_num_digits=n_ancillae + 3, fractional_part_only=True))) np.testing.assert_approx_equal( result['energy'], self.reference_energy, significant=2) if __name__ == '__main__': unittest.main()
https://github.com/chunfuchen/qiskit-chemistry
chunfuchen
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2018, 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. import unittest from parameterized import parameterized import qiskit from qiskit.aqua import QuantumInstance from qiskit.aqua.algorithms.adaptive import VQE from qiskit.aqua.components.variational_forms import RYRZ from qiskit.aqua.components.optimizers import COBYLA, SPSA from test.common import QiskitChemistryTestCase from qiskit.chemistry.drivers import HDF5Driver from qiskit.chemistry.core import Hamiltonian, TransformationType, QubitMappingType class TestEnd2End(QiskitChemistryTestCase): """End2End tests.""" def setUp(self): super().setUp() driver = HDF5Driver(hdf5_input=self._get_resource_path('test_driver_hdf5.hdf5')) self.qmolecule = driver.run() core = Hamiltonian(transformation=TransformationType.FULL, qubit_mapping=QubitMappingType.PARITY, two_qubit_reduction=True, freeze_core=False, orbital_reduction=[]) self.qubit_op, self.aux_ops = core.run(self.qmolecule) self.reference_energy = -1.857275027031588 @parameterized.expand([ ['COBYLA_M', 'COBYLA', qiskit.BasicAer.get_backend('statevector_simulator'), 'matrix', 1], ['COBYLA_P', 'COBYLA', qiskit.BasicAer.get_backend('statevector_simulator'), 'paulis', 1], # ['SPSA_P', 'SPSA', qiskit.BasicAer.get_backend('qasm_simulator'), 'paulis', 1024], # ['SPSA_GP', 'SPSA', qiskit.BasicAer.get_backend('qasm_simulator'), 'grouped_paulis', 1024] ]) def test_end2end_h2(self, name, optimizer, backend, mode, shots): if optimizer == 'COBYLA': optimizer = COBYLA() optimizer.set_options(maxiter=1000) elif optimizer == 'SPSA': optimizer = SPSA(max_trials=2000) ryrz = RYRZ(self.qubit_op.num_qubits, depth=3, entanglement='full') vqe = VQE(self.qubit_op, ryrz, optimizer, mode, aux_operators=self.aux_ops) quantum_instance = QuantumInstance(backend, shots=shots) results = vqe.run(quantum_instance) self.assertAlmostEqual(results['energy'], self.reference_energy, places=4) if __name__ == '__main__': unittest.main()
https://github.com/chunfuchen/qiskit-chemistry
chunfuchen
# -*- coding: utf-8 -*- # 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 of Symmetry UCCSD processing. """ import itertools from test.common import QiskitChemistryTestCase from qiskit import BasicAer from qiskit.aqua import QuantumInstance, Operator from qiskit.aqua.algorithms.adaptive import VQE from qiskit.aqua.components.optimizers import SLSQP from qiskit.chemistry import QiskitChemistryError from qiskit.chemistry.core import Hamiltonian, TransformationType, QubitMappingType from qiskit.chemistry.drivers import PySCFDriver, UnitsType from qiskit.chemistry.aqua_extensions.components.variational_forms import UCCSD from qiskit.chemistry.aqua_extensions.components.initial_states import HartreeFock # from qiskit.chemistry import set_qiskit_chemistry_logging # import logging class TestSymmetries(QiskitChemistryTestCase): """Test for symmetry processing.""" def setUp(self): super().setUp() try: driver = PySCFDriver(atom='Li .0 .0 .0; H .0 .0 1.6', unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') except QiskitChemistryError: self.skipTest('PYSCF driver does not appear to be installed') self.qmolecule = driver.run() self.core = Hamiltonian(transformation=TransformationType.FULL, qubit_mapping=QubitMappingType.PARITY, two_qubit_reduction=True, freeze_core=True, orbital_reduction=[]) self.qubit_op, _ = self.core.run(self.qmolecule) self.symmetries, self.sq_paulis, self.cliffords, self.sq_list = self.qubit_op.find_Z2_symmetries() self.reference_energy = -7.882096489442 def test_symmetries(self): labels = [symm.to_label() for symm in self.symmetries] self.assertSequenceEqual(labels, ['ZIZIZIZI', 'ZZIIZZII']) def test_sq_paulis(self): labels = [sq.to_label() for sq in self.sq_paulis] self.assertSequenceEqual(labels, ['IIIIIIXI', 'IIIIIXII']) def test_cliffords(self): self.assertEqual(2, len(self.cliffords)) def test_sq_list(self): self.assertSequenceEqual(self.sq_list, [1, 2]) def test_tapered_op(self): # set_qiskit_chemistry_logging(logging.DEBUG) tapered_ops = [] for coeff in itertools.product([1, -1], repeat=len(self.sq_list)): tapered_op = Operator.qubit_tapering(self.qubit_op, self.cliffords, self.sq_list, list(coeff)) tapered_ops.append((list(coeff), tapered_op)) smallest_idx = 0 # Prior knowledge of which tapered_op has ground state the_tapered_op = tapered_ops[smallest_idx][1] the_coeff = tapered_ops[smallest_idx][0] optimizer = SLSQP(maxiter=1000) init_state = HartreeFock(num_qubits=the_tapered_op.num_qubits, num_orbitals=self.core._molecule_info['num_orbitals'], qubit_mapping=self.core._qubit_mapping, two_qubit_reduction=self.core._two_qubit_reduction, num_particles=self.core._molecule_info['num_particles'], sq_list=self.sq_list) var_form = UCCSD(num_qubits=the_tapered_op.num_qubits, depth=1, num_orbitals=self.core._molecule_info['num_orbitals'], num_particles=self.core._molecule_info['num_particles'], active_occupied=None, active_unoccupied=None, initial_state=init_state, qubit_mapping=self.core._qubit_mapping, two_qubit_reduction=self.core._two_qubit_reduction, num_time_slices=1, cliffords=self.cliffords, sq_list=self.sq_list, tapering_values=the_coeff, symmetries=self.symmetries) algo = VQE(the_tapered_op, var_form, optimizer, 'matrix') backend = BasicAer.get_backend('statevector_simulator') quantum_instance = QuantumInstance(backend=backend) algo_result = algo.run(quantum_instance) lines, result = self.core.process_algorithm_result(algo_result) self.assertAlmostEqual(result['energy'], self.reference_energy, places=6)
https://github.com/Qiskit-Extensions/qiskit-ibm-experiment
Qiskit-Extensions
from qiskit import IBMQ provider = IBMQ.load_account() service = provider.experiment experiment_data = service.experiment(experiment_id = '5524b504-2f59-11ed-a7c7-bc97e15b08d0') print(experiment_data['creation_datetime']) print(experiment_data['metadata']['user']) from qiskit_ibm_experiment import IBMExperimentService service = IBMExperimentService() experiment_data = service.experiment(experiment_id = '5524b504-2f59-11ed-a7c7-bc97e15b08d0') print(experiment_data.creation_datetime) print(experiment_data.metadata['user'])
https://github.com/Qiskit-Extensions/qiskit-ibm-experiment
Qiskit-Extensions
# This code is part of Qiskit. # # (C) Copyright IBM 2021-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. """Experiment integration tests.""" import os import unittest from unittest import mock, skipIf import contextlib from test.service.ibm_test_case import IBMTestCase import numpy as np from qiskit import transpile, QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.providers import JobStatus from qiskit_experiments.framework import ( ExperimentData, ExperimentDecoder, ExperimentEncoder, ) from qiskit_experiments.framework.experiment_data import ExperimentStatus from qiskit_experiments.framework import AnalysisResult from qiskit_experiments.database_service.exceptions import ExperimentEntryNotFound from qiskit_ibm_runtime import QiskitRuntimeService from qiskit_ibm_experiment import IBMExperimentService from qiskit_ibm_experiment.exceptions import IBMExperimentEntryNotFound from qiskit_ibm_experiment.exceptions import IBMApiError def bell(): """Return a Bell circuit.""" qr = QuantumRegister(2, name="qr") cr = ClassicalRegister(2, name="qc") qc = QuantumCircuit(qr, cr, name="bell") qc.h(qr[0]) qc.cx(qr[0], qr[1]) qc.measure(qr, cr) return qc @skipIf( not os.environ.get("QISKIT_IBM_USE_STAGING_CREDENTIALS", ""), "Only runs on staging" ) class TestExperimentDataIntegration(IBMTestCase): """Test experiment service with experiment data.""" @classmethod def setUpClass(cls): """Initial class level setup.""" super().setUpClass() try: cls._setup_service() cls._setup_provider() cls.circuit = transpile(bell(), cls.backend) except Exception as err: cls.log.info("Error while setting the service/provider: %s", err) raise @classmethod def _setup_service(cls): """Get the service for the class.""" cls.service = IBMExperimentService( token=os.getenv("QISKIT_IBM_STAGING_API_TOKEN"), url=os.getenv("QISKIT_IBM_STAGING_API_URL"), ) @classmethod def _setup_provider(cls): """Get the provider for the class.""" cls.provider = QiskitRuntimeService( channel="ibm_quantum", token=os.getenv("QISKIT_IBM_STAGING_API_TOKEN"), url=os.getenv("QISKIT_IBM_STAGING_API_URL"), instance=os.getenv("QISKIT_IBM_STAGING_HGP"), ) cls.backend = cls.provider.backend(os.getenv("QISKIT_IBM_STAGING_BACKEND")) try: cls.device_components = cls.service.device_components(cls.backend.name) except IBMApiError: cls.device_components = None def setUp(self) -> None: """Test level setup.""" super().setUp() self.experiments_to_delete = [] self.results_to_delete = [] self.jobs_to_cancel = [] def tearDown(self): """Test level tear down.""" for result_uuid in self.results_to_delete: try: with mock.patch("builtins.input", lambda _: "y"): self.service.delete_analysis_result(result_uuid) except Exception as err: # pylint: disable=broad-except self.log.info( "Unable to delete analysis result %s: %s", result_uuid, err ) for expr_uuid in self.experiments_to_delete: try: with mock.patch("builtins.input", lambda _: "y"): self.service.delete_experiment(expr_uuid) except Exception as err: # pylint: disable=broad-except self.log.info("Unable to delete experiment %s: %s", expr_uuid, err) for job in self.jobs_to_cancel: with contextlib.suppress(Exception): job.cancel() super().tearDown() def test_add_data_job(self): """Test add job to experiment data.""" exp_data = ExperimentData( backend=self.backend, provider=self.provider, experiment_type="qiskit_test", service=self.service, ) transpiled = transpile(bell(), self.backend) transpiled.metadata = {"foo": "bar"} job = self._run_circuit(transpiled) exp_data.add_jobs(job) self.assertEqual([job.job_id()], exp_data.job_ids) result = job.result() exp_data.block_for_results() circuit_data = exp_data.data(0) self.assertEqual(result.get_counts(0), circuit_data["counts"]) # currently the returned job_id is different; this is not a qiskit-ibm-experiment # problem but a known behaviour in the new provider # self.assertEqual(job.job_id(), circuit_data["job_id"]) self.assertEqual(transpiled.metadata, circuit_data["metadata"]) def test_new_experiment_data(self): """Test creating a new experiment data.""" metadata = {"complex": 2 + 3j, "numpy": np.zeros(2)} exp_data = ExperimentData( service=self.service, backend=self.backend, provider=self.provider, experiment_type="qiskit_test", tags=["foo", "bar"], share_level="hub", metadata=metadata, notes="some notes", ) job_ids = [] for _ in range(2): job = self._run_circuit() exp_data.add_jobs(job) job_ids.append(job.job_id()) exp_data.block_for_results().save(suppress_errors=False) self.experiments_to_delete.append(exp_data.experiment_id) hub, group, project = list(self.provider._hgps)[0].split("/") rexp = ExperimentData.load(exp_data.experiment_id, self.service) self._verify_experiment_data(exp_data, rexp) self.assertEqual(hub, rexp.hub) # pylint: disable=no-member self.assertEqual(group, rexp.group) # pylint: disable=no-member self.assertEqual(project, rexp.project) # pylint: disable=no-member def test_update_experiment_data(self): """Test updating an experiment.""" exp_data = self._create_experiment_data() for _ in range(2): job = self._run_circuit() exp_data.add_jobs(job) exp_data.tags = ["foo", "bar"] exp_data.share_level = "hub" exp_data.notes = "some notes" exp_data.block_for_results().save(suppress_errors=False) rexp = ExperimentData.load(exp_data.experiment_id, self.service) self._verify_experiment_data(exp_data, rexp) def _verify_experiment_data(self, expected, actual): """Verify the input experiment data.""" self.assertEqual(expected.experiment_id, actual.experiment_id) self.assertEqual(expected.job_ids, actual.job_ids) self.assertEqual(expected.share_level, actual.share_level) self.assertEqual(expected.tags, actual.tags) self.assertEqual(expected.notes, actual.notes) self.assertEqual( expected.metadata.get("complex", {}), actual.metadata.get("complex", {}) ) self.assertTrue(actual.creation_datetime) self.assertTrue(getattr(actual, "creation_datetime").tzinfo) def test_add_analysis_results(self): """Test adding an analysis result.""" exp_data = self._create_experiment_data() result_data = {"complex": 2 + 3j, "numpy": np.zeros(2)} aresult = AnalysisResult( name="qiskit_test", value=result_data, device_components=self.device_components, experiment_id=exp_data.experiment_id, quality="good", tags=["foo", "bar"], service=self.service, ) exp_data.add_analysis_results(aresult) exp_data.save(suppress_errors=False) rresult = AnalysisResult.load(aresult.result_id, self.service) self.assertEqual(exp_data.experiment_id, rresult.experiment_id) self._verify_analysis_result(aresult, rresult) def test_update_analysis_result(self): """Test updating an analysis result.""" aresult, exp_data = self._create_analysis_result() rdata = {"complex": 2 + 3j, "numpy": np.zeros(2)} aresult.value = rdata aresult.quality = "good" aresult.tags = ["foo", "bar"] aresult.save(suppress_errors=False) rexp = ExperimentData.load(exp_data.experiment_id, self.service) rresult = rexp.analysis_results(0) self._verify_analysis_result(aresult, rresult) def _verify_analysis_result(self, expected, actual): """Verify the input analysis result.""" self.assertEqual(expected.result_id, actual.result_id) self.assertEqual(expected.name, actual.name) ecomp = {str(comp) for comp in expected.device_components} acomp = {str(comp) for comp in actual.device_components} self.assertEqual(ecomp, acomp) self.assertEqual(expected.experiment_id, actual.experiment_id) self.assertEqual(expected.quality, actual.quality) self.assertEqual(expected.tags, actual.tags) self.assertEqual(expected.value["complex"], actual.value["complex"]) self.assertEqual(expected.value["numpy"].all(), actual.value["numpy"].all()) def test_delete_analysis_result(self): """Test deleting an analysis result.""" aresult, exp_data = self._create_analysis_result() with mock.patch("builtins.input", lambda _: "y"): exp_data.delete_analysis_result(0) exp_data.save(suppress_errors=False) rexp = ExperimentData.load(exp_data.experiment_id, self.service) self.assertRaises( ExperimentEntryNotFound, rexp.analysis_results, aresult.result_id ) self.assertRaises( IBMExperimentEntryNotFound, self.service.analysis_result, aresult.result_id ) def test_add_figures(self): """Test adding a figure to the experiment data.""" exp_data = self._create_experiment_data() hello_bytes = str.encode("hello world") sub_tests = ["hello.svg", None] for idx, figure_name in enumerate(sub_tests): with self.subTest(figure_name=figure_name): exp_data.add_figures( figures=hello_bytes, figure_names=figure_name, save_figure=True ) rexp = ExperimentData.load(exp_data.experiment_id, self.service) self.assertEqual(rexp.figure(idx).figure, hello_bytes) def test_add_figures_plot(self): """Test adding a matplotlib figure.""" import matplotlib.pyplot as plt figure, axes = plt.subplots() axes.plot([1, 2, 3]) exp_data = self._create_experiment_data() exp_data.add_figures(figure, save_figure=True) rexp = ExperimentData.load(exp_data.experiment_id, self.service) self.assertTrue(rexp.figure(0)) def test_add_figures_file(self): """Test adding a figure file.""" exp_data = self._create_experiment_data() hello_bytes = str.encode("hello world") file_name = "hello_world.svg" self.addCleanup(os.remove, file_name) with open(file_name, "wb") as file: file.write(hello_bytes) exp_data.add_figures(figures=file_name, save_figure=True) rexp = ExperimentData.load(exp_data.experiment_id, self.service) self.assertEqual(rexp.figure(0).figure, hello_bytes) def test_update_figure(self): """Test updating a figure.""" exp_data = self._create_experiment_data() hello_bytes = str.encode("hello world") figure_name = "hello.svg" exp_data.add_figures( figures=hello_bytes, figure_names=figure_name, save_figure=True ) self.assertEqual(exp_data.figure(0).figure, hello_bytes) friend_bytes = str.encode("hello friend") exp_data.add_figures( figures=friend_bytes, figure_names=figure_name, overwrite=True, save_figure=True, ) rexp = ExperimentData.load(exp_data.experiment_id, self.service) self.assertEqual(rexp.figure(0).figure, friend_bytes) self.assertEqual(rexp.figure(figure_name).figure, friend_bytes) def test_delete_figure(self): """Test deleting a figure.""" exp_data = self._create_experiment_data() hello_bytes = str.encode("hello world") figure_name = "hello.svg" exp_data.add_figures( figures=hello_bytes, figure_names=figure_name, save_figure=True ) with mock.patch("builtins.input", lambda _: "y"): exp_data.delete_figure(0) exp_data.save(suppress_errors=False) rexp = ExperimentData.load(exp_data.experiment_id, self.service) self.assertRaises(IBMExperimentEntryNotFound, rexp.figure, figure_name) self.assertRaises( IBMExperimentEntryNotFound, self.service.figure, exp_data.experiment_id, figure_name, ) def test_save_all(self): """Test saving all.""" exp_data = self._create_experiment_data() exp_data.tags = ["foo", "bar"] aresult = AnalysisResult( value={}, name="qiskit_test", device_components=self.device_components, experiment_id=exp_data.experiment_id, ) exp_data.add_analysis_results(aresult) hello_bytes = str.encode("hello world") exp_data.add_figures(hello_bytes, figure_names="hello.svg") exp_data.save(suppress_errors=False) rexp = ExperimentData.load(exp_data.experiment_id, self.service) # Experiment tag order is not necessarily preserved # so compare tags with a predictable sort order. self.assertEqual(["bar", "foo"], sorted(rexp.tags)) self.assertEqual(aresult.result_id, rexp.analysis_results(0).result_id) self.assertEqual(hello_bytes, rexp.figure(0).figure) exp_data.delete_analysis_result(0) exp_data.delete_figure(0) with mock.patch("builtins.input", lambda _: "y"): exp_data.save(suppress_errors=False) rexp = ExperimentData.load(exp_data.experiment_id, self.service) self.assertRaises(IBMExperimentEntryNotFound, rexp.figure, "hello.svg") self.assertRaises( ExperimentEntryNotFound, rexp.analysis_results, aresult.result_id ) def test_set_service_job(self): """Test setting service with a job.""" exp_data = ExperimentData(experiment_type="qiskit_test", service=self.service) job = self._run_circuit() exp_data.add_jobs(job) exp_data.save(suppress_errors=False) self.experiments_to_delete.append(exp_data.experiment_id) rexp = self.service.experiment(exp_data.experiment_id) self.assertEqual([job.job_id()], rexp.job_ids) def test_auto_save_experiment(self): """Test auto save.""" exp_data = self._create_experiment_data() exp_data.auto_save = True subtests = [ ( setattr, ( exp_data, "tags", ["foo"], ), ), (setattr, (exp_data, "notes", "foo")), (setattr, (exp_data, "share_level", "hub")), ] for func, params in subtests: with self.subTest(func=func): with mock.patch.object( IBMExperimentService, "create_or_update_experiment", wraps=exp_data.service.create_or_update_experiment, ) as mocked: func(*params) mocked.assert_called_once() data = mocked.call_args[0][0] self.assertEqual(exp_data.experiment_id, data.experiment_id) mocked.reset_mock() def test_auto_save_figure(self): """Test auto saving figure.""" exp_data = self._create_experiment_data() exp_data.auto_save = True figure_name = "hello.svg" with mock.patch.object( IBMExperimentService, "update_experiment", wraps=exp_data.service.update_experiment, ) as mocked_exp: with mock.patch.object( IBMExperimentService, "create_figure", wraps=exp_data.service.create_figure, ) as mocked_fig: exp_data.add_figures( str.encode("hello world"), figure_names=figure_name ) mocked_exp.assert_called_once() mocked_fig.assert_called_once() mocked_exp.reset_mock() with mock.patch.object( IBMExperimentService, "update_figure", wraps=exp_data.service.update_figure, ) as mocked_fig: exp_data.add_figures( str.encode("hello friend"), figure_names=figure_name, overwrite=True ) mocked_fig.assert_called_once() mocked_exp.assert_called_once() mocked_exp.reset_mock() with mock.patch.object( IBMExperimentService, "delete_figure", wraps=exp_data.service.delete_figure, ) as mocked_fig, mock.patch("builtins.input", lambda _: "y"): exp_data.delete_figure(figure_name) mocked_fig.assert_called_once() mocked_exp.assert_called_once() def test_auto_save_analysis_result(self): """Test auto saving analysis result.""" exp_data = self._create_experiment_data() exp_data.auto_save = True aresult = AnalysisResult( value={}, name="qiskit_test", device_components=self.device_components, experiment_id=exp_data.experiment_id, service=self.service, ) with mock.patch.object( IBMExperimentService, "update_experiment", wraps=exp_data.service.update_experiment, ) as mocked_exp: with mock.patch.object( IBMExperimentService, "create_or_update_analysis_result", wraps=exp_data.service.create_or_update_analysis_result, ) as mocked_res: exp_data.add_analysis_results(aresult) mocked_exp.assert_called_once() mocked_res.assert_called_once() mocked_exp.reset_mock() def test_auto_save_analysis_result_update(self): """Test auto saving analysis result updates.""" aresult, exp_data = self._create_analysis_result() aresult.auto_save = True subtests = [ ("tags", ["foo"]), ("value", {"foo": "bar"}), ("quality", "GOOD"), ] for attr, value in subtests: with self.subTest(attr=attr): with mock.patch.object( IBMExperimentService, "create_or_update_analysis_result", wraps=exp_data.service.create_or_update_analysis_result, ) as mocked: setattr(aresult, attr, value) mocked.assert_called_once() data = mocked.call_args[0][0] self.assertEqual(aresult.result_id, data.result_id) mocked.reset_mock() def test_block_for_results(self): """Test blocking for jobs""" exp_data = ExperimentData( backend=self.backend, provider=self.provider, experiment_type="qiskit_test", service=self.service, ) jobs = [] for _ in range(2): job = self._run_circuit() exp_data.add_jobs(job) jobs.append(job) exp_data.block_for_results() self.assertTrue(all(job.status() == JobStatus.DONE for job in jobs)) self.assertEqual(ExperimentStatus.DONE, exp_data.status()) def test_file_upload_download(self): """test upload and download of actual experiment data""" exp_id = self._create_experiment_data().experiment_id qc = QuantumCircuit(2) qc.h(0) qc.measure_all() data = {"string": "b-string", "int": 10, "float": 0.333, "circuit": qc} json_filename = "data.json" self.service.file_upload( exp_id, json_filename, data, json_encoder=ExperimentEncoder ) rjson_data = self.service.file_download( exp_id, json_filename, json_decoder=ExperimentDecoder ) self.assertEqual(data, rjson_data) def _create_experiment_data(self): """Create an experiment data.""" exp_data = ExperimentData( backend=self.backend, provider=self.provider, experiment_type="qiskit_test", verbose=False, service=self.service, ) exp_data.save(suppress_errors=False) self.experiments_to_delete.append(exp_data.experiment_id) return exp_data def _create_analysis_result(self): """Create a simple analysis result.""" exp_data = self._create_experiment_data() aresult = AnalysisResult( value={}, name="qiskit_test", device_components=self.device_components, experiment_id=exp_data.experiment_id, service=self.service, ) exp_data.add_analysis_results(aresult) exp_data.save(suppress_errors=False) self.results_to_delete.append(aresult.result_id) return aresult, exp_data def _run_circuit(self, circuit=None): """Run a circuit.""" circuit = circuit or self.circuit job = self.backend.run(circuit, shots=1) self.jobs_to_cancel.append(job) return job if __name__ == "__main__": unittest.main()
https://github.com/Qiskit-Extensions/qiskit-ibm-experiment
Qiskit-Extensions
# 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. """Templates for use with unit tests.""" RUNTIME_PROGRAM = """ import random import time import warnings import logging from qiskit import transpile from qiskit.circuit.random import random_circuit logger = logging.getLogger("qiskit-test") def prepare_circuits(backend): circuit = random_circuit(num_qubits=5, depth=4, measure=True, seed=random.randint(0, 1000)) return transpile(circuit, backend) def main(backend, user_messenger, **kwargs): iterations = kwargs['iterations'] sleep_per_iteration = kwargs.pop('sleep_per_iteration', 0) interim_results = kwargs.pop('interim_results', {}) final_result = kwargs.pop("final_result", {}) for it in range(iterations): time.sleep(sleep_per_iteration) qc = prepare_circuits(backend) user_messenger.publish({"iteration": it, "interim_results": interim_results}) backend.run(qc).result() user_messenger.publish(final_result, final=True) print("this is a stdout message") warnings.warn("this is a stderr message") logger.info("this is an info log") """ RUNTIME_PROGRAM_METADATA = { "max_execution_time": 600, "description": "Qiskit test program", } PROGRAM_PREFIX = "qiskit-test"
https://github.com/qiskit-community/qiskit-hackathon-korea-22
qiskit-community
from qiskit_nature.problems.sampling.protein_folding.interactions.random_interaction import ( RandomInteraction, ) from qiskit_nature.problems.sampling.protein_folding.interactions.miyazawa_jernigan_interaction import ( MiyazawaJerniganInteraction, ) from qiskit_nature.problems.sampling.protein_folding.peptide.peptide import Peptide from qiskit_nature.problems.sampling.protein_folding.protein_folding_problem import ( ProteinFoldingProblem, ) from qiskit_nature.problems.sampling.protein_folding.penalty_parameters import PenaltyParameters from qiskit.utils import algorithm_globals, QuantumInstance algorithm_globals.random_seed = 23 main_chain = "APRLRFY" side_chains = [""] * 7 random_interaction = RandomInteraction() mj_interaction = MiyazawaJerniganInteraction() penalty_back = 10 penalty_chiral = 10 penalty_1 = 10 penalty_terms = PenaltyParameters(penalty_chiral, penalty_back, penalty_1) peptide = Peptide(main_chain, side_chains) protein_folding_problem = ProteinFoldingProblem(peptide, mj_interaction, penalty_terms) qubit_op = protein_folding_problem.qubit_op() from qiskit.circuit.library import RealAmplitudes from qiskit.algorithms.optimizers import COBYLA from qiskit.algorithms import NumPyMinimumEigensolver, VQE from qiskit.opflow import PauliExpectation, CVaRExpectation from qiskit import execute, Aer # set classical optimizer optimizer = COBYLA(maxiter=50) # set variational ansatz ansatz = RealAmplitudes(reps=1) # set the backend backend_name = "aer_simulator" backend = QuantumInstance( Aer.get_backend(backend_name), shots=8192, seed_transpiler=algorithm_globals.random_seed, seed_simulator=algorithm_globals.random_seed, ) counts = [] values = [] def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) # initialize CVaR_alpha objective with alpha = 0.1 cvar_exp = CVaRExpectation(0.1, PauliExpectation()) # initialize VQE using CVaR vqe = VQE( expectation=cvar_exp, optimizer=optimizer, ansatz=ansatz, quantum_instance=backend, callback=store_intermediate_result, ) result = vqe.compute_minimum_eigenvalue(qubit_op) print(result) import matplotlib.pyplot as plt fig = plt.figure() plt.plot(counts, values) plt.ylabel("Conformation Energy") plt.xlabel("VQE Iterations") fig.add_axes([0.44, 0.51, 0.44, 0.32]) plt.plot(counts[40:], values[40:]) plt.ylabel("Conformation Energy") plt.xlabel("VQE Iterations") plt.show() main_chain = "APRLRFDR" side_chains = [""] * 8 random_interaction = RandomInteraction() mj_interaction = MiyazawaJerniganInteraction() penalty_back = 10 penalty_chiral = 10 penalty_1 = 10 penalty_terms = PenaltyParameters(penalty_chiral, penalty_back, penalty_1) peptide = Peptide(main_chain, side_chains) protein_folding_problem = ProteinFoldingProblem(peptide, mj_interaction, penalty_terms) qubit_op = protein_folding_problem.qubit_op() "from qiskit.circuit.library import [INSERT YOUR OWN ANSATZ]" from qiskit.circuit.library import RealAmplitudes "from qiskit.algorithms.optimizers import [INSERT YOUR OWN OPTIMIZER]" from qiskit.algorithms.optimizers import COBYLA from qiskit.algorithms import NumPyMinimumEigensolver, VQE from qiskit.opflow import PauliExpectation, CVaRExpectation from qiskit import execute, Aer # set classical optimizer start """ 1. Choose your optimizer Note that you have to import optimizer. """ "optimizer = [INSERT YOUR OWN OPTIMIZER]" optimizer = COBYLA(maxiter=100) # set classical optimizer end # set variational ansatz start """ 2. Choose your ansatz Note that you have to import ansatz. """ "ansatz = [INSERT YOUR OWN ANSATZ]" ansatz = RealAmplitudes(reps=1) # set variational ansatz end # set the backend backend_name = "aer_simulator" backend = QuantumInstance( Aer.get_backend(backend_name), shots=8192, seed_transpiler=algorithm_globals.random_seed, seed_simulator=algorithm_globals.random_seed, ) counts = [] values = [] def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) # initialize CVaR_alpha objective with alpha = 0.1 cvar_exp = CVaRExpectation(0.1, PauliExpectation()) # initialize VQE using CVaR vqe = VQE( expectation=cvar_exp, optimizer=optimizer, ansatz=ansatz, quantum_instance=backend, callback=store_intermediate_result, ) result = vqe.compute_minimum_eigenvalue(qubit_op) print(result) import matplotlib.pyplot as plt fig = plt.figure() plt.plot(counts, values) plt.ylabel("Conformation Energy") plt.xlabel("VQE Iterations") fig.add_axes([0.44, 0.51, 0.44, 0.32]) plt.plot(counts[40:], values[40:]) plt.ylabel("Conformation Energy") plt.xlabel("VQE Iterations") plt.show() print( "Result:", values[-1] )
https://github.com/qiskit-community/qiskit-hackathon-korea-22
qiskit-community
# Import auxiliary libraries # Import Qiskit from qiskit import Aer from qiskit.algorithms import QAOA, NumPyMinimumEigensolver from qiskit.utils import QuantumInstance from qiskit_optimization import QuadraticProgram from qiskit_optimization.algorithms import MinimumEigenOptimizer qp_ex = QuadraticProgram() qp_ex.integer_var(lowerbound=0, upperbound=100, name='x') qp_ex.integer_var(lowerbound=0, upperbound=100, name='y') qp_ex.maximize(linear={'x': 100, 'y': 40}) qp_ex.linear_constraint(linear={'x': 100, 'y': 50}, sense='LE', rhs=3000, name='constraints_1') qp_ex.linear_constraint(linear={'x': 10}, sense='LE', rhs=100, name='constraints_2') print(qp_ex.export_as_lp_string()) qp = QuadraticProgram() qp.integer_var(lowerbound=0, upperbound=5, name='x') qp.integer_var(lowerbound=0, upperbound=5, name='y') qp.maximize(linear={'x': 3, 'y': 2}) qp.linear_constraint(linear={'x': 1, 'y': 2}, sense='LE', rhs=4, name='constraints_1') qp.linear_constraint(linear={'x': 1 }, sense='LE', rhs=2, name='constraints_2') print(qp.export_as_lp_string()) qins = QuantumInstance(backend=Aer.get_backend('qasm_simulator'), shots=1000, seed_simulator=0) meo = MinimumEigenOptimizer(min_eigen_solver=QAOA(reps=1, quantum_instance=qins)) # Define QAOA solver result = meo.solve(qp) print('result:', result._variables_dict) # print('status:', result._status) # print('time:', result.min_eigen_solver_result.optimizer_time) exact_mes = NumPyMinimumEigensolver() exact = MinimumEigenOptimizer(exact_mes) # Using the exact classical numpy minimum eigen solver exact_result = exact.solve(qp) print('result:', exact_result._variables_dict) # print('status:', exact_result._status)
https://github.com/qiskit-community/qiskit-hackathon-korea-22
qiskit-community
## import essential libraries import numpy as np from qiskit import * from qiskit.tools.monitor import job_monitor from qiskit import assemble,pulse,QuantumCircuit,schedule,transpile from qiskit.pulse.channels import ControlChannel, DriveChannel from qiskit.circuit import Gate from qiskit.providers.aer import PulseSimulator from qiskit.providers.aer.pulse import PulseSystemModel from qiskit.test.mock import FakeValencia from qiskit.visualization import plot_histogram from qiskit.visualization.pulse_v2 import draw, IQXSimple, IQXDebugging,IQXStandard IBMQ.load_account() provider = IBMQ.get_provider(group='open') #check open_pulse ibmq device that you can use provider.backends(simulator=False, open_pulse=True) #define pulsesimulator from the backend profile backend = FakeValencia() # setting for build pulse simulation model = PulseSystemModel.from_backend(backend) qubit_lo_freq = model.hamiltonian.get_qubit_lo_from_drift() backend_sim = PulseSimulator(system_model = model) backend_sim.set_options(qubit_lo_freq=backend.defaults().qubit_freq_est) qc = QuantumCircuit(2) qc.h(0) qc.cx(0,1) qc.measure_all() qc.draw('mpl') qc_t = transpile(qc, backend) pulse_sched_qc = schedule(qc_t, backend) draw(pulse_sched_qc, backend=backend) from qiskit import pulse dc = pulse.DriveChannel d0, d1, d2, d3, d4 = dc(0), dc(1), dc(2), dc(3), dc(4) with pulse.build(name='QHK2022_Pulse') as QHK2022: pulse.play([1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1 ], d0) pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1 ], d1) pulse.play([1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0 ], d2) pulse.play([1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0 ], d3) pulse.play([1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1], d4) draw(QHK2022) with pulse.build(backend) as drive_sched_check: for i in range(5): print("The driveing channel of qubit{} is {}".format(i, pulse.drive_channel(i))) from qiskit.tools.jupyter import * backend #check the control channel btw 0-1 with pulse.build(backend) as control_sched_check: print("The control channel of qubit btw qubit (0,1) is {}".format(0, pulse.control_channels(0,1))) with pulse.build(backend) as control_sched_check: print("The control channel of qubit btw qubit (0,2) is {}".format(0, pulse.control_channels(0,2))) with pulse.build(backend) as drive_sched_check: for i in range(5): print("The acquire channel of qubit{} is {}".format(i, pulse.acquire_channel(i))) print("The measurement channel of qubit{} is {}".format(i, pulse.measure_channel(i))) with pulse.build(backend) as actual_playing: d0 = pulse.drive_channel(0) a0 = pulse.acquire_channel(0) #play square constant pulse at drive channel 0 with the duration 10 (computational duration) amplitude 1.0 pulse.play(pulse.library.Constant(64, 1.0), d0) #give 20 steps of delay to the d0 pulse.delay(20, d0) #give pi/2 phase shift to the d0 pulse.shift_phase(2, d0) pulse.play(pulse.library.Constant(64, 1.0), d0) #set phase of d0 as pi pulse.set_phase(0.5, d0) pulse.play(pulse.library.Constant(64, 1), d0) #define inner pulse schedule inside of the pulse builder with pulse.build() as inner_sched: #play a gaussian pulse with duration 20, amplitude 1, sigma 3.0 to d0 pulse.play(pulse.library.Gaussian(64, 0.2, 3.0), d0) #play inner schedule at the main schedule pulse.call(inner_sched) draw(actual_playing, backend = backend) with pulse.build(backend) as actual_playing: #with pulse.build(backend, default_alignment='left') as actual_playing: #with pulse.build(backend, default_alignment='right') as actual_playing: #with pulse.build(backend, default_alignment='sequential') as actual_playing_two: d0 = pulse.drive_channel(0) d1 = pulse.drive_channel(1) a0 = pulse.acquire_channel(0) #play square constant pulse at drive channel 0 with the duration 10 (computational duration) amplitude 1.0 pulse.play(pulse.library.Constant(64, 1.0), d0) pulse.play(pulse.library.Constant(64, 1.0), d1) #give 20 steps of delay to the d0 pulse.delay(20, d0) #give pi/2 phase shift to the d0 pulse.shift_phase(2, d0) pulse.play(pulse.library.Constant(10, 1.0), d0) #set phase of d0 as pi pulse.set_phase(0.5, d0) pulse.play(pulse.library.Constant(64, 1.0), d0) #define inner pulse schedule inside of the pulse builder with pulse.build() as inner_sched: #play a gaussian pulse with duration 20, amplitude 1, sigma 3.0 to d0 pulse.play(pulse.library.Gaussian(64, 1.0, 3.0), d0) #play inner schedule at the main schedule pulse.call(inner_sched) draw(actual_playing_two, backend = backend) with pulse.build(backend, default_alignment='sequential') as meas: pulse.call(actual_playing) with pulse.align_left(): pulse.measure(0) draw(meas, style=IQXDebugging(), backend = backend) result = backend.run(meas, shots=8192).result() result.get_counts() with pulse.build(backend, default_alignment='sequential') as entangle_circ: pulse.u2(0, np.pi, 0) pulse.cx(0,1) with pulse.align_left(): pulse.measure(0) pulse.measure(1) draw(entangle_circ, style=IQXDebugging(), backend=backend) with pulse.build(backend, default_alignment='sequential') as example1: d0 = pulse.drive_channel(0) #play square constant pulse at drive channel 0 with the duration 200 (computational duration) amplitude 0.5 pulse.play(pulse.library.Constant(200, 0.5), d0) draw(example1, backend = backend) with pulse.build(backend, default_alignment='sequential') as example2: d0 = pulse.drive_channel(0) #play square constant pulse at drive channel 0 with the duration 189 (computational duration) amplitude 0.5 pulse.play(pulse.library.Constant(189, 0.5), d0) draw(example2, backend = backend) with pulse.build(backend, default_alignment='sequential') as example3: d0 = pulse.drive_channel(0) #play gaussian pulse at drive channel 0 with the duration 160 (computational duration) amplitude 0.2 with sigma=40 pulse.play(pulse.library.Gaussian(duration=160, amp=(0.2), sigma=40), d0) draw(example3, backend = backend) with pulse.build(backend, default_alignment='sequential') as example4: d0 = pulse.drive_channel(0) #play gaussian pulse at drive channel 0 with the duration 160 (computational duration) amplitude 0.4 with sigma=40 pulse.play(pulse.library.Gaussian(duration=160, amp=(0.5), sigma=40), d0) draw(example4, backend = backend) with pulse.build(backend, default_alignment='sequential') as measure: a0 = pulse.acquire_channel(0) m0 = pulse.MeasureChannel(0) #commenting out and insert pulse schedule you want to play ex:pulse.call(test_pulse1) #pulse.call() pulse.acquire(500, m0, pulse.MemorySlot(0)) result = backend.run(measure, shots=8192).result() result.get_counts()
https://github.com/qiskit-community/qiskit-hackathon-korea-22
qiskit-community
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, IBMQ, schedule import qiskit.pulse as pulse from qiskit.circuit import Parameter from qiskit_experiments.calibration_management import Calibrations import pandas as pd # Loading your IBM Quantum account(s) qubit = 1 phase = np.pi # Generating an instance of Calibrations class def setup_cals( backend ) -> Calibrations: """ A function to instantiate calibrations and add a couple of template schedules. """ # Instantiating Calibrations as cals cals = Calibrations.from_backend( backend ) # Parameters to sweep dur = Parameter( "dur" ) amp = Parameter( "amp" ) amp_2 = Parameter( "amp" ) sigma = Parameter( "σ" ) beta = Parameter( "β" ) beta_2 = Parameter( "β" ) drive = pulse.DriveChannel( Parameter( "ch0" ) ) # Define and add template schedules with pulse.build( name="xp" ) as xp: # X positive pulse.play( pulse.Drag( dur, amp, sigma, beta ), drive ) with pulse.build( name="x" ) as x: # X positive pulse.play( pulse.Drag( dur, amp, sigma, beta ), drive ) with pulse.build( name="y" ) as y: # Y positive pulse.shift_phase( phase, drive ) pulse.play( pulse.Drag( dur, amp, sigma, beta ), drive ) with pulse.build( name="xm" ) as xm: # X minus pulse.play( pulse.Drag( dur, -amp, sigma, beta ), drive ) with pulse.build( name="x90p" ) as x90p: # X/2 positive # Different pulse amplitude and correction pulse amplitude for X/2 pulse.play( pulse.Drag( dur, amp_2, sigma, beta_2 ), drive ) with pulse.build( name="sx" ) as sx: # X/2 positive # Different pulse amplitude and correction pulse amplitude for X/2 pulse.play( pulse.Drag( dur, amp_2, sigma, beta_2 ), drive ) cals.add_schedule( xp, num_qubits=1 ) cals.add_schedule( xm, num_qubits=1 ) cals.add_schedule( x90p, num_qubits=1 ) cals.add_schedule( x, num_qubits=1 ) cals.add_schedule( y, num_qubits=1 ) cals.add_schedule( sx, num_qubits=1 ) return cals def add_parameter_guesses( cals: Calibrations ): """ Add guesses for the parameter values to the calibrations. """ for sched in [ "x", "xp", "y", "sx", "x90p" ]: cals.add_parameter_value( 80, "σ", schedule=sched ) cals.add_parameter_value( 0.5, "β", schedule=sched ) cals.add_parameter_value( 320, "dur", schedule=sched ) cals.add_parameter_value( 0.5, "amp", schedule=sched ) # Calling calibration functions cals = setup_cals( backend ) add_parameter_guesses( cals ) # Using a default frequency import pandas as pd pd.DataFrame( **cals.parameters_table( qubit_list=[ qubit, () ], parameters="drive_freq" ) ) from qiskit_experiments.library.calibration import RoughXSXAmplitudeCal # Define Rabi amplitude sweep sequence rabi = RoughXSXAmplitudeCal( qubit, cals, amplitudes=np.linspace( -0.2, 0.2, 51 ), backend=backend ) # Run the experiment rabi_data = rabi.run().block_for_results() rabi_data.figure( 0 ) # Save pulse amplitude pi_amp = np.pi / ( 2*np.pi*rabi_data.analysis_results( "rabi_rate" ).value.value ) print( pi_amp ) defaults = backend.defaults() x_schedule = defaults.instruction_schedule_map.get( 'x', 1 ) print( x_schedule ) pd.DataFrame(**cals.parameters_table(qubit_list=[qubit, ()], parameters="amp")) cals.get_schedule("sx", qubit) cals.get_schedule("x", qubit) from qiskit_experiments.library import RoughDragCal # Define DRAG coefficient sweep sequence cal_drag = RoughDragCal( qubit, cals, backend=backend, betas=np.linspace( -20, 20, 51 ) ) cal_drag.set_experiment_options( reps=[ 3, 5, 7 ] ) # Run the DRAG measurement drag_data = cal_drag.run().block_for_results() drag_data.figure( 0 ) print( drag_data.analysis_results( "beta" ) ) # Save DRAG coefficient beta = drag_data.analysis_results( "beta" ).value.value print( beta ) # Define DRAG coefficient sweep sequence cal_drag = RoughDragCal( qubit, cals, backend=backend, schedule_name="sx", betas=np.linspace( -20, 20, 51 ) ) cal_drag.set_experiment_options( reps=[ 9, 11, 17 ] ) # Run the DRAG measurement drag_data = cal_drag.run().block_for_results() drag_data.figure( 0 ) # Save DRAG coefficient beta_2 = drag_data.analysis_results( "beta" ).value.value print( beta_2 ) pd.DataFrame(**cals.parameters_table(qubit_list=[qubit, ()], parameters="β")) #print( "Qubit frequency: ", qubit_freq / 1e9, " GHz" ) print( "π-pulse amplitude: ", pi_amp ) print( "DRAG coefficient β fox X: ", beta ) print( "DRAG coefficient β for SX: ", beta_2 ) from qiskit_experiments.library.calibration.fine_amplitude import FineXAmplitudeCal amp_x_cal = FineXAmplitudeCal(qubit, cals, backend=backend, schedule_name="x") amp_x_fine = amp_x_cal.run().block_for_results() amp_x_fine.figure(0) print( amp_x_fine.analysis_results( "d_theta" ) ) dtheta = amp_x_fine.analysis_results( "d_theta" ).value.value target_angle = np.pi scale = target_angle / ( target_angle + dtheta ) print( "Deviation of", dtheta, "is detected for", target_angle, "rotation." ) print( "Hence, switch the π-amplitude from", pi_amp, "to", pi_amp*scale ) fine_x_amp = pi_amp * scale # Check if we have better π-gate. # Note that we don't have to update cals as it is updated automatically. sanity_check = amp_x_cal.run().block_for_results() print( "d_theta has been decreased from", dtheta, "to", sanity_check.analysis_results( "d_theta" ).value.value ) from qiskit_experiments.library.calibration.fine_amplitude import FineSXAmplitudeCal amp_sx_cal = FineSXAmplitudeCal(qubit, cals, backend=backend, schedule_name="sx") amp_sx_fine = amp_sx_cal.run().block_for_results() print( amp_sx_fine.analysis_results( "d_theta" ) ) amp_sx_fine.figure(0) dtheta = amp_sx_fine.analysis_results( "d_theta" ).value.value target_angle = np.pi/2 scale = target_angle / ( target_angle + dtheta ) print( "Deviation of", dtheta, "is detected for", target_angle, "rotation." ) print( "Hence, switch the π/2-amplitude from", pi_amp/2, "to", pi_amp/2*scale ) fine_sx_amp = pi_amp/2 * scale from qiskit_experiments.library.calibration import FineXDragCal, FineSXDragCal drag_x_cal = FineXDragCal( qubit, cals, backend=backend ) drag_x_fine = drag_x_cal.run().block_for_results() drag_x_fine.figure(0) fine_beta = cals.get_parameter_value( "β", qubit, "x" ) print( fine_beta ) drag_sx_cal = FineSXDragCal( qubit, cals, backend=backend ) drag_sx_fine = drag_sx_cal.run().block_for_results() fine_beta_2 = cals.get_parameter_value( "β", qubit, "sx" ) print( fine_beta_2 ) pd.DataFrame(**cals.parameters_table(qubit_list=[qubit, ()], parameters="β")) from qiskit_experiments.library.calibration.half_angle_cal import HalfAngleCal half_angle_cal = HalfAngleCal( qubit, cals, backend=backend ) half_angle_fine = half_angle_cal.run().block_for_results() half_angle_fine.figure(0) finer_sx_amp = cals.get_parameter_value( "amp", qubit, "sx" ) print( finer_sx_amp ) # print( "Qubit frequency:", qubit_freq/1e9, "GHz to Fine Qubit frequency:", fine_qubit_freq/1e9, "GHz." ) print( "π-pulse amplitude:", pi_amp, "to Fine π-pulse amplitude:", fine_x_amp) print( "π/2-pulse amplitude:", pi_amp/2, "to Fine π/2-pulse amplitude:", finer_sx_amp) print( "DRAG coefficient β fox X:", beta, "to Fine DRAG coefficient β for X:", fine_beta ) print( "DRAG coefficient β for SX: ", beta_2, "to Fine DRAG coefficient β for SX:", fine_beta_2 ) # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, pulse, IBMQ # Importing RB-related libraries from qiskit_experiments.library import StandardRB, InterleavedRB from qiskit_experiments.framework import ParallelExperiment from qiskit_experiments.library.randomized_benchmarking import RBUtils import qiskit.circuit.library as circuits x_amp = fine_x_amp sx_amp = fine_sx_amp x_drag = fine_beta sx_drag = fine_beta_2 with pulse.build(backend) as X_pulse: drive_duration=320 drive_sigma=80 drive_chan=pulse.drive_channel(qubit) pulse.play(pulse.library.Drag(duration=drive_duration, amp=x_amp, sigma=drive_sigma, beta=x_drag, name='X pulse'), drive_chan) with pulse.build(backend) as SX_pulse: drive_duration=320 drive_sigma=80 drive_chan=pulse.drive_channel(qubit) pulse.play(pulse.library.Drag(duration=drive_duration, amp=sx_amp, sigma=drive_sigma, beta=sx_drag, name='SX pulse'), drive_chan) inst_map = backend.defaults().instruction_schedule_map print( inst_map.get('x',qubit) ) print( inst_map.get('sx',qubit) ) inst_map.add( 'x', qubit, X_pulse ) inst_map.add( 'sx', qubit, SX_pulse ) print( inst_map.get('x',qubit) ) print( inst_map.get('sx',qubit) ) lengths = np.arange( 1, 2000, 200 ) num_samples = 16 seed = 1010 qubits = [qubit] # Run an RB experiment on qubit 1 expDyn = StandardRB(qubits, lengths, num_samples=num_samples, seed=seed) expdataDyn = expDyn.run(backend=backend) # View result data display(expdataDyn.figure(0))
https://github.com/qiskit-community/qiskit-cold-atom
qiskit-community
import qiskit_qasm3_import project = 'Qiskit OpenQASM 3 Importer' copyright = '2022, Jake Lishman' author = 'Jake Lishman' version = qiskit_qasm3_import.__version__ release = qiskit_qasm3_import.__version__ extensions = [ "sphinx.ext.autodoc", "sphinx.ext.intersphinx", "reno.sphinxext", 'qiskit_sphinx_theme', ] exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # Document the docstring for the class and the __init__ method together. autoclass_content = "both" html_theme = "qiskit-ecosystem" html_title = f"{project} {release}" intersphinx_mapping = { "qiskit-terra": ("https://docs.quantum.ibm.com/api/qiskit/", None), }
https://github.com/qiskit-community/qiskit-cold-atom
qiskit-community
from qiskit_cold_atom.fermions import FermionSimulator # initialize the generic fermionic simulator backend backend = FermionSimulator() from qiskit import QuantumCircuit circ1 = QuantumCircuit(4) # Create a quantum circuit describing four fermionic modes. circ1.fload([1, 2]) # Load fermions into modes 1 and 2. circ1.draw(output="mpl", style="clifford") circ1.measure_all() job = backend.run(circ1) # defaults to 1000 shots taken print(job.result().get_counts()) circ2 = backend.initialize_circuit([1, 0, 1]) circ2.draw(output="mpl", style="clifford") print(f"First circuit's register: {circ1.qregs}") print(f"Second circuit's register: {circ2.qregs}") from qiskit_nature.second_q.operators import FermionicOp import numpy as np # define the Hamiltonian as a FermionicOp H_swap = np.pi / 2 * FermionicOp({"+_0 -_1": 1, "-_0 +_1": -1}, num_spin_orbitals=2) from qiskit_cold_atom.fermions import FermionicGate swap_fermions = FermionicGate(name="swap_fermion", num_modes=2, generator=H_swap) circ = backend.initialize_circuit([1, 0, 1, 0]) circ.append(swap_fermions, qargs=[0, 1]) circ.append(swap_fermions, qargs=[2, 3]) circ.append(swap_fermions, qargs=[1, 2]) circ.measure_all() # circ.draw(output='mpl', scale=0.8) job = backend.run(circ) print(job.result().get_counts()) # define a gate which will create superposition in the circuit split_fermions = FermionicGate(name="split_fermion", num_modes=2, generator=H_swap / 2) qc_sup = backend.initialize_circuit([1, 0, 0]) qc_sup.append(split_fermions, qargs=[0, 1]) qc_sup.append(swap_fermions, qargs=[1, 2]) qc_sup.measure_all() qc_sup.draw(output="mpl", style="clifford", scale=0.8) from qiskit.visualization import plot_histogram job_sup = backend.run(qc_sup) plot_histogram(job_sup.result().get_counts(), figsize=(5, 3)) qc = backend.initialize_circuit([1, 0, 0, 1]) qc.append(split_fermions, qargs=[0, 1]) qc.append(swap_fermions, qargs=[2, 3]) qc.append(swap_fermions, qargs=[0, 1]) qc.append(split_fermions, qargs=[2, 3]) qc.append(swap_fermions, qargs=[0, 2]) qc.measure_all() job = backend.run(qc, shots=10, seed=1234) # access the counts print("counts :", job.result().get_counts()) # access the memory of individual outcomes print("\nmemory :", job.result().get_memory()) # access the statevector print("\nstatevector :", job.result().get_statevector()) # accedd the unitary print("\ncircuit unitary : \n", job.result().get_unitary()) qc.draw(output="mpl", style="clifford") print(backend.get_basis(qc)) corr = FermionicOp({"+_0 -_0 +_2 -_2": 1}, num_spin_orbitals=4) + FermionicOp( {"-_0 +_0 -_2 +_2": 1}, num_spin_orbitals=4 ) exp_val = backend.measure_observable_expectation(qc, observable=corr, shots=1000) print(exp_val) import numpy as np from qiskit_cold_atom.fermions import ( FfsimBackend, Hop, Interaction, Phase, ) # initialize the ffsim backend backend = FfsimBackend() # set the number of orbitals and occupancies norb = 8 nocc = norb // 4 nvrt = norb - nocc occ_a = [1] * nocc + [0] * nvrt occ_b = [1] * nocc + [0] * nvrt occupations = [occ_a, occ_b] # set parameters for fermionic gates hopping = np.ones(norb - 1) interaction = 1.0 mu = np.ones(norb) # construct a circuit with some fermionic gates circuit = backend.initialize_circuit(occupations) circuit.append(Hop(2 * norb, hopping), list(range(2 * norb))) circuit.append(Interaction(2 * norb, interaction), list(range(2 * norb))) circuit.append(Phase(2 * norb, mu), list(range(2 * norb))) circuit.measure_all() # run the circuit and retrieve the measurement counts job = backend.run(circuit, shots=10, seed=1234, num_species=2) # access the counts print("counts :", job.result().get_counts()) # access the memory of individual outcomes print("\nmemory :", job.result().get_memory()) # print the length of the statevector print("\nstatevector length :", len(job.result().get_statevector())) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-cold-atom
qiskit-community
from qiskit_cold_atom.spins import SpinSimulator from qiskit import QuantumCircuit, QuantumRegister backend = SpinSimulator() qc = QuantumCircuit(4) qc.measure_all() # confirm that an empty circuit will return '0 0 0 0' job = backend.run(qc, spin=3) print(job.result().get_counts()) from qiskit_nature.second_q.operators import SpinOp from qiskit_cold_atom.spins import SpinGate import numpy as np Hx = np.pi*SpinOp({"X_0": 1}) # generator of a rotation of angle pi around the x-axis rx_spin = SpinGate(name="rx_spin", num_modes=1, generator=Hx) qc = QuantumCircuit(QuantumRegister(1, "spin")) qc.append(rx_spin, [0]) qc.measure_all() qc.draw(output='mpl', style='clifford') job = backend.run(qc, spin=10) print(job.result().get_counts()) job = backend.run(qc, spin=6) print(job.result().get_counts()) from qiskit_cold_atom.spins import RLXGate qc = QuantumCircuit(QuantumRegister(1, "spin")) qc.append(RLXGate(np.pi/2), [0]) qc.measure_all() qc.draw(output='mpl', style="clifford") # The same circuit can also be built by the following shorthand notation # which is added to QuantumCircuit upon importing from qiskit_cold_atom.spins qc = QuantumCircuit(QuantumRegister(1, "spin")) qc.rlx(np.pi/2, 0) qc.measure_all() qc.draw(output='mpl', style="clifford") from qiskit.visualization import plot_histogram job = backend.run(qc, spin=10, shots=1000, seed=123) counts = job.result().get_counts() # convert counts to integers for better formatting plot_histogram({int(k):v for k,v in counts.items()}) Hzz = SpinOp({"Z_0 Z_1": np.pi}, num_spins=2) # generating Hamiltonian acting on two spins zz_gate = SpinGate(name="zz_spin", num_modes=2, generator=Hzz) qc = QuantumCircuit(QuantumRegister(2, "spin")) qc.rlx(np.pi/2, [0, 1]) qc.append(zz_gate, [0, 1]) qc.rlx(np.pi/2, [0, 1]) qc.measure_all() qc.draw(output='mpl', style="clifford") job = backend.run(qc, spin=1, shots=1000, seed=1234) print("counts: ", job.result().get_counts()) plot_histogram(job.result().get_counts()) # access the statevector print("\nstatevector :", job.result().get_statevector()) # accedd the unitary print("\ncircuit unitary : \n", job.result().get_unitary()) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-cold-atom
qiskit-community
from qiskit_cold_atom.providers import ColdAtomProvider provider = ColdAtomProvider() backend = provider.get_backend("fermionic_tweezer_simulator") # give initial occupations separated by spin species qc = backend.initialize_circuit([[1, 0, 0, 1], [0, 0, 1, 1]]) qc.draw(output='mpl', style='clifford') qc.measure_all() print("measured counts: ", backend.run(qc, shots=10).result().get_counts()) print("measured counts: ", backend.run(qc, shots=10).result().get_memory()) from qiskit_cold_atom.fermions.fermion_gate_library import FermiHubbard qc = backend.initialize_circuit([[1, 0, 0, 1], [0, 0, 1, 1]]) all_modes=range(8) qc.append(FermiHubbard(num_modes=8, j=[0.5, 1., -1.], u=5., mu=[0., -1., 1., 0.]), qargs=all_modes) # alternatively append the FH gate directly: # qc.fhubbard(j=[0.5, 1., -1.], u=5., mu=[0., -1., 1., 0.], modes=all_modes) qc.draw(output='mpl', style='clifford') from qiskit_cold_atom.fermions.fermion_gate_library import Hop, Interaction, Phase qc = backend.initialize_circuit([[0, 1, 1, 0], [0, 1, 0, 1]]) hop_gate = Hop(num_modes=4, j=[0.5]) interaction_gate = Interaction(num_modes=8, u=2.) phase_gate = Phase(num_modes=2, mu=[1.]) qc.append(hop_gate, qargs=[0, 1, 4, 5]) qc.append(interaction_gate, qargs=all_modes) qc.append(phase_gate, qargs=[2, 6]) # equivalently, we can build the same circuit with a shortcut notation: # qc.fhop([0.5], [0, 1, 4, 5]) # qc.fint(2., all_modes) # qc.fphase([1.], [2, 6]) qc.draw(output= "mpl", style='clifford') print("hopping generator: \n", hop_gate.generator) print("\n interaction generator: \n",interaction_gate.generator) print("\n phase generator: \n", phase_gate.generator) qc.measure_all() job = backend.run(qc, shots=100) print("counts: ", job.result().get_counts()) print("time taken: ", job.result().time_taken) print(backend.get_basis(qc)) job_efficient = backend.run(qc, shots=100, num_species=2) print("counts: ", job_efficient.result().get_counts()) print("time taken: ",job_efficient.result().time_taken) print("basis: ", backend.get_basis(qc, num_species=2)) from qiskit_cold_atom.fermions.fermion_gate_library import FRXGate, FRYGate, FRZGate import numpy as np qc = backend.initialize_circuit([[0, 1, 1, 0], [0, 1, 0, 1]]) # flip the spin of the atom at site 3 qc.append(FRXGate(np.pi), [2, 6]) # equivalently use shortcut # qc.frx(np.pi, [2, 6]) qc.measure_all() print("counts: ", backend.run(qc, num_species=2).result().get_counts()) print("basis dimension :", backend.get_basis(qc).dimension) from pprint import pprint tweezer_configuration = backend.configuration().to_dict() pprint(tweezer_configuration) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-cold-atom
qiskit-community
from qiskit_cold_atom.providers import ColdAtomProvider provider = ColdAtomProvider() backend = provider.get_backend("collective_spin_simulator") from qiskit import QuantumCircuit from qiskit_cold_atom.spins.spins_gate_library import OATGate from qiskit.visualization import plot_histogram qc = QuantumCircuit(1) qc.append(OATGate(chi=0.4, delta=-1., omega=2.), qargs=[0]) # alternatively append the OAT gate directly: # qc.oat(chi=0.4, delta=-1., omega=2., wire=0) qc.measure_all() # simulate the circuit with a spin length L=5 counts = backend.run(qc, spin=5).result().get_counts() # convert counts to integers for better formatting plot_histogram({int(k):v for k,v in counts.items()}) from qiskit_cold_atom.spins.spins_gate_library import RLXGate, RLZGate, RLZ2Gate print("LX generator: \n", RLXGate(0.5).generator) print("LZ generator: \n", RLZGate(1.).generator) print("LZ2 generator: \n", RLZ2Gate(1.5).generator) from qiskit.circuit import Parameter import matplotlib.pyplot as plt import numpy as np # lenght of spin for the simulation spin = 20 # sample at 50 angles between 0 and 4*pi vals = 50 angles = np.linspace(0, 4*np.pi, vals) omega = Parameter("omega") # create list of circuits circuit = QuantumCircuit(1, 1) circuit.rlx(omega, 0) circuit.measure(0, 0) rabi_list = [circuit.assign_parameters([angle]) for angle in angles] job_rabi = backend.run(rabi_list, shots = 10, spin = spin, seed=5462) result_rabi = job_rabi.result() outcomes = np.array([np.array(result_rabi.get_memory(i), dtype=float) for i in range(vals)]) plt.errorbar(angles, np.mean(outcomes, axis=1), yerr=np.std(outcomes, axis=1), fmt='o', color="#4589ff") plt.title(f"Rabi oscillations for a single collective spin of length L = {spin}") plt.ylabel("measurement outcome") plt.xlabel("angle of x-rotation") plt.show() # circuit with spin squeezing squeez_circ = QuantumCircuit(1, 1) squeez_circ.rlx(-np.pi/2, 0) squeez_circ.rlz2(0.3, 0) squeez_circ.rlz(-np.pi/2, 0) squeez_circ.rlx(-0.15, 0) squeez_circ.measure(0, 0) job_squeez = backend.run(squeez_circ, shots = 1000, spin=20, seed=14) squeez_circ.draw(output='mpl', style="clifford") # for comparison: circuit with a single rotation circ_x = QuantumCircuit(1, 1) circ_x.rlx(np.pi/2, 0) circ_x.measure_all() job_x = backend.run(circ_x, shots = 1000, spin=20, seed=14) fig, (ax1, ax2) = plt.subplots(2, figsize=(10,8)) fig.tight_layout(pad=5.0) ax1.set_title("spin squeezing circuit") ax2.set_title("single rotation circuit") plot_histogram(job_squeez.result().get_counts(), ax=ax1, color="#9f1853") #, number_to_keep=10) plot_histogram(job_x.result().get_counts(), ax=ax2) #, number_to_keep=10) from qiskit_cold_atom.spins.spins_gate_library import RLZLZGate qc = QuantumCircuit(2) qc.rlx(np.pi/2, [0, 1]) qc.rlzlz(np.pi, [0, 1]) qc.rlx(np.pi/2, [0, 1]) qc.measure_all() plot_histogram(backend.run(qc, spin=2).result().get_counts()) plot_histogram(backend.run(qc, spin=1/2).result().get_counts()) from pprint import pprint collective_spins_configuration = backend.configuration().to_dict() pprint(collective_spins_configuration) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright