repo
stringclasses
900 values
file
stringclasses
754 values
content
stringlengths
4
215k
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for qiskit/tools/parallel""" import os import time from unittest.mock import patch from qiskit.tools.parallel import get_platform_parallel_default, parallel_map from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.pulse import Schedule from qiskit.test import QiskitTestCase def _parfunc(x): """Function for testing parallel_map""" time.sleep(1) return x def _build_simple_circuit(_): qreg = QuantumRegister(2) creg = ClassicalRegister(2) qc = QuantumCircuit(qreg, creg) return qc def _build_simple_schedule(_): return Schedule() class TestGetPlatformParallelDefault(QiskitTestCase): """Tests get_parallel_default_for_platform.""" def test_windows_parallel_default(self): """Verifies the parallel default for Windows.""" with patch("sys.platform", "win32"): parallel_default = get_platform_parallel_default() self.assertEqual(parallel_default, False) def test_mac_os_unsupported_version_parallel_default(self): """Verifies the parallel default for macOS.""" with patch("sys.platform", "darwin"): with patch("sys.version_info", (3, 8, 0, "final", 0)): parallel_default = get_platform_parallel_default() self.assertEqual(parallel_default, False) def test_other_os_parallel_default(self): """Verifies the parallel default for Linux and other OSes.""" with patch("sys.platform", "linux"): parallel_default = get_platform_parallel_default() self.assertEqual(parallel_default, True) class TestParallel(QiskitTestCase): """A class for testing parallel_map functionality.""" def test_parallel_env_flag(self): """Verify parallel env flag is set""" self.assertEqual(os.getenv("QISKIT_IN_PARALLEL", None), "FALSE") def test_parallel(self): """Test parallel_map""" ans = parallel_map(_parfunc, list(range(10))) self.assertEqual(ans, list(range(10))) def test_parallel_circuit_names(self): """Verify unique circuit names in parallel""" out_circs = parallel_map(_build_simple_circuit, list(range(10))) names = [circ.name for circ in out_circs] self.assertEqual(len(names), len(set(names))) def test_parallel_schedule_names(self): """Verify unique schedule names in parallel""" out_schedules = parallel_map(_build_simple_schedule, list(range(10))) names = [schedule.name for schedule in out_schedules] self.assertEqual(len(names), len(set(names)))
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=missing-docstring import unittest import os from unittest.mock import patch from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.test import QiskitTestCase from qiskit.utils import optionals from qiskit import visualization from qiskit.visualization.circuit import text from qiskit.visualization.exceptions import VisualizationError if optionals.HAS_MATPLOTLIB: from matplotlib import figure if optionals.HAS_PIL: from PIL import Image _latex_drawer_condition = unittest.skipUnless( all( ( optionals.HAS_PYLATEX, optionals.HAS_PIL, optionals.HAS_PDFLATEX, optionals.HAS_PDFTOCAIRO, ) ), "Skipped because not all of PIL, pylatex, pdflatex and pdftocairo are available", ) class TestCircuitDrawer(QiskitTestCase): def test_default_output(self): with patch("qiskit.user_config.get_config", return_value={}): circuit = QuantumCircuit() out = visualization.circuit_drawer(circuit) self.assertIsInstance(out, text.TextDrawing) @unittest.skipUnless(optionals.HAS_MATPLOTLIB, "Skipped because matplotlib is not available") def test_user_config_default_output(self): with patch("qiskit.user_config.get_config", return_value={"circuit_drawer": "mpl"}): circuit = QuantumCircuit() out = visualization.circuit_drawer(circuit) self.assertIsInstance(out, figure.Figure) def test_default_output_with_user_config_not_set(self): with patch("qiskit.user_config.get_config", return_value={"other_option": True}): circuit = QuantumCircuit() out = visualization.circuit_drawer(circuit) self.assertIsInstance(out, text.TextDrawing) @unittest.skipUnless(optionals.HAS_MATPLOTLIB, "Skipped because matplotlib is not available") def test_kwarg_priority_over_user_config_default_output(self): with patch("qiskit.user_config.get_config", return_value={"circuit_drawer": "latex"}): circuit = QuantumCircuit() out = visualization.circuit_drawer(circuit, output="mpl") self.assertIsInstance(out, figure.Figure) @unittest.skipUnless(optionals.HAS_MATPLOTLIB, "Skipped because matplotlib is not available") def test_default_backend_auto_output_with_mpl(self): with patch("qiskit.user_config.get_config", return_value={"circuit_drawer": "auto"}): circuit = QuantumCircuit() out = visualization.circuit_drawer(circuit) self.assertIsInstance(out, figure.Figure) def test_default_backend_auto_output_without_mpl(self): with patch("qiskit.user_config.get_config", return_value={"circuit_drawer": "auto"}): with optionals.HAS_MATPLOTLIB.disable_locally(): circuit = QuantumCircuit() out = visualization.circuit_drawer(circuit) self.assertIsInstance(out, text.TextDrawing) @_latex_drawer_condition def test_latex_unsupported_image_format_error_message(self): with patch("qiskit.user_config.get_config", return_value={"circuit_drawer": "latex"}): circuit = QuantumCircuit() with self.assertRaises(VisualizationError, msg="Pillow could not write the image file"): visualization.circuit_drawer(circuit, filename="file.spooky") @_latex_drawer_condition def test_latex_output_file_correct_format(self): with patch("qiskit.user_config.get_config", return_value={"circuit_drawer": "latex"}): circuit = QuantumCircuit() filename = "file.gif" visualization.circuit_drawer(circuit, filename=filename) with Image.open(filename) as im: if filename.endswith("jpg"): self.assertIn(im.format.lower(), "jpeg") else: self.assertIn(im.format.lower(), filename.split(".")[-1]) os.remove(filename) def test_wire_order(self): """Test wire_order See: https://github.com/Qiskit/qiskit-terra/pull/9893""" qr = QuantumRegister(4, "q") cr = ClassicalRegister(4, "c") cr2 = ClassicalRegister(2, "ca") circuit = QuantumCircuit(qr, cr, cr2) circuit.h(0) circuit.h(3) circuit.x(1) circuit.x(3).c_if(cr, 10) expected = "\n".join( [ " ", " q_2: ────────────", " β”Œβ”€β”€β”€β” β”Œβ”€β”€β”€β” ", " q_3: ─ H β”œβ”€β”€ X β”œβ”€", " β”œβ”€β”€β”€β”€ └─β•₯β”€β”˜ ", " q_0: ─ H β”œβ”€β”€β”€β•«β”€β”€β”€", " β”œβ”€β”€β”€β”€ β•‘ ", " q_1: ─ X β”œβ”€β”€β”€β•«β”€β”€β”€", " β””β”€β”€β”€β”˜β”Œβ”€β”€β•¨β”€β”€β”", " c: 4/═════║ 0xa β•ž", " β””β”€β”€β”€β”€β”€β”˜", "ca: 2/════════════", " ", ] ) result = visualization.circuit_drawer(circuit, wire_order=[2, 3, 0, 1]) self.assertEqual(result.__str__(), expected) def test_wire_order_cregbundle(self): """Test wire_order with cregbundle=True See: https://github.com/Qiskit/qiskit-terra/pull/9893""" qr = QuantumRegister(4, "q") cr = ClassicalRegister(4, "c") cr2 = ClassicalRegister(2, "ca") circuit = QuantumCircuit(qr, cr, cr2) circuit.h(0) circuit.h(3) circuit.x(1) circuit.x(3).c_if(cr, 10) expected = "\n".join( [ " ", " q_2: ────────────", " β”Œβ”€β”€β”€β” β”Œβ”€β”€β”€β” ", " q_3: ─ H β”œβ”€β”€ X β”œβ”€", " β”œβ”€β”€β”€β”€ └─β•₯β”€β”˜ ", " q_0: ─ H β”œβ”€β”€β”€β•«β”€β”€β”€", " β”œβ”€β”€β”€β”€ β•‘ ", " q_1: ─ X β”œβ”€β”€β”€β•«β”€β”€β”€", " β””β”€β”€β”€β”˜β”Œβ”€β”€β•¨β”€β”€β”", " c: 4/═════║ 0xa β•ž", " β””β”€β”€β”€β”€β”€β”˜", "ca: 2/════════════", " ", ] ) result = visualization.circuit_drawer(circuit, wire_order=[2, 3, 0, 1], cregbundle=True) self.assertEqual(result.__str__(), expected) def test_wire_order_raises(self): """Verify we raise if using wire order incorrectly.""" circuit = QuantumCircuit(3, 3) circuit.x(1) with self.assertRaisesRegex(VisualizationError, "should not have repeated elements"): visualization.circuit_drawer(circuit, wire_order=[2, 1, 0, 3, 1, 5]) with self.assertRaisesRegex(VisualizationError, "cannot be set when the reverse_bits"): visualization.circuit_drawer(circuit, wire_order=[0, 1, 2, 5, 4, 3], reverse_bits=True) with self.assertWarnsRegex(RuntimeWarning, "cregbundle set"): visualization.circuit_drawer(circuit, cregbundle=True, wire_order=[0, 1, 2, 5, 4, 3]) def test_reverse_bits(self): """Test reverse_bits should not raise warnings when no classical qubits: See: https://github.com/Qiskit/qiskit-terra/pull/8689""" circuit = QuantumCircuit(3) circuit.x(1) expected = "\n".join( [ " ", "q_2: ─────", " β”Œβ”€β”€β”€β”", "q_1: ─ X β”œ", " β””β”€β”€β”€β”˜", "q_0: ─────", " ", ] ) result = visualization.circuit_drawer(circuit, output="text", reverse_bits=True) self.assertEqual(result.__str__(), expected) @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc for LaTeX conversion") def test_no_explict_cregbundle(self): """Test no explicit cregbundle should not raise warnings about being disabled See: https://github.com/Qiskit/qiskit-terra/issues/8690""" inner = QuantumCircuit(1, 1, name="inner") inner.measure(0, 0) circuit = QuantumCircuit(2, 2) circuit.append(inner, [0], [0]) expected = "\n".join( [ " β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”", "q_0: ─0 β”œ", " β”‚ β”‚", "q_1: ─ inner β”œ", " β”‚ β”‚", "c_0: β•‘0 β•ž", " β””β”€β”€β”€β”€β”€β”€β”€β”€β”˜", "c_1: ══════════", " ", ] ) result = circuit.draw("text") self.assertEqual(result.__str__(), expected) # Extra tests that no cregbundle (or any other) warning is raised with the default settings # for the other drawers, if they're available to test. circuit.draw("latex_source") if optionals.HAS_MATPLOTLIB and optionals.HAS_PYLATEX: circuit.draw("mpl")
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for visualization of circuit with Latex drawer.""" import os import unittest import math import numpy as np from qiskit.visualization import circuit_drawer from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, transpile from qiskit.providers.fake_provider import FakeTenerife from qiskit.circuit.library import XGate, MCXGate, RZZGate, SwapGate, DCXGate, CPhaseGate from qiskit.extensions import HamiltonianGate from qiskit.circuit import Parameter, Qubit, Clbit from qiskit.circuit.library import IQP from qiskit.quantum_info.random import random_unitary from qiskit.utils import optionals from .visualization import QiskitVisualizationTestCase pi = np.pi @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc") class TestLatexSourceGenerator(QiskitVisualizationTestCase): """Qiskit latex source generator tests.""" def _get_resource_path(self, filename): reference_dir = os.path.dirname(os.path.abspath(__file__)) return os.path.join(reference_dir, filename) def test_empty_circuit(self): """Test draw an empty circuit""" filename = self._get_resource_path("test_latex_empty.tex") circuit = QuantumCircuit(1) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_tiny_circuit(self): """Test draw tiny circuit.""" filename = self._get_resource_path("test_latex_tiny.tex") circuit = QuantumCircuit(1) circuit.h(0) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_multi_underscore_reg_names(self): """Test multi-underscores in register names display properly""" filename1 = self._get_resource_path("test_latex_multi_underscore_true.tex") filename2 = self._get_resource_path("test_latex_multi_underscore_false.tex") q_reg1 = QuantumRegister(1, "q1_re__g__g") q_reg3 = QuantumRegister(3, "q3_re_g__g") c_reg1 = ClassicalRegister(1, "c1_re_g__g") c_reg3 = ClassicalRegister(3, "c3_re_g__g") circuit = QuantumCircuit(q_reg1, q_reg3, c_reg1, c_reg3) circuit_drawer(circuit, cregbundle=True, filename=filename1, output="latex_source") circuit_drawer(circuit, cregbundle=False, filename=filename2, output="latex_source") self.assertEqualToReference(filename1) self.assertEqualToReference(filename2) def test_normal_circuit(self): """Test draw normal size circuit.""" filename = self._get_resource_path("test_latex_normal.tex") circuit = QuantumCircuit(5) for qubit in range(5): circuit.h(qubit) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_4597(self): """Test cregbundle and conditional gates. See: https://github.com/Qiskit/qiskit-terra/pull/4597""" filename = self._get_resource_path("test_latex_4597.tex") qr = QuantumRegister(3, "q") cr = ClassicalRegister(3, "c") circuit = QuantumCircuit(qr, cr) circuit.x(qr[2]).c_if(cr, 2) circuit.draw(output="latex_source", cregbundle=True) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_deep_circuit(self): """Test draw deep circuit.""" filename = self._get_resource_path("test_latex_deep.tex") circuit = QuantumCircuit(1) for _ in range(100): circuit.h(0) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_huge_circuit(self): """Test draw huge circuit.""" filename = self._get_resource_path("test_latex_huge.tex") circuit = QuantumCircuit(40) for qubit in range(39): circuit.h(qubit) circuit.cx(qubit, 39) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_teleport(self): """Test draw teleport circuit.""" filename = self._get_resource_path("test_latex_teleport.tex") qr = QuantumRegister(3, "q") cr = ClassicalRegister(3, "c") circuit = QuantumCircuit(qr, cr) # Prepare an initial state circuit.u(0.3, 0.2, 0.1, [qr[0]]) # Prepare a Bell pair circuit.h(qr[1]) circuit.cx(qr[1], qr[2]) # Barrier following state preparation circuit.barrier(qr) # Measure in the Bell basis circuit.cx(qr[0], qr[1]) circuit.h(qr[0]) circuit.measure(qr[0], cr[0]) circuit.measure(qr[1], cr[1]) # Apply a correction circuit.z(qr[2]).c_if(cr, 1) circuit.x(qr[2]).c_if(cr, 2) circuit.measure(qr[2], cr[2]) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_global_phase(self): """Test circuit with global phase""" filename = self._get_resource_path("test_latex_global_phase.tex") circuit = QuantumCircuit(3, global_phase=1.57079632679) circuit.h(range(3)) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_no_ops(self): """Test circuit with no ops. See https://github.com/Qiskit/qiskit-terra/issues/5393""" filename = self._get_resource_path("test_latex_no_ops.tex") circuit = QuantumCircuit(2, 3) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_long_name(self): """Test to see that long register names can be seen completely As reported in #2605 """ filename = self._get_resource_path("test_latex_long_name.tex") # add a register with a very long name qr = QuantumRegister(4, "veryLongQuantumRegisterName") # add another to make sure adjustments are made based on longest qrr = QuantumRegister(1, "q0") circuit = QuantumCircuit(qr, qrr) # check gates are shifted over accordingly circuit.h(qr) circuit.h(qr) circuit.h(qr) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_conditional(self): """Test that circuits with conditionals draw correctly""" filename = self._get_resource_path("test_latex_conditional.tex") qr = QuantumRegister(2, "q") cr = ClassicalRegister(2, "c") circuit = QuantumCircuit(qr, cr) # check gates are shifted over accordingly circuit.h(qr) circuit.measure(qr, cr) circuit.h(qr[0]).c_if(cr, 2) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_plot_partial_barrier(self): """Test plotting of partial barriers.""" filename = self._get_resource_path("test_latex_plot_partial_barriers.tex") # generate a circuit with barrier and other barrier like instructions in q = QuantumRegister(2, "q") c = ClassicalRegister(2, "c") circuit = QuantumCircuit(q, c) # check for barriers circuit.h(q[0]) circuit.barrier(0) circuit.h(q[0]) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_plot_barriers(self): """Test to see that plotting barriers works. If it is set to False, no blank columns are introduced""" filename1 = self._get_resource_path("test_latex_plot_barriers_true.tex") filename2 = self._get_resource_path("test_latex_plot_barriers_false.tex") # generate a circuit with barriers and other barrier like instructions in q = QuantumRegister(2, "q") c = ClassicalRegister(2, "c") circuit = QuantumCircuit(q, c) # check for barriers circuit.h(q[0]) circuit.barrier() # check for other barrier like commands circuit.h(q[1]) # this import appears to be unused, but is actually needed to get snapshot instruction import qiskit.extensions.simulator # pylint: disable=unused-import circuit.snapshot("sn 1") # check the barriers plot properly when plot_barriers= True circuit_drawer(circuit, filename=filename1, output="latex_source", plot_barriers=True) self.assertEqualToReference(filename1) circuit_drawer(circuit, filename=filename2, output="latex_source", plot_barriers=False) self.assertEqualToReference(filename2) def test_no_barriers_false(self): """Generate the same circuit as test_plot_barriers but without the barrier commands as this is what the circuit should look like when displayed with plot barriers false""" filename = self._get_resource_path("test_latex_no_barriers_false.tex") q1 = QuantumRegister(2, "q") c1 = ClassicalRegister(2, "c") circuit = QuantumCircuit(q1, c1) circuit.h(q1[0]) circuit.h(q1[1]) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_barrier_label(self): """Test the barrier label""" filename = self._get_resource_path("test_latex_barrier_label.tex") qr = QuantumRegister(2, "q") circuit = QuantumCircuit(qr) circuit.x(0) circuit.y(1) circuit.barrier() circuit.y(0) circuit.x(1) circuit.barrier(label="End Y/X") circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_big_gates(self): """Test large gates with params""" filename = self._get_resource_path("test_latex_big_gates.tex") qr = QuantumRegister(6, "q") circuit = QuantumCircuit(qr) circuit.append(IQP([[6, 5, 3], [5, 4, 5], [3, 5, 1]]), [0, 1, 2]) desired_vector = [ 1 / math.sqrt(16) * complex(0, 1), 1 / math.sqrt(8) * complex(1, 0), 1 / math.sqrt(16) * complex(1, 1), 0, 0, 1 / math.sqrt(8) * complex(1, 2), 1 / math.sqrt(16) * complex(1, 0), 0, ] circuit.initialize(desired_vector, [qr[3], qr[4], qr[5]]) circuit.unitary([[1, 0], [0, 1]], [qr[0]]) matrix = np.zeros((4, 4)) theta = Parameter("theta") circuit.append(HamiltonianGate(matrix, theta), [qr[1], qr[2]]) circuit = circuit.bind_parameters({theta: 1}) circuit.isometry(np.eye(4, 4), list(range(3, 5)), []) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_cnot(self): """Test different cnot gates (ccnot, mcx, etc)""" filename = self._get_resource_path("test_latex_cnot.tex") qr = QuantumRegister(5, "q") circuit = QuantumCircuit(qr) circuit.x(0) circuit.cx(0, 1) circuit.ccx(0, 1, 2) circuit.append(XGate().control(3, ctrl_state="010"), [qr[2], qr[3], qr[0], qr[1]]) circuit.append(MCXGate(num_ctrl_qubits=3, ctrl_state="101"), [qr[0], qr[1], qr[2], qr[4]]) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_pauli_clifford(self): """Test Pauli(green) and Clifford(blue) gates""" filename = self._get_resource_path("test_latex_pauli_clifford.tex") qr = QuantumRegister(5, "q") circuit = QuantumCircuit(qr) circuit.x(0) circuit.y(0) circuit.z(0) circuit.id(0) circuit.h(1) circuit.cx(1, 2) circuit.cy(1, 2) circuit.cz(1, 2) circuit.swap(3, 4) circuit.s(3) circuit.sdg(3) circuit.iswap(3, 4) circuit.dcx(3, 4) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_u_gates(self): """Test U 1, 2, & 3 gates""" filename = self._get_resource_path("test_latex_u_gates.tex") from qiskit.circuit.library import U1Gate, U2Gate, U3Gate, CU1Gate, CU3Gate qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.append(U1Gate(3 * pi / 2), [0]) circuit.append(U2Gate(3 * pi / 2, 2 * pi / 3), [1]) circuit.append(U3Gate(3 * pi / 2, 4.5, pi / 4), [2]) circuit.append(CU1Gate(pi / 4), [0, 1]) circuit.append(U2Gate(pi / 2, 3 * pi / 2).control(1), [2, 3]) circuit.append(CU3Gate(3 * pi / 2, -3 * pi / 4, -pi / 2), [0, 1]) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_creg_initial(self): """Test cregbundle and initial state options""" filename1 = self._get_resource_path("test_latex_creg_initial_true.tex") filename2 = self._get_resource_path("test_latex_creg_initial_false.tex") qr = QuantumRegister(2, "q") cr = ClassicalRegister(2, "c") circuit = QuantumCircuit(qr, cr) circuit.x(0) circuit.h(0) circuit.x(1) circuit_drawer( circuit, filename=filename1, output="latex_source", cregbundle=True, initial_state=True ) self.assertEqualToReference(filename1) circuit_drawer( circuit, filename=filename2, output="latex_source", cregbundle=False, initial_state=False, ) self.assertEqualToReference(filename2) def test_r_gates(self): """Test all R gates""" filename = self._get_resource_path("test_latex_r_gates.tex") qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.r(3 * pi / 4, 3 * pi / 8, 0) circuit.rx(pi / 2, 1) circuit.ry(-pi / 2, 2) circuit.rz(3 * pi / 4, 3) circuit.rxx(pi / 2, 0, 1) circuit.ryy(3 * pi / 4, 2, 3) circuit.rzx(-pi / 2, 0, 1) circuit.rzz(pi / 2, 2, 3) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_cswap_rzz(self): """Test controlled swap and rzz gates""" filename = self._get_resource_path("test_latex_cswap_rzz.tex") qr = QuantumRegister(5, "q") circuit = QuantumCircuit(qr) circuit.x(0) circuit.x(1) circuit.cswap(0, 1, 2) circuit.append(RZZGate(3 * pi / 4).control(3, ctrl_state="010"), [2, 1, 4, 3, 0]) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_ghz_to_gate(self): """Test controlled GHZ to_gate circuit""" filename = self._get_resource_path("test_latex_ghz_to_gate.tex") qr = QuantumRegister(5, "q") circuit = QuantumCircuit(qr) ghz_circuit = QuantumCircuit(3, name="Ctrl-GHZ Circuit") ghz_circuit.h(0) ghz_circuit.cx(0, 1) ghz_circuit.cx(1, 2) ghz = ghz_circuit.to_gate() ccghz = ghz.control(2, ctrl_state="10") circuit.append(ccghz, [4, 0, 1, 3, 2]) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_scale(self): """Tests scale See: https://github.com/Qiskit/qiskit-terra/issues/4179""" filename1 = self._get_resource_path("test_latex_scale_default.tex") filename2 = self._get_resource_path("test_latex_scale_half.tex") filename3 = self._get_resource_path("test_latex_scale_double.tex") circuit = QuantumCircuit(5) circuit.unitary(random_unitary(2**5), circuit.qubits) circuit_drawer(circuit, filename=filename1, output="latex_source") self.assertEqualToReference(filename1) circuit_drawer(circuit, filename=filename2, output="latex_source", scale=0.5) self.assertEqualToReference(filename2) circuit_drawer(circuit, filename=filename3, output="latex_source", scale=2.0) self.assertEqualToReference(filename3) def test_pi_param_expr(self): """Text pi in circuit with parameter expression.""" filename = self._get_resource_path("test_latex_pi_param_expr.tex") x, y = Parameter("x"), Parameter("y") circuit = QuantumCircuit(1) circuit.rx((pi - x) * (pi - y), 0) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_partial_layout(self): """Tests partial_layout See: https://github.com/Qiskit/qiskit-terra/issues/4757""" filename = self._get_resource_path("test_latex_partial_layout.tex") circuit = QuantumCircuit(3) circuit.h(1) transpiled = transpile( circuit, backend=FakeTenerife(), optimization_level=0, initial_layout=[1, 2, 0], seed_transpiler=0, ) circuit_drawer(transpiled, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_init_reset(self): """Test reset and initialize with 1 and 2 qubits""" filename = self._get_resource_path("test_latex_init_reset.tex") circuit = QuantumCircuit(2) circuit.initialize([0, 1], 0) circuit.reset(1) circuit.initialize([0, 1, 0, 0], [0, 1]) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_iqx_colors(self): """Tests with iqx color scheme""" filename = self._get_resource_path("test_latex_iqx.tex") circuit = QuantumCircuit(7) circuit.h(0) circuit.x(0) circuit.cx(0, 1) circuit.ccx(0, 1, 2) circuit.swap(0, 1) circuit.cswap(0, 1, 2) circuit.append(SwapGate().control(2), [0, 1, 2, 3]) circuit.dcx(0, 1) circuit.append(DCXGate().control(1), [0, 1, 2]) circuit.append(DCXGate().control(2), [0, 1, 2, 3]) circuit.z(4) circuit.s(4) circuit.sdg(4) circuit.t(4) circuit.tdg(4) circuit.p(pi / 2, 4) circuit.p(pi / 2, 4) circuit.cz(5, 6) circuit.cp(pi / 2, 5, 6) circuit.y(5) circuit.rx(pi / 3, 5) circuit.rzx(pi / 2, 5, 6) circuit.u(pi / 2, pi / 2, pi / 2, 5) circuit.barrier(5, 6) circuit.reset(5) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_reverse_bits(self): """Tests reverse_bits parameter""" filename = self._get_resource_path("test_latex_reverse_bits.tex") circuit = QuantumCircuit(3) circuit.h(0) circuit.cx(0, 1) circuit.ccx(2, 1, 0) circuit_drawer(circuit, filename=filename, output="latex_source", reverse_bits=True) self.assertEqualToReference(filename) def test_meas_condition(self): """Tests measure with a condition""" filename = self._get_resource_path("test_latex_meas_condition.tex") qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") circuit = QuantumCircuit(qr, cr) circuit.h(qr[0]) circuit.measure(qr[0], cr[0]) circuit.h(qr[1]).c_if(cr, 1) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_inst_with_cbits(self): """Test custom instructions with classical bits""" filename = self._get_resource_path("test_latex_inst_with_cbits.tex") qinst = QuantumRegister(2, "q") cinst = ClassicalRegister(2, "c") inst = QuantumCircuit(qinst, cinst, name="instruction").to_instruction() qr = QuantumRegister(4, "qr") cr = ClassicalRegister(4, "cr") circuit = QuantumCircuit(qr, cr) circuit.append(inst, [qr[1], qr[2]], [cr[2], cr[1]]) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_cif_single_bit(self): """Tests conditioning gates on single classical bit""" filename = self._get_resource_path("test_latex_cif_single_bit.tex") qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") circuit = QuantumCircuit(qr, cr) circuit.h(qr[0]).c_if(cr[1], 0) circuit.x(qr[1]).c_if(cr[0], 1) circuit_drawer(circuit, cregbundle=False, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_cif_single_bit_cregbundle(self): """Tests conditioning gates on single classical bit with cregbundle""" filename = self._get_resource_path("test_latex_cif_single_bit_bundle.tex") qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") circuit = QuantumCircuit(qr, cr) circuit.h(qr[0]).c_if(cr[1], 0) circuit.x(qr[1]).c_if(cr[0], 1) circuit_drawer(circuit, cregbundle=True, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_registerless_one_bit(self): """Text circuit with one-bit registers and registerless bits.""" filename = self._get_resource_path("test_latex_registerless_one_bit.tex") qrx = QuantumRegister(2, "qrx") qry = QuantumRegister(1, "qry") crx = ClassicalRegister(2, "crx") circuit = QuantumCircuit(qrx, [Qubit(), Qubit()], qry, [Clbit(), Clbit()], crx) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_measures_with_conditions(self): """Test that a measure containing a condition displays""" filename1 = self._get_resource_path("test_latex_meas_cond_false.tex") filename2 = self._get_resource_path("test_latex_meas_cond_true.tex") qr = QuantumRegister(2, "qr") cr1 = ClassicalRegister(2, "cr1") cr2 = ClassicalRegister(2, "cr2") circuit = QuantumCircuit(qr, cr1, cr2) circuit.h(0) circuit.h(1) circuit.measure(0, cr1[1]) circuit.measure(1, cr2[0]).c_if(cr1, 1) circuit.h(0).c_if(cr2, 3) circuit_drawer(circuit, cregbundle=False, filename=filename1, output="latex_source") circuit_drawer(circuit, cregbundle=True, filename=filename2, output="latex_source") self.assertEqualToReference(filename1) self.assertEqualToReference(filename2) def test_measures_with_conditions_with_bits(self): """Condition and measure on single bits cregbundle true""" filename1 = self._get_resource_path("test_latex_meas_cond_bits_false.tex") filename2 = self._get_resource_path("test_latex_meas_cond_bits_true.tex") bits = [Qubit(), Qubit(), Clbit(), Clbit()] cr = ClassicalRegister(2, "cr") crx = ClassicalRegister(3, "cs") circuit = QuantumCircuit(bits, cr, [Clbit()], crx) circuit.x(0).c_if(crx[1], 0) circuit.measure(0, bits[3]) circuit_drawer(circuit, cregbundle=False, filename=filename1, output="latex_source") circuit_drawer(circuit, cregbundle=True, filename=filename2, output="latex_source") self.assertEqualToReference(filename1) self.assertEqualToReference(filename2) def test_conditions_with_bits_reverse(self): """Test that gates with conditions and measures work with bits reversed""" filename = self._get_resource_path("test_latex_cond_reverse.tex") bits = [Qubit(), Qubit(), Clbit(), Clbit()] cr = ClassicalRegister(2, "cr") crx = ClassicalRegister(3, "cs") circuit = QuantumCircuit(bits, cr, [Clbit()], crx) circuit.x(0).c_if(bits[3], 0) circuit_drawer( circuit, cregbundle=False, reverse_bits=True, filename=filename, output="latex_source" ) self.assertEqualToReference(filename) def test_sidetext_with_condition(self): """Test that sidetext gates align properly with a condition""" filename = self._get_resource_path("test_latex_sidetext_condition.tex") qr = QuantumRegister(2, "q") cr = ClassicalRegister(2, "c") circuit = QuantumCircuit(qr, cr) circuit.append(CPhaseGate(pi / 2), [qr[0], qr[1]]).c_if(cr[1], 1) circuit_drawer(circuit, cregbundle=False, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_idle_wires_barrier(self): """Test that idle_wires False works with barrier""" filename = self._get_resource_path("test_latex_idle_wires_barrier.tex") circuit = QuantumCircuit(4, 4) circuit.x(2) circuit.barrier() circuit_drawer(circuit, idle_wires=False, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_wire_order(self): """Test the wire_order option to latex drawer""" filename = self._get_resource_path("test_latex_wire_order.tex") qr = QuantumRegister(4, "q") cr = ClassicalRegister(4, "c") cr2 = ClassicalRegister(2, "ca") circuit = QuantumCircuit(qr, cr, cr2) circuit.h(0) circuit.h(3) circuit.x(1) circuit.x(3).c_if(cr, 12) circuit_drawer( circuit, cregbundle=False, wire_order=[2, 1, 3, 0, 6, 8, 9, 5, 4, 7], filename=filename, output="latex_source", ) self.assertEqualToReference(filename) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """A test for visualizing device coupling maps""" import unittest from io import BytesIO from ddt import ddt, data from qiskit.providers.fake_provider import ( FakeProvider, FakeKolkata, FakeWashington, FakeKolkataV2, FakeWashingtonV2, ) from qiskit.visualization import ( plot_gate_map, plot_coupling_map, plot_circuit_layout, plot_error_map, ) from qiskit.utils import optionals from qiskit import QuantumRegister, QuantumCircuit from qiskit.transpiler.layout import Layout, TranspileLayout from .visualization import path_to_diagram_reference, QiskitVisualizationTestCase if optionals.HAS_MATPLOTLIB: import matplotlib.pyplot as plt if optionals.HAS_PIL: from PIL import Image @ddt @unittest.skipUnless(optionals.HAS_MATPLOTLIB, "matplotlib not available.") @unittest.skipUnless(optionals.HAS_PIL, "PIL not available") @unittest.skipUnless(optionals.HAS_SEABORN, "seaborn not available") class TestGateMap(QiskitVisualizationTestCase): """visual tests for plot_gate_map""" backends = list( filter( lambda x: not x.configuration().simulator and x.configuration().num_qubits in range(5, 21), FakeProvider().backends(), ) ) @data(*backends) def test_plot_gate_map(self, backend): """tests plotting of gate map of a device (20 qubit, 16 qubit, 14 qubit and 5 qubit)""" n = backend.configuration().n_qubits img_ref = path_to_diagram_reference(str(n) + "bit_quantum_computer.png") fig = plot_gate_map(backend) with BytesIO() as img_buffer: fig.savefig(img_buffer, format="png") img_buffer.seek(0) self.assertImagesAreEqual(Image.open(img_buffer), img_ref, 0.2) plt.close(fig) @data(*backends) def test_plot_circuit_layout(self, backend): """tests plot_circuit_layout for each device""" layout_length = int(backend._configuration.n_qubits / 2) qr = QuantumRegister(layout_length, "qr") circuit = QuantumCircuit(qr) circuit._layout = TranspileLayout( Layout({qr[i]: i * 2 for i in range(layout_length)}), {qubit: index for index, qubit in enumerate(circuit.qubits)}, ) circuit._layout.initial_layout.add_register(qr) n = backend.configuration().n_qubits img_ref = path_to_diagram_reference(str(n) + "_plot_circuit_layout.png") fig = plot_circuit_layout(circuit, backend) with BytesIO() as img_buffer: fig.savefig(img_buffer, format="png") img_buffer.seek(0) self.assertImagesAreEqual(Image.open(img_buffer), img_ref, 0.1) plt.close(fig) def test_plot_gate_map_no_backend(self): """tests plotting of gate map without a device""" n_qubits = 8 coupling_map = [[0, 1], [1, 2], [2, 3], [3, 5], [4, 5], [5, 6], [2, 4], [6, 7]] qubit_coordinates = [[0, 1], [1, 1], [1, 0], [1, 2], [2, 0], [2, 2], [2, 1], [3, 1]] img_ref = path_to_diagram_reference(str(n_qubits) + "qubits.png") fig = plot_coupling_map( num_qubits=n_qubits, qubit_coordinates=qubit_coordinates, coupling_map=coupling_map ) with BytesIO() as img_buffer: fig.savefig(img_buffer, format="png") img_buffer.seek(0) self.assertImagesAreEqual(Image.open(img_buffer), img_ref, 0.2) plt.close(fig) def test_plot_error_map_backend_v1(self): """Test plotting error map with fake backend v1.""" backend = FakeKolkata() img_ref = path_to_diagram_reference("kolkata_error.png") fig = plot_error_map(backend) with BytesIO() as img_buffer: fig.savefig(img_buffer, format="png") img_buffer.seek(0) self.assertImagesAreEqual(Image.open(img_buffer), img_ref, 0.2) plt.close(fig) def test_plot_error_map_backend_v2(self): """Test plotting error map with fake backend v2.""" backend = FakeKolkataV2() img_ref = path_to_diagram_reference("kolkata_v2_error.png") fig = plot_error_map(backend) with BytesIO() as img_buffer: fig.savefig(img_buffer, format="png") img_buffer.seek(0) self.assertImagesAreEqual(Image.open(img_buffer), img_ref, 0.2) plt.close(fig) def test_plot_error_map_over_100_qubit(self): """Test plotting error map with large fake backend.""" backend = FakeWashington() img_ref = path_to_diagram_reference("washington_error.png") fig = plot_error_map(backend) with BytesIO() as img_buffer: fig.savefig(img_buffer, format="png") img_buffer.seek(0) self.assertImagesAreEqual(Image.open(img_buffer), img_ref, 0.2) plt.close(fig) def test_plot_error_map_over_100_qubit_backend_v2(self): """Test plotting error map with large fake backendv2.""" backend = FakeWashingtonV2() img_ref = path_to_diagram_reference("washington_v2_error.png") fig = plot_error_map(backend) with BytesIO() as img_buffer: fig.savefig(img_buffer, format="png") img_buffer.seek(0) self.assertImagesAreEqual(Image.open(img_buffer), img_ref, 0.2) plt.close(fig) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for pass manager visualization tool.""" import unittest import os from qiskit.transpiler import CouplingMap, Layout from qiskit.transpiler.passmanager import PassManager from qiskit import QuantumRegister from qiskit.transpiler.passes import GateDirection, Unroller from qiskit.transpiler.passes import CheckMap from qiskit.transpiler.passes import SetLayout from qiskit.transpiler.passes import TrivialLayout from qiskit.transpiler.passes import BarrierBeforeFinalMeasurements from qiskit.transpiler.passes import FullAncillaAllocation from qiskit.transpiler.passes import EnlargeWithAncilla from qiskit.transpiler.passes import RemoveResetInZeroState from qiskit.utils import optionals from .visualization import QiskitVisualizationTestCase, path_to_diagram_reference @unittest.skipUnless(optionals.HAS_GRAPHVIZ, "Graphviz not installed.") @unittest.skipUnless(optionals.HAS_PYDOT, "pydot not installed") @unittest.skipUnless(optionals.HAS_PIL, "Pillow not installed") class TestPassManagerDrawer(QiskitVisualizationTestCase): """Qiskit pass manager drawer tests.""" def setUp(self): super().setUp() coupling = [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6]] coupling_map = CouplingMap(couplinglist=coupling) basis_gates = ["u1", "u3", "u2", "cx"] qr = QuantumRegister(7, "q") layout = Layout({qr[i]: i for i in range(coupling_map.size())}) # Create a pass manager with a variety of passes and flow control structures self.pass_manager = PassManager() self.pass_manager.append(SetLayout(layout)) self.pass_manager.append(TrivialLayout(coupling_map), condition=lambda x: True) self.pass_manager.append(FullAncillaAllocation(coupling_map)) self.pass_manager.append(EnlargeWithAncilla()) self.pass_manager.append(Unroller(basis_gates)) self.pass_manager.append(CheckMap(coupling_map)) self.pass_manager.append(BarrierBeforeFinalMeasurements(), do_while=lambda x: False) self.pass_manager.append(GateDirection(coupling_map)) self.pass_manager.append(RemoveResetInZeroState()) def test_pass_manager_drawer_basic(self): """Test to see if the drawer draws a normal pass manager correctly""" filename = "current_standard.dot" self.pass_manager.draw(filename=filename, raw=True) try: self.assertFilesAreEqual( filename, path_to_diagram_reference("pass_manager_standard.dot") ) finally: os.remove(filename) def test_pass_manager_drawer_style(self): """Test to see if the colours are updated when provided by the user""" # set colours for some passes, but leave others to take the default values style = { SetLayout: "cyan", CheckMap: "green", EnlargeWithAncilla: "pink", RemoveResetInZeroState: "grey", } filename = "current_style.dot" self.pass_manager.draw(filename=filename, style=style, raw=True) try: self.assertFilesAreEqual(filename, path_to_diagram_reference("pass_manager_style.dot")) finally: os.remove(filename) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for visualization tools.""" import unittest import numpy as np from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.circuit import Qubit, Clbit from qiskit.visualization.circuit import _utils from qiskit.visualization import array_to_latex from qiskit.test import QiskitTestCase from qiskit.utils import optionals class TestVisualizationUtils(QiskitTestCase): """Tests for circuit drawer utilities.""" def setUp(self): super().setUp() self.qr1 = QuantumRegister(2, "qr1") self.qr2 = QuantumRegister(2, "qr2") self.cr1 = ClassicalRegister(2, "cr1") self.cr2 = ClassicalRegister(2, "cr2") self.circuit = QuantumCircuit(self.qr1, self.qr2, self.cr1, self.cr2) self.circuit.cx(self.qr2[0], self.qr2[1]) self.circuit.measure(self.qr2[0], self.cr2[0]) self.circuit.cx(self.qr2[1], self.qr2[0]) self.circuit.measure(self.qr2[1], self.cr2[1]) self.circuit.cx(self.qr1[0], self.qr1[1]) self.circuit.measure(self.qr1[0], self.cr1[0]) self.circuit.cx(self.qr1[1], self.qr1[0]) self.circuit.measure(self.qr1[1], self.cr1[1]) def test_get_layered_instructions(self): """_get_layered_instructions without reverse_bits""" (qregs, cregs, layered_ops) = _utils._get_layered_instructions(self.circuit) exp = [ [("cx", (self.qr2[0], self.qr2[1]), ()), ("cx", (self.qr1[0], self.qr1[1]), ())], [("measure", (self.qr2[0],), (self.cr2[0],))], [("measure", (self.qr1[0],), (self.cr1[0],))], [("cx", (self.qr2[1], self.qr2[0]), ()), ("cx", (self.qr1[1], self.qr1[0]), ())], [("measure", (self.qr2[1],), (self.cr2[1],))], [("measure", (self.qr1[1],), (self.cr1[1],))], ] self.assertEqual([self.qr1[0], self.qr1[1], self.qr2[0], self.qr2[1]], qregs) self.assertEqual([self.cr1[0], self.cr1[1], self.cr2[0], self.cr2[1]], cregs) self.assertEqual( exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_reverse_bits(self): """_get_layered_instructions with reverse_bits=True""" (qregs, cregs, layered_ops) = _utils._get_layered_instructions( self.circuit, reverse_bits=True ) exp = [ [("cx", (self.qr2[0], self.qr2[1]), ()), ("cx", (self.qr1[0], self.qr1[1]), ())], [("measure", (self.qr2[0],), (self.cr2[0],))], [("measure", (self.qr1[0],), (self.cr1[0],)), ("cx", (self.qr2[1], self.qr2[0]), ())], [("cx", (self.qr1[1], self.qr1[0]), ())], [("measure", (self.qr2[1],), (self.cr2[1],))], [("measure", (self.qr1[1],), (self.cr1[1],))], ] self.assertEqual([self.qr2[1], self.qr2[0], self.qr1[1], self.qr1[0]], qregs) self.assertEqual([self.cr2[1], self.cr2[0], self.cr1[1], self.cr1[0]], cregs) self.assertEqual( exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_remove_idle_wires(self): """_get_layered_instructions with idle_wires=False""" qr1 = QuantumRegister(3, "qr1") qr2 = QuantumRegister(3, "qr2") cr1 = ClassicalRegister(3, "cr1") cr2 = ClassicalRegister(3, "cr2") circuit = QuantumCircuit(qr1, qr2, cr1, cr2) circuit.cx(qr2[0], qr2[1]) circuit.measure(qr2[0], cr2[0]) circuit.cx(qr2[1], qr2[0]) circuit.measure(qr2[1], cr2[1]) circuit.cx(qr1[0], qr1[1]) circuit.measure(qr1[0], cr1[0]) circuit.cx(qr1[1], qr1[0]) circuit.measure(qr1[1], cr1[1]) (qregs, cregs, layered_ops) = _utils._get_layered_instructions(circuit, idle_wires=False) exp = [ [("cx", (qr2[0], qr2[1]), ()), ("cx", (qr1[0], qr1[1]), ())], [("measure", (qr2[0],), (cr2[0],))], [("measure", (qr1[0],), (cr1[0],))], [("cx", (qr2[1], qr2[0]), ()), ("cx", (qr1[1], qr1[0]), ())], [("measure", (qr2[1],), (cr2[1],))], [("measure", (qr1[1],), (cr1[1],))], ] self.assertEqual([qr1[0], qr1[1], qr2[0], qr2[1]], qregs) self.assertEqual([cr1[0], cr1[1], cr2[0], cr2[1]], cregs) self.assertEqual( exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_left_justification_simple(self): """Test _get_layered_instructions left justification simple since #2802 q_0: |0>───────■── β”Œβ”€β”€β”€β” β”‚ q_1: |0>─ H β”œβ”€β”€β”Όβ”€β”€ β”œβ”€β”€β”€β”€ β”‚ q_2: |0>─ H β”œβ”€β”€β”Όβ”€β”€ β””β”€β”€β”€β”˜β”Œβ”€β”΄β”€β” q_3: |0>────── X β”œ β””β”€β”€β”€β”˜ """ qc = QuantumCircuit(4) qc.h(1) qc.h(2) qc.cx(0, 3) (_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="left") l_exp = [ [ ("h", (Qubit(QuantumRegister(4, "q"), 1),), ()), ("h", (Qubit(QuantumRegister(4, "q"), 2),), ()), ], [("cx", (Qubit(QuantumRegister(4, "q"), 0), Qubit(QuantumRegister(4, "q"), 3)), ())], ] self.assertEqual( l_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_right_justification_simple(self): """Test _get_layered_instructions right justification simple since #2802 q_0: |0>──■─────── β”‚ β”Œβ”€β”€β”€β” q_1: |0>──┼─── H β”œ β”‚ β”œβ”€β”€β”€β”€ q_2: |0>──┼─── H β”œ β”Œβ”€β”΄β”€β”β””β”€β”€β”€β”˜ q_3: |0>─ X β”œβ”€β”€β”€β”€β”€ β””β”€β”€β”€β”˜ """ qc = QuantumCircuit(4) qc.h(1) qc.h(2) qc.cx(0, 3) (_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="right") r_exp = [ [("cx", (Qubit(QuantumRegister(4, "q"), 0), Qubit(QuantumRegister(4, "q"), 3)), ())], [ ("h", (Qubit(QuantumRegister(4, "q"), 1),), ()), ("h", (Qubit(QuantumRegister(4, "q"), 2),), ()), ], ] self.assertEqual( r_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_left_justification_less_simple(self): """Test _get_layered_instructions left justification less simple example since #2802 β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β”Œβ”€β”€β”€β”β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β”Œβ”€β”€β”€β”β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” q_0: |0>─ U2(0,pi/1) β”œβ”€ X β”œβ”€ U2(0,pi/1) β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€Mβ”œβ”€ U2(0,pi/1) β”œβ”€ X β”œβ”€ U2(0,pi/1) β”œ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β””β”€β”¬β”€β”˜β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β””β•₯β”˜β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β””β”€β”¬β”€β”˜β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ q_1: |0>─ U2(0,pi/1) β”œβ”€β”€β– β”€β”€β”€ U2(0,pi/1) β”œβ”€ U2(0,pi/1) β”œβ”€β•«β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β– β”€β”€β”€ U2(0,pi/1) β”œ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β•‘ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ q_2: |0>────────────────────────────────────────────────╫────────────────────────────────── β•‘ q_3: |0>────────────────────────────────────────────────╫────────────────────────────────── β•‘ q_4: |0>────────────────────────────────────────────────╫────────────────────────────────── β•‘ c1_0: 0 ════════════════════════════════════════════════╩══════════════════════════════════ """ qasm = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[5]; creg c1[1]; u2(0,3.14159265358979) q[0]; u2(0,3.14159265358979) q[1]; cx q[1],q[0]; u2(0,3.14159265358979) q[0]; u2(0,3.14159265358979) q[1]; u2(0,3.14159265358979) q[1]; measure q[0] -> c1[0]; u2(0,3.14159265358979) q[0]; cx q[1],q[0]; u2(0,3.14159265358979) q[0]; u2(0,3.14159265358979) q[1]; """ qc = QuantumCircuit.from_qasm_str(qasm) (_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="left") l_exp = [ [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], [("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())], [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], [("u2", (Qubit(QuantumRegister(5, "q"), 1),), ())], [ ( "measure", (Qubit(QuantumRegister(5, "q"), 0),), (Clbit(ClassicalRegister(1, "c1"), 0),), ) ], [("u2", (Qubit(QuantumRegister(5, "q"), 0),), ())], [("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())], [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], ] self.assertEqual( l_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_right_justification_less_simple(self): """Test _get_layered_instructions right justification less simple example since #2802 β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β”Œβ”€β”€β”€β”β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β”Œβ”€β”β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β”Œβ”€β”€β”€β”β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” q_0: |0>─ U2(0,pi/1) β”œβ”€ X β”œβ”€ U2(0,pi/1) β”œβ”€Mβ”œβ”€ U2(0,pi/1) β”œβ”€ X β”œβ”€ U2(0,pi/1) β”œ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β””β”€β”¬β”€β”˜β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β””β•₯β”˜β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β””β”€β”¬β”€β”˜β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ q_1: |0>─ U2(0,pi/1) β”œβ”€β”€β– β”€β”€β”€ U2(0,pi/1) β”œβ”€β•«β”€β”€ U2(0,pi/1) β”œβ”€β”€β– β”€β”€β”€ U2(0,pi/1) β”œ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β•‘ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ q_2: |0>──────────────────────────────────╫────────────────────────────────── β•‘ q_3: |0>──────────────────────────────────╫────────────────────────────────── β•‘ q_4: |0>──────────────────────────────────╫────────────────────────────────── β•‘ c1_0: 0 ══════════════════════════════════╩══════════════════════════════════ """ qasm = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[5]; creg c1[1]; u2(0,3.14159265358979) q[0]; u2(0,3.14159265358979) q[1]; cx q[1],q[0]; u2(0,3.14159265358979) q[0]; u2(0,3.14159265358979) q[1]; u2(0,3.14159265358979) q[1]; measure q[0] -> c1[0]; u2(0,3.14159265358979) q[0]; cx q[1],q[0]; u2(0,3.14159265358979) q[0]; u2(0,3.14159265358979) q[1]; """ qc = QuantumCircuit.from_qasm_str(qasm) (_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="right") r_exp = [ [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], [("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())], [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], [ ( "measure", (Qubit(QuantumRegister(5, "q"), 0),), (Clbit(ClassicalRegister(1, "c1"), 0),), ) ], [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], [("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())], [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], ] self.assertEqual( r_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_op_with_cargs(self): """Test _get_layered_instructions op with cargs right of measure β”Œβ”€β”€β”€β”β”Œβ”€β” q_0: |0>─ H β”œβ”€Mβ”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β””β”€β”€β”€β”˜β””β•₯β”˜β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” q_1: |0>──────╫──0 β”œ β•‘ β”‚ add_circ β”‚ c_0: 0 ══════╩═║0 β•ž β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ c_1: 0 ═════════════════════ """ qc = QuantumCircuit(2, 2) qc.h(0) qc.measure(0, 0) qc_2 = QuantumCircuit(1, 1, name="add_circ") qc_2.h(0).c_if(qc_2.cregs[0], 1) qc_2.measure(0, 0) qc.append(qc_2, [1], [0]) (_, _, layered_ops) = _utils._get_layered_instructions(qc) expected = [ [("h", (Qubit(QuantumRegister(2, "q"), 0),), ())], [ ( "measure", (Qubit(QuantumRegister(2, "q"), 0),), (Clbit(ClassicalRegister(2, "c"), 0),), ) ], [ ( "add_circ", (Qubit(QuantumRegister(2, "q"), 1),), (Clbit(ClassicalRegister(2, "c"), 0),), ) ], ] self.assertEqual( expected, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc") def test_generate_latex_label_nomathmode(self): """Test generate latex label default.""" self.assertEqual("abc", _utils.generate_latex_label("abc")) @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc") def test_generate_latex_label_nomathmode_utf8char(self): """Test generate latex label utf8 characters.""" self.assertEqual( "{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y", _utils.generate_latex_label("∭Xβˆ€Y"), ) @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc") def test_generate_latex_label_mathmode_utf8char(self): """Test generate latex label mathtext with utf8.""" self.assertEqual( "abc_{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y", _utils.generate_latex_label("$abc_$∭Xβˆ€Y"), ) @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc") def test_generate_latex_label_mathmode_underscore_outside(self): """Test generate latex label with underscore outside mathmode.""" self.assertEqual( "abc_{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y", _utils.generate_latex_label("$abc$_∭Xβˆ€Y"), ) @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc") def test_generate_latex_label_escaped_dollar_signs(self): """Test generate latex label with escaped dollarsign.""" self.assertEqual("${\\ensuremath{\\forall}}$", _utils.generate_latex_label(r"\$βˆ€\$")) @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc") def test_generate_latex_label_escaped_dollar_sign_in_mathmode(self): """Test generate latex label with escaped dollar sign in mathmode.""" self.assertEqual( "a$bc_{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y", _utils.generate_latex_label(r"$a$bc$_∭Xβˆ€Y"), ) def test_array_to_latex(self): """Test array_to_latex produces correct latex string""" matrix = [ [np.sqrt(1 / 2), 1 / 16, 1 / np.sqrt(8) + 3j, -0.5 + 0.5j], [1 / 3 - 1 / 3j, np.sqrt(1 / 2) * 1j, 34.3210, -9 / 2], ] matrix = np.array(matrix) exp_str = ( "\\begin{bmatrix}\\frac{\\sqrt{2}}{2}&\\frac{1}{16}&" "\\frac{\\sqrt{2}}{4}+3i&-\\frac{1}{2}+\\frac{i}{2}\\\\" "\\frac{1}{3}+\\frac{i}{3}&\\frac{\\sqrt{2}i}{2}&34.321&-" "\\frac{9}{2}\\\\\\end{bmatrix}" ) result = array_to_latex(matrix, source=True).replace(" ", "").replace("\n", "") self.assertEqual(exp_str, result) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for core modules of timeline drawer.""" from qiskit import QuantumCircuit, transpile from qiskit.test import QiskitTestCase from qiskit.visualization.timeline import core, stylesheet, generators, layouts class TestCanvas(QiskitTestCase): """Test for canvas.""" def setUp(self): super().setUp() self.style = stylesheet.QiskitTimelineStyle() circ = QuantumCircuit(4) circ.h(0) circ.barrier() circ.cx(0, 2) circ.cx(1, 3) self.circ = transpile( circ, scheduling_method="alap", basis_gates=["h", "cx"], instruction_durations=[("h", 0, 200), ("cx", [0, 2], 1000), ("cx", [1, 3], 1000)], optimization_level=0, ) def test_time_range(self): """Test calculating time range.""" canvas = core.DrawerCanvas(stylesheet=self.style) canvas.formatter = {"margin.left_percent": 0.1, "margin.right_percent": 0.1} canvas.time_range = (0, 100) ref_range = [-10.0, 110.0] self.assertListEqual(list(canvas.time_range), ref_range) def test_load_program(self): """Test loading program.""" canvas = core.DrawerCanvas(stylesheet=self.style) canvas.generator = { "gates": [generators.gen_sched_gate], "bits": [], "barriers": [], "gate_links": [], } canvas.layout = { "bit_arrange": layouts.qreg_creg_ascending, "time_axis_map": layouts.time_map_in_dt, } canvas.load_program(self.circ) canvas.update() drawings_tested = list(canvas.collections) self.assertEqual(len(drawings_tested), 8) ref_coord = { self.circ.qregs[0][0]: -1.0, self.circ.qregs[0][1]: -2.0, self.circ.qregs[0][2]: -3.0, self.circ.qregs[0][3]: -4.0, } self.assertDictEqual(canvas.assigned_coordinates, ref_coord) def test_gate_link_overlap(self): """Test shifting gate link overlap.""" canvas = core.DrawerCanvas(stylesheet=self.style) canvas.formatter.update( { "margin.link_interval_percent": 0.01, "margin.left_percent": 0, "margin.right_percent": 0, } ) canvas.generator = { "gates": [], "bits": [], "barriers": [], "gate_links": [generators.gen_gate_link], } canvas.layout = { "bit_arrange": layouts.qreg_creg_ascending, "time_axis_map": layouts.time_map_in_dt, } canvas.load_program(self.circ) canvas.update() drawings_tested = list(canvas.collections) self.assertEqual(len(drawings_tested), 2) self.assertListEqual(drawings_tested[0][1].xvals, [706.0]) self.assertListEqual(drawings_tested[1][1].xvals, [694.0]) ref_keys = list(canvas._collections.keys()) self.assertEqual(drawings_tested[0][0], ref_keys[0]) self.assertEqual(drawings_tested[1][0], ref_keys[1]) def test_object_outside_xlimit(self): """Test eliminating drawings outside the horizontal limit.""" canvas = core.DrawerCanvas(stylesheet=self.style) canvas.generator = { "gates": [generators.gen_sched_gate], "bits": [generators.gen_bit_name, generators.gen_timeslot], "barriers": [], "gate_links": [], } canvas.layout = { "bit_arrange": layouts.qreg_creg_ascending, "time_axis_map": layouts.time_map_in_dt, } canvas.load_program(self.circ) canvas.set_time_range(t_start=400, t_end=600) canvas.update() drawings_tested = list(canvas.collections) self.assertEqual(len(drawings_tested), 12) def test_non_transpiled_delay_circuit(self): """Test non-transpiled circuit containing instruction which is trivial on duration.""" circ = QuantumCircuit(1) circ.delay(10, 0) canvas = core.DrawerCanvas(stylesheet=self.style) canvas.generator = { "gates": [generators.gen_sched_gate], "bits": [], "barriers": [], "gate_links": [], } with self.assertWarns(DeprecationWarning): canvas.load_program(circ) self.assertEqual(len(canvas._collections), 1) def test_multi_measurement_with_clbit_not_shown(self): """Test generating bit link drawings of measurements when clbits is disabled.""" circ = QuantumCircuit(2, 2) circ.measure(0, 0) circ.measure(1, 1) circ = transpile( circ, scheduling_method="alap", basis_gates=[], instruction_durations=[("measure", 0, 2000), ("measure", 1, 2000)], optimization_level=0, ) canvas = core.DrawerCanvas(stylesheet=self.style) canvas.formatter.update({"control.show_clbits": False}) canvas.layout = { "bit_arrange": layouts.qreg_creg_ascending, "time_axis_map": layouts.time_map_in_dt, } canvas.generator = { "gates": [], "bits": [], "barriers": [], "gate_links": [generators.gen_gate_link], } canvas.load_program(circ) canvas.update() self.assertEqual(len(canvas._output_dataset), 0) def test_multi_measurement_with_clbit_shown(self): """Test generating bit link drawings of measurements when clbits is enabled.""" circ = QuantumCircuit(2, 2) circ.measure(0, 0) circ.measure(1, 1) circ = transpile( circ, scheduling_method="alap", basis_gates=[], instruction_durations=[("measure", 0, 2000), ("measure", 1, 2000)], optimization_level=0, ) canvas = core.DrawerCanvas(stylesheet=self.style) canvas.formatter.update({"control.show_clbits": True}) canvas.layout = { "bit_arrange": layouts.qreg_creg_ascending, "time_axis_map": layouts.time_map_in_dt, } canvas.generator = { "gates": [], "bits": [], "barriers": [], "gate_links": [generators.gen_gate_link], } canvas.load_program(circ) canvas.update() self.assertEqual(len(canvas._output_dataset), 2)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for drawing of timeline drawer.""" import numpy as np import qiskit from qiskit.test import QiskitTestCase from qiskit.visualization.timeline import drawings, types class TestDrawingObjects(QiskitTestCase): """Tests for drawings.""" def setUp(self) -> None: """Setup.""" super().setUp() # bits self.qubits = list(qiskit.QuantumRegister(2)) # metadata self.meta1 = {"val1": 0, "val2": 1} self.meta2 = {"val1": 2, "val2": 3} # style data self.style1 = {"property1": 0, "property2": 1} self.style2 = {"property1": 2, "property2": 3} def test_line_data_equivalent(self): """Test LineData equivalent check.""" xs = list(np.arange(10)) ys = list(np.ones(10)) obj1 = drawings.LineData( data_type=types.LineType.BARRIER, bit=self.qubits[0], xvals=xs, yvals=ys, meta=self.meta1, styles=self.style1, ) obj2 = drawings.LineData( data_type=types.LineType.BARRIER, bit=self.qubits[0], xvals=xs, yvals=ys, meta=self.meta2, styles=self.style2, ) self.assertEqual(obj1, obj2) def test_line_data_equivalent_abstract_coord(self): """Test LineData equivalent check with abstract coordinate.""" xs = [types.AbstractCoordinate.LEFT, types.AbstractCoordinate.RIGHT] ys = [types.AbstractCoordinate.BOTTOM, types.AbstractCoordinate.TOP] obj1 = drawings.LineData( data_type=types.LineType.BARRIER, bit=self.qubits[0], xvals=xs, yvals=ys, meta=self.meta1, styles=self.style1, ) obj2 = drawings.LineData( data_type=types.LineType.BARRIER, bit=self.qubits[0], xvals=xs, yvals=ys, meta=self.meta2, styles=self.style2, ) self.assertEqual(obj1, obj2) def test_box_data_equivalent(self): """Test BoxData equivalent check.""" xs = [0, 1] ys = [0, 1] obj1 = drawings.BoxData( data_type=types.BoxType.SCHED_GATE, bit=self.qubits[0], xvals=xs, yvals=ys, meta=self.meta1, styles=self.style1, ) obj2 = drawings.BoxData( data_type=types.BoxType.SCHED_GATE, bit=self.qubits[0], xvals=xs, yvals=ys, meta=self.meta2, styles=self.style2, ) self.assertEqual(obj1, obj2) def test_box_data_equivalent_abstract_coord(self): """Test BoxData equivalent check with abstract coordinate.""" xs = [types.AbstractCoordinate.LEFT, types.AbstractCoordinate.RIGHT] ys = [types.AbstractCoordinate.BOTTOM, types.AbstractCoordinate.TOP] obj1 = drawings.BoxData( data_type=types.BoxType.SCHED_GATE, bit=self.qubits[0], xvals=xs, yvals=ys, meta=self.meta1, styles=self.style1, ) obj2 = drawings.BoxData( data_type=types.BoxType.SCHED_GATE, bit=self.qubits[0], xvals=xs, yvals=ys, meta=self.meta2, styles=self.style2, ) self.assertEqual(obj1, obj2) def test_text_data_equivalent(self): """Test TextData equivalent check.""" obj1 = drawings.TextData( data_type=types.LabelType.GATE_NAME, bit=self.qubits[0], xval=0, yval=0, text="test", latex="test", meta=self.meta1, styles=self.style1, ) obj2 = drawings.TextData( data_type=types.LabelType.GATE_NAME, bit=self.qubits[0], xval=0, yval=0, text="test", latex="test", meta=self.meta2, styles=self.style2, ) self.assertEqual(obj1, obj2) def test_text_data_equivalent_abstract_coord(self): """Test TextData equivalent check with abstract coordinate.""" obj1 = drawings.TextData( data_type=types.LabelType.GATE_NAME, bit=self.qubits[0], xval=types.AbstractCoordinate.LEFT, yval=types.AbstractCoordinate.BOTTOM, text="test", latex="test", meta=self.meta1, styles=self.style1, ) obj2 = drawings.TextData( data_type=types.LabelType.GATE_NAME, bit=self.qubits[0], xval=types.AbstractCoordinate.LEFT, yval=types.AbstractCoordinate.BOTTOM, text="test", latex="test", meta=self.meta2, styles=self.style2, ) self.assertEqual(obj1, obj2) def test_bit_link_data_equivalent(self): """Test BitLinkData equivalent check.""" obj1 = drawings.GateLinkData( bits=[self.qubits[0], self.qubits[1]], xval=0, styles=self.style1 ) obj2 = drawings.GateLinkData( bits=[self.qubits[0], self.qubits[1]], xval=0, styles=self.style2 ) self.assertEqual(obj1, obj2) def test_bit_link_data_equivalent_abstract_coord(self): """Test BitLinkData equivalent check with abstract coordinate.""" obj1 = drawings.GateLinkData( bits=[self.qubits[0], self.qubits[1]], xval=types.AbstractCoordinate.LEFT, styles=self.style1, ) obj2 = drawings.GateLinkData( bits=[self.qubits[0], self.qubits[1]], xval=types.AbstractCoordinate.LEFT, styles=self.style2, ) self.assertEqual(obj1, obj2)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for core modules of pulse drawer.""" from qiskit import pulse, circuit from qiskit.test import QiskitTestCase from qiskit.visualization.pulse_v2 import events class TestChannelEvents(QiskitTestCase): """Tests for ChannelEvents.""" def test_parse_program(self): """Test typical pulse program.""" test_pulse = pulse.Gaussian(10, 0.1, 3) sched = pulse.Schedule() sched = sched.insert(0, pulse.SetPhase(3.14, pulse.DriveChannel(0))) sched = sched.insert(0, pulse.Play(test_pulse, pulse.DriveChannel(0))) sched = sched.insert(10, pulse.ShiftPhase(-1.57, pulse.DriveChannel(0))) sched = sched.insert(10, pulse.Play(test_pulse, pulse.DriveChannel(0))) ch_events = events.ChannelEvents.load_program(sched, pulse.DriveChannel(0)) # check waveform data waveforms = list(ch_events.get_waveforms()) inst_data0 = waveforms[0] self.assertEqual(inst_data0.t0, 0) self.assertEqual(inst_data0.frame.phase, 3.14) self.assertEqual(inst_data0.frame.freq, 0) self.assertEqual(inst_data0.inst, pulse.Play(test_pulse, pulse.DriveChannel(0))) inst_data1 = waveforms[1] self.assertEqual(inst_data1.t0, 10) self.assertEqual(inst_data1.frame.phase, 1.57) self.assertEqual(inst_data1.frame.freq, 0) self.assertEqual(inst_data1.inst, pulse.Play(test_pulse, pulse.DriveChannel(0))) # check frame data frames = list(ch_events.get_frame_changes()) inst_data0 = frames[0] self.assertEqual(inst_data0.t0, 0) self.assertEqual(inst_data0.frame.phase, 3.14) self.assertEqual(inst_data0.frame.freq, 0) self.assertListEqual(inst_data0.inst, [pulse.SetPhase(3.14, pulse.DriveChannel(0))]) inst_data1 = frames[1] self.assertEqual(inst_data1.t0, 10) self.assertEqual(inst_data1.frame.phase, -1.57) self.assertEqual(inst_data1.frame.freq, 0) self.assertListEqual(inst_data1.inst, [pulse.ShiftPhase(-1.57, pulse.DriveChannel(0))]) def test_multiple_frames_at_the_same_time(self): """Test multiple frame instruction at the same time.""" # shift phase followed by set phase sched = pulse.Schedule() sched = sched.insert(0, pulse.ShiftPhase(-1.57, pulse.DriveChannel(0))) sched = sched.insert(0, pulse.SetPhase(3.14, pulse.DriveChannel(0))) ch_events = events.ChannelEvents.load_program(sched, pulse.DriveChannel(0)) frames = list(ch_events.get_frame_changes()) inst_data0 = frames[0] self.assertAlmostEqual(inst_data0.frame.phase, 3.14) # set phase followed by shift phase sched = pulse.Schedule() sched = sched.insert(0, pulse.SetPhase(3.14, pulse.DriveChannel(0))) sched = sched.insert(0, pulse.ShiftPhase(-1.57, pulse.DriveChannel(0))) ch_events = events.ChannelEvents.load_program(sched, pulse.DriveChannel(0)) frames = list(ch_events.get_frame_changes()) inst_data0 = frames[0] self.assertAlmostEqual(inst_data0.frame.phase, 1.57) def test_frequency(self): """Test parse frequency.""" sched = pulse.Schedule() sched = sched.insert(0, pulse.ShiftFrequency(1.0, pulse.DriveChannel(0))) sched = sched.insert(5, pulse.SetFrequency(5.0, pulse.DriveChannel(0))) ch_events = events.ChannelEvents.load_program(sched, pulse.DriveChannel(0)) ch_events.set_config(dt=0.1, init_frequency=3.0, init_phase=0) frames = list(ch_events.get_frame_changes()) inst_data0 = frames[0] self.assertAlmostEqual(inst_data0.frame.freq, 1.0) inst_data1 = frames[1] self.assertAlmostEqual(inst_data1.frame.freq, 1.0) def test_parameterized_parametric_pulse(self): """Test generating waveforms that are parameterized.""" param = circuit.Parameter("amp") test_waveform = pulse.Play(pulse.Constant(10, param), pulse.DriveChannel(0)) ch_events = events.ChannelEvents( waveforms={0: test_waveform}, frames={}, channel=pulse.DriveChannel(0) ) pulse_inst = list(ch_events.get_waveforms())[0] self.assertTrue(pulse_inst.is_opaque) self.assertEqual(pulse_inst.inst, test_waveform) def test_parameterized_frame_change(self): """Test generating waveforms that are parameterized. Parameterized phase should be ignored when calculating waveform frame. This is due to phase modulated representation of waveforms, i.e. we cannot calculate the phase factor of waveform if the phase is unbound. """ param = circuit.Parameter("phase") test_fc1 = pulse.ShiftPhase(param, pulse.DriveChannel(0)) test_fc2 = pulse.ShiftPhase(1.57, pulse.DriveChannel(0)) test_waveform = pulse.Play(pulse.Constant(10, 0.1), pulse.DriveChannel(0)) ch_events = events.ChannelEvents( waveforms={0: test_waveform}, frames={0: [test_fc1, test_fc2]}, channel=pulse.DriveChannel(0), ) # waveform frame pulse_inst = list(ch_events.get_waveforms())[0] self.assertFalse(pulse_inst.is_opaque) self.assertEqual(pulse_inst.frame.phase, 1.57) # framechange pulse_inst = list(ch_events.get_frame_changes())[0] self.assertTrue(pulse_inst.is_opaque) self.assertEqual(pulse_inst.frame.phase, param + 1.57) def test_zero_duration_delay(self): """Test generating waveforms that contains zero duration delay. Zero duration delay should be ignored. """ ch = pulse.DriveChannel(0) test_sched = pulse.Schedule() test_sched += pulse.Play(pulse.Gaussian(160, 0.1, 40), ch) test_sched += pulse.Delay(0, ch) test_sched += pulse.Play(pulse.Gaussian(160, 0.1, 40), ch) test_sched += pulse.Delay(1, ch) test_sched += pulse.Play(pulse.Gaussian(160, 0.1, 40), ch) ch_events = events.ChannelEvents.load_program(test_sched, ch) self.assertEqual(len(list(ch_events.get_waveforms())), 4)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=invalid-name """Tests for generator of timeline drawer.""" import qiskit from qiskit.test import QiskitTestCase from qiskit.visualization.timeline import generators, types, stylesheet from qiskit.circuit import library, Delay class TestGates(QiskitTestCase): """Tests for generator.gates.""" def setUp(self) -> None: """Setup.""" super().setUp() self.qubit = list(qiskit.QuantumRegister(1))[0] self.u1 = types.ScheduledGate( t0=100, operand=library.U1Gate(0), duration=0, bits=[self.qubit], bit_position=0 ) self.u3 = types.ScheduledGate( t0=100, operand=library.U3Gate(0, 0, 0), duration=20, bits=[self.qubit], bit_position=0 ) self.delay = types.ScheduledGate( t0=100, operand=Delay(20), duration=20, bits=[self.qubit], bit_position=0 ) style = stylesheet.QiskitTimelineStyle() self.formatter = style.formatter def test_gen_sched_gate_with_finite_duration(self): """Test test_gen_sched_gate generator with finite duration gate.""" drawing_obj = generators.gen_sched_gate(self.u3, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.BoxType.SCHED_GATE.value)) self.assertListEqual(list(drawing_obj.xvals), [100, 120]) self.assertListEqual( list(drawing_obj.yvals), [-0.5 * self.formatter["box_height.gate"], 0.5 * self.formatter["box_height.gate"]], ) self.assertListEqual(drawing_obj.bits, [self.qubit]) ref_meta = { "name": "u3", "label": "n/a", "bits": str(self.qubit.register.name), "t0": 100, "duration": 20, "unitary": "[[1.+0.j 0.-0.j]\n [0.+0.j 1.+0.j]]", "parameters": "0, 0, 0", } self.assertDictEqual(ref_meta, drawing_obj.meta) ref_styles = { "zorder": self.formatter["layer.gate"], "facecolor": self.formatter["color.gates"]["u3"], "alpha": self.formatter["alpha.gate"], "linewidth": self.formatter["line_width.gate"], } self.assertDictEqual(ref_styles, drawing_obj.styles) def test_gen_sched_gate_with_zero_duration(self): """Test test_gen_sched_gate generator with zero duration gate.""" drawing_obj = generators.gen_sched_gate(self.u1, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.SymbolType.FRAME.value)) self.assertListEqual(list(drawing_obj.xvals), [100]) self.assertListEqual(list(drawing_obj.yvals), [0]) self.assertListEqual(drawing_obj.bits, [self.qubit]) self.assertEqual(drawing_obj.text, self.formatter["unicode_symbol.frame_change"]) self.assertEqual(drawing_obj.latex, self.formatter["latex_symbol.frame_change"]) ref_styles = { "zorder": self.formatter["layer.frame_change"], "color": self.formatter["color.gates"]["u1"], "size": self.formatter["text_size.frame_change"], "va": "center", "ha": "center", } self.assertDictEqual(ref_styles, drawing_obj.styles) def test_gen_sched_gate_with_delay(self): """Test test_gen_sched_gate generator with delay.""" drawing_obj = generators.gen_sched_gate(self.delay, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.BoxType.DELAY.value)) def test_gen_full_gate_name_with_finite_duration(self): """Test gen_full_gate_name generator with finite duration gate.""" drawing_obj = generators.gen_full_gate_name(self.u3, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value)) self.assertListEqual(list(drawing_obj.xvals), [110.0]) self.assertListEqual(list(drawing_obj.yvals), [0.0]) self.assertListEqual(drawing_obj.bits, [self.qubit]) self.assertEqual(drawing_obj.text, "u3(0.00, 0.00, 0.00)[20]") ref_latex = "{name}(0.00, 0.00, 0.00)[20]".format( name=self.formatter["latex_symbol.gates"]["u3"] ) self.assertEqual(drawing_obj.latex, ref_latex) ref_styles = { "zorder": self.formatter["layer.gate_name"], "color": self.formatter["color.gate_name"], "size": self.formatter["text_size.gate_name"], "va": "center", "ha": "center", } self.assertDictEqual(ref_styles, drawing_obj.styles) def test_gen_full_gate_name_with_zero_duration(self): """Test gen_full_gate_name generator with zero duration gate.""" drawing_obj = generators.gen_full_gate_name(self.u1, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value)) self.assertListEqual(list(drawing_obj.xvals), [100.0]) self.assertListEqual(list(drawing_obj.yvals), [self.formatter["label_offset.frame_change"]]) self.assertListEqual(drawing_obj.bits, [self.qubit]) self.assertEqual(drawing_obj.text, "u1(0.00)") ref_latex = "{name}(0.00)".format(name=self.formatter["latex_symbol.gates"]["u1"]) self.assertEqual(drawing_obj.latex, ref_latex) ref_styles = { "zorder": self.formatter["layer.gate_name"], "color": self.formatter["color.gate_name"], "size": self.formatter["text_size.gate_name"], "va": "bottom", "ha": "center", } self.assertDictEqual(ref_styles, drawing_obj.styles) def test_gen_full_gate_name_with_delay(self): """Test gen_full_gate_name generator with delay.""" drawing_obj = generators.gen_full_gate_name(self.delay, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LabelType.DELAY.value)) def test_gen_short_gate_name_with_finite_duration(self): """Test gen_short_gate_name generator with finite duration gate.""" drawing_obj = generators.gen_short_gate_name(self.u3, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value)) self.assertListEqual(list(drawing_obj.xvals), [110.0]) self.assertListEqual(list(drawing_obj.yvals), [0.0]) self.assertListEqual(drawing_obj.bits, [self.qubit]) self.assertEqual(drawing_obj.text, "u3") ref_latex = "{name}".format(name=self.formatter["latex_symbol.gates"]["u3"]) self.assertEqual(drawing_obj.latex, ref_latex) ref_styles = { "zorder": self.formatter["layer.gate_name"], "color": self.formatter["color.gate_name"], "size": self.formatter["text_size.gate_name"], "va": "center", "ha": "center", } self.assertDictEqual(ref_styles, drawing_obj.styles) def test_gen_short_gate_name_with_zero_duration(self): """Test gen_short_gate_name generator with zero duration gate.""" drawing_obj = generators.gen_short_gate_name(self.u1, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value)) self.assertListEqual(list(drawing_obj.xvals), [100.0]) self.assertListEqual(list(drawing_obj.yvals), [self.formatter["label_offset.frame_change"]]) self.assertListEqual(drawing_obj.bits, [self.qubit]) self.assertEqual(drawing_obj.text, "u1") ref_latex = "{name}".format(name=self.formatter["latex_symbol.gates"]["u1"]) self.assertEqual(drawing_obj.latex, ref_latex) ref_styles = { "zorder": self.formatter["layer.gate_name"], "color": self.formatter["color.gate_name"], "size": self.formatter["text_size.gate_name"], "va": "bottom", "ha": "center", } self.assertDictEqual(ref_styles, drawing_obj.styles) def test_gen_short_gate_name_with_delay(self): """Test gen_short_gate_name generator with delay.""" drawing_obj = generators.gen_short_gate_name(self.delay, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LabelType.DELAY.value)) class TestTimeslot(QiskitTestCase): """Tests for generator.bits.""" def setUp(self) -> None: """Setup.""" super().setUp() self.qubit = list(qiskit.QuantumRegister(1))[0] style = stylesheet.QiskitTimelineStyle() self.formatter = style.formatter def test_gen_timeslot(self): """Test gen_timeslot generator.""" drawing_obj = generators.gen_timeslot(self.qubit, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.BoxType.TIMELINE.value)) self.assertListEqual( list(drawing_obj.xvals), [types.AbstractCoordinate.LEFT, types.AbstractCoordinate.RIGHT] ) self.assertListEqual( list(drawing_obj.yvals), [ -0.5 * self.formatter["box_height.timeslot"], 0.5 * self.formatter["box_height.timeslot"], ], ) self.assertListEqual(drawing_obj.bits, [self.qubit]) ref_styles = { "zorder": self.formatter["layer.timeslot"], "alpha": self.formatter["alpha.timeslot"], "linewidth": self.formatter["line_width.timeslot"], "facecolor": self.formatter["color.timeslot"], } self.assertDictEqual(ref_styles, drawing_obj.styles) def test_gen_bit_name(self): """Test gen_bit_name generator.""" drawing_obj = generators.gen_bit_name(self.qubit, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LabelType.BIT_NAME.value)) self.assertListEqual(list(drawing_obj.xvals), [types.AbstractCoordinate.LEFT]) self.assertListEqual(list(drawing_obj.yvals), [0]) self.assertListEqual(drawing_obj.bits, [self.qubit]) self.assertEqual(drawing_obj.text, str(self.qubit.register.name)) ref_latex = r"{{\rm {register}}}_{{{index}}}".format( register=self.qubit.register.prefix, index=self.qubit.index ) self.assertEqual(drawing_obj.latex, ref_latex) ref_styles = { "zorder": self.formatter["layer.bit_name"], "color": self.formatter["color.bit_name"], "size": self.formatter["text_size.bit_name"], "va": "center", "ha": "right", } self.assertDictEqual(ref_styles, drawing_obj.styles) class TestBarrier(QiskitTestCase): """Tests for generator.barriers.""" def setUp(self) -> None: """Setup.""" super().setUp() self.qubits = list(qiskit.QuantumRegister(3)) self.barrier = types.Barrier(t0=100, bits=self.qubits, bit_position=1) style = stylesheet.QiskitTimelineStyle() self.formatter = style.formatter def test_gen_barrier(self): """Test gen_barrier generator.""" drawing_obj = generators.gen_barrier(self.barrier, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LineType.BARRIER.value)) self.assertListEqual(list(drawing_obj.xvals), [100, 100]) self.assertListEqual(list(drawing_obj.yvals), [-0.5, 0.5]) self.assertListEqual(drawing_obj.bits, [self.qubits[1]]) ref_styles = { "alpha": self.formatter["alpha.barrier"], "zorder": self.formatter["layer.barrier"], "linewidth": self.formatter["line_width.barrier"], "linestyle": self.formatter["line_style.barrier"], "color": self.formatter["color.barrier"], } self.assertDictEqual(ref_styles, drawing_obj.styles) class TestGateLink(QiskitTestCase): """Tests for generator.gate_links.""" def setUp(self) -> None: """Setup.""" super().setUp() self.qubits = list(qiskit.QuantumRegister(2)) self.gate_link = types.GateLink(t0=100, opname="cx", bits=self.qubits) style = stylesheet.QiskitTimelineStyle() self.formatter = style.formatter def gen_bit_link(self): """Test gen_bit_link generator.""" drawing_obj = generators.gen_gate_link(self.gate_link, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LineType.GATE_LINK.value)) self.assertListEqual(list(drawing_obj.xvals), [100]) self.assertListEqual(list(drawing_obj.yvals), [0]) self.assertListEqual(drawing_obj.bits, self.qubits) ref_styles = { "alpha": self.formatter["alpha.bit_link"], "zorder": self.formatter["layer.bit_link"], "linewidth": self.formatter["line_width.bit_link"], "linestyle": self.formatter["line_style.bit_link"], "color": self.formatter["color.gates"]["cx"], } self.assertDictEqual(ref_styles, drawing_obj.styles)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for layouts of timeline drawer.""" import qiskit from qiskit.test import QiskitTestCase from qiskit.visualization.timeline import layouts class TestBitArrange(QiskitTestCase): """Tests for layout.bit_arrange.""" def setUp(self) -> None: """Setup.""" super().setUp() qregs = qiskit.QuantumRegister(3) cregs = qiskit.ClassicalRegister(3) self.regs = list(qregs) + list(cregs) def test_qreg_creg_ascending(self): """Test qreg_creg_ascending layout function.""" sorted_regs = layouts.qreg_creg_ascending(self.regs) ref_regs = [ self.regs[0], self.regs[1], self.regs[2], self.regs[3], self.regs[4], self.regs[5], ] self.assertListEqual(sorted_regs, ref_regs) def test_qreg_creg_descending(self): """Test qreg_creg_descending layout function.""" sorted_regs = layouts.qreg_creg_descending(self.regs) ref_regs = [ self.regs[2], self.regs[1], self.regs[0], self.regs[5], self.regs[4], self.regs[3], ] self.assertListEqual(sorted_regs, ref_regs) class TestAxisMap(QiskitTestCase): """Tests for layout.time_axis_map.""" def test_time_map_in_dt(self): """Test time_map_in_dt layout function.""" axis_config = layouts.time_map_in_dt(time_window=(-100, 500)) self.assertEqual(axis_config.window, (-100, 500)) self.assertEqual(axis_config.label, "System cycle time (dt)") ref_map = {0: "0", 100: "100", 200: "200", 300: "300", 400: "400", 500: "500"} self.assertDictEqual(axis_config.axis_map, ref_map)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for core modules of timeline drawer.""" from qiskit import QuantumCircuit, transpile from qiskit.test import QiskitTestCase from qiskit.visualization.timeline import core, stylesheet, generators, layouts class TestCanvas(QiskitTestCase): """Test for canvas.""" def setUp(self): super().setUp() self.style = stylesheet.QiskitTimelineStyle() circ = QuantumCircuit(4) circ.h(0) circ.barrier() circ.cx(0, 2) circ.cx(1, 3) self.circ = transpile( circ, scheduling_method="alap", basis_gates=["h", "cx"], instruction_durations=[("h", 0, 200), ("cx", [0, 2], 1000), ("cx", [1, 3], 1000)], optimization_level=0, ) def test_time_range(self): """Test calculating time range.""" canvas = core.DrawerCanvas(stylesheet=self.style) canvas.formatter = {"margin.left_percent": 0.1, "margin.right_percent": 0.1} canvas.time_range = (0, 100) ref_range = [-10.0, 110.0] self.assertListEqual(list(canvas.time_range), ref_range) def test_load_program(self): """Test loading program.""" canvas = core.DrawerCanvas(stylesheet=self.style) canvas.generator = { "gates": [generators.gen_sched_gate], "bits": [], "barriers": [], "gate_links": [], } canvas.layout = { "bit_arrange": layouts.qreg_creg_ascending, "time_axis_map": layouts.time_map_in_dt, } canvas.load_program(self.circ) canvas.update() drawings_tested = list(canvas.collections) self.assertEqual(len(drawings_tested), 8) ref_coord = { self.circ.qregs[0][0]: -1.0, self.circ.qregs[0][1]: -2.0, self.circ.qregs[0][2]: -3.0, self.circ.qregs[0][3]: -4.0, } self.assertDictEqual(canvas.assigned_coordinates, ref_coord) def test_gate_link_overlap(self): """Test shifting gate link overlap.""" canvas = core.DrawerCanvas(stylesheet=self.style) canvas.formatter.update( { "margin.link_interval_percent": 0.01, "margin.left_percent": 0, "margin.right_percent": 0, } ) canvas.generator = { "gates": [], "bits": [], "barriers": [], "gate_links": [generators.gen_gate_link], } canvas.layout = { "bit_arrange": layouts.qreg_creg_ascending, "time_axis_map": layouts.time_map_in_dt, } canvas.load_program(self.circ) canvas.update() drawings_tested = list(canvas.collections) self.assertEqual(len(drawings_tested), 2) self.assertListEqual(drawings_tested[0][1].xvals, [706.0]) self.assertListEqual(drawings_tested[1][1].xvals, [694.0]) ref_keys = list(canvas._collections.keys()) self.assertEqual(drawings_tested[0][0], ref_keys[0]) self.assertEqual(drawings_tested[1][0], ref_keys[1]) def test_object_outside_xlimit(self): """Test eliminating drawings outside the horizontal limit.""" canvas = core.DrawerCanvas(stylesheet=self.style) canvas.generator = { "gates": [generators.gen_sched_gate], "bits": [generators.gen_bit_name, generators.gen_timeslot], "barriers": [], "gate_links": [], } canvas.layout = { "bit_arrange": layouts.qreg_creg_ascending, "time_axis_map": layouts.time_map_in_dt, } canvas.load_program(self.circ) canvas.set_time_range(t_start=400, t_end=600) canvas.update() drawings_tested = list(canvas.collections) self.assertEqual(len(drawings_tested), 12) def test_non_transpiled_delay_circuit(self): """Test non-transpiled circuit containing instruction which is trivial on duration.""" circ = QuantumCircuit(1) circ.delay(10, 0) canvas = core.DrawerCanvas(stylesheet=self.style) canvas.generator = { "gates": [generators.gen_sched_gate], "bits": [], "barriers": [], "gate_links": [], } with self.assertWarns(DeprecationWarning): canvas.load_program(circ) self.assertEqual(len(canvas._collections), 1) def test_multi_measurement_with_clbit_not_shown(self): """Test generating bit link drawings of measurements when clbits is disabled.""" circ = QuantumCircuit(2, 2) circ.measure(0, 0) circ.measure(1, 1) circ = transpile( circ, scheduling_method="alap", basis_gates=[], instruction_durations=[("measure", 0, 2000), ("measure", 1, 2000)], optimization_level=0, ) canvas = core.DrawerCanvas(stylesheet=self.style) canvas.formatter.update({"control.show_clbits": False}) canvas.layout = { "bit_arrange": layouts.qreg_creg_ascending, "time_axis_map": layouts.time_map_in_dt, } canvas.generator = { "gates": [], "bits": [], "barriers": [], "gate_links": [generators.gen_gate_link], } canvas.load_program(circ) canvas.update() self.assertEqual(len(canvas._output_dataset), 0) def test_multi_measurement_with_clbit_shown(self): """Test generating bit link drawings of measurements when clbits is enabled.""" circ = QuantumCircuit(2, 2) circ.measure(0, 0) circ.measure(1, 1) circ = transpile( circ, scheduling_method="alap", basis_gates=[], instruction_durations=[("measure", 0, 2000), ("measure", 1, 2000)], optimization_level=0, ) canvas = core.DrawerCanvas(stylesheet=self.style) canvas.formatter.update({"control.show_clbits": True}) canvas.layout = { "bit_arrange": layouts.qreg_creg_ascending, "time_axis_map": layouts.time_map_in_dt, } canvas.generator = { "gates": [], "bits": [], "barriers": [], "gate_links": [generators.gen_gate_link], } canvas.load_program(circ) canvas.update() self.assertEqual(len(canvas._output_dataset), 2)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for drawing of timeline drawer.""" import numpy as np import qiskit from qiskit.test import QiskitTestCase from qiskit.visualization.timeline import drawings, types class TestDrawingObjects(QiskitTestCase): """Tests for drawings.""" def setUp(self) -> None: """Setup.""" super().setUp() # bits self.qubits = list(qiskit.QuantumRegister(2)) # metadata self.meta1 = {"val1": 0, "val2": 1} self.meta2 = {"val1": 2, "val2": 3} # style data self.style1 = {"property1": 0, "property2": 1} self.style2 = {"property1": 2, "property2": 3} def test_line_data_equivalent(self): """Test LineData equivalent check.""" xs = list(np.arange(10)) ys = list(np.ones(10)) obj1 = drawings.LineData( data_type=types.LineType.BARRIER, bit=self.qubits[0], xvals=xs, yvals=ys, meta=self.meta1, styles=self.style1, ) obj2 = drawings.LineData( data_type=types.LineType.BARRIER, bit=self.qubits[0], xvals=xs, yvals=ys, meta=self.meta2, styles=self.style2, ) self.assertEqual(obj1, obj2) def test_line_data_equivalent_abstract_coord(self): """Test LineData equivalent check with abstract coordinate.""" xs = [types.AbstractCoordinate.LEFT, types.AbstractCoordinate.RIGHT] ys = [types.AbstractCoordinate.BOTTOM, types.AbstractCoordinate.TOP] obj1 = drawings.LineData( data_type=types.LineType.BARRIER, bit=self.qubits[0], xvals=xs, yvals=ys, meta=self.meta1, styles=self.style1, ) obj2 = drawings.LineData( data_type=types.LineType.BARRIER, bit=self.qubits[0], xvals=xs, yvals=ys, meta=self.meta2, styles=self.style2, ) self.assertEqual(obj1, obj2) def test_box_data_equivalent(self): """Test BoxData equivalent check.""" xs = [0, 1] ys = [0, 1] obj1 = drawings.BoxData( data_type=types.BoxType.SCHED_GATE, bit=self.qubits[0], xvals=xs, yvals=ys, meta=self.meta1, styles=self.style1, ) obj2 = drawings.BoxData( data_type=types.BoxType.SCHED_GATE, bit=self.qubits[0], xvals=xs, yvals=ys, meta=self.meta2, styles=self.style2, ) self.assertEqual(obj1, obj2) def test_box_data_equivalent_abstract_coord(self): """Test BoxData equivalent check with abstract coordinate.""" xs = [types.AbstractCoordinate.LEFT, types.AbstractCoordinate.RIGHT] ys = [types.AbstractCoordinate.BOTTOM, types.AbstractCoordinate.TOP] obj1 = drawings.BoxData( data_type=types.BoxType.SCHED_GATE, bit=self.qubits[0], xvals=xs, yvals=ys, meta=self.meta1, styles=self.style1, ) obj2 = drawings.BoxData( data_type=types.BoxType.SCHED_GATE, bit=self.qubits[0], xvals=xs, yvals=ys, meta=self.meta2, styles=self.style2, ) self.assertEqual(obj1, obj2) def test_text_data_equivalent(self): """Test TextData equivalent check.""" obj1 = drawings.TextData( data_type=types.LabelType.GATE_NAME, bit=self.qubits[0], xval=0, yval=0, text="test", latex="test", meta=self.meta1, styles=self.style1, ) obj2 = drawings.TextData( data_type=types.LabelType.GATE_NAME, bit=self.qubits[0], xval=0, yval=0, text="test", latex="test", meta=self.meta2, styles=self.style2, ) self.assertEqual(obj1, obj2) def test_text_data_equivalent_abstract_coord(self): """Test TextData equivalent check with abstract coordinate.""" obj1 = drawings.TextData( data_type=types.LabelType.GATE_NAME, bit=self.qubits[0], xval=types.AbstractCoordinate.LEFT, yval=types.AbstractCoordinate.BOTTOM, text="test", latex="test", meta=self.meta1, styles=self.style1, ) obj2 = drawings.TextData( data_type=types.LabelType.GATE_NAME, bit=self.qubits[0], xval=types.AbstractCoordinate.LEFT, yval=types.AbstractCoordinate.BOTTOM, text="test", latex="test", meta=self.meta2, styles=self.style2, ) self.assertEqual(obj1, obj2) def test_bit_link_data_equivalent(self): """Test BitLinkData equivalent check.""" obj1 = drawings.GateLinkData( bits=[self.qubits[0], self.qubits[1]], xval=0, styles=self.style1 ) obj2 = drawings.GateLinkData( bits=[self.qubits[0], self.qubits[1]], xval=0, styles=self.style2 ) self.assertEqual(obj1, obj2) def test_bit_link_data_equivalent_abstract_coord(self): """Test BitLinkData equivalent check with abstract coordinate.""" obj1 = drawings.GateLinkData( bits=[self.qubits[0], self.qubits[1]], xval=types.AbstractCoordinate.LEFT, styles=self.style1, ) obj2 = drawings.GateLinkData( bits=[self.qubits[0], self.qubits[1]], xval=types.AbstractCoordinate.LEFT, styles=self.style2, ) self.assertEqual(obj1, obj2)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=invalid-name """Tests for generator of timeline drawer.""" import qiskit from qiskit.test import QiskitTestCase from qiskit.visualization.timeline import generators, types, stylesheet from qiskit.circuit import library, Delay class TestGates(QiskitTestCase): """Tests for generator.gates.""" def setUp(self) -> None: """Setup.""" super().setUp() self.qubit = list(qiskit.QuantumRegister(1))[0] self.u1 = types.ScheduledGate( t0=100, operand=library.U1Gate(0), duration=0, bits=[self.qubit], bit_position=0 ) self.u3 = types.ScheduledGate( t0=100, operand=library.U3Gate(0, 0, 0), duration=20, bits=[self.qubit], bit_position=0 ) self.delay = types.ScheduledGate( t0=100, operand=Delay(20), duration=20, bits=[self.qubit], bit_position=0 ) style = stylesheet.QiskitTimelineStyle() self.formatter = style.formatter def test_gen_sched_gate_with_finite_duration(self): """Test test_gen_sched_gate generator with finite duration gate.""" drawing_obj = generators.gen_sched_gate(self.u3, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.BoxType.SCHED_GATE.value)) self.assertListEqual(list(drawing_obj.xvals), [100, 120]) self.assertListEqual( list(drawing_obj.yvals), [-0.5 * self.formatter["box_height.gate"], 0.5 * self.formatter["box_height.gate"]], ) self.assertListEqual(drawing_obj.bits, [self.qubit]) ref_meta = { "name": "u3", "label": "n/a", "bits": str(self.qubit.register.name), "t0": 100, "duration": 20, "unitary": "[[1.+0.j 0.-0.j]\n [0.+0.j 1.+0.j]]", "parameters": "0, 0, 0", } self.assertDictEqual(ref_meta, drawing_obj.meta) ref_styles = { "zorder": self.formatter["layer.gate"], "facecolor": self.formatter["color.gates"]["u3"], "alpha": self.formatter["alpha.gate"], "linewidth": self.formatter["line_width.gate"], } self.assertDictEqual(ref_styles, drawing_obj.styles) def test_gen_sched_gate_with_zero_duration(self): """Test test_gen_sched_gate generator with zero duration gate.""" drawing_obj = generators.gen_sched_gate(self.u1, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.SymbolType.FRAME.value)) self.assertListEqual(list(drawing_obj.xvals), [100]) self.assertListEqual(list(drawing_obj.yvals), [0]) self.assertListEqual(drawing_obj.bits, [self.qubit]) self.assertEqual(drawing_obj.text, self.formatter["unicode_symbol.frame_change"]) self.assertEqual(drawing_obj.latex, self.formatter["latex_symbol.frame_change"]) ref_styles = { "zorder": self.formatter["layer.frame_change"], "color": self.formatter["color.gates"]["u1"], "size": self.formatter["text_size.frame_change"], "va": "center", "ha": "center", } self.assertDictEqual(ref_styles, drawing_obj.styles) def test_gen_sched_gate_with_delay(self): """Test test_gen_sched_gate generator with delay.""" drawing_obj = generators.gen_sched_gate(self.delay, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.BoxType.DELAY.value)) def test_gen_full_gate_name_with_finite_duration(self): """Test gen_full_gate_name generator with finite duration gate.""" drawing_obj = generators.gen_full_gate_name(self.u3, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value)) self.assertListEqual(list(drawing_obj.xvals), [110.0]) self.assertListEqual(list(drawing_obj.yvals), [0.0]) self.assertListEqual(drawing_obj.bits, [self.qubit]) self.assertEqual(drawing_obj.text, "u3(0.00, 0.00, 0.00)[20]") ref_latex = "{name}(0.00, 0.00, 0.00)[20]".format( name=self.formatter["latex_symbol.gates"]["u3"] ) self.assertEqual(drawing_obj.latex, ref_latex) ref_styles = { "zorder": self.formatter["layer.gate_name"], "color": self.formatter["color.gate_name"], "size": self.formatter["text_size.gate_name"], "va": "center", "ha": "center", } self.assertDictEqual(ref_styles, drawing_obj.styles) def test_gen_full_gate_name_with_zero_duration(self): """Test gen_full_gate_name generator with zero duration gate.""" drawing_obj = generators.gen_full_gate_name(self.u1, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value)) self.assertListEqual(list(drawing_obj.xvals), [100.0]) self.assertListEqual(list(drawing_obj.yvals), [self.formatter["label_offset.frame_change"]]) self.assertListEqual(drawing_obj.bits, [self.qubit]) self.assertEqual(drawing_obj.text, "u1(0.00)") ref_latex = "{name}(0.00)".format(name=self.formatter["latex_symbol.gates"]["u1"]) self.assertEqual(drawing_obj.latex, ref_latex) ref_styles = { "zorder": self.formatter["layer.gate_name"], "color": self.formatter["color.gate_name"], "size": self.formatter["text_size.gate_name"], "va": "bottom", "ha": "center", } self.assertDictEqual(ref_styles, drawing_obj.styles) def test_gen_full_gate_name_with_delay(self): """Test gen_full_gate_name generator with delay.""" drawing_obj = generators.gen_full_gate_name(self.delay, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LabelType.DELAY.value)) def test_gen_short_gate_name_with_finite_duration(self): """Test gen_short_gate_name generator with finite duration gate.""" drawing_obj = generators.gen_short_gate_name(self.u3, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value)) self.assertListEqual(list(drawing_obj.xvals), [110.0]) self.assertListEqual(list(drawing_obj.yvals), [0.0]) self.assertListEqual(drawing_obj.bits, [self.qubit]) self.assertEqual(drawing_obj.text, "u3") ref_latex = "{name}".format(name=self.formatter["latex_symbol.gates"]["u3"]) self.assertEqual(drawing_obj.latex, ref_latex) ref_styles = { "zorder": self.formatter["layer.gate_name"], "color": self.formatter["color.gate_name"], "size": self.formatter["text_size.gate_name"], "va": "center", "ha": "center", } self.assertDictEqual(ref_styles, drawing_obj.styles) def test_gen_short_gate_name_with_zero_duration(self): """Test gen_short_gate_name generator with zero duration gate.""" drawing_obj = generators.gen_short_gate_name(self.u1, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value)) self.assertListEqual(list(drawing_obj.xvals), [100.0]) self.assertListEqual(list(drawing_obj.yvals), [self.formatter["label_offset.frame_change"]]) self.assertListEqual(drawing_obj.bits, [self.qubit]) self.assertEqual(drawing_obj.text, "u1") ref_latex = "{name}".format(name=self.formatter["latex_symbol.gates"]["u1"]) self.assertEqual(drawing_obj.latex, ref_latex) ref_styles = { "zorder": self.formatter["layer.gate_name"], "color": self.formatter["color.gate_name"], "size": self.formatter["text_size.gate_name"], "va": "bottom", "ha": "center", } self.assertDictEqual(ref_styles, drawing_obj.styles) def test_gen_short_gate_name_with_delay(self): """Test gen_short_gate_name generator with delay.""" drawing_obj = generators.gen_short_gate_name(self.delay, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LabelType.DELAY.value)) class TestTimeslot(QiskitTestCase): """Tests for generator.bits.""" def setUp(self) -> None: """Setup.""" super().setUp() self.qubit = list(qiskit.QuantumRegister(1))[0] style = stylesheet.QiskitTimelineStyle() self.formatter = style.formatter def test_gen_timeslot(self): """Test gen_timeslot generator.""" drawing_obj = generators.gen_timeslot(self.qubit, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.BoxType.TIMELINE.value)) self.assertListEqual( list(drawing_obj.xvals), [types.AbstractCoordinate.LEFT, types.AbstractCoordinate.RIGHT] ) self.assertListEqual( list(drawing_obj.yvals), [ -0.5 * self.formatter["box_height.timeslot"], 0.5 * self.formatter["box_height.timeslot"], ], ) self.assertListEqual(drawing_obj.bits, [self.qubit]) ref_styles = { "zorder": self.formatter["layer.timeslot"], "alpha": self.formatter["alpha.timeslot"], "linewidth": self.formatter["line_width.timeslot"], "facecolor": self.formatter["color.timeslot"], } self.assertDictEqual(ref_styles, drawing_obj.styles) def test_gen_bit_name(self): """Test gen_bit_name generator.""" drawing_obj = generators.gen_bit_name(self.qubit, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LabelType.BIT_NAME.value)) self.assertListEqual(list(drawing_obj.xvals), [types.AbstractCoordinate.LEFT]) self.assertListEqual(list(drawing_obj.yvals), [0]) self.assertListEqual(drawing_obj.bits, [self.qubit]) self.assertEqual(drawing_obj.text, str(self.qubit.register.name)) ref_latex = r"{{\rm {register}}}_{{{index}}}".format( register=self.qubit.register.prefix, index=self.qubit.index ) self.assertEqual(drawing_obj.latex, ref_latex) ref_styles = { "zorder": self.formatter["layer.bit_name"], "color": self.formatter["color.bit_name"], "size": self.formatter["text_size.bit_name"], "va": "center", "ha": "right", } self.assertDictEqual(ref_styles, drawing_obj.styles) class TestBarrier(QiskitTestCase): """Tests for generator.barriers.""" def setUp(self) -> None: """Setup.""" super().setUp() self.qubits = list(qiskit.QuantumRegister(3)) self.barrier = types.Barrier(t0=100, bits=self.qubits, bit_position=1) style = stylesheet.QiskitTimelineStyle() self.formatter = style.formatter def test_gen_barrier(self): """Test gen_barrier generator.""" drawing_obj = generators.gen_barrier(self.barrier, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LineType.BARRIER.value)) self.assertListEqual(list(drawing_obj.xvals), [100, 100]) self.assertListEqual(list(drawing_obj.yvals), [-0.5, 0.5]) self.assertListEqual(drawing_obj.bits, [self.qubits[1]]) ref_styles = { "alpha": self.formatter["alpha.barrier"], "zorder": self.formatter["layer.barrier"], "linewidth": self.formatter["line_width.barrier"], "linestyle": self.formatter["line_style.barrier"], "color": self.formatter["color.barrier"], } self.assertDictEqual(ref_styles, drawing_obj.styles) class TestGateLink(QiskitTestCase): """Tests for generator.gate_links.""" def setUp(self) -> None: """Setup.""" super().setUp() self.qubits = list(qiskit.QuantumRegister(2)) self.gate_link = types.GateLink(t0=100, opname="cx", bits=self.qubits) style = stylesheet.QiskitTimelineStyle() self.formatter = style.formatter def gen_bit_link(self): """Test gen_bit_link generator.""" drawing_obj = generators.gen_gate_link(self.gate_link, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LineType.GATE_LINK.value)) self.assertListEqual(list(drawing_obj.xvals), [100]) self.assertListEqual(list(drawing_obj.yvals), [0]) self.assertListEqual(drawing_obj.bits, self.qubits) ref_styles = { "alpha": self.formatter["alpha.bit_link"], "zorder": self.formatter["layer.bit_link"], "linewidth": self.formatter["line_width.bit_link"], "linestyle": self.formatter["line_style.bit_link"], "color": self.formatter["color.gates"]["cx"], } self.assertDictEqual(ref_styles, drawing_obj.styles)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for layouts of timeline drawer.""" import qiskit from qiskit.test import QiskitTestCase from qiskit.visualization.timeline import layouts class TestBitArrange(QiskitTestCase): """Tests for layout.bit_arrange.""" def setUp(self) -> None: """Setup.""" super().setUp() qregs = qiskit.QuantumRegister(3) cregs = qiskit.ClassicalRegister(3) self.regs = list(qregs) + list(cregs) def test_qreg_creg_ascending(self): """Test qreg_creg_ascending layout function.""" sorted_regs = layouts.qreg_creg_ascending(self.regs) ref_regs = [ self.regs[0], self.regs[1], self.regs[2], self.regs[3], self.regs[4], self.regs[5], ] self.assertListEqual(sorted_regs, ref_regs) def test_qreg_creg_descending(self): """Test qreg_creg_descending layout function.""" sorted_regs = layouts.qreg_creg_descending(self.regs) ref_regs = [ self.regs[2], self.regs[1], self.regs[0], self.regs[5], self.regs[4], self.regs[3], ] self.assertListEqual(sorted_regs, ref_regs) class TestAxisMap(QiskitTestCase): """Tests for layout.time_axis_map.""" def test_time_map_in_dt(self): """Test time_map_in_dt layout function.""" axis_config = layouts.time_map_in_dt(time_window=(-100, 500)) self.assertEqual(axis_config.window, (-100, 500)) self.assertEqual(axis_config.label, "System cycle time (dt)") ref_map = {0: "0", 100: "100", 200: "200", 300: "300", 400: "400", 500: "500"} self.assertDictEqual(axis_config.axis_map, ref_map)
https://github.com/swe-train/qiskit__qiskit
swe-train
#!/usr/bin/env python3 # This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test cases to verify qpy backwards compatibility.""" import argparse import itertools import random import re import sys import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.circuit.classicalregister import Clbit from qiskit.circuit.quantumregister import Qubit from qiskit.circuit.parameter import Parameter from qiskit.circuit.parametervector import ParameterVector from qiskit.quantum_info.random import random_unitary from qiskit.circuit.library import U1Gate, U2Gate, U3Gate, QFT, DCXGate, PauliGate from qiskit.circuit.gate import Gate try: from qiskit.qpy import dump, load except ModuleNotFoundError: from qiskit.circuit.qpy_serialization import dump, load # This version pattern is taken from the pypa packaging project: # https://github.com/pypa/packaging/blob/21.3/packaging/version.py#L223-L254 # which is dual licensed Apache 2.0 and BSD see the source for the original # authors and other details VERSION_PATTERN = ( "^" + r""" v? (?: (?:(?P<epoch>[0-9]+)!)? # epoch (?P<release>[0-9]+(?:\.[0-9]+)*) # release segment (?P<pre> # pre-release [-_\.]? (?P<pre_l>(a|b|c|rc|alpha|beta|pre|preview)) [-_\.]? (?P<pre_n>[0-9]+)? )? (?P<post> # post release (?:-(?P<post_n1>[0-9]+)) | (?: [-_\.]? (?P<post_l>post|rev|r) [-_\.]? (?P<post_n2>[0-9]+)? ) )? (?P<dev> # dev release [-_\.]? (?P<dev_l>dev) [-_\.]? (?P<dev_n>[0-9]+)? )? ) (?:\+(?P<local>[a-z0-9]+(?:[-_\.][a-z0-9]+)*))? # local version """ + "$" ) def generate_full_circuit(): """Generate a multiregister circuit with name, metadata, phase.""" qr_a = QuantumRegister(4, "a") qr_b = QuantumRegister(4, "b") cr_c = ClassicalRegister(4, "c") cr_d = ClassicalRegister(4, "d") full_circuit = QuantumCircuit( qr_a, qr_b, cr_c, cr_d, name="MyCircuit", metadata={"test": 1, "a": 2}, global_phase=3.14159, ) full_circuit.h(qr_a) full_circuit.cx(qr_a, qr_b) full_circuit.barrier(qr_a) full_circuit.barrier(qr_b) full_circuit.measure(qr_a, cr_c) full_circuit.measure(qr_b, cr_d) return full_circuit def generate_unitary_gate_circuit(): """Generate a circuit with a unitary gate.""" unitary_circuit = QuantumCircuit(5, name="unitary_circuit") unitary_circuit.unitary(random_unitary(32, seed=100), [0, 1, 2, 3, 4]) unitary_circuit.measure_all() return unitary_circuit def generate_random_circuits(): """Generate multiple random circuits.""" random_circuits = [] for i in range(1, 15): qc = QuantumCircuit(i, name=f"random_circuit-{i}") qc.h(0) if i > 1: for j in range(i - 1): qc.cx(0, j + 1) qc.measure_all() for j in range(i): qc.reset(j) qc.x(0).c_if(qc.cregs[0], i) for j in range(i): qc.measure(j, j) random_circuits.append(qc) return random_circuits def generate_string_parameters(): """Generate a circuit for the XYZ pauli string.""" op_circuit = QuantumCircuit(3, name="X^Y^Z") op_circuit.append(PauliGate("XYZ"), op_circuit.qubits, []) return op_circuit def generate_register_edge_cases(): """Generate register edge case circuits.""" register_edge_cases = [] # Circuit with shared bits in a register qubits = [Qubit() for _ in range(5)] shared_qc = QuantumCircuit(name="shared_bits") shared_qc.add_bits(qubits) shared_qr = QuantumRegister(bits=qubits) shared_qc.add_register(shared_qr) shared_qc.h(shared_qr) shared_qc.cx(0, 1) shared_qc.cx(0, 2) shared_qc.cx(0, 3) shared_qc.cx(0, 4) shared_qc.measure_all() register_edge_cases.append(shared_qc) # Circuit with registers that have a mix of standalone and shared register # bits qr = QuantumRegister(5, "foo") qr = QuantumRegister(name="bar", bits=qr[:3] + [Qubit(), Qubit()]) cr = ClassicalRegister(5, "foo") cr = ClassicalRegister(name="classical_bar", bits=cr[:3] + [Clbit(), Clbit()]) hybrid_qc = QuantumCircuit(qr, cr, name="mix_standalone_bits_registers") hybrid_qc.h(0) hybrid_qc.cx(0, 1) hybrid_qc.cx(0, 2) hybrid_qc.cx(0, 3) hybrid_qc.cx(0, 4) hybrid_qc.measure(qr, cr) register_edge_cases.append(hybrid_qc) # Circuit with mixed standalone and shared registers qubits = [Qubit() for _ in range(5)] clbits = [Clbit() for _ in range(5)] mixed_qc = QuantumCircuit(name="mix_standalone_bits_with_registers") mixed_qc.add_bits(qubits) mixed_qc.add_bits(clbits) qr = QuantumRegister(bits=qubits) cr = ClassicalRegister(bits=clbits) mixed_qc.add_register(qr) mixed_qc.add_register(cr) qr_standalone = QuantumRegister(2, "standalone") mixed_qc.add_register(qr_standalone) cr_standalone = ClassicalRegister(2, "classical_standalone") mixed_qc.add_register(cr_standalone) mixed_qc.unitary(random_unitary(32, seed=42), qr) mixed_qc.unitary(random_unitary(4, seed=100), qr_standalone) mixed_qc.measure(qr, cr) mixed_qc.measure(qr_standalone, cr_standalone) register_edge_cases.append(mixed_qc) # Circuit with out of order register bits qr_standalone = QuantumRegister(2, "standalone") qubits = [Qubit() for _ in range(5)] clbits = [Clbit() for _ in range(5)] ooo_qc = QuantumCircuit(name="out_of_order_bits") ooo_qc.add_bits(qubits) ooo_qc.add_bits(clbits) random.seed(42) random.shuffle(qubits) random.shuffle(clbits) qr = QuantumRegister(bits=qubits) cr = ClassicalRegister(bits=clbits) ooo_qc.add_register(qr) ooo_qc.add_register(cr) qr_standalone = QuantumRegister(2, "standalone") cr_standalone = ClassicalRegister(2, "classical_standalone") ooo_qc.add_bits([qr_standalone[1], qr_standalone[0]]) ooo_qc.add_bits([cr_standalone[1], cr_standalone[0]]) ooo_qc.add_register(qr_standalone) ooo_qc.add_register(cr_standalone) ooo_qc.unitary(random_unitary(32, seed=42), qr) ooo_qc.unitary(random_unitary(4, seed=100), qr_standalone) ooo_qc.measure(qr, cr) ooo_qc.measure(qr_standalone, cr_standalone) register_edge_cases.append(ooo_qc) return register_edge_cases def generate_parameterized_circuit(): """Generate a circuit with parameters and parameter expressions.""" param_circuit = QuantumCircuit(1, name="parameterized") theta = Parameter("theta") lam = Parameter("Ξ»") theta_pi = 3.14159 * theta pe = theta_pi / lam param_circuit.append(U3Gate(theta, theta_pi, lam), [0]) param_circuit.append(U1Gate(pe), [0]) param_circuit.append(U2Gate(theta_pi, lam), [0]) return param_circuit def generate_qft_circuit(): """Generate a QFT circuit with initialization.""" k = 5 state = (1 / np.sqrt(8)) * np.array( [ np.exp(-1j * 2 * np.pi * k * (0) / 8), np.exp(-1j * 2 * np.pi * k * (1) / 8), np.exp(-1j * 2 * np.pi * k * (2) / 8), np.exp(-1j * 2 * np.pi * k * 3 / 8), np.exp(-1j * 2 * np.pi * k * 4 / 8), np.exp(-1j * 2 * np.pi * k * 5 / 8), np.exp(-1j * 2 * np.pi * k * 6 / 8), np.exp(-1j * 2 * np.pi * k * 7 / 8), ] ) qubits = 3 qft_circ = QuantumCircuit(qubits, qubits, name="QFT") qft_circ.initialize(state) qft_circ.append(QFT(qubits), range(qubits)) qft_circ.measure(range(qubits), range(qubits)) return qft_circ def generate_param_phase(): """Generate circuits with parameterize global phase.""" output_circuits = [] # Generate circuit with ParameterExpression global phase theta = Parameter("theta") phi = Parameter("phi") sum_param = theta + phi qc = QuantumCircuit(5, 1, global_phase=sum_param, name="parameter_phase") qc.h(0) for i in range(4): qc.cx(i, i + 1) qc.barrier() qc.rz(sum_param, range(3)) qc.rz(phi, 3) qc.rz(theta, 4) qc.barrier() for i in reversed(range(4)): qc.cx(i, i + 1) qc.h(0) qc.measure(0, 0) output_circuits.append(qc) # Generate circuit with Parameter global phase theta = Parameter("theta") bell_qc = QuantumCircuit(2, global_phase=theta, name="bell_param_global_phase") bell_qc.h(0) bell_qc.cx(0, 1) bell_qc.measure_all() output_circuits.append(bell_qc) return output_circuits def generate_single_clbit_condition_teleportation(): # pylint: disable=invalid-name """Generate single clbit condition teleportation circuit.""" qr = QuantumRegister(1) cr = ClassicalRegister(2, name="name") teleport_qc = QuantumCircuit(qr, cr, name="Reset Test") teleport_qc.x(0) teleport_qc.measure(0, cr[0]) teleport_qc.x(0).c_if(cr[0], 1) teleport_qc.measure(0, cr[1]) return teleport_qc def generate_parameter_vector(): """Generate tests for parameter vector element ordering.""" qc = QuantumCircuit(11, name="parameter_vector") input_params = ParameterVector("x_par", 11) user_params = ParameterVector("ΞΈ_par", 11) for i, param in enumerate(user_params): qc.ry(param, i) for i, param in enumerate(input_params): qc.rz(param, i) return qc def generate_parameter_vector_expression(): # pylint: disable=invalid-name """Generate tests for parameter vector element ordering.""" qc = QuantumCircuit(7, name="vector_expansion") entanglement = [[i, i + 1] for i in range(7 - 1)] input_params = ParameterVector("x_par", 14) user_params = ParameterVector("\u03B8_par", 1) for i in range(qc.num_qubits): qc.ry(user_params[0], qc.qubits[i]) for source, target in entanglement: qc.cz(qc.qubits[source], qc.qubits[target]) for i in range(qc.num_qubits): qc.rz(-2 * input_params[2 * i + 1], qc.qubits[i]) qc.rx(-2 * input_params[2 * i], qc.qubits[i]) return qc def generate_evolution_gate(): """Generate a circuit with a pauli evolution gate.""" # Runtime import since this only exists in terra 0.19.0 from qiskit.circuit.library import PauliEvolutionGate from qiskit.synthesis import SuzukiTrotter from qiskit.quantum_info import SparsePauliOp synthesis = SuzukiTrotter() op = SparsePauliOp.from_list([("ZI", 1), ("IZ", 1)]) evo = PauliEvolutionGate([op] * 5, time=2.0, synthesis=synthesis) qc = QuantumCircuit(2, name="pauli_evolution_circuit") qc.append(evo, range(2)) return qc def generate_control_flow_circuits(): """Test qpy serialization with control flow instructions.""" from qiskit.circuit.controlflow import WhileLoopOp, IfElseOp, ForLoopOp # If instruction circuits = [] qc = QuantumCircuit(2, 2, name="control_flow") qc.h(0) qc.measure(0, 0) true_body = QuantumCircuit(1) true_body.x(0) if_op = IfElseOp((qc.clbits[0], True), true_body=true_body) qc.append(if_op, [1]) qc.measure(1, 1) circuits.append(qc) # If else instruction qc = QuantumCircuit(2, 2, name="if_else") qc.h(0) qc.measure(0, 0) false_body = QuantumCircuit(1) false_body.y(0) if_else_op = IfElseOp((qc.clbits[0], True), true_body, false_body) qc.append(if_else_op, [1]) qc.measure(1, 1) circuits.append(qc) # While loop qc = QuantumCircuit(2, 1, name="while_loop") block = QuantumCircuit(2, 1) block.h(0) block.cx(0, 1) block.measure(0, 0) while_loop = WhileLoopOp((qc.clbits[0], 0), block) qc.append(while_loop, [0, 1], [0]) circuits.append(qc) # for loop range qc = QuantumCircuit(2, 1, name="for_loop") body = QuantumCircuit(2, 1) body.h(0) body.cx(0, 1) body.measure(0, 0) body.break_loop().c_if(0, True) for_loop_op = ForLoopOp(range(5), None, body=body) qc.append(for_loop_op, [0, 1], [0]) circuits.append(qc) # For loop iterator qc = QuantumCircuit(2, 1, name="for_loop_iterator") for_loop_op = ForLoopOp(iter(range(5)), None, body=body) qc.append(for_loop_op, [0, 1], [0]) circuits.append(qc) return circuits def generate_control_flow_switch_circuits(): """Generate circuits with switch-statement instructions.""" from qiskit.circuit.controlflow import CASE_DEFAULT circuits = [] qc = QuantumCircuit(2, 1, name="switch_clbit") case_t = qc.copy_empty_like() case_t.x(0) case_f = qc.copy_empty_like() case_f.z(1) qc.switch(qc.clbits[0], [(True, case_t), (False, case_f)], qc.qubits, qc.clbits) circuits.append(qc) qreg = QuantumRegister(2, "q") creg = ClassicalRegister(3, "c") qc = QuantumCircuit(qreg, creg, name="switch_creg") case_0 = QuantumCircuit(qreg, creg) case_0.x(0) case_1 = QuantumCircuit(qreg, creg) case_1.z(1) case_2 = QuantumCircuit(qreg, creg) case_2.x(1) qc.switch( creg, [(0, case_0), ((1, 2), case_1), ((3, 4, CASE_DEFAULT), case_2)], qc.qubits, qc.clbits ) circuits.append(qc) return circuits def generate_schedule_blocks(): """Standard QPY testcase for schedule blocks.""" from qiskit.pulse import builder, channels, library from qiskit.utils import optionals # Parameterized schedule test is avoided. # Generated reference and loaded QPY object may induce parameter uuid mismatch. # As workaround, we need test with bounded parameters, however, schedule.parameters # are returned as Set and thus its order is random. # Since schedule parameters are validated, we cannot assign random numbers. # We need to upgrade testing framework. schedule_blocks = [] # Instructions without parameters with builder.build() as block: with builder.align_sequential(): builder.set_frequency(5e9, channels.DriveChannel(0)) builder.shift_frequency(10e6, channels.DriveChannel(1)) builder.set_phase(1.57, channels.DriveChannel(0)) builder.shift_phase(0.1, channels.DriveChannel(1)) builder.barrier(channels.DriveChannel(0), channels.DriveChannel(1)) builder.play(library.Gaussian(160, 0.1j, 40), channels.DriveChannel(0)) builder.play(library.GaussianSquare(800, 0.1, 64, 544), channels.ControlChannel(0)) builder.play(library.Drag(160, 0.1, 40, 1.5), channels.DriveChannel(1)) builder.play(library.Constant(800, 0.1), channels.MeasureChannel(0)) builder.acquire(1000, channels.AcquireChannel(0), channels.MemorySlot(0)) schedule_blocks.append(block) # Raw symbolic pulse if optionals.HAS_SYMENGINE: import symengine as sym else: import sympy as sym duration, amp, t = sym.symbols("duration amp t") # pylint: disable=invalid-name expr = amp * sym.sin(2 * sym.pi * t / duration) my_pulse = library.SymbolicPulse( pulse_type="Sinusoidal", duration=100, parameters={"amp": 0.1}, envelope=expr, valid_amp_conditions=sym.Abs(amp) <= 1.0, ) with builder.build() as block: builder.play(my_pulse, channels.DriveChannel(0)) schedule_blocks.append(block) # Raw waveform my_waveform = 0.1 * np.sin(2 * np.pi * np.linspace(0, 1, 100)) with builder.build() as block: builder.play(my_waveform, channels.DriveChannel(0)) schedule_blocks.append(block) return schedule_blocks def generate_referenced_schedule(): """Test for QPY serialization of unassigned reference schedules.""" from qiskit.pulse import builder, channels, library schedule_blocks = [] # Completely unassigned schedule with builder.build() as block: builder.reference("cr45p", "q0", "q1") builder.reference("x", "q0") builder.reference("cr45m", "q0", "q1") schedule_blocks.append(block) # Partly assigned schedule with builder.build() as x_q0: builder.play(library.Constant(100, 0.1), channels.DriveChannel(0)) with builder.build() as block: builder.reference("cr45p", "q0", "q1") builder.call(x_q0) builder.reference("cr45m", "q0", "q1") schedule_blocks.append(block) return schedule_blocks def generate_calibrated_circuits(): """Test for QPY serialization with calibrations.""" from qiskit.pulse import builder, Constant, DriveChannel circuits = [] # custom gate mygate = Gate("mygate", 1, []) qc = QuantumCircuit(1, name="calibrated_circuit_1") qc.append(mygate, [0]) with builder.build() as caldef: builder.play(Constant(100, 0.1), DriveChannel(0)) qc.add_calibration(mygate, (0,), caldef) circuits.append(qc) # override instruction qc = QuantumCircuit(1, name="calibrated_circuit_2") qc.x(0) with builder.build() as caldef: builder.play(Constant(100, 0.1), DriveChannel(0)) qc.add_calibration("x", (0,), caldef) circuits.append(qc) return circuits def generate_controlled_gates(): """Test QPY serialization with custom ControlledGates.""" circuits = [] qc = QuantumCircuit(3, name="custom_controlled_gates") controlled_gate = DCXGate().control(1) qc.append(controlled_gate, [0, 1, 2]) circuits.append(qc) custom_gate = Gate("black_box", 1, []) custom_definition = QuantumCircuit(1) custom_definition.h(0) custom_definition.rz(1.5, 0) custom_definition.sdg(0) custom_gate.definition = custom_definition nested_qc = QuantumCircuit(3, name="nested_qc") qc.append(custom_gate, [0]) controlled_gate = custom_gate.control(2) nested_qc.append(controlled_gate, [0, 1, 2]) nested_qc.measure_all() circuits.append(nested_qc) qc_open = QuantumCircuit(2, name="open_cx") qc_open.cx(0, 1, ctrl_state=0) circuits.append(qc_open) return circuits def generate_open_controlled_gates(): """Test QPY serialization with custom ControlledGates with open controls.""" circuits = [] qc = QuantumCircuit(3, name="open_controls_simple") controlled_gate = DCXGate().control(1, ctrl_state=0) qc.append(controlled_gate, [0, 1, 2]) circuits.append(qc) custom_gate = Gate("black_box", 1, []) custom_definition = QuantumCircuit(1) custom_definition.h(0) custom_definition.rz(1.5, 0) custom_definition.sdg(0) custom_gate.definition = custom_definition nested_qc = QuantumCircuit(3, name="open_controls_nested") nested_qc.append(custom_gate, [0]) controlled_gate = custom_gate.control(2, ctrl_state=1) nested_qc.append(controlled_gate, [0, 1, 2]) nested_qc.measure_all() circuits.append(nested_qc) return circuits def generate_acquire_instruction_with_kernel_and_discriminator(): """Test QPY serialization with Acquire instruction with kernel and discriminator.""" from qiskit.pulse import builder, AcquireChannel, MemorySlot, Discriminator, Kernel schedule_blocks = [] with builder.build() as block: builder.acquire( 100, AcquireChannel(0), MemorySlot(0), kernel=Kernel( name="my_kernel", my_params_1={"param1": 0.1, "param2": 0.2}, my_params_2=[0, 1] ), ) schedule_blocks.append(block) with builder.build() as block: builder.acquire( 100, AcquireChannel(0), MemorySlot(0), discriminator=Discriminator( name="my_disc", my_params_1={"param1": 0.1, "param2": 0.2}, my_params_2=[0, 1] ), ) schedule_blocks.append(block) return schedule_blocks def generate_layout_circuits(): """Test qpy circuits with layout set.""" from qiskit.transpiler.layout import TranspileLayout, Layout qr = QuantumRegister(3, "foo") qc = QuantumCircuit(qr, name="GHZ with layout") qc.h(0) qc.cx(0, 1) qc.swap(0, 1) qc.cx(0, 2) input_layout = {qr[index]: index for index in range(len(qc.qubits))} qc._layout = TranspileLayout( Layout(input_layout), input_qubit_mapping=input_layout, final_layout=Layout.from_qubit_list([qc.qubits[1], qc.qubits[0], qc.qubits[2]]), ) return [qc] def generate_control_flow_expr(): """`IfElseOp`, `WhileLoopOp` and `SwitchCaseOp` with `Expr` nodes in their discriminators.""" from qiskit.circuit.classical import expr, types body1 = QuantumCircuit(1) body1.x(0) qr1 = QuantumRegister(2, "q1") cr1 = ClassicalRegister(2, "c1") qc1 = QuantumCircuit(qr1, cr1) qc1.if_test(expr.equal(cr1, 3), body1.copy(), [0], []) qc1.while_loop(expr.logic_not(cr1[1]), body1.copy(), [0], []) inner2 = QuantumCircuit(1) inner2.x(0) outer2 = QuantumCircuit(1, 1) outer2.if_test(expr.logic_not(outer2.clbits[0]), inner2, [0], []) qr2 = QuantumRegister(2, "q2") cr1_2 = ClassicalRegister(3, "c1") cr2_2 = ClassicalRegister(3, "c2") qc2 = QuantumCircuit(qr2, cr1_2, cr2_2) qc2.if_test(expr.logic_or(expr.less(cr1_2, cr2_2), cr1_2[1]), outer2, [1], [1]) inner3 = QuantumCircuit(1) inner3.x(0) outer3 = QuantumCircuit(1, 1) outer3.switch(expr.logic_not(outer2.clbits[0]), [(False, inner2)], [0], []) qr3 = QuantumRegister(2, "q2") cr1_3 = ClassicalRegister(3, "c1") cr2_3 = ClassicalRegister(3, "c2") qc3 = QuantumCircuit(qr3, cr1_3, cr2_3) qc3.switch(expr.bit_xor(cr1_3, cr2_3), [(0, outer2)], [1], [1]) cr1_4 = ClassicalRegister(256, "c1") cr2_4 = ClassicalRegister(4, "c2") cr3_4 = ClassicalRegister(4, "c3") inner4 = QuantumCircuit(1) inner4.x(0) outer_loose = Clbit() outer4 = QuantumCircuit(QuantumRegister(2, "q_outer"), cr2_4, [outer_loose], cr1_4) outer4.if_test( expr.logic_and( expr.logic_or( expr.greater(expr.bit_or(cr2_4, 7), 10), expr.equal(expr.bit_and(cr1_4, cr1_4), expr.bit_not(cr1_4)), ), expr.logic_or( outer_loose, expr.cast(cr1_4, types.Bool()), ), ), inner4, [0], [], ) qc4_loose = Clbit() qc4 = QuantumCircuit(QuantumRegister(2, "qr4"), cr1_4, cr2_4, cr3_4, [qc4_loose]) qc4.rz(np.pi, 0) qc4.switch( expr.logic_and( expr.logic_or( expr.logic_or( expr.less(cr2_4, cr3_4), expr.logic_not(expr.greater_equal(cr3_4, cr2_4)), ), expr.logic_or( expr.logic_not(expr.less_equal(cr3_4, cr2_4)), expr.greater(cr2_4, cr3_4), ), ), expr.logic_and( expr.equal(cr3_4, 2), expr.not_equal(expr.bit_xor(cr1_4, 0x0F), 0x0F), ), ), [(False, outer4)], [1, 0], list(cr2_4) + [qc4_loose] + list(cr1_4), ) qc4.rz(np.pi, 0) return [qc1, qc2, qc3, qc4] def generate_circuits(version_parts): """Generate reference circuits.""" output_circuits = { "full.qpy": [generate_full_circuit()], "unitary.qpy": [generate_unitary_gate_circuit()], "multiple.qpy": generate_random_circuits(), "string_parameters.qpy": [generate_string_parameters()], "register_edge_cases.qpy": generate_register_edge_cases(), "parameterized.qpy": [generate_parameterized_circuit()], } if version_parts is None: return output_circuits if version_parts >= (0, 18, 1): output_circuits["qft_circuit.qpy"] = [generate_qft_circuit()] output_circuits["teleport.qpy"] = [generate_single_clbit_condition_teleportation()] if version_parts >= (0, 19, 0): output_circuits["param_phase.qpy"] = generate_param_phase() if version_parts >= (0, 19, 1): output_circuits["parameter_vector.qpy"] = [generate_parameter_vector()] output_circuits["pauli_evo.qpy"] = [generate_evolution_gate()] output_circuits["parameter_vector_expression.qpy"] = [ generate_parameter_vector_expression() ] if version_parts >= (0, 19, 2): output_circuits["control_flow.qpy"] = generate_control_flow_circuits() if version_parts >= (0, 21, 0): output_circuits["schedule_blocks.qpy"] = generate_schedule_blocks() output_circuits["pulse_gates.qpy"] = generate_calibrated_circuits() if version_parts >= (0, 24, 0): output_circuits["referenced_schedule_blocks.qpy"] = generate_referenced_schedule() output_circuits["control_flow_switch.qpy"] = generate_control_flow_switch_circuits() if version_parts >= (0, 24, 1): output_circuits["open_controlled_gates.qpy"] = generate_open_controlled_gates() output_circuits["controlled_gates.qpy"] = generate_controlled_gates() if version_parts >= (0, 24, 2): output_circuits["layout.qpy"] = generate_layout_circuits() if version_parts >= (0, 25, 0): output_circuits[ "acquire_inst_with_kernel_and_disc.qpy" ] = generate_acquire_instruction_with_kernel_and_discriminator() output_circuits["control_flow_expr.qpy"] = generate_control_flow_expr() return output_circuits def assert_equal(reference, qpy, count, version_parts, bind=None): """Compare two circuits.""" if bind is not None: reference_parameter_names = [x.name for x in reference.parameters] qpy_parameter_names = [x.name for x in qpy.parameters] if reference_parameter_names != qpy_parameter_names: msg = ( f"Circuit {count} parameter mismatch:" f" {reference_parameter_names} != {qpy_parameter_names}" ) sys.stderr.write(msg) sys.exit(4) reference = reference.bind_parameters(bind) qpy = qpy.bind_parameters(bind) if reference != qpy: msg = ( f"Reference Circuit {count}:\n{reference}\nis not equivalent to " f"qpy loaded circuit {count}:\n{qpy}\n" ) sys.stderr.write(msg) sys.exit(1) # Check deprecated bit properties, if set. The QPY dumping code before Terra 0.23.2 didn't # include enough information for us to fully reconstruct this, so we only test if newer. if version_parts >= (0, 23, 2) and isinstance(reference, QuantumCircuit): for ref_bit, qpy_bit in itertools.chain( zip(reference.qubits, qpy.qubits), zip(reference.clbits, qpy.clbits) ): if ref_bit._register is not None and ref_bit != qpy_bit: msg = ( f"Reference Circuit {count}:\n" "deprecated bit-level register information mismatch\n" f"reference bit: {ref_bit}\n" f"loaded bit: {qpy_bit}\n" ) sys.stderr.write(msg) sys.exit(1) if ( version_parts >= (0, 24, 2) and isinstance(reference, QuantumCircuit) and reference.layout != qpy.layout ): msg = f"Circuit {count} layout mismatch {reference.layout} != {qpy.layout}\n" sys.stderr.write(msg) sys.exit(4) # Don't compare name on bound circuits if bind is None and reference.name != qpy.name: msg = f"Circuit {count} name mismatch {reference.name} != {qpy.name}\n{reference}\n{qpy}" sys.stderr.write(msg) sys.exit(2) if reference.metadata != qpy.metadata: msg = f"Circuit {count} metadata mismatch: {reference.metadata} != {qpy.metadata}" sys.stderr.write(msg) sys.exit(3) def generate_qpy(qpy_files): """Generate qpy files from reference circuits.""" for path, circuits in qpy_files.items(): with open(path, "wb") as fd: dump(circuits, fd) def load_qpy(qpy_files, version_parts): """Load qpy circuits from files and compare to reference circuits.""" for path, circuits in qpy_files.items(): print(f"Loading qpy file: {path}") with open(path, "rb") as fd: qpy_circuits = load(fd) for i, circuit in enumerate(circuits): bind = None if path == "parameterized.qpy": bind = [1, 2] elif path == "param_phase.qpy": if i == 0: bind = [1, 2] else: bind = [1] elif path == "parameter_vector.qpy": bind = np.linspace(1.0, 2.0, 22) elif path == "parameter_vector_expression.qpy": bind = np.linspace(1.0, 2.0, 15) assert_equal(circuit, qpy_circuits[i], i, version_parts, bind=bind) def _main(): parser = argparse.ArgumentParser(description="Test QPY backwards compatibilty") parser.add_argument("command", choices=["generate", "load"]) parser.add_argument( "--version", "-v", help=( "Optionally specify the version being tested. " "This will enable additional circuit features " "to test generating and loading QPY." ), ) args = parser.parse_args() # Terra 0.18.0 was the first release with QPY, so that's the default. version_parts = (0, 18, 0) if args.version: version_match = re.search(VERSION_PATTERN, args.version, re.VERBOSE | re.IGNORECASE) version_parts = tuple(int(x) for x in version_match.group("release").split(".")) qpy_files = generate_circuits(version_parts) if args.command == "generate": generate_qpy(qpy_files) else: load_qpy(qpy_files, version_parts) if __name__ == "__main__": _main()
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=invalid-name """Randomized tests of transpiler circuit equivalence. This test can be optionally configured (e.g. by CI) via the following env vars: QISKIT_RANDOMIZED_TEST_LAYOUT_METHODS A space-delimited list of layout method names from which the randomizer should pick the layout method. Defaults to all available built-in methods if unspecified. QISKIT_RANDOMIZED_TEST_ROUTING_METHODS A space-delimited list of routing method names from which the randomizer should pick the routing method. Defaults to all available built-in methods if unspecified. QISKIT_RANDOMIZED_TEST_SCHEDULING_METHODS A space-delimited list of scheduling method names from which the randomizer should pick the scheduling method. Defaults to all available built-in methods if unspecified. QISKIT_RANDOMIZED_TEST_BACKEND_NEEDS_DURATIONS A boolean value (e.g. "true", "Y", etc.) which, when true, forces the randomizer to pick a backend which fully supports scheduling (i.e. has fully specified duration info). Defaults to False. QISKIT_RANDOMIZED_TEST_ALLOW_BARRIERS A boolean value (e.g. "true", "Y", etc.) which, when false, prevents the randomizer from emitting barrier instructions. Defaults to True. """ import os from math import pi from hypothesis import assume, settings, HealthCheck from hypothesis.stateful import multiple, rule, precondition, invariant from hypothesis.stateful import Bundle, RuleBasedStateMachine import hypothesis.strategies as st from qiskit import transpile, Aer from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.circuit import Measure, Reset, Gate, Barrier from qiskit.providers.fake_provider import ( FakeProvider, FakeOpenPulse2Q, FakeOpenPulse3Q, FakeYorktown, FakeTenerife, FakeOurense, FakeVigo, FakeMelbourne, FakeRueschlikon, FakeTokyo, FakePoughkeepsie, FakeAlmaden, FakeSingapore, FakeJohannesburg, FakeBoeblingen, FakeRochester, FakeBurlington, FakeCambridge, FakeCambridgeAlternativeBasis, FakeEssex, FakeLondon, FakeQasmSimulator, FakeArmonk, FakeRome, FakeSantiago, FakeSydney, FakeToronto, FakeValencia, ) from qiskit.test.base import dicts_almost_equal # pylint: disable=wildcard-import,unused-wildcard-import from qiskit.circuit.library.standard_gates import * default_profile = "transpiler_equivalence" settings.register_profile( default_profile, report_multiple_bugs=False, max_examples=200, deadline=None, suppress_health_check=[HealthCheck.filter_too_much], ) settings.load_profile(os.getenv("HYPOTHESIS_PROFILE", default_profile)) BASE_INSTRUCTIONS = { # Key is (n_qubits, n_clbits, n_params). All gates here should be directly known by Aer so they # can be simulated without an initial transpile (whether that's via `execute` or not). (1, 0, 0): [HGate, IGate, SGate, SdgGate, TGate, TdgGate, XGate, YGate, ZGate, Reset], (2, 0, 0): [CXGate, CYGate, CZGate, SwapGate], (3, 0, 0): [CCXGate, CSwapGate], (1, 0, 1): [PhaseGate, RXGate, RYGate, RZGate], (1, 0, 3): [UGate], (2, 0, 1): [RZZGate, CPhaseGate], (2, 0, 4): [CUGate], (1, 1, 0): [Measure], } variadic_gates = [Barrier] def _strtobool(s): return s.lower() in ("y", "yes", "t", "true", "on", "1") if not _strtobool(os.getenv("QISKIT_RANDOMIZED_TEST_ALLOW_BARRIERS", "True")): variadic_gates.remove(Barrier) def _getenv_list(var_name): value = os.getenv(var_name) return None if value is None else value.split() # Note: a value of `None` for any of the following methods means that # the selected pass manager gets to choose. However, to avoid complexity, # its not possible to specify `None` when overriding these with environment # variables. Really, `None` is useful only for testing Terra's pass managers, # and if you're overriding these, your goal is probably to test a specific # pass or set of passes instead. layout_methods = _getenv_list("QISKIT_RANDOMIZED_TEST_LAYOUT_METHODS") or [ None, "trivial", "dense", "noise_adaptive", "sabre", ] routing_methods = _getenv_list("QISKIT_RANDOMIZED_TEST_ROUTING_METHODS") or [ None, "basic", "stochastic", "lookahead", "sabre", ] scheduling_methods = _getenv_list("QISKIT_RANDOMIZED_TEST_SCHEDULING_METHODS") or [ None, "alap", "asap", ] backend_needs_durations = _strtobool( os.getenv("QISKIT_RANDOMIZED_TEST_BACKEND_NEEDS_DURATIONS", "False") ) def _fully_supports_scheduling(backend): """Checks if backend is not in the set of backends known not to have specified gate durations.""" return not isinstance( backend, ( # no coupling map FakeArmonk, # no measure durations FakeAlmaden, FakeBurlington, FakeCambridge, FakeCambridgeAlternativeBasis, FakeEssex, FakeJohannesburg, FakeLondon, FakeOpenPulse2Q, FakeOpenPulse3Q, FakePoughkeepsie, FakeQasmSimulator, FakeRochester, FakeRueschlikon, FakeSingapore, FakeTenerife, FakeTokyo, # No reset duration FakeAlmaden, FakeArmonk, FakeBoeblingen, FakeBurlington, FakeCambridge, FakeCambridgeAlternativeBasis, FakeEssex, FakeJohannesburg, FakeLondon, FakeMelbourne, FakeOpenPulse2Q, FakeOpenPulse3Q, FakeOurense, FakePoughkeepsie, FakeQasmSimulator, FakeRochester, FakeRome, FakeRueschlikon, FakeSantiago, FakeSingapore, FakeSydney, FakeTenerife, FakeTokyo, FakeToronto, FakeValencia, FakeVigo, FakeYorktown, ), ) fake_provider = FakeProvider() mock_backends = fake_provider.backends() mock_backends_with_scheduling = [b for b in mock_backends if _fully_supports_scheduling(b)] @st.composite def transpiler_conf(draw): """Composite search strategy to pick a valid transpiler config.""" all_backends = st.one_of(st.none(), st.sampled_from(mock_backends)) scheduling_backends = st.sampled_from(mock_backends_with_scheduling) scheduling_method = draw(st.sampled_from(scheduling_methods)) backend = ( draw(scheduling_backends) if scheduling_method or backend_needs_durations else draw(all_backends) ) return { "backend": backend, "optimization_level": draw(st.integers(min_value=0, max_value=3)), "layout_method": draw(st.sampled_from(layout_methods)), "routing_method": draw(st.sampled_from(routing_methods)), "scheduling_method": scheduling_method, "seed_transpiler": draw(st.integers(min_value=0, max_value=1_000_000)), } class QCircuitMachine(RuleBasedStateMachine): """Build a Hypothesis rule based state machine for constructing, transpiling and simulating a series of random QuantumCircuits. Build circuits with up to QISKIT_RANDOM_QUBITS qubits, apply a random selection of gates from qiskit.circuit.library with randomly selected qargs, cargs, and parameters. At random intervals, transpile the circuit for a random backend with a random optimization level and simulate both the initial and the transpiled circuits to verify that their counts are the same. """ qubits = Bundle("qubits") clbits = Bundle("clbits") backend = Aer.get_backend("aer_simulator") max_qubits = int(backend.configuration().n_qubits / 2) # Limit reg generation for more interesting circuits max_qregs = 3 max_cregs = 3 def __init__(self): super().__init__() self.qc = QuantumCircuit() self.enable_variadic = bool(variadic_gates) @precondition(lambda self: len(self.qc.qubits) < self.max_qubits) @precondition(lambda self: len(self.qc.qregs) < self.max_qregs) @rule(target=qubits, n=st.integers(min_value=1, max_value=max_qubits)) def add_qreg(self, n): """Adds a new variable sized qreg to the circuit, up to max_qubits.""" n = min(n, self.max_qubits - len(self.qc.qubits)) qreg = QuantumRegister(n) self.qc.add_register(qreg) return multiple(*list(qreg)) @precondition(lambda self: len(self.qc.cregs) < self.max_cregs) @rule(target=clbits, n=st.integers(1, 5)) def add_creg(self, n): """Add a new variable sized creg to the circuit.""" creg = ClassicalRegister(n) self.qc.add_register(creg) return multiple(*list(creg)) # Gates of various shapes @precondition(lambda self: self.qc.num_qubits > 0 and self.qc.num_clbits > 0) @rule(n_arguments=st.sampled_from(sorted(BASE_INSTRUCTIONS.keys())), data=st.data()) def add_gate(self, n_arguments, data): """Append a random fixed gate to the circuit.""" n_qubits, n_clbits, n_params = n_arguments gate_class = data.draw(st.sampled_from(BASE_INSTRUCTIONS[n_qubits, n_clbits, n_params])) qubits = data.draw(st.lists(self.qubits, min_size=n_qubits, max_size=n_qubits, unique=True)) clbits = data.draw(st.lists(self.clbits, min_size=n_clbits, max_size=n_clbits, unique=True)) params = data.draw( st.lists( st.floats( allow_nan=False, allow_infinity=False, min_value=-10 * pi, max_value=10 * pi ), min_size=n_params, max_size=n_params, ) ) self.qc.append(gate_class(*params), qubits, clbits) @precondition(lambda self: self.enable_variadic) @rule(gate=st.sampled_from(variadic_gates), qargs=st.lists(qubits, min_size=1, unique=True)) def add_variQ_gate(self, gate, qargs): """Append a gate with a variable number of qargs.""" self.qc.append(gate(len(qargs)), qargs) @precondition(lambda self: len(self.qc.data) > 0) @rule(carg=clbits, data=st.data()) def add_c_if_last_gate(self, carg, data): """Modify the last gate to be conditional on a classical register.""" creg = self.qc.find_bit(carg).registers[0][0] val = data.draw(st.integers(min_value=0, max_value=2 ** len(creg) - 1)) last_gate = self.qc.data[-1] # Conditional instructions are not supported assume(isinstance(last_gate[0], Gate)) last_gate[0].c_if(creg, val) # Properties to check @invariant() def qasm(self): """After each circuit operation, it should be possible to build QASM.""" self.qc.qasm() @precondition(lambda self: any(isinstance(d[0], Measure) for d in self.qc.data)) @rule(kwargs=transpiler_conf()) def equivalent_transpile(self, kwargs): """Simulate, transpile and simulate the present circuit. Verify that the counts are not significantly different before and after transpilation. """ assume( kwargs["backend"] is None or kwargs["backend"].configuration().n_qubits >= len(self.qc.qubits) ) call = ( "transpile(qc, " + ", ".join(f"{key:s}={value!r}" for key, value in kwargs.items() if value is not None) + ")" ) print(f"Evaluating {call} for:\n{self.qc.qasm()}") shots = 4096 # Note that there's no transpilation here, which is why the gates are limited to only ones # that Aer supports natively. aer_counts = self.backend.run(self.qc, shots=shots).result().get_counts() try: xpiled_qc = transpile(self.qc, **kwargs) except Exception as e: failed_qasm = f"Exception caught during transpilation of circuit: \n{self.qc.qasm()}" raise RuntimeError(failed_qasm) from e xpiled_aer_counts = self.backend.run(xpiled_qc, shots=shots).result().get_counts() count_differences = dicts_almost_equal(aer_counts, xpiled_aer_counts, 0.05 * shots) assert ( count_differences == "" ), "Counts not equivalent: {}\nFailing QASM Input:\n{}\n\nFailing QASM Output:\n{}".format( count_differences, self.qc.qasm(), xpiled_qc.qasm() ) TestQuantumCircuit = QCircuitMachine.TestCase
https://github.com/swe-train/qiskit__qiskit
swe-train
# Testing Circuits import warnings warnings.simplefilter("ignore") %run "mpl/circuit/test_circuit_matplotlib_drawer.py" # Testing Graphs %run "mpl/graph/test_graph_matplotlib_drawer.py" %run -i "results.py" RESULTS_CIRCUIT RESULTS_GRAPH
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for circuit MPL drawer""" import unittest import os import math from test.visual import VisualTestUtilities from pathlib import Path import numpy as np from numpy import pi from qiskit.test import QiskitTestCase from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, transpile from qiskit.providers.fake_provider import FakeTenerife from qiskit.visualization.circuit.circuit_visualization import _matplotlib_circuit_drawer from qiskit.circuit.library import ( XGate, MCXGate, HGate, RZZGate, SwapGate, DCXGate, ZGate, SGate, U1Gate, CPhaseGate, ) from qiskit.circuit.library import MCXVChain from qiskit.extensions import HamiltonianGate from qiskit.circuit import Parameter, Qubit, Clbit from qiskit.circuit.library import IQP from qiskit.quantum_info.random import random_unitary from qiskit.utils import optionals if optionals.HAS_MATPLOTLIB: from matplotlib.pyplot import close as mpl_close else: raise ImportError('Must have Matplotlib installed. To install, run "pip install matplotlib".') BASE_DIR = Path(__file__).parent RESULT_DIR = Path(BASE_DIR) / "circuit_results" TEST_REFERENCE_DIR = Path(BASE_DIR) / "references" FAILURE_DIFF_DIR = Path(BASE_DIR).parent / "visual_test_failures" FAILURE_PREFIX = "circuit_failure_" class TestCircuitMatplotlibDrawer(QiskitTestCase): """Circuit MPL visualization""" def setUp(self): super().setUp() self.circuit_drawer = VisualTestUtilities.save_data_wrap( _matplotlib_circuit_drawer, str(self), RESULT_DIR ) if not os.path.exists(FAILURE_DIFF_DIR): os.makedirs(FAILURE_DIFF_DIR) if not os.path.exists(RESULT_DIR): os.makedirs(RESULT_DIR) def tearDown(self): super().tearDown() mpl_close("all") @staticmethod def _image_path(image_name): return os.path.join(RESULT_DIR, image_name) @staticmethod def _reference_path(image_name): return os.path.join(TEST_REFERENCE_DIR, image_name) def test_empty_circuit(self): """Test empty circuit""" circuit = QuantumCircuit() fname = "empty_circut.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_calibrations(self): """Test calibrations annotations See https://github.com/Qiskit/qiskit-terra/issues/5920 """ circuit = QuantumCircuit(2, 2) circuit.h(0) from qiskit import pulse with pulse.build(name="hadamard") as h_q0: pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(0) ) circuit.add_calibration("h", [0], h_q0) fname = "calibrations.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_calibrations_with_control_gates(self): """Test calibrations annotations See https://github.com/Qiskit/qiskit-terra/issues/5920 """ circuit = QuantumCircuit(2, 2) circuit.cx(0, 1) circuit.ch(0, 1) from qiskit import pulse with pulse.build(name="cnot") as cx_q01: pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(1) ) circuit.add_calibration("cx", [0, 1], cx_q01) with pulse.build(name="ch") as ch_q01: pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(1) ) circuit.add_calibration("ch", [0, 1], ch_q01) fname = "calibrations_with_control_gates.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_calibrations_with_swap_and_reset(self): """Test calibrations annotations See https://github.com/Qiskit/qiskit-terra/issues/5920 """ circuit = QuantumCircuit(2, 2) circuit.swap(0, 1) circuit.reset(0) from qiskit import pulse with pulse.build(name="swap") as swap_q01: pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(1) ) circuit.add_calibration("swap", [0, 1], swap_q01) with pulse.build(name="reset") as reset_q0: pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(1) ) circuit.add_calibration("reset", [0], reset_q0) fname = "calibrations_with_swap_and_reset.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_calibrations_with_rzz_and_rxx(self): """Test calibrations annotations See https://github.com/Qiskit/qiskit-terra/issues/5920 """ circuit = QuantumCircuit(2, 2) circuit.rzz(pi, 0, 1) circuit.rxx(pi, 0, 1) from qiskit import pulse with pulse.build(name="rzz") as rzz_q01: pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(1) ) circuit.add_calibration("rzz", [0, 1], rzz_q01) with pulse.build(name="rxx") as rxx_q01: pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(1) ) circuit.add_calibration("rxx", [0, 1], rxx_q01) fname = "calibrations_with_rzz_and_rxx.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_no_ops(self): """Test circuit with no ops. See https://github.com/Qiskit/qiskit-terra/issues/5393""" circuit = QuantumCircuit(2, 3) fname = "no_op_circut.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_long_name(self): """Test to see that long register names can be seen completely As reported in #2605 """ # add a register with a very long name qr = QuantumRegister(4, "veryLongQuantumRegisterName") # add another to make sure adjustments are made based on longest qrr = QuantumRegister(1, "q0") circuit = QuantumCircuit(qr, qrr) # check gates are shifted over accordingly circuit.h(qr) circuit.h(qr) circuit.h(qr) fname = "long_name.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_multi_underscore_reg_names(self): """Test that multi-underscores in register names display properly""" q_reg1 = QuantumRegister(1, "q1_re__g__g") q_reg3 = QuantumRegister(3, "q3_re_g__g") c_reg1 = ClassicalRegister(1, "c1_re_g__g") c_reg3 = ClassicalRegister(3, "c3_re_g__g") circuit = QuantumCircuit(q_reg1, q_reg3, c_reg1, c_reg3) fname = "multi_underscore_true.png" self.circuit_drawer(circuit, cregbundle=True, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) fname2 = "multi_underscore_false.png" self.circuit_drawer(circuit, cregbundle=False, filename=fname2) ratio2 = VisualTestUtilities._save_diff( self._image_path(fname2), self._reference_path(fname2), fname2, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) self.assertGreaterEqual(ratio2, 0.9999) def test_conditional(self): """Test that circuits with conditionals draw correctly""" qr = QuantumRegister(2, "q") cr = ClassicalRegister(2, "c") circuit = QuantumCircuit(qr, cr) # check gates are shifted over accordingly circuit.h(qr) circuit.measure(qr, cr) circuit.h(qr[0]).c_if(cr, 2) fname = "reg_conditional.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_bit_conditional_with_cregbundle(self): """Test that circuits with single bit conditionals draw correctly with cregbundle=True.""" qr = QuantumRegister(2, "q") cr = ClassicalRegister(2, "c") circuit = QuantumCircuit(qr, cr) circuit.x(qr[0]) circuit.measure(qr, cr) circuit.h(qr[0]).c_if(cr[0], 1) circuit.x(qr[1]).c_if(cr[1], 0) fname = "bit_conditional_bundle.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_bit_conditional_no_cregbundle(self): """Test that circuits with single bit conditionals draw correctly with cregbundle=False.""" qr = QuantumRegister(2, "q") cr = ClassicalRegister(2, "c") circuit = QuantumCircuit(qr, cr) circuit.x(qr[0]) circuit.measure(qr, cr) circuit.h(qr[0]).c_if(cr[0], 1) circuit.x(qr[1]).c_if(cr[1], 0) fname = "bit_conditional_no_bundle.png" self.circuit_drawer(circuit, filename=fname, cregbundle=False) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_plot_partial_barrier(self): """Test plotting of partial barriers.""" # generate a circuit with barrier and other barrier like instructions in q = QuantumRegister(2, "q") c = ClassicalRegister(2, "c") circuit = QuantumCircuit(q, c) # check for barriers circuit.h(q[0]) circuit.barrier(0) circuit.h(q[0]) fname = "plot_partial_barrier.png" self.circuit_drawer(circuit, filename=fname, plot_barriers=True) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_plot_barriers(self): """Test to see that plotting barriers works. If it is set to False, no blank columns are introduced""" # generate a circuit with barriers and other barrier like instructions in q = QuantumRegister(2, "q") c = ClassicalRegister(2, "c") circuit = QuantumCircuit(q, c) # check for barriers circuit.h(q[0]) circuit.barrier() # check for other barrier like commands circuit.h(q[1]) # this import appears to be unused, but is actually needed to get snapshot instruction import qiskit.extensions.simulator # pylint: disable=unused-import circuit.snapshot("1") # check the barriers plot properly when plot_barriers= True fname = "plot_barriers_true.png" self.circuit_drawer(circuit, filename=fname, plot_barriers=True) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) fname2 = "plot_barriers_false.png" self.circuit_drawer(circuit, filename=fname2, plot_barriers=False) ratio2 = VisualTestUtilities._save_diff( self._image_path(fname2), self._reference_path(fname2), fname2, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) self.assertGreaterEqual(ratio2, 0.9999) def test_no_barriers_false(self): """Generate the same circuit as test_plot_barriers but without the barrier commands as this is what the circuit should look like when displayed with plot barriers false""" q1 = QuantumRegister(2, "q") c1 = ClassicalRegister(2, "c") circuit = QuantumCircuit(q1, c1) circuit.h(q1[0]) circuit.h(q1[1]) fname = "no_barriers.png" self.circuit_drawer(circuit, filename=fname, plot_barriers=False) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_fold_minus1(self): """Test to see that fold=-1 is no folding""" qr = QuantumRegister(2, "q") cr = ClassicalRegister(1, "c") circuit = QuantumCircuit(qr, cr) for _ in range(3): circuit.h(0) circuit.x(0) fname = "fold_minus1.png" self.circuit_drawer(circuit, fold=-1, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_fold_4(self): """Test to see that fold=4 is folding""" qr = QuantumRegister(2, "q") cr = ClassicalRegister(1, "c") circuit = QuantumCircuit(qr, cr) for _ in range(3): circuit.h(0) circuit.x(0) fname = "fold_4.png" self.circuit_drawer(circuit, fold=4, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_big_gates(self): """Test large gates with params""" qr = QuantumRegister(6, "q") circuit = QuantumCircuit(qr) circuit.append(IQP([[6, 5, 3], [5, 4, 5], [3, 5, 1]]), [0, 1, 2]) desired_vector = [ 1 / math.sqrt(16) * complex(0, 1), 1 / math.sqrt(8) * complex(1, 0), 1 / math.sqrt(16) * complex(1, 1), 0, 0, 1 / math.sqrt(8) * complex(1, 2), 1 / math.sqrt(16) * complex(1, 0), 0, ] circuit.initialize(desired_vector, [qr[3], qr[4], qr[5]]) circuit.unitary([[1, 0], [0, 1]], [qr[0]]) matrix = np.zeros((4, 4)) theta = Parameter("theta") circuit.append(HamiltonianGate(matrix, theta), [qr[1], qr[2]]) circuit = circuit.bind_parameters({theta: 1}) circuit.isometry(np.eye(4, 4), list(range(3, 5)), []) fname = "big_gates.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_cnot(self): """Test different cnot gates (ccnot, mcx, etc)""" qr = QuantumRegister(6, "q") circuit = QuantumCircuit(qr) circuit.x(0) circuit.cx(0, 1) circuit.ccx(0, 1, 2) circuit.append(XGate().control(3, ctrl_state="010"), [qr[2], qr[3], qr[0], qr[1]]) circuit.append(MCXGate(num_ctrl_qubits=3, ctrl_state="101"), [qr[0], qr[1], qr[2], qr[4]]) circuit.append(MCXVChain(3, dirty_ancillas=True), [qr[0], qr[1], qr[2], qr[3], qr[5]]) fname = "cnot.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_cz(self): """Test Z and Controlled-Z Gates""" qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.z(0) circuit.cz(0, 1) circuit.append(ZGate().control(3, ctrl_state="101"), [0, 1, 2, 3]) circuit.append(ZGate().control(2), [1, 2, 3]) circuit.append(ZGate().control(1, ctrl_state="0", label="CZ Gate"), [2, 3]) fname = "cz.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_pauli_clifford(self): """Test Pauli(green) and Clifford(blue) gates""" qr = QuantumRegister(5, "q") circuit = QuantumCircuit(qr) circuit.x(0) circuit.y(0) circuit.z(0) circuit.id(0) circuit.h(1) circuit.cx(1, 2) circuit.cy(1, 2) circuit.cz(1, 2) circuit.swap(3, 4) circuit.s(3) circuit.sdg(3) circuit.iswap(3, 4) circuit.dcx(3, 4) fname = "pauli_clifford.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_creg_initial(self): """Test cregbundle and initial state options""" qr = QuantumRegister(2, "q") cr = ClassicalRegister(2, "c") circuit = QuantumCircuit(qr, cr) circuit.x(0) circuit.h(0) circuit.x(1) fname = "creg_initial_true.png" self.circuit_drawer(circuit, filename=fname, cregbundle=True, initial_state=True) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) fname2 = "creg_initial_false.png" self.circuit_drawer(circuit, filename=fname2, cregbundle=False, initial_state=False) ratio2 = VisualTestUtilities._save_diff( self._image_path(fname2), self._reference_path(fname2), fname2, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) self.assertGreaterEqual(ratio2, 0.9999) def test_r_gates(self): """Test all R gates""" qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.r(3 * pi / 4, 3 * pi / 8, 0) circuit.rx(pi / 2, 1) circuit.ry(-pi / 2, 2) circuit.rz(3 * pi / 4, 3) circuit.rxx(pi / 2, 0, 1) circuit.ryy(3 * pi / 4, 2, 3) circuit.rzx(-pi / 2, 0, 1) circuit.rzz(pi / 2, 2, 3) fname = "r_gates.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_ctrl_labels(self): """Test control labels""" qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.cy(1, 0, label="Bottom Y label") circuit.cu(pi / 2, pi / 2, pi / 2, 0, 2, 3, label="Top U label") circuit.ch(0, 1, label="Top H label") circuit.append( HGate(label="H gate label").control(3, label="H control label", ctrl_state="010"), [qr[1], qr[2], qr[3], qr[0]], ) fname = "ctrl_labels.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_cswap_rzz(self): """Test controlled swap and rzz gates""" qr = QuantumRegister(5, "q") circuit = QuantumCircuit(qr) circuit.cswap(0, 1, 2) circuit.append(RZZGate(3 * pi / 4).control(3, ctrl_state="010"), [2, 1, 4, 3, 0]) fname = "cswap_rzz.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_ghz_to_gate(self): """Test controlled GHZ to_gate circuit""" qr = QuantumRegister(5, "q") circuit = QuantumCircuit(qr) ghz_circuit = QuantumCircuit(3, name="this is a WWWWWWWWWWWide name Ctrl-GHZ Circuit") ghz_circuit.h(0) ghz_circuit.cx(0, 1) ghz_circuit.cx(1, 2) ghz = ghz_circuit.to_gate() ccghz = ghz.control(2, ctrl_state="10") circuit.append(ccghz, [4, 0, 1, 3, 2]) fname = "ghz_to_gate.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_scale(self): """Tests scale See: https://github.com/Qiskit/qiskit-terra/issues/4179""" circuit = QuantumCircuit(5) circuit.unitary(random_unitary(2**5), circuit.qubits) fname = "scale_default.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) fname2 = "scale_half.png" self.circuit_drawer(circuit, filename=fname2, scale=0.5) ratio2 = VisualTestUtilities._save_diff( self._image_path(fname2), self._reference_path(fname2), fname2, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) fname3 = "scale_double.png" self.circuit_drawer(circuit, filename=fname3, scale=2) ratio3 = VisualTestUtilities._save_diff( self._image_path(fname3), self._reference_path(fname3), fname3, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) self.assertGreaterEqual(ratio2, 0.9999) self.assertGreaterEqual(ratio3, 0.9999) def test_pi_param_expr(self): """Test pi in circuit with parameter expression.""" x, y = Parameter("x"), Parameter("y") circuit = QuantumCircuit(1) circuit.rx((pi - x) * (pi - y), 0) fname = "pi_in_param_expr.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_partial_layout(self): """Tests partial_layout See: https://github.com/Qiskit/qiskit-terra/issues/4757""" circuit = QuantumCircuit(3) circuit.h(1) transpiled = transpile( circuit, backend=FakeTenerife(), basis_gates=["id", "cx", "rz", "sx", "x"], optimization_level=0, initial_layout=[1, 2, 0], seed_transpiler=0, ) fname = "partial_layout.png" self.circuit_drawer(transpiled, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_init_reset(self): """Test reset and initialize with 1 and 2 qubits""" circuit = QuantumCircuit(2) circuit.initialize([0, 1], 0) circuit.reset(1) circuit.initialize([0, 1, 0, 0], [0, 1]) fname = "init_reset.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_with_global_phase(self): """Tests with global phase""" circuit = QuantumCircuit(3, global_phase=1.57079632679) circuit.h(range(3)) fname = "global_phase.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_alternative_colors(self): """Tests alternative color schemes""" ratios = [] for style in ["iqx", "iqx-dark", "textbook"]: with self.subTest(style=style): circuit = QuantumCircuit(7) circuit.h(0) circuit.x(0) circuit.cx(0, 1) circuit.ccx(0, 1, 2) circuit.swap(0, 1) circuit.cswap(0, 1, 2) circuit.append(SwapGate().control(2), [0, 1, 2, 3]) circuit.dcx(0, 1) circuit.append(DCXGate().control(1), [0, 1, 2]) circuit.append(DCXGate().control(2), [0, 1, 2, 3]) circuit.z(4) circuit.s(4) circuit.sdg(4) circuit.t(4) circuit.tdg(4) circuit.p(pi / 2, 4) circuit.cz(5, 6) circuit.cp(pi / 2, 5, 6) circuit.y(5) circuit.rx(pi / 3, 5) circuit.rzx(pi / 2, 5, 6) circuit.u(pi / 2, pi / 2, pi / 2, 5) circuit.barrier(5, 6) circuit.reset(5) fname = f"{style}_color.png" self.circuit_drawer(circuit, style={"name": style}, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) ratios.append(ratio) for ratio in ratios: self.assertGreaterEqual(ratio, 0.9999) def test_reverse_bits(self): """Tests reverse_bits parameter""" circuit = QuantumCircuit(3) circuit.h(0) circuit.cx(0, 1) circuit.ccx(2, 1, 0) fname = "reverse_bits.png" self.circuit_drawer(circuit, reverse_bits=True, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_bw(self): """Tests black and white style parameter""" circuit = QuantumCircuit(3, 3) circuit.h(0) circuit.x(1) circuit.sdg(2) circuit.cx(0, 1) circuit.ccx(2, 1, 0) circuit.swap(1, 2) circuit.measure_all() fname = "bw.png" self.circuit_drawer(circuit, style={"name": "bw"}, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_user_style(self): """Tests loading a user style""" circuit = QuantumCircuit(7) circuit.h(0) circuit.append(HGate(label="H2"), [1]) circuit.x(0) circuit.cx(0, 1) circuit.ccx(0, 1, 2) circuit.swap(0, 1) circuit.cswap(0, 1, 2) circuit.append(SwapGate().control(2), [0, 1, 2, 3]) circuit.dcx(0, 1) circuit.append(DCXGate().control(1), [0, 1, 2]) circuit.append(DCXGate().control(2), [0, 1, 2, 3]) circuit.z(4) circuit.append(SGate(label="S1"), [4]) circuit.sdg(4) circuit.t(4) circuit.tdg(4) circuit.p(pi / 2, 4) circuit.cz(5, 6) circuit.cp(pi / 2, 5, 6) circuit.y(5) circuit.rx(pi / 3, 5) circuit.rzx(pi / 2, 5, 6) circuit.u(pi / 2, pi / 2, pi / 2, 5) circuit.barrier(5, 6) circuit.reset(5) fname = "user_style.png" self.circuit_drawer( circuit, style={ "name": "user_style", "displaytext": {"H2": "H_2"}, "displaycolor": {"H2": ("#EEDD00", "#FF0000")}, }, filename=fname, ) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_subfont_change(self): """Tests changing the subfont size""" circuit = QuantumCircuit(3) circuit.h(0) circuit.x(0) circuit.u(pi / 2, pi / 2, pi / 2, 1) circuit.p(pi / 2, 2) style = {"name": "iqx", "subfontsize": 11} fname = "subfont.png" self.circuit_drawer(circuit, style=style, filename=fname) self.assertEqual(style, {"name": "iqx", "subfontsize": 11}) # check does not change style ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_meas_condition(self): """Tests measure with a condition""" qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") circuit = QuantumCircuit(qr, cr) circuit.h(qr[0]) circuit.measure(qr[0], cr[0]) circuit.h(qr[1]).c_if(cr, 1) fname = "meas_condition.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_reverse_bits_condition(self): """Tests reverse_bits with a condition and gate above""" cr = ClassicalRegister(2, "cr") cr2 = ClassicalRegister(1, "cr2") qr = QuantumRegister(3, "qr") circuit = QuantumCircuit(qr, cr, cr2) circuit.h(0) circuit.h(1) circuit.h(2) circuit.x(0) circuit.x(0) circuit.measure(2, 1) circuit.x(2).c_if(cr, 2) fname = "reverse_bits_cond_true.png" self.circuit_drawer(circuit, cregbundle=False, reverse_bits=True, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) fname2 = "reverse_bits_cond_false.png" self.circuit_drawer(circuit, cregbundle=False, reverse_bits=False, filename=fname2) ratio2 = VisualTestUtilities._save_diff( self._image_path(fname2), self._reference_path(fname2), fname2, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) self.assertGreaterEqual(ratio2, 0.9999) def test_style_custom_gates(self): """Tests style for custom gates""" def cnotnot(gate_label): gate_circuit = QuantumCircuit(3, name=gate_label) gate_circuit.cnot(0, 1) gate_circuit.cnot(0, 2) gate = gate_circuit.to_gate() return gate q = QuantumRegister(3, name="q") circuit = QuantumCircuit(q) circuit.append(cnotnot("CNOTNOT"), [q[0], q[1], q[2]]) circuit.append(cnotnot("CNOTNOT_PRIME"), [q[0], q[1], q[2]]) circuit.h(q[0]) fname = "style_custom_gates.png" self.circuit_drawer( circuit, style={ "displaycolor": {"CNOTNOT": ("#000000", "#FFFFFF"), "h": ("#A1A1A1", "#043812")}, "displaytext": {"CNOTNOT_PRIME": "$\\mathrm{CNOTNOT}'$"}, }, filename=fname, ) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_6095(self): """Tests controlled-phase gate style See https://github.com/Qiskit/qiskit-terra/issues/6095""" circuit = QuantumCircuit(2) circuit.cp(1.0, 0, 1) circuit.h(1) fname = "6095.png" self.circuit_drawer( circuit, style={"displaycolor": {"cp": ("#A27486", "#000000"), "h": ("#A27486", "#000000")}}, filename=fname, ) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_instruction_1q_1c(self): """Tests q0-cr0 instruction on a circuit""" qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") circuit = QuantumCircuit(qr, cr) inst = QuantumCircuit(1, 1, name="Inst").to_instruction() circuit.append(inst, [qr[0]], [cr[0]]) fname = "instruction_1q_1c.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_instruction_3q_3c_circ1(self): """Tests q0-q1-q2-cr_20-cr0-cr1 instruction on a circuit""" qr = QuantumRegister(4, "qr") cr = ClassicalRegister(2, "cr") cr2 = ClassicalRegister(2, "cr2") circuit = QuantumCircuit(qr, cr, cr2) inst = QuantumCircuit(3, 3, name="Inst").to_instruction() circuit.append(inst, [qr[0], qr[1], qr[2]], [cr2[0], cr[0], cr[1]]) fname = "instruction_3q_3c_circ1.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_instruction_3q_3c_circ2(self): """Tests q3-q0-q2-cr0-cr1-cr_20 instruction on a circuit""" qr = QuantumRegister(4, "qr") cr = ClassicalRegister(2, "cr") cr2 = ClassicalRegister(2, "cr2") circuit = QuantumCircuit(qr, cr, cr2) inst = QuantumCircuit(3, 3, name="Inst").to_instruction() circuit.append(inst, [qr[3], qr[0], qr[2]], [cr[0], cr[1], cr2[0]]) fname = "instruction_3q_3c_circ2.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_instruction_3q_3c_circ3(self): """Tests q3-q1-q2-cr_31-cr1-cr_30 instruction on a circuit""" qr = QuantumRegister(4, "qr") cr = ClassicalRegister(2, "cr") cr2 = ClassicalRegister(1, "cr2") cr3 = ClassicalRegister(2, "cr3") circuit = QuantumCircuit(qr, cr, cr2, cr3) inst = QuantumCircuit(3, 3, name="Inst").to_instruction() circuit.append(inst, [qr[3], qr[1], qr[2]], [cr3[1], cr[1], cr3[0]]) fname = "instruction_3q_3c_circ3.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_overwide_gates(self): """Test gates don't exceed width of default fold""" circuit = QuantumCircuit(5) initial_state = np.zeros(2**5) initial_state[5] = 1 circuit.initialize(initial_state) fname = "wide_params.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_one_bit_regs(self): """Test registers with only one bit display without number""" qr1 = QuantumRegister(1, "qr1") qr2 = QuantumRegister(2, "qr2") cr1 = ClassicalRegister(1, "cr1") cr2 = ClassicalRegister(2, "cr2") circuit = QuantumCircuit(qr1, qr2, cr1, cr2) circuit.h(0) circuit.measure(0, 0) fname = "one_bit_regs.png" self.circuit_drawer(circuit, cregbundle=False, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_user_ax_subplot(self): """Test for when user supplies ax for a subplot""" import matplotlib.pyplot as plt fig = plt.figure(1, figsize=(6, 4)) fig.patch.set_facecolor("white") ax1 = fig.add_subplot(1, 2, 1) ax2 = fig.add_subplot(1, 2, 2) ax1.plot([1, 2, 3]) circuit = QuantumCircuit(4) circuit.h(0) circuit.cx(0, 1) circuit.h(1) circuit.cx(1, 2) plt.close(fig) fname = "user_ax.png" self.circuit_drawer(circuit, ax=ax2, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_figwidth(self): """Test style dict 'figwidth'""" circuit = QuantumCircuit(3) circuit.h(0) circuit.cx(0, 1) circuit.x(1) circuit.cx(1, 2) circuit.x(2) fname = "figwidth.png" self.circuit_drawer(circuit, style={"figwidth": 5}, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_registerless_one_bit(self): """Test circuit with one-bit registers and registerless bits.""" qrx = QuantumRegister(2, "qrx") qry = QuantumRegister(1, "qry") crx = ClassicalRegister(2, "crx") circuit = QuantumCircuit(qrx, [Qubit(), Qubit()], qry, [Clbit(), Clbit()], crx) fname = "registerless_one_bit.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_measures_with_conditions(self): """Test that a measure containing a condition displays""" qr = QuantumRegister(2, "qr") cr1 = ClassicalRegister(2, "cr1") cr2 = ClassicalRegister(2, "cr2") circuit = QuantumCircuit(qr, cr1, cr2) circuit.h(0) circuit.h(1) circuit.measure(0, cr1[1]) circuit.measure(1, cr2[0]).c_if(cr1, 1) circuit.h(0).c_if(cr2, 3) fname = "measure_cond_false.png" self.circuit_drawer(circuit, cregbundle=False, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) fname2 = "measure_cond_true.png" self.circuit_drawer(circuit, cregbundle=True, filename=fname2) ratio2 = VisualTestUtilities._save_diff( self._image_path(fname2), self._reference_path(fname2), fname2, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) self.assertGreaterEqual(ratio2, 0.9999) def test_conditions_measures_with_bits(self): """Test that gates with conditions and measures work with bits""" bits = [Qubit(), Qubit(), Clbit(), Clbit()] cr = ClassicalRegister(2, "cr") crx = ClassicalRegister(3, "cs") circuit = QuantumCircuit(bits, cr, [Clbit()], crx) circuit.x(0).c_if(crx[1], 0) circuit.measure(0, bits[3]) fname = "measure_cond_bits_false.png" self.circuit_drawer(circuit, cregbundle=False, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) fname2 = "measure_cond_bits_true.png" self.circuit_drawer(circuit, cregbundle=True, filename=fname2) ratio2 = VisualTestUtilities._save_diff( self._image_path(fname2), self._reference_path(fname2), fname2, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) self.assertGreaterEqual(ratio2, 0.9999) def test_conditional_gates_right_of_measures_with_bits(self): """Test that gates with conditions draw to right of measures when same bit""" qr = QuantumRegister(3, "qr") cr = ClassicalRegister(2, "cr") circuit = QuantumCircuit(qr, cr) circuit.h(qr[0]) circuit.measure(qr[0], cr[1]) circuit.h(qr[1]).c_if(cr[1], 0) circuit.h(qr[2]).c_if(cr[0], 0) fname = "measure_cond_bits_right.png" self.circuit_drawer(circuit, cregbundle=False, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_conditions_with_bits_reverse(self): """Test that gates with conditions work with bits reversed""" bits = [Qubit(), Qubit(), Clbit(), Clbit()] cr = ClassicalRegister(2, "cr") crx = ClassicalRegister(2, "cs") circuit = QuantumCircuit(bits, cr, [Clbit()], crx) circuit.x(0).c_if(bits[3], 0) fname = "cond_bits_reverse.png" self.circuit_drawer(circuit, cregbundle=False, reverse_bits=True, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_sidetext_with_condition(self): """Test that sidetext gates align properly with conditions""" qr = QuantumRegister(2, "q") cr = ClassicalRegister(2, "c") circuit = QuantumCircuit(qr, cr) circuit.append(CPhaseGate(pi / 2), [qr[0], qr[1]]).c_if(cr[1], 1) fname = "sidetext_condition.png" self.circuit_drawer(circuit, cregbundle=False, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_fold_with_conditions(self): """Test that gates with conditions draw correctly when folding""" qr = QuantumRegister(3) cr = ClassicalRegister(5) circuit = QuantumCircuit(qr, cr) circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 1) circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 3) circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 5) circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 7) circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 9) circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 11) circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 13) circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 15) circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 17) circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 19) circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 21) circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 23) circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 25) circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 27) circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 29) circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 31) fname = "fold_with_conditions.png" self.circuit_drawer(circuit, cregbundle=False, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_idle_wires_barrier(self): """Test that idle_wires False works with barrier""" circuit = QuantumCircuit(4, 4) circuit.x(2) circuit.barrier() fname = "idle_wires_barrier.png" self.circuit_drawer(circuit, cregbundle=False, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_wire_order(self): """Test the wire_order option""" qr = QuantumRegister(4, "q") cr = ClassicalRegister(4, "c") cr2 = ClassicalRegister(2, "cx") circuit = QuantumCircuit(qr, cr, cr2) circuit.h(0) circuit.h(3) circuit.x(1) circuit.x(3).c_if(cr, 10) fname = "wire_order.png" self.circuit_drawer( circuit, cregbundle=False, wire_order=[2, 1, 3, 0, 6, 8, 9, 5, 4, 7], filename=fname, ) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_barrier_label(self): """Test the barrier label""" circuit = QuantumCircuit(2) circuit.x(0) circuit.y(1) circuit.barrier() circuit.y(0) circuit.x(1) circuit.barrier(label="End Y/X") fname = "barrier_label.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_if_op(self): """Test the IfElseOp with if only""" qr = QuantumRegister(4, "q") cr = ClassicalRegister(2, "cr") circuit = QuantumCircuit(qr, cr) with circuit.if_test((cr[1], 1)): circuit.h(0) circuit.cx(0, 1) fname = "if_op.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_if_else_op(self): """Test the IfElseOp with else""" qr = QuantumRegister(4, "q") cr = ClassicalRegister(2, "cr") circuit = QuantumCircuit(qr, cr) with circuit.if_test((cr[1], 1)) as _else: circuit.h(0) circuit.cx(0, 1) with _else: circuit.cx(0, 1) fname = "if_else_op.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_if_else_op_textbook_style(self): """Test the IfElseOp with else in textbook style""" qr = QuantumRegister(4, "q") cr = ClassicalRegister(2, "cr") circuit = QuantumCircuit(qr, cr) with circuit.if_test((cr[1], 1)) as _else: circuit.h(0) circuit.cx(0, 1) with _else: circuit.cx(0, 1) fname = "if_else_op_textbook.png" self.circuit_drawer(circuit, style="textbook", filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_if_else_with_body(self): """Test the IfElseOp with adding a body manually""" qr = QuantumRegister(4, "q") cr = ClassicalRegister(3, "cr") circuit = QuantumCircuit(qr, cr) circuit.h(0) circuit.h(1) circuit.measure(0, 1) circuit.measure(1, 2) circuit.x(2) circuit.x(2, label="XLabel").c_if(cr, 2) qr2 = QuantumRegister(3, "qr2") qc2 = QuantumCircuit(qr2, cr) qc2.x(1) qc2.y(1) qc2.z(0) qc2.x(0, label="X1i").c_if(cr, 4) circuit.if_else((cr[1], 1), qc2, None, [0, 1, 2], [0, 1, 2]) circuit.x(0, label="X1i") fname = "if_else_body.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_if_else_op_nested(self): """Test the IfElseOp with complex nested if/else""" qr = QuantumRegister(4, "q") cr = ClassicalRegister(3, "cr") circuit = QuantumCircuit(qr, cr) circuit.h(0) with circuit.if_test((cr[1], 1)) as _else: circuit.x(0, label="X c_if").c_if(cr, 4) with circuit.if_test((cr[2], 1)): circuit.z(0) circuit.y(1) with circuit.if_test((cr[1], 1)): circuit.y(1) circuit.z(2) with circuit.if_test((cr[2], 1)): circuit.cx(0, 1) with circuit.if_test((cr[1], 1)): circuit.h(0) circuit.x(1) with _else: circuit.y(1) with circuit.if_test((cr[2], 1)): circuit.x(0) circuit.x(1) inst = QuantumCircuit(2, 2, name="Inst").to_instruction() circuit.append(inst, [qr[0], qr[1]], [cr[0], cr[1]]) circuit.x(0) fname = "if_else_op_nested.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_if_else_op_wire_order(self): """Test the IfElseOp with complex nested if/else and wire_order""" qr = QuantumRegister(4, "q") cr = ClassicalRegister(3, "cr") circuit = QuantumCircuit(qr, cr) circuit.h(0) with circuit.if_test((cr[1], 1)) as _else: circuit.x(0, label="X c_if").c_if(cr, 4) with circuit.if_test((cr[2], 1)): circuit.z(0) circuit.y(1) with circuit.if_test((cr[1], 1)): circuit.y(1) circuit.z(2) with circuit.if_test((cr[2], 1)): circuit.cx(0, 1) with circuit.if_test((cr[1], 1)): circuit.h(0) circuit.x(1) with _else: circuit.y(1) with circuit.if_test((cr[2], 1)): circuit.x(0) circuit.x(1) inst = QuantumCircuit(2, 2, name="Inst").to_instruction() circuit.append(inst, [qr[0], qr[1]], [cr[0], cr[1]]) circuit.x(0) fname = "if_else_op_wire_order.png" self.circuit_drawer(circuit, wire_order=[2, 0, 3, 1, 4, 5, 6], filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_if_else_op_fold(self): """Test the IfElseOp with complex nested if/else and fold""" qr = QuantumRegister(4, "q") cr = ClassicalRegister(3, "cr") circuit = QuantumCircuit(qr, cr) circuit.h(0) with circuit.if_test((cr[1], 1)) as _else: circuit.x(0, label="X c_if").c_if(cr, 4) with circuit.if_test((cr[2], 1)): circuit.z(0) circuit.y(1) with circuit.if_test((cr[1], 1)): circuit.y(1) circuit.z(2) with circuit.if_test((cr[2], 1)): circuit.cx(0, 1) with circuit.if_test((cr[1], 1)): circuit.h(0) circuit.x(1) with _else: circuit.y(1) with circuit.if_test((cr[2], 1)): circuit.x(0) circuit.x(1) inst = QuantumCircuit(2, 2, name="Inst").to_instruction() circuit.append(inst, [qr[0], qr[1]], [cr[0], cr[1]]) circuit.x(0) fname = "if_else_op_fold.png" self.circuit_drawer(circuit, fold=7, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_while_loop_op(self): """Test the WhileLoopOp""" qr = QuantumRegister(4, "q") cr = ClassicalRegister(3, "cr") circuit = QuantumCircuit(qr, cr) circuit.h(0) circuit.measure(0, 2) with circuit.while_loop((cr[0], 0)): circuit.h(0) circuit.cx(0, 1) circuit.measure(0, 0) with circuit.if_test((cr[2], 1)): circuit.x(0) fname = "while_loop.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_for_loop_op(self): """Test the ForLoopOp""" qr = QuantumRegister(4, "q") cr = ClassicalRegister(3, "cr") circuit = QuantumCircuit(qr, cr) a = Parameter("a") circuit.h(0) circuit.measure(0, 2) with circuit.for_loop((2, 4, 8, 16), loop_parameter=a): circuit.h(0) circuit.cx(0, 1) circuit.rx(pi / a, 1) circuit.measure(0, 0) with circuit.if_test((cr[2], 1)): circuit.z(0) fname = "for_loop.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_switch_case_op(self): """Test the SwitchCaseOp""" qreg = QuantumRegister(3, "q") creg = ClassicalRegister(3, "cr") circuit = QuantumCircuit(qreg, creg) circuit.h([0, 1, 2]) circuit.measure([0, 1, 2], [0, 1, 2]) with circuit.switch(creg) as case: with case(0, 1, 2): circuit.x(0) with case(3, 4, 5): circuit.y(1) circuit.y(0) circuit.y(0) with case(case.DEFAULT): circuit.cx(0, 1) circuit.h(0) fname = "switch_case.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) if __name__ == "__main__": unittest.main(verbosity=1)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for graph MPL drawer""" import unittest import os from test.visual import VisualTestUtilities from contextlib import contextmanager from pathlib import Path from qiskit import BasicAer, execute from qiskit.test import QiskitTestCase from qiskit import QuantumCircuit from qiskit.utils import optionals from qiskit.visualization.state_visualization import state_drawer from qiskit.visualization.counts_visualization import plot_histogram from qiskit.visualization.gate_map import plot_gate_map, plot_coupling_map from qiskit.providers.fake_provider import ( FakeArmonk, FakeBelem, FakeCasablanca, FakeRueschlikon, FakeMumbai, FakeManhattan, ) if optionals.HAS_MATPLOTLIB: from matplotlib.pyplot import close as mpl_close else: raise ImportError('Must have Matplotlib installed. To install, run "pip install matplotlib".') BASE_DIR = Path(__file__).parent RESULT_DIR = Path(BASE_DIR) / "graph_results" TEST_REFERENCE_DIR = Path(BASE_DIR) / "references" FAILURE_DIFF_DIR = Path(BASE_DIR).parent / "visual_test_failures" FAILURE_PREFIX = "graph_failure_" @contextmanager def cwd(path): """A context manager to run in a particular path""" oldpwd = os.getcwd() os.chdir(path) try: yield finally: os.chdir(oldpwd) class TestGraphMatplotlibDrawer(QiskitTestCase): """Graph MPL visualization""" def setUp(self): super().setUp() self.graph_state_drawer = VisualTestUtilities.save_data_wrap( state_drawer, str(self), RESULT_DIR ) self.graph_count_drawer = VisualTestUtilities.save_data_wrap( plot_histogram, str(self), RESULT_DIR ) self.graph_plot_gate_map = VisualTestUtilities.save_data_wrap( plot_gate_map, str(self), RESULT_DIR ) self.graph_plot_coupling_map = VisualTestUtilities.save_data_wrap( plot_coupling_map, str(self), RESULT_DIR ) if not os.path.exists(FAILURE_DIFF_DIR): os.makedirs(FAILURE_DIFF_DIR) if not os.path.exists(RESULT_DIR): os.makedirs(RESULT_DIR) def tearDown(self): super().tearDown() mpl_close("all") @staticmethod def _image_path(image_name): return os.path.join(RESULT_DIR, image_name) @staticmethod def _reference_path(image_name): return os.path.join(TEST_REFERENCE_DIR, image_name) def test_plot_bloch_multivector(self): """test bloch sphere See https://github.com/Qiskit/qiskit-terra/issues/6397. """ circuit = QuantumCircuit(1) circuit.h(0) # getting the state using backend backend = BasicAer.get_backend("statevector_simulator") result = execute(circuit, backend).result() state = result.get_statevector(circuit) fname = "bloch_multivector.png" self.graph_state_drawer(state=state, output="bloch", filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_state_hinton(self): """test plot_state_hinton""" circuit = QuantumCircuit(1) circuit.x(0) # getting the state using backend backend = BasicAer.get_backend("statevector_simulator") result = execute(circuit, backend).result() state = result.get_statevector(circuit) fname = "hinton.png" self.graph_state_drawer(state=state, output="hinton", filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_state_qsphere(self): """test for plot_state_qsphere""" circuit = QuantumCircuit(1) circuit.x(0) # getting the state using backend backend = BasicAer.get_backend("statevector_simulator") result = execute(circuit, backend).result() state = result.get_statevector(circuit) fname = "qsphere.png" self.graph_state_drawer(state=state, output="qsphere", filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_state_city(self): """test for plot_state_city""" circuit = QuantumCircuit(1) circuit.x(0) # getting the state using backend backend = BasicAer.get_backend("statevector_simulator") result = execute(circuit, backend).result() state = result.get_statevector(circuit) fname = "state_city.png" self.graph_state_drawer(state=state, output="city", filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_state_paulivec(self): """test for plot_state_paulivec""" circuit = QuantumCircuit(1) circuit.x(0) # getting the state using backend backend = BasicAer.get_backend("statevector_simulator") result = execute(circuit, backend).result() state = result.get_statevector(circuit) fname = "paulivec.png" self.graph_state_drawer(state=state, output="paulivec", filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_histogram(self): """for testing the plot_histogram""" # specifing counts because we do not want oscillation of # result until a changes is made to plot_histogram counts = {"11": 500, "00": 500} fname = "histogram.png" self.graph_count_drawer(counts, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_histogram_with_rest(self): """test plot_histogram with 2 datasets and number_to_keep""" data = [{"00": 3, "01": 5, "10": 6, "11": 12}] fname = "histogram_with_rest.png" self.graph_count_drawer(data, number_to_keep=2, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_histogram_2_sets_with_rest(self): """test plot_histogram with 2 datasets and number_to_keep""" data = [ {"00": 3, "01": 5, "10": 6, "11": 12}, {"00": 5, "01": 7, "10": 6, "11": 12}, ] fname = "histogram_2_sets_with_rest.png" self.graph_count_drawer(data, number_to_keep=2, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_histogram_color(self): """Test histogram with single color""" counts = {"00": 500, "11": 500} fname = "histogram_color.png" self.graph_count_drawer(data=counts, color="#204940", filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_histogram_multiple_colors(self): """Test histogram with multiple custom colors""" counts = [ {"00": 10, "01": 15, "10": 20, "11": 25}, {"00": 25, "01": 20, "10": 15, "11": 10}, ] fname = "histogram_multiple_colors.png" self.graph_count_drawer( data=counts, color=["#204940", "#c26219"], filename=fname, ) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_histogram_hamming(self): """Test histogram with hamming distance""" counts = {"101": 500, "010": 500, "001": 500, "100": 500} fname = "histogram_hamming.png" self.graph_count_drawer(data=counts, sort="hamming", target_string="101", filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_histogram_value_sort(self): """Test histogram with sorting by value""" counts = {"101": 300, "010": 240, "001": 80, "100": 150, "110": 160, "000": 280, "111": 60} fname = "histogram_value_sort.png" self.graph_count_drawer(data=counts, sort="value", target_string="000", filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_histogram_desc_value_sort(self): """Test histogram with sorting by descending value""" counts = {"101": 150, "010": 50, "001": 180, "100": 10, "110": 190, "000": 80, "111": 260} fname = "histogram_desc_value_sort.png" self.graph_count_drawer( data=counts, sort="value_desc", target_string="000", filename=fname, ) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_histogram_legend(self): """Test histogram with legend""" counts = [{"0": 50, "1": 30}, {"0": 30, "1": 40}] fname = "histogram_legend.png" self.graph_count_drawer( data=counts, legend=["first", "second"], filename=fname, figsize=(15, 5), ) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_histogram_title(self): """Test histogram with title""" counts = [{"0": 50, "1": 30}, {"0": 30, "1": 40}] fname = "histogram_title.png" self.graph_count_drawer(data=counts, title="My Histogram", filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_1_qubit_gate_map(self): """Test plot_gate_map using 1 qubit backend""" # getting the mock backend from FakeProvider backend = FakeArmonk() fname = "1_qubit_gate_map.png" self.graph_plot_gate_map(backend=backend, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_5_qubit_gate_map(self): """Test plot_gate_map using 5 qubit backend""" # getting the mock backend from FakeProvider backend = FakeBelem() fname = "5_qubit_gate_map.png" self.graph_plot_gate_map(backend=backend, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_7_qubit_gate_map(self): """Test plot_gate_map using 7 qubit backend""" # getting the mock backend from FakeProvider backend = FakeCasablanca() fname = "7_qubit_gate_map.png" self.graph_plot_gate_map(backend=backend, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_16_qubit_gate_map(self): """Test plot_gate_map using 16 qubit backend""" # getting the mock backend from FakeProvider backend = FakeRueschlikon() fname = "16_qubit_gate_map.png" self.graph_plot_gate_map(backend=backend, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_27_qubit_gate_map(self): """Test plot_gate_map using 27 qubit backend""" # getting the mock backend from FakeProvider backend = FakeMumbai() fname = "27_qubit_gate_map.png" self.graph_plot_gate_map(backend=backend, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_65_qubit_gate_map(self): """test for plot_gate_map using 65 qubit backend""" # getting the mock backend from FakeProvider backend = FakeManhattan() fname = "65_qubit_gate_map.png" self.graph_plot_gate_map(backend=backend, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_figsize(self): """Test figsize parameter of plot_gate_map""" # getting the mock backend from FakeProvider backend = FakeBelem() fname = "figsize.png" self.graph_plot_gate_map(backend=backend, figsize=(10, 10), filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_qubit_size(self): """Test qubit_size parameter of plot_gate_map""" # getting the mock backend from FakeProvider backend = FakeBelem() fname = "qubit_size.png" self.graph_plot_gate_map(backend=backend, qubit_size=38, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_qubit_color(self): """Test qubit_color parameter of plot_gate_map""" # getting the mock backend from FakeProvider backend = FakeCasablanca() fname = "qubit_color.png" self.graph_plot_gate_map(backend=backend, qubit_color=["#ff0000"] * 7, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_qubit_labels(self): """Test qubit_labels parameter of plot_gate_map""" # getting the mock backend from FakeProvider backend = FakeCasablanca() fname = "qubit_labels.png" self.graph_plot_gate_map( backend=backend, qubit_labels=list(range(10, 17, 1)), filename=fname ) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_line_color(self): """Test line_color parameter of plot_gate_map""" # getting the mock backend from FakeProvider backend = FakeManhattan() fname = "line_color.png" self.graph_plot_gate_map(backend=backend, line_color=["#00ff00"] * 144, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_font_color(self): """Test font_color parameter of plot_gate_map""" # getting the mock backend from FakeProvider backend = FakeManhattan() fname = "font_color.png" self.graph_plot_gate_map(backend=backend, font_color="#ff00ff", filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_coupling_map(self): """Test plot_coupling_map""" num_qubits = 5 qubit_coordinates = [[1, 0], [0, 1], [1, 1], [1, 2], [2, 1]] coupling_map = [[1, 0], [1, 2], [1, 3], [3, 4]] fname = "coupling_map.png" self.graph_plot_coupling_map( num_qubits=num_qubits, qubit_coordinates=qubit_coordinates, coupling_map=coupling_map, filename=fname, ) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_bloch_multivector_figsize_improvements(self): """test bloch sphere figsize, font_size, title_font_size and title_pad See https://github.com/Qiskit/qiskit-terra/issues/7263 and https://github.com/Qiskit/qiskit-terra/pull/7264. """ circuit = QuantumCircuit(3) circuit.h(1) circuit.sxdg(2) # getting the state using backend backend = BasicAer.get_backend("statevector_simulator") result = execute(circuit, backend).result() state = result.get_statevector(circuit) fname = "bloch_multivector_figsize_improvements.png" self.graph_state_drawer( state=state, output="bloch", figsize=(3, 2), font_size=10, title="|0+R> state", title_font_size=14, title_pad=8, filename=fname, ) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) if __name__ == "__main__": unittest.main(verbosity=1)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Determines a commutation library over the unparameterizable standard gates, i.e. a dictionary for each pair of parameterizable standard gates and all qubit overlaps that maps to either True or False, depending on the present commutation relation. """ import itertools from functools import lru_cache from typing import List from qiskit.circuit.commutation_checker import _get_relative_placement, _order_operations from qiskit.circuit import Gate, CommutationChecker import qiskit.circuit.library.standard_gates as stdg from qiskit.dagcircuit import DAGOpNode @lru_cache(None) def _get_unparameterizable_gates() -> List[Gate]: """Retrieve a list of non-parmaterized gates with up to 3 qubits, using the python inspection module Return: A list of non-parameterized gates to be considered in the commutation library """ # These two gates may require a large runtime in later processing steps # blocked_types = [C3SXGate, C4XGate] gates = list(stdg.get_standard_gate_name_mapping().values()) return [g for g in gates if len(g.params) == 0] def _generate_commutation_dict(considered_gates: List[Gate] = None) -> dict: """Compute the commutation relation of considered gates Args: considered_gates List[Gate]: a list of gates between which the commutation should be determined Return: A dictionary that includes the commutation relation for each considered pair of operations and each relative placement """ commutations = {} cc = CommutationChecker() for gate0 in considered_gates: node0 = DAGOpNode(op=gate0, qargs=list(range(gate0.num_qubits)), cargs=[]) for gate1 in considered_gates: # only consider canonical entries ( ( first_gate, _, _, ), (second_gate, _, _), ) = _order_operations(gate0, None, None, gate1, None, None) if (first_gate, second_gate) != (gate0, gate1) and gate0.name != gate1.name: continue # enumerate all relative gate placements with overlap between gate qubits gate_placements = itertools.permutations( range(gate0.num_qubits + gate1.num_qubits - 1), gate0.num_qubits ) gate_pair_commutation = {} for permutation in gate_placements: permutation_list = list(permutation) gate1_qargs = [] # use idx_non_overlapping qubits to represent qubits on g1 that are not connected to g0 next_non_overlapping_qubit_idx = gate0.num_qubits for i in range(gate1.num_qubits): if i in permutation_list: gate1_qargs.append(permutation_list.index(i)) else: gate1_qargs.append(next_non_overlapping_qubit_idx) next_non_overlapping_qubit_idx += 1 node1 = DAGOpNode(op=gate1, qargs=gate1_qargs, cargs=[]) # replace non-overlapping qubits with None to act as a key in the commutation library relative_placement = _get_relative_placement(node0.qargs, node1.qargs) if not gate0.is_parameterized() and not gate1.is_parameterized(): # if no gate includes parameters, compute commutation relation using # matrix multiplication op1 = node0.op qargs1 = node0.qargs cargs1 = node0.cargs op2 = node1.op qargs2 = node1.qargs cargs2 = node1.cargs commutation_relation = cc.commute( op1, qargs1, cargs1, op2, qargs2, cargs2, max_num_qubits=4 ) else: pass # TODO gate_pair_commutation[relative_placement] = commutation_relation commutations[gate0.name, gate1.name] = gate_pair_commutation return commutations def _simplify_commuting_dict(commuting_dict: dict) -> dict: """Compress some of the commutation library entries Args: commuting_dict (dict): A commutation dictionary Return: commuting_dict (dict): A commutation dictionary with simplified entries """ # Remove relative placement key if commutation is independent of relative placement for ops in commuting_dict.keys(): gates_commutations = set(commuting_dict[ops].values()) if len(gates_commutations) == 1: commuting_dict[ops] = next(iter(gates_commutations)) return commuting_dict def _dump_commuting_dict_as_python( commutations: dict, file_name: str = "../_standard_gates_commutations.py" ): """Write commutation dictionary as python object to ./qiskit/circuit/_standard_gates_commutations.py. Args: commutations (dict): a dictionary that includes the commutation relation for each considered pair of operations """ with open(file_name, "w") as fp: dir_str = "standard_gates_commutations = {\n" for k, v in commutations.items(): if not isinstance(v, dict): dir_str += ' ("{}", "{}"): {},\n'.format(*k, v) else: dir_str += ' ("{}", "{}"): {{\n'.format(*k) for entry_key, entry_val in v.items(): dir_str += " {}: {},\n".format(entry_key, entry_val) dir_str += " },\n" dir_str += "}\n" fp.write(dir_str.replace("'", "")) if __name__ == "__main__": cgates = [ g for g in _get_unparameterizable_gates() if g.name not in ["reset", "measure", "delay"] ] commutation_dict = _generate_commutation_dict(considered_gates=cgates) commutation_dict = _simplify_commuting_dict(commutation_dict) _dump_commuting_dict_as_python(commutation_dict)
https://github.com/swe-train/qiskit__qiskit
swe-train
#!/usr/bin/env python3 # This code is part of Qiskit. # # (C) Copyright IBM 2021 # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Utility to check that slow imports are not used in the default path.""" import subprocess import sys # This is not unused: importing it sets up sys.modules import qiskit # pylint: disable=unused-import def _main(): optional_imports = [ "networkx", "sympy", "pydot", "pygments", "ipywidgets", "scipy.stats", "matplotlib", "qiskit.providers.aer", "qiskit.providers.ibmq", "qiskit.ignis", "qiskit.aqua", "docplex", ] modules_imported = [] for mod in optional_imports: if mod in sys.modules: modules_imported.append(mod) if not modules_imported: sys.exit(0) res = subprocess.run( [sys.executable, "-X", "importtime", "-c", "import qiskit"], capture_output=True, encoding="utf8", check=True, ) import_tree = [ x.split("|")[-1] for x in res.stderr.split("\n") if "RuntimeWarning" not in x or "warnings.warn" not in x ] indent = -1 matched_module = None for module in import_tree: line_indent = len(module) - len(module.lstrip()) module_name = module.strip() if module_name in modules_imported: if indent > 0: continue indent = line_indent matched_module = module_name if indent > 0: if line_indent < indent: print(f"ERROR: {matched_module} is imported via {module_name}") indent = -1 matched_module = None sys.exit(len(modules_imported)) if __name__ == "__main__": _main()
https://github.com/swe-train/qiskit__qiskit
swe-train
#!/usr/bin/env python3 # This code is part of Qiskit. # # (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. """Script to generate 'utility scale' load for profiling in a PGO context""" import os from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit.providers.fake_provider import GenericBackendV2 from qiskit.transpiler import CouplingMap from qiskit import qasm2 QASM_DIR = os.path.join( os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "test", "benchmarks", "qasm", ) def _main(): cmap = CouplingMap.from_heavy_hex(9) cz_backend = GenericBackendV2( cmap.size(), ["rz", "x", "sx", "cz", "id"], coupling_map=cmap, control_flow=True, seed=12345678942, ) ecr_backend = GenericBackendV2( cmap.size(), ["rz", "x", "sx", "ecr", "id"], coupling_map=cmap, control_flow=True, seed=12345678942, ) cx_backend = GenericBackendV2( cmap.size(), ["rz", "x", "sx", "cx", "id"], coupling_map=cmap, control_flow=True, seed=12345678942, ) cz_pm = generate_preset_pass_manager(2, cz_backend) ecr_pm = generate_preset_pass_manager(2, ecr_backend) cx_pm = generate_preset_pass_manager(2, cx_backend) qft_circ = qasm2.load( os.path.join(QASM_DIR, "qft_N100.qasm"), include_path=qasm2.LEGACY_INCLUDE_PATH, custom_instructions=qasm2.LEGACY_CUSTOM_INSTRUCTIONS, custom_classical=qasm2.LEGACY_CUSTOM_CLASSICAL, strict=False, ) qft_circ.name = "qft_N100" square_heisenberg_circ = qasm2.load( os.path.join(QASM_DIR, "square_heisenberg_N100.qasm"), include_path=qasm2.LEGACY_INCLUDE_PATH, custom_instructions=qasm2.LEGACY_CUSTOM_INSTRUCTIONS, custom_classical=qasm2.LEGACY_CUSTOM_CLASSICAL, strict=False, ) square_heisenberg_circ.name = "square_heisenberg_N100" qaoa_circ = qasm2.load( os.path.join(QASM_DIR, "qaoa_barabasi_albert_N100_3reps.qasm"), include_path=qasm2.LEGACY_INCLUDE_PATH, custom_instructions=qasm2.LEGACY_CUSTOM_INSTRUCTIONS, custom_classical=qasm2.LEGACY_CUSTOM_CLASSICAL, strict=False, ) qaoa_circ.name = "qaoa_barabasi_albert_N100_3reps" # Uncomment when this is fast enough to run during release builds # qv_circ = QuantumVolume(100, seed=123456789) # qv_circ.measure_all() # qv_circ.name = "QV1267650600228229401496703205376" for pm in [cz_pm, ecr_pm, cx_pm]: for circ in [qft_circ, square_heisenberg_circ, qaoa_circ]: print(f"Compiling: {circ.name}") pm.run(circ) if __name__ == "__main__": _main()
https://github.com/IBMSystemsCenterMontpellier/Qiskit-Tips-and-Tricks
IBMSystemsCenterMontpellier
# Set up imports, IBMQ account, and backend from qiskit import QuantumCircuit, execute, IBMQ IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') backend = provider.get_backend('ibmq_qasm_simulator') # Create 2 circuits circuit_1 = QuantumCircuit(2, 2) circuit_1.h(0) circuit_1.cx(0, 1) circuit_1.measure([0, 1], [0, 1]) circuit_2 = QuantumCircuit(2, 2) circuit_2.h(1) circuit_2.cx(1, 0) circuit_2.measure([0, 1], [0, 1]) # Submit a job for each circuit job_1 = execute(circuit_1, backend) job_2 = execute(circuit_2, backend) print("Job 1: {}".format(job_1.result().get_counts(circuit_1))) print("Job 2: {}".format(job_2.result().get_counts(circuit_2))) # Set up imports, IBMQ account, and backend from qiskit import QuantumCircuit, execute, IBMQ IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') backend = provider.get_backend('ibmq_qasm_simulator') circuit_list = [] # This will be what we send with our job # Create 2 circuits circuit_1 = QuantumCircuit(2, 2) circuit_1.h(0) circuit_1.cx(0, 1) circuit_1.measure([0, 1], [0, 1]) circuit_2 = QuantumCircuit(2, 2) circuit_2.h(1) circuit_2.cx(1, 0) circuit_2.measure([0, 1], [0, 1]) # Add both circuits to the list circuit_list.append(circuit_1) circuit_list.append(circuit_2) # Submit a single job that contains both circuits job = execute(circuit_list, backend) results = job.result() # Option 1: Use the circuit name circuit_1_counts = results.get_counts(circuit_1) circuit_2_counts = results.get_counts(circuit_2) print("Circuit 1 using circuit name: {}".format(circuit_1_counts)) print("Circuit 2 using circuit name: {}".format(circuit_2_counts)) # Option 2: Use the list index circuit_1_counts = results.get_counts(circuit_list[0]) circuit_2_counts = results.get_counts(circuit_list[1]) print("Circuit 1 using list index: {}".format(circuit_1_counts)) print("Circuit 2 using list index: {}".format(circuit_2_counts)) import time circuit_list = [] total_time_taken_individual = 0 # This will be the total runtime for the individual job method total_execution_time_individual = 0 # This will be the total execution time for the individual job method for __ in range(5): # Create a new circuit qc = QuantumCircuit(2, 2) qc.h(0) qc.cx(0, 1) qc.measure([0, 1], [0, 1]) # Add the circuit to circuit_list circuit_list.append(qc) # Execute the circuit in its own individual job and get total time taken start_time = time.time() job_individual = execute(qc, backend) if job_individual.result(): # Once job has finished executing get end time end_time = time.time() total_time_taken_individual += (end_time - start_time) # Retrieve time_taken executing and add to total time taken total_execution_time_individual += job_individual.result().time_taken # Create single job and execute, and get total time taken start_time = time.time() job_bundled = execute(circuit_list, backend) if job_bundled.result(): # Once job has finished executing get end time end_time = time.time() total_time_taken_bundled = (end_time - start_time) total_execution_time_bundled = job_bundled.result().time_taken # Compare execution time and total time taken between the two methods. Round to 5 decimal places. print("Total execution time with individual jobs: {} seconds".format(round(total_execution_time_individual, 5))) print("Total execution time with a single job: {} seconds".format(round(total_execution_time_bundled, 5))) print("Total time taken with individual jobs: {} seconds".format(round(total_time_taken_individual, 5))) print("Total time taken with a single job: {} seconds".format(round(total_time_taken_bundled, 5)))
https://github.com/mistryiam/IBM-Qiskit-Machine-Learning
mistryiam
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, assemble, Aer, IBMQ, execute from qiskit.quantum_info import Statevector from qiskit.visualization import plot_bloch_multivector, plot_histogram from qiskit_textbook.problems import dj_problem_oracle def lab1_ex1(): qc = QuantumCircuit(1) # # # FILL YOUR CODE IN HERE # # qc.x(0) return qc state = Statevector.from_instruction(lab1_ex1()) plot_bloch_multivector(state) from qc_grader import grade_lab1_ex1 # Note that the grading function is expecting a quantum circuit without measurements grade_lab1_ex1(lab1_ex1()) def lab1_ex2(): qc = QuantumCircuit(1) # # # FILL YOUR CODE IN HERE # # qc.h(0) return qc state = Statevector.from_instruction(lab1_ex2()) plot_bloch_multivector(state) from qc_grader import grade_lab1_ex2 # Note that the grading function is expecting a quantum circuit without measurements grade_lab1_ex2(lab1_ex2()) def lab1_ex3(): qc = QuantumCircuit(1) # # # FILL YOUR CODE IN HERE # # qc.x(0) qc.h(0) return qc state = Statevector.from_instruction(lab1_ex3()) plot_bloch_multivector(state) from qc_grader import grade_lab1_ex3 # Note that the grading function is expecting a quantum circuit without measurements grade_lab1_ex3(lab1_ex3()) def lab1_ex4(): qc = QuantumCircuit(1) # # # FILL YOUR CODE IN HERE # # qc.h(0) qc.sdg(0) return qc state = Statevector.from_instruction(lab1_ex4()) plot_bloch_multivector(state) from qc_grader import grade_lab1_ex4 # Note that the grading function is expecting a quantum circuit without measurements grade_lab1_ex4(lab1_ex4()) def lab1_ex5(): qc = QuantumCircuit(2,2) # this time, we not only want two qubits, but also two classical bits for the measurement # # # FILL YOUR CODE IN HERE # # qc.h(0) qc.cx(0,1) qc.x(0) return qc qc = lab1_ex5() qc.draw() # we draw the circuit from qc_grader import grade_lab1_ex5 # Note that the grading function is expecting a quantum circuit without measurements grade_lab1_ex5(lab1_ex5()) qc.measure(0, 0) # we perform a measurement on qubit q_0 and store the information on the classical bit c_0 qc.measure(1, 1) # we perform a measurement on qubit q_1 and store the information on the classical bit c_1 backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend counts = execute(qc, backend, shots = 1000).result().get_counts() # we run the simulation and get the counts plot_histogram(counts) # let us plot a histogram to see the possible outcomes and corresponding probabilities def lab1_ex6(): # # # FILL YOUR CODE IN HERE # # qc = QuantumCircuit(3,3) qc.h(0) qc.cx(0,1) qc.cx(1,2) qc.y(1) return qc qc = lab1_ex6() qc.draw() # we draw the circuit from qc_grader import grade_lab1_ex6 # Note that the grading function is expecting a quantum circuit without measurements grade_lab1_ex6(lab1_ex6()) oraclenr = 4 # determines the oracle (can range from 1 to 5) oracle = dj_problem_oracle(oraclenr) # gives one out of 5 oracles oracle.name = "DJ-Oracle" def dj_classical(n, input_str): # build a quantum circuit with n qubits and 1 classical readout bit dj_circuit = QuantumCircuit(n+1,1) # Prepare the initial state corresponding to your input bit string for i in range(n): if input_str[i] == '1': dj_circuit.x(i) # append oracle dj_circuit.append(oracle, range(n+1)) # measure the fourth qubit dj_circuit.measure(n,0) return dj_circuit n = 4 # number of qubits input_str = '1111' dj_circuit = dj_classical(n, input_str) dj_circuit.draw() # draw the circuit input_str = '1111' dj_circuit = dj_classical(n, input_str) qasm_sim = Aer.get_backend('qasm_simulator') transpiled_dj_circuit = transpile(dj_circuit, qasm_sim) qobj = assemble(transpiled_dj_circuit, qasm_sim) results = qasm_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer) def lab1_ex7(): min_nr_inputs = 2 max_nr_inputs = 9 return [min_nr_inputs, max_nr_inputs] from qc_grader import grade_lab1_ex7 # Note that the grading function is expecting a list of two integers grade_lab1_ex7(lab1_ex7()) n=4 def psi_0(n): qc = QuantumCircuit(n+1,n) # Build the state (|00000> - |10000>)/sqrt(2) # # # FILL YOUR CODE IN HERE # # qc.x(4) qc.h(4) return qc dj_circuit = psi_0(n) dj_circuit.draw() def psi_1(n): # obtain the |psi_0> = |00001> state qc = psi_0(n) # create the superposition state |psi_1> # # qc.h(0) qc.h(1) qc.h(2) qc.h(3) # # qc.barrier() return qc dj_circuit = psi_1(n) dj_circuit.draw() def psi_2(oracle,n): # circuit to obtain psi_1 qc = psi_1(n) # append the oracle qc.append(oracle, range(n+1)) return qc dj_circuit = psi_2(oracle, n) dj_circuit.draw() def lab1_ex8(oracle, n): # note that this exercise also depends on the code in the functions psi_0 (In [24]) and psi_1 (In [25]) qc = psi_2(oracle, n) # apply n-fold hadamard gate # # # FILL YOUR CODE IN HERE # # qc.h(0) qc.h(1) qc.h(2) qc.h(3) # add the measurement by connecting qubits to classical bits # # qc.measure(0,0) qc.measure(1,1) qc.measure(2,2) qc.measure(3,3) # # return qc dj_circuit = lab1_ex8(oracle, n) dj_circuit.draw() from qc_grader import grade_lab1_ex8 # Note that the grading function is expecting a quantum circuit with measurements grade_lab1_ex8(lab1_ex8(dj_problem_oracle(4),n)) qasm_sim = Aer.get_backend('qasm_simulator') transpiled_dj_circuit = transpile(dj_circuit, qasm_sim) qobj = assemble(transpiled_dj_circuit) results = qasm_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer)
https://github.com/mistryiam/IBM-Qiskit-Machine-Learning
mistryiam
import networkx as nx import numpy as np import plotly.graph_objects as go import matplotlib as mpl import pandas as pd from IPython.display import clear_output from plotly.subplots import make_subplots from matplotlib import pyplot as plt from qiskit import Aer from qiskit import QuantumCircuit from qiskit.visualization import plot_state_city from qiskit.algorithms.optimizers import COBYLA, SLSQP, ADAM from time import time from copy import copy from typing import List from qc_grader.graph_util import display_maxcut_widget, QAOA_widget, graphs mpl.rcParams['figure.dpi'] = 300 from qiskit.circuit import Parameter, ParameterVector #Parameters are initialized with a simple string identifier parameter_0 = Parameter('ΞΈ[0]') parameter_1 = Parameter('ΞΈ[1]') circuit = QuantumCircuit(1) #We can then pass the initialized parameters as the rotation angle argument to the Rx and Ry gates circuit.ry(theta = parameter_0, qubit = 0) circuit.rx(theta = parameter_1, qubit = 0) circuit.draw('mpl') parameter = Parameter('ΞΈ') circuit = QuantumCircuit(1) circuit.ry(theta = parameter, qubit = 0) circuit.rx(theta = parameter, qubit = 0) circuit.draw('mpl') #Set the number of layers and qubits n=3 num_layers = 2 #ParameterVectors are initialized with a string identifier and an integer specifying the vector length parameters = ParameterVector('ΞΈ', n*(num_layers+1)) circuit = QuantumCircuit(n, n) for layer in range(num_layers): #Appending the parameterized Ry gates using parameters from the vector constructed above for i in range(n): circuit.ry(parameters[n*layer+i], i) circuit.barrier() #Appending the entangling CNOT gates for i in range(n): for j in range(i): circuit.cx(j,i) circuit.barrier() #Appending one additional layer of parameterized Ry gates for i in range(n): circuit.ry(parameters[n*num_layers+i], i) circuit.barrier() circuit.draw('mpl') print(circuit.parameters) #Create parameter dictionary with random values to bind param_dict = {parameter: np.random.random() for parameter in parameters} print(param_dict) #Assign parameters using the assign_parameters method bound_circuit = circuit.assign_parameters(parameters = param_dict) bound_circuit.draw('mpl') new_parameters = ParameterVector('Ξ¨',9) new_circuit = circuit.assign_parameters(parameters = [k*new_parameters[i] for k in range(9)]) new_circuit.draw('mpl') #Run the circuit with assigned parameters on Aer's statevector simulator simulator = Aer.get_backend('statevector_simulator') result = simulator.run(bound_circuit).result() statevector = result.get_statevector(bound_circuit) plot_state_city(statevector) #The following line produces an error when run because 'circuit' still contains non-assigned parameters #result = simulator.run(circuit).result() for key in graphs.keys(): print(key) graph = nx.Graph() #Add nodes and edges graph.add_nodes_from(np.arange(0,6,1)) edges = [(0,1,2.0),(0,2,3.0),(0,3,2.0),(0,4,4.0),(0,5,1.0),(1,2,4.0),(1,3,1.0),(1,4,1.0),(1,5,3.0),(2,4,2.0),(2,5,3.0),(3,4,5.0),(3,5,1.0)] graph.add_weighted_edges_from(edges) graphs['custom'] = graph #Display widget display_maxcut_widget(graphs['custom']) def maxcut_cost_fn(graph: nx.Graph, bitstring: List[int]) -> float: """ Computes the maxcut cost function value for a given graph and cut represented by some bitstring Args: graph: The graph to compute cut values for bitstring: A list of integer values '0' or '1' specifying a cut of the graph Returns: The value of the cut """ #Get the weight matrix of the graph weight_matrix = nx.adjacency_matrix(graph).toarray() size = weight_matrix.shape[0] value = 0. #INSERT YOUR CODE TO COMPUTE THE CUT VALUE HERE for i in range(size): for j in range(size): value+= weight_matrix[i,j]*bitstring[i]*(1-bitstring[j]) return value def plot_maxcut_histogram(graph: nx.Graph) -> None: """ Plots a bar diagram with the values for all possible cuts of a given graph. Args: graph: The graph to compute cut values for """ num_vars = graph.number_of_nodes() #Create list of bitstrings and corresponding cut values bitstrings = ['{:b}'.format(i).rjust(num_vars, '0')[::-1] for i in range(2**num_vars)] values = [maxcut_cost_fn(graph = graph, bitstring = [int(x) for x in bitstring]) for bitstring in bitstrings] #Sort both lists by largest cut value values, bitstrings = zip(*sorted(zip(values, bitstrings))) #Plot bar diagram bar_plot = go.Bar(x = bitstrings, y = values, marker=dict(color=values, colorscale = 'plasma', colorbar=dict(title='Cut Value'))) fig = go.Figure(data=bar_plot, layout = dict(xaxis=dict(type = 'category'), width = 1500, height = 600)) fig.show() plot_maxcut_histogram(graph = graphs['custom']) from qc_grader import grade_lab2_ex1 bitstring = [1, 0, 1, 1, 0, 0] #DEFINE THE CORRECT MAXCUT BITSTRING HERE # Note that the grading function is expecting a list of integers '0' and '1' grade_lab2_ex1(bitstring) from qiskit_optimization import QuadraticProgram quadratic_program = QuadraticProgram('sample_problem') print(quadratic_program.export_as_lp_string()) quadratic_program.binary_var(name = 'x_0') quadratic_program.integer_var(name = 'x_1') quadratic_program.continuous_var(name = 'x_2', lowerbound = -2.5, upperbound = 1.8) quadratic = [[0,1,2],[3,4,5],[0,1,2]] linear = [10,20,30] quadratic_program.minimize(quadratic = quadratic, linear = linear, constant = -5) print(quadratic_program.export_as_lp_string()) def quadratic_program_from_graph(graph: nx.Graph) -> QuadraticProgram: """Constructs a quadratic program from a given graph for a MaxCut problem instance. Args: graph: Underlying graph of the problem. Returns: QuadraticProgram """ #Get weight matrix of graph weight_matrix = nx.adjacency_matrix(graph) shape = weight_matrix.shape size = shape[0] #Build qubo matrix Q from weight matrix W qubo_matrix = np.zeros((size, size)) qubo_vector = np.zeros(size) for i in range(size): for j in range(size): qubo_matrix[i, j] -= weight_matrix[i, j] for i in range(size): for j in range(size): qubo_vector[i] += weight_matrix[i,j] #INSERT YOUR CODE HERE quadratic_program=QuadraticProgram('sample_problem') for i in range(size): quadratic_program.binary_var(name='x_{}'.format(i)) quadratic_program.maximize(quadratic =qubo_matrix, linear = qubo_vector) return quadratic_program quadratic_program = quadratic_program_from_graph(graphs['custom']) print(quadratic_program.export_as_lp_string()) from qc_grader import grade_lab2_ex2 # Note that the grading function is expecting a quadratic program grade_lab2_ex2(quadratic_program) def qaoa_circuit(qubo: QuadraticProgram, p: int = 1): """ Given a QUBO instance and the number of layers p, constructs the corresponding parameterized QAOA circuit with p layers. Args: qubo: The quadratic program instance p: The number of layers in the QAOA circuit Returns: The parameterized QAOA circuit """ size = len(qubo.variables) qubo_matrix = qubo.objective.quadratic.to_array(symmetric=True) qubo_linearity = qubo.objective.linear.to_array() #Prepare the quantum and classical registers qaoa_circuit = QuantumCircuit(size,size) #Apply the initial layer of Hadamard gates to all qubits qaoa_circuit.h(range(size)) #Create the parameters to be used in the circuit gammas = ParameterVector('gamma', p) betas = ParameterVector('beta', p) #Outer loop to create each layer for i in range(p): #Apply R_Z rotational gates from cost layer #INSERT YOUR CODE HERE for j in range(size): qubo_matrix_sum_of_col = 0 for k in range(size): qubo_matrix_sum_of_col+= qubo_matrix[j][k] qaoa_circuit.rz(gammas[i]*(qubo_linearity[j]+qubo_matrix_sum_of_col),j) #Apply R_ZZ rotational gates for entangled qubit rotations from cost layer #INSERT YOUR CODE HERE for j in range(size): for k in range(size): if j!=k: qaoa_circuit.rzz(gammas[i]*qubo_matrix[j][k]*0.5,j,k) # Apply single qubit X - rotations with angle 2*beta_i to all qubits #INSERT YOUR CODE HERE for j in range(size): qaoa_circuit.rx(2*betas[i],j) return qaoa_circuit quadratic_program = quadratic_program_from_graph(graphs['custom']) custom_circuit = qaoa_circuit(qubo = quadratic_program) test = custom_circuit.assign_parameters(parameters=[1.0]*len(custom_circuit.parameters)) from qc_grader import grade_lab2_ex3 # Note that the grading function is expecting a quantum circuit grade_lab2_ex3(test) from qiskit.algorithms import QAOA from qiskit_optimization.algorithms import MinimumEigenOptimizer backend = Aer.get_backend('statevector_simulator') qaoa = QAOA(optimizer = ADAM(), quantum_instance = backend, reps=1, initial_point = [0.1,0.1]) eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa) quadratic_program = quadratic_program_from_graph(graphs['custom']) result = eigen_optimizer.solve(quadratic_program) print(result) def plot_samples(samples): """ Plots a bar diagram for the samples of a quantum algorithm Args: samples """ #Sort samples by probability samples = sorted(samples, key = lambda x: x.probability) #Get list of probabilities, function values and bitstrings probabilities = [sample.probability for sample in samples] values = [sample.fval for sample in samples] bitstrings = [''.join([str(int(i)) for i in sample.x]) for sample in samples] #Plot bar diagram sample_plot = go.Bar(x = bitstrings, y = probabilities, marker=dict(color=values, colorscale = 'plasma',colorbar=dict(title='Function Value'))) fig = go.Figure( data=sample_plot, layout = dict( xaxis=dict( type = 'category' ) ) ) fig.show() plot_samples(result.samples) graph_name = 'custom' quadratic_program = quadratic_program_from_graph(graph=graphs[graph_name]) trajectory={'beta_0':[], 'gamma_0':[], 'energy':[]} offset = 1/4*quadratic_program.objective.quadratic.to_array(symmetric = True).sum() + 1/2*quadratic_program.objective.linear.to_array().sum() def callback(eval_count, params, mean, std_dev): trajectory['beta_0'].append(params[1]) trajectory['gamma_0'].append(params[0]) trajectory['energy'].append(-mean + offset) optimizers = { 'cobyla': COBYLA(), 'slsqp': SLSQP(), 'adam': ADAM() } qaoa = QAOA(optimizer = optimizers['cobyla'], quantum_instance = backend, reps=1, initial_point = [6.2,1.8],callback = callback) eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa) result = eigen_optimizer.solve(quadratic_program) fig = QAOA_widget(landscape_file=f'./resources/energy_landscapes/{graph_name}.csv', trajectory = trajectory, samples = result.samples) fig.show() graph_name = 'custom' quadratic_program = quadratic_program_from_graph(graphs[graph_name]) #Create callback to record total number of evaluations max_evals = 0 def callback(eval_count, params, mean, std_dev): global max_evals max_evals = eval_count #Create empty lists to track values energies = [] runtimes = [] num_evals=[] #Run QAOA for different values of p for p in range(1,10): print(f'Evaluating for p = {p}...') qaoa = QAOA(optimizer = optimizers['cobyla'], quantum_instance = backend, reps=p, callback=callback) eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa) start = time() result = eigen_optimizer.solve(quadratic_program) runtimes.append(time()-start) num_evals.append(max_evals) #Calculate energy of final state from samples avg_value = 0. for sample in result.samples: avg_value += sample.probability*sample.fval energies.append(avg_value) #Create and display plots energy_plot = go.Scatter(x = list(range(1,10)), y =energies, marker=dict(color=energies, colorscale = 'plasma')) runtime_plot = go.Scatter(x = list(range(1,10)), y =runtimes, marker=dict(color=runtimes, colorscale = 'plasma')) num_evals_plot = go.Scatter(x = list(range(1,10)), y =num_evals, marker=dict(color=num_evals, colorscale = 'plasma')) fig = make_subplots(rows = 1, cols = 3, subplot_titles = ['Energy value', 'Runtime', 'Number of evaluations']) fig.update_layout(width=1800,height=600, showlegend=False) fig.add_trace(energy_plot, row=1, col=1) fig.add_trace(runtime_plot, row=1, col=2) fig.add_trace(num_evals_plot, row=1, col=3) clear_output() fig.show() def plot_qaoa_energy_landscape(graph: nx.Graph, cvar: float = None): num_shots = 1000 seed = 42 simulator = Aer.get_backend('qasm_simulator') simulator.set_options(seed_simulator = 42) #Generate circuit circuit = qaoa_circuit(qubo = quadratic_program_from_graph(graph), p=1) circuit.measure(range(graph.number_of_nodes()),range(graph.number_of_nodes())) #Create dictionary with precomputed cut values for all bitstrings cut_values = {} size = graph.number_of_nodes() for i in range(2**size): bitstr = '{:b}'.format(i).rjust(size, '0')[::-1] x = [int(bit) for bit in bitstr] cut_values[bitstr] = maxcut_cost_fn(graph, x) #Perform grid search over all parameters data_points = [] max_energy = None for beta in np.linspace(0,np.pi, 50): for gamma in np.linspace(0, 4*np.pi, 50): bound_circuit = circuit.assign_parameters([beta, gamma]) result = simulator.run(bound_circuit, shots = num_shots).result() statevector = result.get_counts(bound_circuit) energy = 0 measured_cuts = [] for bitstring, count in statevector.items(): measured_cuts = measured_cuts + [cut_values[bitstring]]*count if cvar is None: #Calculate the mean of all cut values energy = sum(measured_cuts)/num_shots else: #raise NotImplementedError() #INSERT YOUR CODE HERE measured_cuts = sorted(measured_cuts, reverse = True) for w in range(int(cvar*num_shots)): energy += measured_cuts[w]/int((cvar*num_shots)) #Update optimal parameters if max_energy is None or energy > max_energy: max_energy = energy optimum = {'beta': beta, 'gamma': gamma, 'energy': energy} #Update data data_points.append({'beta': beta, 'gamma': gamma, 'energy': energy}) #Create and display surface plot from data_points df = pd.DataFrame(data_points) df = df.pivot(index='beta', columns='gamma', values='energy') matrix = df.to_numpy() beta_values = df.index.tolist() gamma_values = df.columns.tolist() surface_plot = go.Surface( x=gamma_values, y=beta_values, z=matrix, coloraxis = 'coloraxis' ) fig = go.Figure(data = surface_plot) fig.show() #Return optimum return optimum graph = graphs['custom'] optimal_parameters = plot_qaoa_energy_landscape(graph = graph) print('Optimal parameters:') print(optimal_parameters) optimal_parameters = plot_qaoa_energy_landscape(graph = graph, cvar = 0.2) print(optimal_parameters) from qc_grader import grade_lab2_ex4 # Note that the grading function is expecting a python dictionary # with the entries 'beta', 'gamma' and 'energy' grade_lab2_ex4(optimal_parameters)
https://github.com/mistryiam/IBM-Qiskit-Machine-Learning
mistryiam
# General Imports import numpy as np # Visualisation Imports import matplotlib.pyplot as plt # Scikit Imports from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.svm import SVC from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler, MinMaxScaler # Qiskit Imports from qiskit import Aer, execute from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector from qiskit.circuit.library import PauliFeatureMap, ZFeatureMap, ZZFeatureMap from qiskit.circuit.library import TwoLocal, NLocal, RealAmplitudes, EfficientSU2 from qiskit.circuit.library import HGate, RXGate, RYGate, RZGate, CXGate, CRXGate, CRZGate from qiskit_machine_learning.kernels import QuantumKernel # Load digits dataset digits = datasets.load_digits(n_class=2) # Plot example '0' and '1' fig, axs = plt.subplots(1, 2, figsize=(6,3)) axs[0].set_axis_off() axs[0].imshow(digits.images[0], cmap=plt.cm.gray_r, interpolation='nearest') axs[1].set_axis_off() axs[1].imshow(digits.images[1], cmap=plt.cm.gray_r, interpolation='nearest') plt.show() # Split dataset sample_train, sample_test, label_train, label_test = train_test_split( digits.data, digits.target, test_size=0.2, random_state=22) # Reduce dimensions n_dim = 4 pca = PCA(n_components=n_dim).fit(sample_train) sample_train = pca.transform(sample_train) sample_test = pca.transform(sample_test) # Normalise std_scale = StandardScaler().fit(sample_train) sample_train = std_scale.transform(sample_train) sample_test = std_scale.transform(sample_test) # Scale samples = np.append(sample_train, sample_test, axis=0) minmax_scale = MinMaxScaler((-1, 1)).fit(samples) sample_train = minmax_scale.transform(sample_train) sample_test = minmax_scale.transform(sample_test) # Select train_size = 100 sample_train = sample_train[:train_size] label_train = label_train[:train_size] test_size = 20 sample_test = sample_test[:test_size] label_test = label_test[:test_size] print(sample_train[0], label_train[0]) print(sample_test[0], label_test[0]) # 3 features, depth 2 map_z = ZFeatureMap(feature_dimension=3, reps=2) map_z.draw('mpl') # 3 features, depth 1 map_zz = ZZFeatureMap(feature_dimension=3, reps=1) map_zz.draw('mpl') # 3 features, depth 1, linear entanglement map_zz = ZZFeatureMap(feature_dimension=3, reps=1, entanglement='linear') map_zz.draw('mpl') # 3 features, depth 1, circular entanglement map_zz = ZZFeatureMap(feature_dimension=3, reps=1, entanglement='circular') map_zz.draw('mpl') # 3 features, depth 1 map_pauli = PauliFeatureMap(feature_dimension=3, reps=1, paulis = ['X', 'Y', 'ZZ']) map_pauli.draw('mpl') def custom_data_map_func(x): coeff = x[0] if len(x) == 1 else reduce(lambda m, n: m * n, np.sin(np.pi - x)) return coeff map_customdatamap = PauliFeatureMap(feature_dimension=3, reps=1, paulis=['Z','ZZ'], data_map_func=custom_data_map_func) #map_customdatamap.draw() # qiskit isn't able to draw the circuit with np.sin in the custom data map twolocal = TwoLocal(num_qubits=3, reps=2, rotation_blocks=['ry','rz'], entanglement_blocks='cx', entanglement='circular', insert_barriers=True) twolocal.draw('mpl') twolocaln = NLocal(num_qubits=3, reps=2, rotation_blocks=[RYGate(Parameter('a')), RZGate(Parameter('a'))], entanglement_blocks=CXGate(), entanglement='circular', insert_barriers=True) twolocaln.draw('mpl') # rotation block: rot = QuantumCircuit(2) params = ParameterVector('r', 2) rot.ry(params[0], 0) rot.rz(params[1], 1) # entanglement block: ent = QuantumCircuit(4) params = ParameterVector('e', 3) ent.crx(params[0], 0, 1) ent.crx(params[1], 1, 2) ent.crx(params[2], 2, 3) nlocal = NLocal(num_qubits=6, rotation_blocks=rot, entanglement_blocks=ent, entanglement='linear', insert_barriers=True) nlocal.draw('mpl') qubits = 3 repeats = 2 x = ParameterVector('x', length=qubits) var_custom = QuantumCircuit(qubits) for _ in range(repeats): for i in range(qubits): var_custom.rx(x[i], i) for i in range(qubits): for j in range(i + 1, qubits): var_custom.cx(i, j) var_custom.p(x[i] * x[j], j) var_custom.cx(i, j) var_custom.barrier() var_custom.draw('mpl') print(sample_train[0]) encode_map = ZZFeatureMap(feature_dimension=4, reps=2, entanglement='linear', insert_barriers=True) encode_circuit = encode_map.bind_parameters(sample_train[0]) encode_circuit.draw(output='mpl') x = [-0.1,0.2] # YOUR CODE HERE encode_map_x =ZZFeatureMap(feature_dimension=2, reps=4) ex1_circuit =encode_map_x.bind_parameters(x) ex1_circuit.draw(output='mpl') from qc_grader import grade_lab3_ex1 # Note that the grading function is expecting a quantum circuit grade_lab3_ex1(ex1_circuit) zz_map = ZZFeatureMap(feature_dimension=4, reps=2, entanglement='linear', insert_barriers=True) zz_kernel = QuantumKernel(feature_map=zz_map, quantum_instance=Aer.get_backend('statevector_simulator')) print(sample_train[0]) print(sample_train[1]) zz_circuit = zz_kernel.construct_circuit(sample_train[0], sample_train[1]) zz_circuit.decompose().decompose().draw(output='mpl') backend = Aer.get_backend('qasm_simulator') job = execute(zz_circuit, backend, shots=8192, seed_simulator=1024, seed_transpiler=1024) counts = job.result().get_counts(zz_circuit) counts['0000']/sum(counts.values()) matrix_train = zz_kernel.evaluate(x_vec=sample_train) matrix_test = zz_kernel.evaluate(x_vec=sample_test, y_vec=sample_train) fig, axs = plt.subplots(1, 2, figsize=(10, 5)) axs[0].imshow(np.asmatrix(matrix_train), interpolation='nearest', origin='upper', cmap='Blues') axs[0].set_title("training kernel matrix") axs[1].imshow(np.asmatrix(matrix_test), interpolation='nearest', origin='upper', cmap='Reds') axs[1].set_title("testing kernel matrix") plt.show() x = [-0.1,0.2] y = [0.4,-0.6] # YOUR CODE HERE encode_map_x2 = ZZFeatureMap(feature_dimension=2, reps=4) zz_kernel_x2 =QuantumKernel(feature_map=encode_map_x2,quantum_instance=Aer.get_backend('statevector_simulator')) zz_circuit_x2 =zz_kernel_x2.construct_circuit(x,y) backend =Aer.get_backend('qasm_simulator') job = execute(zz_circuit_x2,backend,shots=8192, seed_simulator=1024, seed_transpiler=1024) counts_x2 = job.result().get_counts(zz_circuit_x2) amplitude= counts_x2['00']/sum(counts_x2.values()) from qc_grader import grade_lab3_ex2 # Note that the grading function is expecting a floating point number grade_lab3_ex2(amplitude) zzpc_svc = SVC(kernel='precomputed') zzpc_svc.fit(matrix_train, label_train) zzpc_score = zzpc_svc.score(matrix_test, label_test) print(f'Precomputed kernel classification test score: {zzpc_score}') zzcb_svc = SVC(kernel=zz_kernel.evaluate) zzcb_svc.fit(sample_train, label_train) zzcb_score = zzcb_svc.score(sample_test, label_test) print(f'Callable kernel classification test score: {zzcb_score}') classical_kernels = ['linear', 'poly', 'rbf', 'sigmoid'] for kernel in classical_kernels: classical_svc = SVC(kernel=kernel) classical_svc.fit(sample_train, label_train) classical_score = classical_svc.score(sample_test, label_test) print('%s kernel classification test score: %0.2f' % (kernel, classical_score))
https://github.com/mistryiam/IBM-Qiskit-Machine-Learning
mistryiam
from qiskit.circuit.library import RealAmplitudes ansatz = RealAmplitudes(num_qubits=2, reps=1, entanglement='linear') ansatz.draw('mpl', style='iqx') from qiskit.opflow import Z, I hamiltonian = Z ^ Z from qiskit.opflow import StateFn expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz) import numpy as np point = np.random.random(ansatz.num_parameters) index = 2 from qiskit import Aer from qiskit.utils import QuantumInstance backend = Aer.get_backend('qasm_simulator') q_instance = QuantumInstance(backend, shots = 8192, seed_simulator = 2718, seed_transpiler = 2718) from qiskit.circuit import QuantumCircuit from qiskit.opflow import Z, X H = X ^ X U = QuantumCircuit(2) U.h(0) U.cx(0, 1) # YOUR CODE HERE expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(U) matmult_result =expectation.eval() from qc_grader import grade_lab4_ex1 # Note that the grading function is expecting a complex number grade_lab4_ex1(matmult_result) from qiskit.opflow import CircuitSampler, PauliExpectation sampler = CircuitSampler(q_instance) # YOUR CODE HERE sampler = CircuitSampler(q_instance) # q_instance is the QuantumInstance from the beginning of the notebook expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(U) in_pauli_basis = PauliExpectation().convert(expectation) shots_result = sampler.convert(in_pauli_basis).eval() from qc_grader import grade_lab4_ex2 # Note that the grading function is expecting a complex number grade_lab4_ex2(shots_result) from qiskit.opflow import PauliExpectation, CircuitSampler expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz) in_pauli_basis = PauliExpectation().convert(expectation) sampler = CircuitSampler(q_instance) def evaluate_expectation(x): value_dict = dict(zip(ansatz.parameters, x)) result = sampler.convert(in_pauli_basis, params=value_dict).eval() return np.real(result) eps = 0.2 e_i = np.identity(point.size)[:, index] # identity vector with a 1 at index ``index``, otherwise 0 plus = point + eps * e_i minus = point - eps * e_i finite_difference = (evaluate_expectation(plus) - evaluate_expectation(minus)) / (2 * eps) print(finite_difference) from qiskit.opflow import Gradient expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz) shifter = Gradient('fin_diff', analytic=False, epsilon=eps) grad = shifter.convert(expectation, params=ansatz.parameters[index]) print(grad) value_dict = dict(zip(ansatz.parameters, point)) sampler.convert(grad, value_dict).eval().real eps = np.pi / 2 e_i = np.identity(point.size)[:, index] # identity vector with a 1 at index ``index``, otherwise 0 plus = point + eps * e_i minus = point - eps * e_i finite_difference = (evaluate_expectation(plus) - evaluate_expectation(minus)) / 2 print(finite_difference) expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz) shifter = Gradient() # parameter-shift rule is the default grad = shifter.convert(expectation, params=ansatz.parameters[index]) sampler.convert(grad, value_dict).eval().real expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz) shifter = Gradient('lin_comb') # parameter-shift rule is the default grad = shifter.convert(expectation, params=ansatz.parameters[index]) sampler.convert(grad, value_dict).eval().real # initial_point = np.random.random(ansatz.num_parameters) initial_point = np.array([0.43253681, 0.09507794, 0.42805949, 0.34210341]) expectation = StateFn(hamiltonian, is_measurement=True).compose(StateFn(ansatz)) gradient = Gradient().convert(expectation) gradient_in_pauli_basis = PauliExpectation().convert(gradient) sampler = CircuitSampler(q_instance) def evaluate_gradient(x): value_dict = dict(zip(ansatz.parameters, x)) result = sampler.convert(gradient_in_pauli_basis, params=value_dict).eval() # add parameters in here! return np.real(result) # Note: The GradientDescent class will be released with Qiskit 0.28.0 and can then be imported as: # from qiskit.algorithms.optimizers import GradientDescent from qc_grader.gradient_descent import GradientDescent gd_loss = [] def gd_callback(nfevs, x, fx, stepsize): gd_loss.append(fx) gd = GradientDescent(maxiter=300, learning_rate=0.01, callback=gd_callback) x_opt, fx_opt, nfevs = gd.optimize(initial_point.size, # number of parameters evaluate_expectation, # function to minimize gradient_function=evaluate_gradient, # function to evaluate the gradient initial_point=initial_point) # initial point import matplotlib import matplotlib.pyplot as plt matplotlib.rcParams['font.size'] = 14 plt.figure(figsize=(12, 6)) plt.plot(gd_loss, label='vanilla gradient descent') plt.axhline(-1, ls='--', c='tab:red', label='target') plt.ylabel('loss') plt.xlabel('iterations') plt.legend(); from qiskit.opflow import NaturalGradient expectation = StateFn(hamiltonian, is_measurement=True).compose(StateFn(ansatz)) natural_gradient = NaturalGradient(regularization='ridge').convert(expectation) natural_gradient_in_pauli_basis = PauliExpectation().convert(natural_gradient) sampler = CircuitSampler(q_instance, caching="all") def evaluate_natural_gradient(x): value_dict = dict(zip(ansatz.parameters, x)) result = sampler.convert(natural_gradient, params=value_dict).eval() return np.real(result) print('Vanilla gradient:', evaluate_gradient(initial_point)) print('Natural gradient:', evaluate_natural_gradient(initial_point)) qng_loss = [] def qng_callback(nfevs, x, fx, stepsize): qng_loss.append(fx) qng = GradientDescent(maxiter=300, learning_rate=0.01, callback=qng_callback) x_opt, fx_opt, nfevs = qng.optimize(initial_point.size, evaluate_expectation, gradient_function=evaluate_natural_gradient, initial_point=initial_point) def plot_loss(): plt.figure(figsize=(12, 6)) plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent') plt.plot(qng_loss, 'tab:green', label='quantum natural gradient') plt.axhline(-1, c='tab:red', ls='--', label='target') plt.ylabel('loss') plt.xlabel('iterations') plt.legend() plot_loss() from qc_grader.spsa import SPSA spsa_loss = [] def spsa_callback(nfev, x, fx, stepsize, accepted): spsa_loss.append(fx) spsa = SPSA(maxiter=300, learning_rate=0.01, perturbation=0.01, callback=spsa_callback) x_opt, fx_opt, nfevs = spsa.optimize(initial_point.size, evaluate_expectation, initial_point=initial_point) def plot_loss(): plt.figure(figsize=(12, 6)) plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent') plt.plot(qng_loss, 'tab:green', label='quantum natural gradient') plt.plot(spsa_loss, 'tab:blue', ls='--', label='SPSA') plt.axhline(-1, c='tab:red', ls='--', label='target') plt.ylabel('loss') plt.xlabel('iterations') plt.legend() plot_loss() # Note: The QNSPSA class will be released with Qiskit 0.28.0 and can then be imported as: # from qiskit.algorithms.optimizers import QNSPSA from qc_grader.qnspsa import QNSPSA qnspsa_loss = [] def qnspsa_callback(nfev, x, fx, stepsize, accepted): qnspsa_loss.append(fx) fidelity = QNSPSA.get_fidelity(ansatz, q_instance, expectation=PauliExpectation()) qnspsa = QNSPSA(fidelity, maxiter=300, learning_rate=0.01, perturbation=0.01, callback=qnspsa_callback) x_opt, fx_opt, nfevs = qnspsa.optimize(initial_point.size, evaluate_expectation, initial_point=initial_point) def plot_loss(): plt.figure(figsize=(12, 6)) plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent') plt.plot(qng_loss, 'tab:green', label='quantum natural gradient') plt.plot(spsa_loss, 'tab:blue', ls='--', label='SPSA') plt.plot(qnspsa_loss, 'tab:green', ls='--', label='QN-SPSA') plt.axhline(-1, c='tab:red', ls='--', label='target') plt.ylabel('loss') plt.xlabel('iterations') plt.legend() plot_loss() autospsa_loss = [] def autospsa_callback(nfev, x, fx, stepsize, accepted): autospsa_loss.append(fx) autospsa = SPSA(maxiter=300, learning_rate=None, perturbation=None, callback=autospsa_callback) x_opt, fx_opt, nfevs = autospsa.optimize(initial_point.size, evaluate_expectation, initial_point=initial_point) def plot_loss(): plt.figure(figsize=(12, 6)) plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent') plt.plot(qng_loss, 'tab:green', label='quantum natural gradient') plt.plot(spsa_loss, 'tab:blue', ls='--', label='SPSA') plt.plot(qnspsa_loss, 'tab:green', ls='--', label='QN-SPSA') plt.plot(autospsa_loss, 'tab:red', label='Powerlaw SPSA') plt.axhline(-1, c='tab:red', ls='--', label='target') plt.ylabel('loss') plt.xlabel('iterations') plt.legend() plot_loss() H_tfi = -(Z^Z^I)-(I^Z^Z)-(X^I^I)-(I^X^I)-(I^I^X) from qc_grader import grade_lab4_ex3 # Note that the grading function is expecting a Hamiltonian grade_lab4_ex3(H_tfi) from qiskit.circuit.library import EfficientSU2 efficient_su2 = EfficientSU2(3, entanglement="linear", reps=2) tfi_sampler = CircuitSampler(q_instance) def evaluate_tfi(parameters): exp = StateFn(H_tfi, is_measurement=True).compose(StateFn(efficient_su2)) value_dict = dict(zip(efficient_su2.parameters, parameters)) result = tfi_sampler.convert(PauliExpectation().convert(exp), params=value_dict).eval() return np.real(result) # target energy tfi_target = -3.4939592074349326 # initial point for reproducibility tfi_init = np.array([0.95667807, 0.06192812, 0.47615196, 0.83809827, 0.89022282, 0.27140831, 0.9540853 , 0.41374024, 0.92595507, 0.76150126, 0.8701938 , 0.05096063, 0.25476016, 0.71807858, 0.85661325, 0.48311132, 0.43623886, 0.6371297 ]) tfi_result = SPSA(maxiter=300, learning_rate=None, perturbation=None) tfi_result = tfi_result.optimize(tfi_init.size, evaluate_tfi, initial_point=tfi_init) tfi_minimum = tfi_result[1] print("Error:", np.abs(tfi_result[1] - tfi_target)) from qc_grader import grade_lab4_ex4 # Note that the grading function is expecting a floating point number grade_lab4_ex4(tfi_minimum) from qiskit_machine_learning.datasets import ad_hoc_data training_features, training_labels, test_features, test_labels = ad_hoc_data( training_size=20, test_size=10, n=2, one_hot=False, gap=0.5 ) # the training labels are in {0, 1} but we'll use {-1, 1} as class labels! training_labels = 2 * training_labels - 1 test_labels = 2 * test_labels - 1 def plot_sampled_data(): from matplotlib.patches import Patch from matplotlib.lines import Line2D import matplotlib.pyplot as plt plt.figure(figsize=(12,6)) for feature, label in zip(training_features, training_labels): marker = 'o' color = 'tab:green' if label == -1 else 'tab:blue' plt.scatter(feature[0], feature[1], marker=marker, s=100, color=color) for feature, label in zip(test_features, test_labels): marker = 's' plt.scatter(feature[0], feature[1], marker=marker, s=100, facecolor='none', edgecolor='k') legend_elements = [ Line2D([0], [0], marker='o', c='w', mfc='tab:green', label='A', ms=15), Line2D([0], [0], marker='o', c='w', mfc='tab:blue', label='B', ms=15), Line2D([0], [0], marker='s', c='w', mfc='none', mec='k', label='test features', ms=10) ] plt.legend(handles=legend_elements, bbox_to_anchor=(1, 0.6)) plt.title('Training & test data') plt.xlabel('$x$') plt.ylabel('$y$') plot_sampled_data() from qiskit.circuit.library import ZZFeatureMap dim = 2 feature_map = ZZFeatureMap(dim, reps=1) # let's keep it simple! feature_map.draw('mpl', style='iqx') ansatz = RealAmplitudes(num_qubits=dim, entanglement='linear', reps=1) # also simple here! ansatz.draw('mpl', style='iqx') circuit = feature_map.compose(ansatz) circuit.draw('mpl', style='iqx') hamiltonian = Z ^ Z # global Z operators gd_qnn_loss = [] def gd_qnn_callback(*args): gd_qnn_loss.append(args[2]) gd = GradientDescent(maxiter=100, learning_rate=0.01, callback=gd_qnn_callback) from qiskit_machine_learning.neural_networks import OpflowQNN qnn_expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(circuit) qnn = OpflowQNN(qnn_expectation, input_params=list(feature_map.parameters), weight_params=list(ansatz.parameters), exp_val=PauliExpectation(), gradient=Gradient(), # <-- Parameter-Shift gradients quantum_instance=q_instance) from qiskit_machine_learning.algorithms import NeuralNetworkClassifier #initial_point = np.array([0.2, 0.1, 0.3, 0.4]) classifier = NeuralNetworkClassifier(qnn, optimizer=gd) classifier.fit(training_features, training_labels); predicted = classifier.predict(test_features) def plot_predicted(): from matplotlib.lines import Line2D plt.figure(figsize=(12, 6)) for feature, label in zip(training_features, training_labels): marker = 'o' color = 'tab:green' if label == -1 else 'tab:blue' plt.scatter(feature[0], feature[1], marker=marker, s=100, color=color) for feature, label, pred in zip(test_features, test_labels, predicted): marker = 's' color = 'tab:green' if pred == -1 else 'tab:blue' if label != pred: # mark wrongly classified plt.scatter(feature[0], feature[1], marker='o', s=500, linewidths=2.5, facecolor='none', edgecolor='tab:red') plt.scatter(feature[0], feature[1], marker=marker, s=100, color=color) legend_elements = [ Line2D([0], [0], marker='o', c='w', mfc='tab:green', label='A', ms=15), Line2D([0], [0], marker='o', c='w', mfc='tab:blue', label='B', ms=15), Line2D([0], [0], marker='s', c='w', mfc='tab:green', label='predict A', ms=10), Line2D([0], [0], marker='s', c='w', mfc='tab:blue', label='predict B', ms=10), Line2D([0], [0], marker='o', c='w', mfc='none', mec='tab:red', label='wrongly classified', mew=2, ms=15) ] plt.legend(handles=legend_elements, bbox_to_anchor=(1, 0.7)) plt.title('Training & test data') plt.xlabel('$x$') plt.ylabel('$y$') plot_predicted() qng_qnn_loss = [] def qng_qnn_callback(*args): qng_qnn_loss.append(args[2]) gd = GradientDescent(maxiter=100, learning_rate=0.01, callback=qng_qnn_callback) qnn = OpflowQNN(qnn_expectation, input_params=list(feature_map.parameters), weight_params=list(ansatz.parameters), gradient=NaturalGradient(regularization='ridge'), # <-- using Natural Gradients! quantum_instance=q_instance) classifier = NeuralNetworkClassifier(qnn, optimizer=gd)#, initial_point=initial_point) classifier.fit(training_features, training_labels); def plot_losses(): plt.figure(figsize=(12, 6)) plt.plot(gd_qnn_loss, 'tab:blue', marker='o', label='vanilla gradients') plt.plot(qng_qnn_loss, 'tab:green', marker='o', label='natural gradients') plt.xlabel('iterations') plt.ylabel('loss') plt.legend(loc='best') plot_losses() from qiskit.opflow import I def sample_gradients(num_qubits, reps, local=False): """Sample the gradient of our model for ``num_qubits`` qubits and ``reps`` repetitions. We sample 100 times for random parameters and compute the gradient of the first RY rotation gate. """ index = num_qubits - 1 # you can also exchange this for a local operator and observe the same! if local: operator = Z ^ Z ^ (I ^ (num_qubits - 2)) else: operator = Z ^ num_qubits # real amplitudes ansatz ansatz = RealAmplitudes(num_qubits, entanglement='linear', reps=reps) # construct Gradient we want to evaluate for different values expectation = StateFn(operator, is_measurement=True).compose(StateFn(ansatz)) grad = Gradient().convert(expectation, params=ansatz.parameters[index]) # evaluate for 100 different, random parameter values num_points = 100 grads = [] for _ in range(num_points): # points are uniformly chosen from [0, pi] point = np.random.uniform(0, np.pi, ansatz.num_parameters) value_dict = dict(zip(ansatz.parameters, point)) grads.append(sampler.convert(grad, value_dict).eval()) return grads num_qubits = list(range(2, 13)) reps = num_qubits # number of layers = numbers of qubits gradients = [sample_gradients(n, r) for n, r in zip(num_qubits, reps)] fit = np.polyfit(num_qubits, np.log(np.var(gradients, axis=1)), deg=1) x = np.linspace(num_qubits[0], num_qubits[-1], 200) plt.figure(figsize=(12, 6)) plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='measured variance') plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}') plt.xlabel('number of qubits') plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$') plt.legend(loc='best'); from qiskit.opflow import NaturalGradient def sample_natural_gradients(num_qubits, reps): index = num_qubits - 1 operator = Z ^ num_qubits ansatz = RealAmplitudes(num_qubits, entanglement='linear', reps=reps) expectation = StateFn(operator, is_measurement=True).compose(StateFn(ansatz)) grad = # TODO: ``grad`` should be the natural gradient for the parameter at index ``index``. # Hint: Check the ``sample_gradients`` function, this one is almost the same. grad = NaturalGradient().convert(expectation, params=ansatz.parameters[index]) num_points = 100 grads = [] for _ in range(num_points): point = np.random.uniform(0, np.pi, ansatz.num_parameters) value_dict = dict(zip(ansatz.parameters, point)) grads.append(sampler.convert(grad, value_dict).eval()) return grads num_qubits = list(range(2, 13)) reps = num_qubits # number of layers = numbers of qubits natural_gradients = [sample_natural_gradients(n, r) for n, r in zip(num_qubits, reps)] fit = np.polyfit(num_qubits, np.log(np.var(natural_gradients, axis=1)), deg=1) x = np.linspace(num_qubits[0], num_qubits[-1], 200) plt.figure(figsize=(12, 6)) plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='vanilla gradients') plt.semilogy(num_qubits, np.var(natural_gradients, axis=1), 's-', label='natural gradients') plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {float(fit[0]):.2f}') plt.xlabel('number of qubits') plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$') plt.legend(loc='best'); num_qubits = list(range(2, 13)) fixed_depth_global_gradients = [sample_gradients(n, 1) for n in num_qubits] fit = np.polyfit(num_qubits, np.log(np.var(fixed_depth_global_gradients, axis=1)), deg=1) x = np.linspace(num_qubits[0], num_qubits[-1], 200) plt.figure(figsize=(12, 6)) plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='global cost, linear depth') plt.semilogy(num_qubits, np.var(fixed_depth_global_gradients, axis=1), 'o-', label='global cost, constant depth') plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}') plt.xlabel('number of qubits') plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$') plt.legend(loc='best'); num_qubits = list(range(2, 13)) linear_depth_local_gradients = [sample_gradients(n, n, local=True) for n in num_qubits] fit = np.polyfit(num_qubits, np.log(np.var(linear_depth_local_gradients, axis=1)), deg=1) x = np.linspace(num_qubits[0], num_qubits[-1], 200) plt.figure(figsize=(12, 6)) plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='global cost, linear depth') plt.semilogy(num_qubits, np.var(fixed_depth_global_gradients, axis=1), 'o-', label='global cost, constant depth') plt.semilogy(num_qubits, np.var(linear_depth_local_gradients, axis=1), 'o-', label='local cost, linear depth') plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}') plt.xlabel('number of qubits') plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$') plt.legend(loc='best'); num_qubits = list(range(2, 13)) fixed_depth_local_gradients = [sample_gradients(n, 1, local=True) for n in num_qubits] fit = np.polyfit(num_qubits, np.log(np.var(fixed_depth_local_gradients, axis=1)), deg=1) x = np.linspace(num_qubits[0], num_qubits[-1], 200) plt.figure(figsize=(12, 6)) plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='global cost, linear depth') plt.semilogy(num_qubits, np.var(fixed_depth_global_gradients, axis=1), 'o-', label='global cost, constant depth') plt.semilogy(num_qubits, np.var(linear_depth_local_gradients, axis=1), 'o-', label='local cost, linear depth') plt.semilogy(num_qubits, np.var(fixed_depth_local_gradients, axis=1), 'o-', label='local cost, constant depth') plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}') plt.xlabel('number of qubits') plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$') plt.legend(loc='best'); num_qubits = 6 operator = Z ^ Z ^ (I ^ (num_qubits - 4)) def minimize(circuit, optimizer): initial_point = np.random.random(circuit.num_parameters) exp = StateFn(operator, is_measurement=True) @ StateFn(circuit) grad = Gradient().convert(exp) # pauli basis exp = PauliExpectation().convert(exp) grad = PauliExpectation().convert(grad) sampler = CircuitSampler(q_instance, caching="all") def loss(x): values_dict = dict(zip(circuit.parameters, x)) return np.real(sampler.convert(exp, values_dict).eval()) def gradient(x): values_dict = dict(zip(circuit.parameters, x)) return np.real(sampler.convert(grad, values_dict).eval()) return optimizer.optimize(circuit.num_parameters, loss, gradient, initial_point=initial_point) circuit = RealAmplitudes(4, reps=1, entanglement='linear') circuit.draw('mpl', style='iqx') circuit.reps = 5 circuit.draw('mpl', style='iqx') def layerwise_training(ansatz, max_num_layers, optimizer): optimal_parameters = [] fopt = None for reps in range(1, max_num_layers): ansatz.reps = reps # bind already optimized parameters values_dict = dict(zip(ansatz.parameters, optimal_parameters)) partially_bound = ansatz.bind_parameters(values_dict) xopt, fopt, _ = minimize(partially_bound, optimizer) print('Circuit depth:', ansatz.depth(), 'best value:', fopt) optimal_parameters += list(xopt) return fopt, optimal_parameters ansatz = RealAmplitudes(4, entanglement='linear') optimizer = GradientDescent(maxiter=50) np.random.seed(12) fopt, optimal_parameters = layerwise_training(ansatz, 4, optimizer)
https://github.com/mistryiam/IBM-Qiskit-Machine-Learning
mistryiam
# General tools import numpy as np import matplotlib.pyplot as plt # Qiskit Circuit Functions from qiskit import execute,QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, transpile import qiskit.quantum_info as qi # Tomography functions from qiskit.ignis.verification.tomography import process_tomography_circuits, ProcessTomographyFitter from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter import warnings warnings.filterwarnings('ignore') target = QuantumCircuit(2) #target = # YOUR CODE HERE target.h(0) target.h(1) target.rx(np.pi/2,0) target.rx(np.pi/2,1) target.cx(0,1) target.p(np.pi,1) target.cx(0,1) target_unitary = qi.Operator(target) target.draw('mpl') from qc_grader import grade_lab5_ex1 # Note that the grading function is expecting a quantum circuit with no measurements grade_lab5_ex1(target) simulator = Aer.get_backend('qasm_simulator') qpt_circs = process_tomography_circuits(target,measured_qubits=[0,1])# YOUR CODE HERE qpt_job = execute(qpt_circs,simulator,seed_simulator=3145,seed_transpiler=3145,shots=8192) qpt_result = qpt_job.result() # YOUR CODE HERE qpt_tomo= ProcessTomographyFitter(qpt_result,qpt_circs) Choi_qpt= qpt_tomo.fit(method='lstsq') fidelity = qi.average_gate_fidelity(Choi_qpt,target_unitary) from qc_grader import grade_lab5_ex2 # Note that the grading function is expecting a floating point number grade_lab5_ex2(fidelity) # T1 and T2 values for qubits 0-3 T1s = [15000, 19000, 22000, 14000] T2s = [30000, 25000, 18000, 28000] # Instruction times (in nanoseconds) time_u1 = 0 # virtual gate time_u2 = 50 # (single X90 pulse) time_u3 = 100 # (two X90 pulses) time_cx = 300 time_reset = 1000 # 1 microsecond time_measure = 1000 # 1 microsecond from qiskit.providers.aer.noise import thermal_relaxation_error from qiskit.providers.aer.noise import NoiseModel # QuantumError objects errors_reset = [thermal_relaxation_error(t1, t2, time_reset) for t1, t2 in zip(T1s, T2s)] errors_measure = [thermal_relaxation_error(t1, t2, time_measure) for t1, t2 in zip(T1s, T2s)] errors_u1 = [thermal_relaxation_error(t1, t2, time_u1) for t1, t2 in zip(T1s, T2s)] errors_u2 = [thermal_relaxation_error(t1, t2, time_u2) for t1, t2 in zip(T1s, T2s)] errors_u3 = [thermal_relaxation_error(t1, t2, time_u3) for t1, t2 in zip(T1s, T2s)] errors_cx = [[thermal_relaxation_error(t1a, t2a, time_cx).expand( thermal_relaxation_error(t1b, t2b, time_cx)) for t1a, t2a in zip(T1s, T2s)] for t1b, t2b in zip(T1s, T2s)] # Add errors to noise model noise_thermal = NoiseModel() for j in range(4): noise_thermal.add_quantum_error(errors_measure[j],'measure',[j]) noise_thermal.add_quantum_error(errors_reset[j],'reset',[j]) noise_thermal.add_quantum_error(errors_u3[j],'u3',[j]) noise_thermal.add_quantum_error(errors_u2[j],'u2',[j]) noise_thermal.add_quantum_error(errors_u1[j],'u1',[j]) for k in range(4): noise_thermal.add_quantum_error(errors_cx[j][k],'cx',[j,k]) # YOUR CODE HERE from qc_grader import grade_lab5_ex3 # Note that the grading function is expecting a NoiseModel grade_lab5_ex3(noise_thermal) np.random.seed(0) noise_qpt_circs = process_tomography_circuits(target,measured_qubits=[0,1])# YOUR CODE HERE noise_qpt_job = execute(noise_qpt_circs,simulator,seed_simulator=3145,seed_transpiler=3145,shots=8192,noise_model=noise_thermal) noise_qpt_result = noise_qpt_job.result() # YOUR CODE HERE noise_qpt_tomo= ProcessTomographyFitter(noise_qpt_result,noise_qpt_circs) noise_Choi_qpt= noise_qpt_tomo.fit(method='lstsq') fidelity = qi.average_gate_fidelity(noise_Choi_qpt,target_unitary) from qc_grader import grade_lab5_ex4 # Note that the grading function is expecting a floating point number grade_lab5_ex4(fidelity) np.random.seed(0) # YOUR CODE HERE #qr = QuantumRegister(2) qubit_list = [0,1] meas_calibs, state_labels = complete_meas_cal(qubit_list=qubit_list) meas_calibs_job = execute(meas_calibs,simulator,seed_simulator=3145,seed_transpiler=3145,shots=8192,noise_model=noise_thermal) cal_results = meas_calibs_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, qubit_list=qubit_list) Cal_result = meas_fitter.filter.apply(noise_qpt_result) # YOUR CODE HERE Cal_qpt_tomo= ProcessTomographyFitter(Cal_result,noise_qpt_circs) Cal_Choi_qpt= Cal_qpt_tomo.fit(method='lstsq') fidelity = qi.average_gate_fidelity(Cal_Choi_qpt,target_unitary) from qc_grader import grade_lab5_ex5 # Note that the grading function is expecting a floating point number grade_lab5_ex5(fidelity)
https://github.com/filipecorrea/deutsch-jozsa
filipecorrea
import numpy as np import qiskit from qiskit import IBMQ, BasicAer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, execute from qiskit.visualization import plot_histogram qiskit.__qiskit_version__ # set the length of the n-bit input string n = 3 balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) balanced_oracle.draw(output='mpl') balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Use barrier as divider balanced_oracle.barrier() # Controlled-NOT gates for qubit in range(n): balanced_oracle.cx(qubit, n) balanced_oracle.barrier() balanced_oracle.draw(output='mpl') balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Use barrier as divider balanced_oracle.barrier() # Controlled-NOT gates for qubit in range(n): balanced_oracle.cx(qubit, n) balanced_oracle.barrier() # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Show oracle balanced_oracle.draw(output='mpl') dj_circuit = QuantumCircuit(n+1, n) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) dj_circuit.draw(output='mpl') dj_circuit = QuantumCircuit(n+1, n) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) # Add oracle dj_circuit += balanced_oracle dj_circuit.draw(output='mpl') dj_circuit = QuantumCircuit(n+1, n) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) # Add oracle dj_circuit += balanced_oracle # Repeat H-gates for qubit in range(n): dj_circuit.h(qubit) dj_circuit.barrier() # Measure for i in range(n): dj_circuit.measure(i, i) # Display circuit dj_circuit.draw(output='mpl') # use local simulator backend = BasicAer.get_backend('qasm_simulator') shots = 1024 results = execute(dj_circuit, backend=backend, shots=shots).result() answer = results.get_counts() plot_histogram(answer)
https://github.com/filipecorrea/deutsch-jozsa
filipecorrea
import numpy as np import qiskit from qiskit import IBMQ, BasicAer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, execute from qiskit.visualization import plot_histogram qiskit.__qiskit_version__ # set the length of the n-bit input string n = 3 const_oracle = QuantumCircuit(n+1) output = np.random.randint(2) if output == 1: const_oracle.x(n) const_oracle.draw(output='mpl') dj_circuit = QuantumCircuit(n+1, n) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) dj_circuit.draw(output='mpl') dj_circuit = QuantumCircuit(n+1, n) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) # Add oracle dj_circuit += const_oracle dj_circuit.draw(output='mpl') dj_circuit = QuantumCircuit(n+1, n) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) # Add oracle dj_circuit += const_oracle # Repeat H-gates for qubit in range(n): dj_circuit.h(qubit) dj_circuit.barrier() # Measure for i in range(n): dj_circuit.measure(i, i) # Display circuit dj_circuit.draw(output='mpl') # use local simulator backend = BasicAer.get_backend('qasm_simulator') shots = 1024 results = execute(dj_circuit, backend=backend, shots=shots).result() answer = results.get_counts() plot_histogram(answer)
https://github.com/filipecorrea/deutsch-jozsa
filipecorrea
import qiskit from qiskit import IBMQ # IBMQ.save_account('<IBMQ_API_TOKEN>') IBMQ.load_account() from qiskit import BasicAer from qiskit.aqua import QuantumInstance from qiskit.aqua.algorithms import DeutschJozsa from qiskit.aqua.components.oracles import TruthTableOracle qiskit.__qiskit_version__ bitstr = '11110000' oracle = TruthTableOracle(bitstr) oracle.circuit.draw(output='mpl') dj = DeutschJozsa(oracle) backend = BasicAer.get_backend('qasm_simulator') result = dj.run(QuantumInstance(backend, shots=1024)) print('The truth table {} represents a {} function.'.format(bitstr, result['result'])) bitstr = '1' * 32 oracle = TruthTableOracle(bitstr) dj = DeutschJozsa(oracle) result = dj.run(QuantumInstance(backend, shots=1024)) print('The truth table {} represents a {} function.'.format(bitstr, result['result']))
https://github.com/filipecorrea/deutsch-jozsa
filipecorrea
# initialization import numpy as np # importing Qiskit from qiskit import IBMQ, Aer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, transpile # import basic plot tools from qiskit.visualization import plot_histogram # set the length of the n-bit input string. n = 3 # set the length of the n-bit input string. n = 3 const_oracle = QuantumCircuit(n+1) output = np.random.randint(2) if output == 1: const_oracle.x(n) const_oracle.draw() balanced_oracle = QuantumCircuit(n+1) b_str = "101" balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) balanced_oracle.draw() balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Use barrier as divider balanced_oracle.barrier() # Controlled-NOT gates for qubit in range(n): balanced_oracle.cx(qubit, n) balanced_oracle.barrier() balanced_oracle.draw() balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Use barrier as divider balanced_oracle.barrier() # Controlled-NOT gates for qubit in range(n): balanced_oracle.cx(qubit, n) balanced_oracle.barrier() # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Show oracle balanced_oracle.draw() dj_circuit = QuantumCircuit(n+1, n) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) dj_circuit.draw() dj_circuit = QuantumCircuit(n+1, n) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) # Add oracle dj_circuit = dj_circuit.compose(balanced_oracle) dj_circuit.draw() dj_circuit = QuantumCircuit(n+1, n) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) # Add oracle dj_circuit = dj_circuit.compose(balanced_oracle) # Repeat H-gates for qubit in range(n): dj_circuit.h(qubit) dj_circuit.barrier() # Measure for i in range(n): dj_circuit.measure(i, i) # Display circuit dj_circuit.draw() # use local simulator aer_sim = Aer.get_backend('aer_simulator') results = aer_sim.run(dj_circuit).result() answer = results.get_counts() plot_histogram(answer) # ...we have a 0% chance of measuring 000. assert answer.get('000', 0) == 0 def dj_oracle(case, n): # We need to make a QuantumCircuit object to return # This circuit has n+1 qubits: the size of the input, # plus one output qubit oracle_qc = QuantumCircuit(n+1) # First, let's deal with the case in which oracle is balanced if case == "balanced": # First generate a random number that tells us which CNOTs to # wrap in X-gates: b = np.random.randint(1,2**n) # Next, format 'b' as a binary string of length 'n', padded with zeros: b_str = format(b, '0'+str(n)+'b') # Next, we place the first X-gates. Each digit in our binary string # corresponds to a qubit, if the digit is 0, we do nothing, if it's 1 # we apply an X-gate to that qubit: for qubit in range(len(b_str)): if b_str[qubit] == '1': oracle_qc.x(qubit) # Do the controlled-NOT gates for each qubit, using the output qubit # as the target: for qubit in range(n): oracle_qc.cx(qubit, n) # Next, place the final X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': oracle_qc.x(qubit) # Case in which oracle is constant if case == "constant": # First decide what the fixed output of the oracle will be # (either always 0 or always 1) output = np.random.randint(2) if output == 1: oracle_qc.x(n) oracle_gate = oracle_qc.to_gate() oracle_gate.name = "Oracle" # To show when we display the circuit return oracle_gate def dj_algorithm(oracle, n): dj_circuit = QuantumCircuit(n+1, n) # Set up the output qubit: dj_circuit.x(n) dj_circuit.h(n) # And set up the input register: for qubit in range(n): dj_circuit.h(qubit) # Let's append the oracle gate to our circuit: dj_circuit.append(oracle, range(n+1)) # Finally, perform the H-gates again and measure: for qubit in range(n): dj_circuit.h(qubit) for i in range(n): dj_circuit.measure(i, i) return dj_circuit n = 4 oracle_gate = dj_oracle('balanced', n) dj_circuit = dj_algorithm(oracle_gate, n) dj_circuit.draw() transpiled_dj_circuit = transpile(dj_circuit, aer_sim) results = aer_sim.run(transpiled_dj_circuit).result() answer = results.get_counts() plot_histogram(answer) # Load our saved IBMQ accounts and get the least busy backend device with greater than or equal to (n+1) qubits IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (n+1) and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) # Run our circuit on the least busy backend. Monitor the execution of the job in the queue from qiskit.tools.monitor import job_monitor transpiled_dj_circuit = transpile(dj_circuit, backend, optimization_level=3) job = backend.run(transpiled_dj_circuit) job_monitor(job, interval=2) # Get the results of the computation results = job.result() answer = results.get_counts() plot_histogram(answer) # ...the most likely result is 1111. assert max(answer, key=answer.get) == '1111' from qiskit_textbook.problems import dj_problem_oracle oracle = dj_problem_oracle(1) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Example showing how to draw a quantum circuit using Qiskit. """ from qiskit import QuantumCircuit def build_bell_circuit(): """Returns a circuit putting 2 qubits in the Bell state.""" qc = QuantumCircuit(2, 2) qc.h(0) qc.cx(0, 1) qc.measure([0, 1], [0, 1]) return qc # Create the circuit bell_circuit = build_bell_circuit() # Use the internal .draw() to print the circuit print(bell_circuit)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. from qiskit import QuantumCircuit from qiskit.transpiler import PassManager from qiskit.transpiler.passes import CommutationAnalysis, CommutativeCancellation circuit = QuantumCircuit(5) # Quantum Instantaneous Polynomial Time example circuit.cx(0, 1) circuit.cx(2, 1) circuit.cx(4, 3) circuit.cx(2, 3) circuit.z(0) circuit.z(4) circuit.cx(0, 1) circuit.cx(2, 1) circuit.cx(4, 3) circuit.cx(2, 3) circuit.cx(3, 2) print(circuit) pm = PassManager() pm.append([CommutationAnalysis(), CommutativeCancellation()]) new_circuit = pm.run(circuit) print(new_circuit)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit, execute from qiskit import Aer import numpy as np import sys N=int(sys.argv[1]) filename = sys.argv[2] backend = Aer.get_backend('unitary_simulator') def GHZ(n): if n<=0: return None circ = QuantumCircuit(n) # Put your code below # ---------------------------- circ.h(0) for x in range(1,n): circ.cx(x-1,x) # ---------------------------- return circ circuit = GHZ(N) job = execute(circuit, backend, shots=8192) result = job.result() array = result.get_unitary(circuit,3) np.savetxt(filename, array, delimiter=",", fmt = "%0.3f")
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Example use of the initialize gate to prepare arbitrary pure states. """ import math from qiskit import QuantumCircuit, execute, BasicAer ############################################################### # Make a quantum circuit for state initialization. ############################################################### circuit = QuantumCircuit(4, 4, name="initializer_circ") desired_vector = [ 1 / math.sqrt(4) * complex(0, 1), 1 / math.sqrt(8) * complex(1, 0), 0, 0, 0, 0, 0, 0, 1 / math.sqrt(8) * complex(1, 0), 1 / math.sqrt(8) * complex(0, 1), 0, 0, 0, 0, 1 / math.sqrt(4) * complex(1, 0), 1 / math.sqrt(8) * complex(1, 0), ] circuit.initialize(desired_vector, [0, 1, 2, 3]) circuit.measure([0, 1, 2, 3], [0, 1, 2, 3]) print(circuit) ############################################################### # Execute on a simulator backend. ############################################################### shots = 10000 # Desired vector print("Desired probabilities: ") print([format(abs(x * x), ".3f") for x in desired_vector]) # Initialize on local simulator sim_backend = BasicAer.get_backend("qasm_simulator") job = execute(circuit, sim_backend, shots=shots) result = job.result() counts = result.get_counts(circuit) qubit_strings = [format(i, "04b") for i in range(2**4)] print("Probabilities from simulator: ") print([format(counts.get(s, 0) / shots, ".3f") for s in qubit_strings])
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Example on how to load a file into a QuantumCircuit.""" from qiskit import QuantumCircuit from qiskit import execute, BasicAer circ = QuantumCircuit.from_qasm_file("examples/qasm/entangled_registers.qasm") print(circ) # See the backend sim_backend = BasicAer.get_backend("qasm_simulator") # Compile and run the Quantum circuit on a local simulator backend job_sim = execute(circ, sim_backend) sim_result = job_sim.result() # Show the results print("simulation: ", sim_result) print(sim_result.get_counts(circ))
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- 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 module contains the definition of a base class for quantum fourier transforms. """ from abc import abstractmethod from qiskit import QuantumRegister, QuantumCircuit from qiskit.aqua import Pluggable, AquaError class QFT(Pluggable): """Base class for QFT. This method should initialize the module and its configuration, and use an exception if a component of the module is available. Args: configuration (dict): configuration dictionary """ @abstractmethod def __init__(self, *args, **kwargs): super().__init__() @classmethod def init_params(cls, params): qft_params = params.get(Pluggable.SECTION_KEY_QFT) kwargs = {k: v for k, v in qft_params.items() if k != 'name'} return cls(**kwargs) @abstractmethod def _build_matrix(self): raise NotImplementedError @abstractmethod def _build_circuit(self, qubits=None, circuit=None, do_swaps=True): raise NotImplementedError def construct_circuit(self, mode='circuit', qubits=None, circuit=None, do_swaps=True): """Construct the circuit. Args: mode (str): 'matrix' or 'circuit' qubits (QuantumRegister or qubits): register or qubits to build the circuit on. circuit (QuantumCircuit): circuit for construction. do_swaps (bool): include the swaps. Returns: The matrix or circuit depending on the specified mode. """ if mode == 'circuit': return self._build_circuit(qubits=qubits, circuit=circuit, do_swaps=do_swaps) elif mode == 'matrix': return self._build_matrix() else: raise AquaError('Unrecognized mode: {}.'.format(mode))
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Ripple adder example based on Cuccaro et al., quant-ph/0410184. """ from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import BasicAer from qiskit import execute ############################################################### # Set the backend name and coupling map. ############################################################### backend = BasicAer.get_backend("qasm_simulator") coupling_map = [ [0, 1], [0, 8], [1, 2], [1, 9], [2, 3], [2, 10], [3, 4], [3, 11], [4, 5], [4, 12], [5, 6], [5, 13], [6, 7], [6, 14], [7, 15], [8, 9], [9, 10], [10, 11], [11, 12], [12, 13], [13, 14], [14, 15], ] ############################################################### # Make a quantum program for the n-bit ripple adder. ############################################################### n = 2 a = QuantumRegister(n, "a") b = QuantumRegister(n, "b") cin = QuantumRegister(1, "cin") cout = QuantumRegister(1, "cout") ans = ClassicalRegister(n + 1, "ans") qc = QuantumCircuit(a, b, cin, cout, ans, name="rippleadd") def majority(p, a, b, c): """Majority gate.""" p.cx(c, b) p.cx(c, a) p.ccx(a, b, c) def unmajority(p, a, b, c): """Unmajority gate.""" p.ccx(a, b, c) p.cx(c, a) p.cx(a, b) # Build a temporary subcircuit that adds a to b, # storing the result in b adder_subcircuit = QuantumCircuit(cin, a, b, cout) majority(adder_subcircuit, cin[0], b[0], a[0]) for j in range(n - 1): majority(adder_subcircuit, a[j], b[j + 1], a[j + 1]) adder_subcircuit.cx(a[n - 1], cout[0]) for j in reversed(range(n - 1)): unmajority(adder_subcircuit, a[j], b[j + 1], a[j + 1]) unmajority(adder_subcircuit, cin[0], b[0], a[0]) # Set the inputs to the adder qc.x(a[0]) # Set input a = 0...0001 qc.x(b) # Set input b = 1...1111 # Apply the adder qc &= adder_subcircuit # Measure the output register in the computational basis for j in range(n): qc.measure(b[j], ans[j]) qc.measure(cout[0], ans[n]) ############################################################### # execute the program. ############################################################### # First version: not mapped job = execute(qc, backend=backend, coupling_map=None, shots=1024) result = job.result() print(result.get_counts(qc)) # Second version: mapped to 2x8 array coupling graph job = execute(qc, backend=backend, coupling_map=coupling_map, shots=1024) result = job.result() print(result.get_counts(qc)) # Both versions should give the same distribution
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Example of using the StochasticSwap pass.""" from qiskit.transpiler.passes import StochasticSwap from qiskit.transpiler import CouplingMap from qiskit.converters import circuit_to_dag from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit 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) # β”Œβ”€β”β”Œβ”€β”€β”€β” β”Œβ”€β” # 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 ═══════════════════════════════╩═══════════════════════ # # β”Œβ”€β”β”Œβ”€β”€β”€β” β”Œβ”€β” # q_0: |0>────────────────────■───Mβ”œβ”€ H β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β– β”€β”€β”€Mβ”œβ”€β”€β”€β”€β”€β”€ # β”Œβ”€β”΄β”€β”β””β•₯β”˜β””β”€β”€β”€β”˜β”Œβ”€β”€β”€β”β”Œβ”€β”€β”€β” β”Œβ”€β”΄β”€β”β””β•₯β”˜β”Œβ”€β” # q_1: |0>──■───X──────────── X β”œβ”€β•«β”€β”€β”€β”€β”€β”€β”€ H β”œβ”€ X β”œβ”€X───── 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 ═════════════════════════════════════════════╩═══════════════ # # # 2 # | # 0 - 1 - 3 # Build the expected output to verify the pass worked 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) # Run the pass on the dag from the input circuit pass_ = StochasticSwap(coupling, 20, 999) after = pass_.run(dag) # Verify the output of the pass matches our expectation assert expected_dag == after
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Quantum teleportation example. Note: if you have only cloned the Qiskit repository but not used `pip install`, the examples only work from the root directory. """ from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import BasicAer from qiskit import execute ############################################################### # Set the backend name and coupling map. ############################################################### coupling_map = [[0, 1], [0, 2], [1, 2], [3, 2], [3, 4], [4, 2]] backend = BasicAer.get_backend("qasm_simulator") ############################################################### # Make a quantum program for quantum teleportation. ############################################################### q = QuantumRegister(3, "q") c0 = ClassicalRegister(1, "c0") c1 = ClassicalRegister(1, "c1") c2 = ClassicalRegister(1, "c2") qc = QuantumCircuit(q, c0, c1, c2, name="teleport") # Prepare an initial state qc.u(0.3, 0.2, 0.1, q[0]) # Prepare a Bell pair qc.h(q[1]) qc.cx(q[1], q[2]) # Barrier following state preparation qc.barrier(q) # Measure in the Bell basis qc.cx(q[0], q[1]) qc.h(q[0]) qc.measure(q[0], c0[0]) qc.measure(q[1], c1[0]) # Apply a correction qc.barrier(q) qc.z(q[2]).c_if(c0, 1) qc.x(q[2]).c_if(c1, 1) qc.measure(q[2], c2[0]) ############################################################### # Execute. # Experiment does not support feedback, so we use the simulator ############################################################### # First version: not mapped initial_layout = {q[0]: 0, q[1]: 1, q[2]: 2} job = execute(qc, backend=backend, coupling_map=None, shots=1024, initial_layout=initial_layout) result = job.result() print(result.get_counts(qc)) # Second version: mapped to 2x8 array coupling graph job = execute( qc, backend=backend, coupling_map=coupling_map, shots=1024, initial_layout=initial_layout ) result = job.result() print(result.get_counts(qc)) # Both versions should give the same distribution
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Example showing how to use Qiskit-Terra at level 0 (novice). This example shows the most basic way to user Terra. It builds some circuits and runs them on both the BasicAer (local Qiskit provider) or IBMQ (remote IBMQ provider). To control the compile parameters we have provided a transpile function which can be used as a level 1 user. """ # Import the Qiskit modules from qiskit import QuantumCircuit from qiskit import execute, BasicAer # making first circuit: bell state qc1 = QuantumCircuit(2, 2) qc1.h(0) qc1.cx(0, 1) qc1.measure([0, 1], [0, 1]) # making another circuit: superpositions qc2 = QuantumCircuit(2, 2) qc2.h([0, 1]) qc2.measure([0, 1], [0, 1]) # setting up the backend print("(BasicAER Backends)") print(BasicAer.backends()) # running the job job_sim = execute([qc1, qc2], BasicAer.get_backend("qasm_simulator")) sim_result = job_sim.result() # Show the results print(sim_result.get_counts(qc1)) print(sim_result.get_counts(qc2))
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ ====================================================== Executing Experiments (:mod:`qiskit.execute_function`) ====================================================== .. currentmodule:: qiskit.execute_function .. autofunction:: execute """ import logging from time import time from qiskit.compiler import transpile, schedule from qiskit.providers.backend import Backend from qiskit.pulse import Schedule, ScheduleBlock from qiskit.exceptions import QiskitError from qiskit.utils.deprecation import deprecate_arg logger = logging.getLogger(__name__) def _log_submission_time(start_time, end_time): log_msg = "Total Job Submission Time - %.5f (ms)" % ((end_time - start_time) * 1000) logger.info(log_msg) @deprecate_arg("qobj_id", since="0.21.0", additional_msg="This argument has no effect anymore.") @deprecate_arg("qobj_header", since="0.21.0", additional_msg="This argument has no effect anymore.") def execute( experiments, backend, basis_gates=None, coupling_map=None, # circuit transpile options backend_properties=None, initial_layout=None, seed_transpiler=None, optimization_level=None, pass_manager=None, qobj_id=None, qobj_header=None, shots=None, # common run options memory=None, seed_simulator=None, default_qubit_los=None, default_meas_los=None, # schedule run options qubit_lo_range=None, meas_lo_range=None, schedule_los=None, meas_level=None, meas_return=None, memory_slots=None, memory_slot_size=None, rep_time=None, rep_delay=None, parameter_binds=None, schedule_circuit=False, inst_map=None, meas_map=None, scheduling_method=None, init_qubits=None, **run_config, ): """Execute a list of :class:`qiskit.circuit.QuantumCircuit` or :class:`qiskit.pulse.Schedule` on a backend. The execution is asynchronous, and a handle to a job instance is returned. Args: experiments (QuantumCircuit or list[QuantumCircuit] or Schedule or list[Schedule]): Circuit(s) or pulse schedule(s) to execute backend (Backend): Backend to execute circuits on. Transpiler options are automatically grabbed from backend.configuration() and backend.properties(). If any other option is explicitly set (e.g. coupling_map), it will override the backend's. basis_gates (list[str]): List of basis gate names to unroll to. e.g: ``['u1', 'u2', 'u3', 'cx']`` If ``None``, do not unroll. coupling_map (CouplingMap or list): Coupling map (perhaps custom) to target in mapping. Multiple formats are supported: #. CouplingMap instance #. list Must be given as an adjacency matrix, where each entry specifies all two-qubit interactions supported by backend e.g: ``[[0, 1], [0, 3], [1, 2], [1, 5], [2, 5], [4, 1], [5, 3]]`` backend_properties (BackendProperties): Properties returned by a backend, including information on gate errors, readout errors, qubit coherence times, etc. Find a backend that provides this information with: ``backend.properties()`` initial_layout (Layout or dict or list): Initial position of virtual qubits on physical qubits. If this layout makes the circuit compatible with the coupling_map constraints, it will be used. The final layout is not guaranteed to be the same, as the transpiler may permute qubits through swaps or other means. Multiple formats are supported: #. :class:`qiskit.transpiler.Layout` instance #. ``dict``: * virtual to physical:: {qr[0]: 0, qr[1]: 3, qr[2]: 5} * physical to virtual:: {0: qr[0], 3: qr[1], 5: qr[2]} #. ``list``: * virtual to physical:: [0, 3, 5] # virtual qubits are ordered (in addition to named) * physical to virtual:: [qr[0], None, None, qr[1], None, qr[2]] seed_transpiler (int): Sets random seed for the stochastic parts of the transpiler optimization_level (int): How much optimization to perform on the circuits. Higher levels generate more optimized circuits, at the expense of longer transpilation time. * 0: no optimization * 1: light optimization * 2: heavy optimization * 3: even heavier optimization If None, level 1 will be chosen as default. pass_manager (PassManager): The pass manager to use during transpilation. If this arg is present, auto-selection of pass manager based on the transpile options will be turned off and this pass manager will be used directly. qobj_id (str): DEPRECATED: String identifier to annotate the Qobj. This has no effect and the :attr:`~.QuantumCircuit.name` attribute of the input circuit(s) should be used instead. qobj_header (QobjHeader or dict): DEPRECATED: User input that will be inserted in Qobj header, and will also be copied to the corresponding :class:`qiskit.result.Result` header. Headers do not affect the run. Headers do not affect the run. This kwarg has no effect anymore and the :attr:`~.QuantumCircuit.metadata` attribute of the input circuit(s) should be used instead. shots (int): Number of repetitions of each circuit, for sampling. Default: 1024 memory (bool): If True, per-shot measurement bitstrings are returned as well (provided the backend supports it). For OpenPulse jobs, only measurement level 2 supports this option. Default: False seed_simulator (int): Random seed to control sampling, for when backend is a simulator default_qubit_los (Optional[List[float]]): List of job level qubit drive LO frequencies in Hz. Overridden by ``schedule_los`` if specified. Must have length ``n_qubits``. default_meas_los (Optional[List[float]]): List of job level measurement LO frequencies in Hz. Overridden by ``schedule_los`` if specified. Must have length ``n_qubits``. qubit_lo_range (Optional[List[List[float]]]): List of job level drive LO ranges each of form ``[range_min, range_max]`` in Hz. Used to validate ``qubit_lo_freq``. Must have length ``n_qubits``. meas_lo_range (Optional[List[List[float]]]): List of job level measurement LO ranges each of form ``[range_min, range_max]`` in Hz. Used to validate ``meas_lo_freq``. Must have length ``n_qubits``. schedule_los (list): Experiment level (ie circuit or schedule) LO frequency configurations for qubit drive and measurement channels. These values override the job level values from ``default_qubit_los`` and ``default_meas_los``. Frequencies are in Hz. Settable for qasm and pulse jobs. If a single LO config or dict is used, the values are set at job level. If a list is used, the list must be the size of the number of experiments in the job, except in the case of a single experiment. In this case, a frequency sweep will be assumed and one experiment will be created for every list entry. Not every channel is required to be specified. If not specified, the backend default value will be used. meas_level (int or MeasLevel): Set the appropriate level of the measurement output for pulse experiments. meas_return (str or MeasReturn): Level of measurement data for the backend to return For ``meas_level`` 0 and 1: ``"single"`` returns information from every shot. ``"avg"`` returns average measurement output (averaged over number of shots). memory_slots (int): Number of classical memory slots used in this job. memory_slot_size (int): Size of each memory slot if the output is Level 0. rep_time (int): Time per program execution in seconds. Must be from the list provided by the backend (``backend.configuration().rep_times``). Defaults to the first entry. rep_delay (float): Delay between programs in seconds. Only supported on certain backends (``backend.configuration().dynamic_reprate_enabled`` ). If supported, ``rep_delay`` will be used instead of ``rep_time`` and must be from the range supplied by the backend (``backend.configuration().rep_delay_range``). Default is given by ``backend.configuration().default_rep_delay``. parameter_binds (list[dict]): List of Parameter bindings over which the set of experiments will be executed. Each list element (bind) should be of the form ``{Parameter1: value1, Parameter2: value2, ...}``. All binds will be executed across all experiments, e.g. if parameter_binds is a length-:math:`n` list, and there are :math:`m` experiments, a total of :math:`m \\times n` experiments will be run (one for each experiment/bind pair). schedule_circuit (bool): If ``True``, ``experiments`` will be converted to :class:`qiskit.pulse.Schedule` objects prior to execution. inst_map (InstructionScheduleMap): Mapping of circuit operations to pulse schedules. If None, defaults to the ``instruction_schedule_map`` of ``backend``. meas_map (list(list(int))): List of sets of qubits that must be measured together. If None, defaults to the ``meas_map`` of ``backend``. scheduling_method (str or list(str)): Optionally specify a particular scheduling method. init_qubits (bool): Whether to reset the qubits to the ground state for each shot. Default: ``True``. run_config (dict): Extra arguments used to configure the run (e.g. for Aer configurable backends). Refer to the backend documentation for details on these arguments. Note: for now, these keyword arguments will both be copied to the Qobj config, and passed to backend.run() Returns: Job: returns job instance derived from Job Raises: QiskitError: if the execution cannot be interpreted as either circuits or schedules Example: Construct a 5-qubit GHZ circuit and execute 4321 shots on a backend. .. code-block:: from qiskit import QuantumCircuit, execute, BasicAer backend = BasicAer.get_backend('qasm_simulator') qc = QuantumCircuit(5, 5) qc.h(0) qc.cx(0, range(1, 5)) qc.measure_all() job = execute(qc, backend, shots=4321) """ del qobj_id del qobj_header if isinstance(experiments, (Schedule, ScheduleBlock)) or ( isinstance(experiments, list) and isinstance(experiments[0], (Schedule, ScheduleBlock)) ): # do not transpile a schedule circuit if schedule_circuit: raise QiskitError("Must supply QuantumCircuit to schedule circuit.") elif pass_manager is not None: # transpiling using pass_manager _check_conflicting_argument( optimization_level=optimization_level, basis_gates=basis_gates, coupling_map=coupling_map, seed_transpiler=seed_transpiler, backend_properties=backend_properties, initial_layout=initial_layout, ) experiments = pass_manager.run(experiments) else: # transpiling the circuits using given transpile options experiments = transpile( experiments, basis_gates=basis_gates, coupling_map=coupling_map, backend_properties=backend_properties, initial_layout=initial_layout, seed_transpiler=seed_transpiler, optimization_level=optimization_level, backend=backend, ) if schedule_circuit: experiments = schedule( circuits=experiments, backend=backend, inst_map=inst_map, meas_map=meas_map, method=scheduling_method, ) if isinstance(backend, Backend): start_time = time() run_kwargs = { "shots": shots, "memory": memory, "seed_simulator": seed_simulator, "qubit_lo_freq": default_qubit_los, "meas_lo_freq": default_meas_los, "qubit_lo_range": qubit_lo_range, "meas_lo_range": meas_lo_range, "schedule_los": schedule_los, "meas_level": meas_level, "meas_return": meas_return, "memory_slots": memory_slots, "memory_slot_size": memory_slot_size, "rep_time": rep_time, "rep_delay": rep_delay, "init_qubits": init_qubits, } for key in list(run_kwargs.keys()): if not hasattr(backend.options, key): if run_kwargs[key] is not None: logger.info( "%s backend doesn't support option %s so not passing that kwarg to run()", backend.name, key, ) del run_kwargs[key] elif run_kwargs[key] is None: del run_kwargs[key] if parameter_binds: run_kwargs["parameter_binds"] = parameter_binds run_kwargs.update(run_config) job = backend.run(experiments, **run_kwargs) end_time = time() _log_submission_time(start_time, end_time) else: raise QiskitError("Invalid backend type %s" % type(backend)) return job def _check_conflicting_argument(**kargs): conflicting_args = [arg for arg, value in kargs.items() if value] if conflicting_args: raise QiskitError( "The parameters pass_manager conflicts with the following " "parameter(s): {}.".format(", ".join(conflicting_args)) )
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # 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. """Utils for reading a user preference config files.""" import configparser import os from qiskit import exceptions DEFAULT_FILENAME = os.path.join(os.path.expanduser("~"), '.qiskit', 'settings.conf') class UserConfig: """Class representing a user config file The config file format should look like: [default] circuit_drawer = mpl """ def __init__(self, filename=None): """Create a UserConfig Args: filename (str): The path to the user config file. If one isn't specified ~/.qiskit/settings.conf is used. """ if filename is None: self.filename = DEFAULT_FILENAME else: self.filename = filename self.settings = {} self.config_parser = configparser.ConfigParser() def read_config_file(self): """Read config file and parse the contents into the settings attr.""" if not os.path.isfile(self.filename): return self.config_parser.read(self.filename) if 'default' in self.config_parser.sections(): circuit_drawer = self.config_parser.get('default', 'circuit_drawer') if circuit_drawer: if circuit_drawer not in ['text', 'mpl', 'latex', 'latex_source']: raise exceptions.QiskitUserConfigError( "%s is not a valid circuit drawer backend. Must be " "either 'text', 'mpl', 'latex', or 'latex_source'" % circuit_drawer) self.settings['circuit_drawer'] = circuit_drawer def get_config(): """Read the config file from the default location or env var It will read a config file at either the default location ~/.qiskit/settings.conf or if set the value of the QISKIT_SETTINGS env var. It will return the parsed settings dict from the parsed config file. Returns: dict: The settings dict from the parsed config file. """ filename = os.getenv('QISKIT_SETTINGS', DEFAULT_FILENAME) if not os.path.isfile(filename): return {} user_config = UserConfig(filename) user_config.read_config_file() return user_config.settings
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=no-name-in-module,broad-except,cyclic-import """Contains Qiskit (terra) version.""" import os import subprocess from collections.abc import Mapping import warnings ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) def _minimal_ext_cmd(cmd): # construct minimal environment env = {} for k in ["SYSTEMROOT", "PATH"]: v = os.environ.get(k) if v is not None: env[k] = v # LANGUAGE is used on win32 env["LANGUAGE"] = "C" env["LANG"] = "C" env["LC_ALL"] = "C" with subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env, cwd=os.path.join(os.path.dirname(ROOT_DIR)), ) as proc: stdout, stderr = proc.communicate() if proc.returncode > 0: error_message = stderr.strip().decode("ascii") raise OSError(f"Command {cmd} exited with code {proc.returncode}: {error_message}") return stdout def git_version(): """Get the current git head sha1.""" # Determine if we're at main try: out = _minimal_ext_cmd(["git", "rev-parse", "HEAD"]) git_revision = out.strip().decode("ascii") except OSError: git_revision = "Unknown" return git_revision with open(os.path.join(ROOT_DIR, "VERSION.txt")) as version_file: VERSION = version_file.read().strip() def get_version_info(): """Get the full version string.""" # Adding the git rev number needs to be done inside # write_version_py(), otherwise the import of scipy.version messes # up the build under Python 3. full_version = VERSION if not os.path.exists(os.path.join(os.path.dirname(ROOT_DIR), ".git")): return full_version try: release = _minimal_ext_cmd(["git", "tag", "-l", "--points-at", "HEAD"]) except Exception: # pylint: disable=broad-except return full_version git_revision = git_version() if not release: full_version += ".dev0+" + git_revision[:7] return full_version __version__ = get_version_info() class QiskitVersion(Mapping): """DEPRECATED in 0.25.0 use qiskit.__version__""" __slots__ = ["_version_dict", "_loaded"] def __init__(self): self._version_dict = { "qiskit-terra": __version__, "qiskit": None, } self._loaded = False def _load_versions(self): warnings.warn( "qiskit.__qiskit_version__ is deprecated since " "Qiskit Terra 0.25.0, and will be removed 3 months or more later. " "Instead, you should use qiskit.__version__. The other packages listed in the" "former qiskit.__qiskit_version__ have their own __version__ module level dunder, " "as standard in PEP 8.", category=DeprecationWarning, stacklevel=3, ) from importlib.metadata import version try: # TODO: Update to use qiskit_aer instead when we remove the # namespace redirect from qiskit.providers import aer self._version_dict["qiskit-aer"] = aer.__version__ except Exception: self._version_dict["qiskit-aer"] = None try: from qiskit import ignis self._version_dict["qiskit-ignis"] = ignis.__version__ except Exception: self._version_dict["qiskit-ignis"] = None try: from qiskit.providers import ibmq self._version_dict["qiskit-ibmq-provider"] = ibmq.__version__ except Exception: self._version_dict["qiskit-ibmq-provider"] = None try: import qiskit_nature self._version_dict["qiskit-nature"] = qiskit_nature.__version__ except Exception: self._version_dict["qiskit-nature"] = None try: import qiskit_finance self._version_dict["qiskit-finance"] = qiskit_finance.__version__ except Exception: self._version_dict["qiskit-finance"] = None try: import qiskit_optimization self._version_dict["qiskit-optimization"] = qiskit_optimization.__version__ except Exception: self._version_dict["qiskit-optimization"] = None try: import qiskit_machine_learning self._version_dict["qiskit-machine-learning"] = qiskit_machine_learning.__version__ except Exception: self._version_dict["qiskit-machine-learning"] = None try: self._version_dict["qiskit"] = version("qiskit") except Exception: self._version_dict["qiskit"] = None self._loaded = True def __repr__(self): if not self._loaded: self._load_versions() return repr(self._version_dict) def __str__(self): if not self._loaded: self._load_versions() return str(self._version_dict) def __getitem__(self, key): if not self._loaded: self._load_versions() return self._version_dict[key] def __iter__(self): if not self._loaded: self._load_versions() return iter(self._version_dict) def __len__(self): return len(self._version_dict) __qiskit_version__ = QiskitVersion()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- 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=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# 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. """Evaluator of auxiliary operators for algorithms.""" from __future__ import annotations import numpy as np from qiskit import QuantumCircuit from qiskit.opflow import ( CircuitSampler, ListOp, StateFn, OperatorBase, ExpectationBase, ) from qiskit.providers import Backend from qiskit.quantum_info import Statevector from qiskit.utils import QuantumInstance from qiskit.utils.deprecation import deprecate_func from .list_or_dict import ListOrDict @deprecate_func( additional_msg=( "Instead, use the function " "``qiskit_algorithms.observables_evaluator.estimate_observables``. See " "https://qisk.it/algo_migration for a migration guide." ), since="0.24.0", ) def eval_observables( quantum_instance: QuantumInstance | Backend, quantum_state: Statevector | QuantumCircuit | OperatorBase, observables: ListOrDict[OperatorBase], expectation: ExpectationBase, threshold: float = 1e-12, ) -> ListOrDict[tuple[complex, complex]]: """ Deprecated: Accepts a list or a dictionary of operators and calculates their expectation values - means and standard deviations. They are calculated with respect to a quantum state provided. A user can optionally provide a threshold value which filters mean values falling below the threshold. This function has been superseded by the :func:`qiskit_algorithms.observables_evaluator.eval_observables` function. It will be deprecated in a future release and subsequently removed after that. Args: quantum_instance: A quantum instance used for calculations. quantum_state: An unparametrized quantum circuit representing a quantum state that expectation values are computed against. observables: A list or a dictionary of operators whose expectation values are to be calculated. expectation: An instance of ExpectationBase which defines a method for calculating expectation values. threshold: A threshold value that defines which mean values should be neglected (helpful for ignoring numerical instabilities close to 0). Returns: A list or a dictionary of tuples (mean, standard deviation). Raises: ValueError: If a ``quantum_state`` with free parameters is provided. """ if ( isinstance( quantum_state, (QuantumCircuit, OperatorBase) ) # Statevector cannot be parametrized and len(quantum_state.parameters) > 0 ): raise ValueError( "A parametrized representation of a quantum_state was provided. It is not " "allowed - it cannot have free parameters." ) # Create new CircuitSampler to avoid breaking existing one's caches. sampler = CircuitSampler(quantum_instance) list_op = _prepare_list_op(quantum_state, observables) observables_expect = expectation.convert(list_op) observables_expect_sampled = sampler.convert(observables_expect) # compute means values = np.real(observables_expect_sampled.eval()) # compute standard deviations # We use sampler.quantum_instance to take care of case in which quantum_instance is Backend std_devs = _compute_std_devs( observables_expect_sampled, observables, expectation, sampler.quantum_instance ) # Discard values below threshold observables_means = values * (np.abs(values) > threshold) # zip means and standard deviations into tuples observables_results = list(zip(observables_means, std_devs)) # Return None eigenvalues for None operators if observables is a list. # None operators are already dropped in compute_minimum_eigenvalue if observables is a dict. return _prepare_result(observables_results, observables) def _prepare_list_op( quantum_state: Statevector | QuantumCircuit | OperatorBase, observables: ListOrDict[OperatorBase], ) -> ListOp: """ Accepts a list or a dictionary of operators and converts them to a ``ListOp``. Args: quantum_state: An unparametrized quantum circuit representing a quantum state that expectation values are computed against. observables: A list or a dictionary of operators. Returns: A ``ListOp`` that includes all provided observables. """ if isinstance(observables, dict): observables = list(observables.values()) if not isinstance(quantum_state, StateFn): quantum_state = StateFn(quantum_state) return ListOp([StateFn(obs, is_measurement=True).compose(quantum_state) for obs in observables]) def _prepare_result( observables_results: list[tuple[complex, complex]], observables: ListOrDict[OperatorBase], ) -> ListOrDict[tuple[complex, complex]]: """ Prepares a list or a dictionary of eigenvalues from ``observables_results`` and ``observables``. Args: observables_results: A list of of tuples (mean, standard deviation). observables: A list or a dictionary of operators whose expectation values are to be calculated. Returns: A list or a dictionary of tuples (mean, standard deviation). """ if isinstance(observables, list): observables_eigenvalues: ListOrDict[tuple[complex, complex]] = [None] * len(observables) key_value_iterator = enumerate(observables_results) else: observables_eigenvalues = {} key_value_iterator = zip(observables.keys(), observables_results) for key, value in key_value_iterator: if observables[key] is not None: observables_eigenvalues[key] = value return observables_eigenvalues def _compute_std_devs( observables_expect_sampled: OperatorBase, observables: ListOrDict[OperatorBase], expectation: ExpectationBase, quantum_instance: QuantumInstance | Backend, ) -> list[complex]: """ Calculates a list of standard deviations from expectation values of observables provided. Args: observables_expect_sampled: Expected values of observables. observables: A list or a dictionary of operators whose expectation values are to be calculated. expectation: An instance of ExpectationBase which defines a method for calculating expectation values. quantum_instance: A quantum instance used for calculations. Returns: A list of standard deviations. """ variances = np.real(expectation.compute_variance(observables_expect_sampled)) if not isinstance(variances, np.ndarray) and variances == 0.0: # when `variances` is a single value equal to 0., our expectation value is exact and we # manually ensure the variances to be a list of the correct length variances = np.zeros(len(observables), dtype=float) # TODO: this will crash if quantum_instance is a backend std_devs = np.sqrt(variances / quantum_instance.run_config.shots) return std_devs
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# 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. """Evaluator of observables for algorithms.""" from __future__ import annotations from collections.abc import Sequence from typing import Any import numpy as np from qiskit import QuantumCircuit from qiskit.opflow import PauliSumOp from qiskit.quantum_info import SparsePauliOp from .exceptions import AlgorithmError from .list_or_dict import ListOrDict from ..primitives import BaseEstimator from ..quantum_info.operators.base_operator import BaseOperator def estimate_observables( estimator: BaseEstimator, quantum_state: QuantumCircuit, observables: ListOrDict[BaseOperator | PauliSumOp], parameter_values: Sequence[float] | None = None, threshold: float = 1e-12, ) -> ListOrDict[tuple[complex, dict[str, Any]]]: """ Accepts a sequence of operators and calculates their expectation values - means and metadata. They are calculated with respect to a quantum state provided. A user can optionally provide a threshold value which filters mean values falling below the threshold. Args: estimator: An estimator primitive used for calculations. quantum_state: A (parameterized) quantum circuit preparing a quantum state that expectation values are computed against. observables: A list or a dictionary of operators whose expectation values are to be calculated. parameter_values: Optional list of parameters values to evaluate the quantum circuit on. threshold: A threshold value that defines which mean values should be neglected (helpful for ignoring numerical instabilities close to 0). Returns: A list or a dictionary of tuples (mean, metadata). Raises: AlgorithmError: If a primitive job is not successful. """ if isinstance(observables, dict): observables_list = list(observables.values()) else: observables_list = observables if len(observables_list) > 0: observables_list = _handle_zero_ops(observables_list) quantum_state = [quantum_state] * len(observables) if parameter_values is not None: parameter_values = [parameter_values] * len(observables) try: estimator_job = estimator.run(quantum_state, observables_list, parameter_values) expectation_values = estimator_job.result().values except Exception as exc: raise AlgorithmError("The primitive job failed!") from exc metadata = estimator_job.result().metadata # Discard values below threshold observables_means = expectation_values * (np.abs(expectation_values) > threshold) # zip means and metadata into tuples observables_results = list(zip(observables_means, metadata)) else: observables_results = [] return _prepare_result(observables_results, observables) def _handle_zero_ops( observables_list: list[BaseOperator | PauliSumOp], ) -> list[BaseOperator | PauliSumOp]: """Replaces all occurrence of operators equal to 0 in the list with an equivalent ``PauliSumOp`` operator.""" if observables_list: zero_op = SparsePauliOp.from_list([("I" * observables_list[0].num_qubits, 0)]) for ind, observable in enumerate(observables_list): if observable == 0: observables_list[ind] = zero_op return observables_list def _prepare_result( observables_results: list[tuple[complex, dict]], observables: ListOrDict[BaseOperator | PauliSumOp], ) -> ListOrDict[tuple[complex, dict[str, Any]]]: """ Prepares a list of tuples of eigenvalues and metadata tuples from ``observables_results`` and ``observables``. Args: observables_results: A list of tuples (mean, metadata). observables: A list or a dictionary of operators whose expectation values are to be calculated. Returns: A list or a dictionary of tuples (mean, metadata). """ if isinstance(observables, list): # by construction, all None values will be overwritten observables_eigenvalues: ListOrDict[tuple[complex, complex]] = [None] * len(observables) key_value_iterator = enumerate(observables_results) else: observables_eigenvalues = {} key_value_iterator = zip(observables.keys(), observables_results) for key, value in key_value_iterator: observables_eigenvalues[key] = value return observables_eigenvalues
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- 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=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
"""Python implementation of Grovers algorithm through use of the Qiskit library to find the value 3 (|11>) out of four possible values.""" #import numpy and plot library import matplotlib.pyplot as plt import numpy as np # importing Qiskit from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.providers.ibmq import least_busy from qiskit.quantum_info import Statevector # import basic plot tools from qiskit.visualization import plot_histogram # define variables, 1) initialize qubits to zero n = 2 grover_circuit = QuantumCircuit(n) #define initialization function def initialize_s(qc, qubits): '''Apply a H-gate to 'qubits' in qc''' for q in qubits: qc.h(q) return qc ### begin grovers circuit ### #2) Put qubits in equal state of superposition grover_circuit = initialize_s(grover_circuit, [0,1]) # 3) Apply oracle reflection to marked instance x_0 = 3, (|11>) grover_circuit.cz(0,1) statevec = job_sim.result().get_statevector() from qiskit_textbook.tools import vector2latex vector2latex(statevec, pretext="|\\psi\\rangle =") # 4) apply additional reflection (diffusion operator) grover_circuit.h([0,1]) grover_circuit.z([0,1]) grover_circuit.cz(0,1) grover_circuit.h([0,1]) # 5) measure the qubits grover_circuit.measure_all() # Load IBM Q account and get the least busy backend device provider = IBMQ.load_account() device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and not x.configuration().simulator and x.status().operational==True)) print("Running on current least busy device: ", device) from qiskit.tools.monitor import job_monitor job = execute(grover_circuit, backend=device, shots=1024, optimization_level=3) job_monitor(job, interval = 2) results = job.result() answer = results.get_counts(grover_circuit) plot_histogram(answer) #highest amplitude should correspond with marked value x_0 (|11>)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- 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. """ The Amplitude Estimation Algorithm. """ import logging from collections import OrderedDict import numpy as np from qiskit import ClassicalRegister from qiskit.aqua import AquaError from qiskit.aqua import Pluggable, PluggableType, get_pluggable_class from qiskit.aqua.algorithms import QuantumAlgorithm from qiskit.aqua.circuits import PhaseEstimationCircuit from qiskit.aqua.components.iqfts import Standard from .q_factory import QFactory logger = logging.getLogger(__name__) class AmplitudeEstimation(QuantumAlgorithm): """ The Amplitude Estimation algorithm. """ CONFIGURATION = { 'name': 'AmplitudeEstimation', 'description': 'Amplitude Estimation Algorithm', 'input_schema': { '$schema': 'http://json-schema.org/schema#', 'id': 'AmplitudeEstimation_schema', 'type': 'object', 'properties': { 'num_eval_qubits': { 'type': 'integer', 'default': 5, 'minimum': 1 } }, 'additionalProperties': False }, 'problems': ['uncertainty'], 'depends': [ { 'pluggable_type': 'uncertainty_problem', 'default': { 'name': 'EuropeanCallDelta' } }, { 'pluggable_type': 'iqft', 'default': { 'name': 'STANDARD', } }, ], } def __init__(self, num_eval_qubits, a_factory, i_objective=None, q_factory=None, iqft=None): """ Constructor. Args: num_eval_qubits (int): number of evaluation qubits a_factory (CircuitFactory): the CircuitFactory subclass object representing the problem unitary q_factory (CircuitFactory): the CircuitFactory subclass object representing an amplitude estimation sample (based on a_factory) iqft (IQFT): the Inverse Quantum Fourier Transform pluggable component, defaults to using a standard iqft when None """ self.validate(locals()) super().__init__() # get/construct A/Q operator self.a_factory = a_factory if q_factory is None: if i_objective is None: i_objective = self.a_factory.num_target_qubits - 1 self.q_factory = QFactory(a_factory, i_objective) else: self.q_factory = q_factory # get parameters self._m = num_eval_qubits self._M = 2 ** num_eval_qubits # determine number of ancillas self._num_ancillas = self.q_factory.required_ancillas_controlled() self._num_qubits = self.a_factory.num_target_qubits + self._m + self._num_ancillas if iqft is None: iqft = Standard(self._m) self._iqft = iqft self._circuit = None self._ret = {} @classmethod def init_params(cls, params, algo_input): """ Initialize via parameters dictionary and algorithm input instance Args: params: parameters dictionary algo_input: Input instance """ if algo_input is not None: raise AquaError("Input instance not supported.") ae_params = params.get(Pluggable.SECTION_KEY_ALGORITHM) num_eval_qubits = ae_params.get('num_eval_qubits') # Set up uncertainty problem. The params can include an uncertainty model # type dependent on the uncertainty problem and is this its responsibility # to create for itself from the complete params set that is passed to it. uncertainty_problem_params = params.get(Pluggable.SECTION_KEY_UNCERTAINTY_PROBLEM) uncertainty_problem = get_pluggable_class( PluggableType.UNCERTAINTY_PROBLEM, uncertainty_problem_params['name']).init_params(params) # Set up iqft, we need to add num qubits to params which is our num_ancillae bits here iqft_params = params.get(Pluggable.SECTION_KEY_IQFT) iqft_params['num_qubits'] = num_eval_qubits iqft = get_pluggable_class(PluggableType.IQFT, iqft_params['name']).init_params(params) return cls(num_eval_qubits, uncertainty_problem, q_factory=None, iqft=iqft) def construct_circuit(self, measurement=False): """ Construct the Amplitude Estimation quantum circuit. Args: measurement (bool): Boolean flag to indicate if measurement should be included in the circuit. Returns: the QuantumCircuit object for the constructed circuit """ pec = PhaseEstimationCircuit( iqft=self._iqft, num_ancillae=self._m, state_in_circuit_factory=self.a_factory, unitary_circuit_factory=self.q_factory ) self._circuit = pec.construct_circuit(measurement=measurement) return self._circuit def _evaluate_statevector_results(self, probabilities): # map measured results to estimates y_probabilities = OrderedDict() for i, probability in enumerate(probabilities): b = "{0:b}".format(i).rjust(self._num_qubits, '0')[::-1] y = int(b[:self._m], 2) y_probabilities[y] = y_probabilities.get(y, 0) + probability a_probabilities = OrderedDict() for y, probability in y_probabilities.items(): if y >= int(self._M / 2): y = self._M - y a = np.power(np.sin(y * np.pi / 2 ** self._m), 2) a_probabilities[a] = a_probabilities.get(a, 0) + probability return a_probabilities, y_probabilities def _run(self): if self._quantum_instance.is_statevector: self.construct_circuit(measurement=False) # run circuit on statevector simlator ret = self._quantum_instance.execute(self._circuit) state_vector = np.asarray([ret.get_statevector(self._circuit)]) self._ret['statevector'] = state_vector # get state probabilities state_probabilities = np.real(state_vector.conj() * state_vector)[0] # evaluate results a_probabilities, y_probabilities = self._evaluate_statevector_results(state_probabilities) else: # run circuit on QASM simulator self.construct_circuit(measurement=True) ret = self._quantum_instance.execute(self._circuit) # get counts self._ret['counts'] = ret.get_counts() # construct probabilities y_probabilities = {} a_probabilities = {} shots = sum(ret.get_counts().values()) for state, counts in ret.get_counts().items(): y = int(state.replace(' ', '')[:self._m][::-1], 2) p = counts / shots y_probabilities[y] = p a = np.power(np.sin(y * np.pi / 2 ** self._m), 2) a_probabilities[a] = a_probabilities.get(a, 0.0) + p # construct a_items and y_items a_items = [(a, p) for (a, p) in a_probabilities.items() if p > 1e-6] y_items = [(y, p) for (y, p) in y_probabilities.items() if p > 1e-6] a_items = sorted(a_items) y_items = sorted(y_items) self._ret['a_items'] = a_items self._ret['y_items'] = y_items # map estimated values to original range and extract probabilities self._ret['mapped_values'] = [self.a_factory.value_to_estimation(a_item[0]) for a_item in self._ret['a_items']] self._ret['values'] = [a_item[0] for a_item in self._ret['a_items']] self._ret['y_values'] = [y_item[0] for y_item in y_items] self._ret['probabilities'] = [a_item[1] for a_item in self._ret['a_items']] self._ret['mapped_items'] = [(self._ret['mapped_values'][i], self._ret['probabilities'][i]) for i in range(len(self._ret['mapped_values']))] # determine most likely estimator self._ret['estimation'] = None self._ret['max_probability'] = 0 for val, prob in self._ret['mapped_items']: if prob > self._ret['max_probability']: self._ret['max_probability'] = prob self._ret['estimation'] = val return self._ret
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 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. """The Iterative Quantum Amplitude Estimation Algorithm.""" from __future__ import annotations from typing import cast import warnings import numpy as np from scipy.stats import beta from qiskit import ClassicalRegister, QuantumCircuit from qiskit.providers import Backend from qiskit.primitives import BaseSampler from qiskit.utils import QuantumInstance from qiskit.utils.deprecation import deprecate_arg, deprecate_func from .amplitude_estimator import AmplitudeEstimator, AmplitudeEstimatorResult from .estimation_problem import EstimationProblem from ..exceptions import AlgorithmError class IterativeAmplitudeEstimation(AmplitudeEstimator): r"""The Iterative Amplitude Estimation algorithm. This class implements the Iterative Quantum Amplitude Estimation (IQAE) algorithm, proposed in [1]. The output of the algorithm is an estimate that, with at least probability :math:`1 - \alpha`, differs by epsilon to the target value, where both alpha and epsilon can be specified. It differs from the original QAE algorithm proposed by Brassard [2] in that it does not rely on Quantum Phase Estimation, but is only based on Grover's algorithm. IQAE iteratively applies carefully selected Grover iterations to find an estimate for the target amplitude. References: [1]: Grinko, D., Gacon, J., Zoufal, C., & Woerner, S. (2019). Iterative Quantum Amplitude Estimation. `arXiv:1912.05559 <https://arxiv.org/abs/1912.05559>`_. [2]: Brassard, G., Hoyer, P., Mosca, M., & Tapp, A. (2000). Quantum Amplitude Amplification and Estimation. `arXiv:quant-ph/0005055 <http://arxiv.org/abs/quant-ph/0005055>`_. """ @deprecate_arg( "quantum_instance", additional_msg=( "Instead, use the ``sampler`` argument. See https://qisk.it/algo_migration for a " "migration guide." ), since="0.24.0", ) def __init__( self, epsilon_target: float, alpha: float, confint_method: str = "beta", min_ratio: float = 2, quantum_instance: QuantumInstance | Backend | None = None, sampler: BaseSampler | None = None, ) -> None: r""" The output of the algorithm is an estimate for the amplitude `a`, that with at least probability 1 - alpha has an error of epsilon. The number of A operator calls scales linearly in 1/epsilon (up to a logarithmic factor). Args: epsilon_target: Target precision for estimation target `a`, has values between 0 and 0.5 alpha: Confidence level, the target probability is 1 - alpha, has values between 0 and 1 confint_method: Statistical method used to estimate the confidence intervals in each iteration, can be 'chernoff' for the Chernoff intervals or 'beta' for the Clopper-Pearson intervals (default) min_ratio: Minimal q-ratio (:math:`K_{i+1} / K_i`) for FindNextK quantum_instance: Deprecated: Quantum Instance or Backend sampler: A sampler primitive to evaluate the circuits. Raises: AlgorithmError: if the method to compute the confidence intervals is not supported ValueError: If the target epsilon is not in (0, 0.5] ValueError: If alpha is not in (0, 1) ValueError: If confint_method is not supported """ # validate ranges of input arguments if not 0 < epsilon_target <= 0.5: raise ValueError(f"The target epsilon must be in (0, 0.5], but is {epsilon_target}.") if not 0 < alpha < 1: raise ValueError(f"The confidence level alpha must be in (0, 1), but is {alpha}") if confint_method not in {"chernoff", "beta"}: raise ValueError( f"The confidence interval method must be chernoff or beta, but is {confint_method}." ) super().__init__() # set quantum instance with warnings.catch_warnings(): warnings.simplefilter("ignore") self.quantum_instance = quantum_instance # store parameters self._epsilon = epsilon_target self._alpha = alpha self._min_ratio = min_ratio self._confint_method = confint_method self._sampler = sampler @property def sampler(self) -> BaseSampler | None: """Get the sampler primitive. Returns: The sampler primitive to evaluate the circuits. """ return self._sampler @sampler.setter def sampler(self, sampler: BaseSampler) -> None: """Set sampler primitive. Args: sampler: A sampler primitive to evaluate the circuits. """ self._sampler = sampler @property @deprecate_func( since="0.24.0", is_property=True, additional_msg="See https://qisk.it/algo_migration for a migration guide.", ) def quantum_instance(self) -> QuantumInstance | None: """Deprecated. Get the quantum instance. Returns: The quantum instance used to run this algorithm. """ return self._quantum_instance @quantum_instance.setter @deprecate_func( since="0.24.0", is_property=True, additional_msg="See https://qisk.it/algo_migration for a migration guide.", ) def quantum_instance(self, quantum_instance: QuantumInstance | Backend) -> None: """Deprecated. Set quantum instance. Args: quantum_instance: The quantum instance used to run this algorithm. """ if isinstance(quantum_instance, Backend): quantum_instance = QuantumInstance(quantum_instance) self._quantum_instance = quantum_instance @property def epsilon_target(self) -> float: """Returns the target precision ``epsilon_target`` of the algorithm. Returns: The target precision (which is half the width of the confidence interval). """ return self._epsilon @epsilon_target.setter def epsilon_target(self, epsilon: float) -> None: """Set the target precision of the algorithm. Args: epsilon: Target precision for estimation target `a`. """ self._epsilon = epsilon def _find_next_k( self, k: int, upper_half_circle: bool, theta_interval: tuple[float, float], min_ratio: float = 2.0, ) -> tuple[int, bool]: """Find the largest integer k_next, such that the interval (4 * k_next + 2)*theta_interval lies completely in [0, pi] or [pi, 2pi], for theta_interval = (theta_lower, theta_upper). Args: k: The current power of the Q operator. upper_half_circle: Boolean flag of whether theta_interval lies in the upper half-circle [0, pi] or in the lower one [pi, 2pi]. theta_interval: The current confidence interval for the angle theta, i.e. (theta_lower, theta_upper). min_ratio: Minimal ratio K/K_next allowed in the algorithm. Returns: The next power k, and boolean flag for the extrapolated interval. Raises: AlgorithmError: if min_ratio is smaller or equal to 1 """ if min_ratio <= 1: raise AlgorithmError("min_ratio must be larger than 1 to ensure convergence") # initialize variables theta_l, theta_u = theta_interval old_scaling = 4 * k + 2 # current scaling factor, called K := (4k + 2) # the largest feasible scaling factor K cannot be larger than K_max, # which is bounded by the length of the current confidence interval max_scaling = int(1 / (2 * (theta_u - theta_l))) scaling = max_scaling - (max_scaling - 2) % 4 # bring into the form 4 * k_max + 2 # find the largest feasible scaling factor K_next, and thus k_next while scaling >= min_ratio * old_scaling: theta_min = scaling * theta_l - int(scaling * theta_l) theta_max = scaling * theta_u - int(scaling * theta_u) if theta_min <= theta_max <= 0.5 and theta_min <= 0.5: # the extrapolated theta interval is in the upper half-circle upper_half_circle = True return int((scaling - 2) / 4), upper_half_circle elif theta_max >= 0.5 and theta_max >= theta_min >= 0.5: # the extrapolated theta interval is in the upper half-circle upper_half_circle = False return int((scaling - 2) / 4), upper_half_circle scaling -= 4 # if we do not find a feasible k, return the old one return int(k), upper_half_circle def construct_circuit( self, estimation_problem: EstimationProblem, k: int = 0, measurement: bool = False ) -> QuantumCircuit: r"""Construct the circuit :math:`\mathcal{Q}^k \mathcal{A} |0\rangle`. The A operator is the unitary specifying the QAE problem and Q the associated Grover operator. Args: estimation_problem: The estimation problem for which to construct the QAE circuit. k: The power of the Q operator. measurement: Boolean flag to indicate if measurements should be included in the circuits. Returns: The circuit implementing :math:`\mathcal{Q}^k \mathcal{A} |0\rangle`. """ num_qubits = max( estimation_problem.state_preparation.num_qubits, estimation_problem.grover_operator.num_qubits, ) circuit = QuantumCircuit(num_qubits, name="circuit") # add classical register if needed if measurement: c = ClassicalRegister(len(estimation_problem.objective_qubits)) circuit.add_register(c) # add A operator circuit.compose(estimation_problem.state_preparation, inplace=True) # add Q^k if k != 0: circuit.compose(estimation_problem.grover_operator.power(k), inplace=True) # add optional measurement if measurement: # real hardware can currently not handle operations after measurements, which might # happen if the circuit gets transpiled, hence we're adding a safeguard-barrier circuit.barrier() circuit.measure(estimation_problem.objective_qubits, c[:]) return circuit def _good_state_probability( self, problem: EstimationProblem, counts_or_statevector: dict[str, int] | np.ndarray, num_state_qubits: int, ) -> tuple[int, float] | float: """Get the probability to measure '1' in the last qubit. Args: problem: The estimation problem, used to obtain the number of objective qubits and the ``is_good_state`` function. counts_or_statevector: Either a counts-dictionary (with one measured qubit only!) or the statevector returned from the statevector_simulator. num_state_qubits: The number of state qubits. Returns: If a dict is given, return (#one-counts, #one-counts/#all-counts), otherwise Pr(measure '1' in the last qubit). """ if isinstance(counts_or_statevector, dict): one_counts = 0 for state, counts in counts_or_statevector.items(): if problem.is_good_state(state): one_counts += counts return int(one_counts), one_counts / sum(counts_or_statevector.values()) else: statevector = counts_or_statevector num_qubits = int(np.log2(len(statevector))) # the total number of qubits # sum over all amplitudes where the objective qubit is 1 prob = 0 for i, amplitude in enumerate(statevector): # consider only state qubits and revert bit order bitstr = bin(i)[2:].zfill(num_qubits)[-num_state_qubits:][::-1] objectives = [bitstr[index] for index in problem.objective_qubits] if problem.is_good_state(objectives): prob = prob + np.abs(amplitude) ** 2 return prob def estimate( self, estimation_problem: EstimationProblem ) -> "IterativeAmplitudeEstimationResult": """Run the amplitude estimation algorithm on provided estimation problem. Args: estimation_problem: The estimation problem. Returns: An amplitude estimation results object. Raises: ValueError: A quantum instance or Sampler must be provided. AlgorithmError: Sampler job run error. """ if self._quantum_instance is None and self._sampler is None: raise ValueError("A quantum instance or sampler must be provided.") # initialize memory variables powers = [0] # list of powers k: Q^k, (called 'k' in paper) ratios = [] # list of multiplication factors (called 'q' in paper) theta_intervals = [[0, 1 / 4]] # a priori knowledge of theta / 2 / pi a_intervals = [[0.0, 1.0]] # a priori knowledge of the confidence interval of the estimate num_oracle_queries = 0 num_one_shots = [] # maximum number of rounds max_rounds = ( int(np.log(self._min_ratio * np.pi / 8 / self._epsilon) / np.log(self._min_ratio)) + 1 ) upper_half_circle = True # initially theta is in the upper half-circle if self._quantum_instance is not None and self._quantum_instance.is_statevector: # for statevector we can directly return the probability to measure 1 # note, that no iterations here are necessary # simulate circuit circuit = self.construct_circuit(estimation_problem, k=0, measurement=False) ret = self._quantum_instance.execute(circuit) # get statevector statevector = ret.get_statevector(circuit) # calculate the probability of measuring '1' num_qubits = circuit.num_qubits - circuit.num_ancillas prob = self._good_state_probability(estimation_problem, statevector, num_qubits) prob = cast(float, prob) # tell MyPy it's a float and not Tuple[int, float ] a_confidence_interval = [prob, prob] # type: list[float] a_intervals.append(a_confidence_interval) theta_i_interval = [ np.arccos(1 - 2 * a_i) / 2 / np.pi for a_i in a_confidence_interval # type: ignore ] theta_intervals.append(theta_i_interval) num_oracle_queries = 0 # no Q-oracle call, only a single one to A else: num_iterations = 0 # keep track of the number of iterations # number of shots per iteration shots = 0 # do while loop, keep in mind that we scaled theta mod 2pi such that it lies in [0,1] while theta_intervals[-1][1] - theta_intervals[-1][0] > self._epsilon / np.pi: num_iterations += 1 # get the next k k, upper_half_circle = self._find_next_k( powers[-1], upper_half_circle, theta_intervals[-1], # type: ignore min_ratio=self._min_ratio, ) # store the variables powers.append(k) ratios.append((2 * powers[-1] + 1) / (2 * powers[-2] + 1)) # run measurements for Q^k A|0> circuit circuit = self.construct_circuit(estimation_problem, k, measurement=True) counts = {} if self._quantum_instance is not None: ret = self._quantum_instance.execute(circuit) # get the counts and store them counts = ret.get_counts(circuit) shots = self._quantum_instance._run_config.shots else: try: job = self._sampler.run([circuit]) ret = job.result() except Exception as exc: raise AlgorithmError("The job was not completed successfully. ") from exc shots = ret.metadata[0].get("shots") if shots is None: circuit = self.construct_circuit(estimation_problem, k=0, measurement=True) try: job = self._sampler.run([circuit]) ret = job.result() except Exception as exc: raise AlgorithmError( "The job was not completed successfully. " ) from exc # calculate the probability of measuring '1' prob = 0.0 for bit, probabilities in ret.quasi_dists[0].binary_probabilities().items(): # check if it is a good state if estimation_problem.is_good_state(bit): prob += probabilities a_confidence_interval = [prob, prob] a_intervals.append(a_confidence_interval) theta_i_interval = [ np.arccos(1 - 2 * a_i) / 2 / np.pi for a_i in a_confidence_interval ] theta_intervals.append(theta_i_interval) num_oracle_queries = 0 # no Q-oracle call, only a single one to A break counts = { k: round(v * shots) for k, v in ret.quasi_dists[0].binary_probabilities().items() } # calculate the probability of measuring '1', 'prob' is a_i in the paper num_qubits = circuit.num_qubits - circuit.num_ancillas # type: ignore one_counts, prob = self._good_state_probability( estimation_problem, counts, num_qubits ) num_one_shots.append(one_counts) # track number of Q-oracle calls num_oracle_queries += shots * k # if on the previous iterations we have K_{i-1} == K_i, we sum these samples up j = 1 # number of times we stayed fixed at the same K round_shots = shots round_one_counts = one_counts if num_iterations > 1: while ( powers[num_iterations - j] == powers[num_iterations] and num_iterations >= j + 1 ): j = j + 1 round_shots += shots round_one_counts += num_one_shots[-j] # compute a_min_i, a_max_i if self._confint_method == "chernoff": a_i_min, a_i_max = _chernoff_confint(prob, round_shots, max_rounds, self._alpha) else: # 'beta' a_i_min, a_i_max = _clopper_pearson_confint( round_one_counts, round_shots, self._alpha / max_rounds ) # compute theta_min_i, theta_max_i if upper_half_circle: theta_min_i = np.arccos(1 - 2 * a_i_min) / 2 / np.pi theta_max_i = np.arccos(1 - 2 * a_i_max) / 2 / np.pi else: theta_min_i = 1 - np.arccos(1 - 2 * a_i_max) / 2 / np.pi theta_max_i = 1 - np.arccos(1 - 2 * a_i_min) / 2 / np.pi # compute theta_u, theta_l of this iteration scaling = 4 * k + 2 # current K_i factor theta_u = (int(scaling * theta_intervals[-1][1]) + theta_max_i) / scaling theta_l = (int(scaling * theta_intervals[-1][0]) + theta_min_i) / scaling theta_intervals.append([theta_l, theta_u]) # compute a_u_i, a_l_i a_u = np.sin(2 * np.pi * theta_u) ** 2 a_l = np.sin(2 * np.pi * theta_l) ** 2 a_u = cast(float, a_u) a_l = cast(float, a_l) a_intervals.append([a_l, a_u]) # get the latest confidence interval for the estimate of a confidence_interval = tuple(a_intervals[-1]) # the final estimate is the mean of the confidence interval estimation = np.mean(confidence_interval) result = IterativeAmplitudeEstimationResult() result.alpha = self._alpha result.post_processing = estimation_problem.post_processing result.num_oracle_queries = num_oracle_queries result.estimation = estimation result.epsilon_estimated = (confidence_interval[1] - confidence_interval[0]) / 2 result.confidence_interval = confidence_interval result.estimation_processed = estimation_problem.post_processing(estimation) confidence_interval = tuple( estimation_problem.post_processing(x) for x in confidence_interval ) result.confidence_interval_processed = confidence_interval result.epsilon_estimated_processed = (confidence_interval[1] - confidence_interval[0]) / 2 result.estimate_intervals = a_intervals result.theta_intervals = theta_intervals result.powers = powers result.ratios = ratios return result class IterativeAmplitudeEstimationResult(AmplitudeEstimatorResult): """The ``IterativeAmplitudeEstimation`` result object.""" def __init__(self) -> None: super().__init__() self._alpha: float | None = None self._epsilon_target: float | None = None self._epsilon_estimated: float | None = None self._epsilon_estimated_processed: float | None = None self._estimate_intervals: list[list[float]] | None = None self._theta_intervals: list[list[float]] | None = None self._powers: list[int] | None = None self._ratios: list[float] | None = None self._confidence_interval_processed: tuple[float, float] | None = None @property def alpha(self) -> float: r"""Return the confidence level :math:`\alpha`.""" return self._alpha @alpha.setter def alpha(self, value: float) -> None: r"""Set the confidence level :math:`\alpha`.""" self._alpha = value @property def epsilon_target(self) -> float: """Return the target half-width of the confidence interval.""" return self._epsilon_target @epsilon_target.setter def epsilon_target(self, value: float) -> None: """Set the target half-width of the confidence interval.""" self._epsilon_target = value @property def epsilon_estimated(self) -> float: """Return the estimated half-width of the confidence interval.""" return self._epsilon_estimated @epsilon_estimated.setter def epsilon_estimated(self, value: float) -> None: """Set the estimated half-width of the confidence interval.""" self._epsilon_estimated = value @property def epsilon_estimated_processed(self) -> float: """Return the post-processed estimated half-width of the confidence interval.""" return self._epsilon_estimated_processed @epsilon_estimated_processed.setter def epsilon_estimated_processed(self, value: float) -> None: """Set the post-processed estimated half-width of the confidence interval.""" self._epsilon_estimated_processed = value @property def estimate_intervals(self) -> list[list[float]]: """Return the confidence intervals for the estimate in each iteration.""" return self._estimate_intervals @estimate_intervals.setter def estimate_intervals(self, value: list[list[float]]) -> None: """Set the confidence intervals for the estimate in each iteration.""" self._estimate_intervals = value @property def theta_intervals(self) -> list[list[float]]: """Return the confidence intervals for the angles in each iteration.""" return self._theta_intervals @theta_intervals.setter def theta_intervals(self, value: list[list[float]]) -> None: """Set the confidence intervals for the angles in each iteration.""" self._theta_intervals = value @property def powers(self) -> list[int]: """Return the powers of the Grover operator in each iteration.""" return self._powers @powers.setter def powers(self, value: list[int]) -> None: """Set the powers of the Grover operator in each iteration.""" self._powers = value @property def ratios(self) -> list[float]: r"""Return the ratios :math:`K_{i+1}/K_{i}` for each iteration :math:`i`.""" return self._ratios @ratios.setter def ratios(self, value: list[float]) -> None: r"""Set the ratios :math:`K_{i+1}/K_{i}` for each iteration :math:`i`.""" self._ratios = value @property def confidence_interval_processed(self) -> tuple[float, float]: """Return the post-processed confidence interval.""" return self._confidence_interval_processed @confidence_interval_processed.setter def confidence_interval_processed(self, value: tuple[float, float]) -> None: """Set the post-processed confidence interval.""" self._confidence_interval_processed = value def _chernoff_confint( value: float, shots: int, max_rounds: int, alpha: float ) -> tuple[float, float]: """Compute the Chernoff confidence interval for `shots` i.i.d. Bernoulli trials. The confidence interval is [value - eps, value + eps], where eps = sqrt(3 * log(2 * max_rounds/ alpha) / shots) but at most [0, 1]. Args: value: The current estimate. shots: The number of shots. max_rounds: The maximum number of rounds, used to compute epsilon_a. alpha: The confidence level, used to compute epsilon_a. Returns: The Chernoff confidence interval. """ eps = np.sqrt(3 * np.log(2 * max_rounds / alpha) / shots) lower = np.maximum(0, value - eps) upper = np.minimum(1, value + eps) return lower, upper def _clopper_pearson_confint(counts: int, shots: int, alpha: float) -> tuple[float, float]: """Compute the Clopper-Pearson confidence interval for `shots` i.i.d. Bernoulli trials. Args: counts: The number of positive counts. shots: The number of shots. alpha: The confidence level for the confidence interval. Returns: The Clopper-Pearson confidence interval. """ lower, upper = 0, 1 # if counts == 0, the beta quantile returns nan if counts != 0: lower = beta.ppf(alpha / 2, counts, shots - counts + 1) # if counts == shots, the beta quantile returns nan if counts != shots: upper = beta.ppf(1 - alpha / 2, counts + 1, shots - counts) return lower, upper
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 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. """The Maximum Likelihood Amplitude Estimation algorithm.""" from __future__ import annotations import warnings from collections.abc import Sequence from typing import Callable, List, Tuple import numpy as np from scipy.optimize import brute from scipy.stats import norm, chi2 from qiskit.providers import Backend from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit from qiskit.utils import QuantumInstance from qiskit.primitives import BaseSampler from qiskit.utils.deprecation import deprecate_arg, deprecate_func from .amplitude_estimator import AmplitudeEstimator, AmplitudeEstimatorResult from .estimation_problem import EstimationProblem from ..exceptions import AlgorithmError MINIMIZER = Callable[[Callable[[float], float], List[Tuple[float, float]]], float] class MaximumLikelihoodAmplitudeEstimation(AmplitudeEstimator): """The Maximum Likelihood Amplitude Estimation algorithm. This class implements the quantum amplitude estimation (QAE) algorithm without phase estimation, as introduced in [1]. In comparison to the original QAE algorithm [2], this implementation relies solely on different powers of the Grover operator and does not require additional evaluation qubits. Finally, the estimate is determined via a maximum likelihood estimation, which is why this class in named ``MaximumLikelihoodAmplitudeEstimation``. References: [1]: Suzuki, Y., Uno, S., Raymond, R., Tanaka, T., Onodera, T., & Yamamoto, N. (2019). Amplitude Estimation without Phase Estimation. `arXiv:1904.10246 <https://arxiv.org/abs/1904.10246>`_. [2]: Brassard, G., Hoyer, P., Mosca, M., & Tapp, A. (2000). Quantum Amplitude Amplification and Estimation. `arXiv:quant-ph/0005055 <http://arxiv.org/abs/quant-ph/0005055>`_. """ @deprecate_arg( "quantum_instance", additional_msg=( "Instead, use the ``sampler`` argument. See https://qisk.it/algo_migration for a " "migration guide." ), since="0.24.0", ) def __init__( self, evaluation_schedule: list[int] | int, minimizer: MINIMIZER | None = None, quantum_instance: QuantumInstance | Backend | None = None, sampler: BaseSampler | None = None, ) -> None: r""" Args: evaluation_schedule: If a list, the powers applied to the Grover operator. The list element must be non-negative. If a non-negative integer, an exponential schedule is used where the highest power is 2 to the integer minus 1: `[id, Q^2^0, ..., Q^2^(evaluation_schedule-1)]`. minimizer: A minimizer used to find the minimum of the likelihood function. Defaults to a brute search where the number of evaluation points is determined according to ``evaluation_schedule``. The minimizer takes a function as first argument and a list of (float, float) tuples (as bounds) as second argument and returns a single float which is the found minimum. quantum_instance: Deprecated: Quantum Instance or Backend sampler: A sampler primitive to evaluate the circuits. Raises: ValueError: If the number of oracle circuits is smaller than 1. """ super().__init__() # set quantum instance with warnings.catch_warnings(): warnings.simplefilter("ignore") self.quantum_instance = quantum_instance # get parameters if isinstance(evaluation_schedule, int): if evaluation_schedule < 0: raise ValueError("The evaluation schedule cannot be < 0.") self._evaluation_schedule = [0] + [2**j for j in range(evaluation_schedule)] else: if any(value < 0 for value in evaluation_schedule): raise ValueError("The elements of the evaluation schedule cannot be < 0.") self._evaluation_schedule = evaluation_schedule if minimizer is None: # default number of evaluations is max(10^4, pi/2 * 10^3 * 2^(m)) nevals = max(10000, int(np.pi / 2 * 1000 * 2 * self._evaluation_schedule[-1])) def default_minimizer(objective_fn, bounds): return brute(objective_fn, bounds, Ns=nevals)[0] self._minimizer = default_minimizer else: self._minimizer = minimizer self._sampler = sampler @property def sampler(self) -> BaseSampler | None: """Get the sampler primitive. Returns: The sampler primitive to evaluate the circuits. """ return self._sampler @sampler.setter def sampler(self, sampler: BaseSampler) -> None: """Set sampler primitive. Args: sampler: A sampler primitive to evaluate the circuits. """ self._sampler = sampler @property @deprecate_func( since="0.24.0", is_property=True, additional_msg="See https://qisk.it/algo_migration for a migration guide.", ) def quantum_instance(self) -> QuantumInstance | None: """Deprecated. Get the quantum instance. Returns: The quantum instance used to run this algorithm. """ return self._quantum_instance @quantum_instance.setter @deprecate_func( since="0.24.0", is_property=True, additional_msg="See https://qisk.it/algo_migration for a migration guide.", ) def quantum_instance(self, quantum_instance: QuantumInstance | Backend) -> None: """Deprecated. Set quantum instance. Args: quantum_instance: The quantum instance used to run this algorithm. """ if isinstance(quantum_instance, Backend): quantum_instance = QuantumInstance(quantum_instance) self._quantum_instance = quantum_instance def construct_circuits( self, estimation_problem: EstimationProblem, measurement: bool = False ) -> list[QuantumCircuit]: """Construct the Amplitude Estimation w/o QPE quantum circuits. Args: estimation_problem: The estimation problem for which to construct the QAE circuit. measurement: Boolean flag to indicate if measurement should be included in the circuits. Returns: A list with the QuantumCircuit objects for the algorithm. """ # keep track of the Q-oracle queries circuits = [] num_qubits = max( estimation_problem.state_preparation.num_qubits, estimation_problem.grover_operator.num_qubits, ) q = QuantumRegister(num_qubits, "q") qc_0 = QuantumCircuit(q, name="qc_a") # 0 applications of Q, only a single A operator # add classical register if needed if measurement: c = ClassicalRegister(len(estimation_problem.objective_qubits)) qc_0.add_register(c) qc_0.compose(estimation_problem.state_preparation, inplace=True) for k in self._evaluation_schedule: qc_k = qc_0.copy(name=f"qc_a_q_{k}") if k != 0: qc_k.compose(estimation_problem.grover_operator.power(k), inplace=True) if measurement: # real hardware can currently not handle operations after measurements, # which might happen if the circuit gets transpiled, hence we're adding # a safeguard-barrier qc_k.barrier() qc_k.measure(estimation_problem.objective_qubits, c[:]) circuits += [qc_k] return circuits @staticmethod def compute_confidence_interval( result: "MaximumLikelihoodAmplitudeEstimationResult", alpha: float, kind: str = "fisher", apply_post_processing: bool = False, ) -> tuple[float, float]: """Compute the `alpha` confidence interval using the method `kind`. The confidence level is (1 - `alpha`) and supported kinds are 'fisher', 'likelihood_ratio' and 'observed_fisher' with shorthand notations 'fi', 'lr' and 'oi', respectively. Args: result: A maximum likelihood amplitude estimation result. alpha: The confidence level. kind: The method to compute the confidence interval. Defaults to 'fisher', which computes the theoretical Fisher information. apply_post_processing: If True, apply post-processing to the confidence interval. Returns: The specified confidence interval. Raises: AlgorithmError: If `run()` hasn't been called yet. NotImplementedError: If the method `kind` is not supported. """ interval: tuple[float, float] | None = None # if statevector simulator the estimate is exact if all(isinstance(data, (list, np.ndarray)) for data in result.circuit_results): interval = (result.estimation, result.estimation) elif kind in ["likelihood_ratio", "lr"]: interval = _likelihood_ratio_confint(result, alpha) elif kind in ["fisher", "fi"]: interval = _fisher_confint(result, alpha, observed=False) elif kind in ["observed_fisher", "observed_information", "oi"]: interval = _fisher_confint(result, alpha, observed=True) if interval is None: raise NotImplementedError(f"CI `{kind}` is not implemented.") if apply_post_processing: return result.post_processing(interval[0]), result.post_processing(interval[1]) return interval def compute_mle( self, circuit_results: list[dict[str, int] | np.ndarray], estimation_problem: EstimationProblem, num_state_qubits: int | None = None, return_counts: bool = False, ) -> float | tuple[float, list[float]]: """Compute the MLE via a grid-search. This is a stable approach if sufficient gridpoints are used. Args: circuit_results: A list of circuit outcomes. Can be counts or statevectors. estimation_problem: The estimation problem containing the evaluation schedule and the number of likelihood function evaluations used to find the minimum. num_state_qubits: The number of state qubits, required for statevector simulations. return_counts: If True, returns the good counts. Returns: The MLE for the provided result object. """ good_counts, all_counts = _get_counts(circuit_results, estimation_problem, num_state_qubits) # search range eps = 1e-15 # to avoid invalid value in log search_range = [0 + eps, np.pi / 2 - eps] def loglikelihood(theta): # loglik contains the first `it` terms of the full loglikelihood loglik = 0 for i, k in enumerate(self._evaluation_schedule): angle = (2 * k + 1) * theta loglik += np.log(np.sin(angle) ** 2) * good_counts[i] loglik += np.log(np.cos(angle) ** 2) * (all_counts[i] - good_counts[i]) return -loglik est_theta = self._minimizer(loglikelihood, [search_range]) if return_counts: return est_theta, good_counts return est_theta def estimate( self, estimation_problem: EstimationProblem ) -> "MaximumLikelihoodAmplitudeEstimationResult": """Run the amplitude estimation algorithm on provided estimation problem. Args: estimation_problem: The estimation problem. Returns: An amplitude estimation results object. Raises: ValueError: A quantum instance or Sampler must be provided. AlgorithmError: If `state_preparation` is not set in `estimation_problem`. AlgorithmError: Sampler job run error """ if self._quantum_instance is None and self._sampler is None: raise ValueError("A quantum instance or sampler must be provided.") if estimation_problem.state_preparation is None: raise AlgorithmError( "The state_preparation property of the estimation problem must be set." ) result = MaximumLikelihoodAmplitudeEstimationResult() result.evaluation_schedule = self._evaluation_schedule result.minimizer = self._minimizer result.post_processing = estimation_problem.post_processing shots = 0 if self._quantum_instance is not None and self._quantum_instance.is_statevector: # run circuit on statevector simulator circuits = self.construct_circuits(estimation_problem, measurement=False) ret = self._quantum_instance.execute(circuits) # get statevectors and construct MLE input statevectors = [np.asarray(ret.get_statevector(circuit)) for circuit in circuits] result.circuit_results = statevectors # to count the number of Q-oracle calls (don't count shots) result.shots = 1 else: circuits = self.construct_circuits(estimation_problem, measurement=True) if self._quantum_instance is not None: # run circuit on QASM simulator ret = self._quantum_instance.execute(circuits) # get counts and construct MLE input result.circuit_results = [ret.get_counts(circuit) for circuit in circuits] shots = self._quantum_instance._run_config.shots else: try: job = self._sampler.run(circuits) ret = job.result() except Exception as exc: raise AlgorithmError("The job was not completed successfully. ") from exc result.circuit_results = [] shots = ret.metadata[0].get("shots") if shots is None: for quasi_dist in ret.quasi_dists: circuit_result = quasi_dist.binary_probabilities() result.circuit_results.append(circuit_result) shots = 1 else: # get counts and construct MLE input for quasi_dist in ret.quasi_dists: counts = { k: round(v * shots) for k, v in quasi_dist.binary_probabilities().items() } result.circuit_results.append(counts) result.shots = shots # run maximum likelihood estimation num_state_qubits = circuits[0].num_qubits - circuits[0].num_ancillas theta, good_counts = self.compute_mle( result.circuit_results, estimation_problem, num_state_qubits, True ) # store results result.theta = theta result.good_counts = good_counts result.estimation = np.sin(result.theta) ** 2 # not sure why pylint complains, this is a callable and the tests pass # pylint: disable=not-callable result.estimation_processed = result.post_processing(result.estimation) result.fisher_information = _compute_fisher_information(result) result.num_oracle_queries = result.shots * sum(k for k in result.evaluation_schedule) # compute and store confidence interval confidence_interval = self.compute_confidence_interval(result, alpha=0.05, kind="fisher") result.confidence_interval = confidence_interval result.confidence_interval_processed = tuple( estimation_problem.post_processing(value) for value in confidence_interval ) return result class MaximumLikelihoodAmplitudeEstimationResult(AmplitudeEstimatorResult): """The ``MaximumLikelihoodAmplitudeEstimation`` result object.""" def __init__(self) -> None: super().__init__() self._theta: float | None = None self._minimizer: Callable | None = None self._good_counts: list[float] | None = None self._evaluation_schedule: list[int] | None = None self._fisher_information: float | None = None @property def theta(self) -> float: r"""Return the estimate for the angle :math:`\theta`.""" return self._theta @theta.setter def theta(self, value: float) -> None: r"""Set the estimate for the angle :math:`\theta`.""" self._theta = value @property def minimizer(self) -> Callable: """Return the minimizer used for the search of the likelihood function.""" return self._minimizer @minimizer.setter def minimizer(self, value: Callable) -> None: """Set the number minimizer used for the search of the likelihood function.""" self._minimizer = value @property def good_counts(self) -> list[float]: """Return the percentage of good counts per circuit power.""" return self._good_counts @good_counts.setter def good_counts(self, counts: list[float]) -> None: """Set the percentage of good counts per circuit power.""" self._good_counts = counts @property def evaluation_schedule(self) -> list[int]: """Return the evaluation schedule for the powers of the Grover operator.""" return self._evaluation_schedule @evaluation_schedule.setter def evaluation_schedule(self, evaluation_schedule: list[int]) -> None: """Set the evaluation schedule for the powers of the Grover operator.""" self._evaluation_schedule = evaluation_schedule @property def fisher_information(self) -> float: """Return the Fisher information for the estimated amplitude.""" return self._fisher_information @fisher_information.setter def fisher_information(self, value: float) -> None: """Set the Fisher information for the estimated amplitude.""" self._fisher_information = value def _safe_min(array, default=0): if len(array) == 0: return default return np.min(array) def _safe_max(array, default=(np.pi / 2)): if len(array) == 0: return default return np.max(array) def _compute_fisher_information( result: "MaximumLikelihoodAmplitudeEstimationResult", num_sum_terms: int | None = None, observed: bool = False, ) -> float: """Compute the Fisher information. Args: result: A maximum likelihood amplitude estimation result. num_sum_terms: The number of sum terms to be included in the calculation of the Fisher information. By default all values are included. observed: If True, compute the observed Fisher information, otherwise the theoretical one. Returns: The computed Fisher information, or np.inf if statevector simulation was used. Raises: KeyError: Call run() first! """ a = result.estimation # Corresponding angle to the value a (only use real part of 'a') theta_a = np.arcsin(np.sqrt(np.real(a))) # Get the number of hits (shots_k) and one-hits (h_k) one_hits = result.good_counts all_hits = [result.shots] * len(one_hits) # Include all sum terms or just up to a certain term? evaluation_schedule = result.evaluation_schedule if num_sum_terms is not None: evaluation_schedule = evaluation_schedule[:num_sum_terms] # not necessary since zip goes as far as shortest list: # all_hits = all_hits[:num_sum_terms] # one_hits = one_hits[:num_sum_terms] # Compute the Fisher information fisher_information = None if observed: # Note, that the observed Fisher information is very unreliable in this algorithm! d_loglik = 0 for shots_k, h_k, m_k in zip(all_hits, one_hits, evaluation_schedule): tan = np.tan((2 * m_k + 1) * theta_a) d_loglik += (2 * m_k + 1) * (h_k / tan + (shots_k - h_k) * tan) d_loglik /= np.sqrt(a * (1 - a)) fisher_information = d_loglik**2 / len(all_hits) else: fisher_information = sum( shots_k * (2 * m_k + 1) ** 2 for shots_k, m_k in zip(all_hits, evaluation_schedule) ) fisher_information /= a * (1 - a) return fisher_information def _fisher_confint( result: MaximumLikelihoodAmplitudeEstimationResult, alpha: float = 0.05, observed: bool = False ) -> tuple[float, float]: """Compute the `alpha` confidence interval based on the Fisher information. Args: result: A maximum likelihood amplitude estimation results object. alpha: The level of the confidence interval (must be <= 0.5), default to 0.05. observed: If True, use observed Fisher information. Returns: float: The alpha confidence interval based on the Fisher information Raises: AssertionError: Call run() first! """ # Get the (observed) Fisher information fisher_information = None try: fisher_information = result.fisher_information except KeyError as ex: raise AssertionError("Call run() first!") from ex if observed: fisher_information = _compute_fisher_information(result, observed=True) normal_quantile = norm.ppf(1 - alpha / 2) confint = np.real(result.estimation) + normal_quantile / np.sqrt(fisher_information) * np.array( [-1, 1] ) return result.post_processing(confint[0]), result.post_processing(confint[1]) def _likelihood_ratio_confint( result: MaximumLikelihoodAmplitudeEstimationResult, alpha: float = 0.05, nevals: int | None = None, ) -> tuple[float, float]: """Compute the likelihood-ratio confidence interval. Args: result: A maximum likelihood amplitude estimation results object. alpha: The level of the confidence interval (< 0.5), defaults to 0.05. nevals: The number of evaluations to find the intersection with the loglikelihood function. Defaults to an adaptive value based on the maximal power of Q. Returns: The alpha-likelihood-ratio confidence interval. """ if nevals is None: nevals = max(10000, int(np.pi / 2 * 1000 * 2 * result.evaluation_schedule[-1])) def loglikelihood(theta, one_counts, all_counts): loglik = 0 for i, k in enumerate(result.evaluation_schedule): loglik += np.log(np.sin((2 * k + 1) * theta) ** 2) * one_counts[i] loglik += np.log(np.cos((2 * k + 1) * theta) ** 2) * (all_counts[i] - one_counts[i]) return loglik one_counts = result.good_counts all_counts = [result.shots] * len(one_counts) eps = 1e-15 # to avoid invalid value in log thetas = np.linspace(0 + eps, np.pi / 2 - eps, nevals) values = np.zeros(len(thetas)) for i, theta in enumerate(thetas): values[i] = loglikelihood(theta, one_counts, all_counts) loglik_mle = loglikelihood(result.theta, one_counts, all_counts) chi2_quantile = chi2.ppf(1 - alpha, df=1) thres = loglik_mle - chi2_quantile / 2 # the (outer) LR confidence interval above_thres = thetas[values >= thres] # it might happen that the `above_thres` array is empty, # to still provide a valid result use safe_min/max which # then yield [0, pi/2] confint = [_safe_min(above_thres, default=0), _safe_max(above_thres, default=np.pi / 2)] mapped_confint = tuple(result.post_processing(np.sin(bound) ** 2) for bound in confint) return mapped_confint def _get_counts( circuit_results: Sequence[np.ndarray | list[float] | dict[str, int]], estimation_problem: EstimationProblem, num_state_qubits: int, ) -> tuple[list[float], list[int]]: """Get the good and total counts. Returns: A pair of two lists, ([1-counts per experiment], [shots per experiment]). Raises: AlgorithmError: If self.run() has not been called yet. """ one_hits = [] # h_k: how often 1 has been measured, for a power Q^(m_k) # shots_k: how often has been measured at a power Q^(m_k) all_hits: np.ndarray | list[float] = [] if all(isinstance(data, (list, np.ndarray)) for data in circuit_results): probabilities = [] num_qubits = int(np.log2(len(circuit_results[0]))) # the total number of qubits for statevector in circuit_results: p_k = 0.0 for i, amplitude in enumerate(statevector): probability = np.abs(amplitude) ** 2 # consider only state qubits and revert bit order bitstr = bin(i)[2:].zfill(num_qubits)[-num_state_qubits:][::-1] objectives = [bitstr[index] for index in estimation_problem.objective_qubits] if estimation_problem.is_good_state(objectives): p_k += probability probabilities += [p_k] one_hits = probabilities all_hits = np.ones_like(one_hits) else: for counts in circuit_results: all_hits.append(sum(counts.values())) one_hits.append( sum( count for bitstr, count in counts.items() if estimation_problem.is_good_state(bitstr) ) ) return one_hits, all_hits
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Evolution problem class.""" from __future__ import annotations from qiskit import QuantumCircuit from qiskit.circuit import Parameter from qiskit.opflow import OperatorBase, StateFn from qiskit.utils.deprecation import deprecate_func from ..list_or_dict import ListOrDict class EvolutionProblem: """Deprecated: Evolution problem class. The EvolutionProblem class has been superseded by the :class:`qiskit_algorithms.time_evolvers.TimeEvolutionProblem` class. This class will be deprecated in a future release and subsequently removed after that. This class is the input to time evolution algorithms and must contain information on the total evolution time, a quantum state to be evolved and under which Hamiltonian the state is evolved. """ @deprecate_func( additional_msg=( "Instead, use the class ``qiskit_algorithms.time_evolvers.TimeEvolutionProblem``. " "See https://qisk.it/algo_migration for a migration guide." ), since="0.24.0", ) def __init__( self, hamiltonian: OperatorBase, time: float, initial_state: StateFn | QuantumCircuit | None = None, aux_operators: ListOrDict[OperatorBase] | None = None, truncation_threshold: float = 1e-12, t_param: Parameter | None = None, param_value_dict: dict[Parameter, complex] | None = None, ): """ Args: hamiltonian: The Hamiltonian under which to evolve the system. time: Total time of evolution. initial_state: The quantum state to be evolved for methods like Trotterization. For variational time evolutions, where the evolution happens in an ansatz, this argument is not required. aux_operators: Optional list of auxiliary operators to be evaluated with the evolved ``initial_state`` and their expectation values returned. truncation_threshold: Defines a threshold under which values can be assumed to be 0. Used when ``aux_operators`` is provided. t_param: Time parameter in case of a time-dependent Hamiltonian. This free parameter must be within the ``hamiltonian``. param_value_dict: Maps free parameters in the problem to values. Depending on the algorithm, it might refer to e.g. a Hamiltonian or an initial state. Raises: ValueError: If non-positive time of evolution is provided. """ self.t_param = t_param self.param_value_dict = param_value_dict self.hamiltonian = hamiltonian self.time = time self.initial_state = initial_state self.aux_operators = aux_operators self.truncation_threshold = truncation_threshold @property def time(self) -> float: """Returns time.""" return self._time @time.setter def time(self, time: float) -> None: """ Sets time and validates it. Raises: ValueError: If time is not positive. """ if time <= 0: raise ValueError(f"Evolution time must be > 0 but was {time}.") self._time = time def validate_params(self) -> None: """ Checks if all parameters present in the Hamiltonian are also present in the dictionary that maps them to values. Raises: ValueError: If Hamiltonian parameters cannot be bound with data provided. """ if isinstance(self.hamiltonian, OperatorBase): t_param_set = set() if self.t_param is not None: t_param_set.add(self.t_param) hamiltonian_dict_param_set: set[Parameter] = set() if self.param_value_dict is not None: hamiltonian_dict_param_set = hamiltonian_dict_param_set.union( set(self.param_value_dict.keys()) ) params_set = t_param_set.union(hamiltonian_dict_param_set) hamiltonian_param_set = set(self.hamiltonian.parameters) if hamiltonian_param_set != params_set: raise ValueError( f"Provided parameters {params_set} do not match Hamiltonian parameters " f"{hamiltonian_param_set}." )
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# 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. """Class for holding evolution result.""" from __future__ import annotations from qiskit import QuantumCircuit from qiskit_algorithms.list_or_dict import ListOrDict from qiskit.opflow import StateFn, OperatorBase from qiskit.utils.deprecation import deprecate_func from ..algorithm_result import AlgorithmResult class EvolutionResult(AlgorithmResult): """Deprecated: Class for holding evolution result. The EvolutionResult class has been superseded by the :class:`qiskit_algorithms.time_evolvers.TimeEvolutionResult` class. This class will be deprecated in a future release and subsequently removed after that. """ @deprecate_func( additional_msg=( "Instead, use the class ``qiskit_algorithms.time_evolvers.TimeEvolutionResult``. " "See https://qisk.it/algo_migration for a migration guide." ), since="0.24.0", ) def __init__( self, evolved_state: StateFn | QuantumCircuit | OperatorBase, aux_ops_evaluated: ListOrDict[tuple[complex, complex]] | None = None, ): """ Args: evolved_state: An evolved quantum state. aux_ops_evaluated: Optional list of observables for which expected values on an evolved state are calculated. These values are in fact tuples formatted as (mean, standard deviation). """ self.evolved_state = evolved_state self.aux_ops_evaluated = aux_ops_evaluated
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2021, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """An algorithm to implement a Trotterization real time-evolution.""" from __future__ import annotations from qiskit import QuantumCircuit from qiskit_algorithms.time_evolvers.time_evolution_problem import TimeEvolutionProblem from qiskit_algorithms.time_evolvers.time_evolution_result import TimeEvolutionResult from qiskit_algorithms.time_evolvers.real_time_evolver import RealTimeEvolver from qiskit_algorithms.observables_evaluator import estimate_observables from qiskit.opflow import PauliSumOp from qiskit.circuit.library import PauliEvolutionGate from qiskit.circuit.parametertable import ParameterView from qiskit.primitives import BaseEstimator from qiskit.quantum_info import Pauli, SparsePauliOp from qiskit.synthesis import ProductFormula, LieTrotter class TrotterQRTE(RealTimeEvolver): """Quantum Real Time Evolution using Trotterization. Type of Trotterization is defined by a ``ProductFormula`` provided. Examples: .. code-block:: python from qiskit.opflow import PauliSumOp from qiskit.quantum_info import Pauli, SparsePauliOp from qiskit import QuantumCircuit from qiskit_algorithms import TimeEvolutionProblem from qiskit_algorithms.time_evolvers import TrotterQRTE from qiskit.primitives import Estimator operator = PauliSumOp(SparsePauliOp([Pauli("X"), Pauli("Z")])) initial_state = QuantumCircuit(1) time = 1 evolution_problem = TimeEvolutionProblem(operator, time, initial_state) # LieTrotter with 1 rep estimator = Estimator() trotter_qrte = TrotterQRTE(estimator=estimator) evolved_state = trotter_qrte.evolve(evolution_problem).evolved_state """ def __init__( self, product_formula: ProductFormula | None = None, estimator: BaseEstimator | None = None, num_timesteps: int = 1, ) -> None: """ Args: product_formula: A Lie-Trotter-Suzuki product formula. If ``None`` provided, the Lie-Trotter first order product formula with a single repetition is used. ``reps`` should be 1 to obtain a number of time-steps equal to ``num_timesteps`` and an evaluation of :attr:`.TimeEvolutionProblem.aux_operators` at every time-step. If ``reps`` is larger than 1, the true number of time-steps will be ``num_timesteps * reps``. num_timesteps: The number of time-steps the full evolution time is devided into (repetitions of ``product_formula``) estimator: An estimator primitive used for calculating expectation values of ``TimeEvolutionProblem.aux_operators``. """ self.product_formula = product_formula self.num_timesteps = num_timesteps self.estimator = estimator @property def product_formula(self) -> ProductFormula: """Returns a product formula.""" return self._product_formula @product_formula.setter def product_formula(self, product_formula: ProductFormula | None): """Sets a product formula. If ``None`` provided, sets the Lie-Trotter first order product formula with a single repetition.""" if product_formula is None: product_formula = LieTrotter() self._product_formula = product_formula @property def estimator(self) -> BaseEstimator | None: """ Returns an estimator. """ return self._estimator @estimator.setter def estimator(self, estimator: BaseEstimator) -> None: """ Sets an estimator. """ self._estimator = estimator @property def num_timesteps(self) -> int: """Returns the number of timesteps.""" return self._num_timesteps @num_timesteps.setter def num_timesteps(self, num_timesteps: int) -> None: """ Sets the number of time-steps. Raises: ValueError: If num_timesteps is not positive. """ if num_timesteps <= 0: raise ValueError( f"Number of time steps must be positive integer, {num_timesteps} provided" ) self._num_timesteps = num_timesteps @classmethod def supports_aux_operators(cls) -> bool: """ Whether computing the expectation value of auxiliary operators is supported. Returns: ``True`` if ``aux_operators`` expectations in the ``TimeEvolutionProblem`` can be evaluated, ``False`` otherwise. """ return True def evolve(self, evolution_problem: TimeEvolutionProblem) -> TimeEvolutionResult: """ Evolves a quantum state for a given time using the Trotterization method based on a product formula provided. The result is provided in the form of a quantum circuit. If auxiliary operators are included in the ``evolution_problem``, they are evaluated on the ``init_state`` and on the evolved state at every step (``num_timesteps`` times) using an estimator primitive provided. Args: evolution_problem: Instance defining evolution problem. For the included Hamiltonian, ``Pauli`` or ``PauliSumOp`` are supported by TrotterQRTE. Returns: Evolution result that includes an evolved state as a quantum circuit and, optionally, auxiliary operators evaluated for a resulting state on an estimator primitive. Raises: ValueError: If ``t_param`` is not set to ``None`` in the ``TimeEvolutionProblem`` (feature not currently supported). ValueError: If ``aux_operators`` provided in the time evolution problem but no estimator provided to the algorithm. ValueError: If the ``initial_state`` is not provided in the ``TimeEvolutionProblem``. ValueError: If an unsupported Hamiltonian type is provided. """ evolution_problem.validate_params() if evolution_problem.aux_operators is not None and self.estimator is None: raise ValueError( "The time evolution problem contained ``aux_operators`` but no estimator was " "provided. The algorithm continues without calculating these quantities. " ) # ensure the hamiltonian is a sparse pauli op hamiltonian = evolution_problem.hamiltonian if not isinstance(hamiltonian, (Pauli, PauliSumOp, SparsePauliOp)): raise ValueError( f"TrotterQRTE only accepts Pauli | PauliSumOp | SparsePauliOp, {type(hamiltonian)} " "provided." ) if isinstance(hamiltonian, PauliSumOp): hamiltonian = hamiltonian.primitive * hamiltonian.coeff elif isinstance(hamiltonian, Pauli): hamiltonian = SparsePauliOp(hamiltonian) t_param = evolution_problem.t_param free_parameters = hamiltonian.parameters if t_param is not None and free_parameters != ParameterView([t_param]): raise ValueError( f"Hamiltonian time parameters ({free_parameters}) do not match " f"evolution_problem.t_param ({t_param})." ) # make sure PauliEvolutionGate does not implement more than one Trotter step dt = evolution_problem.time / self.num_timesteps if evolution_problem.initial_state is not None: initial_state = evolution_problem.initial_state else: raise ValueError("``initial_state`` must be provided in the ``TimeEvolutionProblem``.") evolved_state = QuantumCircuit(initial_state.num_qubits) evolved_state.append(initial_state, evolved_state.qubits) if evolution_problem.aux_operators is not None: observables = [] observables.append( estimate_observables( self.estimator, evolved_state, evolution_problem.aux_operators, None, evolution_problem.truncation_threshold, ) ) else: observables = None if t_param is None: # the evolution gate single_step_evolution_gate = PauliEvolutionGate( hamiltonian, dt, synthesis=self.product_formula ) for n in range(self.num_timesteps): # if hamiltonian is time-dependent, bind new time-value at every step to construct # evolution for next step if t_param is not None: time_value = (n + 1) * dt bound_hamiltonian = hamiltonian.assign_parameters([time_value]) single_step_evolution_gate = PauliEvolutionGate( bound_hamiltonian, dt, synthesis=self.product_formula, ) evolved_state.append(single_step_evolution_gate, evolved_state.qubits) if evolution_problem.aux_operators is not None: observables.append( estimate_observables( self.estimator, evolved_state, evolution_problem.aux_operators, None, evolution_problem.truncation_threshold, ) ) evaluated_aux_ops = None if evolution_problem.aux_operators is not None: evaluated_aux_ops = observables[-1] return TimeEvolutionResult(evolved_state, evaluated_aux_ops, observables)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2022, 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. """An implementation of the AdaptVQE algorithm.""" from __future__ import annotations from collections.abc import Sequence from enum import Enum import re import logging from typing import Any import numpy as np from qiskit import QiskitError from qiskit_algorithms.list_or_dict import ListOrDict from qiskit.quantum_info.operators.base_operator import BaseOperator from qiskit.opflow import OperatorBase, PauliSumOp from qiskit.circuit.library import EvolvedOperatorAnsatz from qiskit.utils.deprecation import deprecate_arg, deprecate_func from qiskit.utils.validation import validate_min from .minimum_eigensolver import MinimumEigensolver from .vqe import VQE, VQEResult from ..observables_evaluator import estimate_observables from ..variational_algorithm import VariationalAlgorithm logger = logging.getLogger(__name__) class TerminationCriterion(Enum): """A class enumerating the various finishing criteria.""" CONVERGED = "Threshold converged" CYCLICITY = "Aborted due to a cyclic selection of evolution operators" MAXIMUM = "Maximum number of iterations reached" class AdaptVQE(VariationalAlgorithm, MinimumEigensolver): """The Adaptive Variational Quantum Eigensolver algorithm. `AdaptVQE <https://arxiv.org/abs/1812.11173>`__ is a quantum algorithm which creates a compact ansatz from a set of evolution operators. It iteratively extends the ansatz circuit, by selecting the building block that leads to the largest gradient from a set of candidates. In chemistry, this is usually a list of orbital excitations. Thus, a common choice of ansatz to be used with this algorithm is the Unitary Coupled Cluster ansatz implemented in Qiskit Nature. This results in a wavefunction ansatz which is uniquely adapted to the operator whose minimum eigenvalue is being determined. This class relies on a supplied instance of :class:`~.VQE` to find the minimum eigenvalue. The performance of AdaptVQE significantly depends on the minimization routine. .. code-block:: python from qiskit_algorithms.minimum_eigensolvers import AdaptVQE, VQE from qiskit_algorithms.optimizers import SLSQP from qiskit.primitives import Estimator from qiskit.circuit.library import EvolvedOperatorAnsatz # get your Hamiltonian hamiltonian = ... # construct your ansatz ansatz = EvolvedOperatorAnsatz(...) vqe = VQE(Estimator(), ansatz, SLSQP()) adapt_vqe = AdaptVQE(vqe) eigenvalue, _ = adapt_vqe.compute_minimum_eigenvalue(hamiltonian) The following attributes can be set via the initializer but can also be read and updated once the AdaptVQE object has been constructed. Attributes: solver: a :class:`~.VQE` instance used internally to compute the minimum eigenvalues. It is a requirement that the :attr:`~.VQE.ansatz` of this solver is of type :class:`~qiskit.circuit.library.EvolvedOperatorAnsatz`. gradient_threshold: once all gradients have an absolute value smaller than this threshold, the algorithm has converged and terminates. eigenvalue_threshold: once the eigenvalue has changed by less than this threshold from one iteration to the next, the algorithm has converged and terminates. When this case occurs, the excitation included in the final iteration did not result in a significant improvement of the eigenvalue and, thus, the results from this iteration are not considered. max_iterations: the maximum number of iterations for the adaptive loop. If ``None``, the algorithm is not bound in its number of iterations. """ @deprecate_arg( "threshold", since="0.24.0", pending=True, new_alias="gradient_threshold", ) def __init__( self, solver: VQE, *, gradient_threshold: float = 1e-5, eigenvalue_threshold: float = 1e-5, max_iterations: int | None = None, threshold: float | None = None, # pylint: disable=unused-argument ) -> None: """ Args: solver: a :class:`~.VQE` instance used internally to compute the minimum eigenvalues. It is a requirement that the :attr:`~.VQE.ansatz` of this solver is of type :class:`~qiskit.circuit.library.EvolvedOperatorAnsatz`. gradient_threshold: once all gradients have an absolute value smaller than this threshold, the algorithm has converged and terminates. eigenvalue_threshold: once the eigenvalue has changed by less than this threshold from one iteration to the next, the algorithm has converged and terminates. When this case occurs, the excitation included in the final iteration did not result in a significant improvement of the eigenvalue and, thus, the results from this iteration are not considered. max_iterations: the maximum number of iterations for the adaptive loop. If ``None``, the algorithm is not bound in its number of iterations. threshold: once all gradients have an absolute value smaller than this threshold, the algorithm has converged and terminates. Defaults to ``1e-5``. """ validate_min("gradient_threshold", gradient_threshold, 1e-15) validate_min("eigenvalue_threshold", eigenvalue_threshold, 1e-15) self.solver = solver self.gradient_threshold = gradient_threshold self.eigenvalue_threshold = eigenvalue_threshold self.max_iterations = max_iterations self._tmp_ansatz: EvolvedOperatorAnsatz | None = None self._excitation_pool: list[OperatorBase] = [] self._excitation_list: list[OperatorBase] = [] @property @deprecate_func( since="0.24.0", pending=True, is_property=True, additional_msg="Instead, use the gradient_threshold attribute.", ) def threshold(self) -> float: """The threshold for the gradients. Once all gradients have an absolute value smaller than this threshold, the algorithm has converged and terminates. """ return self.gradient_threshold @threshold.setter @deprecate_func( since="0.24.0", pending=True, is_property=True, additional_msg="Instead, use the gradient_threshold attribute.", ) def threshold(self, threshold: float) -> None: self.gradient_threshold = threshold @property def initial_point(self) -> Sequence[float] | None: """Returns the initial point of the internal :class:`~.VQE` solver.""" return self.solver.initial_point @initial_point.setter def initial_point(self, value: Sequence[float] | None) -> None: """Sets the initial point of the internal :class:`~.VQE` solver.""" self.solver.initial_point = value @classmethod def supports_aux_operators(cls) -> bool: return True def _compute_gradients( self, theta: list[float], operator: BaseOperator | OperatorBase, ) -> list[tuple[complex, dict[str, Any]]]: """ Computes the gradients for all available excitation operators. Args: theta: List of (up to now) optimal parameters. operator: operator whose gradient needs to be computed. Returns: List of pairs consisting of the computed gradient and excitation operator. """ # The excitations operators are applied later as exp(i*theta*excitation). # For this commutator, we need to explicitly pull in the imaginary phase. commutators = [1j * (operator @ exc - exc @ operator) for exc in self._excitation_pool] res = estimate_observables(self.solver.estimator, self.solver.ansatz, commutators, theta) return res @staticmethod def _check_cyclicity(indices: list[int]) -> bool: """ Auxiliary function to check for cycles in the indices of the selected excitations. Args: indices: The list of chosen gradient indices. Returns: Whether repeating sequences of indices have been detected. """ cycle_regex = re.compile(r"(\b.+ .+\b)( \b\1\b)+") # reg-ex explanation: # 1. (\b.+ .+\b) will match at least two numbers and try to match as many as possible. The # word boundaries in the beginning and end ensure that now numbers are split into digits. # 2. the match of this part is placed into capture group 1 # 3. ( \b\1\b)+ will match a space followed by the contents of capture group 1 (again # delimited by word boundaries to avoid separation into digits). # -> this results in any sequence of at least two numbers being detected match = cycle_regex.search(" ".join(map(str, indices))) logger.debug("Cycle detected: %s", match) # Additionally we also need to check whether the last two numbers are identical, because the # reg-ex above will only find cycles of at least two consecutive numbers. # It is sufficient to assert that the last two numbers are different due to the iterative # nature of the algorithm. return match is not None or (len(indices) > 1 and indices[-2] == indices[-1]) def compute_minimum_eigenvalue( self, operator: BaseOperator | PauliSumOp, aux_operators: ListOrDict[BaseOperator | PauliSumOp] | None = None, ) -> AdaptVQEResult: """Computes the minimum eigenvalue. Args: operator: Operator whose minimum eigenvalue we want to find. aux_operators: Additional auxiliary operators to evaluate. Raises: TypeError: If an ansatz other than :class:`~.EvolvedOperatorAnsatz` is provided. QiskitError: If all evaluated gradients lie below the convergence threshold in the first iteration of the algorithm. Returns: An :class:`~.AdaptVQEResult` which is a :class:`~.VQEResult` but also but also includes runtime information about the AdaptVQE algorithm like the number of iterations, termination criterion, and the final maximum gradient. """ if not isinstance(self.solver.ansatz, EvolvedOperatorAnsatz): raise TypeError("The AdaptVQE ansatz must be of the EvolvedOperatorAnsatz type.") # Overwrite the solver's ansatz with the initial state self._tmp_ansatz = self.solver.ansatz self._excitation_pool = self._tmp_ansatz.operators self.solver.ansatz = self._tmp_ansatz.initial_state prev_op_indices: list[int] = [] prev_raw_vqe_result: VQEResult | None = None raw_vqe_result: VQEResult | None = None theta: list[float] = [] max_grad: tuple[complex, dict[str, Any] | None] = (0.0, None) self._excitation_list = [] history: list[complex] = [] iteration = 0 while self.max_iterations is None or iteration < self.max_iterations: iteration += 1 logger.info("--- Iteration #%s ---", str(iteration)) # compute gradients logger.debug("Computing gradients") cur_grads = self._compute_gradients(theta, operator) # pick maximum gradient max_grad_index, max_grad = max( enumerate(cur_grads), key=lambda item: np.abs(item[1][0]) ) logger.info( "Found maximum gradient %s at index %s", str(np.abs(max_grad[0])), str(max_grad_index), ) # log gradients if np.abs(max_grad[0]) < self.gradient_threshold: if iteration == 1: raise QiskitError( "All gradients have been evaluated to lie below the convergence threshold " "during the first iteration of the algorithm. Try to either tighten the " "convergence threshold or pick a different ansatz." ) logger.info( "AdaptVQE terminated successfully with a final maximum gradient: %s", str(np.abs(max_grad[0])), ) termination_criterion = TerminationCriterion.CONVERGED break # store maximum gradient's index for cycle detection prev_op_indices.append(max_grad_index) # check indices of picked gradients for cycles if self._check_cyclicity(prev_op_indices): logger.info("Alternating sequence found. Finishing.") logger.info("Final maximum gradient: %s", str(np.abs(max_grad[0]))) termination_criterion = TerminationCriterion.CYCLICITY break # add new excitation to self._ansatz logger.info( "Adding new operator to the ansatz: %s", str(self._excitation_pool[max_grad_index]) ) self._excitation_list.append(self._excitation_pool[max_grad_index]) theta.append(0.0) # setting up the ansatz for the VQE iteration self._tmp_ansatz.operators = self._excitation_list self.solver.ansatz = self._tmp_ansatz self.solver.initial_point = theta # evaluating the eigenvalue with the internal VQE prev_raw_vqe_result = raw_vqe_result raw_vqe_result = self.solver.compute_minimum_eigenvalue(operator) theta = raw_vqe_result.optimal_point.tolist() # checking convergence based on the change in eigenvalue if iteration > 1: eigenvalue_diff = np.abs(raw_vqe_result.eigenvalue - history[-1]) if eigenvalue_diff < self.eigenvalue_threshold: logger.info( "AdaptVQE terminated successfully with a final change in eigenvalue: %s", str(eigenvalue_diff), ) termination_criterion = TerminationCriterion.CONVERGED logger.debug( "Reverting the addition of the last excitation to the ansatz since it " "resulted in a change of the eigenvalue below the configured threshold." ) self._excitation_list.pop() theta.pop() self._tmp_ansatz.operators = self._excitation_list self.solver.ansatz = self._tmp_ansatz self.solver.initial_point = theta raw_vqe_result = prev_raw_vqe_result break # appending the computed eigenvalue to the tracking history history.append(raw_vqe_result.eigenvalue) logger.info("Current eigenvalue: %s", str(raw_vqe_result.eigenvalue)) else: # reached maximum number of iterations termination_criterion = TerminationCriterion.MAXIMUM logger.info("Maximum number of iterations reached. Finishing.") logger.info("Final maximum gradient: %s", str(np.abs(max_grad[0]))) result = AdaptVQEResult() result.combine(raw_vqe_result) result.num_iterations = iteration result.final_max_gradient = max_grad[0] result.termination_criterion = termination_criterion result.eigenvalue_history = history # once finished evaluate auxiliary operators if any if aux_operators is not None: aux_values = estimate_observables( self.solver.estimator, self.solver.ansatz, aux_operators, result.optimal_point ) result.aux_operators_evaluated = aux_values logger.info("The final eigenvalue is: %s", str(result.eigenvalue)) self.solver.ansatz.operators = self._excitation_pool return result class AdaptVQEResult(VQEResult): """AdaptVQE Result.""" def __init__(self) -> None: super().__init__() self._num_iterations: int | None = None self._final_max_gradient: float | None = None self._termination_criterion: str = "" self._eigenvalue_history: list[float] | None = None @property def num_iterations(self) -> int: """Returns the number of iterations.""" return self._num_iterations @num_iterations.setter def num_iterations(self, value: int) -> None: """Sets the number of iterations.""" self._num_iterations = value @property def final_max_gradient(self) -> float: """Returns the final maximum gradient.""" return self._final_max_gradient @final_max_gradient.setter def final_max_gradient(self, value: float) -> None: """Sets the final maximum gradient.""" self._final_max_gradient = value @property def termination_criterion(self) -> str: """Returns the termination criterion.""" return self._termination_criterion @termination_criterion.setter def termination_criterion(self, value: str) -> None: """Sets the termination criterion.""" self._termination_criterion = value @property def eigenvalue_history(self) -> list[float]: """Returns the history of computed eigenvalues. The history's length matches the number of iterations and includes the final computed value. """ return self._eigenvalue_history @eigenvalue_history.setter def eigenvalue_history(self, eigenvalue_history: list[float]) -> None: """Sets the history of computed eigenvalues.""" self._eigenvalue_history = eigenvalue_history
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 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. """Univariate Marginal Distribution Algorithm (Estimation-of-Distribution-Algorithm).""" from __future__ import annotations from collections.abc import Callable from typing import Any import numpy as np from scipy.stats import norm from qiskit.utils import algorithm_globals from .optimizer import OptimizerResult, POINT from .scipy_optimizer import Optimizer, OptimizerSupportLevel class UMDA(Optimizer): """Continuous Univariate Marginal Distribution Algorithm (UMDA). UMDA [1] is a specific type of Estimation of Distribution Algorithm (EDA) where new individuals are sampled from univariate normal distributions and are updated in each iteration of the algorithm by the best individuals found in the previous iteration. .. seealso:: This original implementation of the UDMA optimizer for Qiskit was inspired by my (Vicente P. Soloviev) work on the EDAspy Python package [2]. EDAs are stochastic search algorithms and belong to the family of the evolutionary algorithms. The main difference is that EDAs have a probabilistic model which is updated in each iteration from the best individuals of previous generations (elite selection). Depending on the complexity of the probabilistic model, EDAs can be classified in different ways. In this case, UMDA is a univariate EDA as the embedded probabilistic model is univariate. UMDA has been compared to some of the already implemented algorithms in Qiskit library to optimize the parameters of variational algorithms such as QAOA or VQE and competitive results have been obtained [1]. UMDA seems to provide very good solutions for those circuits in which the number of layers is not big. The optimization process can be personalized depending on the paremeters chosen in the initialization. The main parameter is the population size. The bigger it is, the final result will be better. However, this increases the complexity of the algorithm and the runtime will be much heavier. In the work [1] different experiments have been performed where population size has been set to 20 - 30. .. note:: The UMDA implementation has more parameters but these have default values for the initialization for better understanding of the user. For example, ``\alpha`` parameter has been set to 0.5 and is the percentage of the population which is selected in each iteration to update the probabilistic model. Example: This short example runs UMDA to optimize the parameters of a variational algorithm. Here we will use the same operator as used in the algorithms introduction, which was originally computed by Qiskit Nature for an H2 molecule. The minimum energy of the H2 Hamiltonian can be found quite easily so we are able to set maxiters to a small value. .. code-block:: python from qiskit.opflow import X, Z, I from qiskit import Aer from qiskit_algorithms.optimizers import UMDA from qiskit_algorithms import QAOA from qiskit.utils import QuantumInstance H2_op = (-1.052373245772859 * I ^ I) + \ (0.39793742484318045 * I ^ Z) + \ (-0.39793742484318045 * Z ^ I) + \ (-0.01128010425623538 * Z ^ Z) + \ (0.18093119978423156 * X ^ X) p = 2 # Toy example: 2 layers with 2 parameters in each layer: 4 variables opt = UMDA(maxiter=100, size_gen=20) backend = Aer.get_backend('statevector_simulator') vqe = QAOA(opt, quantum_instance=QuantumInstance(backend=backend), reps=p) result = vqe.compute_minimum_eigenvalue(operator=H2_op) If it is desired to modify the percentage of individuals considered to update the probabilistic model, then this code can be used. Here for example we set the 60% instead of the 50% predefined. .. code-block:: python opt = UMDA(maxiter=100, size_gen=20, alpha = 0.6) backend = Aer.get_backend('statevector_simulator') vqe = QAOA(opt, quantum_instance=QuantumInstance(backend=backend), reps=p) result = vqe.compute_minimum_eigenvalue(operator=qubit_op) References: [1]: Vicente P. Soloviev, Pedro LarraΓ±aga and Concha Bielza (2022, July). Quantum Parametric Circuit Optimization with Estimation of Distribution Algorithms. In 2022 The Genetic and Evolutionary Computation Conference (GECCO). DOI: https://doi.org/10.1145/3520304.3533963 [2]: Vicente P. Soloviev. Python package EDAspy. https://github.com/VicentePerezSoloviev/EDAspy. """ ELITE_FACTOR = 0.4 STD_BOUND = 0.3 def __init__( self, maxiter: int = 100, size_gen: int = 20, alpha: float = 0.5, callback: Callable[[int, np.array, float], None] | None = None, ) -> None: r""" Args: maxiter: Maximum number of iterations. size_gen: Population size of each generation. alpha: Percentage (0, 1] of the population to be selected as elite selection. callback: A callback function passed information in each iteration step. The information is, in this order: the number of function evaluations, the parameters, the best function value in this iteration. """ self.size_gen = size_gen self.maxiter = maxiter self.alpha = alpha self._vector: np.ndarray | None = None # initialization of generation self._generation: np.ndarray | None = None self._dead_iter = int(self._maxiter / 5) self._truncation_length = int(size_gen * alpha) super().__init__() self._best_cost_global: float | None = None self._best_ind_global: int | None = None self._evaluations: np.ndarray | None = None self._n_variables: int | None = None self.callback = callback def _initialization(self) -> np.ndarray: vector = np.zeros((4, self._n_variables)) vector[0, :] = np.pi # mu vector[1, :] = 0.5 # std return vector # build a generation of size SIZE_GEN from prob vector def _new_generation(self): """Build a new generation sampled from the vector of probabilities. Updates the generation pandas dataframe """ gen = algorithm_globals.random.normal( self._vector[0, :], self._vector[1, :], [self._size_gen, self._n_variables] ) self._generation = self._generation[: int(self.ELITE_FACTOR * len(self._generation))] self._generation = np.vstack((self._generation, gen)) # truncate the generation at alpha percent def _truncation(self): """Selection of the best individuals of the actual generation. Updates the generation by selecting the best individuals. """ best_indices = self._evaluations.argsort()[: self._truncation_length] self._generation = self._generation[best_indices, :] self._evaluations = np.take(self._evaluations, best_indices) # check each individual of the generation def _check_generation(self, objective_function): """Check the cost of each individual in the cost function implemented by the user.""" self._evaluations = np.apply_along_axis(objective_function, 1, self._generation) # update the probability vector def _update_vector(self): """From the best individuals update the vector of normal distributions in order to the next generation can sample from it. Update the vector of normal distributions """ for i in range(self._n_variables): self._vector[0, i], self._vector[1, i] = norm.fit(self._generation[:, i]) if self._vector[1, i] < self.STD_BOUND: self._vector[1, i] = self.STD_BOUND def minimize( self, fun: Callable[[POINT], float], x0: POINT, jac: Callable[[POINT], POINT] | None = None, bounds: list[tuple[float, float]] | None = None, ) -> OptimizerResult: not_better_count = 0 result = OptimizerResult() if isinstance(x0, float): x0 = [x0] self._n_variables = len(x0) self._best_cost_global = 999999999999 self._best_ind_global = 9999999 history = [] self._evaluations = np.array(0) self._vector = self._initialization() # initialization of generation self._generation = algorithm_globals.random.normal( self._vector[0, :], self._vector[1, :], [self._size_gen, self._n_variables] ) for _ in range(self._maxiter): self._check_generation(fun) self._truncation() self._update_vector() best_mae_local: float = min(self._evaluations) history.append(best_mae_local) best_ind_local = np.where(self._evaluations == best_mae_local)[0][0] best_ind_local = self._generation[best_ind_local] # update the best values ever if best_mae_local < self._best_cost_global: self._best_cost_global = best_mae_local self._best_ind_global = best_ind_local not_better_count = 0 else: not_better_count += 1 if not_better_count >= self._dead_iter: break if self.callback is not None: self.callback( len(history) * self._size_gen, self._best_ind_global, self._best_cost_global ) self._new_generation() result.x = self._best_ind_global result.fun = self._best_cost_global result.nfev = len(history) * self._size_gen return result @property def size_gen(self) -> int: """Returns the size of the generations (number of individuals per generation)""" return self._size_gen @size_gen.setter def size_gen(self, value: int): """ Sets the size of the generations of the algorithm. Args: value: Size of the generations (number of individuals per generation). Raises: ValueError: If `value` is lower than 1. """ if value <= 0: raise ValueError("The size of the generation should be greater than 0.") self._size_gen = value @property def maxiter(self) -> int: """Returns the maximum number of iterations""" return self._maxiter @maxiter.setter def maxiter(self, value: int): """ Sets the maximum number of iterations of the algorithm. Args: value: Maximum number of iterations of the algorithm. Raises: ValueError: If `value` is lower than 1. """ if value <= 0: raise ValueError("The maximum number of iterations should be greater than 0.") self._maxiter = value @property def alpha(self) -> float: """Returns the alpha parameter value (percentage of population selected to update probabilistic model)""" return self._alpha @alpha.setter def alpha(self, value: float): """ Sets the alpha parameter (percentage of individuals selected to update the probabilistic model) Args: value: Percentage (0,1] of generation selected to update the probabilistic model. Raises: ValueError: If `value` is lower than 0 or greater than 1. """ if (value <= 0) or (value > 1): raise ValueError(f"alpha must be in the range (0, 1], value given was {value}") self._alpha = value @property def settings(self) -> dict[str, Any]: return { "maxiter": self.maxiter, "alpha": self.alpha, "size_gen": self.size_gen, "callback": self.callback, } def get_support_level(self): """Get the support level dictionary.""" return { "gradient": OptimizerSupportLevel.ignored, "bounds": OptimizerSupportLevel.ignored, "initial_point": OptimizerSupportLevel.required, }
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020, 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. """Phase estimation for the spectrum of a Hamiltonian""" from __future__ import annotations import warnings from qiskit import QuantumCircuit from qiskit.utils import QuantumInstance from qiskit.utils.deprecation import deprecate_arg from qiskit.opflow import ( SummedOp, PauliOp, MatrixOp, PauliSumOp, StateFn, EvolutionBase, PauliTrotterEvolution, I, ) from qiskit.providers import Backend from .phase_estimation import PhaseEstimation from .hamiltonian_phase_estimation_result import HamiltonianPhaseEstimationResult from .phase_estimation_scale import PhaseEstimationScale from ...circuit.library import PauliEvolutionGate from ...primitives import BaseSampler from ...quantum_info import SparsePauliOp, Statevector, Pauli from ...synthesis import EvolutionSynthesis class HamiltonianPhaseEstimation: r"""Run the Quantum Phase Estimation algorithm to find the eigenvalues of a Hermitian operator. This class is nearly the same as :class:`~qiskit_algorithms.PhaseEstimation`, differing only in that the input in that class is a unitary operator, whereas here the input is a Hermitian operator from which a unitary will be obtained by scaling and exponentiating. The scaling is performed in order to prevent the phases from wrapping around :math:`2\pi`. The problem of estimating eigenvalues :math:`\lambda_j` of the Hermitian operator :math:`H` is solved by running a circuit representing .. math:: \exp(i b H) |\psi\rangle = \sum_j \exp(i b \lambda_j) c_j |\lambda_j\rangle, where the input state is .. math:: |\psi\rangle = \sum_j c_j |\lambda_j\rangle, and :math:`\lambda_j` are the eigenvalues of :math:`H`. Here, :math:`b` is a scaling factor sufficiently large to map positive :math:`\lambda` to :math:`[0,\pi)` and negative :math:`\lambda` to :math:`[\pi,2\pi)`. Each time the circuit is run, one measures a phase corresponding to :math:`lambda_j` with probability :math:`|c_j|^2`. If :math:`H` is a Pauli sum, the bound :math:`b` is computed from the sum of the absolute values of the coefficients of the terms. There is no way to reliably recover eigenvalues from phases very near the endpoints of these intervals. Because of this you should be aware that for degenerate cases, such as :math:`H=Z`, the eigenvalues :math:`\pm 1` will be mapped to the same phase, :math:`\pi`, and so cannot be distinguished. In this case, you need to specify a larger bound as an argument to the method ``estimate``. This class uses and works together with :class:`~qiskit_algorithms.PhaseEstimationScale` to manage scaling the Hamiltonian and the phases that are obtained by the QPE algorithm. This includes setting, or computing, a bound on the eigenvalues of the operator, using this bound to obtain a scale factor, scaling the operator, and shifting and scaling the measured phases to recover the eigenvalues. Note that, although we speak of "evolving" the state according the Hamiltonian, in the present algorithm, we are not actually considering time evolution. Rather, the role of time is played by the scaling factor, which is chosen to best extract the eigenvalues of the Hamiltonian. A few of the ideas in the algorithm may be found in Ref. [1]. **Reference:** [1]: Quantum phase estimation of multiple eigenvalues for small-scale (noisy) experiments T.E. O'Brien, B. Tarasinski, B.M. Terhal `arXiv:1809.09697 <https://arxiv.org/abs/1809.09697>`_ """ @deprecate_arg( "quantum_instance", additional_msg=( "Instead, use the ``sampler`` argument. See https://qisk.it/algo_migration for a " "migration guide." ), since="0.24.0", ) def __init__( self, num_evaluation_qubits: int, quantum_instance: QuantumInstance | Backend | None = None, sampler: BaseSampler | None = None, ) -> None: r""" Args: num_evaluation_qubits: The number of qubits used in estimating the phase. The phase will be estimated as a binary string with this many bits. quantum_instance: Deprecated: The quantum instance on which the circuit will be run. sampler: The sampler primitive on which the circuit will be sampled. """ # Avoid double warning on deprecated used of `quantum_instance`. with warnings.catch_warnings(): warnings.simplefilter("ignore", DeprecationWarning) self._phase_estimation = PhaseEstimation( num_evaluation_qubits=num_evaluation_qubits, quantum_instance=quantum_instance, sampler=sampler, ) def _get_scale(self, hamiltonian, bound=None) -> PhaseEstimationScale: if bound is None: return PhaseEstimationScale.from_pauli_sum(hamiltonian) return PhaseEstimationScale(bound) def _get_unitary( self, hamiltonian, pe_scale, evolution: EvolutionSynthesis | EvolutionBase ) -> QuantumCircuit: """Evolve the Hamiltonian to obtain a unitary. Apply the scaling to the Hamiltonian that has been computed from an eigenvalue bound and compute the unitary by applying the evolution object. """ if self._phase_estimation._sampler is not None: evo = PauliEvolutionGate(hamiltonian, -pe_scale.scale, synthesis=evolution) unitary = QuantumCircuit(evo.num_qubits) unitary.append(evo, unitary.qubits) return unitary.decompose().decompose() else: # scale so that phase does not wrap. scaled_hamiltonian = -pe_scale.scale * hamiltonian unitary = evolution.convert(scaled_hamiltonian.exp_i()) if not isinstance(unitary, QuantumCircuit): unitary = unitary.to_circuit() return unitary.decompose().decompose() # Decomposing twice allows some 1Q Hamiltonians to give correct results # when using MatrixEvolution(), that otherwise would give incorrect results. # It does not break any others that we tested. def estimate( self, hamiltonian: PauliOp | MatrixOp | SummedOp | Pauli | SparsePauliOp | PauliSumOp, state_preparation: StateFn | QuantumCircuit | Statevector | None = None, evolution: EvolutionSynthesis | EvolutionBase | None = None, bound: float | None = None, ) -> HamiltonianPhaseEstimationResult: """Run the Hamiltonian phase estimation algorithm. Args: hamiltonian: A Hermitian operator. If the algorithm is used with a ``Sampler`` primitive, the allowed types are ``Pauli``, ``SparsePauliOp``, and ``PauliSumOp``. If the algorithm is used with a ``QuantumInstance``, ``PauliOp, ``MatrixOp``, ``PauliSumOp``, and ``SummedOp`` types are allowed. state_preparation: The ``StateFn`` to be prepared, whose eigenphase will be measured. If this parameter is omitted, no preparation circuit will be run and input state will be the all-zero state in the computational basis. evolution: An evolution converter that generates a unitary from ``hamiltonian``. If ``None``, then the default ``PauliTrotterEvolution`` is used. bound: An upper bound on the absolute value of the eigenvalues of ``hamiltonian``. If omitted, then ``hamiltonian`` must be a Pauli sum, or a ``PauliOp``, in which case a bound will be computed. If ``hamiltonian`` is a ``MatrixOp``, then ``bound`` may not be ``None``. The tighter the bound, the higher the resolution of computed phases. Returns: ``HamiltonianPhaseEstimationResult`` instance containing the result of the estimation and diagnostic information. Raises: TypeError: If ``evolution`` is not of type ``EvolutionSynthesis`` when a ``Sampler`` is provided. TypeError: If ``hamiltonian`` type is not ``Pauli`` or ``SparsePauliOp`` or ``PauliSumOp`` when a ``Sampler`` is provided. ValueError: If ``bound`` is ``None`` and ``hamiltonian`` is not a Pauli sum, i.e. a ``PauliSumOp`` or a ``SummedOp`` whose terms are of type ``PauliOp``. TypeError: If ``evolution`` is not of type ``EvolutionBase`` when no ``Sampler`` is provided. """ if self._phase_estimation._sampler is not None: if evolution is not None and not isinstance(evolution, EvolutionSynthesis): raise TypeError(f"Expecting type EvolutionSynthesis, got {type(evolution)}") if not isinstance(hamiltonian, (Pauli, SparsePauliOp, PauliSumOp)): raise TypeError( f"Expecting Hamiltonian type Pauli, SparsePauliOp or PauliSumOp, " f"got {type(hamiltonian)}." ) if isinstance(state_preparation, Statevector): circuit = QuantumCircuit(state_preparation.num_qubits) circuit.prepare_state(state_preparation.data) state_preparation = circuit if isinstance(hamiltonian, PauliSumOp): id_coefficient, hamiltonian_no_id = _remove_identity_pauli_sum_op(hamiltonian) else: id_coefficient = 0.0 hamiltonian_no_id = hamiltonian pe_scale = self._get_scale(hamiltonian_no_id, bound) unitary = self._get_unitary(hamiltonian_no_id, pe_scale, evolution) else: if evolution is None: evolution = PauliTrotterEvolution() elif not isinstance(evolution, EvolutionBase): raise TypeError(f"Expecting type EvolutionBase, got {type(evolution)}") if isinstance(hamiltonian, PauliSumOp): hamiltonian = hamiltonian.to_pauli_op() elif isinstance(hamiltonian, PauliOp): hamiltonian = SummedOp([hamiltonian]) if isinstance(hamiltonian, SummedOp): # remove identitiy terms # The term prop to the identity is removed from hamiltonian. # This is done for three reasons: # 1. Work around an unknown bug that otherwise causes the energies to be wrong in some # cases. # 2. Allow working with a simpler Hamiltonian, one with fewer terms. # 3. Tighten the bound on the eigenvalues so that the spectrum is better resolved, i.e. # occupies more of the range of values representable by the qubit register. # The coefficient of this term will be added to the eigenvalues. id_coefficient, hamiltonian_no_id = _remove_identity(hamiltonian) # get the rescaling object pe_scale = self._get_scale(hamiltonian_no_id, bound) # get the unitary unitary = self._get_unitary(hamiltonian_no_id, pe_scale, evolution) elif isinstance(hamiltonian, MatrixOp): if bound is None: raise ValueError("bound must be specified if Hermitian operator is MatrixOp") # Do not subtract an identity term from the matrix, so do not compensate. id_coefficient = 0.0 pe_scale = self._get_scale(hamiltonian, bound) unitary = self._get_unitary(hamiltonian, pe_scale, evolution) else: raise TypeError(f"Hermitian operator of type {type(hamiltonian)} not supported.") if state_preparation is not None and isinstance(state_preparation, StateFn): state_preparation = state_preparation.to_circuit_op().to_circuit() # run phase estimation phase_estimation_result = self._phase_estimation.estimate( unitary=unitary, state_preparation=state_preparation ) return HamiltonianPhaseEstimationResult( phase_estimation_result=phase_estimation_result, id_coefficient=id_coefficient, phase_estimation_scale=pe_scale, ) def _remove_identity(pauli_sum: SummedOp): """Remove any identity operators from `pauli_sum`. Return the sum of the coefficients of the identities and the new operator. """ idcoeff = 0.0 ops = [] for op in pauli_sum: p = op.primitive if p.x.any() or p.z.any(): ops.append(op) else: idcoeff += op.coeff return idcoeff, SummedOp(ops) def _remove_identity_pauli_sum_op(pauli_sum: PauliSumOp | SparsePauliOp): """Remove any identity operators from ``pauli_sum``. Return the sum of the coefficients of the identities and the new operator. """ def _get_identity(size): identity = I for _ in range(size - 1): identity = identity ^ I return identity idcoeff = 0.0 if isinstance(pauli_sum, PauliSumOp): for operator in pauli_sum: if operator.primitive.paulis == ["I" * pauli_sum.num_qubits]: idcoeff += operator.primitive.coeffs[0] pauli_sum = pauli_sum - operator.primitive.coeffs[0] * _get_identity( pauli_sum.num_qubits ) return idcoeff, pauli_sum.reduce()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# 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. """The Iterative Quantum Phase Estimation Algorithm.""" from __future__ import annotations import numpy import qiskit from qiskit.circuit import QuantumCircuit, QuantumRegister from qiskit.circuit.classicalregister import ClassicalRegister from qiskit.providers import Backend from qiskit.utils import QuantumInstance from qiskit.utils.deprecation import deprecate_arg from qiskit_algorithms.exceptions import AlgorithmError from .phase_estimator import PhaseEstimator from .phase_estimator import PhaseEstimatorResult from ...primitives import BaseSampler class IterativePhaseEstimation(PhaseEstimator): """Run the Iterative quantum phase estimation (QPE) algorithm. Given a unitary circuit and a circuit preparing an eigenstate, return the phase of the eigenvalue as a number in :math:`[0,1)` using the iterative phase estimation algorithm. [1]: Dobsicek et al. (2006), Arbitrary accuracy iterative phase estimation algorithm as a two qubit benchmark, `arxiv/quant-ph/0610214 <https://arxiv.org/abs/quant-ph/0610214>`_ """ @deprecate_arg( "quantum_instance", additional_msg=( "Instead, use the ``sampler`` argument. See https://qisk.it/algo_migration for a " "migration guide." ), since="0.24.0", ) def __init__( self, num_iterations: int, quantum_instance: QuantumInstance | Backend | None = None, sampler: BaseSampler | None = None, ) -> None: r""" Args: num_iterations: The number of iterations (rounds) of the phase estimation to run. quantum_instance: Deprecated: The quantum instance on which the circuit will be run. sampler: The sampler primitive on which the circuit will be sampled. Raises: ValueError: if num_iterations is not greater than zero. AlgorithmError: If neither sampler nor quantum instance is provided. """ if sampler is None and quantum_instance is None: raise AlgorithmError( "Neither a sampler nor a quantum instance was provided. Please provide one of them." ) if isinstance(quantum_instance, Backend): quantum_instance = QuantumInstance(quantum_instance) self._quantum_instance = quantum_instance if num_iterations <= 0: raise ValueError("`num_iterations` must be greater than zero.") self._num_iterations = num_iterations self._sampler = sampler def construct_circuit( self, unitary: QuantumCircuit, state_preparation: QuantumCircuit, k: int, omega: float = 0.0, measurement: bool = False, ) -> QuantumCircuit: """Construct the kth iteration Quantum Phase Estimation circuit. For details of parameters, see Fig. 2 in https://arxiv.org/pdf/quant-ph/0610214.pdf. Args: unitary: The circuit representing the unitary operator whose eigenvalue (via phase) will be measured. state_preparation: The circuit that prepares the state whose eigenphase will be measured. If this parameter is omitted, no preparation circuit will be run and input state will be the all-zero state in the computational basis. k: the iteration idx. omega: the feedback angle. measurement: Boolean flag to indicate if measurement should be included in the circuit. Returns: QuantumCircuit: the quantum circuit per iteration """ k = self._num_iterations if k is None else k # The auxiliary (phase measurement) qubit phase_register = QuantumRegister(1, name="a") eigenstate_register = QuantumRegister(unitary.num_qubits, name="q") qc = QuantumCircuit(eigenstate_register) qc.add_register(phase_register) if isinstance(state_preparation, QuantumCircuit): qc.append(state_preparation, eigenstate_register) elif state_preparation is not None: qc += state_preparation.construct_circuit("circuit", eigenstate_register) # hadamard on phase_register[0] qc.h(phase_register[0]) # controlled-U # TODO: We may want to allow flexibility in how the power is computed # For example, it may be desirable to compute the power via Trotterization, if # we are doing Trotterization anyway. unitary_power = unitary.power(2 ** (k - 1)).control() qc = qc.compose(unitary_power, [unitary.num_qubits] + list(range(0, unitary.num_qubits))) qc.p(omega, phase_register[0]) # hadamard on phase_register[0] qc.h(phase_register[0]) if measurement: c = ClassicalRegister(1, name="c") qc.add_register(c) qc.measure(phase_register, c) return qc def _estimate_phase_iteratively(self, unitary, state_preparation): """ Main loop of iterative phase estimation. """ omega_coef = 0 # k runs from the number of iterations back to 1 for k in range(self._num_iterations, 0, -1): omega_coef /= 2 if self._sampler is not None: qc = self.construct_circuit( unitary, state_preparation, k, -2 * numpy.pi * omega_coef, True ) try: sampler_job = self._sampler.run([qc]) result = sampler_job.result().quasi_dists[0] except Exception as exc: raise AlgorithmError("The primitive job failed!") from exc x = 1 if result.get(1, 0) > result.get(0, 0) else 0 elif self._quantum_instance.is_statevector: qc = self.construct_circuit( unitary, state_preparation, k, -2 * numpy.pi * omega_coef, measurement=False ) result = self._quantum_instance.execute(qc) complete_state_vec = result.get_statevector(qc) ancilla_density_mat = qiskit.quantum_info.partial_trace( complete_state_vec, range(unitary.num_qubits) ) ancilla_density_mat_diag = numpy.diag(ancilla_density_mat) max_amplitude = max( ancilla_density_mat_diag.min(), ancilla_density_mat_diag.max(), key=abs ) x = numpy.where(ancilla_density_mat_diag == max_amplitude)[0][0] else: qc = self.construct_circuit( unitary, state_preparation, k, -2 * numpy.pi * omega_coef, measurement=True ) measurements = self._quantum_instance.execute(qc).get_counts(qc) x = 1 if measurements.get("1", 0) > measurements.get("0", 0) else 0 omega_coef = omega_coef + x / 2 return omega_coef # pylint: disable=signature-differs def estimate( self, unitary: QuantumCircuit, state_preparation: QuantumCircuit ) -> "IterativePhaseEstimationResult": """ Estimate the eigenphase of the input unitary and initial-state pair. Args: unitary: The circuit representing the unitary operator whose eigenvalue (via phase) will be measured. state_preparation: The circuit that prepares the state whose eigenphase will be measured. If this parameter is omitted, no preparation circuit will be run and input state will be the all-zero state in the computational basis. Returns: Estimated phase in an IterativePhaseEstimationResult object. Raises: AlgorithmError: If neither sampler nor quantum instance is provided. """ phase = self._estimate_phase_iteratively(unitary, state_preparation) return IterativePhaseEstimationResult(self._num_iterations, phase) class IterativePhaseEstimationResult(PhaseEstimatorResult): """Phase Estimation Result.""" def __init__(self, num_iterations: int, phase: float) -> None: """ Args: num_iterations: number of iterations used in the phase estimation. phase: the estimated phase. """ self._num_iterations = num_iterations self._phase = phase @property def phase(self) -> float: r"""Return the estimated phase as a number in :math:`[0.0, 1.0)`. 1.0 corresponds to a phase of :math:`2\pi`. It is assumed that the input vector is an eigenvector of the unitary so that the peak of the probability density occurs at the bit string that most closely approximates the true phase. """ return self._phase @property def num_iterations(self) -> int: r"""Return the number of iterations used in the estimation algorithm.""" return self._num_iterations
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
from qiskit import QuantumCircuit, Aer, execute from math import pi, sin from qiskit.compiler import transpile, assemble from grover_operator import GroverOperator def qft(n): # returns circuit for inverse quantum fourier transformation for given n 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): if n == 0: return circuit n -= 1 circuit.h(n) for qubit in range(n): circuit.cp(pi / 2 ** (n - qubit), qubit, n) qft_rotations(circuit, n) qft_rotations(circuit, n) swap_registers(circuit, n) return circuit class PhaseEstimation: def get_control_gft(self, label="QFT †"): qft_dagger = self.qft_circuit.to_gate().inverse() qft_dagger.label = label return qft_dagger def get_main_circuit(self): qc = QuantumCircuit(self.c_bits + self.s_bits, self.c_bits) # Circuit with n+t qubits and t classical bits # Initialize all qubits to |+> qc.h(range(self.c_bits + self.n_bits)) qc.h(self.c_bits + self.s_bits - 1) qc.z(self.c_bits + self.s_bits - 1) # Begin controlled Grover iterations iterations = 1 for qubit in range(self.c_bits): for i in range(iterations): qc.append(self.c_grover, [qubit] + [*range(self.c_bits, self.s_bits + self.c_bits)]) iterations *= 2 # Do inverse QFT on counting qubits qc.append(self.c_qft, range(self.c_bits)) # Measure counting qubits qc.measure(range(self.c_bits), range(self.c_bits)) return qc def simulate(self): aer_sim = Aer.get_backend('aer_simulator') transpiled_qc = transpile(self.main_circuit, aer_sim) qobj = assemble(transpiled_qc) job = aer_sim.run(qobj) hist = job.result().get_counts() # plot_histogram(hist) measured_int = int(max(hist, key=hist.get), 2) theta = (measured_int / (2 ** self.c_bits)) * pi * 2 N = 2 ** self.n_bits M = N * (sin(theta / 2) ** 2) # print(N - M, round(N - M)) return round(N - M) def __init__(self, grover: GroverOperator, c_bits=5): self.c_grover = grover.get_control_circuit() self.c_bits = c_bits self.n_bits = grover.n_bits self.s_bits = grover.total_bits self.qft_circuit = qft(c_bits) self.c_qft = self.get_control_gft() self.main_circuit = self.get_main_circuit() self.M = self.simulate()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Base state fidelity interface """ from __future__ import annotations from abc import ABC, abstractmethod from collections.abc import Sequence, Mapping import numpy as np from qiskit import QuantumCircuit from qiskit.circuit import ParameterVector from ..algorithm_job import AlgorithmJob from .state_fidelity_result import StateFidelityResult class BaseStateFidelity(ABC): r""" An interface to calculate state fidelities (state overlaps) for pairs of (parametrized) quantum circuits. The calculation depends on the particular fidelity method implementation, but can be always defined as the state overlap: .. math:: |\langle\psi(x)|\phi(y)\rangle|^2 where :math:`x` and :math:`y` are optional parametrizations of the states :math:`\psi` and :math:`\phi` prepared by the circuits ``circuit_1`` and ``circuit_2``, respectively. """ def __init__(self) -> None: # use cache for preventing unnecessary circuit compositions self._circuit_cache: Mapping[tuple[int, int], QuantumCircuit] = {} @staticmethod def _preprocess_values( circuits: QuantumCircuit | Sequence[QuantumCircuit], values: Sequence[float] | Sequence[Sequence[float]] | None = None, ) -> Sequence[Sequence[float]]: """ Checks whether the passed values match the shape of the parameters of the corresponding circuits and formats values to 2D list. Args: circuits: List of circuits to be checked. values: Parameter values corresponding to the circuits to be checked. Returns: A 2D value list if the values match the circuits, or an empty 2D list if values is None. Raises: ValueError: if the number of parameter values doesn't match the number of circuit parameters TypeError: if the input values are not a sequence. """ if isinstance(circuits, QuantumCircuit): circuits = [circuits] if values is None: for circuit in circuits: if circuit.num_parameters != 0: raise ValueError( f"`values` cannot be `None` because circuit <{circuit.name}> has " f"{circuit.num_parameters} free parameters." ) return [[]] else: # Support ndarray if isinstance(values, np.ndarray): values = values.tolist() if len(values) > 0 and isinstance(values[0], np.ndarray): values = [v.tolist() for v in values] if not isinstance(values, Sequence): raise TypeError( f"Expected a sequence of numerical parameter values, " f"but got input type {type(values)} instead." ) # ensure 2d if len(values) > 0 and not isinstance(values[0], Sequence) or len(values) == 0: values = [values] return values def _check_qubits_match(self, circuit_1: QuantumCircuit, circuit_2: QuantumCircuit) -> None: """ Checks that the number of qubits of 2 circuits matches. Args: circuit_1: (Parametrized) quantum circuit. circuit_2: (Parametrized) quantum circuit. Raises: ValueError: when ``circuit_1`` and ``circuit_2`` don't have the same number of qubits. """ if circuit_1.num_qubits != circuit_2.num_qubits: raise ValueError( f"The number of qubits for the first circuit ({circuit_1.num_qubits}) " f"and second circuit ({circuit_2.num_qubits}) are not the same." ) @abstractmethod def create_fidelity_circuit( self, circuit_1: QuantumCircuit, circuit_2: QuantumCircuit ) -> QuantumCircuit: """ Implementation-dependent method to create a fidelity circuit from 2 circuit inputs. Args: circuit_1: (Parametrized) quantum circuit. circuit_2: (Parametrized) quantum circuit. Returns: The fidelity quantum circuit corresponding to ``circuit_1`` and ``circuit_2``. """ raise NotImplementedError def _construct_circuits( self, circuits_1: QuantumCircuit | Sequence[QuantumCircuit], circuits_2: QuantumCircuit | Sequence[QuantumCircuit], ) -> Sequence[QuantumCircuit]: """ Constructs the list of fidelity circuits to be evaluated. These circuits represent the state overlap between pairs of input circuits, and their construction depends on the fidelity method implementations. Args: circuits_1: (Parametrized) quantum circuits. circuits_2: (Parametrized) quantum circuits. Returns: List of constructed fidelity circuits. Raises: ValueError: if the length of the input circuit lists doesn't match. """ if isinstance(circuits_1, QuantumCircuit): circuits_1 = [circuits_1] if isinstance(circuits_2, QuantumCircuit): circuits_2 = [circuits_2] if len(circuits_1) != len(circuits_2): raise ValueError( f"The length of the first circuit list({len(circuits_1)}) " f"and second circuit list ({len(circuits_2)}) is not the same." ) circuits = [] for (circuit_1, circuit_2) in zip(circuits_1, circuits_2): # TODO: improve caching, what if the circuit is modified without changing the id? circuit = self._circuit_cache.get((id(circuit_1), id(circuit_2))) if circuit is not None: circuits.append(circuit) else: self._check_qubits_match(circuit_1, circuit_2) # re-parametrize input circuits # TODO: make smarter checks to avoid unnecesary reparametrizations parameters_1 = ParameterVector("x", circuit_1.num_parameters) parametrized_circuit_1 = circuit_1.assign_parameters(parameters_1) parameters_2 = ParameterVector("y", circuit_2.num_parameters) parametrized_circuit_2 = circuit_2.assign_parameters(parameters_2) circuit = self.create_fidelity_circuit( parametrized_circuit_1, parametrized_circuit_2 ) circuits.append(circuit) # update cache self._circuit_cache[id(circuit_1), id(circuit_2)] = circuit return circuits def _construct_value_list( self, circuits_1: Sequence[QuantumCircuit], circuits_2: Sequence[QuantumCircuit], values_1: Sequence[float] | Sequence[Sequence[float]] | None = None, values_2: Sequence[float] | Sequence[Sequence[float]] | None = None, ) -> list[float]: """ Preprocesses input parameter values to match the fidelity circuit parametrization, and return in list format. Args: circuits_1: (Parametrized) quantum circuits preparing the first list of quantum states. circuits_2: (Parametrized) quantum circuits preparing the second list of quantum states. values_1: Numerical parameters to be bound to the first circuits. values_2: Numerical parameters to be bound to the second circuits. Returns: List of parameter values for fidelity circuit. """ values_1 = self._preprocess_values(circuits_1, values_1) values_2 = self._preprocess_values(circuits_2, values_2) values = [] if len(values_2[0]) == 0: values = list(values_1) elif len(values_1[0]) == 0: values = list(values_2) else: for (val_1, val_2) in zip(values_1, values_2): values.append(val_1 + val_2) return values @abstractmethod def _run( self, circuits_1: QuantumCircuit | Sequence[QuantumCircuit], circuits_2: QuantumCircuit | Sequence[QuantumCircuit], values_1: Sequence[float] | Sequence[Sequence[float]] | None = None, values_2: Sequence[float] | Sequence[Sequence[float]] | None = None, **options, ) -> StateFidelityResult: r""" Computes the state overlap (fidelity) calculation between two (parametrized) circuits (first and second) for a specific set of parameter values (first and second). Args: circuits_1: (Parametrized) quantum circuits preparing :math:`|\psi\rangle`. circuits_2: (Parametrized) quantum circuits preparing :math:`|\phi\rangle`. values_1: Numerical parameters to be bound to the first set of circuits values_2: Numerical parameters to be bound to the second set of circuits. options: Primitive backend runtime options used for circuit execution. The order of priority is\: options in ``run`` method > fidelity's default options > primitive's default setting. Higher priority setting overrides lower priority setting. Returns: The result of the fidelity calculation. """ raise NotImplementedError def run( self, circuits_1: QuantumCircuit | Sequence[QuantumCircuit], circuits_2: QuantumCircuit | Sequence[QuantumCircuit], values_1: Sequence[float] | Sequence[Sequence[float]] | None = None, values_2: Sequence[float] | Sequence[Sequence[float]] | None = None, **options, ) -> AlgorithmJob: r""" Runs asynchronously the state overlap (fidelity) calculation between two (parametrized) circuits (first and second) for a specific set of parameter values (first and second). This calculation depends on the particular fidelity method implementation. Args: circuits_1: (Parametrized) quantum circuits preparing :math:`|\psi\rangle`. circuits_2: (Parametrized) quantum circuits preparing :math:`|\phi\rangle`. values_1: Numerical parameters to be bound to the first set of circuits. values_2: Numerical parameters to be bound to the second set of circuits. options: Primitive backend runtime options used for circuit execution. The order of priority is\: options in ``run`` method > fidelity's default options > primitive's default setting. Higher priority setting overrides lower priority setting. Returns: Primitive job for the fidelity calculation. The job's result is an instance of ``StateFidelityResult``. """ job = AlgorithmJob(self._run, circuits_1, circuits_2, values_1, values_2, **options) job.submit() return job def _truncate_fidelities(self, fidelities: Sequence[float]) -> Sequence[float]: """ Ensures fidelity result in [0,1]. Args: fidelities: Sequence of raw fidelity results. Returns: List of truncated fidelities. """ return np.clip(fidelities, 0, 1).tolist()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2022, 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. """ Compute-uncompute fidelity interface using primitives """ from __future__ import annotations from collections.abc import Sequence from copy import copy from qiskit import QuantumCircuit from qiskit.primitives import BaseSampler from qiskit.providers import Options from ..exceptions import AlgorithmError from .base_state_fidelity import BaseStateFidelity from .state_fidelity_result import StateFidelityResult class ComputeUncompute(BaseStateFidelity): r""" This class leverages the sampler primitive to calculate the state fidelity of two quantum circuits following the compute-uncompute method (see [1] for further reference). The fidelity can be defined as the state overlap. .. math:: |\langle\psi(x)|\phi(y)\rangle|^2 where :math:`x` and :math:`y` are optional parametrizations of the states :math:`\psi` and :math:`\phi` prepared by the circuits ``circuit_1`` and ``circuit_2``, respectively. **Reference:** [1] Havlíček, V., Córcoles, A. D., Temme, K., Harrow, A. W., Kandala, A., Chow, J. M., & Gambetta, J. M. (2019). Supervised learning with quantum-enhanced feature spaces. Nature, 567(7747), 209-212. `arXiv:1804.11326v2 [quant-ph] <https://arxiv.org/pdf/1804.11326.pdf>`_ """ def __init__( self, sampler: BaseSampler, options: Options | None = None, local: bool = False, ) -> None: r""" Args: sampler: Sampler primitive instance. options: Primitive backend runtime options used for circuit execution. The order of priority is: options in ``run`` method > fidelity's default options > primitive's default setting. Higher priority setting overrides lower priority setting. local: If set to ``True``, the fidelity is averaged over single-qubit projectors .. math:: \hat{O} = \frac{1}{N}\sum_{i=1}^N|0_i\rangle\langle 0_i|, instead of the global projector :math:`|0\rangle\langle 0|^{\otimes n}`. This coincides with the standard (global) fidelity in the limit of the fidelity approaching 1. Might be used to increase the variance to improve trainability in algorithms such as :class:`~.time_evolvers.PVQD`. Raises: ValueError: If the sampler is not an instance of ``BaseSampler``. """ if not isinstance(sampler, BaseSampler): raise ValueError( f"The sampler should be an instance of BaseSampler, " f"but got {type(sampler)}" ) self._sampler: BaseSampler = sampler self._local = local self._default_options = Options() if options is not None: self._default_options.update_options(**options) super().__init__() def create_fidelity_circuit( self, circuit_1: QuantumCircuit, circuit_2: QuantumCircuit ) -> QuantumCircuit: """ Combines ``circuit_1`` and ``circuit_2`` to create the fidelity circuit following the compute-uncompute method. Args: circuit_1: (Parametrized) quantum circuit. circuit_2: (Parametrized) quantum circuit. Returns: The fidelity quantum circuit corresponding to circuit_1 and circuit_2. """ if len(circuit_1.clbits) > 0: circuit_1.remove_final_measurements() if len(circuit_2.clbits) > 0: circuit_2.remove_final_measurements() circuit = circuit_1.compose(circuit_2.inverse()) circuit.measure_all() return circuit def _run( self, circuits_1: QuantumCircuit | Sequence[QuantumCircuit], circuits_2: QuantumCircuit | Sequence[QuantumCircuit], values_1: Sequence[float] | Sequence[Sequence[float]] | None = None, values_2: Sequence[float] | Sequence[Sequence[float]] | None = None, **options, ) -> StateFidelityResult: r""" Computes the state overlap (fidelity) calculation between two (parametrized) circuits (first and second) for a specific set of parameter values (first and second) following the compute-uncompute method. Args: circuits_1: (Parametrized) quantum circuits preparing :math:`|\psi\rangle`. circuits_2: (Parametrized) quantum circuits preparing :math:`|\phi\rangle`. values_1: Numerical parameters to be bound to the first circuits. values_2: Numerical parameters to be bound to the second circuits. options: Primitive backend runtime options used for circuit execution. The order of priority is: options in ``run`` method > fidelity's default options > primitive's default setting. Higher priority setting overrides lower priority setting. Returns: The result of the fidelity calculation. Raises: ValueError: At least one pair of circuits must be defined. AlgorithmError: If the sampler job is not completed successfully. """ circuits = self._construct_circuits(circuits_1, circuits_2) if len(circuits) == 0: raise ValueError( "At least one pair of circuits must be defined to calculate the state overlap." ) values = self._construct_value_list(circuits_1, circuits_2, values_1, values_2) # The priority of run options is as follows: # options in `evaluate` method > fidelity's default options > # primitive's default options. opts = copy(self._default_options) opts.update_options(**options) job = self._sampler.run(circuits=circuits, parameter_values=values, **opts.__dict__) try: result = job.result() except Exception as exc: raise AlgorithmError("Sampler job failed!") from exc if self._local: raw_fidelities = [ self._get_local_fidelity(prob_dist, circuit.num_qubits) for prob_dist, circuit in zip(result.quasi_dists, circuits) ] else: raw_fidelities = [ self._get_global_fidelity(prob_dist) for prob_dist in result.quasi_dists ] fidelities = self._truncate_fidelities(raw_fidelities) return StateFidelityResult( fidelities=fidelities, raw_fidelities=raw_fidelities, metadata=result.metadata, options=self._get_local_options(opts.__dict__), ) @property def options(self) -> Options: """Return the union of estimator options setting and fidelity default options, where, if the same field is set in both, the fidelity's default options override the primitive's default setting. Returns: The fidelity default + estimator options. """ return self._get_local_options(self._default_options.__dict__) def update_default_options(self, **options): """Update the fidelity's default options setting. Args: **options: The fields to update the default options. """ self._default_options.update_options(**options) def _get_local_options(self, options: Options) -> Options: """Return the union of the primitive's default setting, the fidelity default options, and the options in the ``run`` method. The order of priority is: options in ``run`` method > fidelity's default options > primitive's default setting. Args: options: The fields to update the options Returns: The fidelity default + estimator + run options. """ opts = copy(self._sampler.options) opts.update_options(**options) return opts def _get_global_fidelity(self, probability_distribution: dict[int, float]) -> float: """Process the probability distribution of a measurement to determine the global fidelity. Args: probability_distribution: Obtained from the measurement result Returns: The global fidelity. """ return probability_distribution.get(0, 0) def _get_local_fidelity( self, probability_distribution: dict[int, float], num_qubits: int ) -> float: """Process the probability distribution of a measurement to determine the local fidelity by averaging over single-qubit projectors. Args: probability_distribution: Obtained from the measurement result Returns: The local fidelity. """ fidelity = 0.0 for qubit in range(num_qubits): for bitstring, prob in probability_distribution.items(): # Check whether the bit representing the current qubit is 0 if not bitstring >> qubit & 1: fidelity += prob / num_qubits return fidelity
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2022, 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. """Time evolution problem class.""" from __future__ import annotations from collections.abc import Mapping from qiskit import QuantumCircuit from qiskit.circuit import Parameter, ParameterExpression from qiskit.opflow import PauliSumOp from ..list_or_dict import ListOrDict from ...quantum_info import Statevector from ...quantum_info.operators.base_operator import BaseOperator class TimeEvolutionProblem: """Time evolution problem class. This class is the input to time evolution algorithms and must contain information on the total evolution time, a quantum state to be evolved and under which Hamiltonian the state is evolved. Attributes: hamiltonian (BaseOperator | PauliSumOp): The Hamiltonian under which to evolve the system. initial_state (QuantumCircuit | Statevector | None): The quantum state to be evolved for methods like Trotterization. For variational time evolutions, where the evolution happens in an ansatz, this argument is not required. aux_operators (ListOrDict[BaseOperator | PauliSumOp] | None): Optional list of auxiliary operators to be evaluated with the evolved ``initial_state`` and their expectation values returned. truncation_threshold (float): Defines a threshold under which values can be assumed to be 0. Used when ``aux_operators`` is provided. t_param (Parameter | None): Time parameter in case of a time-dependent Hamiltonian. This free parameter must be within the ``hamiltonian``. param_value_map (dict[Parameter, complex] | None): Maps free parameters in the problem to values. Depending on the algorithm, it might refer to e.g. a Hamiltonian or an initial state. """ def __init__( self, hamiltonian: BaseOperator | PauliSumOp, time: float, initial_state: QuantumCircuit | Statevector | None = None, aux_operators: ListOrDict[BaseOperator | PauliSumOp] | None = None, truncation_threshold: float = 1e-12, t_param: Parameter | None = None, param_value_map: Mapping[Parameter, complex] | None = None, ): """ Args: hamiltonian: The Hamiltonian under which to evolve the system. time: Total time of evolution. initial_state: The quantum state to be evolved for methods like Trotterization. For variational time evolutions, where the evolution happens in an ansatz, this argument is not required. aux_operators: Optional list of auxiliary operators to be evaluated with the evolved ``initial_state`` and their expectation values returned. truncation_threshold: Defines a threshold under which values can be assumed to be 0. Used when ``aux_operators`` is provided. t_param: Time parameter in case of a time-dependent Hamiltonian. This free parameter must be within the ``hamiltonian``. param_value_map: Maps free parameters in the problem to values. Depending on the algorithm, it might refer to e.g. a Hamiltonian or an initial state. Raises: ValueError: If non-positive time of evolution is provided. """ self.t_param = t_param self.param_value_map = param_value_map self.hamiltonian = hamiltonian self.time = time if isinstance(initial_state, Statevector): circuit = QuantumCircuit(initial_state.num_qubits) circuit.prepare_state(initial_state.data) initial_state = circuit self.initial_state: QuantumCircuit | None = initial_state self.aux_operators = aux_operators self.truncation_threshold = truncation_threshold @property def time(self) -> float: """Returns time.""" return self._time @time.setter def time(self, time: float) -> None: """ Sets time and validates it. """ self._time = time def validate_params(self) -> None: """ Checks if all parameters present in the Hamiltonian are also present in the dictionary that maps them to values. Raises: ValueError: If Hamiltonian parameters cannot be bound with data provided. """ if isinstance(self.hamiltonian, PauliSumOp) and isinstance( self.hamiltonian.coeff, ParameterExpression ): raise ValueError("A global parametrized coefficient for PauliSumOp is not allowed.")
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2021, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Class for holding time evolution result.""" from __future__ import annotations import numpy as np from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector from qiskit_algorithms.list_or_dict import ListOrDict from ..algorithm_result import AlgorithmResult class TimeEvolutionResult(AlgorithmResult): """ Class for holding time evolution result. Attributes: evolved_state (QuantumCircuit|Statevector): An evolved quantum state. aux_ops_evaluated (ListOrDict[tuple[complex, complex]] | None): Optional list of observables for which expected values on an evolved state are calculated. These values are in fact tuples formatted as (mean, standard deviation). observables (ListOrDict[tuple[np.ndarray, np.ndarray]] | None): Optional list of observables for which expected on an evolved state are calculated at each timestep. These values are in fact lists of tuples formatted as (mean, standard deviation). times (np.array | None): Optional list of times at which each observable has been evaluated. """ def __init__( self, evolved_state: QuantumCircuit | Statevector, aux_ops_evaluated: ListOrDict[tuple[complex, complex]] | None = None, observables: ListOrDict[tuple[np.ndarray, np.ndarray]] | None = None, times: np.ndarray | None = None, ): """ Args: evolved_state: An evolved quantum state. aux_ops_evaluated: Optional list of observables for which expected values on an evolved state are calculated. These values are in fact tuples formatted as (mean, standard deviation). observables: Optional list of observables for which expected values are calculated for each timestep. These values are in fact tuples formatted as (mean array, standard deviation array). times: Optional list of times at which each observable has been evaluated. """ self.evolved_state = evolved_state self.aux_ops_evaluated = aux_ops_evaluated self.observables = observables self.times = times
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Auxiliary functions for SciPy Time Evolvers""" from __future__ import annotations import logging from scipy.sparse import csr_matrix from scipy.sparse.linalg import expm_multiply import numpy as np from qiskit.quantum_info.states import Statevector from qiskit.quantum_info.operators.base_operator import BaseOperator from qiskit import QuantumCircuit from qiskit.opflow import PauliSumOp from ..time_evolution_problem import TimeEvolutionProblem from ..time_evolution_result import TimeEvolutionResult from ...exceptions import AlgorithmError from ...list_or_dict import ListOrDict logger = logging.getLogger(__name__) def _create_observable_output( ops_ev_mean: np.ndarray, evolution_problem: TimeEvolutionProblem, ) -> tuple[ListOrDict[tuple[np.ndarray, np.ndarray]], np.ndarray]: """Creates the right output format for the evaluated auxiliary operators. Args: ops_ev_mean: Array containing the expectation value of each observable at each timestep. evolution_problem: Time Evolution Problem to create the output of. Returns: An output with the observables mean value at the appropriate times depending on whether the auxiliary operators in the time evolution problem are a `list` or a `dict`. """ aux_ops = evolution_problem.aux_operators time_array = np.linspace(0, evolution_problem.time, ops_ev_mean.shape[-1]) zero_array = np.zeros(ops_ev_mean.shape[-1]) # std=0 since it is an exact method operators_number = 0 if aux_ops is None else len(aux_ops) observable_evolution = [(ops_ev_mean[i], zero_array) for i in range(operators_number)] if isinstance(aux_ops, dict): observable_evolution = dict(zip(aux_ops.keys(), observable_evolution)) return observable_evolution, time_array def _create_obs_final( ops_ev_mean: np.ndarray, evolution_problem: TimeEvolutionProblem, ) -> ListOrDict[tuple[complex, complex]]: """Creates the right output format for the final value of the auxiliary operators. Args: ops_ev_mean: Array containing the expectation value of each observable at the final timestep. evolution_problem: Evolution problem to create the output of. Returns: An output with the observables mean value at the appropriate times depending on whether the auxiliary operators in the evolution problem are a `list` or a `dict`. """ aux_ops = evolution_problem.aux_operators aux_ops_evaluated: ListOrDict[tuple[complex, complex]] = [(op_ev, 0) for op_ev in ops_ev_mean] if isinstance(aux_ops, dict): aux_ops_evaluated = dict(zip(aux_ops.keys(), aux_ops_evaluated)) return aux_ops_evaluated def _evaluate_aux_ops( aux_ops: list[csr_matrix], state: np.ndarray, ) -> np.ndarray: """Evaluates the aux operators if they are provided and stores their value. Returns: Mean of the aux operators for a given state. """ op_means = np.array([np.real(state.conjugate().dot(op.dot(state))) for op in aux_ops]) return op_means def _operator_to_matrix(operator: BaseOperator | PauliSumOp): if isinstance(operator, PauliSumOp): op_matrix = operator.to_spmatrix() else: try: op_matrix = operator.to_matrix(sparse=True) except TypeError: logger.debug( "WARNING: operator of type `%s` does not support sparse matrices. " "Trying dense computation", type(operator), ) try: op_matrix = operator.to_matrix() except AttributeError as ex: raise AlgorithmError(f"Unsupported operator type `{type(operator)}`.") from ex return op_matrix def _build_scipy_operators( evolution_problem: TimeEvolutionProblem, num_timesteps: int, real_time: bool ) -> tuple[np.ndarray, list[csr_matrix], csr_matrix]: """Returns the matrices and parameters needed for time evolution in the appropriate format. Args: evolution_problem: The definition of the evolution problem. num_timesteps: Number of timesteps to be performed. real_time: If `True`, returned operators will correspond to real time evolution, Else, they will correspond to imaginary time evolution. Returns: A tuple with the initial state, the list of operators to evaluate and the operator to be exponentiated to perform one timestep. Raises: ValueError: If the Hamiltonian can not be converted into a sparse matrix or dense matrix. """ # Convert the initial state and Hamiltonian into sparse matrices. if isinstance(evolution_problem.initial_state, QuantumCircuit): state = Statevector(evolution_problem.initial_state).data else: state = evolution_problem.initial_state.data hamiltonian = _operator_to_matrix(operator=evolution_problem.hamiltonian) if isinstance(evolution_problem.aux_operators, list): aux_ops = [ _operator_to_matrix(operator=aux_op) for aux_op in evolution_problem.aux_operators ] elif isinstance(evolution_problem.aux_operators, dict): aux_ops = [ _operator_to_matrix(operator=aux_op) for aux_op in evolution_problem.aux_operators.values() ] else: aux_ops = [] timestep = evolution_problem.time / num_timesteps step_operator = -((1.0j) ** real_time) * timestep * hamiltonian return state, aux_ops, step_operator def _evolve( evolution_problem: TimeEvolutionProblem, num_timesteps: int, real_time: bool ) -> TimeEvolutionResult: r"""Performs either real or imaginary time evolution :math:`\exp(-i t H)|\Psi\rangle`. Args: evolution_problem: The definition of the evolution problem. num_timesteps: Number of timesteps to be performed. real_time: If `True`, returned operators will correspond to real time evolution, Else, they will correspond to imaginary time evolution. Returns: Evolution result which includes an evolved quantum state. Raises: ValueError: If the Hamiltonian is time dependent. ValueError: If the initial state is `None`. """ if num_timesteps <= 0: raise ValueError("Variable `num_timesteps` needs to be a positive integer.") if evolution_problem.t_param is not None: raise ValueError("Time dependent Hamiltonians are not supported.") if evolution_problem.initial_state is None: raise ValueError("Initial state is `None`") state, aux_ops, step_operator = _build_scipy_operators( evolution_problem=evolution_problem, num_timesteps=num_timesteps, real_time=real_time ) # Create empty arrays to store the time evolution of the aux operators. number_operators = ( 0 if evolution_problem.aux_operators is None else len(evolution_problem.aux_operators) ) ops_ev_mean = np.empty(shape=(number_operators, num_timesteps + 1), dtype=complex) renormalize = ( (lambda state: state) if real_time else (lambda state: state / np.linalg.norm(state)) ) # Perform the time evolution and stores the value of the operators at each timestep. for ts in range(num_timesteps): ops_ev_mean[:, ts] = _evaluate_aux_ops(aux_ops, state) state = expm_multiply(A=step_operator, B=state) state = renormalize(state) ops_ev_mean[:, num_timesteps] = _evaluate_aux_ops(aux_ops, state) observable_history, times = _create_observable_output(ops_ev_mean, evolution_problem) aux_ops_evaluated = _create_obs_final(ops_ev_mean[:, -1], evolution_problem) return TimeEvolutionResult( evolved_state=Statevector(state), aux_ops_evaluated=aux_ops_evaluated, observables=observable_history, times=times, )
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2021, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """An algorithm to implement a Trotterization real time-evolution.""" from __future__ import annotations from qiskit import QuantumCircuit from qiskit_algorithms.time_evolvers.time_evolution_problem import TimeEvolutionProblem from qiskit_algorithms.time_evolvers.time_evolution_result import TimeEvolutionResult from qiskit_algorithms.time_evolvers.real_time_evolver import RealTimeEvolver from qiskit_algorithms.observables_evaluator import estimate_observables from qiskit.opflow import PauliSumOp from qiskit.circuit.library import PauliEvolutionGate from qiskit.circuit.parametertable import ParameterView from qiskit.primitives import BaseEstimator from qiskit.quantum_info import Pauli, SparsePauliOp from qiskit.synthesis import ProductFormula, LieTrotter class TrotterQRTE(RealTimeEvolver): """Quantum Real Time Evolution using Trotterization. Type of Trotterization is defined by a ``ProductFormula`` provided. Examples: .. code-block:: python from qiskit.opflow import PauliSumOp from qiskit.quantum_info import Pauli, SparsePauliOp from qiskit import QuantumCircuit from qiskit_algorithms import TimeEvolutionProblem from qiskit_algorithms.time_evolvers import TrotterQRTE from qiskit.primitives import Estimator operator = PauliSumOp(SparsePauliOp([Pauli("X"), Pauli("Z")])) initial_state = QuantumCircuit(1) time = 1 evolution_problem = TimeEvolutionProblem(operator, time, initial_state) # LieTrotter with 1 rep estimator = Estimator() trotter_qrte = TrotterQRTE(estimator=estimator) evolved_state = trotter_qrte.evolve(evolution_problem).evolved_state """ def __init__( self, product_formula: ProductFormula | None = None, estimator: BaseEstimator | None = None, num_timesteps: int = 1, ) -> None: """ Args: product_formula: A Lie-Trotter-Suzuki product formula. If ``None`` provided, the Lie-Trotter first order product formula with a single repetition is used. ``reps`` should be 1 to obtain a number of time-steps equal to ``num_timesteps`` and an evaluation of :attr:`.TimeEvolutionProblem.aux_operators` at every time-step. If ``reps`` is larger than 1, the true number of time-steps will be ``num_timesteps * reps``. num_timesteps: The number of time-steps the full evolution time is devided into (repetitions of ``product_formula``) estimator: An estimator primitive used for calculating expectation values of ``TimeEvolutionProblem.aux_operators``. """ self.product_formula = product_formula self.num_timesteps = num_timesteps self.estimator = estimator @property def product_formula(self) -> ProductFormula: """Returns a product formula.""" return self._product_formula @product_formula.setter def product_formula(self, product_formula: ProductFormula | None): """Sets a product formula. If ``None`` provided, sets the Lie-Trotter first order product formula with a single repetition.""" if product_formula is None: product_formula = LieTrotter() self._product_formula = product_formula @property def estimator(self) -> BaseEstimator | None: """ Returns an estimator. """ return self._estimator @estimator.setter def estimator(self, estimator: BaseEstimator) -> None: """ Sets an estimator. """ self._estimator = estimator @property def num_timesteps(self) -> int: """Returns the number of timesteps.""" return self._num_timesteps @num_timesteps.setter def num_timesteps(self, num_timesteps: int) -> None: """ Sets the number of time-steps. Raises: ValueError: If num_timesteps is not positive. """ if num_timesteps <= 0: raise ValueError( f"Number of time steps must be positive integer, {num_timesteps} provided" ) self._num_timesteps = num_timesteps @classmethod def supports_aux_operators(cls) -> bool: """ Whether computing the expectation value of auxiliary operators is supported. Returns: ``True`` if ``aux_operators`` expectations in the ``TimeEvolutionProblem`` can be evaluated, ``False`` otherwise. """ return True def evolve(self, evolution_problem: TimeEvolutionProblem) -> TimeEvolutionResult: """ Evolves a quantum state for a given time using the Trotterization method based on a product formula provided. The result is provided in the form of a quantum circuit. If auxiliary operators are included in the ``evolution_problem``, they are evaluated on the ``init_state`` and on the evolved state at every step (``num_timesteps`` times) using an estimator primitive provided. Args: evolution_problem: Instance defining evolution problem. For the included Hamiltonian, ``Pauli`` or ``PauliSumOp`` are supported by TrotterQRTE. Returns: Evolution result that includes an evolved state as a quantum circuit and, optionally, auxiliary operators evaluated for a resulting state on an estimator primitive. Raises: ValueError: If ``t_param`` is not set to ``None`` in the ``TimeEvolutionProblem`` (feature not currently supported). ValueError: If ``aux_operators`` provided in the time evolution problem but no estimator provided to the algorithm. ValueError: If the ``initial_state`` is not provided in the ``TimeEvolutionProblem``. ValueError: If an unsupported Hamiltonian type is provided. """ evolution_problem.validate_params() if evolution_problem.aux_operators is not None and self.estimator is None: raise ValueError( "The time evolution problem contained ``aux_operators`` but no estimator was " "provided. The algorithm continues without calculating these quantities. " ) # ensure the hamiltonian is a sparse pauli op hamiltonian = evolution_problem.hamiltonian if not isinstance(hamiltonian, (Pauli, PauliSumOp, SparsePauliOp)): raise ValueError( f"TrotterQRTE only accepts Pauli | PauliSumOp | SparsePauliOp, {type(hamiltonian)} " "provided." ) if isinstance(hamiltonian, PauliSumOp): hamiltonian = hamiltonian.primitive * hamiltonian.coeff elif isinstance(hamiltonian, Pauli): hamiltonian = SparsePauliOp(hamiltonian) t_param = evolution_problem.t_param free_parameters = hamiltonian.parameters if t_param is not None and free_parameters != ParameterView([t_param]): raise ValueError( f"Hamiltonian time parameters ({free_parameters}) do not match " f"evolution_problem.t_param ({t_param})." ) # make sure PauliEvolutionGate does not implement more than one Trotter step dt = evolution_problem.time / self.num_timesteps if evolution_problem.initial_state is not None: initial_state = evolution_problem.initial_state else: raise ValueError("``initial_state`` must be provided in the ``TimeEvolutionProblem``.") evolved_state = QuantumCircuit(initial_state.num_qubits) evolved_state.append(initial_state, evolved_state.qubits) if evolution_problem.aux_operators is not None: observables = [] observables.append( estimate_observables( self.estimator, evolved_state, evolution_problem.aux_operators, None, evolution_problem.truncation_threshold, ) ) else: observables = None if t_param is None: # the evolution gate single_step_evolution_gate = PauliEvolutionGate( hamiltonian, dt, synthesis=self.product_formula ) for n in range(self.num_timesteps): # if hamiltonian is time-dependent, bind new time-value at every step to construct # evolution for next step if t_param is not None: time_value = (n + 1) * dt bound_hamiltonian = hamiltonian.assign_parameters([time_value]) single_step_evolution_gate = PauliEvolutionGate( bound_hamiltonian, dt, synthesis=self.product_formula, ) evolved_state.append(single_step_evolution_gate, evolved_state.qubits) if evolution_problem.aux_operators is not None: observables.append( estimate_observables( self.estimator, evolved_state, evolution_problem.aux_operators, None, evolution_problem.truncation_threshold, ) ) evaluated_aux_ops = None if evolution_problem.aux_operators is not None: evaluated_aux_ops = observables[-1] return TimeEvolutionResult(evolved_state, evaluated_aux_ops, observables)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Variational Quantum Imaginary Time Evolution algorithm.""" from __future__ import annotations from collections.abc import Mapping, Sequence from typing import Type, Callable import numpy as np from scipy.integrate import OdeSolver from qiskit import QuantumCircuit from qiskit.circuit import Parameter from qiskit.primitives import BaseEstimator from .solvers.ode.forward_euler_solver import ForwardEulerSolver from .variational_principles import ImaginaryVariationalPrinciple, ImaginaryMcLachlanPrinciple from .var_qte import VarQTE from ..imaginary_time_evolver import ImaginaryTimeEvolver class VarQITE(VarQTE, ImaginaryTimeEvolver): """Variational Quantum Imaginary Time Evolution algorithm. .. code-block::python import numpy as np from qiskit_algorithms import TimeEvolutionProblem, VarQITE from qiskit_algorithms.time_evolvers.variational import ImaginaryMcLachlanPrinciple from qiskit.circuit.library import EfficientSU2 from qiskit.quantum_info import SparsePauliOp, Pauli from qiskit.primitives import Estimator observable = SparsePauliOp.from_list( [ ("II", 0.2252), ("ZZ", 0.5716), ("IZ", 0.3435), ("ZI", -0.4347), ("YY", 0.091), ("XX", 0.091), ] ) ansatz = EfficientSU2(observable.num_qubits, reps=1) init_param_values = np.ones(len(ansatz.parameters)) * np.pi/2 var_principle = ImaginaryMcLachlanPrinciple() time = 1 # without evaluating auxiliary operators evolution_problem = TimeEvolutionProblem(observable, time) var_qite = VarQITE(ansatz, init_param_values, var_principle) evolution_result = var_qite.evolve(evolution_problem) # evaluating auxiliary operators aux_ops = [Pauli("XX"), Pauli("YZ")] evolution_problem = TimeEvolutionProblem(observable, time, aux_operators=aux_ops) var_qite = VarQITE(ansatz, init_param_values, var_principle, Estimator()) evolution_result = var_qite.evolve(evolution_problem) """ def __init__( self, ansatz: QuantumCircuit, initial_parameters: Mapping[Parameter, float] | Sequence[float], variational_principle: ImaginaryVariationalPrinciple | None = None, estimator: BaseEstimator | None = None, ode_solver: Type[OdeSolver] | str = ForwardEulerSolver, lse_solver: Callable[[np.ndarray, np.ndarray], np.ndarray] | None = None, num_timesteps: int | None = None, imag_part_tol: float = 1e-7, num_instability_tol: float = 1e-7, ) -> None: r""" Args: ansatz: Ansatz to be used for variational time evolution. initial_parameters: Initial parameter values for the ansatz. variational_principle: Variational Principle to be used. Defaults to ``ImaginaryMcLachlanPrinciple``. estimator: An estimator primitive used for calculating expectation values of TimeEvolutionProblem.aux_operators. ode_solver: ODE solver callable that implements a SciPy ``OdeSolver`` interface or a string indicating a valid method offered by SciPy. lse_solver: Linear system of equations solver callable. It accepts ``A`` and ``b`` to solve ``Ax=b`` and returns ``x``. If ``None``, the default ``np.linalg.lstsq`` solver is used. num_timesteps: The number of timesteps to take. If ``None``, it is automatically selected to achieve a timestep of approximately 0.01. Only relevant in case of the ``ForwardEulerSolver``. imag_part_tol: Allowed value of an imaginary part that can be neglected if no imaginary part is expected. num_instability_tol: The amount of negative value that is allowed to be rounded up to 0 for quantities that are expected to be non-negative. """ if variational_principle is None: variational_principle = ImaginaryMcLachlanPrinciple() super().__init__( ansatz, initial_parameters, variational_principle, estimator, ode_solver, lse_solver=lse_solver, num_timesteps=num_timesteps, imag_part_tol=imag_part_tol, num_instability_tol=num_instability_tol, )
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Variational Quantum Real Time Evolution algorithm.""" from __future__ import annotations from collections.abc import Mapping, Sequence from typing import Type, Callable import numpy as np from scipy.integrate import OdeSolver from qiskit import QuantumCircuit from qiskit.circuit import Parameter from qiskit.primitives import BaseEstimator from .solvers.ode.forward_euler_solver import ForwardEulerSolver from .variational_principles import RealVariationalPrinciple, RealMcLachlanPrinciple from .var_qte import VarQTE from ..real_time_evolver import RealTimeEvolver class VarQRTE(VarQTE, RealTimeEvolver): """Variational Quantum Real Time Evolution algorithm. .. code-block::python import numpy as np from qiskit_algorithms import TimeEvolutionProblem, VarQRTE from qiskit.circuit.library import EfficientSU2 from qiskit_algorithms.time_evolvers.variational import RealMcLachlanPrinciple from qiskit.quantum_info import SparsePauliOp from qiskit.quantum_info import SparsePauliOp, Pauli from qiskit.primitives import Estimator observable = SparsePauliOp.from_list( [ ("II", 0.2252), ("ZZ", 0.5716), ("IZ", 0.3435), ("ZI", -0.4347), ("YY", 0.091), ("XX", 0.091), ] ) ansatz = EfficientSU2(observable.num_qubits, reps=1) init_param_values = np.ones(len(ansatz.parameters)) * np.pi/2 var_principle = RealMcLachlanPrinciple() time = 1 # without evaluating auxiliary operators evolution_problem = TimeEvolutionProblem(observable, time) var_qrte = VarQRTE(ansatz, init_param_values, var_principle) evolution_result = var_qrte.evolve(evolution_problem) # evaluating auxiliary operators aux_ops = [Pauli("XX"), Pauli("YZ")] evolution_problem = TimeEvolutionProblem(observable, time, aux_operators=aux_ops) var_qrte = VarQRTE(ansatz, init_param_values, var_principle, Estimator()) evolution_result = var_qrte.evolve(evolution_problem) """ def __init__( self, ansatz: QuantumCircuit, initial_parameters: Mapping[Parameter, float] | Sequence[float], variational_principle: RealVariationalPrinciple | None = None, estimator: BaseEstimator | None = None, ode_solver: Type[OdeSolver] | str = ForwardEulerSolver, lse_solver: Callable[[np.ndarray, np.ndarray], np.ndarray] | None = None, num_timesteps: int | None = None, imag_part_tol: float = 1e-7, num_instability_tol: float = 1e-7, ) -> None: r""" Args: ansatz: Ansatz to be used for variational time evolution. initial_parameters: Initial parameter values for an ansatz. variational_principle: Variational Principle to be used. Defaults to ``RealMcLachlanPrinciple``. estimator: An estimator primitive used for calculating expectation values of TimeEvolutionProblem.aux_operators. ode_solver: ODE solver callable that implements a SciPy ``OdeSolver`` interface or a string indicating a valid method offered by SciPy. lse_solver: Linear system of equations solver callable. It accepts ``A`` and ``b`` to solve ``Ax=b`` and returns ``x``. If ``None``, the default ``np.linalg.lstsq`` solver is used. num_timesteps: The number of timesteps to take. If ``None``, it is automatically selected to achieve a timestep of approximately 0.01. Only relevant in case of the ``ForwardEulerSolver``. imag_part_tol: Allowed value of an imaginary part that can be neglected if no imaginary part is expected. num_instability_tol: The amount of negative value that is allowed to be rounded up to 0 for quantities that are expected to be non-negative. """ if variational_principle is None: variational_principle = RealMcLachlanPrinciple() super().__init__( ansatz, initial_parameters, variational_principle, estimator, ode_solver, lse_solver=lse_solver, num_timesteps=num_timesteps, imag_part_tol=imag_part_tol, num_instability_tol=num_instability_tol, )
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """The Variational Quantum Time Evolution Interface""" from __future__ import annotations from abc import ABC from collections.abc import Mapping, Callable, Sequence from typing import Type import numpy as np from scipy.integrate import OdeSolver from qiskit import QuantumCircuit from qiskit.circuit import Parameter from qiskit.opflow import PauliSumOp from qiskit.primitives import BaseEstimator from qiskit.quantum_info.operators.base_operator import BaseOperator from .solvers.ode.forward_euler_solver import ForwardEulerSolver from .solvers.ode.ode_function_factory import OdeFunctionFactory from .solvers.ode.var_qte_ode_solver import VarQTEOdeSolver from .solvers.var_qte_linear_solver import VarQTELinearSolver from .variational_principles.variational_principle import VariationalPrinciple from .var_qte_result import VarQTEResult from ..time_evolution_problem import TimeEvolutionProblem from ...observables_evaluator import estimate_observables class VarQTE(ABC): """Variational Quantum Time Evolution. Algorithms that use variational principles to compute a time evolution for a given Hermitian operator (Hamiltonian) and a quantum state prepared by a parameterized quantum circuit. Attributes: ansatz (QuantumCircuit): Ansatz to be used for variational time evolution. initial_parameters (Mapping[Parameter, float] | Sequence[float]): Initial parameter values for an ansatz. variational_principle (VariationalPrinciple): Variational Principle to be used. estimator (BaseEstimator): An estimator primitive used for calculating expectation values of ``TimeEvolutionProblem.aux_operators``. ode_solver(Type[OdeSolver] | str): ODE solver callable that implements a SciPy ``OdeSolver`` interface or a string indicating a valid method offered by SciPy. lse_solver (Callable[[np.ndarray, np.ndarray], np.ndarray] | None): Linear system of equations solver callable. It accepts ``A`` and ``b`` to solve ``Ax=b`` and returns ``x``. num_timesteps (int | None): The number of timesteps to take. If None, it is automatically selected to achieve a timestep of approximately 0.01. Only relevant in case of the ``ForwardEulerSolver``. imag_part_tol (float): Allowed value of an imaginary part that can be neglected if no imaginary part is expected. num_instability_tol (float): The amount of negative value that is allowed to be rounded up to 0 for quantities that are expected to be non-negative. References: [1] Benjamin, Simon C. et al. (2019). Theory of variational quantum simulation. `<https://doi.org/10.22331/q-2019-10-07-191>`_ """ def __init__( self, ansatz: QuantumCircuit, initial_parameters: Mapping[Parameter, float] | Sequence[float], variational_principle: VariationalPrinciple, estimator: BaseEstimator, ode_solver: Type[OdeSolver] | str = ForwardEulerSolver, lse_solver: Callable[[np.ndarray, np.ndarray], np.ndarray] | None = None, num_timesteps: int | None = None, imag_part_tol: float = 1e-7, num_instability_tol: float = 1e-7, ) -> None: r""" Args: ansatz: Ansatz to be used for variational time evolution. initial_parameters: Initial parameter values for an ansatz. variational_principle: Variational Principle to be used. estimator: An estimator primitive used for calculating expectation values of TimeEvolutionProblem.aux_operators. ode_solver: ODE solver callable that implements a SciPy ``OdeSolver`` interface or a string indicating a valid method offered by SciPy. lse_solver: Linear system of equations solver callable. It accepts ``A`` and ``b`` to solve ``Ax=b`` and returns ``x``. num_timesteps: The number of timesteps to take. If None, it is automatically selected to achieve a timestep of approximately 0.01. Only relevant in case of the ``ForwardEulerSolver``. imag_part_tol: Allowed value of an imaginary part that can be neglected if no imaginary part is expected. num_instability_tol: The amount of negative value that is allowed to be rounded up to 0 for quantities that are expected to be non-negative. """ super().__init__() self.ansatz = ansatz self.initial_parameters = initial_parameters self.variational_principle = variational_principle self.estimator = estimator self.num_timesteps = num_timesteps self.lse_solver = lse_solver self.ode_solver = ode_solver self.imag_part_tol = imag_part_tol self.num_instability_tol = num_instability_tol # OdeFunction abstraction kept for potential extensions - unclear at the moment; # currently hidden from the user self._ode_function_factory = OdeFunctionFactory() def evolve(self, evolution_problem: TimeEvolutionProblem) -> VarQTEResult: """Apply Variational Quantum Time Evolution to the given operator. Args: evolution_problem: Instance defining an evolution problem. Returns: Result of the evolution which includes a quantum circuit with bound parameters as an evolved state and, if provided, observables evaluated on the evolved state. Raises: ValueError: If ``initial_state`` is included in the ``evolution_problem``. """ self._validate_aux_ops(evolution_problem) if evolution_problem.initial_state is not None: raise ValueError( "An initial_state was provided to the TimeEvolutionProblem but this is not " "supported by VarQTE. Please remove this state from the problem definition " "and set VarQTE.initial_parameters with the corresponding initial parameter " "values instead." ) init_state_param_dict = self._create_init_state_param_dict( self.initial_parameters, self.ansatz.parameters ) # unwrap PauliSumOp (in the future this will be deprecated) if isinstance(evolution_problem.hamiltonian, PauliSumOp): hamiltonian = ( evolution_problem.hamiltonian.primitive * evolution_problem.hamiltonian.coeff ) else: hamiltonian = evolution_problem.hamiltonian evolved_state, param_values, time_points = self._evolve( init_state_param_dict, hamiltonian, evolution_problem.time, evolution_problem.t_param, ) observables = [] if evolution_problem.aux_operators is not None: for values in param_values: # cannot batch evaluation because estimate_observables # only accepts single circuits evol_state = self.ansatz.assign_parameters( dict(zip(init_state_param_dict.keys(), values)) ) observable = estimate_observables( self.estimator, evol_state, evolution_problem.aux_operators, ) observables.append(observable) # TODO: deprecate returning evaluated_aux_ops. # As these are the observables for the last time step. evaluated_aux_ops = observables[-1] if len(observables) > 0 else None return VarQTEResult( evolved_state, evaluated_aux_ops, observables, time_points, param_values ) def _evolve( self, init_state_param_dict: Mapping[Parameter, float], hamiltonian: BaseOperator, time: float, t_param: Parameter | None = None, ) -> tuple[QuantumCircuit | None, Sequence[Sequence[float]], Sequence[float]]: r""" Helper method for performing time evolution. Works both for imaginary and real case. Args: init_state_param_dict: Parameter dictionary with initial values for a given parametrized state/ansatz. hamiltonian: Operator used for Variational Quantum Time Evolution (VarQTE). time: Total time of evolution. t_param: Time parameter in case of a time-dependent Hamiltonian. Returns: Result of the evolution which is a quantum circuit with bound parameters as an evolved state. """ init_state_parameters = list(init_state_param_dict.keys()) init_state_parameter_values = list(init_state_param_dict.values()) linear_solver = VarQTELinearSolver( self.variational_principle, hamiltonian, self.ansatz, init_state_parameters, t_param, self.lse_solver, self.imag_part_tol, ) # Convert the operator that holds the Hamiltonian and ansatz into a NaturalGradient operator ode_function = self._ode_function_factory._build( linear_solver, init_state_param_dict, t_param ) ode_solver = VarQTEOdeSolver( init_state_parameter_values, ode_function, self.ode_solver, self.num_timesteps ) final_param_values, param_values, time_points = ode_solver.run(time) param_dict_from_ode = dict(zip(init_state_parameters, final_param_values)) return self.ansatz.assign_parameters(param_dict_from_ode), param_values, time_points @staticmethod def _create_init_state_param_dict( param_values: Mapping[Parameter, float] | Sequence[float], init_state_parameters: Sequence[Parameter], ) -> Mapping[Parameter, float]: r""" If ``param_values`` is a dictionary, it looks for parameters present in an initial state (an ansatz) in a ``param_values``. Based on that, it creates a new dictionary containing only parameters present in an initial state and their respective values. If ``param_values`` is a list of values, it creates a new dictionary containing parameters present in an initial state and their respective values. Args: param_values: Dictionary which relates parameter values to the parameters or a list of values. init_state_parameters: Parameters present in a quantum state. Returns: Dictionary that maps parameters of an initial state to some values. Raises: ValueError: If the dictionary with parameter values provided does not include all parameters present in the initial state or if the list of values provided is not the same length as the list of parameters. TypeError: If an unsupported type of ``param_values`` provided. """ if isinstance(param_values, Mapping): init_state_parameter_values: Sequence[float] = [] for param in init_state_parameters: if param in param_values.keys(): init_state_parameter_values.append(param_values[param]) else: raise ValueError( f"The dictionary with parameter values provided does not " f"include all parameters present in the initial state." f"Parameters present in the state: {init_state_parameters}, " f"parameters in the dictionary: " f"{list(param_values.keys())}." ) elif isinstance(param_values, (Sequence, np.ndarray)): if len(init_state_parameters) != len(param_values): raise ValueError( f"Initial state has {len(init_state_parameters)} parameters and the" f" list of values has {len(param_values)} elements. They should be" f" equal in length." ) init_state_parameter_values = param_values else: raise TypeError(f"Unsupported type of param_values provided: {type(param_values)}.") init_state_param_dict = dict(zip(init_state_parameters, init_state_parameter_values)) return init_state_param_dict def _validate_aux_ops(self, evolution_problem: TimeEvolutionProblem) -> None: if evolution_problem.aux_operators is not None and self.estimator is None: raise ValueError( "aux_operators were provided for evaluations but no ``estimator`` was provided." )
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Class for solving linear equations for Quantum Time Evolution.""" from __future__ import annotations from collections.abc import Mapping, Sequence, Callable import numpy as np from qiskit import QuantumCircuit from qiskit.circuit import Parameter from qiskit.quantum_info import SparsePauliOp from qiskit.quantum_info.operators.base_operator import BaseOperator from ..variational_principles import VariationalPrinciple class VarQTELinearSolver: """Class for solving linear equations for Quantum Time Evolution.""" def __init__( self, var_principle: VariationalPrinciple, hamiltonian: BaseOperator, ansatz: QuantumCircuit, gradient_params: Sequence[Parameter] | None = None, t_param: Parameter | None = None, lse_solver: Callable[[np.ndarray, np.ndarray], np.ndarray] | None = None, imag_part_tol: float = 1e-7, ) -> None: """ Args: var_principle: Variational Principle to be used. hamiltonian: Operator used for Variational Quantum Time Evolution. ansatz: Quantum state in the form of a parametrized quantum circuit. gradient_params: List of parameters with respect to which gradients should be computed. If ``None`` given, gradients w.r.t. all parameters will be computed. t_param: Time parameter in case of a time-dependent Hamiltonian. lse_solver: Linear system of equations solver callable. It accepts ``A`` and ``b`` to solve ``Ax=b`` and returns ``x``. If ``None``, the default ``np.linalg.lstsq`` solver is used. imag_part_tol: Allowed value of an imaginary part that can be neglected if no imaginary part is expected. Raises: TypeError: If t_param is provided and Hamiltonian is not of type SparsePauliOp. """ self._var_principle = var_principle self._hamiltonian = hamiltonian self._ansatz = ansatz self._gradient_params = gradient_params self._bind_params = gradient_params self._time_param = t_param self.lse_solver = lse_solver self._imag_part_tol = imag_part_tol if self._time_param is not None and not isinstance(self._hamiltonian, SparsePauliOp): raise TypeError( f"A time parameter {t_param} has been specified, so a time-dependent " f"hamiltonian is expected. The operator provided is of type {type(self._hamiltonian)}, " f"which might not support parametrization. " f"Please provide the parametrized hamiltonian as a SparsePauliOp." ) @property def lse_solver(self) -> Callable[[np.ndarray, np.ndarray], np.ndarray]: """Returns an LSE solver callable.""" return self._lse_solver @lse_solver.setter def lse_solver(self, lse_solver: Callable[[np.ndarray, np.ndarray], np.ndarray] | None) -> None: """Sets an LSE solver. Uses a ``np.linalg.lstsq`` callable if ``None`` provided.""" if lse_solver is None: lse_solver = lambda a, b: np.linalg.lstsq(a, b, rcond=1e-2)[0] self._lse_solver = lse_solver def solve_lse( self, param_dict: Mapping[Parameter, float], time_value: float | None = None, ) -> tuple[np.ndarray, np.ndarray, np.ndarray]: """ Solve the system of linear equations underlying McLachlan's variational principle for the calculation without error bounds. Args: param_dict: Dictionary which relates parameter values to the parameters in the ansatz. time_value: Time value that will be bound to ``t_param``. It is required if ``t_param`` is not ``None``. Returns: Solution to the LSE, A from Ax=b, b from Ax=b. Raises: ValueError: If no time value is provided for time dependent hamiltonians. """ param_values = list(param_dict.values()) metric_tensor_lse_lhs = self._var_principle.metric_tensor(self._ansatz, param_values) hamiltonian = self._hamiltonian if self._time_param is not None: if time_value is not None: hamiltonian = hamiltonian.assign_parameters([time_value]) else: raise ValueError( "Providing a time_value is required for time-dependent hamiltonians, " f"but got time_value = {time_value}. " "Please provide a time_value to the solve_lse method." ) evolution_grad_lse_rhs = self._var_principle.evolution_gradient( hamiltonian, self._ansatz, param_values, self._gradient_params ) x = self._lse_solver(metric_tensor_lse_lhs, evolution_grad_lse_rhs) return np.real(x), metric_tensor_lse_lhs, evolution_grad_lse_rhs
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Class for an Imaginary McLachlan's Variational Principle.""" from __future__ import annotations import warnings from collections.abc import Sequence import numpy as np from qiskit import QuantumCircuit from qiskit.circuit import Parameter from qiskit.primitives import Estimator from qiskit.quantum_info.operators.base_operator import BaseOperator from .imaginary_variational_principle import ImaginaryVariationalPrinciple from ....exceptions import AlgorithmError from ....gradients import ( BaseEstimatorGradient, BaseQGT, DerivativeType, LinCombQGT, LinCombEstimatorGradient, ) class ImaginaryMcLachlanPrinciple(ImaginaryVariationalPrinciple): """Class for an Imaginary McLachlan's Variational Principle. It aims to minimize the distance between both sides of the Wick-rotated SchrΓΆdinger equation with a quantum state given as a parametrized trial state. The principle leads to a system of linear equations handled by a linear solver. The imaginary variant means that we consider imaginary time dynamics. """ def __init__( self, qgt: BaseQGT | None = None, gradient: BaseEstimatorGradient | None = None, ) -> None: """ Args: qgt: Instance of a the GQT class used to compute the QFI. If ``None`` provided, ``LinCombQGT`` is used. gradient: Instance of a class used to compute the state gradient. If ``None`` provided, ``LinCombEstimatorGradient`` is used. Raises: AlgorithmError: If the gradient instance does not contain an estimator. """ self._validate_grad_settings(gradient) if gradient is not None: try: estimator = gradient._estimator except Exception as exc: raise AlgorithmError( "The provided gradient instance does not contain an estimator primitive." ) from exc else: estimator = Estimator() gradient = LinCombEstimatorGradient(estimator) if qgt is None: qgt = LinCombQGT(estimator) super().__init__(qgt, gradient) def evolution_gradient( self, hamiltonian: BaseOperator, ansatz: QuantumCircuit, param_values: Sequence[float], gradient_params: Sequence[Parameter] | None = None, ) -> np.ndarray: """ Calculates an evolution gradient according to the rules of this variational principle. Args: hamiltonian: Operator used for Variational Quantum Time Evolution. ansatz: Quantum state in the form of a parametrized quantum circuit. param_values: Values of parameters to be bound. gradient_params: List of parameters with respect to which gradients should be computed. If ``None`` given, gradients w.r.t. all parameters will be computed. Returns: An evolution gradient. Raises: AlgorithmError: If a gradient job fails. """ try: evolution_grad_lse_rhs = ( self.gradient.run([ansatz], [hamiltonian], [param_values], [gradient_params]) .result() .gradients[0] ) except Exception as exc: raise AlgorithmError("The gradient primitive job failed!") from exc return -0.5 * evolution_grad_lse_rhs @staticmethod def _validate_grad_settings(gradient): if ( gradient is not None and hasattr(gradient, "_derivative_type") and gradient._derivative_type != DerivativeType.REAL ): warnings.warn( "A gradient instance with a setting for calculating imaginary part of " "the gradient was provided. This variational principle requires the" "real part. The setting to real was changed automatically." ) gradient._derivative_type = DerivativeType.REAL
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Class for a Real McLachlan's Variational Principle.""" from __future__ import annotations import warnings from collections.abc import Sequence import numpy as np from numpy import real from qiskit import QuantumCircuit from qiskit.circuit import Parameter from qiskit.primitives import Estimator from qiskit.quantum_info import SparsePauliOp from qiskit.quantum_info.operators.base_operator import BaseOperator from .real_variational_principle import RealVariationalPrinciple from ....exceptions import AlgorithmError from ....gradients import ( BaseEstimatorGradient, BaseQGT, DerivativeType, LinCombQGT, LinCombEstimatorGradient, ) class RealMcLachlanPrinciple(RealVariationalPrinciple): """Class for a Real McLachlan's Variational Principle. It aims to minimize the distance between both sides of the SchrΓΆdinger equation with a quantum state given as a parametrized trial state. The principle leads to a system of linear equations handled by a linear solver. The real variant means that we consider real time dynamics. """ def __init__( self, qgt: BaseQGT | None = None, gradient: BaseEstimatorGradient | None = None, ) -> None: """ Args: qgt: Instance of a the GQT class used to compute the QFI. If ``None`` provided, ``LinCombQGT`` is used. gradient: Instance of a class used to compute the state gradient. If ``None`` provided, ``LinCombEstimatorGradient`` is used. Raises: AlgorithmError: If the gradient instance does not contain an estimator. """ self._validate_grad_settings(gradient) if gradient is not None: try: estimator = gradient._estimator except Exception as exc: raise AlgorithmError( "The provided gradient instance does not contain an estimator primitive." ) from exc else: estimator = Estimator() gradient = LinCombEstimatorGradient(estimator, derivative_type=DerivativeType.IMAG) if qgt is None: qgt = LinCombQGT(estimator) super().__init__(qgt, gradient) def evolution_gradient( self, hamiltonian: BaseOperator, ansatz: QuantumCircuit, param_values: Sequence[float], gradient_params: Sequence[Parameter] | None = None, ) -> np.ndarray: """ Calculates an evolution gradient according to the rules of this variational principle. Args: hamiltonian: Operator used for Variational Quantum Time Evolution. ansatz: Quantum state in the form of a parametrized quantum circuit. param_values: Values of parameters to be bound. gradient_params: List of parameters with respect to which gradients should be computed. If ``None`` given, gradients w.r.t. all parameters will be computed. Returns: An evolution gradient. Raises: AlgorithmError: If a gradient job fails. """ try: estimator_job = self.gradient._estimator.run([ansatz], [hamiltonian], [param_values]) energy = estimator_job.result().values[0] except Exception as exc: raise AlgorithmError("The primitive job failed!") from exc modified_hamiltonian = self._construct_modified_hamiltonian(hamiltonian, real(energy)) try: evolution_grad = ( 0.5 * self.gradient.run( [ansatz], [modified_hamiltonian], parameters=[gradient_params], parameter_values=[param_values], ) .result() .gradients[0] ) except Exception as exc: raise AlgorithmError("The gradient primitive job failed!") from exc # The BaseEstimatorGradient class returns the gradient of the opposite sign than we expect # here (i.e. with a minus sign), hence the correction that cancels it to recover the # real McLachlan's principle equations that do not have a minus sign. evolution_grad = (-1) * evolution_grad return evolution_grad @staticmethod def _construct_modified_hamiltonian(hamiltonian: BaseOperator, energy: float) -> BaseOperator: """ Modifies a Hamiltonian according to the rules of this variational principle. Args: hamiltonian: Operator used for Variational Quantum Time Evolution. energy: The energy correction value. Returns: A modified Hamiltonian. """ energy_term = SparsePauliOp.from_list( hamiltonian.to_list() + [("I" * hamiltonian.num_qubits, -energy)] ) return energy_term @staticmethod def _validate_grad_settings(gradient): if gradient is not None: if not hasattr(gradient, "_derivative_type"): raise ValueError( "The gradient instance provided does not support calculating imaginary part. " "Please choose a different gradient class." ) if gradient._derivative_type != DerivativeType.IMAG: warnings.warn( "A gradient instance with a setting for calculating real part of the" "gradient was provided. This variational principle requires the" "imaginary part. The setting to imaginary was changed automatically." ) gradient._derivative_type = DerivativeType.IMAG
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Class for a Variational Principle.""" from __future__ import annotations from abc import ABC, abstractmethod from collections.abc import Sequence import numpy as np from qiskit import QuantumCircuit from qiskit.circuit import Parameter from qiskit.quantum_info.operators.base_operator import BaseOperator from ....exceptions import AlgorithmError from ....gradients import BaseEstimatorGradient, BaseQGT, DerivativeType class VariationalPrinciple(ABC): """A Variational Principle class. It determines the time propagation of parameters in a quantum state provided as a parametrized quantum circuit (ansatz). Attributes: qgt (BaseQGT): Instance of a class used to compute the GQT. gradient (BaseEstimatorGradient): Instance of a class used to compute the state gradient. """ def __init__( self, qgt: BaseQGT, gradient: BaseEstimatorGradient, ) -> None: """ Args: qgt: Instance of a class used to compute the GQT. gradient: Instance of a class used to compute the state gradient. """ self.qgt = qgt self.gradient = gradient def metric_tensor( self, ansatz: QuantumCircuit, param_values: Sequence[float] ) -> Sequence[float]: """ Calculates a metric tensor according to the rules of this variational principle. Args: ansatz: Quantum state in the form of a parametrized quantum circuit. param_values: Values of parameters to be bound. Returns: Metric tensor. Raises: AlgorithmError: If a QFI job fails. """ self.qgt.derivative_type = DerivativeType.REAL try: metric_tensor = self.qgt.run([ansatz], [param_values], [None]).result().qgts[0] except Exception as exc: raise AlgorithmError("The QFI primitive job failed!") from exc return metric_tensor @abstractmethod def evolution_gradient( self, hamiltonian: BaseOperator, ansatz: QuantumCircuit, param_values: Sequence[float], gradient_params: Sequence[Parameter] | None = None, ) -> np.ndarray: """ Calculates an evolution gradient according to the rules of this variational principle. Args: hamiltonian: Operator used for Variational Quantum Time Evolution. ansatz: Quantum state in the form of a parametrized quantum circuit. param_values: Values of parameters to be bound. gradient_params: List of parameters with respect to which gradients should be computed. If ``None`` given, gradients w.r.t. all parameters will be computed. Returns: An evolution gradient. """ pass
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Assemble function for converting a list of circuits into a qobj.""" import hashlib from collections import defaultdict from typing import Any, Dict, List, Tuple, Union from qiskit import qobj, pulse from qiskit.assembler.run_config import RunConfig from qiskit.exceptions import QiskitError from qiskit.pulse import instructions, transforms, library, schedule, channels from qiskit.qobj import utils as qobj_utils, converters from qiskit.qobj.converters.pulse_instruction import ParametricPulseShapes def assemble_schedules( schedules: List[ Union[ schedule.ScheduleBlock, schedule.ScheduleComponent, Tuple[int, schedule.ScheduleComponent], ] ], qobj_id: int, qobj_header: qobj.QobjHeader, run_config: RunConfig, ) -> qobj.PulseQobj: """Assembles a list of schedules into a qobj that can be run on the backend. Args: schedules: Schedules to assemble. qobj_id: Identifier for the generated qobj. qobj_header: Header to pass to the results. run_config: Configuration of the runtime environment. Returns: The Qobj to be run on the backends. Raises: QiskitError: when frequency settings are not supplied. Examples: .. code-block:: python from qiskit import pulse from qiskit.assembler import assemble_schedules from qiskit.assembler.run_config import RunConfig # Construct a Qobj header for the output Qobj header = {"backend_name": "FakeOpenPulse2Q", "backend_version": "0.0.0"} # Build a configuration object for the output Qobj config = RunConfig(shots=1024, memory=False, meas_level=1, meas_return='avg', memory_slot_size=100, parametric_pulses=[], init_qubits=True, qubit_lo_freq=[4900000000.0, 5000000000.0], meas_lo_freq=[6500000000.0, 6600000000.0], schedule_los=[]) # Build a Pulse schedule to assemble into a Qobj schedule = pulse.Schedule() schedule += pulse.Play(pulse.Waveform([0.1] * 16, name="test0"), pulse.DriveChannel(0), name="test1") schedule += pulse.Play(pulse.Waveform([0.1] * 16, name="test1"), pulse.DriveChannel(0), name="test2") schedule += pulse.Play(pulse.Waveform([0.5] * 16, name="test0"), pulse.DriveChannel(0), name="test1") # Assemble a Qobj from the schedule. pulseQobj = assemble_schedules(schedules=[schedule], qobj_id="custom-id", qobj_header=header, run_config=config) """ if not hasattr(run_config, "qubit_lo_freq"): raise QiskitError("qubit_lo_freq must be supplied.") if not hasattr(run_config, "meas_lo_freq"): raise QiskitError("meas_lo_freq must be supplied.") lo_converter = converters.LoConfigConverter( qobj.PulseQobjExperimentConfig, **run_config.to_dict() ) experiments, experiment_config = _assemble_experiments(schedules, lo_converter, run_config) qobj_config = _assemble_config(lo_converter, experiment_config, run_config) return qobj.PulseQobj( experiments=experiments, qobj_id=qobj_id, header=qobj_header, config=qobj_config ) def _assemble_experiments( schedules: List[Union[schedule.ScheduleComponent, Tuple[int, schedule.ScheduleComponent]]], lo_converter: converters.LoConfigConverter, run_config: RunConfig, ) -> Tuple[List[qobj.PulseQobjExperiment], Dict[str, Any]]: """Assembles a list of schedules into PulseQobjExperiments, and returns related metadata that will be assembled into the Qobj configuration. Args: schedules: Schedules to assemble. lo_converter: The configured frequency converter and validator. run_config: Configuration of the runtime environment. Returns: The list of assembled experiments, and the dictionary of related experiment config. Raises: QiskitError: when frequency settings are not compatible with the experiments. """ freq_configs = [lo_converter(lo_dict) for lo_dict in getattr(run_config, "schedule_los", [])] if len(schedules) > 1 and len(freq_configs) not in [0, 1, len(schedules)]: raise QiskitError( "Invalid 'schedule_los' setting specified. If specified, it should be " "either have a single entry to apply the same LOs for each schedule or " "have length equal to the number of schedules." ) instruction_converter = getattr( run_config, "instruction_converter", converters.InstructionToQobjConverter ) instruction_converter = instruction_converter(qobj.PulseQobjInstruction, **run_config.to_dict()) formatted_schedules = [transforms.target_qobj_transform(sched) for sched in schedules] compressed_schedules = transforms.compress_pulses(formatted_schedules) user_pulselib = {} experiments = [] for idx, sched in enumerate(compressed_schedules): qobj_instructions, max_memory_slot = _assemble_instructions( sched, instruction_converter, run_config, user_pulselib ) metadata = sched.metadata if metadata is None: metadata = {} # TODO: add other experimental header items (see circuit assembler) qobj_experiment_header = qobj.QobjExperimentHeader( memory_slots=max_memory_slot + 1, # Memory slots are 0 indexed name=sched.name or "Experiment-%d" % idx, metadata=metadata, ) experiment = qobj.PulseQobjExperiment( header=qobj_experiment_header, instructions=qobj_instructions ) if freq_configs: # This handles the cases where one frequency setting applies to all experiments and # where each experiment has a different frequency freq_idx = idx if len(freq_configs) != 1 else 0 experiment.config = freq_configs[freq_idx] experiments.append(experiment) # Frequency sweep if freq_configs and len(experiments) == 1: experiment = experiments[0] experiments = [] for freq_config in freq_configs: experiments.append( qobj.PulseQobjExperiment( header=experiment.header, instructions=experiment.instructions, config=freq_config, ) ) # Top level Qobj configuration experiment_config = { "pulse_library": [ qobj.PulseLibraryItem(name=name, samples=samples) for name, samples in user_pulselib.items() ], "memory_slots": max(exp.header.memory_slots for exp in experiments), } return experiments, experiment_config def _assemble_instructions( sched: Union[pulse.Schedule, pulse.ScheduleBlock], instruction_converter: converters.InstructionToQobjConverter, run_config: RunConfig, user_pulselib: Dict[str, List[complex]], ) -> Tuple[List[qobj.PulseQobjInstruction], int]: """Assembles the instructions in a schedule into a list of PulseQobjInstructions and returns related metadata that will be assembled into the Qobj configuration. Lookup table for pulses defined in all experiments are registered in ``user_pulselib``. This object should be mutable python dictionary so that items are properly updated after each instruction assemble. The dictionary is not returned to avoid redundancy. Args: sched: Schedule to assemble. instruction_converter: A converter instance which can convert PulseInstructions to PulseQobjInstructions. run_config: Configuration of the runtime environment. user_pulselib: User pulse library from previous schedule. Returns: A list of converted instructions, the user pulse library dictionary (from pulse name to pulse samples), and the maximum number of readout memory slots used by this Schedule. """ sched = transforms.target_qobj_transform(sched) max_memory_slot = 0 qobj_instructions = [] acquire_instruction_map = defaultdict(list) for time, instruction in sched.instructions: if isinstance(instruction, instructions.Play): if isinstance(instruction.pulse, (library.ParametricPulse, library.SymbolicPulse)): is_backend_supported = True try: pulse_shape = ParametricPulseShapes.from_instance(instruction.pulse).name if pulse_shape not in run_config.parametric_pulses: is_backend_supported = False except ValueError: # Custom pulse class, or bare SymbolicPulse object. is_backend_supported = False if not is_backend_supported: instruction = instructions.Play( instruction.pulse.get_waveform(), instruction.channel, name=instruction.name ) if isinstance(instruction.pulse, library.Waveform): name = hashlib.sha256(instruction.pulse.samples).hexdigest() instruction = instructions.Play( library.Waveform(name=name, samples=instruction.pulse.samples), channel=instruction.channel, name=name, ) user_pulselib[name] = instruction.pulse.samples # ignore explicit delay instrs on acq channels as they are invalid on IBMQ backends; # timing of other instrs will still be shifted appropriately if isinstance(instruction, instructions.Delay) and isinstance( instruction.channel, channels.AcquireChannel ): continue if isinstance(instruction, instructions.Acquire): if instruction.mem_slot: max_memory_slot = max(max_memory_slot, instruction.mem_slot.index) # Acquires have a single AcquireChannel per inst, but we have to bundle them # together into the Qobj as one instruction with many channels acquire_instruction_map[(time, instruction.duration)].append(instruction) continue qobj_instructions.append(instruction_converter(time, instruction)) if acquire_instruction_map: if hasattr(run_config, "meas_map"): _validate_meas_map(acquire_instruction_map, run_config.meas_map) for (time, _), instruction_bundle in acquire_instruction_map.items(): qobj_instructions.append( instruction_converter(time, instruction_bundle), ) return qobj_instructions, max_memory_slot def _validate_meas_map( instruction_map: Dict[Tuple[int, instructions.Acquire], List[instructions.Acquire]], meas_map: List[List[int]], ) -> None: """Validate all qubits tied in ``meas_map`` are to be acquired. Args: instruction_map: A dictionary grouping Acquire instructions according to their start time and duration. meas_map: List of groups of qubits that must be acquired together. Raises: QiskitError: If the instructions do not satisfy the measurement map. """ sorted_inst_map = sorted(instruction_map.items(), key=lambda item: item[0]) meas_map_sets = [set(m) for m in meas_map] # error if there is time overlap between qubits in the same meas_map for idx, inst in enumerate(sorted_inst_map[:-1]): inst_end_time = inst[0][0] + inst[0][1] next_inst = sorted_inst_map[idx + 1] next_inst_time = next_inst[0][0] if next_inst_time < inst_end_time: inst_qubits = {inst.channel.index for inst in inst[1]} next_inst_qubits = {inst.channel.index for inst in next_inst[1]} for meas_set in meas_map_sets: common_instr_qubits = inst_qubits.intersection(meas_set) common_next = next_inst_qubits.intersection(meas_set) if common_instr_qubits and common_next: raise QiskitError( "Qubits {} and {} are in the same measurement grouping: {}. " "They must either be acquired at the same time, or disjointly" ". Instead, they were acquired at times: {}-{} and " "{}-{}".format( common_instr_qubits, common_next, meas_map, inst[0][0], inst_end_time, next_inst_time, next_inst_time + next_inst[0][1], ) ) def _assemble_config( lo_converter: converters.LoConfigConverter, experiment_config: Dict[str, Any], run_config: RunConfig, ) -> qobj.PulseQobjConfig: """Assembles the QobjConfiguration from experimental config and runtime config. Args: lo_converter: The configured frequency converter and validator. experiment_config: Schedules to assemble. run_config: Configuration of the runtime environment. Returns: The assembled PulseQobjConfig. """ qobj_config = run_config.to_dict() qobj_config.update(experiment_config) # Run config not needed in qobj config qobj_config.pop("meas_map", None) qobj_config.pop("qubit_lo_range", None) qobj_config.pop("meas_lo_range", None) # convert enums to serialized values meas_return = qobj_config.get("meas_return", "avg") if isinstance(meas_return, qobj_utils.MeasReturnType): qobj_config["meas_return"] = meas_return.value meas_level = qobj_config.get("meas_level", 2) if isinstance(meas_level, qobj_utils.MeasLevel): qobj_config["meas_level"] = meas_level.value # convert LO frequencies to GHz qobj_config["qubit_lo_freq"] = [freq / 1e9 for freq in qobj_config["qubit_lo_freq"]] qobj_config["meas_lo_freq"] = [freq / 1e9 for freq in qobj_config["meas_lo_freq"]] # override defaults if single entry for ``schedule_los`` schedule_los = qobj_config.pop("schedule_los", []) if len(schedule_los) == 1: lo_dict = schedule_los[0] q_los = lo_converter.get_qubit_los(lo_dict) # Hz -> GHz if q_los: qobj_config["qubit_lo_freq"] = [freq / 1e9 for freq in q_los] m_los = lo_converter.get_meas_los(lo_dict) if m_los: qobj_config["meas_lo_freq"] = [freq / 1e9 for freq in m_los] return qobj.PulseQobjConfig(**qobj_config)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Disassemble function for a qobj into a list of circuits and its config""" from typing import Any, Dict, List, NewType, Tuple, Union import collections import math from qiskit import pulse from qiskit.circuit.classicalregister import ClassicalRegister from qiskit.circuit.instruction import Instruction from qiskit.circuit.quantumcircuit import QuantumCircuit from qiskit.circuit.quantumregister import QuantumRegister from qiskit.qobj import PulseQobjInstruction from qiskit.qobj.converters import QobjToInstructionConverter # A ``CircuitModule`` is a representation of a circuit execution on the backend. # It is currently a list of quantum circuits to execute, a run Qobj dictionary # and a header dictionary. CircuitModule = NewType( "CircuitModule", Tuple[List[QuantumCircuit], Dict[str, Any], Dict[str, Any]] ) # A ``PulseModule`` is a representation of a pulse execution on the backend. # It is currently a list of pulse schedules to execute, a run Qobj dictionary # and a header dictionary. PulseModule = NewType("PulseModule", Tuple[List[pulse.Schedule], Dict[str, Any], Dict[str, Any]]) def disassemble(qobj) -> Union[CircuitModule, PulseModule]: """Disassemble a qobj and return the circuits or pulse schedules, run_config, and user header. .. note:: ``disassemble(assemble(qc))`` is not guaranteed to produce an exactly equal circuit to the input, due to limitations in the :obj:`.QasmQobj` format that need to be maintained for backend system compatibility. This is most likely to be the case when using newer features of :obj:`.QuantumCircuit`. In most cases, the output should be equivalent, if not quite equal. Args: qobj (Qobj): The input qobj object to disassemble Returns: Union[CircuitModule, PulseModule]: The disassembled program which consists of: * programs: A list of quantum circuits or pulse schedules * run_config: The dict of the run config * user_qobj_header: The dict of any user headers in the qobj Examples: .. code-block:: python from qiskit.circuit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.compiler.assembler import assemble from qiskit.assembler.disassemble import disassemble # Create a circuit to assemble into a qobj q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.h(q[0]) qc.cx(q[0], q[1]) qc.measure(q, c) # Assemble the circuit into a Qobj qobj = assemble(qc, shots=2000, memory=True) # Disassemble the qobj back into a circuit circuits, run_config_out, headers = disassemble(qobj) """ if qobj.type == "PULSE": return _disassemble_pulse_schedule(qobj) else: return _disassemble_circuit(qobj) def _disassemble_circuit(qobj) -> CircuitModule: run_config = qobj.config.to_dict() # convert lo freq back to Hz qubit_lo_freq = run_config.get("qubit_lo_freq", []) if qubit_lo_freq: run_config["qubit_lo_freq"] = [freq * 1e9 for freq in qubit_lo_freq] meas_lo_freq = run_config.get("meas_lo_freq", []) if meas_lo_freq: run_config["meas_lo_freq"] = [freq * 1e9 for freq in meas_lo_freq] user_qobj_header = qobj.header.to_dict() return CircuitModule((_experiments_to_circuits(qobj), run_config, user_qobj_header)) def _qobj_to_circuit_cals(qobj, pulse_lib): """Return circuit calibrations dictionary from qobj/exp config calibrations.""" qobj_cals = qobj.config.calibrations.to_dict()["gates"] converter = QobjToInstructionConverter(pulse_lib) qc_cals = {} for gate in qobj_cals: config = (tuple(gate["qubits"]), tuple(gate["params"])) cal = { config: pulse.Schedule( name="{} {} {}".format(gate["name"], str(gate["params"]), str(gate["qubits"])) ) } for instruction in gate["instructions"]: qobj_instruction = PulseQobjInstruction.from_dict(instruction) schedule = converter(qobj_instruction) cal[config] = cal[config].insert(schedule.ch_start_time(), schedule) if gate["name"] in qc_cals: qc_cals[gate["name"]].update(cal) else: qc_cals[gate["name"]] = cal return qc_cals def _experiments_to_circuits(qobj): """Return a list of QuantumCircuit object(s) from a qobj. Args: qobj (Qobj): The Qobj object to convert to QuantumCircuits Returns: list: A list of QuantumCircuit objects from the qobj """ if not qobj.experiments: return None circuits = [] for exp in qobj.experiments: quantum_registers = [QuantumRegister(i[1], name=i[0]) for i in exp.header.qreg_sizes] classical_registers = [ClassicalRegister(i[1], name=i[0]) for i in exp.header.creg_sizes] circuit = QuantumCircuit(*quantum_registers, *classical_registers, name=exp.header.name) qreg_dict = collections.OrderedDict() creg_dict = collections.OrderedDict() for reg in quantum_registers: qreg_dict[reg.name] = reg for reg in classical_registers: creg_dict[reg.name] = reg conditional = {} for i in exp.instructions: name = i.name qubits = [] params = getattr(i, "params", []) try: for qubit in i.qubits: qubit_label = exp.header.qubit_labels[qubit] qubits.append(qreg_dict[qubit_label[0]][qubit_label[1]]) except Exception: # pylint: disable=broad-except pass clbits = [] try: for clbit in i.memory: clbit_label = exp.header.clbit_labels[clbit] clbits.append(creg_dict[clbit_label[0]][clbit_label[1]]) except Exception: # pylint: disable=broad-except pass if hasattr(circuit, name): instr_method = getattr(circuit, name) if i.name in ["snapshot"]: _inst = instr_method( i.label, snapshot_type=i.snapshot_type, qubits=qubits, params=params ) elif i.name == "initialize": _inst = instr_method(params, qubits) elif i.name == "isometry": _inst = instr_method(*params, qubits, clbits) elif i.name in ["mcx", "mcu1", "mcp"]: _inst = instr_method(*params, qubits[:-1], qubits[-1], *clbits) else: _inst = instr_method(*params, *qubits, *clbits) elif name == "bfunc": conditional["value"] = int(i.val, 16) full_bit_size = sum(creg_dict[x].size for x in creg_dict) mask_map = {} raw_map = {} raw = [] for creg in creg_dict: size = creg_dict[creg].size reg_raw = [1] * size if not raw: raw = reg_raw else: for pos, val in enumerate(raw): if val == 1: raw[pos] = 0 raw = reg_raw + raw mask = [0] * (full_bit_size - len(raw)) + raw raw_map[creg] = mask mask_map[int("".join(str(x) for x in mask), 2)] = creg if bin(int(i.mask, 16)).count("1") == 1: # The condition is on a single bit. This might be a single-bit condition, or it # might be a register of length one. The case that it's a single-bit condition # in a register of length one is ambiguous, and we choose to return a condition # on the register. This may not match the input circuit exactly, but is at # least equivalent. cbit = int(math.log2(int(i.mask, 16))) for reg in creg_dict.values(): size = reg.size if cbit >= size: cbit -= size else: conditional["register"] = reg if reg.size == 1 else reg[cbit] break mask_str = bin(int(i.mask, 16))[2:].zfill(full_bit_size) mask = [int(item) for item in list(mask_str)] else: creg = mask_map[int(i.mask, 16)] conditional["register"] = creg_dict[creg] mask = raw_map[creg] val = int(i.val, 16) for j in reversed(mask): if j == 0: val = val >> 1 else: conditional["value"] = val break else: _inst = temp_opaque_instruction = Instruction( name=name, num_qubits=len(qubits), num_clbits=len(clbits), params=params ) circuit.append(temp_opaque_instruction, qubits, clbits) if conditional and name != "bfunc": _inst.c_if(conditional["register"], conditional["value"]) conditional = {} pulse_lib = qobj.config.pulse_library if hasattr(qobj.config, "pulse_library") else [] # The dict update method did not work here; could investigate in the future if hasattr(qobj.config, "calibrations"): circuit.calibrations = dict( **circuit.calibrations, **_qobj_to_circuit_cals(qobj, pulse_lib) ) if hasattr(exp.config, "calibrations"): circuit.calibrations = dict( **circuit.calibrations, **_qobj_to_circuit_cals(exp, pulse_lib) ) circuits.append(circuit) return circuits def _disassemble_pulse_schedule(qobj) -> PulseModule: run_config = qobj.config.to_dict() run_config.pop("pulse_library") qubit_lo_freq = run_config.get("qubit_lo_freq") if qubit_lo_freq: run_config["qubit_lo_freq"] = [freq * 1e9 for freq in qubit_lo_freq] meas_lo_freq = run_config.get("meas_lo_freq") if meas_lo_freq: run_config["meas_lo_freq"] = [freq * 1e9 for freq in meas_lo_freq] user_qobj_header = qobj.header.to_dict() # extract schedule lo settings schedule_los = [] for program in qobj.experiments: program_los = {} if hasattr(program, "config"): if hasattr(program.config, "qubit_lo_freq"): for i, lo in enumerate(program.config.qubit_lo_freq): program_los[pulse.DriveChannel(i)] = lo * 1e9 if hasattr(program.config, "meas_lo_freq"): for i, lo in enumerate(program.config.meas_lo_freq): program_los[pulse.MeasureChannel(i)] = lo * 1e9 schedule_los.append(program_los) if any(schedule_los): run_config["schedule_los"] = schedule_los return PulseModule((_experiments_to_schedules(qobj), run_config, user_qobj_header)) def _experiments_to_schedules(qobj) -> List[pulse.Schedule]: """Return a list of :class:`qiskit.pulse.Schedule` object(s) from a qobj. Args: qobj (Qobj): The Qobj object to convert to pulse schedules. Returns: A list of :class:`qiskit.pulse.Schedule` objects from the qobj Raises: pulse.PulseError: If a parameterized instruction is supplied. """ converter = QobjToInstructionConverter(qobj.config.pulse_library) schedules = [] for program in qobj.experiments: insts = [] for inst in program.instructions: insts.append(converter(inst)) schedule = pulse.Schedule(*insts) schedules.append(schedule) return schedules
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Controlled unitary gate.""" from __future__ import annotations import copy from typing import Optional, Union from qiskit.circuit.exceptions import CircuitError # pylint: disable=cyclic-import from .quantumcircuit import QuantumCircuit from .gate import Gate from .quantumregister import QuantumRegister from ._utils import _ctrl_state_to_int class ControlledGate(Gate): """Controlled unitary gate.""" def __init__( self, name: str, num_qubits: int, params: list, label: Optional[str] = None, num_ctrl_qubits: Optional[int] = 1, definition: Optional["QuantumCircuit"] = None, ctrl_state: Optional[Union[int, str]] = None, base_gate: Optional[Gate] = None, ): """Create a new ControlledGate. In the new gate the first ``num_ctrl_qubits`` of the gate are the controls. Args: name: The name of the gate. num_qubits: The number of qubits the gate acts on. params: A list of parameters for the gate. label: An optional label for the gate. num_ctrl_qubits: Number of control qubits. definition: A list of gate rules for implementing this gate. The elements of the list are tuples of (:meth:`~qiskit.circuit.Gate`, [qubit_list], [clbit_list]). ctrl_state: The control state in decimal or as a bitstring (e.g. '111'). If specified as a bitstring the length must equal num_ctrl_qubits, MSB on left. If None, use 2**num_ctrl_qubits-1. base_gate: Gate object to be controlled. Raises: CircuitError: If ``num_ctrl_qubits`` >= ``num_qubits``. CircuitError: ctrl_state < 0 or ctrl_state > 2**num_ctrl_qubits. Examples: Create a controlled standard gate and apply it to a circuit. .. plot:: :include-source: from qiskit import QuantumCircuit, QuantumRegister from qiskit.circuit.library.standard_gates import HGate qr = QuantumRegister(3) qc = QuantumCircuit(qr) c3h_gate = HGate().control(2) qc.append(c3h_gate, qr) qc.draw('mpl') Create a controlled custom gate and apply it to a circuit. .. plot:: :include-source: from qiskit import QuantumCircuit, QuantumRegister from qiskit.circuit.library.standard_gates import HGate qc1 = QuantumCircuit(2) qc1.x(0) qc1.h(1) custom = qc1.to_gate().control(2) qc2 = QuantumCircuit(4) qc2.append(custom, [0, 3, 1, 2]) qc2.draw('mpl') """ self.base_gate = None if base_gate is None else base_gate.copy() super().__init__(name, num_qubits, params, label=label) self._num_ctrl_qubits = 1 self.num_ctrl_qubits = num_ctrl_qubits self.definition = copy.deepcopy(definition) self._ctrl_state = None self.ctrl_state = ctrl_state self._name = name @property def definition(self) -> QuantumCircuit: """Return definition in terms of other basic gates. If the gate has open controls, as determined from `self.ctrl_state`, the returned definition is conjugated with X without changing the internal `_definition`. """ if self._open_ctrl: closed_gate = self.copy() closed_gate.ctrl_state = None bit_ctrl_state = bin(self.ctrl_state)[2:].zfill(self.num_ctrl_qubits) qreg = QuantumRegister(self.num_qubits, "q") qc_open_ctrl = QuantumCircuit(qreg) for qind, val in enumerate(bit_ctrl_state[::-1]): if val == "0": qc_open_ctrl.x(qind) qc_open_ctrl.append(closed_gate, qargs=qreg[:]) for qind, val in enumerate(bit_ctrl_state[::-1]): if val == "0": qc_open_ctrl.x(qind) return qc_open_ctrl else: return super().definition @definition.setter def definition(self, excited_def: "QuantumCircuit"): """Set controlled gate definition with closed controls. Args: excited_def: The circuit with all closed controls. """ self._definition = excited_def @property def name(self) -> str: """Get name of gate. If the gate has open controls the gate name will become: <original_name_o<ctrl_state> where <original_name> is the gate name for the default case of closed control qubits and <ctrl_state> is the integer value of the control state for the gate. """ if self._open_ctrl: return f"{self._name}_o{self.ctrl_state}" else: return self._name @name.setter def name(self, name_str): """Set the name of the gate. Note the reported name may differ from the set name if the gate has open controls. """ self._name = name_str @property def num_ctrl_qubits(self): """Get number of control qubits. Returns: int: The number of control qubits for the gate. """ return self._num_ctrl_qubits @num_ctrl_qubits.setter def num_ctrl_qubits(self, num_ctrl_qubits): """Set the number of control qubits. Args: num_ctrl_qubits (int): The number of control qubits. Raises: CircuitError: ``num_ctrl_qubits`` is not an integer in ``[1, num_qubits]``. """ if num_ctrl_qubits != int(num_ctrl_qubits): raise CircuitError("The number of control qubits must be an integer.") num_ctrl_qubits = int(num_ctrl_qubits) # This is a range rather than an equality limit because some controlled gates represent a # controlled version of the base gate whose definition also uses auxiliary qubits. upper_limit = self.num_qubits - getattr(self.base_gate, "num_qubits", 0) if num_ctrl_qubits < 1 or num_ctrl_qubits > upper_limit: limit = "num_qubits" if self.base_gate is None else "num_qubits - base_gate.num_qubits" raise CircuitError(f"The number of control qubits must be in `[1, {limit}]`.") self._num_ctrl_qubits = num_ctrl_qubits @property def ctrl_state(self) -> int: """Return the control state of the gate as a decimal integer.""" return self._ctrl_state @ctrl_state.setter def ctrl_state(self, ctrl_state: Union[int, str, None]): """Set the control state of this gate. Args: ctrl_state: The control state of the gate. Raises: CircuitError: ctrl_state is invalid. """ self._ctrl_state = _ctrl_state_to_int(ctrl_state, self.num_ctrl_qubits) @property def params(self): """Get parameters from base_gate. Returns: list: List of gate parameters. Raises: CircuitError: Controlled gate does not define a base gate """ if self.base_gate: return self.base_gate.params else: raise CircuitError("Controlled gate does not define base gate for extracting params") @params.setter def params(self, parameters): """Set base gate parameters. Args: parameters (list): The list of parameters to set. Raises: CircuitError: If controlled gate does not define a base gate. """ if self.base_gate: self.base_gate.params = parameters else: raise CircuitError("Controlled gate does not define base gate for extracting params") def __deepcopy__(self, _memo=None): cpy = copy.copy(self) cpy.base_gate = self.base_gate.copy() if self._definition: cpy._definition = copy.deepcopy(self._definition, _memo) return cpy @property def _open_ctrl(self) -> bool: """Return whether gate has any open controls""" return self.ctrl_state < 2**self.num_ctrl_qubits - 1 def __eq__(self, other) -> bool: return ( isinstance(other, ControlledGate) and self.num_ctrl_qubits == other.num_ctrl_qubits and self.ctrl_state == other.ctrl_state and self.base_gate == other.base_gate and self.num_qubits == other.num_qubits and self.num_clbits == other.num_clbits and self.definition == other.definition ) def inverse(self) -> "ControlledGate": """Invert this gate by calling inverse on the base gate.""" return self.base_gate.inverse().control(self.num_ctrl_qubits, ctrl_state=self.ctrl_state)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Instruction collection. """ from __future__ import annotations from typing import Callable from qiskit.circuit.exceptions import CircuitError from .classicalregister import Clbit, ClassicalRegister from .operation import Operation from .quantumcircuitdata import CircuitInstruction class InstructionSet: """Instruction collection, and their contexts.""" __slots__ = ("_instructions", "_requester") def __init__( # pylint: disable=bad-docstring-quotes self, *, resource_requester: Callable[..., ClassicalRegister | Clbit] | None = None, ): """New collection of instructions. The context (``qargs`` and ``cargs`` that each instruction is attached to) is also stored separately for each instruction. Args: resource_requester: A callable that takes in the classical resource used in the condition, verifies that it is present in the attached circuit, resolves any indices into concrete :obj:`.Clbit` instances, and returns the concrete resource. If this is not given, specifying a condition with an index is forbidden, and all concrete :obj:`.Clbit` and :obj:`.ClassicalRegister` resources will be assumed to be valid. .. note:: The callback ``resource_requester`` is called once for each call to :meth:`.c_if`, and assumes that a call implies that the resource will now be used. It may throw an error if the resource is not valid for usage. """ self._instructions: list[CircuitInstruction] = [] self._requester = resource_requester def __len__(self): """Return number of instructions in set""" return len(self._instructions) def __getitem__(self, i): """Return instruction at index""" return self._instructions[i] def add(self, instruction, qargs=None, cargs=None): """Add an instruction and its context (where it is attached).""" if not isinstance(instruction, CircuitInstruction): if not isinstance(instruction, Operation): raise CircuitError("attempt to add non-Operation to InstructionSet") if qargs is None or cargs is None: raise CircuitError("missing qargs or cargs in old-style InstructionSet.add") instruction = CircuitInstruction(instruction, tuple(qargs), tuple(cargs)) self._instructions.append(instruction) def inverse(self): """Invert all instructions.""" for i, instruction in enumerate(self._instructions): self._instructions[i] = instruction.replace(operation=instruction.operation.inverse()) return self def c_if(self, classical: Clbit | ClassicalRegister | int, val: int) -> "InstructionSet": """Set a classical equality condition on all the instructions in this set between the :obj:`.ClassicalRegister` or :obj:`.Clbit` ``classical`` and value ``val``. .. note:: This is a setter method, not an additive one. Calling this multiple times will silently override any previously set condition on any of the contained instructions; it does not stack. Args: classical: the classical resource the equality condition should be on. If this is given as an integer, it will be resolved into a :obj:`.Clbit` using the same conventions as the circuit these instructions are attached to. val: the value the classical resource should be equal to. Returns: This same instance of :obj:`.InstructionSet`, but now mutated to have the given equality condition. Raises: CircuitError: if the passed classical resource is invalid, or otherwise not resolvable to a concrete resource that these instructions are permitted to access. Example: .. plot:: :include-source: from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) qc.h(range(2)) qc.measure(range(2), range(2)) # apply x gate if the classical register has the value 2 (10 in binary) qc.x(0).c_if(cr, 2) # apply y gate if bit 0 is set to 1 qc.y(1).c_if(0, 1) qc.draw('mpl') """ if self._requester is None and not isinstance(classical, (Clbit, ClassicalRegister)): raise CircuitError( "Cannot pass an index as a condition variable without specifying a requester" " when creating this InstructionSet." ) if self._requester is not None: classical = self._requester(classical) for instruction in self._instructions: instruction.operation.c_if(classical, val) return self # Legacy support for properties. Added in Terra 0.21 to support the internal switch in # `QuantumCircuit.data` from the 3-tuple to `CircuitInstruction`. @property def instructions(self): """Legacy getter for the instruction components of an instruction set. This does not support mutation.""" return [instruction.operation for instruction in self._instructions] @property def qargs(self): """Legacy getter for the qargs components of an instruction set. This does not support mutation.""" return [list(instruction.qubits) for instruction in self._instructions] @property def cargs(self): """Legacy getter for the cargs components of an instruction set. This does not support mutation.""" return [list(instruction.clbits) for instruction in self._instructions]
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Quantum Operation Mixin.""" from abc import ABC, abstractmethod class Operation(ABC): """Quantum Operation Interface Class. For objects that can be added to a :class:`~qiskit.circuit.QuantumCircuit`. These objects include :class:`~qiskit.circuit.Gate`, :class:`~qiskit.circuit.Reset`, :class:`~qiskit.circuit.Barrier`, :class:`~qiskit.circuit.Measure`, and operators such as :class:`~qiskit.quantum_info.Clifford`. The main purpose is to add an :class:`~qiskit.circuit.Operation` to a :class:`~qiskit.circuit.QuantumCircuit` without synthesizing it before the transpilation. Example: Add a Clifford and a Toffoli gate to a QuantumCircuit. .. plot:: :include-source: from qiskit import QuantumCircuit from qiskit.quantum_info import Clifford, random_clifford qc = QuantumCircuit(3) cliff = random_clifford(2) qc.append(cliff, [0, 1]) qc.ccx(0, 1, 2) qc.draw('mpl') """ __slots__ = () @property @abstractmethod def name(self): """Unique string identifier for operation type.""" raise NotImplementedError @property @abstractmethod def num_qubits(self): """Number of qubits.""" raise NotImplementedError @property @abstractmethod def num_clbits(self): """Number of classical bits.""" raise NotImplementedError
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Alias for Qiskit QPY import.""" def __getattr__(name): import warnings from qiskit import qpy # Skip warning on special Python dunders, which Python occasionally queries on its own accord. if f"__{name[2:-2]}__" != name: warnings.warn( f"Module '{__name__}' is deprecated since Qiskit Terra 0.23," " and will be removed in a future release. Please import from 'qiskit.qpy' instead.", category=DeprecationWarning, stacklevel=2, ) return getattr(qpy, name)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=bad-docstring-quotes,invalid-name """Quantum circuit object.""" from __future__ import annotations import collections.abc import copy import itertools import multiprocessing as mp import string import re import warnings import typing from collections import OrderedDict, defaultdict, namedtuple from typing import ( Union, Optional, Tuple, Type, TypeVar, Sequence, Callable, Mapping, Iterable, Any, DefaultDict, Literal, overload, ) import numpy as np from qiskit.exceptions import QiskitError from qiskit.utils.multiprocessing import is_main_process from qiskit.circuit.instruction import Instruction from qiskit.circuit.gate import Gate from qiskit.circuit.parameter import Parameter from qiskit.circuit.exceptions import CircuitError from qiskit.utils import optionals as _optionals from . import _classical_resource_map from ._utils import sort_parameters from .classical import expr from .parameterexpression import ParameterExpression, ParameterValueType from .quantumregister import QuantumRegister, Qubit, AncillaRegister, AncillaQubit from .classicalregister import ClassicalRegister, Clbit from .parametertable import ParameterReferences, ParameterTable, ParameterView from .parametervector import ParameterVector from .instructionset import InstructionSet from .operation import Operation from .register import Register from .bit import Bit from .quantumcircuitdata import QuantumCircuitData, CircuitInstruction from .delay import Delay from .measure import Measure from .reset import Reset from .tools import pi_check if typing.TYPE_CHECKING: import qiskit # pylint: disable=cyclic-import from qiskit.transpiler.layout import TranspileLayout # pylint: disable=cyclic-import BitLocations = namedtuple("BitLocations", ("index", "registers")) # The following types are not marked private to avoid leaking this "private/public" abstraction out # into the documentation. They are not imported by circuit.__init__, nor are they meant to be. # Arbitrary type variables for marking up generics. S = TypeVar("S") T = TypeVar("T") # Types that can be coerced to a valid Qubit specifier in a circuit. QubitSpecifier = Union[ Qubit, QuantumRegister, int, slice, Sequence[Union[Qubit, int]], ] # Types that can be coerced to a valid Clbit specifier in a circuit. ClbitSpecifier = Union[ Clbit, ClassicalRegister, int, slice, Sequence[Union[Clbit, int]], ] # Generic type which is either :obj:`~Qubit` or :obj:`~Clbit`, used to specify types of functions # which operate on either type of bit, but not both at the same time. BitType = TypeVar("BitType", Qubit, Clbit) # Regex pattern to match valid OpenQASM identifiers VALID_QASM2_IDENTIFIER = re.compile("[a-z][a-zA-Z_0-9]*") QASM2_RESERVED = { "OPENQASM", "qreg", "creg", "include", "gate", "opaque", "U", "CX", "measure", "reset", "if", "barrier", } class QuantumCircuit: """Create a new circuit. A circuit is a list of instructions bound to some registers. Args: regs (list(:class:`~.Register`) or list(``int``) or list(list(:class:`~.Bit`))): The registers to be included in the circuit. * If a list of :class:`~.Register` objects, represents the :class:`.QuantumRegister` and/or :class:`.ClassicalRegister` objects to include in the circuit. For example: * ``QuantumCircuit(QuantumRegister(4))`` * ``QuantumCircuit(QuantumRegister(4), ClassicalRegister(3))`` * ``QuantumCircuit(QuantumRegister(4, 'qr0'), QuantumRegister(2, 'qr1'))`` * If a list of ``int``, the amount of qubits and/or classical bits to include in the circuit. It can either be a single int for just the number of quantum bits, or 2 ints for the number of quantum bits and classical bits, respectively. For example: * ``QuantumCircuit(4) # A QuantumCircuit with 4 qubits`` * ``QuantumCircuit(4, 3) # A QuantumCircuit with 4 qubits and 3 classical bits`` * If a list of python lists containing :class:`.Bit` objects, a collection of :class:`.Bit` s to be added to the circuit. name (str): the name of the quantum circuit. If not set, an automatically generated string will be assigned. global_phase (float or ParameterExpression): The global phase of the circuit in radians. metadata (dict): Arbitrary key value metadata to associate with the circuit. This gets stored as free-form data in a dict in the :attr:`~qiskit.circuit.QuantumCircuit.metadata` attribute. It will not be directly used in the circuit. Raises: CircuitError: if the circuit name, if given, is not valid. Examples: Construct a simple Bell state circuit. .. plot:: :include-source: from qiskit import QuantumCircuit qc = QuantumCircuit(2, 2) qc.h(0) qc.cx(0, 1) qc.measure([0, 1], [0, 1]) qc.draw('mpl') Construct a 5-qubit GHZ circuit. .. code-block:: from qiskit import QuantumCircuit qc = QuantumCircuit(5) qc.h(0) qc.cx(0, range(1, 5)) qc.measure_all() Construct a 4-qubit Bernstein-Vazirani circuit using registers. .. plot:: :include-source: from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit qr = QuantumRegister(3, 'q') anc = QuantumRegister(1, 'ancilla') cr = ClassicalRegister(3, 'c') qc = QuantumCircuit(qr, anc, cr) qc.x(anc[0]) qc.h(anc[0]) qc.h(qr[0:3]) qc.cx(qr[0:3], anc[0]) qc.h(qr[0:3]) qc.barrier(qr) qc.measure(qr, cr) qc.draw('mpl') """ instances = 0 prefix = "circuit" # Class variable OPENQASM header header = "OPENQASM 2.0;" extension_lib = 'include "qelib1.inc";' def __init__( self, *regs: Register | int | Sequence[Bit], name: str | None = None, global_phase: ParameterValueType = 0, metadata: dict | None = None, ): if any(not isinstance(reg, (list, QuantumRegister, ClassicalRegister)) for reg in regs): # check if inputs are integers, but also allow e.g. 2.0 try: valid_reg_size = all(reg == int(reg) for reg in regs) except (ValueError, TypeError): valid_reg_size = False if not valid_reg_size: raise CircuitError( "Circuit args must be Registers or integers. (%s '%s' was " "provided)" % ([type(reg).__name__ for reg in regs], regs) ) regs = tuple(int(reg) for reg in regs) # cast to int self._base_name = None if name is None: self._base_name = self.cls_prefix() self._name_update() elif not isinstance(name, str): raise CircuitError( "The circuit name should be a string (or None to auto-generate a name)." ) else: self._base_name = name self.name = name self._increment_instances() # Data contains a list of instructions and their contexts, # in the order they were applied. self._data: list[CircuitInstruction] = [] self._op_start_times = None # A stack to hold the instruction sets that are being built up during for-, if- and # while-block construction. These are stored as a stripped down sequence of instructions, # and sets of qubits and clbits, rather than a full QuantumCircuit instance because the # builder interfaces need to wait until they are completed before they can fill in things # like `break` and `continue`. This is because these instructions need to "operate" on the # full width of bits, but the builder interface won't know what bits are used until the end. self._control_flow_scopes: list[ "qiskit.circuit.controlflow.builder.ControlFlowBuilderBlock" ] = [] self.qregs: list[QuantumRegister] = [] self.cregs: list[ClassicalRegister] = [] self._qubits: list[Qubit] = [] self._clbits: list[Clbit] = [] # Dict mapping Qubit or Clbit instances to tuple comprised of 0) the # corresponding index in circuit.{qubits,clbits} and 1) a list of # Register-int pairs for each Register containing the Bit and its index # within that register. self._qubit_indices: dict[Qubit, BitLocations] = {} self._clbit_indices: dict[Clbit, BitLocations] = {} self._ancillas: list[AncillaQubit] = [] self._calibrations: DefaultDict[str, dict[tuple, Any]] = defaultdict(dict) self.add_register(*regs) # Parameter table tracks instructions with variable parameters. self._parameter_table = ParameterTable() # Cache to avoid re-sorting parameters self._parameters = None self._layout = None self._global_phase: ParameterValueType = 0 self.global_phase = global_phase self.duration = None self.unit = "dt" self.metadata = {} if metadata is None else metadata @staticmethod def from_instructions( instructions: Iterable[ CircuitInstruction | tuple[qiskit.circuit.Instruction] | tuple[qiskit.circuit.Instruction, Iterable[Qubit]] | tuple[qiskit.circuit.Instruction, Iterable[Qubit], Iterable[Clbit]] ], *, qubits: Iterable[Qubit] = (), clbits: Iterable[Clbit] = (), name: str | None = None, global_phase: ParameterValueType = 0, metadata: dict | None = None, ) -> "QuantumCircuit": """Construct a circuit from an iterable of CircuitInstructions. Args: instructions: The instructions to add to the circuit. qubits: Any qubits to add to the circuit. This argument can be used, for example, to enforce a particular ordering of qubits. clbits: Any classical bits to add to the circuit. This argument can be used, for example, to enforce a particular ordering of classical bits. name: The name of the circuit. global_phase: The global phase of the circuit in radians. metadata: Arbitrary key value metadata to associate with the circuit. Returns: The quantum circuit. """ circuit = QuantumCircuit(name=name, global_phase=global_phase, metadata=metadata) added_qubits = set() added_clbits = set() if qubits: qubits = list(qubits) circuit.add_bits(qubits) added_qubits.update(qubits) if clbits: clbits = list(clbits) circuit.add_bits(clbits) added_clbits.update(clbits) for instruction in instructions: if not isinstance(instruction, CircuitInstruction): instruction = CircuitInstruction(*instruction) qubits = [qubit for qubit in instruction.qubits if qubit not in added_qubits] clbits = [clbit for clbit in instruction.clbits if clbit not in added_clbits] circuit.add_bits(qubits) circuit.add_bits(clbits) added_qubits.update(qubits) added_clbits.update(clbits) circuit._append(instruction) return circuit @property def layout(self) -> Optional[TranspileLayout]: r"""Return any associated layout information about the circuit This attribute contains an optional :class:`~.TranspileLayout` object. This is typically set on the output from :func:`~.transpile` or :meth:`.PassManager.run` to retain information about the permutations caused on the input circuit by transpilation. There are two types of permutations caused by the :func:`~.transpile` function, an initial layout which permutes the qubits based on the selected physical qubits on the :class:`~.Target`, and a final layout which is an output permutation caused by :class:`~.SwapGate`\s inserted during routing. """ return self._layout @property def data(self) -> QuantumCircuitData: """Return the circuit data (instructions and context). Returns: QuantumCircuitData: a list-like object containing the :class:`.CircuitInstruction`\\ s for each instruction. """ return QuantumCircuitData(self) @data.setter def data(self, data_input: Iterable): """Sets the circuit data from a list of instructions and context. Args: data_input (Iterable): A sequence of instructions with their execution contexts. The elements must either be instances of :class:`.CircuitInstruction` (preferred), or a 3-tuple of ``(instruction, qargs, cargs)`` (legacy). In the legacy format, ``instruction`` must be an :class:`~.circuit.Instruction`, while ``qargs`` and ``cargs`` must be iterables of :class:`.Qubit` or :class:`.Clbit` specifiers (similar to the allowed forms in calls to :meth:`append`). """ # If data_input is QuantumCircuitData(self), clearing self._data # below will also empty data_input, so make a shallow copy first. data_input = list(data_input) self._data = [] self._parameter_table = ParameterTable() if not data_input: return if isinstance(data_input[0], CircuitInstruction): for instruction in data_input: self.append(instruction) else: for instruction, qargs, cargs in data_input: self.append(instruction, qargs, cargs) @property def op_start_times(self) -> list[int]: """Return a list of operation start times. This attribute is enabled once one of scheduling analysis passes runs on the quantum circuit. Returns: List of integers representing instruction start times. The index corresponds to the index of instruction in :attr:`QuantumCircuit.data`. Raises: AttributeError: When circuit is not scheduled. """ if self._op_start_times is None: raise AttributeError( "This circuit is not scheduled. " "To schedule it run the circuit through one of the transpiler scheduling passes." ) return self._op_start_times @property def calibrations(self) -> dict: """Return calibration dictionary. The custom pulse definition of a given gate is of the form ``{'gate_name': {(qubits, params): schedule}}`` """ return dict(self._calibrations) @calibrations.setter def calibrations(self, calibrations: dict): """Set the circuit calibration data from a dictionary of calibration definition. Args: calibrations (dict): A dictionary of input in the format ``{'gate_name': {(qubits, gate_params): schedule}}`` """ self._calibrations = defaultdict(dict, calibrations) def has_calibration_for(self, instruction: CircuitInstruction | tuple): """Return True if the circuit has a calibration defined for the instruction context. In this case, the operation does not need to be translated to the device basis. """ if isinstance(instruction, CircuitInstruction): operation = instruction.operation qubits = instruction.qubits else: operation, qubits, _ = instruction if not self.calibrations or operation.name not in self.calibrations: return False qubits = tuple(self.qubits.index(qubit) for qubit in qubits) params = [] for p in operation.params: if isinstance(p, ParameterExpression) and not p.parameters: params.append(float(p)) else: params.append(p) params = tuple(params) return (qubits, params) in self.calibrations[operation.name] @property def metadata(self) -> dict: """The user provided metadata associated with the circuit. The metadata for the circuit is a user provided ``dict`` of metadata for the circuit. It will not be used to influence the execution or operation of the circuit, but it is expected to be passed between all transforms of the circuit (ie transpilation) and that providers will associate any circuit metadata with the results it returns from execution of that circuit. """ return self._metadata @metadata.setter def metadata(self, metadata: dict | None): """Update the circuit metadata""" if metadata is None: metadata = {} warnings.warn( "Setting metadata to None was deprecated in Terra 0.24.0 and this ability will be " "removed in a future release. Instead, set metadata to an empty dictionary.", DeprecationWarning, stacklevel=2, ) elif not isinstance(metadata, dict): raise TypeError("Only a dictionary is accepted for circuit metadata") self._metadata = metadata def __str__(self) -> str: return str(self.draw(output="text")) def __eq__(self, other) -> bool: if not isinstance(other, QuantumCircuit): return False # TODO: remove the DAG from this function from qiskit.converters import circuit_to_dag return circuit_to_dag(self, copy_operations=False) == circuit_to_dag( other, copy_operations=False ) @classmethod def _increment_instances(cls): cls.instances += 1 @classmethod def cls_instances(cls) -> int: """Return the current number of instances of this class, useful for auto naming.""" return cls.instances @classmethod def cls_prefix(cls) -> str: """Return the prefix to use for auto naming.""" return cls.prefix def _name_update(self) -> None: """update name of instance using instance number""" if not is_main_process(): pid_name = f"-{mp.current_process().pid}" else: pid_name = "" self.name = f"{self._base_name}-{self.cls_instances()}{pid_name}" def has_register(self, register: Register) -> bool: """ Test if this circuit has the register r. Args: register (Register): a quantum or classical register. Returns: bool: True if the register is contained in this circuit. """ has_reg = False if isinstance(register, QuantumRegister) and register in self.qregs: has_reg = True elif isinstance(register, ClassicalRegister) and register in self.cregs: has_reg = True return has_reg def reverse_ops(self) -> "QuantumCircuit": """Reverse the circuit by reversing the order of instructions. This is done by recursively reversing all instructions. It does not invert (adjoint) any gate. Returns: QuantumCircuit: the reversed circuit. Examples: input: .. parsed-literal:: β”Œβ”€β”€β”€β” q_0: ─ H β”œβ”€β”€β”€β”€β”€β– β”€β”€β”€β”€β”€β”€ β””β”€β”€β”€β”˜β”Œβ”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β” q_1: ────── RX(1.57) β”œ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ output: .. parsed-literal:: β”Œβ”€β”€β”€β” q_0: ─────■─────── H β”œ β”Œβ”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”β””β”€β”€β”€β”˜ q_1: ─ RX(1.57) β”œβ”€β”€β”€β”€β”€ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ """ reverse_circ = QuantumCircuit( self.qubits, self.clbits, *self.qregs, *self.cregs, name=self.name + "_reverse" ) for instruction in reversed(self.data): reverse_circ._append(instruction.replace(operation=instruction.operation.reverse_ops())) reverse_circ.duration = self.duration reverse_circ.unit = self.unit return reverse_circ def reverse_bits(self) -> "QuantumCircuit": """Return a circuit with the opposite order of wires. The circuit is "vertically" flipped. If a circuit is defined over multiple registers, the resulting circuit will have the same registers but with their order flipped. This method is useful for converting a circuit written in little-endian convention to the big-endian equivalent, and vice versa. Returns: QuantumCircuit: the circuit with reversed bit order. Examples: input: .. parsed-literal:: β”Œβ”€β”€β”€β” a_0: ─ H β”œβ”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β””β”€β”€β”€β”˜β”Œβ”€β”΄β”€β” a_1: ────── X β”œβ”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β””β”€β”€β”€β”˜β”Œβ”€β”΄β”€β” a_2: ─────────── X β”œβ”€β”€β– β”€β”€β”€β”€β”€β”€β”€ β””β”€β”€β”€β”˜β”Œβ”€β”΄β”€β” b_0: ──────────────── X β”œβ”€β”€β– β”€β”€ β””β”€β”€β”€β”˜β”Œβ”€β”΄β”€β” b_1: ───────────────────── X β”œ β””β”€β”€β”€β”˜ output: .. parsed-literal:: β”Œβ”€β”€β”€β” b_0: ───────────────────── X β”œ β”Œβ”€β”€β”€β”β””β”€β”¬β”€β”˜ b_1: ──────────────── X β”œβ”€β”€β– β”€β”€ β”Œβ”€β”€β”€β”β””β”€β”¬β”€β”˜ a_0: ─────────── X β”œβ”€β”€β– β”€β”€β”€β”€β”€β”€β”€ β”Œβ”€β”€β”€β”β””β”€β”¬β”€β”˜ a_1: ────── X β”œβ”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”Œβ”€β”€β”€β”β””β”€β”¬β”€β”˜ a_2: ─ H β”œβ”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β””β”€β”€β”€β”˜ """ circ = QuantumCircuit( list(reversed(self.qubits)), list(reversed(self.clbits)), name=self.name, global_phase=self.global_phase, ) new_qubit_map = circ.qubits[::-1] new_clbit_map = circ.clbits[::-1] for reg in reversed(self.qregs): bits = [new_qubit_map[self.find_bit(qubit).index] for qubit in reversed(reg)] circ.add_register(QuantumRegister(bits=bits, name=reg.name)) for reg in reversed(self.cregs): bits = [new_clbit_map[self.find_bit(clbit).index] for clbit in reversed(reg)] circ.add_register(ClassicalRegister(bits=bits, name=reg.name)) for instruction in self.data: qubits = [new_qubit_map[self.find_bit(qubit).index] for qubit in instruction.qubits] clbits = [new_clbit_map[self.find_bit(clbit).index] for clbit in instruction.clbits] circ._append(instruction.replace(qubits=qubits, clbits=clbits)) return circ def inverse(self) -> "QuantumCircuit": """Invert (take adjoint of) this circuit. This is done by recursively inverting all gates. Returns: QuantumCircuit: the inverted circuit Raises: CircuitError: if the circuit cannot be inverted. Examples: input: .. parsed-literal:: β”Œβ”€β”€β”€β” q_0: ─ H β”œβ”€β”€β”€β”€β”€β– β”€β”€β”€β”€β”€β”€ β””β”€β”€β”€β”˜β”Œβ”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β” q_1: ────── RX(1.57) β”œ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ output: .. parsed-literal:: β”Œβ”€β”€β”€β” q_0: ──────■─────── H β”œ β”Œβ”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”β””β”€β”€β”€β”˜ q_1: ─ RX(-1.57) β”œβ”€β”€β”€β”€β”€ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ """ inverse_circ = QuantumCircuit( self.qubits, self.clbits, *self.qregs, *self.cregs, name=self.name + "_dg", global_phase=-self.global_phase, ) for instruction in reversed(self._data): inverse_circ._append(instruction.replace(operation=instruction.operation.inverse())) return inverse_circ def repeat(self, reps: int) -> "QuantumCircuit": """Repeat this circuit ``reps`` times. Args: reps (int): How often this circuit should be repeated. Returns: QuantumCircuit: A circuit containing ``reps`` repetitions of this circuit. """ repeated_circ = QuantumCircuit( self.qubits, self.clbits, *self.qregs, *self.cregs, name=self.name + f"**{reps}" ) # benefit of appending instructions: decomposing shows the subparts, i.e. the power # is actually `reps` times this circuit, and it is currently much faster than `compose`. if reps > 0: try: # try to append as gate if possible to not disallow to_gate inst: Instruction = self.to_gate() except QiskitError: inst = self.to_instruction() for _ in range(reps): repeated_circ._append(inst, self.qubits, self.clbits) return repeated_circ def power(self, power: float, matrix_power: bool = False) -> "QuantumCircuit": """Raise this circuit to the power of ``power``. If ``power`` is a positive integer and ``matrix_power`` is ``False``, this implementation defaults to calling ``repeat``. Otherwise, if the circuit is unitary, the matrix is computed to calculate the matrix power. Args: power (float): The power to raise this circuit to. matrix_power (bool): If True, the circuit is converted to a matrix and then the matrix power is computed. If False, and ``power`` is a positive integer, the implementation defaults to ``repeat``. Raises: CircuitError: If the circuit needs to be converted to a gate but it is not unitary. Returns: QuantumCircuit: A circuit implementing this circuit raised to the power of ``power``. """ if power >= 0 and isinstance(power, (int, np.integer)) and not matrix_power: return self.repeat(power) # attempt conversion to gate if self.num_parameters > 0: raise CircuitError( "Cannot raise a parameterized circuit to a non-positive power " "or matrix-power, please bind the free parameters: " "{}".format(self.parameters) ) try: gate = self.to_gate() except QiskitError as ex: raise CircuitError( "The circuit contains non-unitary operations and cannot be " "controlled. Note that no qiskit.circuit.Instruction objects may " "be in the circuit for this operation." ) from ex power_circuit = QuantumCircuit(self.qubits, self.clbits, *self.qregs, *self.cregs) power_circuit.append(gate.power(power), list(range(gate.num_qubits))) return power_circuit def control( self, num_ctrl_qubits: int = 1, label: str | None = None, ctrl_state: str | int | None = None, ) -> "QuantumCircuit": """Control this circuit on ``num_ctrl_qubits`` qubits. Args: num_ctrl_qubits (int): The number of control qubits. label (str): An optional label to give the controlled operation for visualization. ctrl_state (str or int): The control state in decimal or as a bitstring (e.g. '111'). If None, use ``2**num_ctrl_qubits - 1``. Returns: QuantumCircuit: The controlled version of this circuit. Raises: CircuitError: If the circuit contains a non-unitary operation and cannot be controlled. """ try: gate = self.to_gate() except QiskitError as ex: raise CircuitError( "The circuit contains non-unitary operations and cannot be " "controlled. Note that no qiskit.circuit.Instruction objects may " "be in the circuit for this operation." ) from ex controlled_gate = gate.control(num_ctrl_qubits, label, ctrl_state) control_qreg = QuantumRegister(num_ctrl_qubits) controlled_circ = QuantumCircuit( control_qreg, self.qubits, *self.qregs, name=f"c_{self.name}" ) controlled_circ.append(controlled_gate, controlled_circ.qubits) return controlled_circ def compose( self, other: Union["QuantumCircuit", Instruction], qubits: QubitSpecifier | Sequence[QubitSpecifier] | None = None, clbits: ClbitSpecifier | Sequence[ClbitSpecifier] | None = None, front: bool = False, inplace: bool = False, wrap: bool = False, ) -> Optional["QuantumCircuit"]: """Compose circuit with ``other`` circuit or instruction, optionally permuting wires. ``other`` can be narrower or of equal width to ``self``. Args: other (qiskit.circuit.Instruction or QuantumCircuit): (sub)circuit or instruction to compose onto self. If not a :obj:`.QuantumCircuit`, this can be anything that :obj:`.append` will accept. qubits (list[Qubit|int]): qubits of self to compose onto. clbits (list[Clbit|int]): clbits of self to compose onto. front (bool): If True, front composition will be performed. This is not possible within control-flow builder context managers. inplace (bool): If True, modify the object. Otherwise return composed circuit. wrap (bool): If True, wraps the other circuit into a gate (or instruction, depending on whether it contains only unitary instructions) before composing it onto self. Returns: QuantumCircuit: the composed circuit (returns None if inplace==True). Raises: CircuitError: if no correct wire mapping can be made between the two circuits, such as if ``other`` is wider than ``self``. CircuitError: if trying to emit a new circuit while ``self`` has a partially built control-flow context active, such as the context-manager forms of :meth:`if_test`, :meth:`for_loop` and :meth:`while_loop`. CircuitError: if trying to compose to the front of a circuit when a control-flow builder block is active; there is no clear meaning to this action. Examples: .. code-block:: python >>> lhs.compose(rhs, qubits=[3, 2], inplace=True) .. parsed-literal:: β”Œβ”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β” lqr_1_0: ──── H β”œβ”€β”€β”€ rqr_0: ──■─── Tdg β”œ lqr_1_0: ──── H β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”œβ”€β”€β”€β”€ β”Œβ”€β”΄β”€β”β””β”€β”€β”€β”€β”€β”˜ β”œβ”€β”€β”€β”€ lqr_1_1: ──── X β”œβ”€β”€β”€ rqr_1: ─ X β”œβ”€β”€β”€β”€β”€β”€β”€ lqr_1_1: ──── X β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”Œβ”€β”€β”΄β”€β”€β”€β”΄β”€β”€β” β””β”€β”€β”€β”˜ β”Œβ”€β”€β”΄β”€β”€β”€β”΄β”€β”€β”β”Œβ”€β”€β”€β” lqr_1_2: ─ U1(0.1) β”œ + = lqr_1_2: ─ U1(0.1) β”œβ”€ X β”œβ”€β”€β”€β”€β”€β”€β”€ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β””β”€β”¬β”€β”˜β”Œβ”€β”€β”€β”€β”€β” lqr_2_0: ─────■───── lqr_2_0: ─────■───────■─── Tdg β”œ β”Œβ”€β”΄β”€β” β”Œβ”€β”΄β”€β” β””β”€β”€β”€β”€β”€β”˜ lqr_2_1: ──── X β”œβ”€β”€β”€ lqr_2_1: ──── X β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β””β”€β”€β”€β”˜ β””β”€β”€β”€β”˜ lcr_0: 0 ═══════════ lcr_0: 0 ═══════════════════════ lcr_1: 0 ═══════════ lcr_1: 0 ═══════════════════════ """ # pylint: disable=cyclic-import from qiskit.circuit.controlflow.switch_case import SwitchCaseOp if inplace and front and self._control_flow_scopes: # If we're composing onto ourselves while in a stateful control-flow builder context, # there's no clear meaning to composition to the "front" of the circuit. raise CircuitError( "Cannot compose to the front of a circuit while a control-flow context is active." ) if not inplace and self._control_flow_scopes: # If we're inside a stateful control-flow builder scope, even if we successfully cloned # the partial builder scope (not simple), the scope wouldn't be controlled by an active # `with` statement, so the output circuit would be permanently broken. raise CircuitError( "Cannot emit a new composed circuit while a control-flow context is active." ) dest = self if inplace else self.copy() # As a special case, allow composing some clbits onto no clbits - normally the destination # has to be strictly larger. This allows composing final measurements onto unitary circuits. if isinstance(other, QuantumCircuit): if not self.clbits and other.clbits: dest.add_bits(other.clbits) for reg in other.cregs: dest.add_register(reg) if wrap and isinstance(other, QuantumCircuit): other = ( other.to_gate() if all(isinstance(ins.operation, Gate) for ins in other.data) else other.to_instruction() ) if not isinstance(other, QuantumCircuit): if qubits is None: qubits = self.qubits[: other.num_qubits] if clbits is None: clbits = self.clbits[: other.num_clbits] if front: # Need to keep a reference to the data for use after we've emptied it. old_data = list(dest.data) dest.clear() dest.append(other, qubits, clbits) for instruction in old_data: dest._append(instruction) else: dest.append(other, qargs=qubits, cargs=clbits) if inplace: return None return dest if other.num_qubits > dest.num_qubits or other.num_clbits > dest.num_clbits: raise CircuitError( "Trying to compose with another QuantumCircuit which has more 'in' edges." ) # number of qubits and clbits must match number in circuit or None edge_map: dict[Qubit | Clbit, Qubit | Clbit] = {} if qubits is None: edge_map.update(zip(other.qubits, dest.qubits)) else: mapped_qubits = dest.qbit_argument_conversion(qubits) if len(mapped_qubits) != len(other.qubits): raise CircuitError( f"Number of items in qubits parameter ({len(mapped_qubits)}) does not" f" match number of qubits in the circuit ({len(other.qubits)})." ) edge_map.update(zip(other.qubits, mapped_qubits)) if clbits is None: edge_map.update(zip(other.clbits, dest.clbits)) else: mapped_clbits = dest.cbit_argument_conversion(clbits) if len(mapped_clbits) != len(other.clbits): raise CircuitError( f"Number of items in clbits parameter ({len(mapped_clbits)}) does not" f" match number of clbits in the circuit ({len(other.clbits)})." ) edge_map.update(zip(other.clbits, dest.cbit_argument_conversion(clbits))) variable_mapper = _classical_resource_map.VariableMapper( dest.cregs, edge_map, dest.add_register ) mapped_instrs: list[CircuitInstruction] = [] for instr in other.data: n_qargs: list[Qubit] = [edge_map[qarg] for qarg in instr.qubits] n_cargs: list[Clbit] = [edge_map[carg] for carg in instr.clbits] n_op = instr.operation.copy() if (condition := getattr(n_op, "condition", None)) is not None: n_op.condition = variable_mapper.map_condition(condition) if isinstance(n_op, SwitchCaseOp): n_op.target = variable_mapper.map_target(n_op.target) mapped_instrs.append(CircuitInstruction(n_op, n_qargs, n_cargs)) if front: # adjust new instrs before original ones and update all parameters mapped_instrs += dest.data dest.clear() append = dest._control_flow_scopes[-1].append if dest._control_flow_scopes else dest._append for instr in mapped_instrs: append(instr) for gate, cals in other.calibrations.items(): dest._calibrations[gate].update(cals) dest.global_phase += other.global_phase if inplace: return None return dest def tensor(self, other: "QuantumCircuit", inplace: bool = False) -> Optional["QuantumCircuit"]: """Tensor ``self`` with ``other``. Remember that in the little-endian convention the leftmost operation will be at the bottom of the circuit. See also `the docs <qiskit.org/documentation/tutorials/circuits/3_summary_of_quantum_operations.html>`__ for more information. .. parsed-literal:: β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β” q_0: ─ bottom β”œ βŠ— q_0: ─ top β”œ = q_0: ── top β”œβ”€β”€ β””β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”˜ β”Œβ”΄β”€β”€β”€β”€β”€β”΄β”€β” q_1: ─ bottom β”œ β””β”€β”€β”€β”€β”€β”€β”€β”€β”˜ Args: other (QuantumCircuit): The other circuit to tensor this circuit with. inplace (bool): If True, modify the object. Otherwise return composed circuit. Examples: .. plot:: :include-source: from qiskit import QuantumCircuit top = QuantumCircuit(1) top.x(0); bottom = QuantumCircuit(2) bottom.cry(0.2, 0, 1); tensored = bottom.tensor(top) tensored.draw('mpl') Returns: QuantumCircuit: The tensored circuit (returns None if inplace==True). """ num_qubits = self.num_qubits + other.num_qubits num_clbits = self.num_clbits + other.num_clbits # If a user defined both circuits with via register sizes and not with named registers # (e.g. QuantumCircuit(2, 2)) then we have a naming collision, as the registers are by # default called "q" resp. "c". To still allow tensoring we define new registers of the # correct sizes. if ( len(self.qregs) == len(other.qregs) == 1 and self.qregs[0].name == other.qregs[0].name == "q" ): # check if classical registers are in the circuit if num_clbits > 0: dest = QuantumCircuit(num_qubits, num_clbits) else: dest = QuantumCircuit(num_qubits) # handle case if ``measure_all`` was called on both circuits, in which case the # registers are both named "meas" elif ( len(self.cregs) == len(other.cregs) == 1 and self.cregs[0].name == other.cregs[0].name == "meas" ): cr = ClassicalRegister(self.num_clbits + other.num_clbits, "meas") dest = QuantumCircuit(*other.qregs, *self.qregs, cr) # Now we don't have to handle any more cases arising from special implicit naming else: dest = QuantumCircuit( other.qubits, self.qubits, other.clbits, self.clbits, *other.qregs, *self.qregs, *other.cregs, *self.cregs, ) # compose self onto the output, and then other dest.compose(other, range(other.num_qubits), range(other.num_clbits), inplace=True) dest.compose( self, range(other.num_qubits, num_qubits), range(other.num_clbits, num_clbits), inplace=True, ) # Replace information from tensored circuit into self when inplace = True if inplace: self.__dict__.update(dest.__dict__) return None return dest @property def qubits(self) -> list[Qubit]: """ Returns a list of quantum bits in the order that the registers were added. """ return self._qubits @property def clbits(self) -> list[Clbit]: """ Returns a list of classical bits in the order that the registers were added. """ return self._clbits @property def ancillas(self) -> list[AncillaQubit]: """ Returns a list of ancilla bits in the order that the registers were added. """ return self._ancillas def __and__(self, rhs: "QuantumCircuit") -> "QuantumCircuit": """Overload & to implement self.compose.""" return self.compose(rhs) def __iand__(self, rhs: "QuantumCircuit") -> "QuantumCircuit": """Overload &= to implement self.compose in place.""" self.compose(rhs, inplace=True) return self def __xor__(self, top: "QuantumCircuit") -> "QuantumCircuit": """Overload ^ to implement self.tensor.""" return self.tensor(top) def __ixor__(self, top: "QuantumCircuit") -> "QuantumCircuit": """Overload ^= to implement self.tensor in place.""" self.tensor(top, inplace=True) return self def __len__(self) -> int: """Return number of operations in circuit.""" return len(self._data) @typing.overload def __getitem__(self, item: int) -> CircuitInstruction: ... @typing.overload def __getitem__(self, item: slice) -> list[CircuitInstruction]: ... def __getitem__(self, item): """Return indexed operation.""" return self._data[item] @staticmethod def cast(value: S, type_: Callable[..., T]) -> Union[S, T]: """Best effort to cast value to type. Otherwise, returns the value.""" try: return type_(value) except (ValueError, TypeError): return value def qbit_argument_conversion(self, qubit_representation: QubitSpecifier) -> list[Qubit]: """ Converts several qubit representations (such as indexes, range, etc.) into a list of qubits. Args: qubit_representation (Object): representation to expand Returns: List(Qubit): the resolved instances of the qubits. """ return _bit_argument_conversion( qubit_representation, self.qubits, self._qubit_indices, Qubit ) def cbit_argument_conversion(self, clbit_representation: ClbitSpecifier) -> list[Clbit]: """ Converts several classical bit representations (such as indexes, range, etc.) into a list of classical bits. Args: clbit_representation (Object): representation to expand Returns: List(tuple): Where each tuple is a classical bit. """ return _bit_argument_conversion( clbit_representation, self.clbits, self._clbit_indices, Clbit ) def _resolve_classical_resource(self, specifier): """Resolve a single classical resource specifier into a concrete resource, raising an error if the specifier is invalid. This is slightly different to :meth:`.cbit_argument_conversion`, because it should not unwrap :obj:`.ClassicalRegister` instances into lists, and in general it should not allow iterables or broadcasting. It is expected to be used as a callback for things like :meth:`.InstructionSet.c_if` to check the validity of their arguments. Args: specifier (Union[Clbit, ClassicalRegister, int]): a specifier of a classical resource present in this circuit. An ``int`` will be resolved into a :obj:`.Clbit` using the same conventions as measurement operations on this circuit use. Returns: Union[Clbit, ClassicalRegister]: the resolved resource. Raises: CircuitError: if the resource is not present in this circuit, or if the integer index passed is out-of-bounds. """ if isinstance(specifier, Clbit): if specifier not in self._clbit_indices: raise CircuitError(f"Clbit {specifier} is not present in this circuit.") return specifier if isinstance(specifier, ClassicalRegister): # This is linear complexity for something that should be constant, but QuantumCircuit # does not currently keep a hashmap of registers, and requires non-trivial changes to # how it exposes its registers publically before such a map can be safely stored so it # doesn't miss updates. (Jake, 2021-11-10). if specifier not in self.cregs: raise CircuitError(f"Register {specifier} is not present in this circuit.") return specifier if isinstance(specifier, int): try: return self._clbits[specifier] except IndexError: raise CircuitError(f"Classical bit index {specifier} is out-of-range.") from None raise CircuitError(f"Unknown classical resource specifier: '{specifier}'.") def _validate_expr(self, node: expr.Expr) -> expr.Expr: for var in expr.iter_vars(node): if isinstance(var.var, Clbit): if var.var not in self._clbit_indices: raise CircuitError(f"Clbit {var.var} is not present in this circuit.") elif isinstance(var.var, ClassicalRegister): if var.var not in self.cregs: raise CircuitError(f"Register {var.var} is not present in this circuit.") return node def append( self, instruction: Operation | CircuitInstruction, qargs: Sequence[QubitSpecifier] | None = None, cargs: Sequence[ClbitSpecifier] | None = None, ) -> InstructionSet: """Append one or more instructions to the end of the circuit, modifying the circuit in place. The ``qargs`` and ``cargs`` will be expanded and broadcast according to the rules of the given :class:`~.circuit.Instruction`, and any non-:class:`.Bit` specifiers (such as integer indices) will be resolved into the relevant instances. If a :class:`.CircuitInstruction` is given, it will be unwrapped, verified in the context of this circuit, and a new object will be appended to the circuit. In this case, you may not pass ``qargs`` or ``cargs`` separately. Args: instruction: :class:`~.circuit.Instruction` instance to append, or a :class:`.CircuitInstruction` with all its context. qargs: specifiers of the :class:`.Qubit`\\ s to attach instruction to. cargs: specifiers of the :class:`.Clbit`\\ s to attach instruction to. Returns: qiskit.circuit.InstructionSet: a handle to the :class:`.CircuitInstruction`\\ s that were actually added to the circuit. Raises: CircuitError: if the operation passed is not an instance of :class:`~.circuit.Instruction` . """ if isinstance(instruction, CircuitInstruction): operation = instruction.operation qargs = instruction.qubits cargs = instruction.clbits else: operation = instruction # Convert input to instruction if not isinstance(operation, Operation): if hasattr(operation, "to_instruction"): operation = operation.to_instruction() if not isinstance(operation, Operation): raise CircuitError("operation.to_instruction() is not an Operation.") else: if issubclass(operation, Operation): raise CircuitError( "Object is a subclass of Operation, please add () to " "pass an instance of this object." ) raise CircuitError( "Object to append must be an Operation or have a to_instruction() method." ) # Make copy of parameterized gate instances if hasattr(operation, "params"): is_parameter = any(isinstance(param, Parameter) for param in operation.params) if is_parameter: operation = copy.deepcopy(operation) expanded_qargs = [self.qbit_argument_conversion(qarg) for qarg in qargs or []] expanded_cargs = [self.cbit_argument_conversion(carg) for carg in cargs or []] if self._control_flow_scopes: appender = self._control_flow_scopes[-1].append requester = self._control_flow_scopes[-1].request_classical_resource else: appender = self._append requester = self._resolve_classical_resource instructions = InstructionSet(resource_requester=requester) if isinstance(operation, Instruction): for qarg, carg in operation.broadcast_arguments(expanded_qargs, expanded_cargs): self._check_dups(qarg) instruction = CircuitInstruction(operation, qarg, carg) appender(instruction) instructions.add(instruction) else: # For Operations that are non-Instructions, we use the Instruction's default method for qarg, carg in Instruction.broadcast_arguments( operation, expanded_qargs, expanded_cargs ): self._check_dups(qarg) instruction = CircuitInstruction(operation, qarg, carg) appender(instruction) instructions.add(instruction) return instructions # Preferred new style. @typing.overload def _append( self, instruction: CircuitInstruction, _qargs: None = None, _cargs: None = None ) -> CircuitInstruction: ... # To-be-deprecated old style. @typing.overload def _append( self, operation: Operation, qargs: Sequence[Qubit], cargs: Sequence[Clbit], ) -> Operation: ... def _append( self, instruction: CircuitInstruction | Instruction, qargs: Sequence[Qubit] | None = None, cargs: Sequence[Clbit] | None = None, ): """Append an instruction to the end of the circuit, modifying the circuit in place. .. warning:: This is an internal fast-path function, and it is the responsibility of the caller to ensure that all the arguments are valid; there is no error checking here. In particular, all the qubits and clbits must already exist in the circuit and there can be no duplicates in the list. .. note:: This function may be used by callers other than :obj:`.QuantumCircuit` when the caller is sure that all error-checking, broadcasting and scoping has already been performed, and the only reference to the circuit the instructions are being appended to is within that same function. In particular, it is not safe to call :meth:`QuantumCircuit._append` on a circuit that is received by a function argument. This is because :meth:`.QuantumCircuit._append` will not recognise the scoping constructs of the control-flow builder interface. Args: instruction: Operation instance to append qargs: Qubits to attach the instruction to. cargs: Clbits to attach the instruction to. Returns: Operation: a handle to the instruction that was just added :meta public: """ old_style = not isinstance(instruction, CircuitInstruction) if old_style: instruction = CircuitInstruction(instruction, qargs, cargs) self._data.append(instruction) if isinstance(instruction.operation, Instruction): self._update_parameter_table(instruction) # mark as normal circuit if a new instruction is added self.duration = None self.unit = "dt" return instruction.operation if old_style else instruction def _update_parameter_table(self, instruction: CircuitInstruction): for param_index, param in enumerate(instruction.operation.params): if isinstance(param, (ParameterExpression, QuantumCircuit)): # Scoped constructs like the control-flow ops use QuantumCircuit as a parameter. atomic_parameters = set(param.parameters) else: atomic_parameters = set() for parameter in atomic_parameters: if parameter in self._parameter_table: self._parameter_table[parameter].add((instruction.operation, param_index)) else: if parameter.name in self._parameter_table.get_names(): raise CircuitError(f"Name conflict on adding parameter: {parameter.name}") self._parameter_table[parameter] = ParameterReferences( ((instruction.operation, param_index),) ) # clear cache if new parameter is added self._parameters = None def add_register(self, *regs: Register | int | Sequence[Bit]) -> None: """Add registers.""" if not regs: return if any(isinstance(reg, int) for reg in regs): # QuantumCircuit defined without registers if len(regs) == 1 and isinstance(regs[0], int): # QuantumCircuit with anonymous quantum wires e.g. QuantumCircuit(2) if regs[0] == 0: regs = () else: regs = (QuantumRegister(regs[0], "q"),) elif len(regs) == 2 and all(isinstance(reg, int) for reg in regs): # QuantumCircuit with anonymous wires e.g. QuantumCircuit(2, 3) if regs[0] == 0: qregs: tuple[QuantumRegister, ...] = () else: qregs = (QuantumRegister(regs[0], "q"),) if regs[1] == 0: cregs: tuple[ClassicalRegister, ...] = () else: cregs = (ClassicalRegister(regs[1], "c"),) regs = qregs + cregs else: raise CircuitError( "QuantumCircuit parameters can be Registers or Integers." " If Integers, up to 2 arguments. QuantumCircuit was called" " with %s." % (regs,) ) for register in regs: if isinstance(register, Register) and any( register.name == reg.name for reg in self.qregs + self.cregs ): raise CircuitError('register name "%s" already exists' % register.name) if isinstance(register, AncillaRegister): for bit in register: if bit not in self._qubit_indices: self._ancillas.append(bit) if isinstance(register, QuantumRegister): self.qregs.append(register) for idx, bit in enumerate(register): if bit in self._qubit_indices: self._qubit_indices[bit].registers.append((register, idx)) else: self._qubits.append(bit) self._qubit_indices[bit] = BitLocations( len(self._qubits) - 1, [(register, idx)] ) elif isinstance(register, ClassicalRegister): self.cregs.append(register) for idx, bit in enumerate(register): if bit in self._clbit_indices: self._clbit_indices[bit].registers.append((register, idx)) else: self._clbits.append(bit) self._clbit_indices[bit] = BitLocations( len(self._clbits) - 1, [(register, idx)] ) elif isinstance(register, list): self.add_bits(register) else: raise CircuitError("expected a register") def add_bits(self, bits: Iterable[Bit]) -> None: """Add Bits to the circuit.""" duplicate_bits = set(self._qubit_indices).union(self._clbit_indices).intersection(bits) if duplicate_bits: raise CircuitError(f"Attempted to add bits found already in circuit: {duplicate_bits}") for bit in bits: if isinstance(bit, AncillaQubit): self._ancillas.append(bit) if isinstance(bit, Qubit): self._qubits.append(bit) self._qubit_indices[bit] = BitLocations(len(self._qubits) - 1, []) elif isinstance(bit, Clbit): self._clbits.append(bit) self._clbit_indices[bit] = BitLocations(len(self._clbits) - 1, []) else: raise CircuitError( "Expected an instance of Qubit, Clbit, or " "AncillaQubit, but was passed {}".format(bit) ) def find_bit(self, bit: Bit) -> BitLocations: """Find locations in the circuit which can be used to reference a given :obj:`~Bit`. Args: bit (Bit): The bit to locate. Returns: namedtuple(int, List[Tuple(Register, int)]): A 2-tuple. The first element (``index``) contains the index at which the ``Bit`` can be found (in either :obj:`~QuantumCircuit.qubits`, :obj:`~QuantumCircuit.clbits`, depending on its type). The second element (``registers``) is a list of ``(register, index)`` pairs with an entry for each :obj:`~Register` in the circuit which contains the :obj:`~Bit` (and the index in the :obj:`~Register` at which it can be found). Notes: The circuit index of an :obj:`~AncillaQubit` will be its index in :obj:`~QuantumCircuit.qubits`, not :obj:`~QuantumCircuit.ancillas`. Raises: CircuitError: If the supplied :obj:`~Bit` was of an unknown type. CircuitError: If the supplied :obj:`~Bit` could not be found on the circuit. """ try: if isinstance(bit, Qubit): return self._qubit_indices[bit] elif isinstance(bit, Clbit): return self._clbit_indices[bit] else: raise CircuitError(f"Could not locate bit of unknown type: {type(bit)}") except KeyError as err: raise CircuitError( f"Could not locate provided bit: {bit}. Has it been added to the QuantumCircuit?" ) from err def _check_dups(self, qubits: Sequence[Qubit]) -> None: """Raise exception if list of qubits contains duplicates.""" squbits = set(qubits) if len(squbits) != len(qubits): raise CircuitError("duplicate qubit arguments") def to_instruction( self, parameter_map: dict[Parameter, ParameterValueType] | None = None, label: str | None = None, ) -> Instruction: """Create an Instruction out of this circuit. Args: parameter_map(dict): For parameterized circuits, a mapping from parameters in the circuit to parameters to be used in the instruction. If None, existing circuit parameters will also parameterize the instruction. label (str): Optional gate label. Returns: qiskit.circuit.Instruction: a composite instruction encapsulating this circuit (can be decomposed back) """ from qiskit.converters.circuit_to_instruction import circuit_to_instruction return circuit_to_instruction(self, parameter_map, label=label) def to_gate( self, parameter_map: dict[Parameter, ParameterValueType] | None = None, label: str | None = None, ) -> Gate: """Create a Gate out of this circuit. Args: parameter_map(dict): For parameterized circuits, a mapping from parameters in the circuit to parameters to be used in the gate. If None, existing circuit parameters will also parameterize the gate. label (str): Optional gate label. Returns: Gate: a composite gate encapsulating this circuit (can be decomposed back) """ from qiskit.converters.circuit_to_gate import circuit_to_gate return circuit_to_gate(self, parameter_map, label=label) def decompose( self, gates_to_decompose: Type[Gate] | Sequence[Type[Gate]] | Sequence[str] | str | None = None, reps: int = 1, ) -> "QuantumCircuit": """Call a decomposition pass on this circuit, to decompose one level (shallow decompose). Args: gates_to_decompose (type or str or list(type, str)): Optional subset of gates to decompose. Can be a gate type, such as ``HGate``, or a gate name, such as 'h', or a gate label, such as 'My H Gate', or a list of any combination of these. If a gate name is entered, it will decompose all gates with that name, whether the gates have labels or not. Defaults to all gates in circuit. reps (int): Optional number of times the circuit should be decomposed. For instance, ``reps=2`` equals calling ``circuit.decompose().decompose()``. can decompose specific gates specific time Returns: QuantumCircuit: a circuit one level decomposed """ # pylint: disable=cyclic-import from qiskit.transpiler.passes.basis.decompose import Decompose from qiskit.transpiler.passes.synthesis import HighLevelSynthesis from qiskit.converters.circuit_to_dag import circuit_to_dag from qiskit.converters.dag_to_circuit import dag_to_circuit dag = circuit_to_dag(self) dag = HighLevelSynthesis().run(dag) pass_ = Decompose(gates_to_decompose) for _ in range(reps): dag = pass_.run(dag) return dag_to_circuit(dag) def qasm( self, formatted: bool = False, filename: str | None = None, encoding: str | None = None, ) -> str | None: """Return OpenQASM string. Args: formatted (bool): Return formatted Qasm string. filename (str): Save Qasm to file with name 'filename'. encoding (str): Optionally specify the encoding to use for the output file if ``filename`` is specified. By default this is set to the system's default encoding (ie whatever ``locale.getpreferredencoding()`` returns) and can be set to any valid codec or alias from stdlib's `codec module <https://docs.python.org/3/library/codecs.html#standard-encodings>`__ Returns: str: If formatted=False. Raises: MissingOptionalLibraryError: If pygments is not installed and ``formatted`` is ``True``. QASM2ExportError: If circuit has free parameters. QASM2ExportError: If an operation that has no OpenQASM 2 representation is encountered. """ from qiskit.qasm2 import QASM2ExportError # pylint: disable=cyclic-import if self.num_parameters > 0: raise QASM2ExportError( "Cannot represent circuits with unbound parameters in OpenQASM 2." ) existing_gate_names = { "barrier", "measure", "reset", "u3", "u2", "u1", "cx", "id", "u0", "u", "p", "x", "y", "z", "h", "s", "sdg", "t", "tdg", "rx", "ry", "rz", "sx", "sxdg", "cz", "cy", "swap", "ch", "ccx", "cswap", "crx", "cry", "crz", "cu1", "cp", "cu3", "csx", "cu", "rxx", "rzz", "rccx", "rc3x", "c3x", "c3sx", # This is the Qiskit gate name, but the qelib1.inc name is 'c3sqrtx'. "c4x", } # Mapping of instruction name to a pair of the source for a definition, and an OQ2 string # that includes the `gate` or `opaque` statement that defines the gate. gates_to_define: OrderedDict[str, tuple[Instruction, str]] = OrderedDict() regless_qubits = [bit for bit in self.qubits if not self.find_bit(bit).registers] regless_clbits = [bit for bit in self.clbits if not self.find_bit(bit).registers] dummy_registers: list[QuantumRegister | ClassicalRegister] = [] if regless_qubits: dummy_registers.append(QuantumRegister(name="qregless", bits=regless_qubits)) if regless_clbits: dummy_registers.append(ClassicalRegister(name="cregless", bits=regless_clbits)) register_escaped_names: dict[str, QuantumRegister | ClassicalRegister] = {} for regs in (self.qregs, self.cregs, dummy_registers): for reg in regs: register_escaped_names[ _make_unique(_qasm_escape_name(reg.name, "reg_"), register_escaped_names) ] = reg bit_labels: dict[Qubit | Clbit, str] = { bit: "%s[%d]" % (name, idx) for name, register in register_escaped_names.items() for (idx, bit) in enumerate(register) } register_definitions_qasm = "".join( f"{'qreg' if isinstance(reg, QuantumRegister) else 'creg'} {name}[{reg.size}];\n" for name, reg in register_escaped_names.items() ) instruction_calls = [] for instruction in self._data: operation = instruction.operation if operation.name == "measure": qubit = instruction.qubits[0] clbit = instruction.clbits[0] instruction_qasm = f"measure {bit_labels[qubit]} -> {bit_labels[clbit]};" elif operation.name == "reset": instruction_qasm = f"reset {bit_labels[instruction.qubits[0]]};" elif operation.name == "barrier": if not instruction.qubits: # Barriers with no operands are invalid in (strict) OQ2, and the statement # would have no meaning anyway. continue qargs = ",".join(bit_labels[q] for q in instruction.qubits) instruction_qasm = "barrier;" if not qargs else f"barrier {qargs};" else: instruction_qasm = _qasm2_custom_operation_statement( instruction, existing_gate_names, gates_to_define, bit_labels ) instruction_calls.append(instruction_qasm) instructions_qasm = "".join(f"{call}\n" for call in instruction_calls) gate_definitions_qasm = "".join(f"{qasm}\n" for _, qasm in gates_to_define.values()) out = "".join( ( self.header, "\n", self.extension_lib, "\n", gate_definitions_qasm, register_definitions_qasm, instructions_qasm, ) ) if filename: with open(filename, "w+", encoding=encoding) as file: file.write(out) if formatted: _optionals.HAS_PYGMENTS.require_now("formatted OpenQASM 2 output") import pygments from pygments.formatters import ( # pylint: disable=no-name-in-module Terminal256Formatter, ) from qiskit.qasm.pygments import OpenQASMLexer from qiskit.qasm.pygments import QasmTerminalStyle code = pygments.highlight( out, OpenQASMLexer(), Terminal256Formatter(style=QasmTerminalStyle) ) print(code) return None return out def draw( self, output: str | None = None, scale: float | None = None, filename: str | None = None, style: dict | str | None = None, interactive: bool = False, plot_barriers: bool = True, reverse_bits: bool = None, justify: str | None = None, vertical_compression: str | None = "medium", idle_wires: bool = True, with_layout: bool = True, fold: int | None = None, # The type of ax is matplotlib.axes.Axes, but this is not a fixed dependency, so cannot be # safely forward-referenced. ax: Any | None = None, initial_state: bool = False, cregbundle: bool = None, wire_order: list = None, ): """Draw the quantum circuit. Use the output parameter to choose the drawing format: **text**: ASCII art TextDrawing that can be printed in the console. **mpl**: images with color rendered purely in Python using matplotlib. **latex**: high-quality images compiled via latex. **latex_source**: raw uncompiled latex output. .. warning:: Support for :class:`~.expr.Expr` nodes in conditions and :attr:`.SwitchCaseOp.target` fields is preliminary and incomplete. The ``text`` and ``mpl`` drawers will make a best-effort attempt to show data dependencies, but the LaTeX-based drawers will skip these completely. Args: output (str): select the output method to use for drawing the circuit. Valid choices are ``text``, ``mpl``, ``latex``, ``latex_source``. By default the `text` drawer is used unless the user config file (usually ``~/.qiskit/settings.conf``) has an alternative backend set as the default. For example, ``circuit_drawer = latex``. If the output kwarg is set, that backend will always be used over the default in the user config file. scale (float): scale of image to draw (shrink if < 1.0). Only used by the `mpl`, `latex` and `latex_source` outputs. Defaults to 1.0. filename (str): file path to save image to. Defaults to None. style (dict or str): dictionary of style or file name of style json file. This option is only used by the `mpl` or `latex` output type. If `style` is a str, it is used as the path to a json file which contains a style dict. The file will be opened, parsed, and then any style elements in the dict will replace the default values in the input dict. A file to be loaded must end in ``.json``, but the name entered here can omit ``.json``. For example, ``style='iqx.json'`` or ``style='iqx'``. If `style` is a dict and the ``'name'`` key is set, that name will be used to load a json file, followed by loading the other items in the style dict. For example, ``style={'name': 'iqx'}``. If `style` is not a str and `name` is not a key in the style dict, then the default value from the user config file (usually ``~/.qiskit/settings.conf``) will be used, for example, ``circuit_mpl_style = iqx``. If none of these are set, the `default` style will be used. The search path for style json files can be specified in the user config, for example, ``circuit_mpl_style_path = /home/user/styles:/home/user``. See: :class:`~qiskit.visualization.qcstyle.DefaultStyle` for more information on the contents. interactive (bool): when set to true, show the circuit in a new window (for `mpl` this depends on the matplotlib backend being used supporting this). Note when used with either the `text` or the `latex_source` output type this has no effect and will be silently ignored. Defaults to False. reverse_bits (bool): when set to True, reverse the bit order inside registers for the output visualization. Defaults to False unless the user config file (usually ``~/.qiskit/settings.conf``) has an alternative value set. For example, ``circuit_reverse_bits = True``. plot_barriers (bool): enable/disable drawing barriers in the output circuit. Defaults to True. justify (string): options are ``left``, ``right`` or ``none``. If anything else is supplied, it defaults to left justified. It refers to where gates should be placed in the output circuit if there is an option. ``none`` results in each gate being placed in its own column. vertical_compression (string): ``high``, ``medium`` or ``low``. It merges the lines generated by the `text` output so the drawing will take less vertical room. Default is ``medium``. Only used by the `text` output, will be silently ignored otherwise. idle_wires (bool): include idle wires (wires with no circuit elements) in output visualization. Default is True. with_layout (bool): include layout information, with labels on the physical layout. Default is True. fold (int): sets pagination. It can be disabled using -1. In `text`, sets the length of the lines. This is useful when the drawing does not fit in the console. If None (default), it will try to guess the console width using ``shutil.get_terminal_size()``. However, if running in jupyter, the default line length is set to 80 characters. In `mpl`, it is the number of (visual) layers before folding. Default is 25. ax (matplotlib.axes.Axes): Only used by the `mpl` backend. An optional Axes object to be used for the visualization output. If none is specified, a new matplotlib Figure will be created and used. Additionally, if specified there will be no returned Figure since it is redundant. initial_state (bool): Optional. Adds ``|0>`` in the beginning of the wire. Default is False. cregbundle (bool): Optional. If set True, bundle classical registers. Default is True, except for when ``output`` is set to ``"text"``. wire_order (list): Optional. A list of integers used to reorder the display of the bits. The list must have an entry for every bit with the bits in the range 0 to (``num_qubits`` + ``num_clbits``). Returns: :class:`.TextDrawing` or :class:`matplotlib.figure` or :class:`PIL.Image` or :class:`str`: * `TextDrawing` (output='text') A drawing that can be printed as ascii art. * `matplotlib.figure.Figure` (output='mpl') A matplotlib figure object for the circuit diagram. * `PIL.Image` (output='latex') An in-memory representation of the image of the circuit diagram. * `str` (output='latex_source') The LaTeX source code for visualizing the circuit diagram. Raises: VisualizationError: when an invalid output method is selected ImportError: when the output methods requires non-installed libraries. Example: .. plot:: :include-source: from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit q = QuantumRegister(1) c = ClassicalRegister(1) qc = QuantumCircuit(q, c) qc.h(q) qc.measure(q, c) qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'}) """ # pylint: disable=cyclic-import from qiskit.visualization import circuit_drawer return circuit_drawer( self, scale=scale, filename=filename, style=style, output=output, interactive=interactive, plot_barriers=plot_barriers, reverse_bits=reverse_bits, justify=justify, vertical_compression=vertical_compression, idle_wires=idle_wires, with_layout=with_layout, fold=fold, ax=ax, initial_state=initial_state, cregbundle=cregbundle, wire_order=wire_order, ) def size( self, filter_function: Callable[..., int] = lambda x: not getattr( x.operation, "_directive", False ), ) -> int: """Returns total number of instructions in circuit. Args: filter_function (callable): a function to filter out some instructions. Should take as input a tuple of (Instruction, list(Qubit), list(Clbit)). By default filters out "directives", such as barrier or snapshot. Returns: int: Total number of gate operations. """ return sum(map(filter_function, self._data)) def depth( self, filter_function: Callable[..., int] = lambda x: not getattr( x.operation, "_directive", False ), ) -> int: """Return circuit depth (i.e., length of critical path). Args: filter_function (callable): A function to filter instructions. Should take as input a tuple of (Instruction, list(Qubit), list(Clbit)). Instructions for which the function returns False are ignored in the computation of the circuit depth. By default filters out "directives", such as barrier or snapshot. Returns: int: Depth of circuit. Notes: The circuit depth and the DAG depth need not be the same. """ # Assign each bit in the circuit a unique integer # to index into op_stack. bit_indices: dict[Qubit | Clbit, int] = { bit: idx for idx, bit in enumerate(self.qubits + self.clbits) } # If no bits, return 0 if not bit_indices: return 0 # A list that holds the height of each qubit # and classical bit. op_stack = [0] * len(bit_indices) # Here we are playing a modified version of # Tetris where we stack gates, but multi-qubit # gates, or measurements have a block for each # qubit or cbit that are connected by a virtual # line so that they all stacked at the same depth. # Conditional gates act on all cbits in the register # they are conditioned on. # The max stack height is the circuit depth. for instruction in self._data: levels = [] reg_ints = [] for ind, reg in enumerate(instruction.qubits + instruction.clbits): # Add to the stacks of the qubits and # cbits used in the gate. reg_ints.append(bit_indices[reg]) if filter_function(instruction): levels.append(op_stack[reg_ints[ind]] + 1) else: levels.append(op_stack[reg_ints[ind]]) # Assuming here that there is no conditional # snapshots or barriers ever. if getattr(instruction.operation, "condition", None): # Controls operate over all bits of a classical register # or over a single bit if isinstance(instruction.operation.condition[0], Clbit): condition_bits = [instruction.operation.condition[0]] else: condition_bits = instruction.operation.condition[0] for cbit in condition_bits: idx = bit_indices[cbit] if idx not in reg_ints: reg_ints.append(idx) levels.append(op_stack[idx] + 1) max_level = max(levels) for ind in reg_ints: op_stack[ind] = max_level return max(op_stack) def width(self) -> int: """Return number of qubits plus clbits in circuit. Returns: int: Width of circuit. """ return len(self.qubits) + len(self.clbits) @property def num_qubits(self) -> int: """Return number of qubits.""" return len(self.qubits) @property def num_ancillas(self) -> int: """Return the number of ancilla qubits.""" return len(self.ancillas) @property def num_clbits(self) -> int: """Return number of classical bits.""" return len(self.clbits) # The stringified return type is because OrderedDict can't be subscripted before Python 3.9, and # typing.OrderedDict wasn't added until 3.7.2. It can be turned into a proper type once 3.6 # support is dropped. def count_ops(self) -> "OrderedDict[Instruction, int]": """Count each operation kind in the circuit. Returns: OrderedDict: a breakdown of how many operations of each kind, sorted by amount. """ count_ops: dict[Instruction, int] = {} for instruction in self._data: count_ops[instruction.operation.name] = count_ops.get(instruction.operation.name, 0) + 1 return OrderedDict(sorted(count_ops.items(), key=lambda kv: kv[1], reverse=True)) def num_nonlocal_gates(self) -> int: """Return number of non-local gates (i.e. involving 2+ qubits). Conditional nonlocal gates are also included. """ multi_qubit_gates = 0 for instruction in self._data: if instruction.operation.num_qubits > 1 and not getattr( instruction.operation, "_directive", False ): multi_qubit_gates += 1 return multi_qubit_gates def get_instructions(self, name: str) -> list[CircuitInstruction]: """Get instructions matching name. Args: name (str): The name of instruction to. Returns: list(tuple): list of (instruction, qargs, cargs). """ return [match for match in self._data if match.operation.name == name] def num_connected_components(self, unitary_only: bool = False) -> int: """How many non-entangled subcircuits can the circuit be factored to. Args: unitary_only (bool): Compute only unitary part of graph. Returns: int: Number of connected components in circuit. """ # Convert registers to ints (as done in depth). bits = self.qubits if unitary_only else (self.qubits + self.clbits) bit_indices: dict[Qubit | Clbit, int] = {bit: idx for idx, bit in enumerate(bits)} # Start with each qubit or cbit being its own subgraph. sub_graphs = [[bit] for bit in range(len(bit_indices))] num_sub_graphs = len(sub_graphs) # Here we are traversing the gates and looking to see # which of the sub_graphs the gate joins together. for instruction in self._data: if unitary_only: args = instruction.qubits num_qargs = len(args) else: args = instruction.qubits + instruction.clbits num_qargs = len(args) + ( 1 if getattr(instruction.operation, "condition", None) else 0 ) if num_qargs >= 2 and not getattr(instruction.operation, "_directive", False): graphs_touched = [] num_touched = 0 # Controls necessarily join all the cbits in the # register that they use. if not unitary_only: for bit in instruction.operation.condition_bits: idx = bit_indices[bit] for k in range(num_sub_graphs): if idx in sub_graphs[k]: graphs_touched.append(k) break for item in args: reg_int = bit_indices[item] for k in range(num_sub_graphs): if reg_int in sub_graphs[k]: if k not in graphs_touched: graphs_touched.append(k) break graphs_touched = list(set(graphs_touched)) num_touched = len(graphs_touched) # If the gate touches more than one subgraph # join those graphs together and return # reduced number of subgraphs if num_touched > 1: connections = [] for idx in graphs_touched: connections.extend(sub_graphs[idx]) _sub_graphs = [] for idx in range(num_sub_graphs): if idx not in graphs_touched: _sub_graphs.append(sub_graphs[idx]) _sub_graphs.append(connections) sub_graphs = _sub_graphs num_sub_graphs -= num_touched - 1 # Cannot go lower than one so break if num_sub_graphs == 1: break return num_sub_graphs def num_unitary_factors(self) -> int: """Computes the number of tensor factors in the unitary (quantum) part of the circuit only. """ return self.num_connected_components(unitary_only=True) def num_tensor_factors(self) -> int: """Computes the number of tensor factors in the unitary (quantum) part of the circuit only. Notes: This is here for backwards compatibility, and will be removed in a future release of Qiskit. You should call `num_unitary_factors` instead. """ return self.num_unitary_factors() def copy(self, name: str | None = None) -> "QuantumCircuit": """Copy the circuit. Args: name (str): name to be given to the copied circuit. If None, then the name stays the same. Returns: QuantumCircuit: a deepcopy of the current circuit, with the specified name """ cpy = self.copy_empty_like(name) operation_copies = { id(instruction.operation): instruction.operation.copy() for instruction in self._data } cpy._parameter_table = ParameterTable( { param: ParameterReferences( (operation_copies[id(operation)], param_index) for operation, param_index in self._parameter_table[param] ) for param in self._parameter_table } ) cpy._data = [ instruction.replace(operation=operation_copies[id(instruction.operation)]) for instruction in self._data ] return cpy def copy_empty_like(self, name: str | None = None) -> "QuantumCircuit": """Return a copy of self with the same structure but empty. That structure includes: * name, calibrations and other metadata * global phase * all the qubits and clbits, including the registers Args: name (str): Name for the copied circuit. If None, then the name stays the same. Returns: QuantumCircuit: An empty copy of self. """ if not (name is None or isinstance(name, str)): raise TypeError( f"invalid name for a circuit: '{name}'. The name must be a string or 'None'." ) cpy = copy.copy(self) # copy registers correctly, in copy.copy they are only copied via reference cpy.qregs = self.qregs.copy() cpy.cregs = self.cregs.copy() cpy._qubits = self._qubits.copy() cpy._ancillas = self._ancillas.copy() cpy._clbits = self._clbits.copy() cpy._qubit_indices = self._qubit_indices.copy() cpy._clbit_indices = self._clbit_indices.copy() cpy._parameter_table = ParameterTable() cpy._data = [] cpy._calibrations = copy.deepcopy(self._calibrations) cpy._metadata = copy.deepcopy(self._metadata) if name: cpy.name = name return cpy def clear(self) -> None: """Clear all instructions in self. Clearing the circuits will keep the metadata and calibrations. """ self._data.clear() self._parameter_table.clear() def _create_creg(self, length: int, name: str) -> ClassicalRegister: """Creates a creg, checking if ClassicalRegister with same name exists""" if name in [creg.name for creg in self.cregs]: save_prefix = ClassicalRegister.prefix ClassicalRegister.prefix = name new_creg = ClassicalRegister(length) ClassicalRegister.prefix = save_prefix else: new_creg = ClassicalRegister(length, name) return new_creg def _create_qreg(self, length: int, name: str) -> QuantumRegister: """Creates a qreg, checking if QuantumRegister with same name exists""" if name in [qreg.name for qreg in self.qregs]: save_prefix = QuantumRegister.prefix QuantumRegister.prefix = name new_qreg = QuantumRegister(length) QuantumRegister.prefix = save_prefix else: new_qreg = QuantumRegister(length, name) return new_qreg def reset(self, qubit: QubitSpecifier) -> InstructionSet: """Reset the quantum bit(s) to their default state. Args: qubit: qubit(s) to reset. Returns: qiskit.circuit.InstructionSet: handle to the added instruction. """ return self.append(Reset(), [qubit], []) def measure(self, qubit: QubitSpecifier, cbit: ClbitSpecifier) -> InstructionSet: r"""Measure a quantum bit (``qubit``) in the Z basis into a classical bit (``cbit``). When a quantum state is measured, a qubit is projected in the computational (Pauli Z) basis to either :math:`\lvert 0 \rangle` or :math:`\lvert 1 \rangle`. The classical bit ``cbit`` indicates the result of that projection as a ``0`` or a ``1`` respectively. This operation is non-reversible. Args: qubit: qubit(s) to measure. cbit: classical bit(s) to place the measurement result(s) in. Returns: qiskit.circuit.InstructionSet: handle to the added instructions. Raises: CircuitError: if arguments have bad format. Examples: In this example, a qubit is measured and the result of that measurement is stored in the classical bit (usually expressed in diagrams as a double line): .. code-block:: from qiskit import QuantumCircuit circuit = QuantumCircuit(1, 1) circuit.h(0) circuit.measure(0, 0) circuit.draw() .. parsed-literal:: β”Œβ”€β”€β”€β”β”Œβ”€β” q: ─ H β”œβ”€Mβ”œ β””β”€β”€β”€β”˜β””β•₯β”˜ c: 1/══════╩═ 0 It is possible to call ``measure`` with lists of ``qubits`` and ``cbits`` as a shortcut for one-to-one measurement. These two forms produce identical results: .. code-block:: circuit = QuantumCircuit(2, 2) circuit.measure([0,1], [0,1]) .. code-block:: circuit = QuantumCircuit(2, 2) circuit.measure(0, 0) circuit.measure(1, 1) Instead of lists, you can use :class:`~qiskit.circuit.QuantumRegister` and :class:`~qiskit.circuit.ClassicalRegister` under the same logic. .. code-block:: from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister qreg = QuantumRegister(2, "qreg") creg = ClassicalRegister(2, "creg") circuit = QuantumCircuit(qreg, creg) circuit.measure(qreg, creg) This is equivalent to: .. code-block:: circuit = QuantumCircuit(qreg, creg) circuit.measure(qreg[0], creg[0]) circuit.measure(qreg[1], creg[1]) """ return self.append(Measure(), [qubit], [cbit]) def measure_active(self, inplace: bool = True) -> Optional["QuantumCircuit"]: """Adds measurement to all non-idle qubits. Creates a new ClassicalRegister with a size equal to the number of non-idle qubits being measured. Returns a new circuit with measurements if `inplace=False`. Args: inplace (bool): All measurements inplace or return new circuit. Returns: QuantumCircuit: Returns circuit with measurements when `inplace = False`. """ from qiskit.converters.circuit_to_dag import circuit_to_dag if inplace: circ = self else: circ = self.copy() dag = circuit_to_dag(circ) qubits_to_measure = [qubit for qubit in circ.qubits if qubit not in dag.idle_wires()] new_creg = circ._create_creg(len(qubits_to_measure), "measure") circ.add_register(new_creg) circ.barrier() circ.measure(qubits_to_measure, new_creg) if not inplace: return circ else: return None def measure_all( self, inplace: bool = True, add_bits: bool = True ) -> Optional["QuantumCircuit"]: """Adds measurement to all qubits. By default, adds new classical bits in a :obj:`.ClassicalRegister` to store these measurements. If ``add_bits=False``, the results of the measurements will instead be stored in the already existing classical bits, with qubit ``n`` being measured into classical bit ``n``. Returns a new circuit with measurements if ``inplace=False``. Args: inplace (bool): All measurements inplace or return new circuit. add_bits (bool): Whether to add new bits to store the results. Returns: QuantumCircuit: Returns circuit with measurements when ``inplace=False``. Raises: CircuitError: if ``add_bits=False`` but there are not enough classical bits. """ if inplace: circ = self else: circ = self.copy() if add_bits: new_creg = circ._create_creg(len(circ.qubits), "meas") circ.add_register(new_creg) circ.barrier() circ.measure(circ.qubits, new_creg) else: if len(circ.clbits) < len(circ.qubits): raise CircuitError( "The number of classical bits must be equal or greater than " "the number of qubits." ) circ.barrier() circ.measure(circ.qubits, circ.clbits[0 : len(circ.qubits)]) if not inplace: return circ else: return None def remove_final_measurements(self, inplace: bool = True) -> Optional["QuantumCircuit"]: """Removes final measurements and barriers on all qubits if they are present. Deletes the classical registers that were used to store the values from these measurements that become idle as a result of this operation, and deletes classical bits that are referenced only by removed registers, or that aren't referenced at all but have become idle as a result of this operation. Measurements and barriers are considered final if they are followed by no other operations (aside from other measurements or barriers.) Args: inplace (bool): All measurements removed inplace or return new circuit. Returns: QuantumCircuit: Returns the resulting circuit when ``inplace=False``, else None. """ # pylint: disable=cyclic-import from qiskit.transpiler.passes import RemoveFinalMeasurements from qiskit.converters import circuit_to_dag if inplace: circ = self else: circ = self.copy() dag = circuit_to_dag(circ) remove_final_meas = RemoveFinalMeasurements() new_dag = remove_final_meas.run(dag) kept_cregs = set(new_dag.cregs.values()) kept_clbits = set(new_dag.clbits) # Filter only cregs/clbits still in new DAG, preserving original circuit order cregs_to_add = [creg for creg in circ.cregs if creg in kept_cregs] clbits_to_add = [clbit for clbit in circ._clbits if clbit in kept_clbits] # Clear cregs and clbits circ.cregs = [] circ._clbits = [] circ._clbit_indices = {} # We must add the clbits first to preserve the original circuit # order. This way, add_register never adds clbits and just # creates registers that point to them. circ.add_bits(clbits_to_add) for creg in cregs_to_add: circ.add_register(creg) # Clear instruction info circ.data.clear() circ._parameter_table.clear() # Set circ instructions to match the new DAG for node in new_dag.topological_op_nodes(): # Get arguments for classical condition (if any) inst = node.op.copy() circ.append(inst, node.qargs, node.cargs) if not inplace: return circ else: return None @staticmethod def from_qasm_file(path: str) -> "QuantumCircuit": """Take in a QASM file and generate a QuantumCircuit object. Args: path (str): Path to the file for a QASM program Return: QuantumCircuit: The QuantumCircuit object for the input QASM See also: :func:`.qasm2.load`: the complete interface to the OpenQASM 2 importer. """ # pylint: disable=cyclic-import from qiskit import qasm2 return qasm2.load( path, include_path=qasm2.LEGACY_INCLUDE_PATH, custom_instructions=qasm2.LEGACY_CUSTOM_INSTRUCTIONS, custom_classical=qasm2.LEGACY_CUSTOM_CLASSICAL, strict=False, ) @staticmethod def from_qasm_str(qasm_str: str) -> "QuantumCircuit": """Take in a QASM string and generate a QuantumCircuit object. Args: qasm_str (str): A QASM program string Return: QuantumCircuit: The QuantumCircuit object for the input QASM See also: :func:`.qasm2.loads`: the complete interface to the OpenQASM 2 importer. """ # pylint: disable=cyclic-import from qiskit import qasm2 return qasm2.loads( qasm_str, include_path=qasm2.LEGACY_INCLUDE_PATH, custom_instructions=qasm2.LEGACY_CUSTOM_INSTRUCTIONS, custom_classical=qasm2.LEGACY_CUSTOM_CLASSICAL, strict=False, ) @property def global_phase(self) -> ParameterValueType: """Return the global phase of the circuit in radians.""" return self._global_phase @global_phase.setter def global_phase(self, angle: ParameterValueType): """Set the phase of the circuit. Args: angle (float, ParameterExpression): radians """ if isinstance(angle, ParameterExpression) and angle.parameters: self._global_phase = angle else: # Set the phase to the [0, 2Ο€) interval angle = float(angle) if not angle: self._global_phase = 0 else: self._global_phase = angle % (2 * np.pi) @property def parameters(self) -> ParameterView: """The parameters defined in the circuit. This attribute returns the :class:`.Parameter` objects in the circuit sorted alphabetically. Note that parameters instantiated with a :class:`.ParameterVector` are still sorted numerically. Examples: The snippet below shows that insertion order of parameters does not matter. .. code-block:: python >>> from qiskit.circuit import QuantumCircuit, Parameter >>> a, b, elephant = Parameter("a"), Parameter("b"), Parameter("elephant") >>> circuit = QuantumCircuit(1) >>> circuit.rx(b, 0) >>> circuit.rz(elephant, 0) >>> circuit.ry(a, 0) >>> circuit.parameters # sorted alphabetically! ParameterView([Parameter(a), Parameter(b), Parameter(elephant)]) Bear in mind that alphabetical sorting might be unintuitive when it comes to numbers. The literal "10" comes before "2" in strict alphabetical sorting. .. code-block:: python >>> from qiskit.circuit import QuantumCircuit, Parameter >>> angles = [Parameter("angle_1"), Parameter("angle_2"), Parameter("angle_10")] >>> circuit = QuantumCircuit(1) >>> circuit.u(*angles, 0) >>> circuit.draw() β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” q: ─ U(angle_1,angle_2,angle_10) β”œ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ >>> circuit.parameters ParameterView([Parameter(angle_1), Parameter(angle_10), Parameter(angle_2)]) To respect numerical sorting, a :class:`.ParameterVector` can be used. .. code-block:: python >>> from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector >>> x = ParameterVector("x", 12) >>> circuit = QuantumCircuit(1) >>> for x_i in x: ... circuit.rx(x_i, 0) >>> circuit.parameters ParameterView([ ParameterVectorElement(x[0]), ParameterVectorElement(x[1]), ParameterVectorElement(x[2]), ParameterVectorElement(x[3]), ..., ParameterVectorElement(x[11]) ]) Returns: The sorted :class:`.Parameter` objects in the circuit. """ # parameters from gates if self._parameters is None: self._parameters = sort_parameters(self._unsorted_parameters()) # return as parameter view, which implements the set and list interface return ParameterView(self._parameters) @property def num_parameters(self) -> int: """The number of parameter objects in the circuit.""" return len(self._unsorted_parameters()) def _unsorted_parameters(self) -> set[Parameter]: """Efficiently get all parameters in the circuit, without any sorting overhead.""" parameters = set(self._parameter_table) if isinstance(self.global_phase, ParameterExpression): parameters.update(self.global_phase.parameters) return parameters @overload def assign_parameters( self, parameters: Union[Mapping[Parameter, ParameterValueType], Sequence[ParameterValueType]], inplace: Literal[False] = ..., *, flat_input: bool = ..., strict: bool = ..., ) -> "QuantumCircuit": ... @overload def assign_parameters( self, parameters: Union[Mapping[Parameter, ParameterValueType], Sequence[ParameterValueType]], inplace: Literal[True] = ..., *, flat_input: bool = ..., strict: bool = ..., ) -> None: ... def assign_parameters( # pylint: disable=missing-raises-doc self, parameters: Union[Mapping[Parameter, ParameterValueType], Sequence[ParameterValueType]], inplace: bool = False, *, flat_input: bool = False, strict: bool = True, ) -> Optional["QuantumCircuit"]: """Assign parameters to new parameters or values. If ``parameters`` is passed as a dictionary, the keys must be :class:`.Parameter` instances in the current circuit. The values of the dictionary can either be numeric values or new parameter objects. If ``parameters`` is passed as a list or array, the elements are assigned to the current parameters in the order of :attr:`parameters` which is sorted alphabetically (while respecting the ordering in :class:`.ParameterVector` objects). The values can be assigned to the current circuit object or to a copy of it. Args: parameters: Either a dictionary or iterable specifying the new parameter values. inplace: If False, a copy of the circuit with the bound parameters is returned. If True the circuit instance itself is modified. flat_input: If ``True`` and ``parameters`` is a mapping type, it is assumed to be exactly a mapping of ``{parameter: value}``. By default (``False``), the mapping may also contain :class:`.ParameterVector` keys that point to a corresponding sequence of values, and these will be unrolled during the mapping. strict: If ``False``, any parameters given in the mapping that are not used in the circuit will be ignored. If ``True`` (the default), an error will be raised indicating a logic error. Raises: CircuitError: If parameters is a dict and contains parameters not present in the circuit. ValueError: If parameters is a list/array and the length mismatches the number of free parameters in the circuit. Returns: A copy of the circuit with bound parameters if ``inplace`` is False, otherwise None. Examples: Create a parameterized circuit and assign the parameters in-place. .. plot:: :include-source: from qiskit.circuit import QuantumCircuit, Parameter circuit = QuantumCircuit(2) params = [Parameter('A'), Parameter('B'), Parameter('C')] circuit.ry(params[0], 0) circuit.crx(params[1], 0, 1) circuit.draw('mpl') circuit.assign_parameters({params[0]: params[2]}, inplace=True) circuit.draw('mpl') Bind the values out-of-place by list and get a copy of the original circuit. .. plot:: :include-source: from qiskit.circuit import QuantumCircuit, ParameterVector circuit = QuantumCircuit(2) params = ParameterVector('P', 2) circuit.ry(params[0], 0) circuit.crx(params[1], 0, 1) bound_circuit = circuit.assign_parameters([1, 2]) bound_circuit.draw('mpl') circuit.draw('mpl') """ if inplace: target = self else: target = self.copy() target._increment_instances() target._name_update() # Normalise the inputs into simple abstract interfaces, so we've dispatched the "iteration" # logic in one place at the start of the function. This lets us do things like calculate # and cache expensive properties for (e.g.) the sequence format only if they're used; for # many large, close-to-hardware circuits, we won't need the extra handling for # `global_phase` or recursive definition binding. # # During normalisation, be sure to reference 'parameters' and related things from 'self' not # 'target' so we can take advantage of any caching we might be doing. if isinstance(parameters, dict): raw_mapping = parameters if flat_input else self._unroll_param_dict(parameters) our_parameters = self._unsorted_parameters() if strict and (extras := raw_mapping.keys() - our_parameters): raise CircuitError( f"Cannot bind parameters ({', '.join(str(x) for x in extras)}) not present in" " the circuit." ) parameter_binds = _ParameterBindsDict(raw_mapping, our_parameters) else: our_parameters = self.parameters if len(parameters) != len(our_parameters): raise ValueError( "Mismatching number of values and parameters. For partial binding " "please pass a dictionary of {parameter: value} pairs." ) parameter_binds = _ParameterBindsSequence(our_parameters, parameters) # Clear out the parameter table for the relevant entries, since we'll be binding those. # Any new references to parameters are reinserted as part of the bind. target._parameters = None # This is deliberately eager, because we want the side effect of clearing the table. all_references = [ (parameter, value, target._parameter_table.pop(parameter, ())) for parameter, value in parameter_binds.items() ] seen_operations = {} # The meat of the actual binding for regular operations. for to_bind, bound_value, references in all_references: update_parameters = ( tuple(bound_value.parameters) if isinstance(bound_value, ParameterExpression) else () ) for operation, index in references: seen_operations[id(operation)] = operation assignee = operation.params[index] if isinstance(assignee, ParameterExpression): new_parameter = assignee.assign(to_bind, bound_value) for parameter in update_parameters: if parameter not in target._parameter_table: target._parameter_table[parameter] = ParameterReferences(()) target._parameter_table[parameter].add((operation, index)) if not new_parameter.parameters: if new_parameter.is_real(): new_parameter = ( int(new_parameter) if new_parameter._symbol_expr.is_integer else float(new_parameter) ) else: new_parameter = complex(new_parameter) new_parameter = operation.validate_parameter(new_parameter) elif isinstance(assignee, QuantumCircuit): new_parameter = assignee.assign_parameters( {to_bind: bound_value}, inplace=False, flat_input=True ) else: raise RuntimeError( # pragma: no cover f"Saw an unknown type during symbolic binding: {assignee}." " This may indicate an internal logic error in symbol tracking." ) operation.params[index] = new_parameter # After we've been through everything at the top level, make a single visit to each # operation we've seen, rebinding its definition if necessary. for operation in seen_operations.values(): if ( definition := getattr(operation, "_definition", None) ) is not None and definition.num_parameters: definition.assign_parameters( parameter_binds.mapping, inplace=True, flat_input=True, strict=False ) if isinstance(target.global_phase, ParameterExpression): new_phase = target.global_phase for parameter in new_phase.parameters & parameter_binds.mapping.keys(): new_phase = new_phase.assign(parameter, parameter_binds.mapping[parameter]) target.global_phase = new_phase # Finally, assign the parameters inside any of the calibrations. We don't track these in # the `ParameterTable`, so we manually reconstruct things. def map_calibration(qubits, parameters, schedule): modified = False new_parameters = list(parameters) for i, parameter in enumerate(new_parameters): if not isinstance(parameter, ParameterExpression): continue if not (contained := parameter.parameters & parameter_binds.mapping.keys()): continue for to_bind in contained: parameter = parameter.assign(to_bind, parameter_binds.mapping[to_bind]) if not parameter.parameters: parameter = ( int(parameter) if parameter._symbol_expr.is_integer else float(parameter) ) new_parameters[i] = parameter modified = True if modified: schedule.assign_parameters(parameter_binds.mapping) return (qubits, tuple(new_parameters)), schedule target._calibrations = defaultdict( dict, ( ( gate, dict( map_calibration(qubits, parameters, schedule) for (qubits, parameters), schedule in calibrations.items() ), ) for gate, calibrations in target._calibrations.items() ), ) return None if inplace else target @staticmethod def _unroll_param_dict( parameter_binds: Mapping[Parameter, ParameterValueType] ) -> Mapping[Parameter, ParameterValueType]: out = {} for parameter, value in parameter_binds.items(): if isinstance(parameter, ParameterVector): if len(parameter) != len(value): raise CircuitError( f"Parameter vector '{parameter.name}' has length {len(parameter)}," f" but was assigned to {len(value)} values." ) out.update(zip(parameter, value)) else: out[parameter] = value return out def bind_parameters( self, values: Union[Mapping[Parameter, float], Sequence[float]] ) -> "QuantumCircuit": """Assign numeric parameters to values yielding a new circuit. If the values are given as list or array they are bound to the circuit in the order of :attr:`parameters` (see the docstring for more details). To assign new Parameter objects or bind the values in-place, without yielding a new circuit, use the :meth:`assign_parameters` method. Args: values: ``{parameter: value, ...}`` or ``[value1, value2, ...]`` Raises: CircuitError: If values is a dict and contains parameters not present in the circuit. TypeError: If values contains a ParameterExpression. Returns: Copy of self with assignment substitution. """ if isinstance(values, dict): if any(isinstance(value, ParameterExpression) for value in values.values()): raise TypeError( "Found ParameterExpression in values; use assign_parameters() instead." ) return self.assign_parameters(values) else: if any(isinstance(value, ParameterExpression) for value in values): raise TypeError( "Found ParameterExpression in values; use assign_parameters() instead." ) return self.assign_parameters(values) def barrier(self, *qargs: QubitSpecifier, label=None) -> InstructionSet: """Apply :class:`~.library.Barrier`. If ``qargs`` is empty, applies to all qubits in the circuit. Args: qargs (QubitSpecifier): Specification for one or more qubit arguments. label (str): The string label of the barrier. Returns: qiskit.circuit.InstructionSet: handle to the added instructions. """ from .barrier import Barrier qubits: list[QubitSpecifier] = [] if not qargs: # None qubits.extend(self.qubits) for qarg in qargs: if isinstance(qarg, QuantumRegister): qubits.extend([qarg[j] for j in range(qarg.size)]) elif isinstance(qarg, list): qubits.extend(qarg) elif isinstance(qarg, range): qubits.extend(list(qarg)) elif isinstance(qarg, slice): qubits.extend(self.qubits[qarg]) else: qubits.append(qarg) return self.append(Barrier(len(qubits), label=label), qubits, []) def delay( self, duration: ParameterValueType, qarg: QubitSpecifier | None = None, unit: str = "dt", ) -> InstructionSet: """Apply :class:`~.circuit.Delay`. If qarg is ``None``, applies to all qubits. When applying to multiple qubits, delays with the same duration will be created. Args: duration (int or float or ParameterExpression): duration of the delay. qarg (Object): qubit argument to apply this delay. unit (str): unit of the duration. Supported units: ``'s'``, ``'ms'``, ``'us'``, ``'ns'``, ``'ps'``, and ``'dt'``. Default is ``'dt'``, i.e. integer time unit depending on the target backend. Returns: qiskit.circuit.InstructionSet: handle to the added instructions. Raises: CircuitError: if arguments have bad format. """ qubits: list[QubitSpecifier] = [] if qarg is None: # -> apply delays to all qubits for q in self.qubits: qubits.append(q) else: if isinstance(qarg, QuantumRegister): qubits.extend([qarg[j] for j in range(qarg.size)]) elif isinstance(qarg, list): qubits.extend(qarg) elif isinstance(qarg, (range, tuple)): qubits.extend(list(qarg)) elif isinstance(qarg, slice): qubits.extend(self.qubits[qarg]) else: qubits.append(qarg) instructions = InstructionSet(resource_requester=self._resolve_classical_resource) for q in qubits: inst: tuple[ Instruction, Sequence[QubitSpecifier] | None, Sequence[ClbitSpecifier] | None ] = (Delay(duration, unit), [q], []) self.append(*inst) instructions.add(*inst) return instructions def h(self, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.HGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.h import HGate return self.append(HGate(), [qubit], []) def ch( self, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CHGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.h import CHGate return self.append( CHGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [] ) def i(self, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.IGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.i import IGate return self.append(IGate(), [qubit], []) def id(self, qubit: QubitSpecifier) -> InstructionSet: # pylint: disable=invalid-name """Apply :class:`~qiskit.circuit.library.IGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. See Also: QuantumCircuit.i: the same function. """ return self.i(qubit) def ms(self, theta: ParameterValueType, qubits: Sequence[QubitSpecifier]) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.MSGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The angle of the rotation. qubits: The qubits to apply the gate to. Returns: A handle to the instructions created. """ # pylint: disable=cyclic-import from .library.generalized_gates.gms import MSGate return self.append(MSGate(len(qubits), theta), qubits) def p(self, theta: ParameterValueType, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.PhaseGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: THe angle of the rotation. qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.p import PhaseGate return self.append(PhaseGate(theta), [qubit], []) def cp( self, theta: ParameterValueType, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CPhaseGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The angle of the rotation. control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.p import CPhaseGate return self.append( CPhaseGate(theta, label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [] ) def mcp( self, lam: ParameterValueType, control_qubits: Sequence[QubitSpecifier], target_qubit: QubitSpecifier, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.MCPhaseGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: lam: The angle of the rotation. control_qubits: The qubits used as the controls. target_qubit: The qubit(s) targeted by the gate. Returns: A handle to the instructions created. """ from .library.standard_gates.p import MCPhaseGate num_ctrl_qubits = len(control_qubits) return self.append( MCPhaseGate(lam, num_ctrl_qubits), control_qubits[:] + [target_qubit], [] ) def r( self, theta: ParameterValueType, phi: ParameterValueType, qubit: QubitSpecifier ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The angle of the rotation. phi: The angle of the axis of rotation in the x-y plane. qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.r import RGate return self.append(RGate(theta, phi), [qubit], []) def rv( self, vx: ParameterValueType, vy: ParameterValueType, vz: ParameterValueType, qubit: QubitSpecifier, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RVGate`. For the full matrix form of this gate, see the underlying gate documentation. Rotation around an arbitrary rotation axis :math:`v`, where :math:`|v|` is the angle of rotation in radians. Args: vx: x-component of the rotation axis. vy: y-component of the rotation axis. vz: z-component of the rotation axis. qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.generalized_gates.rv import RVGate return self.append(RVGate(vx, vy, vz), [qubit], []) def rccx( self, control_qubit1: QubitSpecifier, control_qubit2: QubitSpecifier, target_qubit: QubitSpecifier, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RCCXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit1: The qubit(s) used as the first control. control_qubit2: The qubit(s) used as the second control. target_qubit: The qubit(s) targeted by the gate. Returns: A handle to the instructions created. """ from .library.standard_gates.x import RCCXGate return self.append(RCCXGate(), [control_qubit1, control_qubit2, target_qubit], []) def rcccx( self, control_qubit1: QubitSpecifier, control_qubit2: QubitSpecifier, control_qubit3: QubitSpecifier, target_qubit: QubitSpecifier, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RC3XGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit1: The qubit(s) used as the first control. control_qubit2: The qubit(s) used as the second control. control_qubit3: The qubit(s) used as the third control. target_qubit: The qubit(s) targeted by the gate. Returns: A handle to the instructions created. """ from .library.standard_gates.x import RC3XGate return self.append( RC3XGate(), [control_qubit1, control_qubit2, control_qubit3, target_qubit], [] ) def rx( self, theta: ParameterValueType, qubit: QubitSpecifier, label: str | None = None ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The rotation angle of the gate. qubit: The qubit(s) to apply the gate to. label: The string label of the gate in the circuit. Returns: A handle to the instructions created. """ from .library.standard_gates.rx import RXGate return self.append(RXGate(theta, label=label), [qubit], []) def crx( self, theta: ParameterValueType, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CRXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The angle of the rotation. control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.rx import CRXGate return self.append( CRXGate(theta, label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [] ) def rxx( self, theta: ParameterValueType, qubit1: QubitSpecifier, qubit2: QubitSpecifier ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RXXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The angle of the rotation. qubit1: The qubit(s) to apply the gate to. qubit2: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.rxx import RXXGate return self.append(RXXGate(theta), [qubit1, qubit2], []) def ry( self, theta: ParameterValueType, qubit: QubitSpecifier, label: str | None = None ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RYGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The rotation angle of the gate. qubit: The qubit(s) to apply the gate to. label: The string label of the gate in the circuit. Returns: A handle to the instructions created. """ from .library.standard_gates.ry import RYGate return self.append(RYGate(theta, label=label), [qubit], []) def cry( self, theta: ParameterValueType, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CRYGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The angle of the rotation. control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.ry import CRYGate return self.append( CRYGate(theta, label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [] ) def ryy( self, theta: ParameterValueType, qubit1: QubitSpecifier, qubit2: QubitSpecifier ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RYYGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The rotation angle of the gate. qubit1: The qubit(s) to apply the gate to. qubit2: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.ryy import RYYGate return self.append(RYYGate(theta), [qubit1, qubit2], []) def rz(self, phi: ParameterValueType, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RZGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: phi: The rotation angle of the gate. qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.rz import RZGate return self.append(RZGate(phi), [qubit], []) def crz( self, theta: ParameterValueType, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CRZGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The angle of the rotation. control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.rz import CRZGate return self.append( CRZGate(theta, label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [] ) def rzx( self, theta: ParameterValueType, qubit1: QubitSpecifier, qubit2: QubitSpecifier ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RZXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The rotation angle of the gate. qubit1: The qubit(s) to apply the gate to. qubit2: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.rzx import RZXGate return self.append(RZXGate(theta), [qubit1, qubit2], []) def rzz( self, theta: ParameterValueType, qubit1: QubitSpecifier, qubit2: QubitSpecifier ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RZZGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The rotation angle of the gate. qubit1: The qubit(s) to apply the gate to. qubit2: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.rzz import RZZGate return self.append(RZZGate(theta), [qubit1, qubit2], []) def ecr(self, qubit1: QubitSpecifier, qubit2: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.ECRGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit1, qubit2: The qubits to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.ecr import ECRGate return self.append(ECRGate(), [qubit1, qubit2], []) def s(self, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.SGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.s import SGate return self.append(SGate(), [qubit], []) def sdg(self, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.SdgGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.s import SdgGate return self.append(SdgGate(), [qubit], []) def cs( self, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CSGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.s import CSGate return self.append( CSGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [], ) def csdg( self, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CSdgGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.s import CSdgGate return self.append( CSdgGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [], ) def swap(self, qubit1: QubitSpecifier, qubit2: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.SwapGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit1, qubit2: The qubits to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.swap import SwapGate return self.append(SwapGate(), [qubit1, qubit2], []) def iswap(self, qubit1: QubitSpecifier, qubit2: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.iSwapGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit1, qubit2: The qubits to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.iswap import iSwapGate return self.append(iSwapGate(), [qubit1, qubit2], []) def cswap( self, control_qubit: QubitSpecifier, target_qubit1: QubitSpecifier, target_qubit2: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CSwapGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the control. target_qubit1: The qubit(s) targeted by the gate. target_qubit2: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. ``'1'``). Defaults to controlling on the ``'1'`` state. Returns: A handle to the instructions created. """ from .library.standard_gates.swap import CSwapGate return self.append( CSwapGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit1, target_qubit2], [], ) def fredkin( self, control_qubit: QubitSpecifier, target_qubit1: QubitSpecifier, target_qubit2: QubitSpecifier, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CSwapGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the control. target_qubit1: The qubit(s) targeted by the gate. target_qubit2: The qubit(s) targeted by the gate. Returns: A handle to the instructions created. See Also: QuantumCircuit.cswap: the same function with a different name. """ return self.cswap(control_qubit, target_qubit1, target_qubit2) def sx(self, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.SXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.sx import SXGate return self.append(SXGate(), [qubit], []) def sxdg(self, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.SXdgGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.sx import SXdgGate return self.append(SXdgGate(), [qubit], []) def csx( self, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CSXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.sx import CSXGate return self.append( CSXGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [], ) def t(self, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.TGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.t import TGate return self.append(TGate(), [qubit], []) def tdg(self, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.TdgGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.t import TdgGate return self.append(TdgGate(), [qubit], []) def u( self, theta: ParameterValueType, phi: ParameterValueType, lam: ParameterValueType, qubit: QubitSpecifier, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.UGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The :math:`\theta` rotation angle of the gate. phi: The :math:`\phi` rotation angle of the gate. lam: The :math:`\lambda` rotation angle of the gate. qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.u import UGate return self.append(UGate(theta, phi, lam), [qubit], []) def cu( self, theta: ParameterValueType, phi: ParameterValueType, lam: ParameterValueType, gamma: ParameterValueType, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.CUGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The :math:`\theta` rotation angle of the gate. phi: The :math:`\phi` rotation angle of the gate. lam: The :math:`\lambda` rotation angle of the gate. gamma: The global phase applied of the U gate, if applied. control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.u import CUGate return self.append( CUGate(theta, phi, lam, gamma, label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [], ) def x(self, qubit: QubitSpecifier, label: str | None = None) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.XGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. label: The string label of the gate in the circuit. Returns: A handle to the instructions created. """ from .library.standard_gates.x import XGate return self.append(XGate(label=label), [qubit], []) def cx( self, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.CXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.x import CXGate return self.append( CXGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [] ) def cnot( self, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.CXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. See Also: QuantumCircuit.cx: the same function with a different name. """ return self.cx(control_qubit, target_qubit, label, ctrl_state) def dcx(self, qubit1: QubitSpecifier, qubit2: QubitSpecifier) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.DCXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit1: The qubit(s) to apply the gate to. qubit2: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.dcx import DCXGate return self.append(DCXGate(), [qubit1, qubit2], []) def ccx( self, control_qubit1: QubitSpecifier, control_qubit2: QubitSpecifier, target_qubit: QubitSpecifier, ctrl_state: str | int | None = None, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.CCXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit1: The qubit(s) used as the first control. control_qubit2: The qubit(s) used as the second control. target_qubit: The qubit(s) targeted by the gate. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.x import CCXGate return self.append( CCXGate(ctrl_state=ctrl_state), [control_qubit1, control_qubit2, target_qubit], [], ) def toffoli( self, control_qubit1: QubitSpecifier, control_qubit2: QubitSpecifier, target_qubit: QubitSpecifier, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.CCXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit1: The qubit(s) used as the first control. control_qubit2: The qubit(s) used as the second control. target_qubit: The qubit(s) targeted by the gate. Returns: A handle to the instructions created. See Also: QuantumCircuit.ccx: the same gate with a different name. """ return self.ccx(control_qubit1, control_qubit2, target_qubit) def mcx( self, control_qubits: Sequence[QubitSpecifier], target_qubit: QubitSpecifier, ancilla_qubits: QubitSpecifier | Sequence[QubitSpecifier] | None = None, mode: str = "noancilla", ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.MCXGate`. The multi-cX gate can be implemented using different techniques, which use different numbers of ancilla qubits and have varying circuit depth. These modes are: - ``'noancilla'``: Requires 0 ancilla qubits. - ``'recursion'``: Requires 1 ancilla qubit if more than 4 controls are used, otherwise 0. - ``'v-chain'``: Requires 2 less ancillas than the number of control qubits. - ``'v-chain-dirty'``: Same as for the clean ancillas (but the circuit will be longer). For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubits: The qubits used as the controls. target_qubit: The qubit(s) targeted by the gate. ancilla_qubits: The qubits used as the ancillae, if the mode requires them. mode: The choice of mode, explained further above. Returns: A handle to the instructions created. Raises: ValueError: if the given mode is not known, or if too few ancilla qubits are passed. AttributeError: if no ancilla qubits are passed, but some are needed. """ from .library.standard_gates.x import MCXGrayCode, MCXRecursive, MCXVChain num_ctrl_qubits = len(control_qubits) available_implementations = { "noancilla": MCXGrayCode(num_ctrl_qubits), "recursion": MCXRecursive(num_ctrl_qubits), "v-chain": MCXVChain(num_ctrl_qubits, False), "v-chain-dirty": MCXVChain(num_ctrl_qubits, dirty_ancillas=True), # outdated, previous names "advanced": MCXRecursive(num_ctrl_qubits), "basic": MCXVChain(num_ctrl_qubits, dirty_ancillas=False), "basic-dirty-ancilla": MCXVChain(num_ctrl_qubits, dirty_ancillas=True), } # check ancilla input if ancilla_qubits: _ = self.qbit_argument_conversion(ancilla_qubits) try: gate = available_implementations[mode] except KeyError as ex: all_modes = list(available_implementations.keys()) raise ValueError( f"Unsupported mode ({mode}) selected, choose one of {all_modes}" ) from ex if hasattr(gate, "num_ancilla_qubits") and gate.num_ancilla_qubits > 0: required = gate.num_ancilla_qubits if ancilla_qubits is None: raise AttributeError(f"No ancillas provided, but {required} are needed!") # convert ancilla qubits to a list if they were passed as int or qubit if not hasattr(ancilla_qubits, "__len__"): ancilla_qubits = [ancilla_qubits] if len(ancilla_qubits) < required: actually = len(ancilla_qubits) raise ValueError(f"At least {required} ancillas required, but {actually} given.") # size down if too many ancillas were provided ancilla_qubits = ancilla_qubits[:required] else: ancilla_qubits = [] return self.append(gate, control_qubits[:] + [target_qubit] + ancilla_qubits[:], []) def mct( self, control_qubits: Sequence[QubitSpecifier], target_qubit: QubitSpecifier, ancilla_qubits: QubitSpecifier | Sequence[QubitSpecifier] | None = None, mode: str = "noancilla", ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.MCXGate`. The multi-cX gate can be implemented using different techniques, which use different numbers of ancilla qubits and have varying circuit depth. These modes are: - ``'noancilla'``: Requires 0 ancilla qubits. - ``'recursion'``: Requires 1 ancilla qubit if more than 4 controls are used, otherwise 0. - ``'v-chain'``: Requires 2 less ancillas than the number of control qubits. - ``'v-chain-dirty'``: Same as for the clean ancillas (but the circuit will be longer). For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubits: The qubits used as the controls. target_qubit: The qubit(s) targeted by the gate. ancilla_qubits: The qubits used as the ancillae, if the mode requires them. mode: The choice of mode, explained further above. Returns: A handle to the instructions created. Raises: ValueError: if the given mode is not known, or if too few ancilla qubits are passed. AttributeError: if no ancilla qubits are passed, but some are needed. See Also: QuantumCircuit.mcx: the same gate with a different name. """ return self.mcx(control_qubits, target_qubit, ancilla_qubits, mode) def y(self, qubit: QubitSpecifier) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.YGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.y import YGate return self.append(YGate(), [qubit], []) def cy( self, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.CYGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the controls. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.y import CYGate return self.append( CYGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [] ) def z(self, qubit: QubitSpecifier) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.ZGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.z import ZGate return self.append(ZGate(), [qubit], []) def cz( self, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.CZGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the controls. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.z import CZGate return self.append( CZGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [] ) def ccz( self, control_qubit1: QubitSpecifier, control_qubit2: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.CCZGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit1: The qubit(s) used as the first control. control_qubit2: The qubit(s) used as the second control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '10'). Defaults to controlling on the '11' state. Returns: A handle to the instructions created. """ from .library.standard_gates.z import CCZGate return self.append( CCZGate(label=label, ctrl_state=ctrl_state), [control_qubit1, control_qubit2, target_qubit], [], ) def pauli( self, pauli_string: str, qubits: Sequence[QubitSpecifier], ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.PauliGate`. Args: pauli_string: A string representing the Pauli operator to apply, e.g. 'XX'. qubits: The qubits to apply this gate to. Returns: A handle to the instructions created. """ from qiskit.circuit.library.generalized_gates.pauli import PauliGate return self.append(PauliGate(pauli_string), qubits, []) def _push_scope( self, qubits: Iterable[Qubit] = (), clbits: Iterable[Clbit] = (), registers: Iterable[Register] = (), allow_jumps: bool = True, forbidden_message: Optional[str] = None, ): """Add a scope for collecting instructions into this circuit. This should only be done by the control-flow context managers, which will handle cleaning up after themselves at the end as well. Args: qubits: Any qubits that this scope should automatically use. clbits: Any clbits that this scope should automatically use. allow_jumps: Whether this scope allows jumps to be used within it. forbidden_message: If given, all attempts to add instructions to this scope will raise a :exc:`.CircuitError` with this message. """ # pylint: disable=cyclic-import from qiskit.circuit.controlflow.builder import ControlFlowBuilderBlock # Chain resource requests so things like registers added to inner scopes via conditions are # requested in the outer scope as well. if self._control_flow_scopes: resource_requester = self._control_flow_scopes[-1].request_classical_resource else: resource_requester = self._resolve_classical_resource self._control_flow_scopes.append( ControlFlowBuilderBlock( qubits, clbits, resource_requester=resource_requester, registers=registers, allow_jumps=allow_jumps, forbidden_message=forbidden_message, ) ) def _pop_scope(self) -> "qiskit.circuit.controlflow.builder.ControlFlowBuilderBlock": """Finish a scope used in the control-flow builder interface, and return it to the caller. This should only be done by the control-flow context managers, since they naturally synchronise the creation and deletion of stack elements.""" return self._control_flow_scopes.pop() def _peek_previous_instruction_in_scope(self) -> CircuitInstruction: """Return the instruction 3-tuple of the most recent instruction in the current scope, even if that scope is currently under construction. This function is only intended for use by the control-flow ``if``-statement builders, which may need to modify a previous instruction.""" if self._control_flow_scopes: return self._control_flow_scopes[-1].peek() if not self._data: raise CircuitError("This circuit contains no instructions.") return self._data[-1] def _pop_previous_instruction_in_scope(self) -> CircuitInstruction: """Return the instruction 3-tuple of the most recent instruction in the current scope, even if that scope is currently under construction, and remove it from that scope. This function is only intended for use by the control-flow ``if``-statement builders, which may need to replace a previous instruction with another. """ if self._control_flow_scopes: return self._control_flow_scopes[-1].pop() if not self._data: raise CircuitError("This circuit contains no instructions.") instruction = self._data.pop() if isinstance(instruction.operation, Instruction): self._update_parameter_table_on_instruction_removal(instruction) return instruction def _update_parameter_table_on_instruction_removal(self, instruction: CircuitInstruction): """Update the :obj:`.ParameterTable` of this circuit given that an instance of the given ``instruction`` has just been removed from the circuit. .. note:: This does not account for the possibility for the same instruction instance being added more than once to the circuit. At the time of writing (2021-11-17, main commit 271a82f) there is a defensive ``deepcopy`` of parameterised instructions inside :meth:`.QuantumCircuit.append`, so this should be safe. Trying to account for it would involve adding a potentially quadratic-scaling loop to check each entry in ``data``. """ atomic_parameters: list[tuple[Parameter, int]] = [] for index, parameter in enumerate(instruction.operation.params): if isinstance(parameter, (ParameterExpression, QuantumCircuit)): atomic_parameters.extend((p, index) for p in parameter.parameters) for atomic_parameter, index in atomic_parameters: new_entries = self._parameter_table[atomic_parameter].copy() new_entries.discard((instruction.operation, index)) if not new_entries: del self._parameter_table[atomic_parameter] # Invalidate cache. self._parameters = None else: self._parameter_table[atomic_parameter] = new_entries @typing.overload def while_loop( self, condition: tuple[ClassicalRegister | Clbit, int] | expr.Expr, body: None, qubits: None, clbits: None, *, label: str | None, ) -> "qiskit.circuit.controlflow.while_loop.WhileLoopContext": ... @typing.overload def while_loop( self, condition: tuple[ClassicalRegister | Clbit, int] | expr.Expr, body: "QuantumCircuit", qubits: Sequence[QubitSpecifier], clbits: Sequence[ClbitSpecifier], *, label: str | None, ) -> InstructionSet: ... def while_loop(self, condition, body=None, qubits=None, clbits=None, *, label=None): """Create a ``while`` loop on this circuit. There are two forms for calling this function. If called with all its arguments (with the possible exception of ``label``), it will create a :obj:`~qiskit.circuit.controlflow.WhileLoopOp` with the given ``body``. If ``body`` (and ``qubits`` and ``clbits``) are *not* passed, then this acts as a context manager, which will automatically build a :obj:`~qiskit.circuit.controlflow.WhileLoopOp` when the scope finishes. In this form, you do not need to keep track of the qubits or clbits you are using, because the scope will handle it for you. Example usage:: from qiskit.circuit import QuantumCircuit, Clbit, Qubit bits = [Qubit(), Qubit(), Clbit()] qc = QuantumCircuit(bits) with qc.while_loop((bits[2], 0)): qc.h(0) qc.cx(0, 1) qc.measure(0, 0) Args: condition (Tuple[Union[ClassicalRegister, Clbit], int]): An equality condition to be checked prior to executing ``body``. The left-hand side of the condition must be a :obj:`~ClassicalRegister` or a :obj:`~Clbit`, and the right-hand side must be an integer or boolean. body (Optional[QuantumCircuit]): The loop body to be repeatedly executed. Omit this to use the context-manager mode. qubits (Optional[Sequence[Qubit]]): The circuit qubits over which the loop body should be run. Omit this to use the context-manager mode. clbits (Optional[Sequence[Clbit]]): The circuit clbits over which the loop body should be run. Omit this to use the context-manager mode. label (Optional[str]): The string label of the instruction in the circuit. Returns: InstructionSet or WhileLoopContext: If used in context-manager mode, then this should be used as a ``with`` resource, which will infer the block content and operands on exit. If the full form is used, then this returns a handle to the instructions created. Raises: CircuitError: if an incorrect calling convention is used. """ # pylint: disable=cyclic-import from qiskit.circuit.controlflow.while_loop import WhileLoopOp, WhileLoopContext if isinstance(condition, expr.Expr): condition = self._validate_expr(condition) else: condition = (self._resolve_classical_resource(condition[0]), condition[1]) if body is None: if qubits is not None or clbits is not None: raise CircuitError( "When using 'while_loop' as a context manager," " you cannot pass qubits or clbits." ) return WhileLoopContext(self, condition, label=label) elif qubits is None or clbits is None: raise CircuitError( "When using 'while_loop' with a body, you must pass qubits and clbits." ) return self.append(WhileLoopOp(condition, body, label), qubits, clbits) @typing.overload def for_loop( self, indexset: Iterable[int], loop_parameter: Parameter | None, body: None, qubits: None, clbits: None, *, label: str | None, ) -> "qiskit.circuit.controlflow.for_loop.ForLoopContext": ... @typing.overload def for_loop( self, indexset: Iterable[int], loop_parameter: Union[Parameter, None], body: "QuantumCircuit", qubits: Sequence[QubitSpecifier], clbits: Sequence[ClbitSpecifier], *, label: str | None, ) -> InstructionSet: ... def for_loop( self, indexset, loop_parameter=None, body=None, qubits=None, clbits=None, *, label=None ): """Create a ``for`` loop on this circuit. There are two forms for calling this function. If called with all its arguments (with the possible exception of ``label``), it will create a :class:`~qiskit.circuit.ForLoopOp` with the given ``body``. If ``body`` (and ``qubits`` and ``clbits``) are *not* passed, then this acts as a context manager, which, when entered, provides a loop variable (unless one is given, in which case it will be reused) and will automatically build a :class:`~qiskit.circuit.ForLoopOp` when the scope finishes. In this form, you do not need to keep track of the qubits or clbits you are using, because the scope will handle it for you. For example:: from qiskit import QuantumCircuit qc = QuantumCircuit(2, 1) with qc.for_loop(range(5)) as i: qc.h(0) qc.cx(0, 1) qc.measure(0, 0) qc.break_loop().c_if(0, True) Args: indexset (Iterable[int]): A collection of integers to loop over. Always necessary. loop_parameter (Optional[Parameter]): The parameter used within ``body`` to which the values from ``indexset`` will be assigned. In the context-manager form, if this argument is not supplied, then a loop parameter will be allocated for you and returned as the value of the ``with`` statement. This will only be bound into the circuit if it is used within the body. If this argument is ``None`` in the manual form of this method, ``body`` will be repeated once for each of the items in ``indexset`` but their values will be ignored. body (Optional[QuantumCircuit]): The loop body to be repeatedly executed. Omit this to use the context-manager mode. qubits (Optional[Sequence[QubitSpecifier]]): The circuit qubits over which the loop body should be run. Omit this to use the context-manager mode. clbits (Optional[Sequence[ClbitSpecifier]]): The circuit clbits over which the loop body should be run. Omit this to use the context-manager mode. label (Optional[str]): The string label of the instruction in the circuit. Returns: InstructionSet or ForLoopContext: depending on the call signature, either a context manager for creating the for loop (it will automatically be added to the circuit at the end of the block), or an :obj:`~InstructionSet` handle to the appended loop operation. Raises: CircuitError: if an incorrect calling convention is used. """ # pylint: disable=cyclic-import from qiskit.circuit.controlflow.for_loop import ForLoopOp, ForLoopContext if body is None: if qubits is not None or clbits is not None: raise CircuitError( "When using 'for_loop' as a context manager, you cannot pass qubits or clbits." ) return ForLoopContext(self, indexset, loop_parameter, label=label) elif qubits is None or clbits is None: raise CircuitError( "When using 'for_loop' with a body, you must pass qubits and clbits." ) return self.append(ForLoopOp(indexset, loop_parameter, body, label), qubits, clbits) @typing.overload def if_test( self, condition: tuple[ClassicalRegister | Clbit, int], true_body: None, qubits: None, clbits: None, *, label: str | None, ) -> "qiskit.circuit.controlflow.if_else.IfContext": ... @typing.overload def if_test( self, condition: tuple[ClassicalRegister | Clbit, int], true_body: "QuantumCircuit", qubits: Sequence[QubitSpecifier], clbits: Sequence[ClbitSpecifier], *, label: str | None = None, ) -> InstructionSet: ... def if_test( self, condition, true_body=None, qubits=None, clbits=None, *, label=None, ): """Create an ``if`` statement on this circuit. There are two forms for calling this function. If called with all its arguments (with the possible exception of ``label``), it will create a :obj:`~qiskit.circuit.IfElseOp` with the given ``true_body``, and there will be no branch for the ``false`` condition (see also the :meth:`.if_else` method). However, if ``true_body`` (and ``qubits`` and ``clbits``) are *not* passed, then this acts as a context manager, which can be used to build ``if`` statements. The return value of the ``with`` statement is a chainable context manager, which can be used to create subsequent ``else`` blocks. In this form, you do not need to keep track of the qubits or clbits you are using, because the scope will handle it for you. For example:: from qiskit.circuit import QuantumCircuit, Qubit, Clbit bits = [Qubit(), Qubit(), Qubit(), Clbit(), Clbit()] qc = QuantumCircuit(bits) qc.h(0) qc.cx(0, 1) qc.measure(0, 0) qc.h(0) qc.cx(0, 1) qc.measure(0, 1) with qc.if_test((bits[3], 0)) as else_: qc.x(2) with else_: qc.h(2) qc.z(2) Args: condition (Tuple[Union[ClassicalRegister, Clbit], int]): A condition to be evaluated at circuit runtime which, if true, will trigger the evaluation of ``true_body``. Can be specified as either a tuple of a ``ClassicalRegister`` to be tested for equality with a given ``int``, or as a tuple of a ``Clbit`` to be compared to either a ``bool`` or an ``int``. true_body (Optional[QuantumCircuit]): The circuit body to be run if ``condition`` is true. qubits (Optional[Sequence[QubitSpecifier]]): The circuit qubits over which the if/else should be run. clbits (Optional[Sequence[ClbitSpecifier]]): The circuit clbits over which the if/else should be run. label (Optional[str]): The string label of the instruction in the circuit. Returns: InstructionSet or IfContext: depending on the call signature, either a context manager for creating the ``if`` block (it will automatically be added to the circuit at the end of the block), or an :obj:`~InstructionSet` handle to the appended conditional operation. Raises: CircuitError: If the provided condition references Clbits outside the enclosing circuit. CircuitError: if an incorrect calling convention is used. Returns: A handle to the instruction created. """ # pylint: disable=cyclic-import from qiskit.circuit.controlflow.if_else import IfElseOp, IfContext if isinstance(condition, expr.Expr): condition = self._validate_expr(condition) else: condition = (self._resolve_classical_resource(condition[0]), condition[1]) if true_body is None: if qubits is not None or clbits is not None: raise CircuitError( "When using 'if_test' as a context manager, you cannot pass qubits or clbits." ) # We can only allow jumps if we're in a loop block, but the default path (no scopes) # also allows adding jumps to support the more verbose internal mode. in_loop = bool(self._control_flow_scopes and self._control_flow_scopes[-1].allow_jumps) return IfContext(self, condition, in_loop=in_loop, label=label) elif qubits is None or clbits is None: raise CircuitError("When using 'if_test' with a body, you must pass qubits and clbits.") return self.append(IfElseOp(condition, true_body, None, label), qubits, clbits) def if_else( self, condition: tuple[ClassicalRegister, int] | tuple[Clbit, int] | tuple[Clbit, bool], true_body: "QuantumCircuit", false_body: "QuantumCircuit", qubits: Sequence[QubitSpecifier], clbits: Sequence[ClbitSpecifier], label: str | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.IfElseOp`. .. note:: This method does not have an associated context-manager form, because it is already handled by the :meth:`.if_test` method. You can use the ``else`` part of that with something such as:: from qiskit.circuit import QuantumCircuit, Qubit, Clbit bits = [Qubit(), Qubit(), Clbit()] qc = QuantumCircuit(bits) qc.h(0) qc.cx(0, 1) qc.measure(0, 0) with qc.if_test((bits[2], 0)) as else_: qc.h(0) with else_: qc.x(0) Args: condition: A condition to be evaluated at circuit runtime which, if true, will trigger the evaluation of ``true_body``. Can be specified as either a tuple of a ``ClassicalRegister`` to be tested for equality with a given ``int``, or as a tuple of a ``Clbit`` to be compared to either a ``bool`` or an ``int``. true_body: The circuit body to be run if ``condition`` is true. false_body: The circuit to be run if ``condition`` is false. qubits: The circuit qubits over which the if/else should be run. clbits: The circuit clbits over which the if/else should be run. label: The string label of the instruction in the circuit. Raises: CircuitError: If the provided condition references Clbits outside the enclosing circuit. Returns: A handle to the instruction created. """ # pylint: disable=cyclic-import from qiskit.circuit.controlflow.if_else import IfElseOp if isinstance(condition, expr.Expr): condition = self._validate_expr(condition) else: condition = (self._resolve_classical_resource(condition[0]), condition[1]) return self.append(IfElseOp(condition, true_body, false_body, label), qubits, clbits) @typing.overload def switch( self, target: Union[ClbitSpecifier, ClassicalRegister], cases: None, qubits: None, clbits: None, *, label: Optional[str], ) -> "qiskit.circuit.controlflow.switch_case.SwitchContext": ... @typing.overload def switch( self, target: Union[ClbitSpecifier, ClassicalRegister], cases: Iterable[Tuple[typing.Any, QuantumCircuit]], qubits: Sequence[QubitSpecifier], clbits: Sequence[ClbitSpecifier], *, label: Optional[str], ) -> InstructionSet: ... def switch(self, target, cases=None, qubits=None, clbits=None, *, label=None): """Create a ``switch``/``case`` structure on this circuit. There are two forms for calling this function. If called with all its arguments (with the possible exception of ``label``), it will create a :class:`.SwitchCaseOp` with the given case structure. If ``cases`` (and ``qubits`` and ``clbits``) are *not* passed, then this acts as a context manager, which will automatically build a :class:`.SwitchCaseOp` when the scope finishes. In this form, you do not need to keep track of the qubits or clbits you are using, because the scope will handle it for you. Example usage:: from qiskit.circuit import QuantumCircuit, ClassicalRegister, QuantumRegister qreg = QuantumRegister(3) creg = ClassicalRegister(3) qc = QuantumCircuit(qreg, creg) qc.h([0, 1, 2]) qc.measure([0, 1, 2], [0, 1, 2]) with qc.switch(creg) as case: with case(0): qc.x(0) with case(1, 2): qc.z(1) with case(case.DEFAULT): qc.cx(0, 1) Args: target (Union[ClassicalRegister, Clbit]): The classical value to switch one. This must be integer-like. cases (Iterable[Tuple[typing.Any, QuantumCircuit]]): A sequence of case specifiers. Each tuple defines one case body (the second item). The first item of the tuple can be either a single integer value, the special value :data:`.CASE_DEFAULT`, or a tuple of several integer values. Each of the integer values will be tried in turn; control will then pass to the body corresponding to the first match. :data:`.CASE_DEFAULT` matches all possible values. Omit in context-manager form. qubits (Sequence[Qubit]): The circuit qubits over which all case bodies execute. Omit in context-manager form. clbits (Sequence[Clbit]): The circuit clbits over which all case bodies execute. Omit in context-manager form. label (Optional[str]): The string label of the instruction in the circuit. Returns: InstructionSet or SwitchCaseContext: If used in context-manager mode, then this should be used as a ``with`` resource, which will return an object that can be repeatedly entered to produce cases for the switch statement. If the full form is used, then this returns a handle to the instructions created. Raises: CircuitError: if an incorrect calling convention is used. """ # pylint: disable=cyclic-import from qiskit.circuit.controlflow.switch_case import SwitchCaseOp, SwitchContext if isinstance(target, expr.Expr): target = self._validate_expr(target) else: target = self._resolve_classical_resource(target) if cases is None: if qubits is not None or clbits is not None: raise CircuitError( "When using 'switch' as a context manager, you cannot pass qubits or clbits." ) in_loop = bool(self._control_flow_scopes and self._control_flow_scopes[-1].allow_jumps) return SwitchContext(self, target, in_loop=in_loop, label=label) if qubits is None or clbits is None: raise CircuitError("When using 'switch' with cases, you must pass qubits and clbits.") return self.append(SwitchCaseOp(target, cases, label=label), qubits, clbits) def break_loop(self) -> InstructionSet: """Apply :class:`~qiskit.circuit.BreakLoopOp`. .. warning:: If you are using the context-manager "builder" forms of :meth:`.if_test`, :meth:`.for_loop` or :meth:`.while_loop`, you can only call this method if you are within a loop context, because otherwise the "resource width" of the operation cannot be determined. This would quickly lead to invalid circuits, and so if you are trying to construct a reusable loop body (without the context managers), you must also use the non-context-manager form of :meth:`.if_test` and :meth:`.if_else`. Take care that the :obj:`.BreakLoopOp` instruction must span all the resources of its containing loop, not just the immediate scope. Returns: A handle to the instruction created. Raises: CircuitError: if this method was called within a builder context, but not contained within a loop. """ # pylint: disable=cyclic-import from qiskit.circuit.controlflow.break_loop import BreakLoopOp, BreakLoopPlaceholder if self._control_flow_scopes: operation = BreakLoopPlaceholder() resources = operation.placeholder_resources() return self.append(operation, resources.qubits, resources.clbits) return self.append(BreakLoopOp(self.num_qubits, self.num_clbits), self.qubits, self.clbits) def continue_loop(self) -> InstructionSet: """Apply :class:`~qiskit.circuit.ContinueLoopOp`. .. warning:: If you are using the context-manager "builder" forms of :meth:`.if_test`, :meth:`.for_loop` or :meth:`.while_loop`, you can only call this method if you are within a loop context, because otherwise the "resource width" of the operation cannot be determined. This would quickly lead to invalid circuits, and so if you are trying to construct a reusable loop body (without the context managers), you must also use the non-context-manager form of :meth:`.if_test` and :meth:`.if_else`. Take care that the :class:`~qiskit.circuit.ContinueLoopOp` instruction must span all the resources of its containing loop, not just the immediate scope. Returns: A handle to the instruction created. Raises: CircuitError: if this method was called within a builder context, but not contained within a loop. """ # pylint: disable=cyclic-import from qiskit.circuit.controlflow.continue_loop import ContinueLoopOp, ContinueLoopPlaceholder if self._control_flow_scopes: operation = ContinueLoopPlaceholder() resources = operation.placeholder_resources() return self.append(operation, resources.qubits, resources.clbits) return self.append( ContinueLoopOp(self.num_qubits, self.num_clbits), self.qubits, self.clbits ) def add_calibration( self, gate: Union[Gate, str], qubits: Sequence[int], # Schedule has the type `qiskit.pulse.Schedule`, but `qiskit.pulse` cannot be imported # while this module is, and so Sphinx will not accept a forward reference to it. Sphinx # needs the types available at runtime, whereas mypy will accept it, because it handles the # type checking by static analysis. schedule, params: Sequence[ParameterValueType] | None = None, ) -> None: """Register a low-level, custom pulse definition for the given gate. Args: gate (Union[Gate, str]): Gate information. qubits (Union[int, Tuple[int]]): List of qubits to be measured. schedule (Schedule): Schedule information. params (Optional[List[Union[float, Parameter]]]): A list of parameters. Raises: Exception: if the gate is of type string and params is None. """ def _format(operand): try: # Using float/complex value as a dict key is not good idea. # This makes the mapping quite sensitive to the rounding error. # However, the mechanism is already tied to the execution model (i.e. pulse gate) # and we cannot easily update this rule. # The same logic exists in DAGCircuit.add_calibration. evaluated = complex(operand) if np.isreal(evaluated): evaluated = float(evaluated.real) if evaluated.is_integer(): evaluated = int(evaluated) return evaluated except TypeError: # Unassigned parameter return operand if isinstance(gate, Gate): params = gate.params gate = gate.name if params is not None: params = tuple(map(_format, params)) else: params = () self._calibrations[gate][(tuple(qubits), params)] = schedule # Functions only for scheduled circuits def qubit_duration(self, *qubits: Union[Qubit, int]) -> float: """Return the duration between the start and stop time of the first and last instructions, excluding delays, over the supplied qubits. Its time unit is ``self.unit``. Args: *qubits: Qubits within ``self`` to include. Returns: Return the duration between the first start and last stop time of non-delay instructions """ return self.qubit_stop_time(*qubits) - self.qubit_start_time(*qubits) def qubit_start_time(self, *qubits: Union[Qubit, int]) -> float: """Return the start time of the first instruction, excluding delays, over the supplied qubits. Its time unit is ``self.unit``. Return 0 if there are no instructions over qubits Args: *qubits: Qubits within ``self`` to include. Integers are allowed for qubits, indicating indices of ``self.qubits``. Returns: Return the start time of the first instruction, excluding delays, over the qubits Raises: CircuitError: if ``self`` is a not-yet scheduled circuit. """ if self.duration is None: # circuit has only delays, this is kind of scheduled for instruction in self._data: if not isinstance(instruction.operation, Delay): raise CircuitError( "qubit_start_time undefined. Circuit must be scheduled first." ) return 0 qubits = [self.qubits[q] if isinstance(q, int) else q for q in qubits] starts = {q: 0 for q in qubits} dones = {q: False for q in qubits} for instruction in self._data: for q in qubits: if q in instruction.qubits: if isinstance(instruction.operation, Delay): if not dones[q]: starts[q] += instruction.operation.duration else: dones[q] = True if len(qubits) == len([done for done in dones.values() if done]): # all done return min(start for start in starts.values()) return 0 # If there are no instructions over bits def qubit_stop_time(self, *qubits: Union[Qubit, int]) -> float: """Return the stop time of the last instruction, excluding delays, over the supplied qubits. Its time unit is ``self.unit``. Return 0 if there are no instructions over qubits Args: *qubits: Qubits within ``self`` to include. Integers are allowed for qubits, indicating indices of ``self.qubits``. Returns: Return the stop time of the last instruction, excluding delays, over the qubits Raises: CircuitError: if ``self`` is a not-yet scheduled circuit. """ if self.duration is None: # circuit has only delays, this is kind of scheduled for instruction in self._data: if not isinstance(instruction.operation, Delay): raise CircuitError( "qubit_stop_time undefined. Circuit must be scheduled first." ) return 0 qubits = [self.qubits[q] if isinstance(q, int) else q for q in qubits] stops = {q: self.duration for q in qubits} dones = {q: False for q in qubits} for instruction in reversed(self._data): for q in qubits: if q in instruction.qubits: if isinstance(instruction.operation, Delay): if not dones[q]: stops[q] -= instruction.operation.duration else: dones[q] = True if len(qubits) == len([done for done in dones.values() if done]): # all done return max(stop for stop in stops.values()) return 0 # If there are no instructions over bits class _ParameterBindsDict: __slots__ = ("mapping", "allowed_keys") def __init__(self, mapping, allowed_keys): self.mapping = mapping self.allowed_keys = allowed_keys def items(self): """Iterator through all the keys in the mapping that we care about. Wrapping the main mapping allows us to avoid reconstructing a new 'dict', but just use the given 'mapping' without any copy / reconstruction.""" for parameter, value in self.mapping.items(): if parameter in self.allowed_keys: yield parameter, value class _ParameterBindsSequence: __slots__ = ("parameters", "values", "mapping_cache") def __init__(self, parameters, values): self.parameters = parameters self.values = values self.mapping_cache = None def items(self): """Iterator through all the keys in the mapping that we care about.""" return zip(self.parameters, self.values) @property def mapping(self): """Cached version of a mapping. This is only generated on demand.""" if self.mapping_cache is None: self.mapping_cache = dict(zip(self.parameters, self.values)) return self.mapping_cache # Used by the OQ2 exporter. Just needs to have enough parameters to support the largest standard # (non-controlled) gate in our standard library. We have to use the same `Parameter` instances each # time so the equality comparisons will work. _QASM2_FIXED_PARAMETERS = [Parameter("param0"), Parameter("param1"), Parameter("param2")] def _qasm2_custom_operation_statement( instruction, existing_gate_names, gates_to_define, bit_labels ): operation = _qasm2_define_custom_operation( instruction.operation, existing_gate_names, gates_to_define ) # Insert qasm representation of the original instruction if instruction.clbits: bits = itertools.chain(instruction.qubits, instruction.clbits) else: bits = instruction.qubits bits_qasm = ",".join(bit_labels[j] for j in bits) instruction_qasm = f"{_instruction_qasm2(operation)} {bits_qasm};" return instruction_qasm def _qasm2_define_custom_operation(operation, existing_gate_names, gates_to_define): """Extract a custom definition from the given operation, and append any necessary additional subcomponents' definitions to the ``gates_to_define`` ordered dictionary. Returns a potentially new :class:`.Instruction`, which should be used for the :meth:`~.Instruction.qasm` call (it may have been renamed).""" # pylint: disable=cyclic-import from qiskit.circuit import library as lib from qiskit.qasm2 import QASM2ExportError if operation.name in existing_gate_names: return operation # Check instructions names or label are valid escaped = _qasm_escape_name(operation.name, "gate_") if escaped != operation.name: operation = operation.copy(name=escaped) # These are built-in gates that are known to be safe to construct by passing the correct number # of `Parameter` instances positionally, and have no other information. We can't guarantee that # if they've been subclassed, though. This is a total hack; ideally we'd be able to inspect the # "calling" signatures of Qiskit `Gate` objects to know whether they're safe to re-parameterise. known_good_parameterized = { lib.PhaseGate, lib.RGate, lib.RXGate, lib.RXXGate, lib.RYGate, lib.RYYGate, lib.RZGate, lib.RZXGate, lib.RZZGate, lib.XXMinusYYGate, lib.XXPlusYYGate, lib.UGate, lib.U1Gate, lib.U2Gate, lib.U3Gate, } # In known-good situations we want to use a manually parametrised object as the source of the # definition, but still continue to return the given object as the call-site object. if type(operation) in known_good_parameterized: parameterized_operation = type(operation)(*_QASM2_FIXED_PARAMETERS[: len(operation.params)]) elif hasattr(operation, "_qasm2_decomposition"): new_op = operation._qasm2_decomposition() parameterized_operation = operation = new_op.copy( name=_qasm_escape_name(new_op.name, "gate_") ) else: parameterized_operation = operation # If there's an _equal_ operation in the existing circuits to be defined, then our job is done. previous_definition_source, _ = gates_to_define.get(operation.name, (None, None)) if parameterized_operation == previous_definition_source: return operation # Otherwise, if there's a naming clash, we need a unique name. if operation.name in gates_to_define: operation = _rename_operation(operation) new_name = operation.name if parameterized_operation.params: parameters_qasm = ( "(" + ",".join(f"param{i}" for i in range(len(parameterized_operation.params))) + ")" ) else: parameters_qasm = "" if operation.num_qubits == 0: raise QASM2ExportError( f"OpenQASM 2 cannot represent '{operation.name}, which acts on zero qubits." ) if operation.num_clbits != 0: raise QASM2ExportError( f"OpenQASM 2 cannot represent '{operation.name}', which acts on {operation.num_clbits}" " classical bits." ) qubits_qasm = ",".join(f"q{i}" for i in range(parameterized_operation.num_qubits)) parameterized_definition = getattr(parameterized_operation, "definition", None) if parameterized_definition is None: gates_to_define[new_name] = ( parameterized_operation, f"opaque {new_name}{parameters_qasm} {qubits_qasm};", ) else: qubit_labels = {bit: f"q{i}" for i, bit in enumerate(parameterized_definition.qubits)} body_qasm = " ".join( _qasm2_custom_operation_statement( instruction, existing_gate_names, gates_to_define, qubit_labels ) for instruction in parameterized_definition.data ) # if an inner operation has the same name as the actual operation, it needs to be renamed if operation.name in gates_to_define: operation = _rename_operation(operation) new_name = operation.name definition_qasm = f"gate {new_name}{parameters_qasm} {qubits_qasm} {{ {body_qasm} }}" gates_to_define[new_name] = (parameterized_operation, definition_qasm) return operation def _rename_operation(operation): """Returns the operation with a new name following this pattern: {operation name}_{operation id}""" new_name = f"{operation.name}_{id(operation)}" updated_operation = operation.copy(name=new_name) return updated_operation def _qasm_escape_name(name: str, prefix: str) -> str: """Returns a valid OpenQASM identifier, using `prefix` as a prefix if necessary. `prefix` must itself be a valid identifier.""" # Replace all non-ASCII-word characters (letters, digits, underscore) with the underscore. escaped_name = re.sub(r"\W", "_", name, flags=re.ASCII) if ( not escaped_name or escaped_name[0] not in string.ascii_lowercase or escaped_name in QASM2_RESERVED ): escaped_name = prefix + escaped_name return escaped_name def _instruction_qasm2(operation): """Return an OpenQASM 2 string for the instruction.""" from qiskit.qasm2 import QASM2ExportError # pylint: disable=cyclic-import if operation.name == "c3sx": qasm2_call = "c3sqrtx" else: qasm2_call = operation.name if operation.params: qasm2_call = "{}({})".format( qasm2_call, ",".join([pi_check(i, output="qasm", eps=1e-12) for i in operation.params]), ) if operation.condition is not None: if not isinstance(operation.condition[0], ClassicalRegister): raise QASM2ExportError( "OpenQASM 2 can only condition on registers, but got '{operation.condition[0]}'" ) qasm2_call = ( "if(%s==%d) " % (operation.condition[0].name, operation.condition[1]) + qasm2_call ) return qasm2_call def _make_unique(name: str, already_defined: collections.abc.Set[str]) -> str: """Generate a name by suffixing the given stem that is unique within the defined set.""" if name not in already_defined: return name used = {in_use[len(name) :] for in_use in already_defined if in_use.startswith(name)} characters = (string.digits + string.ascii_letters) if name else string.ascii_letters for parts in itertools.chain.from_iterable( itertools.product(characters, repeat=n) for n in itertools.count(1) ): suffix = "".join(parts) if suffix not in used: return name + suffix # This isn't actually reachable because the above loop is infinite. return name def _bit_argument_conversion(specifier, bit_sequence, bit_set, type_) -> list[Bit]: """Get the list of bits referred to by the specifier ``specifier``. Valid types for ``specifier`` are integers, bits of the correct type (as given in ``type_``), or iterables of one of those two scalar types. Integers are interpreted as indices into the sequence ``bit_sequence``. All allowed bits must be in ``bit_set`` (which should implement fast lookup), which is assumed to contain the same bits as ``bit_sequence``. Returns: List[Bit]: a list of the specified bits from ``bits``. Raises: CircuitError: if an incorrect type or index is encountered, if the same bit is specified more than once, or if the specifier is to a bit not in the ``bit_set``. """ # The duplication between this function and `_bit_argument_conversion_scalar` is so that fast # paths return as quickly as possible, and all valid specifiers will resolve without needing to # try/catch exceptions (which is too slow for inner-loop code). if isinstance(specifier, type_): if specifier in bit_set: return [specifier] raise CircuitError(f"Bit '{specifier}' is not in the circuit.") if isinstance(specifier, (int, np.integer)): try: return [bit_sequence[specifier]] except IndexError as ex: raise CircuitError( f"Index {specifier} out of range for size {len(bit_sequence)}." ) from ex # Slices can't raise IndexError - they just return an empty list. if isinstance(specifier, slice): return bit_sequence[specifier] try: return [ _bit_argument_conversion_scalar(index, bit_sequence, bit_set, type_) for index in specifier ] except TypeError as ex: message = ( f"Incorrect bit type: expected '{type_.__name__}' but got '{type(specifier).__name__}'" if isinstance(specifier, Bit) else f"Invalid bit index: '{specifier}' of type '{type(specifier)}'" ) raise CircuitError(message) from ex def _bit_argument_conversion_scalar(specifier, bit_sequence, bit_set, type_): if isinstance(specifier, type_): if specifier in bit_set: return specifier raise CircuitError(f"Bit '{specifier}' is not in the circuit.") if isinstance(specifier, (int, np.integer)): try: return bit_sequence[specifier] except IndexError as ex: raise CircuitError( f"Index {specifier} out of range for size {len(bit_sequence)}." ) from ex message = ( f"Incorrect bit type: expected '{type_.__name__}' but got '{type(specifier).__name__}'" if isinstance(specifier, Bit) else f"Invalid bit index: '{specifier}' of type '{type(specifier)}'" ) raise CircuitError(message)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- 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=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """User-space constructor functions for the expression tree, which do some of the inference and lifting boilerplate work.""" # pylint: disable=redefined-builtin,redefined-outer-name from __future__ import annotations __all__ = [ "lift", "bit_not", "logic_not", "bit_and", "bit_or", "bit_xor", "logic_and", "logic_or", "equal", "not_equal", "less", "less_equal", "greater", "greater_equal", "lift_legacy_condition", ] import enum import typing from .expr import Expr, Var, Value, Unary, Binary, Cast from .. import types if typing.TYPE_CHECKING: import qiskit class _CastKind(enum.Enum): EQUAL = enum.auto() """The two types are equal; no cast node is required at all.""" IMPLICIT = enum.auto() """The 'from' type can be cast to the 'to' type implicitly. A ``Cast(implicit=True)`` node is the minimum required to specify this.""" LOSSLESS = enum.auto() """The 'from' type can be cast to the 'to' type explicitly, and the cast will be lossless. This requires a ``Cast(implicit=False)`` node, but there's no danger from inserting one.""" DANGEROUS = enum.auto() """The 'from' type has a defined cast to the 'to' type, but depending on the value, it may lose data. A user would need to manually specify casts.""" NONE = enum.auto() """There is no casting permitted from the 'from' type to the 'to' type.""" def _uint_cast(from_: types.Uint, to_: types.Uint, /) -> _CastKind: if from_.width == to_.width: return _CastKind.EQUAL if from_.width < to_.width: return _CastKind.LOSSLESS return _CastKind.DANGEROUS _ALLOWED_CASTS = { (types.Bool, types.Bool): lambda _a, _b, /: _CastKind.EQUAL, (types.Bool, types.Uint): lambda _a, _b, /: _CastKind.LOSSLESS, (types.Uint, types.Bool): lambda _a, _b, /: _CastKind.IMPLICIT, (types.Uint, types.Uint): _uint_cast, } def _cast_kind(from_: types.Type, to_: types.Type, /) -> _CastKind: if (coercer := _ALLOWED_CASTS.get((from_.kind, to_.kind))) is None: return _CastKind.NONE return coercer(from_, to_) def _coerce_lossless(expr: Expr, type: types.Type) -> Expr: """Coerce ``expr`` to ``type`` by inserting a suitable :class:`Cast` node, if the cast is lossless. Otherwise, raise a ``TypeError``.""" kind = _cast_kind(expr.type, type) if kind is _CastKind.EQUAL: return expr if kind is _CastKind.IMPLICIT: return Cast(expr, type, implicit=True) if kind is _CastKind.LOSSLESS: return Cast(expr, type, implicit=False) if kind is _CastKind.DANGEROUS: raise TypeError(f"cannot cast '{expr}' to '{type}' without loss of precision") raise TypeError(f"no cast is defined to take '{expr}' to '{type}'") def lift_legacy_condition( condition: tuple[qiskit.circuit.Clbit | qiskit.circuit.ClassicalRegister, int], / ) -> Expr: """Lift a legacy two-tuple equality condition into a new-style :class:`Expr`. Examples: Taking an old-style conditional instruction and getting an :class:`Expr` from its condition:: from qiskit.circuit import ClassicalRegister from qiskit.circuit.library import HGate from qiskit.circuit.classical import expr cr = ClassicalRegister(2) instr = HGate().c_if(cr, 3) lifted = expr.lift_legacy_condition(instr.condition) """ from qiskit.circuit import Clbit # pylint: disable=cyclic-import target, value = condition if isinstance(target, Clbit): bool_ = types.Bool() return Var(target, bool_) if value else Unary(Unary.Op.LOGIC_NOT, Var(target, bool_), bool_) left = Var(target, types.Uint(width=target.size)) if value.bit_length() > target.size: left = Cast(left, types.Uint(width=value.bit_length()), implicit=True) right = Value(value, left.type) return Binary(Binary.Op.EQUAL, left, right, types.Bool()) def lift(value: typing.Any, /, type: types.Type | None = None) -> Expr: """Lift the given Python ``value`` to a :class:`~.expr.Value` or :class:`~.expr.Var`. If an explicit ``type`` is given, the typing in the output will reflect that. Examples: Lifting simple circuit objects to be :class:`~.expr.Var` instances:: >>> from qiskit.circuit import Clbit, ClassicalRegister >>> from qiskit.circuit.classical import expr >>> expr.lift(Clbit()) Var(<clbit>, Bool()) >>> expr.lift(ClassicalRegister(3, "c")) Var(ClassicalRegister(3, "c"), Uint(3)) The type of the return value can be influenced, if the given value could be interpreted losslessly as the given type (use :func:`cast` to perform a full set of casting operations, include lossy ones):: >>> from qiskit.circuit import ClassicalRegister >>> from qiskit.circuit.classical import expr, types >>> expr.lift(ClassicalRegister(3, "c"), types.Uint(5)) Var(ClassicalRegister(3, "c"), Uint(5)) >>> expr.lift(5, types.Uint(4)) Value(5, Uint(4)) """ if isinstance(value, Expr): if type is not None: raise ValueError("use 'cast' to cast existing expressions, not 'lift'") return value from qiskit.circuit import Clbit, ClassicalRegister # pylint: disable=cyclic-import inferred: types.Type if value is True or value is False or isinstance(value, Clbit): inferred = types.Bool() constructor = Value if value is True or value is False else Var elif isinstance(value, ClassicalRegister): inferred = types.Uint(width=value.size) constructor = Var elif isinstance(value, int): if value < 0: raise ValueError("cannot represent a negative value") inferred = types.Uint(width=value.bit_length() or 1) constructor = Value else: raise TypeError(f"failed to infer a type for '{value}'") if type is None: type = inferred if types.is_supertype(type, inferred): return constructor(value, type) raise TypeError( f"the explicit type '{type}' is not suitable for representing '{value}';" f" it must be non-strict supertype of '{inferred}'" ) def cast(operand: typing.Any, type: types.Type, /) -> Expr: """Create an explicit cast from the given value to the given type. Examples: Add an explicit cast node that explicitly casts a higher precision type to a lower precision one:: >>> from qiskit.circuit.classical import expr, types >>> value = expr.value(5, types.Uint(32)) >>> expr.cast(value, types.Uint(8)) Cast(Value(5, types.Uint(32)), types.Uint(8), implicit=False) """ operand = lift(operand) if _cast_kind(operand.type, type) is _CastKind.NONE: raise TypeError(f"cannot cast '{operand}' to '{type}'") return Cast(operand, type) def bit_not(operand: typing.Any, /) -> Expr: """Create a bitwise 'not' expression node from the given value, resolving any implicit casts and lifting the value into a :class:`Value` node if required. Examples: Bitwise negation of a :class:`.ClassicalRegister`:: >>> from qiskit.circuit import ClassicalRegister >>> from qiskit.circuit.classical import expr >>> expr.bit_not(ClassicalRegister(3, "c")) Unary(Unary.Op.BIT_NOT, Var(ClassicalRegister(3, 'c'), Uint(3)), Uint(3)) """ operand = lift(operand) if operand.type.kind not in (types.Bool, types.Uint): raise TypeError(f"cannot apply '{Unary.Op.BIT_NOT}' to type '{operand.type}'") return Unary(Unary.Op.BIT_NOT, operand, operand.type) def logic_not(operand: typing.Any, /) -> Expr: """Create a logical 'not' expression node from the given value, resolving any implicit casts and lifting the value into a :class:`Value` node if required. Examples: Logical negation of a :class:`.ClassicalRegister`:: >>> from qiskit.circuit import ClassicalRegister >>> from qiskit.circuit.classical import expr >>> expr.logic_not(ClassicalRegister(3, "c")) Unary(\ Unary.Op.LOGIC_NOT, \ Cast(Var(ClassicalRegister(3, 'c'), Uint(3)), Bool(), implicit=True), \ Bool()) """ operand = _coerce_lossless(lift(operand), types.Bool()) return Unary(Unary.Op.LOGIC_NOT, operand, operand.type) def _lift_binary_operands(left: typing.Any, right: typing.Any) -> tuple[Expr, Expr]: """Lift two binary operands simultaneously, inferring the widths of integer literals in either position to match the other operand.""" left_int = isinstance(left, int) and not isinstance(left, bool) right_int = isinstance(right, int) and not isinstance(right, bool) if not (left_int or right_int): left = lift(left) right = lift(right) elif not right_int: right = lift(right) if right.type.kind is types.Uint: if left.bit_length() > right.type.width: raise TypeError( f"integer literal '{left}' is wider than the other operand '{right}'" ) left = Value(left, right.type) else: left = lift(left) elif not left_int: left = lift(left) if left.type.kind is types.Uint: if right.bit_length() > left.type.width: raise TypeError( f"integer literal '{right}' is wider than the other operand '{left}'" ) right = Value(right, left.type) else: right = lift(right) else: # Both are `int`, so we take our best case to make things work. uint = types.Uint(max(left.bit_length(), right.bit_length(), 1)) left = Value(left, uint) right = Value(right, uint) return left, right def _binary_bitwise(op: Binary.Op, left: typing.Any, right: typing.Any) -> Expr: left, right = _lift_binary_operands(left, right) type: types.Type if left.type.kind is right.type.kind is types.Bool: type = types.Bool() elif left.type.kind is types.Uint and right.type.kind is types.Uint: if left.type != right.type: raise TypeError( "binary bitwise operations are defined between unsigned integers of the same width," f" but got {left.type.width} and {right.type.width}." ) type = left.type else: raise TypeError(f"invalid types for '{op}': '{left.type}' and '{right.type}'") return Binary(op, left, right, type) def bit_and(left: typing.Any, right: typing.Any, /) -> Expr: """Create a bitwise 'and' expression node from the given value, resolving any implicit casts and lifting the values into :class:`Value` nodes if required. Examples: Bitwise 'and' of a classical register and an integer literal:: >>> from qiskit.circuit import ClassicalRegister >>> from qiskit.circuit.classical import expr >>> expr.bit_and(ClassicalRegister(3, "c"), 0b111) Binary(\ Binary.Op.BIT_AND, \ Var(ClassicalRegister(3, 'c'), Uint(3)), \ Value(7, Uint(3)), \ Uint(3)) """ return _binary_bitwise(Binary.Op.BIT_AND, left, right) def bit_or(left: typing.Any, right: typing.Any, /) -> Expr: """Create a bitwise 'or' expression node from the given value, resolving any implicit casts and lifting the values into :class:`Value` nodes if required. Examples: Bitwise 'or' of a classical register and an integer literal:: >>> from qiskit.circuit import ClassicalRegister >>> from qiskit.circuit.classical import expr >>> expr.bit_or(ClassicalRegister(3, "c"), 0b101) Binary(\ Binary.Op.BIT_OR, \ Var(ClassicalRegister(3, 'c'), Uint(3)), \ Value(5, Uint(3)), \ Uint(3)) """ return _binary_bitwise(Binary.Op.BIT_OR, left, right) def bit_xor(left: typing.Any, right: typing.Any, /) -> Expr: """Create a bitwise 'exclusive or' expression node from the given value, resolving any implicit casts and lifting the values into :class:`Value` nodes if required. Examples: Bitwise 'exclusive or' of a classical register and an integer literal:: >>> from qiskit.circuit import ClassicalRegister >>> from qiskit.circuit.classical import expr >>> expr.bit_xor(ClassicalRegister(3, "c"), 0b101) Binary(\ Binary.Op.BIT_XOR, \ Var(ClassicalRegister(3, 'c'), Uint(3)), \ Value(5, Uint(3)), \ Uint(3)) """ return _binary_bitwise(Binary.Op.BIT_XOR, left, right) def _binary_logical(op: Binary.Op, left: typing.Any, right: typing.Any) -> Expr: bool_ = types.Bool() left = _coerce_lossless(lift(left), bool_) right = _coerce_lossless(lift(right), bool_) return Binary(op, left, right, bool_) def logic_and(left: typing.Any, right: typing.Any, /) -> Expr: """Create a logical 'and' expression node from the given value, resolving any implicit casts and lifting the values into :class:`Value` nodes if required. Examples: Logical 'and' of two classical bits:: >>> from qiskit.circuit import Clbit >>> from qiskit.circuit.classical import expr >>> expr.logical_and(Clbit(), Clbit()) Binary(Binary.Op.LOGIC_AND, Var(<clbit 0>, Bool()), Var(<clbit 1>, Bool()), Bool()) """ return _binary_logical(Binary.Op.LOGIC_AND, left, right) def logic_or(left: typing.Any, right: typing.Any, /) -> Expr: """Create a logical 'or' expression node from the given value, resolving any implicit casts and lifting the values into :class:`Value` nodes if required. Examples: Logical 'or' of two classical bits >>> from qiskit.circuit import Clbit >>> from qiskit.circuit.classical import expr >>> expr.logical_and(Clbit(), Clbit()) Binary(Binary.Op.LOGIC_OR, Var(<clbit 0>, Bool()), Var(<clbit 1>, Bool()), Bool()) """ return _binary_logical(Binary.Op.LOGIC_OR, left, right) def _equal_like(op: Binary.Op, left: typing.Any, right: typing.Any) -> Expr: left, right = _lift_binary_operands(left, right) if left.type.kind is not right.type.kind: raise TypeError(f"invalid types for '{op}': '{left.type}' and '{right.type}'") type = types.greater(left.type, right.type) return Binary(op, _coerce_lossless(left, type), _coerce_lossless(right, type), types.Bool()) def equal(left: typing.Any, right: typing.Any, /) -> Expr: """Create an 'equal' expression node from the given value, resolving any implicit casts and lifting the values into :class:`Value` nodes if required. Examples: Equality between a classical register and an integer:: >>> from qiskit.circuit import ClassicalRegister >>> from qiskit.circuit.classical import expr >>> expr.equal(ClassicalRegister(3, "c"), 7) Binary(Binary.Op.EQUAL, \ Var(ClassicalRegister(3, "c"), Uint(3)), \ Value(7, Uint(3)), \ Uint(3)) """ return _equal_like(Binary.Op.EQUAL, left, right) def not_equal(left: typing.Any, right: typing.Any, /) -> Expr: """Create a 'not equal' expression node from the given value, resolving any implicit casts and lifting the values into :class:`Value` nodes if required. Examples: Inequality between a classical register and an integer:: >>> from qiskit.circuit import ClassicalRegister >>> from qiskit.circuit.classical import expr >>> expr.not_equal(ClassicalRegister(3, "c"), 7) Binary(Binary.Op.NOT_EQUAL, \ Var(ClassicalRegister(3, "c"), Uint(3)), \ Value(7, Uint(3)), \ Uint(3)) """ return _equal_like(Binary.Op.NOT_EQUAL, left, right) def _binary_relation(op: Binary.Op, left: typing.Any, right: typing.Any) -> Expr: left, right = _lift_binary_operands(left, right) if left.type.kind is not right.type.kind or left.type.kind is types.Bool: raise TypeError(f"invalid types for '{op}': '{left.type}' and '{right.type}'") type = types.greater(left.type, right.type) return Binary(op, _coerce_lossless(left, type), _coerce_lossless(right, type), types.Bool()) def less(left: typing.Any, right: typing.Any, /) -> Expr: """Create a 'less than' expression node from the given value, resolving any implicit casts and lifting the values into :class:`Value` nodes if required. Examples: Query if a classical register is less than an integer:: >>> from qiskit.circuit import ClassicalRegister >>> from qiskit.circuit.classical import expr >>> expr.less(ClassicalRegister(3, "c"), 5) Binary(Binary.Op.LESS, \ Var(ClassicalRegister(3, "c"), Uint(3)), \ Value(5, Uint(3)), \ Uint(3)) """ return _binary_relation(Binary.Op.LESS, left, right) def less_equal(left: typing.Any, right: typing.Any, /) -> Expr: """Create a 'less than or equal to' expression node from the given value, resolving any implicit casts and lifting the values into :class:`Value` nodes if required. Examples: Query if a classical register is less than or equal to another:: >>> from qiskit.circuit import ClassicalRegister >>> from qiskit.circuit.classical import expr >>> expr.less(ClassicalRegister(3, "a"), ClassicalRegister(3, "b")) Binary(Binary.Op.LESS_EQUAL, \ Var(ClassicalRegister(3, "a"), Uint(3)), \ Var(ClassicalRegister(3, "b"), Uint(3)), \ Uint(3)) """ return _binary_relation(Binary.Op.LESS_EQUAL, left, right) def greater(left: typing.Any, right: typing.Any, /) -> Expr: """Create a 'greater than' expression node from the given value, resolving any implicit casts and lifting the values into :class:`Value` nodes if required. Examples: Query if a classical register is greater than an integer:: >>> from qiskit.circuit import ClassicalRegister >>> from qiskit.circuit.classical import expr >>> expr.less(ClassicalRegister(3, "c"), 5) Binary(Binary.Op.GREATER, \ Var(ClassicalRegister(3, "c"), Uint(3)), \ Value(5, Uint(3)), \ Uint(3)) """ return _binary_relation(Binary.Op.GREATER, left, right) def greater_equal(left: typing.Any, right: typing.Any, /) -> Expr: """Create a 'greater than or equal to' expression node from the given value, resolving any implicit casts and lifting the values into :class:`Value` nodes if required. Examples: Query if a classical register is greater than or equal to another:: >>> from qiskit.circuit import ClassicalRegister >>> from qiskit.circuit.classical import expr >>> expr.less(ClassicalRegister(3, "a"), ClassicalRegister(3, "b")) Binary(Binary.Op.GREATER_EQUAL, \ Var(ClassicalRegister(3, "a"), Uint(3)), \ Var(ClassicalRegister(3, "b"), Uint(3)), \ Uint(3)) """ return _binary_relation(Binary.Op.GREATER_EQUAL, left, right)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Expression-tree nodes.""" # Given the nature of the tree representation and that there are helper functions associated with # many of the classes whose arguments naturally share names with themselves, it's inconvenient to # use synonyms everywhere. This goes for the builtin 'type' as well. # pylint: disable=redefined-builtin,redefined-outer-name from __future__ import annotations __all__ = [ "Expr", "Var", "Value", "Cast", "Unary", "Binary", ] import abc import enum import typing from .. import types if typing.TYPE_CHECKING: import qiskit _T_co = typing.TypeVar("_T_co", covariant=True) # If adding nodes, remember to update `visitors.ExprVisitor` as well. class Expr(abc.ABC): """Root base class of all nodes in the expression tree. The base case should never be instantiated directly. This must not be subclassed by users; subclasses form the internal data of the representation of expressions, and it does not make sense to add more outside of Qiskit library code. All subclasses are responsible for setting their ``type`` attribute in their ``__init__``, and should not call the parent initialiser.""" __slots__ = ("type",) type: types.Type # Sentinel to prevent instantiation of the base class. @abc.abstractmethod def __init__(self): # pragma: no cover pass def accept( self, visitor: qiskit.circuit.classical.expr.ExprVisitor[_T_co], / ) -> _T_co: # pragma: no cover """Call the relevant ``visit_*`` method on the given :class:`ExprVisitor`. The usual entry point for a simple visitor is to construct it, and then call :meth:`accept` on the root object to be visited. For example:: expr = ... visitor = MyVisitor() visitor.accept(expr) Subclasses of :class:`Expr` should override this to call the correct virtual method on the visitor. This implements double dispatch with the visitor.""" return visitor.visit_generic(self) @typing.final class Cast(Expr): """A cast from one type to another, implied by the use of an expression in a different context.""" __slots__ = ("operand", "implicit") def __init__(self, operand: Expr, type: types.Type, implicit: bool = False): self.type = type self.operand = operand self.implicit = implicit def accept(self, visitor, /): return visitor.visit_cast(self) def __eq__(self, other): return ( isinstance(other, Cast) and self.type == other.type and self.operand == other.operand and self.implicit == other.implicit ) def __repr__(self): return f"Cast({self.operand}, {self.type}, implicit={self.implicit})" @typing.final class Var(Expr): """A classical variable.""" __slots__ = ("var",) def __init__( self, var: qiskit.circuit.Clbit | qiskit.circuit.ClassicalRegister, type: types.Type ): self.type = type self.var = var def accept(self, visitor, /): return visitor.visit_var(self) def __eq__(self, other): return isinstance(other, Var) and self.type == other.type and self.var == other.var def __repr__(self): return f"Var({self.var}, {self.type})" @typing.final class Value(Expr): """A single scalar value.""" __slots__ = ("value",) def __init__(self, value: typing.Any, type: types.Type): self.type = type self.value = value def accept(self, visitor, /): return visitor.visit_value(self) def __eq__(self, other): return isinstance(other, Value) and self.type == other.type and self.value == other.value def __repr__(self): return f"Value({self.value}, {self.type})" @typing.final class Unary(Expr): """A unary expression. Args: op: The opcode describing which operation is being done. operand: The operand of the operation. type: The resolved type of the result. """ __slots__ = ("op", "operand") class Op(enum.Enum): """Enumeration of the opcodes for unary operations. The bitwise negation :data:`BIT_NOT` takes a single bit or an unsigned integer of known width, and returns a value of the same type. The logical negation :data:`LOGIC_NOT` takes an input that is implicitly coerced to a Boolean, and returns a Boolean. """ # If adding opcodes, remember to add helper constructor functions in `constructors.py`. # The opcode integers should be considered a public interface; they are used by # serialisation formats that may transfer data between different versions of Qiskit. BIT_NOT = 1 """Bitwise negation. ``~operand``.""" LOGIC_NOT = 2 """Logical negation. ``!operand``.""" def __str__(self): return f"Unary.{super().__str__()}" def __repr__(self): return f"Unary.{super().__repr__()}" def __init__(self, op: Unary.Op, operand: Expr, type: types.Type): self.op = op self.operand = operand self.type = type def accept(self, visitor, /): return visitor.visit_unary(self) def __eq__(self, other): return ( isinstance(other, Unary) and self.type == other.type and self.op is other.op and self.operand == other.operand ) def __repr__(self): return f"Unary({self.op}, {self.operand}, {self.type})" @typing.final class Binary(Expr): """A binary expression. Args: op: The opcode describing which operation is being done. left: The left-hand operand. right: The right-hand operand. type: The resolved type of the result. """ __slots__ = ("op", "left", "right") class Op(enum.Enum): """Enumeration of the opcodes for binary operations. The bitwise operations :data:`BIT_AND`, :data:`BIT_OR` and :data:`BIT_XOR` apply to two operands of the same type, which must be a single bit or an unsigned integer of fixed width. The resultant type is the same as the two input types. The logical operations :data:`LOGIC_AND` and :data:`LOGIC_OR` first implicitly coerce their arguments to Booleans, and then apply the logical operation. The resultant type is always Boolean. The binary mathematical relations :data:`EQUAL`, :data:`NOT_EQUAL`, :data:`LESS`, :data:`LESS_EQUAL`, :data:`GREATER` and :data:`GREATER_EQUAL` take unsigned integers (with an implicit cast to make them the same width), and return a Boolean. """ # If adding opcodes, remember to add helper constructor functions in `constructors.py` # The opcode integers should be considered a public interface; they are used by # serialisation formats that may transfer data between different versions of Qiskit. BIT_AND = 1 """Bitwise "and". ``lhs & rhs``.""" BIT_OR = 2 """Bitwise "or". ``lhs | rhs``.""" BIT_XOR = 3 """Bitwise "exclusive or". ``lhs ^ rhs``.""" LOGIC_AND = 4 """Logical "and". ``lhs && rhs``.""" LOGIC_OR = 5 """Logical "or". ``lhs || rhs``.""" EQUAL = 6 """Numeric equality. ``lhs == rhs``.""" NOT_EQUAL = 7 """Numeric inequality. ``lhs != rhs``.""" LESS = 8 """Numeric less than. ``lhs < rhs``.""" LESS_EQUAL = 9 """Numeric less than or equal to. ``lhs <= rhs``""" GREATER = 10 """Numeric greater than. ``lhs > rhs``.""" GREATER_EQUAL = 11 """Numeric greater than or equal to. ``lhs >= rhs``.""" def __str__(self): return f"Binary.{super().__str__()}" def __repr__(self): return f"Binary.{super().__repr__()}" def __init__(self, op: Binary.Op, left: Expr, right: Expr, type: types.Type): self.op = op self.left = left self.right = right self.type = type def accept(self, visitor, /): return visitor.visit_binary(self) def __eq__(self, other): return ( isinstance(other, Binary) and self.type == other.type and self.op is other.op and self.left == other.left and self.right == other.right ) def __repr__(self): return f"Binary({self.op}, {self.left}, {self.right}, {self.type})"
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. r""" .. _pulse_builder: ============= Pulse Builder ============= .. We actually want people to think of these functions as being defined within the ``qiskit.pulse`` namespace, not the submodule ``qiskit.pulse.builder``. .. currentmodule: qiskit.pulse Use the pulse builder DSL to write pulse programs with an imperative syntax. .. warning:: The pulse builder interface is still in active development. It may have breaking API changes without deprecation warnings in future releases until otherwise indicated. The pulse builder provides an imperative API for writing pulse programs with less difficulty than the :class:`~qiskit.pulse.Schedule` API. It contextually constructs a pulse schedule and then emits the schedule for execution. For example, to play a series of pulses on channels is as simple as: .. plot:: :include-source: 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='pulse_programming_in') as pulse_prog: pulse.play([1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1], d0) pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d1) pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0], d2) pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d3) pulse.play([1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0], d4) pulse_prog.draw() To begin pulse programming we must first initialize our program builder context with :func:`build`, after which we can begin adding program statements. For example, below we write a simple program that :func:`play`\s a pulse: .. plot:: :include-source: from qiskit import execute, pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.play(pulse.Constant(100, 1.0), d0) pulse_prog.draw() The builder initializes a :class:`.pulse.Schedule`, ``pulse_prog`` and then begins to construct the program within the context. The output pulse schedule will survive after the context is exited and can be executed like a normal Qiskit schedule using ``qiskit.execute(pulse_prog, backend)``. Pulse programming has a simple imperative style. This leaves the programmer to worry about the raw experimental physics of pulse programming and not constructing cumbersome data structures. We can optionally pass a :class:`~qiskit.providers.Backend` to :func:`build` to enable enhanced functionality. Below, we prepare a Bell state by automatically compiling the required pulses from their gate-level representations, while simultaneously applying a long decoupling pulse to a neighboring qubit. We terminate the experiment with a measurement to observe the state we prepared. This program which mixes circuits and pulses will be automatically lowered to be run as a pulse program: .. plot:: :include-source: import math from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse3Q # TODO: This example should use a real mock backend. backend = FakeOpenPulse3Q() d2 = pulse.DriveChannel(2) with pulse.build(backend) as bell_prep: pulse.u2(0, math.pi, 0) pulse.cx(0, 1) with pulse.build(backend) as decoupled_bell_prep_and_measure: # We call our bell state preparation schedule constructed above. with pulse.align_right(): pulse.call(bell_prep) pulse.play(pulse.Constant(bell_prep.duration, 0.02), d2) pulse.barrier(0, 1, 2) registers = pulse.measure_all() decoupled_bell_prep_and_measure.draw() With the pulse builder we are able to blend programming on qubits and channels. While the pulse schedule is based on instructions that operate on channels, the pulse builder automatically handles the mapping from qubits to channels for you. In the example below we demonstrate some more features of the pulse builder: .. code-block:: import math from qiskit import pulse, QuantumCircuit from qiskit.pulse import library from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend) as pulse_prog: # Create a pulse. gaussian_pulse = library.gaussian(10, 1.0, 2) # Get the qubit's corresponding drive channel from the backend. d0 = pulse.drive_channel(0) d1 = pulse.drive_channel(1) # Play a pulse at t=0. pulse.play(gaussian_pulse, d0) # Play another pulse directly after the previous pulse at t=10. pulse.play(gaussian_pulse, d0) # The default scheduling behavior is to schedule pulses in parallel # across channels. For example, the statement below # plays the same pulse on a different channel at t=0. pulse.play(gaussian_pulse, d1) # We also provide pulse scheduling alignment contexts. # The default alignment context is align_left. # The sequential context schedules pulse instructions sequentially in time. # This context starts at t=10 due to earlier pulses above. with pulse.align_sequential(): pulse.play(gaussian_pulse, d0) # Play another pulse after at t=20. pulse.play(gaussian_pulse, d1) # We can also nest contexts as each instruction is # contained in its local scheduling context. # The output of a child context is a context-schedule # with the internal instructions timing fixed relative to # one another. This is schedule is then called in the parent context. # Context starts at t=30. with pulse.align_left(): # Start at t=30. pulse.play(gaussian_pulse, d0) # Start at t=30. pulse.play(gaussian_pulse, d1) # Context ends at t=40. # Alignment context where all pulse instructions are # aligned to the right, ie., as late as possible. with pulse.align_right(): # Shift the phase of a pulse channel. pulse.shift_phase(math.pi, d1) # Starts at t=40. pulse.delay(100, d0) # Ends at t=140. # Starts at t=130. pulse.play(gaussian_pulse, d1) # Ends at t=140. # Acquire data for a qubit and store in a memory slot. pulse.acquire(100, 0, pulse.MemorySlot(0)) # We also support a variety of macros for common operations. # Measure all qubits. pulse.measure_all() # Delay on some qubits. # This requires knowledge of which channels belong to which qubits. # delay for 100 cycles on qubits 0 and 1. pulse.delay_qubits(100, 0, 1) # Call a quantum circuit. The pulse builder lazily constructs a quantum # circuit which is then transpiled and scheduled before inserting into # a pulse schedule. # NOTE: Quantum register indices correspond to physical qubit indices. qc = QuantumCircuit(2, 2) qc.cx(0, 1) pulse.call(qc) # Calling a small set of standard gates and decomposing to pulses is # also supported with more natural syntax. pulse.u3(0, math.pi, 0, 0) pulse.cx(0, 1) # It is also be possible to call a preexisting schedule tmp_sched = pulse.Schedule() tmp_sched += pulse.Play(gaussian_pulse, d0) pulse.call(tmp_sched) # We also support: # frequency instructions pulse.set_frequency(5.0e9, d0) # phase instructions pulse.shift_phase(0.1, d0) # offset contexts with pulse.phase_offset(math.pi, d0): pulse.play(gaussian_pulse, d0) The above is just a small taste of what is possible with the builder. See the rest of the module documentation for more information on its capabilities. .. autofunction:: build Channels ======== Methods to return the correct channels for the respective qubit indices. .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeArmonk backend = FakeArmonk() with pulse.build(backend) as drive_sched: d0 = pulse.drive_channel(0) print(d0) .. parsed-literal:: DriveChannel(0) .. autofunction:: acquire_channel .. autofunction:: control_channels .. autofunction:: drive_channel .. autofunction:: measure_channel Instructions ============ Pulse instructions are available within the builder interface. Here's an example: .. plot:: :include-source: from qiskit import pulse from qiskit.providers.fake_provider import FakeArmonk backend = FakeArmonk() with pulse.build(backend) as drive_sched: d0 = pulse.drive_channel(0) a0 = pulse.acquire_channel(0) pulse.play(pulse.library.Constant(10, 1.0), d0) pulse.delay(20, d0) pulse.shift_phase(3.14/2, d0) pulse.set_phase(3.14, d0) pulse.shift_frequency(1e7, d0) pulse.set_frequency(5e9, d0) with pulse.build() as temp_sched: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), d0) pulse.play(pulse.library.Gaussian(20, -1.0, 3.0), d0) pulse.call(temp_sched) pulse.acquire(30, a0, pulse.MemorySlot(0)) drive_sched.draw() .. autofunction:: acquire .. autofunction:: barrier .. autofunction:: call .. autofunction:: delay .. autofunction:: play .. autofunction:: reference .. autofunction:: set_frequency .. autofunction:: set_phase .. autofunction:: shift_frequency .. autofunction:: shift_phase .. autofunction:: snapshot Contexts ======== Builder aware contexts that modify the construction of a pulse program. For example an alignment context like :func:`align_right` may be used to align all pulses as late as possible in a pulse program. .. plot:: :include-source: from qiskit import pulse d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) with pulse.build() as pulse_prog: with pulse.align_right(): # this pulse will start at t=0 pulse.play(pulse.Constant(100, 1.0), d0) # this pulse will start at t=80 pulse.play(pulse.Constant(20, 1.0), d1) pulse_prog.draw() .. autofunction:: align_equispaced .. autofunction:: align_func .. autofunction:: align_left .. autofunction:: align_right .. autofunction:: align_sequential .. autofunction:: circuit_scheduler_settings .. autofunction:: frequency_offset .. autofunction:: phase_offset .. autofunction:: transpiler_settings Macros ====== Macros help you add more complex functionality to your pulse program. .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeArmonk backend = FakeArmonk() with pulse.build(backend) as measure_sched: mem_slot = pulse.measure(0) print(mem_slot) .. parsed-literal:: MemorySlot(0) .. autofunction:: measure .. autofunction:: measure_all .. autofunction:: delay_qubits Circuit Gates ============= To use circuit level gates within your pulse program call a circuit with :func:`call`. .. warning:: These will be removed in future versions with the release of a circuit builder interface in which it will be possible to calibrate a gate in terms of pulses and use that gate in a circuit. .. code-block:: import math from qiskit import pulse from qiskit.providers.fake_provider import FakeArmonk backend = FakeArmonk() with pulse.build(backend) as u3_sched: pulse.u3(math.pi, 0, math.pi, 0) .. autofunction:: cx .. autofunction:: u1 .. autofunction:: u2 .. autofunction:: u3 .. autofunction:: x Utilities ========= The utility functions can be used to gather attributes about the backend and modify how the program is built. .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeArmonk backend = FakeArmonk() with pulse.build(backend) as u3_sched: print('Number of qubits in backend: {}'.format(pulse.num_qubits())) samples = 160 print('There are {} samples in {} seconds'.format( samples, pulse.samples_to_seconds(160))) seconds = 1e-6 print('There are {} seconds in {} samples.'.format( seconds, pulse.seconds_to_samples(1e-6))) .. parsed-literal:: Number of qubits in backend: 1 There are 160 samples in 3.5555555555555554e-08 seconds There are 1e-06 seconds in 4500 samples. .. autofunction:: active_backend .. autofunction:: active_transpiler_settings .. autofunction:: active_circuit_scheduler_settings .. autofunction:: num_qubits .. autofunction:: qubit_channels .. autofunction:: samples_to_seconds .. autofunction:: seconds_to_samples """ import collections import contextvars import functools import itertools import uuid import warnings from contextlib import contextmanager from functools import singledispatchmethod from typing import ( Any, Callable, ContextManager, Dict, Iterable, List, Mapping, Optional, Set, Tuple, TypeVar, Union, NewType, ) import numpy as np from qiskit import circuit from qiskit.circuit.library import standard_gates as gates from qiskit.circuit.parameterexpression import ParameterExpression, ParameterValueType from qiskit.pulse import ( channels as chans, configuration, exceptions, instructions, macros, library, transforms, ) from qiskit.providers.backend import BackendV2 from qiskit.pulse.instructions import directives from qiskit.pulse.schedule import Schedule, ScheduleBlock from qiskit.pulse.transforms.alignments import AlignmentKind #: contextvars.ContextVar[BuilderContext]: active builder BUILDER_CONTEXTVAR = contextvars.ContextVar("backend") T = TypeVar("T") StorageLocation = NewType("StorageLocation", Union[chans.MemorySlot, chans.RegisterSlot]) def _compile_lazy_circuit_before(function: Callable[..., T]) -> Callable[..., T]: """Decorator thats schedules and calls the lazily compiled circuit before executing the decorated builder method.""" @functools.wraps(function) def wrapper(self, *args, **kwargs): self._compile_lazy_circuit() return function(self, *args, **kwargs) return wrapper def _requires_backend(function: Callable[..., T]) -> Callable[..., T]: """Decorator a function to raise if it is called without a builder with a set backend. """ @functools.wraps(function) def wrapper(self, *args, **kwargs): if self.backend is None: raise exceptions.BackendNotSet( 'This function requires the builder to have a "backend" set.' ) return function(self, *args, **kwargs) return wrapper class _PulseBuilder: """Builder context class.""" __alignment_kinds__ = { "left": transforms.AlignLeft(), "right": transforms.AlignRight(), "sequential": transforms.AlignSequential(), } def __init__( self, backend=None, block: Optional[ScheduleBlock] = None, name: Optional[str] = None, default_alignment: Union[str, AlignmentKind] = "left", default_transpiler_settings: Mapping = None, default_circuit_scheduler_settings: Mapping = None, ): """Initialize the builder context. .. note:: At some point we may consider incorporating the builder into the :class:`~qiskit.pulse.Schedule` class. However, the risk of this is tying the user interface to the intermediate representation. For now we avoid this at the cost of some code duplication. Args: backend (Backend): Input backend to use in builder. If not set certain functionality will be unavailable. block: Initital ``ScheduleBlock`` to build on. name: Name of pulse program to be built. default_alignment: Default scheduling alignment for builder. One of ``left``, ``right``, ``sequential`` or an instance of :class:`~qiskit.pulse.transforms.alignments.AlignmentKind` subclass. default_transpiler_settings: Default settings for the transpiler. default_circuit_scheduler_settings: Default settings for the circuit to pulse scheduler. Raises: PulseError: When invalid ``default_alignment`` or `block` is specified. """ #: Backend: Backend instance for context builder. self._backend = backend #: Union[None, ContextVar]: Token for this ``_PulseBuilder``'s ``ContextVar``. self._backend_ctx_token = None #: QuantumCircuit: Lazily constructed quantum circuit self._lazy_circuit = None #: Dict[str, Any]: Transpiler setting dictionary. self._transpiler_settings = default_transpiler_settings or {} #: Dict[str, Any]: Scheduler setting dictionary. self._circuit_scheduler_settings = default_circuit_scheduler_settings or {} #: List[ScheduleBlock]: Stack of context. self._context_stack = [] #: str: Name of the output program self._name = name # Add root block if provided. Schedule will be built on top of this. if block is not None: if isinstance(block, ScheduleBlock): root_block = block elif isinstance(block, Schedule): root_block = self._naive_typecast_schedule(block) else: raise exceptions.PulseError( f"Input `block` type {block.__class__.__name__} is " "not a valid format. Specify a pulse program." ) self._context_stack.append(root_block) # Set default alignment context alignment = _PulseBuilder.__alignment_kinds__.get(default_alignment, default_alignment) if not isinstance(alignment, AlignmentKind): raise exceptions.PulseError( f"Given `default_alignment` {repr(default_alignment)} is " "not a valid transformation. Set one of " f'{", ".join(_PulseBuilder.__alignment_kinds__.keys())}, ' "or set an instance of `AlignmentKind` subclass." ) self.push_context(alignment) def __enter__(self) -> ScheduleBlock: """Enter this builder context and yield either the supplied schedule or the schedule created for the user. Returns: The schedule that the builder will build on. """ self._backend_ctx_token = BUILDER_CONTEXTVAR.set(self) output = self._context_stack[0] output._name = self._name or output.name return output @_compile_lazy_circuit_before def __exit__(self, exc_type, exc_val, exc_tb): """Exit the builder context and compile the built pulse program.""" self.compile() BUILDER_CONTEXTVAR.reset(self._backend_ctx_token) @property def backend(self): """Returns the builder backend if set. Returns: Optional[Backend]: The builder's backend. """ return self._backend @_compile_lazy_circuit_before def push_context(self, alignment: AlignmentKind): """Push new context to the stack.""" self._context_stack.append(ScheduleBlock(alignment_context=alignment)) @_compile_lazy_circuit_before def pop_context(self) -> ScheduleBlock: """Pop the last context from the stack.""" if len(self._context_stack) == 1: raise exceptions.PulseError("The root context cannot be popped out.") return self._context_stack.pop() def get_context(self) -> ScheduleBlock: """Get current context. Notes: New instruction can be added by `.append_subroutine` or `.append_instruction` method. Use above methods rather than directly accessing to the current context. """ return self._context_stack[-1] @property @_requires_backend def num_qubits(self): """Get the number of qubits in the backend.""" # backendV2 if isinstance(self.backend, BackendV2): return self.backend.num_qubits return self.backend.configuration().n_qubits @property def transpiler_settings(self) -> Mapping: """The builder's transpiler settings.""" return self._transpiler_settings @transpiler_settings.setter @_compile_lazy_circuit_before def transpiler_settings(self, settings: Mapping): self._compile_lazy_circuit() self._transpiler_settings = settings @property def circuit_scheduler_settings(self) -> Mapping: """The builder's circuit to pulse scheduler settings.""" return self._circuit_scheduler_settings @circuit_scheduler_settings.setter @_compile_lazy_circuit_before def circuit_scheduler_settings(self, settings: Mapping): self._compile_lazy_circuit() self._circuit_scheduler_settings = settings @_compile_lazy_circuit_before def compile(self) -> ScheduleBlock: """Compile and output the built pulse program.""" # Not much happens because we currently compile as we build. # This should be offloaded to a true compilation module # once we define a more sophisticated IR. while len(self._context_stack) > 1: current = self.pop_context() self.append_subroutine(current) return self._context_stack[0] def _compile_lazy_circuit(self): """Call a context QuantumCircuit (lazy circuit) and append the output pulse schedule to the builder's context schedule. Note that the lazy circuit is not stored as a call instruction. """ if self._lazy_circuit: lazy_circuit = self._lazy_circuit # reset lazy circuit self._lazy_circuit = self._new_circuit() self.call_subroutine(self._compile_circuit(lazy_circuit)) def _compile_circuit(self, circ) -> Schedule: """Take a QuantumCircuit and output the pulse schedule associated with the circuit.""" from qiskit import compiler # pylint: disable=cyclic-import transpiled_circuit = compiler.transpile(circ, self.backend, **self.transpiler_settings) sched = compiler.schedule( transpiled_circuit, self.backend, **self.circuit_scheduler_settings ) return sched def _new_circuit(self): """Create a new circuit for lazy circuit scheduling.""" return circuit.QuantumCircuit(self.num_qubits) @_compile_lazy_circuit_before def append_instruction(self, instruction: instructions.Instruction): """Add an instruction to the builder's context schedule. Args: instruction: Instruction to append. """ self._context_stack[-1].append(instruction) def append_reference(self, name: str, *extra_keys: str): """Add external program as a :class:`~qiskit.pulse.instructions.Reference` instruction. Args: name: Name of subroutine. extra_keys: Assistance keys to uniquely specify the subroutine. """ inst = instructions.Reference(name, *extra_keys) self.append_instruction(inst) @_compile_lazy_circuit_before def append_subroutine(self, subroutine: Union[Schedule, ScheduleBlock]): """Append a :class:`ScheduleBlock` to the builder's context schedule. This operation doesn't create a reference. Subroutine is directly appended to current context schedule. Args: subroutine: ScheduleBlock to append to the current context block. Raises: PulseError: When subroutine is not Schedule nor ScheduleBlock. """ if not isinstance(subroutine, (ScheduleBlock, Schedule)): raise exceptions.PulseError( f"'{subroutine.__class__.__name__}' is not valid data format in the builder. " "'Schedule' and 'ScheduleBlock' can be appended to the builder context." ) if len(subroutine) == 0: return if isinstance(subroutine, Schedule): subroutine = self._naive_typecast_schedule(subroutine) self._context_stack[-1].append(subroutine) @singledispatchmethod def call_subroutine( self, subroutine: Union[circuit.QuantumCircuit, Schedule, ScheduleBlock], name: Optional[str] = None, value_dict: Optional[Dict[ParameterExpression, ParameterValueType]] = None, **kw_params: ParameterValueType, ): """Call a schedule or circuit defined outside of the current scope. The ``subroutine`` is appended to the context schedule as a call instruction. This logic just generates a convenient program representation in the compiler. Thus, this doesn't affect execution of inline subroutines. See :class:`~pulse.instructions.Call` for more details. Args: subroutine: Target schedule or circuit to append to the current context. name: Name of subroutine if defined. value_dict: Parameter object and assigned value mapping. This is more precise way to identify a parameter since mapping is managed with unique object id rather than name. Especially there is any name collision in a parameter table. kw_params: Parameter values to bind to the target subroutine with string parameter names. If there are parameter name overlapping, these parameters are updated with the same assigned value. Raises: PulseError: - When input subroutine is not valid data format. """ raise exceptions.PulseError( f"Subroutine type {subroutine.__class__.__name__} is " "not valid data format. Call QuantumCircuit, " "Schedule, or ScheduleBlock." ) @call_subroutine.register def _( self, target_block: ScheduleBlock, name: Optional[str] = None, value_dict: Optional[Dict[ParameterExpression, ParameterValueType]] = None, **kw_params: ParameterValueType, ): if len(target_block) == 0: return # Create local parameter assignment local_assignment = {} for param_name, value in kw_params.items(): params = target_block.get_parameters(param_name) if not params: raise exceptions.PulseError( f"Parameter {param_name} is not defined in the target subroutine. " f'{", ".join(map(str, target_block.parameters))} can be specified.' ) for param in params: local_assignment[param] = value if value_dict: if local_assignment.keys() & value_dict.keys(): warnings.warn( "Some parameters provided by 'value_dict' conflict with one through " "keyword arguments. Parameter values in the keyword arguments " "are overridden by the dictionary values.", UserWarning, ) local_assignment.update(value_dict) if local_assignment: target_block = target_block.assign_parameters(local_assignment, inplace=False) if name is None: # Add unique string, not to accidentally override existing reference entry. keys = (target_block.name, uuid.uuid4().hex) else: keys = (name,) self.append_reference(*keys) self.get_context().assign_references({keys: target_block}, inplace=True) @call_subroutine.register def _( self, target_schedule: Schedule, name: Optional[str] = None, value_dict: Optional[Dict[ParameterExpression, ParameterValueType]] = None, **kw_params: ParameterValueType, ): if len(target_schedule) == 0: return self.call_subroutine( self._naive_typecast_schedule(target_schedule), name=name, value_dict=value_dict, **kw_params, ) @call_subroutine.register def _( self, target_circuit: circuit.QuantumCircuit, name: Optional[str] = None, value_dict: Optional[Dict[ParameterExpression, ParameterValueType]] = None, **kw_params: ParameterValueType, ): if len(target_circuit) == 0: return self._compile_lazy_circuit() self.call_subroutine( self._compile_circuit(target_circuit), name=name, value_dict=value_dict, **kw_params, ) @_requires_backend def call_gate(self, gate: circuit.Gate, qubits: Tuple[int, ...], lazy: bool = True): """Call the circuit ``gate`` in the pulse program. The qubits are assumed to be defined on physical qubits. If ``lazy == True`` this circuit will extend a lazily constructed quantum circuit. When an operation occurs that breaks the underlying circuit scheduling assumptions such as adding a pulse instruction or changing the alignment context the circuit will be transpiled and scheduled into pulses with the current active settings. Args: gate: Gate to call. qubits: Qubits to call gate on. lazy: If false the circuit will be transpiled and pulse scheduled immediately. Otherwise, it will extend the active lazy circuit as defined above. """ try: iter(qubits) except TypeError: qubits = (qubits,) if lazy: self._call_gate(gate, qubits) else: self._compile_lazy_circuit() self._call_gate(gate, qubits) self._compile_lazy_circuit() def _call_gate(self, gate, qargs): if self._lazy_circuit is None: self._lazy_circuit = self._new_circuit() self._lazy_circuit.append(gate, qargs=qargs) @staticmethod def _naive_typecast_schedule(schedule: Schedule): # Naively convert into ScheduleBlock from qiskit.pulse.transforms import inline_subroutines, flatten, pad preprocessed_schedule = inline_subroutines(flatten(schedule)) pad(preprocessed_schedule, inplace=True, pad_with=instructions.TimeBlockade) # default to left alignment, namely ASAP scheduling target_block = ScheduleBlock(name=schedule.name) for _, inst in preprocessed_schedule.instructions: target_block.append(inst, inplace=True) return target_block def get_dt(self): """Retrieve dt differently based on the type of Backend""" if isinstance(self.backend, BackendV2): return self.backend.dt return self.backend.configuration().dt def build( backend=None, schedule: Optional[ScheduleBlock] = None, name: Optional[str] = None, default_alignment: Optional[Union[str, AlignmentKind]] = "left", default_transpiler_settings: Optional[Dict[str, Any]] = None, default_circuit_scheduler_settings: Optional[Dict[str, Any]] = None, ) -> ContextManager[ScheduleBlock]: """Create a context manager for launching the imperative pulse builder DSL. To enter a building context and starting building a pulse program: .. code-block:: from qiskit import execute, pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.play(pulse.Constant(100, 0.5), d0) While the output program ``pulse_prog`` cannot be executed as we are using a mock backend. If a real backend is being used, executing the program is done with: .. code-block:: python qiskit.execute(pulse_prog, backend) Args: backend (Backend): A Qiskit backend. If not supplied certain builder functionality will be unavailable. schedule: A pulse ``ScheduleBlock`` in which your pulse program will be built. name: Name of pulse program to be built. default_alignment: Default scheduling alignment for builder. One of ``left``, ``right``, ``sequential`` or an alignment context. default_transpiler_settings: Default settings for the transpiler. default_circuit_scheduler_settings: Default settings for the circuit to pulse scheduler. Returns: A new builder context which has the active builder initialized. """ return _PulseBuilder( backend=backend, block=schedule, name=name, default_alignment=default_alignment, default_transpiler_settings=default_transpiler_settings, default_circuit_scheduler_settings=default_circuit_scheduler_settings, ) # Builder Utilities def _active_builder() -> _PulseBuilder: """Get the active builder in the active context. Returns: The active active builder in this context. Raises: exceptions.NoActiveBuilder: If a pulse builder function is called outside of a builder context. """ try: return BUILDER_CONTEXTVAR.get() except LookupError as ex: raise exceptions.NoActiveBuilder( "A Pulse builder function was called outside of " "a builder context. Try calling within a builder " 'context, eg., "with pulse.build() as schedule: ...".' ) from ex def active_backend(): """Get the backend of the currently active builder context. Returns: Backend: The active backend in the currently active builder context. Raises: exceptions.BackendNotSet: If the builder does not have a backend set. """ builder = _active_builder().backend if builder is None: raise exceptions.BackendNotSet( 'This function requires the active builder to have a "backend" set.' ) return builder def append_schedule(schedule: Union[Schedule, ScheduleBlock]): """Call a schedule by appending to the active builder's context block. Args: schedule: Schedule or ScheduleBlock to append. """ _active_builder().append_subroutine(schedule) def append_instruction(instruction: instructions.Instruction): """Append an instruction to the active builder's context schedule. Examples: .. code-block:: from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.builder.append_instruction(pulse.Delay(10, d0)) print(pulse_prog.instructions) .. parsed-literal:: ((0, Delay(10, DriveChannel(0))),) """ _active_builder().append_instruction(instruction) def num_qubits() -> int: """Return number of qubits in the currently active backend. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): print(pulse.num_qubits()) .. parsed-literal:: 2 .. note:: Requires the active builder context to have a backend set. """ if isinstance(active_backend(), BackendV2): return active_backend().num_qubits return active_backend().configuration().n_qubits def seconds_to_samples(seconds: Union[float, np.ndarray]) -> Union[int, np.ndarray]: """Obtain the number of samples that will elapse in ``seconds`` on the active backend. Rounds down. Args: seconds: Time in seconds to convert to samples. Returns: The number of samples for the time to elapse """ dt = _active_builder().get_dt() if isinstance(seconds, np.ndarray): return (seconds / dt).astype(int) return int(seconds / dt) def samples_to_seconds(samples: Union[int, np.ndarray]) -> Union[float, np.ndarray]: """Obtain the time in seconds that will elapse for the input number of samples on the active backend. Args: samples: Number of samples to convert to time in seconds. Returns: The time that elapses in ``samples``. """ return samples * _active_builder().get_dt() def qubit_channels(qubit: int) -> Set[chans.Channel]: """Returns the set of channels associated with a qubit. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): print(pulse.qubit_channels(0)) .. parsed-literal:: {MeasureChannel(0), ControlChannel(0), DriveChannel(0), AcquireChannel(0), ControlChannel(1)} .. note:: Requires the active builder context to have a backend set. .. note:: A channel may still be associated with another qubit in this list such as in the case where significant crosstalk exists. """ # implement as the inner function to avoid API change for a patch release in 0.24.2. def get_qubit_channels_v2(backend: BackendV2, qubit: int): r"""Return a list of channels which operate on the given ``qubit``. Returns: List of ``Channel``\s operated on my the given ``qubit``. """ channels = [] # add multi-qubit channels for node_qubits in backend.coupling_map: if qubit in node_qubits: control_channel = backend.control_channel(node_qubits) if control_channel: channels.extend(control_channel) # add single qubit channels channels.append(backend.drive_channel(qubit)) channels.append(backend.measure_channel(qubit)) channels.append(backend.acquire_channel(qubit)) return channels # backendV2 if isinstance(active_backend(), BackendV2): return set(get_qubit_channels_v2(active_backend(), qubit)) return set(active_backend().configuration().get_qubit_channels(qubit)) def _qubits_to_channels(*channels_or_qubits: Union[int, chans.Channel]) -> Set[chans.Channel]: """Returns the unique channels of the input qubits.""" channels = set() for channel_or_qubit in channels_or_qubits: if isinstance(channel_or_qubit, int): channels |= qubit_channels(channel_or_qubit) elif isinstance(channel_or_qubit, chans.Channel): channels.add(channel_or_qubit) else: raise exceptions.PulseError( f'{channel_or_qubit} is not a "Channel" or qubit (integer).' ) return channels def active_transpiler_settings() -> Dict[str, Any]: """Return the current active builder context's transpiler settings. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() transpiler_settings = {'optimization_level': 3} with pulse.build(backend, default_transpiler_settings=transpiler_settings): print(pulse.active_transpiler_settings()) .. parsed-literal:: {'optimization_level': 3} """ return dict(_active_builder().transpiler_settings) def active_circuit_scheduler_settings() -> Dict[str, Any]: """Return the current active builder context's circuit scheduler settings. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() circuit_scheduler_settings = {'method': 'alap'} with pulse.build( backend, default_circuit_scheduler_settings=circuit_scheduler_settings): print(pulse.active_circuit_scheduler_settings()) .. parsed-literal:: {'method': 'alap'} """ return dict(_active_builder().circuit_scheduler_settings) # Contexts @contextmanager def align_left() -> ContextManager[None]: """Left alignment pulse scheduling context. Pulse instructions within this context are scheduled as early as possible by shifting them left to the earliest available time. Examples: .. code-block:: from qiskit import pulse d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) with pulse.build() as pulse_prog: with pulse.align_left(): # this pulse will start at t=0 pulse.play(pulse.Constant(100, 1.0), d0) # this pulse will start at t=0 pulse.play(pulse.Constant(20, 1.0), d1) pulse_prog = pulse.transforms.block_to_schedule(pulse_prog) assert pulse_prog.ch_start_time(d0) == pulse_prog.ch_start_time(d1) Yields: None """ builder = _active_builder() builder.push_context(transforms.AlignLeft()) try: yield finally: current = builder.pop_context() builder.append_subroutine(current) @contextmanager def align_right() -> AlignmentKind: """Right alignment pulse scheduling context. Pulse instructions within this context are scheduled as late as possible by shifting them right to the latest available time. Examples: .. code-block:: from qiskit import pulse d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) with pulse.build() as pulse_prog: with pulse.align_right(): # this pulse will start at t=0 pulse.play(pulse.Constant(100, 1.0), d0) # this pulse will start at t=80 pulse.play(pulse.Constant(20, 1.0), d1) pulse_prog = pulse.transforms.block_to_schedule(pulse_prog) assert pulse_prog.ch_stop_time(d0) == pulse_prog.ch_stop_time(d1) Yields: None """ builder = _active_builder() builder.push_context(transforms.AlignRight()) try: yield finally: current = builder.pop_context() builder.append_subroutine(current) @contextmanager def align_sequential() -> AlignmentKind: """Sequential alignment pulse scheduling context. Pulse instructions within this context are scheduled sequentially in time such that no two instructions will be played at the same time. Examples: .. code-block:: from qiskit import pulse d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) with pulse.build() as pulse_prog: with pulse.align_sequential(): # this pulse will start at t=0 pulse.play(pulse.Constant(100, 1.0), d0) # this pulse will also start at t=100 pulse.play(pulse.Constant(20, 1.0), d1) pulse_prog = pulse.transforms.block_to_schedule(pulse_prog) assert pulse_prog.ch_stop_time(d0) == pulse_prog.ch_start_time(d1) Yields: None """ builder = _active_builder() builder.push_context(transforms.AlignSequential()) try: yield finally: current = builder.pop_context() builder.append_subroutine(current) @contextmanager def align_equispaced(duration: Union[int, ParameterExpression]) -> AlignmentKind: """Equispaced alignment pulse scheduling context. Pulse instructions within this context are scheduled with the same interval spacing such that the total length of the context block is ``duration``. If the total free ``duration`` cannot be evenly divided by the number of instructions within the context, the modulo is split and then prepended and appended to the returned schedule. Delay instructions are automatically inserted in between pulses. This context is convenient to write a schedule for periodical dynamic decoupling or the Hahn echo sequence. Examples: .. plot:: :include-source: from qiskit import pulse d0 = pulse.DriveChannel(0) x90 = pulse.Gaussian(10, 0.1, 3) x180 = pulse.Gaussian(10, 0.2, 3) with pulse.build() as hahn_echo: with pulse.align_equispaced(duration=100): pulse.play(x90, d0) pulse.play(x180, d0) pulse.play(x90, d0) hahn_echo.draw() Args: duration: Duration of this context. This should be larger than the schedule duration. Yields: None Notes: The scheduling is performed for sub-schedules within the context rather than channel-wise. If you want to apply the equispaced context for each channel, you should use the context independently for channels. """ builder = _active_builder() builder.push_context(transforms.AlignEquispaced(duration=duration)) try: yield finally: current = builder.pop_context() builder.append_subroutine(current) @contextmanager def align_func( duration: Union[int, ParameterExpression], func: Callable[[int], float] ) -> AlignmentKind: """Callback defined alignment pulse scheduling context. Pulse instructions within this context are scheduled at the location specified by arbitrary callback function `position` that takes integer index and returns the associated fractional location within [0, 1]. Delay instruction is automatically inserted in between pulses. This context may be convenient to write a schedule of arbitrary dynamical decoupling sequences such as Uhrig dynamical decoupling. Examples: .. plot:: :include-source: import numpy as np from qiskit import pulse d0 = pulse.DriveChannel(0) x90 = pulse.Gaussian(10, 0.1, 3) x180 = pulse.Gaussian(10, 0.2, 3) def udd10_pos(j): return np.sin(np.pi*j/(2*10 + 2))**2 with pulse.build() as udd_sched: pulse.play(x90, d0) with pulse.align_func(duration=300, func=udd10_pos): for _ in range(10): pulse.play(x180, d0) pulse.play(x90, d0) udd_sched.draw() Args: duration: Duration of context. This should be larger than the schedule duration. func: A function that takes an index of sub-schedule and returns the fractional coordinate of of that sub-schedule. The returned value should be defined within [0, 1]. The pulse index starts from 1. Yields: None Notes: The scheduling is performed for sub-schedules within the context rather than channel-wise. If you want to apply the numerical context for each channel, you need to apply the context independently to channels. """ builder = _active_builder() builder.push_context(transforms.AlignFunc(duration=duration, func=func)) try: yield finally: current = builder.pop_context() builder.append_subroutine(current) @contextmanager def general_transforms(alignment_context: AlignmentKind) -> ContextManager[None]: """Arbitrary alignment transformation defined by a subclass instance of :class:`~qiskit.pulse.transforms.alignments.AlignmentKind`. Args: alignment_context: Alignment context instance that defines schedule transformation. Yields: None Raises: PulseError: When input ``alignment_context`` is not ``AlignmentKind`` subclasses. """ if not isinstance(alignment_context, AlignmentKind): raise exceptions.PulseError("Input alignment context is not `AlignmentKind` subclass.") builder = _active_builder() builder.push_context(alignment_context) try: yield finally: current = builder.pop_context() builder.append_subroutine(current) @contextmanager def transpiler_settings(**settings) -> ContextManager[None]: """Set the currently active transpiler settings for this context. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): print(pulse.active_transpiler_settings()) with pulse.transpiler_settings(optimization_level=3): print(pulse.active_transpiler_settings()) .. parsed-literal:: {} {'optimization_level': 3} """ builder = _active_builder() curr_transpiler_settings = builder.transpiler_settings builder.transpiler_settings = collections.ChainMap(settings, curr_transpiler_settings) try: yield finally: builder.transpiler_settings = curr_transpiler_settings @contextmanager def circuit_scheduler_settings(**settings) -> ContextManager[None]: """Set the currently active circuit scheduler settings for this context. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): print(pulse.active_circuit_scheduler_settings()) with pulse.circuit_scheduler_settings(method='alap'): print(pulse.active_circuit_scheduler_settings()) .. parsed-literal:: {} {'method': 'alap'} """ builder = _active_builder() curr_circuit_scheduler_settings = builder.circuit_scheduler_settings builder.circuit_scheduler_settings = collections.ChainMap( settings, curr_circuit_scheduler_settings ) try: yield finally: builder.circuit_scheduler_settings = curr_circuit_scheduler_settings @contextmanager def phase_offset(phase: float, *channels: chans.PulseChannel) -> ContextManager[None]: """Shift the phase of input channels on entry into context and undo on exit. Examples: .. code-block:: import math from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: with pulse.phase_offset(math.pi, d0): pulse.play(pulse.Constant(10, 1.0), d0) assert len(pulse_prog.instructions) == 3 Args: phase: Amount of phase offset in radians. channels: Channels to offset phase of. Yields: None """ for channel in channels: shift_phase(phase, channel) try: yield finally: for channel in channels: shift_phase(-phase, channel) @contextmanager def frequency_offset( frequency: float, *channels: chans.PulseChannel, compensate_phase: bool = False ) -> ContextManager[None]: """Shift the frequency of inputs channels on entry into context and undo on exit. Examples: .. code-block:: python :emphasize-lines: 7, 16 from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build(backend) as pulse_prog: # shift frequency by 1GHz with pulse.frequency_offset(1e9, d0): pulse.play(pulse.Constant(10, 1.0), d0) assert len(pulse_prog.instructions) == 3 with pulse.build(backend) as pulse_prog: # Shift frequency by 1GHz. # Undo accumulated phase in the shifted frequency frame # when exiting the context. with pulse.frequency_offset(1e9, d0, compensate_phase=True): pulse.play(pulse.Constant(10, 1.0), d0) assert len(pulse_prog.instructions) == 4 Args: frequency: Amount of frequency offset in Hz. channels: Channels to offset frequency of. compensate_phase: Compensate for accumulated phase accumulated with respect to the channels' frame at its initial frequency. Yields: None """ builder = _active_builder() # TODO: Need proper implementation of compensation. t0 may depend on the parent context. # For example, the instruction position within the equispaced context depends on # the current total number of instructions, thus adding more instruction after # offset context may change the t0 when the parent context is transformed. t0 = builder.get_context().duration for channel in channels: shift_frequency(frequency, channel) try: yield finally: if compensate_phase: duration = builder.get_context().duration - t0 accumulated_phase = 2 * np.pi * ((duration * builder.get_dt() * frequency) % 1) for channel in channels: shift_phase(-accumulated_phase, channel) for channel in channels: shift_frequency(-frequency, channel) # Channels def drive_channel(qubit: int) -> chans.DriveChannel: """Return ``DriveChannel`` for ``qubit`` on the active builder backend. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): assert pulse.drive_channel(0) == pulse.DriveChannel(0) .. note:: Requires the active builder context to have a backend set. """ # backendV2 if isinstance(active_backend(), BackendV2): return active_backend().drive_channel(qubit) return active_backend().configuration().drive(qubit) def measure_channel(qubit: int) -> chans.MeasureChannel: """Return ``MeasureChannel`` for ``qubit`` on the active builder backend. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): assert pulse.measure_channel(0) == pulse.MeasureChannel(0) .. note:: Requires the active builder context to have a backend set. """ # backendV2 if isinstance(active_backend(), BackendV2): return active_backend().measure_channel(qubit) return active_backend().configuration().measure(qubit) def acquire_channel(qubit: int) -> chans.AcquireChannel: """Return ``AcquireChannel`` for ``qubit`` on the active builder backend. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): assert pulse.acquire_channel(0) == pulse.AcquireChannel(0) .. note:: Requires the active builder context to have a backend set. """ # backendV2 if isinstance(active_backend(), BackendV2): return active_backend().acquire_channel(qubit) return active_backend().configuration().acquire(qubit) def control_channels(*qubits: Iterable[int]) -> List[chans.ControlChannel]: """Return ``ControlChannel`` for ``qubit`` on the active builder backend. Return the secondary drive channel for the given qubit -- typically utilized for controlling multi-qubit interactions. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): assert pulse.control_channels(0, 1) == [pulse.ControlChannel(0)] .. note:: Requires the active builder context to have a backend set. Args: qubits: Tuple or list of ordered qubits of the form `(control_qubit, target_qubit)`. Returns: List of control channels associated with the supplied ordered list of qubits. """ # backendV2 if isinstance(active_backend(), BackendV2): return active_backend().control_channel(qubits) return active_backend().configuration().control(qubits=qubits) # Base Instructions def delay(duration: int, channel: chans.Channel, name: Optional[str] = None): """Delay on a ``channel`` for a ``duration``. Examples: .. code-block:: from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.delay(10, d0) Args: duration: Number of cycles to delay for on ``channel``. channel: Channel to delay on. name: Name of the instruction. """ append_instruction(instructions.Delay(duration, channel, name=name)) def play( pulse: Union[library.Pulse, np.ndarray], channel: chans.PulseChannel, name: Optional[str] = None ): """Play a ``pulse`` on a ``channel``. Examples: .. code-block:: from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.play(pulse.Constant(10, 1.0), d0) Args: pulse: Pulse to play. channel: Channel to play pulse on. name: Name of the pulse. """ if not isinstance(pulse, library.Pulse): pulse = library.Waveform(pulse) append_instruction(instructions.Play(pulse, channel, name=name)) def acquire( duration: int, qubit_or_channel: Union[int, chans.AcquireChannel], register: StorageLocation, **metadata: Union[configuration.Kernel, configuration.Discriminator], ): """Acquire for a ``duration`` on a ``channel`` and store the result in a ``register``. Examples: .. code-block:: from qiskit import pulse acq0 = pulse.AcquireChannel(0) mem0 = pulse.MemorySlot(0) with pulse.build() as pulse_prog: pulse.acquire(100, acq0, mem0) # measurement metadata kernel = pulse.configuration.Kernel('linear_discriminator') pulse.acquire(100, acq0, mem0, kernel=kernel) .. note:: The type of data acquire will depend on the execution ``meas_level``. Args: duration: Duration to acquire data for qubit_or_channel: Either the qubit to acquire data for or the specific :class:`~qiskit.pulse.channels.AcquireChannel` to acquire on. register: Location to store measured result. metadata: Additional metadata for measurement. See :class:`~qiskit.pulse.instructions.Acquire` for more information. Raises: exceptions.PulseError: If the register type is not supported. """ if isinstance(qubit_or_channel, int): qubit_or_channel = chans.AcquireChannel(qubit_or_channel) if isinstance(register, chans.MemorySlot): append_instruction( instructions.Acquire(duration, qubit_or_channel, mem_slot=register, **metadata) ) elif isinstance(register, chans.RegisterSlot): append_instruction( instructions.Acquire(duration, qubit_or_channel, reg_slot=register, **metadata) ) else: raise exceptions.PulseError(f'Register of type: "{type(register)}" is not supported') def set_frequency(frequency: float, channel: chans.PulseChannel, name: Optional[str] = None): """Set the ``frequency`` of a pulse ``channel``. Examples: .. code-block:: from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.set_frequency(1e9, d0) Args: frequency: Frequency in Hz to set channel to. channel: Channel to set frequency of. name: Name of the instruction. """ append_instruction(instructions.SetFrequency(frequency, channel, name=name)) def shift_frequency(frequency: float, channel: chans.PulseChannel, name: Optional[str] = None): """Shift the ``frequency`` of a pulse ``channel``. Examples: .. code-block:: python :emphasize-lines: 6 from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.shift_frequency(1e9, d0) Args: frequency: Frequency in Hz to shift channel frequency by. channel: Channel to shift frequency of. name: Name of the instruction. """ append_instruction(instructions.ShiftFrequency(frequency, channel, name=name)) def set_phase(phase: float, channel: chans.PulseChannel, name: Optional[str] = None): """Set the ``phase`` of a pulse ``channel``. Examples: .. code-block:: python :emphasize-lines: 8 import math from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.set_phase(math.pi, d0) Args: phase: Phase in radians to set channel carrier signal to. channel: Channel to set phase of. name: Name of the instruction. """ append_instruction(instructions.SetPhase(phase, channel, name=name)) def shift_phase(phase: float, channel: chans.PulseChannel, name: Optional[str] = None): """Shift the ``phase`` of a pulse ``channel``. Examples: .. code-block:: import math from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.shift_phase(math.pi, d0) Args: phase: Phase in radians to shift channel carrier signal by. channel: Channel to shift phase of. name: Name of the instruction. """ append_instruction(instructions.ShiftPhase(phase, channel, name)) def snapshot(label: str, snapshot_type: str = "statevector"): """Simulator snapshot. Examples: .. code-block:: from qiskit import pulse with pulse.build() as pulse_prog: pulse.snapshot('first', 'statevector') Args: label: Label for snapshot. snapshot_type: Type of snapshot. """ append_instruction(instructions.Snapshot(label, snapshot_type=snapshot_type)) def call( target: Optional[Union[circuit.QuantumCircuit, Schedule, ScheduleBlock]], name: Optional[str] = None, value_dict: Optional[Dict[ParameterValueType, ParameterValueType]] = None, **kw_params: ParameterValueType, ): """Call the subroutine within the currently active builder context with arbitrary parameters which will be assigned to the target program. .. note:: If the ``target`` program is a :class:`.ScheduleBlock`, then a :class:`.Reference` instruction will be created and appended to the current context. The ``target`` program will be immediately assigned to the current scope as a subroutine. If the ``target`` program is :class:`.Schedule`, it will be wrapped by the :class:`.Call` instruction and appended to the current context to avoid a mixed representation of :class:`.ScheduleBlock` and :class:`.Schedule`. If the ``target`` program is a :class:`.QuantumCircuit` it will be scheduled and the new :class:`.Schedule` will be added as a :class:`.Call` instruction. Examples: 1. Calling a schedule block (recommended) .. code-block:: from qiskit import circuit, pulse from qiskit.providers.fake_provider import FakeBogotaV2 backend = FakeBogotaV2() with pulse.build() as x_sched: pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0)) with pulse.build() as pulse_prog: pulse.call(x_sched) print(pulse_prog) .. parsed-literal:: ScheduleBlock( ScheduleBlock( Play( Gaussian(duration=160, amp=(0.1+0j), sigma=40), DriveChannel(0) ), name="block0", transform=AlignLeft() ), name="block1", transform=AlignLeft() ) The actual program is stored in the reference table attached to the schedule. .. code-block:: print(pulse_prog.references) .. parsed-literal:: ReferenceManager: - ('block0', '634b3b50bd684e26a673af1fbd2d6c81'): ScheduleBlock(Play(Gaussian(... In addition, you can call a parameterized target program with parameter assignment. .. code-block:: amp = circuit.Parameter("amp") with pulse.build() as subroutine: pulse.play(pulse.Gaussian(160, amp, 40), pulse.DriveChannel(0)) with pulse.build() as pulse_prog: pulse.call(subroutine, amp=0.1) pulse.call(subroutine, amp=0.3) print(pulse_prog) .. parsed-literal:: ScheduleBlock( ScheduleBlock( Play( Gaussian(duration=160, amp=(0.1+0j), sigma=40), DriveChannel(0) ), name="block2", transform=AlignLeft() ), ScheduleBlock( Play( Gaussian(duration=160, amp=(0.3+0j), sigma=40), DriveChannel(0) ), name="block2", transform=AlignLeft() ), name="block3", transform=AlignLeft() ) If there is a name collision between parameters, you can distinguish them by specifying each parameter object in a python dictionary. For example, .. code-block:: amp1 = circuit.Parameter('amp') amp2 = circuit.Parameter('amp') with pulse.build() as subroutine: pulse.play(pulse.Gaussian(160, amp1, 40), pulse.DriveChannel(0)) pulse.play(pulse.Gaussian(160, amp2, 40), pulse.DriveChannel(1)) with pulse.build() as pulse_prog: pulse.call(subroutine, value_dict={amp1: 0.1, amp2: 0.3}) print(pulse_prog) .. parsed-literal:: ScheduleBlock( ScheduleBlock( Play(Gaussian(duration=160, amp=(0.1+0j), sigma=40), DriveChannel(0)), Play(Gaussian(duration=160, amp=(0.3+0j), sigma=40), DriveChannel(1)), name="block4", transform=AlignLeft() ), name="block5", transform=AlignLeft() ) 2. Calling a schedule .. code-block:: x_sched = backend.instruction_schedule_map.get("x", (0,)) with pulse.build(backend) as pulse_prog: pulse.call(x_sched) print(pulse_prog) .. parsed-literal:: ScheduleBlock( Call( Schedule( ( 0, Play( Drag( duration=160, amp=(0.18989731546729305+0j), sigma=40, beta=-1.201258305015517, name='drag_86a8' ), DriveChannel(0), name='drag_86a8' ) ), name="x" ), name='x' ), name="block6", transform=AlignLeft() ) Currently, the backend calibrated gates are provided in the form of :class:`~.Schedule`. The parameter assignment mechanism is available also for schedules. However, the called schedule is not treated as a reference. 3. Calling a quantum circuit .. code-block:: backend = FakeBogotaV2() qc = circuit.QuantumCircuit(1) qc.x(0) with pulse.build(backend) as pulse_prog: pulse.call(qc) print(pulse_prog) .. parsed-literal:: ScheduleBlock( Call( Schedule( ( 0, Play( Drag( duration=160, amp=(0.18989731546729305+0j), sigma=40, beta=-1.201258305015517, name='drag_86a8' ), DriveChannel(0), name='drag_86a8' ) ), name="circuit-87" ), name='circuit-87' ), name="block7", transform=AlignLeft() ) .. warning:: Calling a circuit from a schedule is not encouraged. Currently, the Qiskit execution model is migrating toward the pulse gate model, where schedules are attached to circuits through the :meth:`.QuantumCircuit.add_calibration` method. Args: target: Target circuit or pulse schedule to call. name: Optional. A unique name of subroutine if defined. When the name is explicitly provided, one cannot call different schedule blocks with the same name. value_dict: Optional. Parameters assigned to the ``target`` program. If this dictionary is provided, the ``target`` program is copied and then stored in the main built schedule and its parameters are assigned to the given values. This dictionary is keyed on :class:`~.Parameter` objects, allowing parameter name collision to be avoided. kw_params: Alternative way to provide parameters. Since this is keyed on the string parameter name, the parameters having the same name are all updated together. If you want to avoid name collision, use ``value_dict`` with :class:`~.Parameter` objects instead. """ _active_builder().call_subroutine(target, name, value_dict, **kw_params) def reference(name: str, *extra_keys: str): """Refer to undefined subroutine by string keys. A :class:`~qiskit.pulse.instructions.Reference` instruction is implicitly created and a schedule can be separately registered to the reference at a later stage. .. code-block:: python from qiskit import pulse with pulse.build() as main_prog: pulse.reference("x_gate", "q0") with pulse.build() as subroutine: pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0)) main_prog.assign_references(subroutine_dict={("x_gate", "q0"): subroutine}) Args: name: Name of subroutine. extra_keys: Helper keys to uniquely specify the subroutine. """ _active_builder().append_reference(name, *extra_keys) # Directives def barrier(*channels_or_qubits: Union[chans.Channel, int], name: Optional[str] = None): """Barrier directive for a set of channels and qubits. This directive prevents the compiler from moving instructions across the barrier. Consider the case where we want to enforce that one pulse happens after another on separate channels, this can be done with: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) with pulse.build(backend) as barrier_pulse_prog: pulse.play(pulse.Constant(10, 1.0), d0) pulse.barrier(d0, d1) pulse.play(pulse.Constant(10, 1.0), d1) Of course this could have been accomplished with: .. code-block:: from qiskit.pulse import transforms with pulse.build(backend) as aligned_pulse_prog: with pulse.align_sequential(): pulse.play(pulse.Constant(10, 1.0), d0) pulse.play(pulse.Constant(10, 1.0), d1) barrier_pulse_prog = transforms.target_qobj_transform(barrier_pulse_prog) aligned_pulse_prog = transforms.target_qobj_transform(aligned_pulse_prog) assert barrier_pulse_prog == aligned_pulse_prog The barrier allows the pulse compiler to take care of more advanced scheduling alignment operations across channels. For example in the case where we are calling an outside circuit or schedule and want to align a pulse at the end of one call: .. code-block:: import math d0 = pulse.DriveChannel(0) with pulse.build(backend) as pulse_prog: with pulse.align_right(): pulse.x(1) # Barrier qubit 1 and d0. pulse.barrier(1, d0) # Due to barrier this will play before the gate on qubit 1. pulse.play(pulse.Constant(10, 1.0), d0) # This will end at the same time as the pulse above due to # the barrier. pulse.x(1) .. note:: Requires the active builder context to have a backend set if qubits are barriered on. Args: channels_or_qubits: Channels or qubits to barrier. name: Name for the barrier """ channels = _qubits_to_channels(*channels_or_qubits) if len(channels) > 1: append_instruction(directives.RelativeBarrier(*channels, name=name)) # Macros def macro(func: Callable): """Wrap a Python function and activate the parent builder context at calling time. This enables embedding Python functions as builder macros. This generates a new :class:`pulse.Schedule` that is embedded in the parent builder context with every call of the decorated macro function. The decorated macro function will behave as if the function code was embedded inline in the parent builder context after parameter substitution. Examples: .. plot:: :include-source: from qiskit import pulse @pulse.macro def measure(qubit: int): pulse.play(pulse.GaussianSquare(16384, 256, 15872), pulse.measure_channel(qubit)) mem_slot = pulse.MemorySlot(qubit) pulse.acquire(16384, pulse.acquire_channel(qubit), mem_slot) return mem_slot with pulse.build(backend=backend) as sched: mem_slot = measure(0) print(f"Qubit measured into {mem_slot}") sched.draw() Args: func: The Python function to enable as a builder macro. There are no requirements on the signature of the function, any calls to pulse builder methods will be added to builder context the wrapped function is called from. Returns: Callable: The wrapped ``func``. """ func_name = getattr(func, "__name__", repr(func)) @functools.wraps(func) def wrapper(*args, **kwargs): _builder = _active_builder() # activate the pulse builder before calling the function with build(backend=_builder.backend, name=func_name) as built: output = func(*args, **kwargs) _builder.call_subroutine(built) return output return wrapper def measure( qubits: Union[List[int], int], registers: Union[List[StorageLocation], StorageLocation] = None, ) -> Union[List[StorageLocation], StorageLocation]: """Measure a qubit within the currently active builder context. At the pulse level a measurement is composed of both a stimulus pulse and an acquisition instruction which tells the systems measurement unit to acquire data and process it. We provide this measurement macro to automate the process for you, but if desired full control is still available with :func:`acquire` and :func:`play`. To use the measurement it is as simple as specifying the qubit you wish to measure: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() qubit = 0 with pulse.build(backend) as pulse_prog: # Do something to the qubit. qubit_drive_chan = pulse.drive_channel(0) pulse.play(pulse.Constant(100, 1.0), qubit_drive_chan) # Measure the qubit. reg = pulse.measure(qubit) For now it is not possible to do much with the handle to ``reg`` but in the future we will support using this handle to a result register to build up ones program. It is also possible to supply this register: .. code-block:: with pulse.build(backend) as pulse_prog: pulse.play(pulse.Constant(100, 1.0), qubit_drive_chan) # Measure the qubit. mem0 = pulse.MemorySlot(0) reg = pulse.measure(qubit, mem0) assert reg == mem0 .. note:: Requires the active builder context to have a backend set. Args: qubits: Physical qubit to measure. registers: Register to store result in. If not selected the current behavior is to return the :class:`MemorySlot` with the same index as ``qubit``. This register will be returned. Returns: The ``register`` the qubit measurement result will be stored in. """ backend = active_backend() try: qubits = list(qubits) except TypeError: qubits = [qubits] if registers is None: registers = [chans.MemorySlot(qubit) for qubit in qubits] else: try: registers = list(registers) except TypeError: registers = [registers] measure_sched = macros.measure( qubits=qubits, backend=backend, qubit_mem_slots={qubit: register.index for qubit, register in zip(qubits, registers)}, ) # note this is not a subroutine. # just a macro to automate combination of stimulus and acquisition. # prepare unique reference name based on qubit and memory slot index. qubits_repr = "&".join(map(str, qubits)) mslots_repr = "&".join((str(r.index) for r in registers)) _active_builder().call_subroutine(measure_sched, name=f"measure_{qubits_repr}..{mslots_repr}") if len(qubits) == 1: return registers[0] else: return registers def measure_all() -> List[chans.MemorySlot]: r"""Measure all qubits within the currently active builder context. A simple macro function to measure all of the qubits in the device at the same time. This is useful for handling device ``meas_map`` and single measurement constraints. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend) as pulse_prog: # Measure all qubits and return associated registers. regs = pulse.measure_all() .. note:: Requires the active builder context to have a backend set. Returns: The ``register``\s the qubit measurement results will be stored in. """ backend = active_backend() qubits = range(num_qubits()) registers = [chans.MemorySlot(qubit) for qubit in qubits] measure_sched = macros.measure( qubits=qubits, backend=backend, qubit_mem_slots={qubit: qubit for qubit in qubits}, ) # note this is not a subroutine. # just a macro to automate combination of stimulus and acquisition. _active_builder().call_subroutine(measure_sched, name="measure_all") return registers def delay_qubits(duration: int, *qubits: Union[int, Iterable[int]]): r"""Insert delays on all of the :class:`channels.Channel`\s that correspond to the input ``qubits`` at the same time. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse3Q backend = FakeOpenPulse3Q() with pulse.build(backend) as pulse_prog: # Delay for 100 cycles on qubits 0, 1 and 2. regs = pulse.delay_qubits(100, 0, 1, 2) .. note:: Requires the active builder context to have a backend set. Args: duration: Duration to delay for. qubits: Physical qubits to delay on. Delays will be inserted based on the channels returned by :func:`pulse.qubit_channels`. """ qubit_chans = set(itertools.chain.from_iterable(qubit_channels(qubit) for qubit in qubits)) with align_left(): for chan in qubit_chans: delay(duration, chan) # Gate instructions def call_gate(gate: circuit.Gate, qubits: Tuple[int, ...], lazy: bool = True): """Call a gate and lazily schedule it to its corresponding pulse instruction. .. note:: Calling gates directly within the pulse builder namespace will be deprecated in the future in favor of tight integration with a circuit builder interface which is under development. Examples: .. code-block:: from qiskit import pulse from qiskit.pulse import builder from qiskit.circuit.library import standard_gates as gates from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend) as pulse_prog: builder.call_gate(gates.CXGate(), (0, 1)) We can see the role of the transpiler in scheduling gates by optimizing away two consecutive CNOT gates: .. code-block:: with pulse.build(backend) as pulse_prog: with pulse.transpiler_settings(optimization_level=3): builder.call_gate(gates.CXGate(), (0, 1)) builder.call_gate(gates.CXGate(), (0, 1)) assert pulse_prog == pulse.Schedule() .. note:: If multiple gates are called in a row they may be optimized by the transpiler, depending on the :func:`pulse.active_transpiler_settings``. .. note:: Requires the active builder context to have a backend set. Args: gate: Circuit gate instance to call. qubits: Qubits to call gate on. lazy: If ``false`` the gate will be compiled immediately, otherwise it will be added onto a lazily evaluated quantum circuit to be compiled when the builder is forced to by a circuit assumption being broken, such as the inclusion of a pulse instruction or new alignment context. """ _active_builder().call_gate(gate, qubits, lazy=lazy) def cx(control: int, target: int): # pylint: disable=invalid-name """Call a :class:`~qiskit.circuit.library.standard_gates.CXGate` on the input physical qubits. .. note:: Calling gates directly within the pulse builder namespace will be deprecated in the future in favor of tight integration with a circuit builder interface which is under development. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend) as pulse_prog: pulse.cx(0, 1) """ call_gate(gates.CXGate(), (control, target)) def u1(theta: float, qubit: int): # pylint: disable=invalid-name """Call a :class:`~qiskit.circuit.library.standard_gates.U1Gate` on the input physical qubit. .. note:: Calling gates directly within the pulse builder namespace will be deprecated in the future in favor of tight integration with a circuit builder interface which is under development. Examples: .. code-block:: import math from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend) as pulse_prog: pulse.u1(math.pi, 1) """ call_gate(gates.U1Gate(theta), qubit) def u2(phi: float, lam: float, qubit: int): # pylint: disable=invalid-name """Call a :class:`~qiskit.circuit.library.standard_gates.U2Gate` on the input physical qubit. .. note:: Calling gates directly within the pulse builder namespace will be deprecated in the future in favor of tight integration with a circuit builder interface which is under development. Examples: .. code-block:: import math from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend) as pulse_prog: pulse.u2(0, math.pi, 1) """ call_gate(gates.U2Gate(phi, lam), qubit) def u3(theta: float, phi: float, lam: float, qubit: int): # pylint: disable=invalid-name """Call a :class:`~qiskit.circuit.library.standard_gates.U3Gate` on the input physical qubit. .. note:: Calling gates directly within the pulse builder namespace will be deprecated in the future in favor of tight integration with a circuit builder interface which is under development. Examples: .. code-block:: import math from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend) as pulse_prog: pulse.u3(math.pi, 0, math.pi, 1) """ call_gate(gates.U3Gate(theta, phi, lam), qubit) def x(qubit: int): """Call a :class:`~qiskit.circuit.library.standard_gates.XGate` on the input physical qubit. .. note:: Calling gates directly within the pulse builder namespace will be deprecated in the future in favor of tight integration with a circuit builder interface which is under development. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend) as pulse_prog: pulse.x(0) """ call_gate(gates.XGate(), qubit)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. "Circuit operation representing a ``for`` loop." import warnings from typing import Iterable, Optional, Union from qiskit.circuit.parameter import Parameter from qiskit.circuit.exceptions import CircuitError from qiskit.circuit.quantumcircuit import QuantumCircuit from .control_flow import ControlFlowOp class ForLoopOp(ControlFlowOp): """A circuit operation which repeatedly executes a subcircuit (``body``) parameterized by a parameter ``loop_parameter`` through the set of integer values provided in ``indexset``. Parameters: indexset: A collection of integers to loop over. loop_parameter: The placeholder parameterizing ``body`` to which the values from ``indexset`` will be assigned. body: The loop body to be repeatedly executed. label: An optional label for identifying the instruction. **Circuit symbol:** .. parsed-literal:: β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” q_0: ─0 β”œ β”‚ β”‚ q_1: ─1 β”œ β”‚ for_loop β”‚ q_2: ─2 β”œ β”‚ β”‚ c_0: β•‘0 β•ž β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ """ def __init__( self, indexset: Iterable[int], loop_parameter: Union[Parameter, None], body: QuantumCircuit, label: Optional[str] = None, ): num_qubits = body.num_qubits num_clbits = body.num_clbits super().__init__( "for_loop", num_qubits, num_clbits, [indexset, loop_parameter, body], label=label ) @property def params(self): return self._params @params.setter def params(self, parameters): indexset, loop_parameter, body = parameters if not isinstance(loop_parameter, (Parameter, type(None))): raise CircuitError( "ForLoopOp expects a loop_parameter parameter to " "be either of type Parameter or None, but received " f"{type(loop_parameter)}." ) if not isinstance(body, QuantumCircuit): raise CircuitError( "ForLoopOp expects a body parameter to be of type " f"QuantumCircuit, but received {type(body)}." ) if body.num_qubits != self.num_qubits or body.num_clbits != self.num_clbits: raise CircuitError( "Attempted to assign a body parameter with a num_qubits or " "num_clbits different than that of the ForLoopOp. " f"ForLoopOp num_qubits/clbits: {self.num_qubits}/{self.num_clbits} " f"Supplied body num_qubits/clbits: {body.num_qubits}/{body.num_clbits}." ) if ( loop_parameter is not None and loop_parameter not in body.parameters and loop_parameter.name in (p.name for p in body.parameters) ): warnings.warn( "The Parameter provided as a loop_parameter was not found " "on the loop body and so no binding of the indexset to loop " "parameter will occur. A different Parameter of the same name " f"({loop_parameter.name}) was found. If you intended to loop " "over that Parameter, please use that Parameter instance as " "the loop_parameter.", stacklevel=2, ) # Consume indexset into a tuple unless it was provided as a range. # Preserve ranges so that they can be exported as OpenQASM3 ranges. indexset = indexset if isinstance(indexset, range) else tuple(indexset) self._params = [indexset, loop_parameter, body] @property def blocks(self): return (self._params[2],) def replace_blocks(self, blocks): (body,) = blocks return ForLoopOp(self.params[0], self.params[1], body, label=self.label) class ForLoopContext: """A context manager for building up ``for`` loops onto circuits in a natural order, without having to construct the loop body first. Within the block, a lot of the bookkeeping is done for you; you do not need to keep track of which qubits and clbits you are using, for example, and a loop parameter will be allocated for you, if you do not supply one yourself. All normal methods of accessing the qubits on the underlying :obj:`~QuantumCircuit` will work correctly, and resolve into correct accesses within the interior block. You generally should never need to instantiate this object directly. Instead, use :obj:`.QuantumCircuit.for_loop` in its context-manager form, i.e. by not supplying a ``body`` or sets of qubits and clbits. Example usage:: import math from qiskit import QuantumCircuit qc = QuantumCircuit(2, 1) with qc.for_loop(range(5)) as i: qc.rx(i * math.pi/4, 0) qc.cx(0, 1) qc.measure(0, 0) qc.break_loop().c_if(0, True) This context should almost invariably be created by a :meth:`.QuantumCircuit.for_loop` call, and the resulting instance is a "friend" of the calling circuit. The context will manipulate the circuit's defined scopes when it is entered (by pushing a new scope onto the stack) and exited (by popping its scope, building it, and appending the resulting :obj:`.ForLoopOp`). .. warning:: This is an internal interface and no part of it should be relied upon outside of Qiskit Terra. """ # Class-level variable keep track of the number of auto-generated loop variables, so we don't # get naming clashes. _generated_loop_parameters = 0 __slots__ = ( "_circuit", "_generate_loop_parameter", "_loop_parameter", "_indexset", "_label", "_used", ) def __init__( self, circuit: QuantumCircuit, indexset: Iterable[int], loop_parameter: Optional[Parameter] = None, *, label: Optional[str] = None, ): self._circuit = circuit self._generate_loop_parameter = loop_parameter is None self._loop_parameter = loop_parameter # We can pass through `range` instances because OpenQASM 3 has native support for this type # of iterator set. self._indexset = indexset if isinstance(indexset, range) else tuple(indexset) self._label = label self._used = False def __enter__(self): if self._used: raise CircuitError("A for-loop context manager cannot be re-entered.") self._used = True self._circuit._push_scope() if self._generate_loop_parameter: self._loop_parameter = Parameter(f"_loop_i_{self._generated_loop_parameters}") type(self)._generated_loop_parameters += 1 return self._loop_parameter def __exit__(self, exc_type, exc_val, exc_tb): if exc_type is not None: # If we're leaving the context manager because an exception was raised, there's nothing # to do except restore the circuit state. self._circuit._pop_scope() return False scope = self._circuit._pop_scope() # Loops do not need to pass any further resources in, because this scope itself defines the # extent of ``break`` and ``continue`` statements. body = scope.build(scope.qubits, scope.clbits) # We always bind the loop parameter if the user gave it to us, even if it isn't actually # used, because they requested we do that by giving us a parameter. However, if they asked # us to auto-generate a parameter, then we only add it if they actually used it, to avoid # using unnecessary resources. if self._generate_loop_parameter and self._loop_parameter not in body.parameters: loop_parameter = None else: loop_parameter = self._loop_parameter self._circuit.append( ForLoopOp(self._indexset, loop_parameter, body, label=self._label), tuple(body.qubits), tuple(body.clbits), ) return False
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- 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=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Piecewise polynomial Chebyshev approximation to a given f(x).""" from __future__ import annotations from typing import Callable import numpy as np from numpy.polynomial.chebyshev import Chebyshev from qiskit.circuit import QuantumRegister, AncillaRegister from qiskit.circuit.library.blueprintcircuit import BlueprintCircuit from qiskit.circuit.exceptions import CircuitError from .piecewise_polynomial_pauli_rotations import PiecewisePolynomialPauliRotations class PiecewiseChebyshev(BlueprintCircuit): r"""Piecewise Chebyshev approximation to an input function. For a given function :math:`f(x)` and degree :math:`d`, this class implements a piecewise polynomial Chebyshev approximation on :math:`n` qubits to :math:`f(x)` on the given intervals. All the polynomials in the approximation are of degree :math:`d`. The values of the parameters are calculated according to [1] and see [2] for a more detailed explanation of the circuit construction and how it acts on the qubits. Examples: .. plot:: :include-source: import numpy as np from qiskit import QuantumCircuit from qiskit.circuit.library.arithmetic.piecewise_chebyshev import PiecewiseChebyshev f_x, degree, breakpoints, num_state_qubits = lambda x: np.arcsin(1 / x), 2, [2, 4], 2 pw_approximation = PiecewiseChebyshev(f_x, degree, breakpoints, num_state_qubits) pw_approximation._build() qc = QuantumCircuit(pw_approximation.num_qubits) qc.h(list(range(num_state_qubits))) qc.append(pw_approximation.to_instruction(), qc.qubits) qc.draw(output='mpl') References: [1]: Haener, T., Roetteler, M., & Svore, K. M. (2018). Optimizing Quantum Circuits for Arithmetic. `arXiv:1805.12445 <http://arxiv.org/abs/1805.12445>`_ [2]: Carrera Vazquez, A., Hiptmair, H., & Woerner, S. (2022). Enhancing the Quantum Linear Systems Algorithm Using Richardson Extrapolation. `ACM Transactions on Quantum Computing 3, 1, Article 2 <https://doi.org/10.1145/3490631>`_ """ def __init__( self, f_x: float | Callable[[int], float], degree: int | None = None, breakpoints: list[int] | None = None, num_state_qubits: int | None = None, name: str = "pw_cheb", ) -> None: r""" Args: f_x: the function to be approximated. Constant functions should be specified as f_x = constant. degree: the degree of the polynomials. Defaults to ``1``. breakpoints: the breakpoints to define the piecewise-linear function. Defaults to the full interval. num_state_qubits: number of qubits representing the state. name: The name of the circuit object. """ super().__init__(name=name) # define internal parameters self._num_state_qubits = None # Store parameters self._f_x = f_x self._degree = degree if degree is not None else 1 self._breakpoints = breakpoints if breakpoints is not None else [0] self._polynomials: list[list[float]] | None = None self.num_state_qubits = num_state_qubits def _check_configuration(self, raise_on_failure: bool = True) -> bool: """Check if the current configuration is valid.""" valid = True if self._f_x is None: valid = False if raise_on_failure: raise AttributeError("The function to be approximated has not been set.") if self._degree is None: valid = False if raise_on_failure: raise AttributeError("The degree of the polynomials has not been set.") if self._breakpoints is None: valid = False if raise_on_failure: raise AttributeError("The breakpoints have not been set.") if self.num_state_qubits is None: valid = False if raise_on_failure: raise AttributeError("The number of qubits has not been set.") if self.num_qubits < self.num_state_qubits + 1: valid = False if raise_on_failure: raise CircuitError( "Not enough qubits in the circuit, need at least " "{}.".format(self.num_state_qubits + 1) ) return valid @property def f_x(self) -> float | Callable[[int], float]: """The function to be approximated. Returns: The function to be approximated. """ return self._f_x @f_x.setter def f_x(self, f_x: float | Callable[[int], float] | None) -> None: """Set the function to be approximated. Note that this may change the underlying quantum register, if the number of state qubits changes. Args: f_x: The new function to be approximated. """ if self._f_x is None or f_x != self._f_x: self._invalidate() self._f_x = f_x self._reset_registers(self.num_state_qubits) @property def degree(self) -> int: """The degree of the polynomials. Returns: The degree of the polynomials. """ return self._degree @degree.setter def degree(self, degree: int | None) -> None: """Set the error tolerance. Note that this may change the underlying quantum register, if the number of state qubits changes. Args: degree: The new degree. """ if self._degree is None or degree != self._degree: self._invalidate() self._degree = degree self._reset_registers(self.num_state_qubits) @property def breakpoints(self) -> list[int]: """The breakpoints for the piecewise approximation. Returns: The breakpoints for the piecewise approximation. """ breakpoints = self._breakpoints # it the state qubits are set ensure that the breakpoints match beginning and end if self.num_state_qubits is not None: num_states = 2**self.num_state_qubits # If the last breakpoint is < num_states, add the identity polynomial if breakpoints[-1] < num_states: breakpoints = breakpoints + [num_states] # If the first breakpoint is > 0, add the identity polynomial if breakpoints[0] > 0: breakpoints = [0] + breakpoints return breakpoints @breakpoints.setter def breakpoints(self, breakpoints: list[int] | None) -> None: """Set the breakpoints for the piecewise approximation. Note that this may change the underlying quantum register, if the number of state qubits changes. Args: breakpoints: The new breakpoints for the piecewise approximation. """ if self._breakpoints is None or breakpoints != self._breakpoints: self._invalidate() self._breakpoints = breakpoints if breakpoints is not None else [0] self._reset_registers(self.num_state_qubits) @property def polynomials(self) -> list[list[float]]: """The polynomials for the piecewise approximation. Returns: The polynomials for the piecewise approximation. Raises: TypeError: If the input function is not in the correct format. """ if self.num_state_qubits is None: return [[]] # note this must be the private attribute since we handle missing breakpoints at # 0 and 2 ^ num_qubits here (e.g. if the function we approximate is not defined at 0 # and the user takes that into account we just add an identity) breakpoints = self._breakpoints # Need to take into account the case in which no breakpoints were provided in first place if breakpoints == [0]: breakpoints = [0, 2**self.num_state_qubits] num_intervals = len(breakpoints) # Calculate the polynomials polynomials = [] for i in range(0, num_intervals - 1): # Calculate the polynomial approximating the function on the current interval try: # If the function is constant don't call Chebyshev (not necessary and gives errors) if isinstance(self.f_x, (float, int)): # Append directly to list of polynomials polynomials.append([self.f_x]) else: poly = Chebyshev.interpolate( self.f_x, self.degree, domain=[breakpoints[i], breakpoints[i + 1]] ) # Convert polynomial to the standard basis and rescale it for the rotation gates poly = 2 * poly.convert(kind=np.polynomial.Polynomial).coef # Convert to list and append polynomials.append(poly.tolist()) except ValueError as err: raise TypeError( " <lambda>() missing 1 required positional argument: '" + self.f_x.__code__.co_varnames[0] + "'." + " Constant functions should be specified as 'f_x = constant'." ) from err # If the last breakpoint is < 2 ** num_qubits, add the identity polynomial if breakpoints[-1] < 2**self.num_state_qubits: polynomials = polynomials + [[2 * np.arcsin(1)]] # If the first breakpoint is > 0, add the identity polynomial if breakpoints[0] > 0: polynomials = [[2 * np.arcsin(1)]] + polynomials return polynomials @polynomials.setter def polynomials(self, polynomials: list[list[float]] | None) -> None: """Set the polynomials for the piecewise approximation. Note that this may change the underlying quantum register, if the number of state qubits changes. Args: polynomials: The new breakpoints for the piecewise approximation. """ if self._polynomials is None or polynomials != self._polynomials: self._invalidate() self._polynomials = polynomials self._reset_registers(self.num_state_qubits) @property def num_state_qubits(self) -> int: r"""The number of state qubits representing the state :math:`|x\rangle`. Returns: The number of state qubits. """ return self._num_state_qubits @num_state_qubits.setter def num_state_qubits(self, num_state_qubits: int | None) -> None: """Set the number of state qubits. Note that this may change the underlying quantum register, if the number of state qubits changes. Args: num_state_qubits: The new number of qubits. """ if self._num_state_qubits is None or num_state_qubits != self._num_state_qubits: self._invalidate() self._num_state_qubits = num_state_qubits # Set breakpoints if they haven't been set if num_state_qubits is not None and self._breakpoints is None: self.breakpoints = [0, 2**num_state_qubits] self._reset_registers(num_state_qubits) def _reset_registers(self, num_state_qubits: int | None) -> None: """Reset the registers.""" self.qregs = [] if num_state_qubits is not None: qr_state = QuantumRegister(num_state_qubits, "state") qr_target = QuantumRegister(1, "target") self.qregs = [qr_state, qr_target] num_ancillas = num_state_qubits if num_ancillas > 0: qr_ancilla = AncillaRegister(num_ancillas) self.add_register(qr_ancilla) def _build(self): """Build the circuit if not already build. The operation is considered successful when q_objective is :math:`|1>`""" if self._is_built: return super()._build() poly_r = PiecewisePolynomialPauliRotations( self.num_state_qubits, self.breakpoints, self.polynomials, name=self.name ) # qr_state = self.qubits[: self.num_state_qubits] # qr_target = [self.qubits[self.num_state_qubits]] # qr_ancillas = self.qubits[self.num_state_qubits + 1 :] # Apply polynomial approximation self.append(poly_r.to_gate(), self.qubits)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Piecewise-polynomially-controlled Pauli rotations.""" from __future__ import annotations from typing import List, Optional import numpy as np from qiskit.circuit import QuantumRegister, AncillaRegister, QuantumCircuit from qiskit.circuit.exceptions import CircuitError from .functional_pauli_rotations import FunctionalPauliRotations from .polynomial_pauli_rotations import PolynomialPauliRotations from .integer_comparator import IntegerComparator class PiecewisePolynomialPauliRotations(FunctionalPauliRotations): r"""Piecewise-polynomially-controlled Pauli rotations. This class implements a piecewise polynomial (not necessarily continuous) function, :math:`f(x)`, on qubit amplitudes, which is defined through breakpoints and coefficients as follows. Suppose the breakpoints :math:`(x_0, ..., x_J)` are a subset of :math:`[0, 2^n-1]`, where :math:`n` is the number of state qubits. Further on, denote the corresponding coefficients by :math:`[a_{j,1},...,a_{j,d}]`, where :math:`d` is the highest degree among all polynomials. Then :math:`f(x)` is defined as: .. math:: f(x) = \begin{cases} 0, x < x_0 \\ \sum_{i=0}^{i=d}a_{j,i}/2 x^i, x_j \leq x < x_{j+1} \end{cases} where if given the same number of breakpoints as polynomials, we implicitly assume :math:`x_{J+1} = 2^n`. .. note:: Note the :math:`1/2` factor in the coefficients of :math:`f(x)`, this is consistent with Qiskit's Pauli rotations. Examples: >>> from qiskit import QuantumCircuit >>> from qiskit.circuit.library.arithmetic.piecewise_polynomial_pauli_rotations import\ ... PiecewisePolynomialPauliRotations >>> qubits, breakpoints, coeffs = (2, [0, 2], [[0, -1.2],[-1, 1, 3]]) >>> poly_r = PiecewisePolynomialPauliRotations(num_state_qubits=qubits, ...breakpoints=breakpoints, coeffs=coeffs) >>> >>> qc = QuantumCircuit(poly_r.num_qubits) >>> qc.h(list(range(qubits))); >>> qc.append(poly_r.to_instruction(), list(range(qc.num_qubits))); >>> qc.draw() β”Œβ”€β”€β”€β”β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” q_0: ─ H β”œβ”€0 β”œ β”œβ”€β”€β”€β”€β”‚ β”‚ q_1: ─ H β”œβ”€1 β”œ β””β”€β”€β”€β”˜β”‚ β”‚ q_2: ──────2 β”œ β”‚ pw_poly β”‚ q_3: ──────3 β”œ β”‚ β”‚ q_4: ──────4 β”œ β”‚ β”‚ q_5: ──────5 β”œ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ References: [1]: Haener, T., Roetteler, M., & Svore, K. M. (2018). Optimizing Quantum Circuits for Arithmetic. `arXiv:1805.12445 <http://arxiv.org/abs/1805.12445>`_ [2]: Carrera Vazquez, A., Hiptmair, R., & Woerner, S. (2022). Enhancing the Quantum Linear Systems Algorithm using Richardson Extrapolation. `ACM Transactions on Quantum Computing 3, 1, Article 2 <https://doi.org/10.1145/3490631>`_ """ def __init__( self, num_state_qubits: Optional[int] = None, breakpoints: Optional[List[int]] = None, coeffs: Optional[List[List[float]]] = None, basis: str = "Y", name: str = "pw_poly", ) -> None: """ Args: num_state_qubits: The number of qubits representing the state. breakpoints: The breakpoints to define the piecewise-linear function. Defaults to ``[0]``. coeffs: The coefficients of the polynomials for different segments of the piecewise-linear function. ``coeffs[j][i]`` is the coefficient of the i-th power of x for the j-th polynomial. Defaults to linear: ``[[1]]``. basis: The type of Pauli rotation (``'X'``, ``'Y'``, ``'Z'``). name: The name of the circuit. """ # store parameters self._breakpoints = breakpoints if breakpoints is not None else [0] self._coeffs = coeffs if coeffs is not None else [[1]] # store a list of coefficients as homogeneous polynomials adding 0's where necessary self._hom_coeffs = [] self._degree = len(max(self._coeffs, key=len)) - 1 for poly in self._coeffs: self._hom_coeffs.append(poly + [0] * (self._degree + 1 - len(poly))) super().__init__(num_state_qubits=num_state_qubits, basis=basis, name=name) @property def breakpoints(self) -> List[int]: """The breakpoints of the piecewise polynomial function. The function is polynomial in the intervals ``[point_i, point_{i+1}]`` where the last point implicitly is ``2**(num_state_qubits + 1)``. Returns: The list of breakpoints. """ if ( self.num_state_qubits is not None and len(self._breakpoints) == len(self.coeffs) and self._breakpoints[-1] < 2**self.num_state_qubits ): return self._breakpoints + [2**self.num_state_qubits] return self._breakpoints @breakpoints.setter def breakpoints(self, breakpoints: List[int]) -> None: """Set the breakpoints. Args: breakpoints: The new breakpoints. """ self._invalidate() self._breakpoints = breakpoints if self.num_state_qubits and breakpoints: self._reset_registers(self.num_state_qubits) @property def coeffs(self) -> List[List[float]]: """The coefficients of the polynomials. Returns: The polynomial coefficients per interval as nested lists. """ return self._coeffs @coeffs.setter def coeffs(self, coeffs: List[List[float]]) -> None: """Set the polynomials. Args: coeffs: The new polynomials. """ self._invalidate() self._coeffs = coeffs # update the homogeneous polynomials and degree self._hom_coeffs = [] self._degree = len(max(self._coeffs, key=len)) - 1 for poly in self._coeffs: self._hom_coeffs.append(poly + [0] * (self._degree + 1 - len(poly))) if self.num_state_qubits and coeffs: self._reset_registers(self.num_state_qubits) @property def mapped_coeffs(self) -> List[List[float]]: """The coefficients mapped to the internal representation, since we only compare x>=breakpoint. Returns: The mapped coefficients. """ mapped_coeffs = [] # First polynomial mapped_coeffs.append(self._hom_coeffs[0]) for i in range(1, len(self._hom_coeffs)): mapped_coeffs.append([]) for j in range(0, self._degree + 1): mapped_coeffs[i].append(self._hom_coeffs[i][j] - self._hom_coeffs[i - 1][j]) return mapped_coeffs @property def contains_zero_breakpoint(self) -> bool | np.bool_: """Whether 0 is the first breakpoint. Returns: True, if 0 is the first breakpoint, otherwise False. """ return np.isclose(0, self.breakpoints[0]) def evaluate(self, x: float) -> float: """Classically evaluate the piecewise polynomial rotation. Args: x: Value to be evaluated at. Returns: Value of piecewise polynomial function at x. """ y = 0 for i in range(0, len(self.breakpoints)): y = y + (x >= self.breakpoints[i]) * (np.poly1d(self.mapped_coeffs[i][::-1])(x)) return y def _check_configuration(self, raise_on_failure: bool = True) -> bool: """Check if the current configuration is valid.""" valid = True if self.num_state_qubits is None: valid = False if raise_on_failure: raise AttributeError("The number of qubits has not been set.") if self.num_qubits < self.num_state_qubits + 1: valid = False if raise_on_failure: raise CircuitError( "Not enough qubits in the circuit, need at least " "{}.".format(self.num_state_qubits + 1) ) if len(self.breakpoints) != len(self.coeffs) + 1: valid = False if raise_on_failure: raise ValueError("Mismatching number of breakpoints and polynomials.") return valid def _reset_registers(self, num_state_qubits: Optional[int]) -> None: """Reset the registers.""" self.qregs = [] if num_state_qubits: qr_state = QuantumRegister(num_state_qubits) qr_target = QuantumRegister(1) self.qregs = [qr_state, qr_target] # Calculate number of ancilla qubits required num_ancillas = num_state_qubits + 1 if self.contains_zero_breakpoint: num_ancillas -= 1 if num_ancillas > 0: qr_ancilla = AncillaRegister(num_ancillas) self.add_register(qr_ancilla) def _build(self): """If not already built, build the circuit.""" if self._is_built: return super()._build() circuit = QuantumCircuit(*self.qregs, name=self.name) qr_state = circuit.qubits[: self.num_state_qubits] qr_target = [circuit.qubits[self.num_state_qubits]] # Ancilla for the comparator circuit qr_ancilla = circuit.qubits[self.num_state_qubits + 1 :] # apply comparators and controlled linear rotations for i, point in enumerate(self.breakpoints[:-1]): if i == 0 and self.contains_zero_breakpoint: # apply rotation poly_r = PolynomialPauliRotations( num_state_qubits=self.num_state_qubits, coeffs=self.mapped_coeffs[i], basis=self.basis, ) circuit.append(poly_r.to_gate(), qr_state[:] + qr_target) else: # apply Comparator comp = IntegerComparator(num_state_qubits=self.num_state_qubits, value=point) qr_state_full = qr_state[:] + [qr_ancilla[0]] # add compare qubit qr_remaining_ancilla = qr_ancilla[1:] # take remaining ancillas circuit.append( comp.to_gate(), qr_state_full[:] + qr_remaining_ancilla[: comp.num_ancillas] ) # apply controlled rotation poly_r = PolynomialPauliRotations( num_state_qubits=self.num_state_qubits, coeffs=self.mapped_coeffs[i], basis=self.basis, ) circuit.append( poly_r.to_gate().control(), [qr_ancilla[0]] + qr_state[:] + qr_target ) # uncompute comparator circuit.append( comp.to_gate().inverse(), qr_state_full[:] + qr_remaining_ancilla[: comp.num_ancillas], ) self.append(circuit.to_gate(), self.qubits)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Prepare a quantum state from the state where all qubits are 0.""" from typing import Union, Optional import math import numpy as np from qiskit.exceptions import QiskitError from qiskit.circuit import QuantumCircuit, QuantumRegister, Qubit from qiskit.circuit.gate import Gate from qiskit.circuit.library.standard_gates.x import CXGate, XGate from qiskit.circuit.library.standard_gates.h import HGate from qiskit.circuit.library.standard_gates.s import SGate, SdgGate from qiskit.circuit.library.standard_gates.ry import RYGate from qiskit.circuit.library.standard_gates.rz import RZGate from qiskit.circuit.exceptions import CircuitError from qiskit.quantum_info import Statevector _EPS = 1e-10 # global variable used to chop very small numbers to zero class StatePreparation(Gate): """Complex amplitude state preparation. Class that implements the (complex amplitude) state preparation of some flexible collection of qubit registers. """ def __init__( self, params: Union[str, list, int, Statevector], num_qubits: Optional[int] = None, inverse: bool = False, label: Optional[str] = None, normalize: bool = False, ): r""" Args: params: * Statevector: Statevector to initialize to. * list: vector of complex amplitudes to initialize to. * string: labels of basis states of the Pauli eigenstates Z, X, Y. See :meth:`.Statevector.from_label`. Notice the order of the labels is reversed with respect to the qubit index to be applied to. Example label '01' initializes the qubit zero to :math:`|1\rangle` and the qubit one to :math:`|0\rangle`. * int: an integer that is used as a bitmap indicating which qubits to initialize to :math:`|1\rangle`. Example: setting params to 5 would initialize qubit 0 and qubit 2 to :math:`|1\rangle` and qubit 1 to :math:`|0\rangle`. num_qubits: This parameter is only used if params is an int. Indicates the total number of qubits in the `initialize` call. Example: `initialize` covers 5 qubits and params is 3. This allows qubits 0 and 1 to be initialized to :math:`|1\rangle` and the remaining 3 qubits to be initialized to :math:`|0\rangle`. inverse: if True, the inverse state is constructed. label: An optional label for the gate normalize (bool): Whether to normalize an input array to a unit vector. Raises: QiskitError: ``num_qubits`` parameter used when ``params`` is not an integer When a Statevector argument is passed the state is prepared using a recursive initialization algorithm, including optimizations, from [1], as well as some additional optimizations including removing zero rotations and double cnots. **References:** [1] Shende, Bullock, Markov. Synthesis of Quantum Logic Circuits (2004) [`https://arxiv.org/abs/quant-ph/0406176v5`] """ self._params_arg = params self._inverse = inverse self._name = "state_preparation_dg" if self._inverse else "state_preparation" if label is None: self._label = "State Preparation Dg" if self._inverse else "State Preparation" else: self._label = f"{label} Dg" if self._inverse else label if isinstance(params, Statevector): params = params.data if not isinstance(params, int) and num_qubits is not None: raise QiskitError( "The num_qubits parameter to StatePreparation should only be" " used when params is an integer" ) self._from_label = isinstance(params, str) self._from_int = isinstance(params, int) # if initialized from a vector, check that the parameters are normalized if not self._from_label and not self._from_int: norm = np.linalg.norm(params) if normalize: params = np.array(params, dtype=np.complex128) / norm elif not math.isclose(norm, 1.0, abs_tol=_EPS): raise QiskitError(f"Sum of amplitudes-squared is not 1, but {norm}.") num_qubits = self._get_num_qubits(num_qubits, params) params = [params] if isinstance(params, int) else params super().__init__(self._name, num_qubits, params, label=self._label) def _define(self): if self._from_label: self.definition = self._define_from_label() elif self._from_int: self.definition = self._define_from_int() else: self.definition = self._define_synthesis() def _define_from_label(self): q = QuantumRegister(self.num_qubits, "q") initialize_circuit = QuantumCircuit(q, name="init_def") for qubit, param in enumerate(reversed(self.params)): if param == "1": initialize_circuit.append(XGate(), [q[qubit]]) elif param == "+": initialize_circuit.append(HGate(), [q[qubit]]) elif param == "-": initialize_circuit.append(XGate(), [q[qubit]]) initialize_circuit.append(HGate(), [q[qubit]]) elif param == "r": # |+i> initialize_circuit.append(HGate(), [q[qubit]]) initialize_circuit.append(SGate(), [q[qubit]]) elif param == "l": # |-i> initialize_circuit.append(HGate(), [q[qubit]]) initialize_circuit.append(SdgGate(), [q[qubit]]) if self._inverse: initialize_circuit = initialize_circuit.inverse() return initialize_circuit def _define_from_int(self): q = QuantumRegister(self.num_qubits, "q") initialize_circuit = QuantumCircuit(q, name="init_def") # Convert to int since QuantumCircuit converted to complex # and make a bit string and reverse it intstr = f"{int(np.real(self.params[0])):0{self.num_qubits}b}"[::-1] # Raise if number of bits is greater than num_qubits if len(intstr) > self.num_qubits: raise QiskitError( "StatePreparation integer has %s bits, but this exceeds the" " number of qubits in the circuit, %s." % (len(intstr), self.num_qubits) ) for qubit, bit in enumerate(intstr): if bit == "1": initialize_circuit.append(XGate(), [q[qubit]]) # note: X is it's own inverse, so even if self._inverse is True, # we don't need to invert anything return initialize_circuit def _define_synthesis(self): """Calculate a subcircuit that implements this initialization Implements a recursive initialization algorithm, including optimizations, from "Synthesis of Quantum Logic Circuits" Shende, Bullock, Markov https://arxiv.org/abs/quant-ph/0406176v5 Additionally implements some extra optimizations: remove zero rotations and double cnots. """ # call to generate the circuit that takes the desired vector to zero disentangling_circuit = self._gates_to_uncompute() # invert the circuit to create the desired vector from zero (assuming # the qubits are in the zero state) if self._inverse is False: initialize_instr = disentangling_circuit.to_instruction().inverse() else: initialize_instr = disentangling_circuit.to_instruction() q = QuantumRegister(self.num_qubits, "q") initialize_circuit = QuantumCircuit(q, name="init_def") initialize_circuit.append(initialize_instr, q[:]) return initialize_circuit def _get_num_qubits(self, num_qubits, params): """Get number of qubits needed for state preparation""" if isinstance(params, str): num_qubits = len(params) elif isinstance(params, int): if num_qubits is None: num_qubits = int(math.log2(params)) + 1 else: num_qubits = math.log2(len(params)) # Check if param is a power of 2 if num_qubits == 0 or not num_qubits.is_integer(): raise QiskitError("Desired statevector length not a positive power of 2.") num_qubits = int(num_qubits) return num_qubits def inverse(self): """Return inverted StatePreparation""" label = ( None if self._label in ("State Preparation", "State Preparation Dg") else self._label ) return StatePreparation(self._params_arg, inverse=not self._inverse, label=label) def broadcast_arguments(self, qargs, cargs): flat_qargs = [qarg for sublist in qargs for qarg in sublist] if self.num_qubits != len(flat_qargs): raise QiskitError( "StatePreparation parameter vector has %d elements, therefore expects %s " "qubits. However, %s were provided." % (2**self.num_qubits, self.num_qubits, len(flat_qargs)) ) yield flat_qargs, [] def validate_parameter(self, parameter): """StatePreparation instruction parameter can be str, int, float, and complex.""" # StatePreparation instruction parameter can be str if isinstance(parameter, str): if parameter in ["0", "1", "+", "-", "l", "r"]: return parameter raise CircuitError( "invalid param label {} for instruction {}. Label should be " "0, 1, +, -, l, or r ".format(type(parameter), self.name) ) # StatePreparation instruction parameter can be int, float, and complex. if isinstance(parameter, (int, float, complex)): return complex(parameter) elif isinstance(parameter, np.number): return complex(parameter.item()) else: raise CircuitError(f"invalid param type {type(parameter)} for instruction {self.name}") def _return_repeat(self, exponent: float) -> "Gate": return Gate(name=f"{self.name}*{exponent}", num_qubits=self.num_qubits, params=[]) def _gates_to_uncompute(self): """Call to create a circuit with gates that take the desired vector to zero. Returns: QuantumCircuit: circuit to take self.params vector to :math:`|{00\\ldots0}\\rangle` """ q = QuantumRegister(self.num_qubits) circuit = QuantumCircuit(q, name="disentangler") # kick start the peeling loop, and disentangle one-by-one from LSB to MSB remaining_param = self.params for i in range(self.num_qubits): # work out which rotations must be done to disentangle the LSB # qubit (we peel away one qubit at a time) (remaining_param, thetas, phis) = StatePreparation._rotations_to_disentangle( remaining_param ) # perform the required rotations to decouple the LSB qubit (so that # it can be "factored" out, leaving a shorter amplitude vector to peel away) add_last_cnot = True if np.linalg.norm(phis) != 0 and np.linalg.norm(thetas) != 0: add_last_cnot = False if np.linalg.norm(phis) != 0: rz_mult = self._multiplex(RZGate, phis, last_cnot=add_last_cnot) circuit.append(rz_mult.to_instruction(), q[i : self.num_qubits]) if np.linalg.norm(thetas) != 0: ry_mult = self._multiplex(RYGate, thetas, last_cnot=add_last_cnot) circuit.append(ry_mult.to_instruction().reverse_ops(), q[i : self.num_qubits]) circuit.global_phase -= np.angle(sum(remaining_param)) return circuit @staticmethod def _rotations_to_disentangle(local_param): """ Static internal method to work out Ry and Rz rotation angles used to disentangle the LSB qubit. These rotations make up the block diagonal matrix U (i.e. multiplexor) that disentangles the LSB. [[Ry(theta_1).Rz(phi_1) 0 . . 0], [0 Ry(theta_2).Rz(phi_2) . 0], . . 0 0 Ry(theta_2^n).Rz(phi_2^n)]] """ remaining_vector = [] thetas = [] phis = [] param_len = len(local_param) for i in range(param_len // 2): # Ry and Rz rotations to move bloch vector from 0 to "imaginary" # qubit # (imagine a qubit state signified by the amplitudes at index 2*i # and 2*(i+1), corresponding to the select qubits of the # multiplexor being in state |i>) (remains, add_theta, add_phi) = StatePreparation._bloch_angles( local_param[2 * i : 2 * (i + 1)] ) remaining_vector.append(remains) # rotations for all imaginary qubits of the full vector # to move from where it is to zero, hence the negative sign thetas.append(-add_theta) phis.append(-add_phi) return remaining_vector, thetas, phis @staticmethod def _bloch_angles(pair_of_complex): """ Static internal method to work out rotation to create the passed-in qubit from the zero vector. """ [a_complex, b_complex] = pair_of_complex # Force a and b to be complex, as otherwise numpy.angle might fail. a_complex = complex(a_complex) b_complex = complex(b_complex) mag_a = abs(a_complex) final_r = np.sqrt(mag_a**2 + np.absolute(b_complex) ** 2) if final_r < _EPS: theta = 0 phi = 0 final_r = 0 final_t = 0 else: theta = 2 * np.arccos(mag_a / final_r) a_arg = np.angle(a_complex) b_arg = np.angle(b_complex) final_t = a_arg + b_arg phi = b_arg - a_arg return final_r * np.exp(1.0j * final_t / 2), theta, phi def _multiplex(self, target_gate, list_of_angles, last_cnot=True): """ Return a recursive implementation of a multiplexor circuit, where each instruction itself has a decomposition based on smaller multiplexors. The LSB is the multiplexor "data" and the other bits are multiplexor "select". Args: target_gate (Gate): Ry or Rz gate to apply to target qubit, multiplexed over all other "select" qubits list_of_angles (list[float]): list of rotation angles to apply Ry and Rz last_cnot (bool): add the last cnot if last_cnot = True Returns: DAGCircuit: the circuit implementing the multiplexor's action """ list_len = len(list_of_angles) local_num_qubits = int(math.log2(list_len)) + 1 q = QuantumRegister(local_num_qubits) circuit = QuantumCircuit(q, name="multiplex" + str(local_num_qubits)) lsb = q[0] msb = q[local_num_qubits - 1] # case of no multiplexing: base case for recursion if local_num_qubits == 1: circuit.append(target_gate(list_of_angles[0]), [q[0]]) return circuit # calc angle weights, assuming recursion (that is the lower-level # requested angles have been correctly implemented by recursion angle_weight = np.kron([[0.5, 0.5], [0.5, -0.5]], np.identity(2 ** (local_num_qubits - 2))) # calc the combo angles list_of_angles = angle_weight.dot(np.array(list_of_angles)).tolist() # recursive step on half the angles fulfilling the above assumption multiplex_1 = self._multiplex(target_gate, list_of_angles[0 : (list_len // 2)], False) circuit.append(multiplex_1.to_instruction(), q[0:-1]) # attach CNOT as follows, thereby flipping the LSB qubit circuit.append(CXGate(), [msb, lsb]) # implement extra efficiency from the paper of cancelling adjacent # CNOTs (by leaving out last CNOT and reversing (NOT inverting) the # second lower-level multiplex) multiplex_2 = self._multiplex(target_gate, list_of_angles[(list_len // 2) :], False) if list_len > 1: circuit.append(multiplex_2.to_instruction().reverse_ops(), q[0:-1]) else: circuit.append(multiplex_2.to_instruction(), q[0:-1]) # attach a final CNOT if last_cnot: circuit.append(CXGate(), [msb, lsb]) return circuit def prepare_state(self, state, qubits=None, label=None, normalize=False): r"""Prepare qubits in a specific state. This class implements a state preparing unitary. Unlike :class:`qiskit.extensions.Initialize` it does not reset the qubits first. Args: state (str or list or int or Statevector): * Statevector: Statevector to initialize to. * str: labels of basis states of the Pauli eigenstates Z, X, Y. See :meth:`.Statevector.from_label`. Notice the order of the labels is reversed with respect to the qubit index to be applied to. Example label '01' initializes the qubit zero to :math:`|1\rangle` and the qubit one to :math:`|0\rangle`. * list: vector of complex amplitudes to initialize to. * int: an integer that is used as a bitmap indicating which qubits to initialize to :math:`|1\rangle`. Example: setting params to 5 would initialize qubit 0 and qubit 2 to :math:`|1\rangle` and qubit 1 to :math:`|0\rangle`. qubits (QuantumRegister or Qubit or int): * QuantumRegister: A list of qubits to be initialized [Default: None]. * Qubit: Single qubit to be initialized [Default: None]. * int: Index of qubit to be initialized [Default: None]. * list: Indexes of qubits to be initialized [Default: None]. label (str): An optional label for the gate normalize (bool): Whether to normalize an input array to a unit vector. Returns: qiskit.circuit.Instruction: a handle to the instruction that was just initialized Examples: Prepare a qubit in the state :math:`(|0\rangle - |1\rangle) / \sqrt{2}`. .. code-block:: import numpy as np from qiskit import QuantumCircuit circuit = QuantumCircuit(1) circuit.prepare_state([1/np.sqrt(2), -1/np.sqrt(2)], 0) circuit.draw() output: .. parsed-literal:: β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” q_0: ─ State Preparation(0.70711,-0.70711) β”œ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ Prepare from a string two qubits in the state :math:`|10\rangle`. The order of the labels is reversed with respect to qubit index. More information about labels for basis states are in :meth:`.Statevector.from_label`. .. code-block:: import numpy as np from qiskit import QuantumCircuit circuit = QuantumCircuit(2) circuit.prepare_state('01', circuit.qubits) circuit.draw() output: .. parsed-literal:: β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” q_0: ─0 β”œ β”‚ State Preparation(0,1) β”‚ q_1: ─1 β”œ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ Initialize two qubits from an array of complex amplitudes .. code-block:: import numpy as np from qiskit import QuantumCircuit circuit = QuantumCircuit(2) circuit.prepare_state([0, 1/np.sqrt(2), -1.j/np.sqrt(2), 0], circuit.qubits) circuit.draw() output: .. parsed-literal:: β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” q_0: ─0 β”œ β”‚ State Preparation(0,0.70711,-0.70711j,0) β”‚ q_1: ─1 β”œ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ """ if qubits is None: qubits = self.qubits elif isinstance(qubits, (int, np.integer, slice, Qubit)): qubits = [qubits] num_qubits = len(qubits) if isinstance(state, int) else None return self.append( StatePreparation(state, num_qubits, label=label, normalize=normalize), qubits ) QuantumCircuit.prepare_state = prepare_state
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Multiple-Control, Multiple-Target Gate.""" from __future__ import annotations from collections.abc import Callable from qiskit import circuit from qiskit.circuit import ControlledGate, Gate, Qubit, QuantumRegister, QuantumCircuit from qiskit.exceptions import QiskitError from ..standard_gates import XGate, YGate, ZGate, HGate, TGate, TdgGate, SGate, SdgGate class MCMT(QuantumCircuit): """The multi-controlled multi-target gate, for an arbitrary singly controlled target gate. For example, the H gate controlled on 3 qubits and acting on 2 target qubit is represented as: .. parsed-literal:: ───■──── β”‚ ───■──── β”‚ ───■──── β”Œβ”€β”€β”΄β”€β”€β”€β” ─0 β”œ β”‚ 2-H β”‚ ─1 β”œ β””β”€β”€β”€β”€β”€β”€β”˜ This default implementations requires no ancilla qubits, by broadcasting the target gate to the number of target qubits and using Qiskit's generic control routine to control the broadcasted target on the control qubits. If ancilla qubits are available, a more efficient variant using the so-called V-chain decomposition can be used. This is implemented in :class:`~qiskit.circuit.library.MCMTVChain`. """ def __init__( self, gate: Gate | Callable[[QuantumCircuit, Qubit, Qubit], circuit.Instruction], num_ctrl_qubits: int, num_target_qubits: int, ) -> None: """Create a new multi-control multi-target gate. Args: gate: The gate to be applied controlled on the control qubits and applied to the target qubits. Can be either a Gate or a circuit method. If it is a callable, it will be casted to a Gate. num_ctrl_qubits: The number of control qubits. num_target_qubits: The number of target qubits. Raises: AttributeError: If the gate cannot be casted to a controlled gate. AttributeError: If the number of controls or targets is 0. """ if num_ctrl_qubits == 0 or num_target_qubits == 0: raise AttributeError("Need at least one control and one target qubit.") # set the internal properties and determine the number of qubits self.gate = self._identify_gate(gate) self.num_ctrl_qubits = num_ctrl_qubits self.num_target_qubits = num_target_qubits num_qubits = num_ctrl_qubits + num_target_qubits + self.num_ancilla_qubits # initialize the circuit object super().__init__(num_qubits, name="mcmt") self._label = f"{num_target_qubits}-{self.gate.name.capitalize()}" # build the circuit self._build() def _build(self): """Define the MCMT gate without ancillas.""" if self.num_target_qubits == 1: # no broadcasting needed (makes for better circuit diagrams) broadcasted_gate = self.gate else: broadcasted = QuantumCircuit(self.num_target_qubits, name=self._label) for target in list(range(self.num_target_qubits)): broadcasted.append(self.gate, [target], []) broadcasted_gate = broadcasted.to_gate() mcmt_gate = broadcasted_gate.control(self.num_ctrl_qubits) self.append(mcmt_gate, self.qubits, []) @property def num_ancilla_qubits(self): """Return the number of ancillas.""" return 0 def _identify_gate(self, gate): """Case the gate input to a gate.""" valid_gates = { "ch": HGate(), "cx": XGate(), "cy": YGate(), "cz": ZGate(), "h": HGate(), "s": SGate(), "sdg": SdgGate(), "x": XGate(), "y": YGate(), "z": ZGate(), "t": TGate(), "tdg": TdgGate(), } if isinstance(gate, ControlledGate): base_gate = gate.base_gate elif isinstance(gate, Gate): if gate.num_qubits != 1: raise AttributeError("Base gate must act on one qubit only.") base_gate = gate elif isinstance(gate, QuantumCircuit): if gate.num_qubits != 1: raise AttributeError( "The circuit you specified as control gate can only have one qubit!" ) base_gate = gate.to_gate() # raises error if circuit contains non-unitary instructions else: if callable(gate): # identify via name of the passed function name = gate.__name__ elif isinstance(gate, str): name = gate else: raise AttributeError(f"Invalid gate specified: {gate}") base_gate = valid_gates[name] return base_gate def control(self, num_ctrl_qubits=1, label=None, ctrl_state=None): """Return the controlled version of the MCMT circuit.""" if ctrl_state is None: # TODO add ctrl state implementation by adding X gates return MCMT(self.gate, self.num_ctrl_qubits + num_ctrl_qubits, self.num_target_qubits) return super().control(num_ctrl_qubits, label, ctrl_state) def inverse(self): """Return the inverse MCMT circuit, which is itself.""" return MCMT(self.gate, self.num_ctrl_qubits, self.num_target_qubits) class MCMTVChain(MCMT): """The MCMT implementation using the CCX V-chain. This implementation requires ancillas but is decomposed into a much shallower circuit than the default implementation in :class:`~qiskit.circuit.library.MCMT`. **Expanded Circuit:** .. plot:: from qiskit.circuit.library import MCMTVChain, ZGate from qiskit.tools.jupyter.library import _generate_circuit_library_visualization circuit = MCMTVChain(ZGate(), 2, 2) _generate_circuit_library_visualization(circuit.decompose()) **Examples:** >>> from qiskit.circuit.library import HGate >>> MCMTVChain(HGate(), 3, 2).draw() q_0: ──■────────────────────────■── β”‚ β”‚ q_1: ──■────────────────────────■── β”‚ β”‚ q_2: ──┼────■──────────────■────┼── β”‚ β”‚ β”Œβ”€β”€β”€β” β”‚ β”‚ q_3: ──┼────┼─── H β”œβ”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”Όβ”€β”€ β”‚ β”‚ β””β”€β”¬β”€β”˜β”Œβ”€β”€β”€β” β”‚ β”‚ q_4: ──┼────┼────┼─── H β”œβ”€β”€β”Όβ”€β”€β”€β”€β”Όβ”€β”€ β”Œβ”€β”΄β”€β” β”‚ β”‚ β””β”€β”¬β”€β”˜ β”‚ β”Œβ”€β”΄β”€β” q_5: ─ X β”œβ”€β”€β– β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”Όβ”€β”€β”€β”€β– β”€β”€β”€ X β”œ β””β”€β”€β”€β”˜β”Œβ”€β”΄β”€β” β”‚ β”‚ β”Œβ”€β”΄β”€β”β””β”€β”€β”€β”˜ q_6: ────── X β”œβ”€β”€β– β”€β”€β”€β”€β– β”€β”€β”€ X β”œβ”€β”€β”€β”€β”€ β””β”€β”€β”€β”˜ β””β”€β”€β”€β”˜ """ def _build(self): """Define the MCMT gate.""" control_qubits = self.qubits[: self.num_ctrl_qubits] target_qubits = self.qubits[ self.num_ctrl_qubits : self.num_ctrl_qubits + self.num_target_qubits ] ancilla_qubits = self.qubits[self.num_ctrl_qubits + self.num_target_qubits :] if len(ancilla_qubits) > 0: master_control = ancilla_qubits[-1] else: master_control = control_qubits[0] self._ccx_v_chain_rule(control_qubits, ancilla_qubits, reverse=False) for qubit in target_qubits: self.append(self.gate.control(), [master_control, qubit], []) self._ccx_v_chain_rule(control_qubits, ancilla_qubits, reverse=True) @property def num_ancilla_qubits(self): """Return the number of ancilla qubits required.""" return max(0, self.num_ctrl_qubits - 1) def _ccx_v_chain_rule( self, control_qubits: QuantumRegister | list[Qubit], ancilla_qubits: QuantumRegister | list[Qubit], reverse: bool = False, ) -> None: """Get the rule for the CCX V-chain. The CCX V-chain progressively computes the CCX of the control qubits and puts the final result in the last ancillary qubit. Args: control_qubits: The control qubits. ancilla_qubits: The ancilla qubits. reverse: If True, compute the chain down to the qubit. If False, compute upwards. Returns: The rule for the (reversed) CCX V-chain. Raises: QiskitError: If an insufficient number of ancilla qubits was provided. """ if len(ancilla_qubits) == 0: return if len(ancilla_qubits) < len(control_qubits) - 1: raise QiskitError("Insufficient number of ancilla qubits.") iterations = list(enumerate(range(2, len(control_qubits)))) if not reverse: self.ccx(control_qubits[0], control_qubits[1], ancilla_qubits[0]) for i, j in iterations: self.ccx(control_qubits[j], ancilla_qubits[i], ancilla_qubits[i + 1]) else: for i, j in reversed(iterations): self.ccx(control_qubits[j], ancilla_qubits[i], ancilla_qubits[i + 1]) self.ccx(control_qubits[0], control_qubits[1], ancilla_qubits[0]) def inverse(self): return MCMTVChain(self.gate, self.num_ctrl_qubits, self.num_target_qubits)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """The EfficientSU2 2-local circuit.""" from __future__ import annotations import typing from collections.abc import Callable from numpy import pi from qiskit.circuit import QuantumCircuit from qiskit.circuit.library.standard_gates import RYGate, RZGate, CXGate from .two_local import TwoLocal if typing.TYPE_CHECKING: import qiskit # pylint: disable=cyclic-import class EfficientSU2(TwoLocal): r"""The hardware efficient SU(2) 2-local circuit. The ``EfficientSU2`` circuit consists of layers of single qubit operations spanned by SU(2) and :math:`CX` entanglements. This is a heuristic pattern that can be used to prepare trial wave functions for variational quantum algorithms or classification circuit for machine learning. SU(2) stands for special unitary group of degree 2, its elements are :math:`2 \times 2` unitary matrices with determinant 1, such as the Pauli rotation gates. On 3 qubits and using the Pauli :math:`Y` and :math:`Z` su2_gates as single qubit gates, the hardware efficient SU(2) circuit is represented by: .. parsed-literal:: β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β–‘ β–‘ β–‘ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” ─ RY(ΞΈ[0]) β”œβ”€ RZ(ΞΈ[3]) β”œβ”€β–‘β”€β”€β”€β”€β”€β”€β”€β”€β– β”€β”€β”€β–‘β”€ ... ─░── RY(ΞΈ[12]) β”œβ”€ RZ(ΞΈ[15]) β”œ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β–‘ β”Œβ”€β”΄β”€β” β–‘ β–‘ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ ─ RY(ΞΈ[1]) β”œβ”€ RZ(ΞΈ[4]) β”œβ”€β–‘β”€β”€β”€β– β”€β”€β”€ X β”œβ”€β–‘β”€ ... ─░── RY(ΞΈ[13]) β”œβ”€ RZ(ΞΈ[16]) β”œ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β–‘ β”Œβ”€β”΄β”€β”β””β”€β”€β”€β”˜ β–‘ β–‘ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ ─ RY(ΞΈ[2]) β”œβ”€ RZ(ΞΈ[5]) β”œβ”€β–‘β”€β”€ X β”œβ”€β”€β”€β”€β”€β”€β–‘β”€ ... ─░── RY(ΞΈ[14]) β”œβ”€ RZ(ΞΈ[17]) β”œ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β–‘ β””β”€β”€β”€β”˜ β–‘ β–‘ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ See :class:`~qiskit.circuit.library.RealAmplitudes` for more detail on the possible arguments and options such as skipping unentanglement qubits, which apply here too. Examples: >>> circuit = EfficientSU2(3, reps=1) >>> print(circuit) β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” q_0: ─ RY(ΞΈ[0]) β”œβ”€ RZ(ΞΈ[3]) β”œβ”€β”€β– β”€β”€β”€β”€β– β”€β”€β”€ RY(ΞΈ[6]) β”œβ”€ RZ(ΞΈ[9]) β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Œβ”€β”΄β”€β” β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” q_1: ─ RY(ΞΈ[1]) β”œβ”€ RZ(ΞΈ[4]) β”œβ”€ X β”œβ”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β– β”€β”€β”€β”€β”€β”€β”€ RY(ΞΈ[7]) β”œβ”€ RZ(ΞΈ[10]) β”œ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β””β”€β”€β”€β”˜β”Œβ”€β”΄β”€β” β”Œβ”€β”΄β”€β” β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ q_2: ─ RY(ΞΈ[2]) β”œβ”€ RZ(ΞΈ[5]) β”œβ”€β”€β”€β”€β”€β”€ X β”œβ”€β”€β”€β”€ X β”œβ”€β”€β”€β”€β”€ RY(ΞΈ[8]) β”œβ”€ RZ(ΞΈ[11]) β”œ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”˜ β””β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ >>> ansatz = EfficientSU2(4, su2_gates=['rx', 'y'], entanglement='circular', reps=1) >>> qc = QuantumCircuit(4) # create a circuit and append the RY variational form >>> qc.compose(ansatz, inplace=True) >>> qc.draw() β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β”Œβ”€β”€β”€β”β”Œβ”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β” q_0: ─ RX(ΞΈ[0]) β”œβ”€ Y β”œβ”€ X β”œβ”€β”€β– β”€β”€β”€ RX(ΞΈ[4]) β”œβ”€β”€β”€β”€ Y β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”œβ”€β”€β”€β”€β””β”€β”¬β”€β”˜β”Œβ”€β”΄β”€β”β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β”Œβ”€β”€β”΄β”€β”€β”€β”΄β”€β”€β”€β” β”Œβ”€β”€β”€β” q_1: ─ RX(ΞΈ[1]) β”œβ”€ Y β”œβ”€β”€β”Όβ”€β”€β”€ X β”œβ”€β”€β”€β”€β”€β– β”€β”€β”€β”€β”€β”€β”€ RX(ΞΈ[5]) β”œβ”€β”€β”€β”€ Y β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”œβ”€β”€β”€β”€ β”‚ β””β”€β”€β”€β”˜ β”Œβ”€β”΄β”€β” β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β”Œβ”€β”€β”΄β”€β”€β”€β”΄β”€β”€β”€β”β”Œβ”€β”€β”€β” q_2: ─ RX(ΞΈ[2]) β”œβ”€ Y β”œβ”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ X β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β– β”€β”€β”€β”€β”€β”€β”€ RX(ΞΈ[6]) β”œβ”€ Y β”œ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”œβ”€β”€β”€β”€ β”‚ β””β”€β”€β”€β”˜ β”Œβ”€β”΄β”€β” β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”œβ”€β”€β”€β”€ q_3: ─ RX(ΞΈ[3]) β”œβ”€ Y β”œβ”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ X β”œβ”€β”€β”€β”€β”€ RX(ΞΈ[7]) β”œβ”€ Y β”œ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”˜ β””β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”˜ """ def __init__( self, num_qubits: int | None = None, su2_gates: str | type | qiskit.circuit.Instruction | QuantumCircuit | list[str | type | qiskit.circuit.Instruction | QuantumCircuit] | None = None, entanglement: str | list[list[int]] | Callable[[int], list[int]] = "reverse_linear", reps: int = 3, skip_unentangled_qubits: bool = False, skip_final_rotation_layer: bool = False, parameter_prefix: str = "ΞΈ", insert_barriers: bool = False, initial_state: QuantumCircuit | None = None, name: str = "EfficientSU2", flatten: bool | None = None, ) -> None: """ Args: num_qubits: The number of qubits of the EfficientSU2 circuit. reps: Specifies how often the structure of a rotation layer followed by an entanglement layer is repeated. su2_gates: The SU(2) single qubit gates to apply in single qubit gate layers. If only one gate is provided, the same gate is applied to each qubit. If a list of gates is provided, all gates are applied to each qubit in the provided order. entanglement: Specifies the entanglement structure. Can be a string ('full', 'linear' , 'reverse_linear', 'circular' or 'sca'), a list of integer-pairs specifying the indices of qubits entangled with one another, or a callable returning such a list provided with the index of the entanglement layer. Default to 'reverse_linear' entanglement. Note that 'reverse_linear' entanglement provides the same unitary as 'full' with fewer entangling gates. See the Examples section of :class:`~qiskit.circuit.library.TwoLocal` for more detail. initial_state: A `QuantumCircuit` object to prepend to the circuit. skip_unentangled_qubits: If True, the single qubit gates are only applied to qubits that are entangled with another qubit. If False, the single qubit gates are applied to each qubit in the Ansatz. Defaults to False. skip_final_rotation_layer: If False, a rotation layer is added at the end of the ansatz. If True, no rotation layer is added. parameter_prefix: The parameterized gates require a parameter to be defined, for which we use :class:`~qiskit.circuit.ParameterVector`. insert_barriers: If True, barriers are inserted in between each layer. If False, no barriers are inserted. flatten: Set this to ``True`` to output a flat circuit instead of nesting it inside multiple layers of gate objects. By default currently the contents of the output circuit will be wrapped in nested objects for cleaner visualization. However, if you're using this circuit for anything besides visualization its **strongly** recommended to set this flag to ``True`` to avoid a large performance overhead for parameter binding. """ if su2_gates is None: su2_gates = [RYGate, RZGate] super().__init__( num_qubits=num_qubits, rotation_blocks=su2_gates, entanglement_blocks=CXGate, entanglement=entanglement, reps=reps, skip_unentangled_qubits=skip_unentangled_qubits, skip_final_rotation_layer=skip_final_rotation_layer, parameter_prefix=parameter_prefix, insert_barriers=insert_barriers, initial_state=initial_state, name=name, flatten=flatten, ) @property def parameter_bounds(self) -> list[tuple[float, float]]: """Return the parameter bounds. Returns: The parameter bounds. """ return self.num_parameters * [(-pi, pi)]
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """The n-local circuit class.""" from __future__ import annotations import typing from collections.abc import Callable, Mapping, Sequence from itertools import combinations import numpy from qiskit.circuit.quantumcircuit import QuantumCircuit from qiskit.circuit.quantumregister import QuantumRegister from qiskit.circuit import Instruction, Parameter, ParameterVector, ParameterExpression from qiskit.exceptions import QiskitError from ..blueprintcircuit import BlueprintCircuit if typing.TYPE_CHECKING: import qiskit # pylint: disable=cyclic-import class NLocal(BlueprintCircuit): """The n-local circuit class. The structure of the n-local circuit are alternating rotation and entanglement layers. In both layers, parameterized circuit-blocks act on the circuit in a defined way. In the rotation layer, the blocks are applied stacked on top of each other, while in the entanglement layer according to the ``entanglement`` strategy. The circuit blocks can have arbitrary sizes (smaller equal to the number of qubits in the circuit). Each layer is repeated ``reps`` times, and by default a final rotation layer is appended. For instance, a rotation block on 2 qubits and an entanglement block on 4 qubits using ``'linear'`` entanglement yields the following circuit. .. parsed-literal:: β”Œβ”€β”€β”€β”€β”€β”€β” β–‘ β”Œβ”€β”€β”€β”€β”€β”€β” β–‘ β”Œβ”€β”€β”€β”€β”€β”€β” ─0 β”œβ”€β–‘β”€β”€0 β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ ... ─░──0 β”œ β”‚ Rot β”‚ β–‘ β”‚ β”‚β”Œβ”€β”€β”€β”€β”€β”€β” β–‘ β”‚ Rot β”‚ ─1 β”œβ”€β–‘β”€β”€1 β”œβ”€0 β”œβ”€β”€β”€β”€β”€β”€β”€β”€ ... ─░──1 β”œ β”œβ”€β”€β”€β”€β”€β”€β”€ β–‘ β”‚ Ent β”‚β”‚ β”‚β”Œβ”€β”€β”€β”€β”€β”€β” β–‘ β”œβ”€β”€β”€β”€β”€β”€β”€ ─0 β”œβ”€β–‘β”€β”€2 β”œβ”€1 β”œβ”€0 β”œ ... ─░──0 β”œ β”‚ Rot β”‚ β–‘ β”‚ β”‚β”‚ Ent β”‚β”‚ β”‚ β–‘ β”‚ Rot β”‚ ─1 β”œβ”€β–‘β”€β”€3 β”œβ”€2 β”œβ”€1 β”œ ... ─░──1 β”œ β”œβ”€β”€β”€β”€β”€β”€β”€ β–‘ β””β”€β”€β”€β”€β”€β”€β”˜β”‚ β”‚β”‚ Ent β”‚ β–‘ β”œβ”€β”€β”€β”€β”€β”€β”€ ─0 β”œβ”€β–‘β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€3 β”œβ”€2 β”œ ... ─░──0 β”œ β”‚ Rot β”‚ β–‘ β””β”€β”€β”€β”€β”€β”€β”˜β”‚ β”‚ β–‘ β”‚ Rot β”‚ ─1 β”œβ”€β–‘β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€3 β”œ ... ─░──1 β”œ β””β”€β”€β”€β”€β”€β”€β”˜ β–‘ β””β”€β”€β”€β”€β”€β”€β”˜ β–‘ β””β”€β”€β”€β”€β”€β”€β”˜ | | +---------------------------------+ repeated reps times If specified, barriers can be inserted in between every block. If an initial state object is provided, it is added in front of the NLocal. """ def __init__( self, num_qubits: int | None = None, rotation_blocks: QuantumCircuit | list[QuantumCircuit] | qiskit.circuit.Instruction | list[qiskit.circuit.Instruction] | None = None, entanglement_blocks: QuantumCircuit | list[QuantumCircuit] | qiskit.circuit.Instruction | list[qiskit.circuit.Instruction] | None = None, entanglement: list[int] | list[list[int]] | None = None, reps: int = 1, insert_barriers: bool = False, parameter_prefix: str = "ΞΈ", overwrite_block_parameters: bool | list[list[Parameter]] = True, skip_final_rotation_layer: bool = False, skip_unentangled_qubits: bool = False, initial_state: QuantumCircuit | None = None, name: str | None = "nlocal", flatten: bool | None = None, ) -> None: """ Args: num_qubits: The number of qubits of the circuit. rotation_blocks: The blocks used in the rotation layers. If multiple are passed, these will be applied one after another (like new sub-layers). entanglement_blocks: The blocks used in the entanglement layers. If multiple are passed, these will be applied one after another. To use different entanglements for the sub-layers, see :meth:`get_entangler_map`. entanglement: The indices specifying on which qubits the input blocks act. If ``None``, the entanglement blocks are applied at the top of the circuit. reps: Specifies how often the rotation blocks and entanglement blocks are repeated. insert_barriers: If ``True``, barriers are inserted in between each layer. If ``False``, no barriers are inserted. parameter_prefix: The prefix used if default parameters are generated. overwrite_block_parameters: If the parameters in the added blocks should be overwritten. If ``False``, the parameters in the blocks are not changed. skip_final_rotation_layer: Whether a final rotation layer is added to the circuit. skip_unentangled_qubits: If ``True``, the rotation gates act only on qubits that are entangled. If ``False``, the rotation gates act on all qubits. initial_state: A :class:`.QuantumCircuit` object which can be used to describe an initial state prepended to the NLocal circuit. name: The name of the circuit. flatten: Set this to ``True`` to output a flat circuit instead of nesting it inside multiple layers of gate objects. By default currently the contents of the output circuit will be wrapped in nested objects for cleaner visualization. However, if you're using this circuit for anything besides visualization its **strongly** recommended to set this flag to ``True`` to avoid a large performance overhead for parameter binding. Raises: ValueError: If ``reps`` parameter is less than or equal to 0. TypeError: If ``reps`` parameter is not an int value. """ super().__init__(name=name) self._num_qubits: int | None = None self._insert_barriers = insert_barriers self._reps = reps self._entanglement_blocks: list[QuantumCircuit] = [] self._rotation_blocks: list[QuantumCircuit] = [] self._prepended_blocks: list[QuantumCircuit] = [] self._prepended_entanglement: list[list[list[int]] | str] = [] self._appended_blocks: list[QuantumCircuit] = [] self._appended_entanglement: list[list[list[int]] | str] = [] self._entanglement = None self._entangler_maps = None self._ordered_parameters: ParameterVector | list[Parameter] = ParameterVector( name=parameter_prefix ) self._overwrite_block_parameters = overwrite_block_parameters self._skip_final_rotation_layer = skip_final_rotation_layer self._skip_unentangled_qubits = skip_unentangled_qubits self._initial_state: QuantumCircuit | None = None self._initial_state_circuit: QuantumCircuit | None = None self._bounds: list[tuple[float | None, float | None]] | None = None self._flatten = flatten if int(reps) != reps: raise TypeError("The value of reps should be int") if reps < 0: raise ValueError("The value of reps should be larger than or equal to 0") if num_qubits is not None: self.num_qubits = num_qubits if entanglement_blocks is not None: self.entanglement_blocks = entanglement_blocks if rotation_blocks is not None: self.rotation_blocks = rotation_blocks if entanglement is not None: self.entanglement = entanglement if initial_state is not None: self.initial_state = initial_state @property def num_qubits(self) -> int: """Returns the number of qubits in this circuit. Returns: The number of qubits. """ return self._num_qubits if self._num_qubits is not None else 0 @num_qubits.setter def num_qubits(self, num_qubits: int) -> None: """Set the number of qubits for the n-local circuit. Args: The new number of qubits. """ if self._num_qubits != num_qubits: # invalidate the circuit self._invalidate() self._num_qubits = num_qubits self.qregs = [QuantumRegister(num_qubits, name="q")] @property def flatten(self) -> bool: """Returns whether the circuit is wrapped in nested gates/instructions or flattened.""" return bool(self._flatten) @flatten.setter def flatten(self, flatten: bool) -> None: self._invalidate() self._flatten = flatten def _convert_to_block(self, layer: typing.Any) -> QuantumCircuit: """Try to convert ``layer`` to a QuantumCircuit. Args: layer: The object to be converted to an NLocal block / Instruction. Returns: The layer converted to a circuit. Raises: TypeError: If the input cannot be converted to a circuit. """ if isinstance(layer, QuantumCircuit): return layer if isinstance(layer, Instruction): circuit = QuantumCircuit(layer.num_qubits) circuit.append(layer, list(range(layer.num_qubits))) return circuit try: circuit = QuantumCircuit(layer.num_qubits) circuit.append(layer.to_instruction(), list(range(layer.num_qubits))) return circuit except AttributeError: pass raise TypeError(f"Adding a {type(layer)} to an NLocal is not supported.") @property def rotation_blocks(self) -> list[QuantumCircuit]: """The blocks in the rotation layers. Returns: The blocks in the rotation layers. """ return self._rotation_blocks @rotation_blocks.setter def rotation_blocks( self, blocks: QuantumCircuit | list[QuantumCircuit] | Instruction | list[Instruction] ) -> None: """Set the blocks in the rotation layers. Args: blocks: The new blocks for the rotation layers. """ # cannot check for the attribute ``'__len__'`` because a circuit also has this attribute if not isinstance(blocks, (list, numpy.ndarray)): blocks = [blocks] self._invalidate() self._rotation_blocks = [self._convert_to_block(block) for block in blocks] @property def entanglement_blocks(self) -> list[QuantumCircuit]: """The blocks in the entanglement layers. Returns: The blocks in the entanglement layers. """ return self._entanglement_blocks @entanglement_blocks.setter def entanglement_blocks( self, blocks: QuantumCircuit | list[QuantumCircuit] | Instruction | list[Instruction] ) -> None: """Set the blocks in the entanglement layers. Args: blocks: The new blocks for the entanglement layers. """ # cannot check for the attribute ``'__len__'`` because a circuit also has this attribute if not isinstance(blocks, (list, numpy.ndarray)): blocks = [blocks] self._invalidate() self._entanglement_blocks = [self._convert_to_block(block) for block in blocks] @property def entanglement( self, ) -> str | list[str] | list[list[str]] | list[int] | list[list[int]] | list[ list[list[int]] ] | list[list[list[list[int]]]] | Callable[[int], str] | Callable[[int], list[list[int]]]: """Get the entanglement strategy. Returns: The entanglement strategy, see :meth:`get_entangler_map` for more detail on how the format is interpreted. """ return self._entanglement @entanglement.setter def entanglement( self, entanglement: str | list[str] | list[list[str]] | list[int] | list[list[int]] | list[list[list[int]]] | list[list[list[list[int]]]] | Callable[[int], str] | Callable[[int], list[list[int]]] | None, ) -> None: """Set the entanglement strategy. Args: entanglement: The entanglement strategy. See :meth:`get_entangler_map` for more detail on the supported formats. """ self._invalidate() self._entanglement = entanglement @property def num_layers(self) -> int: """Return the number of layers in the n-local circuit. Returns: The number of layers in the circuit. """ return 2 * self._reps + int(not self._skip_final_rotation_layer) def _check_configuration(self, raise_on_failure: bool = True) -> bool: """Check if the configuration of the NLocal class is valid. Args: raise_on_failure: Whether to raise on failure. Returns: True, if the configuration is valid and the circuit can be constructed. Otherwise an ValueError is raised. Raises: ValueError: If the blocks are not set. ValueError: If the number of repetitions is not set. ValueError: If the qubit indices are not set. ValueError: If the number of qubit indices does not match the number of blocks. ValueError: If an index in the repetitions list exceeds the number of blocks. ValueError: If the number of repetitions does not match the number of block-wise parameters. ValueError: If a specified qubit index is larger than the (manually set) number of qubits. """ valid = True if self.num_qubits is None: valid = False if raise_on_failure: raise ValueError("No number of qubits specified.") # check no needed parameters are None if self.entanglement_blocks is None and self.rotation_blocks is None: valid = False if raise_on_failure: raise ValueError("The blocks are not set.") return valid @property def ordered_parameters(self) -> list[Parameter]: """The parameters used in the underlying circuit. This includes float values and duplicates. Examples: >>> # prepare circuit ... >>> print(nlocal) β”Œβ”€β”€β”€β”€β”€β”€β”€β”β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” q_0: ─ Ry(1) β”œβ”€ Ry(ΞΈ[1]) β”œβ”€ Ry(ΞΈ[1]) β”œβ”€ Ry(ΞΈ[3]) β”œ β””β”€β”€β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ >>> nlocal.parameters {Parameter(ΞΈ[1]), Parameter(ΞΈ[3])} >>> nlocal.ordered_parameters [1, Parameter(ΞΈ[1]), Parameter(ΞΈ[1]), Parameter(ΞΈ[3])] Returns: The parameters objects used in the circuit. """ if isinstance(self._ordered_parameters, ParameterVector): self._ordered_parameters.resize(self.num_parameters_settable) return list(self._ordered_parameters) return self._ordered_parameters @ordered_parameters.setter def ordered_parameters(self, parameters: ParameterVector | list[Parameter]) -> None: """Set the parameters used in the underlying circuit. Args: The parameters to be used in the underlying circuit. Raises: ValueError: If the length of ordered parameters does not match the number of parameters in the circuit and they are not a ``ParameterVector`` (which could be resized to fit the number of parameters). """ if ( not isinstance(parameters, ParameterVector) and len(parameters) != self.num_parameters_settable ): raise ValueError( "The length of ordered parameters must be equal to the number of " "settable parameters in the circuit ({}), but is {}".format( self.num_parameters_settable, len(parameters) ) ) self._ordered_parameters = parameters self._invalidate() @property def insert_barriers(self) -> bool: """If barriers are inserted in between the layers or not. Returns: ``True``, if barriers are inserted in between the layers, ``False`` if not. """ return self._insert_barriers @insert_barriers.setter def insert_barriers(self, insert_barriers: bool) -> None: """Specify whether barriers should be inserted in between the layers or not. Args: insert_barriers: If True, barriers are inserted, if False not. """ # if insert_barriers changes, we have to invalidate the circuit definition, # if it is the same as before we can leave the NLocal instance as it is if insert_barriers is not self._insert_barriers: self._invalidate() self._insert_barriers = insert_barriers def get_unentangled_qubits(self) -> set[int]: """Get the indices of unentangled qubits in a set. Returns: The unentangled qubits. """ entangled_qubits = set() for i in range(self._reps): for j, block in enumerate(self.entanglement_blocks): entangler_map = self.get_entangler_map(i, j, block.num_qubits) entangled_qubits.update([idx for indices in entangler_map for idx in indices]) unentangled_qubits = set(range(self.num_qubits)) - entangled_qubits return unentangled_qubits @property def num_parameters_settable(self) -> int: """The number of total parameters that can be set to distinct values. This does not change when the parameters are bound or exchanged for same parameters, and therefore is different from ``num_parameters`` which counts the number of unique :class:`~qiskit.circuit.Parameter` objects currently in the circuit. Returns: The number of parameters originally available in the circuit. Note: This quantity does not require the circuit to be built yet. """ num = 0 for i in range(self._reps): for j, block in enumerate(self.entanglement_blocks): entangler_map = self.get_entangler_map(i, j, block.num_qubits) num += len(entangler_map) * len(get_parameters(block)) if self._skip_unentangled_qubits: unentangled_qubits = self.get_unentangled_qubits() num_rot = 0 for block in self.rotation_blocks: block_indices = [ list(range(j * block.num_qubits, (j + 1) * block.num_qubits)) for j in range(self.num_qubits // block.num_qubits) ] if self._skip_unentangled_qubits: block_indices = [ indices for indices in block_indices if set(indices).isdisjoint(unentangled_qubits) ] num_rot += len(block_indices) * len(get_parameters(block)) num += num_rot * (self._reps + int(not self._skip_final_rotation_layer)) return num @property def reps(self) -> int: """The number of times rotation and entanglement block are repeated. Returns: The number of repetitions. """ return self._reps @reps.setter def reps(self, repetitions: int) -> None: """Set the repetitions. If the repetitions are `0`, only one rotation layer with no entanglement layers is applied (unless ``self.skip_final_rotation_layer`` is set to ``True``). Args: repetitions: The new repetitions. Raises: ValueError: If reps setter has parameter repetitions < 0. """ if repetitions < 0: raise ValueError("The repetitions should be larger than or equal to 0") if repetitions != self._reps: self._invalidate() self._reps = repetitions def print_settings(self) -> str: """Returns information about the setting. Returns: The class name and the attributes/parameters of the instance as ``str``. """ ret = f"NLocal: {self.__class__.__name__}\n" params = "" for key, value in self.__dict__.items(): if key[0] == "_": params += f"-- {key[1:]}: {value}\n" ret += f"{params}" return ret @property def preferred_init_points(self) -> list[float] | None: """The initial points for the parameters. Can be stored as initial guess in optimization. Returns: The initial values for the parameters, or None, if none have been set. """ return None # pylint: disable=too-many-return-statements def get_entangler_map( self, rep_num: int, block_num: int, num_block_qubits: int ) -> Sequence[Sequence[int]]: """Get the entangler map for in the repetition ``rep_num`` and the block ``block_num``. The entangler map for the current block is derived from the value of ``self.entanglement``. Below the different cases are listed, where ``i`` and ``j`` denote the repetition number and the block number, respectively, and ``n`` the number of qubits in the block. =================================== ======================================================== entanglement type entangler map =================================== ======================================================== ``None`` ``[[0, ..., n - 1]]`` ``str`` (e.g ``'full'``) the specified connectivity on ``n`` qubits ``List[int]`` [``entanglement``] ``List[List[int]]`` ``entanglement`` ``List[List[List[int]]]`` ``entanglement[i]`` ``List[List[List[List[int]]]]`` ``entanglement[i][j]`` ``List[str]`` the connectivity specified in ``entanglement[i]`` ``List[List[str]]`` the connectivity specified in ``entanglement[i][j]`` ``Callable[int, str]`` same as ``List[str]`` ``Callable[int, List[List[int]]]`` same as ``List[List[List[int]]]`` =================================== ======================================================== Note that all indices are to be taken modulo the length of the array they act on, i.e. no out-of-bounds index error will be raised but we re-iterate from the beginning of the list. Args: rep_num: The current repetition we are in. block_num: The block number within the entanglement layers. num_block_qubits: The number of qubits in the block. Returns: The entangler map for the current block in the current repetition. Raises: ValueError: If the value of ``entanglement`` could not be cast to a corresponding entangler map. """ i, j, n = rep_num, block_num, num_block_qubits entanglement = self._entanglement # entanglement is None if entanglement is None: return [list(range(n))] # entanglement is callable if callable(entanglement): entanglement = entanglement(i) # entanglement is str if isinstance(entanglement, str): return get_entangler_map(n, self.num_qubits, entanglement, offset=i) # check if entanglement is list of something if not isinstance(entanglement, (tuple, list)): raise ValueError(f"Invalid value of entanglement: {entanglement}") num_i = len(entanglement) # entanglement is List[str] if all(isinstance(en, str) for en in entanglement): return get_entangler_map(n, self.num_qubits, entanglement[i % num_i], offset=i) # entanglement is List[int] if all(isinstance(en, (int, numpy.integer)) for en in entanglement): return [[int(en) for en in entanglement]] # check if entanglement is List[List] if not all(isinstance(en, (tuple, list)) for en in entanglement): raise ValueError(f"Invalid value of entanglement: {entanglement}") num_j = len(entanglement[i % num_i]) # entanglement is List[List[str]] if all(isinstance(e2, str) for en in entanglement for e2 in en): return get_entangler_map( n, self.num_qubits, entanglement[i % num_i][j % num_j], offset=i ) # entanglement is List[List[int]] if all(isinstance(e2, (int, numpy.int32, numpy.int64)) for en in entanglement for e2 in en): for ind, en in enumerate(entanglement): entanglement[ind] = tuple(map(int, en)) return entanglement # check if entanglement is List[List[List]] if not all(isinstance(e2, (tuple, list)) for en in entanglement for e2 in en): raise ValueError(f"Invalid value of entanglement: {entanglement}") # entanglement is List[List[List[int]]] if all( isinstance(e3, (int, numpy.int32, numpy.int64)) for en in entanglement for e2 in en for e3 in e2 ): for en in entanglement: for ind, e2 in enumerate(en): en[ind] = tuple(map(int, e2)) return entanglement[i % num_i] # check if entanglement is List[List[List[List]]] if not all(isinstance(e3, (tuple, list)) for en in entanglement for e2 in en for e3 in e2): raise ValueError(f"Invalid value of entanglement: {entanglement}") # entanglement is List[List[List[List[int]]]] if all( isinstance(e4, (int, numpy.int32, numpy.int64)) for en in entanglement for e2 in en for e3 in e2 for e4 in e3 ): for en in entanglement: for e2 in en: for ind, e3 in enumerate(e2): e2[ind] = tuple(map(int, e3)) return entanglement[i % num_i][j % num_j] raise ValueError(f"Invalid value of entanglement: {entanglement}") @property def initial_state(self) -> QuantumCircuit: """Return the initial state that is added in front of the n-local circuit. Returns: The initial state. """ return self._initial_state @initial_state.setter def initial_state(self, initial_state: QuantumCircuit) -> None: """Set the initial state. Args: initial_state: The new initial state. Raises: ValueError: If the number of qubits has been set before and the initial state does not match the number of qubits. """ self._initial_state = initial_state self._invalidate() @property def parameter_bounds(self) -> list[tuple[float, float]] | None: """The parameter bounds for the unbound parameters in the circuit. Returns: A list of pairs indicating the bounds, as (lower, upper). None indicates an unbounded parameter in the corresponding direction. If ``None`` is returned, problem is fully unbounded. """ if not self._is_built: self._build() return self._bounds @parameter_bounds.setter def parameter_bounds(self, bounds: list[tuple[float, float]]) -> None: """Set the parameter bounds. Args: bounds: The new parameter bounds. """ self._bounds = bounds def add_layer( self, other: QuantumCircuit | qiskit.circuit.Instruction, entanglement: list[int] | str | list[list[int]] | None = None, front: bool = False, ) -> "NLocal": """Append another layer to the NLocal. Args: other: The layer to compose, can be another NLocal, an Instruction or Gate, or a QuantumCircuit. entanglement: The entanglement or qubit indices. front: If True, ``other`` is appended to the front, else to the back. Returns: self, such that chained composes are possible. Raises: TypeError: If `other` is not compatible, i.e. is no Instruction and does not have a `to_instruction` method. """ block = self._convert_to_block(other) if entanglement is None: entanglement = [list(range(block.num_qubits))] elif isinstance(entanglement, list) and not isinstance(entanglement[0], list): entanglement = [entanglement] if front: self._prepended_blocks += [block] self._prepended_entanglement += [entanglement] else: self._appended_blocks += [block] self._appended_entanglement += [entanglement] if isinstance(entanglement, list): num_qubits = 1 + max(max(indices) for indices in entanglement) if num_qubits > self.num_qubits: self._invalidate() # rebuild circuit self.num_qubits = num_qubits # modify the circuit accordingly if front is False and self._is_built: if self._insert_barriers and len(self.data) > 0: self.barrier() if isinstance(entanglement, str): entangler_map: Sequence[Sequence[int]] = get_entangler_map( block.num_qubits, self.num_qubits, entanglement ) else: entangler_map = entanglement layer = QuantumCircuit(self.num_qubits) for i in entangler_map: params = self.ordered_parameters[-len(get_parameters(block)) :] parameterized_block = self._parameterize_block(block, params=params) layer.compose(parameterized_block, i, inplace=True) self.compose(layer, inplace=True) else: # cannot prepend a block currently, just rebuild self._invalidate() return self def assign_parameters( self, parameters: Mapping[Parameter, ParameterExpression | float] | Sequence[ParameterExpression | float], inplace: bool = False, **kwargs, ) -> QuantumCircuit | None: """Assign parameters to the n-local circuit. This method also supports passing a list instead of a dictionary. If a list is passed, the list must have the same length as the number of unbound parameters in the circuit. The parameters are assigned in the order of the parameters in :meth:`ordered_parameters`. Returns: A copy of the NLocal circuit with the specified parameters. Raises: AttributeError: If the parameters are given as list and do not match the number of parameters. """ if parameters is None or len(parameters) == 0: return self if not self._is_built: self._build() return super().assign_parameters(parameters, inplace=inplace, **kwargs) def _parameterize_block( self, block, param_iter=None, rep_num=None, block_num=None, indices=None, params=None ): """Convert ``block`` to a circuit of correct width and parameterized using the iterator.""" if self._overwrite_block_parameters: # check if special parameters should be used # pylint: disable=assignment-from-none if params is None: params = self._parameter_generator(rep_num, block_num, indices) if params is None: params = [next(param_iter) for _ in range(len(get_parameters(block)))] update = dict(zip(block.parameters, params)) return block.assign_parameters(update) return block.copy() def _build_rotation_layer(self, circuit, param_iter, i): """Build a rotation layer.""" # if the unentangled qubits are skipped, compute the set of qubits that are not entangled if self._skip_unentangled_qubits: unentangled_qubits = self.get_unentangled_qubits() # iterate over all rotation blocks for j, block in enumerate(self.rotation_blocks): # create a new layer layer = QuantumCircuit(*self.qregs) # we apply the rotation gates stacked on top of each other, i.e. # if we have 4 qubits and a rotation block of width 2, we apply two instances block_indices = [ list(range(k * block.num_qubits, (k + 1) * block.num_qubits)) for k in range(self.num_qubits // block.num_qubits) ] # if unentangled qubits should not be acted on, remove all operations that # touch an unentangled qubit if self._skip_unentangled_qubits: block_indices = [ indices for indices in block_indices if set(indices).isdisjoint(unentangled_qubits) ] # apply the operations in the layer for indices in block_indices: parameterized_block = self._parameterize_block(block, param_iter, i, j, indices) layer.compose(parameterized_block, indices, inplace=True) # add the layer to the circuit circuit.compose(layer, inplace=True) def _build_entanglement_layer(self, circuit, param_iter, i): """Build an entanglement layer.""" # iterate over all entanglement blocks for j, block in enumerate(self.entanglement_blocks): # create a new layer and get the entangler map for this block layer = QuantumCircuit(*self.qregs) entangler_map = self.get_entangler_map(i, j, block.num_qubits) # apply the operations in the layer for indices in entangler_map: parameterized_block = self._parameterize_block(block, param_iter, i, j, indices) layer.compose(parameterized_block, indices, inplace=True) # add the layer to the circuit circuit.compose(layer, inplace=True) def _build_additional_layers(self, circuit, which): if which == "appended": blocks = self._appended_blocks entanglements = self._appended_entanglement elif which == "prepended": blocks = reversed(self._prepended_blocks) entanglements = reversed(self._prepended_entanglement) else: raise ValueError("`which` must be either `appended` or `prepended`.") for block, ent in zip(blocks, entanglements): layer = QuantumCircuit(*self.qregs) if isinstance(ent, str): ent = get_entangler_map(block.num_qubits, self.num_qubits, ent) for indices in ent: layer.compose(block, indices, inplace=True) circuit.compose(layer, inplace=True) def _build(self) -> None: """If not already built, build the circuit.""" if self._is_built: return super()._build() if self.num_qubits == 0: return if not self._flatten: circuit = QuantumCircuit(*self.qregs, name=self.name) else: circuit = self # use the initial state as starting circuit, if it is set if self.initial_state: circuit.compose(self.initial_state.copy(), inplace=True) param_iter = iter(self.ordered_parameters) # build the prepended layers self._build_additional_layers(circuit, "prepended") # main loop to build the entanglement and rotation layers for i in range(self.reps): # insert barrier if specified and there is a preceding layer if self._insert_barriers and (i > 0 or len(self._prepended_blocks) > 0): circuit.barrier() # build the rotation layer self._build_rotation_layer(circuit, param_iter, i) # barrier in between rotation and entanglement layer if self._insert_barriers and len(self._rotation_blocks) > 0: circuit.barrier() # build the entanglement layer self._build_entanglement_layer(circuit, param_iter, i) # add the final rotation layer if not self._skip_final_rotation_layer: if self.insert_barriers and self.reps > 0: circuit.barrier() self._build_rotation_layer(circuit, param_iter, self.reps) # add the appended layers self._build_additional_layers(circuit, "appended") # cast global phase to float if it has no free parameters if isinstance(circuit.global_phase, ParameterExpression): try: circuit.global_phase = float(circuit.global_phase) except TypeError: # expression contains free parameters pass if not self._flatten: try: block = circuit.to_gate() except QiskitError: block = circuit.to_instruction() self.append(block, self.qubits) # pylint: disable=unused-argument def _parameter_generator(self, rep: int, block: int, indices: list[int]) -> Parameter | None: """If certain blocks should use certain parameters this method can be overridden.""" return None def get_parameters(block: QuantumCircuit | Instruction) -> list[Parameter]: """Return the list of Parameters objects inside a circuit or instruction. This is required since, in a standard gate the parameters are not necessarily Parameter objects (e.g. U3Gate(0.1, 0.2, 0.3).params == [0.1, 0.2, 0.3]) and instructions and circuits do not have the same interface for parameters. """ if isinstance(block, QuantumCircuit): return list(block.parameters) else: return [p for p in block.params if isinstance(p, ParameterExpression)] def get_entangler_map( num_block_qubits: int, num_circuit_qubits: int, entanglement: str, offset: int = 0 ) -> Sequence[tuple[int, ...]]: """Get an entangler map for an arbitrary number of qubits. Args: num_block_qubits: The number of qubits of the entangling block. num_circuit_qubits: The number of qubits of the circuit. entanglement: The entanglement strategy. offset: The block offset, can be used if the entanglements differ per block. See mode ``sca`` for instance. Returns: The entangler map using mode ``entanglement`` to scatter a block of ``num_block_qubits`` qubits on ``num_circuit_qubits`` qubits. Raises: ValueError: If the entanglement mode ist not supported. """ n, m = num_circuit_qubits, num_block_qubits if m > n: raise ValueError( "The number of block qubits must be smaller or equal to the number of " "qubits in the circuit." ) if entanglement == "pairwise" and num_block_qubits > 2: raise ValueError("Pairwise entanglement is not defined for blocks with more than 2 qubits.") if entanglement == "full": return list(combinations(list(range(n)), m)) elif entanglement == "reverse_linear": # reverse linear connectivity. In the case of m=2 and the entanglement_block='cx' # then it's equivalent to 'full' entanglement reverse = [tuple(range(n - i - m, n - i)) for i in range(n - m + 1)] return reverse elif entanglement in ["linear", "circular", "sca", "pairwise"]: linear = [tuple(range(i, i + m)) for i in range(n - m + 1)] # if the number of block qubits is 1, we don't have to add the 'circular' part if entanglement == "linear" or m == 1: return linear if entanglement == "pairwise": return linear[::2] + linear[1::2] # circular equals linear plus top-bottom entanglement (if there's space for it) if n > m: circular = [tuple(range(n - m + 1, n)) + (0,)] + linear else: circular = linear if entanglement == "circular": return circular # sca is circular plus shift and reverse shifted = circular[-offset:] + circular[:-offset] if offset % 2 == 1: # if odd, reverse the qubit indices sca = [ind[::-1] for ind in shifted] else: sca = shifted return sca else: raise ValueError(f"Unsupported entanglement type: {entanglement}")
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """The two-local gate circuit.""" from __future__ import annotations import typing from collections.abc import Callable, Sequence from qiskit.circuit.quantumcircuit import QuantumCircuit from qiskit.circuit import Gate, Instruction, Parameter from .n_local import NLocal from ..standard_gates import ( IGate, XGate, YGate, ZGate, RXGate, RYGate, RZGate, HGate, SGate, SdgGate, TGate, TdgGate, RXXGate, RYYGate, RZXGate, RZZGate, SwapGate, CXGate, CYGate, CZGate, CRXGate, CRYGate, CRZGate, CHGate, ) if typing.TYPE_CHECKING: import qiskit # pylint: disable=cyclic-import class TwoLocal(NLocal): r"""The two-local circuit. The two-local circuit is a parameterized circuit consisting of alternating rotation layers and entanglement layers. The rotation layers are single qubit gates applied on all qubits. The entanglement layer uses two-qubit gates to entangle the qubits according to a strategy set using ``entanglement``. Both the rotation and entanglement gates can be specified as string (e.g. ``'ry'`` or ``'cx'``), as gate-type (e.g. ``RYGate`` or ``CXGate``) or as QuantumCircuit (e.g. a 1-qubit circuit or 2-qubit circuit). A set of default entanglement strategies is provided: * ``'full'`` entanglement is each qubit is entangled with all the others. * ``'linear'`` entanglement is qubit :math:`i` entangled with qubit :math:`i + 1`, for all :math:`i \in \{0, 1, ... , n - 2\}`, where :math:`n` is the total number of qubits. * ``'reverse_linear'`` entanglement is qubit :math:`i` entangled with qubit :math:`i + 1`, for all :math:`i \in \{n-2, n-3, ... , 1, 0\}`, where :math:`n` is the total number of qubits. Note that if ``entanglement_blocks = 'cx'`` then this option provides the same unitary as ``'full'`` with fewer entangling gates. * ``'pairwise'`` entanglement is one layer where qubit :math:`i` is entangled with qubit :math:`i + 1`, for all even values of :math:`i`, and then a second layer where qubit :math:`i` is entangled with qubit :math:`i + 1`, for all odd values of :math:`i`. * ``'circular'`` entanglement is linear entanglement but with an additional entanglement of the first and last qubit before the linear part. * ``'sca'`` (shifted-circular-alternating) entanglement is a generalized and modified version of the proposed circuit 14 in `Sim et al. <https://arxiv.org/abs/1905.10876>`__. It consists of circular entanglement where the 'long' entanglement connecting the first with the last qubit is shifted by one each block. Furthermore the role of control and target qubits are swapped every block (therefore alternating). The entanglement can further be specified using an entangler map, which is a list of index pairs, such as >>> entangler_map = [(0, 1), (1, 2), (2, 0)] If different entanglements per block should be used, provide a list of entangler maps. See the examples below on how this can be used. >>> entanglement = [entangler_map_layer_1, entangler_map_layer_2, ... ] Barriers can be inserted in between the different layers for better visualization using the ``insert_barriers`` attribute. For each parameterized gate a new parameter is generated using a :class:`~qiskit.circuit.library.ParameterVector`. The name of these parameters can be chosen using the ``parameter_prefix``. Examples: >>> two = TwoLocal(3, 'ry', 'cx', 'linear', reps=2, insert_barriers=True) >>> print(two) # decompose the layers into standard gates β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β–‘ β–‘ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β–‘ β–‘ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” q_0: ─ Ry(ΞΈ[0]) β”œβ”€β–‘β”€β”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β–‘β”€β”€ Ry(ΞΈ[3]) β”œβ”€β–‘β”€β”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β–‘β”€β”€ Ry(ΞΈ[6]) β”œ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β–‘ β”Œβ”€β”΄β”€β” β–‘ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β–‘ β”Œβ”€β”΄β”€β” β–‘ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ q_1: ─ Ry(ΞΈ[1]) β”œβ”€β–‘β”€β”€ X β”œβ”€β”€β– β”€β”€β”€β–‘β”€β”€ Ry(ΞΈ[4]) β”œβ”€β–‘β”€β”€ X β”œβ”€β”€β– β”€β”€β”€β–‘β”€β”€ Ry(ΞΈ[7]) β”œ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β–‘ β””β”€β”€β”€β”˜β”Œβ”€β”΄β”€β” β–‘ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β–‘ β””β”€β”€β”€β”˜β”Œβ”€β”΄β”€β” β–‘ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ q_2: ─ Ry(ΞΈ[2]) β”œβ”€β–‘β”€β”€β”€β”€β”€β”€β”€ X β”œβ”€β–‘β”€β”€ Ry(ΞΈ[5]) β”œβ”€β–‘β”€β”€β”€β”€β”€β”€β”€ X β”œβ”€β–‘β”€β”€ Ry(ΞΈ[8]) β”œ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β–‘ β””β”€β”€β”€β”˜ β–‘ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β–‘ β””β”€β”€β”€β”˜ β–‘ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ >>> two = TwoLocal(3, ['ry','rz'], 'cz', 'full', reps=1, insert_barriers=True) >>> qc = QuantumCircuit(3) >>> qc += two >>> print(qc.decompose().draw()) β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β–‘ β–‘ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” q_0: ─ Ry(ΞΈ[0]) β”œβ”€ Rz(ΞΈ[3]) β”œβ”€β–‘β”€β”€β– β”€β”€β– β”€β”€β”€β”€β”€β–‘β”€β”€ Ry(ΞΈ[6]) β”œβ”€β”€ Rz(ΞΈ[9]) β”œ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β–‘ β”‚ β”‚ β–‘ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Œβ”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ q_1: ─ Ry(ΞΈ[1]) β”œβ”€ Rz(ΞΈ[4]) β”œβ”€β–‘β”€β”€β– β”€β”€β”Όβ”€β”€β– β”€β”€β–‘β”€β”€ Ry(ΞΈ[7]) β”œβ”€ Rz(ΞΈ[10]) β”œ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β–‘ β”‚ β”‚ β–‘ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ q_2: ─ Ry(ΞΈ[2]) β”œβ”€ Rz(ΞΈ[5]) β”œβ”€β–‘β”€β”€β”€β”€β”€β– β”€β”€β– β”€β”€β–‘β”€β”€ Ry(ΞΈ[8]) β”œβ”€ Rz(ΞΈ[11]) β”œ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β–‘ β–‘ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ >>> entangler_map = [[0, 1], [1, 2], [2, 0]] # circular entanglement for 3 qubits >>> two = TwoLocal(3, 'x', 'crx', entangler_map, reps=1) >>> print(two) # note: no barriers inserted this time! β”Œβ”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β”Œβ”€β”€β”€β” q_0: |0>─ X β”œβ”€β”€β”€β”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ Rx(ΞΈ[2]) β”œβ”€ X β”œ β”œβ”€β”€β”€β”€β”Œβ”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”β””β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”˜β””β”€β”€β”€β”˜ q_1: |0>─ X β”œβ”€ Rx(ΞΈ[0]) β”œβ”€β”€β”€β”€β”€β– β”€β”€β”€β”€β”€β”€β”€ X β”œβ”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”œβ”€β”€β”€β”€β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β”Œβ”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”β””β”€β”€β”€β”˜ β”‚ β”Œβ”€β”€β”€β” q_2: |0>─ X β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ Rx(ΞΈ[1]) β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β– β”€β”€β”€β”€β”€β”€ X β”œ β””β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”˜ >>> entangler_map = [[0, 3], [0, 2]] # entangle the first and last two-way >>> two = TwoLocal(4, [], 'cry', entangler_map, reps=1) >>> circuit = two + two >>> print(circuit.decompose().draw()) # note, that the parameters are the same! q_0: ─────■───────────■───────────■───────────■────── β”‚ β”‚ β”‚ β”‚ q_1: ─────┼───────────┼───────────┼───────────┼────── β”‚ β”Œβ”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β” β”‚ β”Œβ”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β” q_2: ─────┼─────── Ry(ΞΈ[1]) β”œβ”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€ Ry(ΞΈ[1]) β”œ β”Œβ”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β”Œβ”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ q_3: ─ Ry(ΞΈ[0]) β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ Ry(ΞΈ[0]) β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ >>> layer_1 = [(0, 1), (0, 2)] >>> layer_2 = [(1, 2)] >>> two = TwoLocal(3, 'x', 'cx', [layer_1, layer_2], reps=2, insert_barriers=True) >>> print(two) β”Œβ”€β”€β”€β” β–‘ β–‘ β”Œβ”€β”€β”€β” β–‘ β–‘ β”Œβ”€β”€β”€β” q_0: ─ X β”œβ”€β–‘β”€β”€β”€β– β”€β”€β”€β”€β– β”€β”€β”€β–‘β”€β”€ X β”œβ”€β–‘β”€β”€β”€β”€β”€β”€β”€β–‘β”€β”€ X β”œ β”œβ”€β”€β”€β”€ β–‘ β”Œβ”€β”΄β”€β” β”‚ β–‘ β”œβ”€β”€β”€β”€ β–‘ β–‘ β”œβ”€β”€β”€β”€ q_1: ─ X β”œβ”€β–‘β”€β”€ X β”œβ”€β”€β”Όβ”€β”€β”€β–‘β”€β”€ X β”œβ”€β–‘β”€β”€β”€β– β”€β”€β”€β–‘β”€β”€ X β”œ β”œβ”€β”€β”€β”€ β–‘ β””β”€β”€β”€β”˜β”Œβ”€β”΄β”€β” β–‘ β”œβ”€β”€β”€β”€ β–‘ β”Œβ”€β”΄β”€β” β–‘ β”œβ”€β”€β”€β”€ q_2: ─ X β”œβ”€β–‘β”€β”€β”€β”€β”€β”€β”€ X β”œβ”€β–‘β”€β”€ X β”œβ”€β–‘β”€β”€ X β”œβ”€β–‘β”€β”€ X β”œ β””β”€β”€β”€β”˜ β–‘ β””β”€β”€β”€β”˜ β–‘ β””β”€β”€β”€β”˜ β–‘ β””β”€β”€β”€β”˜ β–‘ β””β”€β”€β”€β”˜ """ def __init__( self, num_qubits: int | None = None, rotation_blocks: str | type | qiskit.circuit.Instruction | QuantumCircuit | list[str | type | qiskit.circuit.Instruction | QuantumCircuit] | None = None, entanglement_blocks: str | type | qiskit.circuit.Instruction | QuantumCircuit | list[str | type | qiskit.circuit.Instruction | QuantumCircuit] | None = None, entanglement: str | list[list[int]] | Callable[[int], list[int]] = "full", reps: int = 3, skip_unentangled_qubits: bool = False, skip_final_rotation_layer: bool = False, parameter_prefix: str = "ΞΈ", insert_barriers: bool = False, initial_state: QuantumCircuit | None = None, name: str = "TwoLocal", flatten: bool | None = None, ) -> None: """ Args: num_qubits: The number of qubits of the two-local circuit. rotation_blocks: The gates used in the rotation layer. Can be specified via the name of a gate (e.g. ``'ry'``) or the gate type itself (e.g. :class:`.RYGate`). If only one gate is provided, the gate same gate is applied to each qubit. If a list of gates is provided, all gates are applied to each qubit in the provided order. See the Examples section for more detail. entanglement_blocks: The gates used in the entanglement layer. Can be specified in the same format as ``rotation_blocks``. entanglement: Specifies the entanglement structure. Can be a string (``'full'``, ``'linear'``, ``'reverse_linear'``, ``'circular'`` or ``'sca'``), a list of integer-pairs specifying the indices of qubits entangled with one another, or a callable returning such a list provided with the index of the entanglement layer. Default to ``'full'`` entanglement. Note that if ``entanglement_blocks = 'cx'``, then ``'full'`` entanglement provides the same unitary as ``'reverse_linear'`` but the latter option has fewer entangling gates. See the Examples section for more detail. reps: Specifies how often a block consisting of a rotation layer and entanglement layer is repeated. skip_unentangled_qubits: If ``True``, the single qubit gates are only applied to qubits that are entangled with another qubit. If ``False``, the single qubit gates are applied to each qubit in the ansatz. Defaults to ``False``. skip_final_rotation_layer: If ``False``, a rotation layer is added at the end of the ansatz. If ``True``, no rotation layer is added. parameter_prefix: The parameterized gates require a parameter to be defined, for which we use instances of :class:`~qiskit.circuit.Parameter`. The name of each parameter will be this specified prefix plus its index. insert_barriers: If ``True``, barriers are inserted in between each layer. If ``False``, no barriers are inserted. Defaults to ``False``. initial_state: A :class:`.QuantumCircuit` object to prepend to the circuit. flatten: Set this to ``True`` to output a flat circuit instead of nesting it inside multiple layers of gate objects. By default currently the contents of the output circuit will be wrapped in nested objects for cleaner visualization. However, if you're using this circuit for anything besides visualization its **strongly** recommended to set this flag to ``True`` to avoid a large performance overhead for parameter binding. """ super().__init__( num_qubits=num_qubits, rotation_blocks=rotation_blocks, entanglement_blocks=entanglement_blocks, entanglement=entanglement, reps=reps, skip_final_rotation_layer=skip_final_rotation_layer, skip_unentangled_qubits=skip_unentangled_qubits, insert_barriers=insert_barriers, initial_state=initial_state, parameter_prefix=parameter_prefix, name=name, flatten=flatten, ) def _convert_to_block(self, layer: str | type | Gate | QuantumCircuit) -> QuantumCircuit: """For a layer provided as str (e.g. ``'ry'``) or type (e.g. :class:`.RYGate`) this function returns the according layer type along with the number of parameters (e.g. ``(RYGate, 1)``). Args: layer: The qubit layer. Returns: The specified layer with the required number of parameters. Raises: TypeError: The type of ``layer`` is invalid. ValueError: The type of ``layer`` is str but the name is unknown. ValueError: The type of ``layer`` is type but the layer type is unknown. Note: Outlook: If layers knew their number of parameters as static property, we could also allow custom layer types. """ if isinstance(layer, QuantumCircuit): return layer # check the list of valid layers # this could be a lot easier if the standard layers would have ``name`` and ``num_params`` # as static types, which might be something they should have anyway theta = Parameter("ΞΈ") valid_layers = { "ch": CHGate(), "cx": CXGate(), "cy": CYGate(), "cz": CZGate(), "crx": CRXGate(theta), "cry": CRYGate(theta), "crz": CRZGate(theta), "h": HGate(), "i": IGate(), "id": IGate(), "iden": IGate(), "rx": RXGate(theta), "rxx": RXXGate(theta), "ry": RYGate(theta), "ryy": RYYGate(theta), "rz": RZGate(theta), "rzx": RZXGate(theta), "rzz": RZZGate(theta), "s": SGate(), "sdg": SdgGate(), "swap": SwapGate(), "x": XGate(), "y": YGate(), "z": ZGate(), "t": TGate(), "tdg": TdgGate(), } # try to exchange `layer` from a string to a gate instance if isinstance(layer, str): try: layer = valid_layers[layer] except KeyError as ex: raise ValueError(f"Unknown layer name `{layer}`.") from ex # try to exchange `layer` from a type to a gate instance if isinstance(layer, type): # iterate over the layer types and look for the specified layer instance = None for gate in valid_layers.values(): if isinstance(gate, layer): instance = gate if instance is None: raise ValueError(f"Unknown layer type`{layer}`.") layer = instance if isinstance(layer, Instruction): circuit = QuantumCircuit(layer.num_qubits) circuit.append(layer, list(range(layer.num_qubits))) return circuit raise TypeError( f"Invalid input type {type(layer)}. " + "`layer` must be a type, str or QuantumCircuit." ) def get_entangler_map( self, rep_num: int, block_num: int, num_block_qubits: int ) -> Sequence[Sequence[int]]: """Overloading to handle the special case of 1 qubit where the entanglement are ignored.""" if self.num_qubits <= 1: return [] return super().get_entangler_map(rep_num, block_num, num_block_qubits)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=too-many-function-args, unexpected-keyword-arg """THIS FILE IS DEPRECATED AND WILL BE REMOVED IN RELEASE 0.9. """ import warnings from qiskit.converters import dag_to_circuit, circuit_to_dag from qiskit.transpiler import CouplingMap from qiskit import compiler from qiskit.transpiler.preset_passmanagers import (default_pass_manager_simulator, default_pass_manager) def transpile(circuits, backend=None, basis_gates=None, coupling_map=None, initial_layout=None, seed_mapper=None, pass_manager=None): """transpile one or more circuits. Args: circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile backend (BaseBackend): a backend to compile for basis_gates (list[str]): list of basis gate names supported by the target. Default: ['u1','u2','u3','cx','id'] coupling_map (list): coupling map (perhaps custom) to target in mapping initial_layout (Layout or dict or list): Initial position of virtual qubits on physical qubits. The final layout is not guaranteed to be the same, as the transpiler may permute qubits through swaps or other means. seed_mapper (int): random seed for the swap_mapper pass_manager (PassManager): a pass_manager for the transpiler stages Returns: QuantumCircuit or list[QuantumCircuit]: transpiled circuit(s). Raises: TranspilerError: in case of bad inputs to transpiler or errors in passes """ warnings.warn("qiskit.transpiler.transpile() has been deprecated and will be " "removed in the 0.9 release. Use qiskit.compiler.transpile() instead.", DeprecationWarning) return compiler.transpile(circuits=circuits, backend=backend, basis_gates=basis_gates, coupling_map=coupling_map, initial_layout=initial_layout, seed_transpiler=seed_mapper, pass_manager=pass_manager) def transpile_dag(dag, basis_gates=None, coupling_map=None, initial_layout=None, seed_mapper=None, pass_manager=None): """Deprecated - Use qiskit.compiler.transpile for transpiling from circuits to circuits. Transform a dag circuit into another dag circuit (transpile), through consecutive passes on the dag. Args: dag (DAGCircuit): dag circuit to transform via transpilation basis_gates (list[str]): list of basis gate names supported by the target. Default: ['u1','u2','u3','cx','id'] coupling_map (list): A graph of coupling:: [ [control0(int), target0(int)], [control1(int), target1(int)], ] eg. [[0, 2], [1, 2], [1, 3], [3, 4]} initial_layout (Layout or None): A layout object seed_mapper (int): random seed_mapper for the swap mapper pass_manager (PassManager): pass manager instance for the transpilation process If None, a default set of passes are run. Otherwise, the passes defined in it will run. If contains no passes in it, no dag transformations occur. Returns: DAGCircuit: transformed dag """ warnings.warn("transpile_dag has been deprecated and will be removed in the " "0.9 release. Circuits can be transpiled directly to other " "circuits with the transpile function.", DeprecationWarning) if basis_gates is None: basis_gates = ['u1', 'u2', 'u3', 'cx', 'id'] if pass_manager is None: # default set of passes # if a coupling map is given compile to the map if coupling_map: pass_manager = default_pass_manager(basis_gates, CouplingMap(coupling_map), initial_layout, seed_transpiler=seed_mapper) else: pass_manager = default_pass_manager_simulator(basis_gates) # run the passes specified by the pass manager # TODO return the property set too. See #1086 name = dag.name circuit = dag_to_circuit(dag) circuit = pass_manager.run(circuit) dag = circuit_to_dag(circuit) dag.name = name return dag
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ AST (abstract syntax tree) to DAG (directed acyclic graph) converter. Acts as an OpenQASM interpreter. """ from collections import OrderedDict from qiskit.dagcircuit import DAGCircuit from qiskit.exceptions import QiskitError from qiskit.circuit import QuantumRegister, ClassicalRegister, Gate, QuantumCircuit from qiskit.qasm.node.real import Real from qiskit.circuit.measure import Measure from qiskit.circuit.reset import Reset from qiskit.circuit.barrier import Barrier from qiskit.circuit.delay import Delay from qiskit.circuit.library import standard_gates as std def ast_to_dag(ast): """Build a ``DAGCircuit`` object from an AST ``Node`` object. Args: ast (Program): a Program Node of an AST (parser's output) Return: DAGCircuit: the DAG representing an OpenQASM's AST Raises: QiskitError: if the AST is malformed. Example: .. code-block:: from qiskit.converters import ast_to_dag from qiskit import qasm, QuantumCircuit, ClassicalRegister, QuantumRegister q = QuantumRegister(3, 'q') c = ClassicalRegister(3, 'c') circ = QuantumCircuit(q, c) circ.h(q[0]) circ.cx(q[0], q[1]) circ.measure(q[0], c[0]) circ.rz(0.5, q[1]).c_if(c, 2) qasm_str = circ.qasm() ast = qasm.Qasm(data=qasm_str).parse() dag = ast_to_dag(ast) """ dag = DAGCircuit() AstInterpreter(dag)._process_node(ast) return dag class AstInterpreter: """Interprets an OpenQASM by expanding subroutines and unrolling loops.""" standard_extension = { "u1": std.U1Gate, "u2": std.U2Gate, "u3": std.U3Gate, "u": std.UGate, "p": std.PhaseGate, "x": std.XGate, "y": std.YGate, "z": std.ZGate, "t": std.TGate, "tdg": std.TdgGate, "s": std.SGate, "sdg": std.SdgGate, "sx": std.SXGate, "sxdg": std.SXdgGate, "swap": std.SwapGate, "rx": std.RXGate, "rxx": std.RXXGate, "ry": std.RYGate, "rz": std.RZGate, "rzz": std.RZZGate, "id": std.IGate, "h": std.HGate, "cx": std.CXGate, "cy": std.CYGate, "cz": std.CZGate, "ch": std.CHGate, "crx": std.CRXGate, "cry": std.CRYGate, "crz": std.CRZGate, "csx": std.CSXGate, "cu1": std.CU1Gate, "cp": std.CPhaseGate, "cu": std.CUGate, "cu3": std.CU3Gate, "ccx": std.CCXGate, "cswap": std.CSwapGate, "delay": Delay, "rccx": std.RCCXGate, "rc3x": std.RC3XGate, "c3x": std.C3XGate, "c3sqrtx": std.C3SXGate, "c4x": std.C4XGate, } def __init__(self, dag): """Initialize interpreter's data.""" # DAG object to populate self.dag = dag # OPENQASM version number (ignored for now) self.version = 0.0 # Dict of gates names and properties self.gates = OrderedDict() # Keeping track of conditional gates self.condition = None # List of dictionaries mapping local parameter ids to expression Nodes self.arg_stack = [{}] # List of dictionaries mapping local bit ids to global ids (name, idx) self.bit_stack = [{}] def _process_bit_id(self, node): """Process an Id or IndexedId node as a bit or register type. Return a list of tuples (Register,index). """ reg = None if node.name in self.dag.qregs: reg = self.dag.qregs[node.name] elif node.name in self.dag.cregs: reg = self.dag.cregs[node.name] else: raise QiskitError( "expected qreg or creg name:", "line=%s" % node.line, "file=%s" % node.file ) if node.type == "indexed_id": # An indexed bit or qubit return [reg[node.index]] elif node.type == "id": # A qubit or qreg or creg if not self.bit_stack[-1]: # Global scope return list(reg) else: # local scope if node.name in self.bit_stack[-1]: return [self.bit_stack[-1][node.name]] raise QiskitError( "expected local bit name:", "line=%s" % node.line, "file=%s" % node.file ) return None def _process_custom_unitary(self, node): """Process a custom unitary node.""" name = node.name if node.arguments is not None: args = self._process_node(node.arguments) else: args = [] bits = [self._process_bit_id(node_element) for node_element in node.bitlist.children] if name in self.gates: self._arguments(name, bits, args) else: raise QiskitError( "internal error undefined gate:", "line=%s" % node.line, "file=%s" % node.file ) def _process_u(self, node): """Process a U gate node.""" args = self._process_node(node.arguments) bits = [self._process_bit_id(node.bitlist)] self._arguments("u", bits, args) def _arguments(self, name, bits, args): gargs = self.gates[name]["args"] gbits = self.gates[name]["bits"] maxidx = max(map(len, bits)) for idx in range(maxidx): self.arg_stack.append({gargs[j]: args[j] for j in range(len(gargs))}) # Only index into register arguments. element = [idx * x for x in [len(bits[j]) > 1 for j in range(len(bits))]] self.bit_stack.append({gbits[j]: bits[j][element[j]] for j in range(len(gbits))}) self._create_dag_op( name, [self.arg_stack[-1][s].sym() for s in gargs], [self.bit_stack[-1][s] for s in gbits], ) self.arg_stack.pop() self.bit_stack.pop() def _process_gate(self, node, opaque=False): """Process a gate node. If opaque is True, process the node as an opaque gate node. """ self.gates[node.name] = {} de_gate = self.gates[node.name] de_gate["print"] = True # default de_gate["opaque"] = opaque de_gate["n_args"] = node.n_args() de_gate["n_bits"] = node.n_bits() if node.n_args() > 0: de_gate["args"] = [element.name for element in node.arguments.children] else: de_gate["args"] = [] de_gate["bits"] = [c.name for c in node.bitlist.children] if node.name in self.standard_extension: return if opaque: de_gate["body"] = None else: de_gate["body"] = node.body def _process_cnot(self, node): """Process a CNOT gate node.""" id0 = self._process_bit_id(node.children[0]) id1 = self._process_bit_id(node.children[1]) if not (len(id0) == len(id1) or len(id0) == 1 or len(id1) == 1): raise QiskitError( "internal error: qreg size mismatch", "line=%s" % node.line, "file=%s" % node.file ) maxidx = max([len(id0), len(id1)]) for idx in range(maxidx): cx_gate = std.CXGate() cx_gate.condition = self.condition if len(id0) > 1 and len(id1) > 1: self.dag.apply_operation_back(cx_gate, [id0[idx], id1[idx]], []) elif len(id0) > 1: self.dag.apply_operation_back(cx_gate, [id0[idx], id1[0]], []) else: self.dag.apply_operation_back(cx_gate, [id0[0], id1[idx]], []) def _process_measure(self, node): """Process a measurement node.""" id0 = self._process_bit_id(node.children[0]) id1 = self._process_bit_id(node.children[1]) if len(id0) != len(id1): raise QiskitError( "internal error: reg size mismatch", "line=%s" % node.line, "file=%s" % node.file ) for idx, idy in zip(id0, id1): meas_gate = Measure() meas_gate.condition = self.condition self.dag.apply_operation_back(meas_gate, [idx], [idy]) def _process_if(self, node): """Process an if node.""" creg_name = node.children[0].name creg = self.dag.cregs[creg_name] cval = node.children[1].value self.condition = (creg, cval) self._process_node(node.children[2]) self.condition = None def _process_children(self, node): """Call process_node for all children of node.""" for kid in node.children: self._process_node(kid) def _process_node(self, node): """Carry out the action associated with a node.""" if node.type == "program": self._process_children(node) elif node.type == "qreg": qreg = QuantumRegister(node.index, node.name) self.dag.add_qreg(qreg) elif node.type == "creg": creg = ClassicalRegister(node.index, node.name) self.dag.add_creg(creg) elif node.type == "id": raise QiskitError("internal error: _process_node on id") elif node.type == "int": raise QiskitError("internal error: _process_node on int") elif node.type == "real": raise QiskitError("internal error: _process_node on real") elif node.type == "indexed_id": raise QiskitError("internal error: _process_node on indexed_id") elif node.type == "id_list": # We process id_list nodes when they are leaves of barriers. return [self._process_bit_id(node_children) for node_children in node.children] elif node.type == "primary_list": # We should only be called for a barrier. return [self._process_bit_id(m) for m in node.children] elif node.type == "gate": self._process_gate(node) elif node.type == "custom_unitary": self._process_custom_unitary(node) elif node.type == "universal_unitary": self._process_u(node) elif node.type == "cnot": self._process_cnot(node) elif node.type == "expression_list": return node.children elif node.type == "binop": raise QiskitError("internal error: _process_node on binop") elif node.type == "prefix": raise QiskitError("internal error: _process_node on prefix") elif node.type == "measure": self._process_measure(node) elif node.type == "format": self.version = node.version() elif node.type == "barrier": ids = self._process_node(node.children[0]) qubits = [] for qubit in ids: for j, _ in enumerate(qubit): qubits.append(qubit[j]) self.dag.apply_operation_back(Barrier(len(qubits)), qubits, []) elif node.type == "reset": id0 = self._process_bit_id(node.children[0]) for i, _ in enumerate(id0): reset = Reset() reset.condition = self.condition self.dag.apply_operation_back(reset, [id0[i]], []) elif node.type == "if": self._process_if(node) elif node.type == "opaque": self._process_gate(node, opaque=True) elif node.type == "external": raise QiskitError("internal error: _process_node on external") else: raise QiskitError( "internal error: undefined node type", node.type, "line=%s" % node.line, "file=%s" % node.file, ) return None def _gate_rules_to_qiskit_circuit(self, node, params): """From a gate definition in qasm, to a QuantumCircuit format.""" rules = [] qreg = QuantumRegister(node["n_bits"]) bit_args = {node["bits"][i]: q for i, q in enumerate(qreg)} exp_args = {node["args"][i]: Real(q) for i, q in enumerate(params)} for child_op in node["body"].children: qparams = [] eparams = [] for param_list in child_op.children[1:]: if param_list.type == "id_list": qparams = [bit_args[param.name] for param in param_list.children] elif param_list.type == "expression_list": for param in param_list.children: eparams.append(param.sym(nested_scope=[exp_args])) op = self._create_op(child_op.name, params=eparams) rules.append((op, qparams, [])) circ = QuantumCircuit(qreg) for instr, qargs, cargs in rules: circ._append(instr, qargs, cargs) return circ def _create_dag_op(self, name, params, qargs): """ Create a DAG node out of a parsed AST op node. Args: name (str): operation name to apply to the DAG params (list): op parameters qargs (list(Qubit)): qubits to attach to Raises: QiskitError: if encountering a non-basis opaque gate """ op = self._create_op(name, params) op.condition = self.condition self.dag.apply_operation_back(op, qargs, []) def _create_op(self, name, params): if name in self.standard_extension: op = self.standard_extension[name](*params) elif name in self.gates: op = Gate(name=name, num_qubits=self.gates[name]["n_bits"], params=params) if not self.gates[name]["opaque"]: # call a custom gate (otherwise, opaque) op.definition = self._gate_rules_to_qiskit_circuit(self.gates[name], params=params) else: raise QiskitError("unknown operation for ast node name %s" % name) return op
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Helper function for converting a circuit to a dag""" import copy from qiskit.dagcircuit.dagcircuit import DAGCircuit def circuit_to_dag(circuit, copy_operations=True, *, qubit_order=None, clbit_order=None): """Build a ``DAGCircuit`` object from a ``QuantumCircuit``. Args: circuit (QuantumCircuit): the input circuit. copy_operations (bool): Deep copy the operation objects in the :class:`~.QuantumCircuit` for the output :class:`~.DAGCircuit`. This should only be set to ``False`` if the input :class:`~.QuantumCircuit` will not be used anymore as the operations in the output :class:`~.DAGCircuit` will be shared instances and modifications to operations in the :class:`~.DAGCircuit` will be reflected in the :class:`~.QuantumCircuit` (and vice versa). qubit_order (Iterable[Qubit] or None): the order that the qubits should be indexed in the output DAG. Defaults to the same order as in the circuit. clbit_order (Iterable[Clbit] or None): the order that the clbits should be indexed in the output DAG. Defaults to the same order as in the circuit. Return: DAGCircuit: the DAG representing the input circuit. Raises: ValueError: if the ``qubit_order`` or ``clbit_order`` parameters do not match the bits in the circuit. Example: .. code-block:: from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.dagcircuit import DAGCircuit from qiskit.converters import circuit_to_dag q = QuantumRegister(3, 'q') c = ClassicalRegister(3, 'c') circ = QuantumCircuit(q, c) circ.h(q[0]) circ.cx(q[0], q[1]) circ.measure(q[0], c[0]) circ.rz(0.5, q[1]).c_if(c, 2) dag = circuit_to_dag(circ) """ dagcircuit = DAGCircuit() dagcircuit.name = circuit.name dagcircuit.global_phase = circuit.global_phase dagcircuit.calibrations = circuit.calibrations dagcircuit.metadata = circuit.metadata if qubit_order is None: qubits = circuit.qubits elif len(qubit_order) != circuit.num_qubits or set(qubit_order) != set(circuit.qubits): raise ValueError("'qubit_order' does not contain exactly the same qubits as the circuit") else: qubits = qubit_order if clbit_order is None: clbits = circuit.clbits elif len(clbit_order) != circuit.num_clbits or set(clbit_order) != set(circuit.clbits): raise ValueError("'clbit_order' does not contain exactly the same clbits as the circuit") else: clbits = clbit_order dagcircuit.add_qubits(qubits) dagcircuit.add_clbits(clbits) for register in circuit.qregs: dagcircuit.add_qreg(register) for register in circuit.cregs: dagcircuit.add_creg(register) for instruction in circuit.data: op = instruction.operation if copy_operations: op = copy.deepcopy(op) dagcircuit.apply_operation_back(op, instruction.qubits, instruction.clbits) dagcircuit.duration = circuit.duration dagcircuit.unit = circuit.unit return dagcircuit
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Helper function for converting a circuit to an instruction.""" from qiskit.exceptions import QiskitError from qiskit.circuit.instruction import Instruction from qiskit.circuit.quantumregister import QuantumRegister from qiskit.circuit.classicalregister import ClassicalRegister, Clbit def circuit_to_instruction(circuit, parameter_map=None, equivalence_library=None, label=None): """Build an :class:`~.circuit.Instruction` object from a :class:`.QuantumCircuit`. The instruction is anonymous (not tied to a named quantum register), and so can be inserted into another circuit. The instruction will have the same string name as the circuit. Args: circuit (QuantumCircuit): the input circuit. parameter_map (dict): For parameterized circuits, a mapping from parameters in the circuit to parameters to be used in the instruction. If None, existing circuit parameters will also parameterize the instruction. equivalence_library (EquivalenceLibrary): Optional equivalence library where the converted instruction will be registered. label (str): Optional instruction label. Raises: QiskitError: if parameter_map is not compatible with circuit Return: qiskit.circuit.Instruction: an instruction equivalent to the action of the input circuit. Upon decomposition, this instruction will yield the components comprising the original circuit. Example: .. code-block:: from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.converters import circuit_to_instruction q = QuantumRegister(3, 'q') c = ClassicalRegister(3, 'c') circ = QuantumCircuit(q, c) circ.h(q[0]) circ.cx(q[0], q[1]) circ.measure(q[0], c[0]) circ.rz(0.5, q[1]).c_if(c, 2) circuit_to_instruction(circ) """ # pylint: disable=cyclic-import from qiskit.circuit.quantumcircuit import QuantumCircuit if parameter_map is None: parameter_dict = {p: p for p in circuit.parameters} else: parameter_dict = circuit._unroll_param_dict(parameter_map) if parameter_dict.keys() != circuit.parameters: raise QiskitError( ( "parameter_map should map all circuit parameters. " "Circuit parameters: {}, parameter_map: {}" ).format(circuit.parameters, parameter_dict) ) out_instruction = Instruction( name=circuit.name, num_qubits=circuit.num_qubits, num_clbits=circuit.num_clbits, params=[*parameter_dict.values()], label=label, ) out_instruction.condition = None target = circuit.assign_parameters(parameter_dict, inplace=False) if equivalence_library is not None: equivalence_library.add_equivalence(out_instruction, target) regs = [] if out_instruction.num_qubits > 0: q = QuantumRegister(out_instruction.num_qubits, "q") regs.append(q) if out_instruction.num_clbits > 0: c = ClassicalRegister(out_instruction.num_clbits, "c") regs.append(c) qubit_map = {bit: q[idx] for idx, bit in enumerate(circuit.qubits)} clbit_map = {bit: c[idx] for idx, bit in enumerate(circuit.clbits)} definition = [ instruction.replace( qubits=[qubit_map[y] for y in instruction.qubits], clbits=[clbit_map[y] for y in instruction.clbits], ) for instruction in target.data ] # fix condition for rule in definition: condition = getattr(rule.operation, "condition", None) if condition: reg, val = condition if isinstance(reg, Clbit): rule.operation.condition = (clbit_map[reg], val) elif reg.size == c.size: rule.operation.condition = (c, val) else: raise QiskitError( "Cannot convert condition in circuit with " "multiple classical registers to instruction" ) qc = QuantumCircuit(*regs, name=out_instruction.name) for instruction in definition: qc._append(instruction) if circuit.global_phase: qc.global_phase = circuit.global_phase out_instruction.definition = qc return out_instruction