repo
stringclasses
900 values
file
stringclasses
754 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 # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("./") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="lq") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") t3_st_qcs = transpile(t3_st_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_st_qcs), ")") t3_st_qcs[-1].draw("mpl") # only view trotter gates # from qiskit.test.mock import FakeJakarta # backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') print("provider:", provider) backend = provider.get_backend("ibmq_jakarta") shots = 8192 reps = 8 jobs = [] for _ in range(reps): # execute job = execute(t3_st_qcs, backend, shots=shots) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout=initial_layout) print('Job ID', cal_job.job_id()) dt_now = datetime.datetime.now() print(dt_now) with open("jobs_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) with open("job_ids_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) with open("properties_jakarta" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump(backend.properties(), f) filename = "job_ids_jakarta_100step_20220412_171248_.pkl" # change here with open(filename, "rb") as f: job_ids_dict = pickle.load(f) job_ids = job_ids_dict["job_ids"] cal_job_id = job_ids_dict["cal_job_id"] retrieved_jobs = [] for job_id in job_ids: retrieved_jobs.append(backend.retrieve_job(job_id)) retrieved_cal_job = backend.retrieve_job(cal_job_id) cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') # set the target state target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in retrieved_jobs: # mit_results = meas_fitter.filter.apply(job.result()) # apply QREM rho = StateTomographyFitter(job.result(), st_qcs).fit(method='lstsq') fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids))) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools import pickle # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.providers.aer import QasmSimulator from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.quantum_info import state_fidelity # Suppress warnings import warnings warnings.filterwarnings('ignore') def trotter_gate(dt, to_instruction = True): qc = QuantumCircuit(2) qc.rx(2*dt,0) qc.rz(2*dt,1) qc.h(1) qc.cx(1,0) qc.rz(-2*dt, 0) qc.rx(-2*dt, 1) qc.rz(2*dt, 1) qc.cx(1,0) qc.h(1) qc.rz(2*dt, 0) return qc.to_instruction() if to_instruction else qc trotter_gate(np.pi / 6, to_instruction=False).draw("mpl") # 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) # Number of trotter steps trotter_steps = list(range(1,10)) + list(range(10, 101, 10)) st_qcs_list = [] for num_steps in trotter_steps: # Initialize quantum circuit for 3 qubits qr = QuantumRegister(7) 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.x([5]) # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) # Simulate time evolution under H_heis3 Hamiltonian for _ in range(num_steps): qc.append(Trot_gate, [qr[3], qr[5]]) qc.cx(qr[3], qr[1]) qc.cx(qr[5], qr[3]) # 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}) 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"]) # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(t3_qc, [qr[1], qr[3], qr[5]]) st_qcs_list.append(st_qcs) # Display circuit for confirmation # st_qcs[-1].decompose().draw() # view decomposition of trotter gates st_qcs_list[-1][-1].draw("mpl") # only view trotter gates from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") shots = 8192 reps = 8 jobs = [] for _ in range(reps): # execute job = execute(st_qcs, backend, shots=shots) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout=[5,3,1]) print('Job ID', cal_job.job_id()) dt_now = datetime.datetime.now() print(dt_now) with open("jobs_jakarta_50step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) with open("job_ids_jakarta_50step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) with open("properties_jakarta" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump(backend.properties(), f) with open("jakarta_50step.pkl", "rb") as f: job_list = pickle.load(f) jobs = job_list["jobs"] cal_job = job_list["cal_job"] cal_results = cal_job.result() print("retrieved cal_results") meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') mit_results = [] for i, job in enumerate(jobs): mit_results.append( meas_fitter.filter.apply(job.result()) ) print("retrieved", i, "th results") # Compute the state tomography based on the st_qcs quantum circuits and the results from those ciricuits 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 # Compute tomography fidelities for each repetition fids = [] for result in mit_results: fid = state_tomo(result, st_qcs) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools import pickle # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.providers.aer import QasmSimulator from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.quantum_info import state_fidelity # Suppress warnings import warnings warnings.filterwarnings('ignore') def trotter_gate(dt, to_instruction = True): qc = QuantumCircuit(2) qc.rx(2*dt,0) qc.rz(2*dt,1) qc.h(1) qc.cx(1,0) qc.rz(-2*dt, 0) qc.rx(-2*dt, 1) qc.rz(2*dt, 1) qc.cx(1,0) qc.h(1) qc.rz(2*dt, 0) return qc.to_instruction() if to_instruction else qc trotter_gate(np.pi / 6, to_instruction=False).draw("mpl") # 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) # Number of trotter steps trotter_steps = 15 ### CAN BE >= 4 # Initialize quantum circuit for 3 qubits qr = QuantumRegister(7) 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.x([5]) # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) # Simulate time evolution under H_heis3 Hamiltonian for _ in range(trotter_steps): qc.append(Trot_gate, [qr[3], qr[5]]) qc.cx(qr[3], qr[1]) qc.cx(qr[5], qr[3]) # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time/trotter_steps}) 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"]) # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(t3_qc, [qr[1], qr[3], qr[5]]) # Display circuit for confirmation # st_qcs[-1].decompose().draw() # view decomposition of trotter gates st_qcs[-1].draw("mpl") # only view trotter gates # from qiskit.test.mock import FakeJakarta # backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') print("provider:", provider) backend = provider.get_backend("ibmq_jakarta") shots = 8192 reps = 8 jobs = [] for _ in range(reps): # execute job = execute(st_qcs, backend, shots=shots) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout=[5,3,1]) print('Job ID', cal_job.job_id()) dt_now = datetime.datetime.now() print(dt_now) with open("jobs_jakarta_15step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) with open("job_ids_jakarta_15step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) with open("properties_jakarta" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump(backend.properties(), f) filename = "job_ids_jakarta_15step_20220412_031437_.pkl" # change here with open(filename, "rb") as f: job_ids_dict = pickle.load(f) job_ids = job_ids_dict["job_ids"] cal_job_id = job_ids_dict["cal_job_id"] retrieved_jobs = [] for job_id in job_ids: retrieved_jobs.append(backend.retrieve_job(job_id)) retrieved_cal_job = backend.retrieve_job(cal_job_id) cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') # set the target state target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in retrieved_jobs: mit_results = meas_fitter.filter.apply(job.result()) # apply QREM rho = StateTomographyFitter(mit_results, st_qcs).fit(method='lstsq') fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids))) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools import pickle # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.providers.aer import QasmSimulator from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.quantum_info import state_fidelity # Suppress warnings import warnings warnings.filterwarnings('ignore') def trotter_gate(dt, to_instruction = True): qc = QuantumCircuit(2) qc.rx(2*dt,0) qc.rz(2*dt,1) qc.h(1) qc.cx(1,0) qc.rz(-2*dt, 0) qc.rx(-2*dt, 1) qc.rz(2*dt, 1) qc.cx(1,0) qc.h(1) qc.rz(2*dt, 0) return qc.to_instruction() if to_instruction else qc trotter_gate(np.pi / 6, to_instruction=False).draw("mpl") # 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) # Number of trotter steps trotter_steps = 15 ### CAN BE >= 4 # Initialize quantum circuit for 3 qubits qr = QuantumRegister(7) 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.x([5]) # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) # Simulate time evolution under H_heis3 Hamiltonian for _ in range(trotter_steps): qc.append(Trot_gate, [qr[3], qr[5]]) qc.cx(qr[3], qr[1]) qc.cx(qr[5], qr[3]) # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time/trotter_steps}) 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"]) # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(t3_qc, [qr[1], qr[3], qr[5]]) # Display circuit for confirmation # st_qcs[-1].decompose().draw() # view decomposition of trotter gates st_qcs[-1].draw("mpl") # only view trotter gates # from qiskit.test.mock import FakeJakarta # backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') print("provider:", provider) backend = provider.get_backend("ibmq_jakarta") shots = 8192 reps = 8 jobs = [] for _ in range(reps): # execute job = execute(st_qcs, backend, shots=shots) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout=[5,3,1]) print('Job ID', cal_job.job_id()) dt_now = datetime.datetime.now() print(dt_now) with open("jobs_jakarta_15step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) with open("job_ids_jakarta_15step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) with open("properties_jakarta" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump(backend.properties(), f) filename = "job_ids_jakarta_15step_20220412_031437_.pkl" # change here with open(filename, "rb") as f: job_ids_dict = pickle.load(f) job_ids = job_ids_dict["job_ids"] cal_job_id = job_ids_dict["cal_job_id"] retrieved_jobs = [] for job_id in job_ids: retrieved_jobs.append(backend.retrieve_job(job_id)) retrieved_cal_job = backend.retrieve_job(cal_job_id) cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') # set the target state target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in retrieved_jobs: # mit_results = meas_fitter.filter.apply(job.result()) # apply QREM rho = StateTomographyFitter(job.result(), st_qcs).fit(method='lstsq') fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids))) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools import pickle # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.providers.aer import QasmSimulator from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.quantum_info import state_fidelity # Suppress warnings import warnings warnings.filterwarnings('ignore') def trotter_gate(dt, to_instruction = True): qc = QuantumCircuit(2) qc.rx(2*dt,0) qc.rz(2*dt,1) qc.h(1) qc.cx(1,0) qc.rz(-2*dt, 0) qc.rx(-2*dt, 1) qc.rz(2*dt, 1) qc.cx(1,0) qc.h(1) qc.rz(2*dt, 0) return qc.to_instruction() if to_instruction else qc trotter_gate(np.pi / 6, to_instruction=False).draw("mpl") # 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) # Number of trotter steps trotter_steps = list(range(1,10)) + list(range(10, 101, 10)) st_qcs_list = [] for num_steps in trotter_steps: # Initialize quantum circuit for 3 qubits qr = QuantumRegister(7) 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.x([5]) # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) # Simulate time evolution under H_heis3 Hamiltonian for _ in range(num_steps): qc.append(Trot_gate, [qr[3], qr[5]]) qc.cx(qr[3], qr[1]) qc.cx(qr[5], qr[3]) # 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}) 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"]) # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(t3_qc, [qr[1], qr[3], qr[5]]) st_qcs_list.append(st_qcs) # Display circuit for confirmation # st_qcs[-1].decompose().draw() # view decomposition of trotter gates st_qcs_list[-1][-1].draw("mpl") # only view trotter gates from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") shots = 8192 reps = 8 jobs = [] for _ in range(reps): # execute job = execute(st_qcs, backend, shots=shots) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout=[5,3,1]) print('Job ID', cal_job.job_id()) dt_now = datetime.datetime.now() print(dt_now) with open("jobs_jakarta_50step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) with open("job_ids_jakarta_50step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) with open("properties_jakarta" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump(backend.properties(), f) with open("jakarta_50step.pkl", "rb") as f: job_list = pickle.load(f) jobs = job_list["jobs"] cal_job = job_list["cal_job"] cal_results = cal_job.result() print("retrieved cal_results") meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') mit_results = [] for i, job in enumerate(jobs): mit_results.append( meas_fitter.filter.apply(job.result()) ) print("retrieved", i, "th results") # Compute the state tomography based on the st_qcs quantum circuits and the results from those ciricuits 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 # Compute tomography fidelities for each repetition fids = [] for result in mit_results: fid = state_tomo(result, st_qcs) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools import pickle # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.providers.aer import QasmSimulator from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.quantum_info import state_fidelity # Suppress warnings import warnings warnings.filterwarnings('ignore') def trotter_gate(dt, to_instruction = True): qc = QuantumCircuit(2) qc.rx(2*dt,0) qc.rz(2*dt,1) qc.h(1) qc.cx(1,0) qc.rz(-2*dt, 0) qc.rx(-2*dt, 1) qc.rz(2*dt, 1) qc.cx(1,0) qc.h(1) qc.rz(2*dt, 0) return qc.to_instruction() if to_instruction else qc trotter_gate(np.pi / 6, to_instruction=False).draw("mpl") # 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) # Number of trotter steps trotter_steps = 15 ### CAN BE >= 4 # Initialize quantum circuit for 3 qubits qr = QuantumRegister(7) 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.x([5]) # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) # Simulate time evolution under H_heis3 Hamiltonian for _ in range(trotter_steps): qc.append(Trot_gate, [qr[3], qr[5]]) qc.cx(qr[3], qr[1]) qc.cx(qr[5], qr[3]) # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time/trotter_steps}) 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"]) # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(t3_qc, [qr[1], qr[3], qr[5]]) # Display circuit for confirmation # st_qcs[-1].decompose().draw() # view decomposition of trotter gates st_qcs[-1].draw("mpl") # only view trotter gates # from qiskit.test.mock import FakeJakarta # backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') print("provider:", provider) backend = provider.get_backend("ibmq_jakarta") shots = 8192 reps = 8 jobs = [] for _ in range(reps): # execute job = execute(st_qcs, backend, shots=shots) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout=[5,3,1]) print('Job ID', cal_job.job_id()) dt_now = datetime.datetime.now() print(dt_now) with open("jobs_jakarta_15step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) with open("job_ids_jakarta_15step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) with open("properties_jakarta" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump(backend.properties(), f) filename = "job_ids_jakarta_15step_20220412_031437_.pkl" # change here with open(filename, "rb") as f: job_ids_dict = pickle.load(f) job_ids = job_ids_dict["job_ids"] cal_job_id = job_ids_dict["cal_job_id"] retrieved_jobs = [] for job_id in job_ids: retrieved_jobs.append(backend.retrieve_job(job_id)) retrieved_cal_job = backend.retrieve_job(cal_job_id) cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') # set the target state target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in retrieved_jobs: mit_results = meas_fitter.filter.apply(job.result()) # apply QREM rho = StateTomographyFitter(mit_results, st_qcs).fit(method='lstsq') fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids))) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools import pickle # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.providers.aer import QasmSimulator from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.quantum_info import state_fidelity # Suppress warnings import warnings warnings.filterwarnings('ignore') def trotter_gate(dt, to_instruction = True): qc = QuantumCircuit(2) qc.rx(2*dt,0) qc.rz(2*dt,1) qc.h(1) qc.cx(1,0) qc.rz(-2*dt, 0) qc.rx(-2*dt, 1) qc.rz(2*dt, 1) qc.cx(1,0) qc.h(1) qc.rz(2*dt, 0) return qc.to_instruction() if to_instruction else qc trotter_gate(np.pi / 6, to_instruction=False).draw("mpl") # 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) # Number of trotter steps trotter_steps = 15 ### CAN BE >= 4 # Initialize quantum circuit for 3 qubits qr = QuantumRegister(7) 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.x([5]) # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) # Simulate time evolution under H_heis3 Hamiltonian for _ in range(trotter_steps): qc.append(Trot_gate, [qr[3], qr[5]]) qc.cx(qr[3], qr[1]) qc.cx(qr[5], qr[3]) # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time/trotter_steps}) 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"]) # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(t3_qc, [qr[1], qr[3], qr[5]]) # Display circuit for confirmation # st_qcs[-1].decompose().draw() # view decomposition of trotter gates st_qcs[-1].draw("mpl") # only view trotter gates # from qiskit.test.mock import FakeJakarta # backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') print("provider:", provider) backend = provider.get_backend("ibmq_jakarta") shots = 8192 reps = 8 jobs = [] for _ in range(reps): # execute job = execute(st_qcs, backend, shots=shots) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout=[5,3,1]) print('Job ID', cal_job.job_id()) dt_now = datetime.datetime.now() print(dt_now) with open("jobs_jakarta_15step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) with open("job_ids_jakarta_15step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) with open("properties_jakarta" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump(backend.properties(), f) filename = "job_ids_jakarta_15step_20220412_031437_.pkl" # change here with open(filename, "rb") as f: job_ids_dict = pickle.load(f) job_ids = job_ids_dict["job_ids"] cal_job_id = job_ids_dict["cal_job_id"] retrieved_jobs = [] for job_id in job_ids: retrieved_jobs.append(backend.retrieve_job(job_id)) retrieved_cal_job = backend.retrieve_job(cal_job_id) cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') # set the target state target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in retrieved_jobs: # mit_results = meas_fitter.filter.apply(job.result()) # apply QREM rho = StateTomographyFitter(job.result(), st_qcs).fit(method='lstsq') fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids))) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../utils/") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) # Pauli Twirling print("created zne_qcs (length:", len(zne_qcs), ")") # optimization_level must be 0 # feed initial_layout here to see the picture of the circuits before casting the job t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") print(str(backend)) shots = 1 << 13 reps = 8 # unused jobs = [] for _ in range(reps): #! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits, name="calq") meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # we have to feed initial_layout to calibration matrix cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) meas_calibs[0].draw("mpl") dt_now = datetime.datetime.now() print(dt_now) filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl" print(filename) # with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) # with open(filename, "wb") as f: # pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) # with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump(backend.properties(), f) retrieved_jobs = jobs retrieved_cal_job = cal_job cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in retrieved_jobs: mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors) rho = expvals_to_valid_rho(num_qubits, zne_expvals) fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
https://github.com/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/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../utils/") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) # Pauli Twirling print("created zne_qcs (length:", len(zne_qcs), ")") # optimization_level must be 0 # feed initial_layout here to see the picture of the circuits before casting the job t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") print(str(backend)) shots = 1 << 13 reps = 8 # unused jobs = [] for _ in range(reps): #! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits, name="calq") meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # we have to feed initial_layout to calibration matrix cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) meas_calibs[0].draw("mpl") dt_now = datetime.datetime.now() print(dt_now) filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl" print(filename) # with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) # with open(filename, "wb") as f: # pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) # with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump(backend.properties(), f) retrieved_jobs = jobs retrieved_cal_job = cal_job cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in retrieved_jobs: mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors) rho = expvals_to_valid_rho(num_qubits, zne_expvals) fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
https://github.com/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/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../utils/") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) # Pauli Twirling print("created zne_qcs (length:", len(zne_qcs), ")") # optimization_level must be 0 # feed initial_layout here to see the picture of the circuits before casting the job t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") print(str(backend)) shots = 1 << 13 reps = 8 # unused jobs = [] for _ in range(reps): #! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits, name="calq") meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # we have to feed initial_layout to calibration matrix cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) meas_calibs[0].draw("mpl") dt_now = datetime.datetime.now() print(dt_now) filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl" print(filename) # with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) # with open(filename, "wb") as f: # pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) # with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump(backend.properties(), f) retrieved_jobs = jobs retrieved_cal_job = cal_job cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in retrieved_jobs: mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors) rho = expvals_to_valid_rho(num_qubits, zne_expvals) fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
https://github.com/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/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../utils/") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) # Pauli Twirling print("created zne_qcs (length:", len(zne_qcs), ")") # optimization_level must be 0 # feed initial_layout here to see the picture of the circuits before casting the job t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") print(str(backend)) shots = 1 << 13 reps = 8 # unused jobs = [] for _ in range(reps): #! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits, name="calq") meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # we have to feed initial_layout to calibration matrix cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) meas_calibs[0].draw("mpl") dt_now = datetime.datetime.now() print(dt_now) filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl" print(filename) # with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) # with open(filename, "wb") as f: # pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) # with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump(backend.properties(), f) retrieved_jobs = jobs retrieved_cal_job = cal_job cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in retrieved_jobs: mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors) rho = expvals_to_valid_rho(num_qubits, zne_expvals) fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
https://github.com/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/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../utils/") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) # Pauli Twirling print("created zne_qcs (length:", len(zne_qcs), ")") # optimization_level must be 0 # feed initial_layout here to see the picture of the circuits before casting the job t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") print(str(backend)) shots = 1 << 13 reps = 8 # unused jobs = [] for _ in range(reps): #! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits, name="calq") meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # we have to feed initial_layout to calibration matrix cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) meas_calibs[0].draw("mpl") dt_now = datetime.datetime.now() print(dt_now) filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl" print(filename) # with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) # with open(filename, "wb") as f: # pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) # with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump(backend.properties(), f) retrieved_jobs = jobs retrieved_cal_job = cal_job cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in retrieved_jobs: mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors) rho = expvals_to_valid_rho(num_qubits, zne_expvals) fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
https://github.com/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, StateTomographyFitter 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 = 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), ")") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") print(str(backend)) shots = 1 << 13 reps = 8 # unused jobs = [] for _ in range(reps): #! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits, name="calq") meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # we have to feed initial_layout to calibration matrix cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) meas_calibs[0].draw("mpl") dt_now = datetime.datetime.now() print(dt_now) filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl" print(filename) # with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) # with open(filename, "wb") as f: # pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) # with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump(backend.properties(), f) retrieved_jobs = jobs retrieved_cal_job = cal_job cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in retrieved_jobs: # mit_results = meas_fitter.filter.apply(job.result()) rho = StateTomographyFitter(job.result(), t3_zne_qcs).fit(method='lstsq') fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
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/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("./") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="lq") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") t3_st_qcs = transpile(t3_st_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_st_qcs), ")") t3_st_qcs[-1].draw("mpl") # only view trotter gates # from qiskit.test.mock import FakeJakarta # backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') print("provider:", provider) backend = provider.get_backend("ibmq_jakarta") shots = 8192 reps = 8 jobs = [] for _ in range(reps): # execute job = execute(t3_st_qcs, backend, shots=shots) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout=initial_layout) print('Job ID', cal_job.job_id()) dt_now = datetime.datetime.now() print(dt_now) with open("jobs_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) with open("job_ids_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) with open("properties_jakarta" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump(backend.properties(), f) filename = "job_ids_jakarta_100step_20220412_171248_.pkl" # change here with open(filename, "rb") as f: job_ids_dict = pickle.load(f) job_ids = job_ids_dict["job_ids"] cal_job_id = job_ids_dict["cal_job_id"] retrieved_jobs = [] for job_id in job_ids: retrieved_jobs.append(backend.retrieve_job(job_id)) retrieved_cal_job = backend.retrieve_job(cal_job_id) cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') # set the target state target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in retrieved_jobs: # mit_results = meas_fitter.filter.apply(job.result()) # apply QREM rho = StateTomographyFitter(job.result(), st_qcs).fit(method='lstsq') fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids))) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../utils/") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) # Pauli Twirling print("created zne_qcs (length:", len(zne_qcs), ")") # optimization_level must be 0 # feed initial_layout here to see the picture of the circuits before casting the job t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") print(str(backend)) shots = 1 << 13 reps = 8 # unused jobs = [] for _ in range(reps): #! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits, name="calq") meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # we have to feed initial_layout to calibration matrix cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) meas_calibs[0].draw("mpl") dt_now = datetime.datetime.now() print(dt_now) filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl" print(filename) # with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) # with open(filename, "wb") as f: # pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) # with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump(backend.properties(), f) retrieved_jobs = jobs retrieved_cal_job = cal_job cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in retrieved_jobs: mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors) rho = expvals_to_valid_rho(num_qubits, zne_expvals) fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
https://github.com/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, StateTomographyFitter 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 = 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), ")") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") print(str(backend)) shots = 1 << 13 reps = 8 # unused jobs = [] for _ in range(reps): #! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits, name="calq") meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # we have to feed initial_layout to calibration matrix cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) meas_calibs[0].draw("mpl") dt_now = datetime.datetime.now() print(dt_now) filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl" print(filename) # with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) # with open(filename, "wb") as f: # pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) # with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump(backend.properties(), f) retrieved_jobs = jobs retrieved_cal_job = cal_job cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in retrieved_jobs: # mit_results = meas_fitter.filter.apply(job.result()) rho = StateTomographyFitter(job.result(), t3_zne_qcs).fit(method='lstsq') fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
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/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("./") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="lq") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") t3_st_qcs = transpile(t3_st_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_st_qcs), ")") t3_st_qcs[-1].draw("mpl") # only view trotter gates # from qiskit.test.mock import FakeJakarta # backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') print("provider:", provider) backend = provider.get_backend("ibmq_jakarta") shots = 8192 reps = 8 jobs = [] for _ in range(reps): # execute job = execute(t3_st_qcs, backend, shots=shots) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout=initial_layout) print('Job ID', cal_job.job_id()) dt_now = datetime.datetime.now() print(dt_now) with open("jobs_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) with open("job_ids_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) with open("properties_jakarta" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump(backend.properties(), f) filename = "job_ids_jakarta_100step_20220412_171248_.pkl" # change here with open(filename, "rb") as f: job_ids_dict = pickle.load(f) job_ids = job_ids_dict["job_ids"] cal_job_id = job_ids_dict["cal_job_id"] retrieved_jobs = [] for job_id in job_ids: retrieved_jobs.append(backend.retrieve_job(job_id)) retrieved_cal_job = backend.retrieve_job(cal_job_id) cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') # set the target state target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in retrieved_jobs: # mit_results = meas_fitter.filter.apply(job.result()) # apply QREM rho = StateTomographyFitter(job.result(), st_qcs).fit(method='lstsq') fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids))) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../utils/") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) # Pauli Twirling print("created zne_qcs (length:", len(zne_qcs), ")") # optimization_level must be 0 # feed initial_layout here to see the picture of the circuits before casting the job t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") print(str(backend)) shots = 1 << 13 reps = 8 # unused jobs = [] for _ in range(reps): #! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits, name="calq") meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # we have to feed initial_layout to calibration matrix cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) meas_calibs[0].draw("mpl") dt_now = datetime.datetime.now() print(dt_now) filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl" print(filename) # with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) # with open(filename, "wb") as f: # pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) # with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump(backend.properties(), f) retrieved_jobs = jobs retrieved_cal_job = cal_job cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in retrieved_jobs: mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors) rho = expvals_to_valid_rho(num_qubits, zne_expvals) fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
https://github.com/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/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("./") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="lq") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") t3_st_qcs = transpile(t3_st_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_st_qcs), ")") t3_st_qcs[-1].draw("mpl") # only view trotter gates # from qiskit.test.mock import FakeJakarta # backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') print("provider:", provider) backend = provider.get_backend("ibmq_jakarta") shots = 8192 reps = 8 jobs = [] for _ in range(reps): # execute job = execute(t3_st_qcs, backend, shots=shots) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout=initial_layout) print('Job ID', cal_job.job_id()) dt_now = datetime.datetime.now() print(dt_now) with open("jobs_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) with open("job_ids_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) with open("properties_jakarta" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump(backend.properties(), f) filename = "job_ids_jakarta_100step_20220412_171248_.pkl" # change here with open(filename, "rb") as f: job_ids_dict = pickle.load(f) job_ids = job_ids_dict["job_ids"] cal_job_id = job_ids_dict["cal_job_id"] retrieved_jobs = [] for job_id in job_ids: retrieved_jobs.append(backend.retrieve_job(job_id)) retrieved_cal_job = backend.retrieve_job(cal_job_id) cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') # set the target state target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in retrieved_jobs: # mit_results = meas_fitter.filter.apply(job.result()) # apply QREM rho = StateTomographyFitter(job.result(), st_qcs).fit(method='lstsq') fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids))) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/BOBO1997/osp_solutions
BOBO1997
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. import numpy as np from qiskit import compiler, BasicAer, QuantumRegister from qiskit.converters import circuit_to_dag from qiskit.transpiler import PassManager from qiskit.transpiler.passes import Unroller def convert_to_basis_gates(circuit): # unroll the circuit using the basis u1, u2, u3, cx, and id gates unroller = Unroller(basis=['u1', 'u2', 'u3', 'cx', 'id']) pm = PassManager(passes=[unroller]) qc = compiler.transpile(circuit, BasicAer.get_backend('qasm_simulator'), pass_manager=pm) return qc def is_qubit(qb): # check if the input is a qubit, which is in the form (QuantumRegister, int) return isinstance(qb, tuple) and isinstance(qb[0], QuantumRegister) and isinstance(qb[1], int) def is_qubit_list(qbs): # check if the input is a list of qubits for qb in qbs: if not is_qubit(qb): return False return True def summarize_circuits(circuits): """Summarize circuits based on QuantumCircuit, and four metrics are summarized. Number of qubits and classical bits, and number of operations and depth of circuits. The average statistic is provided if multiple circuits are inputed. Args: circuits (QuantumCircuit or [QuantumCircuit]): the to-be-summarized circuits """ if not isinstance(circuits, list): circuits = [circuits] ret = "" ret += "Submitting {} circuits.\n".format(len(circuits)) ret += "============================================================================\n" stats = np.zeros(4) for i, circuit in enumerate(circuits): dag = circuit_to_dag(circuit) depth = dag.depth() width = dag.width() size = dag.size() classical_bits = dag.num_cbits() op_counts = dag.count_ops() stats[0] += width stats[1] += classical_bits stats[2] += size stats[3] += depth ret = ''.join([ret, "{}-th circuit: {} qubits, {} classical bits and {} operations with depth {}\n op_counts: {}\n".format( i, width, classical_bits, size, depth, op_counts)]) if len(circuits) > 1: stats /= len(circuits) ret = ''.join([ret, "Average: {:.2f} qubits, {:.2f} classical bits and {:.2f} operations with depth {:.2f}\n".format( stats[0], stats[1], stats[2], stats[3])]) ret += "============================================================================\n" return ret
https://github.com/BOBO1997/osp_solutions
BOBO1997
import re import itertools import numpy as np import random random.seed(42) import mitiq from qiskit import QuantumCircuit, QuantumRegister from qiskit.ignis.mitigation import expectation_value # Pauli Twirling def pauli_twirling(circ: QuantumCircuit) -> QuantumCircuit: """ [internal function] This function takes a quantum circuit and return a new quantum circuit with Pauli Twirling around the CNOT gates. Args: circ: QuantumCircuit Returns: QuantumCircuit """ def apply_pauli(num: int, qb: int) -> str: if (num == 0): return f'' elif (num == 1): return f'x q[{qb}];\n' elif (num == 2): return f'y q[{qb}];\n' else: return f'z q[{qb}];\n' paulis = [(i,j) for i in range(0,4) for j in range(0,4)] paulis.remove((0,0)) paulis_map = [(0, 1), (3, 2), (3, 3), (1, 1), (1, 0), (2, 3), (2, 2), (2, 1), (2, 0), (1, 3), (1, 2), (3, 0), (3, 1), (0, 2), (0, 3)] new_circ = '' ops = circ.qasm().splitlines(True) #! split the quantum circuit into qasm operators for op in ops: if (op[:2] == 'cx'): # add Pauli Twirling around the CNOT gate num = random.randrange(len(paulis)) qbs = re.findall('q\[(.)\]', op) new_circ += apply_pauli(paulis[num][0], qbs[0]) new_circ += apply_pauli(paulis[num][1], qbs[1]) new_circ += op new_circ += apply_pauli(paulis_map[num][0], qbs[0]) new_circ += apply_pauli(paulis_map[num][1], qbs[1]) else: new_circ += op return QuantumCircuit.from_qasm_str(new_circ) def zne_wrapper(qcs, scale_factors = [1.0, 2.0, 3.0], pt = False): """ This function outputs the circuit list for zero-noise extrapolation. Args: qcs: List[QuantumCircuit], the input quantum circuits. scale_factors: List[float], to what extent the noise scales are investigated. pt: bool, whether add Pauli Twirling or not. Returns: folded_qcs: List[QuantumCircuit] """ folded_qcs = [] #! ZNE用の回路 for qc in qcs: folded_qcs.append([mitiq.zne.scaling.fold_gates_at_random(qc, scale) for scale in scale_factors]) #! ここでmitiqを使用 folded_qcs = list(itertools.chain(*folded_qcs)) #! folded_qcsを平坦化 if pt: folded_qcs = [pauli_twirling(circ) for circ in folded_qcs] return folded_qcs def make_stf_basis(n, basis_elements = ["X","Y","Z"]): """ [internal function] This function outputs all the combinations of length n string for given basis_elements. When basis_elements is X, Y, and Z (default), the output becomes the n-qubit Pauli basis. Args: n: int basis_elements: List[str] Returns: basis: List[str] """ if n == 1: return basis_elements basis = [] for i in basis_elements: sub_basis = make_stf_basis(n - 1, basis_elements) basis += [i + j for j in sub_basis] return basis def reduce_hist(hist, poses): """ [internal function] This function returns the reduced histogram to the designated positions. Args: hist: Dict[str, float] poses: List[int] Returns: ret_hist: Dict[str, float] """ n = len(poses) ret_hist = {format(i, "0" + str(n) + "b"): 0 for i in range(1 << n)} for k, v in hist.items(): pos = "" for i in range(n): pos += k[poses[i]] ret_hist[pos] += v return ret_hist def make_stf_expvals(n, stf_hists): """ [internal function] This function create the expectations under expanded basis, which are used to reconstruct the density matrix. Args: n: int, the size of classical register in the measurement results. stf_hists: List[Dict[str, float]], the input State Tomography Fitter histograms. Returns: st_expvals: List[float], the output State Tomography expectation values. """ assert len(stf_hists) == 3 ** n stf_basis = make_stf_basis(n, basis_elements=["X","Y","Z"]) st_basis = make_stf_basis(n, basis_elements=["I","X","Y","Z"]) stf_hists_dict = {basis: hist for basis, hist in zip(stf_basis, stf_hists)} st_hists_dict = {basis: stf_hists_dict.get(basis, None) for basis in st_basis} # remaining for basis in sorted(set(st_basis) - set(stf_basis)): if basis == "I" * n: continue reduction_poses = [] reduction_basis = "" for i, b in enumerate(basis): if b != "I": reduction_poses.append(n - 1 - i) # big endian reduction_basis += b # こっちはそのまま(なぜならラベルはlittle endianだから) else: reduction_basis += "Z" st_hists_dict[basis] = reduce_hist(stf_hists_dict[reduction_basis], reduction_poses) st_expvals = dict() for basis, hist in st_hists_dict.items(): if basis == "I" * n: st_expvals[basis] = 1.0 continue st_expvals[basis], _ = expectation_value(hist) return st_expvals def zne_decoder(n, result, scale_factors=[1.0, 2.0, 3.0], fac_type="lin"): """ This function applies the zero-noise extrapolation to the measured results and output the mitigated zero-noise expectation values. Args: n: int, the size of classical register in the measurement results. result: Result, the returned results from job. scale_factors: List[float], this should be the same as the zne_wrapper. fac_type: str, "lin" or "exp", whether to use LinFactory option or ExpFactory option in mitiq, to extrapolate the expectation values. Returns: zne_expvals: List[float], the mitigated zero-noise expectation values. """ hists = result.get_counts() num_scale_factors = len(scale_factors) assert len(hists) % num_scale_factors == 0 scale_wise_expvals = [] # num_scale_factors * 64 for i in range(num_scale_factors): scale_wise_hists = [hists[3 * j + i] for j in range(len(hists) // num_scale_factors)] st_expvals = make_stf_expvals(n, scale_wise_hists) scale_wise_expvals.append( list(st_expvals.values()) ) scale_wise_expvals = np.array(scale_wise_expvals) linfac = mitiq.zne.inference.LinearFactory(scale_factors) expfac = mitiq.zne.ExpFactory(scale_factors) zne_expvals = [] for i in range(4 ** n): if fac_type == "lin": zne_expvals.append( linfac.extrapolate(scale_factors, scale_wise_expvals[:, i]) ) else: zne_expvals.append( expfac.extrapolate(scale_factors, scale_wise_expvals[:, i]) ) return zne_expvals
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../utils/") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) # Pauli Twirling print("created zne_qcs (length:", len(zne_qcs), ")") # optimization_level must be 0 # feed initial_layout here to see the picture of the circuits before casting the job t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") print(str(backend)) shots = 1 << 13 reps = 8 # unused jobs = [] for _ in range(reps): #! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits, name="calq") meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # we have to feed initial_layout to calibration matrix cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) meas_calibs[0].draw("mpl") dt_now = datetime.datetime.now() print(dt_now) filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl" print(filename) # with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) # with open(filename, "wb") as f: # pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) # with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump(backend.properties(), f) retrieved_jobs = jobs retrieved_cal_job = cal_job cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in retrieved_jobs: mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors) rho = expvals_to_valid_rho(num_qubits, zne_expvals) fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
https://github.com/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/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("./") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="lq") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") t3_st_qcs = transpile(t3_st_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_st_qcs), ")") t3_st_qcs[-1].draw("mpl") # only view trotter gates # from qiskit.test.mock import FakeJakarta # backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') print("provider:", provider) backend = provider.get_backend("ibmq_jakarta") shots = 8192 reps = 8 jobs = [] for _ in range(reps): # execute job = execute(t3_st_qcs, backend, shots=shots) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout=initial_layout) print('Job ID', cal_job.job_id()) dt_now = datetime.datetime.now() print(dt_now) with open("jobs_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) with open("job_ids_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) with open("properties_jakarta" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump(backend.properties(), f) filename = "job_ids_jakarta_100step_20220412_171248_.pkl" # change here with open(filename, "rb") as f: job_ids_dict = pickle.load(f) job_ids = job_ids_dict["job_ids"] cal_job_id = job_ids_dict["cal_job_id"] retrieved_jobs = [] for job_id in job_ids: retrieved_jobs.append(backend.retrieve_job(job_id)) retrieved_cal_job = backend.retrieve_job(cal_job_id) cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') # set the target state target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in retrieved_jobs: # mit_results = meas_fitter.filter.apply(job.result()) # apply QREM rho = StateTomographyFitter(job.result(), st_qcs).fit(method='lstsq') fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids))) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../utils/") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) # Pauli Twirling print("created zne_qcs (length:", len(zne_qcs), ")") # optimization_level must be 0 # feed initial_layout here to see the picture of the circuits before casting the job t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") print(str(backend)) shots = 1 << 13 reps = 8 # unused jobs = [] for _ in range(reps): #! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits, name="calq") meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # we have to feed initial_layout to calibration matrix cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) meas_calibs[0].draw("mpl") dt_now = datetime.datetime.now() print(dt_now) filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl" print(filename) # with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) # with open(filename, "wb") as f: # pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) # with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump(backend.properties(), f) retrieved_jobs = jobs retrieved_cal_job = cal_job cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in retrieved_jobs: mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors) rho = expvals_to_valid_rho(num_qubits, zne_expvals) fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
https://github.com/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/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../utils/") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) # Pauli Twirling print("created zne_qcs (length:", len(zne_qcs), ")") # optimization_level must be 0 # feed initial_layout here to see the picture of the circuits before casting the job t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") print(str(backend)) shots = 1 << 13 reps = 8 # unused jobs = [] for _ in range(reps): #! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits, name="calq") meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # we have to feed initial_layout to calibration matrix cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) meas_calibs[0].draw("mpl") dt_now = datetime.datetime.now() print(dt_now) filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl" print(filename) # with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) # with open(filename, "wb") as f: # pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) # with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump(backend.properties(), f) retrieved_jobs = jobs retrieved_cal_job = cal_job cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in retrieved_jobs: mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors) rho = expvals_to_valid_rho(num_qubits, zne_expvals) fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
https://github.com/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/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../utils/") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) # Pauli Twirling print("created zne_qcs (length:", len(zne_qcs), ")") # optimization_level must be 0 # feed initial_layout here to see the picture of the circuits before casting the job t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") print(str(backend)) shots = 1 << 13 reps = 8 # unused jobs = [] for _ in range(reps): #! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits, name="calq") meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # we have to feed initial_layout to calibration matrix cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) meas_calibs[0].draw("mpl") dt_now = datetime.datetime.now() print(dt_now) filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl" print(filename) # with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) # with open(filename, "wb") as f: # pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) # with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump(backend.properties(), f) retrieved_jobs = jobs retrieved_cal_job = cal_job cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in retrieved_jobs: mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors) rho = expvals_to_valid_rho(num_qubits, zne_expvals) fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
https://github.com/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/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../utils/") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) # Pauli Twirling print("created zne_qcs (length:", len(zne_qcs), ")") # optimization_level must be 0 # feed initial_layout here to see the picture of the circuits before casting the job t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") print(str(backend)) shots = 1 << 13 reps = 8 # unused jobs = [] for _ in range(reps): #! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits, name="calq") meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # we have to feed initial_layout to calibration matrix cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) meas_calibs[0].draw("mpl") dt_now = datetime.datetime.now() print(dt_now) filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl" print(filename) # with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) # with open(filename, "wb") as f: # pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) # with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump(backend.properties(), f) retrieved_jobs = jobs retrieved_cal_job = cal_job cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in retrieved_jobs: mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors) rho = expvals_to_valid_rho(num_qubits, zne_expvals) fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
https://github.com/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/BOBO1997/osp_solutions
BOBO1997
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. import numpy as np from qiskit import compiler, BasicAer, QuantumRegister from qiskit.converters import circuit_to_dag from qiskit.transpiler import PassManager from qiskit.transpiler.passes import Unroller def convert_to_basis_gates(circuit): # unroll the circuit using the basis u1, u2, u3, cx, and id gates unroller = Unroller(basis=['u1', 'u2', 'u3', 'cx', 'id']) pm = PassManager(passes=[unroller]) qc = compiler.transpile(circuit, BasicAer.get_backend('qasm_simulator'), pass_manager=pm) return qc def is_qubit(qb): # check if the input is a qubit, which is in the form (QuantumRegister, int) return isinstance(qb, tuple) and isinstance(qb[0], QuantumRegister) and isinstance(qb[1], int) def is_qubit_list(qbs): # check if the input is a list of qubits for qb in qbs: if not is_qubit(qb): return False return True def summarize_circuits(circuits): """Summarize circuits based on QuantumCircuit, and four metrics are summarized. Number of qubits and classical bits, and number of operations and depth of circuits. The average statistic is provided if multiple circuits are inputed. Args: circuits (QuantumCircuit or [QuantumCircuit]): the to-be-summarized circuits """ if not isinstance(circuits, list): circuits = [circuits] ret = "" ret += "Submitting {} circuits.\n".format(len(circuits)) ret += "============================================================================\n" stats = np.zeros(4) for i, circuit in enumerate(circuits): dag = circuit_to_dag(circuit) depth = dag.depth() width = dag.width() size = dag.size() classical_bits = dag.num_cbits() op_counts = dag.count_ops() stats[0] += width stats[1] += classical_bits stats[2] += size stats[3] += depth ret = ''.join([ret, "{}-th circuit: {} qubits, {} classical bits and {} operations with depth {}\n op_counts: {}\n".format( i, width, classical_bits, size, depth, op_counts)]) if len(circuits) > 1: stats /= len(circuits) ret = ''.join([ret, "Average: {:.2f} qubits, {:.2f} classical bits and {:.2f} operations with depth {:.2f}\n".format( stats[0], stats[1], stats[2], stats[3])]) ret += "============================================================================\n" return ret
https://github.com/BOBO1997/osp_solutions
BOBO1997
import re import itertools import numpy as np import random random.seed(42) import mitiq from qiskit import QuantumCircuit, QuantumRegister from qiskit.ignis.mitigation import expectation_value # Pauli Twirling def pauli_twirling(circ: QuantumCircuit) -> QuantumCircuit: """ [internal function] This function takes a quantum circuit and return a new quantum circuit with Pauli Twirling around the CNOT gates. Args: circ: QuantumCircuit Returns: QuantumCircuit """ def apply_pauli(num: int, qb: int) -> str: if (num == 0): return f'' elif (num == 1): return f'x q[{qb}];\n' elif (num == 2): return f'y q[{qb}];\n' else: return f'z q[{qb}];\n' paulis = [(i,j) for i in range(0,4) for j in range(0,4)] paulis.remove((0,0)) paulis_map = [(0, 1), (3, 2), (3, 3), (1, 1), (1, 0), (2, 3), (2, 2), (2, 1), (2, 0), (1, 3), (1, 2), (3, 0), (3, 1), (0, 2), (0, 3)] new_circ = '' ops = circ.qasm().splitlines(True) #! split the quantum circuit into qasm operators for op in ops: if (op[:2] == 'cx'): # add Pauli Twirling around the CNOT gate num = random.randrange(len(paulis)) qbs = re.findall('q\[(.)\]', op) new_circ += apply_pauli(paulis[num][0], qbs[0]) new_circ += apply_pauli(paulis[num][1], qbs[1]) new_circ += op new_circ += apply_pauli(paulis_map[num][0], qbs[0]) new_circ += apply_pauli(paulis_map[num][1], qbs[1]) else: new_circ += op return QuantumCircuit.from_qasm_str(new_circ) def zne_wrapper(qcs, scale_factors = [1.0, 2.0, 3.0], pt = False): """ This function outputs the circuit list for zero-noise extrapolation. Args: qcs: List[QuantumCircuit], the input quantum circuits. scale_factors: List[float], to what extent the noise scales are investigated. pt: bool, whether add Pauli Twirling or not. Returns: folded_qcs: List[QuantumCircuit] """ folded_qcs = [] #! ZNE用の回路 for qc in qcs: folded_qcs.append([mitiq.zne.scaling.fold_gates_at_random(qc, scale) for scale in scale_factors]) #! ここでmitiqを使用 folded_qcs = list(itertools.chain(*folded_qcs)) #! folded_qcsを平坦化 if pt: folded_qcs = [pauli_twirling(circ) for circ in folded_qcs] return folded_qcs def make_stf_basis(n, basis_elements = ["X","Y","Z"]): """ [internal function] This function outputs all the combinations of length n string for given basis_elements. When basis_elements is X, Y, and Z (default), the output becomes the n-qubit Pauli basis. Args: n: int basis_elements: List[str] Returns: basis: List[str] """ if n == 1: return basis_elements basis = [] for i in basis_elements: sub_basis = make_stf_basis(n - 1, basis_elements) basis += [i + j for j in sub_basis] return basis def reduce_hist(hist, poses): """ [internal function] This function returns the reduced histogram to the designated positions. Args: hist: Dict[str, float] poses: List[int] Returns: ret_hist: Dict[str, float] """ n = len(poses) ret_hist = {format(i, "0" + str(n) + "b"): 0 for i in range(1 << n)} for k, v in hist.items(): pos = "" for i in range(n): pos += k[poses[i]] ret_hist[pos] += v return ret_hist def make_stf_expvals(n, stf_hists): """ [internal function] This function create the expectations under expanded basis, which are used to reconstruct the density matrix. Args: n: int, the size of classical register in the measurement results. stf_hists: List[Dict[str, float]], the input State Tomography Fitter histograms. Returns: st_expvals: List[float], the output State Tomography expectation values. """ assert len(stf_hists) == 3 ** n stf_basis = make_stf_basis(n, basis_elements=["X","Y","Z"]) st_basis = make_stf_basis(n, basis_elements=["I","X","Y","Z"]) stf_hists_dict = {basis: hist for basis, hist in zip(stf_basis, stf_hists)} st_hists_dict = {basis: stf_hists_dict.get(basis, None) for basis in st_basis} # remaining for basis in sorted(set(st_basis) - set(stf_basis)): if basis == "I" * n: continue reduction_poses = [] reduction_basis = "" for i, b in enumerate(basis): if b != "I": reduction_poses.append(n - 1 - i) # big endian reduction_basis += b # こっちはそのまま(なぜならラベルはlittle endianだから) else: reduction_basis += "Z" st_hists_dict[basis] = reduce_hist(stf_hists_dict[reduction_basis], reduction_poses) st_expvals = dict() for basis, hist in st_hists_dict.items(): if basis == "I" * n: st_expvals[basis] = 1.0 continue st_expvals[basis], _ = expectation_value(hist) return st_expvals def zne_decoder(n, result, scale_factors=[1.0, 2.0, 3.0], fac_type="lin"): """ This function applies the zero-noise extrapolation to the measured results and output the mitigated zero-noise expectation values. Args: n: int, the size of classical register in the measurement results. result: Result, the returned results from job. scale_factors: List[float], this should be the same as the zne_wrapper. fac_type: str, "lin" or "exp", whether to use LinFactory option or ExpFactory option in mitiq, to extrapolate the expectation values. Returns: zne_expvals: List[float], the mitigated zero-noise expectation values. """ hists = result.get_counts() num_scale_factors = len(scale_factors) assert len(hists) % num_scale_factors == 0 scale_wise_expvals = [] # num_scale_factors * 64 for i in range(num_scale_factors): scale_wise_hists = [hists[3 * j + i] for j in range(len(hists) // num_scale_factors)] st_expvals = make_stf_expvals(n, scale_wise_hists) scale_wise_expvals.append( list(st_expvals.values()) ) scale_wise_expvals = np.array(scale_wise_expvals) linfac = mitiq.zne.inference.LinearFactory(scale_factors) expfac = mitiq.zne.ExpFactory(scale_factors) zne_expvals = [] for i in range(4 ** n): if fac_type == "lin": zne_expvals.append( linfac.extrapolate(scale_factors, scale_wise_expvals[:, i]) ) else: zne_expvals.append( expfac.extrapolate(scale_factors, scale_wise_expvals[:, i]) ) return zne_expvals
https://github.com/jvscursulim/qamp_fall22_project
jvscursulim
import numpy as np import matplotlib.pyplot as plt from frqi import FRQI from qiskit import execute, transpile from qiskit.circuit import ClassicalRegister, QuantumCircuit, QuantumRegister, Parameter from qiskit.circuit.library.standard_gates import RYGate from qiskit.providers.aer.backends import AerSimulator from qiskit.quantum_info import DensityMatrix, state_fidelity, partial_trace from qiskit.visualization import plot_histogram from skimage import data from skimage.color import rgb2gray from skimage.transform import resize SHOTS = 8192 BACKEND = AerSimulator() image_frqi = FRQI() mcry = RYGate(theta=2*Parameter(r"$\theta$")).control(num_ctrl_qubits=2) ry_qc = QuantumCircuit(1) ry_qc.ry(theta=2*Parameter(r"$\theta$"), qubit=0) mcry_alt = ry_qc.to_gate(label="mcry").control(num_ctrl_qubits=2) test = QuantumCircuit(3) test.append(mcry, [0,1,2]) test.draw(output="mpl") qubits = QuantumRegister(size=2, name="pixels") color_qubit = QuantumRegister(size=1, name="color") bits = ClassicalRegister(size=2, name="bits_pixels") color_bit = ClassicalRegister(size=1) qc = QuantumCircuit(qubits, color_qubit, bits, color_bit) qc.h(qubit=qubits) qc.barrier() qc.draw(output="mpl") theta = np.pi/4 for i in range(4): if i == 0: qc.x(qubit=qubits) elif i == 1: qc.x(qubit=qubits[1]) elif i == 2: qc.x(qubit=qubits[0]) qc.cry(theta=theta, control_qubit=qubits[0], target_qubit=color_qubit) qc.cx(control_qubit=qubits[0], target_qubit=qubits[1]) qc.cry(theta=-theta, control_qubit=qubits[1], target_qubit=color_qubit) qc.cx(control_qubit=qubits[0], target_qubit=qubits[1]) qc.cry(theta=theta, control_qubit=qubits[1], target_qubit=color_qubit) if i == 0: qc.x(qubit=qubits) elif i == 1: qc.x(qubit=qubits[1]) elif i == 2: qc.x(qubit=qubits[0]) qc.barrier() qc.measure(qubit=qubits, cbit=bits) qc.measure(qubit=color_qubit, cbit=color_bit) qc.draw(output="mpl") print("Circuit dimensions") print(f"Circuit depth: {qc.depth()}") print(f"Circuit size: {qc.size()}") print(f"Circuit operations: {qc.count_ops()}") transpiled_qc = transpile(circuits=qc, basis_gates=["id", "x", "sx", "cx", "rz"], optimization_level=0) transpiled_qc.draw(output="mpl") print("Circuit dimensions") print(f"Circuit depth: {transpiled_qc.depth()}") print(f"Circuit size: {transpiled_qc.size()}") print(f"Circuit operations: {transpiled_qc.count_ops()}") transpiled_qc = transpile(circuits=qc, basis_gates=["id", "x", "sx", "cx", "rz"], optimization_level=1) transpiled_qc.draw(output="mpl") print("Circuit dimensions") print(f"Circuit depth: {transpiled_qc.depth()}") print(f"Circuit size: {transpiled_qc.size()}") print(f"Circuit operations: {transpiled_qc.count_ops()}") transpiled_qc = transpile(circuits=qc, basis_gates=["id", "x", "sx", "cx", "rz"], optimization_level=2) transpiled_qc.draw(output="mpl") print("Circuit dimensions") print(f"Circuit depth: {transpiled_qc.depth()}") print(f"Circuit size: {transpiled_qc.size()}") print(f"Circuit operations: {transpiled_qc.count_ops()}") transpiled_qc = transpile(circuits=qc, basis_gates=["id", "x", "sx", "cx", "rz"], optimization_level=3) transpiled_qc.draw(output="mpl") print("Circuit dimensions") print(f"Circuit depth: {transpiled_qc.depth()}") print(f"Circuit size: {transpiled_qc.size()}") print(f"Circuit operations: {transpiled_qc.count_ops()}") counts = execute(experiments=qc, backend=BACKEND, shots=SHOTS).result().get_counts() plot_histogram(counts) qubits = QuantumRegister(size=2, name="pixels") color_qubit = QuantumRegister(size=1, name="color") bits = ClassicalRegister(size=2, name="bits_pixels") color_bit = ClassicalRegister(size=1) qc = QuantumCircuit(qubits, color_qubit, bits, color_bit) qc.h(qubit=qubits) qc.barrier() theta = np.pi/4 for i in range(4): if i == 0: qc.x(qubit=qubits) elif i == 1: qc.x(qubit=qubits[1]) elif i == 2: qc.x(qubit=qubits[0]) mcry = RYGate(theta=2*theta).control(num_ctrl_qubits=2) qc.append(mcry, qargs=[qubits[0], qubits[1], color_qubit]) if i == 0: qc.x(qubit=qubits) elif i == 1: qc.x(qubit=qubits[1]) elif i == 2: qc.x(qubit=qubits[0]) qc.barrier() qc.measure(qubit=qubits, cbit=bits) qc.measure(qubit=color_qubit, cbit=color_bit) qc.draw(output="mpl") print("Circuit dimensions") print(f"Circuit depth: {qc.depth()}") print(f"Circuit size: {qc.size()}") print(f"Circuit operations: {qc.count_ops()}") transpiled_qc = transpile(circuits=qc, basis_gates=["id", "x", "sx", "cx", "rz"], optimization_level=3) transpiled_qc.draw(output="mpl") print("Circuit dimensions") print(f"Circuit depth: {transpiled_qc.depth()}") print(f"Circuit size: {transpiled_qc.size()}") print(f"Circuit operations: {transpiled_qc.count_ops()}") counts = execute(experiments=qc, backend=BACKEND, shots=SHOTS).result().get_counts() plot_histogram(counts) from fractions import Fraction a = Fraction(2*255,90) print(a) (((127*3)/17))/90 astronaut_gray = rgb2gray(data.astronaut()) plt.imshow(astronaut_gray, cmap="gray") resized_astronaut_gray = resize(astronaut_gray, (2,2)) resized_astronaut_gray pixels_intensity_list = list(resized_astronaut_gray[0]) + list(resized_astronaut_gray[1]) qubits = QuantumRegister(size=2, name="pixels") color_qubit = QuantumRegister(size=1, name="color") bits = ClassicalRegister(size=2, name="bits_pixels") color_bit = ClassicalRegister(size=1) qc = QuantumCircuit(qubits, color_qubit, bits, color_bit) qc.h(qubit=qubits) qc.barrier() for i, pixel in enumerate(pixels_intensity_list): theta = ((pixel*255*12)/17)/180 if i == 0: qc.x(qubit=qubits) elif i == 1: qc.x(qubit=qubits[1]) elif i == 2: qc.x(qubit=qubits[0]) qc.cry(theta=theta, control_qubit=qubits[0], target_qubit=color_qubit) qc.cx(control_qubit=qubits[0], target_qubit=qubits[1]) qc.cry(theta=-theta, control_qubit=qubits[1], target_qubit=color_qubit) qc.cx(control_qubit=qubits[0], target_qubit=qubits[1]) qc.cry(theta=theta, control_qubit=qubits[1], target_qubit=color_qubit) if i == 0: qc.x(qubit=qubits) elif i == 1: qc.x(qubit=qubits[1]) elif i == 2: qc.x(qubit=qubits[0]) qc.barrier() qc.measure(qubit=qubits, cbit=bits) qc.measure(qubit=color_qubit, cbit=color_bit) qc.draw(output="mpl") counts = execute(experiments=qc, backend=BACKEND, shots=SHOTS).result().get_counts() plot_histogram(counts) image = np.array([[0.5,0.5],[0.5,0.5]]) qc = image_frqi.image_quantum_circuit(image=image, measurements=True) qc.draw(output="mpl") counts = execute(experiments=qc, backend=BACKEND, shots=SHOTS).result().get_counts() plot_histogram(counts) image = np.ones((4,4)) qc = image_frqi.image_quantum_circuit(image=image, measurements=True) qc.draw(output="mpl") counts = execute(experiments=qc, backend=BACKEND, shots=SHOTS).result().get_counts() counts qc = image_frqi.image_quantum_circuit(image=resized_astronaut_gray, measurements=True) qc.draw(output="mpl") counts = execute(experiments=qc, backend=BACKEND, shots=SHOTS).result().get_counts() plot_histogram(counts) astronaut = data.astronaut() plt.imshow(astronaut) resized_astronaut = resize(astronaut, (2,2)) plt.imshow(resized_astronaut) qc = image_frqi.image_quantum_circuit(image=resized_astronaut, measurements=True) qc.draw(output="mpl") counts = execute(experiments=qc, backend=BACKEND, shots=SHOTS).result().get_counts() plot_histogram(counts) print("Circuit dimensions") print(f"Circuit depth: {qc.depth()}") print(f"Circuit size: {qc.size()}") print(f"Circuit operations: {qc.count_ops()}") image = np.ones((4,4,4)) qc = image_frqi.image_quantum_circuit(image=image, measurements=True) qc.draw(output="mpl")
https://github.com/jvscursulim/qamp_fall22_project
jvscursulim
import numpy as np import matplotlib.pyplot as plt import imageio.v2 as imageio from qiskit import execute, transpile from qiskit.circuit import ClassicalRegister, QuantumCircuit, QuantumRegister from qiskit.providers.aer.backends import AerSimulator from qiskit.visualization import plot_histogram from qiskit.quantum_info import DensityMatrix, state_fidelity, partial_trace from skimage import data from skimage.color import rgb2gray from skimage.transform import resize from neqr import NEQR image_neqr = NEQR() shots = 8192 backend = AerSimulator() astronaut = data.astronaut() astronaut.shape plt.imshow(astronaut) plt.show() gray_astro = rgb2gray(astronaut) plt.imshow(gray_astro, cmap="gray") plt.show() resized_gray_astro = resize(gray_astro, (2,2)) plt.imshow(resized_gray_astro, cmap="gray") qubits_idx = QuantumRegister(size=2, name="qubits_idx") intensity = QuantumRegister(size=8, name="intensity") bits_idx = ClassicalRegister(size=2, name="bits_idx") bits_intensity = ClassicalRegister(size=8, name="bits_intensity") qc = QuantumCircuit(intensity, qubits_idx, bits_intensity, bits_idx) qc.draw(output="mpl") qc.h(qubit=qubits_idx) qc.barrier() qc.draw(output="mpl") pixel_pos_intensity = [] for row in resized_gray_astro: for item in row: pixel_pos_intensity.append(int(np.round(255*item))) bin_list = [bin(num)[2:] for num in pixel_pos_intensity] for idx, bnum in enumerate(bin_list): if idx == 0: qc.x(qubit=qubits_idx) for pos, item in enumerate(bnum[::-1]): if item == "1": qc.mct(control_qubits=qubits_idx, target_qubit=intensity[pos]) qc.x(qubit=qubits_idx) qc.barrier() elif idx == 1: qc.x(qubit=qubits_idx[1]) for pos, item in enumerate(bnum[::-1]): if item == "1": qc.mct(control_qubits=qubits_idx, target_qubit=intensity[pos]) qc.x(qubit=qubits_idx[1]) qc.barrier() elif idx == 2: qc.x(qubit=qubits_idx[0]) for pos, item in enumerate(bnum[::-1]): if item == "1": qc.mct(control_qubits=qubits_idx, target_qubit=intensity[pos]) qc.x(qubit=qubits_idx[0]) qc.barrier() else: for pos, item in enumerate(bnum[::-1]): if item == "1": qc.mct(control_qubits=qubits_idx, target_qubit=intensity[pos]) qc.barrier() qc.draw(output="mpl") qc.measure(qubit=intensity, cbit=bits_intensity) qc.barrier() qc.measure(qubit=qubits_idx, cbit=bits_idx) qc.draw(output="mpl") print("Circuit dimensions") print(f"Circuit depth: {qc.depth()}") print(f"Circuit size: {qc.size()}") print(f"Circuit operations: {qc.count_ops()}") transpiled_qc = transpile(circuits=qc, basis_gates=["id", "x", "sx", "cx", "rz"]) transpiled_qc.draw(output="mpl") print("Circuit dimensions") print(f"Circuit depth: {transpiled_qc.depth()}") print(f"Circuit size: {transpiled_qc.size()}") print(f"Circuit operations: {transpiled_qc.count_ops()}") qcircuit = image_neqr.image_quantum_circuit(image=resized_gray_astro, measurements=True) qcircuit.draw(output="mpl") print("Circuit dimensions") print(f"Circuit depth: {qcircuit.depth()}") print(f"Circuit size: {qcircuit.size()}") print(f"Circuit operations: {qcircuit.count_ops()}") counts = execute(experiments=qcircuit, backend=backend, shots=shots).result().get_counts() plot_histogram(counts) resized_gray_astro_33 = resize(gray_astro, (3,3)) plt.imshow(resized_gray_astro_33, cmap="gray") qcircuit = image_neqr.image_quantum_circuit(image=resized_gray_astro_33, measurements=True) qcircuit.draw(output="mpl") print("Circuit dimensions") print(f"Circuit depth: {qcircuit.depth()}") print(f"Circuit size: {qcircuit.size()}") print(f"Circuit operations: {qcircuit.count_ops()}") counts = execute(experiments=qcircuit, backend=backend, shots=shots).result().get_counts() keys_list = [key for key, _ in sorted(counts.items())][:9] processed_counts = {key: counts[key] for key in keys_list} plot_histogram(processed_counts) test_matrix = np.array([[0,0,0],[0,1,0],[0,1,0],[0,0,0]]) plt.imshow(test_matrix, cmap="gray") qcircuit = image_neqr.image_quantum_circuit(image=test_matrix, measurements=True) qcircuit.draw(output="mpl") print("Circuit dimensions") print(f"Circuit depth: {qcircuit.depth()}") print(f"Circuit size: {qcircuit.size()}") print(f"Circuit operations: {qcircuit.count_ops()}") counts = execute(experiments=qcircuit, backend=backend, shots=shots).result().get_counts() plot_histogram(counts) test_matrix = np.array([[0,1,0]]) plt.imshow(test_matrix, cmap="gray") qcircuit = image_neqr.image_quantum_circuit(image=test_matrix, measurements=True) qcircuit.draw(output="mpl") print("Circuit dimensions") print(f"Circuit depth: {qcircuit.depth()}") print(f"Circuit size: {qcircuit.size()}") print(f"Circuit operations: {qcircuit.count_ops()}") counts = execute(experiments=qcircuit, backend=backend, shots=shots).result().get_counts() keys_list = [key for key, _ in sorted(counts.items())][:3] processed_counts = {key: counts[key] for key in keys_list} plot_histogram(processed_counts) test_image = np.array([[0,0],[0,0]]) plt.imshow(test_image, cmap="gray") qc = image_neqr.image_quantum_circuit(image=test_image) qc.draw(output="mpl") dm = DensityMatrix(data=qc) dm dm_reduced = partial_trace(state=dm, qargs=[8,9]) dm_reduced state_fidelity(dm_reduced, dm_reduced) test_image2 = np.array([[1,1],[1,1]]) plt.imshow(test_image2, cmap="gray") qc2 = image_neqr.image_quantum_circuit(image=test_image2) qc2.draw(output="mpl") dm2 = DensityMatrix(data=qc2) dm2 dm_reduced2 = partial_trace(state=dm2, qargs=[8,9]) dm_reduced2 state_fidelity(dm_reduced, dm_reduced2) resized_rgb_astro = resize(astronaut, (2,2)) plt.imshow(resized_rgb_astro) qc = image_neqr.image_quantum_circuit(image=resized_rgb_astro, measurements=True) qc.draw(output="mpl") print("Circuit dimensions") print(f"Circuit depth: {qc.depth()}") print(f"Circuit size: {qc.size()}") print(f"Circuit operations: {qc.count_ops()}") counts = execute(experiments=qc, backend=backend, shots=shots).result().get_counts() keys_list = [key for key, _ in sorted(counts.items())][:12] processed_counts = {key: counts[key] for key in keys_list} plot_histogram(processed_counts)
https://github.com/jvscursulim/qamp_fall22_project
jvscursulim
import matplotlib.pyplot as plt from neqr import NEQR from qiskit import execute from qiskit.providers.aer.backends import AerSimulator from qiskit.quantum_info import Statevector from skimage import data from skimage.color import rgb2gray from skimage.transform import resize neqr_class = NEQR() backend = AerSimulator() shots = 2**14 astro_pic = resize(data.astronaut(), (32,32)) gray_astro_pic = rgb2gray(astro_pic) plt.imshow(gray_astro_pic, cmap="gray") qc_gray = neqr_class.image_quantum_circuit(image=gray_astro_pic, measurements=True) counts = backend.run(qc_gray, shots=shots).result().get_counts() image = neqr_class.reconstruct_image_from_neqr_result(counts=counts, image_shape=gray_astro_pic.shape) plt.imshow(image, cmap="gray") qc_gray = neqr_class.image_quantum_circuit(image=gray_astro_pic) qc_gray.x(qubit=qc_gray.qregs[0]) qc_gray.measure(qubit=qc_gray.qregs[0], cbit=qc_gray.cregs[0]) qc_gray.measure(qubit=qc_gray.qregs[1], cbit=qc_gray.cregs[1]) counts = backend.run(qc_gray, shots=shots).result().get_counts() image = neqr_class.reconstruct_image_from_neqr_result(counts=counts, image_shape=gray_astro_pic.shape) plt.imshow(image, cmap="gray") qc_gray = neqr_class.image_quantum_circuit(image=gray_astro_pic) qc_gray.x(qubit=qc_gray.qregs[1][:int(qc_gray.qregs[1].size/2)]) qc_gray.measure(qubit=qc_gray.qregs[0], cbit=qc_gray.cregs[0]) qc_gray.measure(qubit=qc_gray.qregs[1], cbit=qc_gray.cregs[1]) counts = backend.run(qc_gray, shots=shots).result().get_counts() image = neqr_class.reconstruct_image_from_neqr_result(counts=counts, image_shape=gray_astro_pic.shape) plt.imshow(image, cmap="gray") qc_gray = neqr_class.image_quantum_circuit(image=gray_astro_pic) qc_gray.x(qubit=qc_gray.qregs[1][int(qc_gray.qregs[1].size/2):]) qc_gray.measure(qubit=qc_gray.qregs[0], cbit=qc_gray.cregs[0]) qc_gray.measure(qubit=qc_gray.qregs[1], cbit=qc_gray.cregs[1]) counts = backend.run(qc_gray, shots=shots).result().get_counts() image = neqr_class.reconstruct_image_from_neqr_result(counts=counts, image_shape=gray_astro_pic.shape) plt.imshow(image, cmap="gray") qc_gray = neqr_class.image_quantum_circuit(image=gray_astro_pic) qc_gray.x(qubit=qc_gray.qregs[1]) qc_gray.measure(qubit=qc_gray.qregs[0], cbit=qc_gray.cregs[0]) qc_gray.measure(qubit=qc_gray.qregs[1], cbit=qc_gray.cregs[1]) counts = backend.run(qc_gray, shots=shots).result().get_counts() image = neqr_class.reconstruct_image_from_neqr_result(counts=counts, image_shape=gray_astro_pic.shape) plt.imshow(image, cmap="gray") qc_gray = neqr_class.image_quantum_circuit(image=gray_astro_pic) qc_gray.x(qubit=qc_gray.qregs[0]) qc_gray.x(qubit=qc_gray.qregs[1]) qc_gray.measure(qubit=qc_gray.qregs[0], cbit=qc_gray.cregs[0]) qc_gray.measure(qubit=qc_gray.qregs[1], cbit=qc_gray.cregs[1]) counts = backend.run(qc_gray, shots=shots).result().get_counts() image = neqr_class.reconstruct_image_from_neqr_result(counts=counts, image_shape=gray_astro_pic.shape) plt.imshow(image, cmap="gray") gray_astro_pic_full_size = rgb2gray(data.astronaut()) qc_gray = neqr_class.image_quantum_circuit(image=gray_astro_pic_full_size, measurements=True) print(f"Number of qubits: {qc_gray.qregs[0].size + qc_gray.qregs[1].size}") print(f"Circuit size: {qc_gray.size()}") print(f"Circuit depth: {qc_gray.depth()}") print(f"Circuit ops: {qc_gray.count_ops()}") plt.imshow(gray_astro_pic_full_size, cmap="gray") plt.imshow(astro_pic) qc_rgb = neqr_class.image_quantum_circuit(image=astro_pic, measurements=True) counts = backend.run(qc_rgb, shots=shots*4).result().get_counts() image = neqr_class.reconstruct_image_from_neqr_result(counts=counts, image_shape=astro_pic.shape) plt.imshow(image) qc_rgb = neqr_class.image_quantum_circuit(image=astro_pic) qc_rgb.x(qubit=qc_rgb.qregs[1][:int(qc_rgb.qregs[1].size/2)]) qc_rgb.measure(qubit=qc_rgb.qregs[0], cbit=qc_rgb.cregs[0]) qc_rgb.measure(qubit=qc_rgb.qregs[1], cbit=qc_rgb.cregs[1]) qc_rgb.measure(qubit=qc_rgb.qregs[2], cbit=qc_rgb.cregs[2]) counts = backend.run(qc_rgb, shots=shots*4).result().get_counts() image = neqr_class.reconstruct_image_from_neqr_result(counts=counts, image_shape=astro_pic.shape) plt.imshow(image) qc_rgb = neqr_class.image_quantum_circuit(image=astro_pic) qc_rgb.x(qubit=qc_rgb.qregs[1][int(qc_rgb.qregs[1].size/2):]) qc_rgb.measure(qubit=qc_rgb.qregs[0], cbit=qc_rgb.cregs[0]) qc_rgb.measure(qubit=qc_rgb.qregs[1], cbit=qc_rgb.cregs[1]) qc_rgb.measure(qubit=qc_rgb.qregs[2], cbit=qc_rgb.cregs[2]) counts = backend.run(qc_rgb, shots=shots*4).result().get_counts() image = neqr_class.reconstruct_image_from_neqr_result(counts=counts, image_shape=astro_pic.shape) plt.imshow(image) qc_rgb = neqr_class.image_quantum_circuit(image=astro_pic) qc_rgb.x(qubit=qc_rgb.qregs[1]) qc_rgb.measure(qubit=qc_rgb.qregs[0], cbit=qc_rgb.cregs[0]) qc_rgb.measure(qubit=qc_rgb.qregs[1], cbit=qc_rgb.cregs[1]) qc_rgb.measure(qubit=qc_rgb.qregs[2], cbit=qc_rgb.cregs[2]) counts = backend.run(qc_rgb, shots=shots*4).result().get_counts() image = neqr_class.reconstruct_image_from_neqr_result(counts=counts, image_shape=astro_pic.shape) plt.imshow(image) qc_rgb = neqr_class.image_quantum_circuit(image=astro_pic) qc_rgb.x(qubit=qc_rgb.qregs[0]) qc_rgb.measure(qubit=qc_rgb.qregs[0], cbit=qc_rgb.cregs[0]) qc_rgb.measure(qubit=qc_rgb.qregs[1], cbit=qc_rgb.cregs[1]) qc_rgb.measure(qubit=qc_rgb.qregs[2], cbit=qc_rgb.cregs[2]) counts = backend.run(qc_rgb, shots=shots*4).result().get_counts() image = neqr_class.reconstruct_image_from_neqr_result(counts=counts, image_shape=astro_pic.shape) plt.imshow(image) qc_rgb = neqr_class.image_quantum_circuit(image=astro_pic) qc_rgb.x(qubit=qc_rgb.qregs[2]) for i in range(8): qc_rgb.mct(control_qubits=qc_rgb.qregs[2], target_qubit=qc_rgb.qregs[0][i]) qc_rgb.x(qubit=qc_rgb.qregs[2]) qc_rgb.measure(qubit=qc_rgb.qregs[0], cbit=qc_rgb.cregs[0]) qc_rgb.measure(qubit=qc_rgb.qregs[1], cbit=qc_rgb.cregs[1]) qc_rgb.measure(qubit=qc_rgb.qregs[2], cbit=qc_rgb.cregs[2]) counts = backend.run(qc_rgb, shots=shots*4).result().get_counts() image = neqr_class.reconstruct_image_from_neqr_result(counts=counts, image_shape=astro_pic.shape) plt.imshow(image) qc_rgb = neqr_class.image_quantum_circuit(image=astro_pic) qc_rgb.x(qubit=qc_rgb.qregs[2][1]) for i in range(8): qc_rgb.mct(control_qubits=qc_rgb.qregs[2], target_qubit=qc_rgb.qregs[0][i]) qc_rgb.x(qubit=qc_rgb.qregs[2][1]) qc_rgb.measure(qubit=qc_rgb.qregs[0], cbit=qc_rgb.cregs[0]) qc_rgb.measure(qubit=qc_rgb.qregs[1], cbit=qc_rgb.cregs[1]) qc_rgb.measure(qubit=qc_rgb.qregs[2], cbit=qc_rgb.cregs[2]) counts = backend.run(qc_rgb, shots=shots*4).result().get_counts() image = neqr_class.reconstruct_image_from_neqr_result(counts=counts, image_shape=astro_pic.shape) plt.imshow(image) qc_rgb = neqr_class.image_quantum_circuit(image=astro_pic) qc_rgb.x(qubit=qc_rgb.qregs[2][0]) for i in range(8): qc_rgb.mct(control_qubits=qc_rgb.qregs[2], target_qubit=qc_rgb.qregs[0][i]) qc_rgb.x(qubit=qc_rgb.qregs[2][0]) qc_rgb.measure(qubit=qc_rgb.qregs[0], cbit=qc_rgb.cregs[0]) qc_rgb.measure(qubit=qc_rgb.qregs[1], cbit=qc_rgb.cregs[1]) qc_rgb.measure(qubit=qc_rgb.qregs[2], cbit=qc_rgb.cregs[2]) counts = backend.run(qc_rgb, shots=shots*4).result().get_counts() image = neqr_class.reconstruct_image_from_neqr_result(counts=counts, image_shape=astro_pic.shape) plt.imshow(image) qc_rgb = neqr_class.image_quantum_circuit(image=astro_pic) qc_rgb.x(qubit=qc_rgb.qregs[0]) qc_rgb.x(qubit=qc_rgb.qregs[1]) qc_rgb.measure(qubit=qc_rgb.qregs[0], cbit=qc_rgb.cregs[0]) qc_rgb.measure(qubit=qc_rgb.qregs[1], cbit=qc_rgb.cregs[1]) qc_rgb.measure(qubit=qc_rgb.qregs[2], cbit=qc_rgb.cregs[2]) counts = backend.run(qc_rgb, shots=shots*4).result().get_counts() image = neqr_class.reconstruct_image_from_neqr_result(counts=counts, image_shape=astro_pic.shape) plt.imshow(image) cat = data.cat() cat_gray_resized = resize(rgb2gray(cat), (int(cat.shape[0]/10), int(cat.shape[1]/10))) plt.imshow(cat_gray_resized, cmap="gray") qc_gray = neqr_class.image_quantum_circuit(image=cat_gray_resized, measurements=True) counts = backend.run(qc_gray, shots=shots).result().get_counts() image = neqr_class.reconstruct_image_from_neqr_result(counts=counts, image_shape=cat_gray_resized.shape) plt.imshow(image, cmap="gray") print(f"Number of qubits: {qc_gray.qregs[0].size + qc_gray.qregs[1].size}") print(f"Circuit size: {qc_gray.size()}") print(f"Circuit depth: {qc_gray.depth()}") print(f"Circuit ops: {qc_gray.count_ops()}")
https://github.com/jvscursulim/qamp_fall22_project
jvscursulim
# Importing Libraries import torch from torch import cat, no_grad, manual_seed from torch.utils.data import DataLoader from torchvision import transforms import torch.optim as optim from torch.nn import ( Module, Conv2d, Linear, Dropout2d, NLLLoss ) import torch.nn.functional as F import numpy as np import matplotlib.pyplot as plt from qiskit_machine_learning.neural_networks import EstimatorQNN from qiskit_machine_learning.connectors import TorchConnector from qiskit.circuit.library import RealAmplitudes, ZZFeatureMap from qiskit import QuantumCircuit from qiskit.visualization import circuit_drawer # Imports for CIFAR-10s from torchvision.datasets import CIFAR10 from torchvision import transforms def prepare_data(X, labels_to_keep, batch_size): # Filtering out labels (originally 0-9), leaving only labels 0 and 1 filtered_indices = [i for i in range(len(X.targets)) if X.targets[i] in labels_to_keep] X.data = X.data[filtered_indices] X.targets = [X.targets[i] for i in filtered_indices] # Defining dataloader with filtered data loader = DataLoader(X, batch_size=batch_size, shuffle=True) return loader # Set seed for reproducibility manual_seed(42) # CIFAR-10 data transformation transform = transforms.Compose([ transforms.ToTensor(), # convert the images to tensors transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) # Normalization usign mean and std. ]) labels_to_keep = [0, 1] batch_size = 1 # Preparing Train Data X_train = CIFAR10(root="./data", train=True, download=True, transform=transform) train_loader = prepare_data(X_train, labels_to_keep, batch_size) # Preparing Test Data X_test = CIFAR10(root="./data", train=False, download=True, transform=transform) test_loader = prepare_data(X_test, labels_to_keep, batch_size) print(f"Training dataset size: {len(train_loader.dataset)}") print(f"Test dataset size: {len(test_loader.dataset)}") # Defining and creating QNN def create_qnn(): feature_map = ZZFeatureMap(2) # ZZFeatureMap with 2 bits, entanglement between qubits based on the pairwise product of input features. ansatz = RealAmplitudes(2, reps=1) # parameters (angles, in the case of RealAmplitudes) that are adjusted during the training process to optimize the quantum model for a specific task. qc = QuantumCircuit(2) qc.compose(feature_map, inplace=True) qc.compose(ansatz, inplace=True) qnn = EstimatorQNN( circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters, input_gradients=True, ) return qnn qnn = create_qnn() # Visualizing the QNN circuit circuit_drawer(qnn.circuit, output='mpl') # Defining torch NN module class Net(Module): def __init__(self, qnn): super().__init__() self.conv1 = Conv2d(3, 16, kernel_size=3, padding=1) self.conv2 = Conv2d(16, 32, kernel_size=3, padding=1) self.dropout = Dropout2d() self.fc1 = Linear(32 * 8 * 8, 64) self.fc2 = Linear(64, 2) # 2-dimensional input to QNN self.qnn = TorchConnector(qnn) self.fc3 = Linear(1, 1) # 1-dimensional output from QNN def forward(self, x): x = F.relu(self.conv1(x)) x = F.max_pool2d(x, 2) x = F.relu(self.conv2(x)) x = F.max_pool2d(x, 2) x = self.dropout(x) x = x.view(x.shape[0], -1) x = F.relu(self.fc1(x)) x = self.fc2(x) x = self.qnn(x) x = self.fc3(x) return cat((x, 1 - x), -1) # Creating model model = Net(qnn) device = torch.device("cuda" if torch.cuda.is_available() else "cpu") model.to(device) # Defining model, optimizer, and loss function optimizer = optim.Adam(model.parameters(), lr=0.001) loss_func = NLLLoss() # Starting training epochs = 10 loss_list = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): data, target = data.to(device), target.to(device) # Move data to GPU optimizer.zero_grad(set_to_none=True) output = model(data) loss = loss_func(output, target) loss.backward() optimizer.step() total_loss.append(loss.item()) loss_list.append(sum(total_loss) / len(total_loss)) print("Training [{:.0f}%]\tLoss: {:.4f}".format(100.0 * (epoch + 1) / epochs, loss_list[-1])) # Plotting loss convergence plt.plot(loss_list) plt.title("Hybrid NN Training Convergence") plt.xlabel("Training Iterations") plt.ylabel("Neg. Log Likelihood Loss") plt.show() # Saving the model torch.save( model.state_dict(), "model_cifar10_10EPOCHS.pt") # Loading the model qnn_cifar10 = create_qnn() model_cifar10 = Net(qnn_cifar10) model_cifar10.load_state_dict(torch.load("model_cifar10.pt")) correct = 0 total = 0 model_cifar10.eval() with torch.no_grad(): for data, target in test_loader: output = model_cifar10(data) _, predicted = torch.max(output.data, 1) total += target.size(0) correct += (predicted == target).sum().item() # Calculating and print test accuracy test_accuracy = correct / total * 100 print(f"Test Accuracy: {test_accuracy:.2f}%") # Plotting predicted labels n_samples_show = 6 count = 0 fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3)) model_cifar10.eval() with no_grad(): for batch_idx, (data, target) in enumerate(test_loader): if count == n_samples_show: break output = model_cifar10(data) if len(output.shape) == 1: output = output.reshape(1, *output.shape) pred = output.argmax(dim=1, keepdim=True) axes[count].imshow(np.transpose(data[0].numpy(), (1, 2, 0))) axes[count].set_xticks([]) axes[count].set_yticks([]) axes[count].set_title("Predicted {0}\n Actual {1}".format(pred.item(), target.item())) count += 1 plt.show()
https://github.com/jvscursulim/qamp_fall22_project
jvscursulim
import copy import time import medmnist import numpy as np import torch import torchvision import torch.nn as nn import torch.optim as optim import torch.utils.data as data import torchvision.transforms as transforms import torch.nn.functional as F from torch import cat from medmnist import INFO, Evaluator from tqdm import tqdm from qiskit.circuit import QuantumCircuit, QuantumRegister, Parameter, ParameterVector from qiskit.circuit.library import RealAmplitudes, ZZFeatureMap from qiskit.utils import QuantumInstance, algorithm_globals from qiskit.opflow import AerPauliExpectation from qiskit_aer import Aer from qiskit_machine_learning.neural_networks import CircuitQNN, TwoLayerQNN from qiskit_machine_learning.connectors import TorchConnector from skimage.transform import resize from qpie import QPIE from neqr import NEQR torch.manual_seed(42) algorithm_globals.random_seed = 42 dev = QuantumInstance(backend=Aer.get_backend("statevector_simulator")) device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") flags = ["pathmnist", "octmnist", "pneumoniamnist", "chestmnist", "dermamnist", "retinamnist", "breastmnist", "bloodmnist", "tissuemnist", "organcmnist", "organsmnist", "organmnist3d", "nodulemnist3d", "adrenalmnist3d", "fracturemnist3d", "vesselmnist3d", "synapsemnist3d"] NUM_EPOCHS = 3 BATCH_SIZE = 128 lr = 0.001 n_qubits = 4 q_depth = 6 data_flag = flags[-1] info = INFO[data_flag] task = info["task"] n_channel = info["n_channels"] n_classes = len(info["label"]) DataClass = getattr(medmnist, info["python_class"]) data_transform = transforms.Compose([transforms.ToTensor()]) train_dataset = DataClass(split='train', transform=data_transform) test_dataset = DataClass(split='test', transform=data_transform) from skimage import data brain = data.brain() import matplotlib.pyplot as plt plt.imshow(brain[9], cmap="gray") qc = NEQR().image_quantum_circuit(image=resize(train_dataset.imgs[0], (2,2,2))) qc.draw("mpl") train_loader = data.DataLoader(dataset=train_dataset, batch_size=BATCH_SIZE, shuffle=True) train_loader_at_eval = data.DataLoader(dataset=train_dataset, batch_size=2*BATCH_SIZE, shuffle=True) test_loader = data.DataLoader(dataset=test_dataset, batch_size=2*BATCH_SIZE, shuffle=False) def quantum_net(size_input_features=4, size_weights=4): """ The variational quantum circuit. """ qc = QuantumCircuit(n_qubits) qc.h(qubit=[i for i in range(n_qubits)]) input_params = ParameterVector(name="input", length=size_input_features) for idx, param in enumerate(input_params): qc.ry(theta=param, qubit=idx) for k in range(q_depth): for i in range(0, n_qubits - 1, 2): qc.cx(control_qubit=i, target_qubit=i+1) for i in range(1, n_qubits - 1, 2): qc.cx(control_qubit=i, target_qubit=i+1) params = ParameterVector(name=f"q_weights_{k}", length=size_weights) for idx, param in enumerate(params): qc.ry(theta=param, qubit=idx) qnn = CircuitQNN(qc, qc.parameters[:4], qc.parameters[4:], input_gradients=True, quantum_instance=dev ) return qnn class HybridCNN(nn.Module): def __init__(self, qnn) -> None: super().__init__() self.layer1 = nn.Sequential(nn.Conv2d(1, 2, kernel_size=5), nn.ReLU(), nn.MaxPool2d(2)) self.layer2 = nn.Sequential(nn.Conv2d(2, 16, kernel_size=5), nn.ReLU(), nn.MaxPool2d(2)) self.dropout = nn.Dropout2d() self.layer3 = nn.Sequential(nn.Linear(256, 64), nn.Linear(64, 2)) self.qnn = TorchConnector(qnn) self.layer4 = nn.Sequential( nn.Flatten(), nn.Sigmoid() ) def forward(self, x): x = self.layer1(x) x = self.layer2(x) x = self.dropout(x) x = self.layer3(x) x = x.view(x.size(0), -1) x = self.qnn(x) x = self.layer4(x) return x class HybridNet(nn.Module): def __init__(self, qnn): super().__init__() self.conv1 = nn.Conv2d(1, 2, kernel_size=5) self.conv2 = nn.Conv2d(2, 16, kernel_size=5) self.dropout = nn.Dropout2d() self.fc1 = nn.Linear(256, 64) self.fc2 = nn.Linear(64, 2) # 2-dimensional input to QNN self.qnn = TorchConnector(qnn) # Apply torch connector, weights chosen # uniformly at random from interval [-1,1]. self.fc3 = nn.Linear(1, 1) # 1-dimensional output from QNN def forward(self, x): x = F.relu(self.conv1(x)) x = F.max_pool2d(x, 2) x = F.relu(self.conv2(x)) x = F.max_pool2d(x, 2) x = self.dropout(x) x = x.view(x.shape[0], -1) x = F.relu(self.fc1(x)) x = self.fc2(x) x = self.qnn(x) # apply QNN x = self.fc3(x) return cat((x, 1 - x), -1) def create_qnn(): feature_map = ZZFeatureMap(2) ansatz = RealAmplitudes(2, reps=1) qnn = TwoLayerQNN(2, feature_map=feature_map, ansatz=ansatz, input_gradients=True, exp_val=AerPauliExpectation(), quantum_instance=dev) return qnn # qnn = quantum_net() qnn = create_qnn() model = HybridNet(qnn=qnn) if task == "multi-label, binary-class": criterion = nn.BCEWithLogitsLoss() else: criterion = nn.CrossEntropyLoss() optimizer = optim.Adam(model.parameters(), lr=0.001) for epoch in range(NUM_EPOCHS): train_correct = 0 train_total = 0 test_correct = 0 test_total = 0 model.train() for inputs, targets in tqdm(train_loader): # forward + backward + optimize optimizer.zero_grad() outputs = model(inputs) if task == 'multi-label, binary-class': targets = targets.to(torch.float32) loss = criterion(outputs, targets) else: targets = targets.squeeze().long() loss = criterion(outputs, targets) loss.backward() optimizer.step() def test(split): model.eval() y_true = torch.tensor([]) y_score = torch.tensor([]) data_loader = train_loader_at_eval if split == 'train' else test_loader with torch.no_grad(): for inputs, targets in data_loader: outputs = model(inputs) if task == 'multi-label, binary-class': targets = targets.to(torch.float32) outputs = outputs.softmax(dim=-1) else: targets = targets.squeeze().long() outputs = outputs.softmax(dim=-1) targets = targets.float().resize_(len(targets), 1) y_true = torch.cat((y_true, targets), 0) y_score = torch.cat((y_score, outputs), 0) y_true = y_true.numpy() y_score = y_score.detach().numpy() evaluator = Evaluator(data_flag, split) metrics = evaluator.evaluate(y_score) print('%s auc: %.3f acc: %.3f' % (split, *metrics)) print('==> Evaluating ...') test('train') test('test')
https://github.com/jvscursulim/qamp_fall22_project
jvscursulim
import numpy as np import matplotlib.pyplot as plt from qiskit import Aer from qiskit.circuit import ClassicalRegister, QuantumCircuit, QuantumRegister from qiskit.providers.aer.backends import AerSimulator from qiskit.visualization import plot_histogram from qpie import QPIE from skimage import data from skimage.color import rgb2gray from skimage.transform import resize statevec_sim = Aer.get_backend("statevector_simulator") backend = AerSimulator() shots = 8192 image = np.array([[0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 0, 1, 1, 1, 1, 0], [0, 0, 0, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0]]) plt.style.use("bmh") plt.xticks(range(image.shape[0])) plt.yticks(range(image.shape[1])) plt.imshow(image, extent=[0, image.shape[0], image.shape[1], 0]) qpie_class = QPIE() qc = qpie_class.image_quantum_circuit(image=image) qc.draw(output="mpl") statevec = statevec_sim.run(qc).result().get_statevector() np_statevec = np.real(statevec) np_statevec.reshape(8,8) plt.imshow(np_statevec.reshape(8,8), extent=[0, image.shape[0], image.shape[1], 0]) qc = qpie_class.image_quantum_circuit(image=image, measurements=True) qc.draw(output="mpl") counts = backend.run(qc, shots=2**20).result().get_counts() plot_histogram(counts, bar_labels=False) astro_pic = data.astronaut() plt.style.use("default") plt.imshow(astro_pic) gray_resized_astro_pic = resize(rgb2gray(astro_pic), (8,8)) plt.imshow(gray_resized_astro_pic, cmap="gray") qc = qpie_class.image_quantum_circuit(image=gray_resized_astro_pic) statevec = statevec_sim.run(qc).result().get_statevector() img = np.real(statevec).reshape(8,8) plt.imshow(img, cmap="gray") plt.style.use("bmh") threshold = lambda amp: (amp > 1e-15 or amp < -1e-15) D2n_1 = np.roll(np.identity(2**7), 1, axis=1) D2n_1 qc_h = QuantumCircuit(7) qc_h.initialize(qpie_class._amplitude_encode(image=image), range(1,7)) qc_h.h(0) qc_h.unitary(D2n_1, range(7)) qc_h.h(0) qc_h.draw("mpl") statevec_h = statevec_sim.run(qc_h).result().get_statevector() edge_scan_h = np.abs(np.array([1 if threshold(statevec_h[2*i+1].real) else 0 for i in range(2**6)])).reshape(8,8) plt.imshow(edge_scan_h, extent=[0, image.shape[0], image.shape[1], 0]) qc_v = QuantumCircuit(7) qc_v.initialize(qpie_class._amplitude_encode(image=image.T), range(1,7)) qc_v.h(0) qc_v.unitary(D2n_1, range(7)) qc_v.h(0) qc_v.draw("mpl") statevec_v = statevec_sim.run(qc_v).result().get_statevector() edge_scan_v = np.abs(np.array([1 if threshold(statevec_v[2*i+1].real) else 0 for i in range(2**6)])).reshape(8,8).T plt.imshow(edge_scan_v, extent=[0, image.shape[0], image.shape[1], 0]) edge_scan_sim = edge_scan_h | edge_scan_v plt.imshow(edge_scan_sim, extent=[0, image.shape[0], image.shape[1], 0])
https://github.com/jvscursulim/qamp_fall22_project
jvscursulim
import medmnist import matplotlib.pyplot as plt import numpy as np import torch import torch.nn as nn import torch.optim as optim import torch.utils.data as data import torchvision.transforms as transforms from medmnist import INFO, Evaluator from tqdm import tqdm from qiskit.circuit import QuantumCircuit, Parameter from qiskit.circuit.library import RealAmplitudes, ZZFeatureMap from qiskit.utils import QuantumInstance, algorithm_globals from qiskit.opflow import AerPauliExpectation from qiskit_aer import Aer from qiskit_machine_learning.neural_networks import CircuitQNN, TwoLayerQNN from qiskit_machine_learning.connectors import TorchConnector from qpie import QPIE from neqr import NEQR from skimage.transform import resize import torch.nn.functional as F flags = ["pathmnist", "octmnist", "pneumoniamnist", "chestmnist", "dermamnist", "retinamnist", "breastmnist", "bloodmnist", "tissuemnist", "organcmnist", "organsmnist", "organmnist3d", "nodulemnist3d", "adrenalmnist3d", "fracturemnist3d", "vesselmnist3d", "synapsemnist3d"] NUM_EPOCHS = 3 BATCH_SIZE = 128 lr = 0.001 data_flag = flags[2] info = INFO[data_flag] task = info["task"] n_channel = info["n_channels"] n_classes = len(info["label"]) DataClass = getattr(medmnist, info["python_class"]) data_transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize(mean=[.5], std=[.5])]) train_dataset = DataClass(split='train', transform=data_transform) test_dataset = DataClass(split='test', transform=data_transform) len(train_dataset.imgs) train_dataset.imgs.shape train_dataset.imgs[0].shape plt.imshow(train_dataset.imgs[0], cmap="gray") plt.show() train_loader = data.DataLoader(dataset=train_dataset, batch_size=BATCH_SIZE, shuffle=True) train_loader_at_eval = data.DataLoader(dataset=train_dataset, batch_size=2*BATCH_SIZE, shuffle=True) test_loader = data.DataLoader(dataset=test_dataset, batch_size=2*BATCH_SIZE, shuffle=False) class Net(nn.Module): def __init__(self, in_channels, num_classes) -> None: super(Net, self).__init__() self.layer1 = nn.Sequential(nn.Conv2d(in_channels=in_channels, out_channels=16, kernel_size=3), nn.BatchNorm2d(16), nn.ReLU()) self.layer2 = nn.Sequential(nn.Conv2d(in_channels=16, out_channels=16, kernel_size=3), nn.BatchNorm2d(16), nn.ReLU(), nn.MaxPool2d(kernel_size=2, stride=2)) self.layer3 = nn.Sequential(nn.Conv2d(in_channels=16, out_channels=64, kernel_size=3), nn.BatchNorm2d(64), nn.ReLU()) self.layer4 = nn.Sequential(nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3), nn.BatchNorm2d(64), nn.ReLU()) self.layer5 = nn.Sequential(nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, padding=1), nn.BatchNorm2d(64), nn.ReLU(), nn.MaxPool2d(kernel_size=2, stride=2)) self.fc = nn.Sequential(nn.Linear(64 * 4 * 4, 128), nn.ReLU(), nn.Linear(128, 128), nn.ReLU(), nn.Linear(128, num_classes)) def forward(self, x): x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) x = self.layer4(x) x = self.layer5(x) x = x.view(x.size(0), -1) x = self.fc(x) return x model = Net(in_channels=n_channel, num_classes=n_classes) if task == "multi-label, binary-class": criterion = nn.BCEWithLogitsLoss() else: criterion = nn.CrossEntropyLoss() optimizer = optim.Adam(model.parameters(), lr=lr) # optimizer = optim.LBFGS(model.parameters(), lr=lr) for epoch in range(NUM_EPOCHS): train_correct = 0 train_total = 0 test_correct = 0 test_total = 0 model.train() for inputs, targets in tqdm(train_loader): # forward + backward + optimize optimizer.zero_grad() outputs = model(inputs) if task == 'multi-label, binary-class': targets = targets.to(torch.float32) loss = criterion(outputs, targets) else: targets = targets.squeeze().long() loss = criterion(outputs, targets) loss.backward() optimizer.step() def test(split): model.eval() y_true = torch.tensor([]) y_score = torch.tensor([]) data_loader = train_loader_at_eval if split == 'train' else test_loader with torch.no_grad(): for inputs, targets in data_loader: outputs = model(inputs) if task == 'multi-label, binary-class': targets = targets.to(torch.float32) outputs = outputs.softmax(dim=-1) else: targets = targets.squeeze().long() outputs = outputs.softmax(dim=-1) targets = targets.float().resize_(len(targets), 1) y_true = torch.cat((y_true, targets), 0) y_score = torch.cat((y_score, outputs), 0) y_true = y_true.numpy() y_score = y_score.detach().numpy() evaluator = Evaluator(data_flag, split) metrics = evaluator.evaluate(y_score) print('%s auc: %.3f acc:%.3f' % (split, *metrics)) print('==> Evaluating ...') test('train') test('test') algorithm_globals.random_seed = 42 qi = QuantumInstance(backend=Aer.get_backend("statevector_simulator")) # device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") def create_qnn(): feature_map = ZZFeatureMap(2) ansatz = RealAmplitudes(2, reps=1) qnn = TwoLayerQNN(2, feature_map=feature_map, ansatz=ansatz, input_gradients=True, exp_val=AerPauliExpectation(), quantum_instance=qi) return qnn from torch import cat class HybridNet(nn.Module): def __init__(self, qnn): super().__init__() self.conv1 = nn.Conv2d(1, 2, kernel_size=5) self.conv2 = nn.Conv2d(2, 16, kernel_size=5) self.dropout = nn.Dropout2d() self.fc1 = nn.Linear(256, 64) self.fc2 = nn.Linear(64, 2) # 2-dimensional input to QNN self.qnn = TorchConnector(qnn) # Apply torch connector, weights chosen # uniformly at random from interval [-1,1]. self.fc3 = nn.Linear(1, 1) # 1-dimensional output from QNN def forward(self, x): x = F.relu(self.conv1(x)) x = F.max_pool2d(x, 2) x = F.relu(self.conv2(x)) x = F.max_pool2d(x, 2) x = self.dropout(x) x = x.view(x.shape[0], -1) x = F.relu(self.fc1(x)) x = self.fc2(x) x = self.qnn(x) # apply QNN x = self.fc3(x) return cat((x, 1 - x), -1) qnn = create_qnn() model4 = HybridNet(qnn) data_transform = transforms.Compose([transforms.ToTensor()]) train_dataset = DataClass(split='train', transform=data_transform) test_dataset = DataClass(split='test', transform=data_transform) train_loader = data.DataLoader(dataset=train_dataset, batch_size=BATCH_SIZE, shuffle=True) train_loader_at_eval = data.DataLoader(dataset=train_dataset, batch_size=2*BATCH_SIZE, shuffle=True) test_loader = data.DataLoader(dataset=test_dataset, batch_size=2*BATCH_SIZE, shuffle=False) if task == "multi-label, binary-class": criterion = nn.BCEWithLogitsLoss() else: criterion = nn.CrossEntropyLoss() for epoch in range(NUM_EPOCHS): train_correct = 0 train_total = 0 test_correct = 0 test_total = 0 model4.train() for inputs, targets in tqdm(train_loader): # forward + backward + optimize optimizer.zero_grad() outputs = model4(inputs) if task == 'multi-label, binary-class': targets = targets.to(torch.float32) loss = criterion(outputs, targets) else: targets = targets.squeeze().long() loss = criterion(outputs, targets) loss.backward() optimizer.step() def test(split): model4.eval() y_true = torch.tensor([]) y_score = torch.tensor([]) data_loader = train_loader_at_eval if split == 'train' else test_loader with torch.no_grad(): for inputs, targets in data_loader: outputs = model4(inputs) if task == 'multi-label, binary-class': targets = targets.to(torch.float32) outputs = outputs.softmax(dim=-1) else: targets = targets.squeeze().long() outputs = outputs.softmax(dim=-1) targets = targets.float().resize_(len(targets), 1) y_true = torch.cat((y_true, targets), 0) y_score = torch.cat((y_score, outputs), 0) y_true = y_true.numpy() y_score = y_score.detach().numpy() evaluator = Evaluator(data_flag, split) metrics = evaluator.evaluate(y_score) print('%s auc: %.3f acc: %.3f' % (split, *metrics)) print('==> Evaluating ...') test('train') test('test')
https://github.com/jvscursulim/qamp_fall22_project
jvscursulim
import numpy as np import matplotlib.pyplot as plt import torch import torch.nn.functional as F from torch import Tensor, cat, no_grad, manual_seed from torch.nn import Linear, CrossEntropyLoss, MSELoss from torch.nn import Module, Conv2d, Linear, Dropout2d, NLLLoss, MaxPool2d, Flatten, Sequential, ReLU from torch.optim import Adam, LBFGS from torch.utils.data import DataLoader from torchvision import datasets, transforms from qiskit.circuit import QuantumCircuit, Parameter from qiskit.circuit.library import RealAmplitudes, ZZFeatureMap from qiskit.utils import QuantumInstance, algorithm_globals from qiskit.opflow import AerPauliExpectation from qiskit_aer import Aer from qiskit_machine_learning.neural_networks import CircuitQNN, TwoLayerQNN from qiskit_machine_learning.connectors import TorchConnector algorithm_globals.random_seed = 42 qi = QuantumInstance(backend=Aer.get_backend("statevector_simulator")) device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") num_inputs = 2 num_samples = 20 X = 2 * algorithm_globals.random.random([num_samples, num_inputs]) - 1 y01 = 1 * (np.sum(X, axis=1) >= 0) y = 2 * y01 - 1 X_ = Tensor(X) y01_ = Tensor(y01).reshape(len(y)).long() y_ = Tensor(y).reshape(len(y), 1) for x, y_target in zip(X, y): if y_target == 1: plt.plot(x[0], x[1], "bo") else: plt.plot(x[0], x[1], "go") plt.plot([-1,1], [1,-1], "--", color="black") plt.show() qnn1 = TwoLayerQNN(num_qubits=num_inputs, quantum_instance=qi) print(qnn1.operator) initial_weights = 0.1 * (2 * algorithm_globals.random.random(qnn1.num_weights) - 1) model1 = TorchConnector(qnn1, initial_weights=initial_weights) print(f"Initial weights: {initial_weights}") model1(X_[0, :]) optimizer = LBFGS(model1.parameters()) f_loss = MSELoss(reduction="sum") model1.train() def closure(): optimizer.zero_grad() loss = f_loss(model1(X_), y_) loss.backward() print(loss.item()) return loss optimizer.step(closure) y_predict = [] for x, y_target in zip(X, y): output = model1(Tensor(x)) y_predict += [np.sign(output.detach().numpy())[0]] print(f"Accuracy: {sum(y_predict == y)/len(y)}") for x, y_target, y_p in zip(X, y, y_predict): if y_target == 1: plt.plot(x[0], x[1], "bo") else: plt.plot(x[0], x[1], "go") if y_target != y_p: plt.scatter(x[0], x[1], s=200, facecolors="none", edgecolors="r", linewidths=2) plt.plot([-1, 1], [1, -1], "--", color="black") plt.show() feature_map = ZZFeatureMap(num_inputs) ansatz = RealAmplitudes(num_qubits=num_inputs, entanglement="linear", reps=1) qc = QuantumCircuit(num_inputs) qc.append(feature_map, range(num_inputs)) qc.append(ansatz, range(num_inputs)) parity = lambda x: "{:b}".format(x).count("1") % 2 output_shape = 2 qnn2 = CircuitQNN(qc, input_params=feature_map.parameters, weight_params=ansatz.parameters, interpret=parity, output_shape=output_shape, quantum_instance=qi) initial_weights = 0.1 * (2 * algorithm_globals.random.random(qnn2.num_weights) - 1) print(f"Initial weights: {initial_weights}") model2 = TorchConnector(qnn2, initial_weights=initial_weights) optimizer = LBFGS(model2.parameters()) f_loss = CrossEntropyLoss() model2.train() def closure(): optimizer.zero_grad(set_to_none=True) loss = f_loss(model2(X_), y01_) loss.backward() print(loss.item()) return loss optimizer.step(closure) num_samples = 20 eps = 0.2 lb, ub = -np.pi, np.pi f = lambda x: np.sin(x) X = (ub - lb) * algorithm_globals.random.random([num_samples, 1]) + lb y = f(X) + eps * (2 * algorithm_globals.random.random([num_samples, 1]) - 1) plt.plot(np.linspace(lb, ub), f(np.linspace(lb, ub)), "r--") plt.plot(X, y, "bo") plt.show() param_x = Parameter("x") feature_map = QuantumCircuit(1, name="fm") feature_map.ry(param_x, 0) param_y = Parameter("y") ansatz = QuantumCircuit(1, name="vf") ansatz.ry(param_y, 0) qnn3 = TwoLayerQNN(1, feature_map=feature_map, ansatz=ansatz, quantum_instance=qi) print(qnn3.operator) initial_weights = 0.1 * (2 * algorithm_globals.random.random(qnn3.num_weights) - 1) model3 = TorchConnector(qnn3, initial_weights=initial_weights) optimizer = LBFGS(model3.parameters()) f_loss = MSELoss(reduction="sum") model3.train() def closure(): optimizer.zero_grad(set_to_none=True) loss = f_loss(model3(Tensor(X)), Tensor(y)) loss.backward() print(loss.item()) return loss optimizer.step(closure) plt.plot(np.linspace(lb, ub), f(np.linspace(lb, ub)), "r--") plt.plot(X, y, "bo") y_ = [] for x in np.linspace(lb, ub): output = model3(Tensor([x])) y_ += [output.detach().numpy()[0]] plt.plot(np.linspace(lb, ub), y_, "g-") plt.show() manual_seed(42) batch_size = 1 n_samples = 100 X_train = datasets.MNIST(root="./data", train=True, download=True, transform=transforms.Compose([transforms.ToTensor()])) idx = np.append(np.where(X_train.targets == 0)[0][:n_samples], np.where(X_train.targets == 1)[0][:n_samples]) X_train.data = X_train.data[idx] X_train.targets = X_train.targets[idx] train_loader = DataLoader(X_train, batch_size=batch_size, shuffle=True) n_samples_show = 6 data_iter = iter(train_loader) fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10,3)) while n_samples_show > 0: images, targets = data_iter.__next__() axes[n_samples_show - 1].imshow(images[0, 0].numpy().squeeze(), cmap="gray") axes[n_samples_show - 1].set_xticks([]) axes[n_samples_show - 1].set_yticks([]) axes[n_samples_show - 1].set_title(f"Labeled: {targets[0].item()}") n_samples_show -= 1 n_samples = 50 X_test = datasets.MNIST(root="./data", train=False, download=True, transform=transforms.Compose([transforms.ToTensor()])) idx = np.append(np.where(X_test.targets == 0)[0][:n_samples], np.where(X_test.targets == 1)[0][:n_samples]) X_test.data = X_test.data[idx] X_test.targets = X_test.targets[idx] test_loader = DataLoader(X_test, batch_size=batch_size, shuffle=True) def create_qnn(): feature_map = ZZFeatureMap(2) ansatz = RealAmplitudes(2, reps=1) qnn = TwoLayerQNN(2, feature_map, ansatz, input_gradients=True, exp_val=AerPauliExpectation(), quantum_instance=qi ) return qnn qnn4 = create_qnn() print(qnn4.operator) class Net(Module): def __init__(self, qnn) -> None: super().__init__() self.conv1 = Conv2d(1,2, kernel_size=5) self.conv2 = Conv2d(2,16, kernel_size=5) self.dropout = Dropout2d() self.fc1 = Linear(256, 64) self.fc2 = Linear(64, 2) self.qnn = TorchConnector(qnn) self.fc3 = Linear(1, 1) def forward(self, x): x = F.relu(self.conv1(x)) x = F.max_pool2d(x, 2) x = F.relu(self.conv2(x)) x = F.max_pool2d(x ,2) x = self.dropout(x) x = x.view(x.shape[0], -1) x = F.relu(self.fc1(x)) x = self.fc2(x) x = self.qnn(x) x = self.fc3(x) return cat((x, 1 - x), -1) model4 = Net(qnn4) # Define model, optimizer, and loss function optimizer = Adam(model4.parameters(), lr=0.001) loss_func = NLLLoss() # Start training epochs = 10 # Set number of epochs loss_list = [] # Store loss history model4.train() # Set model to training mode for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad(set_to_none=True) # Initialize gradient output = model4(data) # Forward pass loss = loss_func(output, target) # Calculate loss loss.backward() # Backward pass optimizer.step() # Optimize weights total_loss.append(loss.item()) # Store loss loss_list.append(sum(total_loss) / len(total_loss)) print("Training [{:.0f}%]\tLoss: {:.4f}".format(100.0 * (epoch + 1) / epochs, loss_list[-1])) # Plot loss convergence plt.plot(loss_list) plt.title("Hybrid NN Training Convergence") plt.xlabel("Training Iterations") plt.ylabel("Neg. Log Likelihood Loss") plt.show() torch.save(model4.state_dict(), "model4.pt") qnn5 = create_qnn() model5 = Net(qnn5) model5.load_state_dict(torch.load("model4.pt")) model5.eval() # set model to evaluation mode with no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model5(data) if len(output.shape) == 1: output = output.reshape(1, *output.shape) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print( "Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%".format( sum(total_loss) / len(total_loss), correct / len(test_loader) / batch_size * 100 ) ) n_samples_show = 6 count = 0 fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3)) model5.eval() with no_grad(): for batch_idx, (data, target) in enumerate(test_loader): if count == n_samples_show: break output = model5(data[0:1]) if len(output.shape) == 1: output = output.reshape(1, *output.shape) pred = output.argmax(dim=1, keepdim=True) axes[count].imshow(data[0].numpy().squeeze(), cmap="gray") axes[count].set_xticks([]) axes[count].set_yticks([]) axes[count].set_title("Predicted {}".format(pred.item())) count += 1
https://github.com/jvscursulim/qamp_fall22_project
jvscursulim
import time import os import copy import numpy as np import matplotlib.pyplot as plt import torch import torch.nn as nn import torch.optim as optim from torch.optim import lr_scheduler import torchvision from torchvision import datasets, transforms from qiskit.circuit import QuantumCircuit, ParameterVector from qiskit.utils import QuantumInstance from qiskit.opflow import AerPauliExpectation from qiskit_aer import Aer from qiskit_machine_learning.neural_networks import CircuitQNN from qiskit_machine_learning.connectors import TorchConnector from qiskit.opflow.expectations import PauliExpectation from qiskit.opflow.primitive_ops import PauliOp from qiskit.quantum_info.operators import Pauli torch.manual_seed(42) np.random.seed(42) os.environ["OMP_NUM_THREADS"] = "1" n_qubits = 4 # Number of qubits step = 0.0004 # Learning rate batch_size = 4 # Number of samples for each training step num_epochs = 3 # Number of training epochs q_depth = 6 # Depth of the quantum circuit (number of variational layers) gamma_lr_scheduler = 0.1 # Learning rate reduction applied every 10 epochs. q_delta = 0.01 # Initial spread of random quantum weights start_time = time.time() # Start of the computation timer dev = QuantumInstance(backend=Aer.get_backend("statevector_simulator")) device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") data_dir = "data/hymenoptera_data" data_transforms = { "train": transforms.Compose( [ # transforms.RandomResizedCrop(224), # uncomment for data augmentation # transforms.RandomHorizontalFlip(), # uncomment for data augmentation transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), # Normalize input channels using mean values and standard deviations of ImageNet. transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), ] ), "val": transforms.Compose( [ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), ] ), } image_datasets = { x if x == "train" else "validation": datasets.ImageFolder( os.path.join(data_dir, x), data_transforms[x] ) for x in ["train", "val"] } dataset_sizes = {x: len(image_datasets[x]) for x in ["train", "validation"]} class_names = image_datasets["train"].classes # Initialize dataloader dataloaders = { x: torch.utils.data.DataLoader(image_datasets[x], batch_size=batch_size, shuffle=True) for x in ["train", "validation"] } # function to plot images def imshow(inp, title=None): """Display image from tensor.""" inp = inp.numpy().transpose((1, 2, 0)) # Inverse of the initial normalization operation. mean = np.array([0.485, 0.456, 0.406]) std = np.array([0.229, 0.224, 0.225]) inp = std * inp + mean inp = np.clip(inp, 0, 1) plt.imshow(inp) if title is not None: plt.title(title) # Get a batch of training data inputs, classes = next(iter(dataloaders["validation"])) # Make a grid from batch out = torchvision.utils.make_grid(inputs) imshow(out, title=[class_names[x] for x in classes]) dataloaders = { x: torch.utils.data.DataLoader(image_datasets[x], batch_size=batch_size, shuffle=True) for x in ["train", "validation"] } def quantum_net(size_input_features=4, size_weights=4): """ The variational quantum circuit. """ qc = QuantumCircuit(n_qubits) qc.h(qubit=[i for i in range(n_qubits)]) input_params = ParameterVector(name="input", length=size_input_features) for idx, param in enumerate(input_params): qc.ry(theta=param, qubit=idx) for k in range(q_depth): for i in range(0, n_qubits - 1, 2): qc.cx(control_qubit=i, target_qubit=i+1) for i in range(1, n_qubits - 1, 2): qc.cx(control_qubit=i, target_qubit=i+1) params = ParameterVector(name=f"q_weights_{k}", length=size_weights) for idx, param in enumerate(params): qc.ry(theta=param, qubit=idx) qnn = CircuitQNN(qc, qc.parameters[:4], qc.parameters[4:], input_gradients=True, quantum_instance=dev ) return qnn class DressedQuantumNet(nn.Module): """ Torch module implementing the *dressed* quantum net. """ def __init__(self, qnn): """ Definition of the *dressed* layout. """ super().__init__() self.pre_net = nn.Linear(512, n_qubits) self.qnn = TorchConnector(qnn) self.post_net = nn.Linear(16, 2) def forward(self, x): """ Defining how tensors are supposed to move through the *dressed* quantum net. """ x = self.pre_net(x) x = torch.tanh(x) * np.pi/2.0 x = self.qnn(x) x = self.post_net(x) return x model_hybrid = torchvision.models.resnet18(pretrained=True) for param in model_hybrid.parameters(): param.requires_grad = False # Notice that model_hybrid.fc is the last layer of ResNet18 model_hybrid.fc = DressedQuantumNet(qnn=quantum_net()) # Use CUDA or CPU according to the "device" object. model_hybrid = model_hybrid.to(device) criterion = nn.CrossEntropyLoss() optimizer_hybrid = optim.Adam(model_hybrid.fc.parameters(), lr=step) exp_lr_scheduler = lr_scheduler.StepLR( optimizer_hybrid, step_size=10, gamma=gamma_lr_scheduler ) def train_model(model, criterion, optimizer, scheduler, num_epochs): since = time.time() best_model_wts = copy.deepcopy(model.state_dict()) best_acc = 0.0 best_loss = 10000.0 # Large arbitrary number best_acc_train = 0.0 best_loss_train = 10000.0 # Large arbitrary number print("Training started:") for epoch in range(num_epochs): # Each epoch has a training and validation phase for phase in ["train", "validation"]: if phase == "train": # Set model to training mode model.train() else: # Set model to evaluate mode model.eval() running_loss = 0.0 running_corrects = 0 # Iterate over data. n_batches = dataset_sizes[phase] // batch_size it = 0 for inputs, labels in dataloaders[phase]: since_batch = time.time() batch_size_ = len(inputs) inputs = inputs.to(device) labels = labels.to(device) optimizer.zero_grad() # Track/compute gradient and make an optimization step only when training with torch.set_grad_enabled(phase == "train"): outputs = model(inputs) _, preds = torch.max(outputs, 1) loss = criterion(outputs, labels) if phase == "train": loss.backward() optimizer.step() # Print iteration results running_loss += loss.item() * batch_size_ batch_corrects = torch.sum(preds == labels.data).item() running_corrects += batch_corrects print( "Phase: {} Epoch: {}/{} Iter: {}/{} Batch time: {:.4f}".format( phase, epoch + 1, num_epochs, it + 1, n_batches + 1, time.time() - since_batch, ), end="\r", flush=True, ) it += 1 # Print epoch results epoch_loss = running_loss / dataset_sizes[phase] epoch_acc = running_corrects / dataset_sizes[phase] print( "Phase: {} Epoch: {}/{} Loss: {:.4f} Acc: {:.4f} ".format( "train" if phase == "train" else "validation ", epoch + 1, num_epochs, epoch_loss, epoch_acc, ) ) # Check if this is the best model wrt previous epochs if phase == "validation" and epoch_acc > best_acc: best_acc = epoch_acc best_model_wts = copy.deepcopy(model.state_dict()) if phase == "validation" and epoch_loss < best_loss: best_loss = epoch_loss if phase == "train" and epoch_acc > best_acc_train: best_acc_train = epoch_acc if phase == "train" and epoch_loss < best_loss_train: best_loss_train = epoch_loss # Update learning rate if phase == "train": scheduler.step() # Print final results model.load_state_dict(best_model_wts) time_elapsed = time.time() - since print( "Training completed in {:.0f}m {:.0f}s".format(time_elapsed // 60, time_elapsed % 60) ) print("Best test loss: {:.4f} | Best test accuracy: {:.4f}".format(best_loss, best_acc)) return model model_hybrid = train_model( model_hybrid, criterion, optimizer_hybrid, exp_lr_scheduler, num_epochs=num_epochs ) def visualize_model(model, num_images=6, fig_name="Predictions"): images_so_far = 0 _fig = plt.figure(fig_name) model.eval() with torch.no_grad(): for _i, (inputs, labels) in enumerate(dataloaders["validation"]): inputs = inputs.to(device) labels = labels.to(device) outputs = model(inputs) _, preds = torch.max(outputs, 1) for j in range(inputs.size()[0]): images_so_far += 1 ax = plt.subplot(num_images // 2, 2, images_so_far) ax.axis("off") ax.set_title("[{}]".format(class_names[preds[j]])) imshow(inputs.cpu().data[j]) if images_so_far == num_images: return visualize_model(model_hybrid, num_images=batch_size) plt.show()
https://github.com/jvscursulim/qamp_fall22_project
jvscursulim
import numpy as np from frqi import FRQI from qiskit import execute from qiskit.providers.aer.backends import AerSimulator from skimage import data from skimage.transform import resize class TestFRQI: GATE_SET = {"h", "x", "measure", "barrier", "ccry"} SHOTS = 8192 BACKEND = AerSimulator() FRQI = FRQI() IMAGE1 = np.array([[0, 0], [0, 0]]) IMAGE2 = np.array([[1, 1], [1, 1]]) IMAGE3 = np.array([[0.5, 0.5], [0.5, 0.5]]) ASTRONAUT = resize(data.astronaut(), (2, 2)) def test_result_image1(self): expected_keys = ["0 00", "0 01", "0 10", "0 11"] qc = self.FRQI.image_quantum_circuit(image=self.IMAGE1, measurements=True) counts = ( execute(experiments=qc, backend=self.BACKEND, shots=self.SHOTS) .result() .get_counts() ) result = [int(key in expected_keys) for key, _ in counts.items()] true_list = np.ones(len(expected_keys)) assert np.allclose(result, true_list) def test_result_image2(self): expected_keys = ["1 00", "1 01", "1 10", "1 11"] qc = self.FRQI.image_quantum_circuit(image=self.IMAGE2, measurements=True) counts = ( execute(experiments=qc, backend=self.BACKEND, shots=self.SHOTS) .result() .get_counts() ) result = [int(key in expected_keys) for key, _ in counts.items()] true_list = np.ones(len(expected_keys)) assert np.allclose(result, true_list) def test_result_image3(self): expected_keys = ["0 00", "0 01", "0 10", "0 11", "1 00", "1 01", "1 10", "1 11"] qc = self.FRQI.image_quantum_circuit(image=self.IMAGE3, measurements=True) counts = ( execute(experiments=qc, backend=self.BACKEND, shots=self.SHOTS) .result() .get_counts() ) result = [int(key in expected_keys) for key, _ in counts.items()] true_list = np.ones(len(expected_keys)) assert np.allclose(result, true_list) def test_result_rgb_image(self): expected_keys = [ "0 0 0 00", "0 0 0 01", "0 0 0 10", "0 0 0 11", "0 0 1 00", "0 0 1 01", "0 0 1 10", "0 0 1 11", "0 1 0 00", "0 1 0 01", "0 1 0 10", "0 1 0 11", "0 1 1 00", "0 1 1 01", "0 1 1 10", "0 1 1 11", "1 0 0 00", "1 0 0 01", "1 0 0 10", "1 0 0 11", "1 0 1 00", "1 0 1 01", "1 0 1 10", "1 0 1 11", "1 1 0 00", "1 1 0 01", "1 1 0 10", "1 1 0 11", "1 1 1 00", "1 1 1 01", "1 1 1 10", "1 1 1 11", ] qc = self.FRQI.image_quantum_circuit(image=self.ASTRONAUT, measurements=True) counts = ( execute(experiments=qc, backend=self.BACKEND, shots=self.SHOTS) .result() .get_counts() ) result = [int(key in expected_keys) for key, _ in counts.items()] true_list = np.ones(len(expected_keys)) assert np.allclose(result, true_list) def test_image_qc_gates(self): qc = self.FRQI.image_quantum_circuit(image=self.IMAGE1, measurements=True) qc_rgb = self.FRQI.image_quantum_circuit( image=self.ASTRONAUT, measurements=True ) circuit_gates = list(qc.count_ops()) result_test_gates = [gate in self.GATE_SET for gate in circuit_gates] circuit_gates_rgb = list(qc_rgb.count_ops()) result_test_gates_rgb = [gate in self.GATE_SET for gate in circuit_gates_rgb] gates_true_list = np.ones(len(result_test_gates)) assert np.allclose(result_test_gates, gates_true_list) assert np.allclose(result_test_gates_rgb, gates_true_list) def test_image_qc_gate_count(self): qc = self.FRQI.image_quantum_circuit(image=self.IMAGE1, measurements=True) qc_rgb = self.FRQI.image_quantum_circuit( image=self.ASTRONAUT, measurements=True ) qc_gates_dict = dict(qc.count_ops()) del qc_gates_dict["barrier"] qc_gates_dict_rgb = dict(qc_rgb.count_ops()) del qc_gates_dict_rgb["barrier"] aux_bin_list = [ bin(i)[2:] for i in range(self.IMAGE1.shape[0] * self.IMAGE1.shape[1]) ] aux_len_bin_list = [len(binary) for binary in aux_bin_list] max_length = max(aux_len_bin_list) binary_list = [] for bnum in aux_bin_list: if len(bnum) < max_length: new_binary = "" for _ in range(max_length - len(bnum)): new_binary += "0" new_binary += bnum binary_list.append(new_binary) else: binary_list.append(bnum) hadamard_count = qc.qregs[0].size measure_count = qc.cregs[0].size + qc.cregs[1].size mcry_count = 2 * qc.qregs[0].size x_count = np.array( [2 * str.count(bnumber, "0") for bnumber in binary_list] ).sum() qc_count_gate_list = [ qc_gates_dict["h"], qc_gates_dict["measure"], qc_gates_dict["x"], qc_gates_dict["ccry"], ] qc_rgb_count_gate_list = [ qc_gates_dict_rgb["h"], qc_gates_dict_rgb["measure"], qc_gates_dict_rgb["x"], qc_gates_dict_rgb["ccry"], ] count_gate_list = [hadamard_count, measure_count, x_count, mcry_count] count_gate_list_rgb = [ hadamard_count, measure_count + 2, 3 * x_count, 3 * mcry_count, ] assert np.allclose(qc_count_gate_list, count_gate_list) assert np.allclose(qc_rgb_count_gate_list, count_gate_list_rgb)
https://github.com/jvscursulim/qamp_fall22_project
jvscursulim
import pytest import numpy as np from neqr import NEQR from qiskit import execute from qiskit.providers.aer.backends import AerSimulator from skimage import data from skimage.color import rgb2gray from skimage.transform import resize class TestNEQR: GATE_SET = {"ccx", "mcx", "h", "x", "measure", "barrier"} ASTRONAUT_IMAGE_GRAY = rgb2gray(data.astronaut()) ASTRONAUT_IMAGE_RGB = data.astronaut() ZERO_IMAGE_MATRIX = np.array([[0, 0, 0], [0, 1, 0], [0, 1, 0], [0, 0, 0]]) NEQR = NEQR() SHOTS = 8192 BACKEND = AerSimulator() def _prepare_pixel_intensity_binary_dict(self, image_matrix: np.ndarray) -> dict: if len(image_matrix.shape) == 2: n = 1 else: if image_matrix.shape[2] == 3: n = len(image_matrix.shape) key_value_list = [] else: n = 1 for i in range(n): pixels_intensity = [] if n == 1: pixels_matrix = image_matrix else: pixels_matrix = image_matrix[:, :, i] if len(image_matrix.shape) == 3 and n == 1: for row in pixels_matrix: for column in row: for entry in column: intensity = int(np.round(255 * entry)) pixels_intensity.append(intensity) else: for row in pixels_matrix: for entry in row: intensity = int(np.round(255 * entry)) pixels_intensity.append(intensity) aux_binary_pixel_intensity = [ bin(p_intensity)[2:] for p_intensity in pixels_intensity ] aux_len_bin_list = [ len(binary_num) for binary_num in aux_binary_pixel_intensity ] max_length = max(aux_len_bin_list) binary_pixel_intensity = [] for bnum in aux_binary_pixel_intensity: if len(bnum) < max_length: new_binary = "" for _ in range(max_length - len(bnum)): new_binary += "0" new_binary += bnum binary_pixel_intensity.append(new_binary) else: binary_pixel_intensity.append(bnum) aux_bin_list = [bin(i)[2:] for i in range(len(binary_pixel_intensity))] aux_len_bin_list = [len(binary_num) for binary_num in aux_bin_list] max_length = max(aux_len_bin_list) binary_list = [] for bnum in aux_bin_list: if len(bnum) < max_length: new_binary = "" for _ in range(max_length - len(bnum)): new_binary += "0" new_binary += bnum binary_list.append(new_binary) else: binary_list.append(bnum) if n != 1: if i == 0: new_binary_list = ["00 " + str_bin for str_bin in binary_list] elif i == 1: new_binary_list = ["01 " + str_bin for str_bin in binary_list] elif i == 2: new_binary_list = ["10 " + str_bin for str_bin in binary_list] key_value_list.append( list(zip(new_binary_list, binary_pixel_intensity)) ) if n == 1: pixel_intensity_binary_dict = { tp[0]: tp[1] for tp in zip(binary_list, binary_pixel_intensity) } else: pixel_intensity_binary_dict = {} for item in key_value_list: for tp in item: pixel_intensity_binary_dict[tp[0]] = tp[1] return pixel_intensity_binary_dict def _process_counts(self, counts: dict, image_matrix: np.ndarray) -> dict: if len(image_matrix.shape) == 3: num_pixels = image_matrix.shape[0] * image_matrix.shape[1] * 3 keys_list = [key for key, _ in sorted(counts.items())][:num_pixels] processed_counts = { key.split(" ")[0] + " " + key.split(" ")[1]: key.split(" ")[2] for key in keys_list } else: num_pixels = image_matrix.shape[0] * image_matrix.shape[1] keys_list = [key for key, _ in sorted(counts.items())][:num_pixels] processed_counts = { key.split(" ")[0]: key.split(" ")[1] for key in keys_list } return processed_counts def test_image_qc_non_square_matrix_encoding(self): qc = self.NEQR.image_quantum_circuit( image=self.ZERO_IMAGE_MATRIX, measurements=True ) counts = ( execute(experiments=qc, backend=self.BACKEND, shots=self.SHOTS) .result() .get_counts() ) processed_counts = self._process_counts( counts=counts, image_matrix=self.ZERO_IMAGE_MATRIX ) pixel_intensity_dict = self._prepare_pixel_intensity_binary_dict( image_matrix=self.ZERO_IMAGE_MATRIX ) results = [ int(value == processed_counts[key]) for key, value in pixel_intensity_dict.items() ] pixel_true_list = np.ones(len(results)) assert np.allclose(results, pixel_true_list) def test_image_qc_non_square_matrix_gates(self): qc = self.NEQR.image_quantum_circuit( image=self.ZERO_IMAGE_MATRIX, measurements=True ) circuit_gates = list(qc.count_ops()) result_test_gates = [gate in self.GATE_SET for gate in circuit_gates] gates_true_list = np.ones(len(result_test_gates)) assert np.allclose(result_test_gates, gates_true_list) def test_image_qc_non_square_matrix_gate_count(self): qc = self.NEQR.image_quantum_circuit( image=self.ZERO_IMAGE_MATRIX, measurements=True ) qc_gates_dict = dict(qc.count_ops()) del qc_gates_dict["barrier"] pixel_intensity_dict = self._prepare_pixel_intensity_binary_dict( image_matrix=self.ZERO_IMAGE_MATRIX ) hadamard_count = qc.qregs[1].size measure_count = qc.cregs[0].size + qc.cregs[1].size x_count = np.array( [ 2 * str.count(key, "0") for key, value in pixel_intensity_dict.items() if value != "0" * 8 ] ).sum() ccx_or_mcx_count = np.array( [str.count(bnum, "1") for _, bnum in pixel_intensity_dict.items()] ).sum() qc_count_gate_list = [ qc_gates_dict["h"], qc_gates_dict["measure"], qc_gates_dict["x"], qc_gates_dict["mcx"], ] count_gate_list = [hadamard_count, measure_count, x_count, ccx_or_mcx_count] assert np.allclose(qc_count_gate_list, count_gate_list) def test_image_qc_square_matrix_encoding(self): resized_astronaut_pic = resize(self.ASTRONAUT_IMAGE_GRAY, (2, 2)) qc = self.NEQR.image_quantum_circuit( image=resized_astronaut_pic, measurements=True ) counts = ( execute(experiments=qc, backend=self.BACKEND, shots=self.SHOTS) .result() .get_counts() ) processed_counts = self._process_counts( counts=counts, image_matrix=resized_astronaut_pic ) pixel_intensity_dict = self._prepare_pixel_intensity_binary_dict( image_matrix=resized_astronaut_pic ) results = [ int(value == processed_counts[key]) for key, value in pixel_intensity_dict.items() ] pixel_true_list = np.ones(len(results)) assert np.allclose(results, pixel_true_list) def test_image_qc_square_matrix_gates(self): resized_astronaut_pic = resize(self.ASTRONAUT_IMAGE_GRAY, (2, 2)) qc = self.NEQR.image_quantum_circuit( image=resized_astronaut_pic, measurements=True ) circuit_gates = list(qc.count_ops()) result_test_gates = [gate in self.GATE_SET for gate in circuit_gates] gates_true_list = np.ones(len(result_test_gates)) assert np.allclose(result_test_gates, gates_true_list) def test_image_rgb_qc_square_matrix_gates(self): resized_astronaut_pic = resize(self.ASTRONAUT_IMAGE_RGB, (2, 2)) qc = self.NEQR.image_quantum_circuit( image=resized_astronaut_pic, measurements=True ) circuit_gates = list(qc.count_ops()) result_test_gates = [gate in self.GATE_SET for gate in circuit_gates] gates_true_list = np.ones(len(result_test_gates)) assert np.allclose(result_test_gates, gates_true_list) def test_image_qc_square_matrix_gate_count(self): resized_astronaut_pic = resize(self.ASTRONAUT_IMAGE_GRAY, (2, 2)) qc = self.NEQR.image_quantum_circuit( image=resized_astronaut_pic, measurements=True ) qc_gates_dict = dict(qc.count_ops()) del qc_gates_dict["barrier"] pixel_intensity_dict = self._prepare_pixel_intensity_binary_dict( image_matrix=resized_astronaut_pic ) hadamard_count = qc.qregs[1].size measure_count = qc.cregs[0].size + qc.cregs[1].size x_count = np.array( [ 2 * str.count(key, "0") for key, value in pixel_intensity_dict.items() if value != "0" * 8 ] ).sum() ccx_or_mcx_count = np.array( [str.count(bnum, "1") for _, bnum in pixel_intensity_dict.items()] ).sum() qc_count_gate_list = [ qc_gates_dict["h"], qc_gates_dict["measure"], qc_gates_dict["x"], qc_gates_dict["ccx"], ] count_gate_list = [hadamard_count, measure_count, x_count, ccx_or_mcx_count] assert np.allclose(qc_count_gate_list, count_gate_list) def test_image_rgb_qc_square_matrix_gate_count(self): resized_astronaut_pic = resize(self.ASTRONAUT_IMAGE_RGB, (2, 2)) qc = self.NEQR.image_quantum_circuit( image=resized_astronaut_pic, measurements=True ) qc_gates_dict = dict(qc.count_ops()) del qc_gates_dict["barrier"] pixel_intensity_dict = self._prepare_pixel_intensity_binary_dict( image_matrix=resized_astronaut_pic ) hadamard_count = qc.qregs[1].size + qc.qregs[2].size measure_count = qc.cregs[0].size + qc.cregs[1].size + qc.cregs[2].size x_count = np.array( [ 2 * str.count(key, "0") for key, value in pixel_intensity_dict.items() if value != "0" * 8 ] ).sum() ccx_or_mcx_count = np.array( [str.count(bnum, "1") for _, bnum in pixel_intensity_dict.items()] ).sum() qc_count_gate_list = [ qc_gates_dict["h"], qc_gates_dict["measure"], qc_gates_dict["x"], qc_gates_dict["mcx"], ] count_gate_list = [hadamard_count, measure_count, x_count, ccx_or_mcx_count] assert np.allclose(qc_count_gate_list, count_gate_list) def test_image_rgb_qc_square_matrix_encoding(self): resized_astronaut_pic = resize(self.ASTRONAUT_IMAGE_RGB, (2, 2)) qc = self.NEQR.image_quantum_circuit( image=resized_astronaut_pic, measurements=True ) counts = ( execute(experiments=qc, backend=self.BACKEND, shots=self.SHOTS) .result() .get_counts() ) processed_counts = self._process_counts( counts=counts, image_matrix=resized_astronaut_pic ) pixel_intensity_dict = self._prepare_pixel_intensity_binary_dict( image_matrix=resized_astronaut_pic ) results = [ int(value == processed_counts[key]) for key, value in pixel_intensity_dict.items() ] pixel_true_list = np.ones(len(results)) assert np.allclose(results, pixel_true_list) def test_reconstruct_gray_image_from_neqr_result(self): resized_astronaut_pic = resize(self.ASTRONAUT_IMAGE_GRAY, (2, 2)) resized_astronaut_pic = np.round(resized_astronaut_pic * 255) / 255 qc = self.NEQR.image_quantum_circuit( image=resized_astronaut_pic, measurements=True ) counts = ( execute(experiments=qc, backend=self.BACKEND, shots=self.SHOTS) .result() .get_counts() ) image = self.NEQR.reconstruct_image_from_neqr_result( counts=counts, image_shape=resized_astronaut_pic.shape ) assert np.allclose(resized_astronaut_pic, image) def test_reconstruct_rgb_image_from_neqr_result(self): resized_astronaut_pic = resize(self.ASTRONAUT_IMAGE_RGB, (2, 2)) resized_astronaut_pic = np.round(resized_astronaut_pic * 255) / 255 qc = self.NEQR.image_quantum_circuit( image=resized_astronaut_pic, measurements=True ) counts = ( execute(experiments=qc, backend=self.BACKEND, shots=self.SHOTS) .result() .get_counts() ) image = self.NEQR.reconstruct_image_from_neqr_result( counts=counts, image_shape=resized_astronaut_pic.shape ) assert np.allclose(resized_astronaut_pic, image) def test_reconstruct_image_value_error(self): counts = { "00 11111111": 100, "01 11111111": 100, "10 11111111": 100, "11 11111111": 100, } with pytest.raises( ValueError, match="Image shape should be a tuple of length 2 for images in gray scale or a tuple of length 3 for RGB images and 3D images!", ): _ = self.NEQR.reconstruct_image_from_neqr_result( counts=counts, image_shape=(2, 2, 3, 1) ) def test_3d_images(self): image_3d = np.array( [ [[0.48235294, 0.48235294], [0.45098039, 0.52156863]], [[0.52156863, 0.50980392], [0.46666667, 0.4745098]], ] ) qc = self.NEQR.image_quantum_circuit(image=image_3d, measurements=True) counts = ( execute(experiments=qc, backend=self.BACKEND, shots=self.SHOTS) .result() .get_counts() ) image = self.NEQR.reconstruct_image_from_neqr_result( counts=counts, image_shape=image_3d.shape ) assert np.allclose(image_3d, image)
https://github.com/antontutoveanu/quantum-tic-tac-toe
antontutoveanu
# 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/antontutoveanu/quantum-tic-tac-toe
antontutoveanu
from termcolor import colored, cprint import json from qiskit import * from qiskit.tools.monitor import job_monitor def resetBoard(): return {'1': [' ', 0] , '2': [' ', 0], '3': [' ', 0], '4': [' ', 0], '5': [' ', 0], '6': [' ', 0], '7': [' ', 0], '8': [' ', 0], '9': [' ', 0]} def printBoard(board): print() colour = 0 for i in range (1,10): if board[str(i)][1] == 0: cprint(board[str(i)][0], end='') else: if (colour == 0 or colour == 1): cprint(board[str(i)][0], 'red', end='') colour = colour + 1 elif (colour == 2 or colour == 3): cprint(board[str(i)][0], 'green', end='') colour = colour + 1 elif (colour == 4 or colour == 5): cprint(board[str(i)][0], 'blue', end='') colour = colour + 1 elif (colour == 6 or colour == 7): cprint(board[str(i)][0], 'yellow', end='') colour = colour + 1 if i % 3 == 0: print() if i != 9: print('-+-+-') else: cprint('|', end='') def make_classic_move(theBoard, turn, count, circuit): valid_move = 0 valid_moves = ["1", "2", "3", "4", "5", "6", "7", "8", "9"] while (not valid_move): print() print("Which location? (1-9) ", end='') location = input() if location in valid_moves: if theBoard[location][0] == ' ': valid_move = 1 # set the location's marker theBoard[location][0] = turn # increment counter (total markers on board) *when this = 9, collapse the board, also called measurement count += 1 # set marker's state (classical or quantum) theBoard[location][1] = 0 # classical (not flashing on screen) # set qubit[location] to ON, 100% = 1 # one pauli X gate circuit.x(int(location)-1) print(circuit.draw()) else: print() print("That place is already filled.") else: print("Please select a square from 1-9") return theBoard, turn, count, circuit def make_quantum_move(theBoard, count, circuit, turn): valid_move = False valid_moves = ["1", "2", "3", "4", "5", "6", "7", "8", "9"] while (not valid_move): print() print("Which location? (1-9) ") location1 = input() print("Which location? (1-9) ") location2 = input() if theBoard[location1][0] == ' ' and theBoard[location2][0] == ' ' and location1 != location2: # set the location's marker theBoard[location1][0] = turn theBoard[location2][0] = turn # increment counter (total markers on board) *when this = 9, collapse the board, also called measurement count += 2 # set marker's state (classical or quantum) theBoard[location1][1] = 1 # quantum (flashing on screen) theBoard[location2][1] = 1 # quantum (flashing on screen) # set qubit[location1], qubit[location2] to superposition/entangled # hadamard gates circuit.h(int(location1)-1) # x gate circuit.x(int(location2)-1) # cnot gate circuit.cx(int(location1)-1,int(location2)-1) print(circuit.draw()) valid_move = True else: print() print("You have selected an invalid position/s") return theBoard, count, circuit, turn def measure(circuit, theBoard, count): # trigger collapse printBoard(theBoard) print() print("Trigger collapse.") print() # Use Aer's qasm_simulator simulator = qiskit.Aer.get_backend('qasm_simulator') circuit.measure(0,0) circuit.measure(1,1) circuit.measure(2,2) circuit.measure(3,3) circuit.measure(4,4) circuit.measure(5,5) circuit.measure(6,6) circuit.measure(7,7) circuit.measure(8,8) print(circuit.draw()) # Execute the circuit on quantum simulator job = qiskit.execute(circuit, simulator, shots=1) # Grab results from the job result = job.result() out = json.dumps(result.get_counts()) #Converts the result.get_counts() into a string string = out[2:11] #Removes unnecessary data from string, leaving us with board # update board for i in range(9): if string[i] == '1': # cement value in the board theBoard[str(9-i)][1] = 0 else: # make square empty theBoard[str(9-i)][1] = 0 theBoard[str(9-i)][0] = ' ' # update count (total number of markers on the board) count = 0 for i in range(9): theBoard[str(i+1)][1] = 0 if theBoard[str(i+1)][0] != ' ': count += 1 # reset qubits circuit.reset(0) circuit.reset(1) circuit.reset(2) circuit.reset(3) circuit.reset(4) circuit.reset(5) circuit.reset(6) circuit.reset(7) circuit.reset(8) for i in range(9): if string[8-i] == '1': # add pauli x gate circuit.x(i) return circuit, string, theBoard, count def check_win(theBoard, turn): if theBoard['7'][0] == theBoard['8'][0] == theBoard['9'][0] != ' ': # across the top if theBoard['7'][1] == theBoard['8'][1] == theBoard['9'][1] == 0: # only cemented markers printBoard(theBoard) print("\nGame Over.\n") print(" **** ", end='') print(theBoard['8'][0], end='') print(" won ****") print() return True elif theBoard['4'][0] == theBoard['5'][0] == theBoard['6'][0] != ' ': # across the middle if theBoard['4'][1] == theBoard['5'][1] == theBoard['6'][1] == 0: # only cemented markers printBoard(theBoard) print("\nGame Over.\n") print(" **** ", end='') print(theBoard['5'][0], end='') print(" won ****") print() return True elif theBoard['1'][0] == theBoard['2'][0] == theBoard['3'][0] != ' ': # across the bottom if theBoard['1'][1] == theBoard['2'][1] == theBoard['3'][1] == 0: # only cemented markers printBoard(theBoard) print("\nGame Over.\n") print(" **** ", end='') print(theBoard['2'][0], end='') print(" won ****") print() return True elif theBoard['1'][0] == theBoard['4'][0] == theBoard['7'][0] != ' ': # down the left side if theBoard['1'][1] == theBoard['4'][1] == theBoard['7'][1] == 0: # only cemented markers printBoard(theBoard) print("\nGame Over.\n") print(" **** ", end='') print(theBoard['4'][0], end='') print(" won ****") print() return True elif theBoard['2'][0] == theBoard['5'][0] == theBoard['8'][0] != ' ': # down the middle if theBoard['2'][1] == theBoard['5'][1] == theBoard['8'][1] == 0: # only cemented markers printBoard(theBoard) print("\nGame Over.\n") print(" **** ", end='') print(theBoard['5'][0], end='') print(" won ****") print() return True elif theBoard['3'][0] == theBoard['6'][0] == theBoard['9'][0] != ' ': # down the right side if theBoard['3'][1] == theBoard['6'][1] == theBoard['9'][1] == 0: # only cemented markers printBoard(theBoard) print("\nGame Over.\n") print(" **** ", end='') print(theBoard['6'][0], end='') print(" won ****") print() return True elif theBoard['7'][0] == theBoard['5'][0] == theBoard['3'][0] != ' ': # diagonal if theBoard['7'][1] == theBoard['5'][1] == theBoard['3'][1] == 0: # only cemented markers printBoard(theBoard) print("\nGame Over.\n") print(" **** ", end='') print(theBoard['5'][0], end='') print(" won ****") print() return True elif theBoard['1'][0] == theBoard['5'][0] == theBoard['9'][0] != ' ': # diagonal if theBoard['1'][1] == theBoard['5'][1] == theBoard['9'][1] == 0: # only cemented markers printBoard(theBoard) print("\nGame Over.\n") print(" **** ", end='') print(theBoard['5'][0], end='') print(" won ****") print() return True #Implementation of Two Player Tic-Tac-Toe game in Python. # start game function # Now we'll write the main function which has all the gameplay functionality. def game(): turn = 'X' count = 0 win = False x_collapse = 1 y_collapse = 1 # initialise quantum circuit with 9 qubits (all on OFF = 0) circuit = qiskit.QuantumCircuit(9, 9) while (not win): # ============================= ROUND START ============================ global theBoard printBoard(theBoard) print() print("It's your turn " + turn + ". Do you want to make a (1) classical move, (2) quantum move, (3) collapse?, or (4) quit?") move = input() # ============================= CLASSIC MOVE =========================== if int(move) == 1: theBoard, turn, count, circuit = make_classic_move(theBoard, turn, count, circuit) madeMove = True # ============================= QUANTUM MOVE =========================== elif int(move) == 2 and count > 8: # cant do a quantum move if there's only 1 empty square left print() print("There aren't enough empty spaces for that!") elif int(move) == 2 and count < 8: theBoard, count, circuit, turn = make_quantum_move(theBoard, count, circuit, turn) madeMove = True # ============================= COLLAPSE/MEASURE ======================= elif int(move) == 3: if (turn == 'X' and x_collapse== 1 ): circuit, string, theBoard, count = measure(circuit, theBoard, count) x_collapse = 0 elif (turn == 'O' and y_collapse == 1): circuit, string, theBoard, count = measure(circuit, theBoard, count) y_collapse = 0 else: print("You have already used your collapse this game!") # ============================= QUIT =================================== elif int(move) == 4: break # ============================= CHECK FOR WIN ========================== # Now we will check if player X or O has won,for every move if count >= 5: win = check_win(theBoard, turn) if (win): break # If neither X nor O wins and the board is full, we'll declare the result as 'tie'. if count == 9: circuit, string, theBoard, count = measure(circuit, theBoard, count) win = check_win(theBoard, turn) if count == 9: print("\nGame Over.\n") print("It's a Tie !") print() win = True # Now we have to change the player after every move. if (madeMove): madeMove = False if turn =='X': turn = 'O' else: turn = 'X' # Now we will ask if player wants to restart the game or not. restart = input("Play Again?(y/n) ") if restart == "y" or restart == "Y": theBoard = resetBoard() game() def start_menu(): start_menu = """ Start Menu: 1. Start Game 2. How to Play 3. Quit """ print(""" ########################### ### Quantum Tic-Tac-Toe ### ########################### """) print(start_menu) choice = 0 while (choice != '1'): print("What would you like to do? ", end='') choice = input() if (choice == '2'): How_To = """ In Quantum Tic-Tac-Toe, each square starts empty and your goal is to create a line of three of your naughts/crosses. Playing a classical move will result in setting a square permanently as your piece. Playing a quantum move will create a superposition between two squares of your choosing. You may only complete a quantum move in two empty squares. The board will collapse when the board is full. At collapse, each superposition is viewed and only 1 piece of the superposition will remain. *Powerup* Each player can decide to collapse the board prematurely, they may do this once per round each. """ print(How_To) if (choice == '3'): print("Goodbye") break return choice #Reset the board at start theBoard = resetBoard() #Set no moves made yet if (start_menu() == '1'): madeMove = False game()
https://github.com/renatawong/quantum-protein-structure-prediction
renatawong
''' (C) Renata Wong (CGU-CoIC, NCTS-NTU) 2023. This is a simplified validation code for amino acid sequences of length 3 only. Note: the full algorithm requires a number of qubits that is not achievable on present day devices. This simplification is the largest possible on a quantum simulator and requires the following resources: Number of qubits: 25 Number of gates per iteration: 15 H + 67 X + 24 CX + 724 CCX + 2 CZ = 832 Number of iterations: 4 Runtime: about 2 minutes Description of the algorithm: The algorithm is based on Grover's amplitude amplification routine. In this routine, Algorithm 1 through Algorithm 4 are executed a certain number of times, which is determined by the formula pi/4 * sqrt(N/M) where N is the total number of possible conformations (for sequence of 3 qubits, this is 8) and M is the number of solutions (here we are looking for a single solution only). In each iteration of amplitude amplification, the conformation (solution) is marked and then that conformation's quantum amplitude is amplified. Upon measurement we are guaranteed to obtain the solution with a high probability of 0.9993. See the reference paper for the calculation of this theoretical probability. Algorithm 1: generates the conformational space by calculating the coordinates of each conformation based on the values of w. As this is a 2D model, we need to consider 4 neighbouring amino acids: west (w=11), east (w=01), north (w=00), adn south (w=10). In this simplified version of the algorithm, we arbitrarily choose the conformation w1w2=1100. Hence, this conformation corresponds to the one shown in Fig. 8 of the reference paper. Algorithm 2: calculates the energy values for each conformation and stores them in qubit e. By design, only 1 conformation will have e = 1. This conformation is: w=1100. Algorithm 3: uncomputing coordinate values for all conformations Algorithm 4: Grover's algorithm executed once on vectors w and e the single solution 1100 has theoretical probability of 0.9993 Measurement: measure the vector |w> which encodes all directional transitions for a given conformation Reference: R. Wong and W-L Chang, Fast quantum algorithm for protein structure prediction in hydrophobic-hydrophilic model, Journal of Parallel and Distributed Computing 164: 178-190 doi: 10.1016/j.jpdc.2022.03.011 ''' from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister import numpy as np import math from qiskit.tools.visualization import plot_histogram # Attention: the following code is for sequences of length 3 bit only length = 3 ''' This algorithm uses two's complement to represent the Cartesian coordinates of amino acids, i.e., 0 = 000, 1 = 001, 2 = 010, 3 = 011, -1 = 111, -2 = 110, -3 = 101 (-4 = 100, not needed) For the purpose of this simplified validation we don't need the fixed coordinates of the first amino acid which are all 0 Using two's complement allows us to design a single subcircuit for both addition and subtraction. ''' # quantum register holding the x coordinates for x1, x2 etc. (x0 = 000 omitted) x = QuantumRegister(length*2, 'x') # quantum register holding the y coordinates for y1, y2 etc. (y0 = 000 omitted) y = QuantumRegister(length*2, 'y') # quantum register holding the controls w0, w1, etc. w = QuantumRegister(2*(length-1), 'w') # register holding the binary 1 (3 qubits) a = QuantumRegister(length,'a') # register holding the two's complement of 1 (3 qubits) not needed, # can be replaced by a with the first 2 qubits negated. # register holding the carry bit for ripple-carry adder c = QuantumRegister(1,'c') # quantum register that holds the energy value for each conformation: if first and # last amino acid are located diagonally # from each other, e = 1, otherwise e = 0. # There are 4 conformations for which e = 1. e = QuantumRegister(1, 'e') # additional qubit for grover's algorithm g = QuantumRegister(1, 'g') # classical register out = ClassicalRegister(4,'out') # quantum circuit consisting of all quantum and classical registers qc = QuantumCircuit(x,y,w,a,c,e,g,out) # ancilla qubits, at most three needed for the ccrca function anc = QuantumRegister(3,'anc') qc.add_register(anc) # encoding binary 1 qc.x(a[length-1]) # encoding the two's complement of 1 #qc.x(t[0:length]) # setting the state into superposition qc.h(w[0:(length-1)*2]) # Grvoer qubit must be in its own superposition qc.h(g[0]) ''' Subcircuit for the controlled-controlled ripple-carry adder for 3 bits (the sum is stored by overwriting the values of x) ''' sw = QuantumRegister(2,'sw') # control qubits sa = QuantumRegister(3,'sa') # ancilla qubits ss = QuantumRegister(1,'ss') # carry sx = QuantumRegister(length,'sx') # summand x sy = QuantumRegister(length,'sy') # summand y sc = QuantumCircuit(sw,sa,ss,sx,sy,name='ccrca') sc.ccx(sw[0],sw[1],sa[0]) sc.ccx(sa[0],sy[2],sx[2]) sc.ccx(sa[0],sy[2],ss[0]) sc.ccx(sa[0],ss[0],sa[1]) sc.ccx(sa[1],sx[2],sa[2]) sc.ccx(sa[1],sa[2],sy[2]) # uncompute sc.ccx(sa[1],sx[2],sa[2]) sc.ccx(sa[0],ss[0],sa[1]) sc.ccx(sa[0],sy[1],sx[1]) sc.ccx(sa[0],sy[1],sy[2]) sc.ccx(sa[0],sy[2],sa[1]) sc.ccx(sa[1],sx[1],sa[2]) sc.ccx(sa[1],sa[2],sy[1]) # uncompute sc.ccx(sa[1],sx[1],sa[2]) sc.ccx(sa[0],sy[2],sa[1]) sc.ccx(sa[0],sy[0],sx[0]) sc.ccx(sa[0],sy[0],sy[1]) sc.ccx(sa[0],sy[1],sa[1]) sc.ccx(sa[1],sx[0],sa[2]) sc.ccx(sa[1],sa[2],sy[0]) # uncompute sc.ccx(sa[1],sx[0],sa[2]) sc.ccx(sa[0],sy[1],sa[1]) sc.ccx(sa[0],sy[1],sa[1]) sc.ccx(sa[1],sx[0],sa[2]) sc.ccx(sa[1],sa[2],sy[0]) # uncompute sc.ccx(sa[1],sx[0],sa[2]) sc.ccx(sa[0],sy[1],sa[1]) # continue sc.ccx(sa[0],sy[0],sy[1]) sc.ccx(sa[0],sy[1],sx[0]) sc.ccx(sa[0],sy[2],sa[1]) sc.ccx(sa[1],sx[1],sa[2]) sc.ccx(sa[1],sa[2],sy[1]) # uncompute sc.ccx(sa[1],sx[1],sa[2]) sc.ccx(sa[0],sy[2],sa[1]) # continue sc.ccx(sa[0],sy[1],sy[2]) sc.ccx(sa[0],sy[2],sx[1]) sc.ccx(sa[0],ss[0],sa[1]) sc.ccx(sa[1],sx[2],sa[2]) sc.ccx(sa[1],sa[2],sy[2]) # uncompute sc.ccx(sa[1],sx[2],sa[2]) sc.ccx(sa[0],ss[0],sa[1]) # continue sc.ccx(sa[0],sy[2],ss[0]) sc.ccx(sa[0],ss[0],sx[2]) sc.ccx(sw[0],sw[1],sa[0]) subinst = sc.to_instruction() ''' Main body of the algorithm: Grover iteration ''' num_solutions = 1 # (by design since we only want to find conformation w = 1100) # Number of iterations num_iter = int(math.ceil(np.pi*(np.sqrt(2**(2*(length-1)/num_solutions)))/4)) for j in range(num_iter): # global variable used in Algorithm 1 to navigate among the values of vector w b = 0 arglist = [] ''' Algorithm 1: Generating conformational space ''' for d in range (2, length+1): for q in range (length): if d == 3: qc.cx(x[q],x[length+q]) qc.cx(y[q],y[length+q]) # calculating the western neighbour of site d-1 (w=11) arglist.append(w[b]) arglist.append(w[b+1]) for i in range(3): arglist.append(anc[i]) arglist.append(c[0]) #range [0,1,2] for d=2, range [3,4,5] for d=3 for i in range((d-2)*length,(d-2)*length+3): arglist.append(x[i]) qc.x(a[0]) qc.x(a[1]) for i in range(length): arglist.append(a[i]) qc.append(subinst,arglist) qc.x(a[0]) qc.x(a[1]) # calculating the eastern neighbour of site d-1 (w=01) for i in range(len(arglist)-1,-1,-1): arglist.pop(i) qc.x(w[b]) arglist.append(w[b]) arglist.append(w[b+1]) for i in range(3): arglist.append(anc[i]) arglist.append(c[0]) for i in range((d-2)*length,(d-2)*length+3): arglist.append(x[i]) for i in range(length): arglist.append(a[i]) qc.append(subinst,arglist) # calculating the northern neighbour of site d-1 (w=00) for i in range(len(arglist)-1,-1,-1): arglist.pop(i) qc.x(w[b+1]) arglist.append(w[b]) arglist.append(w[b+1]) for i in range(3): arglist.append(anc[i]) arglist.append(c[0]) for i in range((d-2)*length,(d-2)*length+3): arglist.append(y[i]) for i in range(length): arglist.append(a[i]) qc.append(subinst,arglist) # calculating the southern neighbour of site d-1 (w=10) for i in range(len(arglist)-1,-1,-1): arglist.pop(i) qc.x(w[b]) arglist.append(w[b]) arglist.append(w[b+1]) for i in range(3): arglist.append(anc[i]) arglist.append(c[0]) for i in range((d-2)*length,(d-2)*length+3): arglist.append(y[i]) qc.x(a[0]) qc.x(a[1]) for i in range(length): arglist.append(a[i]) qc.append(subinst,arglist) qc.x(w[b+1]) for i in range(len(arglist)-1,-1,-1): arglist.pop(i) qc.x(a[0]) qc.x(a[1]) b = b+2 ''' Algorithm 2: Finding the conformation |w>=|1100> among the 16 possible conformations. For this conformation, the energy value will be e = 1, while e = 0 for all other conf. Conformation 1100 has the following coordinates: |x2>=111, |x3>=111, |y2>=000, |y3>=001. As this conformation is uniquely identified by the values of the y coordinates and the coordinate x3, the energy value depends on all these values. We only check the first and the third bits of each y coordinate and the first bit of x3 (5 values) The 6 bits of the y vector are indexed as y0y1y2 y3y4y5 ''' qc.x(y[0]) qc.x(y[2]) qc.x(y[3]) qc.ccx(x[3],y[0],anc[0]) qc.ccx(anc[0],y[2],anc[1]) qc.ccx(anc[1],y[3],anc[2]) qc.ccx(anc[2],y[5],e[0]) qc.cz(e[0],g[0]) # resetting all qubits, including the energy qubit qc.ccx(anc[2],y[5],e[0]) qc.ccx(anc[1],y[3],anc[2]) qc.ccx(anc[0],y[2],anc[1]) qc.ccx(x[3],y[0],anc[0]) qc.x(y[0]) qc.x(y[2]) qc.x(y[3]) ''' Algorithm 3: Uncomputing of coordinates by running Algorithm 1 in reverse ''' b = 2 for d in range (length,1,-1): # uncalculating the western neighbour of site d-1 (w=11) arglist.append(w[b]) arglist.append(w[b+1]) for i in range(3): arglist.append(anc[i]) arglist.append(c[0]) #range [0,1,2] for d=2, range [3,4,5] for d=3 for i in range((d-2)*length,(d-2)*length+3): arglist.append(x[i]) qc.x(a[0]) qc.x(a[1]) for i in range(length): arglist.append(a[i]) qc.append(subinst.inverse(),arglist) qc.x(a[0]) qc.x(a[1]) # calculating the eastern neighbour of site d-1 (w=01) for i in range(len(arglist)-1,-1,-1): arglist.pop(i) qc.x(w[b]) arglist.append(w[b]) arglist.append(w[b+1]) for i in range(3): arglist.append(anc[i]) arglist.append(c[0]) for i in range((d-2)*length,(d-2)*length+3): arglist.append(x[i]) for i in range(length): arglist.append(a[i]) qc.append(subinst.inverse(),arglist) # calculating the northern neighbour of site d-1 (w=00) for i in range(len(arglist)-1,-1,-1): arglist.pop(i) qc.x(w[b+1]) arglist.append(w[b]) arglist.append(w[b+1]) for i in range(3): arglist.append(anc[i]) arglist.append(c[0]) for i in range((d-2)*length,(d-2)*length+3): arglist.append(y[i]) for i in range(length): arglist.append(a[i]) qc.append(subinst.inverse(),arglist) # calculating the southern neighbour of site d-1 (w=10) for i in range(len(arglist)-1,-1,-1): arglist.pop(i) qc.x(w[b]) arglist.append(w[b]) arglist.append(w[b+1]) for i in range(3): arglist.append(anc[i]) arglist.append(c[0]) for i in range((d-2)*length,(d-2)*length+3): arglist.append(y[i]) qc.x(a[0]) qc.x(a[1]) for i in range(length): arglist.append(a[i]) qc.append(subinst.inverse(),arglist) qc.x(w[b+1]) qc.x(a[0]) qc.x(a[1]) for i in range(len(arglist)-1,-1,-1): arglist.pop(i) b = b-2 for q in range (length-1, -1,-1): if d == 3: qc.cx(x[q],x[length+q]) qc.cx(y[q],y[length+q]) ''' Algorithm 4: Finding the conformation with e = 1 among 16. This can be done with Grover's diffusion operator, which has to be executed pi/4 * sqrt(N/M) where N = 16 (all conformations) and M = 1 (solutions). This is equal to 3.4. Thus executing the search algorithm 4 times is optimal for finding the solution with a high probability. ''' for i in range(4): qc.h(w[i]) qc.x(w[i]) qc.h(g[0]) qc.x(g[0]) qc.ccx(w[0],w[1],anc[0]) qc.ccx(anc[0],w[2],anc[1]) qc.ccx(anc[1],w[3],anc[2]) qc.cz(anc[2],g[0]) qc.ccx(anc[1],w[3],anc[2]) qc.ccx(anc[0],w[2],anc[1]) qc.ccx(w[0],w[1],anc[0]) qc.x(g[0]) qc.h(g[0]) for i in range(4): qc.x(w[i]) qc.h(w[i]) ''' MEASUREMENT ''' coord = [] for i in range(2*(length-1)): coord.append(w[i]) # Reversing coordinates due to Qiskit's little endian notation coord.reverse() # Measurement qc.measure(coord,out) # Output in the form of vector |w>, which encodes the directional transitions for # each conformation simulator = Aer.get_backend('qasm_simulator') result = execute(qc,backend = simulator, shots = 1024).result() counts = result.get_counts() plot_histogram(counts) '''Print out the quantum circuit''' qc.draw('mpl')
https://github.com/renatawong/quantum-protein-structure-prediction
renatawong
''' (C) Copyright Renata Wong 2023. This code is licensed under the Apache License, Version 2.0. You may obtain a copy of this license at http://www.apache.org/licenses/LICENSE-2.0. Any modifications or derivative works of this code must retain this copyright notice, and modified files need to carry a notice indicating that they have been altered from the originals. This is the accompanying Qiskit code for the paper 'Fast Quantum Algorithm for Protein Structure Prediction in Hydrophobic-Hydrophilic Model' (DOI: 10.1016/j.jpdc.2022.03.011) The code works for amino acid sequences of length > 4. NOTE: This code assumes the sequence 01001 for testing pursposes. Other sequences may require adjustments of variables num_solutions and j. ''' from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister import numpy as np import math ''' Taking in user input of the amino acid sequence. Bit 0 stands for a hydrophilic amino acid, while bit 1 stands for a hydrophobic amino acid ''' sequence_input = list(input('Enter a sequence of length at least 5 encoded as a string of 0s and 1s:' )) length = len(sequence_input) ''' Quantum register holding the sequence encoding ''' sequence = QuantumRegister(length,'s') ''' Quantum registers for each of the three coordinates x, y, and z. Coordinate order within each register: x0, x1, x2, etc., where x0 is the x-coordinate of the 1st amino acid, x1 is the x-coordinate of the 2nd amino acid, etc. Each register holds 2(length - 1) + 1 values. Each value can therefore be repserented with a minimum of ceil(log2(2*length - 1)) bits. There are a 'length' number of amino acids in a sequence. ''' register_length = int(math.ceil(np.log2(2*length-1))) coord_reg_length = length * register_length x_coord = QuantumRegister(coord_reg_length, 'x') y_coord = QuantumRegister(coord_reg_length, 'y') ''' Quantum register holding the controls w0, w1, etc. Each w is of length 2. Amino acid at position (0, 0, 0) is fixed. Hence, length - 1 amino acids in a sequence require directional information encoded in w. ''' w = QuantumRegister(2*(length-1), 'w') ''' Quantum register holding the binary 1, and the two's complement of 1 (= -1). The two's complement of 1 can be obtained by negating all the qubits in binary one but the last. NOTE: Encoding coordinates in two's complement notation allows one to treat subtraction as addition with the same ripple carry circuit. ''' one_reg_length = int(math.ceil(np.log2(2*length-1))) binary_one = QuantumRegister(one_reg_length,'one') ''' Quantum register holding the carry bit for ripple-carry adder ''' carry = QuantumRegister(1, 'c') ''' Register holding the Grover auxialliary qubit ''' g = QuantumRegister(1, 'g') ''' Classical register holding the output of the quantum computation ''' output = ClassicalRegister(length+2*(length-1), 'out')#(length + 2*(length-1) + 2*coord_reg_length,'out') ''' The ancilla register of 3 qubits in needed for the multiplexer (controlled Toffoli gates) in the ripple-carry quantum adder. ''' ancilla = QuantumRegister(3, 'anc') ''' Registers for the section FINDING ENERGY VALUES ''' k_range = length-3 j_range = int((k_range * (k_range+1))/2) x_star = QuantumRegister(4*j_range*register_length, 'x_st') y_star = QuantumRegister(4*j_range*register_length, 'y_st') r_reg = QuantumRegister(4*j_range*(2*register_length + 1), 'r') delta = QuantumRegister(4*2*j_range, 'delta') psi = QuantumRegister(4*j_range, 'psi') ''' Registers for section SUMMING UP ENERGY VALUES. We create 4 index matrices that hold registers for each of 0 <= p <= 3 in the z_reg to obtain the value for kj in register z. ''' p0_matrix = [ [ 0 for m in range(4 * (length-4) + 2) ] for n in range(length-2) ] kj = 0 for k in range(1, length-2): for j in range(4 * (k-1) + 2): p0_matrix[k][j] = kj kj += 1 p1_matrix = [ [ 0 for m in range(4 * (length-4) + 3) ] for n in range(length-2) ] for k in range(1, length-2): for j in range(4 * (k-1) + 3): p1_matrix[k][j] = kj kj += 1 p2_matrix = [ [ 0 for m in range(4 * (length-4) + 4) ] for n in range(length-2) ] for k in range(1, length-2): for j in range(4 * (k-1) + 4): p2_matrix[k][j] = kj kj += 1 p3_matrix = [ [ 0 for m in range(4 * (length-4) + 5) ] for n in range(length-2) ] for k in range(1, length-2): for j in range(4 * (k-1) + 5): p3_matrix[k][j] = kj kj += 1 z = QuantumRegister(kj, 'z') #((4 * length - 12) * (4 * length - 11) / 2, 'z') this value is too low z_or = QuantumRegister(1, 'z_or') # ancilla qubit for the multiplexer in Fig. 4 z_and = QuantumRegister(1, 'z_and') # ancilla to hold the results of the AND operation ''' Defining a quantum circuit consisting of the above quantum and classical registers ''' qc = QuantumCircuit(g, sequence, x_coord, y_coord, w, binary_one, carry, ancilla, x_star, y_star, r_reg, delta, psi, z, z_or, z_and, output) ''' SECTION: PREPARING A UNIFORM SUPERPOSITION STATE Initialisation of sequence values based on user input ''' for index, bit in enumerate(sequence_input): if bit == '1': qc.x(sequence[index]) ''' Initialising binary one and the two's complement of one ''' qc.x(binary_one[one_reg_length-1]) ''' Setting the quantum state in a uniform superposition wrt. w ''' qc.h(w[0:2*(length-1)]) ''' Initialization of r_reg ''' multiplier = int(len(r_reg)/(4*j_range)) for i in range(4*j_range): qc.x(r_reg[i*multiplier]) ''' Initialize z_or to |1> for cascading OR gates implemented with mcx gate. ''' qc.x(z_or) ''' Setting the Grover qubit into the |-> state ''' qc.x(g) qc.h(g) ''' SECTION: CALCULATING COORDINATES Requires a doubly-controlled ripple-carry adder as a subroutine sc The adder below is for amino acid sequences of length > 4. ''' summand_register_length = int(math.ceil(np.log2(2*length-1))) sw = QuantumRegister(2,'sw') # control qubits (w) sa = QuantumRegister(3,'sa') # ancilla qubits ss = QuantumRegister(1,'ss') # carry sx = QuantumRegister(summand_register_length,'sx') # summand x sy = QuantumRegister(summand_register_length,'sy') # summand y sc = QuantumCircuit(sw, sa, ss, sx, sy, name='ccrca') sc.ccx(sw[0],sw[1],sa[0]) for i in range(1, summand_register_length): sc.ccx(sa[0],sx[i],sa[1]) sc.cx(sa[1],sy[i]) sc.ccx(sa[0],sx[i],sa[1]) sc.ccx(sa[0],sx[1],sa[1]) sc.cx(sa[1],ss[0]) sc.ccx(sa[0],sx[1],sa[1]) sc.ccx(sa[0],sx[0],sa[1]) sc.ccx(sa[1],sy[0],sa[2]) sc.cx(sa[2],ss[0]) sc.ccx(sa[1],sy[0],sa[2]) sc.ccx(sa[0],sx[0],sa[1]) sc.ccx(sa[0],sx[2],sa[1]) sc.cx(sa[1],sx[1]) sc.ccx(sa[0],sx[2],sa[1]) sc.ccx(sa[0],ss[0],sa[1]) sc.ccx(sa[1],sy[1],sa[2]) sc.cx(sa[2],sx[1]) sc.ccx(sa[1],sy[1],sa[2]) sc.ccx(sa[0],ss[0],sa[1]) sc.ccx(sa[0],sx[3],sa[1]) sc.cx(sa[1],sx[2]) sc.ccx(sa[0],sx[3],sa[1]) for i in range(2, summand_register_length-2): sc.ccx(sa[0],sy[i],sa[1]) sc.ccx(sa[1],sx[i-1],sa[2]) sc.cx(sa[2],sx[i]) sc.ccx(sa[1],sx[i-1],sa[2]) sc.ccx(sa[0],sy[i],sa[1]) sc.ccx(sa[0],sx[i+2],sa[1]) sc.cx(sa[1],sx[i+1]) sc.ccx(sa[0],sx[i+2],sa[1]) sc.ccx(sa[0],sy[summand_register_length-2],sa[1]) sc.ccx(sa[1],sx[summand_register_length-3],sa[2]) sc.cx(sa[2],sx[summand_register_length-2]) sc.ccx(sa[1],sx[summand_register_length-3],sa[2]) sc.ccx(sa[0],sy[summand_register_length-2],sa[1]) for i in range(1, summand_register_length-1): sc.cx(sa[0],sy[i]) sc.ccx(sa[0],ss[0],sa[1]) sc.cx(sa[1],sy[1]) sc.ccx(sa[0],ss[0],sa[1]) for i in range(2, summand_register_length): sc.ccx(sa[0],sx[i-1],sa[1]) sc.cx(sa[1],sy[i]) sc.ccx(sa[0],sx[i-1],sa[1]) sc.ccx(sa[0],sx[summand_register_length-3],sa[1]) sc.ccx(sa[1],sy[summand_register_length-2],sa[2]) sc.cx(sa[2],sx[summand_register_length-2]) sc.ccx(sa[1],sy[summand_register_length-2],sa[2]) sc.ccx(sa[0],sx[summand_register_length-3],sa[1]) for i in range(summand_register_length-3, 1, -1): sc.ccx(sa[0],sx[i-1],sa[1]) sc.ccx(sa[1],sy[i],sa[2]) sc.cx(sa[2],sx[i]) sc.ccx(sa[1],sy[i],sa[2]) sc.ccx(sa[0],sx[i-1],sa[1]) sc.ccx(sa[0],sx[i+2],sa[1]) sc.cx(sa[1],sx[i+1]) sc.ccx(sa[0],sx[i+2],sa[1]) sc.cx(sa[0],sy[i+1]) sc.ccx(sa[0],ss[0],sa[1]) sc.ccx(sa[1],sy[1],sa[2]) sc.cx(sa[2],sx[1]) sc.ccx(sa[1],sy[1],sa[2]) sc.ccx(sa[0],ss[0],sa[1]) sc.ccx(sa[0],sx[3],sa[1]) sc.cx(sa[1],sx[2]) sc.ccx(sa[0],sx[3],sa[1]) sc.cx(sa[0],sy[2]) sc.ccx(sa[0],sx[0],sa[1]) sc.ccx(sa[1],sy[0],sa[2]) sc.cx(sa[2],ss[0]) sc.ccx(sa[1],sy[0],sa[2]) sc.ccx(sa[0],sx[0],sa[1]) sc.ccx(sa[0],sx[2],sa[1]) sc.cx(sa[1],sx[1]) sc.ccx(sa[0],sx[2],sa[1]) sc.cx(sa[0],sy[1]) sc.ccx(sa[0],sx[1],sa[1]) sc.cx(sa[1],ss[0]) sc.ccx(sa[0],sx[1],sa[1]) for i in range(summand_register_length): sc.ccx(sa[0],sx[i],sa[1]) sc.cx(sa[1],sy[i]) sc.ccx(sa[0],sx[i],sa[1]) sc.ccx(sw[0],sw[1],sa[0]) subinst = sc.to_instruction() ''' Ripple-carry adder without control qubits |w> ''' ssr = QuantumRegister(1,'ssr') # carry sxr = QuantumRegister(summand_register_length,'sxr') # summand x syr = QuantumRegister(summand_register_length,'syr') # summand y rca = QuantumCircuit(ssr, sxr, syr, name='rca') for i in range(1, summand_register_length): rca.cx(sxr[1],syr[i]) rca.cx(sxr[1],ssr[0]) rca.ccx(sxr[0],syr[0],ssr[0]) rca.cx(sxr[2],sxr[1]) rca.ccx(ssr[0],syr[1],sxr[1]) rca.cx(sxr[3],sxr[2]) for i in range(2, summand_register_length-2): rca.ccx(syr[i],sxr[i-1],sxr[i]) rca.cx(sxr[i+2],sxr[i+1]) rca.ccx(syr[summand_register_length-2],sxr[summand_register_length-3],sxr[summand_register_length-2]) for i in range(1, summand_register_length-1): rca.x(syr[i]) rca.cx(ssr[0],syr[1]) for i in range(2, summand_register_length): rca.cx(sxr[i-1],syr[i]) rca.ccx(sxr[summand_register_length-3],syr[summand_register_length-2],sxr[summand_register_length-2]) for i in range(summand_register_length-3, 1, -1): rca.ccx(sxr[i-1],syr[i],sxr[i]) rca.cx(sxr[i+2],sxr[i+1]) rca.cx(sxr[i+2],syr[i+1]) rca.ccx(ssr[0],syr[1],sxr[1]) rca.cx(sxr[3],sxr[2]) rca.x(syr[2]) rca.ccx(sxr[0],syr[0],ssr[0]) rca.cx(sxr[2],sxr[1]) rca.x(syr[1]) rca.cx(sxr[1],ssr[0]) for i in range(summand_register_length): rca.cx(sxr[i],syr[i]) subinst_rca = rca.to_instruction() ''' AMPLITUDE AMPLIFICATION PROCEDURE: Calculation of coordinates using the ripple-carry adder b is a global variable used to navigate among the values of vector w. d stands for the position of an amino acid in a sequence. MODIFY NUMBER OF SOLUTIONS num_solutions FOR DIFFERENT SEQUENCES. ''' num_solutions = 8 num_iter = int(math.ceil(np.pi*(np.sqrt(2**(2*(length-1)/num_solutions)))/4)) # Number of iterations def calculate_neighbour(register, b, d): arglist = [] arglist.append(w[b]) arglist.append(w[b+1]) for i in range(len(ancilla)): arglist.append(ancilla[i]) arglist.append(carry[0]) for i in range(summand_register_length-1, -1, -1): # digit order reversed for adder arglist.append(binary_one[i]) for i in range(d*summand_register_length-1, (d-1)*summand_register_length-1, -1): # digit order reversed for adder arglist.append(register[i]) return arglist def update_coordinates(register_1, register_2): arglist = [] arglist.append(carry[0]) for i in range(summand_register_length-1, -1, -1): # digit order reversed for adder arglist.append(register_1[i]) reg = len(register_2) for i in reversed(range(reg)): # digit order reversed for adder arglist.append(register_2[i]) return arglist ''' THIS IS THE MAIN PART OF THE CODE. ''' for grover_iteration in range(num_iter): b = 0 # Subroutine 1: Generating conformational space by calculating coordinates # This part has been tested and performs correctly for d in range(2, length+1): for q in range(summand_register_length): qc.cx(x_coord[(d-2)*summand_register_length+q],x_coord[(d-1)*summand_register_length+q]) qc.cx(y_coord[(d-2)*summand_register_length+q],y_coord[(d-1)*summand_register_length+q]) ''' Calculating the western neighbour of site d-1 (this is the case when |w> = |11>) ''' for i in range(summand_register_length-1): qc.x(binary_one[i]) neighbour_west = calculate_neighbour(x_coord, b, d) qc.append(subinst, neighbour_west) for i in range(summand_register_length-1): qc.x(binary_one[i]) ''' Calculating the eastern neighbour of site d-1 (this is the case when |w> = |01>) ''' qc.x(w[b]) neighbour_east = calculate_neighbour(x_coord, b, d) qc.append(subinst, neighbour_east) qc.x(w[b]) ''' Calculating the northern neighbour of site d-1 (this is the case when |w> = |00>) ''' qc.x(w[b]) qc.x(w[b+1]) neighbour_north = calculate_neighbour(y_coord, b, d) qc.append(subinst, neighbour_north) qc.x(w[b]) qc.x(w[b+1]) ''' Calculating the southern neighbour of site d-1 (this is the case when |w> = |10>) ''' qc.x(w[b+1]) for i in range(summand_register_length-1): qc.x(binary_one[i]) neighbour_south = calculate_neighbour(x_coord, b, d) qc.append(subinst, neighbour_south) for i in range(summand_register_length-1): qc.x(binary_one[i]) qc.x(w[b+1]) b = b+2 ''' SECTION: FINDING ENERGY VALUES For the conformation that corresponds to the ground energy of the protein, the energy value will be e = 1, while e = 0 for all other confornations. The energy is calculated based on the number of hydrophobic-hydrophobic contacts in the lattice. For each such contact, a 1 is added to the energy value for the given conformation. New registers for calculating energy values based on the coordinates x and y: |x_star> and |y_star>. Register r_reg stores the result of coordinate comparison between sites k and j. Register delta stores the information as to whether the k-th and j-th lattice sites are both hydrophobic and form a loose contact (i.e., are adjacent in the lattice but not in the sequence). At the end of the computation, vector psi contains all the information about hydrophobic-hydrophobic contacts: psi(k, j, p) = |1> iff amino acid k and amino acid j, where j is p-neighbour of k, are both hydrophobic and have a contact in the lattice but not in the sequence. ''' # star_matrix: 3D array to hold the |x_star> and y_star indices # r_matrix: 3D array to hold the indices for r_reg # delta_matrix: 3D array to hold pairs of delta indices # psi_matrix: 3D array to hold psi indices. # All indexed in the coding convention, i.e. from 0 to n-1 instead of from 1 to n. star_matrix = [[[0 for k in range(length)] for j in range(length)] for p in range(4)] r_matrix = [[[0 for k in range(length)] for j in range(length)] for p in range(4)] delta_matrix = [[[0 for k in range(length)] for j in range(length)] for p in range(4)] psi_matrix = [[[0 for k in range(length)] for j in range(length)] for p in range(4)] star_index, r_index, delta_index, psi_index = 0, 0, 0, 0 for k in range(length-3): for j in range(k+3, length): for p in range(4): star_matrix[k][j][p] = [m for m in range(star_index, star_index + register_length)] star_index += register_length r_matrix[k][j][p] = [m for m in range(r_index, r_index + 2*register_length + 1)] r_index += 2 * register_length + 1 delta_matrix[k][j][p] = (delta_index, delta_index+1) delta_index += 2 psi_matrix[k][j][p] = psi_index psi_index += 1 #The code below has not been tested within the algorithm but the indices are assigned correctly and so it should work for k in range(length-3): for j in range(k+3, length): for p in range(4): for r in range(register_length): qc.cx(x_coord[k+r], x_star[star_matrix[k][j][p][r]]) qc.cx(y_coord[k+r], y_star[star_matrix[k][j][p][r]]) if p == 0: neighbour_north = update_coordinates(binary_one, [y_star[star_matrix[k][j][p][r]] for r in range(register_length)]) qc.append(subinst_rca, neighbour_north) if p == 1: neighbour_east = update_coordinates(binary_one, [x_star[star_matrix[k][j][p][r]] for r in range(register_length)]) qc.append(subinst_rca, neighbour_east) if p == 2: for i in range(summand_register_length-1): qc.x(binary_one[i]) neighbour_south = update_coordinates(binary_one, [y_star[star_matrix[k][j][p][r]] for r in range(register_length)]) qc.append(subinst_rca, neighbour_south) for i in range(summand_register_length-1): qc.x(binary_one[i]) if p == 3: for i in range(summand_register_length-1): qc.x(binary_one[i]) neighbour_west = update_coordinates(binary_one, [x_star[star_matrix[k][j][p][r]] for r in range(register_length)]) qc.append(subinst_rca, neighbour_west) for i in range(summand_register_length-1): qc.x(binary_one[i]) for r in range(register_length): qc.cx(x_coord[j+r], x_star[star_matrix[k][j][p][r]]) qc.cx(y_coord[j+r], y_star[star_matrix[k][j][p][r]]) # rows 13 to 19 for r in range(register_length): qc.x(y_star[star_matrix[k][j][p][r]]) qc.x(x_star[star_matrix[k][j][p][r]]) qc.ccx(y_star[star_matrix[k][j][p][0]], r_reg[r_matrix[k][j][p][0]], r_reg[r_matrix[k][j][p][1]]) for r in reversed(range(1, register_length)): qc.ccx(y_star[star_matrix[k][j][p][r]], r_reg[r_matrix[k][j][p][r]], r_reg[r_matrix[k][j][p][r+1]]) for r in reversed(range(register_length, 2*register_length)): qc.ccx(x_star[star_matrix[k][j][p][r-register_length]], r_reg[r_matrix[k][j][p][r]], r_reg[r_matrix[k][j][p][r+1]]) for r in range(register_length): qc.x(y_star[star_matrix[k][j][p][r]]) qc.x(x_star[star_matrix[k][j][p][r]]) # row 20 onwards qc.ccx(sequence[k], r_reg[r_matrix[k][j][p][2*register_length]], delta[delta_matrix[k][j][p][0]]) qc.ccx(sequence[j], delta[delta_matrix[k][j][p][0]], delta[delta_matrix[k][j][p][1]]) qc.cx(delta[delta_matrix[k][j][p][1]], psi[psi_matrix[k][j][p]]) ''' Uncomputing calculation of H-H contacts (stored in vector psi) to free up qubits ''' #This part has not been tested due to running out of memory. But should be correct. for k in reversed(range(length-3)): for j in reversed(range(k+3, length)): for p in reversed(range(3)): qc.ccx(sequence[j], delta[delta_matrix[k][j][p][0]], delta[delta_matrix[k][j][p][1]]) qc.ccx(sequence[k], r_reg[r_matrix[k][j][p][2*register_length]], delta[delta_matrix[k][j][p][0]]) for r in range(register_length): qc.x(y_star[star_matrix[k][j][p][r]]) qc.x(x_star[star_matrix[k][j][p][r]]) for r in range(register_length, 2*register_length): qc.ccx(x_star[star_matrix[k][j][p][r-register_length]], r_reg[r_matrix[k][j][p][r]], r_reg[r_matrix[k][j][p][r+1]]) for r in range(1, register_length): qc.ccx(y_star[star_matrix[k][j][p][r]], r_reg[r_matrix[k][j][p][r]], r_reg[r_matrix[k][j][p][r+1]]) qc.ccx(y_star[star_matrix[k][j][p][0]], r_reg[r_matrix[k][j][p][0]], r_reg[r_matrix[k][j][p][1]]) for r in range(register_length): qc.x(y_star[star_matrix[k][j][p][r]]) qc.x(x_star[star_matrix[k][j][p][r]]) for r in reversed(range(register_length)): qc.cx(x_coord[j+r], x_star[star_matrix[k][j][p][r]]) qc.cx(y_coord[j+r], y_star[star_matrix[k][j][p][r]]) if p == 0: neighbour_north = update_coordinates(binary_one, [y_star[star_matrix[k][j][p][r]] for r in range(register_length)]) qc.append(subinst_rca, neighbour_north) if p == 1: neighbour_east = update_coordinates(binary_one, [x_star[star_matrix[k][j][p][r]] for r in range(register_length)]) qc.append(subinst_rca, neighbour_east) if p == 2: for i in range(summand_register_length-1): qc.x(binary_one[i]) neighbour_south = update_coordinates(binary_one, [y_star[star_matrix[k][j][p][r]] for r in range(register_length)]) qc.append(subinst_rca, neighbour_south) for i in range(summand_register_length-1): qc.x(binary_one[i]) if p == 3: for i in range(summand_register_length-1): qc.x(binary_one[i]) neighbour_west = update_coordinates(binary_one, [x_star[star_matrix[k][j][p][r]] for r in range(register_length)]) qc.append(subinst_rca, neighbour_west) for i in range(summand_register_length-1): qc.x(binary_one[i]) for r in reversed(range(register_length)): qc.cx(x_coord[k+r], x_star[star_matrix[k][j][p][r]]) qc.cx(y_coord[k+r], y_star[star_matrix[k][j][p][r]]) # This part has been tested and performs correctly ''' # Reversing coordinate calculation ''' b = b-2 for d in range (length, 1, -1): # Uncomputing the western neighbour of site d-1 (|w> = |11>) for i in range(summand_register_length-1): qc.x(binary_one[i]) neighbour_west = calculate_neighbour(x_coord, b, d) qc.append(subinst.inverse(), neighbour_west) for i in range(summand_register_length-1): qc.x(binary_one[i]) # Uncomputing the eastern neighbour of site d-1 (|w> = |01>) qc.x(w[b]) neighbour_east = calculate_neighbour(x_coord, b, d) qc.append(subinst.inverse(), neighbour_east) qc.x(w[b]) # Uncomputing the northern neighbour of site d-1 (|w> = |00>) qc.x(w[b]) qc.x(w[b+1]) neighbour_north = calculate_neighbour(y_coord, b, d) qc.append(subinst.inverse(), neighbour_north) qc.x(w[b]) qc.x(w[b+1]) # Uncomputing the southern neighbour of site d-1 (|w> = |10>) qc.x(w[b+1]) for i in range(summand_register_length-1): qc.x(binary_one[i]) neighbour_south = calculate_neighbour(x_coord, b, d) qc.append(subinst.inverse(), neighbour_south) for i in range(summand_register_length-1): qc.x(binary_one[i]) qc.x(w[b+1]) b = b-2 for q in range(summand_register_length-1, -1, -1): qc.cx(x_coord[(d-2)*summand_register_length+q],x_coord[(d-1)*summand_register_length+q]) qc.cx(y_coord[(d-2)*summand_register_length+q],y_coord[(d-1)*summand_register_length+q]) ''' SUMMING UP ENERGY VALUES IN PSI = THIS IS THE CRUCIAL ORACLE PART STORING THE SUM OF ENERGIES IN VECTOR Z_{length-3, 3, j} FLIPPING THE BIT ON GROVER QUBIT g FOR THE LARGEST ENERGY VALUE p0_matrix = [ [ 0 for m in range(4 * (length-4) + 2) ] for n in range(length-2) ] kj = 0 for k in range(1, length-2): for j in range(4 * (k-1) + 2): p0_matrix[k][j] = kj kj += 1 p1_matrix = [ [ 0 for m in range(4 * (length-4) + 3) ] for n in range(length-2) ] for k in range(1, length-2): for j in range(4 * (k-1) + 3): p1_matrix[k][j] = kj kj += 1 p2_matrix = [ [ 0 for m in range(4 * (length-4) + 4) ] for n in range(length-2) ] for k in range(1, length-2): for j in range(4 * (k-1) + 4): p2_matrix[k][j] = kj kj += 1 p3_matrix = [ [ 0 for m in range(4 * (length-4) + 5) ] for n in range(length-2) ] for k in range(1, length-2): for j in range(4 * (k-1) + 5): p3_matrix[k][j] = kj kj += 1 ''' # Adding up the energies. # The energies for each conformation are stored in qubits z_{length-3, 3, j}. # If j = 0, there are no HH contacts and the energy is 0. # If j = 1, there is 1 HH contact and, hence, the energy is 1. And so on. for k in range(length-3): for p in range(4): multiplexer = [psi[psi_matrix[k][i][p]] for i in range(k+3, length)] for j in reversed(range(4*k + p + 1)): if p == 0: for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) qc.mcx(multiplexer, z_or) qc.ccx(z_or, z[p3_matrix[k][3]], z_and) qc.cx(z_and, z[p0_matrix[k+1][j+1]]) # uncomputing to reuse the z_or and z_and ancillas qc.ccx(z_or, z[p3_matrix[k][3]], z_and) qc.mcx(multiplexer, z_or) for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) qc.mcx(multiplexer, z_or) qc.x(z_or) qc.ccx(z_or, z[p3_matrix[k][3]], z_and) qc.cx(z_and, z[p0_matrix[k+1][j]]) qc.ccx(z_or, z[p3_matrix[k][3]], z_and) qc.x(z_or) qc.mcx(multiplexer, z_or) for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) elif p == 1: for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) qc.mcx(multiplexer, z_or) qc.ccx(z_or, z[p0_matrix[k+1][j]], z_and) qc.cx(z_and, z[p1_matrix[k+1][j+1]]) qc.ccx(z_or, z[p0_matrix[k+1][j]], z_and) qc.mcx(multiplexer, z_or) for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) qc.mcx(multiplexer, z_or) qc.x(z_or) qc.ccx(z_or, z[p0_matrix[k+1][j]], z_and) qc.cx(z_and, z[p1_matrix[k+1][j]]) qc.ccx(z_or, z[p0_matrix[k+1][j]], z_and) qc.x(z_or) qc.mcx(multiplexer, z_or) for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) elif p == 2: for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) qc.mcx(multiplexer, z_or) qc.ccx(z_or, z[p1_matrix[k+1][j]], z_and) qc.cx(z_and, z[p2_matrix[k+1][j+1]]) qc.ccx(z_or, z[p1_matrix[k+1][j]], z_and) qc.mcx(multiplexer, z_or) for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) qc.mcx(multiplexer, z_or) qc.x(z_or) qc.ccx(z_or, z[p1_matrix[k+1][j]], z_and) qc.cx(z_and, z[p2_matrix[k+1][j]]) qc.ccx(z_or, z[p1_matrix[k+1][j]], z_and) qc.x(z_or) qc.mcx(multiplexer, z_or) for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) elif p == 3: for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) qc.mcx(multiplexer, z_or) qc.ccx(z_or, z[p2_matrix[k+1][j]], z_and) qc.cx(z_and, z[p3_matrix[k+1][j+1]]) qc.ccx(z_or, z[p2_matrix[k+1][j]], z_and) qc.mcx(multiplexer, z_or) for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) qc.mcx(multiplexer, z_or) qc.x(z_or) qc.ccx(z_or, z[p2_matrix[k+1][j]], z_and) qc.cx(z_and, z[p3_matrix[k+1][j]]) qc.ccx(z_or, z[p2_matrix[k+1][j]], z_and) qc.x(z_or) qc.mcx(multiplexer, z_or) for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) # This is the crucial part of the oracle # WE ASSUME j = 1 SINCE WE ASSUME THAT OUR SEQUENCE IS 01001, # i.e. second and fifth amino acids are hydrophobic, first, third and fourth are hydrophilic. # PARAMETER j IS ADJUSTABLE. j = 1 qc.cx(z[p3_matrix[length-3][j]], g) # Uncomputing the summation of energy for k in reversed(range(length-3)): for p in reversed(range(4)): multiplexer = [psi[psi_matrix[k][i][p]] for i in range(k+3, length)] for j in range(4*k + p + 1): if p == 0: for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) qc.mcx(multiplexer, z_or) qc.ccx(z_or, z[p3_matrix[k][3]], z_and) qc.cx(z_and, z[p0_matrix[k+1][j+1]]) # uncomputing to reuse the z_or and z_and ancillas qc.ccx(z_or, z[p3_matrix[k][3]], z_and) qc.mcx(multiplexer, z_or) for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) qc.mcx(multiplexer, z_or) qc.x(z_or) qc.ccx(z_or, z[p3_matrix[k][3]], z_and) qc.cx(z_and, z[p0_matrix[k+1][j]]) qc.ccx(z_or, z[p3_matrix[k][3]], z_and) qc.x(z_or) qc.mcx(multiplexer, z_or) for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) elif p == 1: for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) qc.mcx(multiplexer, z_or) qc.ccx(z_or, z[p0_matrix[k+1][j]], z_and) qc.cx(z_and, z[p1_matrix[k+1][j+1]]) qc.ccx(z_or, z[p0_matrix[k+1][j]], z_and) qc.mcx(multiplexer, z_or) for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) qc.mcx(multiplexer, z_or) qc.x(z_or) qc.ccx(z_or, z[p0_matrix[k+1][j]], z_and) qc.cx(z_and, z[p1_matrix[k+1][j]]) qc.ccx(z_or, z[p0_matrix[k+1][j]], z_and) qc.x(z_or) qc.mcx(multiplexer, z_or) for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) elif p == 2: for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) qc.mcx(multiplexer, z_or) qc.ccx(z_or, z[p1_matrix[k+1][j]], z_and) qc.cx(z_and, z[p2_matrix[k+1][j+1]]) qc.ccx(z_or, z[p1_matrix[k+1][j]], z_and) qc.mcx(multiplexer, z_or) for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) qc.mcx(multiplexer, z_or) qc.x(z_or) qc.ccx(z_or, z[p1_matrix[k+1][j]], z_and) qc.cx(z_and, z[p2_matrix[k+1][j]]) qc.ccx(z_or, z[p1_matrix[k+1][j]], z_and) qc.x(z_or) qc.mcx(multiplexer, z_or) for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) elif p == 3: for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) qc.mcx(multiplexer, z_or) qc.ccx(z_or, z[p2_matrix[k+1][j]], z_and) qc.cx(z_and, z[p3_matrix[k+1][j+1]]) qc.ccx(z_or, z[p2_matrix[k+1][j]], z_and) qc.mcx(multiplexer, z_or) for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) qc.mcx(multiplexer, z_or) qc.x(z_or) qc.ccx(z_or, z[p2_matrix[k+1][j]], z_and) qc.cx(z_and, z[p3_matrix[k+1][j]]) qc.ccx(z_or, z[p2_matrix[k+1][j]], z_and) qc.x(z_or) qc.mcx(multiplexer, z_or) for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) ''' SECTION: IDENTIFYING THE CONFORMATION WITH THE MINIMAL ENERGY Using Grover's diffusion operation on register w ''' for i in range(len(w)): qc.h(w[i]) qc.x(w[i]) multiplexer = [w[i] for i in range(len(w) - 1)] qc.h(w[len(w) - 1]) qc.mcx(multiplexer, w[len(w) - 1]) qc.h(w[len(w) - 1]) for i in range(len(w)): qc.x(w[i]) qc.h(w[i]) ''' MEASUREMENT. WE ASSUME THAT THE AMINO ACID SEQUENCE IS PHPPH = 01001. HENCE, WE ARE EXPECTING TO SEE THE FOLLOWING VALUES IN THE CHART: 01011011 01101111 00000110 00001110 11111001 11110001 10100100 10101100 ''' conformations = [] for i in range(length): conformations.append(sequence[i]) for i in range(2*(length-1)): conformations.append(w[i]) # Reverse the order in which the output is shown so that it can be read from left to right. conformations.reverse() qc.measure(conformations, output) from qiskit import Aer, execute #from qiskit.providers.aer import QasmSimulator, StatevectorSimulator simulator = Aer.get_backend('qasm_simulator') result = execute(qc, backend = simulator, shots = 10).result() counts = result.get_counts() #statevector = result.get_statevector(qc) #print(statevector) #from qiskit.tools.visualization import plot_histogram #plot_histogram(counts) print(counts, sep='\n') qc.draw('mpl')
https://github.com/zhangx1923/QISKit_Deve_Challenge
zhangx1923
# -*- coding: utf-8 -*- # Copyright 2017 IBM RESEARCH. All Rights Reserved. # # 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. # ============================================================================= """ ---------------> do not modify this file for your submission <--------------- This file is not considered to be part of your submission. It is only provided for you to benchmark your code. The local_qasm_cpp_simulator that is used requires QISKit 0.43 or later. """ import numpy as np import time import copy import qiskit import sys, os, traceback GLOBAL_TIMEOUT = 3600 ERROR_LIMIT = 1e-10 from qiskit import QuantumProgram from qiskit.unroll import Unroller, DAGBackend from qiskit._openquantumcompiler import dag2json from multiprocessing import Pool from qiskit.mapper._mappererror import MapperError from qiskit.tools.qi.qi import state_fidelity def score(depth,cmap,qnum,compiler_function=None,backend = 'local_qiskit_simulator'): """ Scores a compiler function based on a selected set of circuits and layouts available in the two respective subfolders. The final scoring will be done on a similar set of circuits and layouts. Args: compiler_function (function): reference to user compiler function Returns: float : score, speed """ # Load coupling maps maps_q3 = ["circle_3","linear_3","neighbour_3","center_3"] maps_q4 = ["circle_4","linear_4","neighbour_4","center_4"] maps_q5 = ["circle_5","linear_5","neighbour_5","center_5"] maps_q6 = ["circle_6","linear_6","neighbour_6","center_6"] maps_q7 = ["circle_7","linear_7","neighbour_7","center_7"] maps_q8 = ["circle_8","linear_8","neighbour_8","center_8"] maps_q9 = ["circle_9","linear_9","neighbour_9","center_9"] maps_q10 = ["circle_10","linear_10","neighbour_10","center_10"] maps_q11 = ["circle_11","linear_11","neighbour_11","center_11"] maps_q12 = ["circle_12","linear_12","neighbour_12","center_12"] maps_q13 = ["circle_13","linear_13","neighbour_13","center_13"] maps_q14 = ["circle_14","linear_14","neighbour_14","center_14"] maps_q15 = ["circle_15","linear_15","neighbour_15","center_15"] maps_q16 = ["circle_16","linear_16","neighbour_16","center_16"] #maps_q5 = ["circle_rand_q5","ibmqx2_q5","linear_rand_q5","ibmqx4_q5","linear_reg_q5"] #maps_q16 = ["ibmqx3_q16", "linear_rand_q16", "rect_rand_q16", "rect_def_q16", "ibmqx5_q16"] #maps_q20 = ["circle_reg_q20", "linear_rand_q20", "rect_rand_q20", "rect_def_q20", "rect_reg_q20"] # Load circuits files ex_nr = 10 # examples to add per qubit number. maximum is 10 test_circuit_filenames = {} mapss = [] if qnum == 10: mapss = maps_q10 elif qnum ==11: mapss = maps_q11 elif qnum == 12: mapss = maps_q12 elif qnum == 13: mapss = maps_q13 elif qnum == 14: mapss = maps_q14 elif qnum == 15: mapss = maps_q15 elif qnum == 9: mapss = maps_q9 else: pass for ii in range(ex_nr): #test_circuit_filenames['circuits/random%d_n15_d16.qasm' % ii] = load_coupling(maps_q15[1])["coupling_map"] #test_circuit_filenames['circuits/random%d_n8_d11.qasm' % ii] = load_coupling(maps_q8[3])["coupling_map"] test_circuit_filenames['circuits/random%d_n%d_d%d.qasm' % (ii,qnum,depth)] = load_coupling(mapss[cmap])["coupling_map"] #test_circuit_filenames['circuits/random%d_n10_d1.qasm' % ii] = load_coupling(maps_q10[0])["coupling_map"] #test_circuit_filenames['circuits/random%d_n11_d1.qasm' % ii] = load_coupling(maps_q11[0])["coupling_map"] #test_circuit_filenames['circuits/random%d_n12_d1.qasm' % ii] = load_coupling(maps_q12[0])["coupling_map"] #test_circuit_filenames['circuits/random%d_n13_d1.qasm' % ii] = load_coupling(maps_q13[0])["coupling_map"] #test_circuit_filenames['circuits/random%d_n14_d1.qasm' % ii] = load_coupling(maps_q14[0])["coupling_map"] #test_circuit_filenames['circuits/random%d_n15_d1.qasm' % ii] = load_coupling(maps_q15[0])["coupling_map"] # for jj in range(16): # for ii in range(ex_nr): # test_circuit_filenames['circuits/random%d_n16_d%d.qasm' % (ii,jj+1)] = load_coupling(maps_q16[0%len(maps_q16)])["coupling_map"] # for jj in range(16): # for ii in range(ex_nr): # test_circuit_filenames['circuits/random%d_n16_d%d.qasm' % (ii,jj+1)] = load_coupling(maps_q16[1%len(maps_q16)])["coupling_map"] # for jj in range(16): # for ii in range(ex_nr): # test_circuit_filenames['circuits/random%d_n16_d%d.qasm' % (ii,jj+1)] = load_coupling(maps_q16[2%len(maps_q16)])["coupling_map"] # for jj in range(16): # for ii in range(ex_nr): # test_circuit_filenames['circuits/random%d_n16_d%d.qasm' % (ii,jj+1)] = load_coupling(maps_q16[3%len(maps_q16)])["coupling_map"] # for ii in range(ex_nr): # test_circuit_filenames['circuits/random%d_n16_d16.qasm' % ii] = load_coupling(maps_q16[ii%len(maps_q16)])["coupling_map"] # for ii in range(ex_nr): # test_circuit_filenames['circuits/random%d_n20_d20.qasm' % ii] = load_coupling(maps_q20[ii%len(maps_q20)])["coupling_map"] #for ii in range(ex_nr): #test_circuit_filenames['circuits/random%d_n5_d5.qasm' % ii] = load_coupling(maps_q5[ii%len(maps_q5)])["coupling_map"] # for ii in range(ex_nr): # test_circuit_filenames['circuits/random%d_n16_d16.qasm' % ii] = load_coupling(maps_q16[ii%len(maps_q16)])["coupling_map"] # for ii in range(ex_nr): # test_circuit_filenames['circuits/random%d_n20_d20.qasm' % ii] = load_coupling(maps_q20[ii%len(maps_q20)])["coupling_map"] #for ii in range(ex_nr): #test_circuit_filenames['circuits/random%d_n5_d5.qasm' % ii] = load_coupling(maps_q5[ii%len(maps_q5)])["coupling_map"] #for ii in range(ex_nr): #test_circuit_filenames['circuits/random%d_n16_d16.qasm' % ii] = load_coupling(maps_q16[ii%len(maps_q16)])["coupling_map"] #for ii in range(ex_nr): #test_circuit_filenames['circuits/random%d_n20_d20.qasm' % ii] = load_coupling(maps_q20[ii%len(maps_q20)])["coupling_map"] #test_circuit_filenames['circuits/random%d_n16_d16.qasm' % 0] = load_coupling(maps_q16[0])["coupling_map"] #test_circuit_filenames['circuits/random%d_n5_d5.qasm' % 5] = load_coupling(maps_q5[0])["coupling_map"] #test_circuit_filenames['circuits/random%d_n20_d20.qasm' % 3] = load_coupling(maps_q20[3])["coupling_map"] # Load example circuits and coupling maps test_circuits = {} for filename, cmap in test_circuit_filenames.items(): with open(filename, 'r') as infile: qasm = infile.read() test_circuits[filename] = {"qasm": qasm, "coupling_map": cmap} #将verbose设置为False,则不会执行IBM的标准算法 res = evaluate(compiler_function, test_circuits, verbose=True, backend = backend) res_scores=[] for k in res.keys(): print(res[k]) for name in res: if (res[name]["optimizer_time"] > 0) and res[name]["coupling_correct_optimized"]: # only add the score if the QISKit reference compiler worked well if (res[name]["reference_time"] > 0) and res[name]["coupling_correct_reference"]: # both user and reference compiler gave the correct result without error res_scores.append([res[name]["cost_optimized"]/res[name]["cost_reference"],res[name]["optimizer_time"]/res[name]["reference_time"]]) else: # the user compiler had an error or did not produce the right quantum state # this returns a value which is half as good as the reference res_scores.append([2,2]) return [(1./np.mean([ii[0] for ii in res_scores]), 1./np.mean([ii[1] for ii in res_scores])),res] def evaluate(compiler_function=None, test_circuits=None, verbose=False, backend = 'local_qiskit_simulator'): """ Evaluates the given complier_function with the circuits in test_circuits and compares the output circuit and quantum state with the original and a reference obtained with the qiskit compiler. Args: compiler_function (function): reference to user compiler function test_circuits (dict): named dict of circuits for which the compiler performance is evaluated test_circuits: { "name": { "qasm": 'qasm_str', "coupling_map": 'target_coupling_map } } verbose (bool): specifies if performance of basic QISKit unroler and mapper circuit is shown for each circuit backend (string): backend to use. For Windows Systems you should specify 'local_qasm_simulator' until 'local_qiskit_simulator' is available. Returns: dict { "name": circuit name { "optimizer_time": time taken by user compiler, "reference_time": reference time taken by qiskit circuit mapper/unroler (if verbose), "cost_original": original circuit cost function value (if verbose), "cost_reference": reference circuit cost function value (if verbose), "cost_optimized": optimized circuit cost function value, "coupling_correct_original": (bool) does original circuit satisfy the coupling map (if verbose), "coupling_correct_reference": (bool) does circuit produced by the qiskit mapper/unroler satisfy the coupling map (if verbose), "coupling_correct_optimized": (bool) does optimized circuit satisfy the coupling map, "state_correct_optimized": (bool) does optimized circuit return correct state } } """ # Initial Setup basis_gates = 'u1,u2,u3,cx,id' # or use "U,CX?" gate_costs = {'id': 0, 'u1': 0, 'measure': 0, 'reset': 0, 'barrier': 0, 'u2': 1, 'u3': 1, 'U': 1, 'cx': 10, 'CX': 10} # Results data structure results = {} # Load QASM files and extract DAG circuits for name, circuit in test_circuits.items(): qp = QuantumProgram() qp.load_qasm_text( circuit["qasm"], name, basis_gates=basis_gates) circuit["dag_original"] = qasm_to_dag_circuit(circuit["qasm"], basis_gates=basis_gates) test_circuits[name] = circuit results[name] = {} # build empty result dict to be filled later # Only return results if a valid compiler function is provided if compiler_function is not None: # step through all the test circuits using multiprocessing compile_jobs = [[name,circuit,0,compiler_function,gate_costs] for name, circuit in test_circuits.items()] with Pool(len(compile_jobs)) as job: res_values_opt = job.map(_compile_circuits, compile_jobs) # stash the results in the respective dicts for job in range(len(compile_jobs)): name = res_values_opt[job].pop("name") test_circuits[name] = res_values_opt[job].pop("circuit") # remove the circuit from the results and store it results[name] = res_values_opt[job] # do the same for the reference compiler in qiskit if verbose == True if verbose: compile_jobs = [[name, circuit, 1, _qiskit_compiler, gate_costs] for name, circuit in test_circuits.items()] with Pool(len(compile_jobs)) as job: res_values = job.map(_compile_circuits, compile_jobs) # also stash this but use update so we don't overwrite anything for job in range(len(compile_jobs)): name = res_values[job].pop("name") test_circuits[name].update(res_values[job].pop("circuit")) # remove the circuit from the results and store it results[name].update(res_values[job]) # determine the final permutation of the qubits # this is done by analyzing the measurements on the qubits compile_jobs = [[name, circuit, verbose] for name, circuit in test_circuits.items()] with Pool(len(compile_jobs)) as job: res_values = job.map(_prep_sim, compile_jobs) for job in range(len(compile_jobs)): name = res_values[job].pop("name") test_circuits[name].update(res_values[job].pop("circuit")) # remove the circuit from the results and store it results[name].update(res_values[job]) # Compose qobj for simulation config = { 'data': ['quantum_state'], } # generate qobj for original circuit qobj_original = _compose_qobj("original", test_circuits, backend=backend, config=config, basis_gates=basis_gates, shots=1, seed=None) # Compute original cost and check original coupling map for circuit in qobj_original["circuits"]: name = circuit["name"] coupling_map = test_circuits[name].get("coupling_map", None) coupling_map_passes = True cost = 0 for op in circuit["compiled_circuit"]["operations"]: cost += gate_costs.get(op["name"]) # compute cost if op["name"] in ["cx", "CX"] \ and coupling_map is not None: # check coupling map coupling_map_passes &= ( op["qubits"][0] in coupling_map) if op["qubits"][0] in coupling_map: coupling_map_passes &= ( op["qubits"][1] in coupling_map[op["qubits"][0]] ) if verbose: results[name]["cost_original"] = cost results[name]["coupling_correct_original"] = coupling_map_passes # Run simulation time_start = time.process_time() #print(qobj_original['config']) res_original = qp.run(qobj_original, timeout=GLOBAL_TIMEOUT) results[name]["sim_time_orig"] = time.process_time() - time_start # Generate qobj for optimized circuit qobj_optimized = _compose_qobj("optimized", test_circuits, backend=backend, config=config, basis_gates=basis_gates, shots=1, seed=None) # Compute compiled circuit cost and check coupling map for circuit in qobj_optimized["circuits"]: name = circuit["name"] coupling_map = test_circuits[name].get("coupling_map", None) coupling_map_passes = True cost = 0 for op in circuit["compiled_circuit"]["operations"]: cost += gate_costs.get(op["name"]) # compute cost if op["name"] in ["cx", "CX"] \ and coupling_map is not None: # check coupling map coupling_map_passes &= ( op["qubits"][0] in coupling_map) if op["qubits"][0] in coupling_map: coupling_map_passes &= ( op["qubits"][1] in coupling_map[op["qubits"][0]] ) results[name]["cost_optimized"] = cost results[name]["coupling_correct_optimized"] = coupling_map_passes # Run simulation time_start = time.process_time() res_optimized = qp.run(qobj_optimized, timeout=GLOBAL_TIMEOUT) results[name]["sim_time_opti"] = time.process_time() - time_start if verbose: # Generate qobj for reference circuit optimized by qiskit compiler qobj_reference = _compose_qobj("reference", test_circuits, backend=backend, config=config, basis_gates=basis_gates, shots=1, seed=None) # Compute reference cost and check reference coupling map for circuit in qobj_reference["circuits"]: name = circuit["name"] coupling_map = test_circuits[name].get("coupling_map", None) coupling_map_passes = True cost = 0 for op in circuit["compiled_circuit"]["operations"]: cost += gate_costs.get(op["name"]) # compute cost if op["name"] in ["cx", "CX"] \ and coupling_map is not None: # check coupling map coupling_map_passes &= ( op["qubits"][0] in coupling_map) if op["qubits"][0] in coupling_map: coupling_map_passes &= ( op["qubits"][1] in coupling_map[op["qubits"][0]] ) results[name]["cost_reference"] = cost results[name]["coupling_correct_reference"] = coupling_map_passes # Skip simulation of reference State to speed things up! # time_start = time.process_time() # res_reference = qp.run(qobj_reference, timeout=GLOBAL_TIMEOUT) # results[name]["sim_time_ref"] = time.process_time() - time_start # Check output quantum state of optimized circuit is correct in comparison to original for name in results.keys(): # handle errors here data_original = res_original.get_data(name) if test_circuits[name]["dag_optimized"]is not None: data_optimized = res_optimized.get_data(name) correct = _compare_outputs(data_original, data_optimized, test_circuits[name]["perm_optimized"]) results[name]["state_correct_optimized"] = correct else: results[name]["state_correct_optimized"] = False # Skip verification of the reference State to speed things up! # if verbose: # if test_circuits[name]["dag_reference"] is not None: # data_reference = res_reference.get_data(name) # correct = _compare_outputs(data_original, data_reference, test_circuits[name]["perm_reference"]) # results[name]["state_correct_reference"] = correct # else: # results[name]["state_correct_reference"] = False return results def qasm_to_dag_circuit(qasm_string, basis_gates='u1,u2,u3,cx,id'): """ Convert an OPENQASM text string to a DAGCircuit. Args: qasm_string (str): OPENQASM2.0 circuit string. basis_gates (str): QASM gates to unroll circuit to. Returns: A DAGCircuit object of the unrolled QASM circuit. """ program_node_circuit = qiskit.qasm.Qasm(data=qasm_string).parse() dag_circuit = Unroller(program_node_circuit, DAGBackend(basis_gates.split(","))).execute() return dag_circuit def get_layout(qubits = 5): # load a random layout for a specifed number or qubits # only layouts for 5, 16 and 20 qubits are stored from os import path, getcwd from glob import glob from numpy.random import rand filenames = glob(path.join(getcwd(), 'layouts', '*_q' + str(qubits) + '*')) if len(filenames) > 0: file = filenames[round(rand()*len(filenames)-0.5)] return load_coupling(path.basename(file).split('.')[-2])["coupling_map"] else: return [] def load_coupling(name): """ Loads the coupling map that is given as a json file from a subfolder named layouts Args: name (string): name of the coupling map that was used when saving (corresponds to the filename without the extension .json) Returns: dict { "qubits" : the number of qubits in the coupling map "name": coupling map name "coupling_map" : actual coupling map as used by QISKit "position" : arrangement of the qubits in 2D if available "description": additional information on the coupling map } """ import json with open("./layouts/"+name+".json", 'r') as infile: temp = json.load(infile) temp["coupling_map"] = {int(ii): kk for ii, kk in temp["coupling_map"].items()} return temp def _compile_circuits(compile_args): name = compile_args[0] circuit = compile_args[1] comp_type = compile_args[2] compiler_function = compile_args[3] gate_costs = compile_args[4] res_values = {} res_values["name"] = name # initialize error circuit["error"] = {} if comp_type == 0: # Evaluate runtime of submitted compiler_function try: time_start = time.process_time() circuit["dag_optimized"] = compiler_function( circuit["dag_original"], coupling_map=circuit["coupling_map"], gate_costs=gate_costs) res_values["optimizer_time"] = time.process_time() - time_start except: circuit["dag_optimized"] = None err = traceback.format_exc() circuit["error"]["optimized"] = [err, name, circuit["coupling_map"]] res_values["optimizer_time"] = -1 print( "An error occurred in the user compiler while running " + name + " on " + str( circuit["coupling_map"]) + '.') pass else: # Evaluate runtime of qiskit compiler try: time_start = time.process_time() circuit["dag_reference"] = _qiskit_compiler( circuit["dag_original"], coupling_map=circuit["coupling_map"], gate_costs=gate_costs) res_values["reference_time"] = time.process_time() - time_start except: circuit["dag_reference"] = None err = traceback.format_exc() circuit["error"]["reference"] = [err, name, circuit["coupling_map"]] res_values["reference_time"] = -1 print("An error occurred in the QISKit compiler while running " + name + " on " + str( circuit["coupling_map"]) + '.') pass # Store the compiled circuits res_values["circuit"] = circuit return res_values def _prep_sim(sim_args): name = sim_args[0] circuit = sim_args[1] verbose = sim_args[2] res_values = {} res_values["name"] = name # For simulation, delete all of the measurements # original circuit nlist = circuit["dag_original"].get_named_nodes("measure") for n in nlist: circuit["dag_original"]._remove_op_node(n) # Skip verification of the reference State to speed things up! # if verbose and circuit["dag_reference"] is not None: # # reference circuit # nlist = circuit["dag_reference"].get_named_nodes("measure") # perm = {} # for n in nlist: # nd = circuit["dag_reference"].multi_graph.node[n] # perm[nd["qargs"][0][1]] = nd["cargs"][0][1] # circuit["dag_reference"]._remove_op_node(n) # circuit["perm_reference"] = [perm[ii] for ii in range(len(perm))] if circuit["dag_optimized"] is not None: # optimized circuit nlist = circuit["dag_optimized"].get_named_nodes("measure") perm = {} for n in nlist: nd = circuit["dag_optimized"].multi_graph.node[n] perm[nd["qargs"][0][1]] = nd["cargs"][0][1] circuit["dag_optimized"]._remove_op_node(n) circuit["perm_optimized"] = [perm[ii] for ii in range(len(perm))] res_values["circuit"] = circuit return res_values def _qiskit_compiler(dag_circuit, coupling_map=None, gate_costs=None): import copy from qiskit.mapper import swap_mapper, direction_mapper, cx_cancellation, optimize_1q_gates, Coupling from qiskit import qasm, unroll initial_layout = None coupling = Coupling(coupling_map) compiled_dag, final_layout = swap_mapper(copy.deepcopy(dag_circuit), coupling, initial_layout, trials=40, seed=19) # Expand swaps basis_gates = "u1,u2,u3,cx,id" # QE target basis program_node_circuit = qasm.Qasm(data=compiled_dag.qasm()).parse() unroller_circuit = unroll.Unroller(program_node_circuit, unroll.DAGBackend( basis_gates.split(","))) compiled_dag = unroller_circuit.execute() # Change cx directions compiled_dag = direction_mapper(compiled_dag, coupling) # Simplify cx gates cx_cancellation(compiled_dag) # Simplify single qubit gates compiled_dag = optimize_1q_gates(compiled_dag) # Return the compiled dag circuit return compiled_dag def _get_perm(perm): # get the permutation indices for the compiled quantum state given the permutation n = len(perm) res = np.arange(2**n) for num_ind in range(2**n): ss_orig = [digit for digit in bin(num_ind)[2:].zfill(n)] ss_final = ss_orig.copy() for ii in range(n): ss_final[n-1-ii] = ss_orig[n-1-perm[ii]] res[num_ind] = int(''.join(ss_final),2) return list(res) def _compare_outputs(data_original, data_compiled, permutation, threshold=ERROR_LIMIT): # compare the output states of the original and the compiled circuit # the bits of the compiled output state are permuted according to permutation before comparision if 'quantum_state' in data_original \ and 'quantum_state' in data_compiled: state = data_compiled.get('quantum_state') target = data_original.get('quantum_state') elif 'quantum_states' in data_original \ and 'quantum_states' in data_compiled: state = data_compiled.get('quantum_states')[0] target = data_original.get('quantum_states')[0] else: return False state = state[_get_perm(permutation)] fidelity = state_fidelity(target, state) #print("fidelity = ", fidelity) return abs(fidelity - 1.0) < threshold def _compose_qobj(qobj_name, test_circuits, backend="local_qasm_simulator", config=None, basis_gates='u1,u2,u3,id,cx', shots=1, max_credits=3, seed=None): qobj_out = {"id": qobj_name+"_test_circuits", "config": config, "circuits": []} qobj_out["config"] = {"max_credits": max_credits, "backend": backend, "seed": seed, "shots": shots} for name, circuit in test_circuits.items(): # only add the job if there was no error in generating the circuit if circuit["dag_"+qobj_name] is not None: job = {} job["name"] = name # config parameters used by the runner if config is None: config = {} # default to empty config dict job["config"] = copy.deepcopy(config) job["config"]["basis_gates"] = basis_gates job["config"]["seed"] = seed # Add circuit dag_circuit = copy.deepcopy(circuit["dag_"+qobj_name]) job["compiled_circuit"] = dag2json(dag_circuit, basis_gates=basis_gates) job["compiled_circuit_qasm"] = dag_circuit.qasm(qeflag=True) qobj_out["circuits"].append(copy.deepcopy(job)) return qobj_out
https://github.com/zhangx1923/QISKit_Deve_Challenge
zhangx1923
# -*- coding: utf-8 -*- # # 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. # ============================================================================= """ ---------------> please fill out this section <--------------- Your Name : Zhang xin, Xiang hong, Li yanhong, Shen ruping Your E-Mail :zhang.x@cqu.edu.cn Description of the algorithm : - How does the algorithm work? - Did you use any previously published schemes? Cite relevant papers. - What packages did you use in your code and for what part of the algorithm? - How general is your approach? Does it work for arbitrary coupling layouts (qubit number)? - Are there known situations when the algorithm fails? The optimization scheme we designed is divided into three steps: the whole qubit adjustment, the local qubit adjustment and the mergence of the single qubit gates. In the first, we extracte all the CNOT operations in the current quantum program and sorting them according to the order they perform in the quantum program. Then, traversing the CNOT operations fromfront to back, and conducting qubit ID adjustment to each illegal CNOT encountered, since each adjustment will change all of the qubit ID, so we should make sure that this adjustment does not make the previous CNOT operation illegal. And then, continue to adjust backwards until we have no way to modify the current illegal CNOT operation by adjusting the qubit ID without affecting the previous CNOT operation. Secondly, we do the following design in the algorithm: After switching the state of the qubit by using SWAP gates, it is not necessary to use these SWAP gates to restore it again, instead, we use the Qubit ID that participates in transformation as a mapping to adjust the qubit ID to the subsequent code(This is why we call it local qubit adjustment). In the end, we combine the single qubits which act on a same qubit in possible. In order to write and execute programs more conveniently, we introduced the following three Python modules: 1. re 2. copy 3. sympy It should be noted that all of these Python modules can be installed directly through PIP execution or CONDA instructions, and the code can be successfully executed on Windows and MAC systems. Our method is general and works well for arbitrary coupling layouts and all qubits number. For more details, you can read the IBM Developer challenge code manual. ---------------> please fill out this section <--------------- """ # Include any Python modules needed for your implementation here import re from Optimize import * # The following class is the input and output circuit representation for a # QISKit compiler from qiskit.dagcircuit import DAGCircuit from challenge_evaluation import * def compiler_function(dag_circuit,coupling_map=None,gate_costs=None): #Instantiate an object of that class opt = Optimize(dag_circuit,coupling_map) #print(opt.qasm) #print(dag_circuit.qasm()) #there are two cases: #1. the original qasm code can be exeucted on the platform after adjusted the id of qubit #2. the original qasm can't be exeucted by adjusting the id, then we have to use SWAP gates oriQASM = dag_circuit.qasm() opt.setQASM(oriQASM) #the QASM can be executed on the targat platform tarQASM = opt.qasm if opt.badCnot != []: oriQASM = opt.adjustID() #generate the final qasm code tarQASM = opt.generateQASM(oriQASM) tarQASM = opt.reduceSameGate(tarQASM) #generate the instance of DAGCircuit resCircuit = qasm_to_dag_circuit(tarQASM) return resCircuit # def compiler_function(dag_circuit, coupling_map=None, gate_costs=None): # """ # Modify a DAGCircuit based on a gate cost function. # Instructions: # Your submission involves filling in the implementation # of this function. The function takes as input a DAGCircuit # object, which can be generated from a QASM file by using the # function 'qasm_to_dag_circuit' from the included # 'submission_evaluation.py' module. For more information # on the DAGCircuit object see the or QISKit documentation # (eg. 'help(DAGCircuit)'). # Args: # dag_circuit (DAGCircuit): DAGCircuit object to be compiled. # coupling_circuit (list): Coupling map for device topology. # A coupling map of None corresponds an # all-to-all connected topology. # gate_costs (dict) : dictionary of gate names and costs. # Returns: # A modified DAGCircuit object that satisfies an input coupling_map # and has as low a gate_cost as possible. # """ # ##################### # # Put your code here # ##################### # # Example using mapper passes in Qiskit # import copy # from qiskit.mapper import swap_mapper, direction_mapper, cx_cancellation, optimize_1q_gates, Coupling # from qiskit import qasm, unroll # # initial_layout = None # coupling = Coupling(coupling_map) # #print(coupling) # compiled_dag, final_layout = swap_mapper(copy.deepcopy(dag_circuit), coupling, initial_layout, trials=40, seed=19) # # Expand swaps # basis_gates = "u1,u2,u3,cx,id" # QE target basis # program_node_circuit = qasm.Qasm(data=compiled_dag.qasm()).parse() # unroller_circuit = unroll.Unroller(program_node_circuit, # unroll.DAGBackend( # basis_gates.split(","))) # compiled_dag = unroller_circuit.execute() # # Change cx directions # compiled_dag = direction_mapper(compiled_dag, coupling) # # Simplify cx gates # cx_cancellation(compiled_dag) # # Simplify single qubit gates # compiled_dag = optimize_1q_gates(compiled_dag) # ##################### # # Put your code here # ##################### # # Return the compiled dag circuit # return compiled_dag if __name__ == "__main__": dics = {0:"circle",1:"linear",2:"neighbour",3:"center"} for q in range(9,10): for cm in range(3,4): for d in range(5,15): res = score(d,cm,q,compiler_function,'local_qasm_simulator') name= "d" + str(d) + ".txt" location = "ha/" + str(q) + "-" + dics[cm] + "/" files = open(location+name,"w") strs = "" for k in res[1].keys(): strs += str(res[1][k]) strs += "\n" strs += str(res[0]) files.write(strs) files.close()
https://github.com/zhangx1923/QISKit_Deve_Challenge
zhangx1923
# Import your solution function from challenge_submission import compiler_function # Import submission evaluation and scoring functions from challenge_evaluation import evaluate, score # Possibly useful other helper function from challenge_evaluation import qasm_to_dag_circuit, load_coupling, get_layout # Select the simulation backend to calculate the quantum states resulting from the circuits # On Windows platform the C++ Simulator is not yet available with pip install backend = 'local_qiskit_simulator' #backend = 'local_qasm_simulator' # uncomment this line if you are a Windows user # Load example circuits and coupling maps ex_nr = 1 # examples to add per qubit number. maximum is 10 with the provided circuits test_circuit_filenames = {} for i in range(ex_nr): test_circuit_filenames['circuits/random%d_n5_d5.qasm' % i] = get_layout(5) for i in range(ex_nr): test_circuit_filenames['circuits/random%d_n16_d16.qasm' % i] = get_layout(16) for i in range(ex_nr): test_circuit_filenames['circuits/random%d_n20_d20.qasm' % i] = get_layout(20) # store circuit, coupling map pairs in test_circuits. Circuits are in qasm form. test_circuits = {} for filename, cmap in test_circuit_filenames.items(): with open(filename, 'r') as infile: qasm = infile.read() test_circuits[filename] = {"qasm": qasm, "coupling_map": cmap} result = evaluate(compiler_function, test_circuits, verbose=True, backend = backend) result test_circuits['circuits/random0_n5_d5.qasm'].keys() myres = score(compiler_function, backend = backend) print("Your compiler scored %6.5f x better \ and was %6.5f x faster than the QISKit reference compiler." % myres) # import some coupling map generation functions from gencoupling import * # generate a square coupling map with 18 qubits and nearest neighbour connectivity # then remove 4 random links # also try linear, circle, rect, torus, ibmqx etc. lr = rect(6,3,order = 0.5, defects = -4) plot_layout(lr) # save the coupling map in the layouts folder lr["name"] = "random_rectangular_lattice_4_defects_q18" save_coupling(lr) # load the saved coupling by name rr = load_coupling("random_rectangular_lattice_4_defects_q18") rr["coupling_map"] plot_layout(lr) # if your working directory is the folder with this notebook you can also use import os mydir = os.curdir os.chdir('circuits') !python generator.py -n 17 -d 17 os.chdir(mydir) with open('random0_n17_d17.qasm', 'r') as infile: qasm = infile.read() print(qasm)
https://github.com/zhangx1923/QISKit_Deve_Challenge
zhangx1923
# Import your solution function from challenge_submission import compiler_function # Import submission evaluation and scoring functions from challenge_evaluation import evaluate, score # Possibly useful other helper function from challenge_evaluation import qasm_to_dag_circuit, load_coupling, get_layout # Select the simulation backend to calculate the quantum states resulting from the circuits # On Windows platform the C++ Simulator is not yet available with pip install backend = 'local_qiskit_simulator' #backend = 'local_qasm_simulator' # uncomment this line if you are a Windows user # Load example circuits and coupling maps ex_nr = 1 # examples to add per qubit number. maximum is 10 with the provided circuits test_circuit_filenames = {} for i in range(ex_nr): test_circuit_filenames['circuits/random%d_n5_d5.qasm' % i] = get_layout(5) for i in range(ex_nr): test_circuit_filenames['circuits/random%d_n16_d16.qasm' % i] = get_layout(16) for i in range(ex_nr): test_circuit_filenames['circuits/random%d_n20_d20.qasm' % i] = get_layout(20) # store circuit, coupling map pairs in test_circuits. Circuits are in qasm form. test_circuits = {} for filename, cmap in test_circuit_filenames.items(): with open(filename, 'r') as infile: qasm = infile.read() test_circuits[filename] = {"qasm": qasm, "coupling_map": cmap} result = evaluate(compiler_function, test_circuits, verbose=True, backend = backend) result test_circuits['circuits/random0_n5_d5.qasm'].keys() myres = score(compiler_function, backend = backend) print("Your compiler scored %6.5f x better \ and was %6.5f x faster than the QISKit reference compiler." % myres) # import some coupling map generation functions from gencoupling import * # generate a square coupling map with 18 qubits and nearest neighbour connectivity # then remove 4 random links # also try linear, circle, rect, torus, ibmqx etc. lr = rect(6,3,order = 0.5, defects = -4) plot_layout(lr) # save the coupling map in the layouts folder lr["name"] = "random_rectangular_lattice_4_defects_q18" save_coupling(lr) # load the saved coupling by name rr = load_coupling("random_rectangular_lattice_4_defects_q18") rr["coupling_map"] plot_layout(lr) # if your working directory is the folder with this notebook you can also use import os mydir = os.curdir os.chdir('circuits') !python generator.py -n 17 -d 17 os.chdir(mydir) with open('random0_n17_d17.qasm', 'r') as infile: qasm = infile.read() print(qasm)
https://github.com/zhangx1923/QISKit_Deve_Challenge
zhangx1923
from qiskit import QuantumCircuit from TestProperty import TestProperty import cmath import numpy as np from math import cos, sin, radians, degrees import random class Generator: """ This method generates one concrete test case and provides the exact parameters used to initialise the qubits Inputs: a TestProperty Output: a tuple containing the initialised test (a QantumCircuit), and two dictionaries, that store the theta (first one) and phi (second one) of each qubit in degrees """ def generateTest(self, testProperties: TestProperty): preConditions = testProperties.preConditions phiVal = {} thetaVal = {} #Adds 2 classical bits to read the results of any assertion #Those bits will not interfere with the normal functioning of the program if testProperties.minQubits == testProperties.maxQubits: noOfQubits = testProperties.minQubits else: noOfQubits = np.random.randint(testProperties.minQubits, testProperties.maxQubits) qc = QuantumCircuit(noOfQubits, testProperties.noOfClassicalBits + 2) for key, value in preConditions.items(): #ignores the keys that are outside of the range if key >= noOfQubits: continue #converts from degrees to radian randPhi = random.randint(value.minPhi, value.maxPhi) randTheta = random.randint(value.minTheta, value.maxTheta) #stores the random values generated phiVal[key] = randPhi thetaVal[key] = randTheta randPhiRad = radians(randPhi) randThetaRad = radians(randTheta) """WHY THIS HAPPEN""" value0 = cos(randThetaRad/2) value1 = cmath.exp(randPhiRad * 1j) * sin(randThetaRad / 2) qc.initialize([value0, value1], key) return (qc, thetaVal, phiVal) """ This method runs self.generateTest to generate the specified amount of tests in the TestProperty Inputs: a TestProperty Outputs: a list of what self.generateTests returns (a tuple containing a QuantumCircuit, a dictionary for the thetas used and a dictionary for the phi used in degrees) """ def generateTests(self, testProperties: TestProperty): return [self.generateTest(testProperties) for _ in range(testProperties.noOfTests)]
https://github.com/LSEG-API-Samples/Article.EikonAPI.Python.PortfolioOptimizationUsingQiskitAndEikonDataAPI
LSEG-API-Samples
# ! pip install qiskit qiskit-finance==0.2.1 import warnings warnings.filterwarnings("ignore") import qiskit.tools.jupyter %qiskit_version_table # from qiskit import IBMQ # IBMQ.save_account('MY_API_TOKEN') # ! pip install eikon import eikon as ek print("Eikon version: ", ek.__version__) eikon_key = open("eikon.txt","r") ek.set_app_key(str(eikon_key.read())) eikon_key.close() import numpy as np import pandas as pd import datetime import matplotlib.pyplot as plt import seaborn as sns from qiskit import Aer from qiskit_finance.data_providers._base_data_provider import BaseDataProvider from qiskit.finance.applications.ising import portfolio from qiskit.circuit.library import TwoLocal from qiskit.aqua import QuantumInstance from qiskit.optimization.applications.ising.common import sample_most_likely from qiskit.aqua.algorithms import VQE, QAOA, NumPyMinimumEigensolver from qiskit.aqua.components.optimizers import COBYLA class EikonDataProvider(BaseDataProvider): """ The abstract base class for Eikon data_provider. """ def __init__(self, stocks_list, start_date, end_date): ''' stocks -> List of interested assets start -> start date to fetch historical data end -> ''' super().__init__() self._stocks = stocks_list self._start = start_date self._end = end_date self._data = [] self.stock_data = pd.DataFrame() def run(self): self._data = [] stocks_notfound = [] stock_data = ek.get_timeseries(self._stocks, start_date=self._start, end_date=self._end, interval='daily', corax='adjusted') for ticker in self._stocks: stock_value = stock_data[ticker]['CLOSE'] self.stock_data[ticker] = stock_data[ticker]['CLOSE'] if stock_value.dropna().empty: stocks_notfound.append(ticker) self._data.append(stock_value) # List of stocks stock_list = ['FB.O', 'AAPL.O', 'AMZN.O', 'NFLX.O', 'GOOGL.O'] # Start Date start_date = datetime.datetime(2019,6,10) # End Date end_date = datetime.datetime(2021,10,20) # Set number of equities to the number of stocks num_assets = len(stock_list) # Set the risk factor risk_factor = 0.7 # Set budget budget = 2 # Scaling of budget penalty term will be dependant on the number of assets penalty = num_assets data = EikonDataProvider(stocks_list = stock_list, start_date=start_date, end_date=end_date) data.run() # Top 5 rows of data df = data.stock_data df.head() df.describe() # Closing Price History fig, ax = plt.subplots(figsize=(15, 8)) ax.plot(df) plt.title('Close Price History') plt.xlabel('Date',fontsize =20) plt.ylabel('Price in USD',fontsize = 20) ax.legend(df.columns.values) plt.show() # # Mean value of each equities # mean_vector = data.get_mean_vector() # sns.barplot(y=mean_vector, x = stock_list) # plt.show() mu = data.get_period_return_mean_vector() sns.barplot(y=mu, x = stock_list) plt.show() # Covariance Matrix sigma = data.get_period_return_covariance_matrix() f, ax = plt.subplots(figsize=(10, 8)) sns.heatmap(sigma, mask=np.zeros_like(sigma, dtype=np.bool), annot=True, square=True, ax=ax, xticklabels=stock_list, yticklabels=stock_list) plt.title("Covariance between Equities") plt.show() # Correlation Matrix corr = df.corr() f, ax = plt.subplots(figsize=(10, 8)) sns.heatmap(corr, mask=np.zeros_like(corr, dtype=np.bool), annot=True, square=True, ax=ax, xticklabels=stock_list, yticklabels=stock_list) plt.title("Correlation between Equities") plt.show() sns.pairplot(df) plt.show() # returns = np.log(df/df.shift(1)).dropna() # returns.head() # sns.pairplot(returns) # plt.show() # Retrieve Hamiltonian qubitOp, offset = portfolio.get_operator(mu, sigma, risk_factor, budget, penalty) def index_to_selection(i, num_assets): s = "{0:b}".format(i).rjust(num_assets) x = np.array([1 if s[i]=='1' else 0 for i in reversed(range(num_assets))]) return x def selection_to_picks(num_assets, selection): purchase = [] for i in range(num_assets): if selection[i] == 1: purchase.append(stock_list[i]) return purchase # def print_result(result): # selection = sample_most_likely(result.eigenstate) # value = portfolio.portfolio_value(selection, mu, sigma, q, budget, penalty) # print(f"!!! Optimal: portfolio holdings !!!") # return selection def print_result(result): selection = sample_most_likely(result.eigenstate) value = portfolio.portfolio_value(selection, mu, sigma, risk_factor, budget, penalty) print('Optimal: selection {}, value {:.4f}'.format(selection, value)) eigenvector = result.eigenstate if isinstance(result.eigenstate, np.ndarray) else result.eigenstate.to_matrix() probabilities = np.abs(eigenvector)**2 i_sorted = reversed(np.argsort(probabilities)) print('\n----------------- Full result ---------------------') print('selection\tvalue\t\tprobability') print('---------------------------------------------------') states, values, probs = [], [], [] for i in i_sorted: x = index_to_selection(i, num_assets) value = portfolio.portfolio_value(x, mu, sigma, risk_factor, budget, penalty) probability = probabilities[i] print('%10s\t%.4f\t\t%.4f' %(x, value, probability)) states.append(''.join(str(i) for i in x)) values.append(value) probs.append(probability) return selection, states, values, probs def numpyEigensolver(qubitOp): selections = [] exact_eigensolver = NumPyMinimumEigensolver(qubitOp) result = exact_eigensolver.run() selection, state, values, probabilities = print_result(result) print(selection_to_picks(num_assets, selection)) return state, values, probabilities #Classical Benchmark %time state, values, probabilities = numpyEigensolver(qubitOp) # ['FB.O', 'AAPL.O', 'AMZN.O', 'NFLX.O', 'GOOGL.O'] # f, ax = plt.subplots(figsize=(20, 8)) # optimized_value = sns.barplot(state, values) # for item in optimized_value.get_xticklabels(): # item.set_rotation(45) # plt.title("Optimized Values of Each Possible Combination of Assets", fontsize=25) #Lower the value is, best optimal set of asset it is # plt.xlabel('Possible Combinations of Assets',fontsize =20) # plt.ylabel('Optimized Values',fontsize = 20) # plt.show() f, ax = plt.subplots(figsize=(20, 8)) optimized_value = sns.barplot(state, probabilities) for item in optimized_value.get_xticklabels(): item.set_rotation(45) plt.title("Probabilites of Each Possible Combination of Assets", fontsize=25) # Probability of Max Return at given risk level plt.xlabel('Possible Combinations of Assets',fontsize =20) plt.ylabel('Probability',fontsize = 20) plt.show() def vqe(qubitOp): backend = Aer.get_backend('statevector_simulator') # You can switch to different backends by providing the name of backend. seed = 50 cobyla = COBYLA() cobyla.set_options(maxiter=1000) ry = TwoLocal(qubitOp.num_qubits, 'ry', 'cz', reps=3, entanglement='full') vqe = VQE(qubitOp, ry, cobyla) vqe.random_seed = seed quantum_instance = QuantumInstance(backend=backend, seed_simulator=seed, seed_transpiler=seed) result = vqe.run(quantum_instance) selection, state, values, probabilities = print_result(result) print(selection_to_picks(num_assets, selection)) return state, values, probabilities # Variational Quantum EigenSolver %time state, values, probabilities = vqe(qubitOp) # ['FB.O', 'AAPL.O', 'AMZN.O', 'NFLX.O', 'GOOGL.O'] # f, ax = plt.subplots(figsize=(20, 8)) # optimized_value = sns.barplot(state, values) # for item in optimized_value.get_xticklabels(): # item.set_rotation(45) # plt.title("Optimized Values of Each Possible Combination of Assets", fontsize=25) #Lower the value is, best optimal set of asset it is # plt.xlabel('Possible Combinations of Assets',fontsize =20) # plt.ylabel('Optimized Values',fontsize = 20) # plt.show() f, ax = plt.subplots(figsize=(20, 8)) optimized_value = sns.barplot(state, probabilities) for item in optimized_value.get_xticklabels(): item.set_rotation(45) plt.title("Probabilites of Each Possible Combination of Assets", fontsize=25) # Probability of Max Return at given risk level plt.xlabel('Possible Combinations of Assets',fontsize =20) plt.ylabel('Probability',fontsize = 20) plt.show() def qaoa(qubitOp): backend = Aer.get_backend('statevector_simulator') # You can switch to different backends by providing the name of backend. seed = 50 cobyla = COBYLA() cobyla.set_options(maxiter=1000) qaoa = QAOA(qubitOp, cobyla, 3) qaoa.random_seed = seed quantum_instance = QuantumInstance(backend=backend, seed_simulator=seed, seed_transpiler=seed) results= qaoa.run(quantum_instance) selection, state, values, probabilities = print_result(results) print(selection_to_picks(num_assets, selection)) return state, values, probabilities # QAOA (Quantum Approximate Optimization Algorithm) %time state, values, probabilities = qaoa(qubitOp) # ['FB.O', 'AAPL.O', 'AMZN.O', 'NFLX.O', 'GOOGL.O'] # f, ax = plt.subplots(figsize=(20, 8)) # optimized_value = sns.barplot(state, values) # for item in optimized_value.get_xticklabels(): # item.set_rotation(45) # plt.title("Optimized Values of Each Possible Combination of Assets", fontsize=25) #Lower the value is, best optimal set of asset it is # plt.xlabel('Possible Combinations of Assets',fontsize =20) # plt.ylabel('Optimized Values',fontsize = 20) # plt.show() f, ax = plt.subplots(figsize=(20, 8)) optimized_value = sns.barplot(state, probabilities) for item in optimized_value.get_xticklabels(): item.set_rotation(45) plt.title("Probabilites of Each Possible Combination of Assets", fontsize=25) # Probability of Max Return at given risk level plt.xlabel('Possible Combinations of Assets',fontsize =20) plt.ylabel('Probability',fontsize = 20) plt.show()
https://github.com/GlazeDonuts/Variational-Quantum-Classifier
GlazeDonuts
# Installing a few dependencies !pip install --upgrade seaborn==0.10.1 !pip install --upgrade scikit-learn==0.23.1 !pip install --upgrade matplotlib==3.2.0 !pip install --upgrade pandas==1.0.4 !pip install --upgrade qiskit==0.19.6 !pip install --upgrade plotly==4.9.0 !pip install qiskit-qcgpu-provider # The output will be cleared after installation from IPython.display import clear_output clear_output() # we have imported a few libraries we think might be useful from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import Aer from qiskit import * import numpy as np from qiskit.visualization import plot_bloch_multivector, plot_histogram %matplotlib inline import matplotlib.pyplot as plt import time from qiskit.circuit.library import ZZFeatureMap, ZFeatureMap, PauliFeatureMap, RealAmplitudes, EfficientSU2 from qiskit.aqua.utils import split_dataset_to_data_and_labels, map_label_to_class_name from qiskit.aqua import QuantumInstance from qiskit.aqua.algorithms import VQC from qiskit.aqua.components.optimizers import COBYLA # The the write_and_run() magic function creates a file with the content inside the cell that it is run. from IPython.core.magic import register_cell_magic @register_cell_magic def write_and_run(line, cell): argz = line.split() file = argz[-1] mode = 'w' with open(file, mode) as f: f.write(cell) get_ipython().run_cell(cell) !wget -O "dataset_4_9.csv" https://gitlab.com/GlazeDonuts/vqc-datasets/-/raw/master/datasets/dataset_4_9.csv data = np.loadtxt("dataset_4_9.csv", delimiter=",") # extracting the first column which contains the labels data_labels = data[:, :1].reshape(data.shape[0],) # extracting all the columns but the first which are our features data_features = data[:, 1:] import plotly.express as px import pandas as pd # Creating a dataframe using pandas only for the purpose fo plotting df = pd.DataFrame({'Component 0':data_features[:,0], 'Component 1':data_features[:,1], 'Component 2':data_features[:,2], 'label':data_labels}) fig = px.scatter_3d(df, x='Component 0', y='Component 1', z='Component 2', color='label') fig.show() ### WRITE YOUR CODE BETWEEN THESE LINES - START # Percentage of corpus considered for training corp_perc = 4 # Calculating the total number of samples corp_split = int(corp_perc * data.shape[0] // 100) # Choosing random samples from data points corresponind to four and nine four_indices = np.random.choice(np.arange(data.shape[0]//2), corp_split//2, replace=False) nine_indices = np.random.choice(np.arange(data.shape[0]//2, data.shape[0]), corp_split//2, replace=False) my_data_four = np.copy(data[four_indices]) my_data_nine = np.copy(data[nine_indices]) # Forming data set with samples of fours and nines my_data = np.concatenate((my_data_four, my_data_nine)) test_perc = 5 semi_split = int(test_perc*my_data.shape[0]//200) # Creating training and testing input dictionaries training_input = {'A': my_data_four[:-semi_split, 1:], 'B': my_data_nine[:-semi_split, 1:]} test_input = {'A': my_data_four[-semi_split:, 1:], 'B': my_data_nine[-semi_split:, 1:]} testing_input = np.concatenate((my_data_four[-semi_split:, 1:], my_data_nine[-semi_split:, 1:])) testing_labels = np.concatenate((my_data_four[-semi_split:, :1], my_data_nine[-semi_split:, :1])) ### WRITE YOUR CODE BETWEEN THESE LINES - END %%write_and_run feature_map.py # The write_and_run function writes the content in this cell into the file "feature_map.py" ### WRITE YOUR CODE BETWEEN THESE LINES - START # Import libraries that are used in the function below. from qiskit import QuantumCircuit from qiskit.circuit import ParameterVector from qiskit.circuit.library import ZZFeatureMap, ZFeatureMap, PauliFeatureMap ### WRITE YOUR CODE BETWEEN THESE LINES - END def feature_map(): # BUILD FEATURE MAP HERE - START # Import required qiskit libraries if additional libraries are required # Build the feature map reps = 3 num_qubits = 3 feature_map = QuantumCircuit(num_qubits) x = ParameterVector('x', length=num_qubits) # EXPERIMENT 1 : 64 # for _ in range(reps): # for i in range(num_qubits): # feature_map.rx(x[i], i) # for i in range(num_qubits): # for j in range(i + 1, num_qubits): # feature_map.cx(i, j) # feature_map.u1(x[i] * x[j], j) # feature_map.cx(i, j) # EXPERIMENT 2: 63.5 # for _ in range(reps): # for i in range(num_qubits): # feature_map.h(i) # for i in range(num_qubits - 1): # feature_map.cz(i, i+1) # for i in range(num_qubits): # feature_map.rx(x[i], i) # for i in range(num_qubits-1, 0, -1): # feature_map.cz(i, i-1) # for i in range(num_qubits): # feature_map.h(i) # #EXPERIMENT 3: 72.9 # for _ in range(reps): # for i in range(num_qubits): # feature_map.rx(x[i], i) # feature_map.rz(x[i], i) # for i in range(num_qubits-1, 0, -1): # feature_map.cx(i, i-1) #EXPERIMENT 4: 71.2 # for _ in range(reps): # for i in range(num_qubits): # feature_map.rx(x[i], i) # feature_map.rz(x[i], i) # for i in range(num_qubits-1, 0, -1): # feature_map.cz(i, i-1) # EXPERIMENT 5: 75.6 # for _ in range(reps): # for i in range(num_qubits): # feature_map.rx(x[i], i) # feature_map.rz(x[i], i) # for i in range(num_qubits-1, 0, -1): # feature_map.rz(x[i-1], i-1) # feature_map.cx(i, i-1) # feature_map.rz(x[i-1], i-1) # EXPERIMENT 6: 75.7 # for _ in range(reps): # for i in range(num_qubits): # feature_map.rx(x[i], i) # feature_map.rz(x[i], i) # for i in range(num_qubits-1, 0, -1): # feature_map.rx(x[i-1], i-1) # feature_map.cx(i, i-1) # feature_map.rx(x[i-1], i-1) # Experiment 7: 76.8 with 2 reps and 4 vqc # for _ in range(reps): # for i in range(num_qubits): # feature_map.rx(x[i], i) # feature_map.rz(x[i], i) # for control in range(num_qubits-1, -1, -1): # for target in range(num_qubits-1, -1, -1): # if control != target: # feature_map.rz(x[target], target) # feature_map.cx(control, target) # feature_map.rz(x[target], target) # Experiment 8: 75.2 # for _ in range(reps): # for i in range(num_qubits): # feature_map.rx(x[i], i) # feature_map.rz(x[i], i) # for control in range(num_qubits-1, -1, -1): # for target in range(num_qubits-1, -1, -1): # if control != target: # feature_map.rx(x[target], target) # feature_map.cx(control, target) # feature_map.rx(x[target], target) # Experiment 9: 77.6 # for _ in range(reps): # for i in range(num_qubits): # feature_map.rx(x[i], i) # feature_map.rz(x[i], i) # for control in range(num_qubits-1, 0, -1): # target = control - 1 # feature_map.rz(x[target], target) # feature_map.cx(control, target) # feature_map.rz(x[target], target) # | Upto this plus Experiment 10 (both 1 rep each), gave 79 with 4 reps of VQC # for i in range(num_qubits): # Reduced to 75.7 # feature_map.rx(x[i], i) # feature_map.rz(x[i], i) # feature_map.rz(x[1], 1) # Reduced to 70.5 # feature_map.cx(2, 1) # feature_map.rz(x[1], 1) # Experiment 10: 77.8 for _ in range(reps): for i in range(num_qubits): feature_map.rx(x[i], i) feature_map.rz(x[i], i) feature_map.barrier() for control in range(num_qubits-1, 0, -1): target = control - 1 feature_map.rx(x[target], target) feature_map.cx(control, target) feature_map.rx(x[target], target) feature_map.barrier() for i in range(num_qubits): feature_map.rx(x[i], i) feature_map.rz(x[i], i) feature_map.barrier() # Experiment 11: 65.4 with 2 vqc reps | 71.1 with 3 reps of vqc # for _ in range(reps): # for i in range(num_qubits): # feature_map.h(i) # for i in range(num_qubits - 1): # feature_map.cz(i, i+1) # for i in range(num_qubits): # feature_map.rx(x[i], i) # Experiment 12: 76.4 # for _ in range(reps): # for i in range(num_qubits): # feature_map.ry(x[i], i) # for i in range(num_qubits - 1, 0, -1): # feature_map.cz(i, i-1) # feature_map.cz(num_qubits-1, 0) # for i in range(num_qubits): # feature_map.ry(x[i], i) # Experiment 13: 70.1 # for _ in range(reps): # for i in range(num_qubits): # feature_map.ry(x[i], i) # feature_map.rz(x[i], i) # for i in range(num_qubits - 1, 0, -1): # feature_map.cx(i, i-1) # Experiment 14: 75.2 # for _ in range(reps): # for i in range(num_qubits): # feature_map.ry(x[i], i) # feature_map.rz(x[i], i) # for i in range(num_qubits - 1, 0, -1): # feature_map.cx(i, i-1) # feature_map.ry(x[1], 1) # feature_map.rz(x[1], 1) # Experiment 15: 77.3 # for _ in range(reps): # for i in range(num_qubits): # feature_map.ry(x[i], i) # feature_map.rz(x[i], i) # for i in range(num_qubits - 1, 0, -1): # feature_map.cz(i, i-1) # feature_map.ry(x[1], 1) # feature_map.rz(x[1], 1) # Experiment 16: 73.1 # for _ in range(reps): # for i in range(num_qubits): # feature_map.rx(x[i], i) # feature_map.rz(x[i], i) # feature_map.rx(x[0], 0) # feature_map.cx(num_qubits - 1, 0) # feature_map.rx(x[0], 0) # for i in range(num_qubits-2, -1, -1): # feature_map.rx(x[i+1], i+1) # feature_map.cx(i, i+1) # feature_map.rx(x[i+1], i+1) # Experiment 17: 77.0 # for _ in range(reps): # for i in range(num_qubits): # feature_map.rx(x[i], i) # feature_map.rz(x[i], i) # feature_map.rz(x[0], 0) # feature_map.cx(num_qubits - 1, 0) # feature_map.rz(x[0], 0) # for i in range(num_qubits-2, -1, -1): # feature_map.rz(x[i+1], i+1) # feature_map.cx(i, i+1) # feature_map.rz(x[i+1], i+1) # Experiment 18: 73.8 # for _ in range(reps): # for i in range(num_qubits): # feature_map.rx(x[i], i) # feature_map.rz(x[i], i) # for control in range(num_qubits - 1, 0, -1): # target = control - 1 # feature_map.rx(x[target], target) # feature_map.cx(control, target) # feature_map.rx(x[target], target) # Experiment 19: 78.7 2 reps 2 su2 | Gave 52 with RealAmp 4 reps | 68 with 2 reps and SU2 4 reps | 61.4 with 3 reps and su2 4 reps # for _ in range(2): # for i in range(num_qubits): # feature_map.ry(x[i], i) # feature_map.cx(num_qubits-1, 0) # for i in range(num_qubits-1): # feature_map.cx(i, i+1) # for i in range(num_qubits): # feature_map.ry(x[i], i) # feature_map.cx(num_qubits - 1, num_qubits - 2) # feature_map.cx(0, num_qubits - 1) # for i in range(1, num_qubits - 1): # feature_map.cx(i, i-1) # Experiment 19: 79.9 on 3 reps and 4 vqc and 10 perc data. This is almost same as experiment 10, but only the last two gates are reversed in order # for _ in range(reps): # for i in range(num_qubits): # feature_map.rx(x[i], i) # feature_map.rz(x[i], i) # for control in range(num_qubits-1, 0, -1): # target = control - 1 # feature_map.rx(x[target], target) # feature_map.cx(control, target) # feature_map.rx(x[target], target) # for i in range(num_qubits): # feature_map.rz(x[i], i) # feature_map.rx(x[i], i) # Experiment 20: 78.5 | Same as exp 10 just starting 2 and ending 2 xz swapped # 79.6 with 3 and 4 vqc 2perc data | 79.0 with 10 perc # for _ in range(reps): # Exp 20 # for i in range(num_qubits): # feature_map.rz(x[i], i) # feature_map.rx(x[i], i) # for control in range(num_qubits-1, 0, -1): # target = control - 1 # feature_map.rx(x[target], target) # feature_map.cx(control, target) # feature_map.rx(x[target], target) # for i in range(num_qubits): # feature_map.rz(x[i], i) # feature_map.rx(x[i], i) # ALL SCORES ARE WITH 2 REPS OF SU2 LINEARLY ENTAGLED BY DEFAULT UNLESS MENTIONED OTHERWISE # BUILD FEATURE MAP HERE - END #return the feature map which is either a FeatureMap or QuantumCircuit object return feature_map fmap = feature_map() fmap.draw(output='mpl', filename='final_fmap.jpg') %%write_and_run variational_circuit.py # the write_and_run function writes the content in this cell into the file "variational_circuit.py" ### WRITE YOUR CODE BETWEEN THESE LINES - START # import libraries that are used in the function below. from qiskit import QuantumCircuit from qiskit.circuit import ParameterVector from qiskit.circuit.library import RealAmplitudes, EfficientSU2, TwoLocal, NLocal ### WRITE YOUR CODE BETWEEN THESE LINES - END def variational_circuit(): # BUILD VARIATIONAL CIRCUIT HERE - START # import required qiskit libraries if additional libraries are required # build the variational circuit # var_circuit = EfficientSU2(3, entanglement='linear', reps=2, insert_barriers=True) var_circuit = TwoLocal(3, ['ry', 'rz'], ['cx'], entanglement='linear', reps=4, insert_barriers=True) # BUILD VARIATIONAL CIRCUIT HERE - END # return the variational circuit which is either a VaritionalForm or QuantumCircuit object return var_circuit var_circ = variational_circuit() var_circ.draw(output='mpl', filename='final_var_circ.jpg') def classical_optimizer(): # CHOOSE AND RETURN CLASSICAL OPTIMIZER OBJECT - START # import the required clasical optimizer from qiskit.aqua.optimizers from qiskit.aqua.components.optimizers import ADAM, SPSA, COBYLA # create an optimizer object # cls_opt = ADAM(maxiter=250, lr=1e-2, beta_1=0.9, beta_2=0.9, tol=1e-6) cls_opt = COBYLA(maxiter=100, disp=True, tol=1e-6) # cls_opt = SPSA(maxiter=250) # CHOOSE AND RETURN CLASSICAL OPTIMIZER OBJECT - END return cls_opt def call_back_vqc(eval_count, var_params, eval_val, index): print("eval_count: {}".format(eval_count)) print("var_params: {}".format(var_params)) print("eval_val: {}".format(eval_val)) print("index: {}".format(index)) # A fixed seed so that we get the same answer when the same input is given. seed = 10598 # Setting our backend to qasm_simulator with the "statevector" method on. This particular setup is given as it was # Found to perform better than most. Feel free to play around with different backend options. backend = Aer.get_backend('qasm_simulator') backend_options = {"method": "statevector"} # Creating a quantum instance using the backend and backend options taken before quantum_instance = QuantumInstance(backend, shots=1024, seed_simulator=seed, seed_transpiler=seed, backend_options=backend_options) # Creating a VQC instance which you will be used for training. Make sure you input the correct training_dataset and # Testing_dataset as defined in your program. vqc = VQC(optimizer=classical_optimizer(), feature_map=feature_map(), var_form=variational_circuit(), callback=call_back_vqc, training_dataset=training_input, # Training_input must be initialized with your training dataset test_dataset=test_input) # Testing_input must be initialized with your testing dataset start = time.process_time() result = vqc.run(quantum_instance) print("time taken: ") print(time.process_time() - start) print("testing success ratio: {}".format(result['testing_accuracy'])) print(repr(vqc.optimal_params)) %%write_and_run optimal_params.py # The write_and_run function writes the content in this cell into the file "optimal_params.py" ### WRITE YOUR CODE BETWEEN THESE LINES - START # import libraries that are used in the function below. import numpy as np ### WRITE YOUR CODE BETWEEN THESE LINES - END def return_optimal_params(): # STORE THE OPTIMAL PARAMETERS AS AN ARRAY IN THE VARIABLE optimal_parameters optimal_parameters = np.array([-0.82871645, -0.50819365, -0.83197798, 3.64408214, 0.99032149, -1.72461303, -1.8798925 , 0.22324836, 0.7469075 , -0.29177951, 1.18396727, -0.8831999 , -0.20987174, 0.1609452 , 0.72160706, -0.59644311, -1.46078401, -1.12552463, 1.34940875, -0.40489246, -1.20122758, 0.10007856, -0.95181456, -1.6608501 , 0.70347488, -0.37977302, -0.26907574, -0.08800676, -0.56356505, 1.85327073]) # STORE THE OPTIMAL PARAMETERS AS AN ARRAY IN THE VARIABLE optimal_parameters return np.array(optimal_parameters) solution = ['feature_map.py','variational_circuit.py','optimal_params.py'] file = open("summary.py","w") file.truncate(0) for i in solution: with open(i) as f: with open("summary.py", "a") as f1: for line in f: f1.write(line) file.close() #imports required for the grading function from qiskit import * from qiskit.aqua import QuantumInstance from qiskit.aqua.algorithms import VQC from qiskit.aqua.components.feature_maps import FeatureMap from qiskit.aqua.components.variational_forms import VariationalForm import numpy as np def grade(test_data, test_labels, feature_map, variational_form, optimal_params, find_circuit_cost=True, verbose=True): seed = 10598 model_accuracy = None circuit_cost=None ans = None unrolled_circuit = None result_msg='' data_dim = np.array(test_data).shape[1] dataset_size = np.array(test_data).shape[0] dummy_training_dataset=training_input = {'A':np.ones((2,data_dim)), 'B':np.ones((2, data_dim))} # converting 4's to 0's and 9's to 1's for checking test_labels_transformed = np.where(test_labels==4, 0., 1.) max_qubit_count = 6 max_circuit_cost = 2000 # Section 1 if feature_map is None: result_msg += 'feature_map variable is None. Please submit a valid entry' if verbose else '' elif variational_form is None: result_msg += 'variational_form variable is None. Please submit a valid entry' if verbose else '' elif optimal_params is None: result_msg += 'optimal_params variable is None. Please submit a valid entry' if verbose else '' elif test_data is None: result_msg += 'test_data variable is None. Please submit a valid entry' if verbose else '' elif test_labels is None: result_msg += 'test_labels variable is None. Please submit a valid entry' if verbose else '' elif not isinstance(feature_map, (QuantumCircuit, FeatureMap)): result_msg += 'feature_map variable should be a QuantumCircuit or a FeatureMap not (%s)' % \ type(feature_map) if verbose else '' elif not isinstance(variational_form, (QuantumCircuit, VariationalForm)): result_msg += 'variational_form variable should be a QuantumCircuit or a VariationalForm not (%s)' % \ type(variational_form) if verbose else '' elif not isinstance(test_data, np.ndarray): result_msg += 'test_data variable should be a numpy.ndarray not (%s)' % \ type(test_data) if verbose else '' elif not isinstance(test_labels, np.ndarray): result_msg += 'test_labels variable should be a numpy.ndarray not (%s)' % \ type(test_labels) if verbose else '' elif not isinstance(optimal_params, np.ndarray): result_msg += 'optimal_params variable should be a numpy.ndarray not (%s)' % \ type(optimal_params) if verbose else '' elif not dataset_size == test_labels_transformed.shape[0]: result_msg += 'Dataset size and label array size must be equal' # Section 2 else: # setting up COBYLA optimizer as a dummy optimizer from qiskit.aqua.components.optimizers import COBYLA dummy_optimizer = COBYLA() # setting up the backend and creating a quantum instance backend = Aer.get_backend('qasm_simulator') backend_options = {"method": "statevector"} quantum_instance = QuantumInstance(backend, shots=2000, seed_simulator=seed, seed_transpiler=seed, backend_options=backend_options) # creating a VQC instance and running the VQC.predict method to get the accuracy of the model vqc = VQC(optimizer=dummy_optimizer, feature_map=feature_map, var_form=variational_form, training_dataset=dummy_training_dataset) from qiskit.transpiler import PassManager from qiskit.transpiler.passes import Unroller pass_ = Unroller(['u3', 'cx']) pm = PassManager(pass_) # construct circuit with first datapoint circuit = vqc.construct_circuit(data[0], optimal_params) unrolled_circuit = pm.run(circuit) gates = unrolled_circuit.count_ops() if 'u3' in gates: circuit_cost = gates['u3'] if 'cx' in gates: circuit_cost+= 10*gates['cx'] if circuit.num_qubits > max_qubit_count: result_msg += 'Your quantum circuit is using more than 6 qubits. Reduce the number of qubits used and try again.' elif circuit_cost > max_circuit_cost: result_msg += 'The cost of your circuit is exceeding the maximum accpetable cost of 2000. Reduce the circuit cost and try again.' else: ans = vqc.predict(test_data, quantum_instance=quantum_instance, params=np.array(optimal_params)) model_accuracy = np.sum(np.equal(test_labels_transformed, ans[1]))/len(ans[1]) result_msg += 'Accuracy of the model is {}'.format(model_accuracy) if verbose else '' result_msg += ' and circuit cost is {}'.format(circuit_cost) if verbose else '' return model_accuracy, circuit_cost, ans, result_msg, unrolled_circuit grading_dataset_size=2000 # this value is not per digit but in total grading_features = data_features[-grading_dataset_size:] grading_labels = data_labels[-grading_dataset_size:] start = time.process_time() accuracy, circuit_cost, ans, result_msg, full_circuit = grade(test_data=grading_features, test_labels=grading_labels, feature_map=feature_map(), variational_form=variational_circuit(), optimal_params=return_optimal_params()) print("time taken: {} seconds".format(time.process_time() - start)) print(result_msg) print("Accuracy of the model: {}".format(accuracy)) print("Circuit Cost: {}".format(circuit_cost)) print("The complete unrolled circuit: ") full_circuit.draw()
https://github.com/veenaiyuri/qiskit-education
veenaiyuri
# coding: utf-8 # Copyright © 2018 IBM Research # Adapted from and/or inspired by # * initialization tool by Mirko Amico # https://github.com/Qiskit/qiskit-tutorials/blob/awards/community/awards/teach_me_quantum_2018/intro2qc/initialize.py # * qreative by James R. Wootton # https://github.com/quantumjim/qreative/blob/master/qreative/qreative.py from qiskit import * from qiskit.tools.visualization import plot_histogram as plothistogram def get_backend(device): """Returns backend object for device specified by input string.""" try: try: backend = Aer.get_backend(device) except: backend = BasicAer.get_backend(device) except: backend = IBMQ.get_backend(device) return backend def get_noise(noisy): """Returns a noise model when input is not False or None. A string will be interpreted as the name of a backend, and the noise model of this will be extracted. A float will be interpreted as an error probability for a depolarizing+measurement error model. Anything else (such as True) will give the depolarizing+measurement error model with default error probabilities.""" if noisy: if type(noisy) is str: device = get_backend(noisy) noise_model = noise.device.basic_device_noise_model( device.properties() ) else: if type(noisy) is float: p_meas = noisy p_gate1 = noisy else: p_meas = 0.08 p_gate1 = 0.04 error_meas = pauli_error([('X',p_meas), ('I', 1 - p_meas)]) error_gate1 = depolarizing_error(p_gate1, 1) error_gate2 = error_gate1.kron(error_gate1) noise_model = NoiseModel() noise_model.add_all_qubit_quantum_error(error_meas, "measure") noise_model.add_all_qubit_quantum_error(error_gate1, ["u1", "u2", "u3"]) noise_model.add_all_qubit_quantum_error(error_gate2, ["cx"]) else: noise_model = None return noise_model class QuantumAlgorithm: """""" def __init__ (self, qregs, cregs): qubit = {} if type(qregs)!=list: qregs = [(qregs,'q')] if type(cregs)!=list: cregs = [(cregs,'c')] self.qc = QuantumCircuit() for qreg in qregs: exec( 'self.'+qreg[1]+'=QuantumRegister('+str(qreg[0])+',"'+str(qreg[1])+'")' ) exec( 'self.qc.add_register( self.'+qreg[1]+')' ) for creg in cregs: exec( 'self.'+creg[1]+'=ClassicalRegister('+str(creg[0])+',"'+str(creg[1])+'")' ) exec( 'self.qc.add_register( self.'+creg[1]+')' ) # methods to implement the methods of qc, in exactly the same manner as terra 0.7 def x(self,qubit): self.qc.x(qubit) def y(self,qubit): self.qc.y(qubit) def z(self,qubit): self.qc.z(qubit) def h(self,qubit): self.qc.h(qubit) def s(self,qubit): self.qc.s(qubit) def sdg(self,qubit): self.qc.sdg(qubit) def t(self,qubit): self.qc.t(qubit) def tdg(self,qubit): self.qc.tdg(qubit) def cx(self,control,target): self.qc.cx(control,target) def cz(self,control,target): self.qc.cz(control,target) def ccx(self,control1,control2,target): self.qc.cx(control1,control2,target) def measure(self,qubit,bit): self.qc.measure(qubit,bit) def execute(self,device='qasm_simulator',noisy=False,shots=1024,histogram=True): backend = get_backend(device) try: job = execute(self.qc,backend,shots=shots,noise_model=get_noise(noisy),memory=True) data = {'counts':job.result().get_counts(),'memory':job.result().get_memory()} except: try: job = execute(self.qc,backend,shots=shots,memory=True) data = {'counts':job.result().get_counts(),'memory':job.result().get_memory()} except: job = execute(self.qc,backend,shots=shots) data = {'counts':job.result().get_counts()} if histogram: self.plot_histogram(data['counts']) return data def plot_histogram(self,counts): return plothistogram(counts)
https://github.com/veenaiyuri/qiskit-education
veenaiyuri
#initialization import matplotlib.pyplot as plt import numpy as np # importing Qiskit from qiskit import IBMQ, Aer, assemble, transpile from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit.providers.ibmq import least_busy # import basic plot tools from qiskit.visualization import plot_histogram n = 2 grover_circuit = QuantumCircuit(n) def initialize_s(qc, qubits): """Apply a H-gate to 'qubits' in qc""" for q in qubits: qc.h(q) return qc def diffuser(nqubits): qc = QuantumCircuit(nqubits) # Apply transformation |s> -> |00..0> (H-gates) for qubit in range(nqubits): qc.h(qubit) # Apply transformation |00..0> -> |11..1> (X-gates) for qubit in range(nqubits): qc.x(qubit) # Do multi-controlled-Z gate qc.h(nqubits-1) qc.mct(list(range(nqubits-1)), nqubits-1) # multi-controlled-toffoli qc.h(nqubits-1) # Apply transformation |11..1> -> |00..0> for qubit in range(nqubits): qc.x(qubit) # Apply transformation |00..0> -> |s> for qubit in range(nqubits): qc.h(qubit) # We will return the diffuser as a gate U_s = qc.to_gate() U_s.name = "U$_s$" return U_s grover_circuit = initialize_s(grover_circuit, [0,1]) grover_circuit.draw(output="mpl") grover_circuit.cz(0,1) # Oracle grover_circuit.draw(output="mpl") # Diffusion operator (U_s) grover_circuit.append(diffuser(n),[0,1]) grover_circuit.draw(output="mpl") sim = Aer.get_backend('aer_simulator') # we need to make a copy of the circuit with the 'save_statevector' # instruction to run on the Aer simulator grover_circuit_sim = grover_circuit.copy() grover_circuit_sim.save_statevector() qobj = assemble(grover_circuit_sim) result = sim.run(qobj).result() statevec = result.get_statevector() from qiskit_textbook.tools import vector2latex vector2latex(statevec, pretext="|\\psi\\rangle =") grover_circuit.measure_all() aer_sim = Aer.get_backend('aer_simulator') qobj = assemble(grover_circuit) result = aer_sim.run(qobj).result() counts = result.get_counts() plot_histogram(counts) nqubits = 4 qc = QuantumCircuit(nqubits) # Apply transformation |s> -> |00..0> (H-gates) for qubit in range(nqubits): qc.h(qubit) # Apply transformation |00..0> -> |11..1> (X-gates) for qubit in range(nqubits): qc.x(qubit) qc.barrier() # Do multi-controlled-Z gate qc.h(nqubits-1) qc.mct(list(range(nqubits-1)), nqubits-1) # multi-controlled-toffoli qc.h(nqubits-1) qc.barrier() # Apply transformation |11..1> -> |00..0> for qubit in range(nqubits): qc.x(qubit) # Apply transformation |00..0> -> |s> for qubit in range(nqubits): qc.h(qubit) qc.draw(output="mpl") from qiskit.circuit import classical_function, Int1 # define a classical function f(x): this returns 1 for the solutions of the problem # in this case, the solutions are 1010 and 1100 @classical_function def f(x1: Int1, x2: Int1, x3: Int1, x4: Int1) -> Int1: return (x1 and not x2 and x3 and not x4) or (x1 and x2 and not x3 and not x4) nqubits = 4 Uf = f.synth() # turn it into a circuit oracle = QuantumCircuit(nqubits+1) oracle.compose(Uf, inplace=True) oracle.draw(output="mpl") # We will return the diffuser as a gate #U_f = oracle.to_gate() # U_f.name = "U$_f$" # return U_f
https://github.com/veenaiyuri/qiskit-education
veenaiyuri
from qiskit import * from qiskit.tools.visualization import plot_histogram, circuit_drawer q = QuantumRegister(3) c = ClassicalRegister(3) qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.cx(q[1], q[2]) qc.cx(q[0], q[1]) qc.h(q[0]) qc.measure(q[0], c[0]) qc.measure(q[1], c[1]) qc.cx(q[1], q[2]) qc.cz(q[0], q[2]) qc.h(q[2]) qc.measure(q[2], c[2]) backend = Aer.get_backend('qasm_simulator') job_sim = execute(qc, backend, shots=1024) sim_result = job_sim.result() measurement_result = sim_result.get_counts(qc) print(measurement_result) plot_histogram(measurement_result)
https://github.com/veenaiyuri/qiskit-education
veenaiyuri
from QiskitEducation import * qc = QuantumAlgorithm(3,3) q = qc.q; c = qc.c qc.h(q[0]) qc.h(q[1]) qc.cx(q[1], q[2]) qc.cx(q[0], q[1]) qc.h(q[0]) qc.measure(q[0], c[0]) qc.measure(q[1], c[1]) qc.cx(q[1], q[2]) qc.cz(q[0], q[2]) qc.h(q[2]) qc.measure(q[2], c[2]) data = qc.execute(histogram=True) print(data['counts']) qc.plot_histogram(data['counts'])
https://github.com/veenaiyuri/qiskit-education
veenaiyuri
from QiskitEducation import * qc = QuantumAlgorithm(3,3) qc.h(qc.q[0]) qc.h(qc.q[1]) qc.cx(qc.q[1], qc.q[2]) qc.cx(qc.q[0], qc.q[1]) qc.h(qc.q[0]) qc.measure(qc.q[0], qc.c[0]) qc.measure(qc.q[1], qc.c[1]) qc.cx(qc.q[1], qc.q[2]) qc.cz(qc.q[0], qc.q[2]) qc.h(qc.q[2]) qc.measure(qc.q[2], qc.c[2]) print(qc.execute()['counts'])
https://github.com/RohanGautam/storeQ
RohanGautam
import qiskit as qk from qiskit import QuantumCircuit, execute, Aer from qiskit.visualization import plot_histogram, plot_bloch_vector from sklearn.preprocessing import LabelBinarizer from math import sqrt, pi import numpy as np import cv2 import math from tqdm import tqdm # custom : from customLabelBinarizer import CustomLabelBinarizer import imutils info = "rohan" org = cv2.imread('/home/rohan/Desktop/Python_files/quantumExploring/img/puppy.png') img = cv2.cvtColor(org, cv2.COLOR_BGR2GRAY) img = imutils.resize(img, width=100) row1 = img[0] # cv2.imshow("image", img) # cv2.waitKey(0) def closestPowerOfTwo(n): return 2**math.ceil(math.log(n)/math.log(2)) def highestPowerOfTwo(img): '''highest power of two amongst all rows''' maxVal = max([closestPowerOfTwo(len(list(set(row)))) for row in img]) return (maxVal, int(math.log(maxVal,2))) def removePadding(matrix): '''remove padded zeroes from the matrix to give the original LabelBinarizer binary vectors''' # calculate index of the '1' that has the furthest/max index. # This will be the boundary, beyond which we will discard the columns (zeroes) boundary = max([list(l).index(1) for l in matrix]) # index, begins from 0 print(boundary) return matrix[:, :boundary+1] # return sliced matrix powerVal, exponent = highestPowerOfTwo(img) lb_binarizers = [] rows_circuits = [] def startUpload (): print('[INFO] One-Hot encoding matrix rows') for row in tqdm(img) : # one-hot encode them -> convert them to binary vectors # why? because sum of amplitudes we pass should be = 1 lb = CustomLabelBinarizer() r_oneHot = lb.fit_transform(row) lb_binarizers.append(lb) # pad extra with zeroes, so that row length is the max power of 2 padNum = powerVal-r_oneHot.shape[1] r_padded = np.hstack((r_oneHot, np.zeros((r_oneHot.shape[0], padNum), dtype=r_oneHot.dtype))) # qbits = [] # # create qbits circuits = [] for vector in r_padded: qBitNum = exponent qc = QuantumCircuit(qBitNum) initial_state = vector # Define initial_state as |1>. sum of amplitudes = 1, has to be power of 2 qc.initialize(initial_state, list(range(qBitNum))) # Apply initialisation operation to the 0th qubit # qc.draw() circuits.append(qc) rows_circuits.append(circuits) backend = Aer.get_backend('statevector_simulator') def getOneHotVector(qc): result = execute(qc,backend).result() out_state = result.get_statevector() # print(out_state) vector = [int(x.real) for x in out_state] return vector def startDownload(): finalImage = [] for i in tqdm(range(len(rows_circuits))): row_circuit = rows_circuits[i] retrievedVectors=[] for circuit in row_circuit: retrievedVectors.append(getOneHotVector(circuit)) retrievedVectors = np.array(retrievedVectors) # convert to numpy array retrievedVectors = removePadding(retrievedVectors) # set the lb_binarizer to lb_binarizers[-1] to make it seem like it was hazy(error before) row = lb_binarizers[i].inverse_transform(retrievedVectors)# the final vector print(row.shape) finalImage.append(row) finalImage = np.array(finalImage) ## show it : cv2.imshow("Reconstructed image", finalImage) cv2.waitKey(0) # startUpload() # startDownload()
https://github.com/QC-Hub/Examples
QC-Hub
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute from qiskit import BasicAer ''' APItoken="APItoken" config = { "url": 'https://quantumexperience.ng.bluemix.net/api'} ''' n1 = input("Enter a binary number with less than 8 digits:") n2 = input("Enter another binary number with less than 8 digits:") l1 = len(n1) l2 = len(n2) n = 0 if l1>l2: n = l1 else: n = l2 a = QuantumRegister(n) #First number b = QuantumRegister(n+1) #Second number c = QuantumRegister(n) #Carry bits cl = ClassicalRegister(n+1) #Clasical register to store the value of qubits qc = QuantumCircuit(a,b,c,cl) #Creating a quantum circuit using quantum registers and classical registers for i in range(l1): if n1[i] == "1": qc.x(a[l1-(i+1)]) #Changing all qubits corresponding to 1 in the first number to |1> using CNOT gate for i in range(l2): if n2[i] == "1": qc.x(b[l2-(i+1)]) #Changing all qubits corresponding to 1 in the second number to |1> using CNOT gate for i in range(n-1): qc.ccx(a[i],b[i],c[i+1]) #Applying CCNOT gate with current qubits of the two numbers as control and changes the next carry bit qc.cx(a[i],b[i]) #Applying CNOT gate with the qubits of first number as control and make changes to the qubits of the second number qc.ccx(c[i],b[i],c[i+1]) #Applying CCNOT gate with the current carry bit and current qubit of the second number as control and make changes to the next carry bit qc.ccx(a[n-1],b[n-1],b[n]) #Making changes corresponding to the final carry bits qc.cx(a[n-1],b[n-1]) qc.ccx(c[n-1],b[n-1],b[n]) qc.cx(c[n-1],b[n-1]) for i in range(n-1): #Reversing the qubits qc.ccx(c[(n-2)-i],b[(n-2)-i],c[(n-1)-i]) qc.cx(a[(n-2)-i],b[(n-2)-i]) qc.ccx(a[(n-2)-i],b[(n-2)-i],c[(n-1)-i]) qc.cx(c[(n-2)-i],b[(n-2)-i]) qc.cx(a[(n-2)-i],b[(n-2)-i]) for i in range(n+1): qc.measure(b[i],cl[i]) #Measuring thre qubits and storing its values to a classical register print(qc) #Printing the quantum circuit using ASCII characters backend = BasicAer.get_backend('qasm_simulator') #Creating a backend using virtual qasm simulator job = execute(qc, backend, shots=2) #Creating a job counts = job.result().get_counts(qc) #Calculating the occurances of each output print(counts)
https://github.com/QC-Hub/Examples
QC-Hub
from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit, execute from qiskit import Aer import numpy as np import sys N=int(sys.argv[1]) filename = sys.argv[2] backend = Aer.get_backend('unitary_simulator') def GHZ(n): if n<=0: return None circ = QuantumCircuit(n) # Put your code below # ---------------------------- circ.h(0) for x in range(1,n): circ.cx(x-1,x) # ---------------------------- return circ circuit = GHZ(N) job = execute(circuit, backend, shots=8192) result = job.result() array = result.get_unitary(circuit,3) np.savetxt(filename, array, delimiter=",", fmt = "%0.3f")
https://github.com/QC-Hub/Examples
QC-Hub
from qiskit.providers.ibmq import least_busy from qiskit import IBMQ from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute #IBMQ.save_account("Account id") APItoken="APItoken" config = { "url": 'https://quantumexperience.ng.bluemix.net/api'} #IBMQ.backends() #Search for available quantum machines IBMQ.load_accounts() print("Available backends") print(IBMQ.backends()) large_enough_devices = IBMQ.backends(filters=lambda x : x.configuration().n_qubits >3 and not x.configuration().simulator) backend = least_busy(large_enough_devices) print(backend) print("The best backend is "+ backend.name()) #Creating quantum circuits q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q,c) m = QuantumCircuit(q,c) qc.h(q) qc.cx(q[0],q[1]) m.measure(q,c) t = qc + m #Executing the quantum circuits in a real quantum computer job = execute(t,backend,shots=1000) counts = job.result().get_counts(t) print(counts)
https://github.com/QC-Hub/Examples
QC-Hub
import matplotlib.pyplot as plt import numpy as np from math import pi from qiskit import QuantumCircuit ,QuantumRegister ,ClassicalRegister, 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(1) qc = QuantumCircuit(q) qc.u3(pi/2 ,pi/2 ,pi/2 ,q) qc.draw() job = execute(qc, backend) job.result().get_unitary(qc, decimals=3)
https://github.com/menegolli/Quantum_synth
menegolli
#!/usr/bin/env python # coding: utf-8 # In[1]: from qiskit import * import numpy as np from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute from qiskit import Aer, IBMQ # import the Aer and IBMQ providers from qiskit.providers.aer import noise # import Aer noise models from qiskit.tools.monitor import job_monitor from RenormalizeProbability import * # In[7]: def ChooseBackEnd(quantumCircuit, backendType="statevector_simulator", qubitsToBeMeasured=range(4), numberShots=4096, noisePresent=False, RealDeviceName="ibmq_ourense",number=12): if backendType == "statevector_simulator": backend = Aer.get_backend('statevector_simulator') result = execute(quantumCircuit, backend).result() probabilityVectors = np.square(np.absolute(result.get_statevector())) listForMusic = [] for k in range(2**len(qubitsToBeMeasured)): listForMusic.append("%.3f" % (probabilityVectors[k])) elif backendType == "qasm_simulator": if noisePresent == False: # no noise quantumCircuit.measure(qubitsToBeMeasured, qubitsToBeMeasured) print(qubitsToBeMeasured) backend = Aer.get_backend('qasm_simulator') result = execute(quantumCircuit, backend, shots=numberShots).result() counts = result.get_counts() listForMusic = [] for i in range(2**len(qubitsToBeMeasured)): bitstring = str(bin(i)[2:]) bitstring = "0"*(4-len(bitstring))+bitstring if bitstring in counts.keys(): listForMusic.append("%.3f" % (counts[bitstring]/float(numberShots))) else: listForMusic.append("0.000") else: print(qubitsToBeMeasured) quantumCircuit.measure(qubitsToBeMeasured,qubitsToBeMeasured) provider=IBMQ.save_account('XXX-YOUR-TOKEN') # simulate noise of a real device IBMQ.load_account() IBMQ.providers() device = IBMQ.get_provider(hub='ibm-q', group='open', project='main').get_backend(RealDeviceName) properties = device.properties() coupling_map = device.configuration().coupling_map # Generate an Aer noise model for device noise_model = noise.device.basic_device_noise_model(properties) basis_gates = noise_model.basis_gates # Perform noisy simulation backend = Aer.get_backend('qasm_simulator') job_sim = execute(quantumCircuit, backend, coupling_map=coupling_map, noise_model=noise_model, basis_gates=basis_gates) result = job_sim.result() counts = result.get_counts() listForMusic = [] for i in range(2**len(qubitsToBeMeasured)): bitstring = str(bin(i)[2:]) bitstring = "0"*(4-len(bitstring))+bitstring if bitstring in counts.keys(): listForMusic.append("%.3f" % (counts[bitstring]/float(numberShots))) else: listForMusic.append("0.000") elif backendType == "real_device": # real device quantumCircuit.measure(qubitsToBeMeasured,qubitsToBeMeasured) provider=IBMQ.save_account('XXX-YOUR-TOKEN') # simulate noise of a real device IBMQ.load_account() IBMQ.providers() device = IBMQ.get_provider(hub='ibm-q', group='open', project='main').get_backend(RealDeviceName) job_exp = execute(quantumCircuit, backend=device) job_monitor(job_exp) result = job_exp.result() counts = result.get_counts() listForMusic = [] for i in range(2**len(qubitsToBeMeasured)): bitstring = str(bin(i)[2:]) bitstring = "0"*(4-len(bitstring))+bitstring if bitstring in counts.keys(): listForMusic.append(" %.3f" % (counts[bitstring]/float(numberShots))) else: listForMusic.append("0.000") return listForMusic # In[70]: if __name__ == "__main__": # qc = QuantumCircuit(2,2) # qc.h(0) # qc.x(1) # # res = ChooseBackEnd(qc,"qasm_simulator",200) # In[8]: music = QuantumCircuit(4,4) desired_vector = np.zeros(np.power(2,4)) desired_vector[1] = 1 / np.sqrt(3) desired_vector[3] = 1/np.sqrt(3) desired_vector[10] = 1/np.sqrt(3) music.initialize(desired_vector, range(4)) listForMusic= ChooseBackEnd(music,backendType="statevector_simulator",qubitsToBeMeasured=range(4), numberShots=4096, noisePresent=True, RealDeviceName="ibmq_16_melbourne") print(listForMusic) # In[ ]:
https://github.com/menegolli/Quantum_synth
menegolli
from qiskit import * import numpy as np import random import sys from backends_select import ChooseBackEnd def GenerateCircuitSingleNote(circuit, note_id): if (note_id >= 12): sys.exit("Note must be an integer smaller than 11 and larger (or equal) to 0.") bitstring = str(bin(note_id)[2:]) bitstring = "0"*(4-len(bitstring))+bitstring for i in range(len(bitstring)): if bitstring[len(bitstring)-1-i] == "1": circuit.x(i) qc = QuantumCircuit(4,4) GenerateCircuitSingleNote(qc, 7) ChooseBackEnd(qc, 'statevector_simulator') def BellStateGenerationTwoQubits(quantumCircuit, firstQubit=0, secondQubit=1, specificEntangledState="Phi"): if specificEntangledState == "Phi": quantumCircuit.h(firstQubit) quantumCircuit.cx(firstQubit, secondQubit) elif specificEntangledState == "Psi": quantumCircuit.h(firstQubit) quantumCircuit.x(secondQubit) quantumCircuit.cx(firstQubit, secondQubit) qc = QuantumCircuit(4,4) BellStateGenerationTwoQubits(qc, 0, 1) ChooseBackEnd(qc, 'qasm_simulator') def ChooseEqualSuperposition(quantumCircuit, states): desiredVector = np.zeros(2**quantumCircuit.n_qubits) flag = 1 for k in states: if 0 <= k <= 11: desiredVector[k] = 1/np.sqrt(len(states)) flag = flag*1 else: flag = flag*0 if flag == 1: quantumCircuit.initialize(desiredVector, range(4)) def ChooseEqualSuperpositionRandom(quantumCircuit): randomNumberOfNotes = np.random.randint(2,13) listModes = list(range(12)) listToSuperimpose = [] for i in range(randomNumberOfNotes): tmp = random.choice(listModes) listToSuperimpose.append(tmp) listModes.remove(tmp) ChooseEqualSuperposition(quantumCircuit, listToSuperimpose) qc = QuantumCircuit(4,4) ChooseEqualSuperposition(qc, [1, 4, 7]) ChooseBackEnd(qc, 'qasm_simulator') def Hadamard(quantumCircuit, listOfQubits): for k in listOfQubits: if 0 <= k <= quantumCircuit.n_qubits: quantumCircuit.h(k) qc = QuantumCircuit(4,4) Hadamard(qc, [0, 2]) ChooseBackEnd(qc, 'statevector_simulator') def RandomRotation(quantumCircuit): for k in range(quantumCircuit.n_qubits): quantumCircuit.u3(q=k, theta = np.random.random()*2*np.pi, phi = np.random.random()*np.pi, lam = np.random.random()*np.pi) qc = QuantumCircuit(4,4) RandomRotation(qc) ChooseBackEnd(qc, 'qasm_simulator') def __multiplecz(quantumCircuit, target, initialLength): quantumCircuit.ccx(0,1, initialLength) for k in range(2, initialLength-1): quantumCircuit.ccx(k, initialLength+k-2, initialLength+k-1) quantumCircuit.cz(quantumCircuit.n_qubits-1, initialLength-1) for k in reversed(range(2, initialLength-1)): quantumCircuit.ccx(k, initialLength+k-2, initialLength+k-1) quantumCircuit.ccx(0,1, initialLength) def Grover(quantumCircuit, target, initialLength): for k in range(initialLength): quantumCircuit.h(k) ancillaQubit = QuantumRegister(2) quantumCircuit.add_register(ancillaQubit) for n in range(int(np.round(np.pi/4*np.sqrt(2**initialLength)))): for singleBit in range(initialLength): if target[initialLength-singleBit-1] == '0': quantumCircuit.x(singleBit) __multiplecz(quantumCircuit, target, initialLength) for singleBit in range(initialLength): if target[initialLength-singleBit-1] == '0': quantumCircuit.x(singleBit) for qubit in range(initialLength): quantumCircuit.h(qubit) quantumCircuit.x(qubit) __multiplecz(quantumCircuit, target, initialLength) for qubit in range(initialLength): quantumCircuit.x(qubit) quantumCircuit.h(qubit) qc = QuantumCircuit(4,4) targ = format(10, '#06b')[2:] Grover(qc,targ,4) ChooseBackEnd(quantumCircuit=qc, backendType="statevector_simulator", qubitsToBeMeasured=range(4)) def AmplitudeAmplification(quantumCircuit, target, initialLength, numIterations): for k in range(initialLength): quantumCircuit.h(k) ancillaQubit = QuantumRegister(2) quantumCircuit.add_register(ancillaQubit) for n in range(numIterations): for singleBit in range(initialLength): if target[initialLength - singleBit - 1] == '0': quantumCircuit.x(singleBit) __multiplecz(quantumCircuit, target, initialLength) for singleBit in range(initialLength): if target[initialLength - singleBit - 1] == '0': quantumCircuit.x(singleBit) for qubit in range(initialLength): quantumCircuit.h(qubit) quantumCircuit.x(qubit) __multiplecz(quantumCircuit, target, initialLength) for qubit in range(initialLength): quantumCircuit.x(qubit) quantumCircuit.h(qubit) def GroverSequence(target, initialLength,backendType,RealDeviceName,noisePresent): iterations = [] for k in range(4): temporaryQuantumCircuit = QuantumCircuit(initialLength, initialLength) AmplitudeAmplification(temporaryQuantumCircuit, target, initialLength, k) # listForMusic = ChooseBackEnd(music, backendType=mystr[0], qubitsToBeMeasured=range(4), # numberShots=int(mystr[3]), noisePresent=True, RealDeviceName=mystr[1]) iterations.append(ChooseBackEnd(quantumCircuit=temporaryQuantumCircuit, noisePresent=noisePresent,backendType=backendType,qubitsToBeMeasured=range(4),RealDeviceName=RealDeviceName)) # ChooseBackEnd(quantumCircuit=temporaryQuantumCircuit, noisePresent=True,backendType=backendType,qubitsToBeMeasured=range(4),RealDeviceName=RealDeviceName) del (temporaryQuantumCircuit) return iterations targ = format(10, '#06b')[2:] GroverSequence(targ,4,'statevector_simulator','ibmq_ourense',False)
https://github.com/menegolli/Quantum_synth
menegolli
import numpy as np import networkx as nx import qiskit from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, assemble from qiskit.quantum_info import Statevector from qiskit.aqua.algorithms import NumPyEigensolver from qiskit.quantum_info import Pauli from qiskit.aqua.operators import op_converter from qiskit.aqua.operators import WeightedPauliOperator from qiskit.visualization import plot_histogram from qiskit.providers.aer.extensions.snapshot_statevector import * from thirdParty.classical import rand_graph, classical, bitstring_to_path, calc_cost from utils import mapeo_grafo from collections import defaultdict from operator import itemgetter from scipy.optimize import minimize import matplotlib.pyplot as plt LAMBDA = 10 SEED = 10 SHOTS = 10000 # returns the bit index for an alpha and j def bit(i_city, l_time, num_cities): return i_city * num_cities + l_time # e^(cZZ) def append_zz_term(qc, q_i, q_j, gamma, constant_term): qc.cx(q_i, q_j) qc.rz(2*gamma*constant_term,q_j) qc.cx(q_i, q_j) # e^(cZ) def append_z_term(qc, q_i, gamma, constant_term): qc.rz(2*gamma*constant_term, q_i) # e^(cX) def append_x_term(qc,qi,beta): qc.rx(-2*beta, qi) def get_not_edge_in(G): N = G.number_of_nodes() not_edge = [] for i in range(N): for j in range(N): if i != j: buffer_tupla = (i,j) in_edges = False for edge_i, edge_j in G.edges(): if ( buffer_tupla == (edge_i, edge_j) or buffer_tupla == (edge_j, edge_i)): in_edges = True if in_edges == False: not_edge.append((i, j)) return not_edge def get_classical_simplified_z_term(G, _lambda): # recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos N = G.number_of_nodes() E = G.edges() # z term # z_classic_term = [0] * N**2 # first term for l in range(N): for i in range(N): z_il_index = bit(i, l, N) z_classic_term[z_il_index] += -1 * _lambda # second term for l in range(N): for j in range(N): for i in range(N): if i < j: # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 2 # z_jl z_jl_index = bit(j, l, N) z_classic_term[z_jl_index] += _lambda / 2 # third term for i in range(N): for l in range(N): for j in range(N): if l < j: # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 2 # z_ij z_ij_index = bit(i, j, N) z_classic_term[z_ij_index] += _lambda / 2 # fourth term not_edge = get_not_edge_in(G) # include order tuples ej = (1,0), (0,1) for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 4 # z_j(l+1) l_plus = (l+1) % N z_jlplus_index = bit(j, l_plus, N) z_classic_term[z_jlplus_index] += _lambda / 4 # fifthy term weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # z_il z_il_index = bit(edge_i, l, N) z_classic_term[z_il_index] += weight_ij / 4 # z_jlplus l_plus = (l+1) % N z_jlplus_index = bit(edge_j, l_plus, N) z_classic_term[z_jlplus_index] += weight_ij / 4 # add order term because G.edges() do not include order tuples # # z_i'l z_il_index = bit(edge_j, l, N) z_classic_term[z_il_index] += weight_ji / 4 # z_j'lplus l_plus = (l+1) % N z_jlplus_index = bit(edge_i, l_plus, N) z_classic_term[z_jlplus_index] += weight_ji / 4 return z_classic_term def tsp_obj_2(x, G,_lambda): # obtenemos el valor evaluado en f(x_1, x_2,... x_n) not_edge = get_not_edge_in(G) N = G.number_of_nodes() tsp_cost=0 #Distancia weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # x_il x_il_index = bit(edge_i, l, N) # x_jlplus l_plus = (l+1) % N x_jlplus_index = bit(edge_j, l_plus, N) tsp_cost+= int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ij # add order term because G.edges() do not include order tuples # # x_i'l x_il_index = bit(edge_j, l, N) # x_j'lplus x_jlplus_index = bit(edge_i, l_plus, N) tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ji #Constraint 1 for l in range(N): penal1 = 1 for i in range(N): x_il_index = bit(i, l, N) penal1 -= int(x[x_il_index]) tsp_cost += _lambda * penal1**2 #Contstraint 2 for i in range(N): penal2 = 1 for l in range(N): x_il_index = bit(i, l, N) penal2 -= int(x[x_il_index]) tsp_cost += _lambda*penal2**2 #Constraint 3 for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # x_il x_il_index = bit(i, l, N) # x_j(l+1) l_plus = (l+1) % N x_jlplus_index = bit(j, l_plus, N) tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * _lambda return tsp_cost def get_classical_simplified_zz_term(G, _lambda): # recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos N = G.number_of_nodes() E = G.edges() # zz term # zz_classic_term = [[0] * N**2 for i in range(N**2) ] # first term for l in range(N): for j in range(N): for i in range(N): if i < j: # z_il z_il_index = bit(i, l, N) # z_jl z_jl_index = bit(j, l, N) zz_classic_term[z_il_index][z_jl_index] += _lambda / 2 # second term for i in range(N): for l in range(N): for j in range(N): if l < j: # z_il z_il_index = bit(i, l, N) # z_ij z_ij_index = bit(i, j, N) zz_classic_term[z_il_index][z_ij_index] += _lambda / 2 # third term not_edge = get_not_edge_in(G) for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # z_il z_il_index = bit(i, l, N) # z_j(l+1) l_plus = (l+1) % N z_jlplus_index = bit(j, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += _lambda / 4 # fourth term weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # z_il z_il_index = bit(edge_i, l, N) # z_jlplus l_plus = (l+1) % N z_jlplus_index = bit(edge_j, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += weight_ij / 4 # add order term because G.edges() do not include order tuples # # z_i'l z_il_index = bit(edge_j, l, N) # z_j'lplus l_plus = (l+1) % N z_jlplus_index = bit(edge_i, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += weight_ji / 4 return zz_classic_term def get_classical_simplified_hamiltonian(G, _lambda): # z term # z_classic_term = get_classical_simplified_z_term(G, _lambda) # zz term # zz_classic_term = get_classical_simplified_zz_term(G, _lambda) return z_classic_term, zz_classic_term def get_cost_circuit(G, gamma, _lambda): N = G.number_of_nodes() N_square = N**2 qc = QuantumCircuit(N_square,N_square) z_classic_term, zz_classic_term = get_classical_simplified_hamiltonian(G, _lambda) # z term for i in range(N_square): if z_classic_term[i] != 0: append_z_term(qc, i, gamma, z_classic_term[i]) # zz term for i in range(N_square): for j in range(N_square): if zz_classic_term[i][j] != 0: append_zz_term(qc, i, j, gamma, zz_classic_term[i][j]) return qc def get_mixer_operator(G,beta): N = G.number_of_nodes() qc = QuantumCircuit(N**2,N**2) for n in range(N**2): append_x_term(qc, n, beta) return qc def get_QAOA_circuit(G, beta, gamma, _lambda): assert(len(beta)==len(gamma)) N = G.number_of_nodes() qc = QuantumCircuit(N**2,N**2) # init min mix state qc.h(range(N**2)) p = len(beta) for i in range(p): qc = qc.compose(get_cost_circuit(G, gamma[i], _lambda)) qc = qc.compose(get_mixer_operator(G, beta[i])) qc.barrier(range(N**2)) qc.snapshot_statevector("final_state") qc.measure(range(N**2),range(N**2)) return qc def invert_counts(counts): return {k[::-1] :v for k,v in counts.items()} # Sample expectation value def compute_tsp_energy_2(counts, G): energy = 0 get_counts = 0 total_counts = 0 for meas, meas_count in counts.items(): obj_for_meas = tsp_obj_2(meas, G, LAMBDA) energy += obj_for_meas*meas_count total_counts += meas_count mean = energy/total_counts return mean def get_black_box_objective_2(G,p): backend = Aer.get_backend('qasm_simulator') sim = Aer.get_backend('aer_simulator') # function f costo def f(theta): beta = theta[:p] gamma = theta[p:] # Anzats qc = get_QAOA_circuit(G, beta, gamma, LAMBDA) result = execute(qc, backend, seed_simulator=SEED, shots= SHOTS).result() final_state_vector = result.data()["snapshots"]["statevector"]["final_state"][0] state_vector = Statevector(final_state_vector) probabilities = state_vector.probabilities() probabilities_states = invert_counts(state_vector.probabilities_dict()) expected_value = 0 for state,probability in probabilities_states.items(): cost = tsp_obj_2(state, G, LAMBDA) expected_value += cost*probability counts = result.get_counts() mean = compute_tsp_energy_2(invert_counts(counts),G) return mean return f def crear_grafo(cantidad_ciudades): pesos, conexiones = None, None mejor_camino = None while not mejor_camino: pesos, conexiones = rand_graph(cantidad_ciudades) mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False) G = mapeo_grafo(conexiones, pesos) return G, mejor_costo, mejor_camino def run_QAOA(p,ciudades, grafo): if grafo == None: G, mejor_costo, mejor_camino = crear_grafo(ciudades) print("Mejor Costo") print(mejor_costo) print("Mejor Camino") print(mejor_camino) print("Bordes del grafo") print(G.edges()) print("Nodos") print(G.nodes()) print("Pesos") labels = nx.get_edge_attributes(G,'weight') print(labels) else: G = grafo intial_random = [] # beta, mixer Hammiltonian for i in range(p): intial_random.append(np.random.uniform(0,np.pi)) # gamma, cost Hammiltonian for i in range(p): intial_random.append(np.random.uniform(0,2*np.pi)) init_point = np.array(intial_random) obj = get_black_box_objective_2(G,p) res_sample = minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True}) print(res_sample) if __name__ == '__main__': # Run QAOA parametros: profundidad p, numero d ciudades, run_QAOA(5, 3, None)
https://github.com/menegolli/Quantum_synth
menegolli
from qiskit import * import numpy as np import operator import socket import argparse import random import time import logging from backends_select import ChooseBackEnd from SuperpositionGates import * from RenormalizeProbability import * from pythonosc import udp_client UDP_IP_SERVER="127.0.0.1"#change this accordingly UDP_PORT_SERVER=7001 # global functions log = logging.getLogger('udp_server') def sender(results,name): parser = argparse.ArgumentParser() parser.add_argument("--ip", default=UDP_IP_SERVER, help="The ip of the OSC server") parser.add_argument("--port", type=int, default=7000, help="The port the OSC server is listening on") args = parser.parse_args() client = udp_client.SimpleUDPClient(args.ip, args.port) # for k in sorted(results): # print(k, results[k]) # client.send_message(k, results[k]) client.send_message(name, results) return True def server(host='0.0.0.0', port=UDP_PORT_SERVER): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) log.info("Listening on udp %s:%s" % (host, port)) s.bind((host, port)) return s def grover4(target, backendType, RealDeviceName,noisePresent=False,number=12): listForMusic = GroverSequence(target=target, initialLength=4, backendType=backendType, RealDeviceName=RealDeviceName, noisePresent=noisePresent) message = "" for k in listForMusic: # ii = 0 print(k) if number== 12: k=RedistributeCell(k) print(k) for l in k: message = message + str(l) + " " # ii = ii + 1 # if ii == 12: # print(ii) # break print(message) sender(results=message, name="grover") def hadamard(backendType, RealDeviceName, noisePresent,numberShots,number=12): circuit=QuantumCircuit(4,4) Hadamard(circuit, listOfQubits=range(4)) listForMusic = ChooseBackEnd(circuit, backendType=backendType, qubitsToBeMeasured=range(4), numberShots=numberShots, noisePresent=noisePresent, RealDeviceName=RealDeviceName,number=number) print(listForMusic) if number==12: listForMusic = RedistributeCell(listForMusic) print(listForMusic) sender(results=listForMusic, name="prob") del(circuit) def Bell(backendType, RealDeviceName, noisePresent,numberShots,number=12): circuit=QuantumCircuit(4,4) BellStateGenerationTwoQubits(circuit) listForMusic = ChooseBackEnd(circuit, backendType=backendType, qubitsToBeMeasured=range(4), numberShots=numberShots, noisePresent=noisePresent, RealDeviceName=RealDeviceName) print(listForMusic) if number==12: listForMusic = RedistributeCell(listForMusic) print(listForMusic) sender(results=listForMusic, name="prob") del(circuit) def SeperPosition(backendType, RealDeviceName, noisePresent,numberShots,number=12,notes=range(4)): circuit=QuantumCircuit(4,4) ChooseEqualSuperposition(circuit,states=notes)#we have to check togather listForMusic = ChooseBackEnd(circuit, backendType=backendType, qubitsToBeMeasured=range(4), numberShots=numberShots, noisePresent=noisePresent, RealDeviceName=RealDeviceName) print(listForMusic) if number==12: listForMusic = RedistributeCell(listForMusic) print(listForMusic) sender(results=listForMusic, name="prob") del(circuit) if __name__ == '__main__': # app.run() # test=hello_world() FORMAT_CONS = '%(asctime)s %(name)-12s %(levelname)8s\t%(message)s' logging.basicConfig(level=logging.DEBUG, format=FORMAT_CONS) # music = QuantumCircuit(4,4) # ['qasm_simulator', 'ibmq_16_melbourne', 'ChooseEqualSuperposition', '1936', '0'] s=server() while True: while True: (mystr, addr) = s.recvfrom(128*1024) print("Message from MAX:{}".format(mystr)) mystr=str(mystr) mystr = mystr.split("'") mystr = mystr[1] mystr = mystr.split("stop") mystr = mystr[0] mystr = mystr.split("run") mystr = mystr[1] mystr=mystr.strip() mystr = mystr.split(" ") print(mystr) #targ=format(3,'#06b')[2:] targ=mystr[6] targ="0"*(4-len(targ))+targ print(targ) # listForMusic = ChooseBackEnd(music, backendType=mystr[0], qubitsToBeMeasured=range(4), numberShots=int(mystr[3]), noisePresent=True, RealDeviceName=mystr[1]) if mystr[4]=='1': noise=True elif mystr[4]=='1': noise=False else: noise=False print(int(mystr[6],2)) if mystr[2]=="Hadamard": hadamard(backendType=mystr[0], RealDeviceName=mystr[1], noisePresent=noise,numberShots=int(mystr[3]),number=int(mystr[5])) elif mystr[2]=="BellStateGenerationTwoQubits": Bell(backendType=mystr[0], RealDeviceName=mystr[1], noisePresent=noise,numberShots=int(mystr[3]),number=int(mystr[5])) elif mystr[2]=="ChooseEqualSuperposition": SeperPosition(backendType=mystr[0], RealDeviceName=mystr[1], noisePresent=noise,numberShots=int(mystr[3]),number=int(mystr[5])) elif mystr[2]=="Grover": grover4(target=targ, backendType=mystr[0], RealDeviceName=mystr[1], noisePresent=noise,number=int(mystr[5])) else: print("Command Not defined")
https://github.com/menegolli/Quantum_synth
menegolli
#!/usr/bin/env python # coding: utf-8 # In[44]: from qiskit import * import numpy as np #import NewBackends import random import sys from backends_select import ChooseBackEnd # In[64]: def GenerateCircuitSingleNote(circuit, note_id): ''' Adds to the circuit the gates to measure a given note. ''' if (note_id >= 12): sys.exit("Note must be an integer smaller than 11 and larger (or equal) to 0.") bitstring = str(bin(note_id)[2:]) bitstring = "0"*(4-len(bitstring))+bitstring for i in range(len(bitstring)): if bitstring[len(bitstring)-1-i] == "1": circuit.x(i) def BellStateGenerationTwoQubits(quantumCircuit, firstQubit=0, secondQubit=1, specificEntangledState="Phi"): if specificEntangledState == "Phi": quantumCircuit.h(firstQubit) quantumCircuit.cx(firstQubit, secondQubit) elif specificEntangledState == "Psi": quantumCircuit.h(firstQubit) quantumCircuit.x(secondQubit) quantumCircuit.cx(firstQubit, secondQubit) def ChooseEqualSuperposition(quantumCircuit, states): desiredVector = np.zeros(2**quantumCircuit.n_qubits) flag = 1 for k in states: if 0 <= k <= 11: desiredVector[k] = 1/np.sqrt(len(states)) flag = flag*1 else: flag = flag*0 if flag == 1: quantumCircuit.initialize(desiredVector, range(4)) def ChooseEqualSuperpositionRandom(quantumCircuit): randomNumberOfNotes = np.random.randint(2,13) listModes = list(range(12)) listToSuperimpose = [] for i in range(randomNumberOfNotes): tmp = random.choice(listModes) listToSuperimpose.append(tmp) listModes.remove(tmp) ChooseEqualSuperposition(quantumCircuit, listToSuperimpose) def Hadamard(quantumCircuit, listOfQubits): for k in listOfQubits: if 0 <= k <= quantumCircuit.n_qubits: quantumCircuit.h(k) def RandomRotation(quantumCircuit): for k in range(quantumCircuit.n_qubits): quantumCircuit.u3(q=k, theta = np.random.random()*2*np.pi, phi = np.random.random()*np.pi, lam = np.random.random()*np.pi) def __multiplecz(quantumCircuit, target, initialLength): quantumCircuit.ccx(0,1, initialLength) for k in range(2, initialLength-1): quantumCircuit.ccx(k, initialLength+k-2, initialLength+k-1) quantumCircuit.cz(quantumCircuit.n_qubits-1, initialLength-1) for k in reversed(range(2, initialLength-1)): quantumCircuit.ccx(k, initialLength+k-2, initialLength+k-1) quantumCircuit.ccx(0,1, initialLength) def Grover(quantumCircuit, target, initialLength): for k in range(initialLength): quantumCircuit.h(k) ancillaQubit = QuantumRegister(2) quantumCircuit.add_register(ancillaQubit) for n in range(int(np.round(np.pi/4*np.sqrt(2**initialLength)))): for singleBit in range(initialLength): if target[initialLength-singleBit-1] == '0': quantumCircuit.x(singleBit) __multiplecz(quantumCircuit, target, initialLength) for singleBit in range(initialLength): if target[initialLength-singleBit-1] == '0': quantumCircuit.x(singleBit) for qubit in range(initialLength): quantumCircuit.h(qubit) quantumCircuit.x(qubit) __multiplecz(quantumCircuit, target, initialLength) for qubit in range(initialLength): quantumCircuit.x(qubit) quantumCircuit.h(qubit) def AmplitudeAmplification(quantumCircuit, target, initialLength, numIterations): for k in range(initialLength): quantumCircuit.h(k) ancillaQubit = QuantumRegister(2) quantumCircuit.add_register(ancillaQubit) for n in range(numIterations): for singleBit in range(initialLength): if target[initialLength - singleBit - 1] == '0': quantumCircuit.x(singleBit) __multiplecz(quantumCircuit, target, initialLength) for singleBit in range(initialLength): if target[initialLength - singleBit - 1] == '0': quantumCircuit.x(singleBit) for qubit in range(initialLength): quantumCircuit.h(qubit) quantumCircuit.x(qubit) __multiplecz(quantumCircuit, target, initialLength) for qubit in range(initialLength): quantumCircuit.x(qubit) quantumCircuit.h(qubit) def HalfFilledSuperposition(quantumCircuit, number): desiredVector=np.zeros(16) for k in range(number//2): desiredVector[k] = 1./np.sqrt(number/2.) quantumCircuit.initialize(desiredVector, range(4)) def GroverSequence(target, initialLength,backendType,RealDeviceName,noisePresent): iterations = [] for k in range(4): temporaryQuantumCircuit = QuantumCircuit(initialLength, initialLength) AmplitudeAmplification(temporaryQuantumCircuit, target, initialLength, k) print(target) # listForMusic = ChooseBackEnd(music, backendType=mystr[0], qubitsToBeMeasured=range(4), # numberShots=int(mystr[3]), noisePresent=True, RealDeviceName=mystr[1]) iterations.append(ChooseBackEnd(quantumCircuit=temporaryQuantumCircuit, noisePresent=noisePresent,backendType=backendType,qubitsToBeMeasured=range(4),RealDeviceName=RealDeviceName)) # ChooseBackEnd(quantumCircuit=temporaryQuantumCircuit, noisePresent=True,backendType=backendType,qubitsToBeMeasured=range(4),RealDeviceName=RealDeviceName) del (temporaryQuantumCircuit) return iterations
https://github.com/TexanElite/QiskitFallFest2021Project
TexanElite
%pip install qiskit %pip install pylatexenc %pip install matplotlib #initialization import matplotlib.pyplot as plt import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, BasicAer, execute, IBMQ, assemble, Aer, transpile from qiskit.quantum_info import Statevector from qiskit.visualization import plot_histogram, plot_state_qsphere, plot_bloch_multivector, plot_bloch_vector import getpass def hash_oracle(qc, qubits, clause_qubits, output, hash_value): # Prepares the circuit to "compare" the clause_qubits to the hash_value exp = 0 while exp < len(clause_qubits): if not hash_value & (1 << exp) > 0: qc.x(clause_qubits[exp]) exp += 1 qc.barrier() # XORs every two qubits and XORs the result of that into one of the clause_qubits for i in range(0, len(qubits), 1): qc.cx(qubits[i], clause_qubits[i % len(clause_qubits)]) qc.cx(qubits[(i + 1) % len(qubits)], clause_qubits[i % len(clause_qubits)]) # Checks if all the clause_qubits are satisfied qc.mct(clause_qubits, output) # Repeat all the steps to ensure that clause_qubits are |0000> for i in range(0, len(qubits), 1): qc.cx(qubits[i], clause_qubits[i % len(clause_qubits)]) qc.cx(qubits[(i + 1) % len(qubits)], clause_qubits[i % len(clause_qubits)]) qc.barrier() exp = 0 while exp < len(clause_qubits): if not hash_value & (1 << exp) > 0: qc.x(clause_qubits[exp]) exp += 1 def diffuser(n): qc = QuantumCircuit(n) for qubit in range(n): qc.h(qubit) for qubit in range(n): qc.x(qubit) qc.h(n-1) qc.mct(list(range(n-1)), n-1) qc.h(n-1) for qubit in range(n): qc.x(qubit) for qubit in range(n): qc.h(qubit) d = qc.to_gate() d.name = "Diffuser" return d n_qubits = 4 iterations = int(n_qubits ** (1/2)) hash_value = 10 var_qubits = QuantumRegister(n_qubits, name='v') clause_qubits = QuantumRegister(4, name='c') # bits to store clause-checks output_qubit = QuantumRegister(1, name='out') cbits = ClassicalRegister(n_qubits, name='cbits') qc = QuantumCircuit(var_qubits, clause_qubits, output_qubit, cbits) # Initialize the output qubit to |-> qc.initialize([1, -1]/np.sqrt(2), output_qubit) # Initialize the qubits to the state |s> (intially the equal superposition or |+> state) qc.h(var_qubits) qc.barrier() # Repeat the process _iterations_ times for iteration in range(iterations): # Apply our oracle hash_oracle(qc, var_qubits, clause_qubits, output_qubit, hash_value) qc.barrier() # Apply the diffuser qc.append(diffuser(n_qubits), list(range(n_qubits))) # Measure the variable qubits qc.measure(var_qubits, cbits) qc.draw(fold=-1) aer_simulator = Aer.get_backend('aer_simulator') transpiled_qc = transpile(qc, aer_simulator) qobj = assemble(transpiled_qc) result = aer_simulator.run(qobj).result() plot_histogram(result.get_counts())
https://github.com/achilles-d/qiskitsummerjam
achilles-d
%matplotlib inline # Importing standard Qiskit libraries and configuring account from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * # Loading your IBM Q account(s) provider = IBMQ.load_account() from PIL import Image from numpy import* import matplotlib.cm as cm import numpy as np import matplotlib.pyplot as plt temp=Image.open('download.png') temp=temp.convert('1') # Convert to black&white A = array(temp) # Creates an array, white pixels==True and black pixels==False new_A=empty((A.shape[0],A.shape[1]),None) #New array with same size as A for i in range(len(A)): for j in range(len(A[i])): if A[i][j]==True: new_A[i][j]=0 else: new_A[i][j]=1 shape = new_A.shape #new_A = new_A[0:50,0:50] # make a 1-dimensional view of arr flat_arr = new_A.ravel() print(sum(flat_arr), len(flat_arr)) """ COPIED CODE """ import sys sys.path.append("../../qiskit-sdk-py/") from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit import math from qiskit import( QuantumCircuit, execute, Aer) from qiskit.tools.visualization import plot_histogram from qiskit import IBMQ # set up registers and program qr = QuantumRegister(len(flat_arr), 'qr') cr = ClassicalRegister(len(flat_arr),'cr') qc = QuantumCircuit(qr, cr) # rightmost eight (qu)bits have ')' = 00101001 count = 0; #for num, k in enumerate(flat_arr): #if (k == 1): index = [index for index, value in enumerate(flat_arr) if value == 1] for k in index: qc.x(qr[k]) qc.measure(qr[k], cr[k]) print("hello") simulator = Aer.get_backend('qasm_simulator') print("hello") job = execute(qc, simulator, shots=1024) print("hello") results = job.result() print("hello") stats = results.get_counts(qc) print("hello") vector = np.matrix(flat_arr) #print(count) # if (count%100 == 0): # print(count) # count = count +1 from PIL import Image from numpy import* import matplotlib.cm as cm import numpy as np import matplotlib.pyplot as plt from scipy import misc from sklearn.decomposition import PCA def pixelate(first_file, second_file, pixel_size): im1 = Image.open(first_file) im2 = Image.open(second_file) #resizing im1 = im1.resize((size, size), Image.BILINEAR) im2 = im2.resize((size, size), Image.BILINEAR) A1 = (im1) A2 = (im2) return A1, A2 def black_and_white(temp): temp=temp.convert('1') A = array(temp) # Creates an array, white pixels==True and black pixels==False new_A=empty((A.shape[0],A.shape[1]),None) #New array with same size as A for i in range(len(A)): for j in range(len(A[i])): if A[i][j]==True: new_A[i][j]=0 else: new_A[i][j]=1 return A file_1 = "download.png" size = 10 A1, A2 = pixelate(file_1, file_1, size) plt.imsave('filename2.jpeg',A2, cmap=cm.gray) new_A=empty((A1.shape[0],A1.shape[1]),None) #New array with same size as A for i in range(len(A1)): for j in range(len(A1[i])): if A1[i][j]==True: new_A[i][j]=0 else: new_A[i][j]=1 shape = new_A.shape #new_A = new_A[0:50,0:50] img = np.asarray(A1) new_img = img.reshape((img.shape[0]*img.shape[1]), img.shape[2]) new_img = new_img.transpose() new_img.shape from PIL import Image from numpy import* import matplotlib.cm as cm import numpy as np import matplotlib.pyplot as plt #flat_arr = new_A.ravel() #print(sum(flat_arr), len(flat_arr)) """ COPIED CODE """ import sys sys.path.append("../../qiskit-sdk-py/") from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit import math from qiskit import( QuantumCircuit, execute, Aer) from qiskit.tools.visualization import plot_histogram from qiskit import IBMQ # set up registers and program qr = QuantumRegister(15, 'qr') cr = ClassicalRegister(15,'cr') qc = QuantumCircuit(qr, cr) # rightmost eight (qu)bits have ')' = 00101001 count = 0; #for num, k in enumerate(flat_arr): #if (k == 1): #index = [index for index, value in enumerate(flat_arr) if value == 1] double = np.zeros((3,100)) count = 1 for p in range(3): for k in range(100): num_1 = bin(new_img[p][k]) num_2 = bin(new_img[p][k]) #print("num1 index: ", len(str(num_1))) for i in range(len(str(num_1))): if num_1[i] == str(1): qc.x(qr[i]) qc.h(qr[7]) # create superposition on 9 qc.cx(qr[7],qr[8]) # spread it to 8 with a cnot for i in range(len(str(num_2))): if num_2[i] == str(1): qc.x(qr[i+5]) for j in range(15): qc.measure(qr[j], cr[j]) simulator = Aer.get_backend('qasm_simulator') job = execute(qc, simulator, shots=1) results = job.result() stats = results.get_counts(qc) register_value = stats.keys() for x in register_value: split = x[0:7] split2 = x[7:15] #print(split2) total = abs(int(split,2)-int(split2,2)) double[p][k] = total #print(total) print("Quantum1 :", (abs(int(split,2)+int(split2,2)))/2, " num1 :", int(num_1, 2)) print ("count: ", count) count = count +1 double for i in range(len(str(num_1))): if num_1[i] == str(1): qc.x(qr[i]) x = [] for elem in '1000110010111010100101111010110000100010010101011100001010001100000101101100011110000100011100000000': x.append(elem) x arr2 = np.asarray(x).reshape(shape) for j in range(len(flat_arr)): qc.measure(qr[j], cr[j]) print("hello") simulator = Aer.get_backend('qasm_simulator') print("hello") job = execute(qc, simulator, shots=5) print("hello") results = job.result() print("hello") stats = results.get_counts(qc) print("hello") vector = np.matrix(flat_arr) arr2 = np.asarray(vector).reshape(shape) arr2 plt.imsave('filename1.jpeg',arr2, cmap=cm.gray) A1 arr2 x = [] for bitString in stats: # loop over all results for k in range(len(bitString)-1): x.append(int(bitString[k:k+1])) x.append(1) x = np.array(x) x = x[0:2500] vector = np.matrix(x) shape = new_A.shape arr2 = np.asarray(vector).reshape(shape) img = plt.imshow(double) plt.show() img = plt.imshow(new_img) plt.show()
https://github.com/achilles-d/qiskitsummerjam
achilles-d
from PIL import Image from numpy import* import matplotlib.cm as cm import numpy as np import matplotlib.pyplot as plt import sys sys.path.append("../../qiskit-sdk-py/") import math from qiskit import ( QuantumCircuit, execute, QuantumRegister, ClassicalRegister, Aer) from qiskit import IBMQ # Loading your IBM Q account(s) provider = IBMQ.load_account() def pixelate(first_file, second_file, size): im1 = Image.open(first_file) im2 = Image.open(second_file) im1 = im1.resize((size, size), Image.BILINEAR) im2 = im2.resize((size, size), Image.BILINEAR) A1 = (im1) A2 = (im2) return A1, A2 # Run the quantum script def run_quantum(file1, file2): file_1 = file1 file_2 = file2 size = 16 A1, A2 = pixelate(file_1, file_2, size) plt.imsave('filename2.jpeg',A2, cmap=cm.gray) img = np.asarray(A1) new_img = img.reshape(32, 32) # new_img = img.reshape((img.shape[0]*img.shape[1]), img.shape[2]) new_img = new_img.transpose() print(len(new_img[0])) img1 = np.asarray(A2) new_img1 = img1.reshape(32, 32) # new_img1 = img1.reshape((img1.shape[0]*img1.shape[1]), img1.shape[2]) new_img1 = new_img1.transpose() print(len(new_img1)) # set up registers and program qr = QuantumRegister(15, 'qr') cr = ClassicalRegister(15,'cr') qc = QuantumCircuit(qr, cr) # rightmost eight (qu)bits have ')' = 00101001 double = np.zeros((16,16)) # final double array print("Quantum Circuit Complete. Determining Pixel Values...") for p in range(16): for k in range(16): num_1 = bin(new_img[p][k]) num_2 = bin(new_img1[p][k]) for i in range(len(str(num_1))): if num_1[i] == str(1): qc.x(qr[i]) qc.h(qr[7]) # create superposition on 9 qc.cx(qr[7],qr[8]) # spread it to 8 with a cnot for i in range(len(str(num_2))): if num_2[i] == str(1): qc.x(qr[i+5]) for j in range(15): qc.measure(qr[j], cr[j]) simulator = Aer.get_backend('qasm_simulator') job = execute(qc, simulator, shots=1) results = job.result() stats = results.get_counts(qc) register_value = stats.keys() for x in register_value: split = x[0:7] split2 = x[7:15] total = abs(int(split,2)-int(split2,2)) double[p][k] = total # img = plt.imshow(double) # final image plt.imsave('result.jpeg',double)
https://github.com/achilles-d/qiskitsummerjam
achilles-d
# Set up your quantum environment. from qiskit import IBMQ IBMQ.save_account('PASTE QUANTUM KEY HERE') print('Setup Done')
https://github.com/shaimayshah/Quantum-Global-Public-Goods-Game
shaimayshah
from qiskit import * import numpy as np from functools import partial from qiskit.aqua.components.optimizers import COBYLA from scipy.optimize import minimize, fmin_slsqp import pandas as pd import matplotlib.pyplot as plt %matplotlib inline theta = np.array([0.5, np.pi*2, 1.4, 1/3, np.pi/2, 1.3, 1.4, 0.22, 1.2, 0.99, 1.0, 0.23, 0.14, 0.90, np.pi]) def run_quantum_circ(n, theta): ''' This creates a quantum circuit with n qubits. ''' qr = QuantumRegister(n) cr = ClassicalRegister(n) circuit = QuantumCircuit(qr, cr) #Applies Hadamard Gate to first circuit.h(0) #Entangles the qubits for i in range(n-1): circuit.cx(i, i+1) # For ease of understanding circuit.barrier() # Applying U3 gates -- later i = 0 for i in range(n): circuit.u3(theta[3*i], theta[(3*i)+1], theta[(3*i)+2], i) circuit.barrier() # Unentangling qubits for i in reversed(range(n)): if i-1==-1: break else: circuit.cx(i-1, i) circuit.h(0) circuit.barrier() # Measuring the values for i in range(n-1): circuit.measure(i, i) backend = Aer.get_backend('qasm_simulator') result = execute(circuit, backend=backend, shots=10000).result() return result.get_counts() theta_c = np.array([np.pi*2, np.pi/2, 0.22, 1.0, 0.90]) def run_classical_circ(n, theta): ''' This creates a quantum circuit with n qubits. ''' qr = QuantumRegister(n) cr = ClassicalRegister(n) circuit = QuantumCircuit(qr, cr) # For ease of understanding circuit.barrier() # Applying U3 gates -- later i = 0 for i in range(n): circuit.u2(theta[i], 0, i) circuit.barrier() # Measuring the values for i in range(n-1): circuit.measure(i, i) backend = Aer.get_backend('qasm_simulator') result = execute(circuit, backend=backend, shots=10000).result() return result.get_counts() # Translate from dictionary to sorted values. def dic_to_vec(dic): ''' Converts to dictionary outputted by the quantum/classical circuit to a 2^n dimensional (dim = 32) vector. ''' scores = np.zeros(32) num_shots = 10000 for key in dic.keys(): i = int(key,2) scores[i] = dic[key]/num_shots return scores # The Payoff matrix -- made it here at random v1 = np.random.rand(5,1)*np.random.rand(1) v2 = np.random.rand(1,32) payoff_mat = np.matmul(v1,v2) def payoff_finder(result, payoff): ''' Input: results from quantum/classical calc (32x1), payoff matrix. Output: payoff matrix for that particular ''' return np.matmul(payoff, result) def quantum_cost_function(n, rand_payoff_mat, theta): ''' Input: number of qubits, initial values of theta, the payoff matrix you've generated Output: a singular number that represents how large the difference between the standard deviation and L1 norm. ''' # Runs the quantum circuit and returns a dictionary of values. dic = run_quantum_circ(n, theta) vec = dic_to_vec(dic) payoff_vec = payoff_finder(vec, rand_payoff_mat) val = np.linalg.norm(payoff_vec, ord = 1) - np.std(payoff_vec) return -val #quantum_cost_function(5,theta,payoff_mat) def classical_cost_function(n, rand_payoff_mat, theta): ''' Input: number of qubits, initial values of theta, the payoff matrix you've generated Output: a singular number that represents how large the difference between the standard deviation and L1 norm. ''' dic = run_classical_circ(n, theta) vec = dic_to_vec(dic) payoff_vec = payoff_finder(vec, rand_payoff_mat) val = np.linalg.norm(payoff_vec, ord = 1) - np.std(payoff_vec) return -val vals = [] def callback(res): params.append(res) def callback_classic(res): params_c.append(res) #backup_params = params params = [] qcost = partial(quantum_cost_function, 5, payoff_mat) results = minimize(qcost, theta, method='Nelder-Mead', callback = callback)#, tol=1e-9) results params_c = [] ccost = partial(classical_cost_function, 5, payoff_mat) results_c = minimize(ccost, theta_c, method='Nelder-Mead', callback = callback_classic) results_c vals = [] for param in params: vals.append(0-quantum_cost_function(5, payoff_mat, param)) vals_c = [] for param in params_c: vals_c.append(0-classical_cost_function(5, payoff_mat, param)) max_c = np.asarray(vals_c).max() max_q = np.asarray(vals).max() with plt.xkcd(): plt.plot(list(range(len(vals))), vals, label="quantum strategy") plt.plot(list(range(len(vals_c))), vals_c, color='r', label = "classical strategy") #plt.axhline(max_c, color='r', ls='--', label = 'Maximum quantum value reached') #plt.axhline(max_q, color='b', ls='--', label = 'Maximum classical value reached') plt.xlabel('Iterations') plt.ylabel('Maximization Function') plt.legend()
https://github.com/Sinestro38/Wine-quantumSupportVectorMachine
Sinestro38
from matplotlib import pyplot as plt import numpy as np from qiskit import Aer, execute from qiskit.tools import job_monitor from qiskit.aqua import QuantumInstance from qiskit.circuit.library import ZZFeatureMap, PauliFeatureMap, ZFeatureMap from qiskit.aqua.algorithms import QSVM from qiskit.aqua.components.multiclass_extensions import OneAgainstRest from qiskit.aqua.utils import split_dataset_to_data_and_labels, map_label_to_class_name from qiskit.aqua import MissingOptionalLibraryError from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler, MinMaxScaler from sklearn.decomposition import PCA import pandas as pd data = datasets.load_wine() target = data.target data = data.data training_dataset_size = 10 testing_dataset_size = 10 class_labels = ["A", "B", "C"] pd.DataFrame(data) dim = 3 training_dataset_size = 20 testing_dataset_size = 10 sample_train, sample_test, label_train, label_test = train_test_split(data, target, random_state=10) # Standardizing the dataset -- gaussian with unit variance and 0 mean std = StandardScaler() std.fit(sample_train) sample_train = std.transform(sample_train) sample_test = std.transform(sample_test) # Using PCA to reduce no. of dimensions to 2 to match number of qubits pca = PCA(dim) pca.fit(sample_train) sample_train = pca.transform(sample_train) sample_test = pca.transform(sample_test) # Scaling data to range from -1 to 1 minmax = MinMaxScaler() minmax = minmax.fit(sample_train) sample_train = minmax.transform(sample_train) sample_test = minmax.transform(sample_test) # Setting dataset size to number of training_dataset_size training_input = {key: (sample_train[label_train == k, :])[:training_dataset_size] for k, key in enumerate(class_labels)} test_input = {key: (sample_test[label_test == k, :])[:testing_dataset_size] for k, key in enumerate(class_labels)} # Plotting data for k in range(0, 3): plt.scatter(sample_train[label_train == k, 0][:training_dataset_size], sample_train[label_train == k, 1][:training_dataset_size]) plt.title("Wine dataset with reduced dimensions") plt.show() datapoints, class_to_label = split_dataset_to_data_and_labels(test_input) backend = Aer.get_backend("qasm_simulator") feature_map = ZZFeatureMap(dim, reps=2) print(feature_map) svm = QSVM(feature_map, training_input, test_input, None, multiclass_extension=OneAgainstRest()) quantum_instance = QuantumInstance(backend, shots=8000) result = svm.run(quantum_instance) predicted_labels = svm.predict(datapoints[0]) predicted_classes = map_label_to_class_name(predicted_labels, svm.label_to_class) print(f"Ground truth: {datapoints[1]}") print(f"Prediction: {predicted_labels}") print(" RESULTS Testing success ratio: ", result['testing_accuracy'])
https://github.com/ho0-kim/Hamiltonian_Cycle_Problem_with_QC
ho0-kim
import numpy as np # QC-related libraries from qiskit import Aer, IBMQ, execute from qiskit.providers.ibmq import least_busy from qiskit.tools.monitor import job_monitor from qiskit.visualization import plot_histogram # from qiskit.tools.visualization import plot_histogram from qiskit.aqua.algorithms import VQE, NumPyMinimumEigensolver from qiskit.aqua.components.optimizers import SPSA from qiskit.circuit.library import TwoLocal from qiskit.aqua import aqua_globals from qiskit.aqua import QuantumInstance from qiskit.optimization.applications.ising.common import sample_most_likely from qiskit.optimization.algorithms import MinimumEigenOptimizer from qiskit.optimization import QuadraticProgram import networkx as nx import matplotlib.pyplot as plt import matplotlib.axes as axes from docplex.mp.model import Model from qiskit.optimization.applications.ising.docplex import get_operator def not_in_edge( n, Edge ): set_edge = set() for i in range( n ): for k in range( n ): if ( i, k ) in Edge or ( k, i ) in Edge: continue else: set_edge.add( ( i, k ) ) return set_edge Vertex = { 0, 1, 2 } Edge = {(0,1), (1,2), (2,0) } n = len(Vertex) G = nx.Graph() G.add_nodes_from( np.arange( 0, n ) ) eList = list( Edge ) # (i,j): edge G.add_edges_from( eList ) colors = [ 'r' for node in G.nodes() ] pos = nx.spring_layout( G ) def draw_graph(G, colors, pos): default_axes = plt.axes(frameon=True) nx.draw_networkx(G, node_color=colors, node_size=600, alpha=.8, ax=default_axes, pos=pos) nx.draw_networkx_edges(G, pos=pos ) draw_graph(G, colors, pos) # Create an instance of a model and variables with DOcplex. mdl = Model( name='HamiltonCycle' ) x = { ( i, p ): mdl.binary_var( name= 'x_{0}_{1}'.format( i, p ) ) for i in range( n ) for p in range( n ) } # Generate cost funciton P1 = 0 P2 = 0 H = 0 for i in range(n): P1 += ( 1 - mdl.sum( x[(i,j)] for j in range(n) ) ) ** 2 for j in range(n): P2 += ( 1 - mdl.sum( x[(i,j)] for i in range(n) ) ) ** 2 for ( i1, i2 ) in not_in_edge( n, Edge ): H += x[(i1,0)] * x[(i2,n-1)] H += mdl.sum( x[(i1,j)] * x[(i2,j+1)] for j in range(n-1) ) HamiltonCycleFunc = H + P1 + P2 # Set HamiltonCycleFunc to be minimized mdl.minimize( HamiltonCycleFunc ) qubitOp, offset = get_operator(mdl) print('Offset:', offset) # print('Ising Hamiltonian:') # print(qubitOp.print_details()) # mapping Ising Hamiltonian to Quadratic Program qp = QuadraticProgram() qp.from_ising(qubitOp, offset) #qp.to_docplex().prettyprint() # solving Quadratic Program using exact classical eigensolver exact = MinimumEigenOptimizer(NumPyMinimumEigensolver()) result = exact.solve(qp) print(result) #Making the Hamiltonian in its full form and getting the lowest eigenvalue and eigenvector ee = NumPyMinimumEigensolver(qubitOp) result = ee.run() x = sample_most_likely(result.eigenstate) print('energy:', result.eigenvalue.real) print('hamiltonian-cycle objective:', result.eigenvalue.real + offset) provider = IBMQ.load_account() simulator_backend = provider.get_backend("ibmq_qasm_simulator") aqua_globals.random_seed = np.random.default_rng(123) seed = 10598 backend = Aer.get_backend("qasm_simulator") quantum_instance = QuantumInstance(simulator_backend, shots=1024, seed_simulator=seed, seed_transpiler=seed) # construct VQE spsa = SPSA(maxiter=1000) ansatz = TwoLocal( qubitOp.num_qubits, rotation_blocks='ry', entanglement_blocks='cx', reps=2, entanglement='linear' ) vqe = VQE(operator=qubitOp, var_form=ansatz, optimizer=spsa, quantum_instance=quantum_instance) # run VQE result = vqe.run() # print results x = sample_most_likely(result.eigenstate) print('energy:', result.eigenvalue.real) print('time:', result.optimizer_time) print('hamiltonian-cycle objective:', result.eigenvalue.real + offset) print('solution:', x) # create minimum eigen optimizer based on VQE vqe_optimizer = MinimumEigenOptimizer(vqe) # solve quadratic program result = vqe_optimizer.solve(qp) print(result)
https://github.com/ho0-kim/Hamiltonian_Cycle_Problem_with_QC
ho0-kim
import qiskit from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import IBMQ, Aer, execute from qiskit.extensions import UnitaryGate from qiskit.visualization import plot_histogram import matplotlib.pyplot as plt import numpy as np # Graph g = np.array([[0,1,1,0,1,1], [1,0,1,0,0,0], [1,1,0,1,0,1], [0,0,1,0,1,1], [1,0,0,1,0,1], [1,0,1,1,1,0]]) # g = np.array([[0, 1, 1, 1, 1], # [1, 0, 1, 1, 1], # [1, 1, 0, 1, 1], # [1, 1, 1, 0, 1], # [1, 1, 1, 1, 0]]) n_vertices = g.shape[0] n_edges = 0 for i in range(n_vertices): n_edges += sum(g[i, i:]) print('number of vertices:', n_vertices) print('number of edges:', n_edges) print('required qubit number:', n_vertices + n_edges + 1) iter = int(np.pi/(4*np.arcsin(1/np.sqrt(2**n_edges))) - 1/2) # iter = np.pi/4 * np.sqrt(2**n_edges) print('Grover iteration:', iter) g_dict = {} # {edge: [vertex1, vertex2]} edge_idx = 0 for i in range(n_vertices): for j in range(i, n_vertices): if g[i,j] == 1: g_dict[edge_idx] = [i, j] edge_idx += 1 g_dict def oracle(qc, qr_v, qr_e, qr_f, n_vertices): # encode for i in g_dict: qc.cry(np.pi/2, qr_e[i], g_dict[i][0]) qc.cry(np.pi/2, qr_e[i], g_dict[i][1]) qc.barrier() # set flag qc.mcx(v, flag) qc.barrier() # inverse for i in g_dict: qc.cry(-np.pi/2, qr_e[i], g_dict[i][0]) qc.cry(-np.pi/2, qr_e[i], g_dict[i][1]) qc.barrier() def diffuser(qc, qr_e, ancilla): qc.h(qr_e) qc.x(qr_e) qc.h(qr_e[-1]) qc.mct(qr_e[:-1], qr_e[-1])#, ancilla_qubits=ancilla) qc.h(qr_e[-1]) qc.x(qr_e) qc.h(qr_e) v = QuantumRegister(n_vertices, name='v') e = QuantumRegister(n_edges, name='e') flag = QuantumRegister(1, name='flag') n_anc = 32-n_vertices-n_edges-1 anc = QuantumRegister(n_anc, name='anc') c = ClassicalRegister(n_edges) qc = QuantumCircuit(v, e, flag, anc, c) qc.h(e) qc.x(flag) qc.h(flag) qc.barrier() iter = 1 for _ in range(iter): oracle(qc, v, e, flag, n_vertices) qc.barrier() diffuser(qc, e, anc) qc.barrier() qc.measure(e, c) qc.draw('mpl') shots = 5012 backend = Aer.get_backend('qasm_simulator') count = execute(qc, backend=backend, shots=shots).result().get_counts() plot_histogram(count) from collections import defaultdict class Graph: # Constructor def __init__(self): # default dictionary to store graph self.graph = defaultdict(list) # function to add an edge to graph def addEdge(self,u,v): self.graph[u].append(v) self.graph[v].append(u) # Function to print a BFS of graph def BFS(self, s): # Mark all the vertices as not visited visited = [False] * (max(self.graph) + 1) # Create a queue for BFS queue = [] count = 0 # Mark the source node as # visited and enqueue it queue.append(s) visited[s] = True count += 1 while queue: # Dequeue a vertex from # queue and print it s = queue.pop(0) # Get all adjacent vertices of the # dequeued vertex s. If a adjacent # has not been visited, then mark it # visited and enqueue it for i in self.graph[s]: if visited[i] == False: queue.append(i) visited[i] = True count += 1 return count def postprocess(count, g_dict, n_vertices): sorted_count = {k: t for k, t in sorted(count.items(), key=lambda item: item[1], reverse=True)} m = max(sorted_count.values()) filtered_count = {} for k in sorted_count: if sorted_count[k] > m/2+1: filtered_count[k] = sorted_count[k] else: break answer = [] for k in filtered_count.keys(): g = Graph() for i, v in enumerate(k[::-1]): if v == '1': g.addEdge(g_dict[i][0], g_dict[i][1]) if g.BFS(0) == n_vertices: answer.append(k) return answer postprocess(count, g_dict, n_vertices)
https://github.com/mballarin97/mps_qnn
mballarin97
# This code is part of qcircha. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Here we generate the data for Fig 7 where ALL the parameters are random without any data reuploading """ import os import numpy as np from qcircha.circuit_selector import _select_circ from qiskit import QuantumCircuit import qmatchatea as qmt from qmatchatea.qk_utils import qk_transpilation_params import qtealeaves.observables as obs from qtealeaves.emulator import MPS from tqdm import tqdm depth = 14 dir_name = f"data/all_random" num_qubits = 13 num_reps = 1 num_trials = 1 max_bond_dim = 128 if not os.path.isdir(dir_name): os.makedirs(dir_name) observables = obs.TNObservables() observables += obs.TNObsBondEntropy() observables += obs.TNState2File('mps_state.txt', 'F') conv_params = qmt.QCConvergenceParameters(int(max_bond_dim), singval_mode="C") backend = qmt.QCBackend() trans_params = qk_transpilation_params(linearize=True, tensor_compiler=False) feature_map = _select_circ(num_qubits, "zzfeaturemap") ansatz = _select_circ(num_qubits, "twolocal") num_avg = 1000 for idx, data in tqdm(enumerate(range(num_avg))): entanglement_total = [] singvals_cut_total = [] states_total = [] initial_state = "Vacuum" for num_reps in range(depth): print(f"\n__Reps {num_reps}/{depth}") random_params = np.pi * np.random.rand(len(ansatz.parameters)) random_params_data = np.pi * np.random.rand(len(feature_map.parameters)) binded_ansatz = ansatz.bind_parameters(random_params) binded_fmap = feature_map.bind_parameters(random_params_data) # Pick a PQC (modify the function) qc = QuantumCircuit(num_qubits) qc = qc.compose(binded_fmap) qc = qc.compose(binded_ansatz) io_info = qmt.QCIO(initial_state=initial_state) results = qmt.run_simulation(qc, convergence_parameters=conv_params, transpilation_parameters=trans_params, backend=backend, observables=observables, io_info=io_info) entanglement = np.array(list(results.entanglement.values())) initial_state = results.mps entanglement_total.append(entanglement) states_total.append(results.singular_values_cut) initial_state = MPS.from_tensor_list(initial_state) np.save( os.path.join(dir_name, f"entanglement_{idx+num_avg}.npy"), entanglement_total, allow_pickle=True)
https://github.com/mballarin97/mps_qnn
mballarin97
import matplotlib.pyplot as plt import numpy as np from qplotting import Qplotter from qplotting.utils import set_size_pt import seaborn as sns cmap = sns.color_palette('deep', as_cmap=True) def extract_fidelities(num_qubits): fids = {} for nq in num_qubits: path = f"data/svd_checks/{nq}/" singvals = [np.load(path+f"states_0.npy", allow_pickle=True)] for idx in range(1, 10): try: sv = np.load(path+f"states_{idx}.npy", allow_pickle=True) if sv.shape == singvals[0].shape: singvals.append( sv ) except: print(f"No file with index {idx} for {nq} qubits") break fidelities = [] for sv in singvals: fid = np.cumprod( (1-sv)**2 ) fidelities.append(fid) if len(fidelities) >1: mean_fid = np.mean(fidelities, axis=0) std_fid = np.std(fidelities, axis=0) else: mean_fid = fidelities std_fid = np.zeros_like(fidelities) fids[nq] = np.vstack((mean_fid, std_fid)) return fids num_qubits = [30, 50] fids = extract_fidelities(num_qubits) plotter = Qplotter() #plotter(nrows=1, ncols=2, figsize=set_size_pt(2*234, subplots=(1, 2)) ) plotter(figsize=set_size_pt(234)) tt_30 = fids[30].shape[1] tt_50 = fids[50].shape[1] len_layer_30 = int( tt_30/14 ) len_layer_50 = int( tt_50/14 ) fid_30_per_layer = fids[30][0, np.arange(0, tt_30, len_layer_30)] #[ np.prod( fids[30][0, :][ii*len_layer_30:(ii+1)*len_layer_30]) for ii in range(14) ] fid_50_per_layer = fids[50][0, np.arange(0, tt_50, len_layer_50)] #[ np.prod(fids[50][0, :][ii*len_layer_50:(ii+1)*len_layer_50]) for ii in range(14) ] layers = np.arange(1, 15) bonddim = [2**ii for ii in range(13)] entanglement = np.loadtxt("data/svd_checks/50/layer9_ent.npy") entanglement = np.max(entanglement, axis=1) relative_ent_err = np.abs(entanglement - entanglement[-1] )/entanglement[-1] with plotter as qplt: qplt.ax.axhline(1e-4, color="red", ls='--', alpha=0.8, label="Relaiability threshold") qplt.ax.plot(layers, 1-fid_30_per_layer+1e-12, 'o--', label="$n=30$", color=cmap[0]) qplt.ax.plot(layers, 1-fid_50_per_layer+1e-12, '*--', label="$n=50$", color=cmap[1]) qplt.ax.set_yscale("log") qplt.ax.set_xticks(np.arange(1, 15, 4)) #qplt.set_ylim(1e-13, 100) #qplt.ax[0].vlines(len_layer*13, mean_fid[len_layer*13]-0.005, mean_fid[len_layer*13]+0.005, label="layer", color="red") qplt.ax.set_xlabel("Number of layers $L$") qplt.ax.set_ylabel("Infidelity of the state $1-F(t)$") qplt.ax.legend(frameon=False, loc="center left") #qplt.ax[1].plot(bonddim, relative_ent_err[:13], 'o--', label="$L=9$", color=cmap[2]) #qplt.ax[1].set_ylabel("Relative entanglement error") #qplt.ax[1].set_xlabel("Maximum bond dimension $\chi_s$") #qplt.ax[1].set_xscale("log", base=2) #qplt.ax[1].set_yscale("log") #qplt.ax[1].legend(frameon=False) qplt.savefig("images/covergence.pdf") times_aer = np.loadtxt("data/marcos_plot/alternate_abbas16_Aer_time.npy") times_mps = np.loadtxt("data/marcos_plot/alternate_abbas16_MPS_time.npy") layers = np.arange(1, len(times_aer)+1) with Qplotter() as qplt: qplt.plot(layers, (times_aer), 'o--', label="Aer", color=cmap[0]) qplt.plot(layers, (times_mps), '*--', label="Mps", color=cmap[1]) qplt.set_xscale("log") qplt.set_yscale("log") qplt.set_ylabel("Time [s]") qplt.set_xlabel("Number of layers $L$") qplt.legend() qplt.savefig("images/Exact_MPS_comparison.pdf") from marchenko_pastur import gen_mp def kl_div(prob_p, prob_q, dp): prob_p += 1e-12 prob_q += 1e-12 return prob_p*np.log(prob_p/prob_q)*dp def get_mp_distributions(num_qub, max_num_layers, filename): bonddim = 2**(num_qub//2) bins = np.logspace(-5, -1.5, 50) num_layers = np.arange(1, max_num_layers) results = { "bins" : bins, "layers" : num_layers, "num_qubits" : num_qub, "xx" : (bins[1:]+ bins[:-1])/2, "dp" : (bins[1:]- bins[:-1]), } # Marchenko-pastur distributed l1 = num_qub//2 l2 = num_qub//2 if num_qub%2 == 0 else num_qub//2+1 sigma = np.sqrt(1.0 / 2**(max(l1, l2))) sampled_singvals = np.array([]) for _ in range(1000): s_singvals = gen_mp(2**l2, 2**l1, sigma, bonddim, bonddim) s_singvals /= np.sqrt( np.sum(s_singvals**2) ) sampled_singvals = np.append(sampled_singvals, s_singvals) mp_hist, _ = np.histogram(sampled_singvals**2, bins, density=True) results["mp"] = mp_hist results["cmp"] = np.cumsum(mp_hist)/np.sum(mp_hist) # From Haar-random state random_state_singvals = np.array([]) for _ in range(100): psi = np.random.normal(0, sigma, 2**num_qub) + 1j*np.random.normal(0, sigma, 2**num_qub) psi /= np.sqrt( np.sum( np.abs(psi)**2 ) ) rn_ss = np.linalg.svd(psi.reshape(2**l1, 2**l2), False, False) rn_ss /= np.sqrt( np.sum(rn_ss**2) ) random_state_singvals = np.hstack( (random_state_singvals, rn_ss)) rn_hist, _ = np.histogram(random_state_singvals**2, bins, density=True) results["random"] = rn_hist results["crandom"] = np.cumsum(rn_hist)/np.sum(rn_hist) # Experimental exp_hists = [] exp_cum = [] for nl in num_layers: singvals = [] for ss in np.load(filename + f"{num_qub}_{nl}.npy", allow_pickle=True): singvals = np.hstack((singvals, ss)) exp_hist, _ = np.histogram(singvals**2, bins, density=True) exp_hists.append(exp_hist) exp_cum.append( np.cumsum(exp_hist)/np.sum(exp_hist) ) results["exp"] = exp_hists results["cexp"] = exp_cum return results def plot_mp_results(fig, ax, results): mask = results["mp"] > 1e-10 ax[0].plot(results["xx"][mask], results["cmp"][mask], lw=5, label="MP") mask = results["random"] > 1e-10 ax[0].plot(results["xx"][mask], results["crandom"][mask], '--', lw=2, color="black", label="RAND") layers_to_plot = np.linspace( np.max(results["layers"])//3, np.max(results["layers"]), 4 ) layers_to_plot = np.unique( layers_to_plot.astype(int) ) kl_divergences = [] for idx, nl in enumerate(results["layers"]): exp_hist = results["exp"][idx] kl = kl_div(results["mp"], exp_hist, results["dp"]) kl_divergences.append(np.sum(kl) ) if nl in layers_to_plot: mask = exp_hist > 1e-10 ax[0].plot(results["xx"][mask], results["cexp"][idx][mask], '.-', label="$L=$"+str(nl), alpha=0.5 ) ax[0].legend() ax[0].set_yscale("log") ax[0].set_xscale("log") ax[0].set_ylabel("Cumulative probability") ax[0].set_xlabel("Singular values squared") kl_div_good = np.sum( kl_div(results["mp"], results["random"], results["dp"]) ) # Parameters of the variational ansatz + parameters of the feature map ax[1].axhline(kl_div_good, ls='--', color="black", label="Best value") #ax[1].axvline(2**num_qub, ls='--', color="red", label="Best value") ax[1].plot(results["layers"], kl_divergences, 'o', label="Experimental value") ax[1].set_yscale("log") #ax[1].set_xscale("log") ax[1].set_ylabel("KL divergence between experimental and MP distribution") ax[1].set_xlabel("Number of layers") ax[1].legend() def plot_mp_distribution(fig, ax, results): mask = results["mp"] > 1e-10 ax.plot(results["xx"][mask], results["cmp"][mask], lw=3, label="MP") mask = results["random"] > 1e-10 ax.plot(results["xx"][mask], results["crandom"][mask], '--', lw=1.5, color="black", label="Haar") layers_to_plot = [6, 10, 15] kl_divergences = [] for idx, nl in enumerate(results["layers"]): exp_hist = results["exp"][idx] kl = kl_div(results["mp"], exp_hist, results["dp"]) kl_divergences.append(np.sum(kl) ) if nl in layers_to_plot: mask = exp_hist > 1e-10 ax.plot(results["xx"][mask], results["cexp"][idx][mask], '.-', label="$L=$"+str(nl), alpha=0.8 ) ax.legend(frameon=False, handletextpad=0.4) ax.set_yscale("log") ax.set_xscale("log") ax.set_ylabel("CDF $C(\lambda^2)$") ax.set_xlabel("Singular values squared $\lambda^2$") ax.set_ylim(10**(-2.1), 1.5) filename = "data/marchenko-pastur/singvals" num_qub = 15 max_nl = 20 results15_zzc2 = get_mp_distributions(num_qub, max_nl, filename) filename = "data/marchenko-pastur/singvals_c2c2_" num_qub = 15 max_nl = 16 results15_c2c2 = get_mp_distributions(num_qub, max_nl, filename) with Qplotter() as qplt: plot_mp_distribution(qplt.fig, qplt.ax, results15_zzc2) qplt.savefig("images/mp_convergence.pdf")
https://github.com/mballarin97/mps_qnn
mballarin97
import sys sys.path.append('../') from circuits import sampleCircuitA, sampleCircuitB1, sampleCircuitB2,\ sampleCircuitB3, sampleCircuitC, sampleCircuitD, sampleCircuitE,\ sampleCircuitF from entanglement import Ent import warnings warnings.filterwarnings('ignore') labels = [ 'Circuit A', 'Circuit B1', 'Circuit B2', 'Circuit B3', 'Circuit C', 'Circuit D', 'Circuit E', 'Circuit F' ] samplers = [ sampleCircuitA, sampleCircuitB1, sampleCircuitB2, sampleCircuitB3, sampleCircuitC, sampleCircuitD, sampleCircuitE, sampleCircuitF ] q = 4 for layer in range(1, 4): print(f'qubtis: {q}') print('-' * 25) for (label, sampler) in zip(labels, samplers): expr = Ent(sampler, layer=layer, epoch=3000) print(f'{label}(layer={layer}): {expr}') print()
https://github.com/mballarin97/mps_qnn
mballarin97
import numpy as np from qiskit.quantum_info import state_fidelity, Statevector def getStatevector(circuit): return Statevector(circuit).data import warnings warnings.filterwarnings('ignore') def P_haar(N, F): if F == 1: return 0 else: return (N - 1) * ((1 - F) ** (N - 2)) def KL(P, Q): epsilon = 1e-8 kl_divergence = 0.0 for p, q in zip(P, Q): kl_divergence += p * np.log( (p + epsilon) / (q + epsilon) ) return abs(kl_divergence) def expressibility(qubits, sampler, *, bins=100, epoch=3000, layer=1, encode=False, return_detail=False): unit = 1 / bins limits = [] probabilities = np.array([0] * bins) for i in range(1, bins + 1): limits.append(unit * i) for i in range(epoch): circuit_1 = sampler(layer=layer, qubits=qubits) circuit_2 = sampler(layer=layer, qubits=qubits) f = state_fidelity( getStatevector(circuit_1), getStatevector(circuit_2) ) for j in range(bins): if f <= limits[j]: probabilities[j] += 1 break pHaar_vqc = [ P_haar(2 ** qubits, f - (unit/2)) / bins for f in limits] probabilities = [ p / epoch for p in probabilities ] if return_detail: return pHaar_vqc, probabilities else: return KL(probabilities, pHaar_vqc)
https://github.com/mballarin97/mps_qnn
mballarin97
# This code is part of qcircha. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Here we preprocess and produce the data for real work datasets, i.e. the wine and breast cancer datasets """ import os import numpy as np from qcircha.circuit_selector import _select_circ from qiskit import QuantumCircuit import qmatchatea as qmt from qmatchatea.qk_utils import qk_transpilation_params import qtealeaves.observables as obs from qtealeaves.emulator import MPS from sklearn import preprocessing from tqdm import tqdm depth = 14 dataset_name = "breast" if dataset_name == "wine": dir_name = f"data/datasets/wine/" input_file = "datasets/wine.data" num_qubits = 13 else: dir_name = f"data/datasets/breast_cancer/" input_file = "datasets/breast-cancer.data" num_qubits = 9 num_reps = 1 num_avg = 10 max_bond_dim = 128 if not os.path.isdir(dir_name): os.makedirs(dir_name) observables = obs.TNObservables() observables += obs.TNObsBondEntropy() observables += obs.TNState2File('mps_state.txt', 'F') conv_params = qmt.QCConvergenceParameters(int(max_bond_dim), singval_mode="C") backend = qmt.QCBackend() trans_params = qk_transpilation_params(linearize=True) feature_map = _select_circ(num_qubits, "zzfeaturemap") ansatz = _select_circ(num_qubits, "twolocal") # Load dataset and remove dataset = np.loadtxt(input_file, delimiter=",", dtype=str)[:, 1:] if dataset_name == "breast": new_dataset = [] for features in dataset.T: new_dataset.append( preprocessing.LabelEncoder().fit_transform(features) ) dataset = np.array(new_dataset).T min_max_scaler = preprocessing.MinMaxScaler() dataset = min_max_scaler.fit_transform(dataset)*np.pi idx = 0 for data in tqdm((dataset)): binded_fmap = feature_map.bind_parameters(data) for _ in range(num_avg): initial_state = "Vacuum" entanglement_total = [] singvals_cut_total = [] states_total = [] for num_reps in range(depth): #print(f"\n__Reps {num_reps}/{depth}") random_params = np.pi * np.random.rand(len(ansatz.parameters)) binded_ansatz = ansatz.bind_parameters(random_params) # Pick a PQC (modify the function) qc = QuantumCircuit(num_qubits) qc = qc.compose(binded_fmap) qc = qc.compose(binded_ansatz) io_info = qmt.QCIO(initial_state=initial_state) results = qmt.run_simulation(qc, convergence_parameters=conv_params, transpilation_parameters=trans_params, backend=backend, observables=observables, io_info=io_info) entanglement = np.array(list(results.entanglement.values())) initial_state = results.mps entanglement_total.append(entanglement) states_total.append(results.singular_values_cut) initial_state = MPS.from_tensor_list(initial_state) np.save( os.path.join(dir_name, f"entanglement_{idx}.npy"), entanglement_total, allow_pickle=True) #np.save( os.path.join(dir_name, f"states_{idx}.npy"), states_total, allow_pickle=True) idx += 1
https://github.com/mballarin97/mps_qnn
mballarin97
from qiskit import * from oracle_generation import generate_oracle get_bin = lambda x, n: format(x, 'b').zfill(n) def gen_circuits(min,max,size): circuits = [] secrets = [] ORACLE_SIZE = size for i in range(min,max+1): cur_str = get_bin(i,ORACLE_SIZE-1) (circuit, secret) = generate_oracle(ORACLE_SIZE,False,3,cur_str) circuits.append(circuit) secrets.append(secret) return (circuits, secrets)
https://github.com/mballarin97/mps_qnn
mballarin97
# This code is part of qcircha. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Functions to create and manage QNNs, in addition to some pre-defined structures. It is used as an intermediate step to create QNNs using the definitions in the script `circuit.py`. Circuits for the `ZZFeatureMap` and `TwoLocal` schemes with all possible entangling topologies are defined. """ # Import necessary modules from qiskit import QuantumCircuit from qiskit.circuit.library import ZZFeatureMap, TwoLocal from qcircha.circuits import * def pick_circuit(num_qubits, num_reps, feature_map = 'ZZFeatureMap', var_ansatz = 'TwoLocal', alternate=True): """ Select a circuit with a feature map and a variational block. Examples below. Each block must have reps = 1, and then specify the correct number of repetitions is ensured by the :py:func:`general_qnn`. Available circuits: - 'ZZFeatureMap' : circuit with linear entanglement, used as feature map in the Power of Quantum Neural networks by Abbas et al. - 'TwoLocal' : circuit with linear entanglement, used as ansatz in the Power of Quantum Neural networks by Abbas et al. - 'Circuit15' : circuit with ring entanglement, defined in (n.15 from Kim et al.) - 'Circuit12' : circuit with linear entanglement and a piramidal structure, defined in (n.12 from Kim et al.) - 'Circuit1' : circuit without entanglement with two single qubits rotations per qubit (n.1 from Kim et al.) - 'Identity' : identity circuit - 'Circuit9' : circuit n. 9 from Kim et al. - variations of TwoLocal structures are present. Parameters ---------- num_qubits : int Number of qubits num_reps : int Number of repetitions feature_map : str or :py:class:`QuantumCircuit`, optional Type of feature map. Available options in the description. If a :py:class:`QuantumCircuit` it is used instead of the default ones. Default to 'ZZFeatureMap'. ansatz : str or :py:class:`QuantumCircuit`, optional Type of feature map. Available options in the description. If a :py:class:`QuantumCircuit` it is used instead of the default ones. Default to 'TwoLocal'. alternate : bool, optional If the feature map and the variational ansatz should be alternated in the disposition (True) or if first apply ALL the feature map repetitions and then all the ansatz repetitions (False). Default to True. Return ------ :py:class:`QuantumCircuit` quantum circuit with the correct structure """ feature_map = _select_circ(num_qubits, feature_map) var_ansatz = _select_circ(num_qubits, var_ansatz) # Build the PQC ansatz = general_qnn(num_reps, feature_map=feature_map, var_ansatz=var_ansatz, alternate=alternate, barrier=True) return ansatz def _select_circ(num_qubits, circ = 'ZZFeatureMap'): """ Select the circuit based on the possibilities Available circuits: - 'ZZFeatureMap' : circuit with linear entanglement, used as feature map in the Power of Quantum Neural networks by Abbas et al. - 'TwoLocal' : circuit with linear entanglement, used as ansatz in the Power of Quantum Neural networks by Abbas et al. - 'Circuit15' : circuit with ring entanglement, defined in (n.15 from Kim et al.) - 'Circuit12' : circuit with linear entanglement and a piramidal structure, defined in (n.12 from Kim et al.) - 'Circuit1' : easy circuit without entanglement (n.1 from Kim et al.) - 'circuit9' : circuit n. 9 from Kim et al. Parameters ---------- num_qubits : int Number of qubits circ : str or :py:class:`QuantumCircuit`, optional Type of circuit. Available options in the description. If a :py:class:`QuantumCircuit` it is used instead of the default ones. Default to 'ZZFeatureMap'. Return ------ :py:class:`QuantumCircuit` Selected quantum circuit """ # If it is a quantum circuit, directly return that. # Otherwise, go through the list if not isinstance(circ, QuantumCircuit): circ = circ.lower() if circ == 'zzfeaturemap': circ = ZZFeatureMap(num_qubits, reps=1, entanglement='linear') elif circ == 'twolocal': circ = TwoLocal(num_qubits, 'ry', 'cx', 'linear', reps=1, skip_final_rotation_layer=True) elif circ == 'twolocalx': circ = TwoLocal(num_qubits, 'rx', 'cx', 'linear', reps=1, skip_final_rotation_layer=True, name = "TwoLocalX") elif circ == 'twolocalz': circ = TwoLocal(num_qubits, 'rz', 'cx', 'linear', reps=1, skip_final_rotation_layer=True, name="TwoLocalZ") elif circ == 'zzfeaturemap_ring': circ = ZZFeatureMap(num_qubits, reps=1, entanglement='circular') elif circ == 'twolocal_ring': circ = TwoLocal(num_qubits, 'ry', 'cx', 'circular', reps=1, skip_final_rotation_layer=True) elif circ == 'zzfeaturemap_full': circ = ZZFeatureMap(num_qubits, reps=1, entanglement='full') elif circ == 'twolocal_full': circ = TwoLocal(num_qubits, 'ry', 'cx', 'full', reps=1, skip_final_rotation_layer=True) elif circ == 'twolocal_plus': circ = TwoLocal(num_qubits, ['rz', 'ry'], 'cx', 'linear', reps=1, skip_final_rotation_layer=True, name = 'TwoLocal_plus') elif circ == 'twolocal_plus_ring': circ = TwoLocal(num_qubits, ['rz', 'ry'], 'cx', 'circular', reps=1, skip_final_rotation_layer=True, name='TwoLocal_plus') elif circ == 'twolocal_plus_full': circ = TwoLocal(num_qubits, ['rz', 'ry'], 'cx', 'full', reps=1, skip_final_rotation_layer=True, name='TwoLocal_plus') elif circ == 'twolocal_parametric2q': circ = TwoLocal(num_qubits, 'ry', 'crz', 'linear', reps=1, skip_final_rotation_layer=True, name='TwoLocal_parametricRz') elif circ == 'twolocal_parametric2q_ring': circ = TwoLocal(num_qubits, 'ry', 'crz', 'circular', reps=1, skip_final_rotation_layer=True, name='TwoLocal_parametricRz') elif circ == 'twolocal_parametric2q_full': circ = TwoLocal(num_qubits, 'ry', 'crz', 'full', reps=1, skip_final_rotation_layer=True, name='TwoLocal_parametricRz') elif circ == 'twolocal_h_parametric2q': circ = TwoLocal(num_qubits, 'h', 'crx', 'linear', reps=1, skip_final_rotation_layer=True, name='TwoLocal_h_parametricRz') elif circ == 'twolocal_h_parametric2q_ring': circ = TwoLocal(num_qubits, 'h', 'crx', 'circular', reps=1, skip_final_rotation_layer=True, name='TwoLocal_h_parametricRz') elif circ == 'twolocal_h_parametric2q_full': circ = TwoLocal(num_qubits, 'h', 'crx', 'full', reps=1, skip_final_rotation_layer=True, name='TwoLocal_h_parametricRz') elif circ == 'circuit15': circ = circuit15(num_qubits, num_reps=1, barrier=False) elif circ == 'circuit12': circ = circuit12(num_qubits, num_reps=1, piramidal=True, barrier=False) elif circ == 'circuit9': circ = circuit9(num_qubits, num_reps=1, barrier = False) elif circ == 'circuit10': circ = circuit10(num_qubits, num_reps=1, barrier=False) elif circ == 'circuit1': circ = circuit1(num_qubits, num_reps = 1, barrier = False) elif circ == 'identity': circ = identity(num_qubits) elif circ == 'mps': circ = mps_circ(num_qubits) else: raise ValueError(f'Circuit {circ} is not implemented.') return circ
https://github.com/mballarin97/mps_qnn
mballarin97
# This code is part of qcircha. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Main script in the library, where all the computation happens, and that is imported in all other scripts. Here you can pass a PQC of your choice, and select a simulation backend, MPS, or Qiskit's Aer. Several random parameter vectors (100 by default) are generated and the circuit is run this many times, and the entanglement entropy of the final state is saved. In the subdirectiroy `entanglement` there are scripts for the evaluation of the entanglement entropy of quantum states. """ # Import necessary modules import time try: from qmatchatea import run_simulation from qmatchatea.qk_utils import qk_transpilation_params from qmatchatea import QCConvergenceParameters, QCBackend import qtealeaves.observables as obs MPS_AVAILABLE = True except ImportError: MPS_AVAILABLE = False import numpy as np from qiskit import Aer, transpile from qcircha.entanglement.haar_entanglement import haar_bond_entanglement from qcircha.entanglement.statevector_entanglement import entanglement_bond from qcircha.utils import logger import matplotlib.pyplot as plt __all__ = ['entanglement_characterization'] def _run_mps(qc, max_bond_dim=1024, do_statevector=False): """ Runs a quantum circuit (parameters already numerical) with MPS. Parameters ---------- qc : :py:class:`QuantumCircuit` qiskit quantum circuit class max_bond_dim: int, optional Maximum bond dimension for the MPS. Default to 1024 do_statevector : bool, optional If True, compute the statevector of the system. Default to None. Returns ------- :py:class:`qcomps.simulation_results` The results of the simulations, comprehensive of the entanglement """ observables = obs.TNObservables() observables += obs.TNObsBondEntropy() if do_statevector: observables += obs.TNState2File('mps_state.txt', 'F') conv_params = QCConvergenceParameters(int(max_bond_dim) ) trans_params = qk_transpilation_params(linearize=True) backend = QCBackend() results = run_simulation(qc, convergence_parameters=conv_params, transpilation_parameters=trans_params, backend=backend, observables=observables) return results def _run_circuit(qc, parameters, max_bond_dim=1024, do_statevector=False): """ Assigns parameters to the quantum circuits and runs it with python-MPS. Parameters ---------- qc : :py:class:`QuantumCircuit` qiskit quantum circuit class parameters : array-like Array of parameters, which length should match the number of parameters in the variational circuit max_bond_dim: int, optional Maximum bond dimension for the MPS. Default to 1024. do_statevector : bool, optional If True, compute the statevector of the system. Default to None. Returns ------- :py:class:`qcomps.simulation_results` The results of the simulations, comprehensive of the entanglement """ qc = qc.assign_parameters(parameters) results = _run_mps(qc, max_bond_dim=max_bond_dim, do_statevector=do_statevector) return results def _mps_simulation(qc, random_params, max_bond_dim=1024, do_statevector=False): """" Simulation using MPS to study bond entanglement. Parameters ---------- qc : :py:class:`QuantumCircuit` qiskit quantum circuit class random_params : array-like of array-like Sets of random parameters over which obtain the average max_bond_dim : int, optional Maximum bond dimension for MPS simulation do_statevector : bool, optional If True, compute the statevector of the system. Default to None. Returns ------- array-like of floats Average of the entanglement over different parameter sets array-like of floats Standard deviation of the entanglement over different parameter sets array-like of ndarray Array of statevectors if do_statevector=True, otherwise array of None """ sim_bknd = Aer.get_backend('statevector_simulator') mps_results_list = [] statevector_list = [] for idx, params in enumerate(random_params): print(f"Run {idx}/{len(random_params)}", end="\r") qc = transpile(qc, sim_bknd) # Why this transpilation? mps_results = _run_circuit(qc, params, max_bond_dim=max_bond_dim, do_statevector=do_statevector) mps_results_list.append(mps_results) #print(mps_results_list[0].entanglement ) mps_entanglement = np.array([list(res.entanglement.values()) for res in mps_results_list]) ent_means = np.mean(mps_entanglement, axis=0) ent_std = np.std(mps_entanglement, axis=0) statevector_list = [res.statevector for res in mps_results_list] return ent_means, ent_std, statevector_list def _aer_simulation(qc, random_params, get_statevector = False): """ Simulation using Qiskit Aer to study bond entanglement. TODO: add **kwargs to customize the backend Parameters ---------- qc : :py:class:`QuantumCircuit` qiskit quantum circuit class random_params : array-like of array-like Sets of random parameters over which obtain the average Returns ------- array-like of floats Average of the entanglement over different parameter sets array-like of floats Standard deviation of the entanglement over different parameter sets array-like of floats or None statevector of the system """ qk_results_list = [] sim_bknd = Aer.get_backend('statevector_simulator') qc_t = transpile(qc, backend=sim_bknd) for idx, params in enumerate(random_params): print(f"Run {idx}/{len(random_params)}", end="\r") qk_results = sim_bknd.run(qc_t.assign_parameters(params)) qk_results_list.append(np.asarray(qk_results.result().get_statevector())) print("\nPartial tracing...") now = time.time() aer_ent = np.array([entanglement_bond(state) for state in qk_results_list]) print(f" >> Ended in {time.time()-now}") ent_means = np.mean(aer_ent, axis=0) ent_std = np.std(aer_ent, axis=0) if get_statevector == False: qk_results_list = None return ent_means, ent_std, qk_results_list def entanglement_characterization(ansatz = None, backend = 'Aer', get_statevector = False, distribution=None, trials=100, **kwargs): """ Main method to perform the computation, given the simulation details of the ansatz Parameters ---------- ansatz : :py:class:`QuantumCircuit`, optional Quantum circuit with additional metadata, by default None backend : str, optional backend of the simulation. Possible: 'MPS', 'Aer', by default 'Aer' get_statevector : bool, optional If True, returns the statevector, by default False distribution : callable, optional Function to generate the random parameters that will be used in the simulation. It should take only a tuple as input, which is the shape of the generated numpy array. If None, use random parameters uniformly distributed in :math:`U(0, \\pi)`. To obtain this distribution you might use the numpy.random module with the aid of functools.partial. Default to None. trials : int, optional Number of repetitions over which the average is taken. Default to 100. Returns ------- array-like of floats average of the entanglement entropy of the ansatz along all bipartitions array-like of floats standard deviation of the entanglement entropy of the ansatz along all bipartitions array-like of floats average of the entanglement entropy of a Haar circuit along all bipartitions array-like of floats or None statevector of the system """ metadata = ansatz.metadata logger(metadata) num_qubits = metadata['num_qubits'] try: max_bond_dim = metadata['max_bond_dim'] except: max_bond_dim = 100 ###################################################### # GENERATE RANDOM PARAMETERS (both inputs and weights) if distribution is None: random_params = np.pi * np.random.rand(trials, len(ansatz.parameters)) elif callable(distribution): random_params = distribution( (trials, len(ansatz.parameters)) ) else: raise TypeError('The variable distribution should be a callable or None, ' + f'not {type(distribution)}') ###################################################### # SIMULATION WITH MPS or Aer if backend == 'MPS': if not MPS_AVAILABLE: raise RuntimeError('MPS package qmatcha is not installed, so MPS simulation cannot be ran') if 'max_bond_dim' in kwargs: max_bond_dim = kwargs['max_bond_dim'] ent_means, ent_std, statevectors = _mps_simulation(ansatz, random_params, max_bond_dim, do_statevector=get_statevector) elif backend == 'Aer': ent_means, ent_std, statevectors = _aer_simulation(ansatz, random_params, get_statevector=get_statevector) else: raise TypeError(f"Backend {backend} not available") ###################################################### # ENTANGLEMENT STUDY print("Measured entanglement = ", np.round(ent_means, 4)) # Expected entanglement accross cut lines if Haar distributed ent_haar = haar_bond_entanglement(num_qubits) print("Haar entanglement at bond = ", np.round(ent_haar, 4)) ###################################################### return ent_means, ent_std, ent_haar, statevectors
https://github.com/mballarin97/mps_qnn
mballarin97
# This code is part of qcircha. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Uses the simulation results from `entanglement_characterization.py` to evaluate the expressibility of a QNN, using the definition in [Sim et al. 2019](https://arxiv.org/abs/1905.10876). Such measure requires to construct a histogram of fidelities of states generated by the QNN, to be compared with random states sampled from the uniform Haar distribution. The default number of bins of the histogram is 100, the number of fidelities used to build the histogram is 4950 ( = (100**2 - 100) / 2), obtained by all possible different combinations of the 100 states generated by `entanglement_characterization.py` """ import time import json import os import sys import numpy as np import scipy as sp from qiskit import Aer import matplotlib.pyplot as plt import seaborn as sns sns.set_theme() from qcircha.circuits import * from qcircha.circuit_selector import pick_circuit from qcircha.entanglement_characterization import entanglement_characterization from qcircha.entanglement.haar_entanglement import haar_discrete from qcircha.utils import removekey def kl_divergence(p, q, eps = 1e-20) : """ Compute the KL divergence between two probability distributions Parameters ---------- p : array-like of floats First probability distribution q : array-like of floats Second probability distribution Returns ------- float KL divergence of p and q """ # Eliminate divergences (check if safe to do) q = np.array([max(eps, q_j) for q_j in q]) p = np.array([max(eps, p_j) for p_j in p]) #return np.sum(p * np.log(p/q)) return sp.stats.entropy(p, q, base=np.e) def eval_kl(fidelities, n_bins=20, num_qubits=4): """ Evaluate KL divergence Parameters ---------- fidelities : _type_ _description_ n_bins : int, optional _description_, by default 20 num_qubits : int, optional _description_, by default 4 Returns ------- _type_ _description_ """ discrete_haar = np.array([haar_discrete(x, 1/n_bins, 2 ** num_qubits) for x in np.linspace(0, 1, n_bins + 1)[:-1]]) y, _ = np.histogram(fidelities, range=(0, 1), bins=n_bins) y = y / np.sum(y) return kl_divergence(y, discrete_haar), y, discrete_haar def inner_products(state_list, rep): """ """ inner_p = [] num_tests = len(state_list[0, :, 0]) for i in range(num_tests): for j in range(i): tmp = np.abs(state_list[rep, i, :] @ np.conjugate(state_list[rep, j, :])) ** 2 inner_p.append(tmp) return np.array(inner_p) def compute_espressivity(num_qubits, repetitions, feature_map = None, var_ansatz=None, alternate = True, backend='Aer', path='./data/expr/', plot=False, save=False, max_bond_dim=None): if isinstance(repetitions, int): reps = range(1, repetitions + 1) else: reps = repetitions # Generate random states from QNN st_list = [] for num_reps in reps: ansatz = pick_circuit(num_qubits, num_reps, feature_map=feature_map, var_ansatz=var_ansatz, alternate=alternate) _, _, _, statevectors = entanglement_characterization(ansatz, backend=backend, get_statevector=True, max_bond_dim = max_bond_dim) statevectors = np.array(statevectors) st_list.append(statevectors) print("") st_list = np.array(st_list) # Evaluate inner products res = [] for idx, rep in enumerate(reps): res.append(inner_products(st_list, idx)) res = np.array(res) # Build histogram of distribution and evaluate KL divergence with Haar n_bins = 100 num_qubits = ansatz.metadata['num_qubits'] expressibility = [eval_kl(data, n_bins=n_bins, num_qubits = num_qubits)[0] for data in res] if save == True: # Save data if not os.path.isdir(path): os.makedirs(path) timestamp = time.localtime() save_as = time.strftime("%Y-%m-%d_%H-%M-%S", timestamp) + '_' + str(np.random.randint(0, 1000)) name = os.path.join(path, save_as) # Save details of the ansatz meta = dict({"n_bins": n_bins, "backend": backend}) circ_data = removekey(ansatz.metadata, ["num_reps", "params"]) meta.update(circ_data) # add metadata from the ansatz with open(name+'.json', 'w') as file: json.dump(meta, file, indent=4) expressibility = np.array(expressibility, dtype=object) np.save(name, expressibility, allow_pickle=True) if plot == True: fig = plt.figure(figsize=(9.6, 6)) plt.ylim([1e-3, 1]) plt.ylabel(r"$Expr. D_{KL}$") plt.xlabel("Repetitions") plt.yscale('log') plt.plot(reps, expressibility, marker='o', ls='--') plt.tight_layout() plt.show() return expressibility if __name__ == '__main__': # Fixing seed for reproducibility # seed = 120 # np.random.seed(seed) num_qubits = 6 feature_map = 'ZZFeatureMap' var_ansatz = 'TwoLocal' alternate = True backend = 'Aer' repetitions = num_qubits path = './data/expr/' compute_espressivity(num_qubits, repetitions, feature_map = feature_map, var_ansatz=var_ansatz, backend=backend, path=path, plot = True, save = True)
https://github.com/ionq-samples/Ion-Q-Thruster
ionq-samples
from qiskit import transpile from qiskit.transpiler import PassManager, PassManagerConfig from qiskit.transpiler.preset_passmanagers.plugin import PassManagerStagePlugin from rewrite_rules import GPI2_Adjoint, GPI_Adjoint, CommuteGPI2MS, CancelFourGPI2 from qiskit.converters import circuit_to_dag class IonQ_Transpiler: def __init__(self, backend): self.backend = backend self.pass_manager = self.custom_pass_manager() @staticmethod def custom_pass_manager(): # custom pass manager for optimization pm = PassManager() pm.append([ GPI2_Adjoint(), GPI_Adjoint(), CommuteGPI2MS(), CancelFourGPI2() ]) return pm def transpile(self, qc): ibm_transpiled = transpile(qc, backend=self.backend, optimization_level=3) # TODO: Replace with the custom transpiler optimized_circuit = self.pass_manager.run(ibm_transpiled) # Run the pass manager until no further optimizations are possible while True: previous_dag = circuit_to_dag(optimized_circuit) optimized_circuit = self.pass_manager.run(optimized_circuit) if circuit_to_dag(optimized_circuit) == previous_dag: break return optimized_circuit
https://github.com/ionq-samples/Ion-Q-Thruster
ionq-samples
%%capture %pip install qiskit %pip install qiskit_ibm_provider %pip install qiskit-aer # Importing standard Qiskit libraries from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, QuantumCircuit, transpile, Aer from qiskit_ibm_provider import IBMProvider from qiskit.tools.jupyter import * from qiskit.visualization import * from qiskit.circuit.library import C3XGate # Importing matplotlib import matplotlib.pyplot as plt # Importing Numpy, Cmath and math import numpy as np import os, math, cmath from numpy import pi # Other imports from IPython.display import display, Math, Latex # Specify the path to your env file env_file_path = 'config.env' # Load environment variables from the file os.environ.update(line.strip().split('=', 1) for line in open(env_file_path) if '=' in line and not line.startswith('#')) # Load IBM Provider API KEY IBMP_API_KEY = os.environ.get('IBMP_API_KEY') # Loading your IBM Quantum account(s) IBMProvider.save_account(IBMP_API_KEY, overwrite=True) # Run the quantum circuit on a statevector simulator backend backend = Aer.get_backend('statevector_simulator') qc_b1 = QuantumCircuit(2, 2) qc_b1.h(0) qc_b1.cx(0, 1) qc_b1.draw(output='mpl', style="iqp") sv = backend.run(qc_b1).result().get_statevector() sv.draw(output='latex', prefix = "|\Phi^+\\rangle = ") qc_b2 = QuantumCircuit(2, 2) qc_b2.x(0) qc_b2.h(0) qc_b2.cx(0, 1) qc_b2.draw(output='mpl', style="iqp") sv = backend.run(qc_b2).result().get_statevector() sv.draw(output='latex', prefix = "|\Phi^-\\rangle = ") qc_b2 = QuantumCircuit(2, 2) qc_b2.h(0) qc_b2.cx(0, 1) qc_b2.z(0) qc_b2.draw(output='mpl', style="iqp") sv = backend.run(qc_b2).result().get_statevector() sv.draw(output='latex', prefix = "|\Phi^-\\rangle = ") qc_b3 = QuantumCircuit(2, 2) qc_b3.x(1) qc_b3.h(0) qc_b3.cx(0, 1) qc_b3.draw(output='mpl', style="iqp") sv = backend.run(qc_b3).result().get_statevector() sv.draw(output='latex', prefix = "|\Psi^+\\rangle = ") qc_b3 = QuantumCircuit(2, 2) qc_b3.h(0) qc_b3.cx(0, 1) qc_b3.x(0) qc_b3.draw(output='mpl', style="iqp") sv = backend.run(qc_b3).result().get_statevector() sv.draw(output='latex', prefix = "|\Psi^+\\rangle = ") qc_b4 = QuantumCircuit(2, 2) qc_b4.x(0) qc_b4.h(0) qc_b4.x(1) qc_b4.cx(0, 1) qc_b4.draw(output='mpl', style="iqp") sv = backend.run(qc_b4).result().get_statevector() sv.draw(output='latex', prefix = "|\Psi^-\\rangle = ") qc_b4 = QuantumCircuit(2, 2) qc_b4.h(0) qc_b4.cx(0, 1) qc_b4.x(0) qc_b4.z(1) qc_b4.draw(output='mpl', style="iqp") sv = backend.run(qc_b4).result().get_statevector() sv.draw(output='latex', prefix = "|\Psi^-\\rangle = ") def sv_latex_from_qc(qc, backend): sv = backend.run(qc).result().get_statevector() return sv.draw(output='latex') qc_ej2 = QuantumCircuit(4, 4) qc_ej2.x(0) sv_latex_from_qc(qc_ej2, backend) qc_ej2 = QuantumCircuit(4, 4) qc_ej2.x(1) sv_latex_from_qc(qc_ej2, backend) qc_ej2 = QuantumCircuit(4, 4) qc_ej2.x(0) qc_ej2.x(1) sv_latex_from_qc(qc_ej2, backend) qc_ej2 = QuantumCircuit(4, 4) qc_ej2.x(2) sv_latex_from_qc(qc_ej2, backend) qc_ej2 = QuantumCircuit(4, 4) qc_ej2.x(0) qc_ej2.x(2) sv_latex_from_qc(qc_ej2, backend) qc_ej2 = QuantumCircuit(4, 4) qc_ej2.x(0) qc_ej2.x(2) sv_latex_from_qc(qc_ej2, backend) qc_ej2 = QuantumCircuit(4, 4) qc_ej2.x(0) qc_ej2.x(1) qc_ej2.x(2) sv_latex_from_qc(qc_ej2, backend) qc_ej2 = QuantumCircuit(4, 4) qc_ej2.x(3) sv_latex_from_qc(qc_ej2, backend) def circuit_adder (num): if num<1 or num>8: raise ValueError("Out of range") ## El enunciado limita el sumador a los valores entre 1 y 8. Quitar esta restricción sería directo. # Definición del circuito base que vamos a construir qreg_q = QuantumRegister(4, 'q') creg_c = ClassicalRegister(1, 'c') circuit = QuantumCircuit(qreg_q, creg_c) qbit_position = 0 for element in reversed(np.binary_repr(num)): if (element=='1'): circuit.barrier() match qbit_position: case 0: # +1 circuit.append(C3XGate(), [qreg_q[0], qreg_q[1], qreg_q[2], qreg_q[3]]) circuit.ccx(qreg_q[0], qreg_q[1], qreg_q[2]) circuit.cx(qreg_q[0], qreg_q[1]) circuit.x(qreg_q[0]) case 1: # +2 circuit.ccx(qreg_q[1], qreg_q[2], qreg_q[3]) circuit.cx(qreg_q[1], qreg_q[2]) circuit.x(qreg_q[1]) case 2: # +4 circuit.cx(qreg_q[2], qreg_q[3]) circuit.x(qreg_q[2]) case 3: # +8 circuit.x(qreg_q[3]) qbit_position+=1 return circuit add_3 = circuit_adder(3) add_3.draw(output='mpl', style="iqp") qc_test_2 = QuantumCircuit(4, 4) qc_test_2.x(1) qc_test_2_plus_3 = qc_test_2.compose(add_3) qc_test_2_plus_3.draw(output='mpl', style="iqp") sv_latex_from_qc(qc_test_2_plus_3, backend) qc_test_7 = QuantumCircuit(4, 4) qc_test_7.x(0) qc_test_7.x(1) qc_test_7.x(2) qc_test_7_plus_8 = qc_test_7.compose(circuit_adder(8)) sv_latex_from_qc(qc_test_7_plus_8, backend) #qc_test_7_plus_8.draw() theta = 6.544985 phi = 2.338741 lmbda = 0 alice_1 = 0 alice_2 = 1 bob_1 = 2 qr_alice = QuantumRegister(2, 'Alice') qr_bob = QuantumRegister(1, 'Bob') cr = ClassicalRegister(3, 'c') qc_ej3 = QuantumCircuit(qr_alice, qr_bob, cr) qc_ej3.barrier(label='1') qc_ej3.u(theta, phi, lmbda, alice_1); qc_ej3.barrier(label='2') qc_ej3.h(alice_2) qc_ej3.cx(alice_2, bob_1); qc_ej3.barrier(label='3') qc_ej3.cx(alice_1, alice_2) qc_ej3.h(alice_1); qc_ej3.barrier(label='4') qc_ej3.measure([alice_1, alice_2], [alice_1, alice_2]); qc_ej3.barrier(label='5') qc_ej3.x(bob_1).c_if(alice_2, 1) qc_ej3.z(bob_1).c_if(alice_1, 1) qc_ej3.measure(bob_1, bob_1); qc_ej3.draw(output='mpl', style="iqp") result = backend.run(qc_ej3, shots=1024).result() counts = result.get_counts() plot_histogram(counts) sv_0 = np.array([1, 0]) sv_1 = np.array([0, 1]) def find_symbolic_representation(value, symbolic_constants={1/np.sqrt(2): '1/√2'}, tolerance=1e-10): """ Check if the given numerical value corresponds to a symbolic constant within a specified tolerance. Parameters: - value (float): The numerical value to check. - symbolic_constants (dict): A dictionary mapping numerical values to their symbolic representations. Defaults to {1/np.sqrt(2): '1/√2'}. - tolerance (float): Tolerance for comparing values with symbolic constants. Defaults to 1e-10. Returns: str or float: If a match is found, returns the symbolic representation as a string (prefixed with '-' if the value is negative); otherwise, returns the original value. """ for constant, symbol in symbolic_constants.items(): if np.isclose(abs(value), constant, atol=tolerance): return symbol if value >= 0 else '-' + symbol return value def array_to_dirac_notation(array, tolerance=1e-10): """ Convert a complex-valued array representing a quantum state in superposition to Dirac notation. Parameters: - array (numpy.ndarray): The complex-valued array representing the quantum state in superposition. - tolerance (float): Tolerance for considering amplitudes as negligible. Returns: str: The Dirac notation representation of the quantum state. """ # Ensure the statevector is normalized array = array / np.linalg.norm(array) # Get the number of qubits num_qubits = int(np.log2(len(array))) # Find indices where amplitude is not negligible non_zero_indices = np.where(np.abs(array) > tolerance)[0] # Generate Dirac notation terms terms = [ (find_symbolic_representation(array[i]), format(i, f"0{num_qubits}b")) for i in non_zero_indices ] # Format Dirac notation dirac_notation = " + ".join([f"{amplitude}|{binary_rep}⟩" for amplitude, binary_rep in terms]) return dirac_notation def array_to_matrix_representation(array): """ Convert a one-dimensional array to a column matrix representation. Parameters: - array (numpy.ndarray): The one-dimensional array to be converted. Returns: numpy.ndarray: The column matrix representation of the input array. """ # Replace symbolic constants with their representations matrix_representation = np.array([find_symbolic_representation(value) or value for value in array]) # Return the column matrix representation return matrix_representation.reshape((len(matrix_representation), 1)) def array_to_dirac_and_matrix_latex(array): """ Generate LaTeX code for displaying both the matrix representation and Dirac notation of a quantum state. Parameters: - array (numpy.ndarray): The complex-valued array representing the quantum state. Returns: Latex: A Latex object containing LaTeX code for displaying both representations. """ matrix_representation = array_to_matrix_representation(array) latex = "Matrix representation\n\\begin{bmatrix}\n" + \ "\\\\\n".join(map(str, matrix_representation.flatten())) + \ "\n\\end{bmatrix}\n" latex += f'Dirac Notation:\n{array_to_dirac_notation(array)}' return Latex(latex) sv_b1 = np.kron(sv_0, sv_0) array_to_dirac_and_matrix_latex(sv_b1) sv_b1 = (np.kron(sv_0, sv_0) + np.kron(sv_0, sv_1)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b1) sv_b1 = (np.kron(sv_0, sv_0) + np.kron(sv_1, sv_1)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b1) sv_b2 = np.kron(sv_0, sv_0) array_to_dirac_and_matrix_latex(sv_b2) sv_b2 = (np.kron(sv_0, sv_0) + np.kron(sv_0, sv_1)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b2) sv_b2 = (np.kron(sv_0, sv_0) + np.kron(sv_1, sv_1)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b2) sv_b2 = (np.kron(sv_0, sv_0) - np.kron(sv_1, sv_1)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b2) sv_b3 = np.kron(sv_0, sv_0) array_to_dirac_and_matrix_latex(sv_b3) sv_b3 = np.kron(sv_0, sv_1) array_to_dirac_and_matrix_latex(sv_b3) sv_b3 = (np.kron(sv_0, sv_0) - np.kron(sv_0, sv_1)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b3) sv_b3 = (np.kron(sv_0, sv_1) - np.kron(sv_1, sv_0)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b3) sv_b3 = (np.kron(sv_0, sv_1) + np.kron(sv_1, sv_0)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b3) sv_b4 = np.kron(sv_0, sv_0) array_to_dirac_and_matrix_latex(sv_b4) sv_b4 = np.kron(sv_0, sv_1) array_to_dirac_and_matrix_latex(sv_b4) sv_b4 = (np.kron(sv_0, sv_0) - np.kron(sv_0, sv_1)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b4) sv_b4 = (np.kron(sv_0, sv_1) - np.kron(sv_1, sv_0)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b4)
https://github.com/ionq-samples/Ion-Q-Thruster
ionq-samples
import os from qiskit.converters import circuit_to_dag from qiskit import transpile from qiskit_ionq import IonQProvider from custom_transpiler import IonQ_Transpiler from qiskit.circuit.random import random_circuit def compare_circuits(original_circuit, optimized_circuit): original_dag = circuit_to_dag(original_circuit) optimized_dag = circuit_to_dag(optimized_circuit) original_metrics = { 'depth': original_dag.depth(), 'size': original_dag.size(), 'gpi2_count': original_dag.count_ops().get('gpi2', 0), 'gpi_count': original_dag.count_ops().get('gpi', 0), 'ms_count': original_dag.count_ops().get('ms', 0), 'zz_count': original_dag.count_ops().get('zz', 0) } optimized_metrics = { 'depth': optimized_dag.depth(), 'size': optimized_dag.size(), 'gpi2_count': optimized_dag.count_ops().get('gpi2', 0), 'gpi_count': optimized_dag.count_ops().get('gpi', 0), 'ms_count': optimized_dag.count_ops().get('ms', 0), 'zz_count': optimized_dag.count_ops().get('zz', 0) } print(f"The circuit size has reduced from {original_metrics.get('size')} to {optimized_metrics.get('size')}") return original_metrics, optimized_metrics def print_metrics(metrics): print(f"- Depth: {metrics['depth']}") print(f"- Size: {metrics['size']}") print(f"- GPI2 Count: {metrics['gpi2_count']}") print(f"- GPI Count: {metrics['gpi_count']}") print(f"- MS Count: {metrics['ms_count']}") print(f"- ZZ Count: {metrics['zz_count']}") def run_test_case(qc, backend): original_circuit = transpile(qc, backend=backend, optimization_level=3) print("IBM transpiled circuit:") #print(original_circuit.draw()) custom_transpiler = IonQ_Transpiler(backend) optimized_circuit = custom_transpiler.transpile(qc) print("\nCustom transpiled circuit:") #print(optimized_circuit.draw()) original_metrics, optimized_metrics = compare_circuits(original_circuit, optimized_circuit) print("\nIBM transpiled circuit metrics:") print_metrics(original_metrics) print("\nCustom transpiled circuit metrics:") print_metrics(optimized_metrics) return original_circuit, optimized_circuit # Initialize the IonQ provider and backend #api_key = os.getenv("IONQ_API_KEY") or input("Enter your IonQ API key: ") #provider = IonQProvider(token=api_key) #backend = provider.get_backend("simulator", gateset="native") # Generate random circuits #num_qubits = 5 #depth = 10 #num_circuits = 5 #random_circuits = [random_circuit(num_qubits, depth, measure=True) for _ in range(num_circuits)] # Run test cases #for i, qc in enumerate(random_circuits): # print(f"\nTest Case {i+1}:") # run_test_case(qc, backend)
https://github.com/alejomonbar/Bin-Packing-Problem
alejomonbar
import numpy as np import matplotlib.pyplot as plt from docplex.mp.model import Model from qiskit import BasicAer from qiskit.algorithms import QAOA, NumPyMinimumEigensolver from qiskit_optimization.algorithms import CplexOptimizer, MinimumEigenOptimizer from qiskit_optimization.algorithms.admm_optimizer import ADMMParameters, ADMMOptimizer from qiskit_optimization import QuadraticProgram from qiskit_optimization.converters import InequalityToEquality, IntegerToBinary, LinearEqualityToPenalty def data_bins(results, wj, n, m, l=0, simplify=False): """save the results on a dictionary with the three items, bins, items, and index. results (cplex.solve): results of the optimization wj: (array (1,m): weights of the items n: (int) number of items m: (int) number of bins """ if simplify: bins = np.ones((m,)) if m-l > 0: bins[m-l-1:m] = results[:m-l] items = np.zeros((m,n)) items[:,1:] = results[m-l:(m-1)*n+m-l].reshape(m,n-1) items[0,0] = 1 items = items.reshape(m,n) * wj return {"bins":bins, "items":items,"index":np.arange(m)} else: return {"bins":results[:m], "items":results[m:m+m*n].reshape(m,n) * wj, "index":np.arange(m)} def plot_bins(results, wj, n, m, l=0,simplify=False): """plot in a bar diagram the results of an optimization bin packing problem""" res = data_bins(results.x, wj, n, m, l, simplify) plt.figure() ind = res["index"] plt.bar(ind, res["items"][:,0], label=f"item {0}") suma = bottom=res["items"][:,0] for j in range(1,n): plt.bar(ind, res["items"][:,j], bottom=suma, label=f"item {j}") suma += res["items"][:,j] plt.hlines(Q,0-0.5,m-0.5,linestyle="--", color="r",label="Max W") plt.xticks(ind) plt.xlabel("Bin") plt.ylabel("Weight") plt.legend() np.random.seed(2) n = 3 # number of bins m = n # number of items Q = 40 # max weight of a bin wj = np.random.randint(1,Q,n) # Randomly picking the item weight # Construct model using docplex mdl = Model("BinPacking") x = mdl.binary_var_list([f"x{i}" for i in range(n)]) # list of variables that represent the bins e = mdl.binary_var_list([f"e{i//m},{i%m}" for i in range(n*m)]) # variables that represent the items on the specific bin objective = mdl.sum([x[i] for i in range(n)]) mdl.minimize(objective) for j in range(m): # First set of constraints: the items must be in any bin constraint0 = mdl.sum([e[i*m+j] for i in range(n)]) mdl.add_constraint(constraint0 == 1, f"cons0,{j}") for i in range(n): # Second set of constraints: weight constraints constraint1 = mdl.sum([wj[j] * e[i*m+j] for j in range(m)]) mdl.add_constraint(constraint1 <= Q * x[i], f"cons1,{i}") # Load quadratic program from docplex model qp = QuadraticProgram() qp.from_docplex(mdl) print(qp.export_as_lp_string()) # convert from DOcplex model to Qiskit Quadratic program qp = QuadraticProgram() qp.from_docplex(mdl) # Solving Quadratic Program using CPLEX cplex = CplexOptimizer() result = cplex.solve(qp) print(result) plot_bins(result, wj, n, m) # Construct model using docplex mdl = Model("BinPacking_simplify") l = int(np.ceil(np.sum(wj)/Q)) x = mdl.binary_var_list([f"x{i}" for i in range(m)]) # list of variables that represent the bins e = mdl.binary_var_list([f"e{i//m},{i%m}" for i in range(n*m)]) # variables that represent the items on the specific bin objective = mdl.sum([x[i] for i in range(n)]) mdl.minimize(objective) for j in range(m): # First set of constraints: the items must be in any bin constraint0 = mdl.sum([e[i*m+j] for i in range(n)]) mdl.add_constraint(constraint0 == 1, f"cons0,{j}") for i in range(n): # Second set of constraints: weight constraints constraint1 = mdl.sum([wj[j] * e[i*m+j] for j in range(m)]) mdl.add_constraint(constraint1 <= Q * x[i], f"cons1,{i}") # Load quadratic program from docplex model qp = QuadraticProgram() qp.from_docplex(mdl) # Simplifying the problem for i in range(l): qp = qp.substitute_variables({f"x{i}":1}) qp = qp.substitute_variables({"e0,0":1}) for i in range(1,m): qp = qp.substitute_variables({f"e{i},0":0}) print(qp.export_as_lp_string()) simplify_result = cplex.solve(qp) print(simplify_result) plot_bins(simplify_result, wj, n, m, l, simplify=True) ineq2eq = InequalityToEquality() qp_eq = ineq2eq.convert(qp) print(qp_eq.export_as_lp_string()) print(f"The number of variables is {qp_eq.get_num_vars()}") int2bin = IntegerToBinary() qp_eq_bin = int2bin.convert(qp_eq) print(qp_eq_bin.export_as_lp_string()) print(f"The number of variables is {qp_eq_bin.get_num_vars()}") lineq2penalty = LinearEqualityToPenalty() qubo = lineq2penalty.convert(qp_eq_bin) print(f"The number of variables is {qp_eq_bin.get_num_vars()}") print(qubo.export_as_lp_string()) result = cplex.solve(qubo) print(result) data_bins(result.x, wj, n, m, l=l, simplify=True) plot_bins(result, wj, n, m, l=l, simplify=True) from qiskit import Aer backend = Aer.get_backend("qasm_simulator") qaoa = MinimumEigenOptimizer(QAOA(reps=3, quantum_instance=backend)) result_qaoa = qaoa.solve(qubo) print(result_qaoa) plot_bins(result, wj, n, m, l, simplify=True) plt.title("QAOA solution", fontsize=18) # Proposal plt.figure() alpha = -2 x = np.linspace(-5,5,100) f = (-(x+alpha) + (x+alpha)**2) plt.plot(x,f) plt.grid() plt.xlabel("x") plt.ylabel("f(x)") # Construct model using docplex mdl = Model("binPackingMyApproach") x = mdl.binary_var_list([f"x{i}" for i in range(n)]) # list of variables that represent the bins e = mdl.binary_var_list([f"e{i//m},{i%n}" for i in range(n*m)]) # variables that represent the items on the specific bin objective = mdl.sum([x[i] for i in range(m)]) cons = 0 alpha = -10 for i in range(m): cons_1 = 0 cons_1 += Q*x[i] for j in range(n): cons_1 -= wj[j]*e[i*m+j] cons += (-(cons_1+alpha) + (cons_1+alpha)**2) mdl.minimize(objective + cons) for j in range(m): # First set of constraints: the items must be in any bin constraint0 = mdl.sum([e[i*m+j] for i in range(n)]) mdl.add_constraint(constraint0 == 1, f"cons0,{j}") # # Load quadratic program from docplex model qp = QuadraticProgram() qp.from_docplex(mdl) # Simplifying the problem for i in range(l): qp = qp.substitute_variables({f"x{i}":1}) qp = qp.substitute_variables({"e0,0":1}) for i in range(1,m): qp = qp.substitute_variables({f"e{i},0":0}) print(qp.export_as_lp_string()) print(f"The number of variables is {qp.get_num_vars()}") # Solving Quadratic Program using CPLEX cplex = CplexOptimizer() result = cplex.solve(qp) print(result) plot_bins(result, wj, n, m, l, simplify=True) qubo_myapp = lineq2penalty.convert(qp) result_myapp = qaoa.solve(qubo_myapp) print(result_myapp) plot_bins(result_myapp, wj, n, m, l, simplify=True) plt.title("QAOA solution") import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/shell-raiser/Qiskit-Developer-Certification-Notes-and-Code
shell-raiser
# Bundle ckts into single job qc_list = [qc1, qc2] job = execute(qc_list, backend) job.result().get_counts() # Counts come here, as list of counts objects job.result().get_counts(qc1) # gives only one ckt results # to transpile, assemble and run qckts seperatl tqc_list = transpile(qc_list, vigo) # returns a list of transpiled quantm ckts qobj = assemble(tqc_list, vigo) vigo.run(qobj) job.result().get_counts() # Visualise qckts using latex qc.draw('latex') #needs pylatexenc, pillow print(qc.draw('latex_source')) # for latex code # Convert Quantum ckt to and from QASM print(qc.qasm()) # returns the qasm string # or qc.qasm(formatted = True) # or qc.qasm(formatted = True, filename='') # to create from qasm new_qc = QuantumCircuit.from_qasm_file('my_circuit.qasm') # Monitoring a job job = execute(qc,backend) # to see the status job.status() #avoid this, can be rejected by server # or job.wait_for_final_state() # using qiskit job monitor from qiskit.tools import job_monitor job_monitor(job) # or use qiskit job watcher magic import qiskit.tools.jupyter %qiskit_job_watcher # implement a multi-control toffoli gate qc.ccx(0,1,2) #or qc.mct([0,1,2,3],4) # MCT- multicontrol toffoli, ([Control], target) # use a specific version of qiskit qiskit.__qiskit_version__ # Difference bt gate and instruction # qiskit's gate object represents a unitary qGate, whereas instruction objs have non unitary parts gate = qc.to_gate() # convert ckt to gate new_qc.append(gate.power(5),[0,1]) #or instructoin = qc.to_intruction() instructoin.reverse_ops() new_qc.append # adding non unitary parts to qckt qc = QuantumCircuit(2) qc.initialize([0,1],0) # it is an initialize gate qc.h(0) qc.cx(0,1) qc.measure_all() qc.h(0).c_if(qc.clbits[0].register,1) # put h, conditioned on a classical register qc.draw() instructoin = qc.to_instruction() # can't do gate = qc.to_gate(), because it is non-unitary # but we can still append it to another ckt new_qc.append(instructoin,[0,1],[0,1]) new_qx.decompose().draw() # to see original instruction # control unitary part of ckt # measuring or ressetting a ckt is non-unitary controlled_qc = qc.control() # create control ckt, thus adding more qubits automatically to access it # or, to add more control qubits controlled_qc = qc.control(2) new_qc = new_qc.compose(controlled_qc, range(4)) new_qc.decompose().draw() # Combine 2 qckts new_qc = qc1 + qc2 new_qc.draw() # but to add ckts with different no. of qubits, we need to have qc1 and qc2 with same register name, or else we can do below # use compose method new_qc = qc1.compose(qc2, [1,2]) # Parametrised ckts in qiskit a = Parameter("a") qc.cul(a,0,1) b = Parameter("b") qc.assign_parameters({a:b}, inplace=True) # to replace a with b in the ckt transpiled_qc = transpile(qc, basis_gates-['cx','u3'], optimization_level=3) specific_transpiled_qc = transpiled_qc.assign_parameters({b:2}) # convert a unitary matrix to a set of one & two qubit gates, so that we can run code on older qcomputers U = [[...], [...], [...], [...]] qc.unitary(U,[0,1]) trans_qc = transpile(qc, basis_gates=['cx','u3']) # cx and u3 are universal gates, so we can convert any ckt to these gates # What is the unitary simulator # What is a qsphere plot_state_qsphere(sv.data) #use mock backends in qiskit from qiskit.test.mock import FakeVigo fake_vigo = FakeVigo() # this backend can be used without an account or que results = execute(qc, fake_vigo).result() counts = results.get_counts() plot......... # view device properties and config in qiskit from qiskit.tools.jupyter import * vigo = provider.get_backend('ibmq_vigo') vigo # displays widget vigo.configuration() # or vigo.configuration().coupling_map # etc vigo.properties() # or ().t1(3) vigo.defaults() # simulate sv in qiskit # sv describes the state of the computer by a vector with 2^n elements, n=no. of qubits from qiskit.quantum_info import Statevector sv = Statevector.from_label('000') #all 3 qubits initialized to 0 sv # gives output, statevector objects sv = sv.evolve(qc) # Evolve the object through the circuits, returns the simulated state of the qubits, after we run the ckt sv.data # to get the state vector array # Retrieve old job from IBM quantum backend.jobs() # returns 10 most recent jobs # or we can do backend.jobs(limit=2) # for 2 jobs job = backend.jobs(limit=2)[0] # to store the results of the first job counts = job.result().get_counts() # another way to retrieve the job, using the job id job = backend.retrieve_job('JOB_ID_HERE') job.properties().qubits(0) # invert unitary part of ckt my_gate = qc.to_gate() my_inverse_gate = my_gate.inverse() my_inverse_gate.name = 'inverted gate' qc2 = QuantumCircuit(3) qc2.append(my_inverse_gate, [0,1,2]) inverse_qc = qc.inverse() # doesnt work when we have non-unitary part # Not in the Series, Use dark mode for matplotlib plots import matplotlib.pyplot as plt plt.style.use('dark_background') plot_histogram(job.result().get_counts()) # Save Circuit Drawings to Different File Types qc.draw().savefig('fileName.png', dpi=700) # for saving matplotlib image as a png file, dpi is optional qc.draw().savefig('fileName.svg') # for saving as svg qc.draw('latex').save('fileName.png', dpi=700) # to save latex as image # to save as text with open('fileName.txt','w') as f: f.write(str(qc.draw('text'))) # Construct a Quantum Volume Circuit # import the quantum volume constructor from the qiskit library from qiskit.circuit.library import QuantumVolume qv = QuantumVolume(4).decompose() # learn more about the Quantum Volume here # https://learn.qiskit.org/course/quantum-hardware/measuring-quantum-volume