repo
stringclasses
885 values
file
stringclasses
741 values
content
stringlengths
4
215k
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 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/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the optimize-1q-gate pass""" import unittest import numpy as np from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister from qiskit.transpiler import PassManager from qiskit.transpiler.passes import Optimize1qGates, Unroller from qiskit.converters import circuit_to_dag from qiskit.test import QiskitTestCase from qiskit.circuit import Parameter from qiskit.circuit.library import U1Gate, U2Gate, U3Gate, UGate, PhaseGate from qiskit.transpiler.exceptions import TranspilerError from qiskit.transpiler.target import Target class TestOptimize1qGates(QiskitTestCase): """Test for 1q gate optimizations.""" def test_dont_optimize_id(self): """Identity gates are like 'wait' commands. They should never be optimized (even without barriers). See: https://github.com/Qiskit/qiskit-terra/issues/2373 """ qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.i(qr) circuit.i(qr) dag = circuit_to_dag(circuit) pass_ = Optimize1qGates() after = pass_.run(dag) self.assertEqual(dag, after) def test_optimize_h_gates_pass_manager(self): """Transpile: qr:--[H]-[H]-[H]-- == qr:--[u2]--""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.h(qr[0]) circuit.h(qr[0]) expected = QuantumCircuit(qr) expected.append(U2Gate(0, np.pi), [qr[0]]) passmanager = PassManager() passmanager.append(Unroller(["u2"])) passmanager.append(Optimize1qGates()) result = passmanager.run(circuit) self.assertEqual(expected, result) def test_optimize_1q_gates_collapse_identity_equivalent(self): """test optimize_1q_gates removes u1(2*pi) rotations. See: https://github.com/Qiskit/qiskit-terra/issues/159 """ # ┌───┐┌───┐┌────────┐┌───┐┌─────────┐┌───────┐┌─────────┐┌───┐ ┌─┐» # qr_0: ┤ H ├┤ X ├┤ U1(2π) ├┤ X ├┤ U1(π/2) ├┤ U1(π) ├┤ U1(π/2) ├┤ X ├─────────┤M├» # └───┘└─┬─┘└────────┘└─┬─┘└─────────┘└───────┘└─────────┘└─┬─┘┌───────┐└╥┘» # qr_1: ───────■──────────────■───────────────────────────────────■──┤ U1(π) ├─╫─» # └───────┘ ║ » # cr: 2/═══════════════════════════════════════════════════════════════════════╩═» # 0 » # « # «qr_0: ──────────── # « ┌───────┐┌─┐ # «qr_1: ┤ U1(π) ├┤M├ # « └───────┘└╥┘ # «cr: 2/══════════╩═ # « 1 qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") qc = QuantumCircuit(qr, cr) qc.h(qr[0]) qc.cx(qr[1], qr[0]) qc.append(U1Gate(2 * np.pi), [qr[0]]) qc.cx(qr[1], qr[0]) qc.append(U1Gate(np.pi / 2), [qr[0]]) # these three should combine qc.append(U1Gate(np.pi), [qr[0]]) # to identity then qc.append(U1Gate(np.pi / 2), [qr[0]]) # optimized away. qc.cx(qr[1], qr[0]) qc.append(U1Gate(np.pi), [qr[1]]) qc.append(U1Gate(np.pi), [qr[1]]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) dag = circuit_to_dag(qc) simplified_dag = Optimize1qGates().run(dag) num_u1_gates_remaining = len(simplified_dag.named_nodes("u1")) self.assertEqual(num_u1_gates_remaining, 0) def test_optimize_1q_gates_collapse_identity_equivalent_phase_gate(self): """test optimize_1q_gates removes u1(2*pi) rotations. See: https://github.com/Qiskit/qiskit-terra/issues/159 """ # ┌───┐┌───┐┌───────┐┌───┐┌────────┐┌──────┐┌────────┐┌───┐ ┌─┐» # qr_0: ┤ H ├┤ X ├┤ P(2π) ├┤ X ├┤ P(π/2) ├┤ P(π) ├┤ P(π/2) ├┤ X ├────────┤M├» # └───┘└─┬─┘└───────┘└─┬─┘└────────┘└──────┘└────────┘└─┬─┘┌──────┐└╥┘» # qr_1: ───────■─────────────■────────────────────────────────■──┤ P(π) ├─╫─» # └──────┘ ║ » # cr: 2/══════════════════════════════════════════════════════════════════╩═» # 0 » # « # «qr_0: ─────────── # « ┌──────┐┌─┐ # «qr_1: ┤ P(π) ├┤M├ # « └──────┘└╥┘ # «cr: 2/═════════╩═ # « 1 qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") qc = QuantumCircuit(qr, cr) qc.h(qr[0]) qc.cx(qr[1], qr[0]) qc.append(PhaseGate(2 * np.pi), [qr[0]]) qc.cx(qr[1], qr[0]) qc.append(PhaseGate(np.pi / 2), [qr[0]]) # these three should combine qc.append(PhaseGate(np.pi), [qr[0]]) # to identity then qc.append(PhaseGate(np.pi / 2), [qr[0]]) # optimized away. qc.cx(qr[1], qr[0]) qc.append(PhaseGate(np.pi), [qr[1]]) qc.append(PhaseGate(np.pi), [qr[1]]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) dag = circuit_to_dag(qc) simplified_dag = Optimize1qGates(["p", "u2", "u", "cx", "id"]).run(dag) num_u1_gates_remaining = len(simplified_dag.named_nodes("p")) self.assertEqual(num_u1_gates_remaining, 0) def test_ignores_conditional_rotations(self): """Conditional rotations should not be considered in the chain. qr0:--[U1]-[U1]-[U1]-[U1]- qr0:--[U1]-[U1]- || || || || cr0:===.================== == cr0:===.====.=== || || cr1:========.============= cr1:========.=== """ qr = QuantumRegister(1, "qr") cr = ClassicalRegister(2, "cr") circuit = QuantumCircuit(qr, cr) circuit.append(U1Gate(0.1), [qr]).c_if(cr, 1) circuit.append(U1Gate(0.2), [qr]).c_if(cr, 3) circuit.append(U1Gate(0.3), [qr]) circuit.append(U1Gate(0.4), [qr]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr, cr) expected.append(U1Gate(0.1), [qr]).c_if(cr, 1) expected.append(U1Gate(0.2), [qr]).c_if(cr, 3) expected.append(U1Gate(0.7), [qr]) pass_ = Optimize1qGates() after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_ignores_conditional_rotations_phase_gates(self): """Conditional rotations should not be considered in the chain. qr0:--[U1]-[U1]-[U1]-[U1]- qr0:--[U1]-[U1]- || || || || cr0:===.================== == cr0:===.====.=== || || cr1:========.============= cr1:========.=== """ qr = QuantumRegister(1, "qr") cr = ClassicalRegister(2, "cr") circuit = QuantumCircuit(qr, cr) circuit.append(PhaseGate(0.1), [qr]).c_if(cr, 1) circuit.append(PhaseGate(0.2), [qr]).c_if(cr, 3) circuit.append(PhaseGate(0.3), [qr]) circuit.append(PhaseGate(0.4), [qr]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr, cr) expected.append(PhaseGate(0.1), [qr]).c_if(cr, 1) expected.append(PhaseGate(0.2), [qr]).c_if(cr, 3) expected.append(PhaseGate(0.7), [qr]) pass_ = Optimize1qGates(["p", "u2", "u", "cx", "id"]) after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_in_the_back(self): """Optimizations can be in the back of the circuit. See https://github.com/Qiskit/qiskit-terra/issues/2004. qr0:--[U1]-[U1]-[H]-- qr0:--[U1]-[H]-- """ qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.append(U1Gate(0.3), [qr]) circuit.append(U1Gate(0.4), [qr]) circuit.h(qr) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr) expected.append(U1Gate(0.7), [qr]) expected.h(qr) pass_ = Optimize1qGates() after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_in_the_back_phase_gate(self): """Optimizations can be in the back of the circuit. See https://github.com/Qiskit/qiskit-terra/issues/2004. qr0:--[U1]-[U1]-[H]-- qr0:--[U1]-[H]-- """ qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.append(PhaseGate(0.3), [qr]) circuit.append(PhaseGate(0.4), [qr]) circuit.h(qr) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr) expected.append(PhaseGate(0.7), [qr]) expected.h(qr) pass_ = Optimize1qGates(["p", "u2", "u", "cx", "id"]) after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_single_parameterized_circuit(self): """Parameters should be treated as opaque gates.""" qr = QuantumRegister(1) qc = QuantumCircuit(qr) theta = Parameter("theta") qc.append(U1Gate(0.3), [qr]) qc.append(U1Gate(0.4), [qr]) qc.append(U1Gate(theta), [qr]) qc.append(U1Gate(0.1), [qr]) qc.append(U1Gate(0.2), [qr]) dag = circuit_to_dag(qc) expected = QuantumCircuit(qr) expected.append(U1Gate(theta + 1.0), [qr]) after = Optimize1qGates().run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_parameterized_circuits(self): """Parameters should be treated as opaque gates.""" qr = QuantumRegister(1) qc = QuantumCircuit(qr) theta = Parameter("theta") qc.append(U1Gate(0.3), [qr]) qc.append(U1Gate(0.4), [qr]) qc.append(U1Gate(theta), [qr]) qc.append(U1Gate(0.1), [qr]) qc.append(U1Gate(0.2), [qr]) qc.append(U1Gate(theta), [qr]) qc.append(U1Gate(0.3), [qr]) qc.append(U1Gate(0.2), [qr]) dag = circuit_to_dag(qc) expected = QuantumCircuit(qr) expected.append(U1Gate(2 * theta + 1.5), [qr]) after = Optimize1qGates().run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_parameterized_expressions_in_circuits(self): """Expressions of Parameters should be treated as opaque gates.""" qr = QuantumRegister(1) qc = QuantumCircuit(qr) theta = Parameter("theta") phi = Parameter("phi") sum_ = theta + phi product_ = theta * phi qc.append(U1Gate(0.3), [qr]) qc.append(U1Gate(0.4), [qr]) qc.append(U1Gate(theta), [qr]) qc.append(U1Gate(phi), [qr]) qc.append(U1Gate(sum_), [qr]) qc.append(U1Gate(product_), [qr]) qc.append(U1Gate(0.3), [qr]) qc.append(U1Gate(0.2), [qr]) dag = circuit_to_dag(qc) expected = QuantumCircuit(qr) expected.append(U1Gate(2 * theta + 2 * phi + product_ + 1.2), [qr]) after = Optimize1qGates().run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_global_phase_u3_on_left(self): """Check proper phase accumulation with instruction with no definition.""" qr = QuantumRegister(1) qc = QuantumCircuit(qr) u1 = U1Gate(0.1) u1.definition.global_phase = np.pi / 2 qc.append(u1, [0]) qc.global_phase = np.pi / 3 qc.append(U3Gate(0.1, 0.2, 0.3), [0]) dag = circuit_to_dag(qc) after = Optimize1qGates().run(dag) self.assertAlmostEqual(after.global_phase, 5 * np.pi / 6, 8) def test_global_phase_u_on_left(self): """Check proper phase accumulation with instruction with no definition.""" qr = QuantumRegister(1) qc = QuantumCircuit(qr) u1 = U1Gate(0.1) u1.definition.global_phase = np.pi / 2 qc.append(u1, [0]) qc.global_phase = np.pi / 3 qc.append(UGate(0.1, 0.2, 0.3), [0]) dag = circuit_to_dag(qc) after = Optimize1qGates(["u1", "u2", "u", "cx"]).run(dag) self.assertAlmostEqual(after.global_phase, 5 * np.pi / 6, 8) class TestOptimize1qGatesParamReduction(QiskitTestCase): """Test for 1q gate optimizations parameter reduction, reduce n in Un""" def test_optimize_u3_to_u2(self): """U3(pi/2, pi/3, pi/4) -> U2(pi/3, pi/4)""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.append(U3Gate(np.pi / 2, np.pi / 3, np.pi / 4), [qr[0]]) expected = QuantumCircuit(qr) expected.append(U2Gate(np.pi / 3, np.pi / 4), [qr[0]]) passmanager = PassManager() passmanager.append(Optimize1qGates()) result = passmanager.run(circuit) self.assertEqual(expected, result) def test_optimize_u3_to_u2_round(self): """U3(1.5707963267948961, 1.0471975511965971, 0.7853981633974489) -> U2(pi/3, pi/4)""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.append(U3Gate(1.5707963267948961, 1.0471975511965971, 0.7853981633974489), [qr[0]]) expected = QuantumCircuit(qr) expected.append(U2Gate(np.pi / 3, np.pi / 4), [qr[0]]) passmanager = PassManager() passmanager.append(Optimize1qGates()) result = passmanager.run(circuit) self.assertEqual(expected, result) def test_optimize_u3_to_u1(self): """U3(0, 0, pi/4) -> U1(pi/4)""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.append(U3Gate(0, 0, np.pi / 4), [qr[0]]) expected = QuantumCircuit(qr) expected.append(U1Gate(np.pi / 4), [qr[0]]) passmanager = PassManager() passmanager.append(Optimize1qGates()) result = passmanager.run(circuit) self.assertEqual(expected, result) def test_optimize_u3_to_phase_gate(self): """U3(0, 0, pi/4) -> U1(pi/4)""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.append(U3Gate(0, 0, np.pi / 4), [qr[0]]) expected = QuantumCircuit(qr) expected.append(PhaseGate(np.pi / 4), [qr[0]]) passmanager = PassManager() passmanager.append(Optimize1qGates(["p", "u2", "u", "cx", "id"])) result = passmanager.run(circuit) self.assertEqual(expected, result) def test_optimize_u3_to_u1_round(self): """U3(1e-16, 1e-16, pi/4) -> U1(pi/4)""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.append(U3Gate(1e-16, 1e-16, np.pi / 4), [qr[0]]) expected = QuantumCircuit(qr) expected.append(U1Gate(np.pi / 4), [qr[0]]) passmanager = PassManager() passmanager.append(Optimize1qGates()) result = passmanager.run(circuit) self.assertEqual(expected, result) def test_optimize_u3_to_phase_round(self): """U3(1e-16, 1e-16, pi/4) -> U1(pi/4)""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.append(U3Gate(1e-16, 1e-16, np.pi / 4), [qr[0]]) expected = QuantumCircuit(qr) expected.append(PhaseGate(np.pi / 4), [qr[0]]) passmanager = PassManager() passmanager.append(Optimize1qGates(["p", "u2", "u", "cx", "id"])) result = passmanager.run(circuit) self.assertEqual(expected, result) class TestOptimize1qGatesBasis(QiskitTestCase): """Test for 1q gate optimizations parameter reduction with basis""" def test_optimize_u3_basis_u3(self): """U3(pi/2, pi/3, pi/4) (basis[u3]) -> U3(pi/2, pi/3, pi/4)""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.append(U3Gate(np.pi / 2, np.pi / 3, np.pi / 4), [qr[0]]) passmanager = PassManager() passmanager.append(Optimize1qGates(["u3"])) result = passmanager.run(circuit) self.assertEqual(circuit, result) def test_optimize_u3_basis_u(self): """U3(pi/2, pi/3, pi/4) (basis[u3]) -> U(pi/2, pi/3, pi/4)""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.append(U3Gate(np.pi / 2, np.pi / 3, np.pi / 4), [qr[0]]) passmanager = PassManager() passmanager.append(Optimize1qGates(["u"])) result = passmanager.run(circuit) expected = QuantumCircuit(qr) expected.append(UGate(np.pi / 2, np.pi / 3, np.pi / 4), [qr[0]]) self.assertEqual(expected, result) def test_optimize_u3_basis_u2(self): """U3(pi/2, 0, pi/4) -> U2(0, pi/4)""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.append(U3Gate(np.pi / 2, 0, np.pi / 4), [qr[0]]) expected = QuantumCircuit(qr) expected.append(U2Gate(0, np.pi / 4), [qr[0]]) passmanager = PassManager() passmanager.append(Optimize1qGates(["u2"])) result = passmanager.run(circuit) self.assertEqual(expected, result) def test_optimize_u3_basis_u2_with_target(self): """U3(pi/2, 0, pi/4) -> U2(0, pi/4)""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.append(U3Gate(np.pi / 2, 0, np.pi / 4), [qr[0]]) expected = QuantumCircuit(qr) expected.append(U2Gate(0, np.pi / 4), [qr[0]]) target = Target(num_qubits=1) target.add_instruction(U2Gate(Parameter("theta"), Parameter("phi"))) passmanager = PassManager() passmanager.append(Optimize1qGates(target=target)) result = passmanager.run(circuit) self.assertEqual(expected, result) def test_optimize_u_basis_u(self): """U(pi/2, pi/3, pi/4) (basis[u3]) -> U(pi/2, pi/3, pi/4)""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.append(UGate(np.pi / 2, np.pi / 3, np.pi / 4), [qr[0]]) passmanager = PassManager() passmanager.append(Optimize1qGates(["u"])) result = passmanager.run(circuit) self.assertEqual(circuit, result) def test_optimize_u3_basis_u2_cx(self): """U3(pi/2, 0, pi/4) -> U2(0, pi/4). Basis [u2, cx].""" qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.append(U3Gate(np.pi / 2, 0, np.pi / 4), [qr[0]]) circuit.cx(qr[0], qr[1]) expected = QuantumCircuit(qr) expected.append(U2Gate(0, np.pi / 4), [qr[0]]) expected.cx(qr[0], qr[1]) passmanager = PassManager() passmanager.append(Optimize1qGates(["u2", "cx"])) result = passmanager.run(circuit) self.assertEqual(expected, result) def test_optimize_u_basis_u2_cx(self): """U(pi/2, 0, pi/4) -> U2(0, pi/4). Basis [u2, cx].""" qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.append(UGate(np.pi / 2, 0, np.pi / 4), [qr[0]]) circuit.cx(qr[0], qr[1]) expected = QuantumCircuit(qr) expected.append(U2Gate(0, np.pi / 4), [qr[0]]) expected.cx(qr[0], qr[1]) passmanager = PassManager() passmanager.append(Optimize1qGates(["u2", "cx"])) result = passmanager.run(circuit) self.assertEqual(expected, result) def test_optimize_u1_basis_u2_u3(self): """U1(pi/4) -> U3(0, 0, pi/4). Basis [u2, u3].""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.append(U1Gate(np.pi / 4), [qr[0]]) expected = QuantumCircuit(qr) expected.append(U3Gate(0, 0, np.pi / 4), [qr[0]]) passmanager = PassManager() passmanager.append(Optimize1qGates(["u2", "u3"])) result = passmanager.run(circuit) self.assertEqual(expected, result) def test_optimize_u1_basis_u2_u(self): """U1(pi/4) -> U3(0, 0, pi/4). Basis [u2, u3].""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.append(U1Gate(np.pi / 4), [qr[0]]) expected = QuantumCircuit(qr) expected.append(UGate(0, 0, np.pi / 4), [qr[0]]) passmanager = PassManager() passmanager.append(Optimize1qGates(["u2", "u"])) result = passmanager.run(circuit) self.assertEqual(expected, result) def test_optimize_u1_basis_u2(self): """U1(pi/4) -> Raises. Basis [u2]""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.append(U1Gate(np.pi / 4), [qr[0]]) expected = QuantumCircuit(qr) expected.append(U3Gate(0, 0, np.pi / 4), [qr[0]]) passmanager = PassManager() passmanager.append(Optimize1qGates(["u2"])) with self.assertRaises(TranspilerError): _ = passmanager.run(circuit) def test_optimize_u3_basis_u2_u1(self): """U3(pi/2, 0, pi/4) -> U2(0, pi/4). Basis [u2, u1].""" qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.append(U3Gate(np.pi / 2, 0, np.pi / 4), [qr[0]]) expected = QuantumCircuit(qr) expected.append(U2Gate(0, np.pi / 4), [qr[0]]) passmanager = PassManager() passmanager.append(Optimize1qGates(["u2", "u1"])) result = passmanager.run(circuit) self.assertEqual(expected, result) def test_optimize_u3_basis_u2_phase_gate(self): """U3(pi/2, 0, pi/4) -> U2(0, pi/4). Basis [u2, p].""" qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.append(U3Gate(np.pi / 2, 0, np.pi / 4), [qr[0]]) expected = QuantumCircuit(qr) expected.append(U2Gate(0, np.pi / 4), [qr[0]]) passmanager = PassManager() passmanager.append(Optimize1qGates(["u2", "p"])) result = passmanager.run(circuit) self.assertEqual(expected, result) def test_optimize_u3_basis_u1(self): """U3(0, 0, pi/4) -> U1(pi/4). Basis [u1].""" qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.append(U3Gate(0, 0, np.pi / 4), [qr[0]]) expected = QuantumCircuit(qr) expected.append(U1Gate(np.pi / 4), [qr[0]]) passmanager = PassManager() passmanager.append(Optimize1qGates(["u1"])) result = passmanager.run(circuit) self.assertEqual(expected, result) def test_optimize_u3_basis_phase_gate(self): """U3(0, 0, pi/4) -> p(pi/4). Basis [p].""" qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.append(U3Gate(0, 0, np.pi / 4), [qr[0]]) expected = QuantumCircuit(qr) expected.append(PhaseGate(np.pi / 4), [qr[0]]) passmanager = PassManager() passmanager.append(Optimize1qGates(["p"])) result = passmanager.run(circuit) self.assertEqual(expected, result) def test_optimize_u_basis_u1(self): """U(0, 0, pi/4) -> U1(pi/4). Basis [u1].""" qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.append(UGate(0, 0, np.pi / 4), [qr[0]]) expected = QuantumCircuit(qr) expected.append(U1Gate(np.pi / 4), [qr[0]]) passmanager = PassManager() passmanager.append(Optimize1qGates(["u1"])) result = passmanager.run(circuit) self.assertEqual(expected, result) def test_optimize_u_basis_phase_gate(self): """U(0, 0, pi/4) -> p(pi/4). Basis [p].""" qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.append(UGate(0, 0, np.pi / 4), [qr[0]]) expected = QuantumCircuit(qr) expected.append(PhaseGate(np.pi / 4), [qr[0]]) passmanager = PassManager() passmanager.append(Optimize1qGates(["p"])) result = passmanager.run(circuit) self.assertEqual(expected, result) def test_optimize_u3_with_parameters(self): """Test correct behavior for u3 gates.""" phi = Parameter("φ") alpha = Parameter("α") qr = QuantumRegister(1, "qr") qc = QuantumCircuit(qr) qc.ry(2 * phi, qr[0]) qc.ry(alpha, qr[0]) qc.ry(0.1, qr[0]) qc.ry(0.2, qr[0]) passmanager = PassManager([Unroller(["u3"]), Optimize1qGates()]) result = passmanager.run(qc) expected = QuantumCircuit(qr) expected.append(U3Gate(2 * phi, 0, 0), [qr[0]]) expected.append(U3Gate(alpha, 0, 0), [qr[0]]) expected.append(U3Gate(0.3, 0, 0), [qr[0]]) self.assertEqual(expected, result) if __name__ == "__main__": unittest.main()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit import QuantumCircuit from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import LinearAmplitudeFunction from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # number of qubits to represent the uncertainty num_uncertainty_qubits = 3 # parameters for considered random distribution S = 2.0 # initial spot price vol = 0.4 # volatility of 40% r = 0.05 # annual interest rate of 4% T = 40 / 365 # 40 days to maturity # resulting parameters for log-normal distribution mu = (r - 0.5 * vol**2) * T + np.log(S) sigma = vol * np.sqrt(T) mean = np.exp(mu + sigma**2 / 2) variance = (np.exp(sigma**2) - 1) * np.exp(2 * mu + sigma**2) stddev = np.sqrt(variance) # lowest and highest value considered for the spot price; in between, an equidistant discretization is considered. low = np.maximum(0, mean - 3 * stddev) high = mean + 3 * stddev # construct A operator for QAE for the payoff function by # composing the uncertainty model and the objective uncertainty_model = LogNormalDistribution( num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, high) ) # plot probability distribution x = uncertainty_model.values y = uncertainty_model.probabilities plt.bar(x, y, width=0.2) plt.xticks(x, size=15, rotation=90) plt.yticks(size=15) plt.grid() plt.xlabel("Spot Price at Maturity $S_T$ (\$)", size=15) plt.ylabel("Probability ($\%$)", size=15) plt.show() # set the strike price (should be within the low and the high value of the uncertainty) strike_price = 1.896 # set the approximation scaling for the payoff function c_approx = 0.25 # setup piecewise linear objective fcuntion breakpoints = [low, strike_price] slopes = [0, 1] offsets = [0, 0] f_min = 0 f_max = high - strike_price european_call_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, rescaling_factor=c_approx, ) # construct A operator for QAE for the payoff function by # composing the uncertainty model and the objective num_qubits = european_call_objective.num_qubits european_call = QuantumCircuit(num_qubits) european_call.append(uncertainty_model, range(num_uncertainty_qubits)) european_call.append(european_call_objective, range(num_qubits)) # draw the circuit european_call.draw() # plot exact payoff function (evaluated on the grid of the uncertainty model) x = uncertainty_model.values y = np.maximum(0, x - strike_price) plt.plot(x, y, "ro-") plt.grid() plt.title("Payoff Function", size=15) plt.xlabel("Spot Price", size=15) plt.ylabel("Payoff", size=15) plt.xticks(x, size=15, rotation=90) plt.yticks(size=15) plt.show() # evaluate exact expected value (normalized to the [0, 1] interval) exact_value = np.dot(uncertainty_model.probabilities, y) exact_delta = sum(uncertainty_model.probabilities[x >= strike_price]) print("exact expected value:\t%.4f" % exact_value) print("exact delta value: \t%.4f" % exact_delta) european_call.draw() # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=european_call, objective_qubits=[3], post_processing=european_call_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value: \t%.4f" % (result.estimation_processed)) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) from qiskit_finance.applications.estimation import EuropeanCallPricing european_call_pricing = EuropeanCallPricing( num_state_qubits=num_uncertainty_qubits, strike_price=strike_price, rescaling_factor=c_approx, bounds=(low, high), uncertainty_model=uncertainty_model, ) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = european_call_pricing.to_estimation_problem() # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value: \t%.4f" % (european_call_pricing.interpret(result))) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) from qiskit_finance.applications.estimation import EuropeanCallDelta european_call_delta = EuropeanCallDelta( num_state_qubits=num_uncertainty_qubits, strike_price=strike_price, bounds=(low, high), uncertainty_model=uncertainty_model, ) european_call_delta._objective.decompose().draw() european_call_delta_circ = QuantumCircuit(european_call_delta._objective.num_qubits) european_call_delta_circ.append(uncertainty_model, range(num_uncertainty_qubits)) european_call_delta_circ.append( european_call_delta._objective, range(european_call_delta._objective.num_qubits) ) european_call_delta_circ.draw() # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = european_call_delta.to_estimation_problem() # construct amplitude estimation ae_delta = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_delta = ae_delta.estimate(problem) conf_int = np.array(result_delta.confidence_interval_processed) print("Exact delta: \t%.4f" % exact_delta) print("Esimated value: \t%.4f" % european_call_delta.interpret(result_delta)) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
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. """Test the CX Direction pass""" import unittest from math import pi from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit from qiskit.transpiler import TranspilerError from qiskit.transpiler import CouplingMap from qiskit.transpiler.passes import CXDirection from qiskit.converters import circuit_to_dag from qiskit.test import QiskitTestCase class TestCXDirection(QiskitTestCase): """ Tests the CXDirection pass.""" def test_no_cnots(self): """ Trivial map in a circuit without entanglement qr0:---[H]--- qr1:---[H]--- qr2:---[H]--- CouplingMap map: None """ qr = QuantumRegister(3, 'qr') circuit = QuantumCircuit(qr) circuit.h(qr) coupling = CouplingMap() dag = circuit_to_dag(circuit) pass_ = CXDirection(coupling) after = pass_.run(dag) self.assertEqual(dag, after) def test_direction_error(self): """ The mapping cannot be fixed by direction mapper qr0:--------- qr1:---(+)--- | qr2:----.---- CouplingMap map: [2] <- [0] -> [1] """ qr = QuantumRegister(3, 'qr') circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[2]) coupling = CouplingMap([[0, 1], [0, 2]]) dag = circuit_to_dag(circuit) pass_ = CXDirection(coupling) with self.assertRaises(TranspilerError): pass_.run(dag) def test_direction_correct(self): """ The CX is in the right direction qr0:---(+)--- | qr1:----.---- CouplingMap map: [0] -> [1] """ qr = QuantumRegister(2, 'qr') circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) coupling = CouplingMap([[0, 1]]) dag = circuit_to_dag(circuit) pass_ = CXDirection(coupling) after = pass_.run(dag) self.assertEqual(dag, after) def test_direction_flip(self): """ Flip a CX qr0:----.---- | qr1:---(+)--- CouplingMap map: [0] -> [1] qr0:-[H]-(+)-[H]-- | qr1:-[H]--.--[H]-- """ qr = QuantumRegister(2, 'qr') circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[0]) coupling = CouplingMap([[0, 1]]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr) expected.u2(0, pi, qr[0]) expected.u2(0, pi, qr[1]) expected.cx(qr[0], qr[1]) expected.u2(0, pi, qr[0]) expected.u2(0, pi, qr[1]) pass_ = CXDirection(coupling) after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_flip_with_measure(self): """ qr0: -(+)-[m]- | | qr1: --.---|-- | cr0: ------.-- CouplingMap map: [0] -> [1] qr0: -[H]--.--[H]-[m]- | | qr1: -[H]-(+)-[H]--|-- | cr0: --------------.-- """ qr = QuantumRegister(2, 'qr') cr = ClassicalRegister(1, 'cr') circuit = QuantumCircuit(qr, cr) circuit.cx(qr[1], qr[0]) circuit.measure(qr[0], cr[0]) coupling = CouplingMap([[0, 1]]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr, cr) expected.u2(0, pi, qr[0]) expected.u2(0, pi, qr[1]) expected.cx(qr[0], qr[1]) expected.u2(0, pi, qr[0]) expected.u2(0, pi, qr[1]) expected.measure(qr[0], cr[0]) pass_ = CXDirection(coupling) after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) if __name__ == '__main__': unittest.main()
https://github.com/xtophe388/QISKIT
xtophe388
from qiskit import ClassicalRegister, QuantumRegister from qiskit import QuantumCircuit, execute from qiskit import register #import Qconfig and set APIToken and API url 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.') register(qx_config['APItoken'], qx_config['url']) from battleships_engine import * title_screen() device = ask_for_device() from qiskit import get_backend backend = get_backend(device) shipPos = ask_for_ships() # the game variable will be set to False once the game is over game = True # the variable bombs[X][Y] will hold the number of times position Y has been bombed by player X+1 bomb = [ [0]*5 for _ in range(2)] # all values are initialized to zero # set the number of samples used for statistics shots = 1024 # the variable grid[player] will hold the results for the grid of each player grid = [{},{}] while (game): # ask both players where they want to bomb, and update the list of bombings so far bomb = ask_for_bombs( bomb ) # now we create and run the quantum programs that implement this on the grid for each player qc = [] for player in range(2): # now to set up the quantum program to simulate the grid for this player # set up registers and program q = QuantumRegister(5) c = ClassicalRegister(5) qc.append( QuantumCircuit(q, c) ) # add the bombs (of the opposing player) for position in range(5): # add as many bombs as have been placed at this position for n in range( bomb[(player+1)%2][position] ): # the effectiveness of the bomb # (which means the quantum operation we apply) # depends on which ship it is for ship in [0,1,2]: if ( position == shipPos[player][ship] ): frac = 1/(ship+1) # add this fraction of a NOT to the QASM qc[player].u3(frac * math.pi, 0.0, 0.0, q[position]) # Finally, measure them for position in range(5): qc[player].measure(q[position], c[position]) # compile and run the quantum program job = execute(qc, backend, shots=shots) if device=='ibmqx4': print("\nWe've now get submitted the job to the quantum computer to see what happens to the ships of each player\n(it might take a while).\n") else: print("\nWe've now get submitted the job to the simulator to see what happens to the ships of each player.\n") # and extract data for player in range(2): grid[player] = job.result().get_counts(qc[player]) game = display_grid ( grid, shipPos, shots )
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile, schedule from qiskit.visualization.pulse_v2 import draw, IQXDebugging from qiskit.providers.fake_provider import FakeBoeblingen qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc.measure_all() qc = transpile(qc, FakeBoeblingen(), layout_method='trivial') sched = schedule(qc, FakeBoeblingen()) draw(sched, style=IQXDebugging(), backend=FakeBoeblingen())
https://github.com/quantumjim/pewpew_qiskit_workshops
quantumjim
%matplotlib notebook # define a function that determines a brightness for any given point # uses a seed that is a list of four numbers def get_brightness(x,y): qc.data.clear() # empty the circuit # perform rotations, whose angles depend on x and y qc.rx((2*pi/360)*(seed[0]*x-seed[1]*y)*45,0) qc.h(0) qc.rx((2*pi/360)*(seed[2]*x+seed[3]*y**2)*45,0) # calculate probability for outcome 1 qc.measure(0,0) p = simulate(qc,shots=1000,get='counts')['1']/1000 # return brightness depending on this probability # the chosen values here are fairly arbitrarily if p>0.7: if p<0.8: return 1 elif p<0.9: return 2 else: return 3 else: return 0 from microqiskit import QuantumCircuit, simulate from math import pi from random import random seed = [random() for _ in range(4)] # initialize circuit used by the function qc = QuantumCircuit(1,1) for (x,y) in [(3,3),(3,4),(4,3),(4,4)]: print('Brightness at',(x,y),'is B =',get_brightness(x,y)) ########################################################### # Replace this comment with the `get_brightness` function # # if running anywhere other than this notebook # ########################################################### import pew from microqiskit import QuantumCircuit, simulate from math import pi from random import random pew.init() screen = pew.Pix() # initialize circuit qc = QuantumCircuit(1,1) # set a random seed, composed of four numbers seed = [random() for _ in range(4)] # loop over all points, and display the brightness for x in range(8): for y in range(8): B = get_brightness(x,y) screen.pixel(x,y,B) pew.show(screen) pew.tick(5) ########################################################### # Replace this comment with the `get_brightness` function # # if running anywhere other than this notebook # ########################################################### import pew from microqiskit import QuantumCircuit, simulate from math import * from random import random pew.init() screen = pew.Pix() # initialize circuit qc = QuantumCircuit(1,1) # set a random seed, composed of four numbers seed = [(2*(random()<0.5)-1)*(1+random())/2 for _ in range(4)] # coordinate of the current screen X,Y = 0,0 # loop to allow player to move half a screen while True: # arrow keys move to neighbouring screens keys = pew.keys() if keys!=0: if keys&pew.K_UP: Y -= 4 if keys&pew.K_DOWN: Y += 4 if keys&pew.K_LEFT: X -= 4 if keys&pew.K_RIGHT: X += 4 # loop over all points on the screen, and display the brightness for x in range(8): for y in range(8): B = get_brightness(x+X,y+Y) # coordinate of the player is accounted for also screen.pixel(x,y,B) pew.show(screen) pew.tick(1/6)
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/kosakhro/QAOA-for-exact-cover
kosakhro
from qiskit import * from qiskit.visualization import plot_bloch_multivector from qiskit.visualization import plot_histogram import numpy as np import matplotlib.pyplot as plt import seaborn as sns IBMQ.load_account() matplotlib inline my_provider = IBMQ.get_provider() my_provider.backends() simulator = my_provider.get_backend('ibmq_5_yorktown') # Making the quantum circuit def circuitI(gamma, beta, J, h1, h2): qc = QuantumCircuit(2, 2) qc.h([0, 1]) qc.h(1) qc.cz(0,1) qc.rx(2*gamma*J, 1) qc.cz(0,1) qc.h(1) qc.i(0) qc.rz(2*gamma*h1, 0) qc.rz(2*gamma*h2, 1) qc.rx(2*beta, 0) qc.rx(2*beta, 1) qc.measure([0,1], [0,1]) return qc # Initializing the variables for A. J = 0.5 h1 = -0.5 h2 = 0 #Setting the dimesions of the pasephase. The amount of simulated points = n**2 n = 61 p = np.pi/(n-1) res = np.zeros([n, n, 4]) # Running a simulation for each point for i in range(n): qc_list = [] gamma = i*p for j in range(n): beta = j*p qc = circuitI(gamma, beta, J, h1, h2) qc_list.append(qc) transpiled_circs = transpile(qc_list, backend=simulator) job = execute(transpiled_circs, backend = simulator, shots=1000 ) for circ_index in range(len(transpiled_circs)): counts = job.result().get_counts(qc_list[circ_index]) res[i][circ_index][:] = np.array([int(counts.get('00', 0)), int(counts.get('01', 0)), int(counts.get('10', 0)), int(counts.get('11', 0))]) print(res) #Draw the current circuit qc.draw(output='mpl') transpiled_circs[0].draw(output='mpl') # Making a heatmap plot sns.heatmap(res[:, :, 2])
https://github.com/a24l/IBM_Qiskit_QGSS
a24l
!pip install -U -r resources/requirements.txt from IPython.display import clear_output clear_output() from qiskit.quantum_info import Operator from qiskit import QuantumCircuit import numpy as np def phase_oracle(n, indices_to_mark, name = 'Oracle'): # create a quantum circuit on n qubits qc = QuantumCircuit(n, name=name) ### WRITE YOUR CODE BETWEEN THESE LINES - START # create the identity matrix for n qubits idenn = np.identity(2**n) # add the -1 phase to marked elements for i in indices_to_mark: idenn[i,i] = -1 ### WRITE YOUR CODE BETWEEN THESE LINES - END # convert your matrix (called oracle_matrix) into an operator, and add it to the quantum circuit qc.unitary(Operator(idenn), range(n)) return qc def diffuser(n): # create a quantum circuit on n qubits qc = QuantumCircuit(n, name='Diffuser') ### WRITE YOUR CODE BETWEEN THESE LINES - START # apply hadamard gates to all n qubits qc.h(range(n)) # take the phase oracle applied to the zero state qc.append(phase_oracle(n, [0]), range(n)) # apply hadamard gates to all n qubits again qc.h(range(n)) ### WRITE YOUR CODE BETWEEN THESE LINES - END return qc def Grover(n, indices_of_marked_elements): # Create a quantum circuit on n qubits qc = QuantumCircuit(n, n) # Determine r r = int(np.floor(np.pi/4*np.sqrt(2**n/len(indices_of_marked_elements)))) print(f'{n} qubits, basis states {indices_of_marked_elements} marked, {r} rounds') # step 1: apply Hadamard gates on all qubits qc.h(range(n)) # step 2: apply r rounds of the phase oracle and the diffuser for _ in range(r): qc.append(phase_oracle(n, indices_of_marked_elements), range(n)) qc.append(diffuser(n), range(n)) # step 3: measure all qubits qc.measure(range(n), range(n)) return qc mycircuit = Grover(6, [1, 42]) mycircuit.draw() from qiskit import Aer, execute simulator = Aer.get_backend('qasm_simulator') counts = execute(mycircuit, backend=simulator, shots=1000).result().get_counts(mycircuit) from qiskit.visualization import plot_histogram plot_histogram(counts)
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import Aer, QuantumCircuit from qiskit.circuit.library import PhaseEstimation qc= QuantumCircuit(3,3) # dummy unitary circuit unitary_circuit = QuantumCircuit(1) unitary_circuit.h(0) # QPE qc.append(PhaseEstimation(2, unitary_circuit), list(range(3))) qc.measure(list(range(3)), list(range(3))) backend = Aer.get_backend('qasm_simulator') result = backend.run(qc, shots = 8192).result()
https://github.com/MonitSharma/Learn-Quantum-Computing-with-Qiskit
MonitSharma
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit_aer import AerSimulator from qiskit import * from qiskit.visualization import plot_histogram, plot_bloch_vector from math import sqrt, pi qc = QuantumCircuit(1) # Create a quantum circuit with one qubit qc.draw('mpl') qc.initialize([1,0]) # Define initial_state as |0> qc.draw('mpl') initial_state = [0,1] # this is the |1> state qc.initialize(initial_state,0) # apply the initialisation on the qubit qc.draw('mpl') from qiskit.primitives import Sampler sampler = Sampler() # tell qiskit how to simulate the circuit backend = AerSimulator() # tell qiskit to use the AerSimulator backend.available_devices() backend.available_methods() qc.draw('mpl') from qiskit.quantum_info import Statevector # get the statevcector state = Statevector.from_instruction(qc) print(state) # lets plot the histogram qc.measure_all() # run the simulation result = sampler.run(qc).result() counts = result.quasi_dists[0] plot_histogram(counts) initial_state = [1/sqrt(2), 1j/sqrt(2)] # Define state |q_0> qc = QuantumCircuit(1) qc.initialize(initial_state,0) # apply the initialisation on the qubit qc.draw('mpl') # get the statevcector state = Statevector.from_instruction(qc) print(state) qc.measure_all() # run the simulation result = sampler.run(qc).result() counts = result.quasi_dists[0] plot_histogram(counts) vector = [1,1] qc.initialize(vector,0) qc = QuantumCircuit(1) # making a new quantum circuit initial_state = [0.+1.j/sqrt(2),1/sqrt(2)+0.j] qc.initialize(initial_state,0) qc.draw('mpl') qc = QuantumCircuit(1) initial_state = [0.+1.j/sqrt(2),1/sqrt(2)+0.j] qc.initialize(initial_state, 0) # get the statevcector state = Statevector.from_instruction(qc) print(state) qc.draw('mpl') from qiskit.visualization import plot_bloch_vector plot_bloch_vector([pi/2,0,1]) # let's plot |0> plot_bloch_vector([0,0,1]) # let's plot |0> plot_bloch_vector([1,0,0])
https://github.com/BoschSamuel/QizGloria
BoschSamuel
# -- 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. import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.autograd import Function import time from matplotlib import pyplot as plt %matplotlib inline from tqdm import tqdm import scipy from scipy import optimize from qiskit import QuantumRegister,QuantumCircuit,ClassicalRegister,execute from qiskit.circuit import Parameter from qiskit import Aer import numpy as np class L2L(nn.Module): ''' define Learning-2-Learn class with LSTM architecture ''' def __init__(self, circ_function, num_feats=1, batch_size=16): # circ_function should be a function which is a pennylane qnode super().__init__() self.num_feats = num_feats # rnn_output, qnn input params self.batch_size = batch_size # does pennylane support circuits that return multiple measurements? self.rnn_input_size = 1 # qnn output size self.function = circ_function # the target is required self.target = None self.hid_cell = None self.rnn_output = None self.qnn_output = None self.lstm = nn.LSTM( input_size=self.rnn_input_size, hidden_size=self.num_feats, num_layers=1, dropout=0 ) def init_hid_cell(self, seq_len=1): # concatenate and store all the output tensors here self.rnn_output = torch.tensor([]) self.qnn_output = torch.zeros(seq_len, self.batch_size, self.rnn_input_size) hidden = torch.zeros(seq_len, self.batch_size, self.num_feats) cell = torch.zeros(seq_len, self.batch_size, self.num_feats) self.hid_cell = (hidden, cell) def step(self): ckt = self.function.apply assert self.hid_cell is not None x = self.qnn_output[[-1], :, :] # print(f'RNN input {x.shape}') rnn_output, self.hid_cell = self.lstm(x, self.hid_cell) self.rnn_output = torch.cat((self.rnn_output, rnn_output), dim=0) # dims are : (seq_dim, batch_size, feature_size) # print(f'RNN output: {rnn_output.shape} RNN hist {self.rnn_output.shape}') assert rnn_output.shape[0] == 1 qnn_output = torch.zeros_like(x) # # qnode can't handle batching; iterate through the batch one at a time # for i in range(rnn_output.shape[1]): # qnn_input_batch_element = rnn_output[0, i, :].unsqueeze_(0) # qnn_output_batch_element = ckt(qnn_input_batch_element) # assert qnn_output_batch_element.nelement() == self.rnn_input_size # qnn_output[0, i, :] = qnn_output_batch_element #trying with batch qnn_input_element = rnn_output[0, :, :] qnn_output_element = ckt(qnn_input_element) # assert qnn_output_batch_element.nelement() == self.rnn_input_size qnn_output[0, :, :] = qnn_output_element # subtract target value so that loss is simply minimized at 0 qnn_output[0,:,:] = qnn_output[0,:,:] - self.target # print(f'circuit output: {qnn_output.shape}') self.qnn_output = torch.cat((self.qnn_output, qnn_output), dim=0) return self.qnn_output def loss(self, true=None): # compare the qnn output to the given target ('true') # print(f'true: {true.shape}, pred: {self.qnn_output.shape}') if true==None: true = torch.zeros(self.qnn_output.shape) assert true.shape == self.qnn_output.shape return F.mse_loss(self.qnn_output, true) def numpy_output(self): return self.qnn_output.detach().numpy().squeeze() def to_numbers(tensor_list): num_list = [] for tensor in tensor_list: num_list += [tensor.item()] return num_list class QiskitCircuit(): def __init__(self,shots): self.theta = Parameter('Theta') self.phi = Parameter('Phi') self.shots = shots def create_circuit(): qr = QuantumRegister(1,'q') cr = ClassicalRegister(1,'c') ckt = QuantumCircuit(qr,cr) ckt.h(qr[0]) ckt.barrier() ckt.ry(self.theta,qr[0]) ckt.barrier() ckt.measure(qr,cr) return ckt self.circuit = create_circuit() def N_qubit_expectation_Z(self, counts, shots, nr_qubits): expects = np.zeros(nr_qubits) for key in counts.keys(): perc = counts[key]/shots check = np.array([(float(key[i])-1/2)*2*perc for i in range(nr_qubits)]) expects += check return expects def bind(self, parameters): [self.theta] = to_numbers(parameters) self.circuit.data[2][0]._params = to_numbers(parameters) def run(self, i): self.bind(i) backend = Aer.get_backend('qasm_simulator') job_sim = execute(self.circuit,backend,shots=self.shots) result_sim = job_sim.result() counts = result_sim.get_counts(self.circuit) return self.N_qubit_expectation_Z(counts,self.shots,1) class TorchCircuit(Function): @staticmethod def forward(ctx, i): if not hasattr(ctx, 'QiskitCirc'): ctx.QiskitCirc = QiskitCircuit(shots=100) exp_value = [] for j in range(len(i)): exp_value.append(ctx.QiskitCirc.run(i[j])) result = torch.tensor(exp_value) # print(result) ctx.save_for_backward(result, i) return result @staticmethod def backward(ctx, grad_output): eps = np.pi/2 forward_tensor, i = ctx.saved_tensors gradient = [] for j in range(len(i)): input_numbers = to_numbers(i[j]) for k in range(len(input_numbers)): input_eps_plus = input_numbers input_eps_plus[k] = input_numbers[k] + eps exp_value_plus = ctx.QiskitCirc.run(torch.tensor(input_eps_plus))[0] result_eps_plus = torch.tensor([exp_value_plus]) input_eps_minus = input_numbers input_eps_minus[k] = input_numbers[k] - eps exp_value_minus = ctx.QiskitCirc.run(torch.tensor(input_eps_minus))[0] result_eps_minus = torch.tensor([exp_value_minus]) gradient_result = 0.5 * (result_eps_plus - result_eps_minus) gradient.append(gradient_result) # print(gradient) result = torch.tensor(gradient) # print(result) return result.float() * grad_output.float() class L2LRot(L2L): def init_target(self): # pick a random number between 0 and 1 as the target expectation value self.target = (torch.rand(self.batch_size, self.rnn_input_size) - 0.5) * 2 # def circ_function(dev): # @qml.qnode(dev, interface='torch') # def circuit(parameters): # assert len(parameters) == 3 # phi = 2 * np.pi * parameters[:2] # theta = 2 * np.pi * parameters[-1] # qml.RX(phi[0], wires=0) # qml.RZ(phi[1], wires=1) # qml.CNOT(wires=[0, 1]) # qml.RX(theta, wires=0) # return qml.expval(qml.PauliZ(0)) # return circuit circ_function = TorchCircuit %%time torch.autograd.set_detect_anomaly(True) l2l = L2LRot(circ_function, num_feats=1, batch_size=1) optimizer = optim.Adam(l2l.parameters(), lr=0.1) num_epoch = 100 num_steps = 10 #25 all_loss = [] for epoch_ind in tqdm(range(num_epoch)): l2l.zero_grad() l2l.init_hid_cell() l2l.init_target() for i in range(num_steps): # print(i) l2l.step() loss = l2l.loss() loss.backward() optimizer.step() all_loss.append(loss.item()) plt.plot(all_loss)
https://github.com/Qiskit/qiskit-neko
Qiskit
# This code is part of Qiskit. # # (C) Copyright IBM 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test backend on execute().""" import math from qiskit.circuit import QuantumCircuit from qiskit import transpile from qiskit_neko import decorators from qiskit_neko.tests import base class TestExecute(base.BaseTestCase): """Test the use of the execute() method in qiskit-terra.""" def setUp(self): super().setUp() if not hasattr(self.backend.options, "shots"): raise self.skipException( "Provided backend {self.backend} does not have a configurable shots option" ) if hasattr(self.backend.options, "seed_simulator"): self.backend.set_options(seed_simulator=42) @decorators.component_attr("terra", "backend") def test_bell_execute_fixed_shots(self): """Test the execution of a bell circuit with an explicit shot count.""" circuit = QuantumCircuit(2) circuit.h(0) circuit.cx(0, 1) circuit.measure_all() job = self.backend.run(transpile(circuit, self.backend), shots=100) result = job.result() counts = result.get_counts() self.assertDictAlmostEqual(counts, {"00": 50, "11": 50}, delta=10) @decorators.component_attr("terra", "backend") def test_bell_execute_default_shots(self): """Test the execution of a bell circuit with an explicit shot count.""" circuit = QuantumCircuit(2) circuit.h(0) circuit.cx(0, 1) circuit.measure_all() expected_count = self.backend.options.shots / 2 job = self.backend.run(transpile(circuit, self.backend)) result = job.result() counts = result.get_counts() delta = 10 ** (math.log10(self.backend.options.shots) - 1) self.assertDictAlmostEqual( counts, {"00": expected_count, "11": expected_count}, delta=delta ) @decorators.component_attr("terra", "backend") def test_bell_execute_backend_shots_set_options(self): """Test the execution of a bell circuit with an explicit shot count set via options.""" circuit = QuantumCircuit(2) circuit.h(0) circuit.cx(0, 1) circuit.measure_all() self.backend.set_options(shots=100) job = self.backend.run(transpile(circuit, self.backend)) result = job.result() counts = result.get_counts() self.assertDictAlmostEqual(counts, {"00": 50, "11": 50}, delta=10)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.units import DistanceUnit from qiskit_nature.second_q.drivers import PySCFDriver from qiskit_nature.second_q.mappers import ParityMapper from qiskit_nature.second_q.properties import ParticleNumber from qiskit_nature.second_q.transformers import ActiveSpaceTransformer bond_distance = 2.5 # in Angstrom # specify driver driver = PySCFDriver( atom=f"Li 0 0 0; H 0 0 {bond_distance}", basis="sto3g", charge=0, spin=0, unit=DistanceUnit.ANGSTROM, ) problem = driver.run() # specify active space transformation active_space_trafo = ActiveSpaceTransformer( num_electrons=problem.num_particles, num_spatial_orbitals=3 ) # transform the electronic structure problem problem = active_space_trafo.transform(problem) # construct the parity mapper with 2-qubit reduction qubit_mapper = ParityMapper(num_particles=problem.num_particles) from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver from qiskit_nature.second_q.algorithms.ground_state_solvers import GroundStateEigensolver np_solver = NumPyMinimumEigensolver() np_groundstate_solver = GroundStateEigensolver(qubit_mapper, np_solver) np_result = np_groundstate_solver.solve(problem) target_energy = np_result.total_energies[0] print(np_result) from qiskit.circuit.library import EfficientSU2 ansatz = EfficientSU2(num_qubits=4, reps=1, entanglement="linear", insert_barriers=True) ansatz.decompose().draw("mpl", style="iqx") import numpy as np from qiskit.utils import algorithm_globals # fix random seeds for reproducibility np.random.seed(5) algorithm_globals.random_seed = 5 from qiskit.algorithms.optimizers import SPSA optimizer = SPSA(maxiter=100) initial_point = np.random.random(ansatz.num_parameters) from qiskit.algorithms.minimum_eigensolvers import VQE from qiskit.primitives import Estimator estimator = Estimator() local_vqe = VQE( estimator, ansatz, optimizer, initial_point=initial_point, ) local_vqe_groundstate_solver = GroundStateEigensolver(qubit_mapper, local_vqe) local_vqe_result = local_vqe_groundstate_solver.solve(problem) print(local_vqe_result) from qiskit import IBMQ IBMQ.load_account() provider = IBMQ.get_provider(group="open") # replace by your runtime provider backend = provider.get_backend("ibmq_qasm_simulator") # select a backend that supports the runtime from qiskit_nature.runtime import VQEClient runtime_vqe = VQEClient( ansatz=ansatz, optimizer=optimizer, initial_point=initial_point, provider=provider, backend=backend, shots=1024, measurement_error_mitigation=True, ) # use a complete measurement fitter for error mitigation runtime_vqe_groundstate_solver = GroundStateEigensolver(qubit_mapper, runtime_vqe) runtime_vqe_result = runtime_vqe_groundstate_solver.solve(problem) print(runtime_vqe_result) runtime_result = runtime_vqe_result.raw_result history = runtime_result.optimizer_history loss = history["energy"] import matplotlib.pyplot as plt plt.rcParams["font.size"] = 14 # plot loss and reference value plt.figure(figsize=(12, 6)) plt.plot(loss + runtime_vqe_result.nuclear_repulsion_energy, label="Runtime VQE") plt.axhline(y=target_energy + 0.2, color="tab:red", ls=":", label="Target + 200mH") plt.axhline(y=target_energy, color="tab:red", ls="--", label="Target") plt.legend(loc="best") plt.xlabel("Iteration") plt.ylabel("Energy [H]") plt.title("VQE energy"); import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/DaisukeIto-ynu/KosakaQ
DaisukeIto-ynu
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Remove all barriers in a circuit""" from qiskit.dagcircuit import DAGCircuit from qiskit.transpiler.basepasses import TransformationPass from qiskit.transpiler.passes.utils import control_flow class RemoveBarriers(TransformationPass): """Return a circuit with any barrier removed. This transformation is not semantics preserving. Example: .. plot:: :include-source: 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') """ @control_flow.trivial_recurse def run(self, dag: DAGCircuit) -> DAGCircuit: """Run the RemoveBarriers pass on `dag`.""" dag.remove_all_ops_named("barrier") return dag
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile, schedule from qiskit.visualization.pulse_v2 import draw, IQXSimple from qiskit.providers.fake_provider import FakeBoeblingen qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc.measure_all() qc = transpile(qc, FakeBoeblingen(), layout_method='trivial') sched = schedule(qc, FakeBoeblingen()) draw(sched, style=IQXSimple(), backend=FakeBoeblingen())
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.providers.fake_provider import FakeManilaV2 from qiskit import transpile from qiskit.tools.visualization import plot_histogram # Get a fake backend from the fake provider backend = FakeManilaV2() # Create a simple circuit circuit = QuantumCircuit(3) circuit.h(0) circuit.cx(0,1) circuit.cx(0,2) circuit.measure_all() circuit.draw('mpl') # Transpile the ideal circuit to a circuit that can be directly executed by the backend transpiled_circuit = transpile(circuit, backend) transpiled_circuit.draw('mpl') # Run the transpiled circuit using the simulated fake backend job = backend.run(transpiled_circuit) counts = job.result().get_counts() plot_histogram(counts)
https://github.com/DRA-chaos/Quantum-Classical-Hyrid-Neural-Network-for-binary-image-classification-using-PyTorch-Qiskit-pipeline
DRA-chaos
!pip install qiskit import numpy as np import torch from torch.autograd import Function import torch.optim as optim import torch.nn as nn import torch.nn.functional as F import torchvision from torchvision import datasets, transforms from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister, execute from qiskit.circuit import Parameter from qiskit import Aer from tqdm import tqdm from matplotlib import pyplot as plt %matplotlib inline def to_numbers(tensor_list): num_list = [] for tensor in tensor_list: num_list += [tensor.item()] return num_list class QuantumCircuit: """ This class provides a simple interface for interaction with the quantum circuit """ def __init__(self, n_qubits, backend, shots): # --- Circuit definition --- self._circuit = qiskit.QuantumCircuit(n_qubits) all_qubits = [i for i in range(n_qubits)] self.theta = qiskit.circuit.Parameter('theta') self._circuit.h(all_qubits) self._circuit.barrier() self._circuit.ry(self.theta, all_qubits) self._circuit.measure_all() # --------------------------- self.backend = backend self.shots = shots def run(self, thetas): t_qc = transpile(self._circuit, self.backend) qobj = assemble(t_qc, shots=self.shots, parameter_binds = [{self.theta: theta} for theta in thetas]) job = self.backend.run(qobj) result = job.result().get_counts() counts = np.array(list(result.values())) states = np.array(list(result.keys())).astype(float) # Compute probabilities for each state probabilities = counts / self.shots # Get state expectation expectation = np.sum(states * probabilities) return np.array([expectation]) class HybridFunction(Function): """ Hybrid quantum - classical function definition """ @staticmethod def forward(ctx, input, quantum_circuit, shift): """ Forward pass computation """ ctx.shift = shift ctx.quantum_circuit = quantum_circuit expectation_z = ctx.quantum_circuit.run(input[0].tolist()) result = torch.tensor([expectation_z]) ctx.save_for_backward(input, result) return result @staticmethod def backward(ctx, grad_output): """ Backward pass computation """ input, expectation_z = ctx.saved_tensors input_list = np.array(input.tolist()) shift_right = input_list + np.ones(input_list.shape) * ctx.shift shift_left = input_list - np.ones(input_list.shape) * ctx.shift gradients = [] for i in range(len(input_list)): expectation_right = ctx.quantum_circuit.run(shift_right[i]) expectation_left = ctx.quantum_circuit.run(shift_left[i]) gradient = torch.tensor([expectation_right]) - torch.tensor([expectation_left]) gradients.append(gradient) gradients = np.array([gradients]).T return torch.tensor([gradients]).float() * grad_output.float(), None, None class Hybrid(nn.Module): """ Hybrid quantum - classical layer definition """ def __init__(self, backend, shots, shift): super(Hybrid, self).__init__() self.quantum_circuit = QuantumCircuit(1, backend, shots) self.shift = shift def forward(self, input): return HybridFunction.apply(input, self.quantum_circuit, self.shift) import torchvision transform = torchvision.transforms.Compose([torchvision.transforms.ToTensor()]) # transform images to tensors/vectors cifar_trainset = datasets.CIFAR10(root='./data1', train=True, download=True, transform=transform) len(cifar_trainset) from torch.utils.data import DataLoader, random_split cifar_trainset = datasets.CIFAR10(root='./data1', train=True, download=True, transform=transform) labels = cifar_trainset.targets # get the labels for the data labels = np.array(labels) idx1 = np.where(labels == 0) # filter on aeroplanes idx2 = np.where(labels == 1) # filter on automobiles # Specify number of datapoints per class (i.e. there will be n pictures of automobiles and n pictures of aeroplanes in the training set) n=100 # concatenate the data indices idx = np.concatenate((idx1[0][0:n],idx2[0][0:n])) # create the filtered dataset for our training set cifar_trainset.targets = labels[idx] cifar_trainset.data = cifar_trainset.data[idx] cifar_trainset, valid = random_split(cifar_trainset,[150,50]) train_loader = torch.utils.data.DataLoader(cifar_trainset, batch_size=1, shuffle=True) valid_loader = torch.utils.data.DataLoader(valid, batch_size=1) @torch.no_grad() def get_all_preds(model, train_loader): all_preds = torch.tensor([]) for batch in train_loader: images, labels = batch preds = model(images) all_preds = torch.cat( (all_preds, preds) ,dim=0 ) return all_preds import numpy as np import matplotlib.pyplot as plt n_samples_show = 6 data_iter = iter(train_loader) fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 2)) while n_samples_show > 0: images, targets = data_iter.__next__() images=images.squeeze() axes[n_samples_show - 1].imshow(images[0].numpy(), cmap='gray') axes[n_samples_show - 1].set_xticks([]) axes[n_samples_show - 1].set_yticks([]) axes[n_samples_show - 1].set_title("Labeled: {}".format(targets.item())) n_samples_show -= 1 import torchvision transform = torchvision.transforms.Compose([torchvision.transforms.ToTensor()]) # transform images to tensors/vectors cifar_testset = datasets.CIFAR10(root='./data1', train=False, download=True, transform=transform) labels = cifar_testset.targets # get the labels for the data labels = np.array(labels) idx1 = np.where(labels == 0) # filter on aeroplanes idx2 = np.where(labels == 1) # filter on automobiles # Specify number of datapoints per class (i.e. there will be n pictures of automobiles and n pictures of aeroplanes in the training set) n=100 # concatenate the data indices idx = np.concatenate((idx1[0][0:n],idx2[0][0:n])) # create the filtered dataset for our training set cifar_testset.targets = labels[idx] cifar_testset.data = cifar_testset.data[idx] test_loader = torch.utils.data.DataLoader(cifar_testset, batch_size=1, shuffle=False) class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 10, kernel_size=5) self.conv2 = nn.Conv2d(10, 20, kernel_size=5) self.dropout = nn.Dropout2d() self.fc1 = nn.Linear(500, 500) self.fc2 = nn.Linear(500, 1) self.hybrid = Hybrid(qiskit.Aer.get_backend('qasm_simulator'), 100, np.pi / 2) def forward(self, x): x = F.relu(self.conv1(x)) x = F.max_pool2d(x, 2) x = F.relu(self.conv2(x)) x = F.max_pool2d(x, 2) x = self.dropout(x) x = x.view(1, -1) x = F.relu(self.fc1(x)) x = self.fc2(x) x = self.hybrid(x) return torch.cat((x, 1 - x), -1) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.001) loss_func = nn.NLLLoss() epochs = 5 loss_list = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_list.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Now plotting the training graph plt.plot(loss_list) plt.title('Hybrid NN Training Convergence') plt.xlabel('Training Iterations') plt.ylabel('Neg Log Likelihood Loss') model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.001) loss_func = nn.NLLLoss() epochs = 5 loss_list_V = [] model.train() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) #Now plotting the training graph plt.plot(loss_list_V) plt.title('Hybrid NN Training Convergence') plt.xlabel('Training Iterations') plt.ylabel('Neg Log Likelihood Validation Loss') model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(valid_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() validation_loss = loss_func(output, target) valid_loss.append(validation_loss.item()) print('Performance on test data:\n\tValidation Loss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(valid_loss) / len(valid_loss), correct / len(valid_loader) * 100) )
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import transpile 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_basis = transpile(qc, backend) qc_basis.draw(output='mpl')
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
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.') # useful additional packages import matplotlib.pyplot as plt %matplotlib inline import numpy as np from pprint import pprint # importing QISKit from qiskit import QuantumProgram, QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import available_backends, execute, register, least_busy # import basic plot tools from qiskit.tools.visualization import plot_histogram, circuit_drawer backend = 'local_qasm_simulator' # run on local simulator by default # Uncomment the following lines to run on a real device # register(qx_config['APItoken'], qx_config['url']) # backend = least_busy(available_backends({'simulator': False, 'local': False})) # print("the best backend is " + backend) # Creating registers tq = QuantumRegister(3) tc0 = ClassicalRegister(1) tc1 = ClassicalRegister(1) tc2 = ClassicalRegister(1) # Quantum circuit to make the shared entangled state teleport = QuantumCircuit(tq, tc0,tc1,tc2) teleport.h(tq[1]) teleport.cx(tq[1], tq[2]) teleport.ry(np.pi/4,tq[0]) teleport.cx(tq[0], tq[1]) teleport.h(tq[0]) teleport.barrier() teleport.measure(tq[0], tc0[0]) teleport.measure(tq[1], tc1[0]) teleport.z(tq[2]).c_if(tc0, 1) teleport.x(tq[2]).c_if(tc1, 1) teleport.measure(tq[2], tc2[0]) circuit_drawer(teleport) teleport_job = execute(teleport, 'local_qasm_simulator') # note that this circuit doesn't run on a real device teleport_result = teleport_job.result() data = teleport_result.get_counts(teleport) alice = {} alice['00'] = data['0 0 0'] + data['1 0 0'] alice['10'] = data['0 1 0'] + data['1 1 0'] alice['01'] = data['0 0 1'] + data['1 0 1'] alice['11'] = data['0 1 1'] + data['1 1 1'] plot_histogram(alice) bob = {} bob['0'] = data['0 0 0'] + data['0 1 0'] + data['0 0 1'] + data['0 1 1'] bob['1'] = data['1 0 0'] + data['1 1 0'] + data['1 0 1'] + data['1 1 1'] plot_histogram(bob) # Creating registers sdq = QuantumRegister(2) sdc = ClassicalRegister(2) # Quantum circuit to make the shared entangled state superdense = QuantumCircuit(sdq, sdc) superdense.h(sdq[0]) superdense.cx(sdq[0], sdq[1]) # For 00, do nothing # For 01, apply $X$ #shared.x(q[0]) # For 01, apply $Z$ #shared.z(q[0]) # For 11, apply $XZ$ superdense.z(sdq[0]) superdense.x(sdq[0]) superdense.barrier() superdense.cx(sdq[0], sdq[1]) superdense.h(sdq[0]) superdense.measure(sdq[0], sdc[0]) superdense.measure(sdq[1], sdc[1]) circuit_drawer(superdense) superdense_job = execute(superdense, backend) superdense_result = superdense_job.result() plot_histogram(superdense_result.get_counts(superdense))
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import Aer, QuantumCircuit from qiskit.circuit.library import PhaseEstimation qc= QuantumCircuit(3,3) # dummy unitary circuit unitary_circuit = QuantumCircuit(1) unitary_circuit.h(0) # QPE qc.append(PhaseEstimation(2, unitary_circuit), list(range(3))) qc.measure(list(range(3)), list(range(3))) backend = Aer.get_backend('qasm_simulator') result = backend.run(qc, shots = 8192).result()
https://github.com/BOBO1997/osp_solutions
BOBO1997
# Import general libraries (needed for functions) import numpy as np import time # Import Qiskit classes import qiskit from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister, Aer from qiskit.providers.aer import noise from qiskit.tools.visualization import plot_histogram # Import measurement calibration functions from qiskit.ignis.mitigation.measurement import (complete_meas_cal, tensored_meas_cal, CompleteMeasFitter, TensoredMeasFitter) # Generate the calibration circuits qr = qiskit.QuantumRegister(3) qubit_list = [0,1,2] meas_calibs, state_labels = complete_meas_cal(qubit_list=qubit_list, qr=qr, circlabel='mcal') state_labels # Execute the calibration circuits without noise backend = qiskit.Aer.get_backend('qasm_simulator') job = qiskit.execute(meas_calibs, backend=backend, shots=1000) cal_results = job.result() # The calibration matrix without noise is the identity matrix meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') print(meas_fitter.cal_matrix) # Generate a noise model for the 5 qubits noise_model = noise.NoiseModel() for qi in range(1): read_err = noise.errors.readout_error.ReadoutError([[0.9, 0.1],[0.25,0.75]]) noise_model.add_readout_error(read_err, [qi]) # Execute the calibration circuits backend = qiskit.Aer.get_backend('qasm_simulator') job = qiskit.execute(meas_calibs, backend=backend, shots=1000, noise_model=noise_model) cal_results = job.result() # Calculate the calibration matrix with the noise model meas_fitter = CompleteMeasFitter(cal_results, state_labels, qubit_list=qubit_list, circlabel='mcal') print(meas_fitter.cal_matrix) # Plot the calibration matrix meas_fitter.plot_calibration() # What is the measurement fidelity? print("Average Measurement Fidelity: %f" % meas_fitter.readout_fidelity()) # What is the measurement fidelity of Q0? print("Average Measurement Fidelity of Q0: %f" % meas_fitter.readout_fidelity( label_list = [['000','001','010','011'],['100','101','110','111']])) # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.quantum_info import state_fidelity from qiskit.opflow import Zero, One, I, X, Y, Z # Make a 3Q GHZ state cr = ClassicalRegister(3) qc = QuantumCircuit(qr) qc.x([0,1]) # ghz.h(qr[0]) # ghz.cx(qr[0], qr[1]) # ghz.cx(qr[1], qr[2]) # ghz.measure(qr[0],cr[0]) # ghz.measure(qr[1],cr[1]) # ghz.measure(qr[2],cr[2]) st_qcs = state_tomography_circuits(qc, [0,1,2]) st_qcs[-1].draw("mpl") job = qiskit.execute(st_qcs, backend=backend, shots=5000, noise_model=noise_model) results = job.result() # Results without mitigation raw_counts = results.get_counts() # Get the filter object meas_filter = meas_fitter.filter # Results with mitigation mitigated_results = meas_filter.apply(results) mitigated_counts = mitigated_results.get_counts() from qiskit.tools.visualization import * plot_histogram([raw_counts[-1], mitigated_counts[-1]], legend=['raw', 'mitigated']) def state_tomo(result, st_qcs): # The expected final state; necessary to determine state tomography fidelity target_state = (One^One^Zero).to_matrix() # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) # Fit state tomography results tomo_fitter = StateTomographyFitter(result, st_qcs) rho_fit = tomo_fitter.fit(method='lstsq') # Compute fidelity fid = state_fidelity(rho_fit, target_state) return fid state_tomo(mitigated_results, st_qcs) # Make a 3Q GHZ state cr = ClassicalRegister(3) qc = QuantumCircuit(qr) qc.x([0,1]) # ghz.h(qr[0]) # ghz.cx(qr[0], qr[1]) # ghz.cx(qr[1], qr[2]) # ghz.measure(qr[0],cr[0]) # ghz.measure(qr[1],cr[1]) # ghz.measure(qr[2],cr[2]) st_qcs = state_tomography_circuits(qc, [0,1,2][::-1]) job = qiskit.execute(st_qcs, backend=backend, shots=5000, noise_model=noise_model) results = job.result() # Results without mitigation raw_counts = results.get_counts() # Get the filter object meas_filter = meas_fitter.filter # Results with mitigation mitigated_results = meas_filter.apply(results) mitigated_counts = mitigated_results.get_counts() from qiskit.tools.visualization import * plot_histogram([raw_counts[-1], mitigated_counts[-1]], legend=['raw', 'mitigated']) state_tomo(mitigated_results, st_qcs) state_tomo(results, st_qcs)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit qc = QuantumCircuit(1, 1) qc.h(0) qc.measure(0,0) qc.x(0).c_if(0, 0) qc.draw(output='mpl') from qiskit import QuantumRegister, ClassicalRegister q = QuantumRegister(3, 'q') c = ClassicalRegister(3, 'c') qc = QuantumCircuit(q, c) qc.h([0, 1, 2]) qc.barrier() qc.measure(q, c) qc.draw('mpl') print(bin(3)) print(bin(7)) qc.x(2).c_if(c, 3) # for the 011 case qc.x(2).c_if(c, 7) # for the 111 case qc.draw(output='mpl') nq = 2 m = 2 q = QuantumRegister(nq, 'q') c = ClassicalRegister(m, 'c') qc_S = QuantumCircuit(q,c) qc_S.h(0) qc_S.x(1) qc_S.draw('mpl') from math import pi cu_circ = QuantumCircuit(2) cu_circ.cp(pi/2, 0, 1) cu_circ.draw('mpl') for _ in range(2 ** (m - 1)): qc_S.cp(pi/2, 0, 1) qc_S.draw('mpl') def x_measurement(qc, qubit, cbit): """Measure 'qubit' in the X-basis, and store the result in 'cbit'""" qc.h(qubit) qc.measure(qubit, cbit) x_measurement(qc_S, q[0], c[0]) qc_S.draw('mpl') qc_S.reset(0) qc_S.h(0) qc_S.draw('mpl') qc_S.p(-pi/2, 0).c_if(c, 1) qc_S.draw('mpl') ## 2^t c-U operations (with t=m-2) for _ in range(2 ** (m - 2)): qc_S.cp(pi/2, 0, 1) x_measurement(qc_S, q[0], c[1]) qc_S.draw('mpl') import matplotlib.pyplot as plt from qiskit.tools.visualization import plot_histogram from qiskit_aer.primitives import Sampler sampler = Sampler() job = sampler.run(qc_S) result = job.result() dist0 = result.quasi_dists[0] key_new = [str(key/2**m) for key in list(dist0.keys())] dist1 = dict(zip(key_new, dist0.values())) fig, ax = plt.subplots(1,2) plot_histogram(dist0, ax=ax[0]) plot_histogram(dist1, ax=ax[1]) plt.tight_layout() nq = 3 # number of qubits m = 3 # number of classical bits q = QuantumRegister(nq,'q') c = ClassicalRegister(m,'c') qc = QuantumCircuit(q,c) qc.h(0) qc.x([1, 2]) qc.draw('mpl') cu_circ = QuantumCircuit(nq) cu_circ.mcp(pi/4, [0, 1], 2) cu_circ.draw('mpl') for _ in range(2 ** (m - 1)): qc.mcp(pi/4, [0, 1], 2) qc.draw('mpl') x_measurement(qc, q[0], c[0]) qc.draw('mpl') qc.reset(0) qc.h(0) qc.draw('mpl') qc.p(-pi/2, 0).c_if(c, 1) qc.draw('mpl') for _ in range(2 ** (m - 2)): qc.mcp(pi/4, [0, 1], 2) x_measurement(qc, q[0], c[1]) qc.draw('mpl') # initialization of qubit q0 qc.reset(0) qc.h(0) # phase correction qc.p(-pi/4, 0).c_if(c, 1) qc.p(-pi/2, 0).c_if(c, 2) qc.p(-3*pi/2, 0).c_if(c, 3) # c-U operations for _ in range(2 ** (m - 3)): qc.mcp(pi/4, [0, 1], 2) # X measurement qc.h(0) qc.measure(0, 2) qc.draw('mpl') result = sampler.run(qc).result() dist0 = result.quasi_dists[0] key_new = [str(key/2**m) for key in list(dist0.keys())] dist1 = dict(zip(key_new, dist0.values())) fig, ax = plt.subplots(1,2) plot_histogram(dist0, ax=ax[0]) plot_histogram(dist1, ax=ax[1]) plt.tight_layout() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import json import time import warnings import matplotlib.pyplot as plt import numpy as np from IPython.display import clear_output from qiskit import ClassicalRegister, QuantumRegister from qiskit import QuantumCircuit from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import RealAmplitudes from qiskit.quantum_info import Statevector from qiskit.utils import algorithm_globals from qiskit_machine_learning.circuit.library import RawFeatureVector from qiskit_machine_learning.neural_networks import SamplerQNN algorithm_globals.random_seed = 42 def ansatz(num_qubits): return RealAmplitudes(num_qubits, reps=5) num_qubits = 5 circ = ansatz(num_qubits) circ.decompose().draw("mpl") def auto_encoder_circuit(num_latent, num_trash): qr = QuantumRegister(num_latent + 2 * num_trash + 1, "q") cr = ClassicalRegister(1, "c") circuit = QuantumCircuit(qr, cr) circuit.compose(ansatz(num_latent + num_trash), range(0, num_latent + num_trash), inplace=True) circuit.barrier() auxiliary_qubit = num_latent + 2 * num_trash # swap test circuit.h(auxiliary_qubit) for i in range(num_trash): circuit.cswap(auxiliary_qubit, num_latent + i, num_latent + num_trash + i) circuit.h(auxiliary_qubit) circuit.measure(auxiliary_qubit, cr[0]) return circuit num_latent = 3 num_trash = 2 circuit = auto_encoder_circuit(num_latent, num_trash) circuit.draw("mpl") def domain_wall(circuit, a, b): # Here we place the Domain Wall to qubits a - b in our circuit for i in np.arange(int(b / 2), int(b)): circuit.x(i) return circuit domain_wall_circuit = domain_wall(QuantumCircuit(5), 0, 5) domain_wall_circuit.draw("mpl") ae = auto_encoder_circuit(num_latent, num_trash) qc = QuantumCircuit(num_latent + 2 * num_trash + 1, 1) qc = qc.compose(domain_wall_circuit, range(num_latent + num_trash)) qc = qc.compose(ae) qc.draw("mpl") # Here we define our interpret for our SamplerQNN def identity_interpret(x): return x qnn = SamplerQNN( circuit=qc, input_params=[], weight_params=ae.parameters, interpret=identity_interpret, output_shape=2, ) def cost_func_domain(params_values): probabilities = qnn.forward([], params_values) # we pick a probability of getting 1 as the output of the network cost = np.sum(probabilities[:, 1]) # plotting part clear_output(wait=True) objective_func_vals.append(cost) plt.title("Objective function value against iteration") plt.xlabel("Iteration") plt.ylabel("Objective function value") plt.plot(range(len(objective_func_vals)), objective_func_vals) plt.show() return cost opt = COBYLA(maxiter=150) initial_point = algorithm_globals.random.random(ae.num_parameters) objective_func_vals = [] # make the plot nicer plt.rcParams["figure.figsize"] = (12, 6) start = time.time() opt_result = opt.minimize(cost_func_domain, initial_point) elapsed = time.time() - start print(f"Fit in {elapsed:0.2f} seconds") test_qc = QuantumCircuit(num_latent + num_trash) test_qc = test_qc.compose(domain_wall_circuit) ansatz_qc = ansatz(num_latent + num_trash) test_qc = test_qc.compose(ansatz_qc) test_qc.barrier() test_qc.reset(4) test_qc.reset(3) test_qc.barrier() test_qc = test_qc.compose(ansatz_qc.inverse()) test_qc.draw("mpl") test_qc = test_qc.assign_parameters(opt_result.x) domain_wall_state = Statevector(domain_wall_circuit).data output_state = Statevector(test_qc).data fidelity = np.sqrt(np.dot(domain_wall_state.conj(), output_state) ** 2) print("Fidelity of our Output State with our Input State: ", fidelity.real) def zero_idx(j, i): # Index for zero pixels return [ [i, j], [i - 1, j - 1], [i - 1, j + 1], [i - 2, j - 1], [i - 2, j + 1], [i - 3, j - 1], [i - 3, j + 1], [i - 4, j - 1], [i - 4, j + 1], [i - 5, j], ] def one_idx(i, j): # Index for one pixels return [[i, j - 1], [i, j - 2], [i, j - 3], [i, j - 4], [i, j - 5], [i - 1, j - 4], [i, j]] def get_dataset_digits(num, draw=True): # Create Dataset containing zero and one train_images = [] train_labels = [] for i in range(int(num / 2)): # First we introduce background noise empty = np.array([algorithm_globals.random.uniform(0, 0.1) for i in range(32)]).reshape( 8, 4 ) # Now we insert the pixels for the one for i, j in one_idx(2, 6): empty[j][i] = algorithm_globals.random.uniform(0.9, 1) train_images.append(empty) train_labels.append(1) if draw: plt.title("This is a One") plt.imshow(train_images[-1]) plt.show() for i in range(int(num / 2)): empty = np.array([algorithm_globals.random.uniform(0, 0.1) for i in range(32)]).reshape( 8, 4 ) # Now we insert the pixels for the zero for k, j in zero_idx(2, 6): empty[k][j] = algorithm_globals.random.uniform(0.9, 1) train_images.append(empty) train_labels.append(0) if draw: plt.imshow(train_images[-1]) plt.title("This is a Zero") plt.show() train_images = np.array(train_images) train_images = train_images.reshape(len(train_images), 32) for i in range(len(train_images)): sum_sq = np.sum(train_images[i] ** 2) train_images[i] = train_images[i] / np.sqrt(sum_sq) return train_images, train_labels train_images, __ = get_dataset_digits(2) num_latent = 3 num_trash = 2 fm = RawFeatureVector(2 ** (num_latent + num_trash)) ae = auto_encoder_circuit(num_latent, num_trash) qc = QuantumCircuit(num_latent + 2 * num_trash + 1, 1) qc = qc.compose(fm, range(num_latent + num_trash)) qc = qc.compose(ae) qc.draw("mpl") def identity_interpret(x): return x qnn = SamplerQNN( circuit=qc, input_params=fm.parameters, weight_params=ae.parameters, interpret=identity_interpret, output_shape=2, ) def cost_func_digits(params_values): probabilities = qnn.forward(train_images, params_values) cost = np.sum(probabilities[:, 1]) / train_images.shape[0] # plotting part clear_output(wait=True) objective_func_vals.append(cost) plt.title("Objective function value against iteration") plt.xlabel("Iteration") plt.ylabel("Objective function value") plt.plot(range(len(objective_func_vals)), objective_func_vals) plt.show() return cost with open("12_qae_initial_point.json", "r") as f: initial_point = json.load(f) opt = COBYLA(maxiter=150) objective_func_vals = [] # make the plot nicer plt.rcParams["figure.figsize"] = (12, 6) start = time.time() opt_result = opt.minimize(fun=cost_func_digits, x0=initial_point) elapsed = time.time() - start print(f"Fit in {elapsed:0.2f} seconds") # Test test_qc = QuantumCircuit(num_latent + num_trash) test_qc = test_qc.compose(fm) ansatz_qc = ansatz(num_latent + num_trash) test_qc = test_qc.compose(ansatz_qc) test_qc.barrier() test_qc.reset(4) test_qc.reset(3) test_qc.barrier() test_qc = test_qc.compose(ansatz_qc.inverse()) # sample new images test_images, test_labels = get_dataset_digits(2, draw=False) for image, label in zip(test_images, test_labels): original_qc = fm.assign_parameters(image) original_sv = Statevector(original_qc).data original_sv = np.reshape(np.abs(original_sv) ** 2, (8, 4)) param_values = np.concatenate((image, opt_result.x)) output_qc = test_qc.assign_parameters(param_values) output_sv = Statevector(output_qc).data output_sv = np.reshape(np.abs(output_sv) ** 2, (8, 4)) fig, (ax1, ax2) = plt.subplots(1, 2) ax1.imshow(original_sv) ax1.set_title("Input Data") ax2.imshow(output_sv) ax2.set_title("Output Data") plt.show() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the HoareOptimizer pass""" import unittest from numpy import pi from qiskit.utils import optionals from qiskit.transpiler.passes import HoareOptimizer from qiskit.converters import circuit_to_dag from qiskit import QuantumCircuit from qiskit.test import QiskitTestCase from qiskit.circuit.library import XGate, RZGate, CSwapGate, SwapGate from qiskit.dagcircuit import DAGOpNode from qiskit.quantum_info import Statevector @unittest.skipUnless(optionals.HAS_Z3, "z3-solver needs to be installed to run these tests") class TestHoareOptimizer(QiskitTestCase): """Test the HoareOptimizer pass""" def test_phasegate_removal(self): """Should remove the phase on a classical state, but not on a superposition state. """ # ┌───┐ # q_0: ┤ Z ├────── # ├───┤┌───┐ # q_1:─┤ H ├┤ Z ├─ # └───┘└───┘ circuit = QuantumCircuit(3) circuit.z(0) circuit.h(1) circuit.z(1) # q_0: ─────────── # ┌───┐┌───┐ # q_1:─┤ H ├┤ Z ├─ # └───┘└───┘ expected = QuantumCircuit(3) expected.h(1) expected.z(1) stv = Statevector.from_label("0" * circuit.num_qubits) self.assertEqual(stv & circuit, stv & expected) pass_ = HoareOptimizer(size=0) result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_cswap_removal(self): """Should remove Fredkin gates because the optimizer can deduce the targets are in the same state """ # ┌───┐┌───┐ ┌───┐ ┌───┐ ┌───┐ # q_0: ┤ X ├┤ X ├──■──┤ X ├──■──┤ X ├──■────■──┤ X ├───────────────────────────────── # └───┘└─┬─┘┌─┴─┐└─┬─┘ │ └─┬─┘┌─┴─┐ │ └─┬─┘ # q_1: ───────┼──┤ X ├──■────┼────┼──┤ X ├──┼────■───■──■──■──■─────■─────■────────── # │ └─┬─┘ ┌─┴─┐ │ └─┬─┘┌─┴─┐ │ │ │ │ │ │ │ # q_2: ───────┼────┼───────┤ X ├──■────┼──┤ X ├──■───┼──┼──┼──┼──■──┼──■──┼──■──■──■─ # ┌───┐ │ │ └─┬─┘ │ └─┬─┘ │ │ │ │ │ │ │ │ │ │ │ # q_3: ┤ H ├──■────┼─────────┼─────────┼────┼────────┼──┼──X──X──┼──┼──X──┼──┼──X──┼─ # ├───┤ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ # q_4: ┤ H ├───────■─────────┼─────────┼────┼────────┼──┼──┼──X──┼──X──┼──┼──X──┼──X─ # ├───┤ │ │ │ │ │ │ │ │ │ │ │ │ │ # q_5: ┤ H ├─────────────────■─────────┼────┼────────┼──┼──┼─────┼──X──┼──X──┼──X──┼─ # ├───┤ │ │ │ │ │ │ │ │ │ │ # q_6: ┤ H ├───────────────────────────■────■────────┼──┼──┼─────┼─────┼──X──┼─────X─ # └───┘ │ │ │ │ │ │ # q_7: ──────────────────────────────────────────────X──┼──┼─────X─────┼─────┼─────── # │ │ │ │ │ │ # q_8: ──────────────────────────────────────────────X──X──┼─────┼─────X─────┼─────── # │ │ │ │ # q_9: ─────────────────────────────────────────────────X──X─────X───────────X─────── circuit = QuantumCircuit(10) # prep circuit.x(0) circuit.h(3) circuit.h(4) circuit.h(5) circuit.h(6) # find first non-zero bit of reg(3-6), store position in reg(1-2) circuit.cx(3, 0) circuit.ccx(0, 4, 1) circuit.cx(1, 0) circuit.ccx(0, 5, 2) circuit.cx(2, 0) circuit.ccx(0, 6, 1) circuit.ccx(0, 6, 2) circuit.ccx(1, 2, 0) # shift circuit circuit.cswap(1, 7, 8) circuit.cswap(1, 8, 9) circuit.cswap(1, 9, 3) circuit.cswap(1, 3, 4) circuit.cswap(1, 4, 5) circuit.cswap(1, 5, 6) circuit.cswap(2, 7, 9) circuit.cswap(2, 8, 3) circuit.cswap(2, 9, 4) circuit.cswap(2, 3, 5) circuit.cswap(2, 4, 6) # ┌───┐┌───┐ ┌───┐ ┌───┐ ┌───┐ # q_0: ┤ X ├┤ X ├──■──┤ X ├──■──┤ X ├──■────■──┤ X ├─────────────── # └───┘└─┬─┘┌─┴─┐└─┬─┘ │ └─┬─┘┌─┴─┐ │ └─┬─┘ # q_1: ───────┼──┤ X ├──■────┼────┼──┤ X ├──┼────■───■──■──■─────── # │ └─┬─┘ ┌─┴─┐ │ └─┬─┘┌─┴─┐ │ │ │ │ # q_2: ───────┼────┼───────┤ X ├──■────┼──┤ X ├──■───┼──┼──┼──■──■─ # ┌───┐ │ │ └─┬─┘ │ └─┬─┘ │ │ │ │ │ # q_3: ┤ H ├──■────┼─────────┼─────────┼────┼────────X──┼──┼──X──┼─ # ├───┤ │ │ │ │ │ │ │ │ │ # q_4: ┤ H ├───────■─────────┼─────────┼────┼────────X──X──┼──┼──X─ # ├───┤ │ │ │ │ │ │ │ # q_5: ┤ H ├─────────────────■─────────┼────┼───────────X──X──X──┼─ # ├───┤ │ │ │ │ # q_6: ┤ H ├───────────────────────────■────■──────────────X─────X─ # └───┘ # q_7: ──────────────────────────────────────────────────────────── # # q_8: ──────────────────────────────────────────────────────────── # # q_9: ──────────────────────────────────────────────────────────── expected = QuantumCircuit(10) # prep expected.x(0) expected.h(3) expected.h(4) expected.h(5) expected.h(6) # find first non-zero bit of reg(3-6), store position in reg(1-2) expected.cx(3, 0) expected.ccx(0, 4, 1) expected.cx(1, 0) expected.ccx(0, 5, 2) expected.cx(2, 0) expected.ccx(0, 6, 1) expected.ccx(0, 6, 2) expected.ccx(1, 2, 0) # optimized shift circuit expected.cswap(1, 3, 4) expected.cswap(1, 4, 5) expected.cswap(1, 5, 6) expected.cswap(2, 3, 5) expected.cswap(2, 4, 6) stv = Statevector.from_label("0" * circuit.num_qubits) self.assertEqual(stv & circuit, stv & expected) pass_ = HoareOptimizer(size=0) result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_lnn_cnot_removal(self): """Should remove some cnots from swaps introduced because of linear nearest architecture. Only uses single-gate optimization techniques. """ # ┌───┐ ┌───┐ » # q_0: ┤ H ├──■──┤ X ├──■────────────────────────────────────────────────────» # └───┘┌─┴─┐└─┬─┘┌─┴─┐ ┌───┐ » # q_1: ─────┤ X ├──■──┤ X ├──■──┤ X ├──■──────────────────────────────────■──» # └───┘ └───┘┌─┴─┐└─┬─┘┌─┴─┐ ┌───┐ ┌───┐┌─┴─┐» # q_2: ────────────────────┤ X ├──■──┤ X ├──■──┤ X ├──■─────────■──┤ X ├┤ X ├» # └───┘ └───┘┌─┴─┐└─┬─┘┌─┴─┐ ┌─┴─┐└─┬─┘└───┘» # q_3: ───────────────────────────────────┤ X ├──■──┤ X ├──■──┤ X ├──■───────» # └───┘ └───┘┌─┴─┐└───┘ » # q_4: ──────────────────────────────────────────────────┤ X ├───────────────» # └───┘ » # « ┌───┐ # «q_0: ───────■──┤ X ├ # « ┌───┐┌─┴─┐└─┬─┘ # «q_1: ┤ X ├┤ X ├──■── # « └─┬─┘└───┘ # «q_2: ──■──────────── # « # «q_3: ─────────────── # « # «q_4: ─────────────── circuit = QuantumCircuit(5) circuit.h(0) for i in range(0, 3): circuit.cx(i, i + 1) circuit.cx(i + 1, i) circuit.cx(i, i + 1) circuit.cx(3, 4) for i in range(3, 0, -1): circuit.cx(i - 1, i) circuit.cx(i, i - 1) # ┌───┐ ┌───┐ ┌───┐ # q_0: ┤ H ├──■──┤ X ├───────────────────────────────────┤ X ├ # └───┘┌─┴─┐└─┬─┘ ┌───┐ ┌───┐└─┬─┘ # q_1: ─────┤ X ├──■────■──┤ X ├────────────────────┤ X ├──■── # └───┘ ┌─┴─┐└─┬─┘ ┌───┐ ┌───┐└─┬─┘ # q_2: ───────────────┤ X ├──■────■──┤ X ├─────┤ X ├──■─────── # └───┘ ┌─┴─┐└─┬─┘ └─┬─┘ # q_3: ─────────────────────────┤ X ├──■────■────■──────────── # └───┘ ┌─┴─┐ # q_4: ───────────────────────────────────┤ X ├─────────────── # └───┘ expected = QuantumCircuit(5) expected.h(0) for i in range(0, 3): expected.cx(i, i + 1) expected.cx(i + 1, i) expected.cx(3, 4) for i in range(3, 0, -1): expected.cx(i, i - 1) stv = Statevector.from_label("0" * circuit.num_qubits) self.assertEqual(stv & circuit, stv & expected) pass_ = HoareOptimizer(size=0) result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_lnncnot_advanced_removal(self): """Should remove all cnots from swaps introduced because of linear nearest architecture. This time using multi-gate optimization techniques. """ # ┌───┐ ┌───┐ » # q_0: ┤ H ├──■──┤ X ├──■────────────────────────────────────────────────────» # └───┘┌─┴─┐└─┬─┘┌─┴─┐ ┌───┐ » # q_1: ─────┤ X ├──■──┤ X ├──■──┤ X ├──■──────────────────────────────────■──» # └───┘ └───┘┌─┴─┐└─┬─┘┌─┴─┐ ┌───┐ ┌───┐┌─┴─┐» # q_2: ────────────────────┤ X ├──■──┤ X ├──■──┤ X ├──■─────────■──┤ X ├┤ X ├» # └───┘ └───┘┌─┴─┐└─┬─┘┌─┴─┐ ┌─┴─┐└─┬─┘└───┘» # q_3: ───────────────────────────────────┤ X ├──■──┤ X ├──■──┤ X ├──■───────» # └───┘ └───┘┌─┴─┐└───┘ » # q_4: ──────────────────────────────────────────────────┤ X ├───────────────» # └───┘ » # « ┌───┐ # «q_0: ───────■──┤ X ├ # « ┌───┐┌─┴─┐└─┬─┘ # «q_1: ┤ X ├┤ X ├──■── # « └─┬─┘└───┘ # «q_2: ──■──────────── # « # «q_3: ─────────────── # « # «q_4: ─────────────── circuit = QuantumCircuit(5) circuit.h(0) for i in range(0, 3): circuit.cx(i, i + 1) circuit.cx(i + 1, i) circuit.cx(i, i + 1) circuit.cx(3, 4) for i in range(3, 0, -1): circuit.cx(i - 1, i) circuit.cx(i, i - 1) # ┌───┐ # q_0: ┤ H ├──■───────────────── # └───┘┌─┴─┐ # q_1: ─────┤ X ├──■──────────── # └───┘┌─┴─┐ # q_2: ──────────┤ X ├──■─────── # └───┘┌─┴─┐ # q_3: ───────────────┤ X ├──■── # └───┘┌─┴─┐ # q_4: ────────────────────┤ X ├ # └───┘ expected = QuantumCircuit(5) expected.h(0) for i in range(0, 4): expected.cx(i, i + 1) stv = Statevector.from_label("0" * circuit.num_qubits) self.assertEqual(stv & circuit, stv & expected) pass_ = HoareOptimizer(size=6) result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_successive_identity_removal(self): """Should remove a successive pair of H gates applying on the same qubit. """ circuit = QuantumCircuit(1) circuit.h(0) circuit.h(0) circuit.h(0) expected = QuantumCircuit(1) expected.h(0) stv = Statevector.from_label("0" * circuit.num_qubits) self.assertEqual(stv & circuit, stv & expected) pass_ = HoareOptimizer(size=4) result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_targetsuccessive_identity_removal(self): """Should remove pair of controlled target successive which are the inverse of each other, if they can be identified to be executed as a unit (either both or none). """ # ┌───┐ ┌───┐┌───┐ # q_0: ┤ H ├──■──┤ X ├┤ X ├──■── # ├───┤ │ └─┬─┘└───┘ │ # q_1: ┤ H ├──■────■─────────■── # ├───┤┌─┴─┐ ┌─┴─┐ # q_2: ┤ H ├┤ X ├──────────┤ X ├ # └───┘└───┘ └───┘ circuit = QuantumCircuit(3) circuit.h(0) circuit.h(1) circuit.h(2) circuit.ccx(0, 1, 2) circuit.cx(1, 0) circuit.x(0) circuit.ccx(0, 1, 2) # ┌───┐┌───┐┌───┐ # q_0: ┤ H ├┤ X ├┤ X ├ # ├───┤└─┬─┘└───┘ # q_1: ┤ H ├──■─────── # ├───┤ # q_2: ┤ H ├────────── # └───┘ expected = QuantumCircuit(3) expected.h(0) expected.h(1) expected.h(2) expected.cx(1, 0) expected.x(0) stv = Statevector.from_label("0" * circuit.num_qubits) self.assertEqual(stv & circuit, stv & expected) pass_ = HoareOptimizer(size=4) result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_targetsuccessive_identity_advanced_removal(self): """Should remove target successive identity gates with DIFFERENT sets of control qubits. In this case CCCX(4,5,6,7) & CCX(5,6,7). """ # ┌───┐┌───┐ » # q_0: ┤ H ├┤ X ├───────■─────────────────────────────■───────────────────■──» # ├───┤└─┬─┘ │ │ │ » # q_1: ┤ H ├──■─────────■─────────────────────────────■───────────────────■──» # ├───┤┌───┐ │ ┌───┐ │ │ » # q_2: ┤ H ├┤ X ├───────┼──┤ X ├──■──────────────■────┼───────────────────┼──» # ├───┤└─┬─┘ ┌─┴─┐└─┬─┘ │ │ ┌─┴─┐ ┌─┴─┐» # q_3: ┤ H ├──■────■──┤ X ├──■────■──────────────■──┤ X ├──■─────────■──┤ X ├» # ├───┤┌───┐ │ └───┘ │ ┌───┐ │ └───┘ │ │ └───┘» # q_4: ┤ H ├┤ X ├──┼──────────────┼──┤ X ├──■────┼─────────┼─────────┼───────» # ├───┤└─┬─┘┌─┴─┐ ┌─┴─┐└─┬─┘ │ ┌─┴─┐ ┌─┴─┐ ┌─┴─┐ » # q_5: ┤ H ├──■──┤ X ├──────────┤ X ├──■────■──┤ X ├─────┤ X ├──■──┤ X ├─────» # └───┘ └───┘ └───┘ ┌─┴─┐└───┘ └───┘┌─┴─┐├───┤ » # q_6: ───────────────────────────────────┤ X ├───────────────┤ X ├┤ X ├─────» # └───┘ └───┘└───┘ » # q_7: ──────────────────────────────────────────────────────────────────────» # » # « ┌───┐┌───┐ » # «q_0: ──────────────────────■──┤ X ├┤ X ├──■─────────────────────────────■──» # « │ └─┬─┘└─┬─┘ │ │ » # «q_1: ──────────────────────■────■────■────■─────────────────────────────■──» # « ┌───┐ │ │ │ ┌───┐ │ » # «q_2: ──■─────────■──┤ X ├──┼─────────┼────┼──┤ X ├──■──────────────■────┼──» # « │ │ └─┬─┘┌─┴─┐ │ ┌─┴─┐└─┬─┘ │ │ ┌─┴─┐» # «q_3: ──■─────────■────■──┤ X ├───────┼──┤ X ├──■────■──────────────■──┤ X ├» # « │ ┌───┐ │ └───┘ │ └───┘ │ │ ┌───┐ │ └───┘» # «q_4: ──┼──┤ X ├──┼───────────────────┼─────────┼────┼──┤ X ├──■────┼───────» # « ┌─┴─┐└─┬─┘┌─┴─┐ │ │ ┌─┴─┐└─┬─┘ │ ┌─┴─┐ » # «q_5: ┤ X ├──■──┤ X ├─────────────────┼─────────┼──┤ X ├──■────■──┤ X ├─────» # « └───┘ └───┘ │ │ └───┘ │ │ └───┘ » # «q_6: ────────────────────────────────■─────────■─────────■────■────────────» # « ┌─┴─┐ » # «q_7: ───────────────────────────────────────────────────────┤ X ├──────────» # « └───┘ » # « # «q_0: ─────────────── # « # «q_1: ─────────────── # « ┌───┐ # «q_2: ─────┤ X ├───── # « └─┬─┘ # «q_3: ──■────■─────── # « │ ┌───┐ # «q_4: ──┼──┤ X ├───── # « ┌─┴─┐└─┬─┘ # «q_5: ┤ X ├──■────■── # « └───┘ │ # «q_6: ────────────■── # « ┌─┴─┐ # «q_7: ──────────┤ X ├ # « └───┘ circuit = QuantumCircuit(8) circuit.h(0) circuit.h(1) circuit.h(2) circuit.h(3) circuit.h(4) circuit.h(5) for i in range(3): circuit.cx(i * 2 + 1, i * 2) circuit.cx(3, 5) for i in range(2): circuit.ccx(i * 2, i * 2 + 1, i * 2 + 3) circuit.cx(i * 2 + 3, i * 2 + 2) circuit.ccx(4, 5, 6) for i in range(1, -1, -1): circuit.ccx(i * 2, i * 2 + 1, i * 2 + 3) circuit.cx(3, 5) circuit.cx(5, 6) circuit.cx(3, 5) circuit.x(6) for i in range(2): circuit.ccx(i * 2, i * 2 + 1, i * 2 + 3) for i in range(1, -1, -1): circuit.cx(i * 2 + 3, i * 2 + 2) circuit.ccx(i * 2, i * 2 + 1, i * 2 + 3) circuit.cx(1, 0) circuit.ccx(6, 1, 0) circuit.ccx(0, 1, 3) circuit.ccx(6, 3, 2) circuit.ccx(2, 3, 5) circuit.ccx(6, 5, 4) circuit.append(XGate().control(3), [4, 5, 6, 7], []) for i in range(1, -1, -1): circuit.ccx(i * 2, i * 2 + 1, i * 2 + 3) circuit.cx(3, 5) for i in range(1, 3): circuit.cx(i * 2 + 1, i * 2) circuit.ccx(5, 6, 7) # ┌───┐┌───┐ » # q_0: ┤ H ├┤ X ├───────■─────────────────────────────■───────────────────■──» # ├───┤└─┬─┘ │ │ │ » # q_1: ┤ H ├──■─────────■─────────────────────────────■───────────────────■──» # ├───┤┌───┐ │ ┌───┐ │ │ » # q_2: ┤ H ├┤ X ├───────┼──┤ X ├──■──────────────■────┼───────────────────┼──» # ├───┤└─┬─┘ ┌─┴─┐└─┬─┘ │ │ ┌─┴─┐ ┌─┴─┐» # q_3: ┤ H ├──■────■──┤ X ├──■────■──────────────■──┤ X ├──■─────────■──┤ X ├» # ├───┤┌───┐ │ └───┘ │ ┌───┐ │ └───┘ │ │ └───┘» # q_4: ┤ H ├┤ X ├──┼──────────────┼──┤ X ├──■────┼─────────┼─────────┼───────» # ├───┤└─┬─┘┌─┴─┐ ┌─┴─┐└─┬─┘ │ ┌─┴─┐ ┌─┴─┐ ┌─┴─┐ » # q_5: ┤ H ├──■──┤ X ├──────────┤ X ├──■────■──┤ X ├─────┤ X ├──■──┤ X ├─────» # └───┘ └───┘ └───┘ ┌─┴─┐└───┘ └───┘┌─┴─┐├───┤ » # q_6: ───────────────────────────────────┤ X ├───────────────┤ X ├┤ X ├─────» # └───┘ └───┘└───┘ » # q_7: ──────────────────────────────────────────────────────────────────────» # » # « ┌───┐┌───┐ » # «q_0: ──────────────────────■──┤ X ├┤ X ├──■────────────────────────■───────» # « │ └─┬─┘└─┬─┘ │ │ » # «q_1: ──────────────────────■────■────■────■────────────────────────■───────» # « ┌───┐ │ │ │ ┌───┐ │ » # «q_2: ──■─────────■──┤ X ├──┼─────────┼────┼──┤ X ├──■─────────■────┼───────» # « │ │ └─┬─┘┌─┴─┐ │ ┌─┴─┐└─┬─┘ │ │ ┌─┴─┐ » # «q_3: ──■─────────■────■──┤ X ├───────┼──┤ X ├──■────■─────────■──┤ X ├──■──» # « │ ┌───┐ │ └───┘ │ └───┘ │ │ ┌───┐ │ └───┘ │ » # «q_4: ──┼──┤ X ├──┼───────────────────┼─────────┼────┼──┤ X ├──┼─────────┼──» # « ┌─┴─┐└─┬─┘┌─┴─┐ │ │ ┌─┴─┐└─┬─┘┌─┴─┐ ┌─┴─┐» # «q_5: ┤ X ├──■──┤ X ├─────────────────┼─────────┼──┤ X ├──■──┤ X ├─────┤ X ├» # « └───┘ └───┘ │ │ └───┘ │ └───┘ └───┘» # «q_6: ────────────────────────────────■─────────■─────────■─────────────────» # « » # «q_7: ──────────────────────────────────────────────────────────────────────» # « » # « # «q_0: ───── # « # «q_1: ───── # « ┌───┐ # «q_2: ┤ X ├ # « └─┬─┘ # «q_3: ──■── # « ┌───┐ # «q_4: ┤ X ├ # « └─┬─┘ # «q_5: ──■── # « # «q_6: ───── # « # «q_7: ───── # « expected = QuantumCircuit(8) expected.h(0) expected.h(1) expected.h(2) expected.h(3) expected.h(4) expected.h(5) for i in range(3): expected.cx(i * 2 + 1, i * 2) expected.cx(3, 5) for i in range(2): expected.ccx(i * 2, i * 2 + 1, i * 2 + 3) expected.cx(i * 2 + 3, i * 2 + 2) expected.ccx(4, 5, 6) for i in range(1, -1, -1): expected.ccx(i * 2, i * 2 + 1, i * 2 + 3) expected.cx(3, 5) expected.cx(5, 6) expected.cx(3, 5) expected.x(6) for i in range(2): expected.ccx(i * 2, i * 2 + 1, i * 2 + 3) for i in range(1, -1, -1): expected.cx(i * 2 + 3, i * 2 + 2) expected.ccx(i * 2, i * 2 + 1, i * 2 + 3) expected.cx(1, 0) expected.ccx(6, 1, 0) expected.ccx(0, 1, 3) expected.ccx(6, 3, 2) expected.ccx(2, 3, 5) expected.ccx(6, 5, 4) for i in range(1, -1, -1): expected.ccx(i * 2, i * 2 + 1, i * 2 + 3) expected.cx(3, 5) for i in range(1, 3): expected.cx(i * 2 + 1, i * 2) stv = Statevector.from_label("0" * circuit.num_qubits) self.assertEqual(stv & circuit, stv & expected) pass_ = HoareOptimizer(size=5) result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_control_removal(self): """Should replace CX by X.""" # ┌───┐ # q_0: ┤ X ├──■── # └───┘┌─┴─┐ # q_1: ─────┤ X ├ # └───┘ circuit = QuantumCircuit(2) circuit.x(0) circuit.cx(0, 1) # ┌───┐ # q_0: ┤ X ├ # ├───┤ # q_1: ┤ X ├ # └───┘ expected = QuantumCircuit(2) expected.x(0) expected.x(1) stv = Statevector.from_label("0" * circuit.num_qubits) self.assertEqual(stv & circuit, stv & expected) pass_ = HoareOptimizer(size=5) result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) # Should replace CZ by Z # # ┌───┐ ┌───┐ # q_0: ┤ H ├─■─┤ H ├ # ├───┤ │ └───┘ # q_1: ┤ X ├─■────── # └───┘ circuit = QuantumCircuit(2) circuit.h(0) circuit.x(1) circuit.cz(0, 1) circuit.h(0) # ┌───┐┌───┐┌───┐ # q_0: ┤ H ├┤ Z ├┤ H ├ # ├───┤└───┘└───┘ # q_1: ┤ X ├────────── # └───┘ expected = QuantumCircuit(2) expected.h(0) expected.x(1) expected.z(0) expected.h(0) stv = Statevector.from_label("0" * circuit.num_qubits) self.assertEqual(stv & circuit, stv & expected) pass_ = HoareOptimizer(size=5) result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_is_identity(self): """The is_identity function determines whether a pair of gates forms the identity, when ignoring control qubits. """ seq = [DAGOpNode(op=XGate().control()), DAGOpNode(op=XGate().control(2))] self.assertTrue(HoareOptimizer()._is_identity(seq)) seq = [ DAGOpNode(op=RZGate(-pi / 2).control()), DAGOpNode(op=RZGate(pi / 2).control(2)), ] self.assertTrue(HoareOptimizer()._is_identity(seq)) seq = [DAGOpNode(op=CSwapGate()), DAGOpNode(op=SwapGate())] self.assertTrue(HoareOptimizer()._is_identity(seq)) def test_multiple_pass(self): """Verify that multiple pass can be run with the same Hoare instance. """ # ┌───┐┌───┐ # q_0:─┤ H ├┤ Z ├─ # ├───┤└───┘ # q_1: ┤ Z ├────── # └───┘ circuit1 = QuantumCircuit(2) circuit1.z(0) circuit1.h(1) circuit1.z(1) circuit2 = QuantumCircuit(2) circuit2.z(1) circuit2.h(0) circuit2.z(0) # ┌───┐┌───┐ # q_0:─┤ H ├┤ Z ├─ # └───┘└───┘ # q_1: ─────────── expected = QuantumCircuit(2) expected.h(0) expected.z(0) pass_ = HoareOptimizer() pass_.run(circuit_to_dag(circuit1)) result2 = pass_.run(circuit_to_dag(circuit2)) self.assertEqual(result2, circuit_to_dag(expected)) if __name__ == "__main__": unittest.main()
https://github.com/v0lta/Quantum-init
v0lta
# based on https://github.com/pytorch/examples/blob/master/mnist/main.py import math import numpy as np 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 qrandom import get_quantum_uniform, get_backend from qiskit import Aer import matplotlib.pyplot as plt import pickle def _calculate_fan_in_and_fan_out(tensor): # from torch.nn dimensions = tensor.dim() if dimensions < 2: raise ValueError("Fan in and fan out can not be computed for \ tensor with fewer than 2 dimensions") num_input_fmaps = tensor.size(1) num_output_fmaps = tensor.size(0) receptive_field_size = 1 if tensor.dim() > 2: receptive_field_size = tensor[0][0].numel() fan_in = num_input_fmaps * receptive_field_size fan_out = num_output_fmaps * receptive_field_size return fan_in, fan_out def kaiming_normal_(tensor, a=0, fan=None, nonlinearity='relu', quantum=False, backend=Aer.get_backend('qasm_simulator'), qbits=5): if not fan: fan, _ = _calculate_fan_in_and_fan_out(tensor) gain = torch.nn.init.calculate_gain(nonlinearity, a) std = gain / math.sqrt(fan) bound = math.sqrt(3.0) * std if not quantum: with torch.no_grad(): tensor.uniform_(-bound, bound) else: quantum_random = get_quantum_uniform(tensor.shape, -bound, bound, backend=backend, n_qbits=qbits) with torch.no_grad(): tensor.data.copy_( torch.from_numpy(quantum_random.astype(np.float16))) class Net(nn.Module): """ Fully connected parameters have been reduced to reduce the number of random numbers required. """ def __init__(self, quantum_init=True, qbits=5): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 32, 3, stride=2) self.conv2 = nn.Conv2d(32, 64, 3, 1) self.dropout1 = nn.Dropout(0.25) self.dropout2 = nn.Dropout(0.5) self.fc1 = nn.Linear(1600, 64) self.fc2 = nn.Linear(64, 10) self.quantum_init = quantum_init if self.quantum_init: self.qbits = qbits self.qbackend = get_backend(self.qbits) # self.qbackend = Aer.get_backend('qasm_simulator') else: self.qbackend = None self.qbits = None # initialize weights # loop over the parameters previous_tensor = None for param in self.parameters(): if param.dim() < 2: # use kernel fan for bias terms. fan, _ = _calculate_fan_in_and_fan_out(previous_tensor) else: fan = None kaiming_normal_(param, fan=fan, quantum=self.quantum_init, backend=self.qbackend, qbits=self.qbits) previous_tensor = param def forward(self, x): x = self.conv1(x) x = F.relu(x) x = self.conv2(x) x = F.relu(x) x = F.max_pool2d(x, 2) x = self.dropout1(x) x = torch.flatten(x, 1) x = self.fc1(x) x = F.relu(x) x = self.dropout2(x) x = self.fc2(x) output = F.log_softmax(x, dim=1) return output def train(args, model, device, train_loader, optimizer, epoch): model.train() for batch_idx, (data, target) in enumerate(train_loader): data, target = data.to(device), target.to(device) optimizer.zero_grad() output = model(data) loss = F.nll_loss(output, target) loss.backward() optimizer.step() if batch_idx % args.log_interval == 0: print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format( epoch, batch_idx * len(data), len(train_loader.dataset), 100. * batch_idx / len(train_loader), loss.item())) if args.dry_run: break def test(model, device, test_loader): model.eval() test_loss = 0 correct = 0 with torch.no_grad(): for data, target in test_loader: data, target = data.to(device), target.to(device) output = model(data) test_loss += F.nll_loss(output, target, reduction='sum').item() pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() test_loss /= len(test_loader.dataset) print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format( test_loss, correct, len(test_loader.dataset), 100. * correct / len(test_loader.dataset))) test_acc = 100. * correct / len(test_loader.dataset) return test_loss, test_acc def main(): # Training settings parser = argparse.ArgumentParser(description='PyTorch MNIST Example') parser.add_argument('--batch-size', type=int, default=64, metavar='N', help='input batch size for training (default: 64)') parser.add_argument('--test-batch-size', type=int, default=1000, metavar='N', help='input batch size for testing (default: 1000)') parser.add_argument('--epochs', type=int, default=14, metavar='N', help='number of epochs to train (default: 14)') parser.add_argument('--lr', type=float, default=1.0, metavar='LR', help='learning rate (default: 1.0)') parser.add_argument('--gamma', type=float, default=0.7, metavar='M', help='Learning rate step gamma (default: 0.7)') parser.add_argument('--no-cuda', action='store_true', default=False, help='disables CUDA training') parser.add_argument('--dry-run', action='store_true', default=False, help='quickly check a single pass') parser.add_argument('--seed', type=int, default=1, metavar='S', help='random seed (default: 1)') parser.add_argument('--log-interval', type=int, default=10, metavar='N', help='how many batches to wait before logging training status') parser.add_argument('--save-model', action='store_true', default=False, help='For Saving the current Model') parser.add_argument('--pseudo-init', action='store_true', default=False, help='If True initialize using real qseudo randomnes') parser.add_argument('--pickle-stats', action='store_true', default=False, help='If True stores test loss and acc in pickle file.') parser.add_argument('--qbits', type=int, default=5, metavar='N', help='The number of qbits to use. Defaults to 5.') args = parser.parse_args() print('args', args) use_cuda = not args.no_cuda and torch.cuda.is_available() torch.manual_seed(args.seed) device = torch.device("cuda" if use_cuda else "cpu") train_kwargs = {'batch_size': args.batch_size} test_kwargs = {'batch_size': args.test_batch_size} if use_cuda: cuda_kwargs = {'num_workers': 1, 'pin_memory': True, 'shuffle': True} train_kwargs.update(cuda_kwargs) test_kwargs.update(cuda_kwargs) transform=transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,)) ]) dataset1 = datasets.MNIST('../data', train=True, download=True, transform=transform) dataset2 = datasets.MNIST('../data', train=False, transform=transform) train_loader = torch.utils.data.DataLoader(dataset1,**train_kwargs) test_loader = torch.utils.data.DataLoader(dataset2, **test_kwargs) if args.pseudo_init: print('initializing using pseudorandom numbers.') model = Net(quantum_init=False).to(device) else: print('initializing using quantum randomness.') model = Net(quantum_init=True, qbits=args.qbits).to(device) optimizer = optim.Adadelta(model.parameters(), lr=args.lr) scheduler = StepLR(optimizer, step_size=1, gamma=args.gamma) test_loss_lst = [] test_acc_lst = [] for epoch in range(1, args.epochs + 1): train(args, model, device, train_loader, optimizer, epoch) epoch_test_loss, epoch_acc_loss = test(model, device, test_loader) test_loss_lst.append(epoch_test_loss) test_acc_lst.append(epoch_acc_loss) scheduler.step() if args.save_model: torch.save(model.state_dict(), "mnist_cnn.pt") plt.plot(test_loss_lst) plt.xlabel('epochs') plt.ylabel('test loss') if args.pseudo_init: plt.title('pseudo-random-init') plt.savefig('pseudornd.png') else: plt.title('quantum-random-init') plt.savefig('qrnd.png') if args.pickle_stats: try: res = pickle.load(open("stats.pickle", "rb")) except (OSError, IOError) as e: res = [] print(e, 'stats.pickle does not exist, creating a new file.') res.append({'args': args, 'test_loss_lst': test_loss_lst, 'test_acc_lst': test_acc_lst}) pickle.dump(res, open("stats.pickle", "wb")) print('stats.pickle saved.') if __name__ == '__main__': main()
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np import matplotlib.pyplot as plt %matplotlib inline # importing Qiskit from qiskit import Aer, IBMQ from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import available_backends, execute, register, get_backend, compile from qiskit.tools import visualization from qiskit.tools.visualization import circuit_drawer q = QuantumRegister(6) qc = QuantumCircuit(q) qc.x(q[2]) qc.cx(q[1], q[5]) qc.cx(q[2], q[5]) qc.cx(q[3], q[5]) qc.ccx(q[1], q[2], q[4]) qc.ccx(q[3], q[4], q[5]) qc.ccx(q[1], q[2], q[4]) qc.x(q[2]) circuit_drawer(qc) def black_box_u_f(circuit, f_in, f_out, aux, n, exactly_1_3_sat_formula): """Circuit that computes the black-box function from f_in to f_out. Create a circuit that verifies whether a given exactly-1 3-SAT formula is satisfied by the input. The exactly-1 version requires exactly one literal out of every clause to be satisfied. """ num_clauses = len(exactly_1_3_sat_formula) for (k, clause) in enumerate(exactly_1_3_sat_formula): # This loop ensures aux[k] is 1 if an odd number of literals # are true for literal in clause: if literal > 0: circuit.cx(f_in[literal-1], aux[k]) else: circuit.x(f_in[-literal-1]) circuit.cx(f_in[-literal-1], aux[k]) # Flip aux[k] if all literals are true, using auxiliary qubit # (ancilla) aux[num_clauses] circuit.ccx(f_in[0], f_in[1], aux[num_clauses]) circuit.ccx(f_in[2], aux[num_clauses], aux[k]) # Flip back to reverse state of negative literals and ancilla circuit.ccx(f_in[0], f_in[1], aux[num_clauses]) for literal in clause: if literal < 0: circuit.x(f_in[-literal-1]) # The formula is satisfied if and only if all auxiliary qubits # except aux[num_clauses] are 1 if (num_clauses == 1): circuit.cx(aux[0], f_out[0]) elif (num_clauses == 2): circuit.ccx(aux[0], aux[1], f_out[0]) elif (num_clauses == 3): circuit.ccx(aux[0], aux[1], aux[num_clauses]) circuit.ccx(aux[2], aux[num_clauses], f_out[0]) circuit.ccx(aux[0], aux[1], aux[num_clauses]) else: raise ValueError('We only allow at most 3 clauses') # Flip back any auxiliary qubits to make sure state is consistent # for future executions of this routine; same loop as above. for (k, clause) in enumerate(exactly_1_3_sat_formula): for literal in clause: if literal > 0: circuit.cx(f_in[literal-1], aux[k]) else: circuit.x(f_in[-literal-1]) circuit.cx(f_in[-literal-1], aux[k]) circuit.ccx(f_in[0], f_in[1], aux[num_clauses]) circuit.ccx(f_in[2], aux[num_clauses], aux[k]) circuit.ccx(f_in[0], f_in[1], aux[num_clauses]) for literal in clause: if literal < 0: circuit.x(f_in[-literal-1]) # -- end function def n_controlled_Z(circuit, controls, target): """Implement a Z gate with multiple controls""" if (len(controls) > 2): raise ValueError('The controlled Z with more than 2 ' + 'controls is not implemented') elif (len(controls) == 1): circuit.h(target) circuit.cx(controls[0], target) circuit.h(target) elif (len(controls) == 2): circuit.h(target) circuit.ccx(controls[0], controls[1], target) circuit.h(target) # -- end function def inversion_about_mean(circuit, f_in, n): """Apply inversion about the mean step of Grover's algorithm.""" # Hadamards everywhere for j in range(n): circuit.h(f_in[j]) # D matrix: flips the sign of the state |000> only for j in range(n): circuit.x(f_in[j]) n_controlled_Z(circuit, [f_in[j] for j in range(n-1)], f_in[n-1]) for j in range(n): circuit.x(f_in[j]) # Hadamards everywhere again for j in range(n): circuit.h(f_in[j]) # -- end function qr = QuantumRegister(3) qInvAvg = QuantumCircuit(qr) inversion_about_mean(qInvAvg, qr, 3) circuit_drawer(qInvAvg) """ Grover search implemented in Qiskit. This module contains the code necessary to run Grover search on 3 qubits, both with a simulator and with a real quantum computing device. This code is the companion for the paper "An introduction to quantum computing, without the physics", Giacomo Nannicini, https://arxiv.org/abs/1708.03684. """ def input_state(circuit, f_in, f_out, n): """(n+1)-qubit input state for Grover search.""" for j in range(n): circuit.h(f_in[j]) circuit.x(f_out) circuit.h(f_out) # -- end function # Make a quantum program for the n-bit Grover search. n = 3 # Exactly-1 3-SAT formula to be satisfied, in conjunctive # normal form. We represent literals with integers, positive or # negative, to indicate a Boolean variable or its negation. exactly_1_3_sat_formula = [[1, 2, -3], [-1, -2, -3], [-1, 2, 3]] # Define three quantum registers: 'f_in' is the search space (input # to the function f), 'f_out' is bit used for the output of function # f, aux are the auxiliary bits used by f to perform its # computation. f_in = QuantumRegister(n) f_out = QuantumRegister(1) aux = QuantumRegister(len(exactly_1_3_sat_formula) + 1) # Define classical register for algorithm result ans = ClassicalRegister(n) # Define quantum circuit with above registers grover = QuantumCircuit() grover.add(f_in) grover.add(f_out) grover.add(aux) grover.add(ans) input_state(grover, f_in, f_out, n) T = 2 for t in range(T): # Apply T full iterations black_box_u_f(grover, f_in, f_out, aux, n, exactly_1_3_sat_formula) inversion_about_mean(grover, f_in, n) # Measure the output register in the computational basis for j in range(n): grover.measure(f_in[j], ans[j]) # Execute circuit backend = Aer.get_backend('qasm_simulator') job = execute([grover], backend=backend, shots=1000) result = job.result() # Get counts and plot histogram counts = result.get_counts(grover) visualization.plot_histogram(counts) IBMQ.load_accounts() # get ibmq_16_rueschlikon configuration and coupling map backend = IBMQ.get_backend('ibmq_16_melbourne') backend_config = backend.configuration() backend_coupling = backend_config['coupling_map'] # compile the circuit for ibmq_16_rueschlikon grover_compiled = compile(grover, backend=backend, coupling_map=backend_coupling, seed=1) grover_compiled_qasm = grover_compiled.experiments[0].header.compiled_circuit_qasm print("Number of gates for", backend.name(), "is", len(grover_compiled_qasm.split("\n")) - 4) circuit_drawer(grover)
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() # our backend is the Pulse Simulator from resources import helper from qiskit.providers.aer import PulseSimulator backend_sim = PulseSimulator() # sample duration for pulse instructions dt = 1e-9 # create the model duffing_model = helper.get_transmon(dt) # get qubit frequency from Duffing model qubit_lo_freq = duffing_model.hamiltonian.get_qubit_lo_from_drift() import numpy as np # visualization tools import matplotlib.pyplot as plt plt.style.use('dark_background') # unit conversion factors -> all backend properties returned in SI (Hz, sec, etc) GHz = 1.0e9 # Gigahertz MHz = 1.0e6 # Megahertz kHz = 1.0e3 # kilohertz us = 1.0e-6 # microseconds ns = 1.0e-9 # nanoseconds from qiskit import pulse from qiskit.pulse import Play, Acquire from qiskit.pulse.pulse_lib import GaussianSquare # qubit to be used throughout the notebook qubit = 0 ### Collect the necessary channels drive_chan = pulse.DriveChannel(qubit) meas_chan = pulse.MeasureChannel(qubit) acq_chan = pulse.AcquireChannel(qubit) # Construct a measurement schedule and add it to an InstructionScheduleMap meas_samples = 1200 meas_pulse = GaussianSquare(duration=meas_samples, amp=0.025, sigma=4, width=1150) measure_sched = Play(meas_pulse, meas_chan) | Acquire(meas_samples, acq_chan, pulse.MemorySlot(qubit)) inst_map = pulse.InstructionScheduleMap() inst_map.add('measure', [qubit], measure_sched) # save the measurement/acquire pulse for later measure = inst_map.get('measure', qubits=[qubit]) from qiskit.pulse import pulse_lib # the same spect pulse used in every schedule drive_amp = 0.9 drive_sigma = 16 drive_duration = 128 spec_pulse = pulse_lib.gaussian(duration=drive_duration, amp=drive_amp, sigma=drive_sigma, name=f"Spec drive amplitude = {drive_amp}") # Construct an np array of the frequencies for our experiment spec_freqs_GHz = np.arange(5.0, 5.2, 0.005) # Create the base schedule # Start with drive pulse acting on the drive channel spec_schedules = [] for freq in spec_freqs_GHz: sb_spec_pulse = helper.apply_sideband(spec_pulse, qubit_lo_freq[0]-freq*GHz, dt) spec_schedule = pulse.Schedule(name='SB Frequency = {}'.format(freq)) spec_schedule += Play(sb_spec_pulse, drive_chan) # The left shift `<<` is special syntax meaning to shift the start time of the schedule by some duration spec_schedule += measure << spec_schedule.duration spec_schedules.append(spec_schedule) spec_schedules[0].draw() from qiskit import assemble # assemble the schedules into a Qobj spec01_qobj = assemble(**helper.get_params('spec01', globals())) # run the simulation spec01_result = backend_sim.run(spec01_qobj, duffing_model).result() # retrieve the data from the experiment spec01_values = helper.get_values_from_result(spec01_result, qubit) fit_params, y_fit = helper.fit_lorentzian(spec_freqs_GHz, spec01_values, [5, 5, 1, 0]) f01 = fit_params[1] plt.scatter(spec_freqs_GHz, np.real(spec01_values), color='white') # plot real part of sweep values plt.plot(spec_freqs_GHz, y_fit, color='red') plt.xlim([min(spec_freqs_GHz), max(spec_freqs_GHz)]) plt.xlabel("Frequency [GHz]") plt.ylabel("Measured Signal [a.u.]") plt.show() print("01 Spectroscopy yields %f GHz"%f01) x180_amp = 0.629070 #from lab 6 Rabi experiment x_pulse = pulse_lib.gaussian(duration=drive_duration, amp=x180_amp, sigma=drive_sigma, name='x_pulse') anharmonicity_guess_GHz = -0.3 def build_spec12_pulse_schedule(freq): sb12_spec_pulse = helper.apply_sideband(spec_pulse, (freq + anharmonicity_guess_GHz)*GHz, dt) ### create a 12 spectroscopy pulse schedule spec12_schedule (already done) ### play an x pulse on the drive channel ### play sidebanded spec pulse on the drive channel ### add measurement pulse to schedule spec12_schedule = pulse.Schedule() ### WRITE YOUR CODE BETWEEN THESE LINES - START spec12_schedule += Play(x_pulse, drive_chan) spec12_schedule += Play(sb12_spec_pulse, drive_chan) spec12_schedule += measure << spec12_schedule.duration ### WRITE YOUR CODE BETWEEN THESE LINES - STOP return spec12_schedule sb_freqs_GHz = np.arange(-.1, .1, 0.005) # sweep +/- 100 MHz around guess # now vary the sideband frequency for each spec pulse spec_schedules = [] for freq in sb_freqs_GHz: spec_schedules.append(build_spec12_pulse_schedule(freq)) spec_schedules[0].draw() # assemble the schedules into a Qobj spec12_qobj = assemble(**helper.get_params('spec12', globals())) answer1 = spec12_qobj # run the simulation spec12_result = backend_sim.run(spec12_qobj, duffing_model).result() # retrieve the data from the experiment spec12_values = helper.get_values_from_result(spec12_result, qubit) anharm_offset = qubit_lo_freq[0]/GHz + anharmonicity_guess_GHz fit_params, y_fit = helper.fit_lorentzian(anharm_offset + sb_freqs_GHz, spec12_values, [5, 4.5, .1, 3]) f12 = fit_params[1] plt.scatter(anharm_offset + sb_freqs_GHz, np.real(spec12_values), color='white') # plot real part of sweep values plt.plot(anharm_offset + sb_freqs_GHz, y_fit, color='red') plt.xlim([anharm_offset + min(sb_freqs_GHz), anharm_offset + max(sb_freqs_GHz)]) plt.xlabel("Frequency [GHz]") plt.ylabel("Measured Signal [a.u.]") plt.show() print("12 Spectroscopy yields %f GHz"%f12) print("Measured transmon anharmonicity is %f MHz"%((f12-f01)*GHz/MHz)) from IPython.display import display, Javascript;display(Javascript('IPython.notebook.save_checkpoint();')); from grading_tools import send_code;send_code('ex1.ipynb')
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
from qiskit import * %matplotlib inline import matplotlib.pyplot as plt # The Circuit q = QuantumRegister(3) c = ClassicalRegister(3) qc = QuantumCircuit(q,c) qc.u1(3.6,0) qc.cx(0,1) qc.u1(2.6,2) qc.cx(1,0) qc.s(2) qc.y(2) qc.measure(q,c,basis='Ensemble',add_param='Z') backend = BasicAer.get_backend('dm_simulator') # Noise parameters options = {} options1 = { "thermal_factor": 0., "decoherence_factor": .9, "depolarization_factor": 0.99, "bell_depolarization_factor": 0.99, "decay_factor": 0.99, "rotation_error": {'rx':[1., 0.], 'ry':[1., 0.], 'rz': [1., 0.]}, "tsp_model_error": [1., 0.], "plot": False } # Execution with and without noise run = execute(qc,backend,**options) result = run.result() run_error = execute(qc,backend,**options1) result_error = run_error.result() # Final state (probabilities) prob = result['results'][0]['data']['ensemble_probability'] prob1 = result_error['results'][0]['data']['ensemble_probability'] import numpy as np labels = prob1.keys() without_noise = prob.values() with_noise = prob1.values() x = np.arange(len(labels)) # the label locations width = 0.35 # the width of the bars fig, ax = plt.subplots() rects1 = ax.bar(x - width/2, without_noise, width, label='Without Noise') rects2 = ax.bar(x + width/2, with_noise, width, label='With Noise') # Add some text for labels, title and custom x-axis tick labels, etc. ax.set_ylabel('Probability') ax.set_title('Ensemble Probabilities with Noise') ax.set_xticks(x) ax.set_xticklabels(labels) ax.legend() plt.show()
https://github.com/Fergus-Hayes/qiskit_tools
Fergus-Hayes
def QFT(N): ''' Constructing the fourier transform of size NxN. ''' return np.array([[(np.exp(2.*i*j*1j*np.pi/N)) for j in np.arange(N)] for i in np.arange(N)])*1./np.sqrt(N) from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ import qiskit_tools as qt import numpy as np import matplotlib.pyplot as plt import matplotlib n = 5 xreg = QuantumRegister(n, 'x') circ = QuantumCircuit(xreg) circ = qt.QFT(circ, xreg) circ.draw(output="latex") backend = Aer.get_backend('unitary_simulator') job = execute(circ, backend) result = job.result() unit_mat = np.array(result.get_unitary(circ, decimals=8)) print(np.sum(np.abs(unit_mat-QFT(2**n))**2))
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2019, 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # ============================================================================= """Test Sampler Gradients""" import unittest from typing import List import numpy as np from ddt import ddt, data from qiskit import QuantumCircuit from qiskit_algorithms.gradients import ( FiniteDiffSamplerGradient, LinCombSamplerGradient, ParamShiftSamplerGradient, SPSASamplerGradient, ) from qiskit.circuit import Parameter from qiskit.circuit.library import EfficientSU2, RealAmplitudes from qiskit.circuit.library.standard_gates import RXXGate from qiskit.primitives import Sampler from qiskit.result import QuasiDistribution from qiskit.test import QiskitTestCase from .logging_primitives import LoggingSampler gradient_factories = [ lambda sampler: FiniteDiffSamplerGradient(sampler, epsilon=1e-6, method="central"), lambda sampler: FiniteDiffSamplerGradient(sampler, epsilon=1e-6, method="forward"), lambda sampler: FiniteDiffSamplerGradient(sampler, epsilon=1e-6, method="backward"), ParamShiftSamplerGradient, LinCombSamplerGradient, ] @ddt class TestSamplerGradient(QiskitTestCase): """Test Sampler Gradient""" @data(*gradient_factories) def test_single_circuit(self, grad): """Test the sampler gradient for a single circuit""" sampler = Sampler() a = Parameter("a") qc = QuantumCircuit(1) qc.h(0) qc.p(a, 0) qc.h(0) qc.measure_all() gradient = grad(sampler) param_list = [[np.pi / 4], [0], [np.pi / 2]] expected = [ [{0: -0.5 / np.sqrt(2), 1: 0.5 / np.sqrt(2)}], [{0: 0, 1: 0}], [{0: -0.499999, 1: 0.499999}], ] for i, param in enumerate(param_list): gradients = gradient.run([qc], [param]).result().gradients[0] array1 = _quasi2array(gradients, num_qubits=1) array2 = _quasi2array(expected[i], num_qubits=1) np.testing.assert_allclose(array1, array2, atol=1e-3) @data(*gradient_factories) def test_gradient_p(self, grad): """Test the sampler gradient for p""" sampler = Sampler() a = Parameter("a") qc = QuantumCircuit(1) qc.h(0) qc.p(a, 0) qc.h(0) qc.measure_all() gradient = grad(sampler) param_list = [[np.pi / 4], [0], [np.pi / 2]] expected = [ [{0: -0.5 / np.sqrt(2), 1: 0.5 / np.sqrt(2)}], [{0: 0, 1: 0}], [{0: -0.499999, 1: 0.499999}], ] for i, param in enumerate(param_list): gradients = gradient.run([qc], [param]).result().gradients[0] array1 = _quasi2array(gradients, num_qubits=1) array2 = _quasi2array(expected[i], num_qubits=1) np.testing.assert_allclose(array1, array2, atol=1e-3) @data(*gradient_factories) def test_gradient_u(self, grad): """Test the sampler gradient for u""" sampler = Sampler() a = Parameter("a") b = Parameter("b") c = Parameter("c") qc = QuantumCircuit(1) qc.h(0) qc.u(a, b, c, 0) qc.h(0) qc.measure_all() gradient = grad(sampler) param_list = [[np.pi / 4, 0, 0], [np.pi / 4, np.pi / 4, np.pi / 4]] expected = [ [{0: -0.5 / np.sqrt(2), 1: 0.5 / np.sqrt(2)}, {0: 0, 1: 0}, {0: 0, 1: 0}], [{0: -0.176777, 1: 0.176777}, {0: -0.426777, 1: 0.426777}, {0: -0.426777, 1: 0.426777}], ] for i, param in enumerate(param_list): gradients = gradient.run([qc], [param]).result().gradients[0] array1 = _quasi2array(gradients, num_qubits=1) array2 = _quasi2array(expected[i], num_qubits=1) np.testing.assert_allclose(array1, array2, atol=1e-3) @data(*gradient_factories) def test_gradient_efficient_su2(self, grad): """Test the sampler gradient for EfficientSU2""" sampler = Sampler() qc = EfficientSU2(2, reps=1) qc.measure_all() gradient = grad(sampler) param_list = [ [np.pi / 4 for param in qc.parameters], [np.pi / 2 for param in qc.parameters], ] expected = [ [ { 0: -0.11963834764831836, 1: -0.05713834764831845, 2: -0.21875000000000003, 3: 0.39552669529663675, }, { 0: -0.32230339059327373, 1: -0.031250000000000014, 2: 0.2339150429449554, 3: 0.11963834764831843, }, { 0: 0.012944173824159189, 1: -0.01294417382415923, 2: 0.07544417382415919, 3: -0.07544417382415919, }, { 0: 0.2080266952966367, 1: -0.03125000000000002, 2: -0.11963834764831842, 3: -0.057138347648318405, }, { 0: -0.11963834764831838, 1: 0.11963834764831838, 2: -0.21875000000000003, 3: 0.21875, }, { 0: -0.2781092167691146, 1: -0.0754441738241592, 2: 0.27810921676911443, 3: 0.07544417382415924, }, {0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0}, {0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0}, ], [ { 0: -4.163336342344337e-17, 1: 2.7755575615628914e-17, 2: -4.163336342344337e-17, 3: 0.0, }, {0: 0.0, 1: -1.3877787807814457e-17, 2: 4.163336342344337e-17, 3: 0.0}, { 0: -0.24999999999999994, 1: 0.24999999999999994, 2: 0.24999999999999994, 3: -0.24999999999999994, }, { 0: 0.24999999999999994, 1: 0.24999999999999994, 2: -0.24999999999999994, 3: -0.24999999999999994, }, { 0: -4.163336342344337e-17, 1: 4.163336342344337e-17, 2: -4.163336342344337e-17, 3: 5.551115123125783e-17, }, { 0: -0.24999999999999994, 1: 0.24999999999999994, 2: 0.24999999999999994, 3: -0.24999999999999994, }, {0: 0.0, 1: 2.7755575615628914e-17, 2: 0.0, 3: 2.7755575615628914e-17}, {0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0}, ], ] for i, param in enumerate(param_list): gradients = gradient.run([qc], [param]).result().gradients[0] array1 = _quasi2array(gradients, num_qubits=2) array2 = _quasi2array(expected[i], num_qubits=2) np.testing.assert_allclose(array1, array2, atol=1e-3) @data(*gradient_factories) def test_gradient_2qubit_gate(self, grad): """Test the sampler gradient for 2 qubit gates""" sampler = Sampler() for gate in [RXXGate]: param_list = [[np.pi / 4], [np.pi / 2]] correct_results = [ [{0: -0.5 / np.sqrt(2), 1: 0, 2: 0, 3: 0.5 / np.sqrt(2)}], [{0: -0.5, 1: 0, 2: 0, 3: 0.5}], ] for i, param in enumerate(param_list): a = Parameter("a") qc = QuantumCircuit(2) qc.append(gate(a), [qc.qubits[0], qc.qubits[1]], []) qc.measure_all() gradient = grad(sampler) gradients = gradient.run([qc], [param]).result().gradients[0] array1 = _quasi2array(gradients, num_qubits=2) array2 = _quasi2array(correct_results[i], num_qubits=2) np.testing.assert_allclose(array1, array2, atol=1e-3) @data(*gradient_factories) def test_gradient_parameter_coefficient(self, grad): """Test the sampler gradient for parameter variables with coefficients""" sampler = Sampler() qc = RealAmplitudes(num_qubits=2, reps=1) qc.rz(qc.parameters[0].exp() + 2 * qc.parameters[1], 0) qc.rx(3.0 * qc.parameters[0] + qc.parameters[1].sin(), 1) qc.u(qc.parameters[0], qc.parameters[1], qc.parameters[3], 1) qc.p(2 * qc.parameters[0] + 1, 0) qc.rxx(qc.parameters[0] + 2, 0, 1) qc.measure_all() gradient = grad(sampler) param_list = [[np.pi / 4 for _ in qc.parameters], [np.pi / 2 for _ in qc.parameters]] correct_results = [ [ { 0: 0.30014831912265927, 1: -0.6634809704357856, 2: 0.343589357193753, 3: 0.019743294119373426, }, { 0: 0.16470607453981906, 1: -0.40996282450610577, 2: 0.08791803062881773, 3: 0.15733871933746948, }, { 0: 0.27036068339663866, 1: -0.273790986018701, 2: 0.12752010079553433, 3: -0.12408979817347202, }, { 0: -0.2098616294167757, 1: -0.2515823946449894, 2: 0.21929102305386305, 3: 0.24215300100790207, }, ], [ { 0: -1.844810060881004, 1: 0.04620532700836027, 2: 1.6367366426074323, 3: 0.16186809126521057, }, { 0: 0.07296073407769421, 1: -0.021774869186331716, 2: 0.02177486918633173, 3: -0.07296073407769456, }, { 0: -0.07794369186049102, 1: -0.07794369186049122, 2: 0.07794369186049117, 3: 0.07794369186049112, }, { 0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0, }, ], ] for i, param in enumerate(param_list): gradients = gradient.run([qc], [param]).result().gradients[0] array1 = _quasi2array(gradients, num_qubits=2) array2 = _quasi2array(correct_results[i], num_qubits=2) np.testing.assert_allclose(array1, array2, atol=1e-3) @data(*gradient_factories) def test_gradient_parameters(self, grad): """Test the sampler gradient for parameters""" sampler = Sampler() a = Parameter("a") b = Parameter("b") qc = QuantumCircuit(1) qc.rx(a, 0) qc.rz(b, 0) qc.measure_all() gradient = grad(sampler) param_list = [[np.pi / 4, np.pi / 2]] expected = [ [{0: -0.5 / np.sqrt(2), 1: 0.5 / np.sqrt(2)}], ] for i, param in enumerate(param_list): gradients = gradient.run([qc], [param], parameters=[[a]]).result().gradients[0] array1 = _quasi2array(gradients, num_qubits=1) array2 = _quasi2array(expected[i], num_qubits=1) np.testing.assert_allclose(array1, array2, atol=1e-3) # parameter order with self.subTest(msg="The order of gradients"): c = Parameter("c") qc = QuantumCircuit(1) qc.rx(a, 0) qc.rz(b, 0) qc.rx(c, 0) qc.measure_all() param_values = [[np.pi / 4, np.pi / 2, np.pi / 3]] params = [[a, b, c], [c, b, a], [a, c], [c, a]] expected = [ [ {0: -0.17677666583387008, 1: 0.17677666583378482}, {0: 0.3061861668168149, 1: -0.3061861668167012}, {0: -0.3061861668168149, 1: 0.30618616681678645}, ], [ {0: -0.3061861668168149, 1: 0.30618616681678645}, {0: 0.3061861668168149, 1: -0.3061861668167012}, {0: -0.17677666583387008, 1: 0.17677666583378482}, ], [ {0: -0.17677666583387008, 1: 0.17677666583378482}, {0: -0.3061861668168149, 1: 0.30618616681678645}, ], [ {0: -0.3061861668168149, 1: 0.30618616681678645}, {0: -0.17677666583387008, 1: 0.17677666583378482}, ], ] for i, p in enumerate(params): gradients = gradient.run([qc], param_values, parameters=[p]).result().gradients[0] array1 = _quasi2array(gradients, num_qubits=1) array2 = _quasi2array(expected[i], num_qubits=1) np.testing.assert_allclose(array1, array2, atol=1e-3) @data(*gradient_factories) def test_gradient_multi_arguments(self, grad): """Test the sampler gradient for multiple arguments""" sampler = Sampler() a = Parameter("a") b = Parameter("b") qc = QuantumCircuit(1) qc.rx(a, 0) qc.measure_all() qc2 = QuantumCircuit(1) qc2.rx(b, 0) qc2.measure_all() gradient = grad(sampler) param_list = [[np.pi / 4], [np.pi / 2]] correct_results = [ [{0: -0.5 / np.sqrt(2), 1: 0.5 / np.sqrt(2)}], [{0: -0.499999, 1: 0.499999}], ] gradients = gradient.run([qc, qc2], param_list).result().gradients for i, q_dists in enumerate(gradients): array1 = _quasi2array(q_dists, num_qubits=1) array2 = _quasi2array(correct_results[i], num_qubits=1) np.testing.assert_allclose(array1, array2, atol=1e-3) # parameters with self.subTest(msg="Different parameters"): c = Parameter("c") qc3 = QuantumCircuit(1) qc3.rx(c, 0) qc3.ry(a, 0) qc3.measure_all() param_list2 = [[np.pi / 4], [np.pi / 4, np.pi / 4], [np.pi / 4, np.pi / 4]] gradients = ( gradient.run([qc, qc3, qc3], param_list2, parameters=[[a], [c], None]) .result() .gradients ) correct_results = [ [{0: -0.5 / np.sqrt(2), 1: 0.5 / np.sqrt(2)}], [{0: -0.25, 1: 0.25}], [{0: -0.25, 1: 0.25}, {0: -0.25, 1: 0.25}], ] for i, q_dists in enumerate(gradients): array1 = _quasi2array(q_dists, num_qubits=1) array2 = _quasi2array(correct_results[i], num_qubits=1) np.testing.assert_allclose(array1, array2, atol=1e-3) @data(*gradient_factories) def test_gradient_validation(self, grad): """Test sampler gradient's validation""" sampler = Sampler() a = Parameter("a") qc = QuantumCircuit(1) qc.rx(a, 0) qc.measure_all() gradient = grad(sampler) param_list = [[np.pi / 4], [np.pi / 2]] with self.assertRaises(ValueError): gradient.run([qc], param_list) with self.assertRaises(ValueError): gradient.run([qc, qc], param_list, parameters=[[a]]) with self.assertRaises(ValueError): gradient.run([qc], [[np.pi / 4, np.pi / 4]]) def test_spsa_gradient(self): """Test the SPSA sampler gradient""" sampler = Sampler() with self.assertRaises(ValueError): _ = SPSASamplerGradient(sampler, epsilon=-0.1) a = Parameter("a") b = Parameter("b") c = Parameter("c") qc = QuantumCircuit(2) qc.rx(b, 0) qc.rx(a, 1) qc.measure_all() param_list = [[1, 2]] correct_results = [ [ {0: 0.2273244, 1: -0.6480598, 2: 0.2273244, 3: 0.1934111}, {0: -0.2273244, 1: 0.6480598, 2: -0.2273244, 3: -0.1934111}, ], ] gradient = SPSASamplerGradient(sampler, epsilon=1e-6, seed=123) for i, param in enumerate(param_list): gradients = gradient.run([qc], [param]).result().gradients[0] array1 = _quasi2array(gradients, num_qubits=2) array2 = _quasi2array(correct_results[i], num_qubits=2) np.testing.assert_allclose(array1, array2, atol=1e-3) # multi parameters with self.subTest(msg="Multiple parameters"): param_list2 = [[1, 2], [1, 2], [3, 4]] correct_results2 = [ [ {0: 0.2273244, 1: -0.6480598, 2: 0.2273244, 3: 0.1934111}, {0: -0.2273244, 1: 0.6480598, 2: -0.2273244, 3: -0.1934111}, ], [ {0: -0.2273244, 1: 0.6480598, 2: -0.2273244, 3: -0.1934111}, ], [ {0: -0.0141129, 1: -0.0564471, 2: -0.3642884, 3: 0.4348484}, {0: 0.0141129, 1: 0.0564471, 2: 0.3642884, 3: -0.4348484}, ], ] gradient = SPSASamplerGradient(sampler, epsilon=1e-6, seed=123) gradients = ( gradient.run([qc] * 3, param_list2, parameters=[None, [b], None]).result().gradients ) for i, result in enumerate(gradients): array1 = _quasi2array(result, num_qubits=2) array2 = _quasi2array(correct_results2[i], num_qubits=2) np.testing.assert_allclose(array1, array2, atol=1e-3) # batch size with self.subTest(msg="Batch size"): param_list = [[1, 1]] gradient = SPSASamplerGradient(sampler, epsilon=1e-6, batch_size=4, seed=123) gradients = gradient.run([qc], param_list).result().gradients correct_results3 = [ [ { 0: -0.1620149622932887, 1: -0.25872053011771756, 2: 0.3723827084675668, 3: 0.04835278392088804, }, { 0: -0.1620149622932887, 1: 0.3723827084675668, 2: -0.25872053011771756, 3: 0.04835278392088804, }, ] ] for i, q_dists in enumerate(gradients): array1 = _quasi2array(q_dists, num_qubits=2) array2 = _quasi2array(correct_results3[i], num_qubits=2) np.testing.assert_allclose(array1, array2, atol=1e-3) # parameter order with self.subTest(msg="The order of gradients"): qc = QuantumCircuit(1) qc.rx(a, 0) qc.rz(b, 0) qc.rx(c, 0) qc.measure_all() param_list = [[np.pi / 4, np.pi / 2, np.pi / 3]] param = [[a, b, c], [c, b, a], [a, c], [c, a]] correct_results = [ [ {0: -0.17677624757590138, 1: 0.17677624757590138}, {0: 0.17677624757590138, 1: -0.17677624757590138}, {0: 0.17677624757590138, 1: -0.17677624757590138}, ], [ {0: 0.17677624757590138, 1: -0.17677624757590138}, {0: 0.17677624757590138, 1: -0.17677624757590138}, {0: -0.17677624757590138, 1: 0.17677624757590138}, ], [ {0: -0.17677624757590138, 1: 0.17677624757590138}, {0: 0.17677624757590138, 1: -0.17677624757590138}, ], [ {0: 0.17677624757590138, 1: -0.17677624757590138}, {0: -0.17677624757590138, 1: 0.17677624757590138}, ], ] for i, p in enumerate(param): gradient = SPSASamplerGradient(sampler, epsilon=1e-6, seed=123) gradients = gradient.run([qc], param_list, parameters=[p]).result().gradients[0] array1 = _quasi2array(gradients, num_qubits=1) array2 = _quasi2array(correct_results[i], num_qubits=1) np.testing.assert_allclose(array1, array2, atol=1e-3) @data(ParamShiftSamplerGradient, LinCombSamplerGradient) def test_gradient_random_parameters(self, grad): """Test param shift and lin comb w/ random parameters""" rng = np.random.default_rng(123) qc = RealAmplitudes(num_qubits=3, reps=1) params = qc.parameters qc.rx(3.0 * params[0] + params[1].sin(), 0) qc.ry(params[0].exp() + 2 * params[1], 1) qc.rz(params[0] * params[1] - params[2], 2) qc.p(2 * params[0] + 1, 0) qc.u(params[0].sin(), params[1] - 2, params[2] * params[3], 1) qc.sx(2) qc.rxx(params[0].sin(), 1, 2) qc.ryy(params[1].cos(), 2, 0) qc.rzz(params[2] * 2, 0, 1) qc.crx(params[0].exp(), 1, 2) qc.cry(params[1].arctan(), 2, 0) qc.crz(params[2] * -2, 0, 1) qc.dcx(0, 1) qc.csdg(0, 1) qc.toffoli(0, 1, 2) qc.iswap(0, 2) qc.swap(1, 2) qc.global_phase = params[0] * params[1] + params[2].cos().exp() qc.measure_all() sampler = Sampler() findiff = FiniteDiffSamplerGradient(sampler, 1e-6) gradient = grad(sampler) num_qubits = qc.num_qubits num_tries = 10 param_values = rng.normal(0, 2, (num_tries, qc.num_parameters)).tolist() result1 = findiff.run([qc] * num_tries, param_values).result().gradients result2 = gradient.run([qc] * num_tries, param_values).result().gradients self.assertEqual(len(result1), len(result2)) for res1, res2 in zip(result1, result2): array1 = _quasi2array(res1, num_qubits) array2 = _quasi2array(res2, num_qubits) np.testing.assert_allclose(array1, array2, rtol=1e-4) @data( FiniteDiffSamplerGradient, ParamShiftSamplerGradient, LinCombSamplerGradient, SPSASamplerGradient, ) def test_options(self, grad): """Test sampler gradient's run options""" a = Parameter("a") qc = QuantumCircuit(1) qc.rx(a, 0) qc.measure_all() sampler = Sampler(options={"shots": 100}) with self.subTest("sampler"): if grad is FiniteDiffSamplerGradient or grad is SPSASamplerGradient: gradient = grad(sampler, epsilon=1e-6) else: gradient = grad(sampler) options = gradient.options result = gradient.run([qc], [[1]]).result() self.assertEqual(result.options.get("shots"), 100) self.assertEqual(options.get("shots"), 100) with self.subTest("gradient init"): if grad is FiniteDiffSamplerGradient or grad is SPSASamplerGradient: gradient = grad(sampler, epsilon=1e-6, options={"shots": 200}) else: gradient = grad(sampler, options={"shots": 200}) options = gradient.options result = gradient.run([qc], [[1]]).result() self.assertEqual(result.options.get("shots"), 200) self.assertEqual(options.get("shots"), 200) with self.subTest("gradient update"): if grad is FiniteDiffSamplerGradient or grad is SPSASamplerGradient: gradient = grad(sampler, epsilon=1e-6, options={"shots": 200}) else: gradient = grad(sampler, options={"shots": 200}) gradient.update_default_options(shots=100) options = gradient.options result = gradient.run([qc], [[1]]).result() self.assertEqual(result.options.get("shots"), 100) self.assertEqual(options.get("shots"), 100) with self.subTest("gradient run"): if grad is FiniteDiffSamplerGradient or grad is SPSASamplerGradient: gradient = grad(sampler, epsilon=1e-6, options={"shots": 200}) else: gradient = grad(sampler, options={"shots": 200}) options = gradient.options result = gradient.run([qc], [[1]], shots=300).result() self.assertEqual(result.options.get("shots"), 300) # Only default + sampler options. Not run. self.assertEqual(options.get("shots"), 200) @data( FiniteDiffSamplerGradient, ParamShiftSamplerGradient, LinCombSamplerGradient, SPSASamplerGradient, ) def test_operations_preserved(self, gradient_cls): """Test non-parameterized instructions are preserved and not unrolled.""" x = Parameter("x") circuit = QuantumCircuit(2) circuit.initialize(np.array([1, 1, 0, 0]) / np.sqrt(2)) # this should remain as initialize circuit.crx(x, 0, 1) # this should get unrolled circuit.measure_all() values = [np.pi / 2] expect = [{0: 0, 1: -0.25, 2: 0, 3: 0.25}] ops = [] def operations_callback(op): ops.append(op) sampler = LoggingSampler(operations_callback=operations_callback) if gradient_cls in [SPSASamplerGradient, FiniteDiffSamplerGradient]: gradient = gradient_cls(sampler, epsilon=0.01) else: gradient = gradient_cls(sampler) job = gradient.run([circuit], [values]) result = job.result() with self.subTest(msg="assert initialize is preserved"): self.assertTrue(all("initialize" in ops_i[0].keys() for ops_i in ops)) with self.subTest(msg="assert result is correct"): array1 = _quasi2array(result.gradients[0], num_qubits=2) array2 = _quasi2array(expect, num_qubits=2) np.testing.assert_allclose(array1, array2, atol=1e-5) def _quasi2array(quasis: List[QuasiDistribution], num_qubits: int) -> np.ndarray: ret = np.zeros((len(quasis), 2**num_qubits)) for i, quasi in enumerate(quasis): ret[i, list(quasi.keys())] = list(quasi.values()) return ret if __name__ == "__main__": unittest.main()
https://github.com/rubenandrebarreiro/ibm-qiskit-global-summer-school-2023
rubenandrebarreiro
# import the quantum circuit, quantum register, and classical register # from the IBM's Qiskit library from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister # import the numpy library import numpy as np # define the function to generate the quantum circuit # for the 1st step of the Iterative Phase Estimation (IPE) of the S gate def step_1_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit: # notes: # - qr is a quantum register with 2 qubits # - cr is a classical register with 2 bits # create a quantum circuit with the quantum register and with # the classical register defined before, to implement # the 1st step of the Iterative Phase Estimation (IPE) of the S gate qc = QuantumCircuit(qr, cr) ####### your code goes here ####### # apply the Hadamard gate to the 1st qubit (system's qubit) qc.h(0) # apply the Pauli-X gate to the 1st qubit (auxiliary qubit) qc.x(1) # apply the Controlled-Phase gate for the theta angle equal to pi, # with control on the 1st qubit and target on the 2nd qubit qc.cp( np.pi, 0, 1 ) # apply the Hadamard gate to the 1st qubit (system's qubit) qc.h(0) # measure the state of the 1st qubit (system's qubit), # storing the classical outcome on the 1st bit of # the classical register qc.measure(0, 0) # return the quantum circuit # for the Iterative Phase Estimation (IPE) of the S gate return qc # create the quantum register for # the quantum circuit to implement the 1st step of # the Iterative Phase Estimation (IPE) of the S gate qr = QuantumRegister(2, "q") # create the classical register for # the quantum circuit to implement the 1st step of # the Iterative Phase Estimation (IPE) of the S gate cr = ClassicalRegister(2, "c") # create the quantum circuit to implement the 1st step of # the Iterative Phase Estimation (IPE) of # the S gate, with the quantum register # and the classical register defined before qc = QuantumCircuit(qr, cr) # create the quantum circuit implementing the 1st step of # the Iterative Phase Estimation (IPE) of the S gate qc = step_1_circuit(qr, cr) # draw the quantum circuit implementing the 1st step of # the Iterative Phase Estimation (IPE) of the S gate qc.draw("mpl") # submit your circuit # import the grader for the exercise 1 of the lab 4 from qc_grader.challenges.qgss_2023 import grade_lab4_ex1 # grade the exercise 1 of the lab 4 grade_lab4_ex1( qc ) # define the function to generate the quantum circuit # for the 2nd step of the Iterative Phase Estimation (IPE) of the S gate def step_2_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit: # notes: # - qr is a quantum register with 2 qubits # - cr is a classical register with 2 bits # retrieve the quantum circuit implementing the 1st step of # the Iterative Phase Estimation (IPE) of the S gate qc = step_1_circuit(qr, cr) ####### your code goes here ####### # reset the state of the 1st qubit (system's qubit) qc.reset(0) # apply the Hadamard gate to the 1st qubit (system's qubit) qc.h(0) # if the 1st bit of the classical register of # the dynamic quantum circuit has the classical state 1 with qc.if_test( ( cr[0], True ) ): # apply the phase correction of -pi / 2 to # the 1st qubit of the quantum register with a P gate qc.p( -np.pi / 2, 0 ) # apply the Controlled-Phase gate for the theta angle equal to pi / 2, # with control on the 1st qubit and target on the 2nd qubit qc.cp( np.pi / 2, 0, 1 ) # apply the Hadamard gate to the 1st qubit (system's qubit) qc.h(0) # measure the state of the 1st qubit (system's qubit), # storing the classical outcome on the 2nd bit of # the classical register qc.measure(0, 1) # return the quantum circuit implementing the 2nd step of # the Iterative Phase Estimation (IPE) of the S gate return qc # create the quantum register for # the quantum circuit to implement the 2nd step of # the Iterative Phase Estimation (IPE) of the S gate qr = QuantumRegister(2, "q") # create the classical register for # the quantum circuit to implement the 2nd step of # the Iterative Phase Estimation (IPE) of the S gate cr = ClassicalRegister(2, "c") # create the quantum circuit to implement the 2nd step of # the Iterative Phase Estimation (IPE) of # the S gate, with the quantum register # and the classical register defined before qc = QuantumCircuit(qr, cr) # create the quantum circuit implementing the 2nd step of # the Iterative Phase Estimation (IPE) of the S gate qc = step_2_circuit(qr, cr) # draw the quantum circuit implementing the 2nd step of # the Iterative Phase Estimation (IPE) of the S gate qc.draw("mpl") # submit your circuit # import the grader for the exercise 2 of the lab 4 from qc_grader.challenges.qgss_2023 import grade_lab4_ex2 # grade the exercise 2 of the lab 4 grade_lab4_ex2( qc ) # import the Aer Simulator from the IBM's Qiskit Aer module from qiskit_aer import AerSimulator # create an Aer Simulator object sim = AerSimulator() # create a job for the quantum circuit implementing # the IPE for the S gate, running the Aer Simulator job = sim.run(qc, shots=1000) # retrieve the result counts of the quantum simulation result = job.result() # retrieve the result counts of the quantum simulation counts = result.get_counts() # show the result counts of the quantum simulation counts # import the quantum circuit, quantum register, and classical register # from the IBM's Qiskit library from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister # import the numpy library import numpy as np # define the function to generate the quantum circuit # for the Iterative Phase Estimation (IPE) of the T gate def t_gate_ipe_circuit( qr: QuantumRegister, cr: ClassicalRegister ) -> QuantumCircuit: # notes: # - qr is a quantum register with 2 qubits # - cr is a classical register with 3 bits # create a quantum circuit with the quantum register and with # the classical register defined before, to implement # the Iterative Phase Estimation (IPE) of the T gate qc = QuantumCircuit(qr, cr) ####### your code goes here ####### # apply the Hadamard gate to the 1st qubit (system's qubit) qc.h(0) # apply the Pauli-X gate to the 1st qubit (auxiliary qubit) qc.x(1) # apply the Controlled-Phase gate for the theta angle equal to pi, # with control on the 1st qubit and target on the 2nd qubit qc.cp( np.pi, 0, 1 ) # apply the Hadamard gate to the 1st qubit (system's qubit) qc.h(0) # measure the state of the 1st qubit (system's qubit), # storing the classical outcome on the 1st bit of # the classical register qc.measure(0, 0) # reset the state of the 1st qubit (system's qubit) qc.reset(0) # apply the Hadamard gate to the 1st qubit (system's qubit) qc.h(0) # if the 1st bit of the classical register of # the dynamic quantum circuit has the classical state 1 with qc.if_test( ( cr[0], True ) ): # apply the phase correction of -pi / 2 to # the 1st qubit of the quantum register with a P gate qc.p( -np.pi / 2, 0 ) # apply the Controlled-Phase gate for the theta angle equal to pi / 2, # with control on the 1st qubit and target on the 2nd qubit qc.cp( np.pi / 2, 0, 1 ) # apply the Hadamard gate to the 1st qubit (system's qubit) qc.h(0) # measure the state of the 1st qubit (system's qubit), # storing the classical outcome on the 2nd bit of # the classical register qc.measure(0, 1) # reset the state of the 1st qubit (system's qubit) qc.reset(0) # apply the Hadamard gate to the 1st qubit (system's qubit) qc.h(0) # if the 1st bit of the classical register of # the dynamic quantum circuit has the classical state 1 with qc.if_test( ( cr[0], True ) ): # apply the phase correction of -pi / 2 to # the 1st qubit of the quantum register with a P gate qc.p(-np.pi / 4, 0) # apply the Controlled-Phase gate for the theta angle equal to pi / , # with control on the 1st qubit and target on the 2nd qubit qc.cp( np.pi / 4, 0, 1 ) # apply the Hadamard gate to the 1st qubit (system's qubit) qc.h(0) # measure the state of the 1st qubit (system's qubit), # storing the classical outcome on the 3rd bit of # the classical register qc.measure(0, 2) # return the quantum circuit # for the Iterative Phase Estimation (IPE) of the T gate return qc # create the quantum register for the quantum circuit to # implement the Iterative Phase Estimation (IPE) of the T gate qr = QuantumRegister(2, "q") # create the classical register for the quantum circuit to # implement the Iterative Phase Estimation (IPE) of the T gate cr = ClassicalRegister(3, "c") # create the quantum circuit to implement # the Iterative Phase Estimation (IPE) of # the T gate, with the quantum register # and the classical register defined before qc = QuantumCircuit(qr, cr) # create the quantum circuit implementing # the Iterative Phase Estimation (IPE) of the T gate qc = t_gate_ipe_circuit(qr, cr) # draw the quantum circuit implementing # the Iterative Phase Estimation (IPE) of the T gate qc.draw("mpl") # import the Aer Simulator from the IBM's Qiskit Aer module from qiskit_aer import AerSimulator # create an Aer Simulator object sim = AerSimulator() # create a job for the quantum circuit implementing # the IPE for the T gate, running the Aer Simulator job = sim.run(qc, shots=1000) # retrieve the result counts of the quantum simulation result = job.result() # retrieve the result counts of the quantum simulation counts = result.get_counts() # show the result counts of the quantum simulation counts # submit your circuit # import the grader for the exercise 3 of the lab 4 from qc_grader.challenges.qgss_2023 import grade_lab4_ex3 # grade the exercise 3 of the lab 4 grade_lab4_ex3( qc ) # import the quantum circuit, quantum register, and classical register # from the IBM's Qiskit library from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister # import the numpy library import numpy as np # define the function to generate the quantum circuit # for the Iterative Phase Estimation (IPE) of an U gate def u_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit: # notes: # - qr is a quantum register with 2 qubits # - cr is a classical register with 2 bits # create a quantum circuit with the quantum register and with # the classical register defined before, to implement # the Iterative Phase Estimation (IPE) of the U gate qc = QuantumCircuit(qr, cr) # retrieve the two qubits of the quantum register q0, q1 = qr # retrieve the two bits of the classical register c0, c1 = cr ####### your code goes here ####### # apply the Hadamard gate to the 1st qubit (system's qubit) qc.h(q0) # apply the Pauli-X gate to the 1st qubit (auxiliary qubit) qc.x(q1) # define the theta angle of the U gate as 2 * pi / 3 u_angle = 2 * np.pi / 3 # define the number of the current iteration for # the Iterative Phase Estimation (IPE) of the U gate k = 1 # define the theta angle of the Controlled-Phase gate, # according to the current iteration of # the Iterative Phase Estimation (IPE) of the U gate cphase_angle = u_angle * 2**k # apply the Controlled-Phase gate for the kth theta angle, # with control on the 1st qubit and target on the 2nd qubit qc.cp( cphase_angle, q0, q1 ) # apply the Hadamard gate to the 1st qubit (system's qubit) qc.h(q0) # measure the state of the 1st qubit (system's qubit), # storing the classical outcome on the 1st bit of # the classical register qc.measure(q0, c0) # reset the state of the 1st qubit (system's qubit) qc.reset(q0) # apply the Hadamard gate to the 1st qubit (system's qubit) qc.h(q0) # define the number of the current iteration for # the Iterative Phase Estimation (IPE) of the U gate k = 0 # define the theta angle of the Controlled-Phase gate, # according to the current iteration of # the Iterative Phase Estimation (IPE) of the U gate cphase_angle = u_angle * 2**k # if the 1st bit of the classical register of # the dynamic quantum circuit has the classical state 1 with qc.if_test( ( cr[0], True ) ): # apply the phase correction of the kth theta angle to # the 1st qubit of the quantum register with a P gate qc.p( -cphase_angle, q0 ) # apply the Controlled-Phase gate for the kth theta angle, # with control on the 1st qubit and target on the 2nd qubit qc.cp( cphase_angle, q0, q1 ) # apply the Hadamard gate to the 1st qubit (system's qubit) qc.h(q0) # measure the state of the 1st qubit (system's qubit), # storing the classical outcome on the 2nd bit of # the classical register qc.measure(q0, c1) # return the quantum circuit # for the Iterative Phase Estimation (IPE) of an U gate return qc # create the quantum register for the quantum circuit to # implement the Iterative Phase Estimation (IPE) of the U gate qr = QuantumRegister(2, "q") # create the classical register for the quantum circuit to # implement the Iterative Phase Estimation (IPE) of the U gate cr = ClassicalRegister(2, "c") # create the quantum circuit to implement # the Iterative Phase Estimation (IPE) of # the U gate, with the quantum register # and the classical register defined before qc = QuantumCircuit(qr, cr) # create the quantum circuit implementing # the Iterative Phase Estimation (IPE) of the U gate qc = u_circuit(qr, cr) # draw the quantum circuit implementing # the Iterative Phase Estimation (IPE) of the U gate qc.draw("mpl") # import the Aer Simulator from the IBM's Qiskit Aer module from qiskit_aer import AerSimulator # create an Aer Simulator object sim = AerSimulator() # create a job for the quantum circuit implementing # the IPE for the U gate, running the Aer Simulator job = sim.run(qc, shots=1000) # retrieve the result counts of the quantum simulation result = job.result() # retrieve the result counts of the quantum simulation counts = result.get_counts() # print the result counts of the quantum simulation print(counts) # compute the success probability of the correct outcome success_probability = counts["01"] / counts.shots() # print the success probability of the correct outcome print(f"Success probability: {success_probability}") # import the quantum circuit, quantum register, and classical register # from the IBM's Qiskit library from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister # import the numpy library import numpy as np # define the function to generate the quantum circuit # for the Iterative Phase Estimation (IPE) of an U gate def u_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit: # notes: # - qr is a quantum register with 2 qubits # - cr is a classical register with 1 bit # create a quantum circuit with the quantum register and with # the classical register defined before, to implement # the Iterative Phase Estimation (IPE) of the U gate qc = QuantumCircuit(qr, cr) # retrieve the two qubits of the quantum register q0, q1 = qr # retrieve bit of the classical register c0 = cr ####### your code goes here ####### # apply the Hadamard gate to the 1st qubit (system's qubit) qc.h(q0) # apply the Pauli-X gate to the 1st qubit (auxiliary qubit) qc.x(q1) # define the theta angle of the U gate as 2 * pi / 3 u_angle = 2 * np.pi / 3 # define the number of the current iteration for # the Iterative Phase Estimation (IPE) of the U gate k = 1 # define the theta angle of the Controlled-Phase gate, # according to the current iteration of # the Iterative Phase Estimation (IPE) of the U gate cphase_angle = u_angle * 2**k # apply the Controlled-Phase gate for the kth theta angle, # with control on the 1st qubit and target on the 2nd qubit qc.cp( cphase_angle, q0, q1 ) # apply the Hadamard gate to the 1st qubit (system's qubit) qc.h(q0) # measure the state of the 1st qubit (system's qubit), # storing the classical outcome on the 1st bit of # the classical register qc.measure(q0, c0) # return the quantum circuit # for the Iterative Phase Estimation (IPE) of an U gate return qc # create the quantum register for the quantum circuit to # implement the Iterative Phase Estimation (IPE) of the U gate qr = QuantumRegister(2, "q") # create the classical register for the quantum circuit to # implement the Iterative Phase Estimation (IPE) of the U gate cr = ClassicalRegister(1, "c") # create the quantum circuit to implement # the Iterative Phase Estimation (IPE) of # the U gate, with the quantum register # and the classical register defined before qc = QuantumCircuit(qr, cr) # create the quantum circuit implementing # the Iterative Phase Estimation (IPE) of the U gate qc = u_circuit(qr, cr) # draw the quantum circuit implementing # the Iterative Phase Estimation (IPE) of the U gate qc.draw("mpl") # create a job for the quantum circuit implementing # the IPE for the U gate, running the Aer Simulator job = sim.run(qc, shots=15) # retrieve the result counts of the quantum simulation result = job.result() # retrieve the result counts of the quantum simulation counts = result.get_counts() # print the result counts of the quantum simulation print(counts) # define the variable for # the bit resulting from the 1st step of # the Iterative Phase Estimation (IPE) step1_bit: int ####### your code goes here ####### # define the bit resulting from the 1st step of # the Iterative Phase Estimation (IPE) step1_bit = 1 # print the bit resulting from the 1st step of # the Iterative Phase Estimation (IPE) print(step1_bit) # submit your result # import the grader for the exercise 4 of the lab 4 from qc_grader.challenges.qgss_2023 import grade_lab4_ex4 # grade the exercise 4 of the lab 4 grade_lab4_ex4( step1_bit ) # import the quantum circuit, quantum register, and classical register # from the IBM's Qiskit library from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister # import the numpy library import numpy as np # define the function to generate the quantum circuit # for the Iterative Phase Estimation (IPE) of an U gate, # based on the classical bit obtained from the 1st step def u_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit: # notes: # - qr is a quantum register with 2 qubits # - cr is a classical register with 1 bit # create a quantum circuit with the quantum register and with # the classical register defined before, to implement # the Iterative Phase Estimation (IPE) of the U gate qc = QuantumCircuit(qr, cr) # retrieve the two qubits of the quantum register q0, q1 = qr # retrieve the two bit of the classical register c0, c1 = cr ####### your code goes here ####### # if the classical bit obtained from # the 1st step is the classical state 1 with qc.if_test( ( step1_bit, True ) ): # apply the Pauli-X gate to the 1st qubit (system's qubit) qc.x(q0) # apply the Pauli-X gate to the 2nd qubit (auxiliary qubit) qc.x(q1) # define the theta angle of the U gate as pi / 3 u_angle = np.pi / 3 # define the number of the current iteration for # the Iterative Phase Estimation (IPE) of the U gate k = 1 # define the theta angle of the Controlled-Phase gate, # according to the current iteration of # the Iterative Phase Estimation (IPE) of the U gate cphase_angle = u_angle * 2**k # apply the Controlled-Phase gate for the kth theta angle, # with control on the 1st qubit and target on the 2nd qubit qc.cp( cphase_angle, q0, q1 ) # measure the state of the 2nd qubit (auxiliary qubit), # storing the classical outcome on the 1st bit of # the classical register qc.measure(q1, c0) # return the quantum circuit # for the Iterative Phase Estimation (IPE) of an U gate, # based on the classical bit obtained from the 1st step return qc # create the quantum register for the quantum circuit to # implement the Iterative Phase Estimation (IPE) of the U gate, # based on the classical bit obtained from the 1st step qr = QuantumRegister(2, "q") # create the classical register for the quantum circuit to # implement the Iterative Phase Estimation (IPE) of the U gate, # based on the classical bit obtained from the 1st step cr = ClassicalRegister(2, "c") # create the quantum circuit to implement # the Iterative Phase Estimation (IPE) of # the U gate, based on the classical bit # obtained from the 1st step, # with the quantum register and # the classical register defined before qc = QuantumCircuit(qr, cr) # create the quantum circuit implementing # the Iterative Phase Estimation (IPE) of the U gate, # based on the classical bit obtained from the 1st step qc = u_circuit(qr, cr) # draw the quantum circuit implementing # the Iterative Phase Estimation (IPE) of the U gate, # based on the classical bit obtained from the 1st step qc.draw("mpl") # submit your result # import the grader for the exercise 5 of the lab 4 from qc_grader.challenges.qgss_2023 import grade_lab4_ex5 # grade the exercise 5 of the lab 4 grade_lab4_ex5( qc ) # import the Aer Simulator from the IBM's Qiskit Aer module from qiskit_aer import AerSimulator # create an Aer Simulator object sim = AerSimulator() # create a job for the quantum circuit implementing # the IPE for the U gate, running the Aer Simulator job = sim.run(qc, shots=1000) # retrieve the result counts of the quantum simulation result = job.result() # retrieve the result counts of the quantum simulation counts = result.get_counts() # print the result counts of the quantum simulation print(counts) # compute the success probability of the correct outcome success_probability = counts["01"] / counts.shots() # print the success probability of the correct outcome print(f"Success probability: {success_probability}") # import the Gate from the IBM's Qiskit Circuit module from qiskit.circuit import Gate # define the function to generate the dynamic quantum circuit # for a general Iterative Phase Estimation (IPE) def iterative_phase_estimation( qr: QuantumRegister, cr: ClassicalRegister, controlled_unitaries: list[Gate], state_prep: Gate, ) -> QuantumCircuit: qc = QuantumCircuit(qr, cr) ####### your code goes here ####### # retrieve the number of the Controlled-U gates m = len( controlled_unitaries ) # create a copy of the list of the Controlled-U gates controlled_unitaries_reversed = controlled_unitaries.copy() # retrieve the reverse list of the Controlled-U gates controlled_unitaries_reversed.reverse() # apply the Hadamard gate to the 1st qubit (system's qubit) qc.h(0) # initialize the preparation of the state # with the eigenstate |1> qc.append( state_prep, [1] ) # apply the Controlled-U gate for t = (m - 1) qc.append( controlled_unitaries_reversed[0], [0, 1] ) # apply the Hadamard gate to the 1st qubit (system's qubit) qc.h(0) # measure the state of the 1st qubit (system's qubit), # storing the classical outcome on the 1st bit qc.measure(0, 0) # for the remaining (m - 1) iterations for k in range(1, m): # reset the state of the 1st qubit (system's qubit) qc.reset(0) # apply the Hadamard gate to the 1st qubit (system's qubit) qc.h(0) # if the 1st bit of the classical register of # the dynamic quantum circuit has the classical state 1 with qc.if_test( ( cr[0], 1 ) ): # apply the phase correction to the 1st qubit of # the quantum register with a P gate qc.p( -controlled_unitaries[ ( m - k - 1 ) ].params[0], 0 ) # apply the Controlled-U gate for t = (m - k) qc.append( controlled_unitaries_reversed[k], [0, 1] ) # apply the Hadamard gate to the 1st qubit (system's qubit) qc.h(0) # measure the state of the 1st qubit (system's qubit), # storing the classical outcome on the kth bit qc.measure(0, k) # return the dynamic quantum circuit # for a general Iterative Phase Estimation (IPE) return qc # import the Controlled-Phase and Pauli-X gates # from the IBM's Qiskit Circuit Library module from qiskit.circuit.library import CPhaseGate, XGate # create the quantum register with two qubits # for the quantum circuit to implement IPE on the Z gate qr = QuantumRegister(2, "q") # create the quantum register with three bits # for the quantum circuit to implement IPE on the Z gate cr = ClassicalRegister(1, "c") # define the theta angle for the Z gate z_angle = np.pi # create the list of Controlled-U/Controlled-Phases gates, # considering the theta angle for the Z gate controlled_unitaries = [ CPhaseGate( z_angle * 2**k ) for k in range(1) ] # generate the quantum circuit implementing # the IPE for the Z gate qc = iterative_phase_estimation( qr, cr, controlled_unitaries, XGate() ) # draw the quantum circuit implementing # the IPE for the Z gate qc.draw("mpl") # create an Aer Simulator object sim = AerSimulator() # create a job for the quantum circuit implementing # the IPE for the Z gate, running the Aer Simulator job = sim.run(qc, shots=1000) # retrieve the result counts of the quantum simulation result = job.result() # retrieve the result counts of the quantum simulation counts = result.get_counts() # show the result counts of the quantum simulation counts # import the Controlled-Phase and Pauli-X gates # from the IBM's Qiskit Circuit Library module from qiskit.circuit.library import CPhaseGate, XGate # create the quantum register with two qubits # for the quantum circuit to implement IPE on the S gate qr = QuantumRegister(2, "q") # create the quantum register with three bits # for the quantum circuit to implement IPE on the S gate cr = ClassicalRegister(2, "c") # define the theta angle for the S gate s_angle = np.pi / 2 # create the list of Controlled-U/Controlled-Phase gates, # considering the theta angle for the S gate controlled_unitaries = [ CPhaseGate( s_angle * 2**k ) for k in range(2) ] # generate the quantum circuit implementing # the IPE for the S gate qc = iterative_phase_estimation( qr, cr, controlled_unitaries, XGate() ) # draw the quantum circuit implementing # the IPE for the S gate qc.draw("mpl") # create an Aer Simulator object sim = AerSimulator() # create a job for the quantum circuit implementing # the IPE for the S gate, running the Aer Simulator job = sim.run(qc, shots=1000) # retrieve the result counts of the quantum simulation result = job.result() # retrieve the result counts of the quantum simulation counts = result.get_counts() # show the result counts of the quantum simulation counts # import the Controlled-Phase and Pauli-X gates # from the IBM's Qiskit Circuit Library module from qiskit.circuit.library import CPhaseGate, XGate # create the quantum register with two qubits # for the quantum circuit to implement IPE on the T gate qr = QuantumRegister(2, "q") # create the quantum register with three bits # for the quantum circuit to implement IPE on the T gate cr = ClassicalRegister(3, "c") # define the theta angle for the T gate t_angle = np.pi / 4 # create the list of Controlled-U/Controlled-Phase gates, # considering the theta angle for the T gate controlled_unitaries = [ CPhaseGate( t_angle * 2**k ) for k in range(3) ] # generate the quantum circuit implementing # the IPE for the T gate qc = iterative_phase_estimation( qr, cr, controlled_unitaries, XGate() ) # draw the quantum circuit implementing # the IPE for the T gate qc.draw("mpl") # create an Aer Simulator object sim = AerSimulator() # create a job for the quantum circuit implementing # the IPE for the T gate, running the Aer Simulator job = sim.run(qc, shots=1000) # retrieve the result counts of the quantum simulation result = job.result() # retrieve the result counts of the quantum simulation counts = result.get_counts() # show the result counts of the quantum simulation counts # import the IBMps Provider from Qiskit IBM Provider module from qiskit_ibm_provider import IBMProvider # create an IBM's Provider object provider = IBMProvider() # define the hub for the IBM's Provider hub = "summer-school-6" # define the group for the IBM's Provider group = "group-3" # define the project for the IBM's Provider project = "7048813929" # define the backend's name for the IBM's Provider backend_name = "ibmq_manila" # retrieve the backend from the IBM's Provider backend = provider.get_backend( backend_name, instance=f"{hub}/{group}/{project}" ) # import the transpile feature # from the IBM's Qiskit library from qiskit import transpile # create the quantum register with two qubits # for the quantum circuit to implement IPE on the S gate qr = QuantumRegister(2, "q") # create a classical register with two bits # for the quantum circuit to implement IPE on the S gate cr = ClassicalRegister(2, "c") # create the quantum circuit with # the quantum and classical registers # defined before to implement IPE on the S gate qc = QuantumCircuit(qr, cr) # perform the 2nd step of the IPE on the S gate to # the quantum circuit created before qc = step_2_circuit(qr, cr) # create the transpiled quantum circuit # to implement IPE on the S gate qc_transpiled = transpile(qc, backend) # draw the quantum circuit implementing # an IPE on the S gate qc_transpiled.draw("mpl") # OPTIONAL: run the job of the IPE for the S gate # run the transpiled dynamic quantum circuit of # the IPE for the S gate #job = backend.run(qc_transpiled, shots=1000, dynamic=True) # retrieve the id of the job of the quantum simulation # for the IPE for the S gate #job_id = job.job_id() # print the id of the job of the quantum simulation # for the IPE for the S gate #print(job_id) # OPTIONAL: retrieve and show the job's status of the IPE for the S gate # retrieve the job of the quantum simulation # for the IPE for the S gate #retrieve_job = provider.retrieve_job(job_id) # show the job's status of the quantum simulation # for the IPE for the S gate #retrieve_job.status() # OPTIONAL: plot the histogram of the results of the IPE for the S gate # import the plot histogram from # the IBM's Qiskit Tools' Visualization module #from qiskit.tools.visualization import plot_histogram # retrieve the counts of the results of the job # for the quantum simulation for the IPE for the S gate #counts = retrieve_job.result().get_counts() # plot the historgram of the count results of # the quantum simulation for the IPE for the S gate #plot_histogram(counts) # import the IBM's Qiskit Jupyter Tools import qiskit.tools.jupyter # show the table of the IBM's Qiskit version %qiskit_version_table
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit q = QuantumRegister(1) c = ClassicalRegister(1) qc = QuantumCircuit(q, c) qc.h(q) qc.measure(q, c) qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'})
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, execute from qiskit.providers.fake_provider import FakeVigoV2 from qiskit.visualization import plot_gate_map backend = FakeVigoV2() plot_gate_map(backend)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute, assemble, Aer from qiskit.tools.visualization import plot_histogram from math import pi import matplotlib.pyplot as plt q = QuantumRegister(1,'q') c = ClassicalRegister(1,'c') qc = QuantumCircuit(q, c) qc.h(0) qc.measure(0,0) qc.x(0).c_if(c, 0) qc.draw(output='mpl') q = QuantumRegister(3,'q') c = ClassicalRegister(3,'c') qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.barrier() qc.measure(q,c) qc.draw('mpl') print(bin(3)) print(bin(7)) q = QuantumRegister(3,'q') c = ClassicalRegister(3,'c') qc = QuantumCircuit(q, c) qc.h(0) qc.h(1) qc.h(2) qc.barrier() qc.measure(q,c) qc.x(2).c_if(c, 3) # for the 011 case qc.x(2).c_if(c, 7) # for the 111 case qc.draw(output='mpl') nq = 2 m = 2 q = QuantumRegister(nq,'q') c = ClassicalRegister(m,'c') qc_S = QuantumCircuit(q,c) qc_S.h(0) qc_S.x(1) qc_S.draw('mpl') cu_circ = QuantumCircuit(2) cu_circ.cp(pi/2,0,1) cu_circ.draw('mpl') for _ in range(2**(m-1)): qc_S.cp(pi/2,0,1) qc_S.draw('mpl') def x_measurement(qc, qubit, cbit): """Measure 'qubit' in the X-basis, and store the result in 'cbit'""" qc.h(qubit) qc.measure(qubit, cbit) x_measurement(qc_S, q[0], c[0]) qc_S.draw('mpl') qc_S.reset(0) qc_S.h(0) qc_S.draw('mpl') qc_S.p(-pi/2,0).c_if(c,1) qc_S.draw('mpl') ## 2^t c-U operations (with t=m-2) for _ in range(2**(m-2)): qc_S.cp(pi/2,0,1) x_measurement(qc_S, q[0], c[1]) qc_S.draw('mpl') sim = Aer.get_backend('qasm_simulator') count0 = execute(qc_S, sim).result().get_counts() key_new = [str(int(key,2)/2**m) for key in list(count0.keys())] count1 = dict(zip(key_new, count0.values())) fig, ax = plt.subplots(1,2) plot_histogram(count0, ax=ax[0]) plot_histogram(count1, ax=ax[1]) plt.tight_layout() nq = 3 # number of qubits m = 3 # number of classical bits q = QuantumRegister(nq,'q') c = ClassicalRegister(m,'c') qc = QuantumCircuit(q,c) qc.h(0) qc.x([1,2]) qc.draw('mpl') cu_circ = QuantumCircuit(nq) cu_circ.mcp(pi/4,[0,1],2) cu_circ.draw('mpl') for _ in range(2**(m-1)): qc.mcp(pi/4,[0,1],2) qc.draw('mpl') x_measurement(qc, q[0], c[0]) qc.draw('mpl') qc.reset(0) qc.h(0) qc.draw('mpl') qc.p(-pi/2,0).c_if(c,1) qc.draw('mpl') for _ in range(2**(m-2)): qc.mcp(pi/4,[0,1],2) x_measurement(qc, q[0], c[1]) qc.draw('mpl') # initialization of qubit q0 qc.reset(0) qc.h(0) # phase correction qc.p(-pi/4,0).c_if(c,1) qc.p(-pi/2,0).c_if(c,2) qc.p(-3*pi/4,0).c_if(c,3) # c-U operations for _ in range(2**(m-3)): qc.mcp(pi/4,[0,1],2) # X measurement qc.h(0) qc.measure(0,2) qc.draw('mpl') count0 = execute(qc, sim).result().get_counts() key_new = [str(int(key,2)/2**m) for key in list(count0.keys())] count1 = dict(zip(key_new, count0.values())) fig, ax = plt.subplots(1,2) plot_histogram(count0, ax=ax[0]) plot_histogram(count1, ax=ax[1]) fig.tight_layout() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import Aer, QuantumCircuit from qiskit.circuit.library import PhaseEstimation qc= QuantumCircuit(3,3) # dummy unitary circuit unitary_circuit = QuantumCircuit(1) unitary_circuit.h(0) # QPE qc.append(PhaseEstimation(2, unitary_circuit), list(range(3))) qc.measure(list(range(3)), list(range(3))) backend = Aer.get_backend('qasm_simulator') result = backend.run(qc, shots = 8192).result()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.second_q.drivers import PySCFDriver driver = PySCFDriver( atom="H 0 0 0; H 0 0 0.72" # Two Hydrogen atoms, 0.72 Angstrom apart ) molecule = driver.run() from qiskit_nature.second_q.mappers import QubitConverter, ParityMapper qubit_converter = QubitConverter(ParityMapper()) hamiltonian = qubit_converter.convert(molecule.second_q_ops()[0]) from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver sol = NumPyMinimumEigensolver().compute_minimum_eigenvalue(hamiltonian) real_solution = molecule.interpret(sol) real_solution.groundenergy from qiskit_ibm_runtime import QiskitRuntimeService, Estimator, Session, Options service = QiskitRuntimeService() backend = "ibmq_qasm_simulator" from qiskit.algorithms.minimum_eigensolvers import VQE # Use RealAmplitudes circuit to create trial states from qiskit.circuit.library import RealAmplitudes ansatz = RealAmplitudes(num_qubits=2, reps=2) # Search for better states using SPSA algorithm from qiskit.algorithms.optimizers import SPSA optimizer = SPSA(150) # Set a starting point for reproduceability import numpy as np np.random.seed(6) initial_point = np.random.uniform(-np.pi, np.pi, 12) # Create an object to store intermediate results from dataclasses import dataclass @dataclass class VQELog: values: list parameters: list def update(self, count, parameters, mean, _metadata): self.values.append(mean) self.parameters.append(parameters) print(f"Running circuit {count} of ~350", end="\r", flush=True) log = VQELog([],[]) # Main calculation with Session(service=service, backend=backend) as session: options = Options() options.optimization_level = 3 vqe = VQE(Estimator(session=session, options=options), ansatz, optimizer, callback=log.update, initial_point=initial_point) result = vqe.compute_minimum_eigenvalue(hamiltonian) print("Experiment complete.".ljust(30)) print(f"Raw result: {result.optimal_value}") if 'simulator' not in backend: # Run once with ZNE error mitigation options.resilience_level = 2 vqe = VQE(Estimator(session=session, options=options), ansatz, SPSA(1), initial_point=result.optimal_point) result = vqe.compute_minimum_eigenvalue(hamiltonian) print(f"Mitigated result: {result.optimal_value}") import matplotlib.pyplot as plt plt.rcParams["font.size"] = 14 # Plot energy and reference value plt.figure(figsize=(12, 6)) plt.plot(log.values, label="Estimator VQE") plt.axhline(y=real_solution.groundenergy, color="tab:red", ls="--", label="Target") plt.legend(loc="best") plt.xlabel("Iteration") plt.ylabel("Energy [H]") plt.title("VQE energy") plt.show() import qiskit_ibm_runtime qiskit_ibm_runtime.version.get_version_info() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/abbarreto/qiskit4
abbarreto
https://github.com/ichen17/Learning-Qiskit
ichen17
pip install pylatexenc !pip install qiskit from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.providers.ibmq import least_busy from qiskit.quantum_info import Statevector from qiskit.visualization import plot_histogram # Create a Quantum Register called "qr" with 2 qubits. qr = QuantumRegister(2,'qr') # Create a Classical Register called "cr" with 2 bits. cr = ClassicalRegister(2,'cr') qc = QuantumCircuit(qr,cr) # Add the H gate in the Qubit 1, putting this qubit in superposition. qc.h(qr[1]) # Add the CX gate on control qubit 1 and target qubit 0, putting the qubits in a Bell state i.e entanglement qc.cx(qr[1], qr[0]) # Add a Measure gate to see the state. qc.measure(qr[0],cr[0]) qc.measure(qr[1],cr[1]) # Compile and execute the Quantum Program in the ibmqx5 qc.draw(output='mpl') qasm_simulator = Aer.get_backend('qasm_simulator') shots = 1024 result = results = execute(qc, backend=qasm_simulator, shots=shots).result() Ans=result.get_counts() plot_histogram(Ans)
https://github.com/GabrielPontolillo/QiskitPBT
GabrielPontolillo
# class that inherits from property based test from qiskit import QuantumCircuit from QiskitPBT.property import Property from QiskitPBT.input_generators.random_state import RandomState from QiskitPBT.case_studies.quantum_teleportation.quantum_teleportation import quantum_teleportation class FailingPrecondition(Property): # specify the inputs that are to be generated def get_input_generators(self): state = RandomState(1) return [state] # specify the preconditions for the test def preconditions(self, q0): return False # specify the operations to be performed on the input def operations(self, q0): qc = QuantumCircuit(3, 3) qc.initialize(q0, [0]) qt = quantum_teleportation() # stitch qc and quantum_teleportation together qc = qc.compose(qt) # initialise qubit to compare to: qc2 = QuantumCircuit(1, 1) qc2.initialize(q0, [0]) self.statistical_analysis.assert_equal(self, 2, qc, 0, qc2)
https://github.com/qiskit-community/community.qiskit.org
qiskit-community
from qiskit import * from qiskit.tools.visualization import plot_histogram from qiskit.providers.aer import noise import numpy as np coupling_map = [[1, 0], [2, 0], [2, 1], [3, 2], [3, 4], [4, 2]] noise_dict = {'errors': [{'type': 'qerror', 'operations': ['u2'], 'instructions': [[{'name': 'x', 'qubits': [0]}], [{'name': 'y', 'qubits': [0]}], [{'name': 'z', 'qubits': [0]}], [{'name': 'id', 'qubits': [0]}]], 'probabilities': [0.0004721766167523067, 0.0004721766167523067, 0.0004721766167523067, 0.9985834701497431], 'gate_qubits': [[0]]}, {'type': 'qerror', 'operations': ['u2'], 'instructions': [[{'name': 'x', 'qubits': [0]}], [{'name': 'y', 'qubits': [0]}], [{'name': 'z', 'qubits': [0]}], [{'name': 'id', 'qubits': [0]}]], 'probabilities': [0.0005151090708174488, 0.0005151090708174488, 0.0005151090708174488, 0.9984546727875476], 'gate_qubits': [[1]]}, {'type': 'qerror', 'operations': ['u2'], 'instructions': [[{'name': 'x', 'qubits': [0]}], [{'name': 'y', 'qubits': [0]}], [{'name': 'z', 'qubits': [0]}], [{'name': 'id', 'qubits': [0]}]], 'probabilities': [0.0005151090708174488, 0.0005151090708174488, 0.0005151090708174488, 0.9984546727875476], 'gate_qubits': [[2]]}, {'type': 'qerror', 'operations': ['u2'], 'instructions': [[{'name': 'x', 'qubits': [0]}], [{'name': 'y', 'qubits': [0]}], [{'name': 'z', 'qubits': [0]}], [{'name': 'id', 'qubits': [0]}]], 'probabilities': [0.000901556048412383, 0.000901556048412383, 0.000901556048412383, 0.9972953318547628], 'gate_qubits': [[3]]}, {'type': 'qerror', 'operations': ['u2'], 'instructions': [[{'name': 'x', 'qubits': [0]}], [{'name': 'y', 'qubits': [0]}], [{'name': 'z', 'qubits': [0]}], [{'name': 'id', 'qubits': [0]}]], 'probabilities': [0.0011592423249461303, 0.0011592423249461303, 0.0011592423249461303, 0.9965222730251616], 'gate_qubits': [[4]]}, {'type': 'qerror', 'operations': ['u3'], 'instructions': [[{'name': 'x', 'qubits': [0]}], [{'name': 'y', 'qubits': [0]}], [{'name': 'z', 'qubits': [0]}], [{'name': 'id', 'qubits': [0]}]], 'probabilities': [0.0009443532335046134, 0.0009443532335046134, 0.0009443532335046134, 0.9971669402994862], 'gate_qubits': [[0]]}, {'type': 'qerror', 'operations': ['u3'], 'instructions': [[{'name': 'x', 'qubits': [0]}], [{'name': 'y', 'qubits': [0]}], [{'name': 'z', 'qubits': [0]}], [{'name': 'id', 'qubits': [0]}]], 'probabilities': [0.0010302181416348977, 0.0010302181416348977, 0.0010302181416348977, 0.9969093455750953], 'gate_qubits': [[1]]}, {'type': 'qerror', 'operations': ['u3'], 'instructions': [[{'name': 'x', 'qubits': [0]}], [{'name': 'y', 'qubits': [0]}], [{'name': 'z', 'qubits': [0]}], [{'name': 'id', 'qubits': [0]}]], 'probabilities': [0.0010302181416348977, 0.0010302181416348977, 0.0010302181416348977, 0.9969093455750953], 'gate_qubits': [[2]]}, {'type': 'qerror', 'operations': ['u3'], 'instructions': [[{'name': 'x', 'qubits': [0]}], [{'name': 'y', 'qubits': [0]}], [{'name': 'z', 'qubits': [0]}], [{'name': 'id', 'qubits': [0]}]], 'probabilities': [0.001803112096824766, 0.001803112096824766, 0.001803112096824766, 0.9945906637095256], 'gate_qubits': [[3]]}, {'type': 'qerror', 'operations': ['u3'], 'instructions': [[{'name': 'x', 'qubits': [0]}], [{'name': 'y', 'qubits': [0]}], [{'name': 'z', 'qubits': [0]}], [{'name': 'id', 'qubits': [0]}]], 'probabilities': [0.0023184846498922607, 0.0023184846498922607, 0.0023184846498922607, 0.9930445460503232], 'gate_qubits': [[4]]}, {'type': 'qerror', 'operations': ['cx'], 'instructions': [[{'name': 'x', 'qubits': [0]}], [{'name': 'y', 'qubits': [0]}], [{'name': 'z', 'qubits': [0]}], [{'name': 'x', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'y', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'z', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'id', 'qubits': [0]}]], 'probabilities': [0.002182844139394187, 0.002182844139394187, 0.002182844139394187, 0.002182844139394187, 0.002182844139394187, 0.002182844139394187, 0.002182844139394187, 0.002182844139394187, 0.002182844139394187, 0.002182844139394187, 0.002182844139394187, 0.002182844139394187, 0.002182844139394187, 0.002182844139394187, 0.002182844139394187, 0.9672573379090872], 'gate_qubits': [[1, 0]]}, {'type': 'qerror', 'operations': ['cx'], 'instructions': [[{'name': 'x', 'qubits': [0]}], [{'name': 'y', 'qubits': [0]}], [{'name': 'z', 'qubits': [0]}], [{'name': 'x', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'y', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'z', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'id', 'qubits': [0]}]], 'probabilities': [0.0020007412998552473, 0.0020007412998552473, 0.0020007412998552473, 0.0020007412998552473, 0.0020007412998552473, 0.0020007412998552473, 0.0020007412998552473, 0.0020007412998552473, 0.0020007412998552473, 0.0020007412998552473, 0.0020007412998552473, 0.0020007412998552473, 0.0020007412998552473, 0.0020007412998552473, 0.0020007412998552473, 0.9699888805021712], 'gate_qubits': [[2, 0]]}, {'type': 'qerror', 'operations': ['cx'], 'instructions': [[{'name': 'x', 'qubits': [0]}], [{'name': 'y', 'qubits': [0]}], [{'name': 'z', 'qubits': [0]}], [{'name': 'x', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'y', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'z', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'id', 'qubits': [0]}]], 'probabilities': [0.002485439516158936, 0.002485439516158936, 0.002485439516158936, 0.002485439516158936, 0.002485439516158936, 0.002485439516158936, 0.002485439516158936, 0.002485439516158936, 0.002485439516158936, 0.002485439516158936, 0.002485439516158936, 0.002485439516158936, 0.002485439516158936, 0.002485439516158936, 0.002485439516158936, 0.9627184072576159], 'gate_qubits': [[2, 1]]}, {'type': 'qerror', 'operations': ['cx'], 'instructions': [[{'name': 'x', 'qubits': [0]}], [{'name': 'y', 'qubits': [0]}], [{'name': 'z', 'qubits': [0]}], [{'name': 'x', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'y', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'z', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'id', 'qubits': [0]}]], 'probabilities': [0.0037502825428055767, 0.0037502825428055767, 0.0037502825428055767, 0.0037502825428055767, 0.0037502825428055767, 0.0037502825428055767, 0.0037502825428055767, 0.0037502825428055767, 0.0037502825428055767, 0.0037502825428055767, 0.0037502825428055767, 0.0037502825428055767, 0.0037502825428055767, 0.0037502825428055767, 0.0037502825428055767, 0.9437457618579164], 'gate_qubits': [[3, 2]]}, {'type': 'qerror', 'operations': ['cx'], 'instructions': [[{'name': 'x', 'qubits': [0]}], [{'name': 'y', 'qubits': [0]}], [{'name': 'z', 'qubits': [0]}], [{'name': 'x', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'y', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'z', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'id', 'qubits': [0]}]], 'probabilities': [0.004401224333760022, 0.004401224333760022, 0.004401224333760022, 0.004401224333760022, 0.004401224333760022, 0.004401224333760022, 0.004401224333760022, 0.004401224333760022, 0.004401224333760022, 0.004401224333760022, 0.004401224333760022, 0.004401224333760022, 0.004401224333760022, 0.004401224333760022, 0.004401224333760022, 0.9339816349935997], 'gate_qubits': [[3, 4]]}, {'type': 'qerror', 'operations': ['cx'], 'instructions': [[{'name': 'x', 'qubits': [0]}], [{'name': 'y', 'qubits': [0]}], [{'name': 'z', 'qubits': [0]}], [{'name': 'x', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'y', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'z', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'id', 'qubits': [0]}]], 'probabilities': [0.0046188825262438934, 0.0046188825262438934, 0.0046188825262438934, 0.0046188825262438934, 0.0046188825262438934, 0.0046188825262438934, 0.0046188825262438934, 0.0046188825262438934, 0.0046188825262438934, 0.0046188825262438934, 0.0046188825262438934, 0.0046188825262438934, 0.0046188825262438934, 0.0046188825262438934, 0.0046188825262438934, 0.9307167621063416], 'gate_qubits': [[4, 2]]}, {'type': 'roerror', 'operations': ['measure'], 'probabilities': [[0.9372499999999999, 0.06275000000000008], [0.06275000000000008, 0.9372499999999999]], 'gate_qubits': [[0]]}, {'type': 'roerror', 'operations': ['measure'], 'probabilities': [[0.9345, 0.0655], [0.0655, 0.9345]], 'gate_qubits': [[1]]}, {'type': 'roerror', 'operations': ['measure'], 'probabilities': [[0.97075, 0.029249999999999998], [0.029249999999999998, 0.97075]], 'gate_qubits': [[2]]}, {'type': 'roerror', 'operations': ['measure'], 'probabilities': [[0.9742500000000001, 0.02574999999999994], [0.02574999999999994, 0.9742500000000001]], 'gate_qubits': [[3]]}, {'type': 'roerror', 'operations': ['measure'], 'probabilities': [[0.8747499999999999, 0.12525000000000008], [0.12525000000000008, 0.8747499999999999]], 'gate_qubits': [[4]]}], 'x90_gates': []} noise_model = noise.noise_model.NoiseModel.from_dict( noise_dict ) qr = QuantumRegister(5, 'qr') cr = ClassicalRegister(1, 'cr') backend = Aer.get_backend('qasm_simulator') def AND (input1,input2, q_1=0,q_2=1,q_out=2): # The keyword q_1 specifies the qubit used to encode input1 # The keyword q_2 specifies qubit used to encode input2 # The keyword q_out specifies qubit to be as output qc = QuantumCircuit(qr, cr) # prepare input on qubits q1 and q2 if input1=='1': qc.x( qr[ q_1 ] ) if input2=='1': qc.x( qr[ q_2 ] ) qc.ccx(qr[ q_1 ],qr[ q_2 ],qr[ q_out ]) # the AND just needs a c qc.measure(qr[ q_out ],cr[0]) # output from qubit 1 is measured # the circuit is run on a simulator, but we do it so that the noise and connectivity of Tenerife are also reproduced job = execute(qc, backend, shots=10000, noise_model=noise_model, coupling_map=coupling_map, basis_gates=noise_model.basis_gates) output = job.result().get_counts() return output result = AND('0','0') print( result ) plot_histogram( result ) worst = 1 for input1 in ['0','1']: for input2 in ['0','1']: print('\nProbability of correct answer for inputs',input1,input2) prob = AND(input1,input2, q_1=0,q_2=1,q_out=2)[str(int( input1=='1' and input2=='1' ))]/10000 print( prob ) worst = min(worst,prob) print('\nThe lowest of these probabilities was',worst)
https://github.com/microsoft/qiskit-qir
microsoft
## # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. ## import pytest from qiskit import QuantumCircuit @pytest.fixture() def while_loop(): circuit = QuantumCircuit(1, 1) circuit.name = "Simple while-loop circuit" with circuit.while_loop((circuit.clbits[0], 0)): circuit.h(0) circuit.measure(0, 0) return circuit @pytest.fixture() def for_loop(): circuit = QuantumCircuit(4, 0) circuit.name = "Simple for-loop circuit" circuit.h(3) with circuit.for_loop(range(3)): # Qiskit doesn't (yet) support cnot(3, i) circuit.cx(3, 0) return circuit @pytest.fixture() def if_else(): circuit = QuantumCircuit(3, 2) circuit.h(0) circuit.cx(0, 1) circuit.measure(0, 0) circuit.h(0) circuit.cx(0, 1) circuit.measure(0, 1) with circuit.if_test((circuit.clbits[0], 0)) as else_: circuit.x(2) with else_: circuit.h(2) circuit.z(2) return circuit cf_fixtures = ["while_loop", "for_loop", "if_else"]
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from scipy.interpolate import griddata %matplotlib inline import numpy as np from qiskit import QuantumRegister, QuantumCircuit, AncillaRegister, transpile from qiskit.circuit.library import IntegerComparator, WeightedAdder, LinearAmplitudeFunction from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # number of qubits per dimension to represent the uncertainty num_uncertainty_qubits = 2 # parameters for considered random distribution S = 2.0 # initial spot price vol = 0.4 # volatility of 40% r = 0.05 # annual interest rate of 4% T = 40 / 365 # 40 days to maturity # resulting parameters for log-normal distribution mu = (r - 0.5 * vol**2) * T + np.log(S) sigma = vol * np.sqrt(T) mean = np.exp(mu + sigma**2 / 2) variance = (np.exp(sigma**2) - 1) * np.exp(2 * mu + sigma**2) stddev = np.sqrt(variance) # lowest and highest value considered for the spot price; in between, an equidistant discretization is considered. low = np.maximum(0, mean - 3 * stddev) high = mean + 3 * stddev # map to higher dimensional distribution # for simplicity assuming dimensions are independent and identically distributed) dimension = 2 num_qubits = [num_uncertainty_qubits] * dimension low = low * np.ones(dimension) high = high * np.ones(dimension) mu = mu * np.ones(dimension) cov = sigma**2 * np.eye(dimension) # construct circuit u = LogNormalDistribution(num_qubits=num_qubits, mu=mu, sigma=cov, bounds=(list(zip(low, high)))) # plot PDF of uncertainty model x = [v[0] for v in u.values] y = [v[1] for v in u.values] z = u.probabilities # z = map(float, z) # z = list(map(float, z)) resolution = np.array([2**n for n in num_qubits]) * 1j grid_x, grid_y = np.mgrid[min(x) : max(x) : resolution[0], min(y) : max(y) : resolution[1]] grid_z = griddata((x, y), z, (grid_x, grid_y)) plt.figure(figsize=(10, 8)) ax = plt.axes(projection="3d") ax.plot_surface(grid_x, grid_y, grid_z, cmap=plt.cm.Spectral) ax.set_xlabel("Spot Price $S_1$ (\$)", size=15) ax.set_ylabel("Spot Price $S_2$ (\$)", size=15) ax.set_zlabel("Probability (\%)", size=15) plt.show() # determine number of qubits required to represent total loss weights = [] for n in num_qubits: for i in range(n): weights += [2**i] # create aggregation circuit agg = WeightedAdder(sum(num_qubits), weights) n_s = agg.num_sum_qubits n_aux = agg.num_qubits - n_s - agg.num_state_qubits # number of additional qubits # set the strike price (should be within the low and the high value of the uncertainty) strike_price_1 = 3 strike_price_2 = 4 # set the barrier threshold barrier = 2.5 # map strike prices and barrier threshold from [low, high] to {0, ..., 2^n-1} max_value = 2**n_s - 1 low_ = low[0] high_ = high[0] mapped_strike_price_1 = ( (strike_price_1 - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1) ) mapped_strike_price_2 = ( (strike_price_2 - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1) ) mapped_barrier = (barrier - low) / (high - low) * (2**num_uncertainty_qubits - 1) # condition and condition result conditions = [] barrier_thresholds = [2] * dimension n_aux_conditions = 0 for i in range(dimension): # target dimension of random distribution and corresponding condition (which is required to be True) comparator = IntegerComparator(num_qubits[i], mapped_barrier[i] + 1, geq=False) n_aux_conditions = max(n_aux_conditions, comparator.num_ancillas) conditions += [comparator] # set the approximation scaling for the payoff function c_approx = 0.25 # setup piecewise linear objective fcuntion breakpoints = [0, mapped_strike_price_1, mapped_strike_price_2] slopes = [0, 1, 0] offsets = [0, 0, mapped_strike_price_2 - mapped_strike_price_1] f_min = 0 f_max = mapped_strike_price_2 - mapped_strike_price_1 objective = LinearAmplitudeFunction( n_s, slopes, offsets, domain=(0, max_value), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) # define overall multivariate problem qr_state = QuantumRegister(u.num_qubits, "state") # to load the probability distribution qr_obj = QuantumRegister(1, "obj") # to encode the function values ar_sum = AncillaRegister(n_s, "sum") # number of qubits used to encode the sum ar_cond = AncillaRegister(len(conditions) + 1, "conditions") ar = AncillaRegister( max(n_aux, n_aux_conditions, objective.num_ancillas), "work" ) # additional qubits objective_index = u.num_qubits # define the circuit asian_barrier_spread = QuantumCircuit(qr_state, qr_obj, ar_cond, ar_sum, ar) # load the probability distribution asian_barrier_spread.append(u, qr_state) # apply the conditions for i, cond in enumerate(conditions): state_qubits = qr_state[(num_uncertainty_qubits * i) : (num_uncertainty_qubits * (i + 1))] asian_barrier_spread.append(cond, state_qubits + [ar_cond[i]] + ar[: cond.num_ancillas]) # aggregate the conditions on a single qubit asian_barrier_spread.mcx(ar_cond[:-1], ar_cond[-1]) # apply the aggregation function controlled on the condition asian_barrier_spread.append(agg.control(), [ar_cond[-1]] + qr_state[:] + ar_sum[:] + ar[:n_aux]) # apply the payoff function asian_barrier_spread.append(objective, ar_sum[:] + qr_obj[:] + ar[: objective.num_ancillas]) # uncompute the aggregation asian_barrier_spread.append( agg.inverse().control(), [ar_cond[-1]] + qr_state[:] + ar_sum[:] + ar[:n_aux] ) # uncompute the conditions asian_barrier_spread.mcx(ar_cond[:-1], ar_cond[-1]) for j, cond in enumerate(reversed(conditions)): i = len(conditions) - j - 1 state_qubits = qr_state[(num_uncertainty_qubits * i) : (num_uncertainty_qubits * (i + 1))] asian_barrier_spread.append( cond.inverse(), state_qubits + [ar_cond[i]] + ar[: cond.num_ancillas] ) print(asian_barrier_spread.draw()) print("objective qubit index", objective_index) # plot exact payoff function plt.figure(figsize=(7, 5)) x = np.linspace(sum(low), sum(high)) y = (x <= 5) * np.minimum(np.maximum(0, x - strike_price_1), strike_price_2 - strike_price_1) plt.plot(x, y, "r-") plt.grid() plt.title("Payoff Function (for $S_1 = S_2$)", size=15) plt.xlabel("Sum of Spot Prices ($S_1 + S_2)$", size=15) plt.ylabel("Payoff", size=15) plt.xticks(size=15, rotation=90) plt.yticks(size=15) plt.show() # plot contour of payoff function with respect to both time steps, including barrier plt.figure(figsize=(7, 5)) z = np.zeros((17, 17)) x = np.linspace(low[0], high[0], 17) y = np.linspace(low[1], high[1], 17) for i, x_ in enumerate(x): for j, y_ in enumerate(y): z[i, j] = np.minimum( np.maximum(0, x_ + y_ - strike_price_1), strike_price_2 - strike_price_1 ) if x_ > barrier or y_ > barrier: z[i, j] = 0 plt.title("Payoff Function", size=15) plt.contourf(x, y, z) plt.colorbar() plt.xlabel("Spot Price $S_1$", size=15) plt.ylabel("Spot Price $S_2$", size=15) plt.xticks(size=15) plt.yticks(size=15) plt.show() # evaluate exact expected value sum_values = np.sum(u.values, axis=1) payoff = np.minimum(np.maximum(sum_values - strike_price_1, 0), strike_price_2 - strike_price_1) leq_barrier = [np.max(v) <= barrier for v in u.values] exact_value = np.dot(u.probabilities[leq_barrier], payoff[leq_barrier]) print("exact expected value:\t%.4f" % exact_value) num_state_qubits = asian_barrier_spread.num_qubits - asian_barrier_spread.num_ancillas print("state qubits: ", num_state_qubits) transpiled = transpile(asian_barrier_spread, basis_gates=["u", "cx"]) print("circuit width:", transpiled.width()) print("circuit depth:", transpiled.depth()) asian_barrier_spread_measure = asian_barrier_spread.measure_all(inplace=False) sampler = Sampler() job = sampler.run(asian_barrier_spread_measure) # evaluate the result value = 0 probabilities = job.result().quasi_dists[0].binary_probabilities() for i, prob in probabilities.items(): if prob > 1e-4 and i[-num_state_qubits:][0] == "1": value += prob # map value to original range mapped_value = objective.post_processing(value) / (2**num_uncertainty_qubits - 1) * (high_ - low_) print("Exact Operator Value: %.4f" % value) print("Mapped Operator value: %.4f" % mapped_value) print("Exact Expected Payoff: %.4f" % exact_value) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=asian_barrier_spread, objective_qubits=[objective_index], post_processing=objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation(epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})) result = ae.estimate(problem) conf_int = ( np.array(result.confidence_interval_processed) / (2**num_uncertainty_qubits - 1) * (high_ - low_) ) print("Exact value: \t%.4f" % exact_value) print( "Estimated value:\t%.4f" % (result.estimation_processed / (2**num_uncertainty_qubits - 1) * (high_ - low_)) ) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# If you introduce a list with less colors than bars, the color of the bars will # alternate following the sequence from the list. import numpy as np from qiskit.quantum_info import DensityMatrix from qiskit import QuantumCircuit from qiskit.visualization import plot_state_paulivec qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc = QuantumCircuit(2) qc.h([0, 1]) qc.cz(0, 1) qc.ry(np.pi/3, 0) qc.rx(np.pi/5, 1) matrix = DensityMatrix(qc) plot_state_paulivec(matrix, color=['crimson', 'midnightblue', 'seagreen'])
https://github.com/quantumyatra/quantum_computing
quantumyatra
# Useful additional packages import matplotlib.pyplot as plt %matplotlib inline import numpy as np from math import pi from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.tools.visualization import circuit_drawer from qiskit.quantum_info import state_fidelity from qiskit import BasicAer backend = BasicAer.get_backend('unitary_simulator') q = QuantumRegister(2) qc = QuantumCircuit(q) qc.u3(pi/2,pi/2,pi/2,q[0]) qc.draw(output='mpl') job = execute(qc, backend) job.result().get_unitary(qc, decimals=3) q = QuantumRegister(2) qc = QuantumCircuit(q) qc.u3(pi/2,pi/2,pi/2,q[1]) qc.draw(output='mpl') job = execute(qc, backend) job.result().get_unitary(qc, decimals=3) q = QuantumRegister(2) qc = QuantumCircuit(q) qc.u3(pi/2,pi/2,pi/2,q[0]) qc.u3(pi/2,pi/2,pi/2,q[1]) qc.draw(output='mpl') job = execute(qc, backend) job.result().get_unitary(qc, decimals=3) q = QuantumRegister(2) qc = QuantumCircuit(q) qc.u3(pi/2,pi/2,pi/2,q[0]) qc.u3(pi/2,pi/2,pi/2,q[0]) qc.u3(pi/2,pi/2,pi/2,q[1]) qc.u3(pi/2,pi/2,pi/2,q[1]) qc.draw(output='mpl') job = execute(qc, backend) job.result().get_unitary(qc, decimals=3)
https://github.com/HuangJunye/Qiskit-for-GameDev
HuangJunye
#!/usr/bin/env python # # Copyright 2019 the original author or authors. # # 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 pygame from qiskit import BasicAer, QuantumRegister, ClassicalRegister, QuantumCircuit, execute from qiskit.tools.visualization import plot_histogram from utils import load_image DEFAULT_NUM_SHOTS = 100 class MeasurementsHistogram(pygame.sprite.Sprite): """Displays a histogram with measurements""" def __init__(self, circuit, num_shots=DEFAULT_NUM_SHOTS): pygame.sprite.Sprite.__init__(self) self.image = None self.rect = None self.set_circuit(circuit, num_shots) # def update(self): # # Nothing yet # a = 1 def set_circuit(self, circuit, num_shots=DEFAULT_NUM_SHOTS): backend_sim = BasicAer.get_backend('qasm_simulator') qr = QuantumRegister(circuit.width(), 'q') cr = ClassicalRegister(circuit.width(), 'c') meas_circ = QuantumCircuit(qr, cr) meas_circ.barrier(qr) meas_circ.measure(qr, cr) complete_circuit = circuit + meas_circ job_sim = execute(complete_circuit, backend_sim, shots=num_shots) result_sim = job_sim.result() counts = result_sim.get_counts(complete_circuit) print(counts) histogram = plot_histogram(counts) histogram.savefig("utils/data/bell_histogram.png") self.image, self.rect = load_image('bell_histogram.png', -1) self.image.convert()
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# all portions are stored in a list all_portions = [7,5,4,2,6,1]; # let's calculate the total portion total_portion = 0 for i in range(6): total_portion = total_portion + all_portions[i] print("total portion is",total_portion) # find the weight of one portion one_portion = 1/total_portion print("the weight of one portion is",one_portion) print() # print an empty line # now we can calculate the probabilities of rolling 1,2,3,4,5, and 6 for i in range(6): print("the probability of rolling",(i+1),"is",(one_portion*all_portions[i])) # we will randomly create a probabilistic state # # we should be careful about two things: # 1. a probability value must be between 0 and 1 # 2. the total probability must be 1 # # therefore, we can randomly pick three probability values. # once we have three probability values, the fourth one is determined automatically # the fourth one cannot be arbitrary, because the summation of the four values must be 1 # let's use a list of size 4 # initial values are zeros my_state = [0,0,0,0] # we pick three random probabilistic values from random import randrange # I assume that I have the following total value to distribute to four parts total = 1000 # I will randomly pick a value, and then continue with the remaining value for i in range(3): # let's find the three values pick_a_value = randrange(total) print("I picked",pick_a_value) my_state[i] = pick_a_value total = total - pick_a_value # remaining value for the others my_state[3] = total # this is the remaining value after three iterations print("The remaining value is",total) # let's verify the summation of the elements in my_state sum = 0 print() # print an empty line for i in range(len(my_state)): sum = sum + my_state[i] print("the summation of the elements in my_state is",sum) # let's convert the selected values to the probabilities # we can also call this procedure as **NORMALIZATION** for i in range(len(my_state)): my_state[i] = my_state[i]/1000 print() # print an empty line print("the entries of my probabilistic state:") # let's print all probabilities for i in range(len(my_state)): print(my_state[i])
https://github.com/abbarreto/qiskit3
abbarreto
https://github.com/mtreinish/bqskit-qiskit-synthesis-plugin
mtreinish
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=missing-function-docstring """ Tests for the default UnitarySynthesis transpiler pass. """ from test import combine import unittest import numpy as np from ddt import ddt, data from qiskit import transpile from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider import FakeVigo, FakeMumbaiFractionalCX, FakeBelemV2 from qiskit.providers.fake_provider.fake_backend_v2 import FakeBackendV2, FakeBackend5QV2 from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.circuit.library import QuantumVolume from qiskit.converters import circuit_to_dag, dag_to_circuit from qiskit.transpiler.passes import UnitarySynthesis from qiskit.quantum_info.operators import Operator from qiskit.quantum_info.random import random_unitary from qiskit.transpiler import PassManager, CouplingMap, Target, InstructionProperties from qiskit.transpiler.exceptions import TranspilerError from qiskit.exceptions import QiskitError from qiskit.transpiler.passes import ( Collect2qBlocks, ConsolidateBlocks, Optimize1qGates, SabreLayout, Unroll3qOrMore, CheckMap, BarrierBeforeFinalMeasurements, SabreSwap, TrivialLayout, ) from qiskit.circuit.library import ( IGate, CXGate, RZGate, RXGate, SXGate, XGate, iSwapGate, ECRGate, UGate, ZGate, RYYGate, RZZGate, RXXGate, ) from qiskit.circuit import Measure from qiskit.circuit.controlflow import IfElseOp from qiskit.circuit import Parameter, Gate @ddt class TestUnitarySynthesis(QiskitTestCase): """Test UnitarySynthesis pass.""" def test_empty_basis_gates(self): """Verify when basis_gates is None, we do not synthesize unitaries.""" qc = QuantumCircuit(3) op_1q = random_unitary(2, seed=0) op_2q = random_unitary(4, seed=0) op_3q = random_unitary(8, seed=0) qc.unitary(op_1q.data, [0]) qc.unitary(op_2q.data, [0, 1]) qc.unitary(op_3q.data, [0, 1, 2]) out = UnitarySynthesis(basis_gates=None, min_qubits=2)(qc) self.assertEqual(out.count_ops(), {"unitary": 3}) @data( ["u3", "cx"], ["u1", "u2", "u3", "cx"], ["rx", "ry", "rxx"], ["rx", "rz", "iswap"], ["u3", "rx", "rz", "cz", "iswap"], ) def test_two_qubit_synthesis_to_basis(self, basis_gates): """Verify two qubit unitaries are synthesized to match basis gates.""" bell = QuantumCircuit(2) bell.h(0) bell.cx(0, 1) bell_op = Operator(bell) qc = QuantumCircuit(2) qc.unitary(bell_op, [0, 1]) dag = circuit_to_dag(qc) out = UnitarySynthesis(basis_gates).run(dag) self.assertTrue(set(out.count_ops()).issubset(basis_gates)) def test_two_qubit_synthesis_to_directional_cx_from_gate_errors(self): """Verify two qubit unitaries are synthesized to match basis gates.""" # TODO: should make check more explicit e.g. explicitly set gate # direction in test instead of using specific fake backend backend = FakeVigo() conf = backend.configuration() qr = QuantumRegister(2) coupling_map = CouplingMap(conf.coupling_map) triv_layout_pass = TrivialLayout(coupling_map) qc = QuantumCircuit(qr) qc.unitary(random_unitary(4, seed=12), [0, 1]) unisynth_pass = UnitarySynthesis( basis_gates=conf.basis_gates, coupling_map=None, backend_props=backend.properties(), pulse_optimize=True, natural_direction=False, ) pm = PassManager([triv_layout_pass, unisynth_pass]) qc_out = pm.run(qc) unisynth_pass_nat = UnitarySynthesis( basis_gates=conf.basis_gates, coupling_map=None, backend_props=backend.properties(), pulse_optimize=True, natural_direction=True, ) pm_nat = PassManager([triv_layout_pass, unisynth_pass_nat]) qc_out_nat = pm_nat.run(qc) self.assertEqual(Operator(qc), Operator(qc_out)) self.assertEqual(Operator(qc), Operator(qc_out_nat)) def test_swap_synthesis_to_directional_cx(self): """Verify two qubit unitaries are synthesized to match basis gates.""" # TODO: should make check more explicit e.g. explicitly set gate # direction in test instead of using specific fake backend backend = FakeVigo() conf = backend.configuration() qr = QuantumRegister(2) coupling_map = CouplingMap(conf.coupling_map) triv_layout_pass = TrivialLayout(coupling_map) qc = QuantumCircuit(qr) qc.swap(qr[0], qr[1]) unisynth_pass = UnitarySynthesis( basis_gates=conf.basis_gates, coupling_map=None, backend_props=backend.properties(), pulse_optimize=True, natural_direction=False, ) pm = PassManager([triv_layout_pass, unisynth_pass]) qc_out = pm.run(qc) unisynth_pass_nat = UnitarySynthesis( basis_gates=conf.basis_gates, coupling_map=None, backend_props=backend.properties(), pulse_optimize=True, natural_direction=True, ) pm_nat = PassManager([triv_layout_pass, unisynth_pass_nat]) qc_out_nat = pm_nat.run(qc) self.assertEqual(Operator(qc), Operator(qc_out)) self.assertEqual(Operator(qc), Operator(qc_out_nat)) def test_two_qubit_synthesis_to_directional_cx_multiple_registers(self): """Verify two qubit unitaries are synthesized to match basis gates across multiple registers.""" # TODO: should make check more explicit e.g. explicitly set gate # direction in test instead of using specific fake backend backend = FakeVigo() conf = backend.configuration() qr0 = QuantumRegister(1) qr1 = QuantumRegister(1) coupling_map = CouplingMap(conf.coupling_map) triv_layout_pass = TrivialLayout(coupling_map) qc = QuantumCircuit(qr0, qr1) qc.unitary(random_unitary(4, seed=12), [qr0[0], qr1[0]]) unisynth_pass = UnitarySynthesis( basis_gates=conf.basis_gates, coupling_map=None, backend_props=backend.properties(), pulse_optimize=True, natural_direction=False, ) pm = PassManager([triv_layout_pass, unisynth_pass]) qc_out = pm.run(qc) unisynth_pass_nat = UnitarySynthesis( basis_gates=conf.basis_gates, coupling_map=None, backend_props=backend.properties(), pulse_optimize=True, natural_direction=True, ) pm_nat = PassManager([triv_layout_pass, unisynth_pass_nat]) qc_out_nat = pm_nat.run(qc) self.assertEqual(Operator(qc), Operator(qc_out)) self.assertEqual(Operator(qc), Operator(qc_out_nat)) def test_two_qubit_synthesis_to_directional_cx_from_coupling_map(self): """Verify natural cx direction is used when specified in coupling map.""" # TODO: should make check more explicit e.g. explicitly set gate # direction in test instead of using specific fake backend backend = FakeVigo() conf = backend.configuration() qr = QuantumRegister(2) coupling_map = CouplingMap([[0, 1], [1, 2], [1, 3], [3, 4]]) triv_layout_pass = TrivialLayout(coupling_map) qc = QuantumCircuit(qr) qc.unitary(random_unitary(4, seed=12), [0, 1]) unisynth_pass = UnitarySynthesis( basis_gates=conf.basis_gates, coupling_map=coupling_map, backend_props=backend.properties(), pulse_optimize=True, natural_direction=False, ) pm = PassManager([triv_layout_pass, unisynth_pass]) qc_out = pm.run(qc) unisynth_pass_nat = UnitarySynthesis( basis_gates=conf.basis_gates, coupling_map=coupling_map, backend_props=backend.properties(), pulse_optimize=True, natural_direction=True, ) pm_nat = PassManager([triv_layout_pass, unisynth_pass_nat]) qc_out_nat = pm_nat.run(qc) # the decomposer defaults to the [1, 0] direction but the coupling # map specifies a [0, 1] direction. Check that this is respected. self.assertTrue( all(((qr[1], qr[0]) == instr.qubits for instr in qc_out.get_instructions("cx"))) ) self.assertTrue( all(((qr[0], qr[1]) == instr.qubits for instr in qc_out_nat.get_instructions("cx"))) ) self.assertEqual(Operator(qc), Operator(qc_out)) self.assertEqual(Operator(qc), Operator(qc_out_nat)) def test_two_qubit_synthesis_to_directional_cx_from_coupling_map_natural_none(self): """Verify natural cx direction is used when specified in coupling map when natural_direction is None.""" # TODO: should make check more explicit e.g. explicitly set gate # direction in test instead of using specific fake backend backend = FakeVigo() conf = backend.configuration() qr = QuantumRegister(2) coupling_map = CouplingMap([[0, 1], [1, 2], [1, 3], [3, 4]]) triv_layout_pass = TrivialLayout(coupling_map) qc = QuantumCircuit(qr) qc.unitary(random_unitary(4, seed=12), [0, 1]) unisynth_pass = UnitarySynthesis( basis_gates=conf.basis_gates, coupling_map=coupling_map, backend_props=backend.properties(), pulse_optimize=True, natural_direction=False, ) pm = PassManager([triv_layout_pass, unisynth_pass]) qc_out = pm.run(qc) unisynth_pass_nat = UnitarySynthesis( basis_gates=conf.basis_gates, coupling_map=coupling_map, backend_props=backend.properties(), pulse_optimize=True, natural_direction=None, ) pm_nat = PassManager([triv_layout_pass, unisynth_pass_nat]) qc_out_nat = pm_nat.run(qc) # the decomposer defaults to the [1, 0] direction but the coupling # map specifies a [0, 1] direction. Check that this is respected. self.assertTrue( all(((qr[1], qr[0]) == instr.qubits for instr in qc_out.get_instructions("cx"))) ) self.assertTrue( all(((qr[0], qr[1]) == instr.qubits for instr in qc_out_nat.get_instructions("cx"))) ) self.assertEqual(Operator(qc), Operator(qc_out)) self.assertEqual(Operator(qc), Operator(qc_out_nat)) def test_two_qubit_synthesis_to_directional_cx_from_coupling_map_natural_false(self): """Verify natural cx direction is used when specified in coupling map when natural_direction is None.""" # TODO: should make check more explicit e.g. explicitly set gate # direction in test instead of using specific fake backend backend = FakeVigo() conf = backend.configuration() qr = QuantumRegister(2) coupling_map = CouplingMap([[0, 1], [1, 2], [1, 3], [3, 4]]) triv_layout_pass = TrivialLayout(coupling_map) qc = QuantumCircuit(qr) qc.unitary(random_unitary(4, seed=12), [0, 1]) unisynth_pass = UnitarySynthesis( basis_gates=conf.basis_gates, coupling_map=coupling_map, backend_props=backend.properties(), pulse_optimize=True, natural_direction=False, ) pm = PassManager([triv_layout_pass, unisynth_pass]) qc_out = pm.run(qc) unisynth_pass_nat = UnitarySynthesis( basis_gates=conf.basis_gates, coupling_map=coupling_map, backend_props=backend.properties(), pulse_optimize=True, natural_direction=False, ) pm_nat = PassManager([triv_layout_pass, unisynth_pass_nat]) qc_out_nat = pm_nat.run(qc) # the decomposer defaults to the [1, 0] direction but the coupling # map specifies a [0, 1] direction. Check that this is respected. self.assertTrue( all(((qr[1], qr[0]) == instr.qubits for instr in qc_out.get_instructions("cx"))) ) self.assertTrue( all(((qr[1], qr[0]) == instr.qubits for instr in qc_out_nat.get_instructions("cx"))) ) self.assertEqual(Operator(qc), Operator(qc_out)) self.assertEqual(Operator(qc), Operator(qc_out_nat)) def test_two_qubit_synthesis_not_pulse_optimal(self): """Verify not attempting pulse optimal decomposition when pulse_optimize==False.""" backend = FakeVigo() conf = backend.configuration() qr = QuantumRegister(2) coupling_map = CouplingMap([[0, 1], [1, 2], [1, 3], [3, 4]]) triv_layout_pass = TrivialLayout(coupling_map) qc = QuantumCircuit(qr) qc.unitary(random_unitary(4, seed=12), [0, 1]) unisynth_pass = UnitarySynthesis( basis_gates=conf.basis_gates, coupling_map=coupling_map, backend_props=backend.properties(), pulse_optimize=False, natural_direction=True, ) pm = PassManager([triv_layout_pass, unisynth_pass]) qc_out = pm.run(qc) if isinstance(qc_out, QuantumCircuit): num_ops = qc_out.count_ops() else: num_ops = qc_out[0].count_ops() self.assertIn("sx", num_ops) self.assertGreaterEqual(num_ops["sx"], 16) def test_two_qubit_pulse_optimal_true_raises(self): """Verify raises if pulse optimal==True but cx is not in the backend basis.""" backend = FakeVigo() conf = backend.configuration() # this assumes iswawp pulse optimal decomposition doesn't exist conf.basis_gates = [gate if gate != "cx" else "iswap" for gate in conf.basis_gates] qr = QuantumRegister(2) coupling_map = CouplingMap([[0, 1], [1, 2], [1, 3], [3, 4]]) triv_layout_pass = TrivialLayout(coupling_map) qc = QuantumCircuit(qr) qc.unitary(random_unitary(4, seed=12), [0, 1]) unisynth_pass = UnitarySynthesis( basis_gates=conf.basis_gates, coupling_map=coupling_map, backend_props=backend.properties(), pulse_optimize=True, natural_direction=True, ) pm = PassManager([triv_layout_pass, unisynth_pass]) with self.assertRaises(QiskitError): pm.run(qc) def test_two_qubit_natural_direction_true_duration_fallback(self): """Verify not attempting pulse optimal decomposition when pulse_optimize==False.""" # this assumes iswawp pulse optimal decomposition doesn't exist backend = FakeVigo() conf = backend.configuration() # conf.basis_gates = [gate if gate != "cx" else "iswap" for gate in conf.basis_gates] qr = QuantumRegister(2) coupling_map = CouplingMap([[0, 1], [1, 0], [1, 2], [1, 3], [3, 4]]) triv_layout_pass = TrivialLayout(coupling_map) qc = QuantumCircuit(qr) qc.unitary(random_unitary(4, seed=12), [0, 1]) unisynth_pass = UnitarySynthesis( basis_gates=conf.basis_gates, coupling_map=coupling_map, backend_props=backend.properties(), pulse_optimize=True, natural_direction=True, ) pm = PassManager([triv_layout_pass, unisynth_pass]) qc_out = pm.run(qc) self.assertTrue( all(((qr[0], qr[1]) == instr.qubits for instr in qc_out.get_instructions("cx"))) ) def test_two_qubit_natural_direction_true_gate_length_raises(self): """Verify not attempting pulse optimal decomposition when pulse_optimize==False.""" # this assumes iswawp pulse optimal decomposition doesn't exist backend = FakeVigo() conf = backend.configuration() for _, nduv in backend.properties()._gates["cx"].items(): nduv["gate_length"] = (4e-7, nduv["gate_length"][1]) nduv["gate_error"] = (7e-3, nduv["gate_error"][1]) qr = QuantumRegister(2) coupling_map = CouplingMap([[0, 1], [1, 0], [1, 2], [1, 3], [3, 4]]) triv_layout_pass = TrivialLayout(coupling_map) qc = QuantumCircuit(qr) qc.unitary(random_unitary(4, seed=12), [0, 1]) unisynth_pass = UnitarySynthesis( basis_gates=conf.basis_gates, backend_props=backend.properties(), pulse_optimize=True, natural_direction=True, ) pm = PassManager([triv_layout_pass, unisynth_pass]) with self.assertRaises(TranspilerError): pm.run(qc) def test_two_qubit_pulse_optimal_none_optimal(self): """Verify pulse optimal decomposition when pulse_optimize==None.""" # this assumes iswawp pulse optimal decomposition doesn't exist backend = FakeVigo() conf = backend.configuration() qr = QuantumRegister(2) coupling_map = CouplingMap([[0, 1], [1, 2], [1, 3], [3, 4]]) triv_layout_pass = TrivialLayout(coupling_map) qc = QuantumCircuit(qr) qc.unitary(random_unitary(4, seed=12), [0, 1]) unisynth_pass = UnitarySynthesis( basis_gates=conf.basis_gates, coupling_map=coupling_map, backend_props=backend.properties(), pulse_optimize=None, natural_direction=True, ) pm = PassManager([triv_layout_pass, unisynth_pass]) qc_out = pm.run(qc) if isinstance(qc_out, QuantumCircuit): num_ops = qc_out.count_ops() else: num_ops = qc_out[0].count_ops() self.assertIn("sx", num_ops) self.assertLessEqual(num_ops["sx"], 12) def test_two_qubit_pulse_optimal_none_no_raise(self): """Verify pulse optimal decomposition when pulse_optimize==None doesn't raise when pulse optimal decomposition unknown.""" # this assumes iswawp pulse optimal decomposition doesn't exist backend = FakeVigo() conf = backend.configuration() conf.basis_gates = [gate if gate != "cx" else "iswap" for gate in conf.basis_gates] qr = QuantumRegister(2) coupling_map = CouplingMap([[0, 1], [1, 2], [1, 3], [3, 4]]) triv_layout_pass = TrivialLayout(coupling_map) qc = QuantumCircuit(qr) qc.unitary(random_unitary(4, seed=12), [0, 1]) unisynth_pass = UnitarySynthesis( basis_gates=conf.basis_gates, coupling_map=coupling_map, backend_props=backend.properties(), pulse_optimize=None, natural_direction=True, ) pm = PassManager([triv_layout_pass, unisynth_pass]) try: qc_out = pm.run(qc) except QiskitError: self.fail("pulse_optimize=None raised exception unexpectedly") if isinstance(qc_out, QuantumCircuit): num_ops = qc_out.count_ops() else: num_ops = qc_out[0].count_ops() self.assertIn("sx", num_ops) self.assertLessEqual(num_ops["sx"], 14) def test_qv_natural(self): """check that quantum volume circuit compiles for natural direction""" qv64 = QuantumVolume(5, seed=15) def construct_passmanager(basis_gates, coupling_map, synthesis_fidelity, pulse_optimize): seed = 2 _map = [SabreLayout(coupling_map, max_iterations=2, seed=seed)] _unroll3q = Unroll3qOrMore() _swap_check = CheckMap(coupling_map) _swap = [ BarrierBeforeFinalMeasurements(), SabreSwap(coupling_map, heuristic="lookahead", seed=seed), ] _optimize = [ Collect2qBlocks(), ConsolidateBlocks(basis_gates=basis_gates), UnitarySynthesis( basis_gates, synthesis_fidelity, coupling_map, pulse_optimize=pulse_optimize, natural_direction=True, ), Optimize1qGates(basis_gates), ] pm = PassManager() pm.append(_map) # map to hardware by inserting swaps pm.append(_unroll3q) pm.append(_swap_check) pm.append(_swap) pm.append(_optimize) return pm coupling_map = CouplingMap([[0, 1], [1, 2], [3, 2], [3, 4], [5, 4]]) basis_gates = ["rz", "sx", "cx"] pm1 = construct_passmanager( basis_gates=basis_gates, coupling_map=coupling_map, synthesis_fidelity=0.99, pulse_optimize=True, ) pm2 = construct_passmanager( basis_gates=basis_gates, coupling_map=coupling_map, synthesis_fidelity=0.99, pulse_optimize=False, ) qv64_1 = pm1.run(qv64.decompose()) qv64_2 = pm2.run(qv64.decompose()) edges = [list(edge) for edge in coupling_map.get_edges()] self.assertTrue( all( [qv64_1.qubits.index(qubit) for qubit in instr.qubits] in edges for instr in qv64_1.get_instructions("cx") ) ) self.assertEqual(Operator(qv64_1), Operator(qv64_2)) @data(1, 2, 3) def test_coupling_map_transpile(self, opt): """test natural_direction works with transpile/execute""" qr = QuantumRegister(2) circ = QuantumCircuit(qr) circ.append(random_unitary(4, seed=1), [0, 1]) circ_01 = transpile( circ, basis_gates=["rz", "sx", "cx"], optimization_level=opt, coupling_map=[[0, 1]] ) circ_10 = transpile( circ, basis_gates=["rz", "sx", "cx"], optimization_level=opt, coupling_map=[[1, 0]] ) circ_01_index = {qubit: index for index, qubit in enumerate(circ_01.qubits)} circ_10_index = {qubit: index for index, qubit in enumerate(circ_10.qubits)} self.assertTrue( all( ( (1, 0) == (circ_10_index[instr.qubits[0]], circ_10_index[instr.qubits[1]]) for instr in circ_10.get_instructions("cx") ) ) ) self.assertTrue( all( ( (0, 1) == (circ_01_index[instr.qubits[0]], circ_01_index[instr.qubits[1]]) for instr in circ_01.get_instructions("cx") ) ) ) @combine( opt_level=[0, 1, 2, 3], bidirectional=[True, False], dsc=( "test natural_direction works with transpile using opt_level {opt_level} on" " target with multiple 2q gates with bidirectional={bidirectional}" ), name="opt_level_{opt_level}_bidirectional_{bidirectional}", ) def test_coupling_map_transpile_with_backendv2(self, opt_level, bidirectional): backend = FakeBackend5QV2(bidirectional) qr = QuantumRegister(2) circ = QuantumCircuit(qr) circ.append(random_unitary(4, seed=1), [0, 1]) circ_01 = transpile( circ, backend=backend, optimization_level=opt_level, layout_method="trivial" ) circ_01_index = {qubit: index for index, qubit in enumerate(circ_01.qubits)} self.assertGreaterEqual(len(circ_01.get_instructions("cx")), 1) for instr in circ_01.get_instructions("cx"): self.assertEqual( (0, 1), (circ_01_index[instr.qubits[0]], circ_01_index[instr.qubits[1]]) ) @data(1, 2, 3) def test_coupling_map_unequal_durations(self, opt): """Test direction with transpile/execute with backend durations.""" qr = QuantumRegister(2) circ = QuantumCircuit(qr) circ.append(random_unitary(4, seed=1), [1, 0]) backend = FakeVigo() tqc = transpile( circ, backend=backend, optimization_level=opt, translation_method="synthesis", layout_method="trivial", ) tqc_index = {qubit: index for index, qubit in enumerate(tqc.qubits)} self.assertTrue( all( ( (0, 1) == (tqc_index[instr.qubits[0]], tqc_index[instr.qubits[1]]) for instr in tqc.get_instructions("cx") ) ) ) @combine( opt_level=[0, 1, 2, 3], bidirectional=[True, False], dsc=( "Test direction with transpile using opt_level {opt_level} on" " target with multiple 2q gates with bidirectional={bidirectional}" "direction [0, 1] is lower error and should be picked." ), name="opt_level_{opt_level}_bidirectional_{bidirectional}", ) def test_coupling_unequal_duration_with_backendv2(self, opt_level, bidirectional): qr = QuantumRegister(2) circ = QuantumCircuit(qr) circ.append(random_unitary(4, seed=1), [1, 0]) backend = FakeBackend5QV2(bidirectional) tqc = transpile( circ, backend=backend, optimization_level=opt_level, translation_method="synthesis", layout_method="trivial", ) tqc_index = {qubit: index for index, qubit in enumerate(tqc.qubits)} self.assertGreaterEqual(len(tqc.get_instructions("cx")), 1) for instr in tqc.get_instructions("cx"): self.assertEqual((0, 1), (tqc_index[instr.qubits[0]], tqc_index[instr.qubits[1]])) @combine( opt_level=[0, 1, 2, 3], dsc=( "Test direction with transpile using opt_level {opt_level} on" " target with multiple 2q gates" ), name="opt_level_{opt_level}", ) def test_non_overlapping_kak_gates_with_backendv2(self, opt_level): qr = QuantumRegister(2) circ = QuantumCircuit(qr) circ.append(random_unitary(4, seed=1), [1, 0]) backend = FakeBackendV2() tqc = transpile( circ, backend=backend, optimization_level=opt_level, translation_method="synthesis", layout_method="trivial", ) tqc_index = {qubit: index for index, qubit in enumerate(tqc.qubits)} self.assertGreaterEqual(len(tqc.get_instructions("ecr")), 1) for instr in tqc.get_instructions("ecr"): self.assertEqual((1, 0), (tqc_index[instr.qubits[0]], tqc_index[instr.qubits[1]])) def test_fractional_cx_with_backendv2(self): """Test fractional CX gets used if present in target.""" qr = QuantumRegister(2) circ = QuantumCircuit(qr) circ.append(random_unitary(4, seed=1), [0, 1]) backend = FakeMumbaiFractionalCX() synth_pass = UnitarySynthesis(target=backend.target) tqc = synth_pass(circ) tqc_index = {qubit: index for index, qubit in enumerate(tqc.qubits)} self.assertGreaterEqual(len(tqc.get_instructions("rzx")), 1) for instr in tqc.get_instructions("rzx"): self.assertEqual((0, 1), (tqc_index[instr.qubits[0]], tqc_index[instr.qubits[1]])) @combine( opt_level=[0, 1, 2, 3], dsc=( "Test direction with transpile using opt_level {opt_level} on" "target with multiple 2q gates available in reverse direction" ), name="opt_level_{opt_level}", ) def test_reverse_direction(self, opt_level): target = Target(2) target.add_instruction(CXGate(), {(0, 1): InstructionProperties(error=1.2e-6)}) target.add_instruction(ECRGate(), {(0, 1): InstructionProperties(error=1.2e-7)}) target.add_instruction( UGate(Parameter("theta"), Parameter("phi"), Parameter("lam")), {(0,): None, (1,): None} ) qr = QuantumRegister(2) circ = QuantumCircuit(qr) circ.append(random_unitary(4, seed=1), [1, 0]) tqc = transpile( circ, target=target, optimization_level=opt_level, translation_method="synthesis", layout_method="trivial", ) tqc_index = {qubit: index for index, qubit in enumerate(tqc.qubits)} self.assertGreaterEqual(len(tqc.get_instructions("ecr")), 1) for instr in tqc.get_instructions("ecr"): self.assertEqual((0, 1), (tqc_index[instr.qubits[0]], tqc_index[instr.qubits[1]])) @combine( opt_level=[0, 1, 2, 3], dsc=("Test controlled but not supercontrolled basis"), name="opt_level_{opt_level}", ) def test_controlled_basis(self, opt_level): target = Target(2) target.add_instruction(RYYGate(np.pi / 8), {(0, 1): InstructionProperties(error=1.2e-6)}) target.add_instruction( UGate(Parameter("theta"), Parameter("phi"), Parameter("lam")), {(0,): None, (1,): None} ) qr = QuantumRegister(2) circ = QuantumCircuit(qr) circ.append(random_unitary(4, seed=1), [1, 0]) tqc = transpile( circ, target=target, optimization_level=opt_level, translation_method="synthesis", layout_method="trivial", ) self.assertGreaterEqual(len(tqc.get_instructions("ryy")), 1) self.assertEqual(Operator(tqc), Operator(circ)) def test_approximation_controlled(self): target = Target(2) target.add_instruction(RZZGate(np.pi / 10), {(0, 1): InstructionProperties(error=0.006)}) target.add_instruction(RXXGate(np.pi / 3), {(0, 1): InstructionProperties(error=0.01)}) target.add_instruction( UGate(Parameter("theta"), Parameter("phi"), Parameter("lam")), {(0,): InstructionProperties(error=0.001), (1,): InstructionProperties(error=0.002)}, ) circ = QuantumCircuit(2) circ.append(random_unitary(4, seed=7), [1, 0]) dag = circuit_to_dag(circ) dag_100 = UnitarySynthesis(target=target, approximation_degree=1.0).run(dag) dag_99 = UnitarySynthesis(target=target, approximation_degree=0.99).run(dag) self.assertGreaterEqual(dag_100.depth(), dag_99.depth()) self.assertEqual(Operator(dag_to_circuit(dag_100)), Operator(circ)) def test_if_simple(self): """Test a simple if statement.""" basis_gates = {"u", "cx"} qr = QuantumRegister(2) cr = ClassicalRegister(2) qc_uni = QuantumCircuit(2) qc_uni.h(0) qc_uni.cx(0, 1) qc_uni_mat = Operator(qc_uni) qc_true_body = QuantumCircuit(2) qc_true_body.unitary(qc_uni_mat, [0, 1]) qc = QuantumCircuit(qr, cr) qc.if_test((cr, 1), qc_true_body, [0, 1], []) dag = circuit_to_dag(qc) cdag = UnitarySynthesis(basis_gates=basis_gates).run(dag) cqc = dag_to_circuit(cdag) cbody = cqc.data[0].operation.params[0] self.assertEqual(cbody.count_ops().keys(), basis_gates) self.assertEqual(qc_uni_mat, Operator(cbody)) def test_nested_control_flow(self): """Test unrolling nested control flow blocks.""" qr = QuantumRegister(2) cr = ClassicalRegister(1) qc_uni1 = QuantumCircuit(2) qc_uni1.swap(0, 1) qc_uni1_mat = Operator(qc_uni1) qc = QuantumCircuit(qr, cr) with qc.for_loop(range(3)): with qc.while_loop((cr, 0)): qc.unitary(qc_uni1_mat, [0, 1]) dag = circuit_to_dag(qc) cdag = UnitarySynthesis(basis_gates=["u", "cx"]).run(dag) cqc = dag_to_circuit(cdag) cbody = cqc.data[0].operation.params[2].data[0].operation.params[0] self.assertEqual(cbody.count_ops().keys(), {"u", "cx"}) self.assertEqual(qc_uni1_mat, Operator(cbody)) def test_mapping_control_flow(self): """Test that inner dags use proper qubit mapping.""" qr = QuantumRegister(3, "q") qc = QuantumCircuit(qr) # Create target that supports CX only between 0 and 2. fake_target = Target() fake_target.add_instruction(CXGate(), {(0, 2): None}) fake_target.add_instruction( UGate(Parameter("t"), Parameter("p"), Parameter("l")), { (0,): None, (1,): None, (2,): None, }, ) qc_uni1 = QuantumCircuit(2) qc_uni1.swap(0, 1) qc_uni1_mat = Operator(qc_uni1) loop_body = QuantumCircuit(2) loop_body.unitary(qc_uni1_mat, [0, 1]) # Loop body uses qubits 0 and 2, mapped to 0 and 1 in the block. # If synthesis doesn't handle recursive mapping, it'll incorrectly # look for a CX on (0, 1) instead of on (0, 2). qc.for_loop((0,), None, loop_body, [0, 2], []) dag = circuit_to_dag(qc) UnitarySynthesis(basis_gates=["u", "cx"], target=fake_target).run(dag) def test_single_qubit_with_target(self): """Test input circuit with only 1q works with target.""" qc = QuantumCircuit(1) qc.append(ZGate(), [qc.qubits[0]]) dag = circuit_to_dag(qc) unitary_synth_pass = UnitarySynthesis(target=FakeBelemV2().target) result_dag = unitary_synth_pass.run(dag) result_qc = dag_to_circuit(result_dag) self.assertEqual(qc, result_qc) def test_single_qubit_identity_with_target(self): """Test input single qubit identity works with target.""" qc = QuantumCircuit(1) qc.unitary([[1.0, 0.0], [0.0, 1.0]], 0) dag = circuit_to_dag(qc) unitary_synth_pass = UnitarySynthesis(target=FakeBelemV2().target) result_dag = unitary_synth_pass.run(dag) result_qc = dag_to_circuit(result_dag) self.assertEqual(result_qc, QuantumCircuit(1)) def test_unitary_synthesis_with_ideal_and_variable_width_ops(self): """Test unitary synthesis works with a target that contains ideal and variadic ops.""" qc = QuantumCircuit(2) qc.unitary(np.eye(4), [0, 1]) dag = circuit_to_dag(qc) target = FakeBelemV2().target target.add_instruction(IfElseOp, name="if_else") target.add_instruction(ZGate()) target.add_instruction(ECRGate()) unitary_synth_pass = UnitarySynthesis(target=target) result_dag = unitary_synth_pass.run(dag) result_qc = dag_to_circuit(result_dag) self.assertEqual(result_qc, QuantumCircuit(2)) def test_unitary_synthesis_custom_gate_target(self): qc = QuantumCircuit(2) qc.unitary(np.eye(4), [0, 1]) dag = circuit_to_dag(qc) class CustomGate(Gate): """Custom Opaque Gate""" def __init__(self): super().__init__("custom", 2, []) target = Target(num_qubits=2) target.add_instruction( UGate(Parameter("t"), Parameter("p"), Parameter("l")), {(0,): None, (1,): None} ) target.add_instruction(CustomGate(), {(0, 1): None, (1, 0): None}) unitary_synth_pass = UnitarySynthesis(target=target) result_dag = unitary_synth_pass.run(dag) result_qc = dag_to_circuit(result_dag) self.assertEqual(result_qc, qc) def test_default_does_not_fail_on_no_syntheses(self): qc = QuantumCircuit(1) qc.unitary(np.eye(2), [0]) pass_ = UnitarySynthesis(["unknown", "gates"]) self.assertEqual(qc, pass_(qc)) def test_iswap_no_cx_synthesis_succeeds(self): """Test basis set with iswap but no cx can synthesize a circuit""" target = Target() theta = Parameter("theta") i_props = { (0,): InstructionProperties(duration=35.5e-9, error=0.000413), (1,): InstructionProperties(duration=35.5e-9, error=0.000502), } target.add_instruction(IGate(), i_props) rz_props = { (0,): InstructionProperties(duration=0, error=0), (1,): InstructionProperties(duration=0, error=0), } target.add_instruction(RZGate(theta), rz_props) sx_props = { (0,): InstructionProperties(duration=35.5e-9, error=0.000413), (1,): InstructionProperties(duration=35.5e-9, error=0.000502), } target.add_instruction(SXGate(), sx_props) x_props = { (0,): InstructionProperties(duration=35.5e-9, error=0.000413), (1,): InstructionProperties(duration=35.5e-9, error=0.000502), } target.add_instruction(XGate(), x_props) iswap_props = { (0, 1): InstructionProperties(duration=519.11e-9, error=0.01201), (1, 0): InstructionProperties(duration=554.66e-9, error=0.01201), } target.add_instruction(iSwapGate(), iswap_props) measure_props = { (0,): InstructionProperties(duration=5.813e-6, error=0.0751), (1,): InstructionProperties(duration=5.813e-6, error=0.0225), } target.add_instruction(Measure(), measure_props) qc = QuantumCircuit(2) cxmat = Operator(CXGate()).to_matrix() qc.unitary(cxmat, [0, 1]) unitary_synth_pass = UnitarySynthesis(target=target) dag = circuit_to_dag(qc) result_dag = unitary_synth_pass.run(dag) result_qc = dag_to_circuit(result_dag) self.assertTrue(np.allclose(Operator(result_qc.to_gate()).to_matrix(), cxmat)) def test_parameterized_basis_gate_in_target(self): """Test synthesis with parameterized RXX gate.""" theta = Parameter("θ") lam = Parameter("λ") target = Target(num_qubits=2) target.add_instruction(RZGate(lam)) target.add_instruction(RXGate(theta)) target.add_instruction(RXXGate(theta)) qc = QuantumCircuit(2) qc.cp(np.pi / 2, 0, 1) qc_transpiled = transpile(qc, target=target, optimization_level=3, seed_transpiler=42) opcount = qc_transpiled.count_ops() self.assertTrue(set(opcount).issubset({"rz", "rx", "rxx"})) self.assertTrue(np.allclose(Operator(qc_transpiled), Operator(qc))) if __name__ == "__main__": unittest.main()
https://github.com/liyaochong/quantum-algorithm-learning-and-implementation
liyaochong
%matplotlib inline from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute from qiskit import BasicAer import math # 设置寄存器中的量子位的数量 n = 4 # 第一寄存器 m = 1 # 第二寄存器 # 用n个量子位创建一个量子寄存器 q = QuantumRegister(n+m, 'q') # 在q寄存器上创建一个量子电路 register = QuantumCircuit(q) # j=3,2,1,0 for j in range(n-1,-1,-1): register.h(q[j]) register.cu1(math.pi/2,q[2],q[3],q[1]) # 实际上是一个受控相位操作,能够看做一个单比特操作;相应电路见小黄书P165 register.u1(math.pi/float(2**(j)), q[j]) for j in range(n): for k in range(j): register.cu1(-math.pi/float(2**(j-k)), q[j], q[k]) register.h(q[j]) def swap(qc, q, i, j): qc.cx(q[i], q[j]) qc.cx(q[j], q[i]) qc.cx(q[i], q[j]) if n%2==1: for i in range(int((n-1)/2)): swap(register, q, i, n-i-1) else: for i in range(int(n/2)): swap(register, q, i, n-i-1) register.draw(output="mpl") # Create a Classical Register with n bits. c = ClassicalRegister(n+m, 'c') # Create a Quantum Circuit measure = QuantumCircuit(q, c) measure.barrier(q) # map the quantum measurement to the classical bits measure.measure(q,c) # The Qiskit circuit object supports composition using # the addition operator. qc = register+measure #drawing the circuit qc.draw(output="mpl") # Use Aer's qasm_simulator backend_sim = BasicAer.get_backend('qasm_simulator') # 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 = execute(qc, backend_sim, shots=1024) # Grab the results from the job. result_sim = job_sim.result() counts = result_sim.get_counts(qc) print(counts) from qiskit.tools.visualization import plot_histogram plot_histogram(result_sim.get_counts(qc)) import numpy as np 1.38148766/(2*np.sqrt(2))
https://github.com/acfilok96/Quantum-Computation
acfilok96
from qiskit import * qr = QuantumRegister(2) cr = ClassicalRegister(2) circuit = QuantumCircuit(qr, cr) %matplotlib inline circuit.draw(output='mpl') circuit.h(qr[0]) circuit.draw(output = 'mpl') circuit.cx(qr[0], qr[1]) circuit.draw(output='mpl') circuit.measure(qr, cr) circuit.draw(output='mpl') simulator = Aer.get_backend('qasm_simulator') execute(circuit, backend=simulator) result = execute(circuit, backend=simulator).result() from qiskit.tools.visualization import plot_histogram plot_histogram(result.get_counts(circuit)) from qiskit import IBMQ MY_API_TOKEN = "b32678329f7f6dd426b8cf18f20bea23c2cd056b0bee2b4bcf49744b612e598f20f7170a8da4bfd99b009b6fa59d596edea7a6926fd388be158843d8e******" IBMQ.save_account(MY_API_TOKEN, overwrite=True) IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main') provider.backends() backend = provider.get_backend('ibmq_santiago') job =execute(circuit, backend= backend) from qiskit.tools.monitor import job_monitor job_monitor(job) result = job.result() # plot_histogram plot_histogram(result.get_counts(circuit))
https://github.com/esquivelgor/Quantum-Route-Minimizer
esquivelgor
# Importing standard Qiskit libraries from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import Aer, assemble from qiskit.visualization import plot_histogram, plot_bloch_multivector, plot_state_qsphere, plot_state_city, plot_state_paulivec, plot_state_hinton # Ignore warnings import warnings warnings.filterwarnings('ignore') # Define backend sim = Aer.get_backend('aer_simulator') def createBellStates(inp1, inp2): qc = QuantumCircuit(2) qc.reset(range(2)) if inp1=='1': qc.x(0) if inp2=='1': qc.x(1) qc.barrier() qc.h(0) qc.cx(0,1) qc.save_statevector() qobj = assemble(qc) result = sim.run(qobj).result() state = result.get_statevector() return qc, state, result print('Note: Since these qubits are in entangled state, their state cannot be written as two separate qubit states. This also means that we lose information when we try to plot our state on separate Bloch spheres as seen below.\n') inp1 = 0 inp2 = 1 qc, state, result = createBellStates(inp1, inp2) display(plot_bloch_multivector(state)) # Uncomment below code in order to explore other states #for inp2 in ['0', '1']: #for inp1 in ['0', '1']: #qc, state, result = createBellStates(inp1, inp2) #print('For inputs',inp2,inp1,'Representation of Entangled States are:') # Uncomment any of the below functions to visualize the resulting quantum states # Draw the quantum circuit #display(qc.draw()) # Plot states on QSphere #display(plot_state_qsphere(state)) # Plot states on Bloch Multivector #display(plot_bloch_multivector(state)) # Plot histogram #display(plot_histogram(result.get_counts())) # Plot state matrix like a city #display(plot_state_city(state)) # Represent state matix using Pauli operators as the basis #display(plot_state_paulivec(state)) # Plot state matrix as Hinton representation #display(plot_state_hinton(state)) #print('\n')''' from qiskit import IBMQ, execute from qiskit.providers.ibmq import least_busy from qiskit.tools import job_monitor # Loading your IBM Quantum account(s) provider = IBMQ.load_account() backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational==True)) def createBSRealDevice(inp1, inp2): qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) qc.reset(range(2)) if inp1 == 1: qc.x(0) if inp2 == 1: qc.x(1) qc.barrier() qc.h(0) qc.cx(0,1) qc.measure(qr, cr) job = execute(qc, backend=backend, shots=100) job_monitor(job) result = job.result() return qc, result inp1 = 0 inp2 = 0 print('For inputs',inp2,inp1,'Representation of Entangled States are,') #first results qc, first_result = createBSRealDevice(inp1, inp2) first_counts = first_result.get_counts() # Draw the quantum circuit display(qc.draw()) #second results qc, second_result = createBSRealDevice(inp1, inp2) second_counts = second_result.get_counts() # Plot results on histogram with legend legend = ['First execution', 'Second execution'] plot_histogram([first_counts, second_counts], legend=legend) def ghzCircuit(inp1, inp2, inp3): qc = QuantumCircuit(3) qc.reset(range(3)) if inp1 == 1: qc.x(0) if inp2 == 1: qc.x(1) if inp3 == 1: qc.x(2) qc.barrier() qc.h(0) qc.cx(0,1) qc.cx(0,2) qc.save_statevector() qobj = assemble(qc) result = sim.run(qobj).result() state = result.get_statevector() return qc, state, result print('Note: Since these qubits are in entangled state, their state cannot be written as two separate qubit states. This also means that we lose information when we try to plot our state on separate Bloch spheres as seen below.\n') inp1 = 0 inp2 = 1 inp3 = 1 qc, state, result = ghzCircuit(inp1, inp2, inp3) display(plot_bloch_multivector(state)) # Uncomment below code in order to explore other states #for inp3 in ['0','1']: #for inp2 in ['0','1']: #for inp1 in ['0','1']: #qc, state, result = ghzCircuit(inp1, inp2, inp3) #print('For inputs',inp3,inp2,inp1,'Representation of GHZ States are:') # Uncomment any of the below functions to visualize the resulting quantum states # Draw the quantum circuit #display(qc.draw()) # Plot states on QSphere #display(plot_state_qsphere(state)) # Plot states on Bloch Multivector #display(plot_bloch_multivector(state)) # Plot histogram #display(plot_histogram(result.get_counts())) # Plot state matrix like a city #display(plot_state_city(state)) # Represent state matix using Pauli operators as the basis #display(plot_state_paulivec(state)) # Plot state matrix as Hinton representation #display(plot_state_hinton(state)) #print('\n') def ghz5QCircuit(inp1, inp2, inp3, inp4, inp5): qc = QuantumCircuit(5) #qc.reset(range(5)) if inp1 == 1: qc.x(0) if inp2 == 1: qc.x(1) if inp3 == 1: qc.x(2) if inp4 == 1: qc.x(3) if inp5 == 1: qc.x(4) qc.barrier() qc.h(0) qc.cx(0,1) qc.cx(0,2) qc.cx(0,3) qc.cx(0,4) qc.save_statevector() qobj = assemble(qc) result = sim.run(qobj).result() state = result.get_statevector() return qc, state, result # Explore GHZ States for input 00010. Note: the input has been stated in little-endian format. inp1 = 0 inp2 = 1 inp3 = 0 inp4 = 0 inp5 = 0 qc, state, result = ghz5QCircuit(inp1, inp2, inp3, inp4, inp5) print('For inputs',inp5,inp4,inp3,inp2,inp1,'Representation of GHZ States are:') display(plot_state_qsphere(state)) print('\n') # Explore GHZ States for input 11001. Note: the input has been stated in little-endian format. inp1 = 1 inp2 = 0 inp3 = 0 inp4 = 1 inp5 = 1 qc, state, result = ghz5QCircuit(inp1, inp2, inp3, inp4, inp5) print('For inputs',inp5,inp4,inp3,inp2,inp1,'Representation of GHZ States are:') display(plot_state_qsphere(state)) print('\n') # Explore GHZ States for input 01010. Note: the input has been stated in little-endian format. inp1 = 0 inp2 = 1 inp3 = 0 inp4 = 1 inp5 = 0 qc, state, result = ghz5QCircuit(inp1, inp2, inp3, inp4, inp5) print('For inputs',inp5,inp4,inp3,inp2,inp1,'Representation of GHZ States are:') display(plot_state_qsphere(state)) print('\n') # Uncomment below code in order to explore other states #for inp5 in ['0','1']: #for inp4 in ['0','1']: #for inp3 in ['0','1']: #for inp2 in ['0','1']: #for inp1 in ['0','1']: #qc, state, result = ghz5QCircuit(inp1, inp2, inp3, inp4, inp5) #print('For inputs',inp5,inp4,inp3,inp2,inp1,'Representation of GHZ States are:') # Uncomment any of the below functions to visualize the resulting quantum states # Draw the quantum circuit #display(qc.draw()) # Plot states on QSphere #display(plot_state_qsphere(state)) # Plot states on Bloch Multivector #display(plot_bloch_multivector(state)) # Plot histogram #display(plot_histogram(result.get_counts())) # Plot state matrix like a city #display(plot_state_city(state)) # Represent state matix using Pauli operators as the basis #display(plot_state_paulivec(state)) # Plot state matrix as Hinton representation #display(plot_state_hinton(state)) #print('\n') backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 5 and not x.configuration().simulator and x.status().operational==True)) def create5QGHZRealDevice(inp1, inp2, inp3, inp4, inp5): qr = QuantumRegister(5) cr = ClassicalRegister(5) qc = QuantumCircuit(qr, cr) qc.reset(range(5)) if inp1=='1': qc.x(0) if inp2=='1': qc.x(1) if inp3=='1': qc.x(1) if inp4=='1': qc.x(1) if inp5=='1': qc.x(1) qc.barrier() qc.h(0) qc.cx(0,1) qc.cx(0,2) qc.cx(0,3) qc.cx(0,4) qc.measure(qr, cr) job = execute(qc, backend=backend, shots=1000) job_monitor(job) result = job.result() return qc, result inp1 = 0 inp2 = 0 inp3 = 0 inp4 = 0 inp5 = 0 #first results qc, first_result = create5QGHZRealDevice(inp1, inp2, inp3, inp4, inp5) first_counts = first_result.get_counts() # Draw the quantum circuit display(qc.draw()) #second results qc, second_result = create5QGHZRealDevice(inp1, inp2, inp3, inp4, inp5) second_counts = second_result.get_counts() print('For inputs',inp5,inp4,inp3,inp2,inp1,'Representation of GHZ circuit states are,') # Plot results on histogram with legend legend = ['First execution', 'Second execution'] plot_histogram([first_counts, second_counts], legend=legend) import qiskit qiskit.__qiskit_version__
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/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit circ = QuantumCircuit(2, 2) circ.h(0) circ.cx(0, 1) circ.measure([0, 1], [0, 1]) circ.draw("mpl") from qiskit import transpile, schedule as build_schedule from qiskit.providers.fake_provider import FakeHanoi backend = FakeHanoi() transpiled_circ = transpile(circ, backend) # Undefined Hadamard is replaced by U1 schedule = build_schedule(transpiled_circ, backend) schedule.draw() from qiskit import pulse with pulse.build() as h_q0: pulse.play(pulse.library.Gaussian(duration=256, amp=0.2, sigma=50, name='custom'), pulse.DriveChannel(0)) circ.add_calibration('h', [0], h_q0) schedule = build_schedule(circ, backend) schedule.draw() circ = QuantumCircuit(2, 2) circ.x(0) circ.x(0) circ.x(1) circ.measure([0, 1], [0, 1]) circ.draw("mpl") schedule = build_schedule(circ, backend, method="as_late_as_possible") schedule.filter(channels=[pulse.DriveChannel(0), pulse.DriveChannel(1)]).draw() schedule = build_schedule(circ, backend, method="as_soon_as_possible") schedule.filter(channels=[pulse.DriveChannel(0), pulse.DriveChannel(1)]).draw() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/bagmk/qiskit-quantum-state-classifier
bagmk
import numpy as np import copy from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister, Aer, execute, transpile, assemble from qiskit.tools.visualization import * from qiskit.ignis.mitigation.measurement import (complete_meas_cal, tensored_meas_cal, CompleteMeasFitter, TensoredMeasFitter) import json from scipy.signal import savgol_filter import time from qiskit.tools.monitor import job_monitor from o_utils import ora # classifier utilities from o_plot import opl # utilities for result plot from c_utils import new_cut # circuit building utilities def json_dic_loader(dic_name): f = open(data_directory+dic_name+'.json') return json.load(f) # common code for calling the classifier for ideal device and for real devices def add_single_dic(target_data_list): start_time = time.time() print("started",time.strftime('%d/%m/%Y %H:%M:%S'),mitig_name, "mitigation",mit_str,o_metric,model_name) # added for D,S,M choice. Mainstream : mixed set of 20 states first = 0 last = nb_states if unique_char == "D": last = int(nb_states/2) elif unique_char == "S": first = int(nb_states/2) # get the classifier error curve in function of the number of shot and the "safe shot number" error_curve, safe_rate, ernb = ora.provide_error_curve(PD_model=model_dic[model_name][first:last,:], PD_test=PD_test[first:last,:], trials=trials, window=window, epsilon=epsilon, max_shots=max_shots, pol=pol, verbosality=verbosality) tail = savgol_filter(ernb, window, pol, axis=0) len_curve = len(error_curve) safe_shot_nb = len_curve - int((window-1)/2) # OK print('safe_shot_nb',safe_shot_nb, 'safe_rate',safe_rate, "nb trials:",trials) err_rates = tail[int((window-1)/2),:]/trials err_rate_max = np.max(err_rates) err_rate_min = np.min(err_rates) r=4 print("savgol interpolated error rate mean:", np.round(np.mean(err_rates),r), "min:", np.round(err_rate_min,r), "max:", np.round(err_rate_max,r), "for", [ien for ien, jen in enumerate(err_rates) if jen == err_rate_max]) end_time = time.time() #save the data in a list of dictionaries : single_dic={"project":mitig_name, "id_gates":id_gates, "mitigation":mit_str, "model":model_name, "metric":o_metric, "device":project_device, "curve_length":len_curve, "shots": safe_shot_nb, "shots_rate": safe_rate, "error_curve":error_curve, "trials":trials,"window":window, "epsilon":epsilon,"SG_pol": pol, "computation_time":end_time-start_time, "time_completed":time.strftime('%d/%m/%Y %H:%M:%S'), "trials":trials, "QV": QV_dic[project_device], "fidelity": fidelity_dic[project_device], "error_nb":ernb} target_data_list.append(single_dic) print("completed",time.strftime('%d/%m/%Y %H:%M:%S'),mitig_name, "mitigation",mit_str,o_metric,model_name,"\n") simulator = Aer.get_backend('qasm_simulator') #specify the layout of the devices used_qubits = 5 qubit_list = [0,1,2,3,4] short_version = True #program_name="QAD" # 1st pilot project GHZ Psi+ / W Phi+ program_name="AL2" # 2d pilot project W Psi+ / Wbar Phi+ Flag_char = "DS" # this for a mix of two types of separable states if len(Flag_char) >= 2: unique_char = "M" else: unique_char = Flag_char # These dictionaries for the devices used in the study if program_name == "QAD": fidelity_dic = {'ibmq_athens': 0.925110, 'ibmq_valencia': 0.809101, 'ibmq_ourense': 0.802380, "ibmqx2": 0.627392, 'ibmq_santiago': 0.919399, 'ibmq_vigo': 0.908840, 'ideal_device': 1.0} data_directory = "data_files/" elif program_name == "AL2": fidelity_dic = {'ibmq_athens': 0.910145, 'ibmq_valencia': 0.794262, 'ibmq_ourense': 0.818974, "ibmqx2": 0.359528, 'ibmq_santiago': 0.900024, 'ibmq_vigo': 0.841831, 'ideal_device': 1.0} data_directory = "data2_files/" QV_dic = {'ibmq_athens': 32.0, 'ibmq_valencia': 16.0, 'ibmq_ourense': 8.0, "ibmqx2": 8.0, 'ibmq_santiago': 32.0, 'ibmq_vigo': 16.0, 'ideal_device': np.inf} dev_dic = {'ibmq_santiago': "San",'ibmq_athens': "Ath", 'ibmq_valencia': "Val", 'ibmq_vigo': 'Vig','ibmq_ourense': "Our", "ibmqx2": 'Yor', 'ideal_device': "Ide"} # specify the device: here first the ideal noise-free device project_device = 'ideal_device' device_name = dev_dic[project_device] # specify the nb of id gates between state creation and measurements # zero for the ideal device id_gates = 0 str_nb_id = str(id_gates) zfilled = str_nb_id.zfill(4-len(str_nb_id)) # tail of the file names for RAM storage mitig_name = program_name + "_" + device_name project_name = mitig_name + "_" + unique_char + zfilled print(mitig_name) print(project_name) # establish the result label list # meas_calibs will be used for mitigation in the real device section qr = QuantumRegister(used_qubits) meas_calibs, label_list = complete_meas_cal(qubit_list=qubit_list, qr=qr, circlabel='mcal') nb_labels=len(label_list) print(nb_labels,label_list) len(meas_calibs) # permutation list # here it is simple to write down the list, # but a version using itertools will be wellcome for >5 qubits projects if used_qubits == 5: q_perm = [[0, 1, 2, 3, 4], [0, 1, 3, 2, 4], [0, 1, 4, 2, 3], [0, 2, 3, 1, 4], [0, 2, 4, 1, 3], [0, 3, 4, 1, 2], [1, 2, 3, 0, 4], [1, 2, 4, 0, 3], [1, 3, 4, 0, 2], [2, 3, 4, 0, 1]] else: print("work in progress - meanwhile please provide the list of permutations") # try loading the dictionary of results if its creation was skipped if short_version == True: ideal_dic = json_dic_loader("ideal_dic_"+project_name) nb_states = len(ideal_dic) nb_labels = len(list(ideal_dic.values())[0]) s_sim = sum(list(ideal_dic.values())[0].values()) PD_ideal = np.ndarray((nb_states,nb_labels)) for i_state in range(nb_states): PD_ideal[i_state, :] = list(ideal_dic[str(i_state)].values()) # now a little trick to get the ideal values from the simulator approximated values with np.errstate(divide='ignore'): # ignore the divide by zero warning PD_ideal = 1/np.round(s_sim/(PD_ideal)) # have a look at the matrix head and tail: print("first and last state probability distributions:") print(np.round(np.vstack((PD_ideal[0:1,:],PD_ideal[-1:,:])),4)) # here will be appended the data we want for the curve plot ideal_data_list=[] # you may want to skip this cell as it will require a long time # because of the high number of trials required by the Monte Carlo simulation for each nb o shots value # the following values are defined in the study summary (readme file): trials=100 # should be 10000 if not demo window=5 # shorter window than for the real device counts epsilon = .001 min_shots = 5 max_shots = 100 pol=2 subset = None # variable not used here verbosality = 5 # printing step for intermediate results when increasing the experiment shot number PD_test = PD_ideal mitigation_dic = {"Na": None} o_metrics_desired = ['jensenshannon', 'sqeuclidean'] model_dic = {"ideal_sim": PD_ideal} for mit_str, mitigation in mitigation_dic.items(): if mitigation != None: # thus only for counts on real device PD_exper = get_clean_matrix(empirical_dic, mitigation=mitigation, m_filter=meas_filter) for o_metric in o_metrics_desired: for model_name in model_dic.keys(): add_single_dic(ideal_data_list) # get the stored results of the Monte Carlo simulation in case you skipped the previous step if len(ideal_data_list) == 0: ideal_data_list = json_dic_loader("ideal_device_data_list_"+project_name) # have a look at the mean error rate curves and error rate at save shot number n_s # NB the r_hat_mean curves and legend reported r_hat_max errors the unsmoothed values opl.plot_curves(ideal_data_list,np.array([0,1]), "Jensen-Shannon vs squared euclidean distance - $\epsilon=0.001$" , ["model"], ["device","metric"], right_xlimit = 20, bottom_ylimit = -0.001, top_ylimit = 0.05) from qiskit import IBMQ IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') provider.backends() project_device = 'ibmq_valencia'# you may choice here a different backend device_name = dev_dic[project_device] mitig_name = program_name + "_" + device_name print(mitig_name) #determine here the backend device = provider.get_backend(project_device) # the backend names are listed here above properties = device.properties() coupling_map = device.configuration().coupling_map # retrieve the corresponding measurement mitigation filter obtained at experimental time # use a fake job because the calibration results were stored as dictionary simulator = Aer.get_backend('qasm_simulator') fake_job_cal = execute(meas_calibs, backend=simulator, shots=1) fake_cal_results = fake_job_cal.result() cal_results_dic = json_dic_loader("cal_results_dic_"+mitig_name) if 'date' in cal_results_dic.keys(): str(cal_results_dic['date']) cal_results = fake_cal_results.from_dict(cal_results_dic) meas_fitter = CompleteMeasFitter(cal_results, label_list, qubit_list=qubit_list, circlabel='mcal') meas_filter = meas_fitter.filter # have a look at the average measurement fidefily of this device: print("Average Measurement Fidelity was: %f" % meas_fitter.readout_fidelity(), "for",project_device) id_gates = 0 str_nb_id = str(id_gates) zfilled = str_nb_id.zfill(4-len(str_nb_id)) project_name = mitig_name + "_" + unique_char + zfilled print(project_name) #changing keys of dictionary for merging: def key_change(ini_dict, i_subset): ini_list = [] len_ini = len(ini_dict) for i in range(len_ini): ini_list.append(str(i+i_subset*len_ini)) return dict(zip(ini_list, list(ini_dict.values()))) if program_name == "QAD": #retrieve the data corresponding to the 1st project lfc = list(Flag_char) circ_ideal =[] empirical_dic = {} for i_subset, subset in enumerate(lfc): qasm_circs_dic = json_dic_loader('qasm_circs_dic_QAD_'+device_name+'_'+ subset + zfilled) j=0 # j included for project with several transpilation sessions for each device - not used here qasm_circs = qasm_circs_dic[str(j)] nb_circs = len(qasm_circs) for i_circs in range(nb_circs): circ_ideal.append(QuantumCircuit().from_qasm_str(qasm_circs[i_circs])) empirical_dic = {**empirical_dic, **key_change(json_dic_loader("experimental"+"_"+mitig_name +"_"\ +subset+zfilled), i_subset)} test_dic = copy.deepcopy(empirical_dic) #nb_states = len(circ_ideal) project_name if program_name == "AL2": empirical_dic = json_dic_loader('experimental_'+project_name) test_dic = json_dic_loader('test_'+project_name) def rectify_counts(tot_res, test_cqi,mitigation,m_filter) : void_counts = dict(zip(label_list, np.zeros(2**used_qubits))) try: counts_results_real_test = tot_res[str(test_cqi)] except KeyError as error: counts_results_real_test = tot_res[test_cqi] raw_counts_test = copy.deepcopy(void_counts) raw_counts_test.update(counts_results_real_test) if mitigation: mitigated_results_test = meas_filter.apply(raw_counts_test, method = 'least_squares') returned_counts = copy.deepcopy(void_counts) returned_counts.update(mitigated_results_test) else: returned_counts = copy.deepcopy(raw_counts_test) return returned_counts def get_clean_matrix(dic, mitigation,m_filter): clean_matrix = np.ndarray((nb_states,nb_labels)) for i_state in range(nb_states): rectified_counts = rectify_counts(dic,i_state, mitigation,m_filter) # get a rectified counts dictionary clean_matrix[i_state, :] = list(rectified_counts.values()) clean_matrix = clean_matrix/clean_matrix.sum(axis=1, keepdims=True) return clean_matrix # We need to create a first matrix version. It will then vary for each considered set of distribution mitigation = False PD_exper = get_clean_matrix(empirical_dic, mitigation=mitigation, m_filter=meas_filter) print("first and last state probability distributions:") print(np.round(np.vstack((PD_exper[0:1,:],PD_exper[-1:,:])),3)) if program_name == "QAD": PD_test = copy.deepcopy(PD_exper) elif program_name == "AL2": mitigation = False PD_test = get_clean_matrix(test_dic, mitigation=mitigation, m_filter=meas_filter) print("first and last state probability distributions:") print(np.round(np.vstack((PD_test[0:1,:],PD_test[-1:,:])),3)) # here will be appended the data we want for the final plot of this notebook empirical_data_list=[] # you may want to skip this cell as it will require a long time # because of the high number of trials required by the Monte Carlo simulation for each nb o shots value # the following values are defined in the study summary notebook: trials=100 window=11 epsilon = .001 max_shots = 500 pol=2 verbosality = 10 # printing step for intermediate results when increasing the experiment shot number # In this section you can easily make your choice of combinations # mitigation or not, metric and model mitigation_dic = {"no":False, "yes" : True} #mitigation_dic = {"no":False} #mitigation_dic = {"yes" : True} o_metrics_desired = ['jensenshannon', 'sqeuclidean'] #o_metrics_desired = ['jensenshannon'] #o_metrics_desired = ['sqeuclidean'] model_dic = {"empirical": PD_exper, "ideal_sim": PD_ideal} #model_dic = {"empirical": PD_exper} #model_dic = {"ideal_sim": PD_ideal} # Obtain a sequence of results in form of a list of dictionaries for mit_str, mitigation in mitigation_dic.items(): # here we toggle PD_exper as we toggled mitigation status PD_exper = get_clean_matrix(empirical_dic, mitigation=mitigation, m_filter=meas_filter) PD_test = get_clean_matrix(test_dic, mitigation=mitigation, m_filter=meas_filter) for o_metric in o_metrics_desired: print(project_name, model_dic.keys(), o_metric) for model_name in model_dic.keys(): add_single_dic(empirical_data_list) # get the stored results of the Monte Carlo simulation in case you skipped the previous step if len(empirical_data_list) == 0: empirical_data_list = json_dic_loader('nemp_data_list_'+project_name) # have a look at the mean error rate curves and error rate at save shot number n_s # NB the r_hat_mean curves and legend reported r_hat_max errors are the unsmoothed values opl.plot_curves(ideal_data_list + empirical_data_list, np.array(range(2+len(empirical_data_list))), "$\epsilon=0.001$" , ["device"], ["model","metric","mitigation","id_gates"], right_xlimit = 80, bottom_ylimit = -0.02, top_ylimit = 1) import winsound duration = 2000 # milliseconds freq = 800 # Hz winsound.Beep(freq, duration) import qiskit.tools.jupyter %qiskit_version_table
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. """ Tests for the baa_lowrank.py module. """ from unittest import TestCase import numpy as np from qiskit import ClassicalRegister, transpile from qiskit_aer import AerSimulator from qclib.util import get_state from qclib.state_preparation import BaaLowRankInitialize # pylint: disable=missing-function-docstring # pylint: disable=missing-class-docstring class TestBaaLowRank(TestCase): @staticmethod def fidelity(state1, state2): bra = np.conj(state1) ket = state2 return np.power(np.abs(bra.dot(ket)), 2) @staticmethod def get_counts(circuit): n_qubits = circuit.num_qubits classical_reg = ClassicalRegister(n_qubits) circuit.add_register(classical_reg) circuit.measure(list(range(n_qubits)), classical_reg) backend = AerSimulator() counts = backend.run( transpile(circuit, backend), shots=8192 ).result().get_counts() counts_with_zeros = {} for i in range(2**n_qubits): pattern = f'{i:0{n_qubits}b}' if pattern in counts: counts_with_zeros[pattern] = counts[pattern] else: counts_with_zeros[pattern] = 0.0 sum_values = sum(counts.values()) return [ value/sum_values for (key, value) in counts_with_zeros.items() ] def _test_initialize_loss(self, fidelity_loss, state_vector=None, n_qubits=5, strategy='brute_force', use_low_rank=False): if state_vector is None: state_vector = np.random.rand(2**n_qubits) + np.random.rand(2**n_qubits) * 1j state_vector = state_vector / np.linalg.norm(state_vector) opt_params = {'max_fidelity_loss':fidelity_loss, 'strategy' : strategy, 'use_low_rank':use_low_rank} circuit = BaaLowRankInitialize(state_vector, opt_params=opt_params).definition state = get_state(circuit) fidelity = TestBaaLowRank.fidelity(state_vector, state) self.assertTrue(round(fidelity,2)>=round(1-fidelity_loss,2)*0.99) def test_initialize_loss_brute_force(self): for loss in range(5, 15): self._test_initialize_loss(loss/100, n_qubits=5, strategy='brute_force') def test_initialize_loss_brute_force_low_rank(self): for loss in range(5, 15): self._test_initialize_loss(loss/100, n_qubits=5, strategy='brute_force', use_low_rank=True) def test_initialize_loss_greedy(self): for loss in range(5, 15): self._test_initialize_loss(loss/100, n_qubits=5, strategy='greedy') def test_initialize_loss_greedy_low_rank(self): for loss in range(5, 15): self._test_initialize_loss(loss/100, n_qubits=5, strategy='greedy', use_low_rank=True) def test_initialize_loss_fixed_n3(self): state_vector = [-0.33*1j,0,-0.44-0.44*1j,0.24+0.23*1j,0,0,0,0.62-0.01*1j] state_vector = state_vector/np.linalg.norm(state_vector) for loss in [0.1, 0.28, 0.9]: self._test_initialize_loss(loss, state_vector=state_vector, strategy='brute_force') self._test_initialize_loss(loss, state_vector=state_vector, strategy='greedy') def test_initialize_loss_fixed_n4(self): state_vector = [0.04214906+0.25870366j, 0.18263984+0.05596082j, 0.17202687+0.1843925j , 0.24972444+0.04666321j, 0.03311006+0.28233458j, 0.26680588+0.22211721j, 0.07205056+0.04556719j, 0.27982261+0.01626855j, 0.22908475+0.25461504j, 0.14290823+0.2425394j , 0.14213592+0.08282699j, 0.0068727 +0.03378424j, 0.2016483 +0.298073j , 0.07520782+0.0639856j , 0.01026576+0.07669651j, 0.31755857+0.09279232j] state_vector = state_vector/np.linalg.norm(state_vector) for loss in [0.1, 0.15, 0.18, 0.2]: self._test_initialize_loss(loss, state_vector=state_vector, strategy='brute_force') self._test_initialize_loss(loss, state_vector=state_vector, strategy='greedy') def test_initialize_loss_fixed_n5(self): state_vector = [0.17777766+0.10171662j, 0.19896424+0.10670792j, 0.07982054+0.19653055j, 0.18155708+0.05746777j, 0.04259147+0.17093567j, 0.21551328+0.08246133j, 0.09549255+0.1117806j , 0.20562749+0.12218064j, 0.16191832+0.01653411j, 0.12255337+0.14109365j, 0.20090638+0.11119666j, 0.19851901+0.04543331j, 0.06842539+0.16671467j, 0.03209685+0.16839388j, 0.01707365+0.20060943j, 0.03853768+0.08183117j, 0.00073591+0.10084589j, 0.09524694+0.18785593j, 0.06005853+0.06977443j, 0.01553849+0.05363906j, 0.10294799+0.12558734j, 0.20142903+0.06801796j, 0.05282011+0.20879126j, 0.11257846+0.20746226j, 0.17737416+0.03461382j, 0.01689154+0.06600272j, 0.06428148+0.06199636j, 0.1163249 +0.160533j , 0.14177201+0.10456823j, 0.03156739+0.04567818j, 0.02078566+0.02023752j, 0.18967059+0.03469463j] state_vector = state_vector/np.linalg.norm(state_vector) for loss in [0.1, 0.12, 0.14, 0.16, 0.2]: self._test_initialize_loss(loss, state_vector=state_vector, strategy='brute_force') self._test_initialize_loss(loss, state_vector=state_vector, strategy='greedy') def test_initialize_no_loss(self): state_vector = np.random.rand(32) + np.random.rand(32) * 1j state_vector = state_vector / np.linalg.norm(state_vector) circuit = BaaLowRankInitialize(state_vector).definition state = get_state(circuit) self.assertTrue(np.allclose(state_vector, state)) def test_initialize_ame(self): """ Test initialization of a absolutely maximally entangled state""" state_vector = [1, 1, 1, 1,1,-1,-1, 1, 1,-1,-1, 1, 1, 1,1,1, 1, 1,-1,-1,1,-1, 1,-1,-1, 1,-1, 1,-1,-1,1,1] state_vector = state_vector / np.linalg.norm(state_vector) circuit = BaaLowRankInitialize(state_vector).definition state = get_state(circuit) self.assertTrue(np.allclose(state_vector, state)) def test_measurement_no_loss(self): state_vector = np.random.rand(32) + np.random.rand(32) * 1j state_vector = state_vector / np.linalg.norm(state_vector) circuit = BaaLowRankInitialize(state_vector).definition state = TestBaaLowRank.get_counts(circuit) self.assertTrue(np.allclose( np.power(np.abs(state_vector),2), state, rtol=1e-01, atol=0.005)) def test_compare_strategies(self): fidelities1 = [] fidelities2 = [] for n_qubits in range(3,7): state_vector = np.random.rand(2**n_qubits) + np.random.rand(2**n_qubits) * 1j state_vector = state_vector / np.linalg.norm(state_vector) for loss in range(10, 20): opt_params = {'max_fidelity_loss' : loss/100, 'strategy' : 'brute_force'} circuit = BaaLowRankInitialize(state_vector, opt_params=opt_params).definition state = get_state(circuit) fidelity1 = TestBaaLowRank.fidelity(state_vector, state) opt_params = {'max_fidelity_loss' : loss/100, 'strategy' : 'greedy'} circuit = BaaLowRankInitialize(state_vector, opt_params=opt_params).definition state = get_state(circuit) fidelity2 = TestBaaLowRank.fidelity(state_vector, state) fidelities1.append(fidelity1) fidelities2.append(fidelity2) self.assertTrue(np.allclose(fidelities1, fidelities2, rtol=0.14, atol=0.0)) def test_large_state(self): # Builds a separable state. n_qubits = 16 state_vector1 = np.random.rand(2**(n_qubits//2)) + np.random.rand(2**(n_qubits//2)) * 1j state_vector1 = state_vector1 / np.linalg.norm(state_vector1) state_vector2 = np.random.rand(2**(n_qubits//2)) + np.random.rand(2**(n_qubits//2)) * 1j state_vector2 = state_vector2 / np.linalg.norm(state_vector2) state_vector = np.kron(state_vector1, state_vector2) opt_params = {'max_fidelity_loss' : 0.1, 'strategy' : 'brute_force'} circuit = BaaLowRankInitialize(state_vector, opt_params=opt_params).definition state = get_state(circuit) self.assertTrue(np.allclose(state_vector, state))
https://github.com/qismib/TraNQI
qismib
# useful additional packages import matplotlib.pyplot as plt #%matplotlib inline import numpy as np from pprint import pprint # importing QISKit from qiskit import QuantumProgram, QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import available_backends, execute, register, least_busy # import basic plot tools from qiskit.tools.visualization import plot_histogram, circuit_drawer qx_config = { "APItoken": 'dcdb2d9414a625c1f57373c544add3711c78c3d7faf39397fe2c41887110e8b59caf81bcb2bc32714d936da41a261fea510f96df379afcbdfa9df6cc6bfe3829', "url": 'https://quantumexperience.ng.bluemix.net/api' } backend = 'local_qasm_simulator' # run on local simulator by default '''register(qx_config['APItoken'], qx_config['url']) backend = least_busy(available_backends({'simulator': False, 'local': False})) print("the best backend is " + backend) ''' # Creating registers q2 = QuantumRegister(2) c2 = ClassicalRegister(2) # quantum circuit to make an entangled bell state bell = QuantumCircuit(q2, c2) bell.h(q2[0]) bell.cx(q2[0], q2[1]) # quantum circuit to measure q0 in the standard basis measureIZ = QuantumCircuit(q2, c2) measureIZ.measure(q2[0], c2[0]) bellIZ = bell+measureIZ # quantum circuit to measure q0 in the superposition basis measureIX = QuantumCircuit(q2, c2) measureIX.h(q2[0]) measureIX.measure(q2[0], c2[0]) bellIX = bell+measureIX # quantum circuit to measure q1 in the standard basis measureZI = QuantumCircuit(q2, c2) measureZI.measure(q2[1], c2[1]) bellZI = bell+measureZI # quantum circuit to measure q1 in the superposition basis measureXI = QuantumCircuit(q2, c2) measureXI.h(q2[1]) measureXI.measure(q2[1], c2[1]) bellXI = bell+measureXI # quantum circuit to measure q in the standard basis measureZZ = QuantumCircuit(q2, c2) measureZZ.measure(q2[0], c2[0]) measureZZ.measure(q2[1], c2[1]) bellZZ = bell+measureZZ # quantum circuit to measure q in the superposition basis measureXX = QuantumCircuit(q2, c2) measureXX.h(q2[0]) measureXX.h(q2[1]) measureXX.measure(q2[0], c2[0]) measureXX.measure(q2[1], c2[1]) bellXX = bell+measureXX # quantum circuit to make a mixed state mixed1 = QuantumCircuit(q2, c2) mixed2 = QuantumCircuit(q2, c2) mixed2.x(q2) mixed1.h(q2[0]) mixed1.h(q2[1]) mixed1.measure(q2[0], c2[0]) mixed1.measure(q2[1], c2[1]) mixed2.h(q2[0]) mixed2.h(q2[1]) mixed2.measure(q2[0], c2[0]) mixed2.measure(q2[1], c2[1]) '''circuits = [bellIZ,bellIX,bellZI,bellXI,bellZZ,bellXX] job = execute(circuits, backend) result = job.result() print(result.get_counts(bellXX)) plot_histogram(result.get_counts(bellXX))''' mixed_state = [mixed1,mixed2] job = execute(mixed_state, backend) result = job.result() counts1 = result.get_counts(mixed_state[0]) counts2 = result.get_counts(mixed_state[1]) from collections import Counter ground = Counter(counts1) excited = Counter(counts2) plot_histogram(ground+excited)
https://github.com/rubenandrebarreiro/ibm-qiskit-quantum-explorers-2023-2024
rubenandrebarreiro
# build your code here answer1 = [3] # run this cell to submit your answer # import the grader for the exercise 1 of the lab/badge 1 from qc_grader.challenges.quantum_explorers23 import grade_badge1_ex1 # expected result type: List grade_badge1_ex1(answer1) # build your code here answer2 = [1] # eun this cell to submit your answer # import the grader for the exercise 2 of the lab/badge 1 from qc_grader.challenges.quantum_explorers23 import grade_badge1_ex2 # expected result type: List grade_badge1_ex2(answer2) # build your code here answer3 = [4] # run this cell to submit your answer # import the grader for the exercise 3 of the lab/badge 1 from qc_grader.challenges.quantum_explorers23 import grade_badge1_ex3 # expected result type: List grade_badge1_ex3(answer3) # build your code here answer4 = [2] # run this cell to submit your answer # import the grader for the exercise 4 of the lab/badge 1 from qc_grader.challenges.quantum_explorers23 import grade_badge1_ex4 # expected result type: List grade_badge1_ex4(answer4) # build your code here answer5 = [2] # run this cell to submit your answer # import the grader for the exercise 5 of the lab/badge 1 from qc_grader.challenges.quantum_explorers23 import grade_badge1_ex5 # expected result type: List grade_badge1_ex5(answer5) # build your code here answer6 = [4] # run this cell to submit your answer # import the grader for the exercise 6 of the lab/badge 1 from qc_grader.challenges.quantum_explorers23 import grade_badge1_ex6 # expected result type: List grade_badge1_ex6(answer6) # build your code here answer7 = [2] # run this cell to submit your answer # import the grader for the exercise 7 of the lab/badge 1 from qc_grader.challenges.quantum_explorers23 import grade_badge1_ex7 # expected result type: List grade_badge1_ex7(answer7) # build your code here answer8 = [4] # run this cell to submit your answer # import the grader for the exercise 8 of the lab/badge 1 from qc_grader.challenges.quantum_explorers23 import grade_badge1_ex8 # expected result type: List grade_badge1_ex8(answer8) # build your code here answer9 = [1] # run this cell to submit your answer # import the grader for the exercise 9 of the lab/badge 1 from qc_grader.challenges.quantum_explorers23 import grade_badge1_ex9 # expected result type: List grade_badge1_ex9(answer9) # build your code here answer10 = [2] # run this cell to submit your answer # import the grader for the exercise 10 of the lab/badge 1 from qc_grader.challenges.quantum_explorers23 import grade_badge1_ex10 # expected result type: List grade_badge1_ex10(answer10) # build your code here answer11 = [1] # run this cell to submit your answer # import the grader for the exercise 11 of the lab/badge 1 from qc_grader.challenges.quantum_explorers23 import grade_badge1_ex11 # expected result type: List grade_badge1_ex11(answer11) # build your code here answer12 = [2] # run this cell to submit your answer # import the grader for the exercise 12 of the lab/badge 1 from qc_grader.challenges.quantum_explorers23 import grade_badge1_ex12 # expected result type: List grade_badge1_ex12(answer12) # import the quantum circuit # from the IBM's Qiskit library from qiskit import QuantumCircuit # import the plotting state of qsphere function # from the IBM's Qiskit Visualization module from qiskit.visualization import plot_state_qsphere ####### build your code below ######### # create a quantum circuit with # a quantum register with 4 qubits circuit = QuantumCircuit(4) # apply the Hadamard gate to all the 4 qubits # to see all the possible combinations of quantum states # note: uncomment to see all the possible # combinations of quantum states # circuit.h( [0, 1, 2, 3] ) # the (entangled) quantum state we need is # |psi> = 1/sqrt(2) * ( |0010> + |1101> ) # apply the Hadamard gate to the 2nd qubit on # the quantum register of the quantum circuit circuit.h(1) # apply the CX/CNOT gate on the 2nd qubit # as control and on the 1st qubit as target, # both on the quantum register of the quantum circuit circuit.cx(1, 0) # apply the CX/CNOT gate on the 2nd qubit # as control and on the 3rd qubit as target, # both on the quantum register of the quantum circuit circuit.cx(1, 2) # apply the CX/CNOT gate on the 2nd qubit # as control and on the 4th qubit as target, # both on the quantum register of the quantum circuit circuit.cx(1, 3) # apply the Pauli-X gate to the 2nd qubit on # the quantum register of the quantum circuit circuit.x(1) ####### build your code above ######### # display the plot of the quantum state from the QSphere # applied to the quantum circuit defined before display( plot_state_qsphere( circuit ) ) # draw the quantum circuit defined before display( circuit.draw("mpl") ) # run this cell to submit your answer # import the grader for the coding exercise of the lab/badge 1 from qc_grader.challenges.quantum_explorers23 import grade_badge1_code # expected result type: QuantumCircuit answer_code = grade_badge1_code(circuit) #### get statevector from a quantum circuit #### # import the statevector from the IBM's Qiskit # Quantum Information module from qiskit.quantum_info import Statevector # retrieve the statevector from the instructions of # the quantum circuit defined before statevector = Statevector.from_instruction( circuit ) #### run this cell to view the output of #### #### your quantum circuit as a histogram #### # import the Sampler from the IBM's Qiskit Aer Primitives module, # with the 'AerSampler' alias being defined from qiskit_aer.primitives import Sampler as AerSampler # import the plot distribution function # from the IBM's Qiskit Tools for Visualization module from qiskit.tools.visualization import plot_distribution #### run the circuit on the simulator #### #### and get probability distribution #### # create an Aer Sampler object sampler = AerSampler() # measure all the qubits from # the quantum circuit defined before circuit.measure_all() # execute the quantum circuit defined before, # on the Aer Sampler, retrieving the respective job job = sampler.run(circuit) # retrieve the probability distribution # from the quasi-distribution of # the results obtained from the execution of # the quantum circuit created before prob_distribution = job.result().quasi_dists[0].binary_probabilities() # print the statevector from the instructions of # the quantum circuit defined before print( statevector ) # print the probability distribution # from the quasi-distribution of # the results obtained from the execution of # the quantum circuit created before print( "Simulator Probability Distribution:", prob_distribution ) # plot the probability distribution # from the quasi-distribution of # the results obtained from the execution of # the quantum circuit created before plot_distribution( prob_distribution, color=[ "lightblue" ] ) # import the Qiskit's Runtime Service, Session, and Sampler # from the Qiskit's IBM Runtime module from qiskit_ibm_runtime import QiskitRuntimeService, Session, Sampler # create a Qiskit's Runtime Service object, # using the IBM Quantum channel service = QiskitRuntimeService( channel="ibm_quantum" ) # retrieve the least busy backend # (this step may take a while) real_backend = service.least_busy( min_num_qubits=4, simulator=False ) # within the context of a session with Session( service, backend=real_backend ) as session: # create the Sampler object for the Session defined before sampler = Sampler( session=session ) # execute the quantum simulation of # the quantum circuit created before, # using the Sampler, and retrieving # the respective job on # a real quantum device job_real = sampler.run( circuit ) # retrieve and show the status of # the job created for the execution of # the quantum circuit defined before, # on the Aer Sampler, using # a real quantum device job_real.status() # retrieve the probability distribution # from the quasi-distribution of # the results obtained from the execution of # the quantum circuit created before, # using a real quantum device prob_distribution_real = job_real.result().quasi_dists[0].binary_probabilities() # fix the probability distributions # from the quasi-distributions of # the results obtained from the execution of # the quantum circuit created before, # using the simulator, for values # lower or equal to 0 (zero) prob_distribution = { binary_string : prob if prob > 0 else 1e-8 for binary_string, prob in prob_distribution.items() } # create a list with all the possible binary strings # with 4 bits (i.e., a total of 16 possible different values) binary_strings_4_bits = [ bin( num )[2:].zfill(4) for num in range( 2**4 ) ] # for each possible binary string with 4 bits for binary_string_4_bits in binary_strings_4_bits: # if the current binary string with 4 bits is # not in the diectionary of the probability # distributions from the quasi-distributions of # the results obtained from the execution of # the quantum circuit created before, # using the simulator if binary_string_4_bits not in prob_distribution: # add the missing binary string with 4 bits to # the diectionary of the probability # distributions from the quasi-distributions of # the results obtained from the execution of # the quantum circuit created before, # using the simulator, with a negligible value prob_distribution[ binary_string_4_bits ] = 1e-8 # fix the probability distributions # from the quasi-distributions of # the results obtained from the execution of # the quantum circuit created before, # using a real quantum device, # for values lower or equal to 0 (zero) prob_distribution_real = { binary_string : prob if prob > 0 else 1e-8 for binary_string, prob in prob_distribution_real.items() } # plot the probability distributions # from the quasi-distributions of # the results obtained from the execution of # the quantum circuit created before, # using the simulator and a real quantum device plot_distribution( data=[ prob_distribution, prob_distribution_real ], legend=[ "Simulator", "Quantum Real Device" ], color=[ "lightblue", "black" ], bar_labels = False ) # import the Quantum Circuit and the execute # instruction from the IBM's Qiskit library from qiskit import QuantumCircuit, execute # import the Qiskit's Aer object # from the IBM's Qiskit library from qiskit import Aer # retrieve the Unitary Simulator object backend = Aer.get_backend( "unitary_simulator" ) ###################################### #### for the 1st quantum circuit #### # create the 1st quantum circuit, # with a quantum register of 2 qubits qc_1 = QuantumCircuit(2) # apply the inverse of S gate on # the 2nd qubit on the quantum register of # the 1st quantum circuit created before qc_1.sdg(1) # apply the CX/CNOT gate on the 1st qubit # as control and on the 2nd qubit as target, # both on the quantum register of # the 1st quantum circuit created before qc_1.cx( 0, 1 ) # apply the S gate on the 2nd # qubit on the quantum register of # the 1st quantum circuit created before qc_1.s(1) # execute the quantum simulation of # the 1st quantum circuit created before, # and retrieve the respective job job = execute( qc_1, backend, shots=10000 ) # retrieve the result obtained # from the quantum simulation of # the 1st quantum circuit created before result = job.result() # retrieve the unitary operator from the results # obtained from the quantum simulation of # the 1st quantum circuit created before qc_1_unitary = result.get_unitary( qc_1, decimals = 3 ) ###################################### #### for the 2nd quantum circuit #### # create the 2nd quantum circuit, # with a quantum register of 2 qubits qc_2 = QuantumCircuit(2) # apply the CY gate on the 1st qubit # as control and on the 2nd qubit as target, # both on the quantum register of # the 2nd quantum circuit created before qc_2.cy( 0, 1) # execute the quantum simulation of # the 2nd quantum circuit created before, # and retrieve the respective job job = execute( qc_2, backend, shots=10000 ) # retrieve the result obtained # from the quantum simulation of # the 2nd quantum circuit created before result = job.result() # retrieve the unitary operator from the results # obtained from the quantum simulation of # the 2nd quantum circuit created before qc_2_unitary = result.get_unitary( qc_2, decimals = 3 ) # if the two quantum circuits are # represented by the same unitary operator if( qc_1_unitary == qc_2_unitary ): # print an informative success message, # in the case that the two quantum circuits # are represented by the same unitary operator print( "The two quantum circuits are represented by " "the same unitary operator!" ) # build your code here answer13 = [3] # run this cell to submit your answer # import the grader for the exercise 13 of the lab/badge 1 from qc_grader.challenges.quantum_explorers23 import grade_badge1_ex13 # expected result type: List grade_badge1_ex13(answer13) # build your code here answer14 = [3] # run this cell to submit your answer # import the grader for the exercise 14 of the lab/badge 1 from qc_grader.challenges.quantum_explorers23 import grade_badge1_ex14 # expected result type: List grade_badge1_ex14(answer14) # build your code here answer15 = [4] # run this cell to submit your answer # import the grader for the exercise 15 of the lab/badge 1 from qc_grader.challenges.quantum_explorers23 import grade_badge1_ex15 # expected result type: List grade_badge1_ex15(answer15) # run this cell to check whether you have passed # import the grader for the badge 1 of # the IBM Qiskit's Quantum Explorers 2023-2024 from qc_grader.challenges.quantum_explorers23 import grade_badge1_score # grade the score of the quiz of the lab for the badge 1 grade_badge1_score("en")
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_optimization.problems import QuadraticProgram # define a problem qp = QuadraticProgram() qp.binary_var("x") qp.integer_var(name="y", lowerbound=-1, upperbound=4) qp.maximize(quadratic={("x", "y"): 1}) qp.linear_constraint({"x": 1, "y": -1}, "<=", 0) print(qp.prettyprint()) from qiskit_optimization.algorithms import CplexOptimizer, GurobiOptimizer cplex_result = CplexOptimizer().solve(qp) gurobi_result = GurobiOptimizer().solve(qp) print("cplex") print(cplex_result.prettyprint()) print() print("gurobi") print(gurobi_result.prettyprint()) result = CplexOptimizer(disp=True, cplex_parameters={"threads": 1, "timelimit": 0.1}).solve(qp) print(result.prettyprint()) from qiskit_optimization.algorithms import MinimumEigenOptimizer from qiskit_aer import Aer from qiskit.algorithms.minimum_eigensolvers import QAOA from qiskit.algorithms.optimizers import COBYLA from qiskit.primitives import Sampler meo = MinimumEigenOptimizer(QAOA(sampler=Sampler(), optimizer=COBYLA(maxiter=100))) result = meo.solve(qp) print(result.prettyprint()) print("\ndisplay the best 5 solution samples") for sample in result.samples[:5]: print(sample) # docplex model from docplex.mp.model import Model docplex_model = Model("docplex") x = docplex_model.binary_var("x") y = docplex_model.integer_var(-1, 4, "y") docplex_model.maximize(x * y) docplex_model.add_constraint(x <= y) docplex_model.prettyprint() # gurobi model import gurobipy as gp gurobipy_model = gp.Model("gurobi") x = gurobipy_model.addVar(vtype=gp.GRB.BINARY, name="x") y = gurobipy_model.addVar(vtype=gp.GRB.INTEGER, lb=-1, ub=4, name="y") gurobipy_model.setObjective(x * y, gp.GRB.MAXIMIZE) gurobipy_model.addConstr(x - y <= 0) gurobipy_model.update() gurobipy_model.display() from qiskit_optimization.translators import from_docplex_mp, from_gurobipy qp = from_docplex_mp(docplex_model) print("QuadraticProgram obtained from docpblex") print(qp.prettyprint()) print("-------------") print("QuadraticProgram obtained from gurobipy") qp2 = from_gurobipy(gurobipy_model) print(qp2.prettyprint()) from qiskit_optimization.translators import to_gurobipy, to_docplex_mp gmod = to_gurobipy(from_docplex_mp(docplex_model)) print("convert docplex to gurobipy via QuadraticProgram") gmod.display() dmod = to_docplex_mp(from_gurobipy(gurobipy_model)) print("\nconvert gurobipy to docplex via QuadraticProgram") print(dmod.export_as_lp_string()) ind_mod = Model("docplex") x = ind_mod.binary_var("x") y = ind_mod.integer_var(-1, 2, "y") z = ind_mod.integer_var(-1, 2, "z") ind_mod.maximize(3 * x + y - z) ind_mod.add_indicator(x, y >= z, 1) print(ind_mod.export_as_lp_string()) qp = from_docplex_mp(ind_mod) result = meo.solve(qp) # apply QAOA to QuadraticProgram print("QAOA") print(result.prettyprint()) print("-----\nCPLEX") print(ind_mod.solve()) # apply CPLEX directly to the Docplex model import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/daniel-molina23/basic-quantum-algorithms
daniel-molina23
my_list = [1,3,6,8,2,7,5,7,9,2,16,4] def my_oracle(my_input): winner = 9 response = False if winner == my_input: response = True return response for index, number in enumerate(my_list): if (my_oracle(number) == True): print("Winner winner chicken dinner! at index = %i"%index) print("%i times the Oracle was called"%(index+1)) break from qiskit import * import matplotlib.pyplot as plt import numpy as np # create the oracle quantum circuit oracle = QuantumCircuit(2, name='oracle') oracle.cz(0,1) # apply the Controlled-Z gate or CZ gate oracle.to_gate() # make oracle into its own gate oracle.draw() backend = Aer.get_backend('statevector_simulator') grover_circuit = QuantumCircuit(2,2) # 2 qubits, 2 classical registers grover_circuit.h([0,1]) # apply hadamard gate on both qubits 0 and 1 to prepare superposition state discussed in description.md grover_circuit.append(oracle, [0,1]) # append oracle to be able to query each state at same time grover_circuit.draw() job = execute(grover_circuit, backend) result = job.result() sv = result.get_statevector() np.around(sv, 2) reflection = QuantumCircuit(2, name='reflection') reflection.h([0,1]) # apply hadamard gate on all qubits to bring them back to '00' state from the original 's' state reflection.z([0,1]) # apply Z gate on both qubits reflection.cz(0,1) # controlled-z gate reflection.h([0,1]) # transform back with hadamard on both qubits reflection.to_gate() reflection.draw() backend = Aer.get_backend('qasm_simulator') grover_circuit = QuantumCircuit(2,2) grover_circuit.h([0,1]) grover_circuit.append(oracle, [0,1]) grover_circuit.append(reflection, [0,1]) grover_circuit.measure([0,1], [0,1]) grover_circuit.draw() job = execute(grover_circuit, backend, shots=1) result = job.result() result.get_counts()
https://github.com/sebasmos/QuantumVE
sebasmos
# !pip install qiskit torch torchvision matplotlib # !pip install qiskit-machine-learning # !pip install torchviz # !pip install qiskit[all] # !pip install qiskit == 0.45.2 # !pip install qiskit_algorithms == 0.7.1 # !pip install qiskit-ibm-runtime == 0.17.0 # !pip install qiskit-aer == 0.13.2 # #Quentum net draw # !pip install pylatexenc import os MODEL_METADATA = "SVM" model_name = "efficientnet_b3_embeddings_feat_space_2"#"efficientnet_v2_m"#"convnext_base"#"efficientnet_b3"#"mobileNet" results_path = f"{model_name}/{MODEL_METADATA}" os.makedirs(results_path, exist_ok = True) train_path = f"{model_name}/train" val_path = f"{model_name}/val" os.makedirs(train_path, exist_ok = True) os.makedirs(val_path, exist_ok=True) from qiskit_algorithms.utils import algorithm_globals import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from qiskit.circuit.library import ZZFeatureMap from qiskit.primitives import Sampler from qiskit_algorithms.state_fidelities import ComputeUncompute from qiskit_machine_learning.kernels import FidelityQuantumKernel from sklearn.metrics import confusion_matrix, classification_report algorithm_globals.random_seed = 12345 train_embeddings = pd.read_csv(f'{train_path}/train_embeddings.csv') val_embeddings = pd.read_csv(f'{val_path}/val_embeddings.csv') print(f"Reading embeddings from: ", train_path) # Prepare data for training train_features = train_embeddings.iloc[:, :-1].values # Features y_train = train_embeddings.iloc[:, -1].values # Labels test_features = val_embeddings.iloc[:, :-1].values # Features y_val = val_embeddings.iloc[:, -1].values # Labels plt.figure(figsize=(18, 5)) ax = sns.countplot(x=y_train, palette='tab10') total = len(y_train) for p in ax.patches: percentage = f'{100 * p.get_height() / total:.1f}%\n' x = p.get_x() + p.get_width() / 2 y = p.get_height() ax.annotate(percentage, (x, y), ha='center', va='center') plt.show() train_labels adhoc_dimension = 2 """ class 0 : {0,2} class 1 : {1,3} """ label_map = {0: 0, 1: 1, 2: 0, 3: 1, 4: 0} # Merge labels using the dictionary labels_train = np.array([label_map[label] for label in y_train]) test_labels = np.array([label_map[label] for label in y_val]) print(f"training".center(60,"-")) print("Original labels:", np.unique(y_train)) print("Merged labels:", np.unique(merged_labels)) print(f"testing".center(60,"-")) print("Original labels:", np.unique(train_labels)) print("Merged labels:", np.unique(y_val)) plt.figure(figsize=(18, 5)) ax = sns.countplot(x=labels_train, palette='tab10') total = len(labels_train) for p in ax.patches: percentage = f'{100 * p.get_height() / total:.1f}%\n' x = p.get_x() + p.get_width() / 2 y = p.get_height() ax.annotate(percentage, (x, y), ha='center', va='center') plt.show() train_labels print(train_features.shape, labels_train.shape) print(test_features.shape, test_labels.shape) adhoc_feature_map = ZZFeatureMap(feature_dimension=adhoc_dimension, reps=2, entanglement="linear") sampler = Sampler() fidelity = ComputeUncompute(sampler=sampler) adhoc_kernel = FidelityQuantumKernel(fidelity=fidelity, feature_map=adhoc_feature_map) train_features.shape # feat_2_train = train_features[:,:2] # feat_2_test = test_features[:,:2] feat_2_train.shape, feat_2_test.shape, labels_train.shape, test_labels.shape train_labels # feat_2_train = feat_2_train[:500] # feat_2_test = feat_2_test[:50] # labels_train = labels_train[:500] # test_labels = test_labels[:50] feat_2_train.shape, feat_2_test.shape, labels_train.shape, test_labels.shape import time from sklearn.metrics import accuracy_score, precision_score, f1_score, recall_score, fbeta_score from sklearn.svm import SVC # Start timer for training start_train = time.time() adhoc_svc = SVC(kernel=adhoc_kernel.evaluate) adhoc_svc.fit(feat_2_train, labels_train) # End timer for training end_train = time.time() # Start timer for inference start_inference = time.time() predictions = adhoc_svc.predict(feat_2_test) # End timer for inference end_inference = time.time() accuracy = accuracy_score(test_labels, predictions) precision = precision_score(test_labels, predictions, average='weighted') f1 = f1_score(test_labels, predictions, average='weighted') recall = recall_score(test_labels, predictions, average='weighted') fbeta_75 = fbeta_score(test_labels, predictions, beta=0.75, average='weighted') # Print metrics and time print(f"Accuracy: {accuracy} Precision: {precision} F1 Score: {f1} Recall: {recall} F0.75 Score: {fbeta_75}") print(f"Training time: {end_train - start_train} seconds") print(f"Inference time: {end_inference - start_inference} seconds") y_pred = predictions y_val = test_labels unique_classes = np.unique(np.concatenate(((y_pred, y_val)))) confusion_mat = confusion_matrix(y_pred, y_val, 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() report = classification_report(y_val,y_pred, target_names=unique_classes,output_dict=True)# Mostrar el informe de df = pd.DataFrame(report).transpose() df.to_csv(os.path.join(results_path, f"confusion_matrix_{MODEL_METADATA}.csv")) print(df)
https://github.com/martynscn/Masters-Thesis-on-Quantum-Cryptography
martynscn
# This code has been adapted and modified from IBM Qiskit 2021 and # uses the constant optimized modular exponentiation circuit for mod 15 as contained # in https://arxiv.org/abs/1202.6614. import numpy as np import math from decimal import * import matplotlib.pyplot as plt from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit.visualization import plot_histogram from qiskit import Aer, transpile, assemble import pandas as pd from fractions import Fraction # # import math # from math import gcd # from numpy.random import randint # # # from decimal import * print("Imports Successful") from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = "all" def my_mod(a,n): getcontext().prec = 27 return round((Decimal(a)/Decimal(n) - Decimal(a)//Decimal(n) ) * n) def constant_optimized_modular_exponentation_modulus15(a, power): 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) control_U = U.control() return control_U def inverse_qft(n): circuit = QuantumCircuit(n) for i in range(n//2): circuit.swap(i, n-1-i) for j in range(n): for m in range(j): circuit.cp(-np.pi/float(2**(j-m)), m, j) circuit.h(j) circuit.name = "QFT†" return circuit N = 15 a = 7 n_count = 8 counting_register = QuantumRegister(size = n_count, name = "counting_register") acting_register = QuantumRegister(size = 4, name="acting_register") classic_register = ClassicalRegister(size = n_count, name="classic_register") qc = QuantumCircuit(counting_register, acting_register ,classic_register) initial_state = [1,0] for q in range(8): qc.initialize(initial_state, q) qc.draw(output = 'mpl', filename = "Step0") for q in range(n_count): qc.h(q) qc.draw(output = 'mpl', filename = "Step1") qc.x(3+n_count) qc.draw(output = 'mpl', filename = "Step1b") for q in range(n_count): qc.append(constant_optimized_modular_exponentation_modulus15(a, 2**q), [q] + [i+n_count for i in range(4)]) qc.measure(range(n_count,n_count + 4), range(4)) qc.barrier() qc.draw(output = 'mpl', filename = "Step2") qc.append(inverse_qft(n_count), range(n_count)) qc.draw(output = 'mpl', filename = "Step3") # Measure circuit qc.measure(range(n_count), range(n_count)) qc.draw(output = 'mpl', filename = "Step4") qasm_sim = Aer.get_backend('qasm_simulator') t_qc = transpile(qc, qasm_sim) qobj = assemble(t_qc) results = qasm_sim.run(qobj).result() counts = results.get_counts() plot_histogram(counts) rows, measured_phases = [], [] for output in counts: decimal = int(output, 2) phase = decimal/(2**n_count) measured_phases.append(phase) rows.append([f"{output}(bin) = {decimal:>3}(dec)", f"{decimal}/{2**n_count} = {phase:.2f}"]) headers=["Register Output", "Phase"] df = pd.DataFrame(rows, columns=headers) df rows = [] for phase in measured_phases: frac = Fraction(phase).limit_denominator(15) rows.append([phase, f"{frac.numerator}/{frac.denominator}", frac.denominator]) headers=["Phase", "Fraction", "Guess for r"] df = pd.DataFrame(rows, columns=headers) my_period_r = max(df["Guess for r"]) print("My period (r) is %i" % my_period_r) # Confirm that the period is 4 xvals = np.arange(N) xvals = [x.item() for x in xvals] yvals = [my_mod(a**x, N) for x in xvals] fig, ax = plt.subplots(); ax.plot(xvals, yvals, linewidth=1, linestyle='dotted', marker='x'); ax.set(xlabel='$x$', ylabel='$%i^x$ mod $%i$' % (a, N), title="Example of Periodic Function in Shor's Algorithm"); try: r = yvals[1:].index(1) +1 plt.annotate(s = '', xy=(0,1), xytext=(r,1), arrowprops=dict(arrowstyle='<->')); plt.annotate(s = '$r=%i$' % r, xy=(r/3,1.5)); except ValueError: print('Could not find a period') first_shared_factor = math.gcd((7**(int(my_period_r/2)) + 1), 15) first_shared_factor second_shared_factor = math.gcd((7**(int(my_period_r/2)) - 1), 15) second_shared_factor %qiskit_copyright
https://github.com/iqm-finland/qiskit-on-iqm
iqm-finland
# Copyright 2024 Qiskit on IQM developers """Naive transpilation for N-star architecture""" from datetime import datetime from typing import Optional, Union from qiskit import QuantumCircuit, user_config from qiskit.circuit import QuantumRegister, Qubit from qiskit.dagcircuit import DAGCircuit, DAGOpNode from qiskit.providers.models import BackendProperties from qiskit.transpiler import CouplingMap, Layout, TranspileLayout from qiskit.transpiler.basepasses import TransformationPass from qiskit.transpiler.exceptions import TranspilerError from qiskit.transpiler.passmanager import PassManager from qiskit.transpiler.passmanager_config import PassManagerConfig from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit.transpiler.target import Target from .fake_backends.iqm_fake_backend import IQMFakeBackend from .iqm_circuit import IQMCircuit from .iqm_provider import IQMBackend from .iqm_transpilation import IQMOptimizeSingleQubitGates from .move_gate import MoveGate class IQMNaiveResonatorMoving(TransformationPass): """WIP Naive transpilation pass for resonator moving A naive transpiler pass for use with the Qiskit PassManager. Although it requires a CouplingMap, Target, or Backend, it does not take this into account when adding MoveGates. It assumes target connectivity graph is star shaped with a single resonator in the middle. Which qubit is the resonator is represented with the resonator_register attribute. The pass assumes that all single qubit and two-qubit gates are allowed. The resonator is used to swap the qubit states for the two-qubit gates. Additionally, it assumes that no single qubit gates are allowed on the resonator. """ def __init__(self, resonator_register: int, move_qubits: list[int], gate_set: list[str]): """WIP Naive transpilation pass for resonator moving Args: resonator_register (int): Which qubit/vertex index represents the resonator. move_qubits (int): Which qubits (indices) can be moved into the resonator. gate_set (list[str]): Which gates are allowed by the target backend. """ super().__init__() self.resonator_register = resonator_register self.current_resonator_state_location = resonator_register self.move_qubits = move_qubits self.gate_set = gate_set def run(self, dag: DAGCircuit): # pylint: disable=too-many-branches """Run the IQMNaiveResonatorMoving pass on `dag`. Args: dag (DAGCircuit): DAG to map. Returns: DAGCircuit: A mapped DAG. Raises: TranspilerError: if the layout are not compatible with the DAG, or if the input gate set is incorrect. """ new_dag = dag.copy_empty_like() # Check for sensible inputs if len(dag.qregs) != 1 or dag.qregs.get("q", None) is None: raise TranspilerError("IQMNaiveResonatorMoving runs on physical circuits only") # Create a trivial layout canonical_register = dag.qregs["q"] trivial_layout = Layout.generate_trivial_layout(canonical_register) current_layout = trivial_layout.copy() for layer in dag.serial_layers(): subdag = layer["graph"] if len(layer["partition"]) > 0: qubits = layer["partition"][0] else: new_dag.compose(subdag) continue # No qubit gate (e.g. Barrier) if sum(subdag.count_ops().values()) > 1: raise TranspilerError( """The DAGCircuit is not flattened enough for this transpiler pass. It needs to be processed by another pass first.""" ) if list(subdag.count_ops().keys())[0] not in self.gate_set: raise TranspilerError( """Encountered an incompatible gate in the DAGCircuit. Please transpile to the correct gate set first.""" ) if len(qubits) == 1: # Single qubit gate # Check if the qubit is not in the resonator if self.current_resonator_state_location == qubits[0].index: # Unload the current qubit from the resonator new_dag.compose(self._move_resonator(qubits[0].index, canonical_register, current_layout)) new_dag.compose(subdag) elif len(qubits) == 2: # Two qubit gate physical_q0 = current_layout[qubits[0]] physical_q1 = current_layout[qubits[1]] if self.current_resonator_state_location in (physical_q0, physical_q1): # The resonator is already loaded with the correct qubit data pass else: swap_layer = DAGCircuit() swap_layer.add_qreg(canonical_register) if self.current_resonator_state_location != self.resonator_register: # Unload the current qubit from the resonator new_dag.compose( self._move_resonator( self.current_resonator_state_location, canonical_register, current_layout ) ) # Load the new qubit to the resonator if physical_q0 in self.move_qubits and physical_q1 in self.move_qubits: # We can choose, let's select the better one by seeing which one is used most. chosen_qubit = self._lookahead_first_qubit_used(dag, subdag) new_qubit_to_load = current_layout[chosen_qubit] elif physical_q0 in self.move_qubits: new_qubit_to_load = physical_q0 elif physical_q1 in self.move_qubits: new_qubit_to_load = physical_q1 else: raise TranspilerError( """Two qubit gate between qubits that are not allowed to move. Please route the circuit first.""" ) new_dag.compose(self._move_resonator(new_qubit_to_load, canonical_register, current_layout)) # Add the gate to the circuit order = list(range(len(canonical_register))) order[self.resonator_register] = self.current_resonator_state_location order[self.current_resonator_state_location] = self.resonator_register new_dag.compose(subdag, qubits=order) else: raise TranspilerError( """Three qubit gates are not allowed as input for this pass. Please use a different transpiler pass to decompose first.""" ) new_dag.compose( self._move_resonator( self.current_resonator_state_location, canonical_register, current_layout, ) ) return new_dag def _lookahead_first_qubit_used(self, full_dag: DAGCircuit, current_layer: DAGCircuit) -> Qubit: """Lookahead function to see which qubit will be used first again for a CZ gate. Args: full_dag (DAGCircuit): The DAG representing the circuit current_layer (DAGCircuit): The DAG representing the current operator Returns: Qubit: Which qubit is recommended to move because it will be used first. """ nodes = [n for n in current_layer.nodes() if isinstance(n, DAGOpNode)] current_opnode = nodes[0] qb1, qb2 = current_opnode.qargs next_ops = [ n for n, _ in full_dag.bfs_successors(current_opnode) if isinstance(n, DAGOpNode) and n.name == "cz" ] # Check which qubit will be used next first for qb1_used, qb2_used in zip([qb1 in n.qargs for n in next_ops], [qb2 in n.qargs for n in next_ops]): if qb1_used and not qb2_used: return qb1 if qb2_used and not qb1_used: return qb2 return qb1 def _move_resonator(self, qubit: int, canonical_register: QuantumRegister, current_layout: Layout): """Logic for creating the DAG for swapping a qubit in and out of the resonator. Args: qubit (int): The qubit to swap in or out. The returning DAG is empty if the qubit is the resonator. canonical_register (QuantumRegister): The qubit register to initialize the DAG current_layout (Layout): The current qubit layout to map the qubit index to a Qiskit Qubit object. Returns: DAGCircuit: A DAG storing the MoveGate logic to be added into the circuit by this TranspilerPass. """ swap_layer = DAGCircuit() swap_layer.add_qreg(canonical_register) if qubit != self.resonator_register: swap_layer.apply_operation_back( MoveGate(), qargs=(current_layout[qubit], current_layout[self.resonator_register]), cargs=(), check=False, ) if self.current_resonator_state_location == self.resonator_register: # We just loaded the qubit into the register self.current_resonator_state_location = qubit else: # We just unloaded the qubit from the register self.current_resonator_state_location = self.resonator_register return swap_layer def _to_qubit_indices(backend: Union[IQMBackend, IQMFakeBackend], qubit_names: list[str]) -> list[int]: indices = [backend.qubit_name_to_index(res) for res in qubit_names] return [i for i in indices if i is not None] def _qubit_to_index_without_resonator( backend: Union[IQMBackend, IQMFakeBackend], resonator_registers: list[str], qb: str ) -> Optional[int]: resonator_indices = _to_qubit_indices(backend, resonator_registers) idx = backend.qubit_name_to_index(qb) return (idx - sum(1 for r in resonator_indices if r < idx)) if idx is not None else None def _generate_coupling_map_without_resonator(backend: Union[IQMBackend, IQMFakeBackend]) -> CouplingMap: # Grab qubits from backend operations allowed_ops = backend.architecture.operations allowed_czs = allowed_ops["cz"] allowed_moves = allowed_ops["move"] iqm_registers = backend.architecture.qubits resonator_registers = [r for r in iqm_registers if r.startswith("COMP_R")] move_qubits = {r: [q for pair in allowed_moves for q in pair if r in pair and q != r] for r in resonator_registers} edges = [] for qb1, qb2 in allowed_czs: if qb1 in resonator_registers: vs1 = move_qubits[qb1] else: vs1 = [qb1] if qb2 in resonator_registers: vs2 = move_qubits[qb2] else: vs2 = [qb2] for v1 in vs1: for v2 in vs2: qb1_idx = _qubit_to_index_without_resonator(backend, resonator_registers, v1) qb2_idx = _qubit_to_index_without_resonator(backend, resonator_registers, v2) if qb1_idx is not None and qb2_idx is not None: edges.append((qb1_idx, qb2_idx)) return CouplingMap(edges) def build_IQM_star_pass_manager_config( backend: Union[IQMBackend, IQMFakeBackend], circuit: QuantumCircuit ) -> PassManagerConfig: """Build configuration for IQM backend. We need to pass precomputed values to be used in transpiler passes via backend_properties. This function performs precomputation for the backend and packages the values to the config object.""" coupling_map = _generate_coupling_map_without_resonator(backend) allowed_ops = backend.architecture.operations allowed_moves = allowed_ops["move"] iqm_registers = backend.architecture.qubits classical_registers = [bit.index for bit in circuit.clbits] resonator_registers = [r for r in iqm_registers if r.startswith("COMP_R")] move_qubits = {r: [q for pair in allowed_moves for q in pair if r in pair and q != r] for r in resonator_registers} qubit_registers = [q for q in iqm_registers if q not in resonator_registers] qubit_indices = [backend.qubit_name_to_index(qb) for qb in qubit_registers] bit_indices = [_qubit_to_index_without_resonator(backend, resonator_registers, qb) for qb in qubit_registers] resonator_indices = [backend.qubit_name_to_index(r) for r in resonator_registers] if len(resonator_indices) != 1: raise NotImplementedError("Device must have exactly one resonator.") if any(idx is None for idx in resonator_indices): raise RuntimeError("Could not find index of a resonator.") move_indices = _to_qubit_indices(backend, move_qubits[resonator_registers[0]]) extra_backend_properties = { "resonator_indices": resonator_indices, "move_indices": move_indices, "qubit_indices": qubit_indices, "bit_indices": bit_indices, "classical_registers": classical_registers, } backend_properties = BackendProperties( backend_name=backend.name, backend_version="", last_update_date=datetime.now(), qubits=[], gates=[], general=[], ) backend_properties._data.update(**extra_backend_properties) return PassManagerConfig( basis_gates=backend.operation_names, backend_properties=backend_properties, target=Target(num_qubits=len(qubit_indices)), coupling_map=coupling_map, ) def build_IQM_star_pass(pass_manager_config: PassManagerConfig) -> TransformationPass: """Build translate pass for IQM star architecture""" backend_props = pass_manager_config.backend_properties.to_dict() resonator_indices = backend_props.get("resonator_indices") return IQMNaiveResonatorMoving( resonator_indices[0], backend_props.get("move_indices"), pass_manager_config.basis_gates, ) def transpile_to_IQM( # pylint: disable=too-many-arguments circuit: QuantumCircuit, backend: Union[IQMBackend, IQMFakeBackend], optimize_single_qubits: bool = True, ignore_barriers: bool = False, remove_final_rzs: bool = False, optimization_level: Optional[int] = None, ) -> QuantumCircuit: """Basic function for transpiling to IQM backends. Currently works with Deneb and Garnet Args: circuit (QuantumCircuit): The circuit to be transpiled without MOVE gates. backend (IQMBackend | IQMFakeBackend): The target backend to compile to containing a single resonator. optimize_single_qubits (bool): Whether to optimize single qubit gates away (default = True). ignore_barriers (bool): Whether to ignore barriers when optimizing single qubit gates away (default = False). remove_final_rzs (bool): Whether to remove the final Rz rotations (default = False). optimization_level: How much optimization to perform on the circuits as per Qiskit transpiler. Higher levels generate more optimized circuits, at the expense of longer transpilation time. * 0: no optimization * 1: light optimization (default) * 2: heavy optimization * 3: even heavier optimization Raises: NotImplementedError: Thrown when the backend supports multiple resonators. Returns: QuantumCircuit: The transpiled circuit ready for running on the backend. """ passes = [] if optimize_single_qubits: optimize_pass = IQMOptimizeSingleQubitGates(remove_final_rzs, ignore_barriers) passes.append(optimize_pass) if optimization_level is None: config = user_config.get_config() optimization_level = config.get("transpile_optimization_level", 1) if "move" not in backend.architecture.operations.keys(): pass_manager = generate_preset_pass_manager(backend=backend, optimization_level=optimization_level) simple_transpile = pass_manager.run(circuit) if passes: return PassManager(passes).run(simple_transpile) return simple_transpile pass_manager_config = build_IQM_star_pass_manager_config(backend, circuit) move_pass = build_IQM_star_pass(pass_manager_config) passes.append(move_pass) backend_props = pass_manager_config.backend_properties.to_dict() qubit_indices = backend_props.get("qubit_indices") resonator_indices = backend_props.get("resonator_indices") classical_registers = backend_props.get("classical_registers") n_qubits = len(qubit_indices) n_resonators = len(resonator_indices) pass_manager = generate_preset_pass_manager( optimization_level, basis_gates=pass_manager_config.basis_gates, coupling_map=pass_manager_config.coupling_map, ) simple_transpile = pass_manager.run(circuit) circuit_with_resonator = IQMCircuit( n_qubits + n_resonators, max(classical_registers) + 1 if len(classical_registers) > 0 else 0, ) layout_dict = { qb: i + sum(1 for r_i in resonator_indices if r_i <= i + n_resonators) for qb, i in simple_transpile._layout.initial_layout._v2p.items() } layout_dict.update({Qubit(QuantumRegister(n_resonators, "resonator"), r_i): r_i for r_i in resonator_indices}) initial_layout = Layout(input_dict=layout_dict) init_mapping = layout_dict final_layout = None if simple_transpile.layout.final_layout: final_layout_dict = { qb: i + sum(1 for r_i in resonator_indices if r_i <= i + n_resonators) for qb, i in simple_transpile.layout.final_layout._v2p.items() } final_layout_dict.update( {Qubit(QuantumRegister(n_resonators, "resonator"), r_i): r_i for r_i in resonator_indices} ) final_layout = Layout(final_layout_dict) new_layout = TranspileLayout(initial_layout, init_mapping, final_layout=final_layout) circuit_with_resonator.append( simple_transpile, qubit_indices, classical_registers if len(classical_registers) > 0 else None ) circuit_with_resonator._layout = new_layout circuit_with_resonator = circuit_with_resonator.decompose() transpiled_circuit = PassManager(passes).run(circuit_with_resonator) transpiled_circuit._layout = new_layout return transpiled_circuit
https://github.com/abbarreto/qiskit4
abbarreto
from sympy import * init_printing(use_unicode=True) %matplotlib inline p00,p01,p10,p11 = symbols('p_{00} p_{01} p_{10} p_{11}') th,ph = symbols('theta phi') Psi00 = Matrix([[cos(th)],[0],[0],[sin(th)]]) Psi01 = Matrix([[0],[sin(ph)],[cos(ph)],[0]]) Psi11 = Matrix([[0],[cos(ph)],[-sin(ph)],[0]]) Psi10 = Matrix([[-sin(th)],[0],[0],[cos(th)]]) #Psi00, Psi00.T, Psi00*Psi00.T rhoX = p00*Psi00*Psi00.T + p01*Psi01*Psi01.T + p10*Psi10*Psi10.T + p11*Psi11*Psi11.T simplify(rhoX) def kp(x,y): return KroneckerProduct(x,y) I = Matrix([[1,0],[0,1]]) Y = Matrix([[0,-1j],[1j,0]]) Y = Matrix([[0,1],[1,0]]) Z = Matrix([[1,0],[0,-1]]) cxx,cyy,czz,az,bz = symbols('c_{xx} c_{yy} c_{zz} a_{z} b_{z}') rhoX = (1/4)*(kp(I,I) + cxx*kp(X,X) + cyy*kp(Y,Y) + czz*kp(Z,Z) + az*kp(Z,I) + bz*kp(I,Z)) simplify(rhoX) th,be,ga = symbols('theta beta gamma') c00 = cos(th/2)*cos(be/2)*cos(ga/2) + sin(th/2)*sin(be/2)*sin(ga/2) c01 = cos(th/2)*cos(be/2)*sin(ga/2) - sin(th/2)*sin(be/2)*cos(ga/2) c10 = cos(th/2)*sin(be/2)*cos(ga/2) - sin(th/2)*cos(be/2)*sin(ga/2) c11 = cos(th/2)*sin(be/2)*sin(ga/2) + sin(th/2)*cos(be/2)*cos(ga/2) simplify(c00**2 + c01**2 + c10**2 + c11**2) # ok! P0 = Matrix([[1,0],[0,0]]) P1 = Matrix([[0,0],[0,1]]) def Ry(th): return cos(th/2)*I - 1j*sin(th/2)*Y def Cx_ab(): return KroneckerProduct(P0,I) + KroneckerProduct(P1,X) def Cx_ba(): return KroneckerProduct(I,P0) + KroneckerProduct(X,P1) MB = Cx_ab()*KroneckerProduct(Ry(th-ph),I)*Cx_ba()*KroneckerProduct(Ry(th+ph),I) # mudanca de base simplify(MB) from qiskit import * import numpy as np import math import qiskit nshots = 8192 IBMQ.load_account() provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') device = provider.get_backend('ibmq_belem') simulator = Aer.get_backend('qasm_simulator') from qiskit.tools.monitor import job_monitor from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter # retorna o circuito quantico que prepara um certo estado real de 1 qubit # coef = array com os 2 coeficientes reais do estado na base computacional def qc_psi_1qb_real(coef): qr = QuantumRegister(1) qc = QuantumCircuit(qr, name='psir_1qb') th = 2*math.acos(np.abs(coef[0])) qc.ry(th, qr[0]) return qc eigvals = [0.1,0.9] coef = np.sqrt(eigvals) print(coef) qc_psi_1qb_real_ = qc_psi_1qb_real(coef) qc_psi_1qb_real_.draw('mpl') from qiskit.quantum_info import Statevector sv = Statevector.from_label('0') sv sv = sv.evolve(qc_psi_1qb_real_) sv # retorna o circuito quantico que prepara um certo estado real de 2 qubits # coef = array com os 4 coeficientes reais do estado na base computacional def qc_psi_2qb_real(coef): qr = QuantumRegister(2) qc = QuantumCircuit(qr, name = 'psir_2qb') xi = 2*math.acos(math.sqrt(coef[0]**2+coef[1]**2)) coef1 = [math.sqrt(coef[0]**2+coef[1]**2),math.sqrt(1-coef[0]**2-coef[1]**2)] c_psi_1qb_real_ = qc_psi_1qb_real(coef1) qc.append(c_psi_1qb_real_, [qr[0]]) th0 = 2*math.atan(np.abs(coef[1])/np.abs(coef[0])) th1 = 2*math.atan(np.abs(coef[3])/np.abs(coef[2])) qc.x(0) qc.cry(th0, 0, 1) qc.x(0) qc.cry(th1, 0, 1) return qc eigvals = [0.1, 0.2, 0.3, 0.4] coef = np.sqrt(eigvals) print(coef) qc_psi_2qb_real_ = qc_psi_2qb_real(coef) qc_psi_2qb_real_.draw('mpl') sv = Statevector.from_label('00') sv sv = sv.evolve(qc_psi_2qb_real_) sv # note o ordenamento, o 2º qb é o 1º e o 1º é o 2º (00,10,01,11) def qc_ry(th): qr = QuantumRegister(1) qc = QuantumCircuit(qr, name = 'RY') qc.ry(th, 0) return qc # retorna o circuito quantico que prepara um certo estado real de 3 qubits # coef = array com os 8 coeficientes reais do estado na base computacional def qc_psi_3qb_real(coef): qr = QuantumRegister(3) qc = QuantumCircuit(qr, name = 'psir_3qb') d = len(coef) coef2 = np.zeros(d//2) th = np.zeros(d//2) for j in range(0,2): for k in range(0,2): coef2[int(str(j)+str(k),2)] = math.sqrt(coef[int(str(j)+str(k)+str(0),2)]**2+coef[int(str(j)+str(k)+str(1),2)]**2) c_psi_2qb_real_ = qc_psi_2qb_real(coef2) qc.append(c_psi_2qb_real_, [qr[0],qr[1]]) for j in range(0,2): for k in range(0,2): th[int(str(j)+str(k),2)] = 2*math.atan(np.abs(coef[int(str(j)+str(k)+str(1),2)])/np.abs(coef[int(str(j)+str(k)+str(0),2)])) if j == 0: qc.x(0) if k == 0: qc.x(1) qc_ry_ = qc_ry(th[int(str(j)+str(k),2)]) ccry = qc_ry_.to_gate().control(2) qc.append(ccry, [0,1,2]) if j == 0: qc.x(0) if k == 0: qc.x(1) return qc list_bin = [] for j in range(0,2**3): b = "{:03b}".format(j) list_bin.append(b) print(list_bin) eigvals = [0.01,0.1,0.04,0.2,0.05,0.3,0.18,0.12] coef = np.sqrt(eigvals) print(coef) qc_psi_3qb_real_ = qc_psi_3qb_real(coef) qc_psi_3qb_real_.draw('mpl') # odernamento: '000', '001', '010', '011', '100', '101', '110', '111' sv = Statevector.from_label('000') sv sv = sv.evolve(qc_psi_3qb_real_) sv # ordenamento aqui: 000 100 010 110 001 101 011 111 # retorna o circuito quantico que prepara um certo estado real de 4 qubits # coef = array com os 16 coeficientes reais do estado na base computacional def qc_psi_4qb_real(coef): qr = QuantumRegister(4) qc = QuantumCircuit(qr, name = 'psir_4qb') d = len(coef) coef3 = np.zeros(d//2) th = np.zeros(d//2) for j in range(0,2): for k in range(0,2): for l in range(0,2): coef3[int(str(j)+str(k)+str(l),2)] = math.sqrt(coef[int(str(j)+str(k)+str(l)+str(0),2)]**2+coef[int(str(j)+str(k)+str(l)+str(1),2)]**2) c_psi_3qb_real_ = qc_psi_3qb_real(coef3) qc.append(c_psi_3qb_real_, [qr[0],qr[1],qr[2]]) for j in range(0,2): for k in range(0,2): for l in range(0,2): th[int(str(j)+str(k)+str(l),2)] = 2*math.atan(np.abs(coef[int(str(j)+str(k)+str(l)+str(1),2)])/np.abs(coef[int(str(j)+str(k)+str(l)+str(0),2)])) if j == 0: qc.x(0) if k == 0: qc.x(1) if l == 0: qc.x(2) qc_ry_ = qc_ry(th[int(str(j)+str(k)+str(l),2)]) ccry = qc_ry_.to_gate().control(3) qc.append(ccry, [0,1,2,3]) if j == 0: qc.x(0) if k == 0: qc.x(1) if l == 0: qc.x(2) return qc list_bin = [] for j in range(0,2**4): b = "{:04b}".format(j) list_bin.append(b) print(list_bin) eigvals = np.zeros(2**4) eigvals[0] = 0.008 for j in range(1,len(eigvals)-1): eigvals[j] = eigvals[j-1]+0.005 #print(np.sum(eigvals)) eigvals[j+1] = 1 - np.sum(eigvals) #print(eigvals) #print(np.sum(eigvals)) coef = np.sqrt(eigvals) print(coef) qc_psi_4qb_real_ = qc_psi_4qb_real(coef) qc_psi_4qb_real_.draw('mpl') # '0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111', '1000', '1001', '1010', '1011', '1100', '1101', '1110', '1111' sv = Statevector.from_label('0000') sv sv = sv.evolve(qc_psi_4qb_real_) sv # ordenamento aqui: 0000 1000 0100 1100 0010 1010 0110 1110 0001 1001 0101 1101 0011 1011 0111 1111 sv[1]
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test of generated fake backends.""" import math import unittest from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, schedule, transpile, assemble from qiskit.pulse import Schedule from qiskit.qobj import PulseQobj from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider.utils.configurable_backend import ConfigurableFakeBackend from qiskit.providers.fake_provider import FakeAthens, FakePerth from qiskit.utils import optionals def get_test_circuit(): """Generates simple circuit for tests.""" desired_vector = [1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)] qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") qc = QuantumCircuit(qr, cr) qc.initialize(desired_vector, [qr[0], qr[1]]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) return qc class GeneratedFakeBackendsTest(QiskitTestCase): """Generated fake backends test.""" def setUp(self) -> None: self.backend = ConfigurableFakeBackend("Tashkent", n_qubits=4) @unittest.skip("Skipped until qiskit-aer#741 is fixed and released") @unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required to run this test") def test_transpile_schedule_and_assemble(self): """Test transpile, schedule and assemble on generated backend.""" qc = get_test_circuit() circuit = transpile(qc, backend=self.backend) self.assertTrue(isinstance(circuit, QuantumCircuit)) self.assertEqual(circuit.num_qubits, 4) experiments = schedule(circuits=circuit, backend=self.backend) self.assertTrue(isinstance(experiments, Schedule)) self.assertGreater(experiments.duration, 0) qobj = assemble(experiments, backend=self.backend) self.assertTrue(isinstance(qobj, PulseQobj)) self.assertEqual(qobj.header.backend_name, "Tashkent") self.assertEqual(len(qobj.experiments), 1) job = self.backend.run(qobj) result = job.result() self.assertTrue(result.success) self.assertEqual(len(result.results), 1) class FakeBackendsTest(QiskitTestCase): """fake backends test.""" @unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required to run this test") def test_fake_backends_get_kwargs(self): """Fake backends honor kwargs passed.""" backend = FakeAthens() qc = QuantumCircuit(2) qc.x(range(0, 2)) qc.measure_all() trans_qc = transpile(qc, backend) raw_counts = backend.run(trans_qc, shots=1000).result().get_counts() self.assertEqual(sum(raw_counts.values()), 1000) @unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required to run this test") def test_fake_backend_v2_noise_model_always_present(self): """Test that FakeBackendV2 instances always run with noise.""" backend = FakePerth() qc = QuantumCircuit(1) qc.x(0) qc.measure_all() res = backend.run(qc, shots=1000).result().get_counts() # Assert noise was present and result wasn't ideal self.assertNotEqual(res, {"1": 1000})
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeVigoV2 from qiskit.visualization import plot_circuit_layout from qiskit.tools.monitor import job_monitor from qiskit.providers.fake_provider import FakeVigoV2 import matplotlib.pyplot as plt ghz = QuantumCircuit(3, 3) ghz.h(0) for idx in range(1,3): ghz.cx(0,idx) ghz.measure(range(3), range(3)) backend = FakeVigoV2() new_circ_lv3 = transpile(ghz, backend=backend, optimization_level=3) plot_circuit_layout(new_circ_lv3, backend)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Tests for Layer2Q implementation. """ import unittest from random import randint import test.python.transpiler.aqc.fast_gradient.utils_for_testing as tut import numpy as np import qiskit.transpiler.synthesis.aqc.fast_gradient.layer as lr from qiskit.transpiler.synthesis.aqc.fast_gradient.pmatrix import PMatrix from qiskit.test import QiskitTestCase class TestLayer2q(QiskitTestCase): """ Tests for Layer2Q class. """ max_num_qubits = 5 # maximum number of qubits in tests num_repeats = 50 # number of repetitions in tests def setUp(self): super().setUp() np.random.seed(0x0696969) def test_layer2q_matrix(self): """ Tests: (1) the correctness of Layer2Q matrix construction; (2) matrix multiplication interleaved with permutations. """ mat_kind = "complex" _eps = 100.0 * np.finfo(float).eps max_rel_err = 0.0 for n in range(2, self.max_num_qubits + 1): dim = 2**n iden = tut.eye_int(n) for j in range(n): for k in range(n): if j == k: continue m_mat = tut.rand_matrix(dim=dim, kind=mat_kind) t_mat, g_mat = tut.make_test_matrices4x4(n=n, j=j, k=k, kind=mat_kind) lmat = lr.Layer2Q(num_qubits=n, j=j, k=k, g4x4=g_mat) g2, perm, inv_perm = lmat.get_attr() self.assertTrue(m_mat.dtype == t_mat.dtype == g_mat.dtype == g2.dtype) self.assertTrue(np.all(g_mat == g2)) self.assertTrue(np.all(iden[perm].T == iden[inv_perm])) g_mat = np.kron(tut.eye_int(n - 2), g_mat) # T == P^t @ G @ P. err = tut.relative_error(t_mat, iden[perm].T @ g_mat @ iden[perm]) self.assertLess(err, _eps, "err = {:0.16f}".format(err)) max_rel_err = max(max_rel_err, err) # Multiplication by permutation matrix of the left can be # replaced by row permutations. tm = t_mat @ m_mat err1 = tut.relative_error(iden[perm].T @ g_mat @ m_mat[perm], tm) err2 = tut.relative_error((g_mat @ m_mat[perm])[inv_perm], tm) # Multiplication by permutation matrix of the right can be # replaced by column permutations. mt = m_mat @ t_mat err3 = tut.relative_error(m_mat @ iden[perm].T @ g_mat @ iden[perm], mt) err4 = tut.relative_error((m_mat[:, perm] @ g_mat)[:, inv_perm], mt) self.assertTrue( err1 < _eps and err2 < _eps and err3 < _eps and err4 < _eps, "err1 = {:f}, err2 = {:f}, " "err3 = {:f}, err4 = {:f}".format(err1, err2, err3, err4), ) max_rel_err = max(max_rel_err, err1, err2, err3, err4) def test_pmatrix_class(self): """ Test the class PMatrix. """ _eps = 100.0 * np.finfo(float).eps mat_kind = "complex" max_rel_err = 0.0 for n in range(2, self.max_num_qubits + 1): dim = 2**n tmp1 = np.ndarray((dim, dim), dtype=np.cfloat) tmp2 = tmp1.copy() for _ in range(self.num_repeats): j0 = randint(0, n - 1) k0 = (j0 + randint(1, n - 1)) % n j1 = randint(0, n - 1) k1 = (j1 + randint(1, n - 1)) % n j2 = randint(0, n - 1) k2 = (j2 + randint(1, n - 1)) % n j3 = randint(0, n - 1) k3 = (j3 + randint(1, n - 1)) % n j4 = randint(0, n - 1) k4 = (j4 + randint(1, n - 1)) % n t0, g0 = tut.make_test_matrices4x4(n=n, j=j0, k=k0, kind=mat_kind) t1, g1 = tut.make_test_matrices4x4(n=n, j=j1, k=k1, kind=mat_kind) t2, g2 = tut.make_test_matrices4x4(n=n, j=j2, k=k2, kind=mat_kind) t3, g3 = tut.make_test_matrices4x4(n=n, j=j3, k=k3, kind=mat_kind) t4, g4 = tut.make_test_matrices4x4(n=n, j=j4, k=k4, kind=mat_kind) c0 = lr.Layer2Q(num_qubits=n, j=j0, k=k0, g4x4=g0) c1 = lr.Layer2Q(num_qubits=n, j=j1, k=k1, g4x4=g1) c2 = lr.Layer2Q(num_qubits=n, j=j2, k=k2, g4x4=g2) c3 = lr.Layer2Q(num_qubits=n, j=j3, k=k3, g4x4=g3) c4 = lr.Layer2Q(num_qubits=n, j=j4, k=k4, g4x4=g4) m_mat = tut.rand_matrix(dim=dim, kind=mat_kind) ttmtt = t0 @ t1 @ m_mat @ np.conj(t2).T @ np.conj(t3).T pmat = PMatrix(n) pmat.set_matrix(m_mat) pmat.mul_left_q2(layer=c1, temp_mat=tmp1) pmat.mul_left_q2(layer=c0, temp_mat=tmp1) pmat.mul_right_q2(layer=c2, temp_mat=tmp1) pmat.mul_right_q2(layer=c3, temp_mat=tmp1) alt_ttmtt = pmat.finalize(temp_mat=tmp1) err1 = tut.relative_error(alt_ttmtt, ttmtt) self.assertLess(err1, _eps, "relative error: {:f}".format(err1)) prod = np.cfloat(np.trace(ttmtt @ t4)) alt_prod = pmat.product_q2(layer=c4, tmp1=tmp1, tmp2=tmp2) err2 = abs(alt_prod - prod) / abs(prod) self.assertLess(err2, _eps, "relative error: {:f}".format(err2)) max_rel_err = max(max_rel_err, err1, err2) if __name__ == "__main__": unittest.main()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.opflow import I, X, Y, Z print(I, X, Y, Z) print(1.5 * I) print(2.5 * X) print(X + 2.0 * Y) print(X^Y^Z) print(X @ Y @ Z) print((X + Y) @ (Y + Z)) print((X + Y) ^ (Y + Z)) (I, X) 2.0 * X^Y^Z print(1.1 * ((1.2 * X)^(Y + (1.3 * Z)))) from qiskit.opflow import (StateFn, Zero, One, Plus, Minus, H, DictStateFn, VectorStateFn, CircuitStateFn, OperatorStateFn) print(Zero, One) print(Plus, Minus) print(Zero.eval('0')) print(Zero.eval('1')) print(One.eval('1')) print(Plus.eval('0')) print(Minus.eval('1')) One.adjoint() ~One (2.0 + 3.0j) * Zero print(Zero + One) import math v_zero_one = (Zero + One) / math.sqrt(2) print(v_zero_one) print(Plus + Minus) print(~One @ One) (~One @ One).eval() (~v_zero_one @ v_zero_one).eval() (~Minus @ One).eval() print((~One).compose(One)) (~One).eval(One) print(Zero^Plus) print((Zero^Plus).to_circuit_op()) print(600 * ((One^5) + (Zero^5))) print((One^Zero)^3) print(((Plus^Minus)^2).to_matrix_op()) print(((Plus^One)^2).to_circuit_op()) print(((Plus^One)^2).to_matrix_op().sample()) print(StateFn({'0':1})) print(StateFn({'0':1}) == Zero) print(StateFn([0,1,1,0])) from qiskit.circuit.library import RealAmplitudes print(StateFn(RealAmplitudes(2))) from qiskit.opflow import X, Y, Z, I, CX, T, H, S, PrimitiveOp X print(X.eval('0')) X.eval('0').eval('1') print(CX) print(CX.to_matrix().real) # The imaginary part vanishes. CX.eval('01') # 01 is the one in decimal. We get the first column. CX.eval('01').eval('11') # This returns element with (zero-based) index (1, 3) print(X @ One) (X @ One).eval() X.eval(One) print(((~One^2) @ (CX.eval('01'))).eval()) print(((H^5) @ ((CX^2)^I) @ (I^(CX^2)))**2) print((((H^5) @ ((CX^2)^I) @ (I^(CX^2)))**2) @ (Minus^5)) print(((H^I^I)@(X^I^I)@Zero)) print(~One @ Minus) from qiskit.opflow import ListOp print((~ListOp([One, Zero]) @ ListOp([One, Zero]))) print((~ListOp([One, Zero]) @ ListOp([One, Zero])).reduce()) print(StateFn(Z).adjoint()) StateFn(Z).adjoint() print(StateFn(Z).adjoint().eval(Zero)) print(StateFn(Z).adjoint().eval(One)) print(StateFn(Z).adjoint().eval(Plus)) import numpy as np from qiskit.opflow import I, X, Y, Z, H, CX, Zero, ListOp, PauliExpectation, PauliTrotterEvolution, CircuitSampler, MatrixEvolution, Suzuki from qiskit.circuit import Parameter from qiskit import Aer two_qubit_H2 = (-1.0523732 * I^I) + \ (0.39793742 * I^Z) + \ (-0.3979374 * Z^I) + \ (-0.0112801 * Z^Z) + \ (0.18093119 * X^X) print(two_qubit_H2) evo_time = Parameter('θ') evolution_op = (evo_time*two_qubit_H2).exp_i() print(evolution_op) # Note, EvolvedOps print as exponentiations print(repr(evolution_op)) h2_measurement = StateFn(two_qubit_H2).adjoint() print(h2_measurement) bell = CX @ (I ^ H) @ Zero print(bell) evo_and_meas = h2_measurement @ evolution_op @ bell print(evo_and_meas) trotterized_op = PauliTrotterEvolution(trotter_mode=Suzuki(order=2, reps=1)).convert(evo_and_meas) # We can also set trotter_mode='suzuki' or leave it empty to default to first order Trotterization. print(trotterized_op) bound = trotterized_op.bind_parameters({evo_time: .5}) bound[1].to_circuit().draw() # Note that XX was the only non-diagonal measurement in our H2 Observable print(PauliExpectation(group_paulis=False).convert(h2_measurement)) print(PauliExpectation().convert(h2_measurement)) diagonalized_meas_op = PauliExpectation().convert(trotterized_op) print(diagonalized_meas_op) evo_time_points = list(range(8)) h2_trotter_expectations = diagonalized_meas_op.bind_parameters({evo_time: evo_time_points}) h2_trotter_expectations.eval() sampler = CircuitSampler(backend=Aer.get_backend('aer_simulator')) # sampler.quantum_instance.run_config.shots = 1000 sampled_trotter_exp_op = sampler.convert(h2_trotter_expectations) sampled_trotter_energies = sampled_trotter_exp_op.eval() print('Sampled Trotterized energies:\n {}'.format(np.real(sampled_trotter_energies))) print('Before:\n') print(h2_trotter_expectations.reduce()[0][0]) print('\nAfter:\n') print(sampled_trotter_exp_op[0][0]) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
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/sprynder/QuantumApproximationOptimizationAlgorithm
sprynder
#In case you don't have qiskit, install it now %pip install qiskit --quiet #Installing/upgrading pylatexenc seems to have fixed my mpl issue #If you try this and it doesn't work, try also restarting the runtime/kernel %pip install pylatexenc --quiet !pip install -Uqq ipdb !pip install qiskit_optimization import networkx as nx import matplotlib.pyplot as plt from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import BasicAer from qiskit.compiler import transpile from qiskit.quantum_info.operators import Operator, Pauli from qiskit.quantum_info import process_fidelity from qiskit.extensions.hamiltonian_gate import HamiltonianGate from qiskit.extensions import RXGate, XGate, CXGate from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, execute import numpy as np from qiskit.visualization import plot_histogram import ipdb from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * #quadratic optimization from qiskit_optimization import QuadraticProgram from qiskit_optimization.converters import QuadraticProgramToQubo %pdb on # def ApplyCost(qc, gamma): # Ix = np.array([[1,0],[0,1]]) # Zx= np.array([[1,0],[0,-1]]) # Xx = np.array([[0,1],[1,0]]) # Temp = (Ix-Zx)/2 # T = Operator(Temp) # I = Operator(Ix) # Z = Operator(Zx) # X = Operator(Xx) # FinalOp=-2*(T^I^T)-(I^T^T)-(T^I^I)+2*(I^T^I)-3*(I^I^T) # ham = HamiltonianGate(FinalOp,gamma) # qc.append(ham,[0,1,2]) task = QuadraticProgram(name = 'QUBO on QC') task.binary_var(name = 'x') task.binary_var(name = 'y') task.binary_var(name = 'z') task.minimize(linear = {"x":-1,"y":2,"z":-3}, quadratic = {("x", "z"): -2, ("y", "z"): -1}) qubo = QuadraticProgramToQubo().convert(task) #convert to QUBO operator, offset = qubo.to_ising() print(operator) # ham = HamiltonianGate(operator,0) # print(ham) Ix = np.array([[1,0],[0,1]]) Zx= np.array([[1,0],[0,-1]]) Xx = np.array([[0,1],[1,0]]) Temp = (Ix-Zx)/2 T = Operator(Temp) I = Operator(Ix) Z = Operator(Zx) X = Operator(Xx) FinalOp=-2*(T^I^T)-(I^T^T)-(T^I^I)+2*(I^T^I)-3*(I^I^T) ham = HamiltonianGate(FinalOp,0) print(ham) #define PYBIND11_DETAILED_ERROR_MESSAGES def compute_expectation(counts): """ Computes expectation value based on measurement results Args: counts: dict key as bitstring, val as count G: networkx graph Returns: avg: float expectation value """ avg = 0 sum_count = 0 for bitstring, count in counts.items(): x = int(bitstring[2]) y = int(bitstring[1]) z = int(bitstring[0]) obj = -2*x*z-y*z-x+2*y-3*z avg += obj * count sum_count += count return avg/sum_count # We will also bring the different circuit components that # build the qaoa circuit under a single function def create_qaoa_circ(theta): """ Creates a parametrized qaoa circuit Args: G: networkx graph theta: list unitary parameters Returns: qc: qiskit circuit """ nqubits = 3 n,m=3,3 p = len(theta)//2 # number of alternating unitaries qc = QuantumCircuit(nqubits,nqubits) Ix = np.array([[1,0],[0,1]]) Zx= np.array([[1,0],[0,-1]]) Xx = np.array([[0,1],[1,0]]) Temp = (Ix-Zx)/2 T = Operator(Temp) I = Operator(Ix) Z = Operator(Zx) X = Operator(Xx) FinalOp=-2*(Z^I^Z)-(I^Z^Z)-(Z^I^I)+2*(I^Z^I)-3*(I^I^Z) beta = theta[:p] gamma = theta[p:] # initial_state for i in range(0, nqubits): qc.h(i) for irep in range(0, p): #ipdb.set_trace(context=6) # problem unitary # for pair in list(G.edges()): # qc.rzz(2 * gamma[irep], pair[0], pair[1]) #ApplyCost(qc,2*0) ham = HamiltonianGate(operator,2 * gamma[irep]) qc.append(ham,[0,1,2]) # mixer unitary for i in range(0, nqubits): qc.rx(2 * beta[irep], i) qc.measure(qc.qubits[:n],qc.clbits[:m]) return qc # Finally we write a function that executes the circuit on the chosen backend def get_expectation(shots=512): """ Runs parametrized circuit Args: G: networkx graph p: int, Number of repetitions of unitaries """ backend = Aer.get_backend('qasm_simulator') backend.shots = shots def execute_circ(theta): qc = create_qaoa_circ(theta) # ipdb.set_trace(context=6) counts = {} job = execute(qc, backend, shots=1024) result = job.result() counts=result.get_counts(qc) return compute_expectation(counts) return execute_circ from scipy.optimize import minimize expectation = get_expectation() res = minimize(expectation, [1, 1], method='COBYLA') expectation = get_expectation() res = minimize(expectation, res.x, method='COBYLA') res from qiskit.visualization import plot_histogram backend = Aer.get_backend('aer_simulator') backend.shots = 512 qc_res = create_qaoa_circ(res.x) backend = Aer.get_backend('qasm_simulator') job = execute(qc_res, backend, shots=1024) result = job.result() counts=result.get_counts(qc_res) plot_histogram(counts)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.second_q.drivers import PySCFDriver driver = PySCFDriver( atom="H 0 0 0; H 0 0 0.72" # Two Hydrogen atoms, 0.72 Angstrom apart ) molecule = driver.run() from qiskit_nature.second_q.mappers import QubitConverter, ParityMapper qubit_converter = QubitConverter(ParityMapper()) hamiltonian = qubit_converter.convert(molecule.second_q_ops()[0]) from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver sol = NumPyMinimumEigensolver().compute_minimum_eigenvalue(hamiltonian) real_solution = molecule.interpret(sol) real_solution.groundenergy from qiskit_ibm_runtime import QiskitRuntimeService, Estimator, Session, Options service = QiskitRuntimeService() backend = "ibmq_qasm_simulator" from qiskit.algorithms.minimum_eigensolvers import VQE # Use RealAmplitudes circuit to create trial states from qiskit.circuit.library import RealAmplitudes ansatz = RealAmplitudes(num_qubits=2, reps=2) # Search for better states using SPSA algorithm from qiskit.algorithms.optimizers import SPSA optimizer = SPSA(150) # Set a starting point for reproduceability import numpy as np np.random.seed(6) initial_point = np.random.uniform(-np.pi, np.pi, 12) # Create an object to store intermediate results from dataclasses import dataclass @dataclass class VQELog: values: list parameters: list def update(self, count, parameters, mean, _metadata): self.values.append(mean) self.parameters.append(parameters) print(f"Running circuit {count} of ~350", end="\r", flush=True) log = VQELog([],[]) # Main calculation with Session(service=service, backend=backend) as session: options = Options() options.optimization_level = 3 vqe = VQE(Estimator(session=session, options=options), ansatz, optimizer, callback=log.update, initial_point=initial_point) result = vqe.compute_minimum_eigenvalue(hamiltonian) print("Experiment complete.".ljust(30)) print(f"Raw result: {result.optimal_value}") if 'simulator' not in backend: # Run once with ZNE error mitigation options.resilience_level = 2 vqe = VQE(Estimator(session=session, options=options), ansatz, SPSA(1), initial_point=result.optimal_point) result = vqe.compute_minimum_eigenvalue(hamiltonian) print(f"Mitigated result: {result.optimal_value}") import matplotlib.pyplot as plt plt.rcParams["font.size"] = 14 # Plot energy and reference value plt.figure(figsize=(12, 6)) plt.plot(log.values, label="Estimator VQE") plt.axhline(y=real_solution.groundenergy, color="tab:red", ls="--", label="Target") plt.legend(loc="best") plt.xlabel("Iteration") plt.ylabel("Energy [H]") plt.title("VQE energy") plt.show() import qiskit_ibm_runtime qiskit_ibm_runtime.version.get_version_info() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/hkhetawat/QArithmetic
hkhetawat
from math import pi from qiskit import QuantumRegister, QuantumCircuit, AncillaRegister from qft import qft, iqft, cqft, ciqft, ccu1 from qiskit.circuit.library import SXdgGate ################################################################################ # Bitwise Operators ################################################################################ # bit-wise operations def bitwise_and(qc, a, b, c, N): for i in range(0, N): qc.ccx(a[i], b[i], c[i]) def bitwise_or(qc, a, b, c, N): for i in range(0, N): qc.ccx(a[i], b[i], c[i]) qc.cx(a[i], c[i]) qc.cx(b[i], c[i]) def bitwise_xor(qc, a, b, c, N): for i in range(0, N): qc.cx(a[i], c[i]) qc.cx(b[i], c[i]) def bitwise_not(qc, a, c, N): for i in range(0, N): qc.cx(a[i], c[i]) qc.x(c[i]) # Cyclically left-shifts a binary string "a" of length n. # If "a" is zero-padded, equivalent to multiplying "a" by 2. def lshift(circ, a, n=-1): # Init n if it was not if n == -1: n = len(a) # Iterate through pairs and do swaps. for i in range(n,1,-1): circ.swap(a[i-1],a[i-2]) # Cyclically left-shifts a binary string "a" of length n, controlled by c. # If "a" is zero-padded, equivalent to multiplying "a" by 2, if and only if c. def c_lshift(circ, c, a, n=-1): # Init n if it was not if n == -1: n = len(a) # Iterate through pairs and do swaps. for i in range(n,1,-1): circ.cswap(c, a[i-1],a[i-2]) # Cyclically right-shifts a binary string "a" of length n. # If "a" is zero-padded, equivalent to dividing "a" by 2. def rshift(circ, a, n=-1): # Init n if it was not if n == -1: n = len(a) # Iterate through pairs and do swaps. for i in range(n-1): circ.swap(a[i],a[i+1]) # Cyclically right-shifts a binary string "a" of length n, controlled by c. # If "a" is zero-padded, equivalent to dividing "a" by 2, if and only if c. def c_rshift(circ, c, a, n=-1): # Init n if it was not if n == -1: n = len(a) # Iterate through pairs and do swaps. for i in range(n,1,-1): circ.cswap(c, a[i-1],a[i-2]) ################################################################################ # Addition Circuits ################################################################################ # Define some functions for the ripple adder. def sum(circ, cin, a, b): circ.cx(a,b) circ.cx(cin,b) def carry(circ, cin, a, b, cout): circ.ccx(a, b, cout) circ.cx(a, b) circ.ccx(cin, b, cout) def carry_dg(circ, cin, a, b, cout): circ.ccx(cin, b, cout) circ.cx(a, b) circ.ccx(a, b, cout) # Draper adder that takes |a>|b> to |a>|a+b>. # |a> has length x and is less than or equal to n # |b> has length n+1 (left padded with a zero). # https://arxiv.org/pdf/quant-ph/0008033.pdf def add(circ, a, b, n): # move n forward by one to account for overflow n += 1 # Take the QFT. qft(circ, b, n) # Compute controlled-phases. # Iterate through the targets. for i in range(n,0,-1): # Iterate through the controls. for j in range(i,0,-1): # If the qubit a[j-1] exists run cu1, if not assume the qubit is 0 and never existed if len(a) - 1 >= j - 1: circ.cu1(2*pi/2**(i-j+1), a[j-1], b[i-1]) # Take the inverse QFT. iqft(circ, b, n) # Draper adder that takes |a>|b> to |a>|a+b>, controlled on |c>. # |a> has length x and is less than or equal to n # |b> has length n+1 (left padded with a zero). # |c> is a single qubit that's the control. def cadd(circ, c, a, b, n): # move n forward by one to account for overflow n += 1 # Take the QFT. cqft(circ, c, b, n) # Compute controlled-phases. # Iterate through the targets. for i in range(n,0,-1): # Iterate through the controls. for j in range(i,0,-1): # If the qubit a[j-1] exists run ccu, if not assume the qubit is 0 and never existed if len(a) - 1 >= j - 1: ccu1(circ, 2*pi/2**(i-j+1), c, a[j-1], b[i-1]) # Take the inverse QFT. ciqft(circ, c, b, n) # Adder that takes |a>|b> to |a>|a+b>. # |a> has length n. # |b> has length n+1. # Based on Vedral, Barenco, and Ekert (1996). def add_ripple(circ, a, b, n): # Create a carry register of length n. c = QuantumRegister(n) circ.add_register(c) # Calculate all the carries except the last one. for i in range(0, n-1): carry(circ, c[i], a[i], b[i], c[i+1]) # The last carry bit is the leftmost bit of the sum. carry(circ, c[n-1], a[n-1], b[n-1], b[n]) # Calculate the second-to-leftmost bit of the sum. circ.cx(c[n-1],b[n-1]) # Invert the carries and calculate the remaining sums. for i in range(n-2,-1,-1): carry_dg(circ, c[i], a[i], b[i], c[i+1]) sum(circ, c[i], a[i], b[i]) # Adder that takes |a>|b>|0> to |a>|b>|a+b>. # |a> has length n. # |b> has length n. # |s> = |0> has length n+1. def add_ripple_ex(circ, a, b, s, n): # Copy b to s. for i in range(0, n): circ.cx(b[i],s[i]) # Add a and s. add_ripple(circ, a, s, n) ################################################################################ # Subtraction Circuits ################################################################################ # Subtractor that takes |a>|b> to |a>|a-b>. # |a> has length n+1 (left padded with a zero). # |b> has length n+1 (left padded with a zero). def sub(circ, a, b, n): # Flip the bits of a. circ.x(a) # Add it to b. add(circ, a, b, n - 1) # Flip the bits of the result. This yields the sum. circ.x(b) # Flip back the bits of a. circ.x(a) # Subtractor that takes |a>|b> to |a-b>|b>. # |a> has length n+1 (left padded with a zero). # |b> has length n+1 (left padded with a zero). def sub_swap(circ, a, b, n): # Flip the bits of a. circ.x(a) # Add it to b. add(circ, b, a, n - 1) # Flip the bits of the result. This yields the sum. circ.x(a) # Subtractor that takes |a>|b> to |a>|a-b>. # |a> has length n. # |b> has length n+1. def sub_ripple(circ, a, b, n): # We add "a" to the 2's complement of "b." # First flip the bits of "b." circ.x(b) # Create a carry register of length n. c = QuantumRegister(n) circ.add_register(c) # Add 1 to the carry register, which adds 1 to b, negating it. circ.x(c[0]) # Calculate all the carries except the last one. for i in range(0, n-1): carry(circ, c[i], a[i], b[i], c[i+1]) # The last carry bit is the leftmost bit of the sum. carry(circ, c[n-1], a[n-1], b[n-1], b[n]) # Calculate the second-to-leftmost bit of the sum. circ.cx(c[n-1],b[n-1]) # Invert the carries and calculate the remaining sums. for i in range(n-2,-1,-1): carry_dg(circ, c[i], a[i], b[i], c[i+1]) sum(circ, c[i], a[i], b[i]) # Flip the carry to restore it to zero. circ.x(c[0]) # Subtractor that takes |a>|b>|0> to |a>|b>|a-b>. # |a> has length n. # |b> has length n. # |s> = |0> has length n+1. def sub_ripple_ex(circ, a, b, s, n): # Copy b to s. for i in range(0, n): circ.cx(b[i],s[i]) # Subtract a and s. sub_ripple(circ, a, s, n) ################################################################################ # Multiplication Circuit ################################################################################ # Controlled operations # Take a subset of a quantum register from index x to y, inclusive. def sub_qr(qr, x, y): # may also be able to use qbit_argument_conversion sub = [] for i in range (x, y+1): sub = sub + [(qr[i])] return sub def full_qr(qr): return sub_qr(qr, 0, len(qr) - 1) # Computes the product c=a*b. # a has length n. # b has length n. # c has length 2n. def mult(circ, a, b, c, n): for i in range (0, n): cadd(circ, a[i], b, sub_qr(c, i, n+i), n) # Computes the product c=a*b if and only if control. # a has length n. # b has length n. # control has length 1. # c has length 2n. def cmult(circ, control, a, b, c, n): qa = QuantumRegister(len(a)) qb = QuantumRegister(len(b)) qc = QuantumRegister(len(c)) tempCircuit = QuantumCircuit(qa, qb, qc) mult(tempCircuit, qa, qb, qc, n) tempCircuit = tempCircuit.control(1) #Add Decomposition after pull request inclusion #5446 on terra print("Remember To Decompose after release >0.16.1") circ.compose(tempCircuit, qubits=full_qr(control) + full_qr(a) + full_qr(b) + full_qr(c), inplace=True) ################################################################################ # Division Circuit ################################################################################ # Divider that takes |p>|d>|q>. # |p> is length 2n and has n zeros on the left: 0 ... 0 p_n ... p_1. # |d> has length 2n and has n zeros on the right: d_2n ... d_{n+1) 0 ... 0. # |q> has length n and is initially all zeros. # At the end of the algorithm, |q> will contain the quotient of p/d, and the # left n qubits of |p> will contain the remainder of p/d. def div(circ, p, d, q, n): # Calculate each bit of the quotient and remainder. for i in range(n,0,-1): # Left shift |p>, which multiplies it by 2. lshift(circ, p, 2*n) # Subtract |d> from |p>. sub_swap(circ, p, d, 2*n) # If |p> is positive, indicated by its most significant bit being 0, # the (i-1)th bit of the quotient is 1. circ.x(p[2*n-1]) circ.cx(p[2*n-1], q[i-1]) circ.x(p[2*n-1]) # If |p> is negative, indicated by the (i-1)th bit of |q> being 0, add D back # to P. circ.x(q[i-1]) cadd(circ, q[i-1], d, p, 2*n - 1) circ.x(q[i-1]) ################################################################################ # Expontential Circuit ################################################################################ # square that takes |a> |b> # |a> is length n and is a unsigned integer # |b> is length 2n and has 2n zeros, after execution b = a^2 def square(circ, a, b, n=-1): if n == -1: n = len(a) # First Addition circ.cx(a[0], b[0]) for i in range(1, n): circ.ccx(a[0], a[i], b[i]) # Custom Addition Circuit For Each Qubit of A for k in range(1, n): # modifying qubits d = b[k:n+k+1] qft(circ, d, n+1) #Technically the first few QFT could be refactored to use less gates due to guaranteed controls # Compute controlled-phases. # Iterate through the targets. for i in range(n+1,0,-1): # Iterate through the controls. for j in range(i,0,-1): if len(a) - 1 < j - 1: pass # skip over non existent qubits elif k == j - 1: # Cannot control twice circ.cu1(2*pi/2**(i-j+1), a[j-1], d[i-1]) else: ccu1(circ, 2*pi/2**(i-j+1), a[k], a[j-1], d[i-1]) iqft(circ, d, n+1) # a has length n # b has length v # finalOut has length n*((2^v)-1), for safety def power(circ, a, b, finalOut): #Because this is reversible/gate friendly memory blooms to say the least # Track Number of Qubits n = len(a) v = len(b) # Left 0 pad a, to satisfy multiplication function arguments aPad = AncillaRegister(n * (pow(2, v) - 3)) # Unsure of where to Anciallas these circ.add_register(aPad) padAList = full_qr(aPad) aList = full_qr(a) a = aList + padAList # Create a register d for mults and init with state 1 d = AncillaRegister(n) # Unsure of where to Anciallas these circ.add_register(d) # Create a register for tracking the output of cmult to the end ancOut = AncillaRegister(n*2) # Unsure of where to Anciallas these circ.add_register(ancOut) # Left 0 pad finalOut to provide safety to the final multiplication if (len(a) * 2) - len(finalOut) > 0: foPad = AncillaRegister((len(a) * 2) - len(finalOut)) circ.add_register(foPad) padFoList = full_qr(foPad) foList = full_qr(finalOut) finalOut = foList + padFoList # Create zero bits num_recycle = (2 * n * (pow(2, v) - 2)) - (n * pow(2, v)) # 24 permaZeros = [] if num_recycle > 0: permaZeros = AncillaRegister(num_recycle) #8 circ.add_register(permaZeros) permaZeros = full_qr(permaZeros) # Instead of MULT copy bits over if v >= 1: for i in range(n): circ.ccx(b[0], a[i], d[i]) circ.x(b[0]) circ.cx(b[0], d[0]) circ.x(b[0]) # iterate through every qubit of b for i in range(1,v): # for every bit of b for j in range(pow(2, i)): # run multiplication operation if and only if b is 1 bonus = permaZeros[:2*len(d) - len(ancOut)] cmult(circ, [b[i]], a[:len(d)], d, full_qr(ancOut) + bonus, len(d)) # if the multiplication was not run copy the qubits so they are not destroyed when creating new register circ.x(b[i]) for qub in range(0,len(d)): circ.ccx(b[i], d[qub], ancOut[qub]) circ.x(b[i]) # Move the output to the input for next function and double the qubit length d = ancOut if i == v - 1 and j == pow(2, i) - 2: # this is the second to last step send qubiits to output ancOut = finalOut elif not (i == v - 1 and j == pow(2, i) - 1): # if this is not the very last step # create a new output register of twice the length and register it ancOut = AncillaRegister(len(d) + n) # Should label permazero bits circ.add_register(ancOut)
https://github.com/Pitt-JonesLab/slam_decomposition
Pitt-JonesLab
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Weyl decomposition of two-qubit gates in terms of echoed cross-resonance gates.""" import cmath import numpy as np import scipy.linalg as la from qiskit import QuantumCircuit from qiskit.circuit.library import IGate, RXGate, RYGate, RZGate from qiskit.converters import circuit_to_dag from qiskit.dagcircuit import DAGCircuit from qiskit.extensions.unitary import UnitaryGate from qiskit.quantum_info.synthesis.two_qubit_decompose import * from qiskit.transpiler.basepasses import TransformationPass from qiskit.transpiler.exceptions import TranspilerError from clonk.utils.qiskit_patch.two_qubit_decompose import TwoQubitBasisDecomposer from clonk.utils.riswap_gates.equivalence_library import SessionEquivalenceLibrary # from qiskit.circuit.library.standard_gates import * from clonk.utils.riswap_gates.riswap import RiSwapGate, fSim _sel = SessionEquivalenceLibrary class RootiSwapWeylDecomposition(TransformationPass): """Rewrite two-qubit gates using the Weyl decomposition. This transpiler pass rewrites two-qubit gates in terms of root iswap gates according to the Weyl decomposition. A two-qubit gate will be replaced with at most 3 root i swap gates. """ def __init__(self, basis_gate=False): """RootiSwapWeylDecomposition pass. Args: instruction_schedule_map (InstructionScheduleMap): the mapping from circuit :class:`~.circuit.Instruction` names and arguments to :class:`.Schedule`\\ s. """ super().__init__() # self.requires = [ # BasisTranslator(_sel, ["u3", "cu3", "cp", "swap", "riswap", "id"]) # ] # self.decompose_swaps = decompose_swaps self.basis_gate = basis_gate # @staticmethod # def _improper_orthogonal_decomp(x, y, z): # alpha = np.arccos( # np.cos(2 * z) - np.cos(2 * y) + np.sqrt((np.cos(4 * z) + np.cos(4 * y)) / 2) # ) # beta = np.arccos( # np.cos(2 * z) - np.cos(2 * y) - np.sqrt((np.cos(4 * z) + np.cos(4 * y)) / 2) # ) # gamma = 0 # psi = -np.arccos(np.sqrt((1 + np.tan(y - z)) / 2)) # phi = np.arccos(np.sqrt((1 + np.tan(y + z)) / 2)) # def_Lxyz = QuantumCircuit(2) # # ISwap # if np.isclose(x, y) and np.isclose(z, 0): # def_Lxyz.append(RiSwapGate(0.5), [0, 1]) # def_Lxyz.rz(2 * x, 0) # def_Lxyz.rz(-2 * x + np.pi, 1) # def_Lxyz.append(RiSwapGate(0.5), [0, 1]) # def_Lxyz.rz(-np.pi, 1) # return def_Lxyz # # CPhase # if np.isclose(y, 0) and np.isclose(z, 0): # def_Lxyz.rz(np.arcsin(np.tan(x)), 1) # def_Lxyz.rx(-np.pi / 2, 1) # def_Lxyz.append(RiSwapGate(0.5), [0, 1]) # def_Lxyz.z(1) # def_Lxyz.ry(2 * np.arcsin(np.sqrt(2) * np.sin(x)), 1) # def_Lxyz.append(RiSwapGate(0.5), [0, 1]) # def_Lxyz.rx(-np.pi / 2, 1) # def_Lxyz.rz(np.arcsin(np.tan(x)) - np.pi, 1) # return def_Lxyz # # Canonicalized SWAP # elif np.isclose(x, np.pi / 4) and y + np.abs(z) <= np.pi / 4: # def_Lxyz.rx(phi + psi, 0) # def_Lxyz.rz(np.pi / 2, 1) # def_Lxyz.rx(phi - psi, 1) # def_Lxyz.append(RiSwapGate(0.5), [0, 1]) # def_Lxyz.rx(alpha, 0) # def_Lxyz.rx(beta, 1) # def_Lxyz.append(RiSwapGate(0.5), [0, 1]) # def_Lxyz.rx(phi + psi, 0) # def_Lxyz.rx(phi - psi, 1) # def_Lxyz.rz(-np.pi / 2, 1) # return def_Lxyz # else: # raise NotImplementedError # @staticmethod # def cphase_decomp(unitary): # # assuming unitary is a CPhase, is true per self.requires pass # # TODO function structure needs to be reoganized to use canonicalize function # x, y, z = weyl_coordinates(Operator(unitary).data) # def_CPhase = RootiSwapWeylDecomposition._improper_orthogonal_decomp(x, y, z) # return def_CPhase # # Note this is the way suggested by alibaba paper, but google has a swap->riswap(1/2) decomp rule that uses less 1Q gates # @staticmethod # def swap_decomp(unitary): # # FIXME: green, blue, maroon rules # def_swap = QuantumCircuit(2) # def_swap.z(0) # def_swap.rx(np.pi / 2, 0) # def_swap.z(0) # def_swap.rx(-np.pi / 2, 1) # x, y, z = weyl_coordinates(Operator(unitary).data) # def_swap += RootiSwapWeylDecomposition._improper_orthogonal_decomp( # x, y - np.pi / 4, z - np.pi / 4 # ) # def_swap.z(0) # def_swap.rx(-np.pi / 2, 0) # def_swap.rz(np.pi / 2, 0) # def_swap.ry(-np.pi / 2, 0) # def_swap.z(0) # def_swap.rx(np.pi / 2, 1) # def_swap.rz(-np.pi / 2, 1) # def_swap.ry(np.pi / 2, 1) # def_swap.append(RiSwapGate(0.5), [0, 1]) # def_swap.z(0) # def_swap.ry(np.pi / 2, 0) # def_swap.rz(-np.pi / 2, 0) # def_swap.z(0) # def_swap.ry(-np.pi / 2, 1) # def_swap.rz(np.pi / 2, 1) # return def_swap # reference: https://arxiv.org/pdf/2105.06074.pdf # from Qiskits two_qubit_decomp #FIXME moving functions around still this won't need to be copied once SQiSwap inside of that same pass def KAKDecomp(self, unitary_matrix, *, fidelity=(1.0 - 1.0e-9)): _ipx = np.array([[0, 1j], [1j, 0]], dtype=complex) _ipy = np.array([[0, 1], [-1, 0]], dtype=complex) _ipz = np.array([[1j, 0], [0, -1j]], dtype=complex) _id = np.array([[1, 0], [0, 1]], dtype=complex) """Perform the Weyl chamber decomposition, and optionally choose a specialized subclass. The flip into the Weyl Chamber is described in B. Kraus and J. I. Cirac, Phys. Rev. A 63, 062309 (2001). FIXME: There's a cleaner-seeming method based on choosing branch cuts carefully, in Andrew M. Childs, Henry L. Haselgrove, and Michael A. Nielsen, Phys. Rev. A 68, 052311, but I wasn't able to get that to work. The overall decomposition scheme is taken from Drury and Love, arXiv:0806.4015 [quant-ph]. """ pi = np.pi pi2 = np.pi / 2 pi4 = np.pi / 4 # Make U be in SU(4) U = np.array(unitary_matrix, dtype=complex, copy=True) detU = la.det(U) U *= detU ** (-0.25) global_phase = cmath.phase(detU) / 4 Up = transform_to_magic_basis(U, reverse=True) M2 = Up.T.dot(Up) # M2 is a symmetric complex matrix. We need to decompose it as M2 = P D P^T where # P ∈ SO(4), D is diagonal with unit-magnitude elements. # # We can't use raw `eig` directly because it isn't guaranteed to give us real or othogonal # eigenvectors. Instead, since `M2` is complex-symmetric, # M2 = A + iB # for real-symmetric `A` and `B`, and as # M2^+ @ M2 = A^2 + B^2 + i [A, B] = 1 # we must have `A` and `B` commute, and consequently they are simultaneously diagonalizable. # Mixing them together _should_ account for any degeneracy problems, but it's not # guaranteed, so we repeat it a little bit. The fixed seed is to make failures # deterministic; the value is not important. state = np.random.default_rng(2020) for _ in range(100): # FIXME: this randomized algorithm is horrendous M2real = state.normal() * M2.real + state.normal() * M2.imag _, P = np.linalg.eigh(M2real) D = P.T.dot(M2).dot(P).diagonal() if np.allclose(P.dot(np.diag(D)).dot(P.T), M2, rtol=0, atol=1.0e-13): break else: raise ValueError d = -np.angle(D) / 2 d[3] = -d[0] - d[1] - d[2] cs = np.mod((d[:3] + d[3]) / 2, 2 * np.pi) # Reorder the eigenvalues to get in the Weyl chamber cstemp = np.mod(cs, pi2) np.minimum(cstemp, pi2 - cstemp, cstemp) order = np.argsort(cstemp)[[1, 2, 0]] cs = cs[order] d[:3] = d[order] P[:, :3] = P[:, order] # Fix the sign of P to be in SO(4) if np.real(la.det(P)) < 0: P[:, -1] = -P[:, -1] # Find K1, K2 so that U = K1.A.K2, with K being product of single-qubit unitaries K1 = transform_to_magic_basis(Up @ P @ np.diag(np.exp(1j * d))) K2 = transform_to_magic_basis(P.T) K1l, K1r, phase_l = decompose_two_qubit_product_gate(K1) K2l, K2r, phase_r = decompose_two_qubit_product_gate(K2) global_phase += phase_l + phase_r K1l = K1l.copy() # Flip into Weyl chamber if cs[0] > pi2: cs[0] -= 3 * pi2 K1l = K1l.dot(_ipy) K1r = K1r.dot(_ipy) global_phase += pi2 if cs[1] > pi2: cs[1] -= 3 * pi2 K1l = K1l.dot(_ipx) K1r = K1r.dot(_ipx) global_phase += pi2 conjs = 0 if cs[0] > pi4: cs[0] = pi2 - cs[0] K1l = K1l.dot(_ipy) K2r = _ipy.dot(K2r) conjs += 1 global_phase -= pi2 if cs[1] > pi4: cs[1] = pi2 - cs[1] K1l = K1l.dot(_ipx) K2r = _ipx.dot(K2r) conjs += 1 global_phase += pi2 if conjs == 1: global_phase -= pi if cs[2] > pi2: cs[2] -= 3 * pi2 K1l = K1l.dot(_ipz) K1r = K1r.dot(_ipz) global_phase += pi2 if conjs == 1: global_phase -= pi if conjs == 1: cs[2] = pi2 - cs[2] K1l = K1l.dot(_ipz) K2r = _ipz.dot(K2r) global_phase += pi2 if cs[2] > pi4: cs[2] -= pi2 K1l = K1l.dot(_ipz) K1r = K1r.dot(_ipz) global_phase -= pi2 a, b, c = cs[1], cs[0], cs[2] return global_phase, (a, b, c), K1l, K1r, K2l, K2r # Reference: https://quantumai.google/reference/python/cirq/transformers/decompose_two_qubit_interaction_into_four_fsim_gates def SYCDecomposer(self, U): qc = QuantumCircuit(2) # totally ignorning 1Q gates because we are just using this method for counting 2Q gate durations qc.append(fSim(np.pi / 2, np.pi / 6), [0, 1]) qc.append(fSim(np.pi / 2, np.pi / 6), [0, 1]) qc.append(fSim(np.pi / 2, np.pi / 6), [0, 1]) qc.append(fSim(np.pi / 2, np.pi / 6), [0, 1]) return qc # Reference: https://arxiv.org/pdf/2105.06074.pdf def riswapWeylDecomp(self, U): """Decompose U into single qubit gates and the SQiSW gates.""" qc = QuantumCircuit(2) _, (x, y, z), A1, A2, B1, B2 = self.KAKDecomp(U) if np.abs(z) <= x - y: C1, C2 = self.interleavingSingleQubitRotations(x, y, z) V = ( RiSwapGate(0.5).to_matrix() @ np.kron(C1, C2) @ RiSwapGate(0.5).to_matrix() ) _, (x, y, z), D1, D2, E1, E2 = self.KAKDecomp(V) qc.append(UnitaryGate(np.matrix(E1).H @ B1), [1]) qc.append(UnitaryGate(np.matrix(E2).H @ B2), [0]) qc.append(RiSwapGate(0.5), [0, 1]) qc.append(UnitaryGate(C1), [1]) qc.append(UnitaryGate(C2), [0]) qc.append(RiSwapGate(0.5), [0, 1]) qc.append(UnitaryGate(A1 @ np.matrix(D1).H), [1]) qc.append(UnitaryGate(A2 @ np.matrix(D2).H), [0]) else: (x, y, z), F1, F2, G1, G2, H1, H2 = self.canonicalize(x, y, z) C1, C2 = self.interleavingSingleQubitRotations(x, y, z) V = ( RiSwapGate(0.5).to_matrix() @ np.kron(C1, C2) @ RiSwapGate(0.5).to_matrix() ) _, (x, y, z), D1, D2, E1, E2 = self.KAKDecomp(V) qc.append(UnitaryGate(H1 @ B1), [1]) qc.append(UnitaryGate(H2 @ B2), [0]) qc.append(RiSwapGate(0.5), [0, 1]) qc.append(UnitaryGate(np.matrix(E1).H @ G1), [1]) qc.append(UnitaryGate(np.matrix(E2).H @ G2), [0]) qc.append(RiSwapGate(0.5), [0, 1]) qc.append(UnitaryGate(C1), [1]) qc.append(UnitaryGate(C2), [0]) qc.append(RiSwapGate(0.5), [0, 1]) qc.append(UnitaryGate(A1 @ F1 @ np.matrix(D1).H), [1]) qc.append(UnitaryGate(A2 @ F2 @ np.matrix(D2).H), [0]) return qc.decompose() def interleavingSingleQubitRotations(self, x, y, z): """Output the single qubit rotations given the interaction coefficients (x,y,z) \in W' when sandiwched by two SQiSW gates.""" C = ( np.sin(x + y - z) * np.sin(x - y + z) * np.sin(-x - y - z) * np.sin(-x + y + z) ) alpha = np.arccos( np.cos(2 * x) - np.cos(2 * y) + np.cos(2 * z) + 2 * np.sqrt(C) ) beta = np.arccos(np.cos(2 * x) - np.cos(2 * y) + np.cos(2 * z) - 2 * np.sqrt(C)) _num = 4 * (np.cos(x) ** 2) * (np.cos(z) ** 2) * (np.cos(y) ** 2) _den = _num + np.cos(2 * x) + np.cos(2 * y) * np.cos(2 * z) gamma = np.arccos(np.sign(z) * np.sqrt(_num / _den)) return ( RZGate(gamma).to_matrix() @ RXGate(alpha).to_matrix() @ RZGate(gamma).to_matrix(), RXGate(beta).to_matrix(), ) def canonicalize(self, x, y, z): """Decompose an arbitrary gate into one SQISW and one L(x,y',z) where (x',y',z') \in W' and output the coefficients (x',y',z') and the interleaving single qubit rotations.""" A1 = IGate().to_matrix() A2 = IGate().to_matrix() B1 = RYGate(-np.pi / 2).to_matrix() B2 = RYGate(np.pi / 2).to_matrix() C1 = RYGate(np.pi / 2).to_matrix() C2 = RYGate(-np.pi / 2).to_matrix() s = np.sign(z) z = np.abs(z) if x > np.pi / 8: y = y - np.pi / 8 z = z - np.pi / 8 B1 = RZGate(np.pi / 2).to_matrix() @ B1 B2 = RZGate(-np.pi / 2).to_matrix() @ B2 C1 = C1 @ RZGate(-np.pi / 2).to_matrix() C2 = C2 @ RZGate(np.pi / 2).to_matrix() else: x = x + np.pi / 8 z = z - np.pi / 8 if np.abs(y) < np.abs(z): # XXX typo in alibaba here (?) z = -z A1 = RXGate(np.pi / 2).to_matrix() A2 = RXGate(-np.pi / 2).to_matrix() B1 = RXGate(-np.pi / 2).to_matrix() @ B1 B2 = RXGate(np.pi / 2).to_matrix() @ B2 if s < 0: z = -z A1 = RZGate(np.pi).to_matrix() @ A1 @ RZGate(np.pi).to_matrix() B1 = RZGate(np.pi).to_matrix() @ B1 @ RZGate(np.pi).to_matrix() C1 = RZGate(np.pi).to_matrix() @ C1 @ RZGate(np.pi).to_matrix() return (x, y, z), A1, A2, B1, B2, C1, C2 def run(self, dag: DAGCircuit): """Run the RootiSwapWeylDecomposition pass on `dag`. Rewrites two-qubit gates in an arbitrary circuit in terms of echoed cross-resonance gates by computing the Weyl decomposition of the corresponding unitary. Modifies the input dag. Args: dag (DAGCircuit): DAG to rewrite. Returns: DAGCircuit: The modified dag. Raises: TranspilerError: If the circuit cannot be rewritten. """ # pylint: disable=cyclic-import from qiskit.quantum_info import Operator if len(dag.qregs) > 1: raise TranspilerError( "RootiSwapWeylDecomposition expects a single qreg input DAG," f"but input DAG had qregs: {dag.qregs}." ) # trivial_layout = Layout.generate_trivial_layout(*dag.qregs.values()) if isinstance(self.basis_gate, RiSwapGate): self.decomposer = self.riswapWeylDecomp elif isinstance(self.basis_gate, fSim): self.decomposer = self.SYCDecomposer else: self.decomposer = TwoQubitBasisDecomposer(self.basis_gate) # add something which caches the result to SWAP so we don't have to do it every time swap_sub = None cnot_sub = None for node in dag.two_qubit_ops(): # denote 2 different decomp rules, either for swap gates, or for U gates in CPhase basis # if node.name == "riswap": # continue # FIXME need to convert unitary to a special unitary first to preserve 1Qs? unitary = Operator(node.op).data if node.name == "swap": if swap_sub is None: swap_sub = circuit_to_dag(self.decomposer(unitary)) dag.substitute_node_with_dag(node, swap_sub) continue if node.name == "cx": if cnot_sub is None: cnot_sub = circuit_to_dag(self.decomposer(unitary)) dag.substitute_node_with_dag(node, cnot_sub) continue # special_unitary = unitary dag_sub = circuit_to_dag(self.decomposer(unitary)) dag.substitute_node_with_dag(node, dag_sub) # if node.name == "swap": # if self.decompose_swaps: # dag_weyl = circuit_to_dag(self.swap_decomp(unitary)) # dag.substitute_node_with_dag(node, dag_weyl) # elif node.name == "cp": # dag_weyl = circuit_to_dag(self.cphase_decomp(unitary)) # dag.substitute_node_with_dag(node, dag_weyl) # # FIXME # # FIXME # # FIXME # # I need to double check the x,y,z coordinates -> why is CX and CPhase both (np.pi/4 ,0 ,0) # # that tells me I need to write CX in CPhase basis first to preverse 1Q gates # # but CU is 2 CPhase gates and yet still a (np.pi/4, 0, 0)- how do I preserve 1Q gates? # elif node.name == "cu3": # dag_weyl = circuit_to_dag(self.cphase_decomp(unitary)) # dag.substitute_node_with_dag(node, dag_weyl) return dag
https://github.com/MonitSharma/Learn-Quantum-Machine-Learning
MonitSharma
import pennylane as qml from pennylane import numpy as np dev1 = qml.device("default.qubit", wires=1) @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], requires_grad=True) 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/swe-train/qiskit__qiskit
swe-train
# Copyright 2022-2023 Ohad Lev. # 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, # or in the root directory of this package("LICENSE.txt"). # 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. """ `SATInterface` class. """ import os import json from typing import List, Tuple, Union, Optional, Dict, Any from sys import stdout from datetime import datetime from hashlib import sha256 from qiskit import transpile, QuantumCircuit, qpy from qiskit.result.counts import Counts from qiskit.visualization.circuit.text import TextDrawing from qiskit.providers.backend import Backend from qiskit.transpiler.passes import RemoveBarriers from IPython import display from matplotlib.figure import Figure from sat_circuits_engine.util import timer_dec, timestamp, flatten_circuit from sat_circuits_engine.util.settings import DATA_PATH, TRANSPILE_KWARGS from sat_circuits_engine.circuit import GroverConstraintsOperator, SATCircuit from sat_circuits_engine.constraints_parse import ParsedConstraints from sat_circuits_engine.interface.circuit_decomposition import decompose_operator from sat_circuits_engine.interface.counts_visualization import plot_histogram from sat_circuits_engine.interface.translator import ConstraintsTranslator from sat_circuits_engine.classical_processing import ( find_iterations_unknown, calc_iterations, ClassicalVerifier, ) from sat_circuits_engine.interface.interactive_inputs import ( interactive_operator_inputs, interactive_solutions_num_input, interactive_run_input, interactive_backend_input, interactive_shots_input, ) # Local globlas for visualization of charts and diagrams IFRAME_WIDTH = "100%" IFRAME_HEIGHT = "700" class SATInterface: """ An interface for building, running and mining data from n-SAT problems quantum circuits. There are 2 options to use this class: (1) Using an interactive interface (intuitive but somewhat limited) - for this just initiate a bare instance of this class: `SATInterface()`. (2) Using the API defined by this class, that includes the following methods: * The following descriptions are partial, for full annotations see the methods' docstrings. - `__init__`: an instance of `SATInterface must be initiated with exactly 1 combination: (a) (high_level_constraints_string + high_level_vars) - for constraints in a high-level format. (b) (num_input_qubits + constraints_string) - for constraints in a low-level foramt. * For formats annotations see `constriants_format.ipynb` in the main directory. - `obtain_grover_operator`: obtains the suitable grover operator for the constraints. - `save_display_grover_operator`: saves and displays data generated by the `obtain_grover_operator` method. - `obtain_overall_circuit`: obtains the suitable overall SAT circuit. - `save_display_overall_circuit: saves and displays data generated by the `obtain_overall_circuit` method. - `run_overall_circuit`: executes the overall SAT circuit. - `save_display_results`: saves and displays data generated by the `run_overall_circuit` method. It is very recommended to go through `demos.ipynb` that demonstrates the various optional uses of this class, in addition to reading `constraints_format.ipynb`, which is a must for using this package properly. Both notebooks are in ther main directory. """ def __init__( self, num_input_qubits: Optional[int] = None, constraints_string: Optional[str] = None, high_level_constraints_string: Optional[str] = None, high_level_vars: Optional[Dict[str, int]] = None, name: Optional[str] = None, save_data: Optional[bool] = True, ) -> None: """ Accepts the combination of paramters: (high_level_constraints_string + high_level_vars) or (num_input_qubits + constraints_string). Exactly one combination is accepted. In other cases either an iteractive user interface will be called to take user's inputs, or an exception will be raised due to misuse of the API. Args: num_input_qubits (Optional[int] = None): number of input qubits. constraints_string (Optional[str] = None): a string of constraints in a low-level format. high_level_constraints_string (Optional[str] = None): a string of constraints in a high-level format. high_level_vars (Optional[Dict[str, int]] = None): a dictionary that configures the high-level variables - keys are names and values are bits-lengths. name (Optional[str] = None): a name for this object, if None than the generic name "SAT" is given automatically. save_data (Optional[bool] = True): if True, saves all data and metadata generated by this class to a unique data folder (by using the `save_XXX` methods of this class). Raises: SyntaxError - if a forbidden combination of arguments has been provided. """ if name is None: name = "SAT" self.name = name # Creating a directory for data to be saved if save_data: self.time_created = timestamp(datetime.now()) self.dir_path = f"{DATA_PATH}{self.time_created}_{self.name}/" os.mkdir(self.dir_path) print(f"Data will be saved into '{self.dir_path}'.") # Initial metadata, more to be added by this class' `save_XXX` methods self.metadata = { "name": self.name, "datetime": self.time_created, "num_input_qubits": num_input_qubits, "constraints_string": constraints_string, "high_level_constraints_string": high_level_constraints_string, "high_level_vars": high_level_vars, } self.update_metadata() # Identifying user's platform, for visualization purposes self.identify_platform() # In the case of low-level constraints format, that is the default value self.high_to_low_map = None # Case A - interactive interface if (num_input_qubits is None or constraints_string is None) and ( high_level_constraints_string is None or high_level_vars is None ): self.interactive_interface() # Case B - API else: self.high_level_constraints_string = high_level_constraints_string self.high_level_vars = high_level_vars # Case B.1 - high-level format constraints inputs if num_input_qubits is None or constraints_string is None: self.num_input_qubits = sum(self.high_level_vars.values()) self.high_to_low_map, self.constraints_string = ConstraintsTranslator( self.high_level_constraints_string, self.high_level_vars ).translate() # Case B.2 - low-level format constraints inputs elif num_input_qubits is not None and constraints_string is not None: self.num_input_qubits = num_input_qubits self.constraints_string = constraints_string # Misuse else: raise SyntaxError( "SATInterface accepts the combination of paramters:" "(high_level_constraints_string + high_level_vars) or " "(num_input_qubits + constraints_string). " "Exactly one combination is accepted, not both." ) self.parsed_constraints = ParsedConstraints( self.constraints_string, self.high_level_constraints_string ) def update_metadata(self, update_metadata: Optional[Dict[str, Any]] = None) -> None: """ Updates the metadata file (in the unique data folder of a given `SATInterface` instance). Args: update_metadata (Optional[Dict[str, Any]] = None): - If None - just dumps `self.metadata` into the metadata JSON file. - If defined - updates the `self.metadata` attribute and then dumps it. """ if update_metadata is not None: self.metadata.update(update_metadata) with open(f"{self.dir_path}metadata.json", "w") as metadata_file: json.dump(self.metadata, metadata_file, indent=4) def identify_platform(self) -> None: """ Identifies user's platform. Writes True to `self.jupyter` for Jupyter notebook, False for terminal. """ # If True then the platform is a terminal/command line/shell if stdout.isatty(): self.jupyter = False # If False, we assume the platform is a Jupyter notebook else: self.jupyter = True def output_to_platform( self, *, title: str, output_terminal: Union[TextDrawing, str], output_jupyter: Union[Figure, str], display_both_on_jupyter: Optional[bool] = False, ) -> None: """ Displays output to user's platform. Args: title (str): a title for the output. output_terminal (Union[TextDrawing, str]): text to print for a terminal platform. output_jupyter: (Union[Figure, str]): objects to display for a Jupyter notebook platform. can handle `Figure` matplotlib objects or strings of paths to IFrame displayable file, e.g PDF files. display_both_on_jupyter (Optional[bool] = False): if True, displays both `output_terminal` and `output_jupyter` in a Jupyter notebook platform. Raises: TypeError - in the case of misusing the `output_jupyter` argument. """ print() print(title) if self.jupyter: if isinstance(output_jupyter, str): display.display(display.IFrame(output_jupyter, width=IFRAME_WIDTH, height=IFRAME_HEIGHT)) elif isinstance(output_jupyter, Figure): display.display(output_jupyter) else: raise TypeError("output_jupyter must be an str (path to image file) or a Figure object.") if display_both_on_jupyter: print(output_terminal) else: print(output_terminal) def interactive_interface(self) -> None: """ An interactive CLI that allows exploiting most (but not all) of the package's features. Uses functions of the form `interactive_XXX_inputs` from the `interactive_inputs.py` module. Divided into 3 main stages: 1. Obtaining Grover's operator for the SAT problem. 2. Obtaining the overall SAT cirucit. 3. Executing the circuit and parsing the results. The interface is built in a modular manner such that a user can halt at any stage. The defualt settings for the interactive user intreface are: 1. `name = "SAT"`. 2. `save_data = True`. 3. `display = True`. 4. `transpile_kwargs = {'basis_gates': ['u', 'cx'], 'optimization_level': 3}`. 5. Backends are limited to those defined in the global-constant-like function `BACKENDS`: - Those are the local `aer_simulator` and the remote `ibmq_qasm_simulator` for now. Due to these default settings the interactive CLI is somewhat restrictive, for full flexibility a user should use the API and not the CLI. """ # Handling operator part operator_inputs = interactive_operator_inputs() self.num_input_qubits = operator_inputs["num_input_qubits"] self.high_to_low_map = operator_inputs["high_to_low_map"] self.constraints_string = operator_inputs["constraints_string"] self.high_level_constraints_string = operator_inputs["high_level_constraints_string"] self.high_level_vars = operator_inputs["high_level_vars"] self.parsed_constraints = ParsedConstraints( self.constraints_string, self.high_level_constraints_string ) self.update_metadata( { "num_input_qubits": self.num_input_qubits, "constraints_string": self.constraints_string, "high_level_constraints_string": self.high_level_constraints_string, "high_level_vars": self.high_level_vars, } ) obtain_grover_operator_output = self.obtain_grover_operator() self.save_display_grover_operator(obtain_grover_operator_output) # Handling overall circuit part solutions_num = interactive_solutions_num_input() if solutions_num is not None: backend = None if solutions_num == -1: backend = interactive_backend_input() overall_circuit_data = self.obtain_overall_sat_circuit( obtain_grover_operator_output["operator"], solutions_num, backend ) self.save_display_overall_circuit(overall_circuit_data) # Handling circuit execution part if interactive_run_input(): if backend is None: backend = interactive_backend_input() shots = interactive_shots_input() counts_parsed = self.run_overall_sat_circuit( overall_circuit_data["circuit"], backend, shots ) self.save_display_results(counts_parsed) print() print(f"Done saving data into '{self.dir_path}'.") def obtain_grover_operator( self, transpile_kwargs: Optional[Dict[str, Any]] = None ) -> Dict[str, Union[GroverConstraintsOperator, QuantumCircuit]]: """ Obtains the suitable `GroverConstraintsOperator` object for the constraints, decomposes it using the `circuit_decomposition.py` module and transpiles it according to `transpile_kwargs`. Args: transpile_kwargs (Optional[Dict[str, Any]]): kwargs for Qiskit's transpile function. The defualt is set to the global constant `TRANSPILE_KWARGS`. Returns: (Dict[str, Union[GroverConstraintsOperator, QuantumCircuit, Dict[str, List[int]]]]): - 'operator' (GroverConstraintsOperator):the high-level blocks operator. - 'decomposed_operator' (QuantumCircuit): decomposed to building-blocks operator. * For annotations regarding the decomposition method see the `circuit_decomposition` module. - 'transpiled_operator' (QuantumCircuit): the transpiled operator. *** The high-level operator and the decomposed operator are generated with barriers between constraints as default for visualizations purposes. The barriers are stripped off before transpiling so the the transpiled operator object contains no barriers. *** - 'high_level_to_bit_indexes_map' (Optional[Dict[str, List[int]]] = None): A map of high-level variables with their allocated bit-indexes in the input register. """ print() print( "The system synthesizes and transpiles a Grover's " "operator for the given constraints. Please wait.." ) if transpile_kwargs is None: transpile_kwargs = TRANSPILE_KWARGS self.transpile_kwargs = transpile_kwargs operator = GroverConstraintsOperator( self.parsed_constraints, self.num_input_qubits, insert_barriers=True ) decomposed_operator = decompose_operator(operator) no_baerriers_operator = RemoveBarriers()(operator) transpiled_operator = transpile(no_baerriers_operator, **transpile_kwargs) print("Done.") return { "operator": operator, "decomposed_operator": decomposed_operator, "transpiled_operator": transpiled_operator, "high_level_to_bit_indexes_map": self.high_to_low_map, } def save_display_grover_operator( self, obtain_grover_operator_output: Dict[str, Union[GroverConstraintsOperator, QuantumCircuit]], display: Optional[bool] = True, ) -> None: """ Handles saving and displaying data generated by the `self.obtain_grover_operator` method. Args: obtain_grover_operator_output(Dict[str, Union[GroverConstraintsOperator, QuantumCircuit]]): the dictionary returned upon calling the `self.obtain_grover_operator` method. display (Optional[bool] = True) - If true, displays objects to user's platform. """ # Creating a directory to save operator's data operator_dir_path = f"{self.dir_path}grover_operator/" os.mkdir(operator_dir_path) # Titles for displaying objects, by order of `obtain_grover_operator_output` titles = [ "The operator diagram - high level blocks:", "The operator diagram - decomposed:", f"The transpiled operator diagram saved into '{operator_dir_path}'.\n" f"It's not presented here due to its complexity.\n" f"Please note that barriers appear in the high-level diagrams above only for convenient\n" f"visual separation between constraints.\n" f"Before transpilation all barriers are removed to avoid redundant inefficiencies.", ] for index, (op_name, op_obj) in enumerate(obtain_grover_operator_output.items()): # Generic path and name for files to be saved files_path = f"{operator_dir_path}{op_name}" # Generating a circuit diagrams figure figure_path = f"{files_path}.pdf" op_obj.draw("mpl", filename=figure_path, fold=-1) # Generating a QPY serialization file for the circuit object qpy_file_path = f"{files_path}.qpy" with open(qpy_file_path, "wb") as qpy_file: qpy.dump(op_obj, qpy_file) # Original high-level operator and decomposed operator if index < 2 and display: # Displaying to user self.output_to_platform( title=titles[index], output_terminal=op_obj.draw("text"), output_jupyter=figure_path ) # Transpiled operator elif index == 2: # Output to user, not including the circuit diagram print() print(titles[index]) print() print(f"The transpilation kwargs are: {self.transpile_kwargs}.") transpiled_operator_depth = op_obj.depth() transpiled_operator_gates_count = op_obj.count_ops() print(f"Transpiled operator depth: {transpiled_operator_depth}.") print(f"Transpiled operator gates count: {transpiled_operator_gates_count}.") print(f"Total number of qubits: {op_obj.num_qubits}.") # Generating QASM 2.0 file only for the (flattened = no registers) tranpsiled operator qasm_file_path = f"{files_path}.qasm" flatten_circuit(op_obj).qasm(filename=qasm_file_path) # Index 3 is 'high_level_to_bit_indexes_map' so it's time to break from the loop break # Mapping from high-level variables to bit-indexes will be displayed as well mapping = obtain_grover_operator_output["high_level_to_bit_indexes_map"] if mapping: print() print(f"The high-level variables mapping to bit-indexes:\n{mapping}") print() print( f"Saved into '{operator_dir_path}':\n", " Circuit diagrams for all levels.\n", " QPY serialization exports for all levels.\n", " QASM 2.0 export only for the transpiled level.", ) with open(f"{operator_dir_path}operator.qpy", "rb") as qpy_file: operator_qpy_sha256 = sha256(qpy_file.read()).hexdigest() self.update_metadata( { "high_level_to_bit_indexes_map": self.high_to_low_map, "transpile_kwargs": self.transpile_kwargs, "transpiled_operator_depth": transpiled_operator_depth, "transpiled_operator_gates_count": transpiled_operator_gates_count, "operator_qpy_sha256": operator_qpy_sha256, } ) def obtain_overall_sat_circuit( self, grover_operator: GroverConstraintsOperator, solutions_num: int, backend: Optional[Backend] = None, ) -> Dict[str, SATCircuit]: """ Obtains the suitable `SATCircuit` object (= the overall SAT circuit) for the SAT problem. Args: grover_operator (GroverConstraintsOperator): Grover's operator for the SAT problem. solutions_num (int): number of solutions for the SAT problem. In the case the number of solutions is unknown, specific negative values are accepted: * '-1' - for launching a classical iterative stochastic process that finds an adequate number of iterations - by calling the `find_iterations_unknown` function (see its docstrings for more information). * '-2' - for generating a dynamic circuit that iterates over Grover's iterator until a solution is obtained, using weak measurements. TODO - this feature isn't ready yet. backend (Optional[Backend] = None): in the case of a '-1' value given to `solutions_num`, a backend object to execute the depicted iterative prcess upon should be provided. Returns: (Dict[str, SATCircuit]): - 'circuit' key for the overall SAT circuit. - 'concise_circuit' key for the overall SAT circuit, with only 1 iteration over Grover's iterator (operator + diffuser). Useful for visualization purposes. *** The concise circuit is generated with barriers between segments as default for visualizations purposes. In the actual circuit there no barriers. *** """ # -1 = Unknown number of solutions - iterative stochastic process print() if solutions_num == -1: assert backend is not None, "Need to specify a backend if `solutions_num == -1`." print("Please wait while the system checks various solutions..") circuit, iterations = find_iterations_unknown( self.num_input_qubits, grover_operator, self.parsed_constraints, precision=10, backend=backend, ) print() print(f"An adequate number of iterations found = {iterations}.") # -2 = Unknown number of solutions - implement a dynamic circuit # TODO this feature isn't fully implemented yet elif solutions_num == -2: print("The system builds a dynamic circuit..") circuit = SATCircuit(self.num_input_qubits, grover_operator, iterations=None) circuit.add_input_reg_measurement() iterations = None # Known number of solutions else: print("The system builds the overall circuit..") iterations = calc_iterations(self.num_input_qubits, solutions_num) print(f"\nFor {solutions_num} solutions, {iterations} iterations needed.") circuit = SATCircuit( self.num_input_qubits, grover_operator, iterations, insert_barriers=False ) circuit.add_input_reg_measurement() self.iterations = iterations # Obtaining a SATCircuit object with one iteration for concise representation concise_circuit = SATCircuit( self.num_input_qubits, grover_operator, iterations=1, insert_barriers=True ) concise_circuit.add_input_reg_measurement() return {"circuit": circuit, "concise_circuit": concise_circuit} def save_display_overall_circuit( self, obtain_overall_sat_circuit_output: Dict[str, SATCircuit], display: Optional[bool] = True ) -> None: """ Handles saving and displaying data generated by the `self.obtain_overall_sat_circuit` method. Args: obtain_overall_sat_circuit_output(Dict[str, SATCircuit]): the dictionary returned upon calling the `self.obtain_overall_sat_circuit` method. display (Optional[bool] = True) - If true, displays objects to user's platform. """ circuit = obtain_overall_sat_circuit_output["circuit"] concise_circuit = obtain_overall_sat_circuit_output["concise_circuit"] # Creating a directory to save overall circuit's data overall_circuit_dir_path = f"{self.dir_path}overall_circuit/" os.mkdir(overall_circuit_dir_path) # Generating a figure of the overall SAT circuit with just 1 iteration (i.e "concise") concise_circuit_fig_path = f"{overall_circuit_dir_path}overall_circuit_1_iteration.pdf" concise_circuit.draw("mpl", filename=concise_circuit_fig_path, fold=-1) # Displaying the concise circuit to user if display: if self.iterations: self.output_to_platform( title=( f"The high level circuit contains {self.iterations}" f" iterations of the following form:" ), output_terminal=concise_circuit.draw("text"), output_jupyter=concise_circuit_fig_path, ) # Dynamic circuit case - TODO NOT FULLY IMPLEMENTED YET else: dynamic_circuit_fig_path = f"{overall_circuit_dir_path}overall_circuit_dynamic.pdf" circuit.draw("mpl", filename=dynamic_circuit_fig_path, fold=-1) self.output_to_platform( title="The dynamic circuit diagram:", output_terminal=circuit.draw("text"), output_jupyter=dynamic_circuit_fig_path, ) if self.iterations: transpiled_overall_circuit = transpile(flatten_circuit(circuit), **self.transpile_kwargs) print() print(f"The transpilation kwargs are: {self.transpile_kwargs}.") transpiled_overall_circuit_depth = transpiled_overall_circuit.depth() transpiled_overall_circuit_gates_count = transpiled_overall_circuit.count_ops() print(f"Transpiled overall-circuit depth: {transpiled_overall_circuit_depth}.") print(f"Transpiled overall-circuit gates count: {transpiled_overall_circuit_gates_count}.") print(f"Total number of qubits: {transpiled_overall_circuit.num_qubits}.") print() print("Exporting the full overall SAT circuit object..") export_files_path = f"{overall_circuit_dir_path}overall_circuit" with open(f"{export_files_path}.qpy", "wb") as qpy_file: qpy.dump(circuit, qpy_file) if self.iterations: transpiled_overall_circuit.qasm(filename=f"{export_files_path}.qasm") print() print( f"Saved into '{overall_circuit_dir_path}':\n", " A concised (1 iteration) circuit diagram of the high-level overall SAT circuit.\n", " QPY serialization export for the full overall SAT circuit object.", ) if self.iterations: print(" QASM 2.0 export for the transpiled full overall SAT circuit object.") metadata_update = { "num_total_qubits": circuit.num_qubits, "num_iterations": circuit.iterations, } if self.iterations: metadata_update["transpiled_overall_circuit_depth"] = (transpiled_overall_circuit_depth,) metadata_update[ "transpiled_overall_circuit_gates_count" ] = transpiled_overall_circuit_gates_count self.update_metadata(metadata_update) @timer_dec("Circuit simulation execution time = ") def run_overall_sat_circuit( self, circuit: QuantumCircuit, backend: Backend, shots: int ) -> Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]: """ Executes a `circuit` on `backend` transpiled w.r.t backend, `shots` times. Args: circuit (QuantumCircuit): `QuantumCircuit` object or child-object (a.k.a `SATCircuit`) to execute. backend (Backend): backend to execute `circuit` upon. shots (int): number of execution shots. Returns: (Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]): dict object returned by `self.parse_counts` - see this method's docstrings for annotations. """ # Defines also instance attributes to use in other methods self.backend = backend self.shots = shots print() print(f"The system is running the circuit {shots} times on {backend}, please wait..") print("This process might take a while.") job = backend.run(transpile(circuit, backend), shots=shots) counts = job.result().get_counts() print("Done.") parsed_counts = self.parse_counts(counts) return parsed_counts def parse_counts( self, counts: Counts ) -> Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]: """ Parses a `Counts` object into several desired datas (see 'Returns' section). Args: counts (Counts): the `Counts` object to parse. Returns: (Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]): 'counts' (Counts) - the original `Counts` object. 'counts_sorted' (List[Tuple[Union[str, int]]]) - results sorted in a descending order. 'distilled_solutions' (List[str]): list of solutions (bitstrings). 'high_level_vars_values' (List[Dict[str, int]]): list of solutions (each solution is a dictionary with variable-names as keys and their integer values as values). """ # Sorting results in an a descending order counts_sorted = sorted(counts.items(), key=lambda x: x[1], reverse=True) # Generating a set of distilled verified-only solutions verifier = ClassicalVerifier(self.parsed_constraints) distilled_solutions = set() for count_item in counts_sorted: if not verifier.verify(count_item[0]): break distilled_solutions.add(count_item[0]) # In the case of high-level format in use, translating `distilled_solutions` into integer values high_level_vars_values = None if self.high_level_constraints_string and self.high_level_vars: # Container for dictionaries with variables integer values high_level_vars_values = [] for solution in distilled_solutions: # Keys are variable-names and values are their integer values solution_vars = {} for var, bits_bundle in self.high_to_low_map.items(): reversed_solution = solution[::-1] var_bitstring = "" for bit_index in bits_bundle: var_bitstring += reversed_solution[bit_index] # Translating to integer value solution_vars[var] = int(var_bitstring, 2) high_level_vars_values.append(solution_vars) return { "counts": counts, "counts_sorted": counts_sorted, "distilled_solutions": distilled_solutions, "high_level_vars_values": high_level_vars_values, } def save_display_results( self, run_overall_sat_circuit_output: Dict[ str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]] ], display: Optional[bool] = True, ) -> None: """ Handles saving and displaying data generated by the `self.run_overall_sat_circuit` method. Args: run_overall_sat_circuit_output (Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]): the dictionary returned upon calling the `self.run_overall_sat_circuit` method. display (Optional[bool] = True) - If true, displays objects to user's platform. """ counts = run_overall_sat_circuit_output["counts"] counts_sorted = run_overall_sat_circuit_output["counts_sorted"] distilled_solutions = run_overall_sat_circuit_output["distilled_solutions"] high_level_vars_values = run_overall_sat_circuit_output["high_level_vars_values"] # Creating a directory to save results data results_dir_path = f"{self.dir_path}results/" os.mkdir(results_dir_path) # Defining custom dimensions for the custom `plot_histogram` of this package histogram_fig_width = max((len(counts) * self.num_input_qubits * (10 / 72)), 7) histogram_fig_height = 5 histogram_figsize = (histogram_fig_width, histogram_fig_height) histogram_path = f"{results_dir_path}histogram.pdf" plot_histogram(counts, figsize=histogram_figsize, sort="value_desc", filename=histogram_path) if display: # Basic output text output_text = ( f"All counts:\n{counts_sorted}\n" f"\nDistilled solutions ({len(distilled_solutions)} total):\n" f"{distilled_solutions}" ) # Additional outputs for a high-level constraints format if high_level_vars_values: # Mapping from high-level variables to bit-indexes will be displayed as well output_text += ( f"\n\nThe high-level variables mapping to bit-indexes:" f"\n{self.high_to_low_map}" ) # Actual integer solutions will be displayed as well additional_text = "" for solution_index, solution in enumerate(high_level_vars_values): additional_text += f"Solution {solution_index + 1}: " for var_index, (var, value) in enumerate(solution.items()): additional_text += f"{var} = {value}" if var_index != len(solution) - 1: additional_text += ", " else: additional_text += "\n" output_text += f"\n\nHigh-level format solutions: \n{additional_text}" self.output_to_platform( title=f"The results for {self.shots} shots are:", output_terminal=output_text, output_jupyter=histogram_path, display_both_on_jupyter=True, ) results_dict = { "high_level_to_bit_indexes_map": self.high_to_low_map, "solutions": list(distilled_solutions), "high_level_solutions": high_level_vars_values, "counts": counts_sorted, } with open(f"{results_dir_path}results.json", "w") as results_file: json.dump(results_dict, results_file, indent=4) self.update_metadata( { "num_solutions": len(distilled_solutions), "backend": str(self.backend), "shots": self.shots, } )
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
mmetcalf14
# Copyright 2019 Cambridge Quantum Computing # # 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 # # https://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 itertools import qiskit from typing import Tuple, Iterable from qiskit import IBMQ, QuantumCircuit from qiskit.compiler import assemble from qiskit.tools.monitor import job_monitor from pytket.backends import Backend from pytket.qiskit import tk_to_qiskit from pytket._routing import route, Architecture from pytket._transform import Transform from pytket._circuit import Circuit import numpy as np VALID_BACKEND_GATES = ( qiskit.extensions.standard.u1.U1Gate, qiskit.extensions.standard.u2.U2Gate, qiskit.extensions.standard.u3.U3Gate, qiskit.extensions.standard.cx.CnotGate, qiskit.circuit.measure.Measure ) def _qiskit_circ_valid(qc: QuantumCircuit, coupling:Iterable[Tuple[int]] ) -> bool: valid = True measure_count = 0 for instruction in qc: if type(instruction[0]) not in VALID_BACKEND_GATES: valid = False break if isinstance(instruction[0], qiskit.circuit.measure.Measure): measure_count += 1 if len(instruction[1]) > 1: control = instruction[1][0][1] target = instruction[1][1][1] if [control, target] not in coupling: valid =False break return valid, (measure_count > 0) def _routed_ibmq_circuit(circuit:Circuit, arc: Architecture) -> QuantumCircuit: c = circuit.copy() Transform.RebaseToQiskit().apply(c) physical_c = route(c, arc) physical_c.decompose_SWAP_to_CX() physical_c.redirect_CX_gates(arc) Transform.OptimisePostRouting().apply(physical_c) qc = tk_to_qiskit(physical_c) return qc def _convert_bin_str(string) : return [int(b) for b in string.replace(' ', '')][::-1] class IBMQBackend(Backend) : def __init__(self, backend_name:str, monitor:bool=True) : """A backend for running circuits on remote IBMQ devices. :param backend_name: name of ibmq device. e.g. `ibmqx4`, `ibmq_16_melbourne`. :type backend_name: str :param monitor: Use IBM job monitor, defaults to True :type monitor: bool, optional :raises ValueError: If no IBMQ account has been set up. """ if len(IBMQ.stored_accounts()) ==0: raise ValueError('No IBMQ credentials found on disk. Store some first.') IBMQ.load_accounts() self._backend = IBMQ.get_backend(backend_name) self.config = self._backend.configuration() self.coupling = self.config.coupling_map self.architecture = Architecture(self.coupling) self._monitor = monitor def run(self, circuit:Circuit, shots:int, fit_to_constraints:bool=True) -> np.ndarray : if fit_to_constraints: qc = _routed_ibmq_circuit(circuit, self.architecture) else: qc = tk_to_qiskit(circuit) valid, measures = _qiskit_circ_valid(qc, self.coupling) if not valid: raise RuntimeWarning("QuantumCircuit does not pass validity test, will likely fail on remote backend.") if not measures: raise RuntimeWarning("Measure gates are required for output.") qobj = assemble(qc, shots=shots, memory=self.config.memory) job = self._backend.run(qobj) if self._monitor : job_monitor(job) shot_list = [] if self.config.memory: shot_list = job.result().get_memory(qc) else: for string, count in job.result().get_counts().items(): shot_list += [string]*count return np.asarray([_convert_bin_str(shot) for shot in shot_list]) def get_counts(self, circuit, shots, fit_to_constraints=True) : """ Run the circuit on the backend and accumulate the results into a summary of counts :param circuit: The circuit to run :param shots: Number of shots (repeats) to run :param fit_to_constraints: Compile the circuit to meet the constraints of the backend, defaults to True :param seed: Random seed to for simulator :return: Dictionary mapping bitvectors of results to number of times that result was observed (zero counts are omitted) """ if fit_to_constraints: qc = _routed_ibmq_circuit(circuit, self.architecture) else: qc = tk_to_qiskit(circuit) valid, measures = _qiskit_circ_valid(qc, self.coupling) if not valid: raise RuntimeWarning("QuantumCircuit does not pass validity test, will likely fail on remote backend.") if not measures: raise RuntimeWarning("Measure gates are required for output.") qobj = assemble(qc, shots=shots) job = self._backend.run(qobj) counts = job.result().get_counts(qc) return {tuple(_convert_bin_str(b)) : c for b, c in counts.items()}
https://github.com/DaisukeIto-ynu/KosakaQ
DaisukeIto-ynu
# 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. """Module for interfacing with an IBM Quantum Experience Backend.""" import logging import warnings import copy from typing import Dict, List, Union, Optional, Any from datetime import datetime as python_datetime from qiskit.compiler import assemble from qiskit.circuit import QuantumCircuit, Parameter, Delay from qiskit.circuit.duration import duration_in_dt from qiskit.pulse import Schedule, LoConfig from qiskit.pulse.channels import PulseChannel from qiskit.qobj import QasmQobj, PulseQobj from qiskit.qobj.utils import MeasLevel, MeasReturnType from qiskit.providers.backend import BackendV1 as Backend from qiskit.providers.options import Options from qiskit.providers.jobstatus import JobStatus from qiskit.providers.models import (BackendStatus, BackendProperties, PulseDefaults, GateConfig) from qiskit.tools.events.pubsub import Publisher from qiskit.providers.models import (QasmBackendConfiguration, PulseBackendConfiguration) from qiskit.utils import deprecate_arguments from qiskit.providers.ibmq import accountprovider # pylint: disable=unused-import from .apiconstants import ApiJobStatus, API_JOB_FINAL_STATES from .api.clients import AccountClient from .api.exceptions import ApiError from .backendjoblimit import BackendJobLimit from .backendreservation import BackendReservation from .credentials import Credentials from .exceptions import (IBMQBackendError, IBMQBackendValueError, IBMQBackendApiError, IBMQBackendApiProtocolError, IBMQBackendJobLimitError) from .job import IBMQJob from .utils import validate_job_tags from .utils.converters import utc_to_local_all, local_to_utc from .utils.json_decoder import decode_pulse_defaults, decode_backend_properties from .utils.backend import convert_reservation_data from .utils.utils import api_status_to_job_status logger = logging.getLogger(__name__) class IBMQBackend(Backend): """Backend class interfacing with an IBM Quantum Experience device. You can run experiments on a backend using the :meth:`run()` method. The :meth:`run()` method takes one or more :class:`~qiskit.circuit.QuantumCircuit` or :class:`~qiskit.pulse.Schedule` and returns an :class:`~qiskit.providers.ibmq.job.IBMQJob` instance that represents the submitted job. Each job has a unique job ID, which can later be used to retrieve the job. An example of this flow:: from qiskit import IBMQ, assemble, transpile from qiskit.circuit.random import random_circuit provider = IBMQ.load_account() backend = provider.backend.ibmq_vigo qx = random_circuit(n_qubits=5, depth=4) transpiled = transpile(qx, backend=backend) job = backend.run(transpiled) retrieved_job = backend.retrieve_job(job.job_id()) Note: * Unlike :meth:`qiskit.execute`, the :meth:`run` method does not transpile the circuits/schedules for you, so be sure to do so before submitting them. * You should not instantiate the ``IBMQBackend`` class directly. Instead, use the methods provided by an :class:`AccountProvider` instance to retrieve and handle backends. Other methods return information about the backend. For example, the :meth:`status()` method returns a :class:`BackendStatus<qiskit.providers.models.BackendStatus>` instance. The instance contains the ``operational`` and ``pending_jobs`` attributes, which state whether the backend is operational and also the number of jobs in the server queue for the backend, respectively:: status = backend.status() is_operational = status.operational jobs_in_queue = status.pending_jobs It is also possible to see the number of remaining jobs you are able to submit to the backend with the :meth:`job_limit()` method, which returns a :class:`BackendJobLimit<qiskit.providers.ibmq.BackendJobLimit>` instance:: job_limit = backend.job_limit() """ qobj_warning_issued = False id_warning_issued = False def __init__( self, configuration: Union[QasmBackendConfiguration, PulseBackendConfiguration], provider: 'accountprovider.AccountProvider', credentials: Credentials, api_client: AccountClient ) -> None: """IBMQBackend constructor. Args: configuration: Backend configuration. provider: IBM Quantum Experience account provider credentials: IBM Quantum Experience credentials. api_client: IBM Quantum Experience client used to communicate with the server. """ super().__init__(provider=provider, configuration=configuration) self._api_client = api_client self._credentials = credentials self.hub = credentials.hub self.group = credentials.group self.project = credentials.project # Attributes used by caching functions. self._properties = None self._defaults = None @classmethod def _default_options(cls) -> Options: """Default runtime options.""" return Options(shots=4000, memory=False, qubit_lo_freq=None, meas_lo_freq=None, schedule_los=None, meas_level=MeasLevel.CLASSIFIED, meas_return=MeasReturnType.AVERAGE, memory_slots=None, memory_slot_size=100, rep_time=None, rep_delay=None, init_qubits=True, use_measure_esp=None, live_data_enabled=None) @deprecate_arguments({'qobj': 'circuits'}) def run( self, circuits: Union[QasmQobj, PulseQobj, QuantumCircuit, Schedule, List[Union[QuantumCircuit, Schedule]]], job_name: Optional[str] = None, job_share_level: Optional[str] = None, job_tags: Optional[List[str]] = None, experiment_id: Optional[str] = None, header: Optional[Dict] = None, shots: Optional[int] = None, memory: Optional[bool] = None, qubit_lo_freq: Optional[List[int]] = None, meas_lo_freq: Optional[List[int]] = None, schedule_los: Optional[Union[List[Union[Dict[PulseChannel, float], LoConfig]], Union[Dict[PulseChannel, float], LoConfig]]] = None, meas_level: Optional[Union[int, MeasLevel]] = None, meas_return: Optional[Union[str, MeasReturnType]] = None, memory_slots: Optional[int] = None, memory_slot_size: Optional[int] = None, rep_time: Optional[int] = None, rep_delay: Optional[float] = None, init_qubits: Optional[bool] = None, parameter_binds: Optional[List[Dict[Parameter, float]]] = None, use_measure_esp: Optional[bool] = None, live_data_enabled: Optional[bool] = None, **run_config: Dict ) -> IBMQJob: """Run on the backend. If a keyword specified here is also present in the ``options`` attribute/object, the value specified here will be used for this run. Args: circuits: An individual or a list of :class:`~qiskit.circuits.QuantumCircuit` or :class:`~qiskit.pulse.Schedule` objects to run on the backend. A :class:`~qiskit.qobj.QasmQobj` or a :class:`~qiskit.qobj.PulseQobj` object is also supported but is deprecated. job_name: Custom name to be assigned to the job. This job name can subsequently be used as a filter in the :meth:`jobs()` method. Job names do not need to be unique. job_share_level: Allows sharing a job at the hub, group, project, or global level. The possible job share levels are: ``global``, ``hub``, ``group``, ``project``, and ``none``. * global: The job is public to any user. * hub: The job is shared between the users in the same hub. * group: The job is shared between the users in the same group. * project: The job is shared between the users in the same project. * none: The job is not shared at any level. If the job share level is not specified, the job is not shared at any level. job_tags: Tags to be assigned to the job. The tags can subsequently be used as a filter in the :meth:`jobs()` function call. experiment_id: Used to add a job to an "experiment", which is a collection of jobs and additional metadata. The following arguments are NOT applicable if a Qobj is passed in. header: User input that will be attached to the job and will be copied to the corresponding result header. Headers do not affect the run. This replaces the old ``Qobj`` header. shots: Number of repetitions of each circuit, for sampling. Default: 4000 or ``max_shots`` from the backend configuration, whichever is smaller. memory: If ``True``, per-shot measurement bitstrings are returned as well (provided the backend supports it). For OpenPulse jobs, only measurement level 2 supports this option. qubit_lo_freq: List of default qubit LO frequencies in Hz. Will be overridden by ``schedule_los`` if set. meas_lo_freq: List of default measurement LO frequencies in Hz. Will be overridden by ``schedule_los`` if set. schedule_los: Experiment LO configurations, frequencies are given in Hz. meas_level: Set the appropriate level of the measurement output for pulse experiments. meas_return: Level of measurement data for the backend to return. For ``meas_level`` 0 and 1: * ``single`` returns information from every shot. * ``avg`` returns average measurement output (averaged over number of shots). memory_slots: Number of classical memory slots to use. memory_slot_size: Size of each memory slot if the output is Level 0. rep_time: Time per program execution in seconds. Must be from the list provided by the backend (``backend.configuration().rep_times``). Defaults to the first entry. rep_delay: Delay between programs in seconds. Only supported on certain backends (if ``backend.configuration().dynamic_reprate_enabled=True``). If supported, ``rep_delay`` will be used instead of ``rep_time`` and must be from the range supplied by the backend (``backend.configuration().rep_delay_range``). Default is given by ``backend.configuration().default_rep_delay``. init_qubits: Whether to reset the qubits to the ground state for each shot. Default: ``True``. parameter_binds: List of Parameter bindings over which the set of experiments will be executed. Each list element (bind) should be of the form {Parameter1: value1, Parameter2: value2, ...}. All binds will be executed across all experiments; e.g., if parameter_binds is a length-n list, and there are m experiments, a total of m x n experiments will be run (one for each experiment/bind pair). use_measure_esp: Whether to use excited state promoted (ESP) readout for measurements which are the terminal instruction to a qubit. ESP readout can offer higher fidelity than standard measurement sequences. See `here <https://arxiv.org/pdf/2008.08571.pdf>`_. Default: ``True`` if backend supports ESP readout, else ``False``. Backend support for ESP readout is determined by the flag ``measure_esp_enabled`` in ``backend.configuration()``. live_data_enabled (bool): Activate the live data in the backend, to receive data from the instruments. **run_config: Extra arguments used to configure the run. Returns: The job to be executed. Raises: IBMQBackendApiError: If an unexpected error occurred while submitting the job. IBMQBackendApiProtocolError: If an unexpected value received from the server. IBMQBackendValueError: - If an input parameter value is not valid. - If ESP readout is used and the backend does not support this. """ # pylint: disable=arguments-differ if job_share_level: warnings.warn("The `job_share_level` keyword is no longer supported " "and will be removed in a future release.", Warning, stacklevel=3) validate_job_tags(job_tags, IBMQBackendValueError) sim_method = None if self.configuration().simulator: sim_method = getattr(self.configuration(), 'simulation_method', None) measure_esp_enabled = getattr(self.configuration(), "measure_esp_enabled", False) # set ``use_measure_esp`` to backend value if not set by user if use_measure_esp is None: use_measure_esp = measure_esp_enabled if use_measure_esp and not measure_esp_enabled: raise IBMQBackendValueError( "ESP readout not supported on this device. Please make sure the flag " "'use_measure_esp' is unset or set to 'False'." ) if not self.configuration().simulator: self._deprecate_id_instruction(circuits) if isinstance(circuits, (QasmQobj, PulseQobj)): if not self.qobj_warning_issued: warnings.warn("Passing a Qobj to Backend.run is deprecated and will " "be removed in a future release. Please pass in circuits " "or pulse schedules instead.", DeprecationWarning, stacklevel=3) # need level 3 because of decorator self.qobj_warning_issued = True qobj = circuits if sim_method and not hasattr(qobj.config, 'method'): qobj.config.method = sim_method else: qobj_header = run_config.pop('qobj_header', None) header = header or qobj_header run_config_dict = self._get_run_config( qobj_header=header, shots=shots, memory=memory, qubit_lo_freq=qubit_lo_freq, meas_lo_freq=meas_lo_freq, schedule_los=schedule_los, meas_level=meas_level, meas_return=meas_return, memory_slots=memory_slots, memory_slot_size=memory_slot_size, rep_time=rep_time, rep_delay=rep_delay, init_qubits=init_qubits, use_measure_esp=use_measure_esp, **run_config) if parameter_binds: run_config_dict['parameter_binds'] = parameter_binds if sim_method and 'method' not in run_config_dict: run_config_dict['method'] = sim_method qobj = assemble(circuits, self, **run_config_dict) return self._submit_job(qobj, job_name, job_tags, experiment_id, live_data_enabled) def _get_run_config(self, **kwargs: Any) -> Dict: """Return the consolidated runtime configuration.""" run_config_dict = copy.copy(self.options.__dict__) for key, val in kwargs.items(): if val is not None: run_config_dict[key] = val if key not in self.options.__dict__ and not isinstance(self, IBMQSimulator): warnings.warn(f"{key} is not a recognized runtime" # type: ignore[unreachable] f" option and may be ignored by the backend.", stacklevel=4) return run_config_dict def _submit_job( self, qobj: Union[QasmQobj, PulseQobj], job_name: Optional[str] = None, job_tags: Optional[List[str]] = None, experiment_id: Optional[str] = None, live_data_enabled: Optional[bool] = None ) -> IBMQJob: """Submit the Qobj to the backend. Args: qobj: The Qobj to be executed. job_name: Custom name to be assigned to the job. This job name can subsequently be used as a filter in the ``jobs()``method. Job names do not need to be unique. job_tags: Tags to be assigned to the job. experiment_id: Used to add a job to an experiment. live_data_enabled: Used to activate/deactivate live data on the backend. Returns: The job to be executed. Events: ibmq.job.start: The job has started. Raises: IBMQBackendApiError: If an unexpected error occurred while submitting the job. IBMQBackendError: If an unexpected error occurred after submitting the job. IBMQBackendApiProtocolError: If an unexpected value is received from the server. IBMQBackendJobLimitError: If the job could not be submitted because the job limit has been reached. """ try: qobj_dict = qobj.to_dict() submit_info = self._api_client.job_submit( backend_name=self.name(), qobj_dict=qobj_dict, job_name=job_name, job_tags=job_tags, experiment_id=experiment_id, live_data_enabled=live_data_enabled) except ApiError as ex: if 'Error code: 3458' in str(ex): raise IBMQBackendJobLimitError('Error submitting job: {}'.format(str(ex))) from ex raise IBMQBackendApiError('Error submitting job: {}'.format(str(ex))) from ex # Error in the job after submission: # Transition to the `ERROR` final state. if 'error' in submit_info: raise IBMQBackendError( 'Error submitting job: {}'.format(str(submit_info['error']))) # Submission success. try: job = IBMQJob(backend=self, api_client=self._api_client, qobj=qobj, **submit_info) logger.debug('Job %s was successfully submitted.', job.job_id()) except TypeError as err: logger.debug("Invalid job data received: %s", submit_info) raise IBMQBackendApiProtocolError('Unexpected return value received from the server ' 'when submitting job: {}'.format(str(err))) from err Publisher().publish("ibmq.job.start", job) return job def properties( self, refresh: bool = False, datetime: Optional[python_datetime] = None ) -> Optional[BackendProperties]: """Return the backend properties, subject to optional filtering. This data describes qubits properties (such as T1 and T2), gates properties (such as gate length and error), and other general properties of the backend. The schema for backend properties can be found in `Qiskit/ibm-quantum-schemas <https://github.com/Qiskit/ibm-quantum-schemas/blob/main/schemas/backend_properties_schema.json>`_. Args: refresh: If ``True``, re-query the server for the backend properties. Otherwise, return a cached version. datetime: By specifying `datetime`, this function returns an instance of the :class:`BackendProperties<qiskit.providers.models.BackendProperties>` whose timestamp is closest to, but older than, the specified `datetime`. Returns: The backend properties or ``None`` if the backend properties are not currently available. Raises: TypeError: If an input argument is not of the correct type. """ # pylint: disable=arguments-differ if not isinstance(refresh, bool): raise TypeError("The 'refresh' argument needs to be a boolean. " "{} is of type {}".format(refresh, type(refresh))) if datetime and not isinstance(datetime, python_datetime): raise TypeError("'{}' is not of type 'datetime'.") if datetime: datetime = local_to_utc(datetime) if datetime or refresh or self._properties is None: api_properties = self._api_client.backend_properties(self.name(), datetime=datetime) if not api_properties: return None decode_backend_properties(api_properties) api_properties = utc_to_local_all(api_properties) backend_properties = BackendProperties.from_dict(api_properties) if datetime: # Don't cache result. return backend_properties self._properties = backend_properties return self._properties def status(self) -> BackendStatus: """Return the backend status. Note: If the returned :class:`~qiskit.providers.models.BackendStatus` instance has ``operational=True`` but ``status_msg="internal"``, then the backend is accepting jobs but not processing them. Returns: The status of the backend. Raises: IBMQBackendApiProtocolError: If the status for the backend cannot be formatted properly. """ api_status = self._api_client.backend_status(self.name()) try: return BackendStatus.from_dict(api_status) except TypeError as ex: raise IBMQBackendApiProtocolError( 'Unexpected return value received from the server when ' 'getting backend status: {}'.format(str(ex))) from ex def defaults(self, refresh: bool = False) -> Optional[PulseDefaults]: """Return the pulse defaults for the backend. The schema for default pulse configuration can be found in `Qiskit/ibm-quantum-schemas <https://github.com/Qiskit/ibm-quantum-schemas/blob/main/schemas/default_pulse_configuration_schema.json>`_. Args: refresh: If ``True``, re-query the server for the backend pulse defaults. Otherwise, return a cached version. Returns: The backend pulse defaults or ``None`` if the backend does not support pulse. """ if refresh or self._defaults is None: api_defaults = self._api_client.backend_pulse_defaults(self.name()) if api_defaults: decode_pulse_defaults(api_defaults) self._defaults = PulseDefaults.from_dict(api_defaults) else: self._defaults = None return self._defaults def job_limit(self) -> BackendJobLimit: """Return the job limit for the backend. The job limit information includes the current number of active jobs you have on the backend and the maximum number of active jobs you can have on it. Note: Job limit information for a backend is provider specific. For example, if you have access to the same backend via different providers, the job limit information might be different for each provider. If the method call was successful, you can inspect the job limit for the backend by accessing the ``maximum_jobs`` and ``active_jobs`` attributes of the :class:`BackendJobLimit<BackendJobLimit>` instance returned. For example:: backend_job_limit = backend.job_limit() maximum_jobs = backend_job_limit.maximum_jobs active_jobs = backend_job_limit.active_jobs If ``maximum_jobs`` is equal to ``None``, then there is no limit to the maximum number of active jobs you could have on the backend. Returns: The job limit for the backend, with this provider. Raises: IBMQBackendApiProtocolError: If an unexpected value is received from the server. """ api_job_limit = self._api_client.backend_job_limit(self.name()) try: job_limit = BackendJobLimit(**api_job_limit) if job_limit.maximum_jobs == -1: # Manually set `maximum` to `None` if backend has no job limit. job_limit.maximum_jobs = None return job_limit except TypeError as ex: raise IBMQBackendApiProtocolError( 'Unexpected return value received from the server when ' 'querying job limit data for the backend: {}.'.format(ex)) from ex def remaining_jobs_count(self) -> Optional[int]: """Return the number of remaining jobs that could be submitted to the backend. Note: The number of remaining jobs for a backend is provider specific. For example, if you have access to the same backend via different providers, the number of remaining jobs might be different for each. See :class:`BackendJobLimit<BackendJobLimit>` for the job limit information of a backend. If ``None`` is returned, there are no limits to the maximum number of active jobs you could have on the backend. Returns: The remaining number of jobs a user could submit to the backend, with this provider, before the maximum limit on active jobs is reached. Raises: IBMQBackendApiProtocolError: If an unexpected value is received from the server. """ job_limit = self.job_limit() if job_limit.maximum_jobs is None: return None return job_limit.maximum_jobs - job_limit.active_jobs def jobs( self, limit: int = 10, skip: int = 0, status: Optional[Union[JobStatus, str, List[Union[JobStatus, str]]]] = None, job_name: Optional[str] = None, start_datetime: Optional[python_datetime] = None, end_datetime: Optional[python_datetime] = None, job_tags: Optional[List[str]] = None, job_tags_operator: Optional[str] = "OR", experiment_id: Optional[str] = None, descending: bool = True, db_filter: Optional[Dict[str, Any]] = None ) -> List[IBMQJob]: """Return the jobs submitted to this backend, subject to optional filtering. Retrieve jobs submitted to this backend that match the given filters and paginate the results if desired. Note that the server has a limit for the number of jobs returned in a single call. As a result, this function might involve making several calls to the server. See also the `skip` parameter for more control over pagination. Args: limit: Number of jobs to retrieve. skip: Starting index for the job retrieval. status: Only get jobs with this status or one of the statuses. For example, you can specify `status=JobStatus.RUNNING` or `status="RUNNING"` or `status=["RUNNING", "ERROR"]` job_name: Filter by job name. The `job_name` is matched partially and `regular expressions <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions>`_ can be used. start_datetime: Filter by the given start date, in local time. This is used to find jobs whose creation dates are after (greater than or equal to) this local date/time. end_datetime: Filter by the given end date, in local time. This is used to find jobs whose creation dates are before (less than or equal to) this local date/time. job_tags: Filter by tags assigned to jobs. job_tags_operator: Logical operator to use when filtering by job tags. Valid values are "AND" and "OR": * If "AND" is specified, then a job must have all of the tags specified in ``job_tags`` to be included. * If "OR" is specified, then a job only needs to have any of the tags specified in ``job_tags`` to be included. experiment_id: Filter by job experiment ID. descending: If ``True``, return the jobs in descending order of the job creation date (newest first). If ``False``, return in ascending order. db_filter: A `loopback-based filter <https://loopback.io/doc/en/lb2/Querying-data.html>`_. This is an interface to a database ``where`` filter. Some examples of its usage are: Filter last five jobs with errors:: job_list = backend.jobs(limit=5, status=JobStatus.ERROR) Filter last five jobs with hub name ``ibm-q``:: filter = {'hubInfo.hub.name': 'ibm-q'} job_list = backend.jobs(limit=5, db_filter=filter) Returns: A list of jobs that match the criteria. Raises: IBMQBackendValueError: If a keyword value is not recognized. """ return self._provider.backend.jobs( limit=limit, skip=skip, backend_name=self.name(), status=status, job_name=job_name, start_datetime=start_datetime, end_datetime=end_datetime, job_tags=job_tags, job_tags_operator=job_tags_operator, experiment_id=experiment_id, descending=descending, db_filter=db_filter) def active_jobs(self, limit: int = 10) -> List[IBMQJob]: """Return the unfinished jobs submitted to this backend. Return the jobs submitted to this backend, with this provider, that are currently in an unfinished job status state. The unfinished :class:`JobStatus<qiskit.providers.jobstatus.JobStatus>` states include: ``INITIALIZING``, ``VALIDATING``, ``QUEUED``, and ``RUNNING``. Args: limit: Number of jobs to retrieve. Returns: A list of the unfinished jobs for this backend on this provider. """ # Get the list of api job statuses which are not a final api job status. active_job_states = list({api_status_to_job_status(status) for status in ApiJobStatus if status not in API_JOB_FINAL_STATES}) return self.jobs(status=active_job_states, limit=limit) def retrieve_job(self, job_id: str) -> IBMQJob: """Return a single job submitted to this backend. Args: job_id: The ID of the job to retrieve. Returns: The job with the given ID. Raises: IBMQBackendError: If job retrieval failed. """ job = self._provider.backend.retrieve_job(job_id) job_backend = job.backend() if self.name() != job_backend.name(): warnings.warn('Job {} belongs to another backend than the one queried. ' 'The query was made on backend {}, ' 'but the job actually belongs to backend {}.' .format(job_id, self.name(), job_backend.name())) raise IBMQBackendError('Failed to get job {}: ' 'job does not belong to backend {}.' .format(job_id, self.name())) return job def reservations( self, start_datetime: Optional[python_datetime] = None, end_datetime: Optional[python_datetime] = None ) -> List[BackendReservation]: """Return backend reservations. If start_datetime and/or end_datetime is specified, reservations with time slots that overlap with the specified time window will be returned. Some of the reservation information is only available if you are the owner of the reservation. Args: start_datetime: Filter by the given start date/time, in local timezone. end_datetime: Filter by the given end date/time, in local timezone. Returns: A list of reservations that match the criteria. """ start_datetime = local_to_utc(start_datetime) if start_datetime else None end_datetime = local_to_utc(end_datetime) if end_datetime else None raw_response = self._api_client.backend_reservations( self.name(), start_datetime, end_datetime) return convert_reservation_data(raw_response, self.name()) def configuration(self) -> Union[QasmBackendConfiguration, PulseBackendConfiguration]: """Return the backend configuration. Backend configuration contains fixed information about the backend, such as its name, number of qubits, basis gates, coupling map, quantum volume, etc. The schema for backend configuration can be found in `Qiskit/ibm-quantum-schemas <https://github.com/Qiskit/ibm-quantum-schemas/blob/main/schemas/backend_configuration_schema.json>`_. Returns: The configuration for the backend. """ return self._configuration def __repr__(self) -> str: credentials_info = '' if self.hub: credentials_info = "hub='{}', group='{}', project='{}'".format( self.hub, self.group, self.project) return "<{}('{}') from IBMQ({})>".format( self.__class__.__name__, self.name(), credentials_info) def _deprecate_id_instruction( self, circuits: Union[QasmQobj, PulseQobj, QuantumCircuit, Schedule, List[Union[QuantumCircuit, Schedule]]] ) -> None: """Raise a DeprecationWarning if any circuit contains an 'id' instruction. Additionally, if 'delay' is a 'supported_instruction', replace each 'id' instruction (in-place) with the equivalent ('sx'-length) 'delay' instruction. Args: circuits: The individual or list of :class:`~qiskit.circuits.QuantumCircuit` or :class:`~qiskit.pulse.Schedule` objects passed to :meth:`IBMQBackend.run()<IBMQBackend.run>`. Modified in-place. Returns: None """ if isinstance(circuits, PulseQobj): return id_support = 'id' in getattr(self.configuration(), 'basis_gates', []) delay_support = 'delay' in getattr(self.configuration(), 'supported_instructions', []) if not delay_support: return if isinstance(circuits, QasmQobj): circuit_has_id = any(instr.name == 'id' for experiment in circuits.experiments for instr in experiment.instructions) else: if not isinstance(circuits, List): circuits = [circuits] circuit_has_id = any(instr.name == 'id' for circuit in circuits if isinstance(circuit, QuantumCircuit) for instr, qargs, cargs in circuit.data) if not circuit_has_id: return if not self.id_warning_issued: if id_support and delay_support: warnings.warn("Support for the 'id' instruction has been deprecated " "from IBM hardware backends. Any 'id' instructions " "will be replaced with their equivalent 'delay' instruction. " "Please use the 'delay' instruction instead.", DeprecationWarning, stacklevel=4) else: warnings.warn("Support for the 'id' instruction has been removed " "from IBM hardware backends. Any 'id' instructions " "will be replaced with their equivalent 'delay' instruction. " "Please use the 'delay' instruction instead.", DeprecationWarning, stacklevel=4) self.id_warning_issued = True dt_in_s = self.configuration().dt if isinstance(circuits, QasmQobj): for experiment in circuits.experiments: for instr in experiment.instructions: if instr.name == 'id': sx_duration = self.properties().gate_length('sx', instr.qubits[0]) sx_duration_in_dt = duration_in_dt(sx_duration, dt_in_s) instr.name = 'delay' instr.params = [sx_duration_in_dt] else: for circuit in circuits: if isinstance(circuit, Schedule): continue for idx, (instr, qargs, cargs) in enumerate(circuit.data): if instr.name == 'id': sx_duration = self.properties().gate_length('sx', qargs[0].index) sx_duration_in_dt = duration_in_dt(sx_duration, dt_in_s) delay_instr = Delay(sx_duration_in_dt) circuit.data[idx] = (delay_instr, qargs, cargs) class IBMQSimulator(IBMQBackend): """Backend class interfacing with an IBM Quantum Experience simulator.""" @classmethod def _default_options(cls) -> Options: """Default runtime options.""" options = super()._default_options() options.update_options(noise_model=None, seed_simulator=None) return options def properties( self, refresh: bool = False, datetime: Optional[python_datetime] = None ) -> None: """Return ``None``, simulators do not have backend properties.""" return None @deprecate_arguments({'qobj': 'circuits'}) def run( # type: ignore[override] self, circuits: Union[QasmQobj, PulseQobj, QuantumCircuit, Schedule, List[Union[QuantumCircuit, Schedule]]], job_name: Optional[str] = None, job_share_level: Optional[str] = None, job_tags: Optional[List[str]] = None, experiment_id: Optional[str] = None, backend_options: Optional[Dict] = None, noise_model: Any = None, **kwargs: Dict ) -> IBMQJob: """Run a Qobj asynchronously. Args: circuits: An individual or a list of :class:`~qiskit.circuits.QuantumCircuit` or :class:`~qiskit.pulse.Schedule` objects to run on the backend. A :class:`~qiskit.qobj.QasmQobj` or a :class:`~qiskit.qobj.PulseQobj` object is also supported but is deprecated. job_name: Custom name to be assigned to the job. This job name can subsequently be used as a filter in the :meth:`jobs` method. Job names do not need to be unique. job_share_level: Allows sharing a job at the hub, group, project and global level (see :meth:`IBMQBackend.run()<IBMQBackend.run>` for more details). job_tags: Tags to be assigned to the jobs. The tags can subsequently be used as a filter in the :meth:`IBMQBackend.jobs()<IBMQBackend.jobs>` method. experiment_id: Used to add a job to an "experiment", which is a collection of jobs and additional metadata. backend_options: DEPRECATED dictionary of backend options for the execution. noise_model: Noise model. kwargs: Additional runtime configuration options. They take precedence over options of the same names specified in `backend_options`. Returns: The job to be executed. """ # pylint: disable=arguments-differ if job_share_level: warnings.warn("The `job_share_level` keyword is no longer supported " "and will be removed in a future release.", Warning, stacklevel=3) if backend_options is not None: warnings.warn("Use of `backend_options` is deprecated and will " "be removed in a future release." "You can now pass backend options as key-value pairs to the " "run() method. For example: backend.run(circs, shots=2048).", DeprecationWarning, stacklevel=2) backend_options = backend_options or {} run_config = copy.deepcopy(backend_options) if noise_model: try: noise_model = noise_model.to_dict() except AttributeError: pass run_config.update(kwargs) return super().run(circuits, job_name=job_name, job_tags=job_tags, experiment_id=experiment_id, noise_model=noise_model, **run_config) class IBMQRetiredBackend(IBMQBackend): """Backend class interfacing with an IBM Quantum Experience device no longer available.""" def __init__( self, configuration: Union[QasmBackendConfiguration, PulseBackendConfiguration], provider: 'accountprovider.AccountProvider', credentials: Credentials, api_client: AccountClient ) -> None: """IBMQRetiredBackend constructor. Args: configuration: Backend configuration. provider: IBM Quantum Experience account provider credentials: IBM Quantum Experience credentials. api_client: IBM Quantum Experience client used to communicate with the server. """ super().__init__(configuration, provider, credentials, api_client) self._status = BackendStatus( backend_name=self.name(), backend_version=self.configuration().backend_version, operational=False, pending_jobs=0, status_msg='This backend is no longer available.') @classmethod def _default_options(cls) -> Options: """Default runtime options.""" return Options() def properties( self, refresh: bool = False, datetime: Optional[python_datetime] = None ) -> None: """Return the backend properties.""" return None def defaults(self, refresh: bool = False) -> None: """Return the pulse defaults for the backend.""" return None def status(self) -> BackendStatus: """Return the backend status.""" return self._status def job_limit(self) -> None: """Return the job limits for the backend.""" return None def remaining_jobs_count(self) -> None: """Return the number of remaining jobs that could be submitted to the backend.""" return None def active_jobs(self, limit: int = 10) -> None: """Return the unfinished jobs submitted to this backend.""" return None def reservations( self, start_datetime: Optional[python_datetime] = None, end_datetime: Optional[python_datetime] = None ) -> List[BackendReservation]: return [] def run( # type: ignore[override] self, *args: Any, **kwargs: Any ) -> None: """Run a Qobj.""" # pylint: disable=arguments-differ raise IBMQBackendError('This backend ({}) is no longer available.'.format(self.name())) @classmethod def from_name( cls, backend_name: str, provider: 'accountprovider.AccountProvider', credentials: Credentials, api: AccountClient ) -> 'IBMQRetiredBackend': """Return a retired backend from its name.""" configuration = QasmBackendConfiguration( backend_name=backend_name, backend_version='0.0.0', n_qubits=1, basis_gates=[], simulator=False, local=False, conditional=False, open_pulse=False, memory=False, max_shots=1, gates=[GateConfig(name='TODO', parameters=[], qasm_def='TODO')], coupling_map=[[0, 1]], ) return cls(configuration, provider, credentials, api)
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test cases for the pulse scheduler passes.""" from numpy import pi from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, schedule from qiskit.circuit import Gate, Parameter from qiskit.circuit.library import U1Gate, U2Gate, U3Gate from qiskit.exceptions import QiskitError from qiskit.pulse import ( Schedule, DriveChannel, AcquireChannel, Acquire, MeasureChannel, MemorySlot, Gaussian, Play, transforms, ) from qiskit.pulse import build, macros, play, InstructionScheduleMap from qiskit.providers.fake_provider import FakeBackend, FakeOpenPulse2Q, FakeOpenPulse3Q from qiskit.test import QiskitTestCase class TestBasicSchedule(QiskitTestCase): """Scheduling tests.""" def setUp(self): super().setUp() self.backend = FakeOpenPulse2Q() self.inst_map = self.backend.defaults().instruction_schedule_map def test_unavailable_defaults(self): """Test backend with unavailable defaults.""" qr = QuantumRegister(1) qc = QuantumCircuit(qr) backend = FakeBackend(None) backend.defaults = backend.configuration self.assertRaises(QiskitError, lambda: schedule(qc, backend)) def test_alap_pass(self): """Test ALAP scheduling.""" # ┌───────────────┐ ░ ┌─┐ # q0_0: ┤ U2(3.14,1.57) ├────────────────────░───■──┤M├─── # └┬──────────────┤ ░ ┌──────────────┐ ░ ┌─┴─┐└╥┘┌─┐ # q0_1: ─┤ U2(0.5,0.25) ├─░─┤ U2(0.5,0.25) ├─░─┤ X ├─╫─┤M├ # └──────────────┘ ░ └──────────────┘ ░ └───┘ ║ └╥┘ # c0: 2/═════════════════════════════════════════════╩══╩═ # 0 1 q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.append(U2Gate(3.14, 1.57), [q[0]]) qc.append(U2Gate(0.5, 0.25), [q[1]]) qc.barrier(q[1]) qc.append(U2Gate(0.5, 0.25), [q[1]]) qc.barrier(q[0], [q[1]]) qc.cx(q[0], q[1]) qc.measure(q, c) sched = schedule(qc, self.backend) # X pulse on q0 should end at the start of the CNOT expected = Schedule( (2, self.inst_map.get("u2", [0], 3.14, 1.57)), self.inst_map.get("u2", [1], 0.5, 0.25), (2, self.inst_map.get("u2", [1], 0.5, 0.25)), (4, self.inst_map.get("cx", [0, 1])), (26, self.inst_map.get("measure", [0, 1])), ) for actual, expected in zip(sched.instructions, expected.instructions): self.assertEqual(actual[0], expected[0]) self.assertEqual(actual[1], expected[1]) def test_single_circuit_list_schedule(self): """Test that passing a single circuit list to schedule() returns a list.""" q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) sched = schedule([qc], self.backend, method="alap") expected = Schedule() self.assertIsInstance(sched, list) self.assertEqual(sched[0].instructions, expected.instructions) def test_alap_with_barriers(self): """Test that ALAP respects barriers on new qubits.""" q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.append(U2Gate(0, 0), [q[0]]) qc.barrier(q[0], q[1]) qc.append(U2Gate(0, 0), [q[1]]) sched = schedule(qc, self.backend, method="alap") expected = Schedule( self.inst_map.get("u2", [0], 0, 0), (2, self.inst_map.get("u2", [1], 0, 0)) ) for actual, expected in zip(sched.instructions, expected.instructions): self.assertEqual(actual[0], expected[0]) self.assertEqual(actual[1], expected[1]) def test_empty_circuit_schedule(self): """Test empty circuit being scheduled.""" q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) sched = schedule(qc, self.backend, method="alap") expected = Schedule() self.assertEqual(sched.instructions, expected.instructions) def test_alap_aligns_end(self): """Test that ALAP always acts as though there is a final global barrier.""" q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.append(U3Gate(0, 0, 0), [q[0]]) qc.append(U2Gate(0, 0), [q[1]]) sched = schedule(qc, self.backend, method="alap") expected_sched = Schedule( (2, self.inst_map.get("u2", [1], 0, 0)), self.inst_map.get("u3", [0], 0, 0, 0) ) for actual, expected in zip(sched.instructions, expected_sched.instructions): self.assertEqual(actual[0], expected[0]) self.assertEqual(actual[1], expected[1]) self.assertEqual( sched.ch_duration(DriveChannel(0)), expected_sched.ch_duration(DriveChannel(1)) ) def test_asap_pass(self): """Test ASAP scheduling.""" # ┌───────────────┐ ░ ┌─┐ # q0_0: ┤ U2(3.14,1.57) ├────────────────────░───■──┤M├─── # └┬──────────────┤ ░ ┌──────────────┐ ░ ┌─┴─┐└╥┘┌─┐ # q0_1: ─┤ U2(0.5,0.25) ├─░─┤ U2(0.5,0.25) ├─░─┤ X ├─╫─┤M├ # └──────────────┘ ░ └──────────────┘ ░ └───┘ ║ └╥┘ # c0: 2/═════════════════════════════════════════════╩══╩═ # 0 1 q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.append(U2Gate(3.14, 1.57), [q[0]]) qc.append(U2Gate(0.5, 0.25), [q[1]]) qc.barrier(q[1]) qc.append(U2Gate(0.5, 0.25), [q[1]]) qc.barrier(q[0], q[1]) qc.cx(q[0], q[1]) qc.measure(q, c) sched = schedule(qc, self.backend, method="as_soon_as_possible") # X pulse on q0 should start at t=0 expected = Schedule( self.inst_map.get("u2", [0], 3.14, 1.57), self.inst_map.get("u2", [1], 0.5, 0.25), (2, self.inst_map.get("u2", [1], 0.5, 0.25)), (4, self.inst_map.get("cx", [0, 1])), (26, self.inst_map.get("measure", [0, 1])), ) for actual, expected in zip(sched.instructions, expected.instructions): self.assertEqual(actual[0], expected[0]) self.assertEqual(actual[1], expected[1]) def test_alap_resource_respecting(self): """Test that the ALAP pass properly respects busy resources when backwards scheduling. For instance, a CX on 0 and 1 followed by an X on only 1 must respect both qubits' timeline.""" q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.cx(q[0], q[1]) qc.append(U2Gate(0.5, 0.25), [q[1]]) sched = schedule(qc, self.backend, method="as_late_as_possible") insts = sched.instructions self.assertEqual(insts[0][0], 0) self.assertEqual(insts[6][0], 22) qc = QuantumCircuit(q, c) qc.cx(q[0], q[1]) qc.append(U2Gate(0.5, 0.25), [q[1]]) qc.measure(q, c) sched = schedule(qc, self.backend, method="as_late_as_possible") self.assertEqual(sched.instructions[-1][0], 24) def test_inst_map_schedules_unaltered(self): """Test that forward scheduling doesn't change relative timing with a command.""" q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.cx(q[0], q[1]) sched1 = schedule(qc, self.backend, method="as_soon_as_possible") sched2 = schedule(qc, self.backend, method="as_late_as_possible") for asap, alap in zip(sched1.instructions, sched2.instructions): self.assertEqual(asap[0], alap[0]) self.assertEqual(asap[1], alap[1]) insts = sched1.instructions self.assertEqual(insts[0][0], 0) # shift phase self.assertEqual(insts[1][0], 0) # ym_d0 self.assertEqual(insts[2][0], 0) # x90p_d1 self.assertEqual(insts[3][0], 2) # cr90p_u0 self.assertEqual(insts[4][0], 11) # xp_d0 self.assertEqual(insts[5][0], 13) # cr90m_u0 def test_measure_combined(self): """ Test to check for measure on the same qubit which generated another measure schedule. The measures on different qubits are combined, but measures on the same qubit adds another measure to the schedule. """ q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.append(U2Gate(3.14, 1.57), [q[0]]) qc.cx(q[0], q[1]) qc.measure(q[0], c[0]) qc.measure(q[1], c[1]) qc.measure(q[1], c[1]) sched = schedule(qc, self.backend, method="as_soon_as_possible") expected = Schedule( self.inst_map.get("u2", [0], 3.14, 1.57), (2, self.inst_map.get("cx", [0, 1])), (24, self.inst_map.get("measure", [0, 1])), (34, self.inst_map.get("measure", [0, 1]).filter(channels=[MeasureChannel(1)])), (34, Acquire(10, AcquireChannel(1), MemorySlot(1))), ) self.assertEqual(sched.instructions, expected.instructions) def test_3q_schedule(self): """Test a schedule that was recommended by David McKay :D""" # ┌─────────────────┐ # q0_0: ─────────■─────────┤ U3(3.14,1.57,0) ├──────────────────────── # ┌─┴─┐ └┬───────────────┬┘ # q0_1: ───────┤ X ├────────┤ U2(3.14,1.57) ├───■───────────────────── # ┌──────┴───┴──────┐ └───────────────┘ ┌─┴─┐┌─────────────────┐ # q0_2: ┤ U2(0.778,0.122) ├───────────────────┤ X ├┤ U2(0.778,0.122) ├ # └─────────────────┘ └───┘└─────────────────┘ backend = FakeOpenPulse3Q() inst_map = backend.defaults().instruction_schedule_map q = QuantumRegister(3) c = ClassicalRegister(3) qc = QuantumCircuit(q, c) qc.cx(q[0], q[1]) qc.append(U2Gate(0.778, 0.122), [q[2]]) qc.append(U3Gate(3.14, 1.57, 0), [q[0]]) qc.append(U2Gate(3.14, 1.57), [q[1]]) qc.cx(q[1], q[2]) qc.append(U2Gate(0.778, 0.122), [q[2]]) sched = schedule(qc, backend) expected = Schedule( inst_map.get("cx", [0, 1]), (22, inst_map.get("u2", [1], 3.14, 1.57)), (22, inst_map.get("u2", [2], 0.778, 0.122)), (24, inst_map.get("cx", [1, 2])), (44, inst_map.get("u3", [0], 3.14, 1.57, 0)), (46, inst_map.get("u2", [2], 0.778, 0.122)), ) for actual, expected in zip(sched.instructions, expected.instructions): self.assertEqual(actual[0], expected[0]) self.assertEqual(actual[1], expected[1]) def test_schedule_multi(self): """Test scheduling multiple circuits at once.""" q = QuantumRegister(2) c = ClassicalRegister(2) qc0 = QuantumCircuit(q, c) qc0.cx(q[0], q[1]) qc1 = QuantumCircuit(q, c) qc1.cx(q[0], q[1]) schedules = schedule([qc0, qc1], self.backend) expected_insts = schedule(qc0, self.backend).instructions for actual, expected in zip(schedules[0].instructions, expected_insts): self.assertEqual(actual[0], expected[0]) self.assertEqual(actual[1], expected[1]) def test_circuit_name_kept(self): """Test that the new schedule gets its name from the circuit.""" q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c, name="CIRCNAME") qc.cx(q[0], q[1]) sched = schedule(qc, self.backend, method="asap") self.assertEqual(sched.name, qc.name) sched = schedule(qc, self.backend, method="alap") self.assertEqual(sched.name, qc.name) def test_can_add_gates_into_free_space(self): """The scheduler does some time bookkeeping to know when qubits are free to be scheduled. Make sure this works for qubits that are used in the future. This was a bug, uncovered by this example: q0 = - - - - |X| q1 = |X| |u2| |X| In ALAP scheduling, the next operation on qubit 0 would be added at t=0 rather than immediately before the X gate. """ qr = QuantumRegister(2) qc = QuantumCircuit(qr) for i in range(2): qc.append(U2Gate(0, 0), [qr[i]]) qc.append(U1Gate(3.14), [qr[i]]) qc.append(U2Gate(0, 0), [qr[i]]) sched = schedule(qc, self.backend, method="alap") expected = Schedule( self.inst_map.get("u2", [0], 0, 0), self.inst_map.get("u2", [1], 0, 0), (2, self.inst_map.get("u1", [0], 3.14)), (2, self.inst_map.get("u1", [1], 3.14)), (2, self.inst_map.get("u2", [0], 0, 0)), (2, self.inst_map.get("u2", [1], 0, 0)), ) for actual, expected in zip(sched.instructions, expected.instructions): self.assertEqual(actual[0], expected[0]) self.assertEqual(actual[1], expected[1]) def test_barriers_in_middle(self): """As a follow on to `test_can_add_gates_into_free_space`, similar issues arose for barriers, specifically. """ qr = QuantumRegister(2) qc = QuantumCircuit(qr) for i in range(2): qc.append(U2Gate(0, 0), [qr[i]]) qc.barrier(qr[i]) qc.append(U1Gate(3.14), [qr[i]]) qc.barrier(qr[i]) qc.append(U2Gate(0, 0), [qr[i]]) sched = schedule(qc, self.backend, method="alap") expected = Schedule( self.inst_map.get("u2", [0], 0, 0), self.inst_map.get("u2", [1], 0, 0), (2, self.inst_map.get("u1", [0], 3.14)), (2, self.inst_map.get("u1", [1], 3.14)), (2, self.inst_map.get("u2", [0], 0, 0)), (2, self.inst_map.get("u2", [1], 0, 0)), ) for actual, expected in zip(sched.instructions, expected.instructions): self.assertEqual(actual[0], expected[0]) self.assertEqual(actual[1], expected[1]) def test_parametric_input(self): """Test that scheduling works with parametric pulses as input.""" qr = QuantumRegister(1) qc = QuantumCircuit(qr) qc.append(Gate("gauss", 1, []), qargs=[qr[0]]) custom_gauss = Schedule( Play(Gaussian(duration=25, sigma=4, amp=0.5, angle=pi / 2), DriveChannel(0)) ) self.inst_map.add("gauss", [0], custom_gauss) sched = schedule(qc, self.backend, inst_map=self.inst_map) self.assertEqual(sched.instructions[0], custom_gauss.instructions[0]) def test_pulse_gates(self): """Test scheduling calibrated pulse gates.""" q = QuantumRegister(2) qc = QuantumCircuit(q) qc.append(U2Gate(0, 0), [q[0]]) qc.barrier(q[0], q[1]) qc.append(U2Gate(0, 0), [q[1]]) qc.add_calibration("u2", [0], Schedule(Play(Gaussian(28, 0.2, 4), DriveChannel(0))), [0, 0]) qc.add_calibration("u2", [1], Schedule(Play(Gaussian(28, 0.2, 4), DriveChannel(1))), [0, 0]) sched = schedule(qc, self.backend) expected = Schedule( Play(Gaussian(28, 0.2, 4), DriveChannel(0)), (28, Schedule(Play(Gaussian(28, 0.2, 4), DriveChannel(1)))), ) self.assertEqual(sched.instructions, expected.instructions) def test_calibrated_measurements(self): """Test scheduling calibrated measurements.""" q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.append(U2Gate(0, 0), [q[0]]) qc.measure(q[0], c[0]) meas_sched = Play(Gaussian(1200, 0.2, 4), MeasureChannel(0)) meas_sched |= Acquire(1200, AcquireChannel(0), MemorySlot(0)) qc.add_calibration("measure", [0], meas_sched) sched = schedule(qc, self.backend) expected = Schedule(self.inst_map.get("u2", [0], 0, 0), (2, meas_sched)) self.assertEqual(sched.instructions, expected.instructions) def test_subset_calibrated_measurements(self): """Test that measurement calibrations can be added and used for some qubits, even if the other qubits do not also have calibrated measurements.""" qc = QuantumCircuit(3, 3) qc.measure(0, 0) qc.measure(1, 1) qc.measure(2, 2) meas_scheds = [] for qubit in [0, 2]: meas = Play(Gaussian(1200, 0.2, 4), MeasureChannel(qubit)) + Acquire( 1200, AcquireChannel(qubit), MemorySlot(qubit) ) meas_scheds.append(meas) qc.add_calibration("measure", [qubit], meas) meas = macros.measure([1], FakeOpenPulse3Q()) meas = meas.exclude(channels=[AcquireChannel(0), AcquireChannel(2)]) sched = schedule(qc, FakeOpenPulse3Q()) expected = Schedule(meas_scheds[0], meas_scheds[1], meas) self.assertEqual(sched.instructions, expected.instructions) def test_clbits_of_calibrated_measurements(self): """Test that calibrated measurements are only used when the classical bits also match.""" q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.measure(q[0], c[1]) meas_sched = Play(Gaussian(1200, 0.2, 4), MeasureChannel(0)) meas_sched |= Acquire(1200, AcquireChannel(0), MemorySlot(0)) qc.add_calibration("measure", [0], meas_sched) sched = schedule(qc, self.backend) # Doesn't use the calibrated schedule because the classical memory slots do not match expected = Schedule(macros.measure([0], self.backend, qubit_mem_slots={0: 1})) self.assertEqual(sched.instructions, expected.instructions) def test_metadata_is_preserved_alap(self): """Test that circuit metadata is preserved in output schedule with alap.""" q = QuantumRegister(2) qc = QuantumCircuit(q) qc.append(U2Gate(0, 0), [q[0]]) qc.barrier(q[0], q[1]) qc.append(U2Gate(0, 0), [q[1]]) qc.metadata = {"experiment_type": "gst", "execution_number": "1234"} sched = schedule(qc, self.backend, method="alap") self.assertEqual({"experiment_type": "gst", "execution_number": "1234"}, sched.metadata) def test_metadata_is_preserved_asap(self): """Test that circuit metadata is preserved in output schedule with asap.""" q = QuantumRegister(2) qc = QuantumCircuit(q) qc.append(U2Gate(0, 0), [q[0]]) qc.barrier(q[0], q[1]) qc.append(U2Gate(0, 0), [q[1]]) qc.metadata = {"experiment_type": "gst", "execution_number": "1234"} sched = schedule(qc, self.backend, method="asap") self.assertEqual({"experiment_type": "gst", "execution_number": "1234"}, sched.metadata) def test_scheduler_with_params_bound(self): """Test scheduler with parameters defined and bound""" x = Parameter("x") qc = QuantumCircuit(2) qc.append(Gate("pulse_gate", 1, [x]), [0]) expected_schedule = Schedule() qc.add_calibration(gate="pulse_gate", qubits=[0], schedule=expected_schedule, params=[x]) qc = qc.assign_parameters({x: 1}) sched = schedule(qc, self.backend) self.assertEqual(sched, expected_schedule) def test_scheduler_with_params_not_bound(self): """Test scheduler with parameters defined but not bound""" x = Parameter("amp") qc = QuantumCircuit(2) qc.append(Gate("pulse_gate", 1, [x]), [0]) with build() as expected_schedule: play(Gaussian(duration=160, amp=x, sigma=40), DriveChannel(0)) qc.add_calibration(gate="pulse_gate", qubits=[0], schedule=expected_schedule, params=[x]) sched = schedule(qc, self.backend) self.assertEqual(sched, transforms.target_qobj_transform(expected_schedule)) def test_schedule_block_in_instmap(self): """Test schedule block in instmap can be scheduled.""" duration = Parameter("duration") with build() as pulse_prog: play(Gaussian(duration, 0.1, 10), DriveChannel(0)) instmap = InstructionScheduleMap() instmap.add("block_gate", (0,), pulse_prog, ["duration"]) qc = QuantumCircuit(1) qc.append(Gate("block_gate", 1, [duration]), [0]) qc.assign_parameters({duration: 100}, inplace=True) sched = schedule(qc, self.backend, inst_map=instmap) ref_sched = Schedule() ref_sched += Play(Gaussian(100, 0.1, 10), DriveChannel(0)) self.assertEqual(sched, ref_sched)
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt plt.style.use("ggplot") from pprint import pprint import pickle import time import datetime %matplotlib inline # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, X, Y, Z, I from qiskit.opflow.state_fns.dict_state_fn import DictStateFn from qiskit.quantum_info import DensityMatrix from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, 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 # unused for this file 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("../../solutions/utils/") import circuit_utils, zne_utils, tomography_utils importlib.reload(circuit_utils) importlib.reload(zne_utils) # unused for this file importlib.reload(tomography_utils) # unused for this file from circuit_utils import * from zne_utils import zne_wrapper, zne_decoder from tomography_utils import expvals_to_valid_rho from qiskit.test.mock import FakeJakarta # backend = FakeJakarta() backend = Aer.get_backend("qasm_simulator") # Returns the matrix representation of the XXX Heisenberg model for 3 spin-1/2 particles in a line def H_heis3(): # Interactions (I is the identity matrix; X, Y, and Z are Pauli matricies; ^ is a tensor product) XXs = (I^X^X) + (X^X^I) YYs = (I^Y^Y) + (Y^Y^I) ZZs = (I^Z^Z) + (Z^Z^I) # Sum interactions H = XXs + YYs + ZZs # Return Hamiltonian return H # Returns the matrix representation of U_heis3(t) for a given time t assuming an XXX Heisenberg Hamiltonian for 3 spins-1/2 particles in a line def U_heis3(t): # Compute XXX Hamiltonian for 3 spins in a line H = H_heis3() # Return the exponential of -i multipled by time t multipled by the 3 spin XXX Heisenberg Hamilonian return (t * H).exp_i() # Define array of time points ts = np.linspace(0, np.pi, 100) target_state = DictStateFn({"000": 0, "001": 0, "010": 1, "011": 0, "100": 0, "101": 0, "110": 1, "111": 0}, 1 / np.sqrt(2)) print(DensityMatrix(target_state.to_density_matrix()).is_valid()) # Compute probability of remaining in |110> state over the array of time points # ~target_state gives the bra of the initial state (<110|) # @ is short hand for matrix multiplication # U_heis3(t) is the unitary time evolution at time t # t needs to be wrapped with float(t) to avoid a bug # (...).eval() returns the inner product <110|U_heis3(t)|110> # np.abs(...)**2 is the modulus squared of the innner product which is the expectation value, or probability, of remaining in |110> probs_010_110 = [np.abs((~target_state @ U_heis3(float(t)) @ target_state).eval())**2 for t in ts] # Plot evolution of |110> plt.figure(dpi=200) plt.plot(ts, probs_010_110) plt.xlabel('time') plt.ylabel(r'probability of state $|010\rangle + |110\rangle$') plt.title(r'Evolution of state $|010\rangle + |110\rangle$ under $H_{Heis3}$') # plt.grid() plt.show() num_qubits = 3 # The final time of the state evolution target_times = [i * np.pi / 20 for i in range(0, 20 + 1)] pprint(target_times) # 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] # unused for this file shots = 1 << 13 reps = 8 # unused target_state = np.zeros((1 << num_qubits, 1 << num_qubits)) target_state[2, 2] = target_state[6, 6] = target_state[2, 6] = target_state[6, 2] = 0.5 target_state = DensityMatrix(target_state) target_state.draw("latex") prob_list = [] for target_time in target_times: print("target_time: ", target_time) t1 = time.perf_counter() # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") cr = ClassicalRegister(num_qubits, name="c") qc = QuantumCircuit(qr, cr) # 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>) qc.h(0) qc.x(1) general_subspace_encoder(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian general_subspace_decoder(qc, targets=[0, 1, 2]) # decode qc.x(1) qc.h(0) qc.measure(qr, cr[::-1]) # 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") # optimize circuit t3_qc = transpile(qc, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_qc = transpile(t3_qc, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_qc (depth:", t3_qc.depth(), ")") t3_qc = transpile(t3_qc, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_qc (depth:", t3_qc.depth(), ")") job = execute(t3_qc, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) prob = job.result().get_counts().get("0" * num_qubits, 0) / shots prob_list.append(prob) t2 = time.perf_counter() print(r'probability of state |010> + |110> = {:.4f}'.format(prob)) print("time:", t2 - t1) print() plt.figure(dpi=200) plt.plot(ts, probs_010_110, label="theoretical prediction") plt.scatter(target_times, prob_list, c="green", zorder=4) plt.legend(("theoretical prediction", "proposed method")) plt.xlabel('time') plt.ylabel(r'probability of state $|010\rangle + |110\rangle$') plt.title(r'Evolution of state $|010\rangle + |110\rangle$ under $H_{Heis3}$') plt.show() import qiskit.tools.jupyter %qiskit_version_table fid_list = [] for target_time in target_times: print("target_time: ", target_time) t1 = time.perf_counter() # 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>) qc.h(0) qc.x(1) general_subspace_encoder(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian general_subspace_decoder(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 = t3_st_qcs # zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = False) # 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), ")") job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) rho = StateTomographyFitter(job.result(), t3_zne_qcs).fit(method='lstsq') fid = state_fidelity(rho, target_state) fid_list.append(fid) t2 = time.perf_counter() print('state tomography fidelity = {:.4f}'.format(fid)) print("time:", t2 - t1) print()
https://github.com/qiskit-community/qiskit-jku-provider
qiskit-community
# -*- coding: utf-8 -*- # Copyright 2017, IBM. # # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. """Generate random circuits.""" import random import numpy from qiskit import (qasm, ClassicalRegister, QuantumCircuit, QuantumRegister) def choices(population, weights=None, k=1): """ Replacement for `random.choices()`, which is only available in Python 3.6+. TODO: drop once Python 3.6 is required by the sdk. """ if weights and sum(weights) != 1: # Normalize the weights if needed, as numpy.random.choice requires so. weights = [float(i)/sum(weights) for i in weights] return numpy.random.choice(population, size=k, p=weights) class RandomCircuitGenerator(object): """ Generate random size circuits for profiling. """ def __init__(self, seed=None, max_qubits=5, min_qubits=1, max_depth=100, min_depth=1): """ Args: seed (int): Random number seed. If none, don't seed the generator. max_qubits (int): Maximum number of qubits in a circuit. min_qubits (int): Minimum number of operations in a cirucit. max_depth (int): Maximum number of operations in a circuit. min_depth (int): Minimum number of operations in circuit. """ self.max_depth = max_depth self.max_qubits = max_qubits self.min_depth = min_depth self.min_qubits = min_qubits self.circuit_list = [] self.n_qubit_list = [] self.depth_list = [] self.basis_gates = None self.circuit_name_list = [] if seed is not None: random.seed(a=seed) # specify number of parameters and args for each op # in the standard extension. If type hints (PEP484) are followed # maybe we can guess this. "nregs" are the number of qubits the # operation uses. If nregs=0 then it means either 1 qubit or # 1 register. "nparams" are the number of parameters the operation takes. self.op_signature = { 'barrier': {'nregs': 0, 'nparams': None}, 'ccx': {'nregs': 3, 'nparams': None}, 'ch': {'nregs': 2, 'nparams': None}, 'crz': {'nregs': 2, 'nparams': 1}, 'cswap': {'nregs': 3, 'nparams': None}, 'cu1': {'nregs': 2, 'nparams': 1}, 'cu3': {'nregs': 2, 'nparams': 3}, 'cx': {'nregs': 2, 'nparams': None}, 'cy': {'nregs': 2, 'nparams': None}, 'cz': {'nregs': 2, 'nparams': None}, 'h': {'nregs': 1, 'nparams': None}, 'iden': {'nregs': 1, 'nparams': None}, 'measure': {'nregs': 0, 'nparams': None}, 'reset': {'nregs': 1, 'nparams': None}, 'rx': {'nregs': 1, 'nparams': 1}, 'ry': {'nregs': 1, 'nparams': 1}, 'rz': {'nregs': 1, 'nparams': 1}, 's': {'nregs': 1, 'nparams': None}, 't': {'nregs': 1, 'nparams': None}, 'u1': {'nregs': 1, 'nparams': 1}, 'u2': {'nregs': 1, 'nparams': 2}, 'u3': {'nregs': 1, 'nparams': 3}, 'x': {'nregs': 1, 'nparams': None}, 'y': {'nregs': 1, 'nparams': None}, 'z': {'nregs': 1, 'nparams': None}} def add_circuits(self, n_circuits, do_measure=True, basis=None, basis_weights=None): """Adds circuits to program. Generates a circuit with a random number of operations in `basis`. Also adds a random number of measurements in [1,nQubits] to end of circuit. Args: n_circuits (int): Number of circuits to add. do_measure (bool): Whether to add measurements. basis (list(str) or None): List of op names. If None, basis is randomly chosen with unique ops in (2,7) basis_weights (list(float) or None): List of weights corresponding to indices in `basis`. Raises: AttributeError: if operation is not recognized. """ if basis is None: basis = list(random.sample(self.op_signature.keys(), random.randint(2, 7))) basis_weights = [1./len(basis)] * len(basis) if basis_weights is not None: assert len(basis) == len(basis_weights) uop_basis = basis[:] if basis_weights: uop_basis_weights = basis_weights[:] else: uop_basis_weights = None # remove barrier from uop basis if it is specified if 'barrier' in uop_basis: ind = uop_basis.index('barrier') del uop_basis[ind] if uop_basis_weights: del uop_basis_weights[ind] # remove measure from uop basis if it is specified if 'measure' in uop_basis: ind = uop_basis.index('measure') del uop_basis[ind] if uop_basis_weights: del uop_basis_weights[ind] # self.basis_gates = uop_basis self.basis_gates = basis self.circuit_name_list = [] # TODO: replace choices with random.choices() when python 3.6 is # required. self.n_qubit_list = choices( range(self.min_qubits, self.max_qubits + 1), k=n_circuits) self.depth_list = choices( range(self.min_depth, self.max_depth + 1), k=n_circuits) for i_circuit in range(n_circuits): n_qubits = self.n_qubit_list[i_circuit] if self.min_regs_exceeds_nqubits(uop_basis, n_qubits): # no gate operation from this circuit can fit in the available # number of qubits. continue depth_cnt = self.depth_list[i_circuit] reg_pop = numpy.arange(1, n_qubits+1) register_weights = reg_pop[::-1].astype(float) register_weights /= register_weights.sum() max_registers = numpy.random.choice(reg_pop, p=register_weights) reg_weight = numpy.ones(max_registers) / float(max_registers) reg_sizes = rand_register_sizes(n_qubits, reg_weight) n_registers = len(reg_sizes) circuit = QuantumCircuit() for i_size, size in enumerate(reg_sizes): cr_name = 'cr' + str(i_size) qr_name = 'qr' + str(i_size) creg = ClassicalRegister(int(size), cr_name) qreg = QuantumRegister(int(size), qr_name) circuit.add_register(qreg, creg) while depth_cnt > 0: # TODO: replace choices with random.choices() when python 3.6 # is required. op_name = choices(basis, weights=basis_weights)[0] if hasattr(circuit, op_name): operator = getattr(circuit, op_name) else: raise AttributeError('operation \"{0}\"' ' not recognized'.format(op_name)) n_regs = self.op_signature[op_name]['nregs'] n_params = self.op_signature[op_name]['nparams'] if n_regs == 0: # this is a barrier or measure n_regs = random.randint(1, n_qubits) if n_qubits >= n_regs: # warning: assumes op function signature specifies # op parameters before qubits op_args = [] if n_params: op_args = [random.random() for _ in range(n_params)] if op_name == 'measure': # if measure occurs here, assume it's to do a conditional # randomly select a register to measure ireg = random.randint(0, n_registers-1) qr_name = 'qr' + str(ireg) cr_name = 'cr' + str(ireg) qreg = circuit.regs[qr_name] creg = circuit.regs[cr_name] for qind in range(qreg.size): operator(qreg[qind], creg[qind]) ifval = random.randint(0, (1 << qreg.size) - 1) # TODO: replace choices with random.choices() when # python 3.6 is required. uop_name = choices(uop_basis, weights=uop_basis_weights)[0] if hasattr(circuit, uop_name): uop = getattr(circuit, uop_name) else: raise AttributeError('operation \"{0}\"' ' not recognized'.format(uop_name)) unregs = self.op_signature[uop_name]['nregs'] unparams = self.op_signature[uop_name]['nparams'] if unregs == 0: # this is a barrier or measure unregs = random.randint(1, n_qubits) if qreg.size >= unregs: qind_list = random.sample(range(qreg.size), unregs) uop_args = [] if unparams: uop_args = [random.random() for _ in range(unparams)] uop_args.extend([qreg[qind] for qind in qind_list]) uop(*uop_args).c_if(creg, ifval) depth_cnt -= 1 elif op_name == 'barrier': ireg = random.randint(0, n_registers-1) qreg = circuit.qregs[ireg] bar_args = [(qreg, mi) for mi in range(qreg.size)] operator(*bar_args) else: # select random register ireg = random.randint(0, n_registers-1) qreg = circuit.qregs[ireg] if qreg.size >= n_regs: qind_list = random.sample(range(qreg.size), n_regs) op_args.extend([qreg[qind] for qind in qind_list]) operator(*op_args) depth_cnt -= 1 else: break nmeasure = random.randint(1, n_qubits) m_list = random.sample(range(nmeasure), nmeasure) if do_measure: for qind in m_list: rind = 0 # register index cumtot = 0 while qind >= cumtot + circuit.qregs[rind].size: cumtot += circuit.qregs[rind].size rind += 1 qrind = int(qind - cumtot) qreg = circuit.qregs[rind] creg = circuit.cregs[rind] circuit.measure(qreg[qrind], creg[qrind]) self.circuit_list.append(circuit) def min_regs_exceeds_nqubits(self, basis, n_qubits): """Check whether the minimum number of qubits used by the operations in basis is between 1 and the number of qubits. Args: basis (list): list of basis names n_qubits (int): number of qubits in circuit Returns: boolean: result of the check. """ return not any((n_qubits >= self.op_signature[opName]['nregs'] > 0 for opName in basis)) def get_circuits(self, format_='QuantumCircuit'): """Get the compiled circuits generated. Args: format_ (str, optional): "qasm" | "qobj" | "QuantumCircuit" Returns: list: List of Compiled QuantumCircuit objects. Raises: NameError: if the output format is not valid. """ if format_ == 'qasm': qasm_list = [] for circuit in self.circuit_list: qasm_list.append(circuit.qasm()) return qasm_list elif format_ == 'QuantumCircuit': qc_list = [] for circuit in self.circuit_list: qc_list.append(circuit) return qc_list else: raise NameError('Unrecognized circuit output format: "{}"'.format( format_)) def rand_register_sizes(n_registers, pvals): """Return a randomly chosen list of nRegisters summing to nQubits.""" vector = numpy.random.multinomial(n_registers, pvals) return vector[vector.nonzero()]
https://github.com/Qottmann/Quantum-anomaly-detection
Qottmann
import sys sys.path.insert(1, '..') # sets the path to the parent folder, where the notebook was originally executed import time import datetime import numpy as np from matplotlib import pyplot as plt import qiskit from qiskit import * from qiskit.opflow import X,Z,I from qiskit.opflow.state_fns import StateFn, CircuitStateFn from qiskit.providers.aer import StatevectorSimulator, AerSimulator from qiskit.algorithms import VQE from qiskit.algorithms.optimizers import COBYLA, SLSQP, SPSA from qiskit.opflow import CircuitSampler from qiskit.ignis.mitigation.measurement import CompleteMeasFitter # you will need to pip install qiskit-ignis from qiskit.ignis.mitigation.measurement import complete_meas_cal from scipy import sparse import scipy.sparse.linalg.eigen.arpack as arp from modules.utils import * anti = -1 L = 5 num_trash = 2 name = "ibmq_antiferro-1D-load_bogota-optimize" # remove test at the end when running on a real device filename = "data/noisy_VQE_maxiter-500_Ising_L5_anti_-1_20" #"data/noisy_VQE_maxiter-100_Ising_L5_anti_-1_20_recycle" print("filename: ", filename, "notebook name: ", name) # where to get the simulated thetas values from? needs to contain a thetas_mitigated array filename_simulated_thetas = 'data/ibmq_antiferro-1D-load_simu_thetas-loss-cost_run2.npz' load = False recompute = False # whether or not to recompute Magnetization, makes sense on device IBMQ.load_account() # this then automatically loads your saved account provider = IBMQ.get_provider(hub='ibm-q-research') device = provider.backend.ibmq_bogota print(device) backend = device #backend = qiskit.providers.aer.AerSimulator.from_backend(device) coupling_map = device.configuration().coupling_map noise_model = qiskit.providers.aer.noise.NoiseModel.from_backend(device) basis_gates = noise_model.basis_gates #aqua_globals.random_seed = seed qi = qiskit.utils.QuantumInstance(backend=backend, # , seed_simulator=seed, seed_transpiler=seed coupling_map=coupling_map, #, noise_model=noise_model, measurement_error_mitigation_cls= CompleteMeasFitter, cals_matrix_refresh_period=30 #How often to refresh the calibration matrix in measurement mitigation. in minutes ) # Very important, at the moment poorly coded so it needs to come back to this instance all the time ansatz = qiskit.circuit.library.TwoLocal(L,rotation_blocks="ry", entanglement_blocks='cz', entanglement="sca", reps=1) ansatz.draw("mpl") ansatz = qiskit.transpile(ansatz, backend) ansatz.draw("mpl") L = 5 num_trash = 2 anti = -1 VQE_params = np.load(filename + ".npz", allow_pickle=True) pick = np.arange(0,len(VQE_params['gx_list']),3) gx_list = VQE_params['gx_list'][pick] gz_list = VQE_params['gz_list'][pick] opt_params = VQE_params['opt_params'][pick] Qmags = VQE_params["Qmag"][pick] Qen = VQE_params["Qen"][pick] Sen = VQE_params["Sen"][pick] Smags = VQE_params["Smag"][pick] gx_vals = np.unique(gx_list) gz_vals = np.unique(gz_list) if load: temp = np.load("data/" + name + "executed_mags-Es.npz",allow_pickle=True) Qmags = temp["Qmags"] Qen = temp["Qen"] Sen = temp["Sen"] Smags = temp["Smags"] verbose=1 if recompute: mag = QMag(L,anti) #magnetization operator (Qiskit) Smag = Mag(L,anti) #magnetization operator (numpy) Qen_executed=np.zeros(len(opt_params), dtype="complex") Qmags_executed=np.zeros(len(opt_params), dtype="complex") for j in range(len(opt_params)): t0 = datetime.datetime.now() gx = gx_list[j] gz = gz_list[j] H = QHIsing(L, anti, np.float32(gx), np.float32(gz)) # build Hamiltonian Op state = ansatz.assign_parameters(opt_params[j]) meas_outcome = ~StateFn(mag) @ StateFn(state) Qmags_executed[j] = CircuitSampler(qi).convert(meas_outcome).eval() #https://quantumcomputing.stackexchange.com/questions/12080/evaluating-expectation-values-of-operators-in-qiskit #e_outcome = ~StateFn(H) @ StateFn(state) #Qen_executed[j] = CircuitSampler(qi).convert(e_outcome).eval() init_state, E, ham = ising_groundstate(L, anti, np.float64(gx), np.float64(gz)) Sen[j] = E Smags[j] = init_state.T.conj()@Smag@init_state #Magnetization with Numpy results print(f"{j+1} / {len(opt_params)}, gx = {gx:.2f}, gz = {gz:.2f}, time : {(datetime.datetime.now() - t0)}") np.savez("data/" + name + "executed_mags-Es.npz",Qmags=Qmags_executed, Qen=Qen_executed, Sen=Sen, Smags=Smags) # for large parameter space takes quite a while because of the exact diagonalization fig, axs = plt.subplots(ncols=2, figsize=(10,5)) ax = axs[0] ax.plot(gx_list, Qmags,"x--", label="noisy VQE simu") ax.plot(gx_list, Smags,"x--", label="ED") ax.set_xscale("log") if recompute: ax.plot(gx_list, Qmags_executed,"x--", label="IBMQ") ax.legend() ############################################################################## ### II - Training ########################################################### ############################################################################## # linear entangler (as in scales linearly with trash qubits) def get_entangler_map(L, num_trash, i_permut=1, nums_trash=[1,2]): result = [] nums_compressed = list(range(L)) for trashqubit in nums_trash: nums_compressed.remove(trashqubit) if nums_trash == None: #old way nums_compressed = list(range(L))[:L-num_trash] nums_trash = list(range(L))[-num_trash:] #print(nums, nums_compressed, nums_trash) # combine all trash qubits with themselves for trash_q in nums_trash[:-1]: result.append((trash_q+1,trash_q)) # combine each of the trash qubits with every n-th repeated = list(nums_trash) * (L-num_trash) # repeat the list of trash indices cyclicly for i in range(L-num_trash): result.append((repeated[i_permut + i], nums_compressed[i])) return result def QAE_Ansatz(thetas, L, num_trash, insert_barriers=False, parametrized_gate = "ry", entangling_gate = "cz", nums_trash = [1,2]): entanglement = [get_entangler_map(L,num_trash,i_permut) for i_permut in range(num_trash)] if nums_trash == None: nums_trash = list(range(L))[-num_trash:] circ = qiskit.circuit.library.TwoLocal(L, parametrized_gate, entangling_gate, entanglement, reps=num_trash, insert_barriers=insert_barriers, skip_final_rotation_layer=True ).assign_parameters(thetas[:-num_trash]) if insert_barriers: circ.barrier() for i in nums_trash: circ.ry(thetas[i], i) #circ.ry(circuit.Parameter(f'θ{i}'), L-i-1) return circ def prepare_circuit(thetas, L=6, num_trash=2, init_state=None, measurement=True, vqe=True): qreg = QuantumRegister(L, 'q') creg = ClassicalRegister(num_trash, 'c') circ = QuantumCircuit(qreg, creg) circ += QAE_Ansatz(thetas, L, num_trash, insert_barriers=False)#.assign_parameters(thetas) # difference to bind? if measurement: for i in range(num_trash): circ.measure(qreg[L-i-1], creg[i]) if init_state is not None: if vqe: circ = ansatz.assign_parameters(init_state) + circ # needs to have ansatz defined somewhere in the script else: circ.initialize(init_state, qreg) return circ def feature_encoding(thetas, x): """ thetas: parameters to be optimized, x: Ising model parameter (eg. field) """ new_thetas = [] thetas = thetas.reshape((-1,2)) for theta in thetas: new_thetas.append(theta[0] * x + theta[1]) return new_thetas def calibrate_circuit(L, num_trash,shots=1000): qreg = QuantumRegister(L, 'q') # obtain calibration matrix qubit_list = [L-i-1 for i in range(num_trash)] # only need to calibrate the trash qubits circlabel = f'mcal_{datetime.datetime.now()}' meas_calibs, state_labels = complete_meas_cal(qubit_list=qubit_list, qr=qreg, circlabel=circlabel) cal_job = backend.run(meas_calibs, shots=shots) #, noise_model=noise_model) cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel=circlabel) print(circlabel, meas_fitter.cal_matrix) return meas_fitter def run_circuit(thetas, L, num_trash, init_state, vqe=True, shots=100, meas_fitter = None): circ = prepare_circuit(thetas, L, num_trash, init_state, vqe=vqe) tcirc = qiskit.transpile(circ, backend) # Execute the circuit job_sim = backend.run(tcirc, shots=shots) # , seed_simulator=123, seed_transpiler=234 fix seed to make it reproducible result = job_sim.result() # Results without mitigation counts = result.get_counts() if meas_fitter != None: # Get the filter object meas_filter = meas_fitter.filter # Results with mitigation mitigated_results = meas_filter.apply(result) counts = mitigated_results.get_counts(0) return counts meas_fitter = calibrate_circuit(L, num_trash) phis = opt_params # translate to Rikes naming gxs = gx_list gzs = gz_list def cost_function_single(thetas, L, num_trash, p, shots=1000, vqe=True, param_encoding=False, x=0, meas_fitter=None): """ Optimizes circuit """ if vqe: init_state = phis[p] else: J, gx, gz = p init_state, _ = ising_groundstate(L, J, gx, gz) if param_encoding: thetas = feature_encoding(thetas, x) out = run_circuit(thetas, L, num_trash, init_state, vqe=vqe, shots=shots, meas_fitter=meas_fitter) cost = out.get('11', 0)*2 + out.get('01', 0) + out.get('10', 0) return cost/shots def cost_function(thetas, L, num_trash, ising_params, shots=1000, vqe=True, param_encoding=False, x=0, meas_fitter=None): """ Optimizes circuit """ cost = 0. n_samples = len(ising_params) for i, p in enumerate(ising_params): if param_encoding: cost += cost_function_single(thetas, L, num_trash, p, shots, vqe, param_encoding, x[i], meas_fitter=meas_fitter) else: cost += cost_function_single(thetas, L, num_trash, p, shots, vqe, param_encoding, meas_fitter=meas_fitter) return cost/n_samples def optimize(ising_params, L=6, num_trash=2, thetas=None, shots=1000, max_iter=400, vqe=True, param_encoding=False, x=0, pick_optimizer = None, meas_fitter=None): if thetas is None: n_params = (2*L+2)*2 if param_encoding else (2*L+2) thetas = np.random.uniform(0, 2*np.pi, n_params) # initial parameters without feature encoding print("Initial cost: {:.3f}".format(cost_function(thetas, L, num_trash, ising_params, shots, vqe, param_encoding, x))) counts, values, accepted = [], [], [] def store_intermediate_result(eval_count, parameters, mean, std, ac): # counts.append(eval_count) values.append(mean) accepted.append(ac) # Initialize optimizer if pick_optimizer == "cobyla": optimizer = COBYLA(maxiter=max_iter, tol=0.0001) if pick_optimizer == "adam" or pick_optimizer == "ADAM": optimizer = qiskit.algorithms.optimizers.ADAM(maxiter=max_iter) # optimizer = L_BFGS_B(maxfun=300, maxiter=max_iter)#, factr=10, iprint=- 1, epsilon=1e-08) if pick_optimizer == "spsa" or pick_optimizer == None: optimizer = SPSA(maxiter=max_iter, #blocking=True, callback=store_intermediate_result, learning_rate=0.3, perturbation=0.1 ) # recommended from qiskit (first iteraction takes quite long) # to reduce time figure out optimal learning rate and perturbation in advance start_time = time.time() ret = optimizer.optimize( num_vars=len(thetas), objective_function=(lambda thetas: cost_function(thetas, L, num_trash, ising_params, shots, vqe, param_encoding, x, meas_fitter=meas_fitter)), initial_point=thetas ) print("Time: {:.5f} sec".format(time.time()-start_time)) print(ret) return ret[0], values, accepted def run_inference(thetas, shots=1000, L=5, meas_fitter=None): points = 50 J = -1.0 x,y = np.meshgrid(gx_vals, gz_vals) cost = np.zeros((len(gx_vals) * len(gz_vals))) Smags = np.zeros((len(gx_vals) * len(gz_vals))) shots = 1000 for i,p in enumerate(list(zip(gxs, gzs))): t0 = datetime.datetime.now() cost[i] = cost_function_single(thetas, L, num_trash, i, shots=shots, meas_fitter=meas_fitter) if not i%verbose: print(f"{i+1} / {len(opt_params)}, gx = {gx:.2f}, gz = {gz:.2f}, time : {verbose*(datetime.datetime.now() - t0)}") cost = cost.reshape((len(gx_vals), len(gz_vals))) return cost phys_params = [-1] thetas_guess = np.load(filename_simulated_thetas, allow_pickle=True)["thetas_mitigated"] # Training thetas_opt_mitigated, loss, accepted = optimize(phys_params, thetas = thetas_guess, max_iter=30, L=5,meas_fitter=meas_fitter) #, pick_optimizer="adam") plt.plot(loss) # Inference cost_mitigated = np.zeros((len(gx_vals))) shots = 1000 for i,p in enumerate(list(zip(gxs, gzs))): t0 = datetime.datetime.now() cost_mitigated[i] = cost_function_single(thetas_opt_mitigated, L, num_trash, i, shots=shots, meas_fitter=meas_fitter) # np.random.uniform(0, 2*np.pi, 2*L+2) random parameters to check if training "does" something - result was: with random paremters just get noise, so yes, it "does" something if not i%verbose: print(f"{i+1} / {len(opt_params)}, gx = {p[0]:.2f}, gz = {p[1]:.2f}, time : {verbose*(datetime.datetime.now() - t0)}") "data/" + name + "_thetas-loss-cost_run2" np.savez("data/" + name + "_thetas-loss-cost_run2", cost_mitigated=cost_mitigated, thetas_mitigated=thetas_opt_mitigated, ) fig, ax = plt.subplots(ncols=1,figsize=(6,5)) ax.set_title("Mitigated results") cost = np.load("data/" + name + "_thetas-loss-cost_run2.npz", allow_pickle=True)["cost_mitigated"] ax.plot(gx_list, cost,".:", label="raw output") ax.plot(gx_list, abs(Qmags),"x--", color="tab:orange", label="Qmag") ax.set_xscale("log") for p in phys_params: ax.plot(gx_list[p],cost[p],"o",alpha=0.3,color="magenta")
https://github.com/Qiskit/feedback
Qiskit
import sys from io import BytesIO from qiskit import pulse, circuit, qpy my_pulse = pulse.Gaussian( circuit.Parameter("duration"), circuit.Parameter("amp"), circuit.Parameter("sigma"), ) with pulse.build(name="my_gate") as my_gate: pulse.shift_phase(1.57, pulse.DriveChannel(0)) pulse.play(my_pulse, pulse.DriveChannel(0)) file_like = BytesIO() qpy.dump(my_gate, file_like) file_like.seek(0) load_gate = qpy.load(file_like)[0] assert my_gate == load_gate print(sys.getsizeof(file_like.getvalue())) my_gate_op = circuit.Gate("my_gate", 1, my_gate.parameters) my_circ = circuit.QuantumCircuit(1) my_circ.append(my_gate_op, [0]) my_circ.measure_active() my_circ.add_calibration(my_gate_op, (0,), my_gate) file_like = BytesIO() qpy.dump(my_circ, file_like) file_like.seek(0) load_circ = qpy.load(file_like)[0] assert my_circ == load_circ print(sys.getsizeof(file_like.getvalue())) from qiskit.pulse.schedule import ScheduleBlock from qiskit.pulse.transforms import AlignLeft from qiskit.pulse.instructions import ShiftPhase, Play from qiskit.pulse.channels import DriveChannel context = AlignLeft() channel = DriveChannel(0) inst1 = ShiftPhase(1.57, channel) inst2 = Play(my_pulse, channel) sched_obj = ScheduleBlock(alignment_context=context) sched_obj.append(inst1) sched_obj.append(inst2) import numpy as np from qiskit.pulse.library.samplers.decorators import functional_pulse @functional_pulse def my_pulse(duration, amp, sigma): center = duration / 2 return amp * np.exp(-((np.arange(duration)-center) / sigma) ** 2 / 2) my_pulse(16, 0.1, 4) from qiskit.pulse.library.parametric_pulses import Gaussian as ParametricGaussian my_pulse_parametric = ParametricGaussian(16, 0.1, 4) my_pulse_parametric my_pulse_parametric_unassigned = ParametricGaussian(circuit.Parameter("duration"), 0.1, 4) my_pulse_parametric_unassigned from qiskit.pulse.library.discrete import gaussian gaussian(16, 0.1, 4) == my_pulse_parametric.get_waveform() from qiskit.pulse.library.symbolic_pulses import Gaussian as SymbolicGaussian my_pulse_symbolic = SymbolicGaussian(16, 0.1, 4) my_pulse_symbolic my_pulse_parametric.get_waveform() == my_pulse_symbolic.get_waveform() my_pulse_symbolic.envelope my_pulse_symbolic._envelope_lam from qiskit.pulse.library.symbolic_pulses import SymbolicPulse from sympy import symbols, tanh t, duration, sigma, amp = symbols("t duration sigma amp") expr = amp * (tanh(t/sigma) + tanh((duration-t)/sigma) - 1) constraints = duration > sigma expr, constraints my_tan_pulse = SymbolicPulse( pulse_type="Tangential", duration=160, parameters={"amp": 0.1, "sigma": 40}, envelope=expr, constraints=constraints, valid_amp_conditions=amp < 1, name="my_tan_pulse", ) my_tan_pulse.draw() %%timeit SymbolicGaussian(160, 0.1, 40).get_waveform() %%timeit ParametricGaussian(160, 0.1, 40).get_waveform()
https://github.com/mspronesti/qlearnkit
mspronesti
import logging from typing import Optional, Union import numpy as np from sklearn.base import ClassifierMixin from sklearn.exceptions import NotFittedError from qiskit.utils import QuantumInstance from qiskit.providers import Backend from qiskit.circuit.library import NLocal, ZZFeatureMap from ..quantum_estimator import QuantumEstimator from ..kernel_method_mixin import KernelMethodMixin logger = logging.getLogger(__name__) class QSVClassifier(KernelMethodMixin, ClassifierMixin, QuantumEstimator): r""" The Quantum Support Vector Machine algorithm for classification. Maps datapoints to quantum states using a FeatureMap or similar QuantumCircuit. Example: Classify data using the Iris dataset. .. jupyter-execute:: import numpy as np from qlearnkit.algorithms import QSVClassifier from qiskit import BasicAer from qiskit.utils import QuantumInstance, algorithm_globals from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from qiskit.circuit.library import ZZFeatureMap seed = 42 algorithm_globals.random_seed = seed quantum_instance = QuantumInstance(BasicAer.get_backend('statevector_simulator'), shots=1024, optimization_level=1, seed_simulator=seed, seed_transpiler=seed) # Use iris data set for training and test data X, y = load_iris(return_X_y=True) num_features = 2 X = np.asarray([x[0:num_features] for x, y_ in zip(X, y) if y_ != 2]) y = np.asarray([y_ for x, y_ in zip(X, y) if y_ != 2]) encoding_map = ZZFeatureMap(2) qsvc = QSVClassifier( encoding_map=encoding_map, quantum_instance=quantum_instance ) # use iris dataset X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=seed) qsvc.fit(X_train, y_train) print(f"Testing accuracy: " f"{qsvc.score(X_test, y_test):0.2f}") """ def __init__(self, encoding_map: Optional[NLocal] = None, quantum_instance: Optional[Union[QuantumInstance, Backend]] = None, gamma: Union[float, str] = 'scale'): """ Creates a Quantum Support Vector Classifier Args: encoding_map: map to classical data to quantum states. Default: :class:`~qiskit_machine_learning.circuit.library.ZZFeatureMap` quantum_instance: the quantum instance to set. Can be a :class:`~qiskit.utils.QuantumInstance` or a :class:`~qiskit.providers.Backend` gamma: regularization parameter (float or string, default 1.0) Admitted string values: { "scale", "auto" } """ if gamma == 0: raise ValueError( "The gamma value of 0.0 is invalid. Use 'auto' to set" " gamma to a value of 1 / n_features." ) encoding_map = encoding_map if encoding_map else ZZFeatureMap(2) super().__init__(encoding_map, quantum_instance) # Initial setting for _gamma # Numerical value is set in fit method self.gamma = gamma self.label_class_dict = None self.class_label_dict = None self.alpha = None self.bias = None self.n_classes = None def fit(self, X, y): """ Fits the model using X as training dataset and y as training labels. The actual computation is done at the "predict" stage to allow running the qiskit backend only once Args: X: training dataset y: training labels """ self.X_train = np.asarray(X) self.y_train = np.asarray(y) self.n_classes = np.unique(y).size n_features = self.X_train.shape[1] if isinstance(self.gamma, str): if self.gamma == "scale": self._gamma = 1.0 / (n_features * np.var(self.X_train)) elif self.gamma == "auto": self._gamma = 1.0 / n_features else: raise ValueError( "When 'gamma' is a string, it should be either 'scale' or " "'auto'. Got '{}' instead." % self.gamma ) else: self._gamma = self.gamma self.label_class_dict, self.class_label_dict = QSVClassifier._create_label_class_dicts(self.y_train) if self.n_classes == 1: raise ValueError("All samples have the same label") if self.n_classes == 2: classes_matrix = np.array(np.vectorize(self.label_class_dict.get)(self.y_train)) else: # Prepares an array of [+1,-1] values for each class # and organizes them in a matrix per the svm formulation. # This matrix notation will be useful later on to avoid nested for loops. classes_array = np.array([np.vectorize(self.label_class_dict.get)(self.y_train)]) classes_array = classes_array.T classes_matrix = np.equal(classes_array, np.arange(self.n_classes) * np.ones((classes_array.size, self.n_classes))) self.train_classes = classes_matrix * 2 - 1 logger.info("setting training data: ") for _X, _y in zip(X, y): logger.info("%s: %s", _X, _y) # Sets the training matrix to None to signal it must be # recomputed again in case train data changes self._reset_train_matrix() @staticmethod def _create_label_class_dicts(labels): """ Creates dictionaries to convert from labels to classes used by svm. Classes are the integer values in range [0, 1, ..., n_classes] Args: labels: labels for which the dictionaries will be created Returns: dictionaries to convert from the user labels to the internal representation and vice versa """ unique_labels = np.unique(labels) label_class_dict = { unique_labels[i]: i for i in range(unique_labels.size) } class_label_dict = { c: unique_labels[c] for c in range(unique_labels.size) } return label_class_dict, class_label_dict def _compute_alpha(self, train_kernel_matrix): """ Computes alpha parameters for data in the training set. Alpha parameters will be used as weights in prediction. Internally distinguishes between binary and multiclass case Args: train_kernel_matrix: matrix of distances from each point to each point in the training set Returns: numpy ndarray of alpha parameters """ n_train = train_kernel_matrix.shape[0] omega = train_kernel_matrix gamma_inv = 1 / self._gamma ones = np.ones(n_train) eye = np.eye(n_train) A = np.vstack([ np.block([np.zeros(1), ones.reshape([1, n_train])]), np.block([ones.reshape([n_train, 1]), omega + gamma_inv * eye]) ]) if self.n_classes == 2: B = np.vstack([np.zeros(1), self.train_classes.reshape(-1, 1)]) else: B = np.vstack([np.zeros(self.n_classes), self.train_classes]) # Binary case: X is a vector containing alpha values. # Multiclass case: X is a (n_train+1,n_classes) matrix # containing alpha values for each of the n_classes qridge systems. # This is equivalent to solving n_classes distinct binary problems. X = np.linalg.solve(A, B) bias = X[0, :] alpha = np.squeeze(X[1:, :]) return alpha, bias def _compute_predictions_multiclass(self, train_kernel_matrix, test_kernel_matrix): """ Uses kernel matrices to find n_classes dividing hyperplanes, following a one-to-rest approach. Based on Least Squares Support Vector Machine formulation. Actually solves n_classes qridge systems in order to separate multiple classes. Args: train_kernel_matrix: matrix of distances between training datapoints test_kernel_matrix: matrix of distances between training and test datapoints Returns: numpy ndarray of predicted classes. Uses the internal representation """ # Fit self.alpha, self.bias = self._compute_alpha(train_kernel_matrix) # Predict prediction_classes = np.argmax(test_kernel_matrix @ self.alpha + self.bias, axis=1) return prediction_classes def _compute_predictions_binary(self, train_kernel_matrix, test_kernel_matrix): """ Uses kernel matrices to find the dividing hyperplane. Based on Least Squares Support Vector Machine formulation. Specialized case which uses a np.sign call instead of computing multiple hyperplanes and using argmax Args: train_kernel_matrix: matrix of distances between training datapoints test_kernel_matrix: matrix of distances between training and test datapoints Returns: numpy ndarray of predicted classes. Uses the internal representation """ # Fit self.alpha, self.bias = self._compute_alpha(train_kernel_matrix) # Predict prediction_classes = np.sign(test_kernel_matrix @ self.alpha + self.bias) prediction_classes = (prediction_classes + 1) / 2 return prediction_classes def predict(self, X_test: np.ndarray) -> np.ndarray: """ Solves a Least Squares problem to predict value of input data. Internally distinguishes between binary and multiclass case. For the binary case solves an optimization problem to find a dividing hyperplane. For the multiclass case uses a one-to-rest approach and thus needs to run the algorithm n_classes different times. Args: X_test: the test data Returns: numpy ndarray of predicted labels """ if self.X_train is None: raise NotFittedError( "This QSVClassifier instance is not fitted yet. " "Call 'fit' with appropriate arguments before using " "this estimator.") logger.info("Computing kernel matrices...") train_kernel_matrix, test_kernel_matrix = self._compute_kernel_matrices(self.X_train, X_test) logger.info("Done.") logger.info("Computing predictions...") if self.n_classes == 2: classes_predict = self._compute_predictions_binary( train_kernel_matrix, test_kernel_matrix ) else: classes_predict = self._compute_predictions_multiclass(train_kernel_matrix, test_kernel_matrix) # Converts back from internal numerical classes used in SVM # to user provided labels. y_predict = np.vectorize(self.class_label_dict.get)(classes_predict) logger.info("Done.") return y_predict
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# External imports from pylab import cm from sklearn import metrics import numpy as np import matplotlib.pyplot as plt # Qiskit imports from qiskit import QuantumCircuit from qiskit.circuit import ParameterVector from qiskit.visualization import circuit_drawer from qiskit.algorithms.optimizers import SPSA from qiskit.circuit.library import ZZFeatureMap from qiskit_machine_learning.kernels import TrainableFidelityQuantumKernel from qiskit_machine_learning.kernels.algorithms import QuantumKernelTrainer from qiskit_machine_learning.algorithms import QSVC from qiskit_machine_learning.datasets import ad_hoc_data class QKTCallback: """Callback wrapper class.""" def __init__(self) -> None: self._data = [[] for i in range(5)] def callback(self, x0, x1=None, x2=None, x3=None, x4=None): """ Args: x0: number of function evaluations x1: the parameters x2: the function value x3: the stepsize x4: whether the step was accepted """ self._data[0].append(x0) self._data[1].append(x1) self._data[2].append(x2) self._data[3].append(x3) self._data[4].append(x4) def get_callback_data(self): return self._data def clear_callback_data(self): self._data = [[] for i in range(5)] adhoc_dimension = 2 X_train, y_train, X_test, y_test, adhoc_total = ad_hoc_data( training_size=20, test_size=5, n=adhoc_dimension, gap=0.3, plot_data=False, one_hot=False, include_sample_total=True, ) plt.figure(figsize=(5, 5)) plt.ylim(0, 2 * np.pi) plt.xlim(0, 2 * np.pi) plt.imshow( np.asmatrix(adhoc_total).T, interpolation="nearest", origin="lower", cmap="RdBu", extent=[0, 2 * np.pi, 0, 2 * np.pi], ) plt.scatter( X_train[np.where(y_train[:] == 0), 0], X_train[np.where(y_train[:] == 0), 1], marker="s", facecolors="w", edgecolors="b", label="A train", ) plt.scatter( X_train[np.where(y_train[:] == 1), 0], X_train[np.where(y_train[:] == 1), 1], marker="o", facecolors="w", edgecolors="r", label="B train", ) plt.scatter( X_test[np.where(y_test[:] == 0), 0], X_test[np.where(y_test[:] == 0), 1], marker="s", facecolors="b", edgecolors="w", label="A test", ) plt.scatter( X_test[np.where(y_test[:] == 1), 0], X_test[np.where(y_test[:] == 1), 1], marker="o", facecolors="r", edgecolors="w", label="B test", ) plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0) plt.title("Ad hoc dataset for classification") plt.show() # Create a rotational layer to train. We will rotate each qubit the same amount. training_params = ParameterVector("θ", 1) fm0 = QuantumCircuit(2) fm0.ry(training_params[0], 0) fm0.ry(training_params[0], 1) # Use ZZFeatureMap to represent input data fm1 = ZZFeatureMap(2) # Create the feature map, composed of our two circuits fm = fm0.compose(fm1) print(circuit_drawer(fm)) print(f"Trainable parameters: {training_params}") # Instantiate quantum kernel quant_kernel = TrainableFidelityQuantumKernel(feature_map=fm, training_parameters=training_params) # Set up the optimizer cb_qkt = QKTCallback() spsa_opt = SPSA(maxiter=10, callback=cb_qkt.callback, learning_rate=0.05, perturbation=0.05) # Instantiate a quantum kernel trainer. qkt = QuantumKernelTrainer( quantum_kernel=quant_kernel, loss="svc_loss", optimizer=spsa_opt, initial_point=[np.pi / 2] ) # Train the kernel using QKT directly qka_results = qkt.fit(X_train, y_train) optimized_kernel = qka_results.quantum_kernel print(qka_results) # Use QSVC for classification qsvc = QSVC(quantum_kernel=optimized_kernel) # Fit the QSVC qsvc.fit(X_train, y_train) # Predict the labels labels_test = qsvc.predict(X_test) # Evalaute the test accuracy accuracy_test = metrics.balanced_accuracy_score(y_true=y_test, y_pred=labels_test) print(f"accuracy test: {accuracy_test}") plot_data = cb_qkt.get_callback_data() # callback data K = optimized_kernel.evaluate(X_train) # kernel matrix evaluated on the training samples plt.rcParams["font.size"] = 20 fig, ax = plt.subplots(1, 2, figsize=(14, 5)) ax[0].plot([i + 1 for i in range(len(plot_data[0]))], np.array(plot_data[2]), c="k", marker="o") ax[0].set_xlabel("Iterations") ax[0].set_ylabel("Loss") ax[1].imshow(K, cmap=cm.get_cmap("bwr", 20)) fig.tight_layout() plt.show() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
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. """The two-local gate circuit.""" from __future__ import annotations import typing from collections.abc import Callable, Sequence from qiskit.circuit.quantumcircuit import QuantumCircuit from qiskit.circuit import Gate, Instruction, Parameter from .n_local import NLocal from ..standard_gates import ( IGate, XGate, YGate, ZGate, RXGate, RYGate, RZGate, HGate, SGate, SdgGate, TGate, TdgGate, RXXGate, RYYGate, RZXGate, RZZGate, SwapGate, CXGate, CYGate, CZGate, CRXGate, CRYGate, CRZGate, CHGate, ) if typing.TYPE_CHECKING: import qiskit # pylint: disable=cyclic-import class TwoLocal(NLocal): r"""The two-local circuit. The two-local circuit is a parameterized circuit consisting of alternating rotation layers and entanglement layers. The rotation layers are single qubit gates applied on all qubits. The entanglement layer uses two-qubit gates to entangle the qubits according to a strategy set using ``entanglement``. Both the rotation and entanglement gates can be specified as string (e.g. ``'ry'`` or ``'cx'``), as gate-type (e.g. ``RYGate`` or ``CXGate``) or as QuantumCircuit (e.g. a 1-qubit circuit or 2-qubit circuit). A set of default entanglement strategies is provided: * ``'full'`` entanglement is each qubit is entangled with all the others. * ``'linear'`` entanglement is qubit :math:`i` entangled with qubit :math:`i + 1`, for all :math:`i \in \{0, 1, ... , n - 2\}`, where :math:`n` is the total number of qubits. * ``'reverse_linear'`` entanglement is qubit :math:`i` entangled with qubit :math:`i + 1`, for all :math:`i \in \{n-2, n-3, ... , 1, 0\}`, where :math:`n` is the total number of qubits. Note that if ``entanglement_blocks = 'cx'`` then this option provides the same unitary as ``'full'`` with fewer entangling gates. * ``'pairwise'`` entanglement is one layer where qubit :math:`i` is entangled with qubit :math:`i + 1`, for all even values of :math:`i`, and then a second layer where qubit :math:`i` is entangled with qubit :math:`i + 1`, for all odd values of :math:`i`. * ``'circular'`` entanglement is linear entanglement but with an additional entanglement of the first and last qubit before the linear part. * ``'sca'`` (shifted-circular-alternating) entanglement is a generalized and modified version of the proposed circuit 14 in `Sim et al. <https://arxiv.org/abs/1905.10876>`__. It consists of circular entanglement where the 'long' entanglement connecting the first with the last qubit is shifted by one each block. Furthermore the role of control and target qubits are swapped every block (therefore alternating). The entanglement can further be specified using an entangler map, which is a list of index pairs, such as >>> entangler_map = [(0, 1), (1, 2), (2, 0)] If different entanglements per block should be used, provide a list of entangler maps. See the examples below on how this can be used. >>> entanglement = [entangler_map_layer_1, entangler_map_layer_2, ... ] Barriers can be inserted in between the different layers for better visualization using the ``insert_barriers`` attribute. For each parameterized gate a new parameter is generated using a :class:`~qiskit.circuit.library.ParameterVector`. The name of these parameters can be chosen using the ``parameter_prefix``. Examples: >>> two = TwoLocal(3, 'ry', 'cx', 'linear', reps=2, insert_barriers=True) >>> print(two) # decompose the layers into standard gates ┌──────────┐ ░ ░ ┌──────────┐ ░ ░ ┌──────────┐ q_0: ┤ Ry(θ[0]) ├─░───■────────░─┤ Ry(θ[3]) ├─░───■────────░─┤ Ry(θ[6]) ├ ├──────────┤ ░ ┌─┴─┐ ░ ├──────────┤ ░ ┌─┴─┐ ░ ├──────────┤ q_1: ┤ Ry(θ[1]) ├─░─┤ X ├──■───░─┤ Ry(θ[4]) ├─░─┤ X ├──■───░─┤ Ry(θ[7]) ├ ├──────────┤ ░ └───┘┌─┴─┐ ░ ├──────────┤ ░ └───┘┌─┴─┐ ░ ├──────────┤ q_2: ┤ Ry(θ[2]) ├─░──────┤ X ├─░─┤ Ry(θ[5]) ├─░──────┤ X ├─░─┤ Ry(θ[8]) ├ └──────────┘ ░ └───┘ ░ └──────────┘ ░ └───┘ ░ └──────────┘ >>> two = TwoLocal(3, ['ry','rz'], 'cz', 'full', reps=1, insert_barriers=True) >>> qc = QuantumCircuit(3) >>> qc += two >>> print(qc.decompose().draw()) ┌──────────┐┌──────────┐ ░ ░ ┌──────────┐ ┌──────────┐ q_0: ┤ Ry(θ[0]) ├┤ Rz(θ[3]) ├─░──■──■─────░─┤ Ry(θ[6]) ├─┤ Rz(θ[9]) ├ ├──────────┤├──────────┤ ░ │ │ ░ ├──────────┤┌┴──────────┤ q_1: ┤ Ry(θ[1]) ├┤ Rz(θ[4]) ├─░──■──┼──■──░─┤ Ry(θ[7]) ├┤ Rz(θ[10]) ├ ├──────────┤├──────────┤ ░ │ │ ░ ├──────────┤├───────────┤ q_2: ┤ Ry(θ[2]) ├┤ Rz(θ[5]) ├─░─────■──■──░─┤ Ry(θ[8]) ├┤ Rz(θ[11]) ├ └──────────┘└──────────┘ ░ ░ └──────────┘└───────────┘ >>> entangler_map = [[0, 1], [1, 2], [2, 0]] # circular entanglement for 3 qubits >>> two = TwoLocal(3, 'x', 'crx', entangler_map, reps=1) >>> print(two) # note: no barriers inserted this time! ┌───┐ ┌──────────┐┌───┐ q_0: |0>┤ X ├─────■───────────────────────┤ Rx(θ[2]) ├┤ X ├ ├───┤┌────┴─────┐ ┌───┐└─────┬────┘└───┘ q_1: |0>┤ X ├┤ Rx(θ[0]) ├─────■──────┤ X ├──────┼────────── ├───┤└──────────┘┌────┴─────┐└───┘ │ ┌───┐ q_2: |0>┤ X ├────────────┤ Rx(θ[1]) ├───────────■─────┤ X ├ └───┘ └──────────┘ └───┘ >>> entangler_map = [[0, 3], [0, 2]] # entangle the first and last two-way >>> two = TwoLocal(4, [], 'cry', entangler_map, reps=1) >>> circuit = two + two >>> print(circuit.decompose().draw()) # note, that the parameters are the same! q_0: ─────■───────────■───────────■───────────■────── │ │ │ │ q_1: ─────┼───────────┼───────────┼───────────┼────── │ ┌────┴─────┐ │ ┌────┴─────┐ q_2: ─────┼──────┤ Ry(θ[1]) ├─────┼──────┤ Ry(θ[1]) ├ ┌────┴─────┐└──────────┘┌────┴─────┐└──────────┘ q_3: ┤ Ry(θ[0]) ├────────────┤ Ry(θ[0]) ├──────────── └──────────┘ └──────────┘ >>> layer_1 = [(0, 1), (0, 2)] >>> layer_2 = [(1, 2)] >>> two = TwoLocal(3, 'x', 'cx', [layer_1, layer_2], reps=2, insert_barriers=True) >>> print(two) ┌───┐ ░ ░ ┌───┐ ░ ░ ┌───┐ q_0: ┤ X ├─░───■────■───░─┤ X ├─░───────░─┤ X ├ ├───┤ ░ ┌─┴─┐ │ ░ ├───┤ ░ ░ ├───┤ q_1: ┤ X ├─░─┤ X ├──┼───░─┤ X ├─░───■───░─┤ X ├ ├───┤ ░ └───┘┌─┴─┐ ░ ├───┤ ░ ┌─┴─┐ ░ ├───┤ q_2: ┤ X ├─░──────┤ X ├─░─┤ X ├─░─┤ X ├─░─┤ X ├ └───┘ ░ └───┘ ░ └───┘ ░ └───┘ ░ └───┘ """ def __init__( self, num_qubits: int | None = None, rotation_blocks: str | type | qiskit.circuit.Instruction | QuantumCircuit | list[str | type | qiskit.circuit.Instruction | QuantumCircuit] | None = None, entanglement_blocks: str | type | qiskit.circuit.Instruction | QuantumCircuit | list[str | type | qiskit.circuit.Instruction | QuantumCircuit] | None = None, entanglement: str | list[list[int]] | Callable[[int], list[int]] = "full", reps: int = 3, skip_unentangled_qubits: bool = False, skip_final_rotation_layer: bool = False, parameter_prefix: str = "θ", insert_barriers: bool = False, initial_state: QuantumCircuit | None = None, name: str = "TwoLocal", flatten: bool | None = None, ) -> None: """ Args: num_qubits: The number of qubits of the two-local circuit. rotation_blocks: The gates used in the rotation layer. Can be specified via the name of a gate (e.g. ``'ry'``) or the gate type itself (e.g. :class:`.RYGate`). If only one gate is provided, the gate same gate is applied to each qubit. If a list of gates is provided, all gates are applied to each qubit in the provided order. See the Examples section for more detail. entanglement_blocks: The gates used in the entanglement layer. Can be specified in the same format as ``rotation_blocks``. entanglement: Specifies the entanglement structure. Can be a string (``'full'``, ``'linear'``, ``'reverse_linear'``, ``'circular'`` or ``'sca'``), a list of integer-pairs specifying the indices of qubits entangled with one another, or a callable returning such a list provided with the index of the entanglement layer. Default to ``'full'`` entanglement. Note that if ``entanglement_blocks = 'cx'``, then ``'full'`` entanglement provides the same unitary as ``'reverse_linear'`` but the latter option has fewer entangling gates. See the Examples section for more detail. reps: Specifies how often a block consisting of a rotation layer and entanglement layer is repeated. skip_unentangled_qubits: If ``True``, the single qubit gates are only applied to qubits that are entangled with another qubit. If ``False``, the single qubit gates are applied to each qubit in the ansatz. Defaults to ``False``. skip_final_rotation_layer: If ``False``, a rotation layer is added at the end of the ansatz. If ``True``, no rotation layer is added. parameter_prefix: The parameterized gates require a parameter to be defined, for which we use instances of :class:`~qiskit.circuit.Parameter`. The name of each parameter will be this specified prefix plus its index. insert_barriers: If ``True``, barriers are inserted in between each layer. If ``False``, no barriers are inserted. Defaults to ``False``. initial_state: A :class:`.QuantumCircuit` object to prepend to the circuit. flatten: Set this to ``True`` to output a flat circuit instead of nesting it inside multiple layers of gate objects. By default currently the contents of the output circuit will be wrapped in nested objects for cleaner visualization. However, if you're using this circuit for anything besides visualization its **strongly** recommended to set this flag to ``True`` to avoid a large performance overhead for parameter binding. """ super().__init__( num_qubits=num_qubits, rotation_blocks=rotation_blocks, entanglement_blocks=entanglement_blocks, entanglement=entanglement, reps=reps, skip_final_rotation_layer=skip_final_rotation_layer, skip_unentangled_qubits=skip_unentangled_qubits, insert_barriers=insert_barriers, initial_state=initial_state, parameter_prefix=parameter_prefix, name=name, flatten=flatten, ) def _convert_to_block(self, layer: str | type | Gate | QuantumCircuit) -> QuantumCircuit: """For a layer provided as str (e.g. ``'ry'``) or type (e.g. :class:`.RYGate`) this function returns the according layer type along with the number of parameters (e.g. ``(RYGate, 1)``). Args: layer: The qubit layer. Returns: The specified layer with the required number of parameters. Raises: TypeError: The type of ``layer`` is invalid. ValueError: The type of ``layer`` is str but the name is unknown. ValueError: The type of ``layer`` is type but the layer type is unknown. Note: Outlook: If layers knew their number of parameters as static property, we could also allow custom layer types. """ if isinstance(layer, QuantumCircuit): return layer # check the list of valid layers # this could be a lot easier if the standard layers would have ``name`` and ``num_params`` # as static types, which might be something they should have anyway theta = Parameter("θ") valid_layers = { "ch": CHGate(), "cx": CXGate(), "cy": CYGate(), "cz": CZGate(), "crx": CRXGate(theta), "cry": CRYGate(theta), "crz": CRZGate(theta), "h": HGate(), "i": IGate(), "id": IGate(), "iden": IGate(), "rx": RXGate(theta), "rxx": RXXGate(theta), "ry": RYGate(theta), "ryy": RYYGate(theta), "rz": RZGate(theta), "rzx": RZXGate(theta), "rzz": RZZGate(theta), "s": SGate(), "sdg": SdgGate(), "swap": SwapGate(), "x": XGate(), "y": YGate(), "z": ZGate(), "t": TGate(), "tdg": TdgGate(), } # try to exchange `layer` from a string to a gate instance if isinstance(layer, str): try: layer = valid_layers[layer] except KeyError as ex: raise ValueError(f"Unknown layer name `{layer}`.") from ex # try to exchange `layer` from a type to a gate instance if isinstance(layer, type): # iterate over the layer types and look for the specified layer instance = None for gate in valid_layers.values(): if isinstance(gate, layer): instance = gate if instance is None: raise ValueError(f"Unknown layer type`{layer}`.") layer = instance if isinstance(layer, Instruction): circuit = QuantumCircuit(layer.num_qubits) circuit.append(layer, list(range(layer.num_qubits))) return circuit raise TypeError( f"Invalid input type {type(layer)}. " + "`layer` must be a type, str or QuantumCircuit." ) def get_entangler_map( self, rep_num: int, block_num: int, num_block_qubits: int ) -> Sequence[Sequence[int]]: """Overloading to handle the special case of 1 qubit where the entanglement are ignored.""" if self.num_qubits <= 1: return [] return super().get_entangler_map(rep_num, block_num, num_block_qubits)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# You can choose different colors for the real and imaginary parts of the density matrix. 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) state = DensityMatrix(qc) plot_state_city(state, color=['midnightblue', 'crimson'], title="New State City")
https://github.com/soultanis/Quantum-Database-Search
soultanis
# Import the Qiskit SDK from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import available_backends, execute, Aer from qiskit.tools.visualization import plot_histogram, circuit_drawer, plot_state # Create a Quantum Register with 2 qubits. q = QuantumRegister(2) # Create a Classical Register with 2 bits. c = ClassicalRegister(2) # Create a Quantum Circuit qc = QuantumCircuit(q, c) # Add a H gate on qubit 0, putting this qubit in superposition. qc.h(q[0]) # Add a CX (CNOT) gate on control qubit 0 and target qubit 1, putting # the qubits in a Bell state. qc.cx(q[0], q[1]) # Add a Measure gate to see the state. qc.measure(q, c) # See a list of available local simulators print("Aer backends: ", Aer.backends()) backend_sim = Aer.get_backend('qasm_simulator') # Compile and run the Quantum circuit on a simulator backend sim_result1 = execute(qc, backend_sim, shots=2).result() sim_result2 = execute(qc, backend_sim, shots=1000).result() counts1 = sim_result1.get_counts(qc) counts2 = sim_result2.get_counts(qc) # Show the results as text and plot print("First simulation: ", sim_result1) print("Output: ", counts1) print("Second simulation: ", sim_result2) print("Output: ", counts2) legend = ['First execution', 'Second execution'] plot_histogram([counts1,counts2], legend=legend) circuit_drawer(qc) # Import the Qiskit from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, QISKitError from qiskit import execute, IBMQ, Aer from qiskit.backends.ibmq import least_busy from qiskit.tools.visualization import plot_histogram, circuit_drawer, plot_state # Authenticate for access to remote backends try: import Qconfig 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 Register with 2 qubits. q = QuantumRegister(2) # Create a Classical Register with 2 bits. c = ClassicalRegister(2) # Create a Quantum Circuit qc = QuantumCircuit(q, c) # Add a H gate on qubit 0, putting this qubit in superposition. qc.h(q[0]) # Add a CX (CNOT) gate on control qubit 0 and target qubit 1, putting # the qubits in a Bell state. qc.cx(q[0], q[1]) # Add a Measure gate to see the state. qc.measure(q, c) # see a list of available remote backends ibmq_backends = IBMQ.backends() print("Remote backends: ", ibmq_backends) # Compile and run the Quantum Program on a real device backend try: least_busy_device = least_busy(IBMQ.backends(simulator=False)) print("Running on current least busy device: ", least_busy_device) #running the job twice and get counts result_exp1 = execute(qc, least_busy_device, shots=1024, max_credits=10).result() result_exp2 = execute(qc, least_busy_device, shots=1024, max_credits=10).result() counts01 = result_exp1.get_counts(qc) counts02 = result_exp2.get_counts(qc) # Show the results print("First experiment: ", result_exp1) print("Output: ", counts01) print("Second experiment: ", result_exp2) print("Output: ", counts02) legend = ['First experiment', 'Second experiment'] plot_histogram([counts01,counts02], legend=legend) except: print("All devices are currently unavailable. Try again later.") except QISKitError as ex: print('There was an error in the circuit!. Error = {}'.format(ex)) # Import the Qiskit SDK. from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import available_backends, execute, Aer from qiskit.tools.visualization import plot_histogram, circuit_drawer, plot_state # Define the number of n-qbits. n = 2 # Create a Quantum Register with n-qbits. q = QuantumRegister(n) # Create a Classical Register with n-bits. c = ClassicalRegister(n) # Create a Quantum Circuit qc = QuantumCircuit(q, c) # Add H-gate to get superposition. qc.h(q[0]) qc.h(q[1]) # Apply the oracle 11. qc.x(q[0]) qc.h(q[1]) qc.cx(q[0],q[1]) qc.x(q[0]) qc.h(q[1]) for x in range(0, 1): # Apply the grover-algorithm 11 qc.h(q[0]) qc.h(q[1]) qc.x(q[0]) qc.x(q[1]) qc.h(q[1]) qc.cx(q[0],q[1]) qc.h(q[1]) qc.x(q[0]) qc.x(q[1]) qc.h(q[0]) qc.h(q[1]) # Measure qubit to bit. . qc.measure(q, c) # Get Aer backend. backend_sim = Aer.get_backend('qasm_simulator') # Compile and run the Quantum circuit on a simulator backend. sim_result1 = execute(qc, backend_sim, shots=1000).result() counts1 = sim_result1.get_counts(qc) # Show the results as text and plot. print("Simulation: ", sim_result1) print("Output: ", counts1) plot_histogram(counts1) circuit_drawer(qc) from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import available_backends, execute, Aer, backends from qiskit.tools.visualization import plot_histogram, circuit_drawer, plot_state import math # Authenticate for access to remote backends try: import Qconfig 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...""") # decide, on which backend you want to run the grover algorithmus backendIBMQ = True # define the number n-Qbits n = 4 N = 2^n O = math.sqrt(N) pi = math.pi try: # Create a Quantum-Register with n-Qbits. qr = QuantumRegister(n) cr = ClassicalRegister(n) qc = QuantumCircuit(qr, cr) # initialize n-Qbits qc.h(qr[0]) qc.h(qr[1]) qc.h(qr[2]) qc.h(qr[3]) # Create oracle for 0010 qc.x(qr[0]) qc.x(qr[2]) qc.x(qr[3]) qc.cu1(pi/4, qr[0], qr[3]) qc.cx(qr[0], qr[1]) qc.cu1(-pi/4, qr[1], qr[3]) qc.cx(qr[0], qr[1]) qc.cu1(pi/4, qr[1], qr[3]) qc.cx(qr[1], qr[2]) qc.cu1(-pi/4, qr[2], qr[3]) qc.cx(qr[0], qr[2]) qc.cu1(pi/4, qr[2], qr[3]) qc.cx(qr[1], qr[2]) qc.cu1(-pi/4, qr[2], qr[3]) qc.cx(qr[0], qr[2]) qc.cu1(pi/4, qr[2], qr[3]) qc.x(qr[0]) qc.x(qr[2]) qc.x(qr[3]) # avarage of O(sqrt(N)) repititions for x in range(0, 1): # Amplification qc.h(qr[0]) qc.h(qr[1]) qc.h(qr[2]) qc.h(qr[3]) qc.x(qr[0]) qc.x(qr[1]) qc.x(qr[2]) qc.x(qr[3]) ######## cccZ ######### qc.cu1(pi/4, qr[0], qr[3]) qc.cx(qr[0], qr[1]) qc.cu1(-pi/4, qr[1], qr[3]) qc.cx(qr[0], qr[1]) qc.cu1(pi/4, qr[1], qr[3]) qc.cx(qr[1], qr[2]) qc.cu1(-pi/4, qr[2], qr[3]) qc.cx(qr[0], qr[2]) qc.cu1(pi/4, qr[2], qr[3]) qc.cx(qr[1], qr[2]) qc.cu1(-pi/4, qr[2], qr[3]) qc.cx(qr[0], qr[2]) qc.cu1(pi/4, qr[2], qr[3]) ####### end cccZ ####### qc.x(qr[0]) qc.x(qr[1]) qc.x(qr[2]) qc.x(qr[3]) qc.h(qr[0]) qc.h(qr[1]) qc.h(qr[2]) qc.h(qr[3]) # Measure: take state from Qbit to Cbit qc.barrier(qr) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) qc.measure(qr[2], cr[2]) qc.measure(qr[3], cr[3]) except QISKitError as ex: print('There was an error in the circuit!. Error = {}'.format(ex)) # run the code on a real quantumcomputer from IBM if backendIBMQ: try: # See a list of available local simulators least_busy_device = least_busy(IBMQ.backends(simulator=False)) # IBMQ.get_backend('ibmq_16_melbourne') print("Running on current least busy device: ", least_busy_device) #running the job twice and get counts result_exp1 = execute(qc, least_busy_device, shots = 500, max_credits = 10).result() result_exp2 = execute(qc, least_busy_device, shots = 500, max_credits = 10).result() counts01 = result_exp1.get_counts(qc) counts02 = result_exp2.get_counts(qc) # Show the results print("First experiment: ", result_exp1) print("Output: ", counts01) print("Second experiment: ", result_exp2) print("Output: ", counts02) legend = ['First experiment', 'Second experiment'] plot_histogram([counts01, counts02], legend=legend) circuit_drawer(qc) except: print("All devices are currently unavailable. Try again later.") # or run the code on your own system with the simulation backend Aer else: # See a list of available local simulators print("Aer backends: ", Aer.backends()) backend_sim = Aer.get_backend('qasm_simulator') # Compile and run the Quantum circuit on a simulator backend sim_result1 = execute(qc, backend_sim, shots=1000).result() sim_result2 = execute(qc, backend_sim, shots=1000).result() counts1 = sim_result1.get_counts(qc) counts2 = sim_result2.get_counts(qc) # Show the results as text and plot print("First simulation: ", sim_result1) print("Output: ", counts1) print("Second simulation: ", sim_result2) print("Output: ", counts2) legend = ['First execution', 'Second execution'] plot_histogram([counts1,counts2], legend=legend) circuit_drawer(qc)
https://github.com/AnikenC/JaxifiedQiskit
AnikenC
# -*- 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. """Utils for using with Qiskit unit tests.""" import logging import os import unittest from enum import Enum from qiskit import __path__ as qiskit_path class Path(Enum): """Helper with paths commonly used during the tests.""" # Main SDK path: qiskit/ SDK = qiskit_path[0] # test.python path: qiskit/test/python/ TEST = os.path.normpath(os.path.join(SDK, '..', 'test', 'python')) # Examples path: examples/ EXAMPLES = os.path.normpath(os.path.join(SDK, '..', 'examples')) # Schemas path: qiskit/schemas SCHEMAS = os.path.normpath(os.path.join(SDK, 'schemas')) # VCR cassettes path: qiskit/test/cassettes/ CASSETTES = os.path.normpath(os.path.join(TEST, '..', 'cassettes')) # Sample QASMs path: qiskit/test/python/qasm QASMS = os.path.normpath(os.path.join(TEST, 'qasm')) def setup_test_logging(logger, log_level, filename): """Set logging to file and stdout for a logger. Args: logger (Logger): logger object to be updated. log_level (str): logging level. filename (str): name of the output file. """ # Set up formatter. log_fmt = ('{}.%(funcName)s:%(levelname)s:%(asctime)s:' ' %(message)s'.format(logger.name)) formatter = logging.Formatter(log_fmt) # Set up the file handler. file_handler = logging.FileHandler(filename) file_handler.setFormatter(formatter) logger.addHandler(file_handler) # Set the logging level from the environment variable, defaulting # to INFO if it is not a valid level. level = logging._nameToLevel.get(log_level, logging.INFO) logger.setLevel(level) class _AssertNoLogsContext(unittest.case._AssertLogsContext): """A context manager used to implement TestCase.assertNoLogs().""" # pylint: disable=inconsistent-return-statements def __exit__(self, exc_type, exc_value, tb): """ This is a modified version of TestCase._AssertLogsContext.__exit__(...) """ self.logger.handlers = self.old_handlers self.logger.propagate = self.old_propagate self.logger.setLevel(self.old_level) if exc_type is not None: # let unexpected exceptions pass through return False if self.watcher.records: msg = 'logs of level {} or higher triggered on {}:\n'.format( logging.getLevelName(self.level), self.logger.name) for record in self.watcher.records: msg += 'logger %s %s:%i: %s\n' % (record.name, record.pathname, record.lineno, record.getMessage()) self._raiseFailure(msg)
https://github.com/bagmk/Quantum_Machine_Learning_Express
bagmk
from matplotlib import pyplot from qiskit import * from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import IBMQ, Aer, execute,assemble,QuantumCircuit, aqua from qiskit.visualization import plot_histogram, plot_bloch_vector, plot_bloch_multivector from qiskit.quantum_info import Statevector from qiskit.extensions import * provider = IBMQ.load_account() from qiskit.quantum_info import random_unitary from qiskit.providers.aer import QasmSimulator, StatevectorSimulator, UnitarySimulator import matplotlib.pyplot as plt %matplotlib inline import numpy as np import math from math import pi, sqrt from scipy.special import rel_entr from random import seed from random import random import cmath #Possible Bin bins_list=[]; for i in range(76): bins_list.append((i)/75) #Center of the Bean bins_x=[] for i in range(75): bins_x.append(bins_list[1]+bins_list[i]) def P_harr(l,u,N): return (1-l)**(N-1)-(1-u)**(N-1) #Harr historgram P_harr_hist=[] for i in range(75): P_harr_hist.append(P_harr(bins_list[i],bins_list[i+1],2)) #Imaginary j=(-1)**(1/2) backend = Aer.get_backend('qasm_simulator') for x in range(1,20,1): print() arr = [] for nsh in range(1,20,1): arr.append([]) for lp in range(1,10,1): nshot=int(round(1000*(nsh)**1.5,0)) nparam=1000*lp fidelity=[] for x in range(nparam): qr = QuantumRegister(1) cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr) u13=UnitaryGate(random_unitary(2)) qc.append(u13, [qr[0]] ) u13=UnitaryGate(random_unitary(2)) qc.append(u13, [qr[0]] ) qc.measure(qr[0],cr[0]) job = execute(qc, backend, shots=nshot) result = job.result() count =result.get_counts() if '0' in count and '1' in count: ratio=count['0']/nshot elif '0' in count and '1' not in count: ratio=count['0']/nshot else: ratio=0 fidelity.append(ratio) #Kullback Leibler divergence weights = np.ones_like(fidelity)/float(len(fidelity)) P_U_hist=np.histogram(fidelity, bins=bins_list, weights=weights, range=[0, 1])[0]; #Kullback Leibler divergence print(nshot,'shots per simulation',nparam,'distribution size') arr[nsh-1].append(sum(rel_entr(P_U_hist, P_harr_hist))) import sys import numpy qasm=arr numpy.set_printoptions(threshold=sys.maxsize) np.savetxt("KLDivg_qasm.txt",qasm,fmt='%.2f') backend = Aer.get_backend('statevector_simulator') for x in range(1,20,1): print() arr = [] for nsh in range(1,20,1): arr.append([]) for lp in range(1,10,1): nshot=int(round(1000*(nsh)**1.5,0)) nparam=1000*lp fidelity=[] for x in range(nparam): qr = QuantumRegister(1) cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr) u13=UnitaryGate(random_unitary(2)) qc.append(u13, [qr[0]] ) u13=UnitaryGate(random_unitary(2)) qc.append(u13, [qr[0]] ) qc.measure(qr[0],cr[0]) job = execute(qc, backend, shots=nshot) result = job.result() count =result.get_counts() if '0' in count and '1' in count: ratio=count['0']/nshot elif '0' in count and '1' not in count: ratio=count['0']/nshot else: ratio=0 fidelity.append(ratio) #Kullback Leibler divergence weights = np.ones_like(fidelity)/float(len(fidelity)) P_U_hist=np.histogram(fidelity, bins=bins_list, weights=weights, range=[0, 1])[0]; #Kullback Leibler divergence print(nshot,'shots per simulation',nparam,'distribution size') arr[nsh-1].append(sum(rel_entr(P_U_hist, P_harr_hist))) import sys import numpy statevector=arr numpy.set_printoptions(threshold=sys.maxsize) np.savetxt("KLDivg_statevector.txt",statevector,fmt='%.2f') ##Plot import pandas as pd import matplotlib.pyplot as plt #loading dataset x = [i+1 for i in range(19)] y = [i[0] for i in arr] plt.plot(x, y, 'o', color='red', label='L=1'); x = [i+1 for i in range(19)] y = [i[1] for i in arr] plt.plot(x, y, 'o', color='blue', label='L=2'); x = [i+1 for i in range(19)] y = [i[2] for i in arr] plt.plot(x, y, 'o', color='black', label='L=3'); x = [i+1 for i in range(19)] y = [i[3] for i in arr] plt.plot(x, y, 'o', color='green', label='L=4'); x = [i+1 for i in range(19)] y = [i[3] for i in arr] plt.plot(x, y, 'o', color='purple', label='L=5'); plt.legend(loc='upper right') plt.yscale('log',base=10) plt.xlabel('Circuit ID') plt.ylabel('Expressibility') # Create names on the x axis plt.xticks([i+1 for i in range(19)]) plt.show()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=invalid-name """Tests for error mitigation routines.""" import unittest from collections import Counter import numpy as np from qiskit import QiskitError, QuantumCircuit from qiskit.quantum_info import Statevector from qiskit.quantum_info.operators.predicates import matrix_equal from qiskit.result import ( CorrelatedReadoutMitigator, Counts, LocalReadoutMitigator, ) from qiskit.result.mitigation.utils import ( counts_probability_vector, expval_with_stddev, stddev, str2diag, ) from qiskit.result.utils import marginal_counts from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider import FakeYorktown class TestReadoutMitigation(QiskitTestCase): """Tests for correlated and local readout mitigation.""" @classmethod def setUpClass(cls): super().setUpClass() cls.rng = np.random.default_rng(42) @staticmethod def compare_results(res1, res2): """Compare the results between two runs""" res1_total_shots = sum(res1.values()) res2_total_shots = sum(res2.values()) keys = set(res1.keys()).union(set(res2.keys())) total = 0 for key in keys: val1 = res1.get(key, 0) / res1_total_shots val2 = res2.get(key, 0) / res2_total_shots total += abs(val1 - val2) ** 2 return total @staticmethod def mitigators(assignment_matrices, qubits=None): """Generates the mitigators to test for given assignment matrices""" full_assignment_matrix = assignment_matrices[0] for m in assignment_matrices[1:]: full_assignment_matrix = np.kron(full_assignment_matrix, m) CRM = CorrelatedReadoutMitigator(full_assignment_matrix, qubits) LRM = LocalReadoutMitigator(assignment_matrices, qubits) mitigators = [CRM, LRM] return mitigators @staticmethod def simulate_circuit(circuit, assignment_matrix, num_qubits, shots=1024): """Simulates the given circuit under the given readout noise""" probs = Statevector.from_instruction(circuit).probabilities() noisy_probs = assignment_matrix @ probs labels = [bin(a)[2:].zfill(num_qubits) for a in range(2**num_qubits)] results = TestReadoutMitigation.rng.choice(labels, size=shots, p=noisy_probs) return Counts(dict(Counter(results))) @staticmethod def ghz_3_circuit(): """A 3-qubit circuit generating |000>+|111>""" c = QuantumCircuit(3) c.h(0) c.cx(0, 1) c.cx(1, 2) return (c, "ghz_3_ciruit", 3) @staticmethod def first_qubit_h_3_circuit(): """A 3-qubit circuit generating |000>+|001>""" c = QuantumCircuit(3) c.h(0) return (c, "first_qubit_h_3_circuit", 3) @staticmethod def assignment_matrices(): """A 3-qubit readout noise assignment matrices""" return LocalReadoutMitigator(backend=FakeYorktown())._assignment_mats[0:3] @staticmethod def counts_data(circuit, assignment_matrices, shots=1024): """Generates count data for the noisy and noiseless versions of the circuit simulation""" full_assignment_matrix = assignment_matrices[0] for m in assignment_matrices[1:]: full_assignment_matrix = np.kron(full_assignment_matrix, m) num_qubits = len(assignment_matrices) ideal_assignment_matrix = np.eye(2**num_qubits) counts_ideal = TestReadoutMitigation.simulate_circuit( circuit, ideal_assignment_matrix, num_qubits, shots ) counts_noise = TestReadoutMitigation.simulate_circuit( circuit, full_assignment_matrix, num_qubits, shots ) probs_noise = {key: value / shots for key, value in counts_noise.items()} return counts_ideal, counts_noise, probs_noise def test_mitigation_improvement(self): """Test whether readout mitigation led to more accurate results""" shots = 1024 assignment_matrices = self.assignment_matrices() num_qubits = len(assignment_matrices) mitigators = self.mitigators(assignment_matrices) circuit, circuit_name, num_qubits = self.ghz_3_circuit() counts_ideal, counts_noise, probs_noise = self.counts_data( circuit, assignment_matrices, shots ) unmitigated_error = self.compare_results(counts_ideal, counts_noise) unmitigated_stddev = stddev(probs_noise, shots) for mitigator in mitigators: mitigated_quasi_probs = mitigator.quasi_probabilities(counts_noise) mitigated_probs = ( mitigated_quasi_probs.nearest_probability_distribution().binary_probabilities( num_bits=num_qubits ) ) mitigated_error = self.compare_results(counts_ideal, mitigated_probs) self.assertLess( mitigated_error, unmitigated_error * 0.8, "Mitigator {} did not improve circuit {} measurements".format( mitigator, circuit_name ), ) mitigated_stddev_upper_bound = mitigated_quasi_probs._stddev_upper_bound max_unmitigated_stddev = max(unmitigated_stddev.values()) self.assertGreaterEqual( mitigated_stddev_upper_bound, max_unmitigated_stddev, "Mitigator {} on circuit {} gave stddev upper bound {} " "while unmitigated stddev maximum is {}".format( mitigator, circuit_name, mitigated_stddev_upper_bound, max_unmitigated_stddev, ), ) def test_expectation_improvement(self): """Test whether readout mitigation led to more accurate results and that its standard deviation is increased""" shots = 1024 assignment_matrices = self.assignment_matrices() mitigators = self.mitigators(assignment_matrices) num_qubits = len(assignment_matrices) diagonals = [] diagonals.append("IZ0") diagonals.append("101") diagonals.append("IZZ") qubit_index = {i: i for i in range(num_qubits)} circuit, circuit_name, num_qubits = self.ghz_3_circuit() counts_ideal, counts_noise, _ = self.counts_data(circuit, assignment_matrices, shots) probs_ideal, _ = counts_probability_vector(counts_ideal, qubit_index=qubit_index) probs_noise, _ = counts_probability_vector(counts_noise, qubit_index=qubit_index) for diagonal in diagonals: if isinstance(diagonal, str): diagonal = str2diag(diagonal) unmitigated_expectation, unmitigated_stddev = expval_with_stddev( diagonal, probs_noise, shots=counts_noise.shots() ) ideal_expectation = np.dot(probs_ideal, diagonal) unmitigated_error = np.abs(ideal_expectation - unmitigated_expectation) for mitigator in mitigators: mitigated_expectation, mitigated_stddev = mitigator.expectation_value( counts_noise, diagonal ) mitigated_error = np.abs(ideal_expectation - mitigated_expectation) self.assertLess( mitigated_error, unmitigated_error, "Mitigator {} did not improve circuit {} expectation computation for diagonal {} " "ideal: {}, unmitigated: {} mitigated: {}".format( mitigator, circuit_name, diagonal, ideal_expectation, unmitigated_expectation, mitigated_expectation, ), ) self.assertGreaterEqual( mitigated_stddev, unmitigated_stddev, "Mitigator {} did not increase circuit {} the standard deviation".format( mitigator, circuit_name ), ) def test_clbits_parameter(self): """Test whether the clbits parameter is handled correctly""" shots = 10000 assignment_matrices = self.assignment_matrices() mitigators = self.mitigators(assignment_matrices) circuit, _, _ = self.first_qubit_h_3_circuit() counts_ideal, counts_noise, _ = self.counts_data(circuit, assignment_matrices, shots) counts_ideal_12 = marginal_counts(counts_ideal, [1, 2]) counts_ideal_02 = marginal_counts(counts_ideal, [0, 2]) for mitigator in mitigators: mitigated_probs_12 = ( mitigator.quasi_probabilities(counts_noise, qubits=[1, 2], clbits=[1, 2]) .nearest_probability_distribution() .binary_probabilities(num_bits=2) ) mitigated_error = self.compare_results(counts_ideal_12, mitigated_probs_12) self.assertLess( mitigated_error, 0.001, "Mitigator {} did not correctly marganalize for qubits 1,2".format(mitigator), ) mitigated_probs_02 = ( mitigator.quasi_probabilities(counts_noise, qubits=[0, 2], clbits=[0, 2]) .nearest_probability_distribution() .binary_probabilities(num_bits=2) ) mitigated_error = self.compare_results(counts_ideal_02, mitigated_probs_02) self.assertLess( mitigated_error, 0.001, "Mitigator {} did not correctly marganalize for qubits 0,2".format(mitigator), ) def test_qubits_parameter(self): """Test whether the qubits parameter is handled correctly""" shots = 10000 assignment_matrices = self.assignment_matrices() mitigators = self.mitigators(assignment_matrices) circuit, _, _ = self.first_qubit_h_3_circuit() counts_ideal, counts_noise, _ = self.counts_data(circuit, assignment_matrices, shots) counts_ideal_012 = counts_ideal counts_ideal_210 = Counts({"000": counts_ideal["000"], "100": counts_ideal["001"]}) counts_ideal_102 = Counts({"000": counts_ideal["000"], "010": counts_ideal["001"]}) for mitigator in mitigators: mitigated_probs_012 = ( mitigator.quasi_probabilities(counts_noise, qubits=[0, 1, 2]) .nearest_probability_distribution() .binary_probabilities(num_bits=3) ) mitigated_error = self.compare_results(counts_ideal_012, mitigated_probs_012) self.assertLess( mitigated_error, 0.001, "Mitigator {} did not correctly handle qubit order 0, 1, 2".format(mitigator), ) mitigated_probs_210 = ( mitigator.quasi_probabilities(counts_noise, qubits=[2, 1, 0]) .nearest_probability_distribution() .binary_probabilities(num_bits=3) ) mitigated_error = self.compare_results(counts_ideal_210, mitigated_probs_210) self.assertLess( mitigated_error, 0.001, "Mitigator {} did not correctly handle qubit order 2, 1, 0".format(mitigator), ) mitigated_probs_102 = ( mitigator.quasi_probabilities(counts_noise, qubits=[1, 0, 2]) .nearest_probability_distribution() .binary_probabilities(num_bits=3) ) mitigated_error = self.compare_results(counts_ideal_102, mitigated_probs_102) self.assertLess( mitigated_error, 0.001, "Mitigator {} did not correctly handle qubit order 1, 0, 2".format(mitigator), ) def test_repeated_qubits_parameter(self): """Tests the order of mitigated qubits.""" shots = 10000 assignment_matrices = self.assignment_matrices() mitigators = self.mitigators(assignment_matrices, qubits=[0, 1, 2]) circuit, _, _ = self.first_qubit_h_3_circuit() counts_ideal, counts_noise, _ = self.counts_data(circuit, assignment_matrices, shots) counts_ideal_012 = counts_ideal counts_ideal_210 = Counts({"000": counts_ideal["000"], "100": counts_ideal["001"]}) for mitigator in mitigators: mitigated_probs_210 = ( mitigator.quasi_probabilities(counts_noise, qubits=[2, 1, 0]) .nearest_probability_distribution() .binary_probabilities(num_bits=3) ) mitigated_error = self.compare_results(counts_ideal_210, mitigated_probs_210) self.assertLess( mitigated_error, 0.001, "Mitigator {} did not correctly handle qubit order 2,1,0".format(mitigator), ) # checking qubit order 2,1,0 should not "overwrite" the default 0,1,2 mitigated_probs_012 = ( mitigator.quasi_probabilities(counts_noise) .nearest_probability_distribution() .binary_probabilities(num_bits=3) ) mitigated_error = self.compare_results(counts_ideal_012, mitigated_probs_012) self.assertLess( mitigated_error, 0.001, "Mitigator {} did not correctly handle qubit order 0,1,2 (the expected default)".format( mitigator ), ) def test_qubits_subset_parameter(self): """Tests mitigation on a subset of the initial set of qubits.""" shots = 10000 assignment_matrices = self.assignment_matrices() mitigators = self.mitigators(assignment_matrices, qubits=[2, 4, 6]) circuit, _, _ = self.first_qubit_h_3_circuit() counts_ideal, counts_noise, _ = self.counts_data(circuit, assignment_matrices, shots) counts_ideal_2 = marginal_counts(counts_ideal, [0]) counts_ideal_6 = marginal_counts(counts_ideal, [2]) for mitigator in mitigators: mitigated_probs_2 = ( mitigator.quasi_probabilities(counts_noise, qubits=[2]) .nearest_probability_distribution() .binary_probabilities(num_bits=1) ) mitigated_error = self.compare_results(counts_ideal_2, mitigated_probs_2) self.assertLess( mitigated_error, 0.001, "Mitigator {} did not correctly handle qubit subset".format(mitigator), ) mitigated_probs_6 = ( mitigator.quasi_probabilities(counts_noise, qubits=[6]) .nearest_probability_distribution() .binary_probabilities(num_bits=1) ) mitigated_error = self.compare_results(counts_ideal_6, mitigated_probs_6) self.assertLess( mitigated_error, 0.001, "Mitigator {} did not correctly handle qubit subset".format(mitigator), ) diagonal = str2diag("ZZ") ideal_expectation = 0 mitigated_expectation, _ = mitigator.expectation_value( counts_noise, diagonal, qubits=[2, 6] ) mitigated_error = np.abs(ideal_expectation - mitigated_expectation) self.assertLess( mitigated_error, 0.1, "Mitigator {} did not improve circuit expectation".format(mitigator), ) def test_from_backend(self): """Test whether a local mitigator can be created directly from backend properties""" backend = FakeYorktown() num_qubits = len(backend.properties().qubits) probs = TestReadoutMitigation.rng.random((num_qubits, 2)) for qubit_idx, qubit_prop in enumerate(backend.properties().qubits): for prop in qubit_prop: if prop.name == "prob_meas1_prep0": prop.value = probs[qubit_idx][0] if prop.name == "prob_meas0_prep1": prop.value = probs[qubit_idx][1] LRM_from_backend = LocalReadoutMitigator(backend=backend) mats = [] for qubit_idx in range(num_qubits): mat = np.array( [ [1 - probs[qubit_idx][0], probs[qubit_idx][1]], [probs[qubit_idx][0], 1 - probs[qubit_idx][1]], ] ) mats.append(mat) LRM_from_matrices = LocalReadoutMitigator(assignment_matrices=mats) self.assertTrue( matrix_equal( LRM_from_backend.assignment_matrix(), LRM_from_matrices.assignment_matrix() ) ) def test_error_handling(self): """Test that the assignment matrices are valid.""" bad_matrix_A = np.array([[-0.3, 1], [1.3, 0]]) # negative indices bad_matrix_B = np.array([[0.2, 1], [0.7, 0]]) # columns not summing to 1 good_matrix_A = np.array([[0.2, 1], [0.8, 0]]) for bad_matrix in [bad_matrix_A, bad_matrix_B]: with self.assertRaises(QiskitError) as cm: CorrelatedReadoutMitigator(bad_matrix) self.assertEqual( cm.exception.message, "Assignment matrix columns must be valid probability distributions", ) with self.assertRaises(QiskitError) as cm: amats = [good_matrix_A, bad_matrix_A] LocalReadoutMitigator(amats) self.assertEqual( cm.exception.message, "Assignment matrix columns must be valid probability distributions", ) with self.assertRaises(QiskitError) as cm: amats = [bad_matrix_B, good_matrix_A] LocalReadoutMitigator(amats) self.assertEqual( cm.exception.message, "Assignment matrix columns must be valid probability distributions", ) def test_expectation_value_endian(self): """Test that endian for expval is little.""" mitigators = self.mitigators(self.assignment_matrices()) counts = Counts({"10": 3, "11": 24, "00": 74, "01": 923}) for mitigator in mitigators: expval, _ = mitigator.expectation_value(counts, diagonal="IZ", qubits=[0, 1]) self.assertAlmostEqual(expval, -1.0, places=0) def test_quasi_probabilities_shots_passing(self): """Test output of LocalReadoutMitigator.quasi_probabilities We require the number of shots to be set in the output. """ mitigator = LocalReadoutMitigator([np.array([[0.9, 0.1], [0.1, 0.9]])], qubits=[0]) counts = Counts({"10": 3, "11": 24, "00": 74, "01": 923}) quasi_dist = mitigator.quasi_probabilities(counts) self.assertEqual(quasi_dist.shots, sum(counts.values())) # custom number of shots quasi_dist = mitigator.quasi_probabilities(counts, shots=1025) self.assertEqual(quasi_dist.shots, 1025) class TestLocalReadoutMitigation(QiskitTestCase): """Tests specific to the local readout mitigator""" def test_assignment_matrix(self): """Tests that the local mitigator generates the full assignment matrix correctly""" qubits = [7, 2, 3] assignment_matrices = LocalReadoutMitigator(backend=FakeYorktown())._assignment_mats[0:3] expected_assignment_matrix = np.kron( np.kron(assignment_matrices[2], assignment_matrices[1]), assignment_matrices[0] ) expected_mitigation_matrix = np.linalg.inv(expected_assignment_matrix) LRM = LocalReadoutMitigator(assignment_matrices, qubits) self.assertTrue(matrix_equal(expected_mitigation_matrix, LRM.mitigation_matrix())) self.assertTrue(matrix_equal(expected_assignment_matrix, LRM.assignment_matrix())) if __name__ == "__main__": unittest.main()
https://github.com/geduardo/Q-Snake-Qiskitcamp-Europe-2019
geduardo
import pew_tunnel as pew import random import pygame from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer import numpy as np ######################################################################### #FUNCTIONS ######################################################################### simulator = Aer.get_backend('statevector_simulator') def qrand(nbits): """generates nbits real random numbers using quantum state measurements in qiskit.""" circ = QuantumCircuit(1, 1) circ.h(0) circ.measure(0, 0) val = np.zeros(nbits) for i in range(nbits): job=execute(circ, simulator) res = job.result() vec = res.get_statevector() val[i] = vec[0] * 1 + vec[1] * 0 #convert val array into bitstring b and then into integer b = '' for i in range(nbits): b += str(int(val[i])) integ= int(b, 2) return integ def Pt(U0, E, L, betac, gamma_sqc): """return tunneling probability for square barrier""" return 1/ (np.cosh(betac * L)**2 + gamma_sqc * np.sinh(betac * L)**2) def beta(U0, E): """supply function for Pt""" return np.sqrt(2* (U0 - E)) def gamma_sq(U0, E): """supply function for Pt""" return 0.25 * ((1 - E/U0)/(E/U0) + (E/U0)/(1-E/U0) - 2) def theta(p_tunnel): """returns rotation angle corresponding to tunneling prob. p_tunnel""" return 2 * np.arcsin(np.sqrt(p_tunnel)) def tunnelres(U0, length_snake, L, betac, gamma_sqc): """returns 0 if tunnel, returns 1 if no tunnel""" P_t = Pt(U0, length_snake, L, betac, gamma_sqc) #get tunneling prob depending on current snake length theta_rot = theta(P_t) #get rot angle #qcirc qr = QuantumRegister(1) cr = ClassicalRegister(1) circ = QuantumCircuit(qr, cr) circ.rx(theta_rot, qr[0]) circ.measure(qr, cr) job = execute(circ, simulator) res = job.result() vec = res.get_statevector() val = vec[0] * 1 + vec[1] * 0 if val == 1: return 0 else: return 1 #r= random.randint(0, 1) #return round(r) ########################################################################## #MAIN ########################################################################## #initialize pew dis = pew.init() screen = pew.Pix() #set size bits = 3 ds= 2**bits #displazsize #set game starting parameters game_speed = 4 snake = [(2, 4)] dx, dy = 1, 0 apple_x, apple_y = 6, 4 screen.pixel(apple_x, apple_y, 2) howmanyapples = 1 #marker for total number of eaten apples, used for scoring #set graphics for probability display pygame.font.init() #gate backkgorund font1 = pygame.font.Font(None, 33) text = font1.render('Probability for tunneling is', True, (255, 0, 0)) dis.blit(text, (20, 330)) font2 = pygame.font.Font(None, 45) text2 = font2.render('100%', True, (255, 0, 0)) dis.blit(text2, (130, 360)) ima = pygame.image.load('pewblack.jpg') #tunneling parameters U0=37 #max snake length = 6x6 = 36 E=1 L=0.05 #optimal barrier size for nice tunneling probabilities #initialize tunneling tracker tunnel=0 #don't see other side as second barrier snakepos=1 #marker of snakepos, 1=head, increase towards tail headtunnel=0 #let the head tunnel again through other even if tail still in process while True: #snake runs #create barrier bar= [] for i in range(ds): screen.pixel(0, i, 1) screen.pixel(ds-1, i, 1) screen.pixel(i, 0, 1) screen.pixel(i, ds-1, 1) bar.append((0, i)) bar.append((ds-1, i)) bar.append((i, 0)) bar.append((i, ds-1)) #find the head if len(snake) > 1: x, y = snake[-2] screen.pixel(x, y, 1) x, y = snake[-1] screen.pixel(x, y, 3) #color the head yellow pew.show(screen) pew.tick(1 / game_speed) #get commands keys = pew.keys() if headtunnel==0: if keys & pew.K_UP and dy == 0: dx, dy = 0, -1 elif keys & pew.K_LEFT and dx == 0: dx, dy = -1, 0 elif keys & pew.K_RIGHT and dx == 0: dx, dy = 1, 0 elif keys & pew.K_DOWN and dy == 0: dx, dy = 0, 1 x = (x + dx) % 8 y = (y + dy) % 8 elif headtunnel==1: #steering not allowed during tunneling of the head (during two rounds) x = (x + dx) % 8 y = (y + dy) % 8 headtunnel=2 elif headtunnel>=2: x = (x + dx) % 8 y = (y + dy) % 8 headtunnel=0 ##TUNNELING PROCESS #snake tail tunnels if tunnel>0 and snakepos<=len(snake): #get segment for tunneling sx, sy = snake[-snakepos] E=len(snake)/2 #divide by two for lower tunnel prob for tail (lower mass->lower energy) tunnels = tunnelres(U0, E, L, beta(U0, E), gamma_sq(U0, E)) if tunnels==1: #tunnels snakepos+=1 else: #does not tunnel del snake[-snakepos] screen.pixel(sx, sy, 0) #reset if last segment tunneled if tunnel>0 and snakepos==(len(snake)+1): tunnel=0 snakepos=1 #snake head tunnels if headtunnel==0 and (x, y) in bar: E=len(snake) tunnel = tunnelres(U0, E, L, beta(U0, E), gamma_sq(U0, E)) if tunnel==0 and len(snake) != 1: #head doesn't tunnel --> game over break else: snakepos+=1 headtunnel+=1 elif headtunnel==1 and (x, y) in bar: headtunnel=0 #display tunneling prob. E = len(snake) if E > 1: prob = Pt(U0, E, L, beta(U0, E), gamma_sq(U0, E)) text3 = font2.render(str(int(round(prob * 100))) + '%', True, (255, 0, 0)) dis.blit(ima, (130, 360)) dis.blit(text3, (130, 360)) else: #if length of snake ==1 (only head), tunneling prob = 100% dis.blit(ima, (130, 360)) #cover the ultimate prob. display dis.blit(text2, (130, 360)) #text2 = '100%' #####TUNNEL END if (x, y) in snake: #exit, game over condition break snake.append((x, y)) #apple generation if x == apple_x and y == apple_y: screen.pixel(apple_x, apple_y, 0) apple_x, apple_y = snake[0] while (apple_x, apple_y) in snake or (apple_x, apple_y) in bar: apple_x = qrand(bits) #random.getrandbits(3) #use this for pseudo random number gen, no qiskit needed apple_y = qrand(bits) #random.getrandbits(3) screen.pixel(apple_x, apple_y, 2) game_speed += 0.2 #increase game speed howmanyapples += 1 #increase number of eaten apples, score +1 else: x, y = snake.pop(0) screen.pixel(x, y, 0) text = pew.Pix.from_text("Game over!") #Game over message and closing for dx in range(-8, text.width): screen.blit(text, -dx, 1) pew.show(screen) pew.tick(1 / 12) text = pew.Pix.from_text("Score:" + str(int(howmanyapples))) #Score message for dx in range(-8, text.width): screen.blit(text, -dx, 1) pew.show(screen) pew.tick(1 / 12)
https://github.com/qiskit-community/qiskit-device-benchmarking
qiskit-community
# This code is part of Qiskit. # # (C) Copyright IBM 2024. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Analyze the benchmarking results """ import argparse import numpy as np import qiskit_device_benchmarking.utilities.file_utils as fu import matplotlib.pyplot as plt def generate_plot(out_data, config_data, args): """Generate a plot from the fast_bench data Generates a plot of the name result_plot_<XXX>.pdf where XXX is the current date and time Args: out_data: data from the run config_data: configuration data from the run args: arguments passed to the parser Returns: None """ markers = ['o','x','.','s','^','v','*'] for i, backend in enumerate(out_data): plt.semilogy(out_data[backend][0],out_data[backend][1], label=backend, marker=markers[np.mod(i,len(markers))]) plt.legend() plt.xlabel('Depth') plt.ylabel('Success Probability (%s over sets)'%args.value) plt.ylim(top=1.0) plt.title('Running Mirror - HE: %s, DD: %s, Trials: %d'%(config_data['he'], config_data['dd'], config_data['trials'])) plt.grid(True) plt.savefig('result_plot_%s.pdf'%fu.timestamp_name()) plt.close() return if __name__ == '__main__': """Analyze a benchmarking run from `fast_bench.py` Args: Call -h for arguments """ parser = argparse.ArgumentParser(description = 'Analyze the results of a ' + 'benchmarking run.') parser.add_argument('-f', '--files', help='Comma separated list of files') parser.add_argument('-b', '--backends', help='Comma separated list of ' + 'backends to plot. If empty plot all.') parser.add_argument('-v', '--value', help='Statistical value to compute', choices=['mean','median', 'max', 'min'], default='mean') parser.add_argument('--plot', help='Generate a plot', action='store_true') args = parser.parse_args() #import from results files and concatenate into a larger results results_dict = {} for file in args.files.split(','): results_dict_new = fu.import_yaml(file) for backend in results_dict_new: if backend not in results_dict: results_dict[backend] = results_dict_new[backend] elif backend!='config': #backend in the results dict but maybe not that depth for depth in results_dict_new[backend]: if depth in results_dict[backend]: err_str = 'Depth %s already exists for backend %s, duplicate results'%(depth,backend) raise ValueError(err_str) else: #check the metadata is the same #TO DO results_dict[backend][depth] = results_dict_new[backend][depth] if args.backends is not None: backends_filt = args.backends.split(',') else: backends_filt = [] out_data = {} for backend in results_dict: if len(backends_filt)>0: if backend not in backends_filt: continue if backend=='config': continue print(backend) depth_list = [] depth_list_i = [] out_data[backend] = [] for depth in results_dict[backend]: if depth=='job_ids': continue depth_list_i.append(depth) if args.value=='mean': depth_list.append(np.mean(results_dict[backend][depth]['mean'])) elif args.value=='max': depth_list.append(np.max(results_dict[backend][depth]['mean'])) elif args.value=='min': depth_list.append(np.min(results_dict[backend][depth]['mean'])) else: depth_list.append(np.median(results_dict[backend][depth]['mean'])) print('Backend %s'%backend) print('Depths: %s'%depth_list_i) if args.value=='mean': print('Means: %s'%depth_list) elif args.value=='max': print('Max: %s'%depth_list) elif args.value=='min': print('Min: %s'%depth_list) else: print('Median: %s'%depth_list) out_data[backend].append(depth_list_i) out_data[backend].append(depth_list) if args.plot: generate_plot(out_data, results_dict['config'], args) elif args.plot: print('Need to run mean/max also')
https://github.com/ohadlev77/sat-circuits-engine
ohadlev77
import json import logging import numpy as np import warnings from functools import wraps from typing import Any, Callable, Optional, Tuple, Union from qiskit import IBMQ, QuantumCircuit, assemble from qiskit.circuit import Barrier, Gate, Instruction, Measure from qiskit.circuit.library import UGate, U3Gate, CXGate from qiskit.providers.ibmq import AccountProvider, IBMQProviderError from qiskit.providers.ibmq.job import IBMQJob def get_provider() -> AccountProvider: with warnings.catch_warnings(): warnings.simplefilter('ignore') ibmq_logger = logging.getLogger('qiskit.providers.ibmq') current_level = ibmq_logger.level ibmq_logger.setLevel(logging.ERROR) # get provider try: provider = IBMQ.get_provider() except IBMQProviderError: provider = IBMQ.load_account() ibmq_logger.setLevel(current_level) return provider def get_job(job_id: str) -> Optional[IBMQJob]: try: job = get_provider().backends.retrieve_job(job_id) return job except Exception: pass return None def circuit_to_json(qc: QuantumCircuit) -> str: class _QobjEncoder(json.encoder.JSONEncoder): def default(self, obj: Any) -> Any: if isinstance(obj, np.ndarray): return obj.tolist() if isinstance(obj, complex): return (obj.real, obj.imag) return json.JSONEncoder.default(self, obj) return json.dumps(circuit_to_dict(qc), cls=_QobjEncoder) def circuit_to_dict(qc: QuantumCircuit) -> dict: qobj = assemble(qc) return qobj.to_dict() def get_job_urls(job: Union[str, IBMQJob]) -> Tuple[bool, Optional[str], Optional[str]]: try: job_id = job.job_id() if isinstance(job, IBMQJob) else job download_url = get_provider()._api_client.account_api.job(job_id).download_url()['url'] result_url = get_provider()._api_client.account_api.job(job_id).result_url()['url'] return download_url, result_url except Exception: return None, None def cached(key_function: Callable) -> Callable: def _decorator(f: Any) -> Callable: f.__cache = {} @wraps(f) def _decorated(*args: Any, **kwargs: Any) -> int: key = key_function(*args, **kwargs) if key not in f.__cache: f.__cache[key] = f(*args, **kwargs) return f.__cache[key] return _decorated return _decorator def gate_key(gate: Gate) -> Tuple[str, int]: return gate.name, gate.num_qubits @cached(gate_key) def gate_cost(gate: Gate) -> int: if isinstance(gate, (UGate, U3Gate)): return 1 elif isinstance(gate, CXGate): return 10 elif isinstance(gate, (Measure, Barrier)): return 0 return sum(map(gate_cost, (g for g, _, _ in gate.definition.data))) def compute_cost(circuit: Union[Instruction, QuantumCircuit]) -> int: print('Computing cost...') circuit_data = None if isinstance(circuit, QuantumCircuit): circuit_data = circuit.data elif isinstance(circuit, Instruction): circuit_data = circuit.definition.data else: raise Exception(f'Unable to obtain circuit data from {type(circuit)}') return sum(map(gate_cost, (g for g, _, _ in circuit_data))) def uses_multiqubit_gate(circuit: QuantumCircuit) -> bool: circuit_data = None if isinstance(circuit, QuantumCircuit): circuit_data = circuit.data elif isinstance(circuit, Instruction) and circuit.definition is not None: circuit_data = circuit.definition.data else: raise Exception(f'Unable to obtain circuit data from {type(circuit)}') for g, _, _ in circuit_data: if isinstance(g, (Barrier, Measure)): continue elif isinstance(g, Gate): if g.num_qubits > 1: return True elif isinstance(g, (QuantumCircuit, Instruction)) and uses_multiqubit_gate(g): return True return False
https://github.com/daimurat/qiskit-implementation
daimurat
from qiskit import QuantumCircuit, Aer from qiskit.visualization import plot_state_qsphere, plot_bloch_multivector import math def plot_bloch_sphere(qc, title, initial): backend = Aer.get_backend('statevector_simulator') result = backend.run(qc).result() sv = result.get_statevector() return plot_bloch_multivector(sv, title=title+' Gate: initial |'+initial+'>') def plot_qsphere_with_phase(qc): backend = Aer.get_backend('statevector_simulator') result = backend.run(qc).result() sv = result.get_statevector() return plot_state_qsphere(sv, show_state_phases=True) qc = QuantumCircuit(1) qc.x(0) plot_bloch_sphere(qc, 'X', '0') qc = QuantumCircuit(1) qc.y(0) plot_bloch_sphere(qc, 'Y', '0') qc = QuantumCircuit(1) qc.initialize([0, 1], 0) qc.y(0) plot_bloch_sphere(qc, 'Y', '1') qc = QuantumCircuit(1) qc.z(0) plot_bloch_sphere(qc, 'Z', '0') qc = QuantumCircuit(1) qc.initialize([0, 1], 0) qc.z(0) plot_bloch_sphere(qc, 'Z', '1') plot_qsphere_with_phase(qc) qc = QuantumCircuit(1) qc.h(0) plot_bloch_sphere(qc, 'Hadamard', '0') qc = QuantumCircuit(1) qc.initialize([1/math.sqrt(2), 1/math.sqrt(2)]) qc.rz(math.pi/4, 0) plot_bloch_sphere(qc, 'Rz', '+') plot_qsphere_with_phase(qc) qc = QuantumCircuit(1) qc.initialize([1/math.sqrt(2), 1/math.sqrt(2)]) qc.s(0) plot_bloch_sphere(qc, 'S', '+') plot_qsphere_with_phase(qc) qc = QuantumCircuit(1) qc.initialize([1/math.sqrt(2), 1/math.sqrt(2)]) qc.t(0) plot_bloch_sphere(qc, 'S', '+') plot_qsphere_with_phase(qc) from qiskit.quantum_info import Operator XX = Operator([[0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0]]) XX qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) bellOp = Operator(qc) bellOp qc = QuantumCircuit(2) qc.append(bellOp, [0, 1]) qc.draw('mpl') from qiskit.quantum_info.operators import Pauli A = Operator(Pauli(label='X')) B = Operator(Pauli(label='Z')) A.tensor(B) A.compose(B) A+B
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.quantum_info import Operator from qiskit.transpiler.passes import UnitarySynthesis circuit = QuantumCircuit(1) circuit.rx(0.8, 0) unitary = Operator(circuit).data unitary_circ = QuantumCircuit(1) unitary_circ.unitary(unitary, [0]) synth = UnitarySynthesis(basis_gates=["h", "s"], method="sk") out = synth(unitary_circ) out.draw('mpl')
https://github.com/Axect/QuantumAlgorithms
Axect
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, execute from qiskit.visualization import plot_histogram import numpy as np import matplotlib.pyplot as plt def circuit(alice): e = QuantumRegister(2, name='e') a = QuantumRegister(1, name='a') b = QuantumRegister(1, name='b') c = ClassicalRegister(2, name='c') qc = QuantumCircuit(e, a, b, c, name='circuit') # Initialize Target qubit qc.initialize(alice / np.linalg.norm(alice), e) qc.barrier() # Create Bell pair qc.h(a) qc.cx(a, b) qc.barrier() # Write target qubit to Bell pair qc.cz(e[0], a) qc.cx(e[1], a) qc.barrier() # Decoding qc.cx(a, b) qc.h(a) qc.measure(a, c[1]) qc.measure(b, c[0]) backend = Aer.get_backend('qasm_simulator') return qc, execute(qc, backend).result().get_counts() qc, counts = circuit([1,0,0,1]) qc.draw(output='mpl', style='iqx') plot_histogram(counts)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import transpile 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_basis = transpile(qc, backend) qc_basis.draw(output='mpl')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit circ = QuantumCircuit(2, 2) circ.h(0) circ.cx(0, 1) circ.measure(0, 0) circ.measure(1, 1) circ.draw('mpl') from qiskit import pulse from qiskit.pulse.library import Gaussian from qiskit.providers.fake_provider import FakeValencia backend = FakeValencia() with pulse.build(backend, name='hadamard') as h_q0: pulse.play(Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(0)) h_q0.draw() circ.add_calibration('h', [0], h_q0) from qiskit import transpile from qiskit.providers.fake_provider import FakeHanoi backend = FakeHanoi() circ = transpile(circ, backend) print(backend.configuration().basis_gates) circ.draw('mpl', idle_wires=False) from qiskit import QuantumCircuit from qiskit.circuit import Gate circ = QuantumCircuit(1, 1) custom_gate = Gate('my_custom_gate', 1, [3.14, 1]) # 3.14 is an arbitrary parameter for demonstration circ.append(custom_gate, [0]) circ.measure(0, 0) circ.draw('mpl') with pulse.build(backend, name='custom') as my_schedule: pulse.play(Gaussian(duration=64, amp=0.2, sigma=8), pulse.drive_channel(0)) circ.add_calibration('my_custom_gate', [0], my_schedule, [3.14, 1]) # Alternatively: circ.add_calibration(custom_gate, [0], my_schedule) circ = transpile(circ, backend) circ.draw('mpl', idle_wires=False) circ = QuantumCircuit(2, 2) circ.append(custom_gate, [1]) from qiskit import QiskitError try: circ = transpile(circ, backend) except QiskitError as e: print(e) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright