repo
stringclasses
885 values
file
stringclasses
741 values
content
stringlengths
4
215k
https://github.com/xtophe388/QISKIT
xtophe388
import sys, getpass try: sys.path.append("../../") # go to parent dir import Qconfig qx_config = { "APItoken": Qconfig.APItoken, "url": Qconfig.config['url']} print('Qconfig loaded from %s.' % Qconfig.__file__) except: APItoken = getpass.getpass('Please input your token and hit enter: ') qx_config = { "APItoken": APItoken, "url":"https://quantumexperience.ng.bluemix.net/api"} print('Qconfig.py not found in qiskit-tutorial directory; Qconfig loaded using user input.') import numpy as np # importing the QISKit import qiskit from qiskit import QuantumCircuit, QuantumProgram # import tomography libary import qiskit.tools.qcvv.tomography as tomo # useful additional packages from qiskit.tools.visualization import plot_state from qiskit.tools.qi.qi import * Q_program = QuantumProgram() # Creating registers qr = Q_program.create_quantum_register("qr", 2) cr = Q_program.create_classical_register("cr", 2) # hadamard on qubit-1 only had = Q_program.create_circuit("had", [qr], [cr]) had.h(qr[1]) # CNOT gate with qubit 1 control, qubit 0 target (target for ibmqx4) cnot = Q_program.create_circuit("cnot", [qr], [cr]) cnot.cx(qr[1], qr[0]) U_had = np.array([[1,1],[1,-1]])/np.sqrt(2) # compute Choi-matrix from unitary had_choi = outer(vectorize(U_had)) plot_state(had_choi) # process tomography set for a quantum operation on qubit 1 had_tomo_set = tomo.process_tomography_set([1]) # Generate process tomography preparation and measurement circuits had_tomo_circuits = tomo.create_tomography_circuits(Q_program, 'had', qr, cr, had_tomo_set) print('Tomography circuit labels for "had" circuit:') for label in had_tomo_circuits: print(label) backend = 'local_qasm_simulator' shots = 1000 had_tomo_results = Q_program.execute(had_tomo_circuits, shots=shots, backend=backend) had_process_data = tomo.tomography_data(had_tomo_results, 'had', had_tomo_set) had_choi_fit = tomo.fit_tomography_data(had_process_data, options={'trace':2}) print('Process Fidelity = ', state_fidelity(vectorize(U_had)/2, had_choi_fit)) plot_state(had_choi_fit) # Register API token for online backends qiskit.register(qx_config['APItoken'], qx_config['url']) # Use the IBM Quantum Experience backend = 'ibmqx4' # Take 500 shots for each measurement basis # Note: reduce this number for larger number of qubits shots = 500 # set max credits max_credits = 8 # Run the experiment hadqx_tomo_results = Q_program.execute(had_tomo_circuits, backend=backend, shots=shots, max_credits=max_credits, timeout=500) print(hadqx_tomo_results) hadqx_process_data = tomo.tomography_data(hadqx_tomo_results, 'had', had_tomo_set) hadqx_choi_fit = tomo.fit_tomography_data(hadqx_process_data, options={'trace':2}) print('Process Fidelity = ', state_fidelity(vectorize(U_had)/2, hadqx_choi_fit)) plot_state(hadqx_choi_fit) #unitary matrix for CNOT with qubit 1 as control and qubit 0 as target. U_cnot = np.array([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]) # compute Choi-matrix from unitary cnot_choi = outer(vectorize(U_cnot)) plot_state(cnot_choi) # process tomography set for quantum operation on qubits 0 and 1 cnot_tomo_set = tomo.process_tomography_set([1, 0]) # Generate process tomography circuits cnot_tomo_circuits = tomo.create_tomography_circuits(Q_program, 'cnot', qr, cr, cnot_tomo_set) backend = 'local_qasm_simulator' shots = 1000 cnot_tomo_results = Q_program.execute(cnot_tomo_circuits, backend=backend, shots=shots, timeout=300) cnot_process_data = tomo.tomography_data(cnot_tomo_results, 'cnot', cnot_tomo_set) cnot_choi_fit = tomo.fit_tomography_data(cnot_process_data, options={'trace':4}) print('Process Fidelity = ', state_fidelity(vectorize(U_cnot)/2, cnot_choi_fit/4)) plot_state(cnot_choi_fit) # Register API token for online backends qiskit.register(qx_config['APItoken'], qx_config['url']) # Use the IBM Quantum Experience backend = 'ibmqx4' # Take 500 shots for each measurement basis # Note: reduce this number for larger number of qubits shots = 500 # set max credits max_credits = 8 # Set batch size and complete batch_size = 18 status = qiskit.get_backend(backend).status if status['operational'] == False or status['pending_jobs'] > 5: print('Warning: the selected backend appears to be busy or unavailable at present; consider choosing a different one if possible.') for j in range(8): batch_circs = cnot_tomo_circuits[j*batch_size:(j+1)*batch_size] if j == 0: cnotqx_tomo_results = Q_program.execute(batch_circs, backend=backend, shots=shots, max_credits=max_credits, timeout=500) else: cnotqx_tomo_results += Q_program.execute(batch_circs, backend=backend, shots=shots, max_credits=max_credits, timeout=500) msg = 'Batch %d/%d: %s' % (j+1, 8, cnotqx_tomo_results) print(msg) cnotqx_process_data = tomo.tomography_data(cnotqx_tomo_results, 'cnot', cnot_tomo_set) cnotqx_choi_fit = tomo.fit_tomography_data(cnotqx_process_data, options={'trace':4}) print('Process Fidelity = ', state_fidelity(vectorize(U_cnot)/2, cnotqx_choi_fit/4)) plot_state(cnotqx_choi_fit)
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for 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, 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 """Test QuantumCircuit.compose().""" import unittest import numpy as np from qiskit import transpile from qiskit.pulse import Schedule from qiskit.circuit import ( QuantumRegister, ClassicalRegister, Clbit, QuantumCircuit, Qubit, Parameter, Gate, Instruction, CASE_DEFAULT, SwitchCaseOp, ) from qiskit.circuit.library import HGate, RZGate, CXGate, CCXGate, TwoLocal from qiskit.circuit.classical import expr from qiskit.test import QiskitTestCase class TestCircuitCompose(QiskitTestCase): """Test composition of two circuits.""" def setUp(self): super().setUp() qreg1 = QuantumRegister(3, "lqr_1") qreg2 = QuantumRegister(2, "lqr_2") creg = ClassicalRegister(2, "lcr") self.circuit_left = QuantumCircuit(qreg1, qreg2, creg) self.circuit_left.h(qreg1[0]) self.circuit_left.x(qreg1[1]) self.circuit_left.p(0.1, qreg1[2]) self.circuit_left.cx(qreg2[0], qreg2[1]) self.left_qubit0 = qreg1[0] self.left_qubit1 = qreg1[1] self.left_qubit2 = qreg1[2] self.left_qubit3 = qreg2[0] self.left_qubit4 = qreg2[1] self.left_clbit0 = creg[0] self.left_clbit1 = creg[1] self.condition = (creg, 3) def test_compose_inorder(self): """Composing two circuits of the same width, default order. β”Œβ”€β”€β”€β” lqr_1_0: |0>─── H β”œβ”€β”€β”€ rqr_0: |0>──■─────── β”œβ”€β”€β”€β”€ β”‚ β”Œβ”€β”€β”€β” lqr_1_1: |0>─── X β”œβ”€β”€β”€ rqr_1: |0>──┼─── X β”œ β”Œβ”€β”΄β”€β”€β”€β”΄β”€β”€β” β”‚ β”œβ”€β”€β”€β”€ lqr_1_2: |0>─ P(0.1) β”œ + rqr_2: |0>──┼─── Y β”œ = β””β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”Œβ”€β”΄β”€β”β””β”€β”€β”€β”˜ lqr_2_0: |0>────■───── rqr_3: |0>─ X β”œβ”€β”€β”€β”€β”€ β”Œβ”€β”΄β”€β” β””β”€β”€β”€β”˜β”Œβ”€β”€β”€β” lqr_2_1: |0>─── X β”œβ”€β”€β”€ rqr_4: |0>────── Z β”œ β””β”€β”€β”€β”˜ β””β”€β”€β”€β”˜ lcr_0: 0 ═══════════ lcr_1: 0 ═══════════ β”Œβ”€β”€β”€β” lqr_1_0: |0>─── H β”œβ”€β”€β”€β”€β”€β– β”€β”€β”€β”€β”€β”€β”€ β”œβ”€β”€β”€β”€ β”‚ β”Œβ”€β”€β”€β” lqr_1_1: |0>─── X β”œβ”€β”€β”€β”€β”€β”Όβ”€β”€β”€ X β”œ β”Œβ”€β”΄β”€β”€β”€β”΄β”€β”€β” β”‚ β”œβ”€β”€β”€β”€ lqr_1_2: |0>─ P(0.1) β”œβ”€β”€β”Όβ”€β”€β”€ Y β”œ β””β”€β”€β”€β”€β”€β”€β”€β”€β”˜β”Œβ”€β”΄β”€β”β””β”€β”€β”€β”˜ lqr_2_0: |0>────■────── X β”œβ”€β”€β”€β”€β”€ β”Œβ”€β”΄β”€β” β””β”€β”€β”€β”˜β”Œβ”€β”€β”€β” lqr_2_1: |0>─── X β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€ Z β”œ β””β”€β”€β”€β”˜ β””β”€β”€β”€β”˜ lcr_0: 0 ═══════════════════════ lcr_1: 0 ═══════════════════════ """ qreg = QuantumRegister(5, "rqr") circuit_right = QuantumCircuit(qreg) circuit_right.cx(qreg[0], qreg[3]) circuit_right.x(qreg[1]) circuit_right.y(qreg[2]) circuit_right.z(qreg[4]) circuit_expected = self.circuit_left.copy() circuit_expected.cx(self.left_qubit0, self.left_qubit3) circuit_expected.x(self.left_qubit1) circuit_expected.y(self.left_qubit2) circuit_expected.z(self.left_qubit4) circuit_composed = self.circuit_left.compose(circuit_right, inplace=False) self.assertEqual(circuit_composed, circuit_expected) def test_compose_inorder_unusual_types(self): """Test that composition works in order, using Numpy integer types as well as regular integer types. In general, it should be permissible to use any of the same `QubitSpecifier` types (or similar for `Clbit`) that `QuantumCircuit.append` uses.""" qreg = QuantumRegister(5, "rqr") creg = ClassicalRegister(2, "rcr") circuit_right = QuantumCircuit(qreg, creg) circuit_right.cx(qreg[0], qreg[3]) circuit_right.x(qreg[1]) circuit_right.y(qreg[2]) circuit_right.z(qreg[4]) circuit_right.measure([0, 1], [0, 1]) circuit_expected = self.circuit_left.copy() circuit_expected.cx(self.left_qubit0, self.left_qubit3) circuit_expected.x(self.left_qubit1) circuit_expected.y(self.left_qubit2) circuit_expected.z(self.left_qubit4) circuit_expected.measure(self.left_qubit0, self.left_clbit0) circuit_expected.measure(self.left_qubit1, self.left_clbit1) circuit_composed = self.circuit_left.compose(circuit_right, np.arange(5), slice(0, 2)) self.assertEqual(circuit_composed, circuit_expected) def test_compose_inorder_inplace(self): """Composing two circuits of the same width, default order, inplace. β”Œβ”€β”€β”€β” lqr_1_0: |0>──── H β”œβ”€β”€β”€ rqr_0: |0>──■─────── β”œβ”€β”€β”€β”€ β”‚ β”Œβ”€β”€β”€β” lqr_1_1: |0>──── X β”œβ”€β”€β”€ rqr_1: |0>──┼─── X β”œ β”Œβ”€β”€β”΄β”€β”€β”€β”΄β”€β”€β” β”‚ β”œβ”€β”€β”€β”€ lqr_1_2: |0>─ U1(0.1) β”œ + rqr_2: |0>──┼─── Y β”œ = β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”Œβ”€β”΄β”€β”β””β”€β”€β”€β”˜ lqr_2_0: |0>─────■───── rqr_3: |0>─ X β”œβ”€β”€β”€β”€β”€ β”Œβ”€β”΄β”€β” β””β”€β”€β”€β”˜β”Œβ”€β”€β”€β” lqr_2_1: |0>──── X β”œβ”€β”€β”€ rqr_4: |0>────── Z β”œ β””β”€β”€β”€β”˜ β””β”€β”€β”€β”˜ lcr_0: 0 ═══════════ lcr_1: 0 ═══════════ β”Œβ”€β”€β”€β” lqr_1_0: |0>──── H β”œβ”€β”€β”€β”€β”€β– β”€β”€β”€β”€β”€β”€β”€ β”œβ”€β”€β”€β”€ β”‚ β”Œβ”€β”€β”€β” lqr_1_1: |0>──── X β”œβ”€β”€β”€β”€β”€β”Όβ”€β”€β”€ X β”œ β”Œβ”€β”€β”΄β”€β”€β”€β”΄β”€β”€β” β”‚ β”œβ”€β”€β”€β”€ lqr_1_2: |0>─ U1(0.1) β”œβ”€β”€β”Όβ”€β”€β”€ Y β”œ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β”Œβ”€β”΄β”€β”β””β”€β”€β”€β”˜ lqr_2_0: |0>─────■────── X β”œβ”€β”€β”€β”€β”€ β”Œβ”€β”΄β”€β” β””β”€β”€β”€β”˜β”Œβ”€β”€β”€β” lqr_2_1: |0>──── X β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€ Z β”œ β””β”€β”€β”€β”˜ β””β”€β”€β”€β”˜ lcr_0: 0 ════════════════════════ lcr_1: 0 ════════════════════════ """ qreg = QuantumRegister(5, "rqr") circuit_right = QuantumCircuit(qreg) circuit_right.cx(qreg[0], qreg[3]) circuit_right.x(qreg[1]) circuit_right.y(qreg[2]) circuit_right.z(qreg[4]) circuit_expected = self.circuit_left.copy() circuit_expected.cx(self.left_qubit0, self.left_qubit3) circuit_expected.x(self.left_qubit1) circuit_expected.y(self.left_qubit2) circuit_expected.z(self.left_qubit4) # inplace circuit_left = self.circuit_left.copy() circuit_left.compose(circuit_right, inplace=True) self.assertEqual(circuit_left, circuit_expected) def test_compose_inorder_smaller(self): """Composing with a smaller RHS dag, default order. β”Œβ”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β” lqr_1_0: |0>──── H β”œβ”€β”€β”€ rqr_0: |0>──■─── Tdg β”œ β”œβ”€β”€β”€β”€ β”Œβ”€β”΄β”€β”β””β”€β”€β”€β”€β”€β”˜ lqr_1_1: |0>──── X β”œβ”€β”€β”€ rqr_1: |0>─ X β”œβ”€β”€β”€β”€β”€β”€β”€ β”Œβ”€β”€β”΄β”€β”€β”€β”΄β”€β”€β” β””β”€β”€β”€β”˜ lqr_1_2: |0>─ U1(0.1) β”œ + = β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ lqr_2_0: |0>─────■───── β”Œβ”€β”΄β”€β” lqr_2_1: |0>──── X β”œβ”€β”€β”€ β””β”€β”€β”€β”˜ lcr_0: 0 ══════════════ lcr_1: 0 ══════════════ β”Œβ”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β” lqr_1_0: |0>──── H β”œβ”€β”€β”€β”€β”€β– β”€β”€β”€ Tdg β”œ β”œβ”€β”€β”€β”€ β”Œβ”€β”΄β”€β”β””β”€β”€β”€β”€β”€β”˜ lqr_1_1: |0>──── X β”œβ”€β”€β”€β”€ X β”œβ”€β”€β”€β”€β”€β”€β”€ β”Œβ”€β”€β”΄β”€β”€β”€β”΄β”€β”€β”β””β”€β”€β”€β”˜ lqr_1_2: |0>─ U1(0.1) β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ lqr_2_0: |0>─────■───────────────── β”Œβ”€β”΄β”€β” lqr_2_1: |0>──── X β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β””β”€β”€β”€β”˜ lcr_0: 0 ══════════════════════════ lcr_1: 0 ══════════════════════════ """ qreg = QuantumRegister(2, "rqr") circuit_right = QuantumCircuit(qreg) circuit_right.cx(qreg[0], qreg[1]) circuit_right.tdg(qreg[0]) circuit_expected = self.circuit_left.copy() circuit_expected.cx(self.left_qubit0, self.left_qubit1) circuit_expected.tdg(self.left_qubit0) circuit_composed = self.circuit_left.compose(circuit_right) self.assertEqual(circuit_composed, circuit_expected) def test_compose_permuted(self): """Composing two dags of the same width, permuted wires. β”Œβ”€β”€β”€β” lqr_1_0: |0>─── H β”œβ”€β”€β”€ rqr_0: |0>──■─────── β”œβ”€β”€β”€β”€ β”‚ β”Œβ”€β”€β”€β” lqr_1_1: |0>─── X β”œβ”€β”€β”€ rqr_1: |0>──┼─── X β”œ β”Œβ”€β”΄β”€β”€β”€β”΄β”€β”€β” β”‚ β”œβ”€β”€β”€β”€ lqr_1_2: |0>─ P(0.1) β”œ rqr_2: |0>──┼─── Y β”œ β””β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”Œβ”€β”΄β”€β”β””β”€β”€β”€β”˜ lqr_2_0: |0>────■───── + rqr_3: |0>─ X β”œβ”€β”€β”€β”€β”€ = β”Œβ”€β”΄β”€β” β””β”€β”€β”€β”˜β”Œβ”€β”€β”€β” lqr_2_1: |0>─── X β”œβ”€β”€β”€ rqr_4: |0>────── Z β”œ β””β”€β”€β”€β”˜ β””β”€β”€β”€β”˜ lcr_0: 0 ══════════════ lcr_1: 0 ══════════════ β”Œβ”€β”€β”€β” β”Œβ”€β”€β”€β” lqr_1_0: |0>─── H β”œβ”€β”€β”€β”€ Z β”œ β”œβ”€β”€β”€β”€ β”œβ”€β”€β”€β”€ lqr_1_1: |0>─── X β”œβ”€β”€β”€β”€ X β”œ β”Œβ”€β”΄β”€β”€β”€β”΄β”€β”€β”β”œβ”€β”€β”€β”€ lqr_1_2: |0>─ P(0.1) β”œβ”€ Y β”œ β””β”€β”€β”€β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”˜ lqr_2_0: |0>────■───────■── β”Œβ”€β”΄β”€β” β”Œβ”€β”΄β”€β” lqr_2_1: |0>─── X β”œβ”€β”€β”€β”€ X β”œ β””β”€β”€β”€β”˜ β””β”€β”€β”€β”˜ lcr_0: 0 ══════════════════ lcr_1: 0 ══════════════════ """ qreg = QuantumRegister(5, "rqr") circuit_right = QuantumCircuit(qreg) circuit_right.cx(qreg[0], qreg[3]) circuit_right.x(qreg[1]) circuit_right.y(qreg[2]) circuit_right.z(qreg[4]) circuit_expected = self.circuit_left.copy() circuit_expected.z(self.left_qubit0) circuit_expected.x(self.left_qubit1) circuit_expected.y(self.left_qubit2) circuit_expected.cx(self.left_qubit3, self.left_qubit4) # permuted wiring circuit_composed = self.circuit_left.compose( circuit_right, qubits=[ self.left_qubit3, self.left_qubit1, self.left_qubit2, self.left_qubit4, self.left_qubit0, ], inplace=False, ) self.assertEqual(circuit_composed, circuit_expected) def test_compose_permuted_smaller(self): """Composing with a smaller RHS dag, and permuted wires. Compose using indices. β”Œβ”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β” lqr_1_0: |0>─── H β”œβ”€β”€β”€ rqr_0: |0>──■─── Tdg β”œ β”œβ”€β”€β”€β”€ β”Œβ”€β”΄β”€β”β””β”€β”€β”€β”€β”€β”˜ lqr_1_1: |0>─── X β”œβ”€β”€β”€ rqr_1: |0>─ X β”œβ”€β”€β”€β”€β”€β”€β”€ β”Œβ”€β”΄β”€β”€β”€β”΄β”€β”€β” β””β”€β”€β”€β”˜ lqr_1_2: |0>─ P(0.1) β”œ + = β””β”€β”€β”€β”€β”€β”€β”€β”€β”˜ lqr_2_0: |0>────■───── β”Œβ”€β”΄β”€β” lqr_2_1: |0>─── X β”œβ”€β”€β”€ β””β”€β”€β”€β”˜ lcr_0: 0 ═════════════ lcr_1: 0 ═════════════ β”Œβ”€β”€β”€β” lqr_1_0: |0>─── H β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”œβ”€β”€β”€β”€ lqr_1_1: |0>─── X β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”Œβ”€β”΄β”€β”€β”€β”΄β”€β”€β”β”Œβ”€β”€β”€β” lqr_1_2: |0>─ P(0.1) β”œβ”€ X β”œβ”€β”€β”€β”€β”€β”€β”€ β””β”€β”€β”€β”€β”€β”€β”€β”€β”˜β””β”€β”¬β”€β”˜β”Œβ”€β”€β”€β”€β”€β” lqr_2_0: |0>────■───────■─── Tdg β”œ β”Œβ”€β”΄β”€β” β””β”€β”€β”€β”€β”€β”˜ lqr_2_1: |0>─── X β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β””β”€β”€β”€β”˜ lcr_0: 0 ═════════════════════════ lcr_1: 0 ═════════════════════════ """ qreg = QuantumRegister(2, "rqr") circuit_right = QuantumCircuit(qreg) circuit_right.cx(qreg[0], qreg[1]) circuit_right.tdg(qreg[0]) # permuted wiring of subset circuit_composed = self.circuit_left.compose(circuit_right, qubits=[3, 2]) circuit_expected = self.circuit_left.copy() circuit_expected.cx(self.left_qubit3, self.left_qubit2) circuit_expected.tdg(self.left_qubit3) self.assertEqual(circuit_composed, circuit_expected) def test_compose_classical(self): """Composing on classical bits. β”Œβ”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”β”Œβ”€β” lqr_1_0: |0>─── H β”œβ”€β”€β”€ rqr_0: |0>──■─── Tdg β”œβ”€Mβ”œ β”œβ”€β”€β”€β”€ β”Œβ”€β”΄β”€β”β””β”€β”¬β”€β”¬β”€β”˜β””β•₯β”˜ lqr_1_1: |0>─── X β”œβ”€β”€β”€ rqr_1: |0>─ X β”œβ”€β”€β”€Mβ”œβ”€β”€β”€β•«β”€ β”Œβ”€β”΄β”€β”€β”€β”΄β”€β”€β” β””β”€β”€β”€β”˜ β””β•₯β”˜ β•‘ lqr_1_2: |0>─ P(0.1) β”œ + rcr_0: 0 ════════╬════╩═ = β””β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β•‘ lqr_2_0: |0>────■───── rcr_1: 0 ════════╩══════ β”Œβ”€β”΄β”€β” lqr_2_1: |0>─── X β”œβ”€β”€β”€ β””β”€β”€β”€β”˜ lcr_0: 0 ══════════════ lcr_1: 0 ══════════════ β”Œβ”€β”€β”€β” lqr_1_0: |0>─── H β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”œβ”€β”€β”€β”€ β”Œβ”€β”€β”€β”€β”€β”β”Œβ”€β” lqr_1_1: |0>─── X β”œβ”€β”€β”€β”€β”€β– β”€β”€β”€ Tdg β”œβ”€Mβ”œ β”Œβ”€β”΄β”€β”€β”€β”΄β”€β”€β” β”‚ β””β”€β”€β”€β”€β”€β”˜β””β•₯β”˜ lqr_1_2: |0>─ P(0.1) β”œβ”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β•«β”€ β””β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β•‘ lqr_2_0: |0>────■───────┼──────────╫─ β”Œβ”€β”΄β”€β” β”Œβ”€β”΄β”€β” β”Œβ”€β” β•‘ lqr_2_1: |0>─── X β”œβ”€β”€β”€β”€ X β”œβ”€β”€β”€Mβ”œβ”€β”€β”€β•«β”€ β””β”€β”€β”€β”˜ β””β”€β”€β”€β”˜ β””β•₯β”˜ β•‘ lcr_0: 0 ══════════════════╩════╬═ β•‘ lcr_1: 0 ═══════════════════════╩═ """ qreg = QuantumRegister(2, "rqr") creg = ClassicalRegister(2, "rcr") circuit_right = QuantumCircuit(qreg, creg) circuit_right.cx(qreg[0], qreg[1]) circuit_right.tdg(qreg[0]) circuit_right.measure(qreg, creg) # permuted subset of qubits and clbits circuit_composed = self.circuit_left.compose(circuit_right, qubits=[1, 4], clbits=[1, 0]) circuit_expected = self.circuit_left.copy() circuit_expected.cx(self.left_qubit1, self.left_qubit4) circuit_expected.tdg(self.left_qubit1) circuit_expected.measure(self.left_qubit4, self.left_clbit0) circuit_expected.measure(self.left_qubit1, self.left_clbit1) self.assertEqual(circuit_composed, circuit_expected) def test_compose_conditional(self): """Composing on classical bits. β”Œβ”€β”€β”€β” β”Œβ”€β”€β”€β” β”Œβ”€β” lqr_1_0: |0>─── H β”œβ”€β”€β”€ rqr_0: ───────── H β”œβ”€β”€Mβ”œβ”€β”€β”€ β”œβ”€β”€β”€β”€ β”Œβ”€β”€β”€β” β””β”€β”¬β”€β”˜ β””β•₯β”˜β”Œβ”€β” lqr_1_1: |0>─── X β”œβ”€β”€β”€ rqr_1: ── X β”œβ”€β”€β”€β”€β”Όβ”€β”€β”€β”€β•«β”€β”€Mβ”œ β”Œβ”€β”΄β”€β”€β”€β”΄β”€β”€β” β””β”€β”¬β”€β”˜ β”‚ β•‘ β””β•₯β”˜ lqr_1_2: |0>─ P(0.1) β”œ + β”Œβ”€β”€β”΄β”€β”€β”β”Œβ”€β”€β”΄β”€β”€β” β•‘ β•‘ β””β”€β”€β”€β”€β”€β”€β”€β”€β”˜ rcr_0: β•‘ β•žβ•‘ β•žβ•β•©β•β•β•¬β• lqr_2_0: |0>────■───── β”‚ = 3 β”‚β”‚ = 3 β”‚ β•‘ β”Œβ”€β”΄β”€β” rcr_1: β•‘ β•žβ•‘ β•žβ•β•β•β•β•©β• lqr_2_1: |0>─── X β”œβ”€β”€β”€ β””β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”˜ lcr_0: 0 ══════════════ lcr_1: 0 ══════════════ β”Œβ”€β”€β”€β” lqr_1_0: ─── H β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”œβ”€β”€β”€β”€ β”Œβ”€β”€β”€β” β”Œβ”€β” lqr_1_1: ─── X β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ H β”œβ”€β”€β”€β”€β”€Mβ”œ β”Œβ”€β”΄β”€β”€β”€β”΄β”€β”€β” β””β”€β”¬β”€β”˜ β””β•₯β”˜ lqr_1_2: ─ P(0.1) β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β•«β”€ β””β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β•‘ lqr_2_0: ────■───────────────┼───────╫─ β”Œβ”€β”΄β”€β” β”Œβ”€β”€β”€β” β”‚ β”Œβ”€β” β•‘ lqr_2_1: ─── X β”œβ”€β”€β”€β”€β”€ X β”œβ”€β”€β”€β”€β”Όβ”€β”€β”€β”€Mβ”œβ”€β•«β”€ β””β”€β”€β”€β”˜ β””β”€β”¬β”€β”˜ β”‚ β””β•₯β”˜ β•‘ β”Œβ”€β”€β”΄β”€β”€β”β”Œβ”€β”€β”΄β”€β”€β” β•‘ β•‘ lcr_0: ════════════║ β•žβ•‘ β•žβ•β•¬β•β•β•©β• β”‚ = 3 β”‚β”‚ = 3 β”‚ β•‘ lcr_1: ════════════║ β•žβ•‘ β•žβ•β•©β•β•β•β• β””β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”˜ """ qreg = QuantumRegister(2, "rqr") creg = ClassicalRegister(2, "rcr") circuit_right = QuantumCircuit(qreg, creg) circuit_right.x(qreg[1]).c_if(creg, 3) circuit_right.h(qreg[0]).c_if(creg, 3) circuit_right.measure(qreg, creg) # permuted subset of qubits and clbits circuit_composed = self.circuit_left.compose(circuit_right, qubits=[1, 4], clbits=[0, 1]) circuit_expected = self.circuit_left.copy() circuit_expected.x(self.left_qubit4).c_if(*self.condition) circuit_expected.h(self.left_qubit1).c_if(*self.condition) circuit_expected.measure(self.left_qubit1, self.left_clbit0) circuit_expected.measure(self.left_qubit4, self.left_clbit1) self.assertEqual(circuit_composed, circuit_expected) def test_compose_conditional_no_match(self): """Test that compose correctly maps registers in conditions to the new circuit, even when there are no matching registers in the destination circuit. Regression test of gh-6583 and gh-6584.""" right = QuantumCircuit(QuantumRegister(3), ClassicalRegister(1), ClassicalRegister(1)) right.h(1) right.cx(1, 2) right.cx(0, 1) right.h(0) right.measure([0, 1], [0, 1]) right.z(2).c_if(right.cregs[0], 1) right.x(2).c_if(right.cregs[1], 1) test = QuantumCircuit(3, 3).compose(right, range(3), range(2)) z = next(ins.operation for ins in test.data[::-1] if ins.operation.name == "z") x = next(ins.operation for ins in test.data[::-1] if ins.operation.name == "x") # The registers should have been mapped, including the bits inside them. Unlike the # previous test, there are no matching registers in the destination circuit, so the # composition needs to add new registers (bit groupings) over the existing mapped bits. self.assertIsNot(z.condition, None) self.assertIsInstance(z.condition[0], ClassicalRegister) self.assertEqual(len(z.condition[0]), len(right.cregs[0])) self.assertIs(z.condition[0][0], test.clbits[0]) self.assertEqual(z.condition[1], 1) self.assertIsNot(x.condition, None) self.assertIsInstance(x.condition[0], ClassicalRegister) self.assertEqual(len(x.condition[0]), len(right.cregs[1])) self.assertEqual(z.condition[1], 1) self.assertIs(x.condition[0][0], test.clbits[1]) def test_compose_switch_match(self): """Test that composition containing a `switch` with a register that matches proceeds correctly.""" case_0 = QuantumCircuit(1, 2) case_0.x(0) case_1 = QuantumCircuit(1, 2) case_1.z(0) case_default = QuantumCircuit(1, 2) cr = ClassicalRegister(2, "target") right = QuantumCircuit(QuantumRegister(1), cr) right.switch(cr, [(0, case_0), (1, case_1), (CASE_DEFAULT, case_default)], [0], [0, 1]) test = QuantumCircuit(QuantumRegister(3), cr, ClassicalRegister(2)).compose( right, [1], [0, 1] ) expected = test.copy_empty_like() expected.switch(cr, [(0, case_0), (1, case_1), (CASE_DEFAULT, case_default)], [1], [0, 1]) self.assertEqual(test, expected) def test_compose_switch_no_match(self): """Test that composition containing a `switch` with a register that matches proceeds correctly.""" case_0 = QuantumCircuit(1, 2) case_0.x(0) case_1 = QuantumCircuit(1, 2) case_1.z(0) case_default = QuantumCircuit(1, 2) cr = ClassicalRegister(2, "target") right = QuantumCircuit(QuantumRegister(1), cr) right.switch(cr, [(0, case_0), (1, case_1), (CASE_DEFAULT, case_default)], [0], [0, 1]) test = QuantumCircuit(3, 3).compose(right, [1], [0, 1]) self.assertEqual(len(test.data), 1) self.assertIsInstance(test.data[0].operation, SwitchCaseOp) target = test.data[0].operation.target self.assertIn(target, test.cregs) self.assertEqual(list(target), test.clbits[0:2]) def test_compose_gate(self): """Composing with a gate. β”Œβ”€β”€β”€β” β”Œβ”€β”€β”€β” β”Œβ”€β”€β”€β” lqr_1_0: ─── H β”œβ”€β”€β”€ lqr_1_0: ─── H β”œβ”€β”€β”€β”€β”€ X β”œ β”œβ”€β”€β”€β”€ β”œβ”€β”€β”€β”€ β””β”€β”¬β”€β”˜ lqr_1_1: ─── X β”œβ”€β”€β”€ lqr_1_1: ─── X β”œβ”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€ β”Œβ”€β”΄β”€β”€β”€β”΄β”€β”€β” ───■─── β”Œβ”€β”΄β”€β”€β”€β”΄β”€β”€β” β”‚ lqr_1_2: ─ P(0.1) β”œ + β”Œβ”€β”΄β”€β” = lqr_1_2: ─ P(0.1) β”œβ”€β”€β”€β”Όβ”€β”€β”€ β””β”€β”€β”€β”€β”€β”€β”€β”€β”˜ ── X β”œβ”€ β””β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ lqr_2_0: ────■───── β””β”€β”€β”€β”˜ lqr_2_0: ────■────────┼── β”Œβ”€β”΄β”€β” β”Œβ”€β”΄β”€β” β”‚ lqr_2_1: ─── X β”œβ”€β”€β”€ lqr_2_1: ─── X β”œβ”€β”€β”€β”€β”€β”€β– β”€β”€β”€ β””β”€β”€β”€β”˜ β””β”€β”€β”€β”˜ lcr_0: 0 ══════════ lcr_0: 0 ═════════════════ lcr_1: 0 ══════════ lcr_1: 0 ═════════════════ """ circuit_composed = self.circuit_left.compose(CXGate(), qubits=[4, 0]) circuit_expected = self.circuit_left.copy() circuit_expected.cx(self.left_qubit4, self.left_qubit0) self.assertEqual(circuit_composed, circuit_expected) def test_compose_calibrations(self): """Test that composing two circuits updates calibrations.""" circ_left = QuantumCircuit(1) circ_left.add_calibration("h", [0], None) circ_right = QuantumCircuit(1) circ_right.add_calibration("rx", [0], None) circ = circ_left.compose(circ_right) self.assertEqual(len(circ.calibrations), 2) self.assertEqual(len(circ_left.calibrations), 1) circ_left = QuantumCircuit(1) circ_left.add_calibration("h", [0], None) circ_right = QuantumCircuit(1) circ_right.add_calibration("h", [1], None) circ = circ_left.compose(circ_right) self.assertEqual(len(circ.calibrations), 1) self.assertEqual(len(circ.calibrations["h"]), 2) self.assertEqual(len(circ_left.calibrations), 1) # Ensure that transpiled _calibration is defaultdict qc = QuantumCircuit(2, 2) qc.h(0) qc.cx(0, 1) qc.measure(0, 0) qc = transpile(qc, None, basis_gates=["h", "cx"], coupling_map=[[0, 1], [1, 0]]) qc.add_calibration("cx", [0, 1], Schedule()) def test_compose_one_liner(self): """Test building a circuit in one line, for fun.""" circ = QuantumCircuit(3) h = HGate() rz = RZGate(0.1) cx = CXGate() ccx = CCXGate() circ = circ.compose(h, [0]).compose(cx, [0, 2]).compose(ccx, [2, 1, 0]).compose(rz, [1]) expected = QuantumCircuit(3) expected.h(0) expected.cx(0, 2) expected.ccx(2, 1, 0) expected.rz(0.1, 1) self.assertEqual(circ, expected) def test_compose_global_phase(self): """Composing with global phase.""" circ1 = QuantumCircuit(1, global_phase=1) circ1.rz(0.5, 0) circ2 = QuantumCircuit(1, global_phase=2) circ3 = QuantumCircuit(1, global_phase=3) circ4 = circ1.compose(circ2).compose(circ3) self.assertEqual( circ4.global_phase, circ1.global_phase + circ2.global_phase + circ3.global_phase ) def test_compose_front_circuit(self): """Test composing a circuit at the front of a circuit.""" qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) other = QuantumCircuit(2) other.cz(1, 0) other.z(1) output = qc.compose(other, front=True) expected = QuantumCircuit(2) expected.cz(1, 0) expected.z(1) expected.h(0) expected.cx(0, 1) self.assertEqual(output, expected) def test_compose_front_gate(self): """Test composing a gate at the front of a circuit.""" qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) output = qc.compose(CXGate(), [1, 0], front=True) expected = QuantumCircuit(2) expected.cx(1, 0) expected.h(0) expected.cx(0, 1) self.assertEqual(output, expected) def test_compose_adds_parameters(self): """Test the composed circuit contains all parameters.""" a, b = Parameter("a"), Parameter("b") qc_a = QuantumCircuit(1) qc_a.rx(a, 0) qc_b = QuantumCircuit(1) qc_b.rx(b, 0) with self.subTest("compose with other circuit out-of-place"): qc_1 = qc_a.compose(qc_b) self.assertEqual(qc_1.parameters, {a, b}) with self.subTest("compose with other instruction out-of-place"): instr_b = qc_b.to_instruction() qc_2 = qc_a.compose(instr_b, [0]) self.assertEqual(qc_2.parameters, {a, b}) with self.subTest("compose with other circuit in-place"): qc_a.compose(qc_b, inplace=True) self.assertEqual(qc_a.parameters, {a, b}) def test_wrapped_compose(self): """Test wrapping the circuit upon composition works.""" qc_a = QuantumCircuit(1) qc_a.x(0) qc_b = QuantumCircuit(1, name="B") qc_b.h(0) qc_a.compose(qc_b, wrap=True, inplace=True) self.assertDictEqual(qc_a.count_ops(), {"B": 1, "x": 1}) self.assertDictEqual(qc_a.decompose().count_ops(), {"h": 1, "u3": 1}) def test_wrapping_unitary_circuit(self): """Test a unitary circuit will be wrapped as Gate, else as Instruction.""" qc_init = QuantumCircuit(1) qc_init.x(0) qc_unitary = QuantumCircuit(1, name="a") qc_unitary.ry(0.23, 0) qc_nonunitary = QuantumCircuit(1) qc_nonunitary.reset(0) with self.subTest("wrapping a unitary circuit"): qc = qc_init.compose(qc_unitary, wrap=True) self.assertIsInstance(qc.data[1].operation, Gate) with self.subTest("wrapping a non-unitary circuit"): qc = qc_init.compose(qc_nonunitary, wrap=True) self.assertIsInstance(qc.data[1].operation, Instruction) def test_single_bit_condition(self): """Test that compose can correctly handle circuits that contain conditions on single bits. This is a regression test of the bug that broke qiskit-experiments in gh-7653.""" base = QuantumCircuit(1, 1) base.x(0).c_if(0, True) test = QuantumCircuit(1, 1).compose(base) self.assertIsNot(base.clbits[0], test.clbits[0]) self.assertEqual(base, test) self.assertIs(test.data[0].operation.condition[0], test.clbits[0]) def test_condition_mapping_ifelseop(self): """Test that the condition in an `IfElseOp` is correctly mapped to a new set of bits and registers.""" base_loose = Clbit() base_creg = ClassicalRegister(2) base_qreg = QuantumRegister(1) base = QuantumCircuit(base_qreg, [base_loose], base_creg) with base.if_test((base_loose, True)): base.x(0) with base.if_test((base_creg, 3)): base.x(0) test_loose = Clbit() test_creg = ClassicalRegister(2) test_qreg = QuantumRegister(1) test = QuantumCircuit(test_qreg, [test_loose], test_creg).compose(base) bit_instruction = test.data[0].operation reg_instruction = test.data[1].operation self.assertIs(bit_instruction.condition[0], test_loose) self.assertEqual(bit_instruction.condition, (test_loose, True)) self.assertIs(reg_instruction.condition[0], test_creg) self.assertEqual(reg_instruction.condition, (test_creg, 3)) def test_condition_mapping_whileloopop(self): """Test that the condition in a `WhileLoopOp` is correctly mapped to a new set of bits and registers.""" base_loose = Clbit() base_creg = ClassicalRegister(2) base_qreg = QuantumRegister(1) base = QuantumCircuit(base_qreg, [base_loose], base_creg) with base.while_loop((base_loose, True)): base.x(0) with base.while_loop((base_creg, 3)): base.x(0) test_loose = Clbit() test_creg = ClassicalRegister(2) test_qreg = QuantumRegister(1) test = QuantumCircuit(test_qreg, [test_loose], test_creg).compose(base) bit_instruction = test.data[0].operation reg_instruction = test.data[1].operation self.assertIs(bit_instruction.condition[0], test_loose) self.assertEqual(bit_instruction.condition, (test_loose, True)) self.assertIs(reg_instruction.condition[0], test_creg) self.assertEqual(reg_instruction.condition, (test_creg, 3)) def test_compose_no_clbits_in_one(self): """Test combining a circuit with cregs to one without""" ansatz = TwoLocal(2, rotation_blocks="ry", entanglement_blocks="cx") qc = QuantumCircuit(2) qc.measure_all() out = ansatz.compose(qc) self.assertEqual(out.clbits, qc.clbits) def test_compose_no_clbits_in_one_inplace(self): """Test combining a circuit with cregs to one without inplace""" ansatz = TwoLocal(2, rotation_blocks="ry", entanglement_blocks="cx") qc = QuantumCircuit(2) qc.measure_all() ansatz.compose(qc, inplace=True) self.assertEqual(ansatz.clbits, qc.clbits) def test_compose_no_clbits_in_one_multireg(self): """Test combining a circuit with cregs to one without, multi cregs""" ansatz = TwoLocal(2, rotation_blocks="ry", entanglement_blocks="cx") qa = QuantumRegister(2, "q") ca = ClassicalRegister(2, "a") cb = ClassicalRegister(2, "b") qc = QuantumCircuit(qa, ca, cb) qc.measure(0, cb[1]) out = ansatz.compose(qc) self.assertEqual(out.clbits, qc.clbits) self.assertEqual(out.cregs, qc.cregs) def test_compose_noclbits_registerless(self): """Combining a circuit with cregs to one without, registerless case""" inner = QuantumCircuit([Qubit(), Qubit()], [Clbit(), Clbit()]) inner.measure([0, 1], [0, 1]) outer = QuantumCircuit(2) outer.compose(inner, inplace=True) self.assertEqual(outer.clbits, inner.clbits) self.assertEqual(outer.cregs, []) def test_expr_condition_is_mapped(self): """Test that an expression in a condition involving several registers is mapped correctly to the destination circuit.""" inner = QuantumCircuit(1) inner.x(0) a_src = ClassicalRegister(2, "a_src") b_src = ClassicalRegister(2, "b_src") c_src = ClassicalRegister(name="c_src", bits=list(a_src) + list(b_src)) source = QuantumCircuit(QuantumRegister(1), a_src, b_src, c_src) test_1 = lambda: expr.lift(a_src[0]) test_2 = lambda: expr.logic_not(b_src[1]) test_3 = lambda: expr.logic_and(expr.bit_and(b_src, 2), expr.less(c_src, 7)) source.if_test(test_1(), inner.copy(), [0], []) source.if_else(test_2(), inner.copy(), inner.copy(), [0], []) source.while_loop(test_3(), inner.copy(), [0], []) a_dest = ClassicalRegister(2, "a_dest") b_dest = ClassicalRegister(2, "b_dest") dest = QuantumCircuit(QuantumRegister(1), a_dest, b_dest).compose(source) # Check that the input conditions weren't mutated. for in_condition, instruction in zip((test_1, test_2, test_3), source.data): self.assertEqual(in_condition(), instruction.operation.condition) # Should be `a_dest`, `b_dest` and an added one to account for `c_src`. self.assertEqual(len(dest.cregs), 3) mapped_reg = dest.cregs[-1] expected = QuantumCircuit(dest.qregs[0], a_dest, b_dest, mapped_reg) expected.if_test(expr.lift(a_dest[0]), inner.copy(), [0], []) expected.if_else(expr.logic_not(b_dest[1]), inner.copy(), inner.copy(), [0], []) expected.while_loop( expr.logic_and(expr.bit_and(b_dest, 2), expr.less(mapped_reg, 7)), inner.copy(), [0], [] ) self.assertEqual(dest, expected) def test_expr_target_is_mapped(self): """Test that an expression in a switch statement's target is mapping correctly to the destination circuit.""" inner1 = QuantumCircuit(1) inner1.x(0) inner2 = QuantumCircuit(1) inner2.z(0) a_src = ClassicalRegister(2, "a_src") b_src = ClassicalRegister(2, "b_src") c_src = ClassicalRegister(name="c_src", bits=list(a_src) + list(b_src)) source = QuantumCircuit(QuantumRegister(1), a_src, b_src, c_src) test_1 = lambda: expr.lift(a_src[0]) test_2 = lambda: expr.logic_not(b_src[1]) test_3 = lambda: expr.lift(b_src) test_4 = lambda: expr.bit_and(c_src, 7) source.switch(test_1(), [(False, inner1.copy()), (True, inner2.copy())], [0], []) source.switch(test_2(), [(False, inner1.copy()), (True, inner2.copy())], [0], []) source.switch(test_3(), [(0, inner1.copy()), (CASE_DEFAULT, inner2.copy())], [0], []) source.switch(test_4(), [(0, inner1.copy()), (CASE_DEFAULT, inner2.copy())], [0], []) a_dest = ClassicalRegister(2, "a_dest") b_dest = ClassicalRegister(2, "b_dest") dest = QuantumCircuit(QuantumRegister(1), a_dest, b_dest).compose(source) # Check that the input expressions weren't mutated. for in_target, instruction in zip((test_1, test_2, test_3, test_4), source.data): self.assertEqual(in_target(), instruction.operation.target) # Should be `a_dest`, `b_dest` and an added one to account for `c_src`. self.assertEqual(len(dest.cregs), 3) mapped_reg = dest.cregs[-1] expected = QuantumCircuit(dest.qregs[0], a_dest, b_dest, mapped_reg) expected.switch( expr.lift(a_dest[0]), [(False, inner1.copy()), (True, inner2.copy())], [0], [] ) expected.switch( expr.logic_not(b_dest[1]), [(False, inner1.copy()), (True, inner2.copy())], [0], [] ) expected.switch( expr.lift(b_dest), [(0, inner1.copy()), (CASE_DEFAULT, inner2.copy())], [0], [] ) expected.switch( expr.bit_and(mapped_reg, 7), [(0, inner1.copy()), (CASE_DEFAULT, inner2.copy())], [0], [], ) self.assertEqual(dest, expected) if __name__ == "__main__": unittest.main()
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../utils/") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) # Pauli Twirling print("created zne_qcs (length:", len(zne_qcs), ")") # optimization_level must be 0 # feed initial_layout here to see the picture of the circuits before casting the job t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") print(str(backend)) shots = 1 << 13 reps = 8 # unused jobs = [] for _ in range(reps): #! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits, name="calq") meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # we have to feed initial_layout to calibration matrix cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) meas_calibs[0].draw("mpl") dt_now = datetime.datetime.now() print(dt_now) filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl" print(filename) # with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) # with open(filename, "wb") as f: # pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) # with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump(backend.properties(), f) retrieved_jobs = jobs retrieved_cal_job = cal_job cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in retrieved_jobs: mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors) rho = expvals_to_valid_rho(num_qubits, zne_expvals) fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
https://github.com/Ilan-Bondarevsky/qiskit_algorithm
Ilan-Bondarevsky
from qiskit import Aer, IBMQ, execute from qiskit import transpile, assemble from qiskit.tools.monitor import job_monitor from qiskit.tools.monitor import job_monitor import matplotlib.pyplot as plt from qiskit.visualization import plot_histogram, plot_state_city """ Qiskit backends to execute the quantum circuit """ def simulator(qc): """ Run on local simulator :param qc: quantum circuit :return: """ backend = Aer.get_backend("qasm_simulator") shots = 2048 tqc = transpile(qc, backend) qobj = assemble(tqc, shots=shots) job_sim = backend.run(qobj) qc_results = job_sim.result() return qc_results, shots def simulator_state_vector(qc): """ Select the StatevectorSimulator from the Aer provider :param qc: quantum circuit :return: statevector """ simulator = Aer.get_backend('statevector_simulator') # Execute and get counts result = execute(qc, simulator).result() state_vector = result.get_statevector(qc) return state_vector def real_quantum_device(qc): """ Use the IBMQ essex device :param qc: quantum circuit :return: """ provider = IBMQ.load_account() backend = provider.get_backend('ibmq_santiago') shots = 2048 TQC = transpile(qc, backend) qobj = assemble(TQC, shots=shots) job_exp = backend.run(qobj) job_monitor(job_exp) QC_results = job_exp.result() return QC_results, shots def counts(qc_results): """ Get counts representing the wave-function amplitudes :param qc_results: :return: dict keys are bit_strings and their counting values """ return qc_results.get_counts() def plot_results(qc_results): """ Visualizing wave-function amplitudes in a histogram :param qc_results: quantum circuit :return: """ plt.show(plot_histogram(qc_results.get_counts(), figsize=(8, 6), bar_labels=False)) def plot_state_vector(state_vector): """Visualizing state vector in the density matrix representation""" plt.show(plot_state_city(state_vector))
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import pulse with pulse.build(name='my_example') as my_program: # Add instructions here pass my_program from qiskit.pulse import DriveChannel channel = DriveChannel(0) from qiskit.providers.fake_provider import FakeValencia backend = FakeValencia() with pulse.build(backend=backend, name='backend_aware') as backend_aware_program: channel = pulse.drive_channel(0) print(pulse.num_qubits()) # Raises an error as backend only has 5 qubits #pulse.drive_channel(100) with pulse.build(backend) as delay_5dt: pulse.delay(5, channel) from qiskit.pulse import library amp = 1 sigma = 10 num_samples = 128 gaus = pulse.library.Gaussian(num_samples, amp, sigma, name="Parametric Gaus") gaus.draw() import numpy as np times = np.arange(num_samples) gaussian_samples = np.exp(-1/2 *((times - num_samples / 2) ** 2 / sigma**2)) gaus = library.Waveform(gaussian_samples, name="WF Gaus") gaus.draw() gaus = library.gaussian(duration=num_samples, amp=amp, sigma=sigma, name="Lib Gaus") gaus.draw() with pulse.build() as schedule: pulse.play(gaus, channel) schedule.draw() with pulse.build() as schedule: pulse.play([0.001*i for i in range(160)], channel) schedule.draw() with pulse.build(backend) as schedule: pulse.set_frequency(4.5e9, channel) with pulse.build(backend) as schedule: pulse.shift_phase(np.pi, channel) from qiskit.pulse import Acquire, AcquireChannel, MemorySlot with pulse.build(backend) as schedule: pulse.acquire(1200, pulse.acquire_channel(0), MemorySlot(0)) with pulse.build(backend, name='Left align example') as program: with pulse.align_left(): gaussian_pulse = library.gaussian(100, 0.5, 20) pulse.play(gaussian_pulse, pulse.drive_channel(0)) pulse.play(gaussian_pulse, pulse.drive_channel(1)) pulse.play(gaussian_pulse, pulse.drive_channel(1)) program.draw() with pulse.build(backend, name='Right align example') as program: with pulse.align_right(): gaussian_pulse = library.gaussian(100, 0.5, 20) pulse.play(gaussian_pulse, pulse.drive_channel(0)) pulse.play(gaussian_pulse, pulse.drive_channel(1)) pulse.play(gaussian_pulse, pulse.drive_channel(1)) program.draw() with pulse.build(backend, name='example') as program: gaussian_pulse = library.gaussian(100, 0.5, 20) with pulse.align_equispaced(2*gaussian_pulse.duration): pulse.play(gaussian_pulse, pulse.drive_channel(0)) pulse.play(gaussian_pulse, pulse.drive_channel(1)) pulse.play(gaussian_pulse, pulse.drive_channel(1)) program.draw() with pulse.build(backend, name='example') as program: with pulse.align_sequential(): gaussian_pulse = library.gaussian(100, 0.5, 20) pulse.play(gaussian_pulse, pulse.drive_channel(0)) pulse.play(gaussian_pulse, pulse.drive_channel(1)) pulse.play(gaussian_pulse, pulse.drive_channel(1)) program.draw() with pulse.build(backend, name='Offset example') as program: with pulse.phase_offset(3.14, pulse.drive_channel(0)): pulse.play(gaussian_pulse, pulse.drive_channel(0)) with pulse.frequency_offset(10e6, pulse.drive_channel(0)): pulse.play(gaussian_pulse, pulse.drive_channel(0)) program.draw() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/Chibikuri/qwopt
Chibikuri
# -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.3.1 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # This cell is added by sphinx-gallery # It can be customized to whatever you like # %matplotlib inline # # # Quantum Generative Adversarial Networks with Cirq + TensorFlow # ============================================================== # # .. meta:: # :property="og:description": This demo constructs and trains a Quantum # Generative Adversarial Network (QGAN) using PennyLane, Cirq, and TensorFlow. # :property="og:image": https://pennylane.ai/qml/_images/qgan3.png # # This demo constructs a Quantum Generative Adversarial Network (QGAN) # (`Lloyd and Weedbrook # (2018) <https://journals.aps.org/prl/abstract/10.1103/PhysRevLett.121.040502>`__, # `Dallaire-Demers and Killoran # (2018) <https://journals.aps.org/pra/abstract/10.1103/PhysRevA.98.012324>`__) # using two subcircuits, a *generator* and a *discriminator*. The # generator attempts to generate synthetic quantum data to match a pattern # of "real" data, while the discriminator tries to discern real data from # fake data (see image below). The gradient of the discriminator’s output provides a # training signal for the generator to improve its fake generated data. # # | # # .. figure:: ../demonstrations/QGAN/qgan.png # :align: center # :width: 75% # :target: javascript:void(0) # # | # # Using Cirq + TensorFlow # ~~~~~~~~~~~~~~~~~~~~~~~ # PennyLane allows us to mix and match quantum devices and classical machine # learning software. For this demo, we will link together # Google's `Cirq <https://cirq.readthedocs.io/en/stable/>`_ and `TensorFlow <https://www.tensorflow.org/>`_ libraries. # # We begin by importing PennyLane, NumPy, and TensorFlow. # # import pennylane as qml import numpy as np import tensorflow as tf # We also declare a 3-qubit simulator device running in Cirq. # # dev = qml.device('cirq.simulator', wires=4) # Generator and Discriminator # ~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # In classical GANs, the starting point is to draw samples either from # some β€œreal data” distribution, or from the generator, and feed them to # the discriminator. In this QGAN example, we will use a quantum circuit # to generate the real data. # # For this simple example, our real data will be a qubit that has been # rotated (from the starting state $\left|0\right\rangle$) to some # arbitrary, but fixed, state. # # def real(angles, **kwargs): qml.RY(0.27740551, wires=0) qml.PauliX(wires =0) qml.CRY(0.20273270, wires=[0, 1]) qml.PauliX(wires =0) qml.CRY(np.pi/2, wires=[0, 1]) qml.CRY(np.pi/2, wires=[0, 2]) qml.PauliX(wires =0) qml.CRY(1.42492, wires=[0, 2]) qml.PauliX(wires =0) # For the generator and discriminator, we will choose the same basic # circuit structure, but acting on different wires. # # Both the real data circuit and the generator will output on wire 0, # which will be connected as an input to the discriminator. Wire 1 is # provided as a workspace for the generator, while the discriminator’s # output will be on wire 2. # # # + def generator(w, **kwargs): qml.Hadamard(wires=0) # qml.Hadamard(wires=1) qml.RX(w[0], wires=0) qml.RX(w[1], wires=1) qml.RX(w[2], wires=2) qml.RY(w[3], wires=0) qml.RY(w[4], wires=1) qml.RY(w[5], wires=2) qml.RZ(w[6], wires=0) qml.RZ(w[7], wires=1) qml.RZ(w[8], wires=2) qml.CNOT(wires=[0, 1]) qml.CNOT(wires=[1, 2]) qml.RX(w[9], wires=0) qml.RY(w[10], wires=0) qml.RZ(w[11], wires=0) qml.RX(w[12], wires=1) qml.RY(w[13], wires=1) qml.RZ(w[14], wires=1) def discriminator(w): qml.Hadamard(wires=1) qml.RX(w[0], wires=1) qml.RX(w[1], wires=2) qml.RX(w[2], wires=3) qml.RY(w[3], wires=1) qml.RY(w[4], wires=2) qml.RY(w[5], wires=3) qml.RZ(w[6], wires=1) qml.RZ(w[7], wires=2) qml.RZ(w[8], wires=3) qml.CNOT(wires=[1, 2]) qml.CNOT(wires=[2, 3]) qml.RX(w[9], wires=2) qml.RY(w[10], wires=2) qml.RZ(w[11], wires=2) qml.RX(w[12], wires=3) qml.RY(w[13], wires=3) qml.RZ(w[14], wires=3) # - # We create two QNodes. One where the real data source is wired up to the # discriminator, and one where the generator is connected to the # discriminator. In order to pass TensorFlow Variables into the quantum # circuits, we specify the ``"tf"`` interface. # # # + @qml.qnode(dev, interface="tf") def real_disc_circuit(phi, theta, omega, disc_weights): real([phi, theta, omega]) discriminator(disc_weights) return qml.expval(qml.PauliZ(3)) @qml.qnode(dev, interface="tf") def gen_disc_circuit(gen_weights, disc_weights): generator(gen_weights) discriminator(disc_weights) return qml.expval(qml.PauliZ(3)) # - # QGAN cost functions # ~~~~~~~~~~~~~~~~~~~ # # There are two cost functions of interest, corresponding to the two # stages of QGAN training. These cost functions are built from two pieces: # the first piece is the probability that the discriminator correctly # classifies real data as real. The second piece is the probability that the # discriminator classifies fake data (i.e., a state prepared by the # generator) as real. # # The discriminator is trained to maximize the probability of # correctly classifying real data, while minimizing the probability of # mistakenly classifying fake data. # # The generator is trained to maximize the probability that the # discriminator accepts fake data as real. # # # + def prob_real_true(disc_weights): true_disc_output = real_disc_circuit(phi, theta, omega, disc_weights) # convert to probability prob_real_true = (true_disc_output + 1) / 2 return prob_real_true def prob_fake_true(gen_weights, disc_weights): fake_disc_output = gen_disc_circuit(gen_weights, disc_weights) # convert to probability prob_fake_true = (fake_disc_output + 1) / 2 return prob_fake_true def disc_cost(disc_weights): cost = prob_fake_true(gen_weights, disc_weights) - prob_real_true(disc_weights) return cost def gen_cost(gen_weights): return -prob_fake_true(gen_weights, disc_weights) # - # Training the QGAN # ~~~~~~~~~~~~~~~~~ # # We initialize the fixed angles of the β€œreal data” circuit, as well as # the initial parameters for both generator and discriminator. These are # chosen so that the generator initially prepares a state on wire 0 that # is very close to the $\left| 1 \right\rangle$ state. # # # + phi = np.pi / 6 theta = np.pi / 2 omega = np.pi / 7 np.random.seed(0) eps = 1e-2 init_gen_weights = np.array([np.pi] + [0] * 14) + \ np.random.normal(scale=eps, size=(15,)) init_disc_weights = np.random.normal(size=(15,)) gen_weights = tf.Variable(init_gen_weights) disc_weights = tf.Variable(init_disc_weights) print(gen_weights) # - # We begin by creating the optimizer: # # opt = tf.keras.optimizers.SGD(0.4) # In the first stage of training, we optimize the discriminator while # keeping the generator parameters fixed. # # # + cost = lambda: disc_cost(disc_weights) for step in range(100): opt.minimize(cost, disc_weights) if step % 5 == 0: cost_val = cost().numpy() print("Step {}: cost = {}".format(step, cost_val)) # - # At the discriminator’s optimum, the probability for the discriminator to # correctly classify the real data should be close to one. # # print("Prob(real classified as real): ", prob_real_true(disc_weights).numpy()) # For comparison, we check how the discriminator classifies the # generator’s (still unoptimized) fake data: # # print("Prob(fake classified as real): ", prob_fake_true(gen_weights, disc_weights).numpy()) # In the adversarial game we now have to train the generator to better # fool the discriminator. For this demo, we only perform one stage of the # game. For more complex models, we would continue training the models in an # alternating fashion until we reach the optimum point of the two-player # adversarial game. # # # + cost = lambda: gen_cost(gen_weights) for step in range(100): opt.minimize(cost, gen_weights) if step % 5 == 0: cost_val = cost().numpy() print("Step {}: cost = {}".format(step, cost_val)) # - # At the optimum of the generator, the probability for the discriminator # to be fooled should be close to 1. # # print("Prob(fake classified as real): ", prob_fake_true(gen_weights, disc_weights).numpy()) # At the joint optimum the discriminator cost will be close to zero, # indicating that the discriminator assigns equal probability to both real and # generated data. # # print("Discriminator cost: ", disc_cost(disc_weights).numpy()) # The generator has successfully learned how to simulate the real data # enough to fool the discriminator. # # Let's conclude by comparing the states of the real data circuit and the generator. We expect # the generator to have learned to be in a state that is very close to the one prepared in the # real data circuit. An easy way to access the state of the first qubit is through its # `Bloch sphere <https://en.wikipedia.org/wiki/Bloch_sphere>`__ representation: # # # + obs = [qml.PauliX(0), qml.PauliY(0), qml.PauliZ(0)] bloch_vector_real = qml.map(real, obs, dev, interface="tf") bloch_vector_generator = qml.map(generator, obs, dev, interface="tf") print("Real Bloch vector: {}".format(bloch_vector_real([phi, theta, omega]))) print("Generator Bloch vector: {}".format(bloch_vector_generator(gen_weights))) # - print(gen_weights) # + from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer w = gen_weights.numpy() q = QuantumRegister(3) c = ClassicalRegister(3) qc = QuantumCircuit(q, c) qc.h(q[0]) qc.rx(w[0], q[0]) qc.rx(w[1], q[1]) qc.rx(w[2], q[2]) qc.ry(w[3], q[0]) qc.ry(w[4], q[1]) qc.ry(w[5], q[2]) qc.rz(w[6], q[0]) qc.rz(w[7], q[1]) qc.rz(w[8], q[2]) qc.cx(q[0], q[1]) qc.cx(q[1], q[2]) qc.rx(w[9], q[0]) qc.ry(w[10], q[0]) qc.rz(w[11], q[0]) qc.rx(w[12], q[1]) qc.ry(w[13], q[1]) qc.rz(w[14], q[1]) # - job = execute(qc, backend=Aer.get_backend("statevector_simulator")) vec = job.result().get_statevector() for i in vec: print(i)
https://github.com/AmirhoseynpowAsghari/Qiskit-Tutorials
AmirhoseynpowAsghari
#DOI : https://doi.org/10.1143/JPSJ.12.570 import numpy as np import matplotlib.pyplot as plt from scipy.linalg import expm # Define Pauli matrices sigma_x = np.array([[0, 1], [1, 0]]) sigma_y = np.array([[0, -1j], [1j, 0]]) sigma_z = np.array([[1, 0], [0, -1]]) # System parameters omega_0 = 1.0 # Transition frequency Omega = 0.1 # Driving strength omega = 1.0 # Driving frequency hbar = 1.0 # Time array t = np.linspace(0, 50, 10000) dt = t[1] - t[0] # Initial density matrix (ground state) rho = np.array([[1, 0], [0, 0]], dtype=complex) # Hamiltonian matrices H0 = (hbar * omega_0 / 2) * sigma_z H_prime = lambda t: hbar * Omega * np.cos(omega * t) * sigma_x # Time evolution rho_t = np.zeros((len(t), 2, 2), dtype=complex) rho_t[0] = rho for i in range(1, len(t)): H = H0 + H_prime(t[i-1]) U = expm(-1j * H * dt / hbar) rho = U @ rho @ U.conj().T rho_t[i] = rho # Calculate expectation values of Pauli z-matrix expectation_z = [np.trace(rho @ sigma_z).real for rho in rho_t] # Plot the results plt.figure(figsize=(10, 6)) plt.plot(t, expectation_z, label=r'$\langle \sigma_z \rangle$') plt.xlabel('Time $t$') plt.ylabel(r'$\langle \sigma_z \rangle$') plt.title('Response of a Two-Level System to a Sinusoidal Driving Field') plt.legend() plt.grid() plt.show() import numpy as np import matplotlib.pyplot as plt from scipy.linalg import expm # Define Pauli matrices sigma_x = np.array([[0, 1], [1, 0]]) sigma_y = np.array([[0, -1j], [1j, 0]]) sigma_z = np.array([[1, 0], [0, -1]]) # System parameters omega_0 = 1.0 # Transition frequency Omega = 0.1 # Driving strength hbar = 1.0 # Time array t = np.linspace(0, 50, 10000) dt = t[1] - t[0] # Initial density matrix (ground state) rho = np.array([[1, 0], [0, 0]], dtype=complex) # Hamiltonian matrices H0 = (hbar * omega_0 / 2) * sigma_z H_prime = lambda t: hbar * Omega * (t >= 0) * sigma_x # Step function perturbation # Time evolution rho_t = np.zeros((len(t), 2, 2), dtype=complex) rho_t[0] = rho for i in range(1, len(t)): H = H0 + H_prime(t[i-1]) U = expm(-1j * H * dt / hbar) rho = U @ rho @ U.conj().T rho_t[i] = rho # Calculate expectation values of Pauli z-matrix expectation_z = [np.trace(rho @ sigma_z).real for rho in rho_t] # Plot the results plt.figure(figsize=(10, 6)) plt.plot(t, expectation_z, label=r'$\langle \sigma_z \rangle$') plt.xlabel('Time $t$') plt.ylabel(r'$\langle \sigma_z \rangle$') plt.title('Response of a Two-Level System to a Step Function Driving Field') plt.legend() plt.grid() plt.show()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_optimization import QuadraticProgram problem = QuadraticProgram("sample") problem.binary_var("x") problem.binary_var("y") problem.maximize(linear={"x": 1, "y": -2}) print(problem.prettyprint()) from qiskit.algorithms import NumPyMinimumEigensolver from qiskit_optimization.algorithms import MinimumEigenOptimizer mes = NumPyMinimumEigensolver() meo = MinimumEigenOptimizer(min_eigen_solver=mes) result = meo.solve(problem) print(result) from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver from qiskit_optimization.algorithms import MinimumEigenOptimizer mes = NumPyMinimumEigensolver() meo = MinimumEigenOptimizer(min_eigen_solver=mes) result = meo.solve(problem) print(result) from qiskit import BasicAer from qiskit.algorithms import QAOA from qiskit.algorithms.optimizers import COBYLA from qiskit.utils import QuantumInstance from qiskit_optimization.algorithms import MinimumEigenOptimizer backend = BasicAer.get_backend("qasm_simulator") shots = 1000 qins = QuantumInstance(backend=backend, shots=shots) mes = QAOA(optimizer=COBYLA(), quantum_instance=qins) meo = MinimumEigenOptimizer(min_eigen_solver=mes) result = meo.solve(problem) print(result) from qiskit.algorithms.minimum_eigensolvers import QAOA from qiskit.algorithms.optimizers import COBYLA from qiskit.primitives import Sampler from qiskit_optimization.algorithms import MinimumEigenOptimizer shots = 1000 mes = QAOA(sampler=Sampler(), optimizer=COBYLA()) meo = MinimumEigenOptimizer(min_eigen_solver=mes) result = meo.solve(problem) print(result) from qiskit import BasicAer from qiskit.algorithms import VQE from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import RealAmplitudes from qiskit.utils import QuantumInstance from qiskit_optimization.algorithms import MinimumEigenOptimizer backend = BasicAer.get_backend("qasm_simulator") shots = 1000 qins = QuantumInstance(backend=backend, shots=shots) mes = VQE(ansatz=RealAmplitudes(), optimizer=COBYLA(), quantum_instance=qins) meo = MinimumEigenOptimizer(min_eigen_solver=mes) result = meo.solve(problem) print(result) from qiskit.algorithms.minimum_eigensolvers import SamplingVQE from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import RealAmplitudes from qiskit.primitives import Sampler from qiskit_optimization.algorithms import MinimumEigenOptimizer mes = SamplingVQE(sampler=Sampler(), ansatz=RealAmplitudes(), optimizer=COBYLA()) meo = MinimumEigenOptimizer(min_eigen_solver=mes) result = meo.solve(problem) print(result) from qiskit.algorithms.minimum_eigensolvers import VQE from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import RealAmplitudes from qiskit.primitives import Estimator from qiskit_optimization.algorithms import MinimumEigenOptimizer mes = VQE(estimator=Estimator(), ansatz=RealAmplitudes(), optimizer=COBYLA()) try: meo = MinimumEigenOptimizer(min_eigen_solver=mes) except TypeError as ex: print(ex) from qiskit import BasicAer from qiskit.algorithms import QAOA from qiskit.algorithms.optimizers import COBYLA from qiskit.utils import QuantumInstance from qiskit_optimization.algorithms import WarmStartQAOAOptimizer, SlsqpOptimizer backend = BasicAer.get_backend("qasm_simulator") shots = 1000 qins = QuantumInstance(backend=backend, shots=shots) qaoa = QAOA(optimizer=COBYLA(), quantum_instance=qins) optimizer = WarmStartQAOAOptimizer( pre_solver=SlsqpOptimizer(), relax_for_pre_solver=True, qaoa=qaoa, epsilon=0.25 ) result = optimizer.solve(problem) print(result) from qiskit.algorithms.minimum_eigensolvers import QAOA from qiskit.algorithms.optimizers import COBYLA from qiskit.primitives import Sampler from qiskit_optimization.algorithms import WarmStartQAOAOptimizer, SlsqpOptimizer qaoa = QAOA(sampler=Sampler(), optimizer=COBYLA()) optimizer = WarmStartQAOAOptimizer( pre_solver=SlsqpOptimizer(), relax_for_pre_solver=True, qaoa=qaoa, epsilon=0.25 ) result = optimizer.solve(problem) print(result) from qiskit import BasicAer from qiskit.algorithms.optimizers import COBYLA from qiskit.utils import QuantumInstance from qiskit_optimization.algorithms import GroverOptimizer backend = BasicAer.get_backend("qasm_simulator") shots = 1000 qins = QuantumInstance(backend=backend, shots=shots) optimizer = GroverOptimizer(num_value_qubits=3, num_iterations=3, quantum_instance=qins) result = optimizer.solve(problem) print(result) from qiskit.algorithms.optimizers import COBYLA from qiskit.primitives import Sampler from qiskit_optimization.algorithms import GroverOptimizer optimizer = GroverOptimizer(num_value_qubits=3, num_iterations=3, sampler=Sampler()) result = optimizer.solve(problem) print(result) from qiskit import BasicAer from qiskit.algorithms.optimizers import COBYLA from qiskit.utils import QuantumInstance from qiskit.primitives import Sampler from qiskit_optimization.algorithms import GroverOptimizer backend = BasicAer.get_backend("qasm_simulator") shots = 1000 qins = QuantumInstance(backend=backend, shots=shots) try: optimizer = GroverOptimizer( num_value_qubits=3, num_iterations=3, quantum_instance=qins, sampler=Sampler() ) # raises an error because both quantum_instance and sampler are set. except ValueError as ex: print(ex) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) ### added y gate ### qc.cx(0, 1) qc.cx(1, 0) return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).issubset({0,1}): raise ValueError(f"message '{msg}' is invalid") if msg[1] == "1": qc.x(qubit) if msg[0] == "1": qc.z(qubit) return qc def decode_message(qc): qc.cx(1, 0) qc.h(1) ### added h gate ### qc.h(0) return qc
https://github.com/jvscursulim/qamp_fall22_project
jvscursulim
import numpy as np import matplotlib.pyplot as plt import torch import torch.nn.functional as F from torch import Tensor, cat, no_grad, manual_seed from torch.nn import Linear, CrossEntropyLoss, MSELoss from torch.nn import Module, Conv2d, Linear, Dropout2d, NLLLoss, MaxPool2d, Flatten, Sequential, ReLU from torch.optim import Adam, LBFGS from torch.utils.data import DataLoader from torchvision import datasets, transforms from qiskit.circuit import QuantumCircuit, Parameter from qiskit.circuit.library import RealAmplitudes, ZZFeatureMap from qiskit.utils import QuantumInstance, algorithm_globals from qiskit.opflow import AerPauliExpectation from qiskit_aer import Aer from qiskit_machine_learning.neural_networks import CircuitQNN, TwoLayerQNN from qiskit_machine_learning.connectors import TorchConnector algorithm_globals.random_seed = 42 qi = QuantumInstance(backend=Aer.get_backend("statevector_simulator")) device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") num_inputs = 2 num_samples = 20 X = 2 * algorithm_globals.random.random([num_samples, num_inputs]) - 1 y01 = 1 * (np.sum(X, axis=1) >= 0) y = 2 * y01 - 1 X_ = Tensor(X) y01_ = Tensor(y01).reshape(len(y)).long() y_ = Tensor(y).reshape(len(y), 1) for x, y_target in zip(X, y): if y_target == 1: plt.plot(x[0], x[1], "bo") else: plt.plot(x[0], x[1], "go") plt.plot([-1,1], [1,-1], "--", color="black") plt.show() qnn1 = TwoLayerQNN(num_qubits=num_inputs, quantum_instance=qi) print(qnn1.operator) initial_weights = 0.1 * (2 * algorithm_globals.random.random(qnn1.num_weights) - 1) model1 = TorchConnector(qnn1, initial_weights=initial_weights) print(f"Initial weights: {initial_weights}") model1(X_[0, :]) optimizer = LBFGS(model1.parameters()) f_loss = MSELoss(reduction="sum") model1.train() def closure(): optimizer.zero_grad() loss = f_loss(model1(X_), y_) loss.backward() print(loss.item()) return loss optimizer.step(closure) y_predict = [] for x, y_target in zip(X, y): output = model1(Tensor(x)) y_predict += [np.sign(output.detach().numpy())[0]] print(f"Accuracy: {sum(y_predict == y)/len(y)}") for x, y_target, y_p in zip(X, y, y_predict): if y_target == 1: plt.plot(x[0], x[1], "bo") else: plt.plot(x[0], x[1], "go") if y_target != y_p: plt.scatter(x[0], x[1], s=200, facecolors="none", edgecolors="r", linewidths=2) plt.plot([-1, 1], [1, -1], "--", color="black") plt.show() feature_map = ZZFeatureMap(num_inputs) ansatz = RealAmplitudes(num_qubits=num_inputs, entanglement="linear", reps=1) qc = QuantumCircuit(num_inputs) qc.append(feature_map, range(num_inputs)) qc.append(ansatz, range(num_inputs)) parity = lambda x: "{:b}".format(x).count("1") % 2 output_shape = 2 qnn2 = CircuitQNN(qc, input_params=feature_map.parameters, weight_params=ansatz.parameters, interpret=parity, output_shape=output_shape, quantum_instance=qi) initial_weights = 0.1 * (2 * algorithm_globals.random.random(qnn2.num_weights) - 1) print(f"Initial weights: {initial_weights}") model2 = TorchConnector(qnn2, initial_weights=initial_weights) optimizer = LBFGS(model2.parameters()) f_loss = CrossEntropyLoss() model2.train() def closure(): optimizer.zero_grad(set_to_none=True) loss = f_loss(model2(X_), y01_) loss.backward() print(loss.item()) return loss optimizer.step(closure) num_samples = 20 eps = 0.2 lb, ub = -np.pi, np.pi f = lambda x: np.sin(x) X = (ub - lb) * algorithm_globals.random.random([num_samples, 1]) + lb y = f(X) + eps * (2 * algorithm_globals.random.random([num_samples, 1]) - 1) plt.plot(np.linspace(lb, ub), f(np.linspace(lb, ub)), "r--") plt.plot(X, y, "bo") plt.show() param_x = Parameter("x") feature_map = QuantumCircuit(1, name="fm") feature_map.ry(param_x, 0) param_y = Parameter("y") ansatz = QuantumCircuit(1, name="vf") ansatz.ry(param_y, 0) qnn3 = TwoLayerQNN(1, feature_map=feature_map, ansatz=ansatz, quantum_instance=qi) print(qnn3.operator) initial_weights = 0.1 * (2 * algorithm_globals.random.random(qnn3.num_weights) - 1) model3 = TorchConnector(qnn3, initial_weights=initial_weights) optimizer = LBFGS(model3.parameters()) f_loss = MSELoss(reduction="sum") model3.train() def closure(): optimizer.zero_grad(set_to_none=True) loss = f_loss(model3(Tensor(X)), Tensor(y)) loss.backward() print(loss.item()) return loss optimizer.step(closure) plt.plot(np.linspace(lb, ub), f(np.linspace(lb, ub)), "r--") plt.plot(X, y, "bo") y_ = [] for x in np.linspace(lb, ub): output = model3(Tensor([x])) y_ += [output.detach().numpy()[0]] plt.plot(np.linspace(lb, ub), y_, "g-") plt.show() manual_seed(42) batch_size = 1 n_samples = 100 X_train = datasets.MNIST(root="./data", train=True, download=True, transform=transforms.Compose([transforms.ToTensor()])) idx = np.append(np.where(X_train.targets == 0)[0][:n_samples], np.where(X_train.targets == 1)[0][:n_samples]) X_train.data = X_train.data[idx] X_train.targets = X_train.targets[idx] train_loader = DataLoader(X_train, batch_size=batch_size, shuffle=True) n_samples_show = 6 data_iter = iter(train_loader) fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10,3)) while n_samples_show > 0: images, targets = data_iter.__next__() axes[n_samples_show - 1].imshow(images[0, 0].numpy().squeeze(), cmap="gray") axes[n_samples_show - 1].set_xticks([]) axes[n_samples_show - 1].set_yticks([]) axes[n_samples_show - 1].set_title(f"Labeled: {targets[0].item()}") n_samples_show -= 1 n_samples = 50 X_test = datasets.MNIST(root="./data", train=False, download=True, transform=transforms.Compose([transforms.ToTensor()])) idx = np.append(np.where(X_test.targets == 0)[0][:n_samples], np.where(X_test.targets == 1)[0][:n_samples]) X_test.data = X_test.data[idx] X_test.targets = X_test.targets[idx] test_loader = DataLoader(X_test, batch_size=batch_size, shuffle=True) def create_qnn(): feature_map = ZZFeatureMap(2) ansatz = RealAmplitudes(2, reps=1) qnn = TwoLayerQNN(2, feature_map, ansatz, input_gradients=True, exp_val=AerPauliExpectation(), quantum_instance=qi ) return qnn qnn4 = create_qnn() print(qnn4.operator) class Net(Module): def __init__(self, qnn) -> None: super().__init__() self.conv1 = Conv2d(1,2, kernel_size=5) self.conv2 = Conv2d(2,16, kernel_size=5) self.dropout = Dropout2d() self.fc1 = Linear(256, 64) self.fc2 = Linear(64, 2) self.qnn = TorchConnector(qnn) self.fc3 = Linear(1, 1) def forward(self, x): x = F.relu(self.conv1(x)) x = F.max_pool2d(x, 2) x = F.relu(self.conv2(x)) x = F.max_pool2d(x ,2) x = self.dropout(x) x = x.view(x.shape[0], -1) x = F.relu(self.fc1(x)) x = self.fc2(x) x = self.qnn(x) x = self.fc3(x) return cat((x, 1 - x), -1) model4 = Net(qnn4) # Define model, optimizer, and loss function optimizer = Adam(model4.parameters(), lr=0.001) loss_func = NLLLoss() # Start training epochs = 10 # Set number of epochs loss_list = [] # Store loss history model4.train() # Set model to training mode for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad(set_to_none=True) # Initialize gradient output = model4(data) # Forward pass loss = loss_func(output, target) # Calculate loss loss.backward() # Backward pass optimizer.step() # Optimize weights total_loss.append(loss.item()) # Store loss loss_list.append(sum(total_loss) / len(total_loss)) print("Training [{:.0f}%]\tLoss: {:.4f}".format(100.0 * (epoch + 1) / epochs, loss_list[-1])) # Plot loss convergence plt.plot(loss_list) plt.title("Hybrid NN Training Convergence") plt.xlabel("Training Iterations") plt.ylabel("Neg. Log Likelihood Loss") plt.show() torch.save(model4.state_dict(), "model4.pt") qnn5 = create_qnn() model5 = Net(qnn5) model5.load_state_dict(torch.load("model4.pt")) model5.eval() # set model to evaluation mode with no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model5(data) if len(output.shape) == 1: output = output.reshape(1, *output.shape) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print( "Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%".format( sum(total_loss) / len(total_loss), correct / len(test_loader) / batch_size * 100 ) ) n_samples_show = 6 count = 0 fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3)) model5.eval() with no_grad(): for batch_idx, (data, target) in enumerate(test_loader): if count == n_samples_show: break output = model5(data[0:1]) if len(output.shape) == 1: output = output.reshape(1, *output.shape) pred = output.argmax(dim=1, keepdim=True) axes[count].imshow(data[0].numpy().squeeze(), cmap="gray") axes[count].set_xticks([]) axes[count].set_yticks([]) axes[count].set_title("Predicted {}".format(pred.item())) count += 1
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile from qiskit.visualization import plot_circuit_layout from qiskit.providers.fake_provider import FakeVigo backend = FakeVigo() ghz = QuantumCircuit(3, 3) ghz.h(0) ghz.cx(0,range(1,3)) ghz.barrier() ghz.measure(range(3), range(3)) ghz.draw(output='mpl')
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
MonitSharma
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() import numpy as np; pi = np.pi from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram from copy import deepcopy as make_copy def prepare_hets_circuit(depth, angle1, angle2): hets_circ = QuantumCircuit(depth) hets_circ.ry(angle1, 0) hets_circ.rz(angle1, 0) hets_circ.ry(angle1, 1) hets_circ.rz(angle1, 1) for ii in range(depth): hets_circ.cx(0,1) hets_circ.ry(angle2,0) hets_circ.rz(angle2,0) hets_circ.ry(angle2,1) hets_circ.rz(angle2,1) return hets_circ hets_circuit = prepare_hets_circuit(2, pi/2, pi/2) hets_circuit.draw() def measure_zz_circuit(given_circuit): zz_meas = make_copy(given_circuit) zz_meas.measure_all() return zz_meas zz_meas = measure_zz_circuit(hets_circuit) zz_meas.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(zz_meas, backend = simulator, shots=10000).result() counts = result.get_counts(zz_meas) plot_histogram(counts) def measure_zz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zz = counts['00'] + counts['11'] - counts['01'] - counts['10'] zz = zz / total_counts return zz zz = measure_zz(hets_circuit) print("<ZZ> =", str(zz)) def measure_zi(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zi = counts['00'] - counts['11'] + counts['01'] - counts['10'] zi = zi / total_counts return zi def measure_iz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] iz = counts['00'] - counts['11'] - counts['01'] + counts['10'] iz = iz / total_counts return iz zi = measure_zi(hets_circuit) print("<ZI> =", str(zi)) iz = measure_iz(hets_circuit) print("<IZ> =", str(iz)) def measure_xx_circuit(given_circuit): xx_meas = make_copy(given_circuit) ### WRITE YOUR CODE BETWEEN THESE LINES - START xx_meas.h(0) xx_meas.h(1) xx_meas.measure_all() ### WRITE YOUR CODE BETWEEN THESE LINES - END return xx_meas xx_meas = measure_xx_circuit(hets_circuit) xx_meas.draw() def measure_xx(given_circuit, num_shots = 10000): xx_meas = measure_xx_circuit(given_circuit) result = execute(xx_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(xx_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] xx = counts['00'] + counts['11'] - counts['01'] - counts['10'] xx = xx / total_counts return xx xx = measure_xx(hets_circuit) print("<XX> =", str(xx)) def get_energy(given_circuit, num_shots = 10000): zz = measure_zz(given_circuit, num_shots = num_shots) iz = measure_iz(given_circuit, num_shots = num_shots) zi = measure_zi(given_circuit, num_shots = num_shots) xx = measure_xx(given_circuit, num_shots = num_shots) energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx return energy energy = get_energy(hets_circuit) print("The energy of the trial state is", str(energy)) hets_circuit_plus = None hets_circuit_minus = None ### WRITE YOUR CODE BETWEEN THESE LINES - START hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2) hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2) ### WRITE YOUR CODE BETWEEN THESE LINES - END energy_plus = get_energy(hets_circuit_plus, num_shots=100000) energy_minus = get_energy(hets_circuit_minus, num_shots=100000) print(energy_plus, energy_minus) name = 'Pon Rahul M' email = 'ponrahul.21it@licet.ac.in' ### Do not change the lines below from grading_tools import grade grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1') grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2') grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3') energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0 energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0 ### WRITE YOUR CODE BETWEEN THESE LINES - START energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100) energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100) energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000) energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000) energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000) energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000) ### WRITE YOUR CODE BETWEEN THESE LINES - END print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100) print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000) print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000) ### WRITE YOUR CODE BETWEEN THESE LINES - START I = np.array([ [1, 0], [0, 1] ]) X = np.array([ [0, 1], [1, 0] ]) Z = np.array([ [1, 0], [0, -1] ]) h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \ (0.39793742) * np.kron(I, Z) + \ (-0.3979374) * np.kron(Z, I) + \ (-0.0112801) * np.kron(Z, Z) + \ (0.18093119) * np.kron(X, X) from numpy import linalg as LA eigenvalues, eigenvectors = LA.eig(h2_hamiltonian) for ii, eigenvalue in enumerate(eigenvalues): print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}") exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)] exact_eigenvalue = np.min(eigenvalues) print() print("Minimum energy is", exact_eigenvalue) ### WRITE YOUR CODE BETWEEN THESE LINES - END
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import * qc = QuantumCircuit(2) qc.h(i) qc.crz (PI/4, 0, 1)
https://github.com/minnukota381/Quantum-Computing-Qiskit
minnukota381
from qiskit import * from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram # Create a quantum circuit with a single qubit # The default initial state of qubit will be |0> or [1,0] qc = QuantumCircuit(1,1) #Apply the Pauli X-gate on the qubit to make the input as |1> #qc.x(0) #Apply the hadamard gate on the qubit qc.h(0) #try to measure the qbit qc.measure(0,0) #Draw the circuit # qc.draw() qc.draw('mpl') #Get the backend for the circuit (simulator or realtime system) backend = Aer.get_backend('statevector_simulator') #execute the circuit using the backend out = execute(qc,backend).result().get_statevector() #plot the result as a bloch sphere visualization plot_bloch_multivector(out) # visualize the output as an animation #visualize_transition(qc) #execute the circuit and get the plain result out = execute(qc,backend).result() #getting the count of the result counts = out.get_counts() #plotting the histogram plot_histogram(counts)
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
# # your solution is here # # let's start with a zero matrix A = [ [0,0,0], [0,0,0], [0,0,0] ] # we will randomly pick the entries and then make normalization for each column # it will be easier to iteratively construct the columns # you may notice that each column is a probabilistic state from random import randrange normalization_factor = [0,0,0] # the normalization factor of each column may be different for j in range(3): # each column is iteratively constructed normalization_factor[j] = 0 while normalization_factor[j]==0: # the normalization factor cannot be zero for i in range(3): A[i][j] = randrange(101) # pick a random value between 0 and 100 normalization_factor[j] += A[i][j] # let's print matrix A before the normalization # the entries are between 0 and 100 print("matrix A before normalization:") for i in range(3): print(A[i]) # let's normalize each column for j in range(3): for i in range(3): A[i][j] /= normalization_factor[j] # shorter form of A[i][j] = A[i][j] / normalization_factor[j] # let's print matrix A after the normalization print() # print an empty line print("matrix A after normalization:") for i in range(3): print(A[i]) print() print("the column summations must be 1") sum = [0,0,0] for j in range(3): for i in range(3): sum[j] += A[i][j] print(sum) # operator B B = [ [0.4,0.6,0], [0.2,0.1,0.7], [0.4,0.3,0.3] ] # the current state v = [0.1,0.3,0.6] # # your solution is here # # operator B B = [ [0.4,0.6,0], [0.2,0.1,0.7], [0.4,0.3,0.3] ] # the current state v = [0.1,0.3,0.6] newstate = [] index = 0 for row in B: newstate.append(0) for i in range(len(row)): newstate[index] = newstate[index] + row[i] * v[i] index = index + 1 print(newstate) # %%writefile linear_evolve.py def linear_evolve(operator,state): newstate=[] for i in range(len(operator)): # for each row # we calculate the corresponding entry of the new state newstate.append(0) # we set this value to 0 for the initialization for j in range(len(state)): # for each element in state newstate[i] = newstate[i] + operator[i][j] * state[j] # summation of pairwise multiplications return newstate # return the new probabilistic state # test the function # operator for the test B = [ [0.4,0.6,0], [0.2,0.1,0.7], [0.4,0.3,0.3] ] # state for test v = [0.1,0.3,0.6] newstate = linear_evolve(B,v) print(newstate) for step in [5,10,20,40]: new_state = [0.1,0.3,0.6] # initial state for i in range(step): new_state = linear_evolve(B,new_state) print(new_state) # change the initial state for step in [5,10,20,40]: new_state = [1,0,0] # initial state for i in range(step): new_state = linear_evolve(B,new_state) print(new_state)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit import QuantumCircuit # Create a Quantum Circuit acting on a quantum register of three qubits circ = QuantumCircuit(3) # Add a H gate on qubit 0, putting this qubit in superposition. circ.h(0) # Add a CX (CNOT) gate on control qubit 0 and target qubit 1, putting # the qubits in a Bell state. circ.cx(0, 1) # Add a CX (CNOT) gate on control qubit 0 and target qubit 2, putting # the qubits in a GHZ state. circ.cx(0, 2) circ.draw('mpl') from qiskit.quantum_info import Statevector # Set the intial state of the simulator to the ground state using from_int state = Statevector.from_int(0, 2**3) # Evolve the state by the quantum circuit state = state.evolve(circ) #draw using latex state.draw('latex') from qiskit.visualization import array_to_latex #Alternative way of representing in latex array_to_latex(state) state.draw('qsphere') state.draw('hinton') from qiskit.quantum_info import Operator U = Operator(circ) # Show the results U.data # Create a Quantum Circuit meas = QuantumCircuit(3, 3) meas.barrier(range(3)) # map the quantum measurement to the classical bits meas.measure(range(3), range(3)) # The Qiskit circuit object supports composition. # Here the meas has to be first and front=True (putting it before) # as compose must put a smaller circuit into a larger one. qc = meas.compose(circ, range(3), front=True) #drawing the circuit qc.draw('mpl') # Adding the transpiler to reduce the circuit to QASM instructions # supported by the backend from qiskit import transpile # Use AerSimulator from qiskit_aer import AerSimulator backend = AerSimulator() # First we have to transpile the quantum circuit # to the low-level QASM instructions used by the # backend qc_compiled = transpile(qc, backend) # Execute the circuit on the qasm simulator. # We've set the number of repeats of the circuit # to be 1024, which is the default. job_sim = backend.run(qc_compiled, shots=1024) # Grab the results from the job. result_sim = job_sim.result() counts = result_sim.get_counts(qc_compiled) print(counts) from qiskit.visualization import plot_histogram plot_histogram(counts) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np import copy # Problem modelling imports from docplex.mp.model import Model # Qiskit imports from qiskit.algorithms.minimum_eigensolvers import QAOA, NumPyMinimumEigensolver from qiskit.algorithms.optimizers import COBYLA from qiskit.primitives import Sampler from qiskit.utils.algorithm_globals import algorithm_globals from qiskit_optimization.algorithms import MinimumEigenOptimizer, CplexOptimizer from qiskit_optimization import QuadraticProgram from qiskit_optimization.problems.variable import VarType from qiskit_optimization.converters.quadratic_program_to_qubo import QuadraticProgramToQubo from qiskit_optimization.translators import from_docplex_mp def create_problem(mu: np.array, sigma: np.array, total: int = 3) -> QuadraticProgram: """Solve the quadratic program using docplex.""" mdl = Model() x = [mdl.binary_var("x%s" % i) for i in range(len(sigma))] objective = mdl.sum([mu[i] * x[i] for i in range(len(mu))]) objective -= 2 * mdl.sum( [sigma[i, j] * x[i] * x[j] for i in range(len(mu)) for j in range(len(mu))] ) mdl.maximize(objective) cost = mdl.sum(x) mdl.add_constraint(cost == total) qp = from_docplex_mp(mdl) return qp def relax_problem(problem) -> QuadraticProgram: """Change all variables to continuous.""" relaxed_problem = copy.deepcopy(problem) for variable in relaxed_problem.variables: variable.vartype = VarType.CONTINUOUS return relaxed_problem mu = np.array([3.418, 2.0913, 6.2415, 4.4436, 10.892, 3.4051]) sigma = np.array( [ [1.07978412, 0.00768914, 0.11227606, -0.06842969, -0.01016793, -0.00839765], [0.00768914, 0.10922887, -0.03043424, -0.0020045, 0.00670929, 0.0147937], [0.11227606, -0.03043424, 0.985353, 0.02307313, -0.05249785, 0.00904119], [-0.06842969, -0.0020045, 0.02307313, 0.6043817, 0.03740115, -0.00945322], [-0.01016793, 0.00670929, -0.05249785, 0.03740115, 0.79839634, 0.07616951], [-0.00839765, 0.0147937, 0.00904119, -0.00945322, 0.07616951, 1.08464544], ] ) qubo = create_problem(mu, sigma) print(qubo.prettyprint()) result = CplexOptimizer().solve(qubo) print(result.prettyprint()) qp = relax_problem(QuadraticProgramToQubo().convert(qubo)) print(qp.prettyprint()) sol = CplexOptimizer().solve(qp) print(sol.prettyprint()) c_stars = sol.samples[0].x print(c_stars) algorithm_globals.random_seed = 12345 qaoa_mes = QAOA(sampler=Sampler(), optimizer=COBYLA(), initial_point=[0.0, 1.0]) exact_mes = NumPyMinimumEigensolver() qaoa = MinimumEigenOptimizer(qaoa_mes) qaoa_result = qaoa.solve(qubo) print(qaoa_result.prettyprint()) from qiskit import QuantumCircuit thetas = [2 * np.arcsin(np.sqrt(c_star)) for c_star in c_stars] init_qc = QuantumCircuit(len(sigma)) for idx, theta in enumerate(thetas): init_qc.ry(theta, idx) init_qc.draw(output="mpl") from qiskit.circuit import Parameter beta = Parameter("Ξ²") ws_mixer = QuantumCircuit(len(sigma)) for idx, theta in enumerate(thetas): ws_mixer.ry(-theta, idx) ws_mixer.rz(-2 * beta, idx) ws_mixer.ry(theta, idx) ws_mixer.draw(output="mpl") ws_qaoa_mes = QAOA( sampler=Sampler(), optimizer=COBYLA(), initial_state=init_qc, mixer=ws_mixer, initial_point=[0.0, 1.0], ) ws_qaoa = MinimumEigenOptimizer(ws_qaoa_mes) ws_qaoa_result = ws_qaoa.solve(qubo) print(ws_qaoa_result.prettyprint()) def format_qaoa_samples(samples, max_len: int = 10): qaoa_res = [] for s in samples: if sum(s.x) == 3: qaoa_res.append(("".join([str(int(_)) for _ in s.x]), s.fval, s.probability)) res = sorted(qaoa_res, key=lambda x: -x[1])[0:max_len] return [(_[0] + f": value: {_[1]:.3f}, probability: {1e2*_[2]:.1f}%") for _ in res] format_qaoa_samples(qaoa_result.samples) format_qaoa_samples(ws_qaoa_result.samples) from qiskit_optimization.algorithms import WarmStartQAOAOptimizer qaoa_mes = QAOA(sampler=Sampler(), optimizer=COBYLA(), initial_point=[0.0, 1.0]) ws_qaoa = WarmStartQAOAOptimizer( pre_solver=CplexOptimizer(), relax_for_pre_solver=True, qaoa=qaoa_mes, epsilon=0.0 ) ws_result = ws_qaoa.solve(qubo) print(ws_result.prettyprint()) format_qaoa_samples(ws_result.samples) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/arthurfaria/Qiskit_certificate_prep
arthurfaria
import numpy as np from qiskit import QuantumCircuit, Aer, IBMQ, assemble, execute, QuantumRegister, ClassicalRegister from qiskit.quantum_info import Statevector from qiskit.visualization import plot_histogram, plot_bloch_multivector # Loading your IBM Quantum account(s) provider = IBMQ.load_account() qc = QuantumCircuit(1) qc.x(0) state = Statevector.from_instruction(qc) plot_bloch_multivector(state) qc = QuantumCircuit(1) qc.h(0) state = Statevector.from_instruction(qc) plot_bloch_multivector(state) qc = QuantumCircuit(1) qc.x(0) qc.h(0) state = Statevector.from_instruction(qc) plot_bloch_multivector(state) qcX = QuantumCircuit(1) qcX.u(np.pi, 0, np.pi, 0) qcX.draw('mpl') qcZ = QuantumCircuit(1) qcZ.u(0, 0, np.pi, 0) qcZ.draw('mpl') qcY = QuantumCircuit(1) qcY.u(np.pi, np.pi/2, np.pi/2, 0) qcY.draw('mpl') qcH = QuantumCircuit(1) qcH.u(np.pi/2, 0, np.pi, 0) qcH.draw('mpl') n_qubits = 1 #number of qubits n_bits = 1 #number of bits q = QuantumRegister(n_qubits, 'qbit' ) c = ClassicalRegister(n_bits, 'cbit' ) qc = QuantumCircuit(q,c) qc.u(np.pi/4,np.pi/4,np.pi/4, q[0]) #or just 0 qc.measure(0,0) qc.draw('mpl') # we choose the simulator as our backend backend = Aer.get_backend('qasm_simulator') # we run the simulation and get the counts Counts = execute(qc, backend, shots = 1024, seed_simulator=312).result().get_counts() # let us plot a histogram to see the possible outcomes and corresponding probabilities plot_histogram(Counts) qc=QuantumCircuit(2,2) qc.cx(0,1) qc.draw('mpl') qc=QuantumCircuit(2,2) qc.x(0) qc.cx(0,1) qc.draw('mpl') qc = QuantumCircuit(2,2) qc.h(0) qc.cx(0,1) for i in range(2): qc.measure(i,i) qc.draw('mpl') # we run the simulation and get the counts # this will be better exaplained in the notebook 'qasm_simulator_and_visualization.ipynb' counts = execute(qc, backend, shots = 1024).result().get_counts() #plot histogram plot_histogram(counts) qc = QuantumCircuit(2,2) qc.h(0) qc.x(1) qc.z(0) qc.cx(0,1) for i in range(2): qc.measure(i,i) qc.draw('mpl') counts = execute(qc, backend, shots = 1024).result().get_counts() plot_histogram(counts)
https://github.com/urwin419/QiskitChecker
urwin419
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) qc.cx(1, 0) return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).issubset({0,1}): raise ValueError(f"message '{msg}' is invalid") if msg[1] == "1": ### replaced x gate ### qc.z(qubit) if msg[0] == "1": ### replaced z gate ### qc.x(qubit) return qc def decode_message(qc): qc.cx(1, 0) qc.h(1) return qc
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020, 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. """CircuitOp Class""" from typing import Dict, List, Optional, Set, Union, cast import numpy as np import qiskit from qiskit import QuantumCircuit from qiskit.circuit import Instruction, ParameterExpression from qiskit.circuit.library import IGate from qiskit.opflow.list_ops.tensored_op import TensoredOp from qiskit.opflow.operator_base import OperatorBase from qiskit.opflow.primitive_ops.primitive_op import PrimitiveOp from qiskit.quantum_info import Statevector from qiskit.utils.deprecation import deprecate_func class CircuitOp(PrimitiveOp): """Deprecated: Class for Operators backed by Terra's ``QuantumCircuit`` module.""" primitive: QuantumCircuit @deprecate_func( since="0.24.0", additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, primitive: Union[Instruction, QuantumCircuit], coeff: Union[complex, ParameterExpression] = 1.0, ) -> None: """ Args: primitive: The QuantumCircuit which defines the behavior of the underlying function. coeff: A coefficient multiplying the primitive Raises: TypeError: Unsupported primitive, or primitive has ClassicalRegisters. """ if isinstance(primitive, Instruction): qc = QuantumCircuit(primitive.num_qubits) qc.append(primitive, qargs=range(primitive.num_qubits)) primitive = qc if not isinstance(primitive, QuantumCircuit): raise TypeError( "CircuitOp can only be instantiated with " "QuantumCircuit, not {}".format(type(primitive)) ) if len(primitive.clbits) != 0: raise TypeError("CircuitOp does not support QuantumCircuits with ClassicalRegisters.") super().__init__(primitive, coeff) self._coeff = coeff def primitive_strings(self) -> Set[str]: return {"QuantumCircuit"} @property def num_qubits(self) -> int: return self.primitive.num_qubits def add(self, other: OperatorBase) -> OperatorBase: if not self.num_qubits == other.num_qubits: raise ValueError( "Sum over operators with different numbers of qubits, {} and {}, is not well " "defined".format(self.num_qubits, other.num_qubits) ) if isinstance(other, CircuitOp) and self.primitive == other.primitive: return CircuitOp(self.primitive, coeff=self.coeff + other.coeff) # Covers all else. # pylint: disable=cyclic-import from ..list_ops.summed_op import SummedOp return SummedOp([self, other]) def adjoint(self) -> "CircuitOp": return CircuitOp(self.primitive.inverse(), coeff=self.coeff.conjugate()) def equals(self, other: OperatorBase) -> bool: if not isinstance(other, CircuitOp) or not self.coeff == other.coeff: return False return self.primitive == other.primitive def tensor(self, other: OperatorBase) -> Union["CircuitOp", TensoredOp]: # pylint: disable=cyclic-import from .pauli_op import PauliOp from .matrix_op import MatrixOp if isinstance(other, (PauliOp, CircuitOp, MatrixOp)): other = other.to_circuit_op() if isinstance(other, CircuitOp): new_qc = QuantumCircuit(self.num_qubits + other.num_qubits) # NOTE!!! REVERSING QISKIT ENDIANNESS HERE new_qc.append( other.to_instruction(), qargs=new_qc.qubits[0 : other.primitive.num_qubits] ) new_qc.append(self.to_instruction(), qargs=new_qc.qubits[other.primitive.num_qubits :]) new_qc = new_qc.decompose() return CircuitOp(new_qc, coeff=self.coeff * other.coeff) return TensoredOp([self, other]) def compose( self, other: OperatorBase, permutation: Optional[List[int]] = None, front: bool = False ) -> OperatorBase: new_self, other = self._expand_shorter_operator_and_permute(other, permutation) new_self = cast(CircuitOp, new_self) if front: return other.compose(new_self) # pylint: disable=cyclic-import from ..operator_globals import Zero from ..state_fns import CircuitStateFn from .pauli_op import PauliOp from .matrix_op import MatrixOp if other == Zero ^ new_self.num_qubits: return CircuitStateFn(new_self.primitive, coeff=new_self.coeff) if isinstance(other, (PauliOp, CircuitOp, MatrixOp)): other = other.to_circuit_op() if isinstance(other, (CircuitOp, CircuitStateFn)): new_qc = other.primitive.compose(new_self.primitive) if isinstance(other, CircuitStateFn): return CircuitStateFn( new_qc, is_measurement=other.is_measurement, coeff=new_self.coeff * other.coeff ) else: return CircuitOp(new_qc, coeff=new_self.coeff * other.coeff) return super(CircuitOp, new_self).compose(other) def to_matrix(self, massive: bool = False) -> np.ndarray: OperatorBase._check_massive("to_matrix", True, self.num_qubits, massive) unitary = qiskit.quantum_info.Operator(self.to_circuit()).data return unitary * self.coeff def __str__(self) -> str: qc = self.to_circuit() prim_str = str(qc.draw(output="text")) if self.coeff == 1.0: return prim_str else: return f"{self.coeff} * {prim_str}" def assign_parameters(self, param_dict: dict) -> OperatorBase: param_value = self.coeff qc = self.primitive if isinstance(self.coeff, ParameterExpression) or self.primitive.parameters: unrolled_dict = self._unroll_param_dict(param_dict) if isinstance(unrolled_dict, list): from ..list_ops.list_op import ListOp return ListOp([self.assign_parameters(param_dict) for param_dict in unrolled_dict]) if isinstance(self.coeff, ParameterExpression) and self.coeff.parameters <= set( unrolled_dict.keys() ): param_instersection = set(unrolled_dict.keys()) & self.coeff.parameters binds = {param: unrolled_dict[param] for param in param_instersection} param_value = float(self.coeff.bind(binds)) # & is set intersection, check if any parameters in unrolled are present in circuit # This is different from bind_parameters in Terra because they check for set equality if set(unrolled_dict.keys()) & self.primitive.parameters: # Only bind the params found in the circuit param_instersection = set(unrolled_dict.keys()) & self.primitive.parameters binds = {param: unrolled_dict[param] for param in param_instersection} qc = self.to_circuit().assign_parameters(binds) return self.__class__(qc, coeff=param_value) def eval( self, front: Optional[ Union[str, Dict[str, complex], np.ndarray, OperatorBase, Statevector] ] = None, ) -> Union[OperatorBase, complex]: from ..state_fns import CircuitStateFn from ..list_ops import ListOp from .pauli_op import PauliOp from .matrix_op import MatrixOp if isinstance(front, ListOp) and front.distributive: return front.combo_fn( [self.eval(front.coeff * front_elem) for front_elem in front.oplist] ) # Composable with circuit if isinstance(front, (PauliOp, CircuitOp, MatrixOp, CircuitStateFn)): return self.compose(front) return self.to_matrix_op().eval(front) def to_circuit(self) -> QuantumCircuit: return self.primitive def to_circuit_op(self) -> "CircuitOp": return self def to_instruction(self) -> Instruction: return self.primitive.to_instruction() # Warning - modifying immutable object!! def reduce(self) -> OperatorBase: if self.primitive.data is not None: # Need to do this from the end because we're deleting items! for i in reversed(range(len(self.primitive.data))): gate = self.primitive.data[i].operation # Check if Identity or empty instruction (need to check that type is exactly # Instruction because some gates have lazy gate.definition population) # pylint: disable=unidiomatic-typecheck if isinstance(gate, IGate) or ( type(gate) == Instruction and gate.definition.data == [] ): del self.primitive.data[i] return self def _expand_dim(self, num_qubits: int) -> "CircuitOp": return self.permute(list(range(num_qubits, num_qubits + self.num_qubits))) def permute(self, permutation: List[int]) -> "CircuitOp": r""" Permute the qubits of the circuit. Args: permutation: A list defining where each qubit should be permuted. The qubit at index j of the circuit should be permuted to position permutation[j]. Returns: A new CircuitOp containing the permuted circuit. """ new_qc = QuantumCircuit(max(permutation) + 1).compose(self.primitive, qubits=permutation) return CircuitOp(new_qc, coeff=self.coeff)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020, 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. """MatrixOp Class""" from typing import Dict, List, Optional, Set, Union, cast, get_type_hints import numpy as np from scipy.sparse import spmatrix from qiskit import QuantumCircuit from qiskit.circuit import Instruction, ParameterExpression from qiskit.extensions.hamiltonian_gate import HamiltonianGate from qiskit.opflow.exceptions import OpflowError from qiskit.opflow.list_ops.summed_op import SummedOp from qiskit.opflow.list_ops.tensored_op import TensoredOp from qiskit.opflow.operator_base import OperatorBase from qiskit.opflow.primitive_ops.circuit_op import CircuitOp from qiskit.opflow.primitive_ops.primitive_op import PrimitiveOp from qiskit.quantum_info import Operator, Statevector from qiskit.utils import arithmetic from qiskit.utils.deprecation import deprecate_func class MatrixOp(PrimitiveOp): """Deprecated: Class for Operators represented by matrices, backed by Terra's ``Operator`` module.""" primitive: Operator @deprecate_func( since="0.24.0", additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, primitive: Union[list, np.ndarray, spmatrix, Operator], coeff: Union[complex, ParameterExpression] = 1.0, ) -> None: """ Args: primitive: The matrix-like object which defines the behavior of the underlying function. coeff: A coefficient multiplying the primitive Raises: TypeError: invalid parameters. ValueError: invalid parameters. """ primitive_orig = primitive if isinstance(primitive, spmatrix): primitive = primitive.toarray() if isinstance(primitive, (list, np.ndarray)): primitive = Operator(primitive) if not isinstance(primitive, Operator): type_hints = get_type_hints(MatrixOp.__init__).get("primitive") valid_cls = [cls.__name__ for cls in type_hints.__args__] raise TypeError( f"MatrixOp can only be instantiated with {valid_cls}, " f"not '{primitive_orig.__class__.__name__}'" ) if primitive.input_dims() != primitive.output_dims(): raise ValueError("Cannot handle non-square matrices yet.") super().__init__(primitive, coeff=coeff) def primitive_strings(self) -> Set[str]: return {"Matrix"} @property def num_qubits(self) -> int: return len(self.primitive.input_dims()) def add(self, other: OperatorBase) -> Union["MatrixOp", SummedOp]: if not self.num_qubits == other.num_qubits: raise ValueError( "Sum over operators with different numbers of qubits, {} and {}, is not well " "defined".format(self.num_qubits, other.num_qubits) ) if isinstance(other, MatrixOp) and self.primitive == other.primitive: return MatrixOp(self.primitive, coeff=self.coeff + other.coeff) # Terra's Operator cannot handle ParameterExpressions if ( isinstance(other, MatrixOp) and not isinstance(self.coeff, ParameterExpression) and not isinstance(other.coeff, ParameterExpression) ): return MatrixOp((self.coeff * self.primitive) + (other.coeff * other.primitive)) # Covers Paulis, Circuits, and all else. return SummedOp([self, other]) def adjoint(self) -> "MatrixOp": return MatrixOp(self.primitive.adjoint(), coeff=self.coeff.conjugate()) def equals(self, other: OperatorBase) -> bool: if not isinstance(other, MatrixOp): return False if isinstance(self.coeff, ParameterExpression) ^ isinstance( other.coeff, ParameterExpression ): return False if isinstance(self.coeff, ParameterExpression) and isinstance( other.coeff, ParameterExpression ): return self.coeff == other.coeff and self.primitive == other.primitive return self.coeff * self.primitive == other.coeff * other.primitive def _expand_dim(self, num_qubits: int) -> "MatrixOp": identity = np.identity(2**num_qubits, dtype=complex) return MatrixOp(self.primitive.tensor(Operator(identity)), coeff=self.coeff) def tensor(self, other: OperatorBase) -> Union["MatrixOp", TensoredOp]: if isinstance(other, MatrixOp): return MatrixOp(self.primitive.tensor(other.primitive), coeff=self.coeff * other.coeff) return TensoredOp([self, other]) def compose( self, other: OperatorBase, permutation: Optional[List[int]] = None, front: bool = False ) -> OperatorBase: new_self, other = self._expand_shorter_operator_and_permute(other, permutation) new_self = cast(MatrixOp, new_self) if front: return other.compose(new_self) if isinstance(other, MatrixOp): return MatrixOp( new_self.primitive.compose(other.primitive, front=True), coeff=new_self.coeff * other.coeff, ) return super(MatrixOp, new_self).compose(other) def permute(self, permutation: Optional[List[int]] = None) -> OperatorBase: """Creates a new MatrixOp that acts on the permuted qubits. Args: permutation: A list defining where each qubit should be permuted. The qubit at index j should be permuted to position permutation[j]. Returns: A new MatrixOp representing the permuted operator. Raises: OpflowError: if indices do not define a new index for each qubit. """ new_self = self new_matrix_size = max(permutation) + 1 if self.num_qubits != len(permutation): raise OpflowError("New index must be defined for each qubit of the operator.") if self.num_qubits < new_matrix_size: # pad the operator with identities new_self = self._expand_dim(new_matrix_size - self.num_qubits) qc = QuantumCircuit(new_matrix_size) # extend the indices to match the size of the new matrix permutation = ( list(filter(lambda x: x not in permutation, range(new_matrix_size))) + permutation ) # decompose permutation into sequence of transpositions transpositions = arithmetic.transpositions(permutation) for trans in transpositions: qc.swap(trans[0], trans[1]) matrix = CircuitOp(qc).to_matrix() return MatrixOp(matrix.transpose()) @ new_self @ MatrixOp(matrix) def to_matrix(self, massive: bool = False) -> np.ndarray: return self.primitive.data * self.coeff def __str__(self) -> str: prim_str = str(self.primitive) if self.coeff == 1.0: return prim_str else: return f"{self.coeff} * {prim_str}" def eval( self, front: Optional[ Union[str, Dict[str, complex], np.ndarray, OperatorBase, Statevector] ] = None, ) -> Union[OperatorBase, complex]: # For other ops' eval we return self.to_matrix_op() here, but that's unnecessary here. if front is None: return self # pylint: disable=cyclic-import from ..list_ops import ListOp from ..state_fns import StateFn, VectorStateFn, OperatorStateFn new_front = None # For now, always do this. If it's not performant, we can be more granular. if not isinstance(front, OperatorBase): front = StateFn(front, is_measurement=False) if isinstance(front, ListOp) and front.distributive: new_front = front.combo_fn( [self.eval(front.coeff * front_elem) for front_elem in front.oplist] ) elif isinstance(front, OperatorStateFn): new_front = OperatorStateFn(self.adjoint().compose(front.to_matrix_op()).compose(self)) elif isinstance(front, OperatorBase): new_front = VectorStateFn(self.to_matrix() @ front.to_matrix()) return new_front def exp_i(self) -> OperatorBase: """Return a ``CircuitOp`` equivalent to e^-iH for this operator H""" return CircuitOp(HamiltonianGate(self.primitive, time=self.coeff)) # Op Conversions def to_matrix_op(self, massive: bool = False) -> "MatrixOp": return self def to_instruction(self) -> Instruction: return (self.coeff * self.primitive).to_instruction()
https://github.com/Fabiha-Noshin/Quantum-Algorithms-with-Qiskit
Fabiha-Noshin
# Importing necessary libraries: import qiskit as q from random import getrandbits %matplotlib inline # Importing standard Qiskit libraries from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * # Loading your IBM Q account(s) provider = IBMQ.load_account() # Defining the constant and balanced oracle: def constant_oraclen(n, x, qc): if x == '0': pass elif x == '1': for i in range(int(n)): qc.x(i+1) def balanced_oraclen(n, x, qc): if x == '0': for i in range(int(n)): qc.cx(i, int(n)) elif x == '1': for i in range(int(n)): qc.x(i) qc.cx(i, int(n)) # Testing oracles: qc= QuantumCircuit(3,1) constant_oraclen(2, '1', qc) qc.draw() def random_oraclen(n, qc): # Selectiong type of oracle if str(getrandbits(1)) == '0': constant_oraclen(n, str(getrandbits(1)), qc) elif str(getrandbits(1)) == '1': balanced_oraclen(n, str(getrandbits(1)), qc) def make_circuitn(n): # Constructiong function to produce n qubit circuit qc= QuantumCircuit(int(n+1),1) # with required oracle (constant/balanced) for i in range(int(n+1)): if i > 0: qc.x(i) for i in range(int(n+1)): qc.h(i) qc.barrier() random_oraclen(n, qc) qc.barrier() for i in range(int(n+1)): qc.h(i) qc.measure(0,0) return qc # An example of 5 qubit circuit: q1= QuantumCircuit() q1= make_circuitn(5) q1.draw('mpl') # Running in qasm simulator: backend= Aer.get_backend('qasm_simulator') job= execute(q1, backend, shots= 3000) results= job.result() counts= results.get_counts() graph= plot_histogram(counts) display(graph) print(counts)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Tests for Layer1Q implementation. """ import unittest from random import randint import test.python.transpiler.aqc.fast_gradient.utils_for_testing as tut import numpy as np import qiskit.transpiler.synthesis.aqc.fast_gradient.layer as lr from qiskit.transpiler.synthesis.aqc.fast_gradient.pmatrix import PMatrix from qiskit.test import QiskitTestCase class TestLayer1q(QiskitTestCase): """ Tests for Layer1Q class. """ max_num_qubits = 5 # maximum number of qubits in tests num_repeats = 50 # number of repetitions in tests def setUp(self): super().setUp() np.random.seed(0x0696969) def test_layer1q_matrix(self): """ Tests: (1) the correctness of Layer2Q matrix construction; (2) matrix multiplication interleaved with permutations. """ mat_kind = "complex" eps = 100.0 * np.finfo(float).eps max_rel_err = 0.0 for n in range(2, self.max_num_qubits + 1): dim = 2**n iden = tut.eye_int(n) for k in range(n): m_mat = tut.rand_matrix(dim=dim, kind=mat_kind) t_mat, g_mat = tut.make_test_matrices2x2(n=n, k=k, kind=mat_kind) lmat = lr.Layer1Q(num_qubits=n, k=k, g2x2=g_mat) g2, perm, inv_perm = lmat.get_attr() self.assertTrue(m_mat.dtype == t_mat.dtype == g_mat.dtype == g2.dtype) self.assertTrue(np.all(g_mat == g2)) self.assertTrue(np.all(iden[perm].T == iden[inv_perm])) g_mat = np.kron(tut.eye_int(n - 1), g_mat) # T == P^t @ G @ P. err = tut.relative_error(t_mat, iden[perm].T @ g_mat @ iden[perm]) self.assertLess(err, eps, "err = {:0.16f}".format(err)) max_rel_err = max(max_rel_err, err) # Multiplication by permutation matrix of the left can be # replaced by row permutations. tm = t_mat @ m_mat err1 = tut.relative_error(iden[perm].T @ g_mat @ m_mat[perm], tm) err2 = tut.relative_error((g_mat @ m_mat[perm])[inv_perm], tm) # Multiplication by permutation matrix of the right can be # replaced by column permutations. mt = m_mat @ t_mat err3 = tut.relative_error(m_mat @ iden[perm].T @ g_mat @ iden[perm], mt) err4 = tut.relative_error((m_mat[:, perm] @ g_mat)[:, inv_perm], mt) self.assertTrue( err1 < eps and err2 < eps and err3 < eps and err4 < eps, "err1 = {:f}, err2 = {:f}, " "err3 = {:f}, err4 = {:f}".format(err1, err2, err3, err4), ) max_rel_err = max(max_rel_err, err1, err2, err3, err4) def test_pmatrix_class(self): """ Test the class PMatrix. """ _eps = 100.0 * np.finfo(float).eps mat_kind = "complex" max_rel_err = 0.0 for n in range(2, self.max_num_qubits + 1): dim = 2**n tmp1 = np.ndarray((dim, dim), dtype=np.cfloat) tmp2 = tmp1.copy() for _ in range(self.num_repeats): k0 = randint(0, n - 1) k1 = randint(0, n - 1) k2 = randint(0, n - 1) k3 = randint(0, n - 1) k4 = randint(0, n - 1) t0, g0 = tut.make_test_matrices2x2(n=n, k=k0, kind=mat_kind) t1, g1 = tut.make_test_matrices2x2(n=n, k=k1, kind=mat_kind) t2, g2 = tut.make_test_matrices2x2(n=n, k=k2, kind=mat_kind) t3, g3 = tut.make_test_matrices2x2(n=n, k=k3, kind=mat_kind) t4, g4 = tut.make_test_matrices2x2(n=n, k=k4, kind=mat_kind) c0 = lr.Layer1Q(num_qubits=n, k=k0, g2x2=g0) c1 = lr.Layer1Q(num_qubits=n, k=k1, g2x2=g1) c2 = lr.Layer1Q(num_qubits=n, k=k2, g2x2=g2) c3 = lr.Layer1Q(num_qubits=n, k=k3, g2x2=g3) c4 = lr.Layer1Q(num_qubits=n, k=k4, g2x2=g4) m_mat = tut.rand_matrix(dim=dim, kind=mat_kind) ttmtt = t0 @ t1 @ m_mat @ np.conj(t2).T @ np.conj(t3).T pmat = PMatrix(n) pmat.set_matrix(m_mat) pmat.mul_left_q1(layer=c1, temp_mat=tmp1) pmat.mul_left_q1(layer=c0, temp_mat=tmp1) pmat.mul_right_q1(layer=c2, temp_mat=tmp1, dagger=True) pmat.mul_right_q1(layer=c3, temp_mat=tmp1, dagger=True) alt_ttmtt = pmat.finalize(temp_mat=tmp1) err1 = tut.relative_error(alt_ttmtt, ttmtt) self.assertLess(err1, _eps, "relative error: {:f}".format(err1)) prod = np.cfloat(np.trace(ttmtt @ t4)) alt_prod = pmat.product_q1(layer=c4, tmp1=tmp1, tmp2=tmp2) err2 = abs(alt_prod - prod) / abs(prod) self.assertLess(err2, _eps, "relative error: {:f}".format(err2)) max_rel_err = max(max_rel_err, err1, err2) if __name__ == "__main__": unittest.main()
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) qc.cx(1, 0) return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).issubset({0,1}): raise ValueError(f"message '{msg}' is invalid") if msg[1] == "1": qc.x(qubit) if msg[0] == "1": ### removed z gate ### pass return qc def decode_message(qc): ### removed cx gate ### qc.h(1) return qc
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit qc = QuantumCircuit(2, 2) qc.h(0) qc.cx(0, 1) qc.measure([0, 1], [0, 1]) qc.draw('mpl')
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("./") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="lq") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") t3_st_qcs = transpile(t3_st_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_st_qcs), ")") t3_st_qcs[-1].draw("mpl") # only view trotter gates # from qiskit.test.mock import FakeJakarta # backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') print("provider:", provider) backend = provider.get_backend("ibmq_jakarta") shots = 8192 reps = 8 jobs = [] for _ in range(reps): # execute job = execute(t3_st_qcs, backend, shots=shots) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout=initial_layout) print('Job ID', cal_job.job_id()) dt_now = datetime.datetime.now() print(dt_now) with open("jobs_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) with open("job_ids_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) with open("properties_jakarta" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump(backend.properties(), f) filename = "job_ids_jakarta_100step_20220412_171248_.pkl" # change here with open(filename, "rb") as f: job_ids_dict = pickle.load(f) job_ids = job_ids_dict["job_ids"] cal_job_id = job_ids_dict["cal_job_id"] retrieved_jobs = [] for job_id in job_ids: retrieved_jobs.append(backend.retrieve_job(job_id)) retrieved_cal_job = backend.retrieve_job(cal_job_id) cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') # set the target state target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in retrieved_jobs: # mit_results = meas_fitter.filter.apply(job.result()) # apply QREM rho = StateTomographyFitter(job.result(), st_qcs).fit(method='lstsq') fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids))) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/alvinli04/Quantum-Steganography
alvinli04
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, Aer, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * # Loading your IBM Quantum account(s) provider = IBMQ.load_account() import qiskit from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute from qiskit import Aer from qiskit import IBMQ from qiskit.compiler import transpile from time import perf_counter from qiskit.tools.visualization import plot_histogram import numpy as np import math ''' params --------------- picture: square 2d array of integers representing grayscale values assume the length (n) is some power of 2 return --------------- a flattened representation of picture using bitstrings (boolean arrays) ''' def convert_to_bits (picture): n = len(picture) ret = [] for i in range(n): for j in range(n): value = picture[i][j] bitstring = bin(value)[2:] ret.append([0 for i in range(8 - len(bitstring))] + [1 if c=='1' else 0 for c in bitstring]) return ret ''' params ---------------- bitStr: a representation of an image using bitstrings to represent grayscale values return ---------------- A quantum circuit containing the NEQR representation of the image ''' def neqr(bitStr): newBitStr = bitStr #print(newBitStr) #print("\n") # Pixel position idx = QuantumRegister(math.ceil(math.log2(len(newBitStr))), 'idx') # Pixel intensity values intensity = QuantumRegister(8, 'intensity') # Classical Register creg = ClassicalRegister(10, 'creg') # Quantum Image Representation as a quantum circuit # with Pixel Position and Intensity registers quantumImage = QuantumCircuit(intensity, idx, creg) numOfQubits = quantumImage.num_qubits print("\n>> Initial Number of Qubits:", numOfQubits) # ----------------------------------- # Drawing the Quantum Circuit # ----------------------------------- lengthIntensity = intensity.size lengthIdx = idx.size start = perf_counter() quantumImage.i([intensity[lengthIntensity-1-i] for i in range(lengthIntensity)]) quantumImage.h([idx[lengthIdx-1-i] for i in range(lengthIdx)]) numOfPixels = len(newBitStr) for i in range(numOfPixels): bin_ind = bin(i)[2:] bin_ind = (lengthIdx - len(bin_ind)) * '0' + bin_ind bin_ind = bin_ind[::-1] # X-gate (enabling zero-controlled nature) for j in range(len(bin_ind)): if bin_ind[j] == '0': quantumImage.x(idx[j]) # Configuring Multi-Qubit Controlled-NOT (mcx) gates with control and target qubits for j in range(len(newBitStr[i])): if newBitStr[i][j] == 1: quantumImage.mcx(idx, intensity[lengthIntensity-1-j]) # X-gate (reversing the Negated state of the qubits) for j in range(len(bin_ind)): if bin_ind[j] == '0': quantumImage.x(idx[j]) quantumImage.barrier() quantumImage.measure(range(10), range(10)) end = perf_counter() print(f">> Circuit construction took {(end-start)} seconds.") return (quantumImage, intensity) if __name__ == '__main__': test_picture_2x2 = [[0, 100], [200, 255]] test_picture_3x3 = [[25, 50, 75], [100, 125, 150], [175, 200, 225]] test_picture_4x4 = [[0, 100, 143, 83], [200, 255, 43, 22], [12, 234, 23, 5], [112, 113, 117, 125]] test_picture_5x5 = [[0, 100, 212, 12, 32], [0, 100, 212, 12, 32], [0, 100, 212, 12, 32], [0, 100, 212, 12, 32], [0, 100, 212, 12, 32]] arr = convert_to_bits(test_picture_2x2) arr1 = convert_to_bits(test_picture_3x3) arr2 = convert_to_bits(test_picture_4x4) arr3 = convert_to_bits(test_picture_5x5) print("2x2: ", arr, "\n") #print("3x3: ", arr1, "\n") #print("4x4: ", arr2, "\n") #print("5x5: ", arr3, "\n") qc_image, _ = neqr(arr) qc_image.draw() # Circuit Dimensions print('>> Circuit dimensions') print('>> Circuit depth (length of critical path): ', qc_image.depth()) print('>> Total Number of Gate Operations: ', qc_image.size()) # Get the number of qubits needed to run the circuit active_qubits = {} for op in qc_image.data: if op[0].name != "barrier" and op[0].name != "snapshot": for qubit in op[1]: active_qubits[qubit.index] = True print(f">> Width: {len(active_qubits)} qubits") print(f">> Width (total number of qubits and clbits): {qc_image.width()} qubits") print(f">> Gates used: {qc_image.count_ops()}") print(f">> Fundamental Gates: {qc_image.decompose().count_ops()}") # Testing qc_image circuit using Fake Simulator # to simulate the error in a real quantum computer from qiskit.providers.aer import AerSimulator from qiskit.test.mock import FakeMontreal device_backend = FakeMontreal() sim_montreal = AerSimulator.from_backend(device_backend) #### TRANSPILING start_transpile = perf_counter() tcirc = transpile(qc_image, sim_montreal, optimization_level=1) # Optimization Level = 1 (default) end_transpile = perf_counter() print(f"\n>> Circuit transpilation took {(end_transpile-start_transpile)} seconds.") #### SIMULATING start_sim = perf_counter() # Run transpiled circuit on FakeMontreal result_noise = sim_montreal.run(tcirc).result() # Get counts for each possible result counts_noise = result_noise.get_counts() end_sim = perf_counter() print(f"\n>> Circuit simulation took {(end_sim-start_sim)} seconds.") #plot_histogram(counts_noise, figsize=(30, 15)) #print(counts_noise) from qiskit.compiler import assemble aer_sim = Aer.get_backend('aer_simulator') t_qc_image = transpile(qc_image, aer_sim) shots = 1024 qobj = assemble(t_qc_image, shots=shots) job_neqr = aer_sim.run(qobj) result_neqr = job_neqr.result() counts_neqr = result_neqr.get_counts() print('Encoded: 00 = ', arr[0]) print('Encoded: 01 = ', arr[1]) print('Encoded: 10 = ', arr[2]) print('Encoded: 11 = ', arr[3]) print("\nExpected Counts per pixel = ", shots/len(arr)) print("Experimental Counts", counts_neqr) print("\nExpected probability for each pixel = ", 1.0/(len(arr))) plot_histogram(counts_neqr) machine = "ibmq_santiago" backend = provider.get_backend(machine) santiago_sim = AerSimulator.from_backend(backend) start_sim = perf_counter() result = santiago_sim.run(qc_image).result() counts = result.get_counts(qc_image) end_sim = perf_counter() print("\n", end_sim-start_sim) print("\nExpected Counts per pixel = ", shots/len(arr), "\n") for(measured_state, count) in counts.items(): big_endian_state = measured_state[::-1] print(f"Measured {big_endian_state} {count} times.") machine = "ibmq_belem" backend = provider.get_backend(machine) santiago_sim = AerSimulator.from_backend(backend) start_sim = perf_counter() result = santiago_sim.run(qc_image).result() counts = result.get_counts(qc_image) end_sim = perf_counter() print(end_sim-start_sim) print("\nExpected Counts per pixel = ", shots/len(arr), "\n") for(measured_state, count) in counts.items(): big_endian_state = measured_state[::-1] print(f"Measured {big_endian_state} {count} times.") # Testing qc_image circuit using Fake Simulator # to simulate the error in a real quantum computer from qiskit.providers.aer import AerSimulator from qiskit.test.mock import FakeMumbai device_backend = FakeMumbai() sim_brooklyn = AerSimulator.from_backend(device_backend) #### TRANSPILING start_transpile = perf_counter() tcirc = transpile(qc_image, sim_brooklyn, optimization_level=1) # Optimization Level = 1 (default) end_transpile = perf_counter() print(f"\n>> Circuit transpilation took {(end_transpile-start_transpile)} seconds.") #### SIMULATING start_sim = perf_counter() # Run transpiled circuit on FakeMontreal result_noise = sim_brooklyn.run(tcirc).result() # Get counts for each possible result counts_noise = result_noise.get_counts() end_sim = perf_counter() print(f"\n>> Circuit simulation took {(end_sim-start_sim)} seconds.") from qiskit.test.mock import FakeMontreal fake_athens = FakeMontreal() t_qc = transpile(qc_image, fake_athens, optimization_level=3) qobj = assemble(t_qc, shots=4096) result = fake_athens.run(qobj).result() counts = result.get_counts(qc_image) print(counts) plot_histogram(counts) plot_histogram(counts, figsize=(30, 15))
https://github.com/Interlin-q/diskit
Interlin-q
"""The circuit remapper logic.""" from typing import ( Optional, List, Iterable, ) import time from qiskit.circuit import QuantumCircuit from qiskit.circuit.quantumcircuitdata import CircuitInstruction from qiskit.circuit.quantumregister import Qubit from qiskit.circuit.classicalregister import ClassicalRegister, Clbit from qiskit.circuit.exceptions import CircuitError from qiskit import transpile from .components import Layer, Topology class CircuitRemapper: """ The circuit remapper class for remapping a ciruit to a topology. """ def __init__(self, topology: Topology): self.topology = topology @staticmethod def _circuit_to_layers( circuit: QuantumCircuit, filter_function: Optional[callable] = lambda x: not getattr( x.operation, "_directive", False ), ) -> "list[list]": """Given a Qiskit circuit, return an array of the layers of that circuit""" # Assign each bit in the circuit a unique integer # to index into op_stack. circ = circuit bit_indices = {bit: idx for idx, bit in enumerate(circ.qubits + circ.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) layers = [] for instruction in circ.data: levels = [] reg_ints = [] max_pos = 0 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) if len(layers) < (op_stack[reg_ints[ind]] + 1): layers.append([]) max_pos = max(max_pos, (op_stack[reg_ints[ind]])) else: levels.append(op_stack[reg_ints[ind]]) layers[max_pos].append(instruction) # 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 assert max(op_stack) == len(layers) return layers @staticmethod def _layer_to_circuit(layers: Iterable[List], qubits: Iterable[Qubit] = (), clbits: Iterable[Clbit] = (), name: Optional[str] = None, global_phase=0, metadata: Optional[dict] = None, ) -> "QuantumCircuit": """Return a circuit from a list of layers. Args: layers: A list of layers, where each layer is a list of :class:`~qiskit.circuit.Instruction` return: A circuit from the layers. """ circuit = QuantumCircuit( name=name, global_phase=global_phase, metadata=metadata) added_qubits = set() added_clbits = set() added_qregs = set() added_cregs = set() if qubits: qubits = list(qubits) circuit.add_bits(qubits) added_qubits.update(qubits) added_qregs.update(qubit.register for qubit in qubits) circuit.add_register(*added_qregs) if clbits: clbits = list(clbits) circuit.add_bits(clbits) added_clbits.update(clbits) added_cregs.update(clbit.register for clbit in clbits) circuit.add_register(*added_cregs) for layer in layers: for instruction in layer: if not isinstance(instruction, CircuitInstruction): instruction = CircuitInstruction(*instruction) qubits = [qubit for qubit in instruction.qubits if qubit not in added_qubits and qubit.register not in added_qregs] clbits = [clbit for clbit in instruction.clbits if clbit not in added_clbits and clbit.register not in added_cregs] qregs = [qubit.register for qubit in qubits] cregs = [clbit.register for clbit in clbits] circuit.add_bits(qubits) circuit.add_bits(clbits) circuit.add_register(*qregs) circuit.add_register(*cregs) added_qubits.update(qubits) added_clbits.update(clbits) added_qregs.update(qregs) added_cregs.update(cregs) circuit.append(instruction) return circuit @staticmethod def _replace_nonlocal_control(operation: CircuitInstruction, topology: Topology, deeper_ops: List[CircuitInstruction] = None): """ Replace the non-local control gates with Cat entanglement gates for a given layer. Args: operation: a non-local control gate topology: The network topology. deeper_ops: The list of operations. Returns: (list): List of new operations to be added in the layer """ control_qubit = operation.qubits[0] target_qubit = operation.qubits[1] control_host = topology.get_host(control_qubit) target_host = topology.get_host(target_qubit) ent_inst = operation.copy() epr_control = topology.get_epr_id(control_host) epr_target = topology.get_epr_id(target_host) epr_qubits = [epr_control, epr_target] opr_qubits = [control_qubit, target_qubit] if len(deeper_ops) > 0: for opi in deeper_ops: opr_qubits.append(opi.qubits[1]) measure_bits = ClassicalRegister(2, "cat_measure") circ = QuantumCircuit(epr_qubits, opr_qubits, measure_bits) # print(deeper_ops) # Generate EPR pair circ.h(0) circ.cx(0, 1) # cat entanglement circ.cx(2, 0) circ.measure(0, 0) circ.x(1).c_if(measure_bits[0], 1) ent_inst.qubits = [epr_qubits[1], opr_qubits[1]] circ.data.append(ent_inst) if len(deeper_ops) > 0: ident = 2 for opi in deeper_ops: ent_inst = opi.copy() ent_inst.qubits = [epr_qubits[1], opr_qubits[ident]] circ.data.append(ent_inst) ident += 1 circ.h(1) circ.measure(1, 1) circ.z(2).c_if(measure_bits[1], 1) circ.reset(epr_qubits) # Make layers from this circuit new_ops = [] for opi in circ.data: new_ops.append([opi]) return new_ops def remap_circuit(self, circuit: QuantumCircuit, decompose: bool = None, decompose_list: List[str] = None): """ Remap the circuit for the topology. Args: circuit: The circuit to be distributed decompose: Decompose the circuit into compatible 2-qubit gates if possible decompose_list: Gate names which should be decomposed Returns: A distributed circuit over the topology. """ if decompose is not None: if decompose_list is not None: circuit, _ = self._decompose_ready(circuit, decompose_list) else: circuit, _ = self._decompose_ready(circuit) else: _, incompatible = self._decompose_ready( circuit, do_decompose=False) if incompatible: raise CircuitError( "The circuit contains incompatible gates, Please try decompose=True keyword argument.") layers = self._circuit_to_layers(circuit=circuit) qubits = circuit.qubits clbits = circuit.clbits distributed_layers = [] idx = 0 circ_qubits = self.topology.qubits deep_dict = {qubit: 0 for qubit in circ_qubits} for a_layer in layers: layer_now = Layer(a_layer, self.topology) non_local_ops = layer_now.non_local_operations() new_layers = [[]] if non_local_ops not in [[], None]: for operation in non_local_ops: control, target = operation.qubits[0], operation.qubits[1] if deep_dict[control] > 0: deep_dict[control] -= 1 continue deeper_ops = self._get_deeper_nlcontrol( layers[idx + 1:], control, target) # deeper_ops = [] if len(deeper_ops) > 0: deep_dict[control] += len(deeper_ops) op_replaced = self._replace_nonlocal_control( operation, self.topology, deeper_ops) new_layers.extend(op_replaced) local_ops = [] for operation in a_layer: if operation not in non_local_ops: local_ops.append(operation) new_layers[0].extend(local_ops) distributed_layers.extend(new_layers) idx += 1 dist_circ = self._layer_to_circuit(distributed_layers, qubits, clbits) return dist_circ @staticmethod def _qubit_ops(layers: List[Layer], qubit: Qubit = None): """ Get the operations on each qubit Args: layers: The list of layers. qubit: The qubit to get the operations for. Returns: dictionary of qubit to operations """ qubit_ops = [] for layer in layers: for opi in layer: for a_qubit in opi.qubits: if qubit == a_qubit: qubit_ops.append(opi) return qubit_ops def _get_deeper_nlcontrol(self, layers, control_qubit: Qubit, target_qubit: Qubit): """ Get the deeper control operation on a qubit. """ control_ops = self._qubit_ops(layers, control_qubit) target_host = self.topology.get_host(target_qubit) ops = [] track_dict = { qubit: 0 for qubit in self.topology.get_qubits(target_host)} for opi in control_ops: if len(opi.qubits) == 2 and opi.qubits[0] == control_qubit: if self.topology.get_host(opi.qubits[1]) == target_host: target_ops = self._qubit_ops(layers, opi.qubits[1]) # print('here') if target_ops[track_dict[opi.qubits[1]]] == opi: ops.append(opi) track_dict[opi.qubits[1]] += 1 else: break else: break return ops @staticmethod def collate_measurements(sim_results: dict, num_qubits: int): """ Collate the measurements from the simulation results. Args: sim_results: simulation results from the simulator num_qubits: number of qubits in the circuit Returns: A dictionary of measurements """ sim_dict = {} for key in sim_results.keys(): new_key = key[0:num_qubits] dict_keys = sim_dict.keys() if new_key not in dict_keys: sim_dict[new_key] = sim_results[key] else: sim_dict[new_key] += sim_results[key] return sim_dict @staticmethod def do_measure_ready(circ: QuantumCircuit, topology: Topology): """ Make the circuit is ready for measurement. Args: circ: the circuit to measure. topology: The network topology. Returns: Circuit ready for measurement """ n_q = topology.num_qubits() all_qubits = topology.get_all_qubits() measure_bits = ClassicalRegister(n_q, "measure") circ.add_register(measure_bits) circ.measure(all_qubits, measure_bits) @staticmethod def _decompose_ready(circ: QuantumCircuit, list_of_gates: List[str] = None, do_decompose: bool = True, max_time=60): """ Decompose the circuit into basic gates(1 and 2 qubit gates). Args: circ: the circuit to decompose. list_of_gates: The network topology. max_time: Seconds to spend decomposing the circuit before falling back to default gate set Returns: Decomposed circuit """ timeout = time.time() + max_time num_large_gates = 1 circ_copy = circ.copy() incompatible_gate_present = False printed_warning = False if list_of_gates is None: list_of_gates = [] while num_large_gates > 0: num_large_gates = 0 for gate in circ_copy.data: if len(gate[1]) > 2: num_large_gates += 1 incompatible_gate_present = True if do_decompose is False: break circ_copy = circ_copy.decompose(gate[0].name) elif gate[0].name == 'swap': num_large_gates += 1 incompatible_gate_present = True if do_decompose is False: break if not printed_warning: print('Warning: Swap gate found in circuit. ' 'Swap gates cannot be automatically decomposed and should be' 'transpiled by the user. Skipping it for now but may lead to errors if ignored.') printed_warning = True num_large_gates -= 1 circ_copy = circ_copy.decompose(gate) elif gate[0].name in list_of_gates: num_large_gates += 1 circ_copy = circ_copy.decompose(gate) if time.time() > timeout: break if do_decompose is False and num_large_gates > 0: break if do_decompose is True and time.time() > timeout: print(f"Warning: Single level decomposition cutoff of {max_time} seconds reached.", "Performing transpilation with basis gates: cx, u1, u2, u3, id") circ_copy = transpile(circ_copy, basis_gates=[ 'cx', 'u1', 'u2', 'u3', 'id']) break return circ_copy, incompatible_gate_present
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=invalid-name """Tests continuous pulse functions.""" import numpy as np from qiskit.test import QiskitTestCase import qiskit.pulse.pulse_lib.continuous as continuous class TestContinuousPulses(QiskitTestCase): """Test continuous pulses.""" def test_constant(self): """Test constant pulse.""" amp = 0.5j samples = 50 times = np.linspace(0, 10, samples) constant_arr = continuous.constant(times, amp=amp) self.assertEqual(constant_arr.dtype, np.complex_) np.testing.assert_equal(constant_arr, amp) self.assertEqual(len(constant_arr), samples) def test_zero(self): """Test constant pulse.""" times = np.linspace(0, 10, 50) zero_arr = continuous.zero(times) self.assertEqual(zero_arr.dtype, np.complex_) np.testing.assert_equal(zero_arr, 0.0) self.assertEqual(len(zero_arr), 50) def test_square(self): """Test square wave.""" amp = 0.5 period = 5 samples = 100 times = np.linspace(0, 10, samples) square_arr = continuous.square(times, amp=amp, period=period) # with new phase square_arr_phased = continuous.square(times, amp=amp, period=period, phase=np.pi/2) self.assertEqual(square_arr.dtype, np.complex_) self.assertAlmostEqual(square_arr[0], amp) # test constant self.assertAlmostEqual(square_arr[1]-square_arr[0], 0.0) self.assertAlmostEqual(square_arr[25], -amp) self.assertAlmostEqual(square_arr_phased[0], -amp) # Assert bounded between -amp and amp self.assertTrue(np.all((-amp <= square_arr) & (square_arr <= amp))) self.assertEqual(len(square_arr), samples) def test_sawtooth(self): """Test sawtooth wave.""" amp = 0.5 period = 5 samples = 101 times, dt = np.linspace(0, 10, samples, retstep=True) sawtooth_arr = continuous.sawtooth(times, amp=amp, period=period) # with new phase sawtooth_arr_phased = continuous.sawtooth(times, amp=amp, period=period, phase=np.pi/2) self.assertEqual(sawtooth_arr.dtype, np.complex_) self.assertAlmostEqual(sawtooth_arr[0], 0.0) # test slope self.assertAlmostEqual((sawtooth_arr[1]-sawtooth_arr[0])/dt, 2*amp/period) self.assertAlmostEqual(sawtooth_arr[24], 0.48) self.assertAlmostEqual(sawtooth_arr[50], 0.) self.assertAlmostEqual(sawtooth_arr[75], -amp) self.assertAlmostEqual(sawtooth_arr_phased[0], -amp) # Assert bounded between -amp and amp self.assertTrue(np.all((-amp <= sawtooth_arr) & (sawtooth_arr <= amp))) self.assertEqual(len(sawtooth_arr), samples) def test_triangle(self): """Test triangle wave.""" amp = 0.5 period = 5 samples = 101 times, dt = np.linspace(0, 10, samples, retstep=True) triangle_arr = continuous.triangle(times, amp=amp, period=period) # with new phase triangle_arr_phased = continuous.triangle(times, amp=amp, period=period, phase=np.pi/2) self.assertEqual(triangle_arr.dtype, np.complex_) self.assertAlmostEqual(triangle_arr[0], 0.0) # test slope self.assertAlmostEqual((triangle_arr[1]-triangle_arr[0])/dt, 4*amp/period) self.assertAlmostEqual(triangle_arr[12], 0.48) self.assertAlmostEqual(triangle_arr[13], 0.48) self.assertAlmostEqual(triangle_arr[50], 0.) self.assertAlmostEqual(triangle_arr_phased[0], amp) # Assert bounded between -amp and amp self.assertTrue(np.all((-amp <= triangle_arr) & (triangle_arr <= amp))) self.assertEqual(len(triangle_arr), samples) def test_cos(self): """Test cosine wave.""" amp = 0.5 period = 5 freq = 1/period samples = 101 times = np.linspace(0, 10, samples) cos_arr = continuous.cos(times, amp=amp, freq=freq) # with new phase cos_arr_phased = continuous.cos(times, amp=amp, freq=freq, phase=np.pi/2) self.assertEqual(cos_arr.dtype, np.complex_) # Assert starts at 1 self.assertAlmostEqual(cos_arr[0], amp) self.assertAlmostEqual(cos_arr[6], 0.3644, places=2) self.assertAlmostEqual(cos_arr[25], -amp) self.assertAlmostEqual(cos_arr[50], amp) self.assertAlmostEqual(cos_arr_phased[0], 0.0) # Assert bounded between -amp and amp self.assertTrue(np.all((-amp <= cos_arr) & (cos_arr <= amp))) self.assertEqual(len(cos_arr), samples) def test_sin(self): """Test sine wave.""" amp = 0.5 period = 5 freq = 1/period samples = 101 times = np.linspace(0, 10, samples) sin_arr = continuous.sin(times, amp=amp, freq=freq) # with new phase sin_arr_phased = continuous.sin(times, amp=0.5, freq=1/5, phase=np.pi/2) self.assertEqual(sin_arr.dtype, np.complex_) # Assert starts at 1 self.assertAlmostEqual(sin_arr[0], 0.0) self.assertAlmostEqual(sin_arr[6], 0.3427, places=2) self.assertAlmostEqual(sin_arr[25], 0.0) self.assertAlmostEqual(sin_arr[13], amp, places=2) self.assertAlmostEqual(sin_arr_phased[0], amp) # Assert bounded between -amp and amp self.assertTrue(np.all((-amp <= sin_arr) & (sin_arr <= amp))) self.assertEqual(len(sin_arr), samples) def test_gaussian(self): """Test gaussian pulse.""" amp = 0.5 center = 10 sigma = 2 times, dt = np.linspace(0, 20, 1001, retstep=True) gaussian_arr = continuous.gaussian(times, amp, center, sigma) gaussian_arr_zeroed = continuous.gaussian(np.array([-1, 10]), amp, center, sigma, zeroed_width=2*(center+1), rescale_amp=True) self.assertEqual(gaussian_arr.dtype, np.complex_) center_time = np.argmax(gaussian_arr) self.assertAlmostEqual(times[center_time], center) self.assertAlmostEqual(gaussian_arr[center_time], amp) self.assertAlmostEqual(gaussian_arr_zeroed[0], 0., places=6) self.assertAlmostEqual(gaussian_arr_zeroed[1], amp) self.assertAlmostEqual(np.sum(gaussian_arr*dt), amp*np.sqrt(2*np.pi*sigma**2), places=3) def test_gaussian_deriv(self): """Test gaussian derivative pulse.""" amp = 0.5 center = 10 sigma = 2 times, dt = np.linspace(0, 20, 1000, retstep=True) deriv_prefactor = -sigma**2/(times-center) gaussian_deriv_arr = continuous.gaussian_deriv(times, amp, center, sigma) gaussian_arr = gaussian_deriv_arr*deriv_prefactor self.assertEqual(gaussian_deriv_arr.dtype, np.complex_) self.assertAlmostEqual(continuous.gaussian_deriv(np.array([0]), amp, center, sigma)[0], 0, places=5) self.assertAlmostEqual(np.sum(gaussian_arr*dt), amp*np.sqrt(2*np.pi*sigma**2), places=3) def test_gaussian_square(self): """Test gaussian square pulse.""" amp = 0.5 center = 10 width = 2 sigma = 0.1 times, dt = np.linspace(0, 20, 2001, retstep=True) gaussian_square_arr = continuous.gaussian_square(times, amp, center, width, sigma) self.assertEqual(gaussian_square_arr.dtype, np.complex_) self.assertEqual(gaussian_square_arr[1000], amp) # test half gaussian rise/fall self.assertAlmostEqual(np.sum(gaussian_square_arr[:900]*dt)*2, amp*np.sqrt(2*np.pi*sigma**2), places=2) self.assertAlmostEqual(np.sum(gaussian_square_arr[1100:]*dt)*2, amp*np.sqrt(2*np.pi*sigma**2), places=2) # test for continuity at gaussian/square boundaries gauss_rise_end_time = center-width/2 gauss_fall_start_time = center+width/2 epsilon = 0.01 rise_times, dt_rise = np.linspace(gauss_rise_end_time-epsilon, gauss_rise_end_time+epsilon, 1001, retstep=True) fall_times, dt_fall = np.linspace(gauss_fall_start_time-epsilon, gauss_fall_start_time+epsilon, 1001, retstep=True) gaussian_square_rise_arr = continuous.gaussian_square(rise_times, amp, center, width, sigma) gaussian_square_fall_arr = continuous.gaussian_square(fall_times, amp, center, width, sigma) # should be locally approximated by amp*dt^2/(2*sigma^2) self.assertAlmostEqual(amp*dt_rise**2/(2*sigma**2), gaussian_square_rise_arr[500]-gaussian_square_rise_arr[499]) self.assertAlmostEqual(amp*dt_fall**2/(2*sigma**2), gaussian_square_fall_arr[501]-gaussian_square_fall_arr[500]) def test_drag(self): """Test drag pulse.""" amp = 0.5 center = 10 sigma = 0.1 beta = 0 times = np.linspace(0, 20, 2001) # test that we recover gaussian for beta=0 gaussian_arr = continuous.gaussian(times, amp, center, sigma, zeroed_width=2*(center+1), rescale_amp=True) drag_arr = continuous.drag(times, amp, center, sigma, beta=beta, zeroed_width=2*(center+1), rescale_amp=True) self.assertEqual(drag_arr.dtype, np.complex_) np.testing.assert_equal(drag_arr, gaussian_arr)
https://github.com/KMU-quantum-classroom/qiskit-classroom
KMU-quantum-classroom
"""Widget for converting informations""" # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=no-name-in-module from PySide6.QtGui import QDragEnterEvent, QDropEvent from PySide6.QtWidgets import ( QWidget, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit, QPlainTextEdit, QPushButton, QFileDialog, QCheckBox, ) from PySide6.QtCore import Qt, Signal from .expression_enum import QuantumExpression from .input_model import Input, QuantumCircuitInput, DiracInput, MatrixInput EXPRESSION_PLACEHOLDERS: dict[QuantumExpression:str] = { QuantumExpression.CIRCUIT: """from qiskit import QuantumCircuit quantum_circuit = QuantumCircuit(2, 2) quantum_circuit.x(0) quantum_circuit.cx(0, 1) """, QuantumExpression.DIRAC: "sqrt(2)*|00>/2+sqrt(2)*|11>/2", QuantumExpression.MATRIX: """[[1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0]]""", QuantumExpression.NONE: "", } class ExpressionPlainText(QPlainTextEdit): """ ExpressionPlainText """ file_dropped = Signal(object) def __init__(self, parent) -> None: super().__init__(parent=parent) self.setAcceptDrops(True) self.set_ui() def set_ui(self) -> None: """ set UI """ self.setFixedHeight(250) def dragEnterEvent(self, event: QDragEnterEvent) -> None: # pylint: disable=invalid-name """ handle drag event and accept only url """ if event.mimeData().hasUrls(): event.accept() else: event.ignore() def dropEvent(self, event: QDropEvent) -> None: # pylint: disable=invalid-name """ handle drop event and emit file imported event """ if event.mimeData().hasUrls(): files = [u.toLocalFile() for u in event.mimeData().urls()] self.file_dropped.emit(files) event.accept() def set_placeholder_text(self, expression: QuantumExpression) -> None: """set placeholder for expression plain text Args: expression (QuantumExpression): selection """ self.setPlaceholderText("") self.setPlaceholderText(EXPRESSION_PLACEHOLDERS[expression]) class InputWidget(QWidget): """Widget group for certain input""" def set_ui(self) -> None: """show widgets""" def get_input(self) -> Input: """return user input Returns: Input: user input class """ return Input class QuantumCircuitInputWidget(InputWidget): """Widget group for QuantumCircuit Input""" file_imported = Signal(str) def __init__(self, parent: QWidget) -> None: super().__init__(parent) self.set_ui() def set_ui(self): """set ui for QuantumCircuitInputWidget""" vbox = QVBoxLayout(self) vbox.setAlignment(Qt.AlignmentFlag.AlignCenter) value_name_box = QHBoxLayout() value_name_label = QLabel("value name") value_name_box.addWidget(value_name_label) self.value_name_text = QLineEdit() self.value_name_text.setPlaceholderText("input value name of quantum circuit") value_name_box.addWidget(self.value_name_text) load_box = QHBoxLayout() load_box.addStretch() self.load_push_button = QPushButton("or load...") self.load_push_button.setMinimumWidth(150) self.load_push_button.clicked.connect(self.on_file_load_clicked) load_box.addWidget(self.load_push_button) vbox.addLayout(value_name_box) vbox.addLayout(load_box) def on_file_load_clicked(self) -> None: """ handling file dialog """ filename = QFileDialog.getOpenFileName( self, "Open .py", "", "python3 script (*.py)" )[0] self.file_imported.emit(filename) def get_input(self) -> QuantumCircuitInput: user_input = QuantumCircuitInput( self.value_name_text.text().strip(), ) return user_input class DiracInputWidget(InputWidget): """Widget group for Dirac Notaion input""" def __init__(self, parent: QWidget) -> None: super().__init__(parent) self.set_ui() def get_input(self) -> DiracInput: return DiracInput() class MatrixInputWidget(InputWidget): """Widget group for matrix input""" matrix_plain_text: QPlainTextEdit num_cubit_text: QLineEdit do_measure_checkbox: QCheckBox def __init__(self, parent: QWidget) -> None: super().__init__(parent) self.set_ui() def set_ui(self): vbox = QVBoxLayout(self) vbox.setAlignment(Qt.AlignmentFlag.AlignCenter) hbox = QHBoxLayout() num_cubit_label = QLabel("number of cubit") self.num_cubit_text = QLineEdit(self) self.num_cubit_text.setToolTip("input 3 digits number") self.do_measure_checkbox = QCheckBox("do measure this circuit?", self) self.do_measure_checkbox.setToolTip("do measure all qubits") hbox.addWidget(num_cubit_label) hbox.addWidget(self.num_cubit_text) hbox.addWidget(self.do_measure_checkbox) vbox.addLayout(hbox) def get_input(self) -> Input: return MatrixInput( int(self.num_cubit_text.text()), self.do_measure_checkbox.isChecked() )
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector from qiskit.visualization import plot_bloch_multivector qc = QuantumCircuit(2) qc.h(0) qc.x(1) # You can reverse the order of the qubits. from qiskit.quantum_info import DensityMatrix qc = QuantumCircuit(2) qc.h([0, 1]) qc.t(1) qc.s(0) qc.cx(0,1) matrix = DensityMatrix(qc) plot_bloch_multivector(matrix, title='My Bloch Spheres', reverse_bits=True)
https://github.com/PabloMartinezAngerosa/QAOA-uniform-convergence
PabloMartinezAngerosa
import qiskit import numpy as np import networkx as nx import matplotlib.pyplot as plt from collections import defaultdict from operator import itemgetter from scipy.optimize import minimize from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer from qiskit.aqua.algorithms import NumPyEigensolver from qiskit.quantum_info import Pauli from qiskit.aqua.operators import op_converter from qiskit.aqua.operators import WeightedPauliOperator from tsp_qaoa import marina_solution G=nx.Graph() i=1 G.add_node(i,pos=(i,i)) G.add_node(2,pos=(2,2)) G.add_node(3,pos=(1,0)) G.add_edge(1,2,weight=20.5) G.add_edge(1,3,weight=9.8) pos=nx.get_node_attributes(G,'pos') nx.draw(G,pos) labels = nx.get_edge_attributes(G,'weight') nx.draw_networkx_edge_labels(G,pos,edge_labels=labels) def append_zz_term(qc,q1,q2,gamma): qc.cx(q1,q2) qc.rz(2*gamma,q2) qc.cx(q1,q2) def get_cost_circuit(G,gamma): N=G.number_of_nodes() qc=QuantumCircuit(N,N) for i,j in G.edges(): append_zz_term(qc,i,j,gamma) return qc #print(get_cost_circuit(G,0.5)) def append_x_term(qc,q1,beta): qc.rx(2*beta,q1) def get_mixer_operator(G,beta): N=G.number_of_nodes() qc=QuantumCircuit(N,N) for n in G.nodes(): append_x_term(qc,n,beta) return qc #print(get_mixer_operator(G,0.5)) def get_QAOA_circuit(G,beta,gamma): assert(len(beta)==len(gamma)) N=G.number_of_nodes() qc=QuantumCircuit(N,N) qc.h(range(N)) p=len(beta) #aplicamos las p rotaciones for i in range(p): qc=qc.compose(get_cost_circuit(G,gamma[i])) qc=qc.compose(get_mixer_operator(G,beta[i])) qc.barrier(range(N)) qc.measure(range(N),range(N)) return qc print(get_QAOA_circuit(G,[0.5,0,6],[0.5,0,6])) def invert_counts(counts): return {k[::-1] :v for k,v in counts.items()} qc=get_QAOA_circuit(G,[0.5,0,6],[0.5,0,6]) backend=Aer.get_backend('qasm_simulator') job=execute(qc,backend) result=job.result() print(invert_counts(result.get_counts())) def maxcut_obj(x,G): cut=0 for i,j in G.edges(): if x[i]!=x[j]: cut = cut-1 return cut print(maxcut_obj("00011",G)) def compute_maxcut_energy(counts,G): energy=0 get_counts=0 total_counts=0 for meas, meas_count in counts.items(): obj_for_meas=maxcut_obj(meas,G) energy+=obj_for_meas*meas_count total_counts+=meas_count return energy/total_counts def get_black_box_objective(G,p): backend=Aer.get_backend('qasm_simulator') def f(theta): beta=theta[:p] gamma=theta[p:] qc=get_QAOA_circuit(G,beta,gamma) counts=execute(qc,backend,seed_simulator=10).result().get_counts() return compute_maxcut_energy(invert_counts(counts),G) return f p=5 obj=get_black_box_objective(G,p) init_point=np.array([0.8,2.2,0.83,2.15,0.37,2.4,6.1,2.2,3.8,6.1])#([2,2,1,1,1,1,1,1,1,1]) res_sample=minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True}) res_sample from thirdParty.classical import rand_graph, classical, bitstring_to_path, calc_cost from utils import mapeo_grafo cantidad_ciudades = 4 pesos, conexiones = None, None mejor_camino = None while not mejor_camino: pesos, conexiones = rand_graph(cantidad_ciudades) mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False) G = mapeo_grafo(conexiones, pesos) pos=nx.spring_layout(G) nx.draw(G,pos) labels = nx.get_edge_attributes(G,'weight') nx.draw_networkx_edge_labels(G,pos,edge_labels=labels) G pos=nx.get_node_attributes(G,'weight') pos labels = nx.get_edge_attributes(G,'weight') labels def funcion_costo(multiplicador_lagrange, cantidad_ciudades, pesos, conexiones ): N = G.number_of_nodes() N_square = N^2 # restriccion 1 for i in range(cantidad_ciudades): cur = sI(N_square) for j in range(num_cities): cur -= D(i, j) ret += cur**2 # retorna el indice de qubit por conversion al problema def quibit_indice(i, l, N): return i * N + l from qiskit.quantum_info.operators import Operator, Pauli # Create an operator XX = Operator(Pauli(label='XX')) # Add to a circuit circ = QuantumCircuit(2, 2) circ.append(XX, [0, 1]) circ.measure([0,1], [0,1]) circ.draw('mpl') # Add to a circuit circ = QuantumCircuit(2, 2) circ.append(a, [0]) #circ.measure([0,1], [0,1]) circ.draw('mpl') a = I - ( 0.5*(I+ Z))**2 a = Operator(a) a.is_unitary() print(I @ Z)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import qiskit.qasm3 program = """ OPENQASM 3.0; include "stdgates.inc"; input float[64] a; qubit[3] q; bit[2] mid; bit[3] out; let aliased = q[0:1]; gate my_gate(a) c, t { gphase(a / 2); ry(a) c; cx c, t; } gate my_phase(a) c { ctrl @ inv @ gphase(a) c; } my_gate(a * 2) aliased[0], q[{1, 2}][0]; measure q[0] -> mid[0]; measure q[1] -> mid[1]; while (mid == "00") { reset q[0]; reset q[1]; my_gate(a) q[0], q[1]; my_phase(a - pi/2) q[1]; mid[0] = measure q[0]; mid[1] = measure q[1]; } if (mid[0]) { let inner_alias = q[{0, 1}]; reset inner_alias; } out = measure q; """ circuit = qiskit.qasm3.loads(program) circuit.draw("mpl")
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# useful additional packages import matplotlib.pyplot as plt import matplotlib.axes as axes %matplotlib inline import numpy as np import networkx as nx from qiskit import Aer from qiskit.tools.visualization import plot_histogram from qiskit_aqua import Operator, run_algorithm from qiskit_aqua.input import EnergyInput from qiskit_aqua.translators.ising import maxcut, tsp from qiskit_aqua.algorithms import VQE, ExactEigensolver from qiskit_aqua.components.optimizers import SPSA from qiskit_aqua.components.variational_forms import RY from qiskit_aqua import QuantumInstance # setup aqua logging import logging from qiskit_aqua import set_aqua_logging # set_aqua_logging(logging.DEBUG) # choose INFO, DEBUG to see the log from qiskit import IBMQ IBMQ.load_accounts() # Generating a graph of 4 nodes n=4 # Number of nodes in graph G=nx.Graph() G.add_nodes_from(np.arange(0,n,1)) elist=[(0,1,1.0),(0,2,1.0),(0,3,1.0),(1,2,1.0),(2,3,1.0)] # tuple is (i,j,weight) where (i,j) is the edge G.add_weighted_edges_from(elist) colors = ['r' for node in G.nodes()] pos = nx.spring_layout(G) default_axes = plt.axes(frameon=True) nx.draw_networkx(G, node_color=colors, node_size=600, alpha=.8, ax=default_axes, pos=pos) # Computing the weight matrix from the random graph w = np.zeros([n,n]) for i in range(n): for j in range(n): temp = G.get_edge_data(i,j,default=0) if temp != 0: w[i,j] = temp['weight'] print(w) best_cost_brute = 0 for b in range(2**n): x = [int(t) for t in reversed(list(bin(b)[2:].zfill(n)))] cost = 0 for i in range(n): for j in range(n): cost = cost + w[i,j]*x[i]*(1-x[j]) if best_cost_brute < cost: best_cost_brute = cost xbest_brute = x print('case = ' + str(x)+ ' cost = ' + str(cost)) colors = ['r' if xbest_brute[i] == 0 else 'b' for i in range(n)] nx.draw_networkx(G, node_color=colors, node_size=600, alpha=.8, pos=pos) print('\nBest solution = ' + str(xbest_brute) + ' cost = ' + str(best_cost_brute)) qubitOp, offset = maxcut.get_maxcut_qubitops(w) algo_input = EnergyInput(qubitOp) #Making the Hamiltonian in its full form and getting the lowest eigenvalue and eigenvector ee = ExactEigensolver(qubitOp, k=1) result = ee.run() """ algorithm_cfg = { 'name': 'ExactEigensolver', } params = { 'problem': {'name': 'ising'}, 'algorithm': algorithm_cfg } result = run_algorithm(params,algo_input) """ x = maxcut.sample_most_likely(result['eigvecs'][0]) print('energy:', result['energy']) print('maxcut objective:', result['energy'] + offset) print('solution:', maxcut.get_graph_solution(x)) print('solution objective:', maxcut.maxcut_value(x, w)) colors = ['r' if maxcut.get_graph_solution(x)[i] == 0 else 'b' for i in range(n)] nx.draw_networkx(G, node_color=colors, node_size=600, alpha = .8, pos=pos) seed = 10598 spsa = SPSA(max_trials=300) ry = RY(qubitOp.num_qubits, depth=5, entanglement='linear') vqe = VQE(qubitOp, ry, spsa, 'matrix') backend = Aer.get_backend('statevector_simulator') quantum_instance = QuantumInstance(backend=backend, seed=seed, seed_mapper=seed) result = vqe.run(quantum_instance) """declarative apporach algorithm_cfg = { 'name': 'VQE', 'operator_mode': 'matrix' } optimizer_cfg = { 'name': 'SPSA', 'max_trials': 300 } var_form_cfg = { 'name': 'RY', 'depth': 5, 'entanglement': 'linear' } params = { 'problem': {'name': 'ising', 'random_seed': seed}, 'algorithm': algorithm_cfg, 'optimizer': optimizer_cfg, 'variational_form': var_form_cfg, 'backend': {'name': 'statevector_simulator'} } result = run_algorithm(params, algo_input) """ x = maxcut.sample_most_likely(result['eigvecs'][0]) print('energy:', result['energy']) print('time:', result['eval_time']) print('maxcut objective:', result['energy'] + offset) print('solution:', maxcut.get_graph_solution(x)) print('solution objective:', maxcut.maxcut_value(x, w)) colors = ['r' if maxcut.get_graph_solution(x)[i] == 0 else 'b' for i in range(n)] nx.draw_networkx(G, node_color=colors, node_size=600, alpha = .8, pos=pos) # run quantum algorithm with shots seed = 10598 spsa = SPSA(max_trials=300) ry = RY(qubitOp.num_qubits, depth=5, entanglement='linear') vqe = VQE(qubitOp, ry, spsa, 'grouped_paulis') backend = Aer.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend=backend, shots=1024, seed=seed, seed_mapper=seed) result = vqe.run(quantum_instance) """declarative approach, update the param from the previous cell. params['algorithm']['operator_mode'] = 'grouped_paulis' params['backend']['name'] = 'qasm_simulator' params['backend']['shots'] = 1024 result = run_algorithm(params, algo_input) """ x = maxcut.sample_most_likely(result['eigvecs'][0]) print('energy:', result['energy']) print('time:', result['eval_time']) print('maxcut objective:', result['energy'] + offset) print('solution:', maxcut.get_graph_solution(x)) print('solution objective:', maxcut.maxcut_value(x, w)) plot_histogram(result['eigvecs'][0]) colors = ['r' if maxcut.get_graph_solution(x)[i] == 0 else 'b' for i in range(n)] nx.draw_networkx(G, node_color=colors, node_size=600, alpha = .8, pos=pos) # Generating a graph of 3 nodes n = 3 num_qubits = n ** 2 ins = tsp.random_tsp(n) G = nx.Graph() G.add_nodes_from(np.arange(0, n, 1)) colors = ['r' for node in G.nodes()] pos = {k: v for k, v in enumerate(ins.coord)} default_axes = plt.axes(frameon=True) nx.draw_networkx(G, node_color=colors, node_size=600, alpha=.8, ax=default_axes, pos=pos) print('distance\n', ins.w) from itertools import permutations def brute_force_tsp(w, N): a=list(permutations(range(1,N))) last_best_distance = 1e10 for i in a: distance = 0 pre_j = 0 for j in i: distance = distance + w[j,pre_j] pre_j = j distance = distance + w[pre_j,0] order = (0,) + i if distance < last_best_distance: best_order = order last_best_distance = distance print('order = ' + str(order) + ' Distance = ' + str(distance)) return last_best_distance, best_order best_distance, best_order = brute_force_tsp(ins.w, ins.dim) print('Best order from brute force = ' + str(best_order) + ' with total distance = ' + str(best_distance)) def draw_tsp_solution(G, order, colors, pos): G2 = G.copy() n = len(order) for i in range(n): j = (i + 1) % n G2.add_edge(order[i], order[j]) default_axes = plt.axes(frameon=True) nx.draw_networkx(G2, node_color=colors, node_size=600, alpha=.8, ax=default_axes, pos=pos) draw_tsp_solution(G, best_order, colors, pos) qubitOp, offset = tsp.get_tsp_qubitops(ins) algo_input = EnergyInput(qubitOp) #Making the Hamiltonian in its full form and getting the lowest eigenvalue and eigenvector ee = ExactEigensolver(qubitOp, k=1) result = ee.run() """ algorithm_cfg = { 'name': 'ExactEigensolver', } params = { 'problem': {'name': 'ising'}, 'algorithm': algorithm_cfg } result = run_algorithm(params,algo_input) """ print('energy:', result['energy']) #print('tsp objective:', result['energy'] + offset) x = tsp.sample_most_likely(result['eigvecs'][0]) print('feasible:', tsp.tsp_feasible(x)) z = tsp.get_tsp_solution(x) print('solution:', z) print('solution objective:', tsp.tsp_value(z, ins.w)) draw_tsp_solution(G, z, colors, pos) seed = 10598 spsa = SPSA(max_trials=300) ry = RY(qubitOp.num_qubits, depth=5, entanglement='linear') vqe = VQE(qubitOp, ry, spsa, 'matrix') backend = Aer.get_backend('statevector_simulator') quantum_instance = QuantumInstance(backend=backend, seed=seed, seed_mapper=seed) result = vqe.run(quantum_instance) """ algorithm_cfg = { 'name': 'VQE', 'operator_mode': 'matrix' } optimizer_cfg = { 'name': 'SPSA', 'max_trials': 300 } var_form_cfg = { 'name': 'RY', 'depth': 5, 'entanglement': 'linear' } params = { 'problem': {'name': 'ising', 'random_seed': seed}, 'algorithm': algorithm_cfg, 'optimizer': optimizer_cfg, 'variational_form': var_form_cfg, 'backend': {'name': 'statevector_simulator'} } result = run_algorithm(parahms,algo_input) """ print('energy:', result['energy']) print('time:', result['eval_time']) #print('tsp objective:', result['energy'] + offset) x = tsp.sample_most_likely(result['eigvecs'][0]) print('feasible:', tsp.tsp_feasible(x)) z = tsp.get_tsp_solution(x) print('solution:', z) print('solution objective:', tsp.tsp_value(z, ins.w)) draw_tsp_solution(G, z, colors, pos) # run quantum algorithm with shots seed = 10598 spsa = SPSA(max_trials=300) ry = RY(qubitOp.num_qubits, depth=5, entanglement='linear') vqe = VQE(qubitOp, ry, spsa, 'grouped_paulis', batch_mode=True) backend = Aer.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend=backend, shots=1024, seed=seed, seed_mapper=seed) result = vqe.run(quantum_instance) """update params in the previous cell params['algorithm']['operator_mode'] = 'grouped_paulis' params['backend']['name'] = 'qasm_simulator' params['backend']['shots'] = 1024 result = run_algorithm(params,algo_input) """ print('energy:', result['energy']) print('time:', result['eval_time']) #print('tsp objective:', result['energy'] + offset) x = tsp.sample_most_likely(result['eigvecs'][0]) print('feasible:', tsp.tsp_feasible(x)) z = tsp.get_tsp_solution(x) print('solution:', z) print('solution objective:', tsp.tsp_value(z, ins.w)) plot_histogram(result['eigvecs'][0]) draw_tsp_solution(G, z, colors, pos)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
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')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
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()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile from qiskit_aer import AerSimulator from qiskit.tools.visualization import plot_histogram import random circ = QuantumCircuit(40, 40) # Initialize with a Hadamard layer circ.h(range(40)) # Apply some random CNOT and T gates qubit_indices = [i for i in range(40)] for i in range(10): control, target, t = random.sample(qubit_indices, 3) circ.cx(control, target) circ.t(t) circ.measure(range(40), range(40)) # Create statevector method simulator statevector_simulator = AerSimulator(method='statevector') # Transpile circuit for backend tcirc = transpile(circ, statevector_simulator) # Try and run circuit statevector_result = statevector_simulator.run(tcirc, shots=1).result() print('This succeeded?: {}'.format(statevector_result.success)) print('Why not? {}'.format(statevector_result.status)) # Create extended stabilizer method simulator extended_stabilizer_simulator = AerSimulator(method='extended_stabilizer') # Transpile circuit for backend tcirc = transpile(circ, extended_stabilizer_simulator) extended_stabilizer_result = extended_stabilizer_simulator.run(tcirc, shots=1).result() print('This succeeded?: {}'.format(extended_stabilizer_result.success)) small_circ = QuantumCircuit(2, 2) small_circ.h(0) small_circ.cx(0, 1) small_circ.t(0) small_circ.measure([0, 1], [0, 1]) # This circuit should give 00 or 11 with equal probability... expected_results ={'00': 50, '11': 50} tsmall_circ = transpile(small_circ, extended_stabilizer_simulator) result = extended_stabilizer_simulator.run( tsmall_circ, shots=100).result() counts = result.get_counts(0) print('100 shots in {}s'.format(result.time_taken)) plot_histogram([expected_results, counts], legend=['Expected', 'Extended Stabilizer']) # Add runtime options for extended stabilizer simulator opts = {'extended_stabilizer_approximation_error': 0.03} reduced_error = extended_stabilizer_simulator.run( tsmall_circ, shots=100, **opts).result() reduced_error_counts = reduced_error.get_counts(0) print('100 shots in {}s'.format(reduced_error.time_taken)) plot_histogram([expected_results, reduced_error_counts], legend=['Expected', 'Extended Stabilizer']) print("The circuit above, with 100 shots at precision 0.03 " "and default mixing time, needed {}s".format(int(reduced_error.time_taken))) opts = { 'extended_stabilizer_approximation_error': 0.03, 'extended_stabilizer_mixing_time': 100 } optimized = extended_stabilizer_simulator.run( tsmall_circ, shots=100, **opts).result() print('Dialing down the mixing time, we completed in just {}s'.format(optimized.time_taken)) # We set these options here only to make the example run more quickly. opts = {'extended_stabilizer_mixing_time': 100} multishot = extended_stabilizer_simulator.run( tcirc, shots=100, **opts).result() print("100 shots took {} s".format(multishot.time_taken)) opts = { 'extended_stabilizer_measure_sampling': True, 'extended_stabilizer_mixing_time': 100 } measure_sampling = extended_stabilizer_simulator.run( circ, shots=100, **opts).result() print("With the optimization, 100 shots took {} s".format(result.time_taken)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np import matplotlib.pyplot as plt try: import cplex from cplex.exceptions import CplexError except: print("Warning: Cplex not found.") import math from qiskit.utils import algorithm_globals from qiskit.algorithms.minimum_eigensolvers import SamplingVQE from qiskit.algorithms.optimizers import SPSA from qiskit.circuit.library import RealAmplitudes from qiskit.primitives import Sampler # Initialize the problem by defining the parameters n = 3 # number of nodes + depot (n+1) K = 2 # number of vehicles # Get the data class Initializer: def __init__(self, n): self.n = n def generate_instance(self): n = self.n # np.random.seed(33) np.random.seed(1543) xc = (np.random.rand(n) - 0.5) * 10 yc = (np.random.rand(n) - 0.5) * 10 instance = np.zeros([n, n]) for ii in range(0, n): for jj in range(ii + 1, n): instance[ii, jj] = (xc[ii] - xc[jj]) ** 2 + (yc[ii] - yc[jj]) ** 2 instance[jj, ii] = instance[ii, jj] return xc, yc, instance # Initialize the problem by randomly generating the instance initializer = Initializer(n) xc, yc, instance = initializer.generate_instance() class ClassicalOptimizer: def __init__(self, instance, n, K): self.instance = instance self.n = n # number of nodes self.K = K # number of vehicles def compute_allowed_combinations(self): f = math.factorial return f(self.n) / f(self.K) / f(self.n - self.K) def cplex_solution(self): # refactoring instance = self.instance n = self.n K = self.K my_obj = list(instance.reshape(1, n**2)[0]) + [0.0 for x in range(0, n - 1)] my_ub = [1 for x in range(0, n**2 + n - 1)] my_lb = [0 for x in range(0, n**2)] + [0.1 for x in range(0, n - 1)] my_ctype = "".join(["I" for x in range(0, n**2)]) + "".join( ["C" for x in range(0, n - 1)] ) my_rhs = ( 2 * ([K] + [1 for x in range(0, n - 1)]) + [1 - 0.1 for x in range(0, (n - 1) ** 2 - (n - 1))] + [0 for x in range(0, n)] ) my_sense = ( "".join(["E" for x in range(0, 2 * n)]) + "".join(["L" for x in range(0, (n - 1) ** 2 - (n - 1))]) + "".join(["E" for x in range(0, n)]) ) try: my_prob = cplex.Cplex() self.populatebyrow(my_prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs) my_prob.solve() except CplexError as exc: print(exc) return x = my_prob.solution.get_values() x = np.array(x) cost = my_prob.solution.get_objective_value() return x, cost def populatebyrow(self, prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs): n = self.n prob.objective.set_sense(prob.objective.sense.minimize) prob.variables.add(obj=my_obj, lb=my_lb, ub=my_ub, types=my_ctype) prob.set_log_stream(None) prob.set_error_stream(None) prob.set_warning_stream(None) prob.set_results_stream(None) rows = [] for ii in range(0, n): col = [x for x in range(0 + n * ii, n + n * ii)] coef = [1 for x in range(0, n)] rows.append([col, coef]) for ii in range(0, n): col = [x for x in range(0 + ii, n**2, n)] coef = [1 for x in range(0, n)] rows.append([col, coef]) # Sub-tour elimination constraints: for ii in range(0, n): for jj in range(0, n): if (ii != jj) and (ii * jj > 0): col = [ii + (jj * n), n**2 + ii - 1, n**2 + jj - 1] coef = [1, 1, -1] rows.append([col, coef]) for ii in range(0, n): col = [(ii) * (n + 1)] coef = [1] rows.append([col, coef]) prob.linear_constraints.add(lin_expr=rows, senses=my_sense, rhs=my_rhs) # Instantiate the classical optimizer class classical_optimizer = ClassicalOptimizer(instance, n, K) # Print number of feasible solutions print("Number of feasible solutions = " + str(classical_optimizer.compute_allowed_combinations())) # Solve the problem in a classical fashion via CPLEX x = None z = None try: x, classical_cost = classical_optimizer.cplex_solution() # Put the solution in the z variable z = [x[ii] for ii in range(n**2) if ii // n != ii % n] # Print the solution print(z) except: print("CPLEX may be missing.") # Visualize the solution def visualize_solution(xc, yc, x, C, n, K, title_str): plt.figure() plt.scatter(xc, yc, s=200) for i in range(len(xc)): plt.annotate(i, (xc[i] + 0.15, yc[i]), size=16, color="r") plt.plot(xc[0], yc[0], "r*", ms=20) plt.grid() for ii in range(0, n**2): if x[ii] > 0: ix = ii // n iy = ii % n plt.arrow( xc[ix], yc[ix], xc[iy] - xc[ix], yc[iy] - yc[ix], length_includes_head=True, head_width=0.25, ) plt.title(title_str + " cost = " + str(int(C * 100) / 100.0)) plt.show() if x is not None: visualize_solution(xc, yc, x, classical_cost, n, K, "Classical") from qiskit_optimization import QuadraticProgram from qiskit_optimization.algorithms import MinimumEigenOptimizer class QuantumOptimizer: def __init__(self, instance, n, K): self.instance = instance self.n = n self.K = K def binary_representation(self, x_sol=0): instance = self.instance n = self.n K = self.K A = np.max(instance) * 100 # A parameter of cost function # Determine the weights w instance_vec = instance.reshape(n**2) w_list = [instance_vec[x] for x in range(n**2) if instance_vec[x] > 0] w = np.zeros(n * (n - 1)) for ii in range(len(w_list)): w[ii] = w_list[ii] # Some variables I will use Id_n = np.eye(n) Im_n_1 = np.ones([n - 1, n - 1]) Iv_n_1 = np.ones(n) Iv_n_1[0] = 0 Iv_n = np.ones(n - 1) neg_Iv_n_1 = np.ones(n) - Iv_n_1 v = np.zeros([n, n * (n - 1)]) for ii in range(n): count = ii - 1 for jj in range(n * (n - 1)): if jj // (n - 1) == ii: count = ii if jj // (n - 1) != ii and jj % (n - 1) == count: v[ii][jj] = 1.0 vn = np.sum(v[1:], axis=0) # Q defines the interactions between variables Q = A * (np.kron(Id_n, Im_n_1) + np.dot(v.T, v)) # g defines the contribution from the individual variables g = ( w - 2 * A * (np.kron(Iv_n_1, Iv_n) + vn.T) - 2 * A * K * (np.kron(neg_Iv_n_1, Iv_n) + v[0].T) ) # c is the constant offset c = 2 * A * (n - 1) + 2 * A * (K**2) try: max(x_sol) # Evaluates the cost distance from a binary representation of a path fun = ( lambda x: np.dot(np.around(x), np.dot(Q, np.around(x))) + np.dot(g, np.around(x)) + c ) cost = fun(x_sol) except: cost = 0 return Q, g, c, cost def construct_problem(self, Q, g, c) -> QuadraticProgram: qp = QuadraticProgram() for i in range(n * (n - 1)): qp.binary_var(str(i)) qp.objective.quadratic = Q qp.objective.linear = g qp.objective.constant = c return qp def solve_problem(self, qp): algorithm_globals.random_seed = 10598 vqe = SamplingVQE(sampler=Sampler(), optimizer=SPSA(), ansatz=RealAmplitudes()) optimizer = MinimumEigenOptimizer(min_eigen_solver=vqe) result = optimizer.solve(qp) # compute cost of the obtained result _, _, _, level = self.binary_representation(x_sol=result.x) return result.x, level # Instantiate the quantum optimizer class with parameters: quantum_optimizer = QuantumOptimizer(instance, n, K) # Check if the binary representation is correct try: if z is not None: Q, g, c, binary_cost = quantum_optimizer.binary_representation(x_sol=z) print("Binary cost:", binary_cost, "classical cost:", classical_cost) if np.abs(binary_cost - classical_cost) < 0.01: print("Binary formulation is correct") else: print("Error in the binary formulation") else: print("Could not verify the correctness, due to CPLEX solution being unavailable.") Q, g, c, binary_cost = quantum_optimizer.binary_representation() print("Binary cost:", binary_cost) except NameError as e: print("Warning: Please run the cells above first.") print(e) qp = quantum_optimizer.construct_problem(Q, g, c) quantum_solution, quantum_cost = quantum_optimizer.solve_problem(qp) print(quantum_solution, quantum_cost) # Put the solution in a way that is compatible with the classical variables x_quantum = np.zeros(n**2) kk = 0 for ii in range(n**2): if ii // n != ii % n: x_quantum[ii] = quantum_solution[kk] kk += 1 # visualize the solution visualize_solution(xc, yc, x_quantum, quantum_cost, n, K, "Quantum") # and visualize the classical for comparison if x is not None: visualize_solution(xc, yc, x, classical_cost, n, K, "Classical") import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.transpiler.passes import RemoveBarriers circuit = QuantumCircuit(1) circuit.x(0) circuit.barrier() circuit.h(0) circuit = RemoveBarriers()(circuit) circuit.draw('mpl')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import torch from qiskit.utils import algorithm_globals algorithm_globals.random_seed = 123456 _ = torch.manual_seed(123456) # suppress output import numpy as np num_dim = 2 num_discrete_values = 8 num_qubits = num_dim * int(np.log2(num_discrete_values)) from scipy.stats import multivariate_normal coords = np.linspace(-2, 2, num_discrete_values) rv = multivariate_normal(mean=[0.0, 0.0], cov=[[1, 0], [0, 1]], seed=algorithm_globals.random_seed) grid_elements = np.transpose([np.tile(coords, len(coords)), np.repeat(coords, len(coords))]) prob_data = rv.pdf(grid_elements) prob_data = prob_data / np.sum(prob_data) import matplotlib.pyplot as plt from matplotlib import cm mesh_x, mesh_y = np.meshgrid(coords, coords) grid_shape = (num_discrete_values, num_discrete_values) fig, ax = plt.subplots(figsize=(9, 9), subplot_kw={"projection": "3d"}) prob_grid = np.reshape(prob_data, grid_shape) surf = ax.plot_surface(mesh_x, mesh_y, prob_grid, cmap=cm.coolwarm, linewidth=0, antialiased=False) fig.colorbar(surf, shrink=0.5, aspect=5) plt.show() from qiskit import QuantumCircuit from qiskit.circuit.library import EfficientSU2 qc = QuantumCircuit(num_qubits) qc.h(qc.qubits) ansatz = EfficientSU2(num_qubits, reps=6) qc.compose(ansatz, inplace=True) qc.decompose().draw("mpl") qc.num_parameters from qiskit.primitives import Sampler shots = 10000 sampler = Sampler(options={"shots": shots, "seed": algorithm_globals.random_seed}) from qiskit_machine_learning.connectors import TorchConnector from qiskit_machine_learning.neural_networks import SamplerQNN def create_generator() -> TorchConnector: qnn = SamplerQNN( circuit=qc, sampler=sampler, input_params=[], weight_params=qc.parameters, sparse=False, ) initial_weights = algorithm_globals.random.random(qc.num_parameters) return TorchConnector(qnn, initial_weights) from torch import nn class Discriminator(nn.Module): def __init__(self, input_size): super(Discriminator, self).__init__() self.linear_input = nn.Linear(input_size, 20) self.leaky_relu = nn.LeakyReLU(0.2) self.linear20 = nn.Linear(20, 1) self.sigmoid = nn.Sigmoid() def forward(self, input: torch.Tensor) -> torch.Tensor: x = self.linear_input(input) x = self.leaky_relu(x) x = self.linear20(x) x = self.sigmoid(x) return x generator = create_generator() discriminator = Discriminator(num_dim) def adversarial_loss(input, target, w): bce_loss = target * torch.log(input) + (1 - target) * torch.log(1 - input) weighted_loss = w * bce_loss total_loss = -torch.sum(weighted_loss) return total_loss from torch.optim import Adam lr = 0.01 # learning rate b1 = 0.7 # first momentum parameter b2 = 0.999 # second momentum parameter generator_optimizer = Adam(generator.parameters(), lr=lr, betas=(b1, b2), weight_decay=0.005) discriminator_optimizer = Adam( discriminator.parameters(), lr=lr, betas=(b1, b2), weight_decay=0.005 ) from IPython.display import clear_output def plot_training_progress(): # we don't plot if we don't have enough data if len(generator_loss_values) < 2: return clear_output(wait=True) fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(18, 9)) # Generator Loss ax1.set_title("Loss") ax1.plot(generator_loss_values, label="generator loss", color="royalblue") ax1.plot(discriminator_loss_values, label="discriminator loss", color="magenta") ax1.legend(loc="best") ax1.set_xlabel("Iteration") ax1.set_ylabel("Loss") ax1.grid() # Relative Entropy ax2.set_title("Relative entropy") ax2.plot(entropy_values) ax2.set_xlabel("Iteration") ax2.set_ylabel("Relative entropy") ax2.grid() plt.show() import time from scipy.stats import multivariate_normal, entropy n_epochs = 50 num_qnn_outputs = num_discrete_values**num_dim generator_loss_values = [] discriminator_loss_values = [] entropy_values = [] start = time.time() for epoch in range(n_epochs): valid = torch.ones(num_qnn_outputs, 1, dtype=torch.float) fake = torch.zeros(num_qnn_outputs, 1, dtype=torch.float) # Configure input real_dist = torch.tensor(prob_data, dtype=torch.float).reshape(-1, 1) # Configure samples samples = torch.tensor(grid_elements, dtype=torch.float) disc_value = discriminator(samples) # Generate data gen_dist = generator(torch.tensor([])).reshape(-1, 1) # Train generator generator_optimizer.zero_grad() generator_loss = adversarial_loss(disc_value, valid, gen_dist) # store for plotting generator_loss_values.append(generator_loss.detach().item()) generator_loss.backward(retain_graph=True) generator_optimizer.step() # Train Discriminator discriminator_optimizer.zero_grad() real_loss = adversarial_loss(disc_value, valid, real_dist) fake_loss = adversarial_loss(disc_value, fake, gen_dist.detach()) discriminator_loss = (real_loss + fake_loss) / 2 # Store for plotting discriminator_loss_values.append(discriminator_loss.detach().item()) discriminator_loss.backward() discriminator_optimizer.step() entropy_value = entropy(gen_dist.detach().squeeze().numpy(), prob_data) entropy_values.append(entropy_value) plot_training_progress() elapsed = time.time() - start print(f"Fit in {elapsed:0.2f} sec") with torch.no_grad(): generated_probabilities = generator().numpy() fig = plt.figure(figsize=(18, 9)) # Generated CDF gen_prob_grid = np.reshape(np.cumsum(generated_probabilities), grid_shape) ax1 = fig.add_subplot(1, 3, 1, projection="3d") ax1.set_title("Generated CDF") ax1.plot_surface(mesh_x, mesh_y, gen_prob_grid, linewidth=0, antialiased=False, cmap=cm.coolwarm) ax1.set_zlim(-0.05, 1.05) # Real CDF real_prob_grid = np.reshape(np.cumsum(prob_data), grid_shape) ax2 = fig.add_subplot(1, 3, 2, projection="3d") ax2.set_title("True CDF") ax2.plot_surface(mesh_x, mesh_y, real_prob_grid, linewidth=0, antialiased=False, cmap=cm.coolwarm) ax2.set_zlim(-0.05, 1.05) # Difference ax3 = fig.add_subplot(1, 3, 3, projection="3d") ax3.set_title("Difference between CDFs") ax3.plot_surface( mesh_x, mesh_y, real_prob_grid - gen_prob_grid, linewidth=2, antialiased=False, cmap=cm.coolwarm ) ax3.set_zlim(-0.05, 0.1) plt.show() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.transpiler.passes import RemoveBarriers circuit = QuantumCircuit(1) circuit.x(0) circuit.barrier() circuit.h(0) circuit = RemoveBarriers()(circuit) circuit.draw('mpl')
https://github.com/arnavdas88/QuGlassyIsing
arnavdas88
!pip install qiskit J = 4.0 B_x = 0.0 B_z = 0.0 import numpy as np from qiskit.providers.aer import AerSimulator, QasmSimulator from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import TwoLocal from qiskit.aqua.operators import * from qiskit.aqua import set_qiskit_aqua_logging, QuantumInstance from qiskit.aqua.algorithms import NumPyMinimumEigensolver, VQE, NumPyEigensolver from qiskit.circuit import QuantumCircuit, ParameterVector from qiskit.visualization import plot_histogram Hamiltonian = J * (Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^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atz = TwoLocal(num_qubits=36, rotation_blocks=['ry', 'rz'], entanglement_blocks=None, entanglement='full', reps=1, skip_unentangled_qubits=False, skip_final_rotation_layer=True) print(ansatz) backend = AerSimulator(method='matrix_product_state') quantum_instance = QuantumInstance(backend, shots = 8192, initial_layout = None, optimization_level = 3) optimizer = COBYLA(maxiter=10000, tol=0.000000001) vqe = VQE(Hamiltonian, ansatz, optimizer, include_custom = False) print('We are using:', quantum_instance.backend) vqe_result = vqe.run(quantum_instance) print(vqe['result']) plot_histogram(vqe_result['eigenstate']) import pickle filename = "2D_Ising_Model_CountsAF1.pkl" a = {'vqe_result': vqe_result} #This saves the data with open(filename, 'wb') as handle: pickle.dump(a, handle, protocol=pickle.HIGHEST_PROTOCOL) # This loads the data with open(filename, 'rb') as handle: b = pickle.load(handle)
https://github.com/kuehnste/QiskitTutorial
kuehnste
# Importing standard Qiskit libraries from qiskit import QuantumCircuit, execute, Aer from qiskit.visualization import * from qiskit.quantum_info import state_fidelity # Magic function to render plots in the notebook after the cell executing the plot command %matplotlib inline def run_on_qasm_simulator(quantum_circuit, num_shots): """Takes a circuit, the number of shots and a backend and returns the counts for running the circuit on the qasm_simulator backend.""" qasm_simulator = Aer.get_backend('qasm_simulator') job = execute(quantum_circuit, backend=qasm_simulator, shots=num_shots) result = job.result() counts = result.get_counts(quantum_circuit) return counts def oracle_f1(): "Oracle implementing function f1" qc = QuantumCircuit(3) qc.cnot(0,2) qc.cnot(1,2) qc.x(2) qc.cnot(1,2) qc.cnot(0,2) return qc def oracle_f2(): "Oracle implementing function f2" qc = QuantumCircuit(3) qc.cnot(0,2) qc.x(2) qc.cnot(1,2) return qc # We visualize the oracle # Create a quantum circuit for 3 qubits and 2 classical registers qc_deutch_josza_oracle1 = QuantumCircuit(3,2) # Add the Hadamard gate # Apply the oracle # Add the z-gate acting on the ancilla # Apply the oracle again # Add the Hadamard gate # Add measurement to the first two qubits qc_deutch_josza_oracle1.barrier() qc_deutch_josza_oracle1.measure(range(2),range(2)) # Visualize the circuit # The number of shots we use num_shots = 100 # Now we run the circuit # Visualize the results in form of a histogram # We visualize the oracle # Create a quantum circuit for 3 qubits and 2 classical registers qc_deutch_josza_oracle2 = QuantumCircuit(3,2) # Add the Hadamard gate # Apply the oracle # Add the z-gate acting on the ancilla # Apply the oracle again # Add the Hadamard gate # Add measurement to the first two qubits # Visualize the circuit # The number of shots we use num_shots = 100 # Now we run the circuit # Visualize the results in form of a histogram
https://github.com/qclib/qclib
qclib
# Copyright 2021 qclib project. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Test divide-and-conquer state preparation """ from unittest import TestCase import numpy as np from qiskit import ClassicalRegister from qiskit_aer import AerSimulator from qclib.state_preparation import DcspInitialize from qclib.util import measurement backend = AerSimulator() SHOTS = 8192 class TestInitialize(TestCase): """ Testing divide-and-conquer state preparation """ @staticmethod def dcsp_experiment(state): """ Run divide-and-conquer state preparation """ circuit = DcspInitialize(state).definition n_qubits = int(np.log2(len(state))) classical_register = ClassicalRegister(n_qubits) circuit.add_register(classical_register) return measurement(circuit, n_qubits, classical_register, backend, SHOTS) def test_dcsp(self): """ Testing divide-and-conquer state preparation """ vector = np.random.rand(16) + np.random.rand(16) * 1j vector = vector / np.linalg.norm(vector) state = TestInitialize.dcsp_experiment(vector) self.assertTrue(np.allclose(np.power(np.abs(vector), 2), state, rtol=1e-01, atol=0.005))
https://github.com/jdellaverson19/qiskit2020
jdellaverson19
# -*- 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 Deutsch-Jozsa algorithm. """ import logging import operator import numpy as np from qiskit import ClassicalRegister, QuantumCircuit from qiskit.aqua import AquaError, Pluggable, PluggableType, get_pluggable_class from qiskit.aqua.algorithms import QuantumAlgorithm from qiskit.aqua.utils import get_subsystem_density_matrix logger = logging.getLogger(__name__) class DeutschJozsa(QuantumAlgorithm): """The Deutsch-Jozsa algorithm.""" CONFIGURATION = { 'name': 'DeutschJozsa', 'description': 'Deutsch Jozsa', 'input_schema': { '$schema': 'http://json-schema.org/schema#', 'id': 'dj_schema', 'type': 'object', 'properties': { }, 'additionalProperties': False }, 'problems': ['functionevaluation'], 'depends': [ { 'pluggable_type': 'oracle', 'default': { 'name': 'TruthTableOracle', }, }, ], } def __init__(self, oracle): self.validate(locals()) super().__init__() self._oracle = oracle self._circuit = None self._ret = {} @classmethod def init_params(cls, params, algo_input): if algo_input is not None: raise AquaError("Input instance not supported.") oracle_params = params.get(Pluggable.SECTION_KEY_ORACLE) oracle = get_pluggable_class( PluggableType.ORACLE, oracle_params['name']).init_params(params) return cls(oracle) def construct_circuit(self, measurement=False): """ Construct the 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 """ if self._circuit is not None: return self._circuit # preoracle circuit qc_preoracle = QuantumCircuit( self._oracle.variable_register, self._oracle.output_register, ) qc_preoracle.h(self._oracle.variable_register) qc_preoracle.x(self._oracle.output_register) qc_preoracle.h(self._oracle.output_register) qc_preoracle.barrier() # oracle circuit qc_oracle = self._oracle.circuit # postoracle circuit qc_postoracle = QuantumCircuit( self._oracle.variable_register, self._oracle.output_register, ) qc_postoracle.h(self._oracle.variable_register) qc_postoracle.barrier() self._circuit = qc_preoracle + qc_oracle + qc_postoracle # measurement circuit if measurement: measurement_cr = ClassicalRegister(len(self._oracle.variable_register), name='m') self._circuit.add_register(measurement_cr) self._circuit.measure(self._oracle.variable_register, measurement_cr) return self._circuit def _run(self): if self._quantum_instance.is_statevector: qc = self.construct_circuit(measurement=False) result = self._quantum_instance.execute(qc) complete_state_vec = result.get_statevector(qc) variable_register_density_matrix = get_subsystem_density_matrix( complete_state_vec, range(len(self._oracle.variable_register), qc.width()) ) variable_register_density_matrix_diag = np.diag(variable_register_density_matrix) max_amplitude = max( variable_register_density_matrix_diag.min(), variable_register_density_matrix_diag.max(), key=abs ) max_amplitude_idx = np.where(variable_register_density_matrix_diag == max_amplitude)[0][0] top_measurement = np.binary_repr(max_amplitude_idx, len(self._oracle.variable_register)) else: qc = self.construct_circuit(measurement=True) measurement = self._quantum_instance.execute(qc).get_counts(qc) self._ret['measurement'] = measurement top_measurement = max(measurement.items(), key=operator.itemgetter(1))[0] self._ret['result'] = 'constant' if int(top_measurement) == 0 else 'balanced' return self._ret
https://github.com/Pitt-JonesLab/slam_decomposition
Pitt-JonesLab
from slam.hamiltonian import DeltaConversionGainHamiltonian import numpy as np # args = gphi_ab, gphi_ac, gphi_bc, g_ab, g_ac, g_bc, cphi_ab, cphi_ac, cphi_bc, c_ab, c_ac, c_bc # 12 parameters to hamitlonain # 10 constraints # instantiate hamiltonian ham = DeltaConversionGainHamiltonian() # ham.construct_U() with random variables, real valued args = np.random.rand(12) U = ham.construct_U(*args) from slam.utils.visualize import plotMatrix plotMatrix(U); # optimize the parameters from slam.basis import HamiltonianTemplate ht = HamiltonianTemplate(h=DeltaConversionGainHamiltonian()) ht.parameter_guess() ht.n_qubits = 3 # unitary cost function from slam.cost_function import SquareCost cost = SquareCost() # define target as a custom 8x8 matrix target = np.array( [ [1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], ] ) from slam.optimizer import TemplateOptimizer to = TemplateOptimizer(ht, objective=cost, override_fail=1) ret = to.approximate_target_U(target) ret_u = ham.construct_U(*ret.Xk) plotMatrix(ret_u); from qiskit import QuantumCircuit from qiskit.quantum_info import Operator qc = QuantumCircuit(3) qc.ccx(0, 1, 2) plotMatrix(Operator(qc).data) qc = QuantumCircuit(3) qc.cx(0, 2) qc.cx(1, 2) plotMatrix(Operator(qc).data); # gphi_ab, gphi_ac, gphi_bc, g_ab, g_ac, g_bc, cphi_ab, cphi_ac, cphi_bc, c_ab, c_ac, c_bc # construct a data class with the parameters from dataclasses import dataclass @dataclass class Params: gphi_ab: float gphi_ac: float gphi_bc: float g_ab: float g_ac: float g_bc: float cphi_ab: float cphi_ac: float cphi_bc: float c_ab: float c_ac: float c_bc: float # define a get function to return the parameters as a tuple def get(self): return ( self.gphi_ab, self.gphi_ac, self.gphi_bc, self.g_ab, self.g_ac, self.g_bc, self.cphi_ab, self.cphi_ac, self.cphi_bc, self.c_ab, self.c_ac, self.c_bc, ) # define a set all phi terms to 0 a = 2 * np.pi / np.sqrt(3) p = Params(a, a, a, 0, 0, 0, 0, 0, 0, 0, 0, 0) # construct the unitary U = ham.construct_U(*p.get()) plotMatrix(U); ! pip install python-constraint from constraint import * # # set up a constraint solver for the hamiltonian # import constraint # # set up the symbols # gphi_ab = 'gphi_ab' # gphi_ac = 'gphi_ac' # gphi_bc = 'gphi_bc' # g_ab = 'g_ab' # g_ac = 'g_ac' # g_bc = 'g_bc' # cphi_ab = 'cphi_ab' # cphi_ac = 'cphi_ac' # cphi_bc = 'cphi_bc' # c_ab = 'c_ab' # c_ac = 'c_ac' # c_bc = 'c_bc' # args = [gphi_ab, gphi_ac, gphi_bc, g_ab, g_ac, g_bc, cphi_ab, cphi_ac, cphi_bc, c_ab, c_ac, c_bc] # # put the symbols into Hamiltonian to build the U # U = DeltaConversionGainHamiltonian().construct_U(*args) # # set up the constraints on U # # 10 total constraints # # U is a 4x4 matrix # prob = constraint.Problem() # # U[0,0] = 1 # # U[3,3] = 1 # prob.addConstraint(lambda x: x == 1, [U[0,0]]) # prob.addConstraint(lambda x: x == 1, [U[3,3]]) # # elements between U[0:2, 0:3] are all zero # # U[0,1] = 0 # # U[0,2] = 0 # # U[1,1] = 0 # # U[1,2] = 0 # # U[2,1] = 0 # # U[2,2] = 0 # # U[3,1] = 0 # # U[3,2] = 0 # prob.addConstraint(lambda x: x == 0, [U[0,1]]) # prob.addConstraint(lambda x: x == 0, [U[0,2]]) # prob.addConstraint(lambda x: x == 0, [U[1,1]]) # prob.addConstraint(lambda x: x == 0, [U[1,2]]) # prob.addConstraint(lambda x: x == 0, [U[2,1]]) # prob.addConstraint(lambda x: x == 0, [U[2,2]]) # prob.addConstraint(lambda x: x == 0, [U[3,1]]) # prob.addConstraint(lambda x: x == 0, [U[3,2]]) # # now solve # prob.getSolutions()
https://github.com/jonasmaziero/computacao_quantica_qiskit
jonasmaziero
%run init.ipynb 1 + cos(2*pi/3) + 1j*sin(2*pi/3) + cos(4*pi/3) + 1j*sin(4*pi/3) 1 + cos(4*pi/3) + 1j*sin(4*pi/3) + cos(8*pi/3) + 1j*sin(8*pi/3) cos(2*pi/3), cos(4*pi/3)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017, 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 at level 1 (intermediate). This example shows how an intermediate user interacts with Terra. It builds some circuits and transpiles them with transpile options. It then makes a qobj object which is just a container to be run on a backend. The same qobj can be submitted to many backends (as shown). It is the user's responsibility to make sure it can be run (i.e. it conforms to the restrictions of the backend, if any). This is useful when you want to compare the same circuit on different backends without recompiling the whole circuit, or just want to change some runtime parameters. To control the passes that transform the circuit, we have a pass manager for the level 2 user. """ import pprint, time # Import the Qiskit modules from qiskit import IBMQ, BasicAer from qiskit import QiskitError from qiskit.circuit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit.compiler import transpile, assemble from qiskit.providers.ibmq import least_busy from qiskit.tools.monitor import job_monitor try: IBMQ.load_accounts() except: print("""WARNING: There's no connection with the API for remote backends. Have you initialized a file with your personal token? For now, there's only access to local simulator backends...""") try: # Create a Quantum and Classical Register and give them names. qubit_reg = QuantumRegister(2, name='q') clbit_reg = ClassicalRegister(2, name='c') # Making first circuit: bell state qc1 = QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc1.h(qubit_reg[0]) qc1.cx(qubit_reg[0], qubit_reg[1]) qc1.measure(qubit_reg, clbit_reg) # Making another circuit: superpositions qc2 = QuantumCircuit(qubit_reg, clbit_reg, name="superposition") qc2.h(qubit_reg) qc2.measure(qubit_reg, clbit_reg) # Setting up the backend print("(Aer Backends)") for backend in BasicAer.backends(): print(backend.status()) qasm_simulator = BasicAer.get_backend('qasm_simulator') # Compile and run the circuit on a real device backend # See a list of available remote backends print("\n(IBMQ Backends)") for backend in IBMQ.backends(): print(backend.status()) try: # select least busy available device and execute. least_busy_device = least_busy(IBMQ.backends(simulator=False)) except: print("All devices are currently unavailable.") print("Running on current least busy device: ", least_busy_device) # Transpile the circuits to make them compatible with the experimental backend [qc1_new, qc2_new] = transpile(circuits=[qc1, qc2], backend=least_busy_device) print("Bell circuit before transpile:") print(qc1.draw()) print("Bell circuit after transpile:") print(qc1_new.draw()) print("Superposition circuit before transpile:") print(qc2.draw()) print("Superposition circuit after transpile:") print(qc2_new.draw()) # Assemble the two circuits into a runnable qobj qobj = assemble([qc1_new, qc2_new], shots=1000) # Running qobj on the simulator sim_job = qasm_simulator.run(qobj) # Getting the result sim_result=sim_job.result() # Show the results print(sim_result.get_counts(qc1)) print(sim_result.get_counts(qc2)) # Running the job. exp_job = least_busy_device.run(qobj) job_monitor(exp_job) exp_result = exp_job.result() # Show the results print(exp_result.get_counts(qc1)) print(exp_result.get_counts(qc2)) except QiskitError as ex: print('There was an error in the circuit!. Error = {}'.format(ex))
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
import numpy as np from qiskit import Aer, IBMQ from qiskit.aqua import aqua_globals, QuantumInstance from qiskit.aqua.algorithms import QAOA from qiskit.aqua.components.optimizers import * from qiskit.quantum_info import Pauli from qiskit.aqua.operators import WeightedPauliOperator from qiskit.providers.aer.noise import NoiseModel provider = IBMQ.load_account() def get_operator(J,h,n): pauli_list = [] for (i,j) in J: # For each coefficient in J (couplings) we add a term J[i,j]Z_iZj x_p = np.zeros(n, dtype=np.bool) z_p = np.zeros(n, dtype=np.bool) z_p[n-1-i] = True z_p[n-1-j] = True pauli_list.append([J[(i,j)],Pauli(z_p, x_p)]) for i in h: # For each coefficient in h we add a term h[i]Z_i x_p = np.zeros(n, dtype=np.bool) z_p = np.zeros(n, dtype=np.bool) z_p[n-1-i] = True pauli_list.append([h[i],Pauli(z_p, x_p)]) return WeightedPauliOperator(paulis=pauli_list) # Edges of the graph J1 = {(0,1):1, (1,2):1, (2,3):1, (3,4):1, (4,0):1} h1 = {} n = 5 # Hamiltonian q_op =get_operator(J1,h1,n) print(q_op) q_op.print_details() rep = 10 backend = Aer.get_backend('statevector_simulator') quantum_instance = QuantumInstance(backend) p = 1 val = 0 for i in range(rep): print("----- ITERATION ",i, " ------") optimizer = COBYLA() qaoa = QAOA(q_op, optimizer, p=p) result = qaoa.run(quantum_instance) print("Optimal value", result['optimal_value']) val+=result['optimal_value'] print("----- AVERAGE -----") print("Average value",val/rep) p = 2 val = 0 for i in range(rep): print("----- ITERATION ",i, " ------") optimizer = COBYLA() qaoa = QAOA(q_op, optimizer, p=p) result = qaoa.run(quantum_instance) print("Optimal value", result['optimal_value']) val+=result['optimal_value'] print("----- AVERAGE -----") print("Average value",val/rep) rep = 10 backendIBM = provider.get_backend('ibmq_ourense') noise_model = NoiseModel.from_backend(backendIBM) coupling_map = backendIBM.configuration().coupling_map basis_gates = noise_model.basis_gates backend = Aer.get_backend("qasm_simulator") shots = 8192 optimization_level = 3 p = 1 quantum_instance = QuantumInstance(backend, shots = shots, optimization_level = optimization_level, noise_model = noise_model, basis_gates = basis_gates, coupling_map = coupling_map) p = 1 val = 0 for i in range(rep): print("----- ITERATION ",i, " ------") optimizer = COBYLA() qaoa = QAOA(q_op, optimizer, p=p) result = qaoa.run(quantum_instance) print("Optimal value", result['optimal_value']) val+=result['optimal_value'] print("----- AVERAGE -----") print("Average value",val/rep)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the Scheduling/PadDelay passes""" import unittest from ddt import ddt, data, unpack from qiskit import QuantumCircuit from qiskit.circuit import Measure from qiskit.circuit.library import CXGate, HGate from qiskit.pulse import Schedule, Play, Constant, DriveChannel from qiskit.test import QiskitTestCase from qiskit.transpiler.instruction_durations import InstructionDurations from qiskit.transpiler.passes import ( ASAPScheduleAnalysis, ALAPScheduleAnalysis, PadDelay, SetIOLatency, ) from qiskit.transpiler.passmanager import PassManager from qiskit.transpiler.exceptions import TranspilerError from qiskit.transpiler.target import Target, InstructionProperties @ddt class TestSchedulingAndPaddingPass(QiskitTestCase): """Tests the Scheduling passes""" def test_alap_agree_with_reverse_asap_reverse(self): """Test if ALAP schedule agrees with doubly-reversed ASAP schedule.""" qc = QuantumCircuit(2) qc.h(0) qc.delay(500, 1) qc.cx(0, 1) qc.measure_all() durations = InstructionDurations( [("h", 0, 200), ("cx", [0, 1], 700), ("measure", None, 1000)] ) pm = PassManager([ALAPScheduleAnalysis(durations), PadDelay()]) alap_qc = pm.run(qc) pm = PassManager([ASAPScheduleAnalysis(durations), PadDelay()]) new_qc = pm.run(qc.reverse_ops()) new_qc = new_qc.reverse_ops() new_qc.name = new_qc.name self.assertEqual(alap_qc, new_qc) def test_alap_agree_with_reverse_asap_with_target(self): """Test if ALAP schedule agrees with doubly-reversed ASAP schedule.""" qc = QuantumCircuit(2) qc.h(0) qc.delay(500, 1) qc.cx(0, 1) qc.measure_all() target = Target(num_qubits=2, dt=3.5555555555555554) target.add_instruction(HGate(), {(0,): InstructionProperties(duration=200)}) target.add_instruction(CXGate(), {(0, 1): InstructionProperties(duration=700)}) target.add_instruction( Measure(), { (0,): InstructionProperties(duration=1000), (1,): InstructionProperties(duration=1000), }, ) pm = PassManager([ALAPScheduleAnalysis(target=target), PadDelay()]) alap_qc = pm.run(qc) pm = PassManager([ASAPScheduleAnalysis(target=target), PadDelay()]) new_qc = pm.run(qc.reverse_ops()) new_qc = new_qc.reverse_ops() new_qc.name = new_qc.name self.assertEqual(alap_qc, new_qc) @data(ALAPScheduleAnalysis, ASAPScheduleAnalysis) def test_classically_controlled_gate_after_measure(self, schedule_pass): """Test if ALAP/ASAP schedules circuits with c_if after measure with a common clbit. See: https://github.com/Qiskit/qiskit-terra/issues/7654 (input) β”Œβ”€β” q_0: ─Mβ”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β””β•₯β”˜ β”Œβ”€β”€β”€β” q_1: ─╫───── X β”œβ”€β”€β”€ β•‘ └─β•₯β”€β”˜ β•‘ β”Œβ”€β”€β”€β”€β•¨β”€β”€β”€β”€β” c: 1/═╩═║ c_0 = T β•ž 0 β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ (scheduled) β”Œβ”€β”β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” q_0: ────────────────────Mβ”œβ”€ Delay(200[dt]) β”œ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β””β•₯β”˜β””β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜ q_1: ─ Delay(1000[dt]) β”œβ”€β•«β”€β”€β”€β”€β”€β”€β”€β”€ X β”œβ”€β”€β”€β”€β”€β”€β”€ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β•‘ └─β•₯β”€β”˜ β•‘ β”Œβ”€β”€β”€β”€β•¨β”€β”€β”€β”€β” c: 1/════════════════════╩════║ c_0=0x1 β•žβ•β•β•β• 0 β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ """ qc = QuantumCircuit(2, 1) qc.measure(0, 0) qc.x(1).c_if(0, True) durations = InstructionDurations([("x", None, 200), ("measure", None, 1000)]) pm = PassManager([schedule_pass(durations), PadDelay()]) scheduled = pm.run(qc) expected = QuantumCircuit(2, 1) expected.measure(0, 0) expected.delay(1000, 1) # x.c_if starts after measure expected.x(1).c_if(0, True) expected.delay(200, 0) self.assertEqual(expected, scheduled) @data(ALAPScheduleAnalysis, ASAPScheduleAnalysis) def test_measure_after_measure(self, schedule_pass): """Test if ALAP/ASAP schedules circuits with measure after measure with a common clbit. See: https://github.com/Qiskit/qiskit-terra/issues/7654 (input) β”Œβ”€β”€β”€β”β”Œβ”€β” q_0: ─ X β”œβ”€Mβ”œβ”€β”€β”€ β””β”€β”€β”€β”˜β””β•₯β”˜β”Œβ”€β” q_1: ──────╫──Mβ”œ β•‘ β””β•₯β”˜ c: 1/══════╩══╩═ 0 0 (scheduled) β”Œβ”€β”€β”€β” β”Œβ”€β”β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” q_0: ──────── X β”œβ”€β”€β”€β”€β”€β”€β”€β”€Mβ”œβ”€ Delay(1000[dt]) β”œ β”Œβ”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”β””β•₯β”˜β””β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜ q_1: ─ Delay(1200[dt]) β”œβ”€β•«β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€Mβ”œβ”€β”€β”€β”€β”€β”€β”€β”€ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β•‘ β””β•₯β”˜ c: 1/════════════════════╩══════════╩═════════ 0 0 """ qc = QuantumCircuit(2, 1) qc.x(0) qc.measure(0, 0) qc.measure(1, 0) durations = InstructionDurations([("x", None, 200), ("measure", None, 1000)]) pm = PassManager([schedule_pass(durations), PadDelay()]) scheduled = pm.run(qc) expected = QuantumCircuit(2, 1) expected.x(0) expected.measure(0, 0) expected.delay(1200, 1) expected.measure(1, 0) expected.delay(1000, 0) self.assertEqual(expected, scheduled) @data(ALAPScheduleAnalysis, ASAPScheduleAnalysis) def test_c_if_on_different_qubits(self, schedule_pass): """Test if ALAP/ASAP schedules circuits with `c_if`s on different qubits. (input) β”Œβ”€β” q_0: ─Mβ”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β””β•₯β”˜ β”Œβ”€β”€β”€β” q_1: ─╫───── X β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β•‘ └─β•₯β”€β”˜ β”Œβ”€β”€β”€β” q_2: ─╫──────╫───────── X β”œβ”€β”€β”€ β•‘ β•‘ └─β•₯β”€β”˜ β•‘ β”Œβ”€β”€β”€β”€β•¨β”€β”€β”€β”€β”β”Œβ”€β”€β”€β”€β•¨β”€β”€β”€β”€β” c: 1/═╩═║ c_0 = T β•žβ•‘ c_0 = T β•ž 0 β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ (scheduled) β”Œβ”€β”β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” q_0: ────────────────────Mβ”œβ”€ Delay(200[dt]) β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β””β•₯β”˜β””β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜ q_1: ─ Delay(1000[dt]) β”œβ”€β•«β”€β”€β”€β”€β”€β”€β”€β”€ X β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β•‘ └─β•₯β”€β”˜ β”Œβ”€β”€β”€β” q_2: ─ Delay(1000[dt]) β”œβ”€β•«β”€β”€β”€β”€β”€β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ X β”œβ”€β”€β”€ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β•‘ β•‘ └─β•₯β”€β”˜ β•‘ β”Œβ”€β”€β”€β”€β•¨β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β•¨β”€β”€β”€β”€β” c: 1/════════════════════╩════║ c_0=0x1 β•žβ•β•β•β•β•‘ c_0=0x1 β•ž 0 β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ """ qc = QuantumCircuit(3, 1) qc.measure(0, 0) qc.x(1).c_if(0, True) qc.x(2).c_if(0, True) durations = InstructionDurations([("x", None, 200), ("measure", None, 1000)]) pm = PassManager([schedule_pass(durations), PadDelay()]) scheduled = pm.run(qc) expected = QuantumCircuit(3, 1) expected.measure(0, 0) expected.delay(1000, 1) expected.delay(1000, 2) expected.x(1).c_if(0, True) expected.x(2).c_if(0, True) expected.delay(200, 0) self.assertEqual(expected, scheduled) @data(ALAPScheduleAnalysis, ASAPScheduleAnalysis) def test_shorter_measure_after_measure(self, schedule_pass): """Test if ALAP/ASAP schedules circuits with shorter measure after measure with a common clbit. (input) β”Œβ”€β” q_0: ─Mβ”œβ”€β”€β”€ β””β•₯β”˜β”Œβ”€β” q_1: ─╫──Mβ”œ β•‘ β””β•₯β”˜ c: 1/═╩══╩═ 0 0 (scheduled) β”Œβ”€β”β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” q_0: ────────────────────Mβ”œβ”€ Delay(700[dt]) β”œ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β””β•₯β”˜β””β”€β”€β”€β”€β”€β”€β”¬β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜ q_1: ─ Delay(1000[dt]) β”œβ”€β•«β”€β”€β”€β”€β”€β”€β”€β”€β”€Mβ”œβ”€β”€β”€β”€β”€β”€β”€β”€ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β•‘ β””β•₯β”˜ c: 1/════════════════════╩═════════╩═════════ 0 0 """ qc = QuantumCircuit(2, 1) qc.measure(0, 0) qc.measure(1, 0) durations = InstructionDurations([("measure", [0], 1000), ("measure", [1], 700)]) pm = PassManager([schedule_pass(durations), PadDelay()]) scheduled = pm.run(qc) expected = QuantumCircuit(2, 1) expected.measure(0, 0) expected.delay(1000, 1) expected.measure(1, 0) expected.delay(700, 0) self.assertEqual(expected, scheduled) @data(ALAPScheduleAnalysis, ASAPScheduleAnalysis) def test_measure_after_c_if(self, schedule_pass): """Test if ALAP/ASAP schedules circuits with c_if after measure with a common clbit. (input) β”Œβ”€β” q_0: ─Mβ”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β””β•₯β”˜ β”Œβ”€β”€β”€β” q_1: ─╫───── X β”œβ”€β”€β”€β”€β”€β”€ β•‘ └─β•₯β”€β”˜ β”Œβ”€β” q_2: ─╫──────╫──────Mβ”œ β•‘ β”Œβ”€β”€β”€β”€β•¨β”€β”€β”€β”€β”β””β•₯β”˜ c: 1/═╩═║ c_0 = T β•žβ•β•©β• 0 β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ 0 (scheduled) β”Œβ”€β”β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” q_0: ────────────────────Mβ”œβ”€ Delay(1000[dt]) β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β””β•₯β”˜β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” q_1: ─ Delay(1000[dt]) β”œβ”€β•«β”€β”€β”€β”€β”€β”€β”€β”€β”€ X β”œβ”€β”€β”€β”€β”€β”€β”€β”€ Delay(800[dt]) β”œ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β•‘ └─β•₯β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”¬β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜ q_2: ─ Delay(1000[dt]) β”œβ”€β•«β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€Mβ”œβ”€β”€β”€β”€β”€β”€β”€β”€ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β•‘ β”Œβ”€β”€β”€β”€β•¨β”€β”€β”€β”€β” β””β•₯β”˜ c: 1/════════════════════╩═════║ c_0=0x1 β•žβ•β•β•β•β•β•β•β•β•β•β•β•β•©β•β•β•β•β•β•β•β•β• 0 β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ 0 """ qc = QuantumCircuit(3, 1) qc.measure(0, 0) qc.x(1).c_if(0, 1) qc.measure(2, 0) durations = InstructionDurations([("x", None, 200), ("measure", None, 1000)]) pm = PassManager([schedule_pass(durations), PadDelay()]) scheduled = pm.run(qc) expected = QuantumCircuit(3, 1) expected.delay(1000, 1) expected.delay(1000, 2) expected.measure(0, 0) expected.x(1).c_if(0, 1) expected.measure(2, 0) expected.delay(1000, 0) expected.delay(800, 1) self.assertEqual(expected, scheduled) def test_parallel_gate_different_length(self): """Test circuit having two parallel instruction with different length. (input) β”Œβ”€β”€β”€β”β”Œβ”€β” q_0: ─ X β”œβ”€Mβ”œβ”€β”€β”€ β”œβ”€β”€β”€β”€β””β•₯β”˜β”Œβ”€β” q_1: ─ X β”œβ”€β•«β”€β”€Mβ”œ β””β”€β”€β”€β”˜ β•‘ β””β•₯β”˜ c: 2/══════╩══╩═ 0 1 (expected, ALAP) β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β”Œβ”€β”€β”€β”β”Œβ”€β” q_0: ─ Delay(200[dt]) β”œβ”€ X β”œβ”€Mβ”œ β””β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜β””β”¬β”€β”¬β”˜β””β•₯β”˜ q_1: ─────── X β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€Mβ”œβ”€β”€β•«β”€ β””β”€β”€β”€β”˜ β””β•₯β”˜ β•‘ c: 2/════════════════════╩═══╩═ 1 0 (expected, ASAP) β”Œβ”€β”€β”€β”β”Œβ”€β”β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” q_0: ─ X β”œβ”€Mβ”œβ”€ Delay(200[dt]) β”œ β”œβ”€β”€β”€β”€β””β•₯β”˜β””β”€β”€β”€β”€β”€β”€β”¬β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜ q_1: ─ X β”œβ”€β•«β”€β”€β”€β”€β”€β”€β”€β”€β”€Mβ”œβ”€β”€β”€β”€β”€β”€β”€β”€ β””β”€β”€β”€β”˜ β•‘ β””β•₯β”˜ c: 2/══════╩═════════╩═════════ 0 1 """ qc = QuantumCircuit(2, 2) qc.x(0) qc.x(1) qc.measure(0, 0) qc.measure(1, 1) durations = InstructionDurations( [("x", [0], 200), ("x", [1], 400), ("measure", None, 1000)] ) pm = PassManager([ALAPScheduleAnalysis(durations), PadDelay()]) qc_alap = pm.run(qc) alap_expected = QuantumCircuit(2, 2) alap_expected.delay(200, 0) alap_expected.x(0) alap_expected.x(1) alap_expected.measure(0, 0) alap_expected.measure(1, 1) self.assertEqual(qc_alap, alap_expected) pm = PassManager([ASAPScheduleAnalysis(durations), PadDelay()]) qc_asap = pm.run(qc) asap_expected = QuantumCircuit(2, 2) asap_expected.x(0) asap_expected.x(1) asap_expected.measure(0, 0) # immediately start after X gate asap_expected.measure(1, 1) asap_expected.delay(200, 0) self.assertEqual(qc_asap, asap_expected) def test_parallel_gate_different_length_with_barrier(self): """Test circuit having two parallel instruction with different length with barrier. (input) β”Œβ”€β”€β”€β”β”Œβ”€β” q_0: ─ X β”œβ”€Mβ”œβ”€β”€β”€ β”œβ”€β”€β”€β”€β””β•₯β”˜β”Œβ”€β” q_1: ─ X β”œβ”€β•«β”€β”€Mβ”œ β””β”€β”€β”€β”˜ β•‘ β””β•₯β”˜ c: 2/══════╩══╩═ 0 1 (expected, ALAP) β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β”Œβ”€β”€β”€β” β–‘ β”Œβ”€β” q_0: ─ Delay(200[dt]) β”œβ”€ X β”œβ”€β–‘β”€β”€Mβ”œβ”€β”€β”€ β””β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”˜ β–‘ β””β•₯β”˜β”Œβ”€β” q_1: ─────── X β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–‘β”€β”€β•«β”€β”€Mβ”œ β””β”€β”€β”€β”˜ β–‘ β•‘ β””β•₯β”˜ c: 2/═══════════════════════════╩══╩═ 0 1 (expected, ASAP) β”Œβ”€β”€β”€β”β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β–‘ β”Œβ”€β” q_0: ─ X β”œβ”€ Delay(200[dt]) β”œβ”€β–‘β”€β”€Mβ”œβ”€β”€β”€ β”œβ”€β”€β”€β”€β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β–‘ β””β•₯β”˜β”Œβ”€β” q_1: ─ X β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–‘β”€β”€β•«β”€β”€Mβ”œ β””β”€β”€β”€β”˜ β–‘ β•‘ β””β•₯β”˜ c: 2/═══════════════════════════╩══╩═ 0 1 """ qc = QuantumCircuit(2, 2) qc.x(0) qc.x(1) qc.barrier() qc.measure(0, 0) qc.measure(1, 1) durations = InstructionDurations( [("x", [0], 200), ("x", [1], 400), ("measure", None, 1000)] ) pm = PassManager([ALAPScheduleAnalysis(durations), PadDelay()]) qc_alap = pm.run(qc) alap_expected = QuantumCircuit(2, 2) alap_expected.delay(200, 0) alap_expected.x(0) alap_expected.x(1) alap_expected.barrier() alap_expected.measure(0, 0) alap_expected.measure(1, 1) self.assertEqual(qc_alap, alap_expected) pm = PassManager([ASAPScheduleAnalysis(durations), PadDelay()]) qc_asap = pm.run(qc) asap_expected = QuantumCircuit(2, 2) asap_expected.x(0) asap_expected.delay(200, 0) asap_expected.x(1) asap_expected.barrier() asap_expected.measure(0, 0) asap_expected.measure(1, 1) self.assertEqual(qc_asap, asap_expected) def test_measure_after_c_if_on_edge_locking(self): """Test if ALAP/ASAP schedules circuits with c_if after measure with a common clbit. The scheduler is configured to reproduce behavior of the 0.20.0, in which clbit lock is applied to the end-edge of measure instruction. See https://github.com/Qiskit/qiskit-terra/pull/7655 (input) β”Œβ”€β” q_0: ─Mβ”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β””β•₯β”˜ β”Œβ”€β”€β”€β” q_1: ─╫───── X β”œβ”€β”€β”€β”€β”€β”€ β•‘ └─β•₯β”€β”˜ β”Œβ”€β” q_2: ─╫──────╫──────Mβ”œ β•‘ β”Œβ”€β”€β”€β”€β•¨β”€β”€β”€β”€β”β””β•₯β”˜ c: 1/═╩═║ c_0 = T β•žβ•β•©β• 0 β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ 0 (ASAP scheduled) β”Œβ”€β”β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” q_0: ────────────────────Mβ”œβ”€ Delay(200[dt]) β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β””β•₯β”˜β””β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜ q_1: ─ Delay(1000[dt]) β”œβ”€β•«β”€β”€β”€β”€β”€β”€β”€β”€ X β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β•‘ └─β•₯β”€β”˜ β”Œβ”€β”β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” q_2: ────────────────────╫─────────╫──────────Mβ”œβ”€ Delay(200[dt]) β”œ β•‘ β”Œβ”€β”€β”€β”€β•¨β”€β”€β”€β”€β” β””β•₯β”˜β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ c: 1/════════════════════╩════║ c_0=0x1 β•žβ•β•β•β•β•β•©β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β• 0 β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ 0 (ALAP scheduled) β”Œβ”€β”β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” q_0: ────────────────────Mβ”œβ”€ Delay(200[dt]) β”œβ”€β”€β”€ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β””β•₯β”˜β””β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜ q_1: ─ Delay(1000[dt]) β”œβ”€β•«β”€β”€β”€β”€β”€β”€β”€β”€ X β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ └┬───────────────── β•‘ └─β•₯β”€β”˜ β”Œβ”€β” q_2: ── Delay(200[dt]) β”œβ”€β•«β”€β”€β”€β”€β”€β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€Mβ”œ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β•‘ β”Œβ”€β”€β”€β”€β•¨β”€β”€β”€β”€β” β””β•₯β”˜ c: 1/════════════════════╩════║ c_0=0x1 β•žβ•β•β•β•β•β•©β• 0 β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ 0 """ qc = QuantumCircuit(3, 1) qc.measure(0, 0) qc.x(1).c_if(0, 1) qc.measure(2, 0) durations = InstructionDurations([("x", None, 200), ("measure", None, 1000)]) # lock at the end edge actual_asap = PassManager( [ SetIOLatency(clbit_write_latency=1000), ASAPScheduleAnalysis(durations), PadDelay(), ] ).run(qc) actual_alap = PassManager( [ SetIOLatency(clbit_write_latency=1000), ALAPScheduleAnalysis(durations), PadDelay(), ] ).run(qc) # start times of 2nd measure depends on ASAP/ALAP expected_asap = QuantumCircuit(3, 1) expected_asap.measure(0, 0) expected_asap.delay(1000, 1) expected_asap.x(1).c_if(0, 1) expected_asap.measure(2, 0) expected_asap.delay(200, 0) expected_asap.delay(200, 2) self.assertEqual(expected_asap, actual_asap) expected_alap = QuantumCircuit(3, 1) expected_alap.measure(0, 0) expected_alap.delay(1000, 1) expected_alap.x(1).c_if(0, 1) expected_alap.delay(200, 2) expected_alap.measure(2, 0) expected_alap.delay(200, 0) self.assertEqual(expected_alap, actual_alap) @data([100, 200], [500, 0], [1000, 200]) @unpack def test_active_reset_circuit(self, write_lat, cond_lat): """Test practical example of reset circuit. Because of the stimulus pulse overlap with the previous XGate on the q register, measure instruction is always triggered after XGate regardless of write latency. Thus only conditional latency matters in the scheduling. (input) β”Œβ”€β” β”Œβ”€β”€β”€β” β”Œβ”€β” β”Œβ”€β”€β”€β” β”Œβ”€β” β”Œβ”€β”€β”€β” q: ─Mβ”œβ”€β”€β”€β”€ X β”œβ”€β”€β”€β”€Mβ”œβ”€β”€β”€β”€ X β”œβ”€β”€β”€β”€Mβ”œβ”€β”€β”€β”€ X β”œβ”€β”€β”€ β””β•₯β”˜ └─β•₯β”€β”˜ β””β•₯β”˜ └─β•₯β”€β”˜ β””β•₯β”˜ └─β•₯β”€β”˜ β•‘ β”Œβ”€β”€β”€β”€β•¨β”€β”€β”€β”€β” β•‘ β”Œβ”€β”€β”€β”€β•¨β”€β”€β”€β”€β” β•‘ β”Œβ”€β”€β”€β”€β•¨β”€β”€β”€β”€β” c: 1/═╩═║ c_0=0x1 β•žβ•β•©β•β•‘ c_0=0x1 β•žβ•β•©β•β•‘ c_0=0x1 β•ž 0 β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ 0 β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ 0 β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ """ qc = QuantumCircuit(1, 1) qc.measure(0, 0) qc.x(0).c_if(0, 1) qc.measure(0, 0) qc.x(0).c_if(0, 1) qc.measure(0, 0) qc.x(0).c_if(0, 1) durations = InstructionDurations([("x", None, 100), ("measure", None, 1000)]) actual_asap = PassManager( [ SetIOLatency(clbit_write_latency=write_lat, conditional_latency=cond_lat), ASAPScheduleAnalysis(durations), PadDelay(), ] ).run(qc) actual_alap = PassManager( [ SetIOLatency(clbit_write_latency=write_lat, conditional_latency=cond_lat), ALAPScheduleAnalysis(durations), PadDelay(), ] ).run(qc) expected = QuantumCircuit(1, 1) expected.measure(0, 0) if cond_lat > 0: expected.delay(cond_lat, 0) expected.x(0).c_if(0, 1) expected.measure(0, 0) if cond_lat > 0: expected.delay(cond_lat, 0) expected.x(0).c_if(0, 1) expected.measure(0, 0) if cond_lat > 0: expected.delay(cond_lat, 0) expected.x(0).c_if(0, 1) self.assertEqual(expected, actual_asap) self.assertEqual(expected, actual_alap) def test_random_complicated_circuit(self): """Test scheduling complicated circuit with control flow. (input) β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β” β–‘ β”Œβ”€β”€β”€β” Β» q_0: ─ Delay(100[dt]) β”œβ”€β”€β”€β”€ X β”œβ”€β”€β”€β”€β–‘β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ X β”œβ”€β”€β”€Β» β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ └─β•₯β”€β”˜ β–‘ β”Œβ”€β”€β”€β” └─β•₯β”€β”˜ Β» q_1: ───────────────────────╫──────░──────── X β”œβ”€β”€β”€β”€β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€Β» β•‘ β–‘ β”Œβ”€β” └─β•₯β”€β”˜ β•‘ Β» q_2: ───────────────────────╫──────░──Mβ”œβ”€β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€Β» β”Œβ”€β”€β”€β”€β•¨β”€β”€β”€β”€β” β–‘ β””β•₯β”˜β”Œβ”€β”€β”€β”€β•¨β”€β”€β”€β”€β”β”Œβ”€β”€β”€β”€β•¨β”€β”€β”€β”€β”Β» c: 1/══════════════════║ c_0=0x1 β•žβ•β•β•β•β•©β•β•‘ c_0=0x0 β•žβ•‘ c_0=0x0 β•žΒ» β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ 0 β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜Β» Β« β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β”Œβ”€β”€β”€β” Β«q_0: ─ Delay(300[dt]) β”œβ”€ X β”œβ”€β”€β”€β”€β”€β– β”€β”€β”€β”€β”€ Β« β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”˜ β”Œβ”€β”΄β”€β” Β«q_1: ────────■────────────────── X β”œβ”€β”€β”€ Β« β”Œβ”€β”΄β”€β” β”Œβ”€β” └─β•₯β”€β”˜ Β«q_2: ─────── X β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€Mβ”œβ”€β”€β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€ Β« β””β”€β”€β”€β”˜ β””β•₯β”˜ β”Œβ”€β”€β”€β”€β•¨β”€β”€β”€β”€β” Β«c: 1/════════════════════╩══║ c_0=0x0 β•ž Β« 0 β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ (ASAP scheduled) duration = 2800 dt β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β” β–‘ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” Β» q_0: ─ Delay(200[dt]) β”œβ”€β”€β”€β”€ X β”œβ”€β”€β”€β”€β–‘β”€β”€ Delay(1400[dt]) β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€Β» β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ └─β•₯β”€β”˜ β–‘ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”Œβ”€β”€β”€β” Β» q_1: ─ Delay(300[dt]) β”œβ”€β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€β”€β–‘β”€β”€ Delay(1200[dt]) β”œβ”€β”€β”€β”€ X β”œβ”€β”€β”€Β» β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β•‘ β–‘ β””β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜ └─β•₯β”€β”˜ Β» q_2: ─ Delay(300[dt]) β”œβ”€β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€β”€β–‘β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€Mβ”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€Β» β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β”Œβ”€β”€β”€β”€β•¨β”€β”€β”€β”€β” β–‘ β””β•₯β”˜ β”Œβ”€β”€β”€β”€β•¨β”€β”€β”€β”€β”Β» c: 1/══════════════════║ c_0=0x1 β•žβ•β•β•β•β•β•β•β•β•β•β•β•β•©β•β•β•β•β•β•β•β•β•β•‘ c_0=0x0 β•žΒ» β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ 0 β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜Β» Β« β”Œβ”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β” Β» Β«q_0: ────────────────────── X β”œβ”€β”€β”€β”€ Delay(300[dt]) β”œβ”€β”€β”€β”€β”€β”€β”€ X β”œβ”€β”€β”€β”€β”€β”€β”€Β» Β« └─β•₯β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β”Œβ”€β”€β”€β”€β”€β”΄β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”Β» Β«q_1: ───────────────────────╫─────────────■────────── Delay(400[dt]) β”œΒ» Β« β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β•‘ β”Œβ”€β”΄β”€β” β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€Β» Β«q_2: ─ Delay(300[dt]) β”œβ”€β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ X β”œβ”€β”€β”€β”€β”€β”€β”€β”€ Delay(300[dt]) β”œΒ» Β« β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β”Œβ”€β”€β”€β”€β•¨β”€β”€β”€β”€β” β””β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜Β» Β«c: 1/══════════════════║ c_0=0x0 β•žβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•Β» Β« β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ Β» Β« β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” Β«q_0: ─────■────── Delay(700[dt]) β”œ Β« β”Œβ”€β”΄β”€β” β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ Β«q_1: ──── X β”œβ”€β”€β”€β”€ Delay(700[dt]) β”œ Β« └─β•₯β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”¬β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜ Β«q_2: ─────╫─────────────Mβ”œβ”€β”€β”€β”€β”€β”€β”€β”€ Β« β”Œβ”€β”€β”€β”€β•¨β”€β”€β”€β”€β” β””β•₯β”˜ Β«c: 1/β•‘ c_0=0x0 β•žβ•β•β•β•β•β•β•β•β•©β•β•β•β•β•β•β•β•β• Β« β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ 0 (ALAP scheduled) duration = 3100 β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β” β–‘ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” Β» q_0: ─ Delay(200[dt]) β”œβ”€β”€β”€β”€ X β”œβ”€β”€β”€β”€β–‘β”€β”€ Delay(1400[dt]) β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€Β» β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ └─β•₯β”€β”˜ β–‘ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”Œβ”€β”€β”€β” Β» q_1: ─ Delay(300[dt]) β”œβ”€β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€β”€β–‘β”€β”€ Delay(1200[dt]) β”œβ”€β”€β”€β”€ X β”œβ”€β”€β”€Β» β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β•‘ β–‘ β””β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜ └─β•₯β”€β”˜ Β» q_2: ─ Delay(300[dt]) β”œβ”€β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€β”€β–‘β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€Mβ”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€Β» β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β”Œβ”€β”€β”€β”€β•¨β”€β”€β”€β”€β” β–‘ β””β•₯β”˜ β”Œβ”€β”€β”€β”€β•¨β”€β”€β”€β”€β”Β» c: 1/══════════════════║ c_0=0x1 β•žβ•β•β•β•β•β•β•β•β•β•β•β•β•©β•β•β•β•β•β•β•β•β•β•‘ c_0=0x0 β•žΒ» β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ 0 β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜Β» Β« β”Œβ”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β” Β» Β«q_0: ────────────────────── X β”œβ”€β”€β”€β”€ Delay(300[dt]) β”œβ”€β”€β”€β”€β”€β”€β”€ X β”œβ”€β”€β”€β”€β”€β”€β”€Β» Β« β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” └─β•₯β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β”Œβ”€β”€β”€β”€β”€β”΄β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”Β» Β«q_1: ─ Delay(300[dt]) β”œβ”€β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ Delay(100[dt]) β”œΒ» Β« β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β•‘ β”Œβ”€β”΄β”€β” β””β”€β”€β”€β”€β”€β”€β”¬β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜Β» Β«q_2: ─ Delay(600[dt]) β”œβ”€β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ X β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€Mβ”œβ”€β”€β”€β”€β”€β”€β”€β”€Β» Β« β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β”Œβ”€β”€β”€β”€β•¨β”€β”€β”€β”€β” β””β”€β”€β”€β”˜ β””β•₯β”˜ Β» Β«c: 1/══════════════════║ c_0=0x0 β•žβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•©β•β•β•β•β•β•β•β•β•Β» Β« β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ 0 Β» Β« β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” Β«q_0: ─────■────── Delay(700[dt]) β”œ Β« β”Œβ”€β”΄β”€β” β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ Β«q_1: ──── X β”œβ”€β”€β”€β”€ Delay(700[dt]) β”œ Β« └─β•₯β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ Β«q_2: ─────╫─────────────────────── Β« β”Œβ”€β”€β”€β”€β•¨β”€β”€β”€β”€β” Β«c: 1/β•‘ c_0=0x0 β•žβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β• Β« β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ """ qc = QuantumCircuit(3, 1) qc.delay(100, 0) qc.x(0).c_if(0, 1) qc.barrier() qc.measure(2, 0) qc.x(1).c_if(0, 0) qc.x(0).c_if(0, 0) qc.delay(300, 0) qc.cx(1, 2) qc.x(0) qc.cx(0, 1).c_if(0, 0) qc.measure(2, 0) durations = InstructionDurations( [("x", None, 100), ("measure", None, 1000), ("cx", None, 200)] ) actual_asap = PassManager( [ SetIOLatency(clbit_write_latency=100, conditional_latency=200), ASAPScheduleAnalysis(durations), PadDelay(), ] ).run(qc) actual_alap = PassManager( [ SetIOLatency(clbit_write_latency=100, conditional_latency=200), ALAPScheduleAnalysis(durations), PadDelay(), ] ).run(qc) expected_asap = QuantumCircuit(3, 1) expected_asap.delay(200, 0) # due to conditional latency of 200dt expected_asap.delay(300, 1) expected_asap.delay(300, 2) expected_asap.x(0).c_if(0, 1) expected_asap.barrier() expected_asap.delay(1400, 0) expected_asap.delay(1200, 1) expected_asap.measure(2, 0) expected_asap.x(1).c_if(0, 0) expected_asap.x(0).c_if(0, 0) expected_asap.delay(300, 0) expected_asap.x(0) expected_asap.delay(300, 2) expected_asap.cx(1, 2) expected_asap.delay(400, 1) expected_asap.cx(0, 1).c_if(0, 0) expected_asap.delay(700, 0) # creg is released at t0 of cx(0,1).c_if(0,0) expected_asap.delay( 700, 1 ) # no creg write until 100dt. thus measure can move left by 300dt. expected_asap.delay(300, 2) expected_asap.measure(2, 0) self.assertEqual(expected_asap, actual_asap) self.assertEqual(actual_asap.duration, 3100) expected_alap = QuantumCircuit(3, 1) expected_alap.delay(200, 0) # due to conditional latency of 200dt expected_alap.delay(300, 1) expected_alap.delay(300, 2) expected_alap.x(0).c_if(0, 1) expected_alap.barrier() expected_alap.delay(1400, 0) expected_alap.delay(1200, 1) expected_alap.measure(2, 0) expected_alap.x(1).c_if(0, 0) expected_alap.x(0).c_if(0, 0) expected_alap.delay(300, 0) expected_alap.x(0) expected_alap.delay(300, 1) expected_alap.delay(600, 2) expected_alap.cx(1, 2) expected_alap.delay(100, 1) expected_alap.cx(0, 1).c_if(0, 0) expected_alap.measure(2, 0) expected_alap.delay(700, 0) expected_alap.delay(700, 1) self.assertEqual(expected_alap, actual_alap) self.assertEqual(actual_alap.duration, 3100) def test_dag_introduces_extra_dependency_between_conditionals(self): """Test dependency between conditional operations in the scheduling. In the below example circuit, the conditional x on q1 could start at time 0, however it must be scheduled after the conditional x on q0 in ASAP scheduling. That is because circuit model used in the transpiler passes (DAGCircuit) interprets instructions acting on common clbits must be run in the order given by the original circuit (QuantumCircuit). (input) β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β” q_0: ─ Delay(100[dt]) β”œβ”€β”€β”€β”€ X β”œβ”€β”€β”€ β””β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜ └─β•₯β”€β”˜ q_1: ─────── X β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€ └─β•₯β”€β”˜ β•‘ β”Œβ”€β”€β”€β”€β•¨β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β•¨β”€β”€β”€β”€β” c: 1/═══║ c_0=0x1 β•žβ•β•β•β•β•‘ c_0=0x1 β•ž β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ (ASAP scheduled) β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β” q_0: ─ Delay(100[dt]) β”œβ”€β”€β”€β”€ X β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ └─β•₯β”€β”˜ β”Œβ”€β”€β”€β” q_1: ─ Delay(100[dt]) β”œβ”€β”€β”€β”€β”€β•«β”€β”€β”€β”€β”€β”€β”€β”€β”€ X β”œβ”€β”€β”€ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β•‘ └─β•₯β”€β”˜ β”Œβ”€β”€β”€β”€β•¨β”€β”€β”€β”€β”β”Œβ”€β”€β”€β”€β•¨β”€β”€β”€β”€β” c: 1/══════════════════║ c_0=0x1 β•žβ•‘ c_0=0x1 β•ž β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ """ qc = QuantumCircuit(2, 1) qc.delay(100, 0) qc.x(0).c_if(0, True) qc.x(1).c_if(0, True) durations = InstructionDurations([("x", None, 160)]) pm = PassManager([ASAPScheduleAnalysis(durations), PadDelay()]) scheduled = pm.run(qc) expected = QuantumCircuit(2, 1) expected.delay(100, 0) expected.delay(100, 1) # due to extra dependency on clbits expected.x(0).c_if(0, True) expected.x(1).c_if(0, True) self.assertEqual(expected, scheduled) def test_scheduling_with_calibration(self): """Test if calibrated instruction can update node duration.""" qc = QuantumCircuit(2) qc.x(0) qc.cx(0, 1) qc.x(1) qc.cx(0, 1) xsched = Schedule(Play(Constant(300, 0.1), DriveChannel(0))) qc.add_calibration("x", (0,), xsched) durations = InstructionDurations([("x", None, 160), ("cx", None, 600)]) pm = PassManager([ASAPScheduleAnalysis(durations), PadDelay()]) scheduled = pm.run(qc) expected = QuantumCircuit(2) expected.x(0) expected.delay(300, 1) expected.cx(0, 1) expected.x(1) expected.delay(160, 0) expected.cx(0, 1) expected.add_calibration("x", (0,), xsched) self.assertEqual(expected, scheduled) def test_padding_not_working_without_scheduling(self): """Test padding fails when un-scheduled DAG is input.""" qc = QuantumCircuit(1, 1) qc.delay(100, 0) qc.x(0) qc.measure(0, 0) with self.assertRaises(TranspilerError): PassManager(PadDelay()).run(qc) def test_no_pad_very_end_of_circuit(self): """Test padding option that inserts no delay at the very end of circuit. This circuit will be unchanged after ASAP-schedule/padding. β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β”Œβ”€β” q_0: ─ Delay(100[dt]) β”œβ”€Mβ”œ β””β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜β””β•₯β”˜ q_1: ─────── X β”œβ”€β”€β”€β”€β”€β”€β”€β”€β•«β”€ β””β”€β”€β”€β”˜ β•‘ c: 1/═══════════════════╩═ 0 """ qc = QuantumCircuit(2, 1) qc.delay(100, 0) qc.x(1) qc.measure(0, 0) durations = InstructionDurations([("x", None, 160), ("measure", None, 1000)]) scheduled = PassManager( [ ASAPScheduleAnalysis(durations), PadDelay(fill_very_end=False), ] ).run(qc) self.assertEqual(scheduled, qc) @data(ALAPScheduleAnalysis, ASAPScheduleAnalysis) def test_respect_target_instruction_constraints(self, schedule_pass): """Test if DD pass does not pad delays for qubits that do not support delay instructions. See: https://github.com/Qiskit/qiskit-terra/issues/9993 """ qc = QuantumCircuit(3) qc.cx(1, 2) target = Target(dt=1) target.add_instruction(CXGate(), {(1, 2): InstructionProperties(duration=1000)}) # delays are not supported pm = PassManager([schedule_pass(target=target), PadDelay(target=target)]) scheduled = pm.run(qc) self.assertEqual(qc, scheduled) if __name__ == "__main__": unittest.main()
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from qiskit_chemistry import QiskitChemistry # Input dictionary to configure Qiskit Chemistry for the chemistry problem. qiskit_chemistry_dict = { 'problem': {'random_seed': 50}, 'driver': {'name': 'PYSCF'}, 'PYSCF': {'atom': 'O 0.0 0.0 0.0; H 0.757 0.586 0.0; H -0.757 0.586 0.0', 'basis': 'sto-3g'}, 'operator': {'name': 'hamiltonian', 'freeze_core': True}, 'algorithm': {'name': 'ExactEigensolver'} } solver = QiskitChemistry() result = solver.run(qiskit_chemistry_dict) print('Ground state energy: {}'.format(result['energy'])) for line in result['printable']: print(line) qiskit_chemistry_dict['algorithm']['name'] = 'VQE' qiskit_chemistry_dict['optimizer'] = {'name': 'COBYLA', 'maxiter': 25000} qiskit_chemistry_dict['variational_form'] = {'name': 'UCCSD'} qiskit_chemistry_dict['initial_state'] = {'name': 'HartreeFock'} solver = QiskitChemistry() result = solver.run(qiskit_chemistry_dict) print('Ground state energy: {}'.format(result['energy'])) for line in result['printable']: print(line) print('Actual VQE evaluations taken: {}'.format(result['algorithm_retvals']['eval_count']))
https://github.com/Tojarieh97/VQE
Tojarieh97
%load_ext autoreload %autoreload 2 import nbimporter from typing import Dict, Tuple, List import numpy as np from tqdm import tqdm QUBITS_NUM = 4 N = 2**QUBITS_NUM NUM_SHOTS = 1024 NUM_ITERATIONS = 100 CIRCUIT_DEPTH = 3 PARAMS_NUM = 2*QUBITS_NUM*(CIRCUIT_DEPTH+1) from qiskit import Aer from qiskit.utils import QuantumInstance, algorithm_globals seed = 50 algorithm_globals.random_seed = seed simulator_backend = Aer.get_backend('qasm_simulator') from scipy.optimize import minimize from linear_entangelment_and_full_entangelment_ansatz_circuits import * def get_ansatz_state(thetas, ansatz_entangelment, input_state): if ansatz_entangelment=="full": return get_full_entangelment_ansatz(QUBITS_NUM, thetas, input_state) if ansatz_entangelment=="linear": return get_linear_entangelment_ansatz(QUBITS_NUM, thetas, input_state) def transfrom_hamiltonian_into_pauli_strings(hamiltonian) -> List: pauli_operators = hamiltonian.to_pauli_op().settings['oplist'] pauli_coeffs = list(map(lambda pauli_operator: pauli_operator.coeff, pauli_operators)) pauli_strings = list(map(lambda pauli_operator: pauli_operator.primitive, pauli_operators)) return pauli_coeffs, pauli_strings from qiskit.circuit.library.standard_gates import HGate, SGate from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister reducing_to_pauli_z_mapping = { 'I': 'I', 'Z': 'Z', 'X': 'Z', 'Y': 'Z' } def reduce_pauli_matrixes_into_sigma_z(pauli_string) -> str: reduced_pauli_string = "" for matrix_index in range(QUBITS_NUM): pauli_matrix = str(pauli_string[matrix_index]) reduced_pauli_matrix = reducing_to_pauli_z_mapping[pauli_matrix] reduced_pauli_string = reduced_pauli_matrix + reduced_pauli_string return reduced_pauli_string def add_layer_of_gates_for_reducing_paulis_to_sigma_z(pauli_string, quantum_circuit): quantum_registers = QuantumRegister(QUBITS_NUM, name="qubit") additional_circuit_layer = QuantumCircuit(quantum_registers) for quantum_register_index, pauli_matrix in enumerate(pauli_string): if pauli_matrix == "X": additional_circuit_layer.append(HGate(), [quantum_registers[quantum_register_index]]) if pauli_string == "Y": additional_circuit_layer.append(HGate(), [quantum_registers[quantum_register_index]]) additional_circuit_layer.append(SGate(), [quantum_registers[quantum_register_index]]) extended_quantum_circuit = quantum_circuit.compose(additional_circuit_layer) return extended_quantum_circuit def get_probability_distribution(counts: Dict) -> Dict: proba_distribution = {state: (count / NUM_SHOTS) for state, count in counts.items()} return proba_distribution def calculate_probabilities_of_measurments_in_computational_basis(quantum_state_circuit) -> Dict: quantum_state_circuit.measure_all() transpiled_quantum_state_circuit = transpile(quantum_state_circuit, simulator_backend) Qobj = assemble(transpiled_quantum_state_circuit) result = simulator_backend.run(Qobj).result() counts = result.get_counts(quantum_state_circuit) return get_probability_distribution(counts) def sort_probas_dict_by_qubits_string_keys(proba_distribution: Dict) -> Dict: return dict(sorted(proba_distribution.items())) def reset_power_of_minus_1(power_of_minus_1): power_of_minus_1 = 0 return power_of_minus_1 def convert_pauli_string_into_str(pauli_string) -> str: return str(pauli_string) def calculate_expectation_value_of_pauli_string_by_measurments_probas(pauli_string, ansatz_circuit): pauli_string_expectation_value = 0 power_of_minus_1 = 0 pauli_string_str = convert_pauli_string_into_str(pauli_string) extended_ansatz_circuit = add_layer_of_gates_for_reducing_paulis_to_sigma_z(pauli_string_str, ansatz_circuit) probas_distribution = calculate_probabilities_of_measurments_in_computational_basis(extended_ansatz_circuit) reduced_pauli_string = reduce_pauli_matrixes_into_sigma_z(pauli_string) sorted_probas_distribuition = sort_probas_dict_by_qubits_string_keys(probas_distribution) for qubits_string, proba in sorted_probas_distribuition.items(): for string_index in range(QUBITS_NUM): if(str(qubits_string[string_index])=="1" and str(reduced_pauli_string[string_index])=="Z"): power_of_minus_1 += 1 pauli_string_expectation_value += pow(-1, power_of_minus_1)*proba power_of_minus_1 = reset_power_of_minus_1(power_of_minus_1) return pauli_string_expectation_value def get_expectation_value(ansatz_circuit, pauli_coeffs, pauli_strings): total_expection_value = 0 for pauli_coeff, pauli_string in tqdm(zip(pauli_coeffs, pauli_strings)): total_expection_value += pauli_coeff*calculate_expectation_value_of_pauli_string_by_measurments_probas( pauli_string, ansatz_circuit) return total_expection_value from qiskit import assemble, transpile def cost_function(thetas, hamiltonian, ansatz_entangelment): initial_eigenvector = np.identity(N)[0] pauli_coeffs, pauli_strings = transfrom_hamiltonian_into_pauli_strings(hamiltonian) ansatz_state = get_ansatz_state(thetas, ansatz_entangelment, initial_eigenvector) L = get_expectation_value(ansatz_state, pauli_coeffs, pauli_strings) insert_approximated_energy_to_list_of_all_approximated_energies(L) return L def get_optimal_thetas_of_ansatz_circuit_for_hamiltonian(hamiltonian, ansatz_entangelment): initial_thetas = np.random.uniform(low=0, high=2*np.pi, size=PARAMS_NUM) optimizer_result = minimize(cost_function, x0=initial_thetas, args=(hamiltonian, ansatz_entangelment), method="TNC", options={"maxiter":NUM_ITERATIONS, "disp": True}) optimal_thetas = optimizer_result.x return optimal_thetas def get_approximated_eigenvalue_of_hamiltonian(hamiltonian, ansatz_entangelment): optimal_thetas = get_optimal_thetas_of_ansatz_circuit_for_hamiltonian(hamiltonian, ansatz_entangelment) print(optimal_thetas) initial_eigenvector = np.identity(N)[0] optimal_ansatz_state = get_ansatz_state(optimal_thetas, ansatz_entangelment, initial_eigenvector) pauli_coeffs, pauli_strings = transfrom_hamiltonian_into_pauli_strings(hamiltonian) approximated_eigenvalue = get_expectation_value(optimal_ansatz_state, pauli_coeffs, pauli_strings) return approximated_eigenvalue from numpy import linalg as LA def get_approximation_error(exact_eigenvalue, approximated_eigenvalue): return abs(abs(exact_eigenvalue)-abs(approximated_eigenvalue))/abs(exact_eigenvalue) def get_minimum_exact_eigenvalue_of_hamiltonian(hamiltonian): eigen_values = LA.eigvals(hamiltonian.to_matrix()) print(sorted(eigen_values)) return min(sorted(eigen_values)) def compare_exact_and_approximated_eigenvalue(hamiltonian, approximated_eigenvalue): exact_eigenvalue = get_minimum_exact_eigenvalue_of_hamiltonian(hamiltonian) print("Exact Eigenvalue:") print(exact_eigenvalue) print("\nApproximated Eigenvalue:") print(approximated_eigenvalue) print("\nApproximation Error") print(get_approximation_error(exact_eigenvalue, approximated_eigenvalue)) plot_convergence_of_optimization_process(approximated_energies, exact_eigenvalue, margin=3) initialize_approximated_energy_to_list_of_all_approximated_energies() approximated_energies = [] def insert_approximated_energy_to_list_of_all_approximated_energies(energy): approximated_energies.append(energy) import matplotlib.pyplot as plt def plot_convergence_of_optimization_process(approximated_energies, exact_eigenvalue, margin): plt.title("convergence of optimization process to the exact eigenvalue") plt.margins(0, margin) plt.plot(approximated_energies[-NUM_ITERATIONS:]) plt.axhline(y = exact_eigenvalue, color = 'r', linestyle = '-') plt.grid() plt.xlabel("# of iterations") plt.ylabel("Energy") def plot_fidelity(): plt.plot(LiH_approximated_energies) plt.xlabel("# of iterations") plt.ylabel("Energy") from qiskit.opflow import X, Z, I, H, Y LiH_molecule_4_qubits = -7.49894690201071*(I^I^I^I) + \ -0.0029329964409502266*(X^X^Y^Y) + \ 0.0029329964409502266*(X^Y^Y^X) + \ 0.01291078027311749*(X^Z^X^I) + \ -0.0013743761078958677*(X^Z^X^Z) + \ 0.011536413200774975*(X^I^X^I) + \ 0.0029329964409502266*(Y^X^X^Y) + \ -0.0029329964409502266*(Y^Y^X^X) + \ 0.01291078027311749*(Y^Z^Y^I) + \ -0.0013743761078958677*(Y^Z^Y^Z) + \ 0.011536413200774975*(Y^I^Y^I) + \ 0.16199475388004184*(Z^I^I^I) + \ 0.011536413200774975*(Z^X^Z^X) + \ 0.011536413200774975*(Z^Y^Z^Y) + \ 0.12444770133137588*(Z^Z^I^I) + \ 0.054130445793298836*(Z^I^Z^I) + \ 0.05706344223424907*(Z^I^I^Z) + \ 0.012910780273117487*(I^X^Z^X) + \ -0.0013743761078958677*(I^X^I^X) + \ 0.012910780273117487*(I^Y^Z^Y) + \ -0.0013743761078958677*(I^Y^I^Y) + \ 0.16199475388004186*(I^Z^I^I) + \ 0.05706344223424907*(I^Z^Z^I) + \ 0.054130445793298836*(I^Z^I^Z) + \ -0.013243698330265966*(I^I^Z^I) + \ 0.08479609543670981*(I^I^Z^Z) + \ -0.013243698330265952*(I^I^I^Z) %%time LiH_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(LiH_molecule_4_qubits, "linear") compare_exact_and_approximated_eigenvalue(LiH_molecule_4_qubits, LiH_approximated_eigenvalue) %%time LiH_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(LiH_molecule_4_qubits, "full") compare_exact_and_approximated_eigenvalue(LiH_molecule_4_qubits, LiH_approximated_eigenvalue) H2_molecule_Hamiltonian_4_qubits = -0.8105479805373279 * (I^I^I^I) \ + 0.1721839326191554 * (I^I^I^Z) \ - 0.22575349222402372 * (I^I^Z^I) \ + 0.17218393261915543 * (I^Z^I^I) \ - 0.2257534922240237 * (Z^I^I^I) \ + 0.12091263261776627 * (I^I^Z^Z) \ + 0.16892753870087907 * (I^Z^I^Z) \ + 0.045232799946057826 * (Y^Y^Y^Y) \ + 0.045232799946057826 * (X^X^Y^Y) \ + 0.045232799946057826 * (Y^Y^X^X) \ + 0.045232799946057826 * (X^X^X^X) \ + 0.1661454325638241 * (Z^I^I^Z) \ + 0.1661454325638241 * (I^Z^Z^I) \ + 0.17464343068300453 * (Z^I^Z^I) \ + 0.12091263261776627 * (Z^Z^I^I) %%time H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_4_qubits, "linear") compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_4_qubits, H2_approximated_eigenvalue) %%time H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_4_qubits, "full") compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_4_qubits, H2_approximated_eigenvalue) transverse_ising_4_qubits = 0.0 * (I^I^I^I) \ + 0.8398088405253477 * (X^I^I^I) \ + 0.7989496312070936 * (I^X^I^I) \ + 0.38189710487113193 * (Z^Z^I^I) \ + 0.057753122422666725 * (I^I^X^I) \ + 0.5633292636970458 * (Z^I^Z^I) \ + 0.3152740621483513 * (I^Z^Z^I) \ + 0.07209487981989715 * (I^I^I^X) \ + 0.17892334004292654 * (Z^I^I^Z) \ + 0.2273896497668042 * (I^Z^I^Z) \ + 0.09762902934216211 * (I^I^Z^Z) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_4_qubits, "linear") compare_exact_and_approximated_eigenvalue(transverse_ising_4_qubits, TI_approximated_eigenvalue) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_4_qubits, "full") compare_exact_and_approximated_eigenvalue(transverse_ising_4_qubits, TI_approximated_eigenvalue) QUBITS_NUM = 3 N = 2**QUBITS_NUM NUM_SHOTS = 1024 NUM_ITERATIONS = 1000 CIRCUIT_DEPTH = 3 PARAMS_NUM = 2*QUBITS_NUM*(CIRCUIT_DEPTH+1) from qiskit.opflow import X, Z, I transverse_ising_3_qubits = 0.0 * (I^I^I) \ + 0.012764169333459807 * (X^I^I) \ + 0.7691573729160869 * (I^X^I) \ + 0.398094746026449 * (Z^Z^I) \ + 0.15250261906586637 * (I^I^X) \ + 0.2094051920882264 * (Z^I^Z) \ + 0.5131291860752999 * (I^Z^Z) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_3_qubits, "linear") compare_exact_and_approximated_eigenvalue(transverse_ising_3_qubits, TI_approximated_eigenvalue) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_3_qubits, "full") compare_exact_and_approximated_eigenvalue(transverse_ising_3_qubits, TI_approximated_eigenvalue) QUBITS_NUM = 2 N = 2**QUBITS_NUM NUM_SHOTS = 1024 NUM_ITERATIONS = 1000 CIRCUIT_DEPTH = 3 PARAMS_NUM = 2*QUBITS_NUM*(CIRCUIT_DEPTH+1) transverse_ising_2_qubits = 0.13755727363376802 * (I^X) \ + 0.43305656297810435 * (X^I) \ + 0.8538597608997253 * (Z^Z) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_2_qubits, "linear") compare_exact_and_approximated_eigenvalue(transverse_ising_2_qubits, TI_approximated_eigenvalue) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_2_qubits, "full") compare_exact_and_approximated_eigenvalue(transverse_ising_2_qubits, TI_approximated_eigenvalue) from qiskit.opflow import X, Z, I H2_molecule_Hamiltonian_2_qubits = -0.5053051899926562*(I^I) + \ -0.3277380754984016*(Z^I) + \ 0.15567463610622564*(Z^Z) + \ -0.3277380754984016*(I^Z) %%time H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_2_qubits, "linear") compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_2_qubits, H2_approximated_eigenvalue) %%time H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_2_qubits, "full") compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_2_qubits, H2_approximated_eigenvalue)
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. """ Gate described by the time evolution of a Hermitian Hamiltonian operator. """ from __future__ import annotations import math import typing from numbers import Number import numpy as np from qiskit import _numpy_compat from qiskit.circuit.gate import Gate from qiskit.circuit.quantumcircuit import QuantumCircuit from qiskit.circuit.quantumregister import QuantumRegister from qiskit.circuit.parameterexpression import ParameterExpression from qiskit.circuit.exceptions import CircuitError from qiskit.quantum_info.operators.predicates import matrix_equal from qiskit.quantum_info.operators.predicates import is_hermitian_matrix from .generalized_gates.unitary import UnitaryGate if typing.TYPE_CHECKING: from qiskit.quantum_info.operators.base_operator import BaseOperator class HamiltonianGate(Gate): r"""Class for representing evolution by a Hamiltonian operator as a gate. This gate resolves to a :class:`~.library.UnitaryGate` as :math:`U(t) = \exp(-i t H)`, which can be decomposed into basis gates if it is 2 qubits or less, or simulated directly in Aer for more qubits. """ def __init__( self, data: np.ndarray | Gate | BaseOperator, time: float | ParameterExpression, label: str | None = None, ) -> None: """ Args: data: A hermitian operator. time: Time evolution parameter. label: Unitary name for backend [Default: ``None``]. Raises: ValueError: if input data is not an N-qubit unitary operator. """ if hasattr(data, "to_matrix"): # If input is Gate subclass or some other class object that has # a to_matrix method this will call that method. data = data.to_matrix() elif hasattr(data, "to_operator"): # If input is a BaseOperator subclass this attempts to convert # the object to an Operator so that we can extract the underlying # numpy matrix from `Operator.data`. data = data.to_operator().data # Convert to np array in case not already an array data = np.asarray(data, dtype=complex) # Check input is unitary if not is_hermitian_matrix(data): raise ValueError("Input matrix is not Hermitian.") if isinstance(time, Number) and time != np.real(time): raise ValueError("Evolution time is not real.") # Check input is N-qubit matrix input_dim, output_dim = data.shape num_qubits = int(math.log2(input_dim)) if input_dim != output_dim or 2**num_qubits != input_dim: raise ValueError("Input matrix is not an N-qubit operator.") # Store instruction params super().__init__("hamiltonian", num_qubits, [data, time], label=label) def __eq__(self, other): if not isinstance(other, HamiltonianGate): return False if self.label != other.label: return False operators_eq = matrix_equal(self.params[0], other.params[0], ignore_phase=False) times_eq = self.params[1] == other.params[1] return operators_eq and times_eq def __array__(self, dtype=None, copy=None): """Return matrix for the unitary.""" import scipy.linalg if copy is False: raise ValueError("unable to avoid copy while creating an array as requested") try: time = float(self.params[1]) except TypeError as ex: raise TypeError( "Unable to generate Unitary matrix for " "unbound t parameter {}".format(self.params[1]) ) from ex arr = scipy.linalg.expm(-1j * self.params[0] * time) dtype = complex if dtype is None else dtype return np.array(arr, dtype=dtype, copy=_numpy_compat.COPY_ONLY_IF_NEEDED) def inverse(self, annotated: bool = False): """Return the adjoint of the unitary.""" return self.adjoint() def conjugate(self): """Return the conjugate of the Hamiltonian.""" return HamiltonianGate(np.conj(self.params[0]), -self.params[1]) def adjoint(self): """Return the adjoint of the unitary.""" return HamiltonianGate(self.params[0], -self.params[1]) def transpose(self): """Return the transpose of the Hamiltonian.""" return HamiltonianGate(np.transpose(self.params[0]), self.params[1]) def _define(self): """Calculate a subcircuit that implements this unitary.""" q = QuantumRegister(self.num_qubits, "q") qc = QuantumCircuit(q, name=self.name) qc._append(UnitaryGate(self.to_matrix()), q[:], []) self.definition = qc def validate_parameter(self, parameter): """Hamiltonian parameter has to be an ndarray, operator or float.""" if isinstance(parameter, (float, int, np.ndarray)): return parameter elif isinstance(parameter, ParameterExpression) and len(parameter.parameters) == 0: return float(parameter) else: raise CircuitError(f"invalid param type {type(parameter)} for gate {self.name}")
https://github.com/AasthaShayla/Qiskit-Teleportation
AasthaShayla
# Do the necessary imports import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import IBMQ, Aer, transpile, assemble from qiskit.visualization import plot_histogram, plot_bloch_multivector, array_to_latex from qiskit.extensions import Initialize from qiskit.ignis.verification import marginal_counts from qiskit.quantum_info import random_statevector # Loading your IBM Quantum account(s) provider = IBMQ.load_account() ## SETUP # Protocol uses 3 qubits and 2 classical bits in 2 different registers qr = QuantumRegister(3, name="q") # Protocol uses 3 qubits crz = ClassicalRegister(1, name="crz") # and 2 classical bits crx = ClassicalRegister(1, name="crx") # in 2 different registers teleportation_circuit = QuantumCircuit(qr, crz, crx) def create_bell_pair(qc, a, b): qc.h(a) qc.cx(a,b) qr = QuantumRegister(3, name="q") crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx") teleportation_circuit = QuantumCircuit(qr, crz, crx) create_bell_pair(teleportation_circuit, 1, 2) teleportation_circuit.draw() def alice_gates(qc, psi, a): qc.cx(psi, a) qc.h(psi) qr = QuantumRegister(3, name="q") crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx") teleportation_circuit = QuantumCircuit(qr, crz, crx) ## STEP 1 create_bell_pair(teleportation_circuit, 1, 2) ## STEP 2 teleportation_circuit.barrier() # Use barrier to separate steps alice_gates(teleportation_circuit, 0, 1) teleportation_circuit.draw() def measure_and_send(qc, a, b): """Measures qubits a & b and 'sends' the results to Bob""" qc.barrier() qc.measure(a,0) qc.measure(b,1) qr = QuantumRegister(3, name="q") crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx") teleportation_circuit = QuantumCircuit(qr, crz, crx) create_bell_pair(teleportation_circuit, 1, 2) teleportation_circuit.barrier() # Use barrier to separate steps alice_gates(teleportation_circuit, 0, 1) measure_and_send(teleportation_circuit, 0 ,1) teleportation_circuit.draw() def bob_gates(qc, qubit, crz, crx): qc.x(qubit).c_if(crx, 1) # Apply gates if the registers qc.z(qubit).c_if(crz, 1) # are in the state '1' qr = QuantumRegister(3, name="q") crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx") teleportation_circuit = QuantumCircuit(qr, crz, crx) ## STEP 1 create_bell_pair(teleportation_circuit, 1, 2) ## STEP 2 teleportation_circuit.barrier() # Use barrier to separate steps alice_gates(teleportation_circuit, 0, 1) ## STEP 3 measure_and_send(teleportation_circuit, 0, 1) ## STEP 4 teleportation_circuit.barrier() # Use barrier to separate steps bob_gates(teleportation_circuit, 2, crz, crx) teleportation_circuit.draw() # Create random 1-qubit state psi = random_statevector(2) # Display it nicely display(array_to_latex(psi, prefix="|\\psi\\rangle =")) # Show it on a Bloch sphere plot_bloch_multivector(psi) init_gate = Initialize(psi) init_gate.label = "init" ## SETUP qr = QuantumRegister(3, name="q") # Protocol uses 3 qubits crz = ClassicalRegister(1, name="crz") # and 2 classical registers crx = ClassicalRegister(1, name="crx") qc = QuantumCircuit(qr, crz, crx) ## STEP 0 # First, let's initialize Alice's q0 qc.append(init_gate, [0]) qc.barrier() ## STEP 1 # Now begins the teleportation protocol create_bell_pair(qc, 1, 2) qc.barrier() ## STEP 2 # Send q1 to Alice and q2 to Bob alice_gates(qc, 0, 1) ## STEP 3 # Alice then sends her classical bits to Bob measure_and_send(qc, 0, 1) ## STEP 4 # Bob decodes qubits bob_gates(qc, 2, crz, crx) # Display the circuit qc.draw() sim = Aer.get_backend('aer_simulator') qc.save_statevector() out_vector = sim.run(qc).result().get_statevector() plot_bloch_multivector(out_vector)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
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')
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=no-member,invalid-name,missing-docstring,no-name-in-module # pylint: disable=attribute-defined-outside-init,unsubscriptable-object import numpy as np from qiskit import assemble from qiskit import transpile from qiskit import Aer import qiskit.ignis.verification.randomized_benchmarking as rb from .tools import kraus_noise_model, no_noise, mixed_unitary_noise_model, \ reset_noise_model def build_rb_circuit(nseeds=1, length_vector=None, rb_pattern=None, length_multiplier=1, seed_offset=0, align_cliffs=False, seed=None): """ Randomized Benchmarking sequences. """ if not seed: np.random.seed(10) else: np.random.seed(seed) rb_opts = {} rb_opts['nseeds'] = nseeds rb_opts['length_vector'] = length_vector rb_opts['rb_pattern'] = rb_pattern rb_opts['length_multiplier'] = length_multiplier rb_opts['seed_offset'] = seed_offset rb_opts['align_cliffs'] = align_cliffs # Generate the sequences try: rb_circs, _ = rb.randomized_benchmarking_seq(**rb_opts) except OSError: skip_msg = ('Skipping tests because ' 'tables are missing') raise NotImplementedError(skip_msg) all_circuits = [] for seq in rb_circs: all_circuits += seq return all_circuits class RandomizedBenchmarkingQasmSimBenchmark: # parameters for RB (1&2 qubits): params = ([[[0]], [[0, 1]], [[0, 2], [1]]], ['statevector', 'density_matrix', 'stabilizer', 'extended_stabilizer', 'matrix_product_state'], [no_noise(), mixed_unitary_noise_model(), reset_noise_model(), kraus_noise_model()]) param_names = ['rb_pattern', 'simulator_method', 'noise_model'] version = '0.2.0' timeout = 600 def setup(self, rb_pattern, _, __): length_vector = np.arange(1, 200, 4) nseeds = 1 self.seed = 10 self.circuits = build_rb_circuit(nseeds=nseeds, length_vector=length_vector, rb_pattern=rb_pattern, seed=self.seed) self.sim_backend = Aer.get_backend('qasm_simulator') trans_circ = transpile(self.circuits, backend=self.sim_backend, seed_transpiler=self.seed) self.qobj = assemble(trans_circ, backend=self.sim_backend) def time_run_rb_circuit(self, _, simulator_method, noise_model): backend_options = { 'method': simulator_method, 'noise_model': noise_model(), } job = self.sim_backend.run(self.qobj, **backend_options) job.result() def peakmem_run_rb_circuit(self, _, simulator_method, noise_model): backend_options = { 'method': simulator_method, 'noise_model': noise_model(), } job = self.sim_backend.run(self.qobj, **backend_options) job.result()
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
import numpy as np from qiskit import QuantumCircuit, Aer, execute from qiskit.circuit.library import CCXGate, CXGate, CSwapGate, HGate, SwapGate, CPhaseGate from math import gcd from numpy.random import randint from fractions import Fraction from math import gcd # greatest common divisor N = 15 def c_amod15(a, power): """Controlled multiplication by a mod 15""" if a not in [2,7,8,11,13]: raise ValueError("'a' must be 2,7,8,11 or 13") U = QuantumCircuit(4) for iteration in range(power): if a in [2,13]: U.swap(0,1) U.swap(1,2) U.swap(2,3) if a in [7,8]: U.swap(2,3) U.swap(1,2) U.swap(0,1) if a == 11: U.swap(1,3) U.swap(0,2) if a in [7,11,13]: for q in range(4): U.x(q) U = U.to_gate() U.name = "%i^%i mod 15" % (a, power) c_U = U.control() return c_U def qft_dagger(n): qc = QuantumCircuit(n) # Don't forget the Swaps! for qubit in range(n//2): qc.swap(qubit, n-qubit-1) for j in range(n): for m in range(j): qc.cp(-np.pi/float(2**(j-m)), m, j) qc.h(j) qc.name = "QFT†" return qc def qpe_amod15(a): n_count = 8 qc = QuantumCircuit(4+n_count, n_count) for q in range(n_count): qc.h(q) # Initialize counting qubits in state |+> qc.x(3+n_count) # And auxiliary register in state |1> for q in range(n_count): # Do controlled-U operations qc.append(c_amod15(a, 2**q), [q] + [i+n_count for i in range(4)]) qc.append(qft_dagger(n_count), range(n_count)) # Do inverse-QFT qc.measure(range(n_count), range(n_count)) # Simulate Results aer_sim = Aer.get_backend('aer_simulator') # Setting memory=True below allows us to see a list of each sequential reading backend = Aer.get_backend('aer_simulator') job = execute(qc, backend, shots=1, memory=True) readings = job.result().get_memory() phase = int(readings[0],2)/(2**n_count) return phase def find_factor(coprime): a = coprime factor_found = False attempt = 0 factors = [] for i in range(30): attempt += 1 print("\nAttempt %i:" % attempt) phase = qpe_amod15(a) # Phase = s/r frac = Fraction(phase).limit_denominator(N) # Denominator should (hopefully!) tell us r r = frac.denominator print("Result: r = %i" % r) if phase != 0: # Guesses for factors are gcd(x^{r/2} Β±1 , 15) guesses = [gcd(a**(r//2)-1, N), gcd(a**(r//2)+1, N)] print("Guessed Factors: %i and %i" % (guesses[0], guesses[1])) for guess in guesses: if guess not in [1,N] and (N % guess) == 0: # Check to see if guess is a factor print("*** Non-trivial factor found: %i ***" % guess) factors += [guess] return factors
https://github.com/msramalho/grover-max-cut
msramalho
##Mar 1, 2019 # #code designed by Yasuhiro Okura and Takahiko Satoh and Miguel Ramalho and Lakshmi Prakash # useful additional packages import matplotlib.pyplot as plt import matplotlib.axes as axes %matplotlib inline import numpy as np import networkx as nx from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute %matplotlib inline # from qiskit import IBMQ #TODO from qiskit import LegacySimulators as Aer # Import Aer # from qiskit import BasicAer # qr = QuantumRegister(5, 'q') # cr = ClassicalRegister(5, 'c') # qc = QuantumCircuit(qr, cr) import random n = 4 # number of node edge_direct = random.randint(1, n) weight = 1.0 print(edge_direct) # define edges and weight # elist = [] # while len(elist)<3: # # print("success1") # e_start = random.randint(0, n-1)#it is used to define node connection # e_end = random.randint(0, n-1)#it is used to define node connection # # print("success2") # if e_start != e_end: # edge = (e_start, e_end, weight) # elist.append(edge) # print(elist) # print(elist) elist=[(2,3,1.0), (0, 1, 1.0)] G=nx.Graph() G.add_nodes_from(np.arange(0, n,1)) G.add_weighted_edges_from(elist) colors = ['r' for node in G.nodes()] pos = nx.spring_layout(G) default_axes = plt.axes(frameon=True) nx.draw_networkx(G, node_color=colors, node_size=600, alpha=.8, ax=default_axes, pos=pos) # Computing the weight matrix from the random graph w = np.zeros([n,n]) for i in range(n): for j in range(n): temp = G.get_edge_data(i,j,default=0) print(temp) if temp != 0: w[i,j] = temp["weight"] print(w) edges = list(G.edges) print(edges) while edges: i, j = edges.pop() # i = int(i) print(i, j) ## difine circuit num_x = n # num of node num_a = 1 num_b = 2 num_c = 1 x = QuantumRegister(num_x, "x") a = QuantumRegister(num_a, "a") b = QuantumRegister(num_b, "b") c = QuantumRegister(num_c, "c") cr = ClassicalRegister(4, "cr") qc = QuantumCircuit(x, a ,b, c, cr) #initialize graph weight #If Threshold >=2 : SUCCESS!! qc = QuantumCircuit(x, a ,b, c, cr) # qc.x(x[0]) # qc.x(x[1]) # qc.x(x[2]) # qc.x(x[3]) qc.h(x[0]) qc.h(x[1]) qc.h(x[2]) qc.h(x[3]) qc.h(c[0]) qc.barrier() qc.draw(output = "mpl") # colors = [] # colors = ['r' if xbest_brute[i] == 0 else 'b' for i in range(n)] # nx.draw_networkx(G, node_color=colors, node_size=600, alpha=.8, pos=pos) edges = list(G.edges) print(edges) ## V part(Oracle) def cut(qc, x, a, b, i, j): qc.cx(x[i], a) qc.cx(x[j], a) qc.ccx(a[0], b[0], b[1]) qc.cx(a[0], b[0]) qc.cx(x[j], a) qc.cx(x[i], a) ## V inverse def icut(qc, x, a, b, i, j): qc.cx(x[i], a) qc.cx(x[j], a) qc.cx(a[0], b[0]) qc.ccx(a[0], b[0], b[1]) qc.cx(x[j], a) qc.cx(x[i], a) def cnx(qc,*qubits): # C^n-NOT gate if len(qubits) > 3: last = qubits[-1] #A matrix: (made up of a and Y rotation, lemma4.3) qc.crz(np.pi/2, qubits[-2], qubits[-1]) #cry qc.cu3(np.pi/2, 0, 0, qubits[-2],qubits[-1]) #Control not gate cnx(qc,*qubits[:-2],qubits[-1]) #B matrix (cry again, but opposite angle) qc.cu3(-np.pi/2, 0, 0, qubits[-2], qubits[-1]) #Control cnx(qc,*qubits[:-2],qubits[-1]) #C matrix (final rotation) qc.crz(-np.pi/2,qubits[-2],qubits[-1]) elif len(qubits)==3: qc.ccx(*qubits) elif len(qubits)==2: qc.cx(*qubits) print(num_x) ## D part(Diffusion matrix) def diff(qc, N): # Diffusion matrix for k in range(N): qc.h(x[k]) qc.x(x[k]) # qc.h(x[3]) qc.h(x[3]) # cnx(qc, x[0], x[1], x[2], x[3]) cnx(qc, x[0], x[1], x[2], x[3]) # qc.h(x[3]) qc.h(x[3]) for k in range(N): qc.x(x[k]) qc.h(x[k]) # qc.h(x[k]) # qc.x(x[k]) # print(round(np.log(num_x))) # How many times execute V and D # for l in np.arange(round(np.log(num_x))): for l in np.arange(1): qc.barrier() for e in edges: i, j = e print(i, j) cut(qc, x, a, b, int(i), int(j)) # when we should apply int ? Is this right timing? print("success!") qc.barrier() qc.cz(b[1], c[0]) qc.barrier() for e in edges[::-1]: i, j = e print(i, j) icut(qc, x, a, b, int(i), int(j)) # when we should apply int ? Is this right timing? print("success!") qc.barrier() diff(qc, num_x) qc.barrier() qc.barrier() qc.h(c[0]) ## measurement for l in range(num_x): qc.measure(x[l], cr[l]) # qc.measure(a[0], cr[4]) # for m in range(num_a): # qc.measure(a[1], cr[num_x+m-1]) qc.draw(output = "mpl") from qiskit.tools.visualization import plot_histogram print("############ running on QASM simulater ############") backend = Aer.get_backend('qasm_simulator') ## StateVector Sim # Run the quantum circuit on a statevector simulator backend # backend = BasicAer.get_backend('statevector_simulator') # job_sim = execute(qc, backend=backend) # result = job_sim.result() # outputstate = result.get_statevector(qc, decimals=3) # print(outputstate) job_sim = execute(qc, backend=backend) result = job_sim.result() count = result.get_counts(qc) print(sorted(count.items(), key = lambda x: x[1],reverse=True)[0]) print(count) # from qiskit.tools.visualization import plot_state_city # plot_state_city(outputstate) plot_histogram(count) # TODO print("############ running on IBMQ ############")
https://github.com/Sinestro38/Generalized-Quantum-Fourier-Transform
Sinestro38
import numpy as np from numpy import pi from qiskit import QuantumCircuit, transpile, assemble, Aer, IBMQ from qiskit.providers.ibmq import least_busy from qiskit.tools.monitor import job_monitor from qiskit.visualization import plot_histogram, plot_bloch_multivector qc = QuantumCircuit(3) #Qiskit's least significant bit has the lowest index (0), thus the circuit will be mirrored through the horizontal qc.h(2) #Next, we want to turn this an extra quarter turn if qubit 1 is in the state |1> qc.cp(pi/2, 1, 2) # CROT from qubit 1 to qubit 2 #And another eighth turn if the least significant qubit (0) is |1> qc.cp(pi/4, 0, 2) # CROT from qubit 2 to qubit 0 qc.h(1) qc.cp(pi/2, 0, 1) # CROT from qubit 0 to qubit 1 qc.h(0) qc.swap(0,2) qc.draw() def qft_rotations(circuit, n): if n == 0: # Exit function if circuit is empty return circuit n -= 1 # Indexes start from 0 circuit.h(n) # Apply the H-gate to the most significant qubit for qubit in range(n): # For each less significant qubit, we need to do a # smaller-angled controlled rotation: circuit.cp(pi/2**(n-qubit), qubit, n) # At the end of our function, we call the same function again on # the next qubits (we reduced n by one earlier in the function) qft_rotations(circuit, n) def swap_registers(circuit, n): for qubit in range(n//2): circuit.swap(qubit, n-qubit-1) return circuit def qft(circuit, n): """QFT on the first n qubits in circuit""" qft_rotations(circuit, n) swap_registers(circuit, n) return circuit qc1 = QuantumCircuit(4) qft(qc1,4) qc1.draw() # Create the circuit qc = QuantumCircuit(3) # Encode the state 5 qc.x(0) # since we need '1' at first qubit and at last qubit qc.x(2) qc.draw() # And let's check the qubit's states using the aer simulator: sim = Aer.get_backend("aer_simulator") qc_init = qc.copy() # making a copy so that we can work on the original one qc_init.save_statevector() statevector = sim.run(qc_init).result().get_statevector() plot_bloch_multivector(statevector) # we can see the state below as '101' qft(qc,3) qc.draw() qc.save_statevector() statevector = sim.run(qc).result().get_statevector() plot_bloch_multivector(statevector) def inverse_qft(circuit, n): """Does the inverse QFT on the first n qubits in circuit""" # First we create a QFT circuit of the correct size: qft_circ = qft(QuantumCircuit(n), n) # Then we take the inverse of this circuit invqft_circ = qft_circ.inverse() # And add it to the first n qubits in our existing circuit circuit.append(invqft_circ, circuit.qubits[:n]) return circuit.decompose() # .decompose() allows us to see the individual gates nqubits = 3 number = 5 qc = QuantumCircuit(nqubits) for qubit in range(nqubits): qc.h(qubit) qc.p(number*pi/4,0) qc.p(number*pi/2,1) qc.p(number*pi,2) qc.draw() qc_init = qc.copy() qc_init.save_statevector() sim = Aer.get_backend("aer_simulator") statevector = sim.run(qc_init).result().get_statevector() plot_bloch_multivector(statevector) qc = inverse_qft(qc, nqubits) qc.measure_all() qc.draw() # Load our saved IBMQ accounts and get the least busy backend device with less than or equal to nqubits IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= nqubits and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) shots = 2048 transpiled_qc = transpile(qc, backend, optimization_level=3) job = backend.run(transpiled_qc, shots=shots) job_monitor(job) counts = job.result().get_counts() plot_histogram(counts)
https://github.com/urwin419/QiskitChecker
urwin419
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) qc.cx(1, 0) return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).issubset({0,1}): raise ValueError(f"message '{msg}' is invalid") if msg[1] == "1": qc.x(qubit) if msg[0] == "1": qc.z(qubit) ### added x gate ### qc.x(qubit) return qc def decode_message(qc): qc.cx(1, 0) ### added z gate ### qc.z(1) qc.h(1) return qc
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_optimization.algorithms import MinimumEigenOptimizer from qiskit.utils import algorithm_globals from qiskit.algorithms.minimum_eigensolvers import QAOA, NumPyMinimumEigensolver from qiskit.algorithms.optimizers import COBYLA from qiskit.primitives import Sampler from qiskit_optimization.applications.vertex_cover import VertexCover import networkx as nx seed = 123 algorithm_globals.random_seed = seed graph = nx.random_regular_graph(d=3, n=6, seed=seed) pos = nx.spring_layout(graph, seed=seed) prob = VertexCover(graph) prob.draw(pos=pos) qp = prob.to_quadratic_program() print(qp.prettyprint()) # Numpy Eigensolver meo = MinimumEigenOptimizer(min_eigen_solver=NumPyMinimumEigensolver()) result = meo.solve(qp) print(result.prettyprint()) print("\nsolution:", prob.interpret(result)) prob.draw(result, pos=pos) # QAOA meo = MinimumEigenOptimizer(min_eigen_solver=QAOA(reps=1, sampler=Sampler(), optimizer=COBYLA())) result = meo.solve(qp) print(result.prettyprint()) print("\nsolution:", prob.interpret(result)) print("\ntime:", result.min_eigen_solver_result.optimizer_time) prob.draw(result, pos=pos) from qiskit_optimization.applications import Knapsack prob = Knapsack(values=[3, 4, 5, 6, 7], weights=[2, 3, 4, 5, 6], max_weight=10) qp = prob.to_quadratic_program() print(qp.prettyprint()) # Numpy Eigensolver meo = MinimumEigenOptimizer(min_eigen_solver=NumPyMinimumEigensolver()) result = meo.solve(qp) print(result.prettyprint()) print("\nsolution:", prob.interpret(result)) # QAOA meo = MinimumEigenOptimizer(min_eigen_solver=QAOA(reps=1, sampler=Sampler(), optimizer=COBYLA())) result = meo.solve(qp) print(result.prettyprint()) print("\nsolution:", prob.interpret(result)) print("\ntime:", result.min_eigen_solver_result.optimizer_time) from qiskit_optimization.converters import QuadraticProgramToQubo # the same knapsack problem instance as in the previous section prob = Knapsack(values=[3, 4, 5, 6, 7], weights=[2, 3, 4, 5, 6], max_weight=10) qp = prob.to_quadratic_program() print(qp.prettyprint()) # intermediate QUBO form of the optimization problem conv = QuadraticProgramToQubo() qubo = conv.convert(qp) print(qubo.prettyprint()) # qubit Hamiltonian and offset op, offset = qubo.to_ising() print(f"num qubits: {op.num_qubits}, offset: {offset}\n") print(op) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/ranaarp/Qiskit-Meetup-content
ranaarp
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import IBMQ, Aer, execute IBMQ.load_account() q = QuantumRegister(3) qc = QuantumCircuit(q) #cutedge checker def ccheck(a, b, c): qc.cx(q[a], q[c]) qc.cx(q[b], q[c]) qc.h(q[0]) qc.h(q[1]) ccheck(0,1,2) qc.draw(output='mpl') q = QuantumRegister(8) qc = QuantumCircuit(q) #half adder #inputs: a,b #outputs: the sum output s and carry output c def hadder(a,b,s,c): #XOR qc.cx(q[b], q[s]) qc.cx(q[a], q[s]) #AND qc.ccx(q[a], q[b], q[c]) qc.h(q[0:3]) ccheck(0,1,3) ccheck(1,2,4) hadder(3,4,6,5) qc.draw(output='mpl') #create an oracle q = QuantumRegister(8) c = ClassicalRegister(1) qc = QuantumCircuit(q,c) qc.h(q[0:3]) ccheck(0,1,3) ccheck(1,2,4) hadder(3,4,6,5) qc.cx(q[5],q[7]) qc.measure(q[7], c[0]) backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend, shots=100000) result = job.result() count =result.get_counts() print(count) qc.draw(output='mpl') q = QuantumRegister(8) c = ClassicalRegister(7) qc = QuantumCircuit(q,c) #inverse operations def iccheck(a, b, c): qc.cx(q[b], q[c]) qc.cx(q[a], q[c]) def ihadder(a,b,s,c): qc.ccx(q[a], q[b], q[c]) qc.cx(q[a], q[s]) qc.cx(q[b], q[s]) qc.h(q[0:3]) qc.x(q[7]) qc.h(q[7]) ccheck(0,1,3) ccheck(1,2,4) hadder(3,4,6,5) qc.cx(q[5],q[7]) ihadder(3,4,6,5) iccheck(1,2,4) iccheck(0,1,3) qc.barrier() qc.measure(q[0:7], c[0:7]) backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend, shots=1000) result = job.result() count =result.get_counts() print(count) qc.draw(output='mpl') q = QuantumRegister(8) c = ClassicalRegister(3) qc = QuantumCircuit(q,c) #diffusion operations def diffusion(a,b,c): qc.h(q[a]) qc.h(q[b]) qc.h(q[c]) qc.x(q[a]) qc.x(q[b]) qc.x(q[c]) qc.h(q[c]) qc.ccx(q[a],q[b], q[c]) qc.h(q[c]) qc.x(q[a]) qc.x(q[b]) qc.x(q[c]) qc.h(q[a]) qc.h(q[b]) qc.h(q[c]) #initialization qc.h(q[0:3]) qc.x(q[7]) qc.h(q[7]) qc.barrier() #oracle part ccheck(0,1,3) ccheck(1,2,4) hadder(3,4,6,5) qc.cx(q[5],q[7]) ihadder(3,4,6,5) iccheck(1,2,4) iccheck(0,1,3) qc.barrier() #diffusion part diffusion(0,1,2) qc.barrier() qc.measure(q[0:3], c[0:3]) backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend, shots=10000) result = job.result() count =result.get_counts() print(count) qc.draw(output='mpl') #from qiskit.aqua.circuits.gates import mct q = QuantumRegister(11) c = ClassicalRegister(4) qc = QuantumCircuit(q,c) ite = 2 #number of iteration #initialization qc.h(q[0:4]) qc.x(q[8]) qc.h(q[8]) qc.barrier() for i in range(ite): #oracle part ccheck(0,1,4) ccheck(0,2,5) ccheck(0,3,6) qc.mct([q[4],q[5],q[6]], q[8] , [q[7]], mode='basic') iccheck(0,3,6) iccheck(0,2,5) iccheck(0,1,4) qc.barrier() #diffusion part qc.h(q[0:4]) qc.barrier() qc.x(q[0:4]) qc.barrier() qc.h(q[3]) qc.mct([q[0],q[1],q[2]], q[3] , [q[7]], mode='basic') qc.h(q[3]) qc.barrier() qc.x(q[0:4]) qc.barrier() qc.h(q[0:4]) qc.barrier() qc.measure(q[0:4], c[0:4]) backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend, shots=10000) result = job.result() count =result.get_counts() print(count) qc.draw(output='mpl') # the measurement results for each quantum state will be shown in reverse order. (i.e. 1000 -> 0001, 0111-> 1110) #Decompose the circuit by using the Unroller from qiskit.transpiler import PassManager from qiskit.transpiler.passes import Unroller pass_ = Unroller(['u3', 'cx']) pm = PassManager(pass_) new_circuit = pm.run(qc) new_circuit.draw(output='mpl') #show elementary gate counts new_circuit.count_ops() #create output text file with the gate counts import json dct = new_circuit.count_ops() with open('wk3_output.txt', 'w') as f: f.write(json.dumps(dct))
https://github.com/DuarteSerranoR/qiskit_quantum_algorithms
DuarteSerranoR
from qiskit import * from qiskit.extensions import * from qiskit.tools.visualization import * def XOR(inp1,inp2): """An XOR gate. Parameters: inpt1 (str): Input 1, encoded in qubit 0. inpt2 (str): Input 2, encoded in qubit 1. Returns: QuantumCircuit: Output XOR circuit. str: Output value measured from qubit 1. """ qc = QuantumCircuit(2, 1) qc.reset(range(2)) if inp1=='1': qc.x(0) if inp2=='1': qc.x(1) # barrier between input state and gate operation qc.barrier() # this is where your program for quantum XOR gate goes qc.cx(0,1) # barrier between input state and gate operation qc.barrier() qc.measure(1,0) # output from qubit 1 is measured #We'll run the program on a simulator backend = Aer.get_backend('aer_simulator') #Since the output will be deterministic, we can use just a single shot to get it job = backend.run(qc, shots=1, memory=True) output = job.result().get_memory()[0] return qc, output ## Test the function for inp1 in ['0', '1']: for inp2 in ['0', '1']: qc, output = XOR(inp1, inp2) print('XOR with inputs',inp1,inp2,'gives output',output) display(qc.draw()) print('\n')
https://github.com/MonitSharma/Learn-Quantum-Machine-Learning
MonitSharma
import pennylane as qml from pennylane import numpy as np dev = qml.device('default.mixed', wires = 2) @qml.qnode(dev) def circuit(): qml.Hadamard(wires = 0) qml.CNOT(wires = [0,1]) return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1)) print(f"QNode output = {circuit() :.4f}") print(f"Output state is = \n{np.real(dev.state)}") @qml.qnode(dev) def bitflip_circuit(p): qml.Hadamard(wires=0) qml.CNOT(wires=[0, 1]) qml.BitFlip(p, wires=0) qml.BitFlip(p, wires=1) return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1)) ps = [0.001, 0.01, 0.1, 0.2] for p in ps: print(f"QNode output for bit flip probability {p} is {bitflip_circuit(p):.4f}") print(f"Output state for bit flip probability {p} is \n{np.real(dev.state)}") @qml.qnode(dev) def depolarizing_circuit(p): qml.Hadamard(wires=0) qml.CNOT(wires=[0, 1]) qml.DepolarizingChannel(p, wires=0) qml.DepolarizingChannel(p, wires=1) return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1)) ps = [0.001, 0.01, 0.1, 0.2] for p in ps: print(f"QNode output for depolarizing probability {p} is {depolarizing_circuit(p):.4f}") ev = np.tensor(0.7781, requires_grad=False) # observed expectation value def sigmoid(x): return 1/(1+np.exp(-x)) @qml.qnode(dev) def damping_circuit(x): qml.Hadamard(wires=0) qml.CNOT(wires=[0, 1]) qml.AmplitudeDamping(sigmoid(x), wires=0) # p = sigmoid(x) qml.AmplitudeDamping(sigmoid(x), wires=1) return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1)) def cost(x, target): return (damping_circuit(x) - target)**2 opt = qml.GradientDescentOptimizer(stepsize=10) steps = 35 x = np.tensor(0.0, requires_grad=True) for i in range(steps): (x, ev), cost_val = opt.step_and_cost(cost, x, ev) if i % 5 == 0 or i == steps - 1: print(f"Step: {i} Cost: {cost_val}") print(f"QNode output after optimization = {damping_circuit(x):.4f}") print(f"Experimental expectation value = {ev}") print(f"Optimized noise parameter p = {sigmoid(x.take(0)):.4f}")
https://github.com/lynnlangit/learning-quantum
lynnlangit
# This cell is added by sphinx-gallery # It can be customized to whatever you like %matplotlib inline import pennylane as qml from pennylane import numpy as np dev1 = qml.device("default.qubit", wires=1) def circuit(params): qml.RX(params[0], wires=0) qml.RY(params[1], wires=0) return qml.expval(qml.PauliZ(0)) @qml.qnode(dev1) def circuit(params): qml.RX(params[0], wires=0) qml.RY(params[1], wires=0) return qml.expval(qml.PauliZ(0)) print(circuit([0.54, 0.12])) dcircuit = qml.grad(circuit, argnum=0) print(dcircuit([0.54, 0.12])) @qml.qnode(dev1) def circuit2(phi1, phi2): qml.RX(phi1, wires=0) qml.RY(phi2, wires=0) return qml.expval(qml.PauliZ(0)) dcircuit = qml.grad(circuit2, argnum=[0, 1]) print(dcircuit(0.54, 0.12)) def cost(x): return circuit(x) init_params = np.array([0.011, 0.012]) print(cost(init_params)) # initialise the optimizer opt = qml.GradientDescentOptimizer(stepsize=0.4) # set the number of steps steps = 100 # set the initial parameter values params = init_params for i in range(steps): # update the circuit parameters params = opt.step(cost, params) if (i + 1) % 5 == 0: print("Cost after step {:5d}: {: .7f}".format(i + 1, cost(params))) print("Optimized rotation angles: {}".format(params))
https://github.com/minminjao/qiskit1
minminjao
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, Aer, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * from qiskit.providers.aer import QasmSimulator # Loading your IBM Quantum account(s) provider = IBMQ.load_account() import numpy as np import qiskit as q qr = q.QuantumRegister(4) circ2 = q.QuantumCircuit(qr) ### encode the state 110 at first circ2.x(qr[0]) circ2.x(qr[1]) circ2.x(qr[2]) circ2.x(qr[3]) ### repeat what's done before ### add the first H gate (in qiskit east significant bit has the lowest index) circ2.h(qr[2]) ### add the controlled phase gate circ2.cp(np.pi/2, qr[1], qr[2]) # based on qubit 1 apply 2pi/2**(k-1) rotation to qubit 2 ### add the next cp gate circ2.cp(np.pi/4, qr[0], qr[2]) # based on qubit 0 apply 2pi/2**(k-1) rotation to qubit 2 ### repeat the process for qubit 1 circ2.h(qr[1]) circ2.cp(np.pi/2, qr[0], qr[1]) ### add the final h gate circ2.h(qr[0]) circ2.ry(np.pi / 4, qr[2]) circ2.ry(-np.pi /2 , qr[3]) circ2.rz(-np.pi/4, qr[3]) ### finally swap the bits 0 th, and 2nd qubit circ2.swap(qr[0], qr[2]) circ2.swap(qr[1],qr[2]) circ2.swap(qr[1],qr[3]) circ2.save_statevector() qasm_sim = q.Aer.get_backend('qasm_simulator') statevector = qasm_sim.run(circ2).result().get_statevector() q.visualization.plot_bloch_multivector(statevector) from qiskit import Aer, execute simulator = Aer.get_backend('qasm_simulator') counts = execute(circ2, backend=simulator, shots=1000).result().get_counts(circ2) from qiskit.visualization import plot_histogram plot_histogram(counts) import numpy as np import qiskit as q qr = q.QuantumRegister(4) circ = q.QuantumCircuit(qr) ### add the first H gate (in qiskit least significant bit has the lowest index) circ.h(qr[3]) ### add the controlled phase gate circ.cp(np.pi/2, qr[1], qr[2]) # based on qubit 1 apply 2pi/2**(k-1) rotation to qubit 2 ### add the next cp gate circ.cp(np.pi/4, qr[0], qr[2]) # based on qubit 0 apply 2pi/2**(k-1) rotation to qubit 2 ### repeat the process for qubit 1 circ.h(qr[1]) circ.cp(np.pi/2, qr[0], qr[1]) ### add the final h gate ### finally swap the bits 0 th, and 2nd qubit circ.swap(qr[0], qr[2])
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for 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/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from datasets import * from qiskit_aqua.utils import split_dataset_to_data_and_labels from qiskit_aqua.input import SVMInput from qiskit_aqua import run_algorithm import numpy as np feature_dim = 2 # dimension of each data point sample_Total, training_input, test_input, class_labels = Wine(training_size=20, test_size=10, n=feature_dim, PLOT_DATA=True) temp = [test_input[k] for k in test_input] total_array = np.concatenate(temp) aqua_dict = { 'problem': {'name': 'svm_classification'}, 'algorithm': { 'name': 'SVM' }, 'multiclass_extension': {'name': 'OneAgainstRest'} } algo_input = SVMInput(training_input, test_input, total_array) extensions = [ {'name': 'OneAgainstRest'}, {'name': 'AllPairs'}, {'name': 'ErrorCorrectingCode', 'code_size': 5} ] for extension in extensions: aqua_dict['multiclass_extension'] = extension result = run_algorithm(aqua_dict, algo_input) print("\n----- Using multiclass extension: '{}' -----\n".format(extension['name'])) for k,v in result.items(): print("'{}' : {}".format(k, v))
https://github.com/carstenblank/qiskit-aws-braket-provider
carstenblank
# Copyright 2020 Carsten Blank # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import time import unittest import uuid import boto3 from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, transpile, assemble from qiskit.circuit.measure import measure from qiskit.providers import JobStatus from qiskit_aws_braket_provider.awsbackend import AWSBackend from qiskit_aws_braket_provider.awsprovider import AWSProvider LOG = logging.getLogger(__name__) class AWSBackendTests(unittest.TestCase): backend_name = 'IonQ Device' def setUp(self) -> None: logging.basicConfig(format=logging.BASIC_FORMAT, level='INFO') self.provider: AWSProvider = AWSProvider(region_name='us-east-1') self.backend: AWSBackend = self.provider.get_backend(self.backend_name) def test_get_job_data_s3_folder(self): key = self.backend._get_job_data_s3_folder('12345') self.assertEqual(key, f'results-{self.backend_name}-12345') def test_save_job_task_arns(self): job_id = str(uuid.uuid4()) task_arns = ['537a196e-8162-41c6-8c72-a7f8b456da31', '537a196e-8162-41c6-8c72-a7f8b456da32', '537a196e-8162-41c6-8c72-a7f8b456da33', '537a196e-8162-41c6-8c72-a7f8b456da34'] s3_bucket, s3_folder = self.backend._save_job_task_arns(job_id, task_arns) self.assertTrue( AWSBackend._exists_file(self.provider._session.client('s3'), s3_bucket, f'{s3_folder}/task_arns.json') ) self.backend._delete_job_task_arns(job_id=job_id, s3_bucket=s3_bucket) def test_save_job_data_s3(self): creg = ClassicalRegister(2) qreg = QuantumRegister(2) qc = QuantumCircuit(qreg, creg, name='test') qc.h(0) qc.cx(0, 1) measure(qc, qreg, creg) qobj = assemble(10 * [qc]) extra_data = { 'test': [ 'yes', 'is', 'there' ] } s3_bucket, s3_key = self.backend._save_job_data_s3(qobj=qobj, s3_bucket=None, extra_data=extra_data) self.assertEqual(s3_bucket, self.backend.provider().get_default_bucket()) self.assertEqual(s3_key, f'results-{self.backend_name}-{qobj.qobj_id}') self.assertTrue( AWSBackend._exists_file(self.provider._session.client('s3'), s3_bucket, f'{s3_key}/qiskit_qobj_data.json') ) self.backend._delete_job_data_s3(job_id=qobj.qobj_id, s3_bucket=None) def test_load_job_task_arns(self): job_id = '2020-09-17T18:47:48.653735-60f7a533-a5d5-481c-9671-681f4823ce25' arns = self.backend._load_job_task_arns(job_id=job_id) self.assertListEqual( arns, ['537a196e-8162-41c6-8c72-a7f8b456da31', '537a196e-8162-41c6-8c72-a7f8b456da32', '537a196e-8162-41c6-8c72-a7f8b456da33', '537a196e-8162-41c6-8c72-a7f8b456da34'] ) def test_load_job_data_s3(self): job_id = '2020-09-17T18:47:48.653735-60f7a533-a5d5-481c-9671-681f4823ce25' qobj, extra_data = self.backend._load_job_data_s3(job_id=job_id) self.assertEqual(qobj.qobj_id, '66da2c50-2e5c-47aa-81c5-d47a04df804c') self.assertTrue('test' in extra_data) self.assertListEqual(extra_data['test'], ['yes', 'is', 'there']) def test_compile(self): creg = ClassicalRegister(2) qreg = QuantumRegister(2) qc = QuantumCircuit(qreg, creg, name='test') qc.h(0) qc.cx(0, 1) measure(qc, qreg, creg) qc_transpiled = transpile(qc, self.backend) qobj = assemble(qc_transpiled, self.backend) LOG.info(qobj) def test_retrieve_job_done(self): job_id = '52284ef5-1cf7-4182-9547-5bbc7c5dd9f5' job = self.backend.retrieve_job(job_id) self.assertIsNotNone(job) self.assertEqual(job.job_id(), job_id) self.assertEqual(job.status(), JobStatus.DONE) def test_retrieve_job_cancelled(self): job_id = '66b6a642-7db3-4134-8181-f7039b56fdfd' job = self.backend.retrieve_job(job_id) self.assertIsNotNone(job) self.assertEqual(job.job_id(), job_id) self.assertEqual(job.status(), JobStatus.CANCELLED) def test_run(self): creg = ClassicalRegister(2) qreg = QuantumRegister(2) qc = QuantumCircuit(qreg, creg, name='test') qc.h(0) qc.cx(0, 1) measure(qc, qreg, creg) qc_transpiled = transpile(qc, self.backend) qobj = assemble(qc_transpiled, self.backend, shots=1) extra_data = { 'test': [ 'yes', 'is', 'there' ] } job = self.backend.run(qobj, extra_data=extra_data) LOG.info(job.job_id()) self.assertIsNotNone(job) self.assertEqual(job.job_id(), qobj.qobj_id) self.assertTrue(job.status() in [JobStatus.INITIALIZING, JobStatus.QUEUED]) while job.status() != JobStatus.QUEUED: time.sleep(1) job.cancel()
https://github.com/qiskit-community/prototype-entanglement-forging
qiskit-community
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=cell-var-from-loop """ Measurement correction fitters. """ import copy import re from typing import List, Union import numpy as np from qiskit import QiskitError from qiskit.utils.mitigation.circuits import count_keys from qiskit.result import Result from entanglement_forging.utils.meas_mit_filters_faster import MeasurementFilter try: from matplotlib import pyplot as plt HAS_MATPLOTLIB = True except ImportError: HAS_MATPLOTLIB = False # pylint: disable=too-many-locals,too-many-branches class CompleteMeasFitter: """ Measurement correction fitter for a full calibration """ def __init__( self, results: Union[Result, List[Result]], state_labels: List[str], qubit_list: List[int] = None, circlabel: str = "", ): """ Initialize a measurement calibration matrix from the results of running the circuits returned by `measurement_calibration_circuits` A wrapper for the tensored fitter Args: results: the results of running the measurement calibration circuits. If this is `None` the user will set a calibration matrix later. state_labels: list of calibration state labels returned from `measurement_calibration_circuits`. The output matrix will obey this ordering. qubit_list: List of the qubits (for reference and if the subset is needed). If `None`, the qubit_list will be created according to the length of state_labels[0]. circlabel: if the qubits were labeled. """ if qubit_list is None: qubit_list = range(len(state_labels[0])) self._qubit_list = qubit_list self._tens_fitt = TensoredMeasFitter( results, [qubit_list], [state_labels], circlabel ) @property def cal_matrix(self): """Return cal_matrix.""" return self._tens_fitt.cal_matrices[0] @cal_matrix.setter def cal_matrix(self, new_cal_matrix): """set cal_matrix.""" self._tens_fitt.cal_matrices = [copy.deepcopy(new_cal_matrix)] @property def state_labels(self): """Return state_labels.""" return self._tens_fitt.substate_labels_list[0] @property def qubit_list(self): """Return list of qubits.""" return self._qubit_list @state_labels.setter def state_labels(self, new_state_labels): """Set state label.""" self._tens_fitt.substate_labels_list[0] = new_state_labels @property def filter(self): """Return a measurement filter using the cal matrix.""" return MeasurementFilter(self.cal_matrix, self.state_labels) def add_data(self, new_results, rebuild_cal_matrix=True): """ Add measurement calibration data Args: new_results (list or qiskit.result.Result): a single result or list of result objects. rebuild_cal_matrix (bool): rebuild the calibration matrix """ self._tens_fitt.add_data(new_results, rebuild_cal_matrix) def subset_fitter(self, qubit_sublist=None): """ Return a fitter object that is a subset of the qubits in the original list. Args: qubit_sublist (list): must be a subset of qubit_list Returns: CompleteMeasFitter: A new fitter that has the calibration for a subset of qubits Raises: QiskitError: If the calibration matrix is not initialized """ if self._tens_fitt.cal_matrices is None: raise QiskitError("Calibration matrix is not initialized") if qubit_sublist is None: raise QiskitError("Qubit sublist must be specified") for qubit in qubit_sublist: if qubit not in self._qubit_list: raise QiskitError("Qubit not in the original set of qubits") # build state labels new_state_labels = count_keys(len(qubit_sublist)) # mapping between indices in the state_labels and the qubits in # the sublist qubit_sublist_ind = [] for sqb in qubit_sublist: for qbind, qubit in enumerate(self._qubit_list): if qubit == sqb: qubit_sublist_ind.append(qbind) # states in the full calibration which correspond # to the reduced labels q_q_mapping = [] state_labels_reduced = [] for label in self.state_labels: tmplabel = [label[index] for index in qubit_sublist_ind] state_labels_reduced.append("".join(tmplabel)) for sub_lab_ind, _ in enumerate(new_state_labels): q_q_mapping.append([]) for labelind, label in enumerate(state_labels_reduced): if label == new_state_labels[sub_lab_ind]: q_q_mapping[-1].append(labelind) new_fitter = CompleteMeasFitter( results=None, state_labels=new_state_labels, qubit_list=qubit_sublist ) new_cal_matrix = np.zeros([len(new_state_labels), len(new_state_labels)]) # do a partial trace for i in range(len(new_state_labels)): for j in range(len(new_state_labels)): for q_q_i_map in q_q_mapping[i]: for q_q_j_map in q_q_mapping[j]: new_cal_matrix[i, j] += self.cal_matrix[q_q_i_map, q_q_j_map] new_cal_matrix[i, j] /= len(q_q_mapping[i]) new_fitter.cal_matrix = new_cal_matrix return new_fitter def readout_fidelity(self, label_list=None): """ Based on the results, output the readout fidelity which is the normalized trace of the calibration matrix Args: label_list (bool): If `None`, returns the average assignment fidelity of a single state. Otherwise it returns the assignment fidelity to be in any one of these states averaged over the second index. Returns: numpy.array: readout fidelity (assignment fidelity) Additional Information: The on-diagonal elements of the calibration matrix are the probabilities of measuring state 'x' given preparation of state 'x' and so the normalized trace is the average assignment fidelity """ return self._tens_fitt.readout_fidelity(0, label_list) def plot_calibration(self, ax=None, show_plot=True): # pylint: disable=invalid-name """ Plot the calibration matrix (2D color grid plot) Args: show_plot (bool): call plt.show() ax (matplotlib.axes.Axes): An optional Axes object to use for the plot """ self._tens_fitt.plot_calibration( 0, ax, show_plot ) # pylint: disable=invalid-name class TensoredMeasFitter: """ Measurement correction fitter for a tensored calibration. """ def __init__( self, results: Union[Result, List[Result]], mit_pattern: List[List[int]], substate_labels_list: List[List[str]] = None, circlabel: str = "", ): """ Initialize a measurement calibration matrix from the results of running the circuits returned by `measurement_calibration_circuits`. Args: results: the results of running the measurement calibration circuits. If this is `None`, the user will set calibration matrices later. mit_pattern: qubits to perform the measurement correction on, divided to groups according to tensors substate_labels_list: for each calibration matrix, the labels of its rows and columns. If `None`, the labels are ordered lexicographically circlabel: if the qubits were labeled Raises: ValueError: if the mit_pattern doesn't match the substate_labels_list """ self._result_list = [] self._cal_matrices = None self._circlabel = circlabel self._qubit_list_sizes = [len(qubit_list) for qubit_list in mit_pattern] self._indices_list = [] if substate_labels_list is None: self._substate_labels_list = [] for list_size in self._qubit_list_sizes: self._substate_labels_list.append(count_keys(list_size)) else: self._substate_labels_list = substate_labels_list if len(self._qubit_list_sizes) != len(substate_labels_list): raise ValueError( "mit_pattern does not match \ substate_labels_list" ) self._indices_list = [] for _, sub_labels in enumerate(self._substate_labels_list): self._indices_list.append({lab: ind for ind, lab in enumerate(sub_labels)}) self.add_data(results) @property def cal_matrices(self): """Returns cal_matrices.""" return self._cal_matrices @cal_matrices.setter def cal_matrices(self, new_cal_mat): """Sets _cal_matrices.""" self._cal_matrices = copy.deepcopy(new_cal_mat) @property def substate_labels_list(self): """Return _substate_labels_list.""" return self._substate_labels_list @property def nqubits(self): """Return _qubit_list_sizes.""" return sum(self._qubit_list_sizes) def add_data(self, new_results, rebuild_cal_matrix=True): """ Add measurement calibration data Args: new_results (list or qiskit.result.Result): a single result or list of Result objects. rebuild_cal_matrix (bool): rebuild the calibration matrix """ if new_results is None: return if not isinstance(new_results, list): new_results = [new_results] for result in new_results: self._result_list.append(result) if rebuild_cal_matrix: self._build_calibration_matrices() def readout_fidelity(self, cal_index=0, label_list=None): """ Based on the results, output the readout fidelity, which is the average of the diagonal entries in the calibration matrices. Args: cal_index(integer): readout fidelity for this index in _cal_matrices label_list (list): Returns the average fidelity over of the groups f states. In the form of a list of lists of states. If `None`, then each state used in the construction of the calibration matrices forms a group of size 1 Returns: numpy.array: The readout fidelity (assignment fidelity) Raises: QiskitError: If the calibration matrix has not been set for the object. Additional Information: The on-diagonal elements of the calibration matrices are the probabilities of measuring state 'x' given preparation of state 'x'. """ if self._cal_matrices is None: raise QiskitError("Cal matrix has not been set") if label_list is None: label_list = [[label] for label in self._substate_labels_list[cal_index]] state_labels = self._substate_labels_list[cal_index] fidelity_label_list = [] if label_list is None: fidelity_label_list = [[label] for label in state_labels] else: for fid_sublist in label_list: fidelity_label_list.append([]) for fid_statelabl in fid_sublist: for label_idx, label in enumerate(state_labels): if fid_statelabl == label: fidelity_label_list[-1].append(label_idx) continue # fidelity_label_list is a 2D list of indices in the # cal_matrix, we find the assignment fidelity of each # row and average over the list assign_fid_list = [] for fid_label_sublist in fidelity_label_list: assign_fid_list.append(0) for state_idx_i in fid_label_sublist: for state_idx_j in fid_label_sublist: assign_fid_list[-1] += self._cal_matrices[cal_index][state_idx_i][ state_idx_j ] assign_fid_list[-1] /= len(fid_label_sublist) return np.mean(assign_fid_list) def _build_calibration_matrices(self): """ Build the measurement calibration matrices from the results of running the circuits returned by `measurement_calibration`. """ # initialize the set of empty calibration matrices self._cal_matrices = [] for list_size in self._qubit_list_sizes: self._cal_matrices.append( np.zeros([2**list_size, 2**list_size], dtype=float) ) # go through for each calibration experiment for result in self._result_list: for experiment in result.results: circ_name = experiment.header.name # extract the state from the circuit name # this was the prepared state circ_search = re.search( "(?<=" + self._circlabel + "cal_)\\w+", circ_name ) # this experiment is not one of the calcs so skip if circ_search is None: continue state = circ_search.group(0) # get the counts from the result state_cnts = result.get_counts(circ_name) for measured_state, counts in state_cnts.items(): end_index = self.nqubits for cal_ind, cal_mat in enumerate(self._cal_matrices): start_index = end_index - self._qubit_list_sizes[cal_ind] substate_index = self._indices_list[cal_ind][ state[start_index:end_index] ] measured_substate_index = self._indices_list[cal_ind][ measured_state[start_index:end_index] ] end_index = start_index cal_mat[measured_substate_index][substate_index] += counts for mat_index, _ in enumerate(self._cal_matrices): sums_of_columns = np.sum(self._cal_matrices[mat_index], axis=0) # pylint: disable=assignment-from-no-return self._cal_matrices[mat_index] = np.divide( self._cal_matrices[mat_index], sums_of_columns, out=np.zeros_like(self._cal_matrices[mat_index]), where=sums_of_columns != 0, ) def plot_calibration(self, cal_index=0, axes=None, show_plot=True): """ Plot one of the calibration matrices (2D color grid plot). Args: cal_index(integer): calibration matrix to plot axes(matplotlib.axes): settings for the graph show_plot (bool): call plt.show() Raises: QiskitError: if _cal_matrices was not set. ImportError: if matplotlib was not installed. """ if self._cal_matrices is None: raise QiskitError("Cal matrix has not been set") if not HAS_MATPLOTLIB: raise ImportError( "The function plot_rb_data needs matplotlib. " 'Run "pip install matplotlib" before.' ) if axes is None: plt.figure() axes = plt.gca() axim = axes.matshow( self.cal_matrices[cal_index], cmap=plt.cm.binary, # pylint: disable=no-member clim=[0, 1], ) axes.figure.colorbar(axim) axes.set_xlabel("Prepared State") axes.xaxis.set_label_position("top") axes.set_ylabel("Measured State") axes.set_xticks(np.arange(len(self._substate_labels_list[cal_index]))) axes.set_yticks(np.arange(len(self._substate_labels_list[cal_index]))) axes.set_xticklabels(self._substate_labels_list[cal_index]) axes.set_yticklabels(self._substate_labels_list[cal_index]) if show_plot: plt.show()
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Assembler Test.""" import unittest import io from logging import StreamHandler, getLogger import sys import copy import numpy as np from qiskit import pulse from qiskit.circuit import Instruction, Gate, Parameter, ParameterVector from qiskit.circuit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.compiler.assembler import assemble from qiskit.exceptions import QiskitError from qiskit.pulse import Schedule, Acquire, Play from qiskit.pulse.channels import MemorySlot, AcquireChannel, DriveChannel, MeasureChannel from qiskit.pulse.configuration import Kernel, Discriminator from qiskit.pulse.library import gaussian from qiskit.qobj import QasmQobj, PulseQobj from qiskit.qobj.utils import MeasLevel, MeasReturnType from qiskit.pulse.macros import measure from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider import ( FakeOpenPulse2Q, FakeOpenPulse3Q, FakeYorktown, FakeHanoi, ) class RxGate(Gate): """Used to test custom gate assembly. Useful for testing pulse gates with parameters, as well. Note: Parallel maps (e.g., in assemble_circuits) pickle their input, so circuit features have to be defined top level. """ def __init__(self, theta): super().__init__("rxtheta", 1, [theta]) class TestCircuitAssembler(QiskitTestCase): """Tests for assembling circuits to qobj.""" def setUp(self): super().setUp() qr = QuantumRegister(2, name="q") cr = ClassicalRegister(2, name="c") self.circ = QuantumCircuit(qr, cr, name="circ") self.circ.h(qr[0]) self.circ.cx(qr[0], qr[1]) self.circ.measure(qr, cr) self.backend = FakeYorktown() self.backend_config = self.backend.configuration() self.num_qubits = self.backend_config.n_qubits # lo test values self.default_qubit_lo_freq = [5e9 for _ in range(self.num_qubits)] self.default_meas_lo_freq = [6.7e9 for _ in range(self.num_qubits)] self.user_lo_config_dict = { pulse.DriveChannel(0): 5.55e9, pulse.MeasureChannel(0): 6.64e9, pulse.DriveChannel(3): 4.91e9, pulse.MeasureChannel(4): 6.1e9, } self.user_lo_config = pulse.LoConfig(self.user_lo_config_dict) def test_assemble_single_circuit(self): """Test assembling a single circuit.""" qobj = assemble(self.circ, shots=2000, memory=True) self.assertIsInstance(qobj, QasmQobj) self.assertEqual(qobj.config.shots, 2000) self.assertEqual(qobj.config.memory, True) self.assertEqual(len(qobj.experiments), 1) self.assertEqual(qobj.experiments[0].instructions[1].name, "cx") def test_assemble_multiple_circuits(self): """Test assembling multiple circuits, all should have the same config.""" qr0 = QuantumRegister(2, name="q0") qc0 = ClassicalRegister(2, name="c0") circ0 = QuantumCircuit(qr0, qc0, name="circ0") circ0.h(qr0[0]) circ0.cx(qr0[0], qr0[1]) circ0.measure(qr0, qc0) qr1 = QuantumRegister(3, name="q1") qc1 = ClassicalRegister(3, name="c1") circ1 = QuantumCircuit(qr1, qc1, name="circ0") circ1.h(qr1[0]) circ1.cx(qr1[0], qr1[1]) circ1.cx(qr1[0], qr1[2]) circ1.measure(qr1, qc1) qobj = assemble([circ0, circ1], shots=100, memory=False, seed_simulator=6) self.assertIsInstance(qobj, QasmQobj) self.assertEqual(qobj.config.seed_simulator, 6) self.assertEqual(len(qobj.experiments), 2) self.assertEqual(qobj.experiments[1].config.n_qubits, 3) self.assertEqual(len(qobj.experiments), 2) self.assertEqual(len(qobj.experiments[1].instructions), 6) def test_assemble_no_run_config(self): """Test assembling with no run_config, relying on default.""" qobj = assemble(self.circ) self.assertIsInstance(qobj, QasmQobj) self.assertEqual(qobj.config.shots, 1024) def test_shots_greater_than_max_shots(self): """Test assembling with shots greater than max shots""" self.assertRaises(QiskitError, assemble, self.backend, shots=1024000) def test_shots_not_of_type_int(self): """Test assembling with shots having type other than int""" self.assertRaises(QiskitError, assemble, self.backend, shots="1024") def test_shots_of_type_numpy_int64(self): """Test assembling with shots having type numpy.int64""" qobj = assemble(self.circ, shots=np.int64(2048)) self.assertEqual(qobj.config.shots, 2048) def test_default_shots_greater_than_max_shots(self): """Test assembling with default shots greater than max shots""" self.backend_config.max_shots = 5 qobj = assemble(self.circ, self.backend) self.assertIsInstance(qobj, QasmQobj) self.assertEqual(qobj.config.shots, 5) def test_assemble_initialize(self): """Test assembling a circuit with an initialize.""" q = QuantumRegister(2, name="q") circ = QuantumCircuit(q, name="circ") circ.initialize([1 / np.sqrt(2), 0, 0, 1 / np.sqrt(2)], q[:]) qobj = assemble(circ) self.assertIsInstance(qobj, QasmQobj) self.assertEqual(qobj.experiments[0].instructions[0].name, "initialize") np.testing.assert_almost_equal( qobj.experiments[0].instructions[0].params, [0.7071067811865, 0, 0, 0.707106781186] ) def test_assemble_meas_level_meas_return(self): """Test assembling a circuit schedule with `meas_level`.""" qobj = assemble(self.circ, meas_level=1, meas_return="single") self.assertIsInstance(qobj, QasmQobj) self.assertEqual(qobj.config.meas_level, 1) self.assertEqual(qobj.config.meas_return, "single") # no meas_level set qobj = assemble(self.circ) self.assertIsInstance(qobj, QasmQobj) self.assertEqual(qobj.config.meas_level, 2) self.assertEqual(hasattr(qobj.config, "meas_return"), False) def test_assemble_backend_rep_delays(self): """Check that rep_delay is properly set from backend values.""" rep_delay_range = [2.5e-3, 4.5e-3] # sec default_rep_delay = 3.0e-3 setattr(self.backend_config, "rep_delay_range", rep_delay_range) setattr(self.backend_config, "default_rep_delay", default_rep_delay) # dynamic rep rates off setattr(self.backend_config, "dynamic_reprate_enabled", False) qobj = assemble(self.circ, self.backend) self.assertEqual(hasattr(qobj.config, "rep_delay"), False) # dynamic rep rates on setattr(self.backend_config, "dynamic_reprate_enabled", True) qobj = assemble(self.circ, self.backend) self.assertEqual(qobj.config.rep_delay, default_rep_delay * 1e6) def test_assemble_user_rep_time_delay(self): """Check that user runtime config rep_delay works.""" # set custom rep_delay in runtime config rep_delay = 2.2e-6 rep_delay_range = [0, 3e-6] # sec setattr(self.backend_config, "rep_delay_range", rep_delay_range) # dynamic rep rates off (no default so shouldn't be in qobj config) setattr(self.backend_config, "dynamic_reprate_enabled", False) qobj = assemble(self.circ, self.backend, rep_delay=rep_delay) self.assertEqual(hasattr(qobj.config, "rep_delay"), False) # turn on dynamic rep rates, rep_delay should be set setattr(self.backend_config, "dynamic_reprate_enabled", True) qobj = assemble(self.circ, self.backend, rep_delay=rep_delay) self.assertEqual(qobj.config.rep_delay, 2.2) # test ``rep_delay=0`` qobj = assemble(self.circ, self.backend, rep_delay=0) self.assertEqual(qobj.config.rep_delay, 0) # use ``rep_delay`` outside of ``rep_delay_range``` rep_delay_large = 5.0e-6 with self.assertRaises(QiskitError): assemble(self.circ, self.backend, rep_delay=rep_delay_large) def test_assemble_opaque_inst(self): """Test opaque instruction is assembled as-is""" opaque_inst = Instruction(name="my_inst", num_qubits=4, num_clbits=2, params=[0.5, 0.4]) q = QuantumRegister(6, name="q") c = ClassicalRegister(4, name="c") circ = QuantumCircuit(q, c, name="circ") circ.append(opaque_inst, [q[0], q[2], q[5], q[3]], [c[3], c[0]]) qobj = assemble(circ) self.assertIsInstance(qobj, QasmQobj) self.assertEqual(len(qobj.experiments[0].instructions), 1) self.assertEqual(qobj.experiments[0].instructions[0].name, "my_inst") self.assertEqual(qobj.experiments[0].instructions[0].qubits, [0, 2, 5, 3]) self.assertEqual(qobj.experiments[0].instructions[0].memory, [3, 0]) self.assertEqual(qobj.experiments[0].instructions[0].params, [0.5, 0.4]) def test_assemble_unroll_parametervector(self): """Verfiy that assemble unrolls parametervectors ref #5467""" pv1 = ParameterVector("pv1", 3) pv2 = ParameterVector("pv2", 3) qc = QuantumCircuit(2, 2) for i in range(3): qc.rx(pv1[i], 0) qc.ry(pv2[i], 1) qc.barrier() qc.measure([0, 1], [0, 1]) qc.bind_parameters({pv1: [0.1, 0.2, 0.3], pv2: [0.4, 0.5, 0.6]}) qobj = assemble(qc, parameter_binds=[{pv1: [0.1, 0.2, 0.3], pv2: [0.4, 0.5, 0.6]}]) self.assertIsInstance(qobj, QasmQobj) self.assertEqual(qobj.experiments[0].instructions[0].params[0], 0.100000000000000) self.assertEqual(qobj.experiments[0].instructions[1].params[0], 0.400000000000000) self.assertEqual(qobj.experiments[0].instructions[2].params[0], 0.200000000000000) self.assertEqual(qobj.experiments[0].instructions[3].params[0], 0.500000000000000) self.assertEqual(qobj.experiments[0].instructions[4].params[0], 0.300000000000000) self.assertEqual(qobj.experiments[0].instructions[5].params[0], 0.600000000000000) def test_measure_to_registers_when_conditionals(self): """Verify assemble_circuits maps all measure ops on to a register slot for a circuit containing conditionals.""" qr = QuantumRegister(2) cr1 = ClassicalRegister(1) cr2 = ClassicalRegister(2) qc = QuantumCircuit(qr, cr1, cr2) qc.measure(qr[0], cr1) # Measure not required for a later conditional qc.measure(qr[1], cr2[1]) # Measure required for a later conditional qc.h(qr[1]).c_if(cr2, 3) qobj = assemble(qc) first_measure, second_measure = ( op for op in qobj.experiments[0].instructions if op.name == "measure" ) self.assertTrue(hasattr(first_measure, "register")) self.assertEqual(first_measure.register, first_measure.memory) self.assertTrue(hasattr(second_measure, "register")) self.assertEqual(second_measure.register, second_measure.memory) def test_convert_to_bfunc_plus_conditional(self): """Verify assemble_circuits converts conditionals from QASM to Qobj.""" qr = QuantumRegister(1) cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr) qc.h(qr[0]).c_if(cr, 1) qobj = assemble(qc) bfunc_op, h_op = qobj.experiments[0].instructions self.assertEqual(bfunc_op.name, "bfunc") self.assertEqual(bfunc_op.mask, "0x1") self.assertEqual(bfunc_op.val, "0x1") self.assertEqual(bfunc_op.relation, "==") self.assertTrue(hasattr(h_op, "conditional")) self.assertEqual(bfunc_op.register, h_op.conditional) def test_convert_to_bfunc_plus_conditional_onebit(self): """Verify assemble_circuits converts single bit conditionals from QASM to Qobj.""" qr = QuantumRegister(1) cr = ClassicalRegister(3) qc = QuantumCircuit(qr, cr) qc.h(qr[0]).c_if(cr[2], 1) qobj = assemble(qc) inst_set = qobj.experiments[0].instructions [bfunc_op, h_op] = inst_set self.assertEqual(len(inst_set), 2) self.assertEqual(bfunc_op.name, "bfunc") self.assertEqual(bfunc_op.mask, "0x4") self.assertEqual(bfunc_op.val, "0x4") self.assertEqual(bfunc_op.relation, "==") self.assertTrue(hasattr(h_op, "conditional")) self.assertEqual(bfunc_op.register, h_op.conditional) def test_resize_value_to_register(self): """Verify assemble_circuits converts the value provided on the classical creg to its mapped location on the device register.""" qr = QuantumRegister(1) cr1 = ClassicalRegister(2) cr2 = ClassicalRegister(2) cr3 = ClassicalRegister(1) qc = QuantumCircuit(qr, cr1, cr2, cr3) qc.h(qr[0]).c_if(cr2, 2) qobj = assemble(qc) bfunc_op, h_op = qobj.experiments[0].instructions self.assertEqual(bfunc_op.name, "bfunc") self.assertEqual(bfunc_op.mask, "0xC") self.assertEqual(bfunc_op.val, "0x8") self.assertEqual(bfunc_op.relation, "==") self.assertTrue(hasattr(h_op, "conditional")) self.assertEqual(bfunc_op.register, h_op.conditional) def test_assemble_circuits_raises_for_bind_circuit_mismatch(self): """Verify assemble_circuits raises error for parameterized circuits without matching binds.""" qr = QuantumRegister(2) x = Parameter("x") y = Parameter("y") full_bound_circ = QuantumCircuit(qr) full_param_circ = QuantumCircuit(qr) partial_param_circ = QuantumCircuit(qr) partial_param_circ.p(x, qr[0]) full_param_circ.p(x, qr[0]) full_param_circ.p(y, qr[1]) partial_bind_args = {"parameter_binds": [{x: 1}, {x: 0}]} full_bind_args = {"parameter_binds": [{x: 1, y: 1}, {x: 0, y: 0}]} inconsistent_bind_args = {"parameter_binds": [{x: 1}, {x: 0, y: 0}]} # Raise when parameters passed for non-parametric circuit self.assertRaises(QiskitError, assemble, full_bound_circ, **partial_bind_args) # Raise when no parameters passed for parametric circuit self.assertRaises(QiskitError, assemble, partial_param_circ) self.assertRaises(QiskitError, assemble, full_param_circ) # Raise when circuit has more parameters than run_config self.assertRaises(QiskitError, assemble, full_param_circ, **partial_bind_args) # Raise when not all circuits have all parameters self.assertRaises( QiskitError, assemble, [full_param_circ, partial_param_circ], **full_bind_args ) # Raise when not all binds have all circuit params self.assertRaises(QiskitError, assemble, full_param_circ, **inconsistent_bind_args) def test_assemble_circuits_rases_for_bind_mismatch_over_expressions(self): """Verify assemble_circuits raises for invalid binds for circuit including ParameterExpressions. """ qr = QuantumRegister(1) x = Parameter("x") y = Parameter("y") expr_circ = QuantumCircuit(qr) expr_circ.p(x + y, qr[0]) partial_bind_args = {"parameter_binds": [{x: 1}, {x: 0}]} # Raise when no parameters passed for parametric circuit self.assertRaises(QiskitError, assemble, expr_circ) # Raise when circuit has more parameters than run_config self.assertRaises(QiskitError, assemble, expr_circ, **partial_bind_args) def test_assemble_circuits_binds_parameters(self): """Verify assemble_circuits applies parameter bindings and output circuits are bound.""" qr = QuantumRegister(1) qc1 = QuantumCircuit(qr) qc2 = QuantumCircuit(qr) qc3 = QuantumCircuit(qr) x = Parameter("x") y = Parameter("y") sum_ = x + y product_ = x * y qc1.u(x, y, 0, qr[0]) qc2.rz(x, qr[0]) qc2.rz(y, qr[0]) qc3.u(sum_, product_, 0, qr[0]) bind_args = {"parameter_binds": [{x: 0, y: 0}, {x: 1, y: 0}, {x: 1, y: 1}]} qobj = assemble([qc1, qc2, qc3], **bind_args) self.assertEqual(len(qobj.experiments), 9) self.assertEqual( [len(expt.instructions) for expt in qobj.experiments], [1, 1, 1, 2, 2, 2, 1, 1, 1] ) def _qobj_inst_params(expt_no, inst_no): expt = qobj.experiments[expt_no] inst = expt.instructions[inst_no] return [float(p) for p in inst.params] self.assertEqual(_qobj_inst_params(0, 0), [0, 0, 0]) self.assertEqual(_qobj_inst_params(1, 0), [1, 0, 0]) self.assertEqual(_qobj_inst_params(2, 0), [1, 1, 0]) self.assertEqual(_qobj_inst_params(3, 0), [0]) self.assertEqual(_qobj_inst_params(3, 1), [0]) self.assertEqual(_qobj_inst_params(4, 0), [1]) self.assertEqual(_qobj_inst_params(4, 1), [0]) self.assertEqual(_qobj_inst_params(5, 0), [1]) self.assertEqual(_qobj_inst_params(5, 1), [1]) self.assertEqual(_qobj_inst_params(6, 0), [0, 0, 0]) self.assertEqual(_qobj_inst_params(7, 0), [1, 0, 0]) self.assertEqual(_qobj_inst_params(8, 0), [2, 1, 0]) def test_init_qubits_default(self): """Check that the init_qubits=None assemble option is passed on to the qobj.""" qobj = assemble(self.circ) self.assertEqual(qobj.config.init_qubits, True) def test_init_qubits_true(self): """Check that the init_qubits=True assemble option is passed on to the qobj.""" qobj = assemble(self.circ, init_qubits=True) self.assertEqual(qobj.config.init_qubits, True) def test_init_qubits_false(self): """Check that the init_qubits=False assemble option is passed on to the qobj.""" qobj = assemble(self.circ, init_qubits=False) self.assertEqual(qobj.config.init_qubits, False) def test_circuit_with_global_phase(self): """Test that global phase for a circuit is handled correctly.""" circ = QuantumCircuit(2) circ.h(0) circ.cx(0, 1) circ.measure_all() circ.global_phase = 0.3 * np.pi qobj = assemble([circ, self.circ]) self.assertEqual(getattr(qobj.experiments[1].header, "global_phase"), 0) self.assertEqual(getattr(qobj.experiments[0].header, "global_phase"), 0.3 * np.pi) def test_circuit_global_phase_gate_definitions(self): """Test circuit with global phase on gate definitions.""" class TestGate(Gate): """dummy gate""" def __init__(self): super().__init__("test_gate", 1, []) def _define(self): circ_def = QuantumCircuit(1) circ_def.x(0) circ_def.global_phase = np.pi self._definition = circ_def gate = TestGate() circ = QuantumCircuit(1) circ.append(gate, [0]) qobj = assemble([circ]) self.assertEqual(getattr(qobj.experiments[0].header, "global_phase"), 0) circ.global_phase = np.pi / 2 qobj = assemble([circ]) self.assertEqual(getattr(qobj.experiments[0].header, "global_phase"), np.pi / 2) def test_pulse_gates_single_circ(self): """Test that we can add calibrations to circuits.""" theta = Parameter("theta") circ = QuantumCircuit(2) circ.h(0) circ.append(RxGate(3.14), [0]) circ.append(RxGate(theta), [1]) circ = circ.assign_parameters({theta: 3.14}) with pulse.build() as custom_h_schedule: pulse.play(pulse.library.Drag(50, 0.15, 4, 2), pulse.DriveChannel(0)) with pulse.build() as x180: pulse.play(pulse.library.Gaussian(50, 0.2, 5), pulse.DriveChannel(1)) circ.add_calibration("h", [0], custom_h_schedule) circ.add_calibration(RxGate(3.14), [0], x180) circ.add_calibration(RxGate(3.14), [1], x180) qobj = assemble(circ, FakeOpenPulse2Q()) # Only one circuit, so everything is stored at the job level cals = qobj.config.calibrations lib = qobj.config.pulse_library self.assertFalse(hasattr(qobj.experiments[0].config, "calibrations")) self.assertEqual([gate.name == "rxtheta" for gate in cals.gates].count(True), 2) self.assertEqual([gate.name == "h" for gate in cals.gates].count(True), 1) self.assertEqual(len(lib), 2) self.assertTrue(all(len(item.samples) == 50 for item in lib)) def test_pulse_gates_with_parameteric_pulses(self): """Test that pulse gates are assembled efficiently for backends that enable parametric pulses. """ with pulse.build() as custom_h_schedule: pulse.play(pulse.library.Drag(50, 0.15, 4, 2), pulse.DriveChannel(0)) circ = QuantumCircuit(2) circ.h(0) circ.add_calibration("h", [0], custom_h_schedule) backend = FakeOpenPulse2Q() backend.configuration().parametric_pulses = ["drag"] qobj = assemble(circ, backend) self.assertFalse(hasattr(qobj.config, "pulse_library")) self.assertTrue(hasattr(qobj.config, "calibrations")) def test_pulse_gates_multiple_circuits(self): """Test one circuit with cals and another without.""" with pulse.build() as dummy_sched: pulse.play(pulse.library.Drag(50, 0.15, 4, 2), pulse.DriveChannel(0)) circ = QuantumCircuit(2) circ.h(0) circ.append(RxGate(3.14), [1]) circ.add_calibration("h", [0], dummy_sched) circ.add_calibration(RxGate(3.14), [1], dummy_sched) circ2 = QuantumCircuit(2) circ2.h(0) qobj = assemble([circ, circ2], FakeOpenPulse2Q()) self.assertEqual(len(qobj.config.pulse_library), 1) self.assertEqual(len(qobj.experiments[0].config.calibrations.gates), 2) self.assertFalse(hasattr(qobj.config, "calibrations")) self.assertFalse(hasattr(qobj.experiments[1].config, "calibrations")) def test_pulse_gates_common_cals(self): """Test that common calibrations are added at the top level.""" with pulse.build() as dummy_sched: pulse.play(pulse.library.Drag(50, 0.15, 4, 2), pulse.DriveChannel(0)) circ = QuantumCircuit(2) circ.h(0) circ.append(RxGate(3.14), [1]) circ.add_calibration("h", [0], dummy_sched) circ.add_calibration(RxGate(3.14), [1], dummy_sched) circ2 = QuantumCircuit(2) circ2.h(0) circ2.add_calibration(RxGate(3.14), [1], dummy_sched) qobj = assemble([circ, circ2], FakeOpenPulse2Q()) # Identical pulses are only added once self.assertEqual(len(qobj.config.pulse_library), 1) # Identical calibrations are only added once self.assertEqual(qobj.config.calibrations.gates[0].name, "rxtheta") self.assertEqual(qobj.config.calibrations.gates[0].params, [3.14]) self.assertEqual(qobj.config.calibrations.gates[0].qubits, [1]) self.assertEqual(len(qobj.experiments[0].config.calibrations.gates), 1) self.assertFalse(hasattr(qobj.experiments[1].config, "calibrations")) def test_assemble_adds_circuit_metadata_to_experiment_header(self): """Verify that any circuit metadata is added to the exeriment header.""" circ = QuantumCircuit(2, metadata={"experiment_type": "gst", "execution_number": "1234"}) qobj = assemble(circ, shots=100, memory=False, seed_simulator=6) self.assertEqual( qobj.experiments[0].header.metadata, {"experiment_type": "gst", "execution_number": "1234"}, ) def test_pulse_gates_delay_only(self): """Test that a single delay gate is translated to an instruction.""" circ = QuantumCircuit(2) circ.append(Gate("test", 1, []), [0]) test_sched = pulse.Delay(64, DriveChannel(0)) + pulse.Delay(160, DriveChannel(0)) circ.add_calibration("test", [0], test_sched) qobj = assemble(circ, FakeOpenPulse2Q()) self.assertEqual(len(qobj.config.calibrations.gates[0].instructions), 2) self.assertEqual( qobj.config.calibrations.gates[0].instructions[1].to_dict(), {"name": "delay", "t0": 64, "ch": "d0", "duration": 160}, ) def test_job_qubit_meas_los_no_range(self): """Test that adding job qubit/meas lo freq lists are assembled into the qobj.config, w/ out any lo range.""" qobj = assemble( self.circ, backend=self.backend, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, ) # convert to ghz qubit_lo_freq_ghz = [freq / 1e9 for freq in self.default_qubit_lo_freq] meas_lo_freq_ghz = [freq / 1e9 for freq in self.default_meas_lo_freq] self.assertEqual(qobj.config.qubit_lo_freq, qubit_lo_freq_ghz) self.assertEqual(qobj.config.meas_lo_freq, meas_lo_freq_ghz) def test_job_lo_errors(self): """Test that job lo's are checked against the lo ranges and that errors are thrown if either quantity has an incorrect length or type.""" qubit_lo_range = [[freq - 5e6, freq + 5e6] for freq in self.default_qubit_lo_freq] meas_lo_range = [[freq - 5e6, freq + 5e6] for freq in self.default_meas_lo_freq] # lo range not a nested list with self.assertRaises(QiskitError): assemble( self.circ, backend=self.backend, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, qubit_lo_range=[4.995e9 for i in range(self.num_qubits)], meas_lo_range=meas_lo_range, ) # qubit lo range inner list not 2d with self.assertRaises(QiskitError): assemble( self.circ, backend=self.backend, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, qubit_lo_range=qubit_lo_range, meas_lo_range=[[6.695e9] for i in range(self.num_qubits)], ) # meas lo range inner list not 2d with self.assertRaises(QiskitError): assemble( self.circ, backend=self.backend, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, qubit_lo_range=qubit_lo_range, meas_lo_range=[[6.695e9] for i in range(self.num_qubits)], ) # qubit lo out of range with self.assertRaises(QiskitError): assemble( self.circ, backend=self.backend, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, qubit_lo_range=[[5.005e9, 5.010e9] for i in range(self.num_qubits)], meas_lo_range=meas_lo_range, ) # meas lo out of range with self.assertRaises(QiskitError): assemble( self.circ, backend=self.backend, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, qubit_lo_range=qubit_lo_range, meas_lo_range=[[6.705e9, 6.710e9] for i in range(self.num_qubits)], ) def test_job_qubit_meas_los_w_range(self): """Test that adding job qubit/meas lo freq lists are assembled into the qobj.config, w/ lo ranges input. Verify that lo ranges do not enter into the config.""" qubit_lo_range = [[freq - 5e6, freq + 5e6] for freq in self.default_qubit_lo_freq] meas_lo_range = [[freq - 5e6, freq + 5e6] for freq in self.default_meas_lo_freq] qobj = assemble( self.circ, backend=self.backend, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, qubit_lo_range=qubit_lo_range, meas_lo_range=meas_lo_range, ) # convert to ghz qubit_lo_freq_ghz = [freq / 1e9 for freq in self.default_qubit_lo_freq] meas_lo_freq_ghz = [freq / 1e9 for freq in self.default_meas_lo_freq] self.assertEqual(qobj.config.qubit_lo_freq, qubit_lo_freq_ghz) self.assertEqual(qobj.config.meas_lo_freq, meas_lo_freq_ghz) self.assertNotIn("qubit_lo_range", qobj.config.to_dict()) self.assertNotIn("meas_lo_range", qobj.config.to_dict()) def test_assemble_single_circ_single_lo_config(self): """Test assembling a single circuit, with a single experiment level lo config.""" qobj = assemble( self.circ, self.backend, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, schedule_los=self.user_lo_config, ) self.assertListEqual(qobj.config.qubit_lo_freq, [5.55, 5, 5, 4.91, 5]) self.assertListEqual(qobj.config.meas_lo_freq, [6.64, 6.7, 6.7, 6.7, 6.1]) self.assertEqual(len(qobj.experiments), 1) def test_assemble_single_circ_single_lo_config_dict(self): """Test assembling a single circuit, with a single experiment level lo config supplied as dictionary.""" qobj = assemble( self.circ, self.backend, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, schedule_los=self.user_lo_config_dict, ) self.assertListEqual(qobj.config.qubit_lo_freq, [5.55, 5, 5, 4.91, 5]) self.assertListEqual(qobj.config.meas_lo_freq, [6.64, 6.7, 6.7, 6.7, 6.1]) self.assertEqual(len(qobj.experiments), 1) def test_assemble_single_circ_multi_lo_config(self): """Test assembling a single circuit, with multiple experiment level lo configs (frequency sweep). """ user_lo_config_dict2 = { pulse.DriveChannel(1): 5.55e9, pulse.MeasureChannel(1): 6.64e9, pulse.DriveChannel(4): 4.91e9, pulse.MeasureChannel(3): 6.1e9, } user_lo_config2 = pulse.LoConfig(user_lo_config_dict2) qobj = assemble( self.circ, self.backend, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, schedule_los=[self.user_lo_config, user_lo_config2], ) qubit_lo_freq_ghz = [freq / 1e9 for freq in self.default_qubit_lo_freq] meas_lo_freq_ghz = [freq / 1e9 for freq in self.default_meas_lo_freq] self.assertListEqual(qobj.config.qubit_lo_freq, qubit_lo_freq_ghz) self.assertListEqual(qobj.config.meas_lo_freq, meas_lo_freq_ghz) self.assertEqual(len(qobj.experiments), 2) # experiment 0 los self.assertEqual(qobj.experiments[0].config.qubit_lo_freq, [5.55, 5, 5, 4.91, 5]) self.assertEqual(qobj.experiments[0].config.meas_lo_freq, [6.64, 6.7, 6.7, 6.7, 6.1]) # experiment 1 los self.assertEqual(qobj.experiments[1].config.qubit_lo_freq, [5, 5.55, 5, 5, 4.91]) self.assertEqual(qobj.experiments[1].config.meas_lo_freq, [6.7, 6.64, 6.7, 6.1, 6.7]) def test_assemble_multi_circ_multi_lo_config(self): """Test assembling circuits, with the same number of experiment level lo configs (n:n setup).""" user_lo_config_dict2 = { pulse.DriveChannel(1): 5.55e9, pulse.MeasureChannel(1): 6.64e9, pulse.DriveChannel(4): 4.91e9, pulse.MeasureChannel(3): 6.1e9, } user_lo_config2 = pulse.LoConfig(user_lo_config_dict2) qobj = assemble( [self.circ, self.circ], self.backend, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, schedule_los=[self.user_lo_config, user_lo_config2], ) qubit_lo_freq_ghz = [freq / 1e9 for freq in self.default_qubit_lo_freq] meas_lo_freq_ghz = [freq / 1e9 for freq in self.default_meas_lo_freq] self.assertListEqual(qobj.config.qubit_lo_freq, qubit_lo_freq_ghz) self.assertListEqual(qobj.config.meas_lo_freq, meas_lo_freq_ghz) self.assertEqual(len(qobj.experiments), 2) # experiment 0 los self.assertEqual(qobj.experiments[0].config.qubit_lo_freq, [5.55, 5, 5, 4.91, 5]) self.assertEqual(qobj.experiments[0].config.meas_lo_freq, [6.64, 6.7, 6.7, 6.7, 6.1]) # experiment 1 los self.assertEqual(qobj.experiments[1].config.qubit_lo_freq, [5, 5.55, 5, 5, 4.91]) self.assertEqual(qobj.experiments[1].config.meas_lo_freq, [6.7, 6.64, 6.7, 6.1, 6.7]) def test_assemble_multi_circ_single_lo_config(self): """Test assembling multiple circuits, with a single experiment level lo config (should override job level).""" qobj = assemble( [self.circ, self.circ], self.backend, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, schedule_los=self.user_lo_config, ) self.assertListEqual(qobj.config.qubit_lo_freq, [5.55, 5, 5, 4.91, 5]) self.assertListEqual(qobj.config.meas_lo_freq, [6.64, 6.7, 6.7, 6.7, 6.1]) self.assertEqual(len(qobj.experiments), 2) def test_assemble_multi_circ_wrong_number_of_multi_lo_configs(self): """Test assembling circuits, with a different number of experiment level lo configs (n:m setup). """ with self.assertRaises(QiskitError): assemble( [self.circ, self.circ, self.circ], self.backend, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, schedule_los=[self.user_lo_config, self.user_lo_config], ) def test_assemble_circ_lo_config_errors(self): """Test that lo config errors are raised properly if experiment level los are provided and some are missing or if default values are not provided. Also check that experiment level lo range is validated.""" # no defaults, but have drive/meas experiment level los for each qubit (no error) full_lo_config_dict = { pulse.DriveChannel(0): 4.85e9, pulse.DriveChannel(1): 4.9e9, pulse.DriveChannel(2): 4.95e9, pulse.DriveChannel(3): 5e9, pulse.DriveChannel(4): 5.05e9, pulse.MeasureChannel(0): 6.8e9, pulse.MeasureChannel(1): 6.85e9, pulse.MeasureChannel(2): 6.9e9, pulse.MeasureChannel(3): 6.95e9, pulse.MeasureChannel(4): 7e9, } qobj = assemble(self.circ, self.backend, schedule_los=full_lo_config_dict) self.assertListEqual(qobj.config.qubit_lo_freq, [4.85, 4.9, 4.95, 5, 5.05]) self.assertListEqual(qobj.config.meas_lo_freq, [6.8, 6.85, 6.9, 6.95, 7]) self.assertEqual(len(qobj.experiments), 1) # no defaults and missing experiment level drive lo raises missing_drive_lo_config_dict = copy.deepcopy(full_lo_config_dict) missing_drive_lo_config_dict.pop(pulse.DriveChannel(0)) with self.assertRaises(QiskitError): qobj = assemble(self.circ, self.backend, schedule_los=missing_drive_lo_config_dict) # no defaults and missing experiment level meas lo raises missing_meas_lo_config_dict = copy.deepcopy(full_lo_config_dict) missing_meas_lo_config_dict.pop(pulse.MeasureChannel(0)) with self.assertRaises(QiskitError): qobj = assemble(self.circ, self.backend, schedule_los=missing_meas_lo_config_dict) # verify lo ranges are checked at experiment level lo_values = list(full_lo_config_dict.values()) qubit_lo_range = [[freq - 5e6, freq + 5e6] for freq in lo_values[:5]] meas_lo_range = [[freq - 5e6, freq + 5e6] for freq in lo_values[5:]] # out of range drive lo full_lo_config_dict[pulse.DriveChannel(0)] -= 5.5e6 with self.assertRaises(QiskitError): qobj = assemble( self.circ, self.backend, qubit_lo_range=qubit_lo_range, schedule_los=full_lo_config_dict, ) full_lo_config_dict[pulse.DriveChannel(0)] += 5.5e6 # reset drive value # out of range meas lo full_lo_config_dict[pulse.MeasureChannel(0)] += 5.5e6 with self.assertRaises(QiskitError): qobj = assemble( self.circ, self.backend, meas_lo_range=meas_lo_range, schedule_los=full_lo_config_dict, ) class TestPulseAssembler(QiskitTestCase): """Tests for assembling schedules to qobj.""" def setUp(self): super().setUp() self.backend = FakeOpenPulse2Q() self.backend_config = self.backend.configuration() test_pulse = pulse.Waveform( samples=np.array([0.02739068, 0.05, 0.05, 0.05, 0.02739068], dtype=np.complex128), name="pulse0", ) self.schedule = pulse.Schedule(name="fake_experiment") self.schedule = self.schedule.insert(0, Play(test_pulse, self.backend_config.drive(0))) for i in range(self.backend_config.n_qubits): self.schedule = self.schedule.insert( 5, Acquire(5, self.backend_config.acquire(i), MemorySlot(i)) ) self.user_lo_config_dict = {self.backend_config.drive(0): 4.91e9} self.user_lo_config = pulse.LoConfig(self.user_lo_config_dict) self.default_qubit_lo_freq = [4.9e9, 5.0e9] self.default_meas_lo_freq = [6.5e9, 6.6e9] self.config = {"meas_level": 1, "memory_slot_size": 100, "meas_return": "avg"} self.header = {"backend_name": "FakeOpenPulse2Q", "backend_version": "0.0.0"} def test_assemble_adds_schedule_metadata_to_experiment_header(self): """Verify that any circuit metadata is added to the exeriment header.""" self.schedule.metadata = {"experiment_type": "gst", "execution_number": "1234"} qobj = assemble( self.schedule, shots=100, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, schedule_los=[], ) self.assertEqual( qobj.experiments[0].header.metadata, {"experiment_type": "gst", "execution_number": "1234"}, ) def test_assemble_sample_pulse(self): """Test that the pulse lib and qobj instruction can be paired up.""" 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" ) qobj = assemble( schedule, qobj_header=self.header, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, schedule_los=[], **self.config, ) test_dict = qobj.to_dict() experiment = test_dict["experiments"][0] inst0_name = experiment["instructions"][0]["name"] inst1_name = experiment["instructions"][1]["name"] inst2_name = experiment["instructions"][2]["name"] pulses = {} for item in test_dict["config"]["pulse_library"]: pulses[item["name"]] = item["samples"] self.assertTrue(all(name in pulses for name in [inst0_name, inst1_name, inst2_name])) # Their pulses are the same self.assertEqual(inst0_name, inst1_name) self.assertTrue(np.allclose(pulses[inst0_name], [0.1] * 16)) self.assertTrue(np.allclose(pulses[inst2_name], [0.5] * 16)) def test_assemble_single_schedule_without_lo_config(self): """Test assembling a single schedule, no lo config.""" qobj = assemble( self.schedule, qobj_header=self.header, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, schedule_los=[], **self.config, ) test_dict = qobj.to_dict() self.assertListEqual(test_dict["config"]["qubit_lo_freq"], [4.9, 5.0]) self.assertEqual(len(test_dict["experiments"]), 1) self.assertEqual(len(test_dict["experiments"][0]["instructions"]), 2) def test_assemble_multi_schedules_without_lo_config(self): """Test assembling schedules, no lo config.""" qobj = assemble( [self.schedule, self.schedule], qobj_header=self.header, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, **self.config, ) test_dict = qobj.to_dict() self.assertListEqual(test_dict["config"]["qubit_lo_freq"], [4.9, 5.0]) self.assertEqual(len(test_dict["experiments"]), 2) self.assertEqual(len(test_dict["experiments"][0]["instructions"]), 2) def test_assemble_single_schedule_with_lo_config(self): """Test assembling a single schedule, with a single lo config.""" qobj = assemble( self.schedule, qobj_header=self.header, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, schedule_los=self.user_lo_config, **self.config, ) test_dict = qobj.to_dict() self.assertListEqual(test_dict["config"]["qubit_lo_freq"], [4.91, 5.0]) self.assertEqual(len(test_dict["experiments"]), 1) self.assertEqual(len(test_dict["experiments"][0]["instructions"]), 2) def test_assemble_single_schedule_with_lo_config_dict(self): """Test assembling a single schedule, with a single lo config supplied as dictionary.""" qobj = assemble( self.schedule, qobj_header=self.header, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, schedule_los=self.user_lo_config_dict, **self.config, ) test_dict = qobj.to_dict() self.assertListEqual(test_dict["config"]["qubit_lo_freq"], [4.91, 5.0]) self.assertEqual(len(test_dict["experiments"]), 1) self.assertEqual(len(test_dict["experiments"][0]["instructions"]), 2) def test_assemble_single_schedule_with_multi_lo_configs(self): """Test assembling a single schedule, with multiple lo configs (frequency sweep).""" qobj = assemble( self.schedule, qobj_header=self.header, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, schedule_los=[self.user_lo_config, self.user_lo_config], **self.config, ) test_dict = qobj.to_dict() self.assertListEqual(test_dict["config"]["qubit_lo_freq"], [4.9, 5.0]) self.assertEqual(len(test_dict["experiments"]), 2) self.assertEqual(len(test_dict["experiments"][0]["instructions"]), 2) self.assertDictEqual(test_dict["experiments"][0]["config"], {"qubit_lo_freq": [4.91, 5.0]}) def test_assemble_multi_schedules_with_multi_lo_configs(self): """Test assembling schedules, with the same number of lo configs (n:n setup).""" qobj = assemble( [self.schedule, self.schedule], qobj_header=self.header, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, schedule_los=[self.user_lo_config, self.user_lo_config], **self.config, ) test_dict = qobj.to_dict() self.assertListEqual(test_dict["config"]["qubit_lo_freq"], [4.9, 5.0]) self.assertEqual(len(test_dict["experiments"]), 2) self.assertEqual(len(test_dict["experiments"][0]["instructions"]), 2) self.assertDictEqual(test_dict["experiments"][0]["config"], {"qubit_lo_freq": [4.91, 5.0]}) def test_assemble_multi_schedules_with_wrong_number_of_multi_lo_configs(self): """Test assembling schedules, with a different number of lo configs (n:m setup).""" with self.assertRaises(QiskitError): assemble( [self.schedule, self.schedule, self.schedule], qobj_header=self.header, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, schedule_los=[self.user_lo_config, self.user_lo_config], **self.config, ) def test_assemble_meas_map(self): """Test assembling a single schedule, no lo config.""" schedule = Schedule(name="fake_experiment") schedule = schedule.insert(5, Acquire(5, AcquireChannel(0), MemorySlot(0))) schedule = schedule.insert(5, Acquire(5, AcquireChannel(1), MemorySlot(1))) qobj = assemble( schedule, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, meas_map=[[0], [1]], ) self.assertIsInstance(qobj, PulseQobj) qobj = assemble( schedule, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, meas_map=[[0, 1, 2]], ) self.assertIsInstance(qobj, PulseQobj) def test_assemble_memory_slots(self): """Test assembling a schedule and inferring number of memoryslots.""" n_memoryslots = 10 # single acquisition schedule = Acquire( 5, self.backend_config.acquire(0), mem_slot=pulse.MemorySlot(n_memoryslots - 1) ) qobj = assemble( schedule, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, meas_map=[[0], [1]], ) self.assertEqual(qobj.config.memory_slots, n_memoryslots) # this should be in experimental header as well self.assertEqual(qobj.experiments[0].header.memory_slots, n_memoryslots) # multiple acquisition schedule = Acquire( 5, self.backend_config.acquire(0), mem_slot=pulse.MemorySlot(n_memoryslots - 1) ) schedule = schedule.insert( 10, Acquire( 5, self.backend_config.acquire(0), mem_slot=pulse.MemorySlot(n_memoryslots - 1) ), ) qobj = assemble( schedule, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, meas_map=[[0], [1]], ) self.assertEqual(qobj.config.memory_slots, n_memoryslots) # this should be in experimental header as well self.assertEqual(qobj.experiments[0].header.memory_slots, n_memoryslots) def test_assemble_memory_slots_for_schedules(self): """Test assembling schedules with different memory slots.""" n_memoryslots = [10, 5, 7] schedules = [] for n_memoryslot in n_memoryslots: schedule = Acquire( 5, self.backend_config.acquire(0), mem_slot=pulse.MemorySlot(n_memoryslot - 1) ) schedules.append(schedule) qobj = assemble( schedules, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, meas_map=[[0], [1]], ) self.assertEqual(qobj.config.memory_slots, max(n_memoryslots)) self.assertEqual(qobj.experiments[0].header.memory_slots, n_memoryslots[0]) self.assertEqual(qobj.experiments[1].header.memory_slots, n_memoryslots[1]) self.assertEqual(qobj.experiments[2].header.memory_slots, n_memoryslots[2]) def test_pulse_name_conflicts(self): """Test that pulse name conflicts can be resolved.""" name_conflict_pulse = pulse.Waveform( samples=np.array([0.02, 0.05, 0.05, 0.05, 0.02], dtype=np.complex128), name="pulse0" ) self.schedule = self.schedule.insert( 1, Play(name_conflict_pulse, self.backend_config.drive(1)) ) qobj = assemble( self.schedule, qobj_header=self.header, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, schedule_los=[], **self.config, ) self.assertNotEqual(qobj.config.pulse_library[0].name, qobj.config.pulse_library[1].name) def test_pulse_name_conflicts_in_other_schedule(self): """Test two pulses with the same name in different schedule can be resolved.""" backend = FakeHanoi() defaults = backend.defaults() schedules = [] ch_d0 = pulse.DriveChannel(0) for amp in (0.1, 0.2): sched = Schedule() sched += Play(gaussian(duration=100, amp=amp, sigma=30, name="my_pulse"), ch_d0) sched += measure(qubits=[0], backend=backend) << 100 schedules.append(sched) qobj = assemble( schedules, qubit_lo_freq=defaults.qubit_freq_est, meas_lo_freq=defaults.meas_freq_est ) # two user pulses and one measurement pulse should be contained self.assertEqual(len(qobj.config.pulse_library), 3) def test_assemble_with_delay(self): """Test that delay instruction is not ignored in assembly.""" delay_schedule = pulse.Delay(10, self.backend_config.drive(0)) delay_schedule += self.schedule delay_qobj = assemble(delay_schedule, self.backend) self.assertEqual(delay_qobj.experiments[0].instructions[0].name, "delay") self.assertEqual(delay_qobj.experiments[0].instructions[0].duration, 10) self.assertEqual(delay_qobj.experiments[0].instructions[0].t0, 0) def test_delay_removed_on_acq_ch(self): """Test that delay instructions on acquire channels are skipped on assembly with times shifted properly. """ delay0 = pulse.Delay(5, self.backend_config.acquire(0)) delay1 = pulse.Delay(7, self.backend_config.acquire(1)) sched0 = delay0 sched0 += self.schedule # includes ``Acquire`` instr sched0 += delay1 sched1 = self.schedule # includes ``Acquire`` instr sched1 += delay0 sched1 += delay1 sched2 = delay0 sched2 += delay1 sched2 += self.schedule # includes ``Acquire`` instr delay_qobj = assemble([sched0, sched1, sched2], self.backend) # check that no delay instrs occur on acquire channels is_acq_delay = False for exp in delay_qobj.experiments: for instr in exp.instructions: if instr.name == "delay" and "a" in instr.ch: is_acq_delay = True self.assertFalse(is_acq_delay) # check that acquire instr are shifted from ``t0=5`` as needed self.assertEqual(delay_qobj.experiments[0].instructions[1].t0, 10) self.assertEqual(delay_qobj.experiments[0].instructions[1].name, "acquire") self.assertEqual(delay_qobj.experiments[1].instructions[1].t0, 5) self.assertEqual(delay_qobj.experiments[1].instructions[1].name, "acquire") self.assertEqual(delay_qobj.experiments[2].instructions[1].t0, 12) self.assertEqual(delay_qobj.experiments[2].instructions[1].name, "acquire") def test_assemble_schedule_enum(self): """Test assembling a schedule with enum input values to assemble.""" qobj = assemble( self.schedule, qobj_header=self.header, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, schedule_los=[], meas_level=MeasLevel.CLASSIFIED, meas_return=MeasReturnType.AVERAGE, ) test_dict = qobj.to_dict() self.assertEqual(test_dict["config"]["meas_return"], "avg") self.assertEqual(test_dict["config"]["meas_level"], 2) def test_assemble_parametric(self): """Test that parametric pulses can be assembled properly into a PulseQobj.""" amp = [0.5, 0.6, 1, 0.2] angle = [np.pi / 2, 0.6, 0, 0] sched = pulse.Schedule(name="test_parametric") sched += Play( pulse.Gaussian(duration=25, sigma=4, amp=amp[0], angle=angle[0]), DriveChannel(0) ) sched += Play( pulse.Drag(duration=25, amp=amp[1], angle=angle[1], sigma=7.8, beta=4), DriveChannel(1) ) sched += Play(pulse.Constant(duration=25, amp=amp[2], angle=angle[2]), DriveChannel(2)) sched += ( Play( pulse.GaussianSquare(duration=150, amp=amp[3], angle=angle[3], sigma=8, width=140), MeasureChannel(0), ) << sched.duration ) backend = FakeOpenPulse3Q() backend.configuration().parametric_pulses = [ "gaussian", "drag", "gaussian_square", "constant", ] qobj = assemble(sched, backend) self.assertEqual(qobj.config.pulse_library, []) qobj_insts = qobj.experiments[0].instructions self.assertTrue(all(inst.name == "parametric_pulse" for inst in qobj_insts)) self.assertEqual(qobj_insts[0].pulse_shape, "gaussian") self.assertEqual(qobj_insts[1].pulse_shape, "drag") self.assertEqual(qobj_insts[2].pulse_shape, "constant") self.assertEqual(qobj_insts[3].pulse_shape, "gaussian_square") self.assertDictEqual( qobj_insts[0].parameters, {"duration": 25, "sigma": 4, "amp": amp[0] * np.exp(1j * angle[0])}, ) self.assertDictEqual( qobj_insts[1].parameters, {"duration": 25, "sigma": 7.8, "amp": amp[1] * np.exp(1j * angle[1]), "beta": 4}, ) self.assertDictEqual( qobj_insts[2].parameters, {"duration": 25, "amp": amp[2] * np.exp(1j * angle[2])} ) self.assertDictEqual( qobj_insts[3].parameters, {"duration": 150, "sigma": 8, "amp": amp[3] * np.exp(1j * angle[3]), "width": 140}, ) self.assertEqual( qobj.to_dict()["experiments"][0]["instructions"][0]["parameters"]["amp"], amp[0] * np.exp(1j * angle[0]), ) def test_assemble_parametric_unsupported(self): """Test that parametric pulses are translated to Waveform if they're not supported by the backend during assemble time. """ sched = pulse.Schedule(name="test_parametric_to_sample_pulse") sched += Play( pulse.Drag(duration=25, amp=0.5, angle=-0.3, sigma=7.8, beta=4), DriveChannel(1) ) sched += Play(pulse.Constant(duration=25, amp=1), DriveChannel(2)) backend = FakeOpenPulse3Q() backend.configuration().parametric_pulses = ["something_extra"] qobj = assemble(sched, backend) self.assertNotEqual(qobj.config.pulse_library, []) qobj_insts = qobj.experiments[0].instructions self.assertFalse(hasattr(qobj_insts[0], "pulse_shape")) def test_assemble_parametric_pulse_kwarg_with_backend_setting(self): """Test that parametric pulses respect the kwarg over backend""" backend = FakeHanoi() qc = QuantumCircuit(1, 1) qc.x(0) qc.measure(0, 0) with pulse.build(backend, name="x") as x_q0: pulse.play(pulse.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(0)) qc.add_calibration("x", (0,), x_q0) qobj = assemble(qc, backend, parametric_pulses=["gaussian"]) self.assertEqual(qobj.config.parametric_pulses, ["gaussian"]) def test_assemble_parametric_pulse_kwarg_empty_list_with_backend_setting(self): """Test that parametric pulses respect the kwarg as empty list over backend""" backend = FakeHanoi() qc = QuantumCircuit(1, 1) qc.x(0) qc.measure(0, 0) with pulse.build(backend, name="x") as x_q0: pulse.play(pulse.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(0)) qc.add_calibration("x", (0,), x_q0) qobj = assemble(qc, backend, parametric_pulses=[]) self.assertEqual(qobj.config.parametric_pulses, []) def test_init_qubits_default(self): """Check that the init_qubits=None assemble option is passed on to the qobj.""" qobj = assemble(self.schedule, self.backend) self.assertEqual(qobj.config.init_qubits, True) def test_init_qubits_true(self): """Check that the init_qubits=True assemble option is passed on to the qobj.""" qobj = assemble(self.schedule, self.backend, init_qubits=True) self.assertEqual(qobj.config.init_qubits, True) def test_init_qubits_false(self): """Check that the init_qubits=False assemble option is passed on to the qobj.""" qobj = assemble(self.schedule, self.backend, init_qubits=False) self.assertEqual(qobj.config.init_qubits, False) def test_assemble_backend_rep_times_delays(self): """Check that rep_time and rep_delay are properly set from backend values.""" # use first entry from allowed backend values rep_times = [2.0, 3.0, 4.0] # sec rep_delay_range = [2.5e-3, 4.5e-3] default_rep_delay = 3.0e-3 self.backend_config.rep_times = rep_times setattr(self.backend_config, "rep_delay_range", rep_delay_range) setattr(self.backend_config, "default_rep_delay", default_rep_delay) # dynamic rep rates off qobj = assemble(self.schedule, self.backend) self.assertEqual(qobj.config.rep_time, int(rep_times[0] * 1e6)) self.assertEqual(hasattr(qobj.config, "rep_delay"), False) # dynamic rep rates on setattr(self.backend_config, "dynamic_reprate_enabled", True) # RuntimeWarning bc ``rep_time`` is specified`` when dynamic rep rates not enabled with self.assertWarns(RuntimeWarning): qobj = assemble(self.schedule, self.backend) self.assertEqual(qobj.config.rep_time, int(rep_times[0] * 1e6)) self.assertEqual(qobj.config.rep_delay, default_rep_delay * 1e6) def test_assemble_user_rep_time_delay(self): """Check that user runtime config rep_time and rep_delay work.""" # set custom rep_time and rep_delay in runtime config rep_time = 200.0e-6 rep_delay = 2.5e-6 self.config["rep_time"] = rep_time self.config["rep_delay"] = rep_delay # dynamic rep rates off # RuntimeWarning bc using ``rep_delay`` when dynamic rep rates off with self.assertWarns(RuntimeWarning): qobj = assemble(self.schedule, self.backend, **self.config) self.assertEqual(qobj.config.rep_time, int(rep_time * 1e6)) self.assertEqual(hasattr(qobj.config, "rep_delay"), False) # now remove rep_delay and enable dynamic rep rates # RuntimeWarning bc using ``rep_time`` when dynamic rep rates are enabled del self.config["rep_delay"] setattr(self.backend_config, "dynamic_reprate_enabled", True) with self.assertWarns(RuntimeWarning): qobj = assemble(self.schedule, self.backend, **self.config) self.assertEqual(qobj.config.rep_time, int(rep_time * 1e6)) self.assertEqual(hasattr(qobj.config, "rep_delay"), False) # use ``default_rep_delay`` # ``rep_time`` comes from allowed backend rep_times rep_times = [0.5, 1.0, 1.5] # sec self.backend_config.rep_times = rep_times setattr(self.backend_config, "rep_delay_range", [0, 3.0e-6]) setattr(self.backend_config, "default_rep_delay", 2.2e-6) del self.config["rep_time"] qobj = assemble(self.schedule, self.backend, **self.config) self.assertEqual(qobj.config.rep_time, int(rep_times[0] * 1e6)) self.assertEqual(qobj.config.rep_delay, 2.2) # use qobj ``default_rep_delay`` self.config["rep_delay"] = 1.5e-6 qobj = assemble(self.schedule, self.backend, **self.config) self.assertEqual(qobj.config.rep_time, int(rep_times[0] * 1e6)) self.assertEqual(qobj.config.rep_delay, 1.5) # use ``rep_delay`` outside of ``rep_delay_range self.config["rep_delay"] = 5.0e-6 with self.assertRaises(QiskitError): assemble(self.schedule, self.backend, **self.config) def test_assemble_with_individual_discriminators(self): """Test that assembly works with individual discriminators.""" disc_one = Discriminator("disc_one", test_params=True) disc_two = Discriminator("disc_two", test_params=False) schedule = Schedule() schedule = schedule.append( Acquire(5, AcquireChannel(0), MemorySlot(0), discriminator=disc_one), ) schedule = schedule.append( Acquire(5, AcquireChannel(1), MemorySlot(1), discriminator=disc_two), ) qobj = assemble( schedule, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, meas_map=[[0, 1]], ) qobj_discriminators = qobj.experiments[0].instructions[0].discriminators self.assertEqual(len(qobj_discriminators), 2) self.assertEqual(qobj_discriminators[0].name, "disc_one") self.assertEqual(qobj_discriminators[0].params["test_params"], True) self.assertEqual(qobj_discriminators[1].name, "disc_two") self.assertEqual(qobj_discriminators[1].params["test_params"], False) def test_assemble_with_single_discriminators(self): """Test that assembly works with both a single discriminator.""" disc_one = Discriminator("disc_one", test_params=True) schedule = Schedule() schedule = schedule.append( Acquire(5, AcquireChannel(0), MemorySlot(0), discriminator=disc_one), ) schedule = schedule.append( Acquire(5, AcquireChannel(1), MemorySlot(1)), ) qobj = assemble( schedule, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, meas_map=[[0, 1]], ) qobj_discriminators = qobj.experiments[0].instructions[0].discriminators self.assertEqual(len(qobj_discriminators), 1) self.assertEqual(qobj_discriminators[0].name, "disc_one") self.assertEqual(qobj_discriminators[0].params["test_params"], True) def test_assemble_with_unequal_discriminators(self): """Test that assembly works with incorrect number of discriminators for number of qubits.""" disc_one = Discriminator("disc_one", test_params=True) disc_two = Discriminator("disc_two", test_params=False) schedule = Schedule() schedule += Acquire(5, AcquireChannel(0), MemorySlot(0), discriminator=disc_one) schedule += Acquire(5, AcquireChannel(1), MemorySlot(1), discriminator=disc_two) schedule += Acquire(5, AcquireChannel(2), MemorySlot(2)) with self.assertRaises(QiskitError): assemble( schedule, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, meas_map=[[0, 1, 2]], ) def test_assemble_with_individual_kernels(self): """Test that assembly works with individual kernels.""" disc_one = Kernel("disc_one", test_params=True) disc_two = Kernel("disc_two", test_params=False) schedule = Schedule() schedule = schedule.append( Acquire(5, AcquireChannel(0), MemorySlot(0), kernel=disc_one), ) schedule = schedule.append( Acquire(5, AcquireChannel(1), MemorySlot(1), kernel=disc_two), ) qobj = assemble( schedule, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, meas_map=[[0, 1]], ) qobj_kernels = qobj.experiments[0].instructions[0].kernels self.assertEqual(len(qobj_kernels), 2) self.assertEqual(qobj_kernels[0].name, "disc_one") self.assertEqual(qobj_kernels[0].params["test_params"], True) self.assertEqual(qobj_kernels[1].name, "disc_two") self.assertEqual(qobj_kernels[1].params["test_params"], False) def test_assemble_with_single_kernels(self): """Test that assembly works with both a single kernel.""" disc_one = Kernel("disc_one", test_params=True) schedule = Schedule() schedule = schedule.append( Acquire(5, AcquireChannel(0), MemorySlot(0), kernel=disc_one), ) schedule = schedule.append( Acquire(5, AcquireChannel(1), MemorySlot(1)), ) qobj = assemble( schedule, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, meas_map=[[0, 1]], ) qobj_kernels = qobj.experiments[0].instructions[0].kernels self.assertEqual(len(qobj_kernels), 1) self.assertEqual(qobj_kernels[0].name, "disc_one") self.assertEqual(qobj_kernels[0].params["test_params"], True) def test_assemble_with_unequal_kernels(self): """Test that assembly works with incorrect number of discriminators for number of qubits.""" disc_one = Kernel("disc_one", test_params=True) disc_two = Kernel("disc_two", test_params=False) schedule = Schedule() schedule += Acquire(5, AcquireChannel(0), MemorySlot(0), kernel=disc_one) schedule += Acquire(5, AcquireChannel(1), MemorySlot(1), kernel=disc_two) schedule += Acquire(5, AcquireChannel(2), MemorySlot(2)) with self.assertRaises(QiskitError): assemble( schedule, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, meas_map=[[0, 1, 2]], ) def test_assemble_single_instruction(self): """Test assembling schedules, no lo config.""" inst = pulse.Play(pulse.Constant(100, 1.0), pulse.DriveChannel(0)) self.assertIsInstance(assemble(inst, self.backend), PulseQobj) def test_assemble_overlapping_time(self): """Test that assembly errors when qubits are measured in overlapping time.""" schedule = Schedule() schedule = schedule.append( Acquire(5, AcquireChannel(0), MemorySlot(0)), ) schedule = schedule.append( Acquire(5, AcquireChannel(1), MemorySlot(1)) << 1, ) with self.assertRaises(QiskitError): assemble( schedule, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, meas_map=[[0, 1]], ) def test_assemble_meas_map_vs_insts(self): """Test that assembly errors when the qubits are measured in overlapping time and qubits are not in the first meas_map list.""" schedule = Schedule() schedule += Acquire(5, AcquireChannel(0), MemorySlot(0)) schedule += Acquire(5, AcquireChannel(1), MemorySlot(1)) schedule += Acquire(5, AcquireChannel(2), MemorySlot(2)) << 2 schedule += Acquire(5, AcquireChannel(3), MemorySlot(3)) << 2 with self.assertRaises(QiskitError): assemble( schedule, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, meas_map=[[0], [1, 2], [3]], ) def test_assemble_non_overlapping_time_single_meas_map(self): """Test that assembly works when qubits are measured in non-overlapping time within the same measurement map list.""" schedule = Schedule() schedule = schedule.append( Acquire(5, AcquireChannel(0), MemorySlot(0)), ) schedule = schedule.append( Acquire(5, AcquireChannel(1), MemorySlot(1)) << 5, ) qobj = assemble( schedule, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, meas_map=[[0, 1]], ) self.assertIsInstance(qobj, PulseQobj) def test_assemble_disjoint_time(self): """Test that assembly works when qubits are in disjoint meas map sets.""" schedule = Schedule() schedule = schedule.append( Acquire(5, AcquireChannel(0), MemorySlot(0)), ) schedule = schedule.append( Acquire(5, AcquireChannel(1), MemorySlot(1)) << 1, ) qobj = assemble( schedule, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, meas_map=[[0, 2], [1, 3]], ) self.assertIsInstance(qobj, PulseQobj) def test_assemble_valid_qubits(self): """Test that assembly works when qubits that are in the measurement map is measured.""" schedule = Schedule() schedule = schedule.append( Acquire(5, AcquireChannel(1), MemorySlot(1)), ) schedule = schedule.append( Acquire(5, AcquireChannel(2), MemorySlot(2)), ) schedule = schedule.append( Acquire(5, AcquireChannel(3), MemorySlot(3)), ) qobj = assemble( schedule, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, meas_map=[[0, 1, 2], [3]], ) self.assertIsInstance(qobj, PulseQobj) class TestPulseAssemblerMissingKwargs(QiskitTestCase): """Verify that errors are raised in case backend is not provided and kwargs are missing.""" def setUp(self): super().setUp() self.schedule = pulse.Schedule(name="fake_experiment") self.backend = FakeOpenPulse2Q() self.config = self.backend.configuration() self.defaults = self.backend.defaults() self.qubit_lo_freq = list(self.defaults.qubit_freq_est) self.meas_lo_freq = list(self.defaults.meas_freq_est) self.qubit_lo_range = self.config.qubit_lo_range self.meas_lo_range = self.config.meas_lo_range self.schedule_los = { pulse.DriveChannel(0): self.qubit_lo_freq[0], pulse.DriveChannel(1): self.qubit_lo_freq[1], pulse.MeasureChannel(0): self.meas_lo_freq[0], pulse.MeasureChannel(1): self.meas_lo_freq[1], } self.meas_map = self.config.meas_map self.memory_slots = self.config.n_qubits # default rep_time and rep_delay self.rep_time = self.config.rep_times[0] self.rep_delay = None def test_defaults(self): """Test defaults work.""" qobj = assemble( self.schedule, qubit_lo_freq=self.qubit_lo_freq, meas_lo_freq=self.meas_lo_freq, qubit_lo_range=self.qubit_lo_range, meas_lo_range=self.meas_lo_range, schedule_los=self.schedule_los, meas_map=self.meas_map, memory_slots=self.memory_slots, rep_time=self.rep_time, rep_delay=self.rep_delay, ) self.assertIsInstance(qobj, PulseQobj) def test_missing_qubit_lo_freq(self): """Test error raised if qubit_lo_freq missing.""" with self.assertRaises(QiskitError): assemble( self.schedule, qubit_lo_freq=None, meas_lo_freq=self.meas_lo_freq, qubit_lo_range=self.qubit_lo_range, meas_lo_range=self.meas_lo_range, meas_map=self.meas_map, memory_slots=self.memory_slots, rep_time=self.rep_time, rep_delay=self.rep_delay, ) def test_missing_meas_lo_freq(self): """Test error raised if meas_lo_freq missing.""" with self.assertRaises(QiskitError): assemble( self.schedule, qubit_lo_freq=self.qubit_lo_freq, meas_lo_freq=None, qubit_lo_range=self.qubit_lo_range, meas_lo_range=self.meas_lo_range, meas_map=self.meas_map, memory_slots=self.memory_slots, rep_time=self.rep_time, rep_delay=self.rep_delay, ) def test_missing_memory_slots(self): """Test error is not raised if memory_slots are missing.""" qobj = assemble( self.schedule, qubit_lo_freq=self.qubit_lo_freq, meas_lo_freq=self.meas_lo_freq, qubit_lo_range=self.qubit_lo_range, meas_lo_range=self.meas_lo_range, schedule_los=self.schedule_los, meas_map=self.meas_map, memory_slots=None, rep_time=self.rep_time, rep_delay=self.rep_delay, ) self.assertIsInstance(qobj, PulseQobj) def test_missing_rep_time_and_delay(self): """Test qobj is valid if rep_time and rep_delay are missing.""" qobj = assemble( self.schedule, qubit_lo_freq=self.qubit_lo_freq, meas_lo_freq=self.meas_lo_freq, qubit_lo_range=self.qubit_lo_range, meas_lo_range=self.meas_lo_range, schedule_los=self.schedule_los, meas_map=self.meas_map, memory_slots=None, rep_time=None, rep_delay=None, ) self.assertEqual(hasattr(qobj, "rep_time"), False) self.assertEqual(hasattr(qobj, "rep_delay"), False) def test_missing_meas_map(self): """Test that assembly still works if meas_map is missing.""" qobj = assemble( self.schedule, qubit_lo_freq=self.qubit_lo_freq, meas_lo_freq=self.meas_lo_freq, qubit_lo_range=self.qubit_lo_range, meas_lo_range=self.meas_lo_range, schedule_los=self.schedule_los, meas_map=None, memory_slots=self.memory_slots, rep_time=self.rep_time, rep_delay=self.rep_delay, ) self.assertIsInstance(qobj, PulseQobj) def test_missing_lo_ranges(self): """Test that assembly still works if lo_ranges are missing.""" qobj = assemble( self.schedule, qubit_lo_freq=self.qubit_lo_freq, meas_lo_freq=self.meas_lo_freq, qubit_lo_range=None, meas_lo_range=None, schedule_los=self.schedule_los, meas_map=self.meas_map, memory_slots=self.memory_slots, rep_time=self.rep_time, rep_delay=self.rep_delay, ) self.assertIsInstance(qobj, PulseQobj) def test_unsupported_meas_level(self): """Test that assembly raises an error if meas_level is not supported""" backend = FakeOpenPulse2Q() backend.configuration().meas_levels = [1, 2] with self.assertRaises(QiskitError): assemble( self.schedule, backend, qubit_lo_freq=self.qubit_lo_freq, meas_lo_freq=self.meas_lo_freq, qubit_lo_range=self.qubit_lo_range, meas_lo_range=self.meas_lo_range, schedule_los=self.schedule_los, meas_level=0, meas_map=self.meas_map, memory_slots=self.memory_slots, rep_time=self.rep_time, rep_delay=self.rep_delay, ) def test_single_and_deprecated_acquire_styles(self): """Test that acquires are identically combined with Acquires that take a single channel.""" backend = FakeOpenPulse2Q() new_style_schedule = Schedule() acq_dur = 1200 for i in range(2): new_style_schedule += Acquire(acq_dur, AcquireChannel(i), MemorySlot(i)) deprecated_style_schedule = Schedule() for i in range(2): deprecated_style_schedule += Acquire(1200, AcquireChannel(i), MemorySlot(i)) # The Qobj IDs will be different n_qobj = assemble(new_style_schedule, backend) n_qobj.qobj_id = None n_qobj.experiments[0].header.name = None d_qobj = assemble(deprecated_style_schedule, backend) d_qobj.qobj_id = None d_qobj.experiments[0].header.name = None self.assertEqual(n_qobj, d_qobj) assembled_acquire = n_qobj.experiments[0].instructions[0] self.assertEqual(assembled_acquire.qubits, [0, 1]) self.assertEqual(assembled_acquire.memory_slot, [0, 1]) class StreamHandlerRaiseException(StreamHandler): """Handler class that will raise an exception on formatting errors.""" def handleError(self, record): raise sys.exc_info() class TestLogAssembler(QiskitTestCase): """Testing the log_assembly option.""" def setUp(self): super().setUp() logger = getLogger() self.addCleanup(logger.setLevel, logger.level) logger.setLevel("DEBUG") self.output = io.StringIO() logger.addHandler(StreamHandlerRaiseException(self.output)) self.circuit = QuantumCircuit(QuantumRegister(1)) def assertAssembleLog(self, log_msg): """Runs assemble and checks for logs containing specified message""" assemble(self.circuit, shots=2000, memory=True) self.output.seek(0) # Filter unrelated log lines output_lines = self.output.readlines() assembly_log_lines = [x for x in output_lines if log_msg in x] self.assertTrue(len(assembly_log_lines) == 1) def test_assembly_log_time(self): """Check Total Assembly Time is logged""" self.assertAssembleLog("Total Assembly Time") if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test executing multiple-register circuits on BasicAer.""" from qiskit import BasicAer, execute from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister from qiskit.quantum_info import Operator, Statevector, process_fidelity, state_fidelity from qiskit.test import QiskitTestCase class TestCircuitMultiRegs(QiskitTestCase): """QuantumCircuit Qasm tests.""" def test_circuit_multi(self): """Test circuit multi regs declared at start.""" qreg0 = QuantumRegister(2, "q0") creg0 = ClassicalRegister(2, "c0") qreg1 = QuantumRegister(2, "q1") creg1 = ClassicalRegister(2, "c1") circ = QuantumCircuit(qreg0, qreg1, creg0, creg1) circ.x(qreg0[1]) circ.x(qreg1[0]) meas = QuantumCircuit(qreg0, qreg1, creg0, creg1) meas.measure(qreg0, creg0) meas.measure(qreg1, creg1) qc = circ.compose(meas) backend_sim = BasicAer.get_backend("qasm_simulator") result = execute(qc, backend_sim, seed_transpiler=34342).result() counts = result.get_counts(qc) target = {"01 10": 1024} backend_sim = BasicAer.get_backend("statevector_simulator") result = execute(circ, backend_sim, seed_transpiler=3438).result() state = result.get_statevector(circ) backend_sim = BasicAer.get_backend("unitary_simulator") result = execute(circ, backend_sim, seed_transpiler=3438).result() unitary = Operator(result.get_unitary(circ)) self.assertEqual(counts, target) self.assertAlmostEqual(state_fidelity(Statevector.from_label("0110"), state), 1.0, places=7) self.assertAlmostEqual( process_fidelity(Operator.from_label("IXXI"), unitary), 1.0, places=7 )
https://github.com/qiskit-community/community.qiskit.org
qiskit-community
from qiskit import * from qiskit.circuit import Gate
https://github.com/rodneyosodo/variational-quantum-classifier-on-heartattack
rodneyosodo
from qiskit.ml.datasets import * from qiskit import QuantumCircuit from qiskit.aqua.components.optimizers import COBYLA, ADAM, SPSA, SLSQP, POWELL, L_BFGS_B, TNC, AQGD from qiskit.circuit.library import ZZFeatureMap, RealAmplitudes from qiskit.quantum_info import Statevector import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.preprocessing import normalize from sklearn.model_selection import train_test_split from sklearn.utils import shuffle import warnings warnings.filterwarnings("ignore") %matplotlib inline # constants n = 4 RANDOM_STATE = 42 LR = 1e-3 class_labels = ['yes', 'no'] def normalizeData(DATA_PATH = "../../Data/Processed/data.csv"): """ Normalizes the data """ # Reads the data data = pd.read_csv(DATA_PATH) data = shuffle(data, random_state=RANDOM_STATE) X, Y = data[['sex', 'cp', 'exang', 'oldpeak']].values, data['num'].values # normalize the data X = normalize(X) X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.3, random_state=RANDOM_STATE) return X_train, X_test, Y_train, Y_test X_train, X_test, Y_train, Y_test = normalizeData() sv = Statevector.from_label('0' * n) feature_map = ZZFeatureMap(n, reps=1) var_form = RealAmplitudes(n, reps=1) circuit = feature_map.combine(var_form) circuit.draw(output='mpl', filename="overallcircuit.png") def get_data_dict(params, x): parameters = {} for i, p in enumerate(feature_map.ordered_parameters): parameters[p] = x[i] for i, p in enumerate(var_form.ordered_parameters): parameters[p] = params[i] return parameters def assign_label(bit_string, class_labels): hamming_weight = sum([int(k) for k in list(bit_string)]) is_odd_parity = hamming_weight & 1 if is_odd_parity: return class_labels[1] else: return class_labels[0] def return_probabilities(counts, class_labels): shots = sum(counts.values()) result = {class_labels[0]: 0, class_labels[1]: 0} for key, item in counts.items(): label = assign_label(key, class_labels) result[label] += counts[key]/shots return result def classify(x_list, params, class_labels): qc_list = [] for x in x_list: circ_ = circuit.assign_parameters(get_data_dict(params, x)) qc = sv.evolve(circ_) qc_list += [qc] probs = [] for qc in qc_list: counts = qc.to_counts() prob = return_probabilities(counts, class_labels) probs += [prob] return probs def mse_cost(probs, expected_label): p = probs.get(expected_label) actual, pred = np.array(1), np.array(p) return np.square(np.subtract(actual,pred)).mean() cost_list = [] def cost_function(X, Y, class_labels, params, shots=100, print_value=False): # map training input to list of labels and list of samples cost = 0 training_labels = [] training_samples = [] for sample in X: training_samples += [sample] for label in Y: if label == 0: training_labels += [class_labels[0]] elif label == 1: training_labels += [class_labels[1]] probs = classify(training_samples, params, class_labels) # evaluate costs for all classified samples for i, prob in enumerate(probs): cost += mse_cost(prob, training_labels[i]) cost /= len(training_samples) # print resulting objective function if print_value: print('%.4f' % cost) # return objective value cost_list.append(cost) return cost cost_list = [] optimizer = ADAM(maxiter=100, ) # define objective function for training objective_function = lambda params: cost_function(X_train, Y_train, class_labels, params, print_value=True) # randomly initialize the parameters np.random.seed(RANDOM_STATE) init_params = 2*np.pi*np.random.rand(n*(1)*2) # train classifier opt_params, value, _ = optimizer.optimize(len(init_params), objective_function, initial_point=init_params) # print results print() print('opt_params:', opt_params) print('opt_value: ', value) fig = plt.figure() plt.plot(range(0,901,1), cost_list) plt.xlabel('Steps') plt.ylabel('Cost value') plt.title("ADAM Cost value against steps") plt.show() fig.savefig('../../Output/Figures/costvssteps.jpeg') def test_model(X, Y, class_labels, params): accuracy = 0 training_labels = [] training_samples = [] for sample in X: training_samples += [sample] probs = classify(training_samples, params, class_labels) for i, prob in enumerate(probs): if (prob.get('yes') >= prob.get('no')) and (Y_test[i] == 0): accuracy += 1 elif (prob.get('no') >= prob.get('yes')) and (Y_test[i] == 1): accuracy += 1 accuracy /= len(Y_test) print("Test accuracy: {}\n".format(accuracy)) test_model(X_test, Y_test, class_labels, opt_params)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.circuit.library import UCCSD ansatz = UCCSD() ansatz.num_spin_orbitals = 10 from qiskit_nature.second_q.circuit.library import UCCSD ansatz = UCCSD() ansatz.num_spatial_orbitals = 5 from qiskit_nature.circuit.library import UCC, UVCC ucc = UCC(qubit_converter=None, num_particles=None, num_spin_orbitals=None, excitations=None) uvcc = UVCC(qubit_converter=None, num_modals=None, excitations=None) from qiskit_nature.second_q.circuit.library import UCC, UVCC ucc = UCC(num_spatial_orbitals=None, num_particles=None, excitations=None, qubit_converter=None) uvcc = UVCC(num_modals=None, excitations=None, qubit_converter=None) from qiskit_nature.circuit.library import HartreeFock, VSCF from qiskit_nature.converters.second_quantization import QubitConverter from qiskit_nature.mappers.second_quantization import DirectMapper, JordanWignerMapper hf = HartreeFock( num_spin_orbitals=4, num_particles=(1, 1), qubit_converter=QubitConverter(JordanWignerMapper()) ) vscf = VSCF(num_modals=[2, 2]) from qiskit_nature.second_q.circuit.library import HartreeFock, VSCF from qiskit_nature.second_q.mappers import DirectMapper, JordanWignerMapper, QubitConverter hf = HartreeFock() hf.num_spatial_orbitals = 2 hf.num_particles = (1, 1) hf.qubit_converter = QubitConverter(JordanWignerMapper()) vscf = VSCF() vscf.num_modals = [2, 2] from qiskit.providers.basicaer import BasicAer from qiskit.utils import QuantumInstance from qiskit_nature.algorithms.ground_state_solvers import VQEUCCFactory quantum_instance = QuantumInstance(BasicAer.get_backend("statevector_simulator")) vqe_factory = VQEUCCFactory(quantum_instance=quantum_instance) from qiskit.algorithms.optimizers import SLSQP from qiskit.primitives import Estimator from qiskit_nature.second_q.circuit.library import UCCSD from qiskit_nature.second_q.algorithms.ground_state_solvers import VQEUCCFactory estimator = Estimator() ansatz = UCCSD() optimizer = SLSQP() vqe_factory = VQEUCCFactory(estimator, ansatz, optimizer) from qiskit_nature.algorithms.ground_state_solvers import GroundStateEigensolver, VQEUCCFactory from qiskit_nature.algorithms.excited_states_solvers import QEOM from qiskit_nature.converters.second_quantization import QubitConverter from qiskit_nature.mappers.second_quantization import JordanWignerMapper vqe_factory = VQEUCCFactory() converter = QubitConverter(JordanWignerMapper()) ground_state_solver = GroundStateEigensolver(converter, vqe_factory) qeom = QEOM(ground_state_solver) from qiskit.algorithms.optimizers import SLSQP from qiskit.primitives import Estimator from qiskit_nature.second_q.circuit.library import UCCSD from qiskit_nature.second_q.algorithms.ground_state_solvers import ( GroundStateEigensolver, VQEUCCFactory, ) from qiskit_nature.second_q.algorithms.excited_states_solvers import QEOM from qiskit_nature.second_q.mappers import JordanWignerMapper, QubitConverter estimator = Estimator() ansatz = UCCSD() optimizer = SLSQP() vqe_factory = VQEUCCFactory(estimator, ansatz, optimizer) converter = QubitConverter(JordanWignerMapper()) ground_state_solver = GroundStateEigensolver(converter, vqe_factory) qeom = QEOM(ground_state_solver, estimator) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/grossiM/Qiskit_workshop1019
grossiM
from IPython.display import IFrame IFrame("https://www.youtube.com/embed/hOlOY7NyMfs?start=75&end=126",560,315) # Example of Brute force period finding algorithm def find_period_classical(x, N): n = 1 t = x while t != 1: t *= x t %= N n += 1 return n N = 4 qrQFT = QuantumRegister(N,'qftr') QFT = QuantumCircuit(qrQFT) for i in range(N): QFT.h(qrQFT[i]) for k in range(i+1,N): l = k-i+1 QFT.cu1(2*math.pi/(2**l),qrQFT[k],qrQFT[i]) QFT.draw(output='mpl') import logging logger = logging.getLogger() logger.setLevel(logging.CRITICAL) from qiskit import IBMQ IBMQ.load_account() import qiskit qiskit.__version__ qiskit.__qiskit_version__ from qiskit.aqua.algorithms.quantum_algorithm import QuantumAlgorithm from qiskit.aqua.algorithms import Shor from qiskit import Aer from qiskit.tools.visualization import plot_histogram backend = Aer.get_backend("qasm_simulator") logger.setLevel(logging.CRITICAL) shor = Shor(15,11) result = shor.run(backend) result circuit = shor.construct_circuit(measurement=True) print(qiskit.aqua.utils.summarize_circuits(circuit)) circuit.draw() cloud_backend = IBMQ.get_provider(group='open').get_backend('ibmq_qasm_simulator') cloud_backend execution = qiskit.execute(circuit,cloud_backend) plot_histogram(execution.result().get_counts()) print('i(M/r)= 10000000=', int('10000000',2), ' M=', pow(2,8), ' r/i=', pow(2,8)/int('10000000',2), ' (i=1)') logger.setLevel(logging.DEBUG) counts = execution.result().get_counts() for output_desired in list(counts.keys()): # Get the x_value from the final state qubits success = shor._get_factors(output_desired, int(2 * shor._n)) if success: logger.info('Found factors {} from measurement {}.\n'.format( shor._ret['results'][output_desired], output_desired )) else: logger.info('Cannot find factors from measurement {} because {}\n'.format( output_desired, shor._ret['results'][output_desired] )) logger.setLevel(logging.CRITICAL) shor = Shor(15,7) result = shor.run(backend) result circuit = shor.construct_circuit(measurement=True) print(qiskit.aqua.utils.summarize_circuits(circuit)) circuit.draw() execution = qiskit.execute(circuit,backend) plot_histogram(execution.result().get_counts()) print('i(M/r)= 01000000=', int('01000000',2), ' M=', pow(2,8), ' r/i=', pow(2,8)/int('01000000',2), ' (i=1)') print('i(M/r)= 10000000=', int('10000000',2), ' M=', pow(2,8), ' r/i=', pow(2,8)/int('10000000',2), ' (i=2)') print('i(M/r)= 11000000=', int('11000000',2), ' M=', pow(2,8), ' r/i=', pow(2,8)/int('11000000',2), ' (i=3)') logger.setLevel(logging.DEBUG) counts = execution.result().get_counts() for output_desired in list(counts.keys()): # Get the x_value from the final state qubits success = shor._get_factors(output_desired, int(2 * shor._n)) if success: logger.info('Found factors {} from measurement {}.\n'.format( shor._ret['results'][output_desired], output_desired )) else: logger.info('Cannot find factors from measurement {} because {}\n'.format( output_desired, shor._ret['results'][output_desired] ))
https://github.com/rmlarose/qcbq
rmlarose
#!pip install qiskit # Include the necessary imports for this program import numpy as np from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute # Create a Quantum Register with 1 qubit (wire). qr = QuantumRegister(1) # Create a Classical Register with 1 bit (double wire). cr = ClassicalRegister(1) # Create a Quantum Circuit from the quantum and classical registers circ = QuantumCircuit(qr, cr) # Place an Hadamard gate on the qubit wire circ.h(qr[0]) # Measure the qubit into the classical register circ.measure(qr, cr) # Draw the circuit circ.draw(output='mpl') # Import BasicAer from qiskit import BasicAer # Use BasicAer's qasm_simulator backend_sim = BasicAer.get_backend('qasm_simulator') # Execute the circuit on the qasm simulator, running it 100 times. job_sim = execute(circ, backend_sim, shots=100) # Grab the results from the job. result_sim = job_sim.result() # Print the counts, which are contained in a Python dictionary counts = result_sim.get_counts(circ) print(counts) from qiskit.tools.visualization import plot_histogram # Plot the results on a bar chart plot_histogram(counts) # Include the necessary imports for this program # Create a Quantum Register with 1 qubit (wire). # Create a Classical Register with 1 bit (double wire). # Create a Quantum Circuit from the quantum and classical registers # Place an X gate followed by a Hadamard gate on the qubit wire. The registers are zero-indexed. # Measure the qubit into the classical register # Draw the circuit # Import BasicAer # Use BasicAer's qasm_simulator # Execute the circuit on the qasm simulator, running it 100 times. # Grab the results from the job. # Print the counts, which are contained in a Python dictionary # Plot the results on a bar chart
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../utils/") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) # Pauli Twirling print("created zne_qcs (length:", len(zne_qcs), ")") # optimization_level must be 0 # feed initial_layout here to see the picture of the circuits before casting the job t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") t3_zne_qcs[-3].draw("mpl") # from qiskit.test.mock import FakeJakarta # backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') print("provider:", provider) backend = provider.get_backend("ibmq_jakarta") print(str(backend)) shots = 1 << 13 reps = 8 # unused jobs = [] for _ in range(reps): #! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits, name="calq") meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # we have to feed initial_layout to calibration matrix cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) meas_calibs[0].draw("mpl") dt_now = datetime.datetime.now() print(dt_now) filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl" print(filename) with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) with open(filename, "wb") as f: pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump(backend.properties(), f) filename = "job_ids_ibmq_jakarta_100step_20220413_030821_.pkl" # change here with open(filename, "rb") as f: job_ids_dict = pickle.load(f) job_ids = job_ids_dict["job_ids"] cal_job_id = job_ids_dict["cal_job_id"] retrieved_jobs = [] for job_id in job_ids: retrieved_jobs.append(backend.retrieve_job(job_id)) retrieved_cal_job = backend.retrieve_job(cal_job_id) cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in retrieved_jobs: mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors) rho = expvals_to_valid_rho(num_qubits, zne_expvals) fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids))) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.quantum_info import DensityMatrix from qiskit.visualization import plot_state_city qc = QuantumCircuit(2) qc.h(0) qc.cx(0,1) # plot using a DensityMatrix state = DensityMatrix(qc) plot_state_city(state)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
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()
https://github.com/benkoehlL/Qiskit_Playground
benkoehlL
''' This program uses quantum computing to solve a linear system of equations ''' import numpy as np from qiskit import * from qiskit.tools.visualization import plot_histogram from matplotlib.pyplot import plot, draw, show circuit_name = 'solve_linear_system' backend = Aer.get_backend('qasm_simulator') qr = QuantumRegister(4, 'q') cr = ClassicalRegister(4, 'c') qc = QuantumCircuit(qr, cr, name=circuit_name) # initilise times that we get the result vector # and duration T of the manipulation n0 = 0 n1 = 0 T = 10 for i in range(T): # set the input |b> state qc.x(qr[2]) # set the phase estimation circuit qc.h(qr[0]) qc.h(qr[1]) qc.p(np.pi, qr[0]) qc.p(np.pi/2, qr[1]) qc.cx(qr[1], qr[2]) # The qunatum inverse Fourier transform qc.h(qr[0]) qc.cp(-np.pi/2, qr[0], qr[1]) qc.h(qr[1]) # R (lambda^-1) rotation qc.x(qr[1]) qc.cu3(np.pi/16, 0, 0, qr[0], qr[3]) qc.cu3(np.pi/8, 0, 0, qr[1], qr[3]) # uncompuation qc.x(qr[1]) qc.h(qr[1]) qc.cp(np.pi/2, qr[0], qr[1]) qc.h(qr[0]) qc.cx(qr[1], qr[2]) qc.p(-np.pi/2, qr[1]) qc.p(-np.pi, qr[0]) qc.h(qr[1]) qc.h(qr[0]) # measure the whole quantum register qc.measure(qr, cr) job = execute(qc, backend=backend, shots=8192,) result = job.result() # get the sum of all results n0 += result.get_counts(circuit_name)['1000'] n1 += result.get_counts(circuit_name)['1100'] #plot_histogram(result.get_counts()) #draw() #show(block=True) # reset the circuit qc.reset(qr) # calculate the scale of the elements in result vector and print it p = n0/n1 print('n0 = ', n0, '\t','n1 = ', n1, '\t','p = ', p)
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. """Test cases for the legacy OpenQASM 2 parser.""" # pylint: disable=missing-function-docstring import os from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.circuit import Gate, Parameter from qiskit.converters import ast_to_dag, dag_to_circuit from qiskit.exceptions import QiskitError from qiskit.qasm import Qasm from qiskit.test import QiskitTestCase from qiskit.transpiler.passes import Unroller from qiskit.converters.circuit_to_dag import circuit_to_dag def from_qasm_str(qasm_str): return dag_to_circuit(ast_to_dag(Qasm(data=qasm_str).parse())) def from_qasm_file(path): return dag_to_circuit(ast_to_dag(Qasm(filename=path).parse())) class LoadFromQasmTest(QiskitTestCase): """Test circuit.from_qasm_* set of methods.""" def setUp(self): super().setUp() self.qasm_file_name = "entangled_registers.qasm" self.qasm_dir = os.path.join( os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm" ) self.qasm_file_path = os.path.join(self.qasm_dir, self.qasm_file_name) def test_qasm_file(self): """ Test qasm_file and get_circuit. If all is correct we should get the qasm file loaded in _qasm_file_path """ q_circuit = from_qasm_file(self.qasm_file_path) qr_a = QuantumRegister(4, "a") qr_b = QuantumRegister(4, "b") cr_c = ClassicalRegister(4, "c") cr_d = ClassicalRegister(4, "d") q_circuit_2 = QuantumCircuit(qr_a, qr_b, cr_c, cr_d) q_circuit_2.h(qr_a) q_circuit_2.cx(qr_a, qr_b) q_circuit_2.barrier(qr_a) q_circuit_2.barrier(qr_b) q_circuit_2.measure(qr_a, cr_c) q_circuit_2.measure(qr_b, cr_d) self.assertEqual(q_circuit, q_circuit_2) def test_loading_all_qelib1_gates(self): """Test setting up a circuit with all gates defined in qiskit/qasm/libs/qelib1.inc.""" from qiskit.circuit.library import U1Gate, U2Gate, U3Gate, CU1Gate, CU3Gate, UGate all_gates_qasm = os.path.join(self.qasm_dir, "all_gates.qasm") qasm_circuit = from_qasm_file(all_gates_qasm) ref_circuit = QuantumCircuit(3, 3) # abstract gates (legacy) ref_circuit.append(UGate(0.2, 0.1, 0.6), [0]) ref_circuit.cx(0, 1) # the hardware primitives ref_circuit.append(U3Gate(0.2, 0.1, 0.6), [0]) ref_circuit.append(U2Gate(0.1, 0.6), [0]) ref_circuit.append(U1Gate(0.6), [0]) ref_circuit.id(0) ref_circuit.cx(0, 1) # the standard single qubit gates ref_circuit.u(0.2, 0.1, 0.6, 0) ref_circuit.p(0.6, 0) ref_circuit.x(0) ref_circuit.y(0) ref_circuit.z(0) ref_circuit.h(0) ref_circuit.s(0) ref_circuit.t(0) ref_circuit.sdg(0) ref_circuit.tdg(0) ref_circuit.sx(0) ref_circuit.sxdg(0) # the standard rotations ref_circuit.rx(0.1, 0) ref_circuit.ry(0.1, 0) ref_circuit.rz(0.1, 0) # the barrier ref_circuit.barrier() # the standard user-defined gates ref_circuit.swap(0, 1) ref_circuit.cswap(0, 1, 2) ref_circuit.cy(0, 1) ref_circuit.cz(0, 1) ref_circuit.ch(0, 1) ref_circuit.csx(0, 1) ref_circuit.append(CU1Gate(0.6), [0, 1]) ref_circuit.append(CU3Gate(0.2, 0.1, 0.6), [0, 1]) ref_circuit.cp(0.6, 0, 1) ref_circuit.cu(0.2, 0.1, 0.6, 0, 0, 1) ref_circuit.ccx(0, 1, 2) ref_circuit.crx(0.6, 0, 1) ref_circuit.cry(0.6, 0, 1) ref_circuit.crz(0.6, 0, 1) ref_circuit.rxx(0.2, 0, 1) ref_circuit.rzz(0.2, 0, 1) ref_circuit.measure([0, 1, 2], [0, 1, 2]) self.assertEqual(qasm_circuit, ref_circuit) def test_fail_qasm_file(self): """ Test fail_qasm_file. If all is correct we should get a QiskitError """ self.assertRaises(QiskitError, from_qasm_file, "") def test_qasm_text(self): """ Test qasm_text and get_circuit. If all is correct we should get the qasm file loaded from the string """ qasm_string = "// A simple 8 qubit example\nOPENQASM 2.0;\n" qasm_string += 'include "qelib1.inc";\nqreg a[4];\n' qasm_string += "qreg b[4];\ncreg c[4];\ncreg d[4];\nh a;\ncx a, b;\n" qasm_string += "barrier a;\nbarrier b;\nmeasure a[0]->c[0];\n" qasm_string += "measure a[1]->c[1];\nmeasure a[2]->c[2];\n" qasm_string += "measure a[3]->c[3];\nmeasure b[0]->d[0];\n" qasm_string += "measure b[1]->d[1];\nmeasure b[2]->d[2];\n" qasm_string += "measure b[3]->d[3];" q_circuit = from_qasm_str(qasm_string) qr_a = QuantumRegister(4, "a") qr_b = QuantumRegister(4, "b") cr_c = ClassicalRegister(4, "c") cr_d = ClassicalRegister(4, "d") ref = QuantumCircuit(qr_a, qr_b, cr_c, cr_d) ref.h(qr_a[3]) ref.cx(qr_a[3], qr_b[3]) ref.h(qr_a[2]) ref.cx(qr_a[2], qr_b[2]) ref.h(qr_a[1]) ref.cx(qr_a[1], qr_b[1]) ref.h(qr_a[0]) ref.cx(qr_a[0], qr_b[0]) ref.barrier(qr_b) ref.measure(qr_b, cr_d) ref.barrier(qr_a) ref.measure(qr_a, cr_c) self.assertEqual(len(q_circuit.cregs), 2) self.assertEqual(len(q_circuit.qregs), 2) self.assertEqual(q_circuit, ref) def test_qasm_text_conditional(self): """ Test qasm_text and get_circuit when conditionals are present. """ qasm_string = ( "\n".join( [ "OPENQASM 2.0;", 'include "qelib1.inc";', "qreg q[1];", "creg c0[4];", "creg c1[4];", "x q[0];", "if(c1==4) x q[0];", ] ) + "\n" ) q_circuit = from_qasm_str(qasm_string) qr = QuantumRegister(1, "q") cr0 = ClassicalRegister(4, "c0") cr1 = ClassicalRegister(4, "c1") ref = QuantumCircuit(qr, cr0, cr1) ref.x(qr[0]) ref.x(qr[0]).c_if(cr1, 4) self.assertEqual(len(q_circuit.cregs), 2) self.assertEqual(len(q_circuit.qregs), 1) self.assertEqual(q_circuit, ref) def test_opaque_gate(self): """ Test parse an opaque gate See https://github.com/Qiskit/qiskit-terra/issues/1566. """ qasm_string = ( "\n".join( [ "OPENQASM 2.0;", 'include "qelib1.inc";', "opaque my_gate(theta,phi,lambda) a,b;", "qreg q[3];", "my_gate(1,2,3) q[1],q[2];", ] ) + "\n" ) circuit = from_qasm_str(qasm_string) qr = QuantumRegister(3, "q") expected = QuantumCircuit(qr) expected.append(Gate(name="my_gate", num_qubits=2, params=[1, 2, 3]), [qr[1], qr[2]]) self.assertEqual(circuit, expected) def test_qasm_example_file(self): """Loads qasm/example.qasm.""" qasm_filename = os.path.join(self.qasm_dir, "example.qasm") expected_circuit = from_qasm_str( "\n".join( [ "OPENQASM 2.0;", 'include "qelib1.inc";', "qreg q[3];", "qreg r[3];", "creg c[3];", "creg d[3];", "h q[2];", "cx q[2],r[2];", "measure r[2] -> d[2];", "h q[1];", "cx q[1],r[1];", "measure r[1] -> d[1];", "h q[0];", "cx q[0],r[0];", "measure r[0] -> d[0];", "barrier q[0],q[1],q[2];", "measure q[2] -> c[2];", "measure q[1] -> c[1];", "measure q[0] -> c[0];", ] ) + "\n" ) q_circuit = from_qasm_file(qasm_filename) self.assertEqual(q_circuit, expected_circuit) self.assertEqual(len(q_circuit.cregs), 2) self.assertEqual(len(q_circuit.qregs), 2) def test_qasm_qas_string_order(self): """Test that gates are returned in qasm in ascending order.""" expected_qasm = ( "\n".join( [ "OPENQASM 2.0;", 'include "qelib1.inc";', "qreg q[3];", "h q[0];", "h q[1];", "h q[2];", ] ) + "\n" ) qasm_string = """OPENQASM 2.0; include "qelib1.inc"; qreg q[3]; h q;""" q_circuit = from_qasm_str(qasm_string) self.assertEqual(q_circuit.qasm(), expected_qasm) def test_from_qasm_str_custom_gate1(self): """Test load custom gates (simple case)""" qasm_string = """OPENQASM 2.0; include "qelib1.inc"; gate rinv q {sdg q; h q; sdg q; h q; } qreg qr[1]; rinv qr[0];""" circuit = from_qasm_str(qasm_string) rinv_q = QuantumRegister(1, name="q") rinv_gate = QuantumCircuit(rinv_q, name="rinv") rinv_gate.sdg(rinv_q) rinv_gate.h(rinv_q) rinv_gate.sdg(rinv_q) rinv_gate.h(rinv_q) rinv = rinv_gate.to_instruction() qr = QuantumRegister(1, name="qr") expected = QuantumCircuit(qr, name="circuit") expected.append(rinv, [qr[0]]) self.assertEqualUnroll(["sdg", "h"], circuit, expected) def test_from_qasm_str_custom_gate2(self): """Test load custom gates (no so simple case, different bit order) See: https://github.com/Qiskit/qiskit-terra/pull/3393#issuecomment-551307250 """ qasm_string = """OPENQASM 2.0; include "qelib1.inc"; gate swap2 a,b { cx a,b; cx b,a; // different bit order cx a,b; } qreg qr[3]; swap2 qr[0], qr[1]; swap2 qr[1], qr[2];""" circuit = from_qasm_str(qasm_string) ab_args = QuantumRegister(2, name="ab") swap_gate = QuantumCircuit(ab_args, name="swap2") swap_gate.cx(ab_args[0], ab_args[1]) swap_gate.cx(ab_args[1], ab_args[0]) swap_gate.cx(ab_args[0], ab_args[1]) swap = swap_gate.to_instruction() qr = QuantumRegister(3, name="qr") expected = QuantumCircuit(qr, name="circuit") expected.append(swap, [qr[0], qr[1]]) expected.append(swap, [qr[1], qr[2]]) self.assertEqualUnroll(["cx"], expected, circuit) def test_from_qasm_str_custom_gate3(self): """Test load custom gates (no so simple case, different bit count) See: https://github.com/Qiskit/qiskit-terra/pull/3393#issuecomment-551307250 """ qasm_string = """OPENQASM 2.0; include "qelib1.inc"; gate cswap2 a,b,c { cx c,b; // different bit count ccx a,b,c; //previously defined gate cx c,b; } qreg qr[3]; cswap2 qr[1], qr[0], qr[2];""" circuit = from_qasm_str(qasm_string) abc_args = QuantumRegister(3, name="abc") cswap_gate = QuantumCircuit(abc_args, name="cswap2") cswap_gate.cx(abc_args[2], abc_args[1]) cswap_gate.ccx(abc_args[0], abc_args[1], abc_args[2]) cswap_gate.cx(abc_args[2], abc_args[1]) cswap = cswap_gate.to_instruction() qr = QuantumRegister(3, name="qr") expected = QuantumCircuit(qr, name="circuit") expected.append(cswap, [qr[1], qr[0], qr[2]]) self.assertEqualUnroll(["cx", "h", "tdg", "t"], circuit, expected) def test_from_qasm_str_custom_gate4(self): """Test load custom gates (parameterized) See: https://github.com/Qiskit/qiskit-terra/pull/3393#issuecomment-551307250 """ qasm_string = """OPENQASM 2.0; include "qelib1.inc"; gate my_gate(phi,lambda) q {u(1.5707963267948966,phi,lambda) q;} qreg qr[1]; my_gate(pi, pi) qr[0];""" circuit = from_qasm_str(qasm_string) my_gate_circuit = QuantumCircuit(1, name="my_gate") phi = Parameter("phi") lam = Parameter("lambda") my_gate_circuit.u(1.5707963267948966, phi, lam, 0) my_gate = my_gate_circuit.to_gate() qr = QuantumRegister(1, name="qr") expected = QuantumCircuit(qr, name="circuit") expected.append(my_gate, [qr[0]]) expected = expected.bind_parameters({phi: 3.141592653589793, lam: 3.141592653589793}) self.assertEqualUnroll("u", circuit, expected) def test_from_qasm_str_custom_gate5(self): """Test load custom gates (parameterized, with biop and constant) See: https://github.com/Qiskit/qiskit-terra/pull/3393#issuecomment-551307250 """ qasm_string = """OPENQASM 2.0; include "qelib1.inc"; gate my_gate(phi,lambda) q {u(pi/2,phi,lambda) q;} // biop with pi qreg qr[1]; my_gate(pi, pi) qr[0];""" circuit = from_qasm_str(qasm_string) my_gate_circuit = QuantumCircuit(1, name="my_gate") phi = Parameter("phi") lam = Parameter("lambda") my_gate_circuit.u(1.5707963267948966, phi, lam, 0) my_gate = my_gate_circuit.to_gate() qr = QuantumRegister(1, name="qr") expected = QuantumCircuit(qr, name="circuit") expected.append(my_gate, [qr[0]]) expected = expected.bind_parameters({phi: 3.141592653589793, lam: 3.141592653589793}) self.assertEqualUnroll("u", circuit, expected) def test_from_qasm_str_custom_gate6(self): """Test load custom gates (parameters used in expressions) See: https://github.com/Qiskit/qiskit-terra/pull/3393#issuecomment-591668924 """ qasm_string = """OPENQASM 2.0; include "qelib1.inc"; gate my_gate(phi,lambda) q {rx(phi+pi) q; ry(lambda/2) q;} // parameters used in expressions qreg qr[1]; my_gate(pi, pi) qr[0];""" circuit = from_qasm_str(qasm_string) my_gate_circuit = QuantumCircuit(1, name="my_gate") phi = Parameter("phi") lam = Parameter("lambda") my_gate_circuit.rx(phi + 3.141592653589793, 0) my_gate_circuit.ry(lam / 2, 0) my_gate = my_gate_circuit.to_gate() qr = QuantumRegister(1, name="qr") expected = QuantumCircuit(qr, name="circuit") expected.append(my_gate, [qr[0]]) expected = expected.bind_parameters({phi: 3.141592653589793, lam: 3.141592653589793}) self.assertEqualUnroll(["rx", "ry"], circuit, expected) def test_from_qasm_str_custom_gate7(self): """Test load custom gates (build in functions) See: https://github.com/Qiskit/qiskit-terra/pull/3393#issuecomment-592208951 """ qasm_string = """OPENQASM 2.0; include "qelib1.inc"; gate my_gate(phi,lambda) q {u(asin(cos(phi)/2), phi+pi, lambda/2) q;} // build func qreg qr[1]; my_gate(pi, pi) qr[0];""" circuit = from_qasm_str(qasm_string) qr = QuantumRegister(1, name="qr") expected = QuantumCircuit(qr, name="circuit") expected.u(-0.5235987755982988, 6.283185307179586, 1.5707963267948966, qr[0]) self.assertEqualUnroll("u", circuit, expected) def test_from_qasm_str_nested_custom_gate(self): """Test chain of custom gates See: https://github.com/Qiskit/qiskit-terra/pull/3393#issuecomment-592261942 """ qasm_string = """OPENQASM 2.0; include "qelib1.inc"; gate my_other_gate(phi,lambda) q {u(asin(cos(phi)/2), phi+pi, lambda/2) q;} gate my_gate(phi) r {my_other_gate(phi, phi+pi) r;} qreg qr[1]; my_gate(pi) qr[0];""" circuit = from_qasm_str(qasm_string) qr = QuantumRegister(1, name="qr") expected = QuantumCircuit(qr, name="circuit") expected.u(-0.5235987755982988, 6.283185307179586, 3.141592653589793, qr[0]) self.assertEqualUnroll("u", circuit, expected) def test_from_qasm_str_delay(self): """Test delay instruction/opaque-gate See: https://github.com/Qiskit/qiskit-terra/issues/6510 """ qasm_string = """OPENQASM 2.0; include "qelib1.inc"; opaque delay(time) q; qreg q[1]; delay(172) q[0];""" circuit = from_qasm_str(qasm_string) qr = QuantumRegister(1, name="q") expected = QuantumCircuit(qr, name="circuit") expected.delay(172, qr[0]) self.assertEqualUnroll("u", circuit, expected) def assertEqualUnroll(self, basis, circuit, expected): """Compares the dags after unrolling to basis""" circuit_dag = circuit_to_dag(circuit) expected_dag = circuit_to_dag(expected) circuit_result = Unroller(basis).run(circuit_dag) expected_result = Unroller(basis).run(expected_dag) self.assertEqual(circuit_result, expected_result)
https://github.com/sebasmos/QuantumVE
sebasmos
from __future__ import print_function import argparse import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision import datasets, transforms from torch.optim.lr_scheduler import StepLR from torch.utils.data import random_split from torch.utils.data import Subset, DataLoader, random_split from torchvision import datasets, transforms import torch.optim as optim from torch.optim.lr_scheduler import StepLR import matplotlib.pyplot as plt import os import numpy as np from sklearn.metrics import confusion_matrix, classification_report import pandas as pd # from MAE code from util.datasets import build_dataset import argparse import util.misc as misc import argparse import datetime import json import numpy as np import os import time from pathlib import Path import torch import torch.backends.cudnn as cudnn from torch.utils.tensorboard import SummaryWriter import timm assert timm.__version__ == "0.3.2" # version check from timm.models.layers import trunc_normal_ from timm.data.mixup import Mixup from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy import util.lr_decay as lrd import util.misc as misc from util.datasets import build_dataset from util.pos_embed import interpolate_pos_embed from util.misc import NativeScalerWithGradNormCount as NativeScaler import models_vit import sys import os import torch import numpy as np import matplotlib.pyplot as plt from PIL import Image import models_mae import torch; print(f'numpy version: {np.__version__}\nCUDA version: {torch.version.cuda} - Torch versteion: {torch.__version__} - device count: {torch.cuda.device_count()}') from engine_finetune import train_one_epoch, evaluate from timm.data import Mixup from timm.utils import accuracy from sklearn.metrics import confusion_matrix, classification_report import seaborn as sns from sklearn.preprocessing import LabelBinarizer from sklearn.metrics import roc_curve, auc import matplotlib.pyplot as plt from itertools import cycle import numpy as np from sklearn.metrics import precision_score, recall_score, f1_score imagenet_mean = np.array([0.485, 0.456, 0.406]) imagenet_std = np.array([0.229, 0.224, 0.225]) def show_image(image, title=''): # image is [H, W, 3] assert image.shape[2] == 3 plt.imshow(torch.clip((image * imagenet_std + imagenet_mean) * 255, 0, 255).int()) plt.title(title, fontsize=16) plt.axis('off') return def prepare_model(chkpt_dir, arch='mae_vit_large_patch16'): # build model model = getattr(models_mae, arch)() # load model checkpoint = torch.load(chkpt_dir, map_location='cpu') msg = model.load_state_dict(checkpoint['model'], strict=False) print(msg) return model def run_one_image(img, model): x = torch.tensor(img) # make it a batch-like x = x.unsqueeze(dim=0) x = torch.einsum('nhwc->nchw', x) # run MAE loss, y, mask = model(x.float(), mask_ratio=0.75) y = model.unpatchify(y) y = torch.einsum('nchw->nhwc', y).detach().cpu() # visualize the mask mask = mask.detach() mask = mask.unsqueeze(-1).repeat(1, 1, model.patch_embed.patch_size[0]**2 *3) # (N, H*W, p*p*3) mask = model.unpatchify(mask) # 1 is removing, 0 is keeping mask = torch.einsum('nchw->nhwc', mask).detach().cpu() x = torch.einsum('nchw->nhwc', x) # masked image im_masked = x * (1 - mask) # MAE reconstruction pasted with visible patches im_paste = x * (1 - mask) + y * mask # make the plt figure larger plt.rcParams['figure.figsize'] = [24, 24] plt.subplot(1, 4, 1) show_image(x[0], "original") plt.subplot(1, 4, 2) show_image(im_masked[0], "masked") plt.subplot(1, 4, 3) show_image(y[0], "reconstruction") plt.subplot(1, 4, 4) show_image(im_paste[0], "reconstruction + visible") plt.show() # Set the seed for PyTorch torch.manual_seed(42) parser = argparse.ArgumentParser('MAE fine-tuning for image classification', add_help=False) parser.add_argument('--batch_size', default=32, type=int, help='Batch size per GPU (effective batch size is batch_size * accum_iter * # gpus') parser.add_argument('--epochs', default=100, type=int) parser.add_argument('--accum_iter', default=4, type=int, help='Accumulate gradient iterations (for increasing the effective batch size under memory constraints)') # Model parameters parser.add_argument('--model', default='vit_base_patch16', type=str, metavar='MODEL', help='Name of model to train') parser.add_argument('--input_size', default=224, type=int, help='images input size') parser.add_argument('--drop_path', type=float, default=0.1, metavar='PCT', help='Drop path rate (default: 0.1)') # Optimizer parameters parser.add_argument('--clip_grad', type=float, default=None, metavar='NORM', help='Clip gradient norm (default: None, no clipping)') parser.add_argument('--weight_decay', type=float, default=0.05, help='weight decay (default: 0.05)') parser.add_argument('--lr', type=float, default=None, metavar='LR', help='learning rate (absolute lr)') parser.add_argument('--blr', type=float, default=5e-4, metavar='LR', help='base learning rate: absolute_lr = base_lr * total_batch_size / 256') parser.add_argument('--layer_decay', type=float, default=0.65, help='layer-wise lr decay from ELECTRA/BEiT') parser.add_argument('--min_lr', type=float, default=1e-6, metavar='LR', help='lower lr bound for cyclic schedulers that hit 0') parser.add_argument('--warmup_epochs', type=int, default=5, metavar='N', help='epochs to warmup LR') # Augmentation parameters parser.add_argument('--color_jitter', type=float, default=None, metavar='PCT', help='Color jitter factor (enabled only when not using Auto/RandAug)') parser.add_argument('--aa', type=str, default='rand-m9-mstd0.5-inc1', metavar='NAME', help='Use AutoAugment policy. "v0" or "original". " + "(default: rand-m9-mstd0.5-inc1)'), parser.add_argument('--smoothing', type=float, default=0.1, help='Label smoothing (default: 0.1)') # * Random Erase params parser.add_argument('--reprob', type=float, default=0.25, metavar='PCT', help='Random erase prob (default: 0.25)') parser.add_argument('--remode', type=str, default='pixel', help='Random erase mode (default: "pixel")') parser.add_argument('--recount', type=int, default=1, help='Random erase count (default: 1)') parser.add_argument('--resplit', action='store_true', default=False, help='Do not random erase first (clean) augmentation split') # * Mixup params parser.add_argument('--mixup', type=float, default=0.8, help='mixup alpha, mixup enabled if > 0.') parser.add_argument('--cutmix', type=float, default=1.0, help='cutmix alpha, cutmix enabled if > 0.') parser.add_argument('--cutmix_minmax', type=float, nargs='+', default=None, help='cutmix min/max ratio, overrides alpha and enables cutmix if set (default: None)') parser.add_argument('--mixup_prob', type=float, default=1.0, help='Probability of performing mixup or cutmix when either/both is enabled') parser.add_argument('--mixup_switch_prob', type=float, default=0.5, help='Probability of switching to cutmix when both mixup and cutmix enabled') parser.add_argument('--mixup_mode', type=str, default='batch', help='How to apply mixup/cutmix params. Per "batch", "pair", or "elem"') # * Finetuning params parser.add_argument('--finetune', default='mae_pretrain_vit_base.pth', help='finetune from checkpoint') parser.add_argument('--global_pool', action='store_true') parser.set_defaults(global_pool=True) parser.add_argument('--cls_token', action='store_false', dest='global_pool', help='Use class token instead of global pool for classification') # Dataset parameters parser.add_argument('--data_path', default='/media/enc/vera1/sebastian/data/ABGQI_mel_spectrograms', type=str, help='dataset path') parser.add_argument('--nb_classes', default=5, type=int, help='number of the classification types') parser.add_argument('--output_dir', default='quinn_5_classes', help='path where to save, empty for no saving') parser.add_argument('--log_dir', default='./output_dir', help='path where to tensorboard log') parser.add_argument('--device', default='cuda', help='device to use for training / testing') parser.add_argument('--seed', default=0, type=int) parser.add_argument('--resume', default='./quinn_5_classes/checkpoint-999.pth', help='resume from checkpoint') parser.add_argument('--start_epoch', default=0, type=int, metavar='N', help='start epoch') parser.add_argument('--eval',default=True, action='store_true', help='Perform evaluation only') parser.add_argument('--dist_eval', action='store_true', default=False, help='Enabling distributed evaluation (recommended during training for faster monitor') parser.add_argument('--num_workers', default=10, type=int) parser.add_argument('--pin_mem', action='store_true', help='Pin CPU memory in DataLoader for more efficient (sometimes) transfer to GPU.') parser.add_argument('--no_pin_mem', action='store_false', dest='pin_mem') parser.set_defaults(pin_mem=True) # distributed training parameters parser.add_argument('--world_size', default=1, type=int, help='number of distributed processes') parser.add_argument('--local_rank', default=-1, type=int) parser.add_argument('--dist_on_itp', action='store_true') parser.add_argument('--dist_url', default='env://', help='url used to set up distributed training') args, unknown = parser.parse_known_args() misc.init_distributed_mode(args) print("{}".format(args).replace(', ', ',\n')) device = torch.device(args.device) misc.init_distributed_mode(args) # print('job dir: {}'.format(os.path.dirname(os.path.realpath(__file__)))) print("{}".format(args).replace(', ', ',\n')) device = torch.device(args.device) # fix the seed for reproducibility seed = args.seed + misc.get_rank() torch.manual_seed(seed) np.random.seed(seed) cudnn.benchmark = True dataset_train = build_dataset(is_train=True, args=args) dataset_val = build_dataset(is_train=False, args=args) if True: # args.distributed: num_tasks = misc.get_world_size() global_rank = misc.get_rank() sampler_train = torch.utils.data.DistributedSampler( dataset_train, num_replicas=num_tasks, rank=global_rank, shuffle=True ) print("Sampler_train = %s" % str(sampler_train)) if args.dist_eval: if len(dataset_val) % num_tasks != 0: print('Warning: Enabling distributed evaluation with an eval dataset not divisible by process number. ' 'This will slightly alter validation results as extra duplicate entries are added to achieve ' 'equal num of samples per-process.') sampler_val = torch.utils.data.DistributedSampler( dataset_val, num_replicas=num_tasks, rank=global_rank, shuffle=True) # shuffle=True to reduce monitor bias else: sampler_val = torch.utils.data.SequentialSampler(dataset_val) else: sampler_train = torch.utils.data.RandomSampler(dataset_train) sampler_val = torch.utils.data.SequentialSampler(dataset_val) if global_rank == 0 and args.log_dir is not None and not args.eval: os.makedirs(args.log_dir, exist_ok=True) log_writer = SummaryWriter(log_dir=args.log_dir) else: log_writer = None data_loader_train = torch.utils.data.DataLoader( dataset_train, sampler=sampler_train, batch_size=args.batch_size, num_workers=args.num_workers, pin_memory=args.pin_mem, drop_last=True, ) data_loader_val = torch.utils.data.DataLoader( dataset_val, sampler=sampler_val, batch_size=args.batch_size, num_workers=args.num_workers, pin_memory=args.pin_mem, drop_last=False ) # #Liberia Validacion cruzada # from sklearn.model_selection import KFold # # K-fold cross-validation # num_splits = 5 # ajusta el nΓΊmero de splits segΓΊn tus necesidades # kf = KFold(n_splits=num_splits, shuffle=True, random_state=42) # for fold, (train_index, val_index) in enumerate(kf.split(dataset_train)): # print(f"\nTraining on Fold {fold + 1}/{num_splits}:") # # create train and validation sets for this fold # train_dataset_fold = Subset(dataset_train, train_index) # val_dataset_fold = Subset(dataset_train, val_index) # data_loader_train = torch.utils.data.DataLoader( # train_dataset_fold, sampler=torch.utils.data.RandomSampler(train_dataset_fold), # batch_size=args.batch_size, # num_workers=args.num_workers, # pin_memory=args.pin_mem, # drop_last=True, # ) # data_loader_val = torch.utils.data.DataLoader( # val_dataset_fold, sampler=torch.utils.data.SequentialSampler(val_dataset_fold), # batch_size=args.batch_size, # num_workers=args.num_workers, # pin_memory=args.pin_mem, # drop_last=False # ) mixup_fn = None mixup_active = args.mixup > 0 or args.cutmix > 0. or args.cutmix_minmax is not None if mixup_active: print("Mixup is activated!") mixup_fn = Mixup( mixup_alpha=args.mixup, cutmix_alpha=args.cutmix, cutmix_minmax=args.cutmix_minmax, prob=args.mixup_prob, switch_prob=args.mixup_switch_prob, mode=args.mixup_mode, label_smoothing=args.smoothing, num_classes=args.nb_classes) model = models_vit.__dict__[args.model]( num_classes=args.nb_classes, drop_path_rate=args.drop_path, global_pool=args.global_pool, ) if args.finetune and not args.eval: checkpoint = torch.load(args.finetune, map_location='cpu') print("Load pre-trained checkpoint from: %s" % args.finetune) checkpoint_model = checkpoint['model'] state_dict = model.state_dict() for k in ['head.weight', 'head.bias']: if k in checkpoint_model and checkpoint_model[k].shape != state_dict[k].shape: print(f"Removing key {k} from pretrained checkpoint") del checkpoint_model[k] # interpolate position embedding interpolate_pos_embed(model, checkpoint_model) # load pre-trained model msg = model.load_state_dict(checkpoint_model, strict=False) print(msg) if args.global_pool: assert set(msg.missing_keys) == {'head.weight', 'head.bias', 'fc_norm.weight', 'fc_norm.bias'} else: assert set(msg.missing_keys) == {'head.weight', 'head.bias'} # manually initialize fc layer trunc_normal_(model.head.weight, std=2e-5) model.to(device) model_without_ddp = model n_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad) print("Model = %s" % str(model_without_ddp)) print('number of params (M): %.2f' % (n_parameters / 1.e6)) eff_batch_size = args.batch_size * args.accum_iter * misc.get_world_size() if args.lr is None: # only base_lr is specified args.lr = args.blr * eff_batch_size / 256 print("base lr: %.2e" % (args.lr * 256 / eff_batch_size)) print("actual lr: %.2e" % args.lr) print("accumulate grad iterations: %d" % args.accum_iter) print("effective batch size: %d" % eff_batch_size) if args.distributed: model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu]) model_without_ddp = model.module # build optimizer with layer-wise lr decay (lrd) param_groups = lrd.param_groups_lrd(model_without_ddp, args.weight_decay, no_weight_decay_list=model_without_ddp.no_weight_decay(), layer_decay=args.layer_decay ) optimizer = torch.optim.AdamW(param_groups, lr=args.lr) loss_scaler = NativeScaler() if mixup_fn is not None: # smoothing is handled with mixup label transform criterion = SoftTargetCrossEntropy() elif args.smoothing > 0.: criterion = LabelSmoothingCrossEntropy(smoothing=args.smoothing) else: criterion = torch.nn.CrossEntropyLoss() print("criterion = %s" % str(criterion)) misc.load_model(args=args, model_without_ddp=model_without_ddp, optimizer=optimizer, loss_scaler=loss_scaler) if args.eval: test_stats = evaluate(data_loader_val, model, device) print(f"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%") # exit(0) train = False if train: print(f"Start training for {args.epochs} epochs") start_time = time.time() max_accuracy = 0.0 for epoch in range(args.start_epoch, args.epochs): if args.distributed: data_loader_train.sampler.set_epoch(epoch) train_stats = train_one_epoch( model, criterion, data_loader_train, optimizer, device, epoch, loss_scaler, args.clip_grad, mixup_fn, log_writer=log_writer, args=args ) if args.output_dir: misc.save_model( args=args, model=model, model_without_ddp=model_without_ddp, optimizer=optimizer, loss_scaler=loss_scaler, epoch=epoch) test_stats = evaluate(data_loader_val, model, device) print(f"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%") max_accuracy = max(max_accuracy, test_stats["acc1"]) print(f'Max accuracy: {max_accuracy:.2f}%') if log_writer is not None: log_writer.add_scalar('perf/test_acc1', test_stats['acc1'], epoch) log_writer.add_scalar('perf/test_acc5', test_stats['acc5'], epoch) log_writer.add_scalar('perf/test_loss', test_stats['loss'], epoch) log_stats = {**{f'train_{k}': v for k, v in train_stats.items()}, **{f'test_{k}': v for k, v in test_stats.items()}, 'epoch': epoch, 'n_parameters': n_parameters} if args.output_dir and misc.is_main_process(): if log_writer is not None: log_writer.flush() with open(os.path.join(args.output_dir, "log.txt"), mode="a", encoding="utf-8") as f: f.write(json.dumps(log_stats) + "\n") total_time = time.time() - start_time total_time_str = str(datetime.timedelta(seconds=int(total_time))) print('Training time {}'.format(total_time_str)) EXPERIMENT_NAME = "quinn_5_classes" saving_model = f"{EXPERIMENT_NAME}/models" os.makedirs(saving_model, exist_ok = True) os.makedirs(EXPERIMENT_NAME, exist_ok=True) if args.eval: test_stats = evaluate(data_loader_val, model, device) print(f"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%") @torch.no_grad() def evaluate_test(data_loader, model, device): criterion = torch.nn.CrossEntropyLoss() metric_logger = misc.MetricLogger(delimiter=" ") header = 'Test:' # switch to evaluation mode model.eval() all_predictions = [] all_labels = [] for batch in metric_logger.log_every(data_loader, 10, header): images = batch[0] target = batch[-1] images = images.to(device, non_blocking=True) target = target.to(device, non_blocking=True) # compute output with torch.cuda.amp.autocast(): output = model(images) loss = criterion(output, target)# pred = output.argmax(dim=1) all_predictions.append(pred.cpu().numpy())# ADDED all_labels.append(target.cpu().numpy())# ADDED acc1, acc5 = accuracy(output, target, topk=(1, 5)) batch_size = images.shape[0] metric_logger.update(loss=loss.item()) metric_logger.meters['acc1'].update(acc1.item(), n=batch_size) metric_logger.meters['acc5'].update(acc5.item(), n=batch_size) all_predictions = np.array(all_predictions)#.squeeze(0) all_labels = np.array(all_labels)#.squeeze(0) # gather the stats from all processes metric_logger.synchronize_between_processes() print('* Acc@1 {top1.global_avg:.3f} Acc@5 {top5.global_avg:.3f} loss {losses.global_avg:.3f}' .format(top1=metric_logger.acc1, top5=metric_logger.acc5, losses=metric_logger.loss)) # return return {k: meter.global_avg for k, meter in metric_logger.meters.items()}, np.concatenate(all_predictions, axis=0), np.concatenate(all_labels, axis=0) metrics, all_predictions, all_labels = evaluate_test(data_loader_val, model, device) # print(f"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%") metrics all_predictions unique_classes = np.unique(np.concatenate((all_labels, all_predictions))) unique_classes confusion_mat = confusion_matrix(all_labels, all_predictions, labels=unique_classes) conf_matrix = pd.DataFrame(confusion_mat, index=unique_classes, columns=unique_classes) conf_matrix unique_classes = np.unique(np.concatenate((all_labels, all_predictions))) confusion_mat = confusion_matrix(all_labels, all_predictions, labels=unique_classes) conf_matrix = pd.DataFrame(confusion_mat, index=unique_classes, columns=unique_classes) # Plot the confusion matrix using seaborn plt.figure(figsize=(5, 4)) ax = sns.heatmap(conf_matrix, annot=True, fmt='.1f', cmap=sns.cubehelix_palette(as_cmap=True), linewidths=0.1, cbar=True) # Set labels and ticks ax.set_xlabel('Predicted Labels') ax.set_ylabel('True Labels') # Set x and y ticks using the unique classes ax.set_xticks(range(len(unique_classes))) ax.set_yticks(range(len(unique_classes))) # Set x and y ticks at the center of the cells ax.set_xticks([i + 0.5 for i in range(len(unique_classes))]) ax.set_yticks([i + 0.5 for i in range(len(unique_classes))]) plt.show() def plot_multiclass_roc_curve(all_labels, all_predictions, EXPERIMENT_NAME="."): # Step 1: Label Binarization label_binarizer = LabelBinarizer() y_onehot = label_binarizer.fit_transform(all_labels) all_predictions_hot = label_binarizer.transform(all_predictions) # Step 2: Calculate ROC curves fpr = dict() tpr = dict() roc_auc = dict() unique_classes = range(y_onehot.shape[1]) for i in unique_classes: fpr[i], tpr[i], _ = roc_curve(y_onehot[:, i], all_predictions_hot[:, i]) roc_auc[i] = auc(fpr[i], tpr[i]) # Step 3: Plot ROC curves fig, ax = plt.subplots(figsize=(8, 8)) # Micro-average ROC curve fpr_micro, tpr_micro, _ = roc_curve(y_onehot.ravel(), all_predictions_hot.ravel()) roc_auc_micro = auc(fpr_micro, tpr_micro) plt.plot( fpr_micro, tpr_micro, label=f"micro-average ROC curve (AUC = {roc_auc_micro:.2f})", color="deeppink", linestyle=":", linewidth=4, ) # Macro-average ROC curve all_fpr = np.unique(np.concatenate([fpr[i] for i in unique_classes])) mean_tpr = np.zeros_like(all_fpr) for i in unique_classes: mean_tpr += np.interp(all_fpr, fpr[i], tpr[i]) mean_tpr /= len(unique_classes) fpr_macro = all_fpr tpr_macro = mean_tpr roc_auc_macro = auc(fpr_macro, tpr_macro) plt.plot( fpr_macro, tpr_macro, label=f"macro-average ROC curve (AUC = {roc_auc_macro:.2f})", color="navy", linestyle=":", linewidth=4, ) # Individual class ROC curves with unique colors colors = plt.cm.rainbow(np.linspace(0, 1, len(unique_classes))) for class_id, color in zip(unique_classes, colors): plt.plot( fpr[class_id], tpr[class_id], color=color, label=f"ROC curve for Class {class_id} (AUC = {roc_auc[class_id]:.2f})", linewidth=2, ) plt.plot([0, 1], [0, 1], color='gray', linestyle='--', linewidth=2) # Add diagonal line for reference plt.axis("equal") plt.xlabel("False Positive Rate") plt.ylabel("True Positive Rate") plt.title("Extension of Receiver Operating Characteristic\n to One-vs-Rest multiclass") plt.legend() plt.savefig(f'{EXPERIMENT_NAME}/roc_curve.png') plt.show() # Example usage: plot_multiclass_roc_curve(all_labels, all_predictions, EXPERIMENT_NAME) # def visualize_predictions(model, val_loader, device, type_label=None, dataset_type=1, unique_classes=np.array([0, 1, 2, 3, 4, 5, 6])): # criterion = torch.nn.CrossEntropyLoss() # metric_logger = misc.MetricLogger(delimiter=" ") # header = 'Test:' # # switch to evaluation mode # model.eval() # all_predictions = [] # all_labels = [] # for batch in metric_logger.log_every(val_loader, 10, header): # images = batch[0] # target = batch[-1] # images = images.to(device, non_blocking=True) # target = target.to(device, non_blocking=True) # # compute output # with torch.cuda.amp.autocast(): # output = model(images) # loss = criterion(output, target)# # pred = output.argmax(dim=1) # all_predictions.append(pred.cpu().numpy())# ADDED # all_labels.append(target.cpu().numpy())# ADDED # acc1, acc5 = accuracy(output, target, topk=(1, 5)) # batch_size = images.shape[0] # metric_logger.update(loss=loss.item()) # metric_logger.meters['acc1'].update(acc1.item(), n=batch_size) # metric_logger.meters['acc5'].update(acc5.item(), n=batch_size) # all_predictions = np.array(all_predictions)#.squeeze(0) # all_labels = np.array(all_labels)#.squeeze(0) # if type_label is None: # type_label = unique_classes # # Create a 4x4 grid for visualization # num_rows = 4 # num_cols = 4 # plt.figure(figsize=(12, 12)) # for i in range(num_rows * num_cols): # plt.subplot(num_rows, num_cols, i + 1) # idx = np.random.randint(len(all_labels)) # import pdb;pdb.set_trace() # plt.imshow(images[idx].cpu().numpy().squeeze(), cmap='gray') # # Use the class names instead of numeric labels for Fashion MNIST # if dataset_type == 1: # class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot'] # predicted_class = class_names[all_predictions[idx]] # actual_class = class_names[all_labels[idx]] # else: # predicted_class = all_predictions[idx] # actual_class = all_labels[idx] # plt.title(f'Pred: {predicted_class}\nActual: {actual_class}') # plt.axis('off') # plt.tight_layout() # plt.show() # visualize_predictions(model, data_loader_val, device, dataset_type=2, unique_classes=unique_classes) unique_classes report = classification_report(all_labels, all_predictions, target_names=unique_classes,output_dict=True)# Mostrar el informe de df = pd.DataFrame(report).transpose() df.to_csv(os.path.join(EXPERIMENT_NAME, "confusion_matrix.csv")) print(df) # Calculate precision, recall, and specificity (micro-averaged) precision = precision_score(all_labels, all_predictions, average='micro') recall = recall_score(all_labels, all_predictions, average='micro') # Calculate true negatives, false positives, and specificity (micro-averaged) tn = np.sum((all_labels != 1) & (all_predictions != 1)) fp = np.sum((all_labels != 1) & (all_predictions == 1)) specificity = tn / (tn + fp) # Calculate F1 score (weighted average) f1 = f1_score(all_labels, all_predictions, average='weighted') evaluation_metrics = { "Acc1": metrics['acc1'], # Add acc1 metric "Acc5": metrics['acc5'], # Add acc5 metric "loss": metrics['loss'], # Add acc5 metric "F1 Score": [f1], "Precision": [precision], "Recall": [recall], "Specificity": [specificity] } evaluation_metrics # Create a DataFrame from the dictionary df = pd.DataFrame(evaluation_metrics) # Save the DataFrame to a CSV file df.to_csv(f'{EXPERIMENT_NAME}/evaluation_metrics_for_table.csv', index=False) df
https://github.com/QuTech-Delft/quantuminspire
QuTech-Delft
import logging import os from projectq import MainEngine from projectq.setups import linear from projectq.ops import H, Rx, Rz, CNOT, CZ, Measure, All from quantuminspire.credentials import get_authentication from quantuminspire.api import QuantumInspireAPI from quantuminspire.projectq.backend_qx import QIBackend QI_URL = os.getenv('API_URL', 'https://api.quantum-inspire.com/') authentication = get_authentication() qi_api = QuantumInspireAPI(QI_URL, authentication) projectq_backend = QIBackend(quantum_inspire_api=qi_api) engine = MainEngine(backend=projectq_backend) # create default compiler (simulator back-end) qubits = engine.allocate_qureg(5) q1 = qubits[0] q2 = qubits[-1] H | q1 # apply a Hadamard gate CNOT | (q1, q2) All(Measure) | qubits # measure the qubits engine.flush() # flush all gates (and execute measurements) print("Measured {}".format(','.join([str(int(q)) for q in qubits]))) print('Probabilities: %s' % (projectq_backend.get_probabilities(qubits),)) print(projectq_backend.cqasm()) projectq_backend = QIBackend(quantum_inspire_api=qi_api) engine_list = linear.get_engine_list(num_qubits=5, one_qubit_gates=(Rx, Rz), two_qubit_gates=(CNOT,)) engine = MainEngine(backend=projectq_backend, engine_list=engine_list) # create default compiler (simulator back-end) qubits = engine.allocate_qureg(5) q1 = qubits[0] q2 = qubits[-1] H | q1 # apply a Hadamard gate CNOT | (q1, q2) All(Measure) | qubits # measure the qubits engine.flush() # flush all gates (and execute measurements) print("Measured {}".format(','.join([str(int(q)) for q in qubits]))) print('Probabilities: %s' % (projectq_backend.get_probabilities(qubits),)) print(projectq_backend.cqasm()) current_mapping = engine.mapper.current_mapping for l, p in current_mapping.items(): print('mapping logical qubit %d to physical qubit %d' % (l, p))
https://github.com/1chooo/Quantum-Oracle
1chooo
#Program 7.1 Show Bloch sphere for computational basis and Fourier basis from qiskit import QuantumRegister, QuantumCircuit from qiskit.quantum_info import Statevector print('='*60,'\nBelow are computational bases:') cb = QuantumRegister(2,'computational_basis') qc1 = QuantumCircuit(cb) qc1.x(1) display(qc1.draw('mpl')) state1 = Statevector.from_instruction(qc1) display(state1.draw('bloch')) print('='*60,'\nBelow are Fourier bases:') fb = QuantumRegister(2,'fourier_basis') qc2 = QuantumCircuit(fb) qc2.x(1) qc2.h([0,1]) display(qc2.draw('mpl')) state2 = Statevector.from_instruction(qc2) display(state2.draw('bloch')) #Program 7.2 Build 2-qubit QFT quantum circuit from qiskit import QuantumRegister, QuantumCircuit from math import pi ar = QuantumRegister(2,'a') qc = QuantumCircuit(ar) qc.h(1) qc.cp(pi/2, 0, 1) qc.h(0) qc.swap(0,1) print('Below is the quantum Fourier transform (QFT) circuit:') display(qc.draw('mpl')) #Program 7.3 Apply QFT to qubit with various initial state from qiskit import QuantumRegister, QuantumCircuit from qiskit.quantum_info import Statevector from qiskit.visualization import array_to_latex from math import pi two_bits = ['00','01','10','11'] for bits in two_bits: ar = QuantumRegister(2,'a') qc = QuantumCircuit(ar) qc.initialize(bits,ar) state1 = Statevector.from_instruction(qc) print('='*75,'\nBelow is for qubits: q0 =',bits[0],'; q1 =',bits[1]) display(array_to_latex(state1, prefix='\\text{Statevector before QFT: }')) display(state1.draw('bloch')) qc.h(1) qc.cp(pi/2, 0, 1) qc.h(0) qc.swap(0,1) state2 = Statevector.from_instruction(qc) #print('Below is the state after QFT') display(array_to_latex(state2, prefix='\\text{Statevector after QFT: }')) display(state2.draw('bloch')) #Program 7.4 Define funciton to build n-qubit QFT quantum circuit from qiskit import QuantumRegister, QuantumCircuit from math import pi def qft(n): ar = QuantumRegister(n,'a') qc = QuantumCircuit(ar) for hbit in range(n-1,-1,-1): qc.h(hbit) for cbit in range(hbit): qc.cp(pi/2**(hbit-cbit), cbit, hbit) for bit in range(n//2): qc.swap(bit,n-bit-1) return qc for i in range(1,5): print('Below is the QFT circuit of',i,'qubit(s):') display(qft(i).draw('mpl')) #Program 7.5 Define function to build n-qubit IQFT quantum circuit from qiskit import QuantumRegister, QuantumCircuit from math import pi def iqft(n): br = QuantumRegister(n,'b') qc = QuantumCircuit(br) for sbit in range(n//2): #sbit: for swap qubit qc.swap(sbit,n-sbit-1) for hbit in range(0,n,1): #hbit: for h-gate qubit for cbit in range(hbit-1,-1,-1): #cbit: for count qubit qc.cp(-pi/2**(hbit-cbit), cbit, hbit) qc.h(hbit) # qc.name = "IQFT" return qc for i in range(1,5): print('Below is the IQFT circuit of',i,'qubit(s):') display(iqft(i).draw('mpl')) #Program 7.6 Apply QFT and then IQFT to qubit from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector qc = QuantumCircuit(4) qc.initialize('1011',range(4)) state0 = Statevector.from_instruction(qc) qc.append(qft(4).to_gate(label='QFT'),range(4)) state1 = Statevector.from_instruction(qc) qc.append(iqft(4).to_gate(label='IQFT'),range(4)) state2 = Statevector.from_instruction(qc) display(qc.draw('mpl')) print('Statevector before QFT:') display(state0.draw('bloch')) print('Statevector after QFT:') display(state1.draw('bloch')) print('Statevector after IQFT:') display(state2.draw('bloch')) #Program 7.7 Use QPE to estimate phase of S-gate from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister, execute from qiskit.providers.aer import AerSimulator from qiskit.visualization import plot_histogram from math import pi count_no = 2 #the number of count qubits countreg = QuantumRegister(count_no,'count') psireg = QuantumRegister(1,'psi') creg = ClassicalRegister(count_no,'c') qc = QuantumCircuit(countreg,psireg,creg) for countbit in range(count_no): qc.h(countbit) qc.x(psireg) repeat = 1 for countbit in range(count_no): for r in range(repeat): qc.cp(pi/2,countbit,psireg) repeat *= 2 qc.barrier() for sbit in range(count_no//2): #sbit: for swap qubit qc.swap(sbit,count_no-sbit-1) for hbit in range(0,count_no,1): #hbit: for h-gate qubit for cbit in range(hbit-1,-1,-1): #cbit: for count qubit qc.cp(-pi/2**(hbit-cbit), cbit, hbit) qc.h(hbit) qc.barrier() qc.measure(range(count_no),range(count_no)) display(qc.draw('mpl')) sim = AerSimulator() job=execute(qc, backend=sim, shots=1000) result = job.result() counts = result.get_counts(qc) print("Total counts for qubit states are:",counts) plot_histogram(counts) #Program 7.8 Classical Shor Algorithm from random import randint from math import gcd def period_finding(a,N): for r in range(1,N): if (a**r) % N == 1: return r def shor_alg(N): while True: a=randint(2,N-1) g=gcd(a,N) if g!=1: p=g q=N//g return p,q else: r=period_finding(a,N) if r % 2 != 0: continue elif a**(r//2) % N == -1 % N: continue else: p=gcd(a**(r//2)+1,N) if p==1 or p==N: p=gcd(a**(r//2)-1,N) q=N//p return p,q for N in [15, 21, 35, 913, 2257, 10999]: print(f'Factors of {N}: {shor_alg(N)}') #Program 7.9 Define function to build modular exponentiation quantum circuit from qiskit import QuantumRegister, QuantumCircuit def qc_mod15(a, power, show=False): assert a in [2,4,7,8,11,13], 'Invalid value of argument a:'+str(a) qrt = QuantumRegister(4,'target') U = QuantumCircuit(qrt) for i in range(power): if a in [2,13]: U.swap(0,1) U.swap(1,2) U.swap(2,3) if a in [7,8]: U.swap(2,3) U.swap(1,2) U.swap(0,1) if a in [4, 11]: U.swap(1,3) U.swap(0,2) if a in [7,11,13]: for j in range(4): U.x(j) if show: print('Below is the circuit of U of '+f'"{a}^{power} mod 15":') display(U.draw('mpl')) U = U.to_gate() U.name = f'{a}^{power} mod 15' C_U = U.control() return C_U power_arg=2 for a_arg in [2,4,7,8,11,13]: qrc = QuantumRegister(1,'control') qrt = QuantumRegister(4,'target') qc = QuantumCircuit(qrc,qrt) qc.append(qc_mod15(a_arg, power_arg, show=True),[0,1,2,3,4]) print('Below is the circuit of controlled U of '+f'"{a_arg}^{power_arg} mod 15":') display(qc.draw('mpl')) #Program 7.10: Define quantum period finding function with N=15 from qiskit import QuantumRegister,ClassicalRegister,QuantumCircuit def qpf15(count_no,a): qrc = QuantumRegister(count_no,'count') qry = QuantumRegister(4,'y') #for input of qc_mod15 gate clr = ClassicalRegister(count_no,'c') qc = QuantumCircuit(qrc, qry, clr) for cbit in range(count_no): qc.h(cbit) qc.x(qry[0]) #Set the input of qc_mod15 as |1> with y0 as LSB for cbit in range(count_no): #Add controlled-qc_mod15 gates qc.append(qc_mod15(a, 2**cbit), [cbit] + list(range(count_no, count_no+4))) qc.append(iqft(count_no).to_gate(label='IQFT'), range(count_no)) qc.measure(range(count_no), range(count_no)) return qc display(qpf15(count_no=3,a=13).draw('mpl')) #Program 7.11 Run quantum period finding function with N=15 from qiskit import execute from qiskit.providers.aer import AerSimulator from qiskit.visualization import plot_histogram from fractions import Fraction sim = AerSimulator() count_no=3 cir = qpf15(count_no=count_no,a=13) job=execute(cir, backend=sim, shots=1000) result = job.result() counts = result.get_counts(cir) display(plot_histogram(counts)) print('Total counts for qubit states are:',counts,'\n') print('%10s %10s %10s %10s %10s' % ('Binary','Decimal','Phase','Fraction','Period')) for akey in counts.keys(): dec=int(akey,base=2) phase=dec/(2**count_no) frac=Fraction(phase).limit_denominator(15) period=frac.denominator print('%10s %10d %10f %10s %10d' % (akey,dec,phase,frac,period))
https://github.com/kurtchahn/QiskitPrx
kurtchahn
import qiskit as qk import qiskit_aer as qaer import numpy as np import math sSimulator = qaer.Aer.backends(name="statevector_simulator")[0] mSimulator = qaer.Aer.backends(name="qasm_simulator")[0] def create_blackbox(): def F1(x): return 0 def F2(x): return 1 def F3(x): return x%2 def F4(x): return (x+1)%2 functions = [F1, F2, F3, F4] function = functions[ np.random.randint(0, 3) ] return function blackbox = create_blackbox() print("f(0): ", blackbox(0)) print("f(1): ", blackbox(1)) if (blackbox(0) == blackbox(1)): print("f is a constant function") else: print("f is a balanced function") def return_blackbox(): q = qk.QuantumRegister(2) blackbox = qk.QuantumCircuit(q, name=r"$\hat{U}_B$") rand = np.random.randint(0, 3) match rand: case 0: ## f(0,1) -> (0,1) blackbox.cx(q[0], q[1]) print("balanced") case 1: ## f(0,1) -> (1,0) blackbox.x(q[0]) blackbox.cx(q[0], q[1]) blackbox.x(q[0]) print("balanced") case 2: ## f(0,1) -> (0,0) blackbox.id(q[0]) blackbox.id(q[1]) print("constant") case 3: ## f(0,1) -> (1,1) blackbox.id(q[0]) blackbox.x(q[1]) print("constant") return blackbox.to_instruction() q = qk.QuantumRegister(2, name="q") c = qk.ClassicalRegister(1, name="c") deutsch = qk.QuantumCircuit(q, c, name="qc") deutsch.id(q[0]) deutsch.x(q[1]) deutsch.h(q[0]) deutsch.h(q[1]) deutsch.barrier(label=r"$|\psi\rangle_{in}$") blackbox = return_blackbox() deutsch.append(blackbox, [0,1]) deutsch.barrier(label=r"$\hat{U}_B|\psi\rangle_{in}$") deutsch.h(q[0]) deutsch.h(q[1]) deutsch.barrier() ## We only need to measure q0 to determine if f is balanced or constant deutsch.measure(q[0], c) deutsch.draw("mpl") ## We only need 1 shot ## We need to decompose the circuit in order for the simulator to read the blackbox instructions counts = mSimulator.run(deutsch.decompose(), shots=1).result().get_counts(deutsch.decompose()) if ("0" in counts): print(r"0 state measured: f is a constant function") elif ("1" in counts): print(r"1 state measured: f is a balanced function")
https://github.com/hkhetawat/QArithmetic
hkhetawat
# Import the Qiskit SDK from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute, Aer from QArithmetic import bitwise_and, bitwise_or, bitwise_xor, bitwise_not # Input N N = 4 a = QuantumRegister(N) b = QuantumRegister(N) c = QuantumRegister(N) ca = ClassicalRegister(N) cb = ClassicalRegister(N) cc = ClassicalRegister(N) qc = QuantumCircuit(a, b, c, ca, cb, cc) # Input Superposition # a = 1110 qc.x(a[1]) qc.x(a[3]) # b = 1011 qc.x(b[0]) qc.x(b[1]) qc.x(b[3]) bitwise_not(qc, a, c, N) qc.measure(a, ca) qc.measure(b, cb) qc.measure(c, cc) backend_sim = Aer.get_backend('qasm_simulator') job_sim = execute(qc, backend_sim) result_sim = job_sim.result() print(result_sim.get_counts(qc))
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test cases for the pulse Schedule transforms.""" import unittest from typing import List, Set import numpy as np from qiskit import pulse from qiskit.pulse import ( Play, Delay, Acquire, Schedule, Waveform, Drag, Gaussian, GaussianSquare, Constant, ) from qiskit.pulse import transforms, instructions from qiskit.pulse.channels import ( MemorySlot, DriveChannel, AcquireChannel, RegisterSlot, SnapshotChannel, ) from qiskit.pulse.instructions import directives from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider import FakeOpenPulse2Q class TestAlignMeasures(QiskitTestCase): """Test the helper function which aligns acquires.""" def setUp(self): super().setUp() self.backend = FakeOpenPulse2Q() self.config = self.backend.configuration() self.inst_map = self.backend.defaults().instruction_schedule_map self.short_pulse = pulse.Waveform( samples=np.array([0.02739068], dtype=np.complex128), name="p0" ) def test_align_measures(self): """Test that one acquire is delayed to match the time of the later acquire.""" sched = pulse.Schedule(name="fake_experiment") sched.insert(0, Play(self.short_pulse, self.config.drive(0)), inplace=True) sched.insert(1, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True) sched.insert(10, Acquire(5, self.config.acquire(1), MemorySlot(1)), inplace=True) sched.insert(10, Play(self.short_pulse, self.config.measure(0)), inplace=True) sched.insert(11, Play(self.short_pulse, self.config.measure(0)), inplace=True) sched.insert(10, Play(self.short_pulse, self.config.measure(1)), inplace=True) aligned = transforms.align_measures([sched])[0] self.assertEqual(aligned.name, "fake_experiment") ref = pulse.Schedule(name="fake_experiment") ref.insert(0, Play(self.short_pulse, self.config.drive(0)), inplace=True) ref.insert(10, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True) ref.insert(10, Acquire(5, self.config.acquire(1), MemorySlot(1)), inplace=True) ref.insert(19, Play(self.short_pulse, self.config.measure(0)), inplace=True) ref.insert(20, Play(self.short_pulse, self.config.measure(0)), inplace=True) ref.insert(10, Play(self.short_pulse, self.config.measure(1)), inplace=True) self.assertEqual(aligned, ref) aligned = transforms.align_measures([sched], self.inst_map, align_time=20)[0] ref = pulse.Schedule(name="fake_experiment") ref.insert(10, Play(self.short_pulse, self.config.drive(0)), inplace=True) ref.insert(20, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True) ref.insert(20, Acquire(5, self.config.acquire(1), MemorySlot(1)), inplace=True) ref.insert(29, Play(self.short_pulse, self.config.measure(0)), inplace=True) ref.insert(30, Play(self.short_pulse, self.config.measure(0)), inplace=True) ref.insert(20, Play(self.short_pulse, self.config.measure(1)), inplace=True) self.assertEqual(aligned, ref) def test_align_post_u3(self): """Test that acquires are scheduled no sooner than the duration of the longest X gate.""" sched = pulse.Schedule(name="fake_experiment") sched = sched.insert(0, Play(self.short_pulse, self.config.drive(0))) sched = sched.insert(1, Acquire(5, self.config.acquire(0), MemorySlot(0))) sched = transforms.align_measures([sched], self.inst_map)[0] for time, inst in sched.instructions: if isinstance(inst, Acquire): self.assertEqual(time, 4) sched = transforms.align_measures([sched], self.inst_map, max_calibration_duration=10)[0] for time, inst in sched.instructions: if isinstance(inst, Acquire): self.assertEqual(time, 10) def test_multi_acquire(self): """Test that the last acquire is aligned to if multiple acquires occur on the same channel.""" sched = pulse.Schedule() sched.insert(0, Play(self.short_pulse, self.config.drive(0)), inplace=True) sched.insert(4, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True) sched.insert(20, Acquire(5, self.config.acquire(1), MemorySlot(1)), inplace=True) sched.insert(10, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True) aligned = transforms.align_measures([sched], self.inst_map) ref = pulse.Schedule() ref.insert(0, Play(self.short_pulse, self.config.drive(0)), inplace=True) ref.insert(20, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True) ref.insert(20, Acquire(5, self.config.acquire(1), MemorySlot(1)), inplace=True) ref.insert(26, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True) self.assertEqual(aligned[0], ref) def test_multiple_acquires(self): """Test that multiple acquires are also aligned.""" sched = pulse.Schedule(name="fake_experiment") sched.insert(0, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True) sched.insert(5, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True) sched.insert(10, Acquire(5, self.config.acquire(1), MemorySlot(1)), inplace=True) ref = pulse.Schedule() ref.insert(10, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True) ref.insert(15, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True) ref.insert(10, Acquire(5, self.config.acquire(1), MemorySlot(1)), inplace=True) aligned = transforms.align_measures([sched], self.inst_map)[0] self.assertEqual(aligned, ref) def test_align_across_schedules(self): """Test that acquires are aligned together across multiple schedules.""" sched1 = pulse.Schedule(name="fake_experiment") sched1 = sched1.insert(0, Play(self.short_pulse, self.config.drive(0))) sched1 = sched1.insert(10, Acquire(5, self.config.acquire(0), MemorySlot(0))) sched2 = pulse.Schedule(name="fake_experiment") sched2 = sched2.insert(3, Play(self.short_pulse, self.config.drive(0))) sched2 = sched2.insert(25, Acquire(5, self.config.acquire(0), MemorySlot(0))) schedules = transforms.align_measures([sched1, sched2], self.inst_map) for time, inst in schedules[0].instructions: if isinstance(inst, Acquire): self.assertEqual(time, 25) for time, inst in schedules[0].instructions: if isinstance(inst, Acquire): self.assertEqual(time, 25) def test_align_all(self): """Test alignment of all instructions in a schedule.""" sched0 = pulse.Schedule() sched0.insert(0, Play(self.short_pulse, self.config.drive(0)), inplace=True) sched0.insert(10, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True) sched1 = pulse.Schedule() sched1.insert(25, Play(self.short_pulse, self.config.drive(0)), inplace=True) sched1.insert(25, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True) all_aligned = transforms.align_measures([sched0, sched1], self.inst_map, align_all=True) ref1_aligned = pulse.Schedule() ref1_aligned.insert(15, Play(self.short_pulse, self.config.drive(0)), inplace=True) ref1_aligned.insert(25, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True) self.assertEqual(all_aligned[0], ref1_aligned) self.assertEqual(all_aligned[1], sched1) ref1_not_aligned = pulse.Schedule() ref1_not_aligned.insert(0, Play(self.short_pulse, self.config.drive(0)), inplace=True) ref1_not_aligned.insert(25, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True) all_not_aligned = transforms.align_measures( [sched0, sched1], self.inst_map, align_all=False, ) self.assertEqual(all_not_aligned[0], ref1_not_aligned) self.assertEqual(all_not_aligned[1], sched1) def test_measurement_at_zero(self): """Test that acquire at t=0 works.""" sched1 = pulse.Schedule(name="fake_experiment") sched1 = sched1.insert(0, Play(self.short_pulse, self.config.drive(0))) sched1 = sched1.insert(0, Acquire(5, self.config.acquire(0), MemorySlot(0))) sched2 = pulse.Schedule(name="fake_experiment") sched2 = sched2.insert(0, Play(self.short_pulse, self.config.drive(0))) sched2 = sched2.insert(0, Acquire(5, self.config.acquire(0), MemorySlot(0))) schedules = transforms.align_measures([sched1, sched2], max_calibration_duration=0) for time, inst in schedules[0].instructions: if isinstance(inst, Acquire): self.assertEqual(time, 0) for time, inst in schedules[0].instructions: if isinstance(inst, Acquire): self.assertEqual(time, 0) class TestAddImplicitAcquires(QiskitTestCase): """Test the helper function which makes implicit acquires explicit.""" def setUp(self): super().setUp() self.backend = FakeOpenPulse2Q() self.config = self.backend.configuration() self.short_pulse = pulse.Waveform( samples=np.array([0.02739068], dtype=np.complex128), name="p0" ) sched = pulse.Schedule(name="fake_experiment") sched = sched.insert(0, Play(self.short_pulse, self.config.drive(0))) sched = sched.insert(5, Acquire(5, self.config.acquire(0), MemorySlot(0))) sched = sched.insert(5, Acquire(5, self.config.acquire(1), MemorySlot(1))) self.sched = sched def test_add_implicit(self): """Test that implicit acquires are made explicit according to the meas map.""" sched = transforms.add_implicit_acquires(self.sched, [[0, 1]]) acquired_qubits = set() for _, inst in sched.instructions: if isinstance(inst, Acquire): acquired_qubits.add(inst.acquire.index) self.assertEqual(acquired_qubits, {0, 1}) def test_add_across_meas_map_sublists(self): """Test that implicit acquires in separate meas map sublists are all added.""" sched = transforms.add_implicit_acquires(self.sched, [[0, 2], [1, 3]]) acquired_qubits = set() for _, inst in sched.instructions: if isinstance(inst, Acquire): acquired_qubits.add(inst.acquire.index) self.assertEqual(acquired_qubits, {0, 1, 2, 3}) def test_dont_add_all(self): """Test that acquires aren't added if no qubits in the sublist aren't being acquired.""" sched = transforms.add_implicit_acquires(self.sched, [[4, 5], [0, 2], [1, 3]]) acquired_qubits = set() for _, inst in sched.instructions: if isinstance(inst, Acquire): acquired_qubits.add(inst.acquire.index) self.assertEqual(acquired_qubits, {0, 1, 2, 3}) def test_multiple_acquires(self): """Test for multiple acquires.""" sched = pulse.Schedule() acq_q0 = pulse.Acquire(1200, AcquireChannel(0), MemorySlot(0)) sched += acq_q0 sched += acq_q0 << sched.duration sched = transforms.add_implicit_acquires(sched, meas_map=[[0]]) self.assertEqual(sched.instructions, ((0, acq_q0), (2400, acq_q0))) class TestPad(QiskitTestCase): """Test padding of schedule with delays.""" def test_padding_empty_schedule(self): """Test padding of empty schedule.""" self.assertEqual(pulse.Schedule(), transforms.pad(pulse.Schedule())) def test_padding_schedule(self): """Test padding schedule.""" delay = 10 sched = ( Delay(delay, DriveChannel(0)).shift(10) + Delay(delay, DriveChannel(0)).shift(10) + Delay(delay, DriveChannel(1)).shift(10) ) ref_sched = ( sched # pylint: disable=unsupported-binary-operation | Delay(delay, DriveChannel(0)) | Delay(delay, DriveChannel(0)).shift(20) | Delay(delay, DriveChannel(1)) | Delay( # pylint: disable=unsupported-binary-operation 2 * delay, DriveChannel(1) ).shift(20) ) self.assertEqual(transforms.pad(sched), ref_sched) def test_padding_schedule_inverse_order(self): """Test padding schedule is insensitive to order in which commands were added. This test is the same as `test_adding_schedule` but the order by channel in which commands were added to the schedule to be padded has been reversed. """ delay = 10 sched = ( Delay(delay, DriveChannel(1)).shift(10) + Delay(delay, DriveChannel(0)).shift(10) + Delay(delay, DriveChannel(0)).shift(10) ) ref_sched = ( sched # pylint: disable=unsupported-binary-operation | Delay(delay, DriveChannel(0)) | Delay(delay, DriveChannel(0)).shift(20) | Delay(delay, DriveChannel(1)) | Delay( # pylint: disable=unsupported-binary-operation 2 * delay, DriveChannel(1) ).shift(20) ) self.assertEqual(transforms.pad(sched), ref_sched) def test_padding_until_less(self): """Test padding until time that is less than schedule duration.""" delay = 10 sched = Delay(delay, DriveChannel(0)).shift(10) + Delay(delay, DriveChannel(1)) ref_sched = sched | Delay(delay, DriveChannel(0)) | Delay(5, DriveChannel(1)).shift(10) self.assertEqual(transforms.pad(sched, until=15), ref_sched) def test_padding_until_greater(self): """Test padding until time that is greater than schedule duration.""" delay = 10 sched = Delay(delay, DriveChannel(0)).shift(10) + Delay(delay, DriveChannel(1)) ref_sched = ( sched # pylint: disable=unsupported-binary-operation | Delay(delay, DriveChannel(0)) | Delay(30, DriveChannel(0)).shift(20) | Delay(40, DriveChannel(1)).shift(10) # pylint: disable=unsupported-binary-operation ) self.assertEqual(transforms.pad(sched, until=50), ref_sched) def test_padding_supplied_channels(self): """Test padding of only specified channels.""" delay = 10 sched = Delay(delay, DriveChannel(0)).shift(10) + Delay(delay, DriveChannel(1)) ref_sched = sched | Delay(delay, DriveChannel(0)) | Delay(2 * delay, DriveChannel(2)) channels = [DriveChannel(0), DriveChannel(2)] self.assertEqual(transforms.pad(sched, channels=channels), ref_sched) def test_padding_less_than_sched_duration(self): """Test that the until arg is respected even for less than the input schedule duration.""" delay = 10 sched = Delay(delay, DriveChannel(0)) + Delay(delay, DriveChannel(0)).shift(20) ref_sched = sched | pulse.Delay(5, DriveChannel(0)).shift(10) self.assertEqual(transforms.pad(sched, until=15), ref_sched) def test_padding_prepended_delay(self): """Test that there is delay before the first instruction.""" delay = 10 sched = Delay(delay, DriveChannel(0)).shift(10) + Delay(delay, DriveChannel(0)) ref_sched = ( Delay(delay, DriveChannel(0)) + Delay(delay, DriveChannel(0)) + Delay(delay, DriveChannel(0)) ) self.assertEqual(transforms.pad(sched, until=30, inplace=True), ref_sched) def test_pad_no_delay_on_classical_io_channels(self): """Test padding does not apply to classical IO channels.""" delay = 10 sched = ( Delay(delay, MemorySlot(0)).shift(20) + Delay(delay, RegisterSlot(0)).shift(10) + Delay(delay, SnapshotChannel()) ) ref_sched = ( Delay(delay, MemorySlot(0)).shift(20) + Delay(delay, RegisterSlot(0)).shift(10) + Delay(delay, SnapshotChannel()) ) self.assertEqual(transforms.pad(sched, until=15), ref_sched) def get_pulse_ids(schedules: List[Schedule]) -> Set[int]: """Returns ids of pulses used in Schedules.""" ids = set() for schedule in schedules: for _, inst in schedule.instructions: ids.add(inst.pulse.id) return ids class TestCompressTransform(QiskitTestCase): """Compress function test.""" def test_with_duplicates(self): """Test compression of schedule.""" schedule = Schedule() drive_channel = DriveChannel(0) schedule += Play(Waveform([0.0, 0.1]), drive_channel) schedule += Play(Waveform([0.0, 0.1]), drive_channel) compressed_schedule = transforms.compress_pulses([schedule]) original_pulse_ids = get_pulse_ids([schedule]) compressed_pulse_ids = get_pulse_ids(compressed_schedule) self.assertEqual(len(compressed_pulse_ids), 1) self.assertEqual(len(original_pulse_ids), 2) self.assertTrue(next(iter(compressed_pulse_ids)) in original_pulse_ids) def test_sample_pulse_with_clipping(self): """Test sample pulses with clipping.""" schedule = Schedule() drive_channel = DriveChannel(0) schedule += Play(Waveform([0.0, 1.0]), drive_channel) schedule += Play(Waveform([0.0, 1.001], epsilon=1e-3), drive_channel) schedule += Play(Waveform([0.0, 1.0000000001]), drive_channel) compressed_schedule = transforms.compress_pulses([schedule]) original_pulse_ids = get_pulse_ids([schedule]) compressed_pulse_ids = get_pulse_ids(compressed_schedule) self.assertEqual(len(compressed_pulse_ids), 1) self.assertEqual(len(original_pulse_ids), 3) self.assertTrue(next(iter(compressed_pulse_ids)) in original_pulse_ids) def test_no_duplicates(self): """Test with no pulse duplicates.""" schedule = Schedule() drive_channel = DriveChannel(0) schedule += Play(Waveform([0.0, 1.0]), drive_channel) schedule += Play(Waveform([0.0, 0.9]), drive_channel) schedule += Play(Waveform([0.0, 0.3]), drive_channel) compressed_schedule = transforms.compress_pulses([schedule]) original_pulse_ids = get_pulse_ids([schedule]) compressed_pulse_ids = get_pulse_ids(compressed_schedule) self.assertEqual(len(original_pulse_ids), len(compressed_pulse_ids)) def test_parametric_pulses_with_duplicates(self): """Test with parametric pulses.""" schedule = Schedule() drive_channel = DriveChannel(0) schedule += Play(Gaussian(duration=25, sigma=4, amp=0.5, angle=np.pi / 2), drive_channel) schedule += Play(Gaussian(duration=25, sigma=4, amp=0.5, angle=np.pi / 2), drive_channel) schedule += Play(GaussianSquare(duration=150, amp=0.2, sigma=8, width=140), drive_channel) schedule += Play(GaussianSquare(duration=150, amp=0.2, sigma=8, width=140), drive_channel) schedule += Play(Constant(duration=150, amp=0.5, angle=0.7), drive_channel) schedule += Play(Constant(duration=150, amp=0.5, angle=0.7), drive_channel) schedule += Play(Drag(duration=25, amp=0.4, angle=-0.3, sigma=7.8, beta=4), drive_channel) schedule += Play(Drag(duration=25, amp=0.4, angle=-0.3, sigma=7.8, beta=4), drive_channel) compressed_schedule = transforms.compress_pulses([schedule]) original_pulse_ids = get_pulse_ids([schedule]) compressed_pulse_ids = get_pulse_ids(compressed_schedule) self.assertEqual(len(original_pulse_ids), 8) self.assertEqual(len(compressed_pulse_ids), 4) def test_parametric_pulses_with_no_duplicates(self): """Test parametric pulses with no duplicates.""" schedule = Schedule() drive_channel = DriveChannel(0) schedule += Play(Gaussian(duration=25, sigma=4, amp=0.5, angle=np.pi / 2), drive_channel) schedule += Play(Gaussian(duration=25, sigma=4, amp=0.49, angle=np.pi / 2), drive_channel) schedule += Play(GaussianSquare(duration=150, amp=0.2, sigma=8, width=140), drive_channel) schedule += Play(GaussianSquare(duration=150, amp=0.19, sigma=8, width=140), drive_channel) schedule += Play(Constant(duration=150, amp=0.5, angle=0.3), drive_channel) schedule += Play(Constant(duration=150, amp=0.51, angle=0.3), drive_channel) schedule += Play(Drag(duration=25, amp=0.5, angle=0.5, sigma=7.8, beta=4), drive_channel) schedule += Play(Drag(duration=25, amp=0.5, angle=0.51, sigma=7.8, beta=4), drive_channel) compressed_schedule = transforms.compress_pulses([schedule]) original_pulse_ids = get_pulse_ids([schedule]) compressed_pulse_ids = get_pulse_ids(compressed_schedule) self.assertEqual(len(original_pulse_ids), len(compressed_pulse_ids)) def test_with_different_channels(self): """Test with different channels.""" schedule = Schedule() schedule += Play(Waveform([0.0, 0.1]), DriveChannel(0)) schedule += Play(Waveform([0.0, 0.1]), DriveChannel(1)) compressed_schedule = transforms.compress_pulses([schedule]) original_pulse_ids = get_pulse_ids([schedule]) compressed_pulse_ids = get_pulse_ids(compressed_schedule) self.assertEqual(len(original_pulse_ids), 2) self.assertEqual(len(compressed_pulse_ids), 1) def test_sample_pulses_with_tolerance(self): """Test sample pulses with tolerance.""" schedule = Schedule() schedule += Play(Waveform([0.0, 0.1001], epsilon=1e-3), DriveChannel(0)) schedule += Play(Waveform([0.0, 0.1], epsilon=1e-3), DriveChannel(1)) compressed_schedule = transforms.compress_pulses([schedule]) original_pulse_ids = get_pulse_ids([schedule]) compressed_pulse_ids = get_pulse_ids(compressed_schedule) self.assertEqual(len(original_pulse_ids), 2) self.assertEqual(len(compressed_pulse_ids), 1) def test_multiple_schedules(self): """Test multiple schedules.""" schedules = [] for _ in range(2): schedule = Schedule() drive_channel = DriveChannel(0) schedule += Play(Waveform([0.0, 0.1]), drive_channel) schedule += Play(Waveform([0.0, 0.1]), drive_channel) schedule += Play(Waveform([0.0, 0.2]), drive_channel) schedules.append(schedule) compressed_schedule = transforms.compress_pulses(schedules) original_pulse_ids = get_pulse_ids(schedules) compressed_pulse_ids = get_pulse_ids(compressed_schedule) self.assertEqual(len(original_pulse_ids), 6) self.assertEqual(len(compressed_pulse_ids), 2) class TestAlignSequential(QiskitTestCase): """Test sequential alignment transform.""" def test_align_sequential(self): """Test sequential alignment without a barrier.""" context = transforms.AlignSequential() d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) schedule = pulse.Schedule() schedule.insert(1, instructions.Delay(3, d0), inplace=True) schedule.insert(4, instructions.Delay(5, d1), inplace=True) schedule.insert(12, instructions.Delay(7, d0), inplace=True) schedule = context.align(schedule) reference = pulse.Schedule() # d0 reference.insert(0, instructions.Delay(3, d0), inplace=True) reference.insert(8, instructions.Delay(7, d0), inplace=True) # d1 reference.insert(3, instructions.Delay(5, d1), inplace=True) self.assertEqual(schedule, reference) def test_align_sequential_with_barrier(self): """Test sequential alignment with a barrier.""" context = transforms.AlignSequential() d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) schedule = pulse.Schedule() schedule.insert(1, instructions.Delay(3, d0), inplace=True) schedule.append(directives.RelativeBarrier(d0, d1), inplace=True) schedule.insert(4, instructions.Delay(5, d1), inplace=True) schedule.insert(12, instructions.Delay(7, d0), inplace=True) schedule = context.align(schedule) reference = pulse.Schedule() reference.insert(0, instructions.Delay(3, d0), inplace=True) reference.insert(3, directives.RelativeBarrier(d0, d1), inplace=True) reference.insert(3, instructions.Delay(5, d1), inplace=True) reference.insert(8, instructions.Delay(7, d0), inplace=True) self.assertEqual(schedule, reference) class TestAlignLeft(QiskitTestCase): """Test left alignment transform.""" def test_align_left(self): """Test left alignment without a barrier.""" context = transforms.AlignLeft() d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) d2 = pulse.DriveChannel(2) schedule = pulse.Schedule() schedule.insert(1, instructions.Delay(3, d0), inplace=True) schedule.insert(17, instructions.Delay(11, d2), inplace=True) sched_grouped = pulse.Schedule() sched_grouped += instructions.Delay(5, d1) sched_grouped += instructions.Delay(7, d0) schedule.append(sched_grouped, inplace=True) schedule = context.align(schedule) reference = pulse.Schedule() # d0 reference.insert(0, instructions.Delay(3, d0), inplace=True) reference.insert(3, instructions.Delay(7, d0), inplace=True) # d1 reference.insert(3, instructions.Delay(5, d1), inplace=True) # d2 reference.insert(0, instructions.Delay(11, d2), inplace=True) self.assertEqual(schedule, reference) def test_align_left_with_barrier(self): """Test left alignment with a barrier.""" context = transforms.AlignLeft() d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) d2 = pulse.DriveChannel(2) schedule = pulse.Schedule() schedule.insert(1, instructions.Delay(3, d0), inplace=True) schedule.append(directives.RelativeBarrier(d0, d1, d2), inplace=True) schedule.insert(17, instructions.Delay(11, d2), inplace=True) sched_grouped = pulse.Schedule() sched_grouped += instructions.Delay(5, d1) sched_grouped += instructions.Delay(7, d0) schedule.append(sched_grouped, inplace=True) schedule = transforms.remove_directives(context.align(schedule)) reference = pulse.Schedule() # d0 reference.insert(0, instructions.Delay(3, d0), inplace=True) reference.insert(3, instructions.Delay(7, d0), inplace=True) # d1 reference = reference.insert(3, instructions.Delay(5, d1)) # d2 reference = reference.insert(3, instructions.Delay(11, d2)) self.assertEqual(schedule, reference) class TestAlignRight(QiskitTestCase): """Test right alignment transform.""" def test_align_right(self): """Test right alignment without a barrier.""" context = transforms.AlignRight() d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) d2 = pulse.DriveChannel(2) schedule = pulse.Schedule() schedule.insert(1, instructions.Delay(3, d0), inplace=True) schedule.insert(17, instructions.Delay(11, d2), inplace=True) sched_grouped = pulse.Schedule() sched_grouped.insert(2, instructions.Delay(5, d1), inplace=True) sched_grouped += instructions.Delay(7, d0) schedule.append(sched_grouped, inplace=True) schedule = context.align(schedule) reference = pulse.Schedule() # d0 reference.insert(1, instructions.Delay(3, d0), inplace=True) reference.insert(4, instructions.Delay(7, d0), inplace=True) # d1 reference.insert(6, instructions.Delay(5, d1), inplace=True) # d2 reference.insert(0, instructions.Delay(11, d2), inplace=True) self.assertEqual(schedule, reference) def test_align_right_with_barrier(self): """Test right alignment with a barrier.""" context = transforms.AlignRight() d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) d2 = pulse.DriveChannel(2) schedule = pulse.Schedule() schedule.insert(1, instructions.Delay(3, d0), inplace=True) schedule.append(directives.RelativeBarrier(d0, d1, d2), inplace=True) schedule.insert(17, instructions.Delay(11, d2), inplace=True) sched_grouped = pulse.Schedule() sched_grouped.insert(2, instructions.Delay(5, d1), inplace=True) sched_grouped += instructions.Delay(7, d0) schedule.append(sched_grouped, inplace=True) schedule = transforms.remove_directives(context.align(schedule)) reference = pulse.Schedule() # d0 reference.insert(0, instructions.Delay(3, d0), inplace=True) reference.insert(7, instructions.Delay(7, d0), inplace=True) # d1 reference.insert(9, instructions.Delay(5, d1), inplace=True) # d2 reference.insert(3, instructions.Delay(11, d2), inplace=True) self.assertEqual(schedule, reference) class TestAlignEquispaced(QiskitTestCase): """Test equispaced alignment transform.""" def test_equispaced_with_short_duration(self): """Test equispaced context with duration shorter than the schedule duration.""" context = transforms.AlignEquispaced(duration=20) d0 = pulse.DriveChannel(0) schedule = pulse.Schedule() for _ in range(3): schedule.append(Delay(10, d0), inplace=True) schedule = context.align(schedule) reference = pulse.Schedule() reference.insert(0, Delay(10, d0), inplace=True) reference.insert(10, Delay(10, d0), inplace=True) reference.insert(20, Delay(10, d0), inplace=True) self.assertEqual(schedule, reference) def test_equispaced_with_longer_duration(self): """Test equispaced context with duration longer than the schedule duration.""" context = transforms.AlignEquispaced(duration=50) d0 = pulse.DriveChannel(0) schedule = pulse.Schedule() for _ in range(3): schedule.append(Delay(10, d0), inplace=True) schedule = context.align(schedule) reference = pulse.Schedule() reference.insert(0, Delay(10, d0), inplace=True) reference.insert(20, Delay(10, d0), inplace=True) reference.insert(40, Delay(10, d0), inplace=True) self.assertEqual(schedule, reference) def test_equispaced_with_multiple_channels_short_duration(self): """Test equispaced context with multiple channels and duration shorter than the total duration.""" context = transforms.AlignEquispaced(duration=20) d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) schedule = pulse.Schedule() schedule.append(Delay(10, d0), inplace=True) schedule.append(Delay(20, d1), inplace=True) schedule = context.align(schedule) reference = pulse.Schedule() reference.insert(0, Delay(10, d0), inplace=True) reference.insert(0, Delay(20, d1), inplace=True) self.assertEqual(schedule, reference) def test_equispaced_with_multiple_channels_longer_duration(self): """Test equispaced context with multiple channels and duration longer than the total duration.""" context = transforms.AlignEquispaced(duration=30) d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) schedule = pulse.Schedule() schedule.append(Delay(10, d0), inplace=True) schedule.append(Delay(20, d1), inplace=True) schedule = context.align(schedule) reference = pulse.Schedule() reference.insert(0, Delay(10, d0), inplace=True) reference.insert(10, Delay(20, d1), inplace=True) self.assertEqual(schedule, reference) class TestAlignFunc(QiskitTestCase): """Test callback alignment transform.""" @staticmethod def _position(ind): """Returns 0.25, 0.5, 0.75 for ind = 1, 2, 3.""" return ind / (3 + 1) def test_numerical_with_short_duration(self): """Test numerical alignment context with duration shorter than the schedule duration.""" context = transforms.AlignFunc(duration=20, func=self._position) d0 = pulse.DriveChannel(0) schedule = pulse.Schedule() for _ in range(3): schedule.append(Delay(10, d0), inplace=True) schedule = context.align(schedule) reference = pulse.Schedule() reference.insert(0, Delay(10, d0), inplace=True) reference.insert(10, Delay(10, d0), inplace=True) reference.insert(20, Delay(10, d0), inplace=True) self.assertEqual(schedule, reference) def test_numerical_with_longer_duration(self): """Test numerical alignment context with duration longer than the schedule duration.""" context = transforms.AlignFunc(duration=80, func=self._position) d0 = pulse.DriveChannel(0) schedule = pulse.Schedule() for _ in range(3): schedule.append(Delay(10, d0), inplace=True) schedule = context.align(schedule) reference = pulse.Schedule() reference.insert(15, Delay(10, d0), inplace=True) reference.insert(35, Delay(10, d0), inplace=True) reference.insert(55, Delay(10, d0), inplace=True) self.assertEqual(schedule, reference) class TestFlatten(QiskitTestCase): """Test flattening transform.""" def test_flatten(self): """Test the flatten transform.""" context_left = transforms.AlignLeft() d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) schedule = pulse.Schedule() schedule += instructions.Delay(3, d0) grouped = pulse.Schedule() grouped += instructions.Delay(5, d1) grouped += instructions.Delay(7, d0) # include a grouped schedule grouped = schedule + grouped # flatten the schedule inline internal groups flattened = transforms.flatten(grouped) # align all the instructions to the left after flattening flattened = context_left.align(flattened) grouped = context_left.align(grouped) reference = pulse.Schedule() # d0 reference.insert(0, instructions.Delay(3, d0), inplace=True) reference.insert(3, instructions.Delay(7, d0), inplace=True) # d1 reference.insert(0, instructions.Delay(5, d1), inplace=True) self.assertEqual(flattened, reference) self.assertNotEqual(grouped, reference) class _TestDirective(directives.Directive): """Pulse ``RelativeBarrier`` directive.""" def __init__(self, *channels): """Test directive""" super().__init__(operands=tuple(channels)) @property def channels(self): return self.operands class TestRemoveDirectives(QiskitTestCase): """Test removing of directives.""" def test_remove_directives(self): """Test that all directives are removed.""" d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) schedule = pulse.Schedule() schedule += _TestDirective(d0, d1) schedule += instructions.Delay(3, d0) schedule += _TestDirective(d0, d1) schedule = transforms.remove_directives(schedule) reference = pulse.Schedule() # d0 reference += instructions.Delay(3, d0) self.assertEqual(schedule, reference) class TestRemoveTrivialBarriers(QiskitTestCase): """Test scheduling transforms.""" def test_remove_trivial_barriers(self): """Test that trivial barriers are properly removed.""" schedule = pulse.Schedule() schedule += directives.RelativeBarrier() schedule += directives.RelativeBarrier(pulse.DriveChannel(0)) schedule += directives.RelativeBarrier(pulse.DriveChannel(0), pulse.DriveChannel(1)) schedule = transforms.remove_trivial_barriers(schedule) reference = pulse.Schedule() reference += directives.RelativeBarrier(pulse.DriveChannel(0), pulse.DriveChannel(1)) self.assertEqual(schedule, reference) class TestRemoveSubroutines(QiskitTestCase): """Test removing of subroutines.""" def test_remove_subroutines(self): """Test that nested subroutiens are removed.""" d0 = pulse.DriveChannel(0) nested_routine = pulse.Schedule() nested_routine.insert(10, pulse.Delay(10, d0), inplace=True) subroutine = pulse.Schedule() subroutine.insert(0, pulse.Delay(20, d0), inplace=True) with self.assertWarns(DeprecationWarning): subroutine.insert(20, pulse.instructions.Call(nested_routine), inplace=True) subroutine.insert(50, pulse.Delay(10, d0), inplace=True) main_program = pulse.Schedule() main_program.insert(0, pulse.Delay(10, d0), inplace=True) with self.assertWarns(DeprecationWarning): main_program.insert(30, pulse.instructions.Call(subroutine), inplace=True) target = transforms.inline_subroutines(main_program) reference = pulse.Schedule() reference.insert(0, pulse.Delay(10, d0), inplace=True) reference.insert(30, pulse.Delay(20, d0), inplace=True) reference.insert(60, pulse.Delay(10, d0), inplace=True) reference.insert(80, pulse.Delay(10, d0), inplace=True) self.assertEqual(target, reference) def test_call_in_nested_schedule(self): """Test that subroutines in nested schedule.""" d0 = pulse.DriveChannel(0) subroutine = pulse.Schedule() subroutine.insert(10, pulse.Delay(10, d0), inplace=True) nested_sched = pulse.Schedule() with self.assertWarns(DeprecationWarning): nested_sched.insert(0, pulse.instructions.Call(subroutine), inplace=True) main_sched = pulse.Schedule() main_sched.insert(0, nested_sched, inplace=True) target = transforms.inline_subroutines(main_sched) # no call instruction reference_nested = pulse.Schedule() reference_nested.insert(0, subroutine, inplace=True) reference = pulse.Schedule() reference.insert(0, reference_nested, inplace=True) self.assertEqual(target, reference) def test_call_in_nested_block(self): """Test that subroutines in nested schedule.""" d0 = pulse.DriveChannel(0) subroutine = pulse.ScheduleBlock() subroutine.append(pulse.Delay(10, d0), inplace=True) nested_block = pulse.ScheduleBlock() with self.assertWarns(DeprecationWarning): nested_block.append(pulse.instructions.Call(subroutine), inplace=True) main_block = pulse.ScheduleBlock() main_block.append(nested_block, inplace=True) target = transforms.inline_subroutines(main_block) # no call instruction reference_nested = pulse.ScheduleBlock() reference_nested.append(subroutine, inplace=True) reference = pulse.ScheduleBlock() reference.append(reference_nested, inplace=True) self.assertEqual(target, reference) if __name__ == "__main__": unittest.main()
https://github.com/urwin419/QiskitChecker
urwin419
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) ### removed cx gate ### return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).issubset({0,1}): raise ValueError(f"message '{msg}' is invalid") if msg[1] == "1": qc.x(qubit) if msg[0] == "1": qc.z(qubit) return qc def decode_message(qc): qc.cx(1, 0) qc.h(1) return qc
https://github.com/18520339/uts-quantum-computing
18520339
from IPython.display import YouTubeVideo YouTubeVideo('U6_wSh_-EQc', width=960, height=490) !pip install qiskit --quiet !pip install qiskit-aer --quiet !pip install pylatexenc --quiet # @markdown ### **1. Import `Qiskit` and essential packages for UI demonstration** { display-mode: "form" } from abc import abstractmethod, ABCMeta # For define pure virtual functions from IPython.display import clear_output from ipywidgets import Output, Button, HBox, VBox, HTML, Dropdown from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, transpile from qiskit.visualization import plot_bloch_multivector, plot_histogram from qiskit_aer import AerSimulator # @markdown ### **2. `Board` class for essential quantum operations** { display-mode: "form" } class Board: def __init__(self, size=3, simulator=None): # Initialize the quantum circuit with one qubit and classical bit for each cell self.size = size self.simulator = simulator self.superposition_count = 0 self.cells = [[' ' for _ in range(size)] for _ in range(size)] # Initialize the board representation self.qubits = QuantumRegister(size**2, 'q') self.bits = ClassicalRegister(size**2, 'c') self.circuit = QuantumCircuit(self.qubits, self.bits) ''' For a 3x3 board, the winning lines are: - Horizontal lines: (0, 1, 2), (3, 4, 5), (6, 7, 8) - Vertical lines: (0, 3, 6), (1, 4, 7), (2, 5, 8) - Diagonal lines: (0, 4, 8), (2, 4, 6) ''' self.winning_lines = [tuple(range(i, size**2, size)) for i in range(size)] + \ [tuple(range(i * size, (i + 1) * size)) for i in range(size)] + \ [tuple(range(0, size**2, size + 1)), tuple(range(size - 1, size**2 - 1, size - 1))] def make_classical_move(self, row, col, player_mark, is_collapsed=False): if self.cells[row][col] == ' ' or is_collapsed: # Check if the cell is occupied self.cells[row][col] = player_mark index = row * self.size + col if player_mark == 'X': self.circuit.x(self.qubits[index]) else: self.circuit.id(self.qubits[index]) return True return False def make_swap_move(self, row1, col1, row2, col2, **kwargs): if self.cells[row1][col1] != ' ' and self.cells[row2][col2] != ' ': indices = [row1 * self.size + col1, row2 * self.size + col2] self.circuit.swap(self.qubits[indices[0]], self.qubits[indices[1]]) self.cells[row1][col1], self.cells[row2][col2] = self.cells[row2][col2], self.cells[row1][col1] return True return False def make_superposition_move(self, row, col, player_mark, **kwargs): if self.cells[row][col] == ' ': index = row * self.size + col self.circuit.h(self.qubits[index]) self.cells[row][col] = player_mark + '?' self.superposition_count += 1 return True return False def make_entangled_move(self, *positions, risk_level, player_mark, **kwargs): # Entangle the quantum states of 2 or 3 cells based on the risk level pos_count = len(positions) if pos_count not in [2, 3] or risk_level not in [1, 2, 3, 4] or len(set(positions)) != pos_count or \ (pos_count == 2 and risk_level not in [1, 3]) or (pos_count == 3 and risk_level not in [2, 4]) or \ any(self.cells[row][col] != ' ' for row, col in positions): return False indices = [row * self.size + col for row, col in positions] self.circuit.h(self.qubits[indices[0]]) if pos_count == 2: # Pairwise Entanglement with Bell state for 2 qubits: # Lv1. |Ψ+⟩ = (∣01⟩ + ∣10⟩)/√2 | Lv3. |Φ+⟩ = (∣00⟩ + ∣11⟩)/√2 if risk_level == 1: self.circuit.x(self.qubits[indices[1]]) self.circuit.cx(self.qubits[indices[0]], self.qubits[indices[1]]) else: # Triple Entanglement with GHZ state for 3 qubits: # Lv2. (∣010⟩ + ∣101⟩)/√2 | Lv4. (∣000⟩ + ∣111⟩)/√2 if risk_level == 2: self.circuit.x(self.qubits[indices[1]]) self.circuit.x(self.qubits[indices[2]]) # Apply CNOT chain to entangle all 3 qubits self.circuit.cx(self.qubits[indices[0]], self.qubits[indices[1]]) self.circuit.cx(self.qubits[indices[1]], self.qubits[indices[2]]) for row, col in positions: self.cells[row][col] = player_mark + '?' self.superposition_count += pos_count return True def can_be_collapsed(self): # If superpositions/entanglement cells form a potential winning line => collapse for line in self.winning_lines: if all(self.cells[i // self.size][i % self.size].endswith('?') for i in line): return True return False def collapse_board(self): # Update the board based on the measurement results and apply the corresponding classical moves self.circuit.barrier() self.circuit.measure(self.qubits, self.bits) # Measure all qubits to collapse them to classical states transpiled_circuit = transpile(self.circuit, self.simulator) job = self.simulator.run(transpiled_circuit, memory=True) counts = job.result().get_counts() max_state = max(counts, key=counts.get)[::-1] # Get the state with the highest probability for i in range(self.size ** 2): row, col = divmod(i, self.size) if self.cells[row][col].endswith('?'): self.circuit.reset(self.qubits[i]) self.make_classical_move(row, col, 'X' if max_state[i] == '1' else 'O', is_collapsed=True) self.superposition_count = 0 return counts def check_win(self): # Dynamic implementation for above logic with dynamic winning lines for line in self.winning_lines: # Check if all cells in the line are the same and not empty first_cell = self.cells[line[0] // self.size][line[0] % self.size] if first_cell not in [' ', 'X?', 'O?']: is_same = all(self.cells[i // self.size][i % self.size] == first_cell for i in line) if is_same: return line # If no spaces and no superpositions left => 'Draw' # If all cells are filled but some are still in superpositions => collapse_board if all(self.cells[i // self.size][i % self.size] not in [' '] for i in range(self.size**2)): if self.superposition_count <= 0: return 'Draw' return self.superposition_count return None # @markdown ### **3. `QuantumT3Widgets` class for game interface** class QuantumT3Widgets(metaclass=ABCMeta): def __init__(self, board, current_player, quantum_move_mode): self.board = board self.current_player = current_player self.quantum_move_mode = quantum_move_mode self.log = Output(layout={'margin': '10px 0 0 0'}) self.histogram_output = Output(layout={'margin': '0 0 10px 10px'}) self.circuit_output = Output() self.create_widgets() def create_widgets(self): # Create widgets for each cell and controls for game actions self.buttons = [] for row in range(self.board.size): self.buttons.append([]) for col in range(self.board.size): button = Button( description = ' ', layout = {'width': '100px', 'height': '100px', 'border': '1px solid black'}, style = {'button_color': 'lightgray', 'font_weight': 'bold', 'text_color': 'white'} ) button.on_click(self.create_on_cell_clicked(row, col)) self.buttons[row].append(button) self.create_action_buttons() self.game_info = HTML(f'<b>Current Player: {self.current_player} / Quantum Mode: {self.quantum_move_mode}</b>') self.board_histogram_widget = HBox( [VBox([VBox([HBox(row) for row in self.buttons]), self.game_info]), self.histogram_output], layout = {'display': 'flex', 'justify_content': 'center', 'align_items': 'flex-end'} ) display(VBox([self.board_histogram_widget, self.action_buttons, self.log, self.circuit_output])) def create_action_buttons(self): self.reset_btn = Button(description='Reset', button_style='danger') self.collapse_btn = Button(description='Collapse', button_style='warning') self.classical_btn = Button(description='Classical Move', button_style='primary') self.swap_btn = Button(description='SWAP Move', button_style='info') self.superposition_btn = Button(description='Superposition', button_style='success') self.entangled_btn = Button(description='Entanglement', button_style='success') self.entangled_options = Dropdown(options=[ ('', 0), # Qubits collapse to opposite states (not consecutive) ('Lv1. PAIRWAISE: ∣Ψ+⟩ = (∣01⟩ + ∣10⟩) / √2', 1), # Qubits collapse to opposite states (not consecutive) ('Lv2. TRIPLE: GHZ_Xs = (∣010⟩ + ∣101⟩) / √2', 2), ('Lv3. PAIRWAISE: ∣Φ+⟩ = (∣00⟩ + ∣11⟩) / √2', 3), # Can form consecutive winning cells or accidentally help the opponent ('Lv4. TRIPLE: GHZ = (∣000⟩ + ∣111⟩) / √2', 4), ], value=0, disabled=True) self.entangled_options.observe(self.update_entangled_options, names='value') self.reset_btn.on_click(self.on_reset_btn_clicked) self.collapse_btn.on_click(self.on_collapse_btn_clicked) self.classical_btn.on_click(self.create_on_move_clicked('CLASSICAL')) self.swap_btn.on_click(self.create_on_move_clicked('SWAP', 'Select 2 cells to swap their states.')) self.superposition_btn.on_click(self.create_on_move_clicked('SUPERPOSITION', 'Select a cell to put in superposition.')) self.entangled_btn.on_click(self.create_on_move_clicked('ENTANGLED', 'Select 2/3 cells based on risk level to entangle.')) self.action_buttons = HBox([ self.reset_btn, self.collapse_btn, self.classical_btn, self.swap_btn, self.superposition_btn, self.entangled_btn, self.entangled_options ]) @abstractmethod # Pure virtual functions => Must be overridden in the derived classes def on_reset_btn_clicked(self, btn=None): raise NotImplementedError('on_reset_btn_clicked method is not implemented.') @abstractmethod # Pure virtual functions => Must be overridden in the derived classes def on_collapse_btn_clicked(self, btn=None): raise NotImplementedError('on_collapse_btn_clicked method is not implemented.') @abstractmethod # Pure virtual functions => Must be overridden in the derived classes def on_move_clicked(self, mode, message=''): raise NotImplementedError('on_move_clicked method is not implemented.') @abstractmethod # Pure virtual functions => Must be overridden in the derived classes def on_cell_clicked(self, btn, row, col): raise NotImplementedError('on_cell_clicked method is not implemented.') def update_entangled_options(self, change): with self.log: self.entangled_options.disabled = change.new != 0 for row in self.buttons: for button in row: button.disabled = change.new == 0 # Check if there are enough empty cells for the selected operation empty_count = sum(cell == ' ' for row in self.board.cells for cell in row) total_empty_required = {1: 2, 2: 3, 3: 2, 4: 3} # Total empty cells required for each risk level if change.new == 0: return elif empty_count < total_empty_required[change.new]: print(f'Not enough empty cells to perform entanglement with risk level {change.new}. Please select another.') self.entangled_options.value = 0 else: print(f'Risk Level {change.new} ACTIVATED =>', end=' ') if change.new in [1, 3]: print(f'Select 2 cells (qubits) for this PAIRWAISE entanglement.') else: print(f'Select 3 cells (qubits) for this TRIPLE entanglement.') def create_on_move_clicked(self, mode, message=''): def on_move_clicked(btn): with self.log: try: self.on_move_clicked(mode, message) except Exception as e: print(f'ERROR: {e}') return on_move_clicked def create_on_cell_clicked(self, row, col): def on_cell_clicked(btn): with self.log: try: self.on_cell_clicked(btn, row, col) except Exception as e: print(f'ERROR: {e}') return on_cell_clicked def display_circuit(self): with self.circuit_output: clear_output(wait=True) display(self.board.circuit.draw('mpl', fold=-1, initial_state=True)) def display_histogram(self, counts): with self.histogram_output: clear_output(wait=True) display(plot_histogram(counts, figsize=(9, 4))) # @markdown ### **4. `QuantumT3GUI` class for game flow and interaction between players and `Board`** class QuantumT3GUI(QuantumT3Widgets): def __init__(self, size=3, simulator=None): super().__init__(Board(size, simulator), 'X', 'CLASSICAL') self.quantum_moves_selected = [] # Selected cells for operation on multi-qubit gates self.game_over = False def buttons_disabled(self, is_disabled=True): for btn in self.action_buttons.children[1:]: btn.disabled = is_disabled for row in self.buttons: for btn in row: btn.disabled = is_disabled def update_entire_board(self): for row in range(self.board.size): for col in range(self.board.size): cell = self.board.cells[row][col] color_map = {'X': 'dodgerblue', 'O': 'purple', '?': 'green', ' ': 'lightgray'} self.buttons[row][col].description = cell if cell != ' ' else ' ' self.buttons[row][col].style.button_color = color_map[cell[-1]] def clean_incompleted_quantum_moves(self): for row, col in self.quantum_moves_selected: if self.board.cells[row][col] == ' ': self.buttons[row][col].description = ' ' self.buttons[row][col].style.button_color = 'lightgray' self.quantum_moves_selected = [] def on_reset_btn_clicked(self, btn=None): with self.log: clear_output(wait=True) self.board = Board(self.board.size, self.board.simulator) self.current_player = 'X' self.quantum_move_mode = 'CLASSICAL' self.quantum_moves_selected = [] self.game_info.value = f'<b>Current Player: {self.current_player} / Quantum Mode: {self.quantum_move_mode}</b>' self.game_over = False self.update_entire_board() self.buttons_disabled(False) self.entangled_options.disabled = True with self.histogram_output: clear_output() with self.circuit_output: clear_output() print('Game reset. New game started.') def on_collapse_btn_clicked(self, btn=None): with self.log: if self.quantum_moves_selected: print('Please complete the current quantum operation before measuring the board.') return clear_output(wait=True) counts = self.board.collapse_board() self.display_histogram(counts) self.update_entire_board() # Update the board cells with the collapsed states self.check_win() print('Board measured and quantum states collapsed.') def on_move_clicked(self, mode, message=''): clear_output(wait=True) self.quantum_move_mode = mode self.game_info.value = f'<b>Current Player: {self.current_player} / Quantum Mode: {self.quantum_move_mode}</b>' self.clean_incompleted_quantum_moves() for row in self.buttons: for button in row: button.disabled = mode == 'ENTANGLED' if mode == 'ENTANGLED': self.entangled_options.value = 0 self.entangled_options.disabled = mode != 'ENTANGLED' print(f'{mode} mode ACTIVATED' + (f': {message}' if message else '')) def on_cell_clicked(self, btn, row, col): if self.quantum_move_mode == 'CLASSICAL': if self.board.make_classical_move(row, col, self.current_player): btn.description = self.board.cells[row][col] btn.style.button_color = 'dodgerblue' if self.current_player == 'X' else 'purple' self.check_win() else: print('That position is already occupied. Please choose another.') elif self.quantum_move_mode == 'SUPERPOSITION': if self.board.cells[row][col] == ' ': btn.description = self.current_player + '?' btn.style.button_color = 'green' self.make_quantum_move_wrapper( pos=(row, col), board_func=self.board.make_superposition_move, success_msg='Cell is now in superposition state.') else: print('Invalid SUPERPOSITION move. Cell must be empty.') elif len(self.quantum_moves_selected) < 3: # Multi-qubit gates operation self.quantum_moves_selected.append((row, col)) # Store the selected cell of operation print(f'Cell ({row + 1}, {col + 1}) selected for {self.quantum_move_mode} move.') if self.quantum_move_mode == 'SWAP' and len(self.quantum_moves_selected) == 2: flat_pos = sum(self.quantum_moves_selected, ()) # Flatten the tuple to match 4 arguments in Board.make_swap_move pos1, pos2 = self.quantum_moves_selected self.make_quantum_move_wrapper( pos=flat_pos, board_func=self.board.make_swap_move, success_msg=f'SWAPPED Cell {pos1} to {pos2}', success_func=self.swap_on_board, failure_msg='Invalid SWAP move. Both cells must be non-empty.') elif self.quantum_move_mode == 'ENTANGLED': if self.board.cells[row][col] == ' ': btn.description = self.current_player + '?' btn.style.button_color = 'green' total_empty_required = {1: 2, 2: 3, 3: 2, 4: 3} # Total empty cells required for each risk level if len(self.quantum_moves_selected) == total_empty_required[self.entangled_options.value]: self.make_quantum_move_wrapper( pos=self.quantum_moves_selected, board_func=self.board.make_entangled_move, success_msg='These positions are now entangled and in a superposition state.', failure_msg='Invalid ENTANGLEMENT move. Duplicated cell selection.') else: clear_output(wait=True) print('Invalid ENTANGLEMENT move. A position is already occupied.') self.quantum_moves_selected.pop() # Remove the invalid cell from the selected list def swap_on_board(self): row1, col1 = self.quantum_moves_selected[0][0], self.quantum_moves_selected[0][1] row2, col2 = self.quantum_moves_selected[1][0], self.quantum_moves_selected[1][1] # Swap the description and color of the selected cells self.buttons[row1][col1].description, self.buttons[row2][col2].description = \ self.buttons[row2][col2].description, self.buttons[row1][col1].description self.buttons[row1][col1].style.button_color, self.buttons[row2][col2].style.button_color = \ self.buttons[row2][col2].style.button_color, self.buttons[row1][col1].style.button_color def make_quantum_move_wrapper(self, pos, board_func, success_msg='', success_func=None, failure_msg=''): if board_func(*pos, risk_level=self.entangled_options.value, player_mark=self.current_player): if success_msg: print(success_msg) if success_func: success_func() if self.board.can_be_collapsed(): print('Perform automatic board measurement and collapse the states.') self.quantum_moves_selected = [] self.on_collapse_btn_clicked() else: self.check_win() else: clear_output(wait=True) if failure_msg: print(failure_msg) self.clean_incompleted_quantum_moves() def check_win(self): self.quantum_moves_selected = [] while not self.game_over: # Check if the game is over after each move self.display_circuit() result = self.board.check_win() if result == 'Draw': # All cells are filled but no winner yet self.game_over = True print("Game Over. It's a draw!") elif type(result) == tuple: # A player wins self.game_over = True for cell_index in result: row, col = divmod(cell_index, self.board.size) self.buttons[row][col].style.button_color = 'orangered' print(f'Game Over. {self.board.cells[row][col]} wins!') elif type(result) == int: # All cells are filled but some are still in superpositions print(f'All cells are filled but {result} of them still in superpositions => Keep Collapsing...') self.quantum_moves_selected = [] self.on_collapse_btn_clicked() # Automatically collapse the board break else: # Switch players if no winner yet then continue the game self.current_player = 'O' if self.current_player == 'X' else 'X' # Switch players self.game_info.value = f'<b>Current Player: {self.current_player} / Quantum Mode: {self.quantum_move_mode}</b>' break if self.game_over: self.buttons_disabled(True) game = QuantumT3GUI(size=3, simulator=AerSimulator())
https://github.com/arnavdas88/QuGlassyIsing
arnavdas88
!pip install qiskit J = 4.0 B_x = 0.25 B_z = 1.5 import numpy as np from qiskit.providers.aer import AerSimulator, QasmSimulator from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import TwoLocal from qiskit.aqua.operators import * from qiskit.aqua import set_qiskit_aqua_logging, QuantumInstance from qiskit.aqua.algorithms import NumPyMinimumEigensolver, VQE, NumPyEigensolver from qiskit.circuit import QuantumCircuit, ParameterVector from qiskit.visualization import plot_histogram Hamiltonian = J * (Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I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I ^ X ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X )) ansatz = TwoLocal(num_qubits=36, rotation_blocks=['ry', 'rz'], entanglement_blocks=None, entanglement='full', reps=1, skip_unentangled_qubits=False, skip_final_rotation_layer=True) print(ansatz) backend = AerSimulator(method='matrix_product_state') quantum_instance = QuantumInstance(backend, shots = 8192, initial_layout = None, optimization_level = 3) optimizer = COBYLA(maxiter=10000, tol=0.000000001) vqe = VQE(Hamiltonian, ansatz, optimizer, include_custom = False) print('We are using:', quantum_instance.backend) vqe_result = vqe.run(quantum_instance) print(vqe['result']) plot_histogram(vqe_result['eigenstate']) import pickle filename = "2D_Ising_Model_CountsAF3.pkl" a = {'vqe_result': vqe_result} #This saves the data with open(filename, 'wb') as handle: pickle.dump(a, handle, protocol=pickle.HIGHEST_PROTOCOL) # This loads the data with open(filename, 'rb') as handle: b = pickle.load(handle)
https://github.com/sanori/quantum-docker
sanori
// The following codes are from // https://docs.microsoft.com/en-us/quantum/tutorials/quantum-random-number-generator open Microsoft.Quantum.Convert; open Microsoft.Quantum.Math; open Microsoft.Quantum.Measurement; open Microsoft.Quantum.Canon; open Microsoft.Quantum.Intrinsic; // test documentation operation SampleQuantumRandomNumberGenerator() : Result { use q = Qubit(); // Allocate a qubit. H(q); // Put the qubit to superposition. It now has a 50% chance of being 0 or 1. return M(q); // Measure the qubit value. } operation SampleRandomNumberInRange(max : Int) : Int { mutable output = 0; repeat { mutable bits = []; for idxBit in 1..BitSizeI(max) { set bits += [SampleQuantumRandomNumberGenerator()]; } set output = ResultArrayAsInt(bits); } until (output <= max); return output; } %simulate SampleRandomNumberInRange max=50 H? %lsmagic
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit import QuantumCircuit from qiskit.providers.fake_provider import FakeVigoV2 backend = FakeVigoV2() qc = QuantumCircuit(2, 1) qc.h(0) qc.x(1) qc.cp(np.pi/4, 0, 1) qc.h(0) qc.measure([0], [0]) qc.draw(output='mpl')
https://github.com/AbeerVaishnav13/4-qubit-design
AbeerVaishnav13
import warnings warnings.filterwarnings('ignore') from qiskit_metal import designs, MetalGUI design = designs.DesignPlanar() design.overwrite_enabled = True design.chips.main.size_x = '12mm' design.chips.main.size_y = '10mm' gui = MetalGUI(design) from qiskit_metal.qlibrary.qubits.transmon_pocket_cl import TransmonPocketCL design.delete_all_components() design_span_x = 5 design_span_y = 3 half_chip_width = design_span_x / 2 half_chip_height = design_span_y / 2 connection_pads_options = dict( a = dict(loc_W=1, loc_H=-1), b = dict(loc_W=1, loc_H=1), c = dict(loc_W=-1, loc_H=-1) ) transmons = [] transmons.append(TransmonPocketCL(design, 'Q1', options=dict(pos_x=f'-{half_chip_width}mm', pos_y=f'{-half_chip_height}mm', connection_pads=dict(**connection_pads_options)))) transmons.append(TransmonPocketCL(design, 'Q2', options=dict(pos_x=f'0mm', pos_y=f'{half_chip_height}mm', orientation=-90, connection_pads=dict(d=dict(loc_W=-1, loc_H=1), **connection_pads_options)))) transmons.append(TransmonPocketCL(design, 'Q3', options=dict(pos_x=f'0mm', pos_y=f'{-half_chip_height}mm', orientation=90, connection_pads=dict(d=dict(loc_W=-1, loc_H=1), **connection_pads_options)))) transmons.append(TransmonPocketCL(design, 'Q4', options=dict(pos_x=f'{half_chip_width}mm', pos_y=f'{half_chip_height}mm', orientation=180, connection_pads=dict(**connection_pads_options)))) gui.rebuild() gui.autoscale() gui.screenshot(name="transmons") from qiskit_metal.qlibrary.tlines.meandered import RouteMeander from qiskit_metal import Dict fillet='99.99um' options = Dict( meander=Dict( lead_start='0.1mm', lead_end='0.1mm', asymmetry='0 um') ) def connect(component_name: str, component1: str, pin1: str, component2: str, pin2: str, length: str, asymmetry='0 um', start_strght='0 um', end_strght='0 um', flip=False): """Connect two pins with a CPW.""" myoptions = Dict( pin_inputs=Dict( start_pin=Dict( component=component1, pin=pin1), end_pin=Dict( component=component2, pin=pin2)), lead=Dict( start_straight=start_strght, end_straight=end_strght ), total_length=length, fillet = '99.9um') myoptions.update(options) myoptions.meander.asymmetry = asymmetry myoptions.meander.lead_direction_inverted = 'true' if flip else 'false' return RouteMeander(design, component_name, myoptions) asym_h = 100 asym_v = 100 cpw = [] cpw.append(connect('cpw1', 'Q1', 'b', 'Q2', 'a', '8 mm', f'+{asym_h}um', '0.1mm', '0.1mm')) cpw.append(connect('cpw2', 'Q3', 'b', 'Q2', 'b', '8 mm', f'-{asym_v}um', '0.6mm', '0.4mm')) cpw.append(connect('cpw3', 'Q4', 'b', 'Q3', 'a', '8 mm', f'+{asym_h}um', '0.1mm', '0.1mm')) cpw.append(connect('cpw4', 'Q3', 'd', 'Q1', 'a', '8 mm', f'-{asym_h}um', '0.1mm', '0.1mm')) cpw.append(connect('cpw5', 'Q2', 'd', 'Q4', 'a', '8 mm', f'-{asym_h}um', '0.1mm', '0.1mm')) gui.rebuild() gui.autoscale() gui.screenshot(name="cpws") from qiskit_metal.qlibrary.terminations.launchpad_wb_coupled import LaunchpadWirebondCoupled readouts_lwc = [] control_lwc = [] offset_x = 0 offset_y = 1 #Readouts readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R1', options = dict( pos_x = '-5mm', pos_y = f'-{half_chip_height+offset_y}mm', lead_length = '30um'))) readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R2', options = dict( pos_x = '-1mm', pos_y = '4mm', orientation = -90, lead_length = '30um'))) readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R3', options = dict( pos_x = '1mm', pos_y = '-4mm', orientation = 90, lead_length = '30um'))) readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R4', options = dict( pos_x = '5mm', pos_y = f'{half_chip_height+offset_y}mm', orientation = 180, lead_length = '30um'))) #Controls control_lwc.append(LaunchpadWirebondCoupled(design, 'CL1', options = dict( pos_x = '-5mm', pos_y = '2mm', lead_length = '30um'))) control_lwc.append(LaunchpadWirebondCoupled(design, 'CL2', options = dict( pos_x = '4mm', pos_y = '4mm', orientation = -90, lead_length = '30um'))) control_lwc.append(LaunchpadWirebondCoupled(design, 'CL3', options = dict( pos_x = '-4mm', pos_y = '-4mm', orientation = 90, lead_length = '30um'))) control_lwc.append(LaunchpadWirebondCoupled(design, 'CL4', options = dict( pos_x = '5mm', pos_y = '-2mm', orientation = 180, lead_length = '30um'))) gui.rebuild() gui.autoscale() gui.screenshot(name="launchpads") readout_lines = [] asym_14 = 700 asym_23 = 700 options = Dict( lead=Dict( start_straight='430um', end_straight='0um'), fillet='99.99um') readout_lines.append(connect('ol1', 'Q1', 'c', 'R1', 'tie', '8 mm', f'{asym_14}um')) readout_lines.append(connect('ol2', 'Q2', 'c', 'R2', 'tie', '8 mm', f'{asym_23}um')) readout_lines.append(connect('ol3', 'Q3', 'c', 'R3', 'tie', '8 mm', f'{asym_23}um')) readout_lines.append(connect('ol4', 'Q4', 'c', 'R4', 'tie', '8 mm', f'{asym_14}um')) gui.rebuild() gui.autoscale() gui.screenshot(name="readouts") from qiskit_metal.qlibrary.tlines.anchored_path import RouteAnchors from collections import OrderedDict import numpy as np control_lines = [] def connectRouteAnchor(name: str, component1: str, pin1: str, component2: str, pin2: str, anchor_points: OrderedDict) -> RouteAnchors: options_line_cl = dict( pin_inputs = dict(start_pin = dict(component = component1, pin = pin1), end_pin = dict(component = component2, pin = pin2)), anchors = anchor_points, lead = dict(start_straight = '200um', end_straight = '225um'), fillet = fillet ) return RouteAnchors(design, name, options_line_cl) anchors1c = OrderedDict() anchors1c[0] = np.array([-4, -1.42]) anchors1c[1] = np.array([-4, 2]) control_lines.append(connectRouteAnchor('line_cl1', 'Q1', 'Charge_Line', 'CL1', 'tie', anchors1c)) anchors2c = OrderedDict() anchors2c[0] = np.array([0.08, 3.25]) anchors2c[1] = np.array([4, 3.25]) control_lines.append(connectRouteAnchor('line_cl2', 'Q2', 'Charge_Line', 'CL2', 'tie', anchors2c)) anchors3c = OrderedDict() anchors3c[0] = np.array([-0.08, -3.25]) anchors3c[1] = np.array([-4, -3.25]) control_lines.append(connectRouteAnchor('line_cl3', 'Q3', 'Charge_Line', 'CL3', 'tie', anchors3c)) anchors4c = OrderedDict() anchors4c[0] = np.array([4, 1.42]) anchors4c[1] = np.array([4, -2]) control_lines.append(connectRouteAnchor('line_cl4', 'Q4', 'Charge_Line', 'CL4', 'tie', anchors4c)) gui.rebuild() gui.autoscale() gui.screenshot(name="full_design") # Qubit Frequencies # Q1 : 5 # Q2 : 5.1 # Q3 : 5.2 # Q4 : 5.3 # Readout Frequencies # R1 : 7 # R2 : 7.1 # R3 : 7.2 # R4 : 7.3 # CPW Frequencies # cpw1 : 7.5 # cpw2 : 7.6 # cpw3 : 7.7 # cpw4 : 7.8 # cpw5 : 7.9 from qiskit_metal.analyses.quantization import EPRanalysis eig_res1 = EPRanalysis(design, "hfss") hfss1 = eig_res1.sim.renderer hfss1.start() transmons[0].options.pad_gap = '40um' transmons[0].options.pad_width = '405um' transmons[0].options.pad_height = '90um' gui.rebuild() hfss1.activate_ansys_design("Tune_Q1", 'eigenmode') hfss1.render_design(['Q1'], [('Q1', 'c'), ('Q1', 'a'),('Q1', 'b'),('Q1', 'Charge_Line')]) # Analysis properties setup1 = hfss1.pinfo.setup setup1.passes = 10 setup1.n_modes = 3 print(f""" Number of eigenmodes to find = {setup1.n_modes} Number of simulation passes = {setup1.passes} Convergence freq max delta percent diff = {setup1.delta_f} """) # Next 2 lines are counterinuitive, since there is no junction in this resonator. # However, these are necessary to make pyEPR work correctly. Please do note delete hfss1.pinfo.design.set_variable('Lj', '12 nH') hfss1.pinfo.design.set_variable('Cj', '1 fF') setup1.analyze() eig_res1.sim.convergence_t, eig_res1.sim.convergence_f, _ = hfss1.get_convergences() eig_res1.sim.plot_convergences() # eig_res1.sim.plot_fields("main") # hfss1.save_screenshot("C:/Users/Nilay/Documents/GitHub/qiskit-metal-qubit-design/ansys_renders/q1_epr_e-field.png") hfss1.save_screenshot("C:/Users/Nilay/Documents/GitHub/qiskit-metal-qubit-design/ansys_renders/q1_epr_e-field.png") from qiskit_metal.analyses.quantization import EPRanalysis eig_res2 = EPRanalysis(design, "hfss") hfss2 = eig_res2.sim.renderer hfss2.start() transmons[1].options.pad_gap = '40um' transmons[1].options.pad_width = '378um' transmons[1].options.pad_height = '90um' gui.rebuild() hfss2.activate_ansys_design("Tune_Q2", 'eigenmode') hfss2.render_design(['Q2'], [('Q2', 'c'), ('Q2', 'a'),('Q2', 'b'),('Q2', 'd'),('Q2', 'Charge_Line')]) # Analysis properties setup2 = hfss2.pinfo.setup setup2.passes = 10 setup2.n_modes = 3 print(f""" Number of eigenmodes to find = {setup2.n_modes} Number of simulation passes = {setup2.passes} Convergence freq max delta percent diff = {setup2.delta_f} """) # Next 2 lines are counterinuitive, since there is no junction in this resonator. # However, these are necessary to make pyEPR work correctly. Please do note delete hfss2.pinfo.design.set_variable('Lj', '12 nH') hfss2.pinfo.design.set_variable('Cj', '1 fF') setup2.analyze() eig_res2.sim.convergence_t, eig_res2.sim.convergence_f, _ = hfss2.get_convergences() eig_res2.sim.plot_convergences() # eig_res2.sim.plot_fields("main") # hfss2.save_screenshot("C:/Users/Nilay/Documents/GitHub/qiskit-metal-qubit-design/ansys_renders/q2_epr_e-field.png") hfss2.save_screenshot("C:/Users/Nilay/Documents/GitHub/qiskit-metal-qubit-design/ansys_renders/q2_epr_e-field.png") from qiskit_metal.analyses.quantization import EPRanalysis eig_res3 = EPRanalysis(design, "hfss") hfss3 = eig_res3.sim.renderer hfss3.start() transmons[2].options.pad_gap = '40um' transmons[2].options.pad_width = '353um' transmons[2].options.pad_height = '90um' gui.rebuild() hfss3.activate_ansys_design("Tune_Q3", 'eigenmode') hfss3.render_design(['Q3'], [('Q3', 'c'), ('Q3', 'a'),('Q3', 'b'),('Q3', 'd'),('Q3', 'Charge_Line')]) # Analysis properties setup3 = hfss3.pinfo.setup setup3.passes = 10 setup3.n_modes = 3 print(f""" Number of eigenmodes to find = {setup3.n_modes} Number of simulation passes = {setup3.passes} Convergence freq max delta percent diff = {setup3.delta_f} """) # Next 2 lines are counterinuitive, since there is no junction in this resonator. # However, these are necessary to make pyEPR work correctly. Please do note delete hfss3.pinfo.design.set_variable('Lj', '12 nH') hfss3.pinfo.design.set_variable('Cj', '1 fF') setup3.analyze() eig_res3.sim.convergence_t, eig_res3.sim.convergence_f, _ = hfss3.get_convergences() eig_res3.sim.plot_convergences() # eig_res3.sim.plot_fields("main") # hfss3.save_screenshot("C:/Users/Nilay/Documents/GitHub/qiskit-metal-qubit-design/ansys_renders/q3_epr_e-field.png") hfss3.save_screenshot("C:/Users/Nilay/Documents/GitHub/qiskit-metal-qubit-design/ansys_renders/q3_epr_e-field.png") from qiskit_metal.analyses.quantization import EPRanalysis eig_res4 = EPRanalysis(design, "hfss") hfss4 = eig_res4.sim.renderer hfss4.start() transmons[3].options.pad_gap = '40um' transmons[3].options.pad_width = '344um' transmons[3].options.pad_height = '90um' gui.rebuild() hfss4.activate_ansys_design("Tune_Q4", 'eigenmode') hfss4.render_design(['Q4'], [('Q4', 'c'), ('Q4', 'a'),('Q4', 'b'),('Q4', 'Charge_Line')]) # Analysis properties setup4 = hfss4.pinfo.setup setup4.passes = 10 setup4.n_modes = 3 print(f""" Number of eigenmodes to find = {setup4.n_modes} Number of simulation passes = {setup4.passes} Convergence freq max delta percent diff = {setup4.delta_f} """) # Next 2 lines are counterinuitive, since there is no junction in this resonator. # However, these are necessary to make pyEPR work correctly. Please do note delete hfss4.pinfo.design.set_variable('Lj', '12 nH') hfss4.pinfo.design.set_variable('Cj', '1 fF') setup4.analyze() eig_res4.sim.convergence_t, eig_res4.sim.convergence_f, _ = hfss4.get_convergences() eig_res4.sim.plot_convergences() # eig_res4.sim.plot_fields("main") # hfss4.save_screenshot("C:/Users/Nilay/Documents/GitHub/qiskit-metal-qubit-design/ansys_renders/q4_epr_e-field.png") hfss4.save_screenshot("C:/Users/Nilay/Documents/GitHub/qiskit-metal-qubit-design/ansys_renders/q4_epr_e-field.png")
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit import QuantumCircuit, transpile from qiskit.quantum_info import Kraus, SuperOp from qiskit_aer import AerSimulator from qiskit.tools.visualization import plot_histogram # Import from Qiskit Aer noise module from qiskit_aer.noise import (NoiseModel, QuantumError, ReadoutError, pauli_error, depolarizing_error, thermal_relaxation_error) # Construct a 1-qubit bit-flip and phase-flip errors p_error = 0.05 bit_flip = pauli_error([('X', p_error), ('I', 1 - p_error)]) phase_flip = pauli_error([('Z', p_error), ('I', 1 - p_error)]) print(bit_flip) print(phase_flip) # Compose two bit-flip and phase-flip errors bitphase_flip = bit_flip.compose(phase_flip) print(bitphase_flip) # Tensor product two bit-flip and phase-flip errors with # bit-flip on qubit-0, phase-flip on qubit-1 error2 = phase_flip.tensor(bit_flip) print(error2) # Convert to Kraus operator bit_flip_kraus = Kraus(bit_flip) print(bit_flip_kraus) # Convert to Superoperator phase_flip_sop = SuperOp(phase_flip) print(phase_flip_sop) # Convert back to a quantum error print(QuantumError(bit_flip_kraus)) # Check conversion is equivalent to original error QuantumError(bit_flip_kraus) == bit_flip # Measurement miss-assignement probabilities p0given1 = 0.1 p1given0 = 0.05 ReadoutError([[1 - p1given0, p1given0], [p0given1, 1 - p0given1]]) # Create an empty noise model noise_model = NoiseModel() # Add depolarizing error to all single qubit u1, u2, u3 gates error = depolarizing_error(0.05, 1) noise_model.add_all_qubit_quantum_error(error, ['u1', 'u2', 'u3']) # Print noise model info print(noise_model) # Create an empty noise model noise_model = NoiseModel() # Add depolarizing error to all single qubit u1, u2, u3 gates on qubit 0 only error = depolarizing_error(0.05, 1) noise_model.add_quantum_error(error, ['u1', 'u2', 'u3'], [0]) # Print noise model info print(noise_model) # System Specification n_qubits = 4 circ = QuantumCircuit(n_qubits) # Test Circuit circ.h(0) for qubit in range(n_qubits - 1): circ.cx(qubit, qubit + 1) circ.measure_all() print(circ) # Ideal simulator and execution sim_ideal = AerSimulator() result_ideal = sim_ideal.run(circ).result() plot_histogram(result_ideal.get_counts(0)) # Example error probabilities p_reset = 0.03 p_meas = 0.1 p_gate1 = 0.05 # QuantumError objects error_reset = pauli_error([('X', p_reset), ('I', 1 - p_reset)]) error_meas = pauli_error([('X',p_meas), ('I', 1 - p_meas)]) error_gate1 = pauli_error([('X',p_gate1), ('I', 1 - p_gate1)]) error_gate2 = error_gate1.tensor(error_gate1) # Add errors to noise model noise_bit_flip = NoiseModel() noise_bit_flip.add_all_qubit_quantum_error(error_reset, "reset") noise_bit_flip.add_all_qubit_quantum_error(error_meas, "measure") noise_bit_flip.add_all_qubit_quantum_error(error_gate1, ["u1", "u2", "u3"]) noise_bit_flip.add_all_qubit_quantum_error(error_gate2, ["cx"]) print(noise_bit_flip) # Create noisy simulator backend sim_noise = AerSimulator(noise_model=noise_bit_flip) # Transpile circuit for noisy basis gates circ_tnoise = transpile(circ, sim_noise) # Run and get counts result_bit_flip = sim_noise.run(circ_tnoise).result() counts_bit_flip = result_bit_flip.get_counts(0) # Plot noisy output plot_histogram(counts_bit_flip) # T1 and T2 values for qubits 0-3 T1s = np.random.normal(50e3, 10e3, 4) # Sampled from normal distribution mean 50 microsec T2s = np.random.normal(70e3, 10e3, 4) # Sampled from normal distribution mean 50 microsec # Truncate random T2s <= T1s T2s = np.array([min(T2s[j], 2 * T1s[j]) for j in range(4)]) # 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 # 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_reset[j], "reset", [j]) noise_thermal.add_quantum_error(errors_measure[j], "measure", [j]) noise_thermal.add_quantum_error(errors_u1[j], "u1", [j]) noise_thermal.add_quantum_error(errors_u2[j], "u2", [j]) noise_thermal.add_quantum_error(errors_u3[j], "u3", [j]) for k in range(4): noise_thermal.add_quantum_error(errors_cx[j][k], "cx", [j, k]) print(noise_thermal) # Run the noisy simulation sim_thermal = AerSimulator(noise_model=noise_thermal) # Transpile circuit for noisy basis gates circ_tthermal = transpile(circ, sim_thermal) # Run and get counts result_thermal = sim_thermal.run(circ_tthermal).result() counts_thermal = result_thermal.get_counts(0) # Plot noisy output plot_histogram(counts_thermal) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/Qiskit-Extensions/circuit-knitting-toolbox
Qiskit-Extensions
# This code is part of Qiskit. # # (C) Copyright IBM 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Two-qubit instruction representing a swap + single-qubit reset.""" from __future__ import annotations from qiskit.circuit import QuantumCircuit, Instruction class Move(Instruction): """A two-qubit instruction representing a reset of the second qubit followed by a swap. **Circuit Symbol:** .. parsed-literal:: β”Œβ”€β”€β”€β”€β”€β”€β”€β” q_0: ─0 β”œ q_0: ──────X─ β”‚ Move β”‚ = β”‚ q_1: ─1 β”œ q_1: ─|0>──X─ β””β”€β”€β”€β”€β”€β”€β”€β”˜ The desired effect of this instruction, typically, is to move the state of the first qubit to the second qubit. For this to work as expected, the second incoming qubit must share no entanglement with the remainder of the system. If this qubit *is* entangled, then performing the reset operation will in turn implement a quantum channel on the other qubit(s) with which it is entangled, resulting in the partial collapse of those qubits. The simplest way to ensure that the second (i.e., destination) qubit shares no entanglement with the remainder of the system is to use a fresh qubit which has not been used since initialization. Another valid way is to use, as a desination qubit, a qubit whose immediate prior use was as the source (i.e., first) qubit of a preceding :class:`Move` operation. The following circuit contains two :class:`Move` operations, corresponding to each of the aforementioned cases: .. plot:: :include-source: import numpy as np from qiskit import QuantumCircuit from circuit_knitting.cutting.instructions import Move qc = QuantumCircuit(4) qc.ryy(np.pi / 4, 0, 1) qc.rx(np.pi / 4, 3) qc.append(Move(), [1, 2]) qc.rz(np.pi / 4, 0) qc.ryy(np.pi / 4, 2, 3) qc.append(Move(), [2, 1]) qc.ryy(np.pi / 4, 0, 1) qc.rx(np.pi / 4, 3) qc.draw("mpl") A full demonstration of the :class:`Move` instruction is available in `the introductory tutorial on wire cutting <../circuit_cutting/tutorials/03_wire_cutting_via_move_instruction.ipynb>`__. """ def __init__(self, label: str | None = None): """Create a :class:`Move` instruction.""" super().__init__("move", 2, 0, [], label=label) def _define(self): """Set definition to equivalent circuit.""" qc = QuantumCircuit(2, name=self.name) qc.reset(1) qc.swap(0, 1) self.definition = qc
https://github.com/saalimon/grover_max_cut
saalimon
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import IBMQ, Aer, execute from qiskit.tools.visualization import plot_histogram IBMQ.load_account() q = QuantumRegister(15) c = ClassicalRegister(4) qc = QuantumCircuit(q,c) #cutedge checker def ccheck(a, b, c): qc.cx(q[a], q[c]) qc.cx(q[b], q[c]) #half adder #inputs: a,b #outputs: the sum output s and carry output c def hadder(a,b,s,c): #XOR qc.cx(q[b], q[s]) qc.cx(q[a], q[s]) #AND qc.ccx(q[a], q[b], q[c]) #inverse operations def iccheck(a, b, c): qc.cx(q[b], q[c]) qc.cx(q[a], q[c]) def ihadder(a,b,s,c): qc.ccx(q[a], q[b], q[c]) qc.cx(q[a], q[s]) qc.cx(q[b], q[s]) #initialization qc.h(q[0:4]) qc.barrier() for i in range(2): #step 3.1 ccheck(0,1,4) ccheck(0,2,5) ccheck(0,3,6) #step 3.2 hadder(4,5,8,7) hadder(5,6,10,9) hadder(7,9,12,11) # grover qc.x(q[13]) qc.h(q[13]) qc.cx(q[11],q[13]) ihadder(7,9,12,11) ihadder(5,6,10,9) ihadder(4,5,8,7) iccheck(0,3,6) iccheck(0,2,5) iccheck(0,1,4) qc.barrier() qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.x(q[0]) qc.x(q[1]) qc.x(q[2]) qc.x(q[3]) qc.barrier() qc.h(q[3]) qc.barrier() qc.ccx(q[0],q[1],q[13]) qc.cx(q[2],q[14]) qc.ccx(q[14],q[13],q[3]) qc.cx(q[2],q[14]) qc.ccx(q[0],q[1],q[13]) qc.barrier() qc.h(q[3]) qc.barrier() qc.x(q[0]) qc.x(q[1]) qc.x(q[2]) qc.x(q[3]) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.barrier() qc.measure(q[0:4], c[0:4]) backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend, shots=10000) result = job.result() count =result.get_counts() print(count) qc.draw(output='mpl') backend = Aer.get_backend('qasm_simulator') job = execute(qc,backend,shots=100000) result = job.result() count = result.get_counts() plot_histogram(count)
https://github.com/mathelatics/QGSS-2023-From-Theory-to-Implementations
mathelatics
from qiskit import BasicAer from qiskit.aqua import QuantumInstance from qiskit.aqua.algorithms import Shor N = 15 shor = Shor(N) backend = BasicAer.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend, shots=1024) ret = shor.run(quantum_instance) print("The list of factors of {} as computed by the Shor's algorithm is {}.".format(N, ret['factors'][0]))
https://github.com/jonasmaziero/computacao_quantica_qiskit
jonasmaziero
10*15+13*125, 10*15-27*125 def euclides_gcd(a,b): if b > a: # put in increasing order t = a; a = b; b = t if a == b or a%b == 0: # test equality or null remainder return b r = a%b print('a =', a, ', b =', b, ', k =', a//b, ', r =', r) while r != 0: a = b; b = r gcd = b r = a%b print('a =', a, ', b =', b, ', k =', a//b, ', r =', r) return b import math a = 6825; b = 1430; egcd = euclides_gcd(a,b) print('euclides_gcd('+str(a)+','+str(b)+')=',egcd, ', python_gcd = ', math.gcd(a,b)) -9*6825 + 43*1430 # ok! a = 126; p = 23; a%p, (a**p)%p, (a**(p-1))%p