repo
stringclasses
885 values
file
stringclasses
741 values
content
stringlengths
4
215k
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile from qiskit_aer import AerSimulator from qiskit.tools.visualization import plot_histogram import random circ = QuantumCircuit(40, 40) # Initialize with a Hadamard layer circ.h(range(40)) # Apply some random CNOT and T gates qubit_indices = [i for i in range(40)] for i in range(10): control, target, t = random.sample(qubit_indices, 3) circ.cx(control, target) circ.t(t) circ.measure(range(40), range(40)) # Create statevector method simulator statevector_simulator = AerSimulator(method='statevector') # Transpile circuit for backend tcirc = transpile(circ, statevector_simulator) # Try and run circuit statevector_result = statevector_simulator.run(tcirc, shots=1).result() print('This succeeded?: {}'.format(statevector_result.success)) print('Why not? {}'.format(statevector_result.status)) # Create extended stabilizer method simulator extended_stabilizer_simulator = AerSimulator(method='extended_stabilizer') # Transpile circuit for backend tcirc = transpile(circ, extended_stabilizer_simulator) extended_stabilizer_result = extended_stabilizer_simulator.run(tcirc, shots=1).result() print('This succeeded?: {}'.format(extended_stabilizer_result.success)) small_circ = QuantumCircuit(2, 2) small_circ.h(0) small_circ.cx(0, 1) small_circ.t(0) small_circ.measure([0, 1], [0, 1]) # This circuit should give 00 or 11 with equal probability... expected_results ={'00': 50, '11': 50} tsmall_circ = transpile(small_circ, extended_stabilizer_simulator) result = extended_stabilizer_simulator.run( tsmall_circ, shots=100).result() counts = result.get_counts(0) print('100 shots in {}s'.format(result.time_taken)) plot_histogram([expected_results, counts], legend=['Expected', 'Extended Stabilizer']) # Add runtime options for extended stabilizer simulator opts = {'extended_stabilizer_approximation_error': 0.03} reduced_error = extended_stabilizer_simulator.run( tsmall_circ, shots=100, **opts).result() reduced_error_counts = reduced_error.get_counts(0) print('100 shots in {}s'.format(reduced_error.time_taken)) plot_histogram([expected_results, reduced_error_counts], legend=['Expected', 'Extended Stabilizer']) print("The circuit above, with 100 shots at precision 0.03 " "and default mixing time, needed {}s".format(int(reduced_error.time_taken))) opts = { 'extended_stabilizer_approximation_error': 0.03, 'extended_stabilizer_mixing_time': 100 } optimized = extended_stabilizer_simulator.run( tsmall_circ, shots=100, **opts).result() print('Dialing down the mixing time, we completed in just {}s'.format(optimized.time_taken)) # We set these options here only to make the example run more quickly. opts = {'extended_stabilizer_mixing_time': 100} multishot = extended_stabilizer_simulator.run( tcirc, shots=100, **opts).result() print("100 shots took {} s".format(multishot.time_taken)) opts = { 'extended_stabilizer_measure_sampling': True, 'extended_stabilizer_mixing_time': 100 } measure_sampling = extended_stabilizer_simulator.run( circ, shots=100, **opts).result() print("With the optimization, 100 shots took {} s".format(result.time_taken)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/jonasmaziero/computacao_quantica_qiskit
jonasmaziero
#!pip install pylatexenc # para desenhar os circuitos quânticos from qiskit import QuantumCircuit qc = QuantumCircuit(1,1) qc.barrier() qc.measure(0,0) qc.draw('mpl') # Para medidas de Z qc = QuantumCircuit(1,1) qc.barrier() qc.h(0) qc.measure(0,0) qc.draw('mpl') # Para medidas de X qc = QuantumCircuit(1,1) qc.barrier() qc.sdg(0) qc.h(0) qc.measure(0,0) qc.draw('mpl') # Para medidas de Y # Calculo da inversa da matrix de Hadamard from sympy import Matrix H2 = Matrix([[1,1],[1,-1]]); H2 H2.inv() def tomo_1qb(avgs): import numpy as np s0 = np.array([[1,0],[0,1]]); s1 = np.array([[0,1],[1,0]]) s2 = np.array([[0,-1j],[1j,0]]); s3 = np.array([[1,0],[0,-1]]) return 0.5*(s0 + avgs[1]*s1 + avgs[2]*s2 + avgs[3]*s3) import numpy as np avgs = np.array([1,0.1,-0.2,0.5]); rho1qb = tomo_1qb(avgs); rho1qb def qc_test_1qb(): from qiskit import QuantumCircuit qc = QuantumCircuit(1, name='qc') qc.h(0) return qc from qiskit import QuantumCircuit, execute from qiskit import Aer simulator = Aer.get_backend('qasm_simulator') nshots = 2**13 qct = qc_test_1qb() # circuito quantico principal # medida de X qc = QuantumCircuit(1,1) qc.append(qct,[0]) qc.h(0); qc.measure(0,0) qcx = qc job = execute(qc, backend = simulator, shots = nshots) counts_x = job.result().get_counts() print('counts_x=',counts_x) if '0' in counts_x: Xavg = counts_x['0'] if '1' in counts_x: Xavg -= counts_x['1'] Xavg = Xavg/nshots print(Xavg) # medida de Y qc = QuantumCircuit(1,1) qc.append(qct,[0]) qc.sdg(0); qc.h(0); qc.measure(0,0) qcy = qc job = execute(qc, backend = simulator, shots = nshots) counts_y = job.result().get_counts() print('counts_y=',counts_y) if '0' in counts_y: Yavg = counts_y['0'] if '1' in counts_y: Yavg -= counts_y['1'] Yavg = Yavg/nshots print(Yavg) # medida de Z qc = QuantumCircuit(1,1) qc.append(qct,[0]) qc.measure(0,0) qcz = qc job = execute(qc, backend = simulator, shots = nshots) counts_z = job.result().get_counts() print('counts_z=',counts_z) if '0' in counts_z: Zavg = counts_z['0'] if '1' in counts_y: Zavg -= counts_z['1'] Zavg = Zavg/nshots print(Zavg) #qcx.draw('mpl') #ok qcy.draw('mpl') #qcz.draw('mpl') avgs = [1, Xavg, Yavg, Zavg] rho1qb = tomo_1qb(avgs) rho1qb from numpy import linalg as LA evals, evecs = LA.eig(rho1qb) evals evecs from sympy.physics.quantum import TensorProduct as tp H4 = tp(H2,H2); H4 H4i = H4.inv(); H4i def tomo_2qb(avgs): # avgs e uma lista com 16 valores medios na seguinte ordem [II,IX,IY,IZ,XI,XX,XY,XZ,YI,YX,YY,YZ,ZI,ZX,ZY,ZZ] import numpy as np s0 = np.array([[1,0],[0,1]]); s1 = np.array([[0,1],[1,0]]) s2 = np.array([[0,-1j],[1j,0]]); s3 = np.array([[1,0],[0,-1]]) paulis = [s0,s1,s2,s3] # lista com as matrizes de Pauli rho = np.zeros([4,4],dtype=complex) l = 0 for j in range(0,3): for k in range(0,3): l += 1 rho += avgs[l]*tp(paulis[j],paulis[k]) return 0.25*rho avgs = [1,0.1,0,0,0.1,0.3,0,0,0.3,0,0.2,0,0,0.1,0,0.5] #[II,IX,IY,IZ,XI,XX,XY,XZ,YI,YX,YY,YZ,ZI,ZX,ZY,ZZ] rho = tomo_2qb(avgs); rho # Inversa da matriz de Hadamard 4x4 (sem o multiplo 1/4) H4i = np.array([[1,1,1,1],[1,-1,1,-1],[1,1,-1,-1],[1,-1,-1,1]]); H4i def qc_test_2qb(): from qiskit import QuantumCircuit qc = QuantumCircuit(2, name='qc2qb') qc.h(0); qc.cx(0,1) return qc def tomo_2qb(avgs): # avgs e uma lista com 64 valores medios na seguinte ordem [III,IIX,IIY,IIZ,IXI,IXX,IXY,IXZ,...] import numpy as np s0 = np.array([[1,0],[0,1]]); s1 = np.array([[0,1],[1,0]]) s2 = np.array([[0,-1j],[1j,0]]); s3 = np.array([[1,0],[0,-1]]) paulis = [s0,s1,s2,s3] rho = np.zeros([4,4],dtype=complex) m = 0 for j in range(0,4): for k in range(0,4): for l in range(0,4): rho += avgs[m]*np.kron(np.kron(paulis[j],paulis[k]),paulis[l]) m += 1 return 0.25*rho from qiskit import QuantumCircuit, execute from qiskit import Aer simulator = Aer.get_backend('qasm_simulator') nshots = 2**13 qct = qc_test_2qb() # circuito quantico principal # medida de XX qc = QuantumCircuit(2,2); qc.append(qct,[0,1]); qc.h([0,1]); qc.measure([0,1],[0,1]); qcxx = qc job = execute(qc, backend = simulator, shots = nshots); counts_xx = job.result().get_counts() pr_xx = np.zeros(4); cb2_labels = ['00','10','01','11'] for j in range(0,4): if cb2_labels[j] in counts_xx: pr_xx[j] = counts_xx[cb2_labels[j]]/nshots print('counts_xx=',counts_xx, pr_xx) XX_vec = np.matmul(H4i,pr_xx); print('XX_vec=',XX_vec) # =[II,IX,XI,XX] qcxx.draw('mpl') ss_vecs = [] # list with the averages of the observables obs = ['x','y','z'] for j in range(0,3): lo = obs[j] # left observable for k in range(0,3): ro = obs[k] # right observable qc = QuantumCircuit(2,2) qc.append(qct,[0,1]) # the quantum circuit for preparing psi if lo == 'x' and ro = 'x': qc.h([0,1]) elif lo == 'x' and ro = 'y': qc.sdg(1); qc.h([0,1]) elif lo == 'y' and ro = 'x': qc.sdg(0); qc.h([0,1]) elif lo == 'y' and ro = 'y': qc.sdg([0,1]); qc.h([0,1]) qc.measure([0,1],[0,1]) job = execute(qc, backend = simulator, shots = nshots) counts = job.result().get_counts() pr = np.zeros(4); cb2_labels = ['00','10','01','11'] for j in range(0,4): if cb2_labels[j] in counts_xx: pr_xx[j] = counts_xx[cb2_labels[j]]/nshots ss_vec = np.matmul(H4i,pr) ss_vecs.append(ss_vec) # matriz de Hadamard H8 = tp(H2,H4); H8 H8i = H8.inv(); H8i from sympy import symbols f000,f001,f010,f011,f100,f101,f110,f111 = symbols('f_{000},f_{001},f_{010},f_{011},f_{100},f_{101},f_{110},f_{111}') f = Matrix([[f000],[f001],[f010],[f011],[f100],[f101],[f110],[f111]]) f.T al = 8*H8i*f; al import numpy as np s0 = np.array([[1,0],[0,1]]); s1 = np.array([[0,1],[1,0]]); s2 = np.array([[0,-1j],[1j,0]]); s3 = np.array([[1,0],[0,-1]]) paulis = [s0,s1,s2,s3] # lista com as matrizes de Pauli list_avgs = [] m = 0 for j in range(0,4): for k in range(0,4): for l in range(0,4): list_avgs.append((j,k,l)) m += 1
https://github.com/abbarreto/qiskit4
abbarreto
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.second_q.drivers import PySCFDriver driver = PySCFDriver() problem = driver.run() print(problem) from qiskit_nature.second_q.problems import ElectronicBasis driver.run_pyscf() problem = driver.to_problem(basis=ElectronicBasis.MO, include_dipole=True) print(problem.basis) ao_problem = driver.to_problem(basis=ElectronicBasis.AO) print(ao_problem.basis) from qiskit_nature.second_q.formats.qcschema_translator import qcschema_to_problem qcschema = driver.to_qcschema() ao_problem = qcschema_to_problem(qcschema, basis=ElectronicBasis.AO) from qiskit_nature.second_q.formats.qcschema_translator import get_ao_to_mo_from_qcschema basis_transformer = get_ao_to_mo_from_qcschema(qcschema) mo_problem = basis_transformer.transform(ao_problem) print(mo_problem.basis) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/abbarreto/qiskit3
abbarreto
pip install qiskit pip install qiskit-ignis import qiskit qiskit.IBMQ.save_account('17efde49764005e8eeb00dd065d44bc208778be72d44b475e508d20504818786f842988b0e506515c78debdd1b0c4b570717863db5e4f85569fb43c4c8626b8a', overwrite = True) qiskit.IBMQ.load_account() import numpy as np import math from qiskit import * nshots = 8192 IBMQ.load_account() #provider= qiskit.IBMQ.get_provider(hub='ibm-q-research-2',group='federal-uni-sant-1',project='main') provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') device = provider.get_backend('ibmq_quito') simulator = Aer.get_backend('qasm_simulator') from qiskit.tools.monitor import job_monitor from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter def coh_l1(rho): d = rho.shape[0]; C = 0 for j in range(0,d-1): for k in range(j+1,d): C += np.abs(rho[j,k]) return 2*C def predict_jb(rho): return abs(rho[0,0]-rho[1,1]) r00 = 2/3; r01 = 1.33/3; r10 = 1.33/3; r11 = 1/3 # initial state r = math.sqrt((r00-r11)**2 + abs(2*r01)**2) # raio de Bloch th = math.acos((r00-r11)/r) ph = math.acos(2*r01.real/(r*math.sin(th))) # angulos de Bloch r0 = (1+r)/2.; r1 = (1-r)/2. # autovetores print(r, th, ph, r0, r1) # simulation p = np.arange(0,1.1,0.1) d = len(p) Csim = np.zeros(d); Psim = np.zeros(d) for j in range(0,d): pI = (4-3*p[j])/4; pX = p[j]/4; pZ = p[j]/4; pY = p[j]/4 # depolarizing # sequencia: 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111 # = 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Phi_ABCD = [math.sqrt(r0*pI)*math.cos(th/2), math.sqrt(r0*pX)*(math.cos(ph)+1j*math.sin(ph))*math.sin(th/2), math.sqrt(r0*pZ)*math.cos(th/2), -1j*math.sqrt(r0*pY)*(math.cos(ph)+1j*math.sin(ph))*math.sin(th/2), math.sqrt(r1*pI)*math.sin(th/2), -math.sqrt(r1*pX)*(math.cos(ph)+1j*math.sin(ph))*math.cos(th/2), math.sqrt(r1*pZ)*math.sin(th/2), 1j*math.sqrt(r1*pY)*(math.cos(ph)+1j*math.sin(ph))*math.cos(th/2), math.sqrt(r0*pI)*(math.cos(ph)+1j*math.sin(ph))*math.sin(th/2), math.sqrt(r0*pX)*math.cos(th/2), -math.sqrt(r0*pZ)*(math.cos(ph)+1j*math.sin(ph))*math.sin(th/2), 1j*math.sqrt(r0*pY)*math.cos(th/2), -math.sqrt(r1*pI)*(math.cos(ph)+1j*math.sin(ph))*math.cos(th/2), math.sqrt(r1*pX)*math.sin(th/2), math.sqrt(r1*pZ)*(math.cos(ph)+1j*math.sin(ph))*math.cos(th/2), 1j*math.sqrt(r1*pY)*math.sin(th/2)] qr = QuantumRegister(4) qc = QuantumCircuit(qr) qc.initialize(Phi_ABCD, [qr[0],qr[3],qr[2],qr[1]]) qstc = state_tomography_circuits(qc, [qr[1]]) job = qiskit.execute(qstc, backend = simulator, shots=nshots) qstf = StateTomographyFitter(job.result(), qstc) rho_sim = qstf.fit(method='lstsq') Csim[j] = coh_l1(rho_sim) Psim[j] = predict_jb(rho_sim) # theoretical pt = np.arange(0,1.01,0.01) Ct = (1-pt)*(2*1.33/3) Pt = (1-pt)*(1/3) # experiment p = np.arange(0,1.1,0.1); d = len(p) Cexp = np.zeros(d); Pexp = np.zeros(d) jobs_ids = [] for j in range(0,d): pI = (4-3*p[j])/4; pX = p[j]/4; pZ = p[j]/4; pY = p[j]/4 Phi_ABCD = [math.sqrt(r0*pI)*math.cos(th/2), math.sqrt(r0*pX)*(math.cos(ph)+1j*math.sin(ph))*math.sin(th/2), math.sqrt(r0*pZ)*math.cos(th/2), -1j*math.sqrt(r0*pY)*(math.cos(ph)+1j*math.sin(ph))*math.sin(th/2), math.sqrt(r1*pI)*math.sin(th/2), -math.sqrt(r1*pX)*(math.cos(ph)+1j*math.sin(ph))*math.cos(th/2), math.sqrt(r1*pZ)*math.sin(th/2), 1j*math.sqrt(r1*pY)*(math.cos(ph)+1j*math.sin(ph))*math.cos(th/2), math.sqrt(r0*pI)*(math.cos(ph)+1j*math.sin(ph))*math.sin(th/2), math.sqrt(r0*pX)*math.cos(th/2), -math.sqrt(r0*pZ)*(math.cos(ph)+1j*math.sin(ph))*math.sin(th/2), 1j*math.sqrt(r0*pY)*math.cos(th/2), -math.sqrt(r1*pI)*(math.cos(ph)+1j*math.sin(ph))*math.cos(th/2), math.sqrt(r1*pX)*math.sin(th/2), math.sqrt(r1*pZ)*(math.cos(ph)+1j*math.sin(ph))*math.cos(th/2), 1j*math.sqrt(r1*pY)*math.sin(th/2)] qr = QuantumRegister(4); qc = QuantumCircuit(qr) qc.initialize(Phi_ABCD, [qr[0],qr[3],qr[2],qr[1]]) qstc = state_tomography_circuits(qc, [qr[1]]) job = qiskit.execute(qstc, backend = device, shots=nshots) jobs_ids.append(job.job_id()) print(job.job_id()) job_monitor(job) qstf = StateTomographyFitter(job.result(), qstc) rho_exp = qstf.fit(method='lstsq') Cexp[j] = coh_l1(rho_exp) #Pexp[j] = predict_jb(rho_exp) # sem mitigacao, chip quito, qr[1] import matplotlib from matplotlib import pyplot as plt matplotlib.rcParams.update({'font.size':12}) plt.figure(figsize = (6,4), dpi = 100) plt.plot(pt,Ct,label=r'$C_{l_1}^{the}$') #plt.plot(pt,Pt,label=r'$P_{jb}^{the}$') plt.plot(p,Csim,'*',label=r'$C_{l_1}^{sim}$') #plt.plot(p,Psim,'o',label=r'$P_{jb}^{sim}$') plt.plot(p,Cexp,'^',label=r'$C_{l_1}^{exp}$') #plt.plot(p,Pexp,'+',label=r'$P_{jb}^{exp}$') plt.xlabel(r'$p$') plt.legend() plt.show() # sem mitigacao, chip belem # sem mitigacao, chip manila # sem mitigacao, chip quito, qr[0] f = open("jobs_ids_CS_rho.txt", "w") f.write(str(jobs_ids)) f.close() f = open("jobs_ids_CS_rho.txt","r") list_ids = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(",") f.close() print(list_ids) # error mitigation qr = QuantumRegister(4); qubit_list = [1] meas_calibs, state_labels = complete_meas_cal(qubit_list = qubit_list, qr = qr) job = qiskit.execute(meas_calibs, backend = device, shots = nshots) print(job.job_id()) job_monitor(job) job = device.retrieve_job('63a124fa05888e2fcb99ab6e') meas_fitter = CompleteMeasFitter(job.result(), state_labels) p = np.arange(0,1.1,0.1); d = len(p) Cexp = np.zeros(d); Pexp = np.zeros(d) for j in range(0,d): job = device.retrieve_job(list_ids[j]) mitigated_results = meas_fitter.filter.apply(job.result()) qstf_exp = StateTomographyFitter(mitigated_results, qstc) rho_exp = qstf_exp.fit(method='lstsq') Cexp[j] = coh_l1(rho_exp) Pexp[j] = predict_jb(rho_exp) # com mitigacao, chip quito, qr[1] import matplotlib from matplotlib import pyplot as plt matplotlib.rcParams.update({'font.size':12}) plt.figure(figsize = (6,4), dpi = 100) plt.plot(pt,Ct,label=r'$C_{l_1}^{the}$')#,color='green') plt.plot(p,Csim,'o',label=r'$C_{l_1}^{sim}$')#,color='blue') plt.plot(p,Cexp,'*',label=r'$C_{l_1}^{exp}$')#,color='orange') #plt.plot(pt,Pt,label=r'$P_{jb}^{the}$') #plt.plot(p,Psim,'o',label=r'$P_{jb}^{sim}$') #plt.plot(p,Pexp,'+',label=r'$P_{jb}^{exp}$') plt.xlabel(r'$p$') plt.legend() plt.savefig('fig_QCS_mixed.pdf') plt.show() # com mitigacao, chip belem # com mitigacao, chip manila # com mitigacao, chip quito, qr[0] # com mitigacao, chip quito # sem mitigacao, chip quito
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
mmetcalf14
"""Qiskit code for running Simon's algorithm on quantum hardware for 2 qubits and b = '11' """ # importing Qiskit from qiskit import IBMQ, BasicAer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, execute # import basic plot tools from qiskit.visualization import plot_histogram from qiskit_textbook.tools import simon_oracle #set b equal to '11' b = '11' #1) initialize qubits n = 2 simon_circuit_2 = QuantumCircuit(n*2, n) #2) Apply Hadamard gates before querying the oracle simon_circuit_2.h(range(n)) #3) Query oracle simon_circuit_2 += simon_oracle(b) #5) Apply Hadamard gates to the input register simon_circuit_2.h(range(n)) #3) and 6) Measure qubits simon_circuit_2.measure(range(n), range(n)) # Load saved IBMQ accounts and get the least busy backend device IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= n and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) # Execute and monitor the job from qiskit.tools.monitor import job_monitor shots = 1024 job = execute(simon_circuit_2, backend=backend, shots=shots, optimization_level=3) job_monitor(job, interval = 2) # Get results and plot counts device_counts = job.result().get_counts() plot_histogram(device_counts) #additionally, function for calculating dot product of results def bdotz(b, z): accum = 0 for i in range(len(b)): accum += int(b[i]) * int(z[i]) return (accum % 2) print('b = ' + b) for z in device_counts: print( '{}.{} = {} (mod 2) ({:.1f}%)'.format(b, z, bdotz(b,z), device_counts[z]*100/shots)) #the most significant results are those for which b dot z=0(mod 2). '''b = 11 11.00 = 0 (mod 2) (45.0%) 11.01 = 1 (mod 2) (6.2%) 11.10 = 1 (mod 2) (6.4%) 11.11 = 0 (mod 2) (42.4%)'''
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# You can choose different colors for the real and imaginary parts of the density matrix. from qiskit import QuantumCircuit from qiskit.quantum_info import DensityMatrix from qiskit.visualization import plot_state_city qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) state = DensityMatrix(qc) plot_state_city(state, color=['midnightblue', 'crimson'], title="New State City")
https://github.com/Naphann/Solving-TSP-Grover
Naphann
import qiskit from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import Aer from qiskit.circuit import Qubit import numpy as np from math import floor, ceil def RTL(qc, a, b, c): ## fig 3 dashed qc.rccx(a, b, c) def RTL_inv(qc, a, b, c): RTL(qc, a, b, c) def RTS(qc, a, b, c): ## fig 3 gates 2-6 qc.h(c) qc.t(c) qc.cx(b, c) qc.tdg(c) qc.cx(a, c) def RTS_inv(qc, a, b, c): qc.cx(a, c) qc.t(c) qc.cx(b, c) qc.tdg(c) qc.h(c) def SRTS(qc, a, b, c): ## circuit 3 dashed qc.h(c) qc.cx(c, b) qc.tdg(b) qc.cx(a, b) qc.t(b) qc.cx(c, b) qc.tdg(b) qc.cx(a, b) qc.t(b) def SRTS_inv(qc, a, b, c): qc.tdg(b) qc.cx(a, b) qc.t(b) qc.cx(c, b) qc.tdg(b) qc.cx(a, b) qc.t(b) qc.cx(c, b) qc.h(c) def RT4L(qc, a, b, c, d): ## fig 4 qc.rcccx(a, b, c, d) def RT4L_inv(qc, a, b, c, d): qc.h(d) qc.t(d) qc.cx(c, d) qc.tdg(d) qc.h(d) qc.t(d) qc.cx(b, d) qc.tdg(d) qc.cx(a, d) qc.t(d) qc.cx(b, d) qc.tdg(d) qc.cx(a, d) qc.h(d) qc.t(d) qc.cx(c, d) qc.tdg(d) qc.h(d) def RT4S(qc, a, b, c, d): ## fig 4 dashed qc.h(d) qc.t(d) qc.cx(c, d) qc.tdg(d) qc.h(d) qc.cx(a, d) qc.t(d) qc.cx(b, d) qc.tdg(d) qc.cx(a, d) def RT4S_inv(qc, a, b, c, d): qc.cx(a, d) qc.t(d) qc.cx(b, d) qc.tdg(d) qc.cx(a, d) qc.h(d) qc.t(d) qc.cx(c, d) qc.tdg(d) qc.h(d) def apply_mct_clean(self, controls, target, ancilla_register): if len(controls) < 3: raise ValueError("there's something wrong") n = len(controls) ancilla = ancilla_register[:ceil((n-2)/2)] if n == 3: # TODO: Check for ancilla length self.rccx(controls[0], controls[1], ancilla[0]) self.ccx(controls[2], ancilla[0], target) self.rccx(controls[0], controls[1], ancilla[0]) return if n == 4: # TODO: Check for ancilla length self.rcccx(controls[0], controls[1], controls[2], ancilla[0]) self.ccx(controls[3], ancilla[0], target) self.rcccx(controls[0], controls[1], controls[2], ancilla[0]) return ## when controls >= 5 if n % 2 == 0: self.rcccx(controls[0], controls[1], controls[2], ancilla[0]) self.barrier() anc_idx = 1 for i in range(3, n-1, 2): # print('i = /{}'.format(i)) self.rcccx(controls[i], controls[i+1], ancilla[anc_idx-1], ancilla[anc_idx]) self.barrier() anc_idx += 1 if (n-3)%2 == 1: self.ccx(controls[-1], ancilla[-1], target) self.barrier() else: self.rccx(controls[-2], ancilla[-2], ancilla[-1]) self.barrier() self.ccx(controls[-1], ancilla[-1], target) self.barrier() self.rccx(controls[-2], ancilla[-2], ancilla[-1]) self.barrier() for i in reversed(range(3, n-1, 2)): anc_idx -= 1 self.rcccx(controls[i], controls[i+1], ancilla[anc_idx-1], ancilla[anc_idx]) self.barrier() self.rcccx(controls[0], controls[1], controls[2], ancilla[0]) else: self.rcccx(controls[0], controls[1], controls[2], ancilla[0]) self.barrier() anc_idx = 1 for i in range(3, n-3, 2): # print('i = /{}'.format(i)) self.rcccx(controls[i], controls[i+1], ancilla[anc_idx-1], ancilla[anc_idx]) self.barrier() anc_idx += 1 if (n-3)%2 == 1: self.ccx(controls[-1], ancilla[-1], target) self.barrier() else: self.rccx(controls[-2], ancilla[-2], ancilla[-1]) self.barrier() self.ccx(controls[-1], ancilla[-1], target) self.barrier() self.rccx(controls[-2], ancilla[-2], ancilla[-1]) self.barrier() for i in reversed(range(3, n-3, 2)): anc_idx -= 1 self.rcccx(controls[i], controls[i+1], ancilla[anc_idx-1], ancilla[anc_idx]) self.barrier() self.rcccx(controls[0], controls[1], controls[2], ancilla[0]) def apply_mct_dirty(self, controls, target, ancilla): # TODO: check controls to be list of bits or register if len(controls) == 1: self.cx(controls[0], target) return if len(controls) == 2: self.ccx(controls[0], controls[1], target) return if len(controls) == 3: SRTS(self, controls[2], ancilla[0], target) RTL(self, controls[0], controls[1], ancilla[0]) SRTS_inv(self, controls[2], ancilla[0], target) RTL_inv(self, controls[0], controls[1], ancilla[0]) return n = len(controls) anc = ancilla[:ceil((n-2)/2)] SRTS(self, controls[-1], anc[-1], target) self.barrier() if (n-4)%2 == 0: a_idx = 1 for i in reversed(range(floor((n-4)/2))): RT4S(self, anc[a_idx - 1 + i], controls[2*i+3], controls[2*i+4], anc[a_idx + i]) self.barrier() else: a_idx = 2 for i in reversed(range(floor((n-4)/2))): RT4S(self, anc[a_idx - 1 + i], controls[2*i+4], controls[2*i+5], anc[a_idx + i]) self.barrier() RTS(self, anc[0], controls[3], anc[1]) self.barrier() RT4L(self, controls[0], controls[1], controls[2], anc[0]) self.barrier() if (n-4)%2 == 0: a_idx = 1 for i in (range(floor((n-4)/2))): RT4S_inv(self, anc[a_idx - 1 + i], controls[2*i+3], controls[2*i+4], anc[a_idx + i]) self.barrier() else: a_idx = 2 RTS_inv(self, anc[0], controls[3], anc[1]) self.barrier() for i in (range(floor((n-4)/2))): RT4S_inv(self, anc[a_idx - 1 + i], controls[2*i+4], controls[2*i+5], anc[a_idx + i]) self.barrier() SRTS_inv(self, controls[-1], anc[-1], target) self.barrier() ## SAME AS ABOVE if (n-4)%2 == 0: a_idx = 1 for i in reversed(range(floor((n-4)/2))): RT4S(self, anc[a_idx - 1 + i], controls[2*i+3], controls[2*i+4], anc[a_idx + i]) self.barrier() else: a_idx = 2 for i in reversed(range(floor((n-4)/2))): RT4S(self, anc[a_idx - 1 + i], controls[2*i+4], controls[2*i+5], anc[a_idx + i]) self.barrier() RTS(self, anc[0], controls[3], anc[1]) self.barrier() RT4L_inv(self, controls[0], controls[1], controls[2], anc[0]) self.barrier() if (n-4)%2 == 0: a_idx = 1 for i in (range(floor((n-4)/2))): RT4S_inv(self, anc[a_idx - 1 + i], controls[2*i+3], controls[2*i+4], anc[a_idx + i]) self.barrier() else: a_idx = 2 RTS_inv(self, anc[0], controls[3], anc[1]) self.barrier() for i in (range(floor((n-4)/2))): RT4S_inv(self, anc[a_idx - 1 + i], controls[2*i+4], controls[2*i+5], anc[a_idx + i]) self.barrier() def apply_mct(circuit, controls, target, anc, mode='clean-ancilla'): if len(controls) == 1: circuit.cx(controls[0], target) elif len(controls) == 2: circuit.ccx(controls[0], controls[1], target) else: if mode == 'clean-ancilla': apply_mct_clean(circuit, controls, target, anc) if mode == 'dirty-ancilla': apply_mct_dirty(circuit, controls, target, anc) def _mct(self, controls, target, ancilla, mode): if controls is None or len(controls) < 0: raise ValueError('you should pass controls as list or registers') if target is None or (not isinstance(target, Qubit) and len(target) != 1): raise ValueError('target length is not 1') if ancilla is None or len(ancilla) < ceil((len(controls)-2)/2): raise ValueError('for {} controls, need at least {} ancilla'.format(len(controls), ceil((len(controls)-2)/2))) if mode is None or (mode != 'dirty-ancilla' and mode != 'clean-ancilla'): raise ValueError('unknown mode') apply_mct(self, controls, target, ancilla, mode) QuantumCircuit.mct = _mct
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import pulse from qiskit.providers.fake_provider import FakeArmonk backend = FakeArmonk() with pulse.build(backend) as drive_sched: d0 = pulse.drive_channel(0) a0 = pulse.acquire_channel(0) pulse.play(pulse.library.Constant(10, 1.0), d0) pulse.delay(20, d0) pulse.shift_phase(3.14/2, d0) pulse.set_phase(3.14, d0) pulse.shift_frequency(1e7, d0) pulse.set_frequency(5e9, d0) with pulse.build() as temp_sched: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), d0) pulse.play(pulse.library.Gaussian(20, -1.0, 3.0), d0) pulse.call(temp_sched) pulse.acquire(30, a0, pulse.MemorySlot(0)) drive_sched.draw()
https://github.com/acfilok96/Quantum-Computation
acfilok96
import qiskit from qiskit import * print(qiskit.__version__) %matplotlib inline from qiskit.tools.visualization import plot_histogram def find_secret_number(secter_number): # Using Bernstein Vazirani Algorithm secret_number = str(secter_number) circuit = QuantumCircuit(len(secret_number)+1, len(secret_number)) circuit.h(range(len(secret_number))) circuit.x(len(secret_number)) circuit.h(len(secret_number)) circuit.barrier() for position,value in enumerate(reversed(secret_number)): if value == '1': circuit.cx(position, len(secret_number)) circuit.barrier() circuit.h(range(len(secret_number))) circuit.barrier() circuit.measure(range(len(secret_number)), range(len(secret_number))) circuit.barrier() # circuit.draw(output='mpl') simulator = Aer.get_backend('qasm_simulator') job = execute(circuit, backend=simulator, shots=1) result = job.result() counts = result.get_counts() # print(counts) return circuit, counts secret_number = int(input("enter number: ")) circuit, number = find_secret_number(secret_number) print('required number: ', number) circuit.draw(output='mpl')
https://github.com/COFAlumni-USB/qiskit-fall-2022
COFAlumni-USB
#Para la construccion de circuitos cuanticos from qiskit import QuantumCircuit, execute #Para la construccion de las calibraciones y su vinculacion from qiskit import pulse, transpile from qiskit.pulse.library import Gaussian from qiskit.providers.fake_provider import FakeValencia, FakeHanoi #Compuertas personalizadas from qiskit.circuit import Gate from qiskit import QiskitError #informacion import qiskit.tools.jupyter circ = QuantumCircuit(2, 2); circ.h(0); circ.cx(0, 1); circ.measure(0, 0); circ.measure(1, 1); circ.draw('mpl'); result = execute(circ, backend=FakeValencia()).result(); counts = result.get_counts(); print("El resultado de la estadística es: \n|00>: {S00} \n|01>: {S01} \n|10>: {S10} \n|11>: {S11}".format(S00=counts['00'],S01=counts['01'],S10=counts['10'],S11=counts['11'])) backend = FakeValencia(); with pulse.build(backend, name='hadamard') as h_q0: pulse.play(Gaussian(duration=100, amp=0.1, sigma=3), pulse.drive_channel(0)); h_q0.draw() backend = FakeValencia()ñ with pulse.build(backend, name='hadamard') as h_q0: pulse.play(Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(0)) h_q0.draw() circ.add_calibration('h', [0], h_q0) backend = FakeHanoi() circ = transpile(circ, backend) print(backend.configuration().basis_gates) circ.draw('mpl', idle_wires=False) result = execute(circ, backend=FakeValencia()).result(); counts = result.get_counts(); print("El resultado de la estadística es: \n|00>: {S00} \n|01>: {S01} \n|10>: {S10} \n|11>: {S11}".format(S00=counts['00'],S01=counts['01'],S10=counts['10'],S11=counts['11'])) circ = QuantumCircuit(1, 1) custom_gate = Gate('my_custom_gate', 1, [3.14, 1]) # 3.14 is an arbitrary parameter for demonstration circ.append(custom_gate, [0]) circ.measure(0, 0) circ.draw('mpl') with pulse.build(backend, name='custom') as my_schedule: pulse.play(Gaussian(duration=64, amp=0.2, sigma=8), pulse.drive_channel(0)) circ.add_calibration('my_custom_gate', [0], my_schedule, [3.14, 1]) # Alternatively: circ.add_calibration(custom_gate, [0], my_schedule) circ = transpile(circ, backend) circ.draw('mpl', idle_wires=False) circ = QuantumCircuit(2, 2) circ.append(custom_gate, [1]) from qiskit import QiskitError try: circ = transpile(circ, backend) except QiskitError as e: print(e) %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# Necessary imports import matplotlib.pyplot as plt import numpy as np from IPython.display import clear_output from qiskit import QuantumCircuit from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import ZFeatureMap, RealAmplitudes from qiskit.utils import algorithm_globals from sklearn.datasets import make_classification from sklearn.preprocessing import MinMaxScaler from qiskit_machine_learning.algorithms.classifiers import NeuralNetworkClassifier from qiskit_machine_learning.neural_networks import EffectiveDimension, LocalEffectiveDimension from qiskit_machine_learning.neural_networks import SamplerQNN, EstimatorQNN # set random seed algorithm_globals.random_seed = 42 num_qubits = 3 # create a feature map feature_map = ZFeatureMap(feature_dimension=num_qubits, reps=1) # create a variational circuit ansatz = RealAmplitudes(num_qubits, reps=1) # combine feature map and ansatz into a single circuit qc = QuantumCircuit(num_qubits) qc.append(feature_map, range(num_qubits)) qc.append(ansatz, range(num_qubits)) qc.decompose().draw("mpl") # parity maps bitstrings to 0 or 1 def parity(x): return "{:b}".format(x).count("1") % 2 output_shape = 2 # corresponds to the number of classes, possible outcomes of the (parity) mapping. # construct QNN qnn = SamplerQNN( circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters, interpret=parity, output_shape=output_shape, sparse=False, ) # we can set the total number of input samples and weight samples for random selection num_input_samples = 10 num_weight_samples = 10 global_ed = EffectiveDimension( qnn=qnn, weight_samples=num_weight_samples, input_samples=num_input_samples ) # we can also provide user-defined samples and parameters input_samples = algorithm_globals.random.normal(0, 1, size=(10, qnn.num_inputs)) weight_samples = algorithm_globals.random.uniform(0, 1, size=(10, qnn.num_weights)) global_ed = EffectiveDimension(qnn=qnn, weight_samples=weight_samples, input_samples=input_samples) # finally, we will define ranges to test different numbers of data, n n = [5000, 8000, 10000, 40000, 60000, 100000, 150000, 200000, 500000, 1000000] global_eff_dim_0 = global_ed.get_effective_dimension(dataset_size=n[0]) d = qnn.num_weights print("Data size: {}, global effective dimension: {:.4f}".format(n[0], global_eff_dim_0)) print( "Number of weights: {}, normalized effective dimension: {:.4f}".format(d, global_eff_dim_0 / d) ) global_eff_dim_1 = global_ed.get_effective_dimension(dataset_size=n) print("Effective dimension: {}".format(global_eff_dim_1)) print("Number of weights: {}".format(d)) # plot the normalized effective dimension for the model plt.plot(n, np.array(global_eff_dim_1) / d) plt.xlabel("Number of data") plt.ylabel("Normalized GLOBAL effective dimension") plt.show() num_inputs = 3 num_samples = 50 X, y = make_classification( n_samples=num_samples, n_features=num_inputs, n_informative=3, n_redundant=0, n_clusters_per_class=1, class_sep=2.0, ) X = MinMaxScaler().fit_transform(X) y = 2 * y - 1 # labels in {-1, 1} estimator_qnn = EstimatorQNN( circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters ) # callback function that draws a live plot when the .fit() method is called def callback_graph(weights, obj_func_eval): clear_output(wait=True) objective_func_vals.append(obj_func_eval) plt.title("Objective function value against iteration") plt.xlabel("Iteration") plt.ylabel("Objective function value") plt.plot(range(len(objective_func_vals)), objective_func_vals) plt.show() # construct classifier initial_point = algorithm_globals.random.random(estimator_qnn.num_weights) estimator_classifier = NeuralNetworkClassifier( neural_network=estimator_qnn, optimizer=COBYLA(maxiter=80), initial_point=initial_point, callback=callback_graph, ) # create empty array for callback to store evaluations of the objective function (callback) objective_func_vals = [] plt.rcParams["figure.figsize"] = (12, 6) # fit classifier to data estimator_classifier.fit(X, y) # return to default figsize plt.rcParams["figure.figsize"] = (6, 4) # score classifier estimator_classifier.score(X, y) trained_weights = estimator_classifier.weights # get Local Effective Dimension for set of trained weights local_ed_trained = LocalEffectiveDimension( qnn=estimator_qnn, weight_samples=trained_weights, input_samples=X ) local_eff_dim_trained = local_ed_trained.get_effective_dimension(dataset_size=n) print( "normalized local effective dimensions for trained QNN: ", local_eff_dim_trained / estimator_qnn.num_weights, ) # get Local Effective Dimension for set of untrained weights local_ed_untrained = LocalEffectiveDimension( qnn=estimator_qnn, weight_samples=initial_point, input_samples=X ) local_eff_dim_untrained = local_ed_untrained.get_effective_dimension(dataset_size=n) print( "normalized local effective dimensions for untrained QNN: ", local_eff_dim_untrained / estimator_qnn.num_weights, ) # plot the normalized effective dimension for the model plt.plot(n, np.array(local_eff_dim_trained) / estimator_qnn.num_weights, label="trained weights") plt.plot( n, np.array(local_eff_dim_untrained) / estimator_qnn.num_weights, label="untrained weights" ) plt.xlabel("Number of data") plt.ylabel("Normalized LOCAL effective dimension") plt.legend() plt.show() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/Hayatto9217/Qiskit6
Hayatto9217
from qiskit import QuantumCircuit from qiskit.compiler import transpile from qiskit.transpiler import PassManager circ = QuantumCircuit(3) circ.ccx(0, 1, 2) circ.draw(output='mpl') from qiskit.transpiler.passes import Unroller pass_ = Unroller(['u1', 'u2', 'u3', 'cx']) pm = PassManager(pass_) new_circ = pm.run(circ) new_circ.draw(output='mpl') #同じパスの異なる実装 from qiskit.transpiler import CouplingMap, Layout from qiskit.transpiler.passes import BasicSwap, LookaheadSwap, StochasticSwap coupling = [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6]] circuit = QuantumCircuit(7) circuit.h(3) circuit.cx(0, 6) circuit.cx(6, 0) circuit.cx(0, 1) circuit.cx(3, 1) circuit.cx(3, 0) coupling_map = CouplingMap(couplinglist=coupling) bs = BasicSwap(coupling_map=coupling_map) pass_manager = PassManager(bs) basic_circ = pass_manager.run(circuit) ls = LookaheadSwap(coupling_map=coupling_map) pass_manager = PassManager(ls) lookahead_circ = pass_manager.run(circuit) ss = StochasticSwap(coupling_map=coupling_map) pass_manager = PassManager(ss) stochastic_circ = pass_manager.run(circuit) circuit.draw(output='mpl') lookahead_circ.draw(output='mpl') stochastic_circ.draw(output='mpl') basic_circ.draw(output='mpl') #プリセット パスマネージャー import math from qiskit.providers.fake_provider import FakeTokyo backend=FakeTokyo() qc = QuantumCircuit(10) random_state = [ 1 / math.sqrt(4) * complex(0,1), 1 / math.sqrt(8) * complex(1,0), 0, 0, 0, 0, 0, 0, 1 / math.sqrt(8) * complex(1,0), 1 / math.sqrt(8) * complex(0,1), 0, 0, 0, 0, 1 / math.sqrt(4) * complex(1,0), 1 / math.sqrt(8) * complex(1,0)] qc.initialize(random_state, range(4)) qc.draw() #異なる最適化 optimized_0 =transpile(qc, backend=backend, seed_transpiler=11, optimization_level=0) print('gates = ', optimized_0.count_ops()) print('depth = ', optimized_0.depth()) optimized_1 = transpile(qc, backend=backend, seed_transpiler=11, optimization_level=1) print('gates = ', optimized_1.count_ops()) print('depth = ', optimized_1.depth()) optimized_2 =transpile(qc, backend=backend,seed_transpiler=11, optimization_level=2) print('gates =', optimized_2.count_ops()) print('depth =', optimized_2.depth()) optimized_3 =transpile(qc, backend=backend, seed_transpiler=11, optimization_level=3) print('gates =', optimized_3.count_ops()) print('depth =', optimized_3.depth()) #有向非巡回グラフ from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.dagcircuit import DAGCircuit q = QuantumRegister(3, 'q') c = ClassicalRegister(3, 'c') circ = QuantumCircuit(q,c) circ.h(q[0]) circ.cx(q[0], q[1]) circ.measure(q[0],c[0]) circ.rz(0.5, q[1]).c_if(c,2) circ.draw(output='mpl')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.providers.fake_provider import FakeHanoi backend = FakeHanoi() config = backend.configuration() # Basic Features print("This backend is called {0}, and is on version {1}. It has {2} qubit{3}. It " "{4} OpenPulse programs. The basis gates supported on this device are {5}." "".format(config.backend_name, config.backend_version, config.n_qubits, '' if config.n_qubits == 1 else 's', 'supports' if config.open_pulse else 'does not support', config.basis_gates)) config.dt # units of seconds config.meas_levels config.dtm config.meas_map config.drive(0) config.measure(0) config.acquire(0) props = backend.properties() def describe_qubit(qubit, properties): """Print a string describing some of reported properties of the given qubit.""" # Conversion factors from standard SI units us = 1e6 ns = 1e9 GHz = 1e-9 print("Qubit {0} has a \n" " - T1 time of {1} microseconds\n" " - T2 time of {2} microseconds\n" " - U2 gate error of {3}\n" " - U2 gate duration of {4} nanoseconds\n" " - resonant frequency of {5} GHz".format( qubit, properties.t1(qubit) * us, properties.t2(qubit) * us, properties.gate_error('sx', qubit), properties.gate_length('sx', qubit) * ns, properties.frequency(qubit) * GHz)) describe_qubit(0, props) defaults = backend.defaults() q0_freq = defaults.qubit_freq_est[0] # Hz q0_meas_freq = defaults.meas_freq_est[0] # Hz GHz = 1e-9 print("DriveChannel(0) defaults to a modulation frequency of {} GHz.".format(q0_freq * GHz)) print("MeasureChannel(0) defaults to a modulation frequency of {} GHz.".format(q0_meas_freq * GHz)) calibrations = defaults.instruction_schedule_map print(calibrations) measure_schedule = calibrations.get('measure', range(config.n_qubits)) measure_schedule.draw(backend=backend) # You can use `has` to see if an operation is defined. Ex: Does qubit 3 have an x gate defined? calibrations.has('x', 3) # Some circuit operations take parameters. U1 takes a rotation angle: calibrations.get('u1', 0, P0=3.1415) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, Aer, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * from qiskit.providers.aer import QasmSimulator # Loading your IBM Quantum account(s) provider = IBMQ.load_account() from qiskit.circuit.library.standard_gates import XGate, HGate from operator import * n = 3 N = 8 #2**n index_colour_table = {} colour_hash_map = {} index_colour_table = {'000':"yellow", '001':"red", '010':"blue", '011':"red", '100':"green", '101':"blue", '110':"orange", '111':"red"} colour_hash_map = {"yellow":'100', "red":'011', "blue":'000', "green":'001', "orange":'010'} def database_oracle(index_colour_table, colour_hash_map): circ_database = QuantumCircuit(n + n) for i in range(N): circ_data = QuantumCircuit(n) idx = bin(i)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion colour = index_colour_table[idx] colour_hash = colour_hash_map[colour][::-1] for j in range(n): if colour_hash[j] == '1': circ_data.x(j) # qiskit maps the rightmost bit as the 0th qubit -> qn, ..., q0 # we therefore reverse the index string -> q0, ..., qn data_gate = circ_data.to_gate(label=colour).control(num_ctrl_qubits=n, ctrl_state=idx, label="index-"+colour) circ_database.append(data_gate, list(range(n+n))) return circ_database # drawing the database oracle circuit print("Database Encoding") database_oracle(index_colour_table, colour_hash_map).draw() circ_data = QuantumCircuit(n) m = 4 idx = bin(m)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion colour = index_colour_table[idx] colour_hash = colour_hash_map[colour][::-1] for j in range(n): if colour_hash[j] == '1': circ_data.x(j) print("Internal colour encoding for the colour green (as an example)"); circ_data.draw() def oracle_grover(database, data_entry): circ_grover = QuantumCircuit(n + n + 1) circ_grover.append(database, list(range(n+n))) target_reflection_gate = XGate().control(num_ctrl_qubits=n, ctrl_state=colour_hash_map[data_entry], label="Reflection of " + "\"" + data_entry + "\" Target") # control() missing 1 required positional argument: 'self' .... if only 'XGate' used instead of 'XGate()' # The “missing 1 required positional argument: 'self'” error is raised when you do not instantiate an object of a class before calling a class method. This error is also raised when you incorrectly instantiate a class. circ_grover.append(target_reflection_gate, list(range(n, n+n+1))) circ_grover.append(database, list(range(n+n))) return circ_grover print("Grover Oracle (target example: orange)") oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), "orange").decompose().draw() def mcz_gate(num_qubits): num_controls = num_qubits - 1 mcz_gate = QuantumCircuit(num_qubits) target_mcz = QuantumCircuit(1) target_mcz.z(0) target_mcz = target_mcz.to_gate(label="Z_Gate").control(num_ctrl_qubits=num_controls, ctrl_state=None, label="MCZ") mcz_gate.append(target_mcz, list(range(num_qubits))) return mcz_gate.reverse_bits() print("Multi-controlled Z (MCZ) Gate") mcz_gate(n).decompose().draw() def diffusion_operator(num_qubits): circ_diffusion = QuantumCircuit(num_qubits) qubits_list = list(range(num_qubits)) # Layer of H^n gates circ_diffusion.h(qubits_list) # Layer of X^n gates circ_diffusion.x(qubits_list) # Layer of Multi-controlled Z (MCZ) Gate circ_diffusion = circ_diffusion.compose(mcz_gate(num_qubits), qubits_list) # Layer of X^n gates circ_diffusion.x(qubits_list) # Layer of H^n gates circ_diffusion.h(qubits_list) return circ_diffusion print("Diffusion Circuit") diffusion_operator(n).draw() # Putting it all together ... !!! item = "green" print("Searching for the index of the colour", item) circuit = QuantumCircuit(n + n + 1, n) circuit.x(n + n) circuit.barrier() circuit.h(list(range(n))) circuit.h(n+n) circuit.barrier() unitary_oracle = oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), item).to_gate(label="Oracle Operator") unitary_diffuser = diffusion_operator(n).to_gate(label="Diffusion Operator") M = countOf(index_colour_table.values(), item) Q = int(np.pi * np.sqrt(N/M) / 4) for i in range(Q): circuit.append(unitary_oracle, list(range(n + n + 1))) circuit.append(unitary_diffuser, list(range(n))) circuit.barrier() circuit.measure(list(range(n)), list(range(n))) circuit.draw() backend_sim = Aer.get_backend('qasm_simulator') job_sim = backend_sim.run(transpile(circuit, backend_sim), shots=1024) result_sim = job_sim.result() counts = result_sim.get_counts(circuit) if M==1: print("Index of the colour", item, "is the index with most probable outcome") else: print("Indices of the colour", item, "are the indices the most probable outcomes") from qiskit.visualization import plot_histogram plot_histogram(counts)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# # your code is here or you may find the values by hand (in mind) # # # your solution is here #
https://github.com/emad-boosari/QuEST_Group
emad-boosari
!pip install qiskit !pip install pylatexenc from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector, Operator from qiskit.visualization import plot_histogram # function for plotting the quantum circuit def qplot(x): return x.draw('mpl', style= 'iqx', initial_state = True, scale = 0.7) n = 7 qc = QuantumCircuit(n) # Build a quantum circuit with 4 qubit qc.h(0) # Apply a Hadamard gate to the first qubit qc.barrier() qplot(qc) # we need to import Hadamard gate from qiskit.circuit.library from qiskit.circuit.library import HGate c_h = HGate().control(1) # Controlled Hadamard gate, 1 is number of control we want to use for i in range(1,n): qc.append(c_h,[0,i]) qc.barrier() qplot(qc) c_h2 = HGate().control(2) # Controlled Hadamard gate, controlled Hadamard gate with two control gate for i in range(2,n): qc.append(c_h2,[0,1,i]) qc. append(c_h2,[1,2,3]) qc.barrier() qplot(qc) # build a simple circuit circ = QuantumCircuit(3, name = "custom") circ.h(range(3)) circ.x(0) circ.cx(1,2) custom = circ.to_gate().control(1) qc.append(custom, [0,1,2,3]) qc.append(custom, [1,4,5,6]) qc.append(custom, [6,0,1,2]) qplot(qc) custom3 = circ.to_gate().control(3) qc.append(custom3, [0,1,2,3,4,5]) qc.append(custom3, [0,2,3,4,5,6]) qplot(qc)
https://github.com/lynnlangit/learning-quantum
lynnlangit
from qiskit import QuantumCircuit, Aer, execute, IBMQ from qiskit.utils import QuantumInstance import numpy as np from qiskit.algorithms import Shor IBMQ.enable_account('ENTER API TOKEN HERE') # Enter your API token here provider = IBMQ.get_provider(hub='ibm-q') backend = Aer.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend, shots=1000) my_shor = Shor(quantum_instance) result_dict = my_shor.factor(15) print(result_dict)
https://github.com/qiskit-community/qiskit-cold-atom
qiskit-community
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """General spin simulator backend tests.""" from time import sleep import numpy as np from qiskit import QuantumCircuit from qiskit.providers import JobStatus from qiskit.result import Result from qiskit.test import QiskitTestCase from qiskit_aer import AerJob from qiskit_cold_atom.exceptions import QiskitColdAtomError from qiskit_cold_atom.spins import SpinSimulator from qiskit_cold_atom.spins.base_spin_backend import BaseSpinBackend class TestSpinSimulatorBackend(QiskitTestCase): """class to test the FermionSimulatorBackend class.""" def setUp(self): super().setUp() self.backend = SpinSimulator() def test_initialization(self): """test the initialization of the backend""" target_config = { "backend_name": "spin_simulator", "backend_version": "0.0.1", "n_qubits": None, "basis_gates": None, "gates": [], "local": True, "simulator": True, "conditional": False, "open_pulse": False, "memory": True, "max_shots": 1e5, "coupling_map": None, "description": "a base simulator for spin circuits. Instead of a qubit, each wire " "represents a single high-dimensional spin", } backend = SpinSimulator() self.assertIsInstance(backend, BaseSpinBackend) self.assertTrue(target_config.items() <= backend.configuration().to_dict().items()) def test_run_method(self): """Test the run method of the backend simulator""" with self.subTest("test call"): circ = QuantumCircuit(2) job = self.backend.run(circ) self.assertIsInstance(job, AerJob) self.assertIsInstance(job.job_id(), str) self.assertIsInstance(job.result(), Result) self.assertEqual(job.status(), JobStatus.DONE) circ1 = QuantumCircuit(2) circ2 = QuantumCircuit(3) with self.subTest("test call with multiple circuits"): job = self.backend.run([circ1, circ2]) self.assertIsInstance(job, AerJob) with self.subTest("test shot number"): target_shots = 123 job = self.backend.run([circ1, circ2], shots=target_shots) for exp in job.result().results: self.assertEqual(exp.shots, target_shots) with self.subTest("test seed of RNG"): target_seed = 123 job = self.backend.run([circ1, circ2], seed=target_seed) for exp in job.result().results: self.assertEqual(exp.header.random_seed, target_seed) with self.subTest("test dimension of simulation"): test_circ = QuantumCircuit(2) test_circ.rlx(np.pi / 2, 0) test_circ.rly(np.pi / 4, [0, 1]) statevector_1 = self.backend.run(test_circ, spin=1).result().get_statevector() self.assertEqual(len(statevector_1), 3**2) statevector_2 = self.backend.run(test_circ, spin=5 / 2).result().get_statevector() self.assertEqual(len(statevector_2), 6**2) with self.subTest("test irregular spin values"): test_circ = QuantumCircuit(2) job = self.backend.run(test_circ, spin=5 / 4) sleep(0.01) self.assertIs(job.status(), JobStatus.ERROR) with self.assertRaises(QiskitColdAtomError): job.result() def test_execute(self): """test the ._execute() method internally called by .run()""" test_circ = QuantumCircuit(2) test_circ.rly(np.pi / 2, 0) test_circ.rlx(np.pi / 2, 1) test_circ.measure_all() result = self.backend.run(test_circ, spin=1, seed=45, shots=5).result() with self.subTest("test simulation counts"): self.assertEqual(result.get_counts(), {"0 1": 1, "2 2": 1, "1 1": 2, "1 0": 1}) with self.subTest("test simulation memory"): self.assertEqual(result.get_memory(), ["2 2", "1 1", "0 1", "1 0", "1 1"]) with self.subTest("test simulation statevector"): self.assertTrue( np.allclose( result.get_statevector(), np.array( [ 1 / 4, -1j / np.sqrt(8), -1 / 4, 1 / np.sqrt(8), -1j / 2, -1 / np.sqrt(8), 1 / 4, -1j / np.sqrt(8), -1 / 4, ] ), ) ) with self.subTest("test simulation unitary"): # test the unitary on a single spin-2 example test_circ = QuantumCircuit(1) test_circ.rlx(np.pi / 2, 0) test_circ.rlz(np.pi / 2, 0) test_circ.measure_all() result = self.backend.run(test_circ, spin=2, seed=45, shots=5).result() self.assertTrue( np.allclose( result.get_unitary(), np.array( [ [-0.25, 0.5j, np.sqrt(3 / 8), -0.5j, -0.25], [-0.5, 0.5j, 0.0, 0.5j, 0.5], [-np.sqrt(3 / 8), 0.0, -0.5, 0.0, -np.sqrt(3 / 8)], [-0.5, -0.5j, 0.0, -0.5j, 0.5], [-0.25, -0.5j, np.sqrt(3 / 8), 0.5j, -0.25], ] ), ) ) with self.subTest("test time taken"): self.assertTrue(result.to_dict()["time_taken"] < 0.5) with self.subTest("test result success"): self.assertTrue(result.to_dict()["success"])
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile from qiskit.visualization import plot_circuit_layout from qiskit.providers.fake_provider import FakeVigo backend = FakeVigo() ghz = QuantumCircuit(3, 3) ghz.h(0) ghz.cx(0,range(1,3)) ghz.barrier() ghz.measure(range(3), range(3)) ghz.draw(output='mpl')
https://github.com/minnukota381/Quantum-Computing-Qiskit
minnukota381
from qiskit import * from qiskit.visualization import plot_bloch_multivector # Create a quantum circuit with a single qubit # The default initial state of qubit will be |0> or [1,0] qc = QuantumCircuit(1) #Apply the Pauli X-gate on the qubit qc.x(0) #Draw the circuit # qc.draw() qc.draw('mpl') #Get the backend for the circuit (simulator or realtime system) backend = Aer.get_backend('statevector_simulator') #execute the circuit using the backend out = execute(qc,backend).result().get_statevector() #plot the result as a bloch sphere visualization plot_bloch_multivector(out)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for PVQD.""" import unittest from test.python.algorithms import QiskitAlgorithmsTestCase from functools import partial import numpy as np from ddt import data, ddt, unpack from qiskit import QiskitError from qiskit_algorithms.time_evolvers import TimeEvolutionProblem from qiskit_algorithms.optimizers import L_BFGS_B, SPSA, GradientDescent, OptimizerResult from qiskit_algorithms.state_fidelities import ComputeUncompute from qiskit_algorithms.time_evolvers.pvqd import PVQD from qiskit.circuit import Gate, Parameter, QuantumCircuit from qiskit.circuit.library import EfficientSU2 from qiskit.opflow import PauliSumOp from qiskit.primitives import Estimator, Sampler from qiskit.quantum_info import Pauli, SparsePauliOp from qiskit.test import QiskitTestCase from qiskit.utils import algorithm_globals # pylint: disable=unused-argument, invalid-name def gradient_supplied(fun, x0, jac, info): """A mock optimizer that checks whether the gradient is supported or not.""" result = OptimizerResult() result.x = x0 result.fun = 0 info["has_gradient"] = jac is not None return result class WhatAmI(Gate): """A custom opaque gate that can be inverted but not decomposed.""" def __init__(self, angle): super().__init__(name="whatami", num_qubits=2, params=[angle]) def inverse(self): return WhatAmI(-self.params[0]) @ddt class TestPVQD(QiskitAlgorithmsTestCase): """Tests for the pVQD algorithm.""" def setUp(self): super().setUp() self.hamiltonian = 0.1 * SparsePauliOp([Pauli("ZZ"), Pauli("IX"), Pauli("XI")]) self.observable = Pauli("ZZ") self.ansatz = EfficientSU2(2, reps=1) self.initial_parameters = np.zeros(self.ansatz.num_parameters) algorithm_globals.random_seed = 123 @data(("ising", True, 2), ("pauli", False, None), ("pauli_sum_op", True, 2)) @unpack def test_pvqd(self, hamiltonian_type, gradient, num_timesteps): """Test a simple evolution.""" time = 0.02 if hamiltonian_type == "ising": hamiltonian = self.hamiltonian elif hamiltonian_type == "pauli_sum_op": with self.assertWarns(DeprecationWarning): hamiltonian = PauliSumOp(self.hamiltonian) else: # hamiltonian_type == "pauli": hamiltonian = Pauli("XX") # parse input arguments if gradient: optimizer = GradientDescent(maxiter=1) else: optimizer = L_BFGS_B(maxiter=1) sampler = Sampler() estimator = Estimator() fidelity_primitive = ComputeUncompute(sampler) # run pVQD keeping track of the energy and the magnetization pvqd = PVQD( fidelity_primitive, self.ansatz, self.initial_parameters, estimator, optimizer=optimizer, num_timesteps=num_timesteps, ) problem = TimeEvolutionProblem( hamiltonian, time, aux_operators=[hamiltonian, self.observable] ) result = pvqd.evolve(problem) self.assertTrue(len(result.fidelities) == 3) self.assertTrue(np.all(result.times == [0.0, 0.01, 0.02])) self.assertTrue(np.asarray(result.observables).shape == (3, 2)) num_parameters = self.ansatz.num_parameters self.assertTrue( len(result.parameters) == 3 and np.all([len(params) == num_parameters for params in result.parameters]) ) def test_step(self): """Test calling the step method directly.""" sampler = Sampler() estimator = Estimator() fidelity_primitive = ComputeUncompute(sampler) pvqd = PVQD( fidelity_primitive, self.ansatz, self.initial_parameters, estimator, optimizer=L_BFGS_B(maxiter=100), ) # perform optimization for a timestep of 0, then the optimal parameters are the current # ones and the fidelity is 1 theta_next, fidelity = pvqd.step( self.hamiltonian, self.ansatz, self.initial_parameters, dt=0.0, initial_guess=np.zeros_like(self.initial_parameters), ) self.assertTrue(np.allclose(theta_next, self.initial_parameters)) self.assertAlmostEqual(fidelity, 1) def test_get_loss(self): """Test getting the loss function directly.""" sampler = Sampler() estimator = Estimator() fidelity_primitive = ComputeUncompute(sampler) pvqd = PVQD( fidelity_primitive, self.ansatz, self.initial_parameters, estimator, use_parameter_shift=False, ) theta = np.ones(self.ansatz.num_parameters) loss, gradient = pvqd.get_loss( self.hamiltonian, self.ansatz, dt=0.0, current_parameters=theta ) displacement = np.arange(self.ansatz.num_parameters) with self.subTest(msg="check gradient is None"): self.assertIsNone(gradient) with self.subTest(msg="check loss works"): self.assertGreater(loss(displacement), 0) self.assertAlmostEqual(loss(np.zeros_like(theta)), 0) def test_invalid_num_timestep(self): """Test raises if the num_timestep is not positive.""" sampler = Sampler() estimator = Estimator() fidelity_primitive = ComputeUncompute(sampler) pvqd = PVQD( fidelity_primitive, self.ansatz, self.initial_parameters, estimator, optimizer=L_BFGS_B(), num_timesteps=0, ) problem = TimeEvolutionProblem( self.hamiltonian, time=0.01, aux_operators=[self.hamiltonian, self.observable] ) with self.assertRaises(ValueError): _ = pvqd.evolve(problem) def test_initial_guess_and_observables(self): """Test doing no optimizations stays at initial guess.""" initial_guess = np.zeros(self.ansatz.num_parameters) sampler = Sampler() estimator = Estimator() fidelity_primitive = ComputeUncompute(sampler) pvqd = PVQD( fidelity_primitive, self.ansatz, self.initial_parameters, estimator, optimizer=SPSA(maxiter=0, learning_rate=0.1, perturbation=0.01), num_timesteps=10, initial_guess=initial_guess, ) problem = TimeEvolutionProblem( self.hamiltonian, time=0.1, aux_operators=[self.hamiltonian, self.observable] ) result = pvqd.evolve(problem) observables = result.aux_ops_evaluated self.assertEqual(observables[0], 0.1) # expected energy self.assertEqual(observables[1], 1) # expected magnetization def test_zero_parameters(self): """Test passing an ansatz with zero parameters raises an error.""" problem = TimeEvolutionProblem(self.hamiltonian, time=0.02) sampler = Sampler() fidelity_primitive = ComputeUncompute(sampler) pvqd = PVQD( fidelity_primitive, QuantumCircuit(2), np.array([]), optimizer=SPSA(maxiter=10, learning_rate=0.1, perturbation=0.01), ) with self.assertRaises(QiskitError): _ = pvqd.evolve(problem) def test_initial_state_raises(self): """Test passing an initial state raises an error for now.""" initial_state = QuantumCircuit(2) initial_state.x(0) problem = TimeEvolutionProblem( self.hamiltonian, time=0.02, initial_state=initial_state, ) sampler = Sampler() fidelity_primitive = ComputeUncompute(sampler) pvqd = PVQD( fidelity_primitive, self.ansatz, self.initial_parameters, optimizer=SPSA(maxiter=0, learning_rate=0.1, perturbation=0.01), ) with self.assertRaises(NotImplementedError): _ = pvqd.evolve(problem) def test_aux_ops_raises(self): """Test passing auxiliary operators with no estimator raises an error.""" problem = TimeEvolutionProblem( self.hamiltonian, time=0.02, aux_operators=[self.hamiltonian, self.observable] ) sampler = Sampler() fidelity_primitive = ComputeUncompute(sampler) pvqd = PVQD( fidelity_primitive, self.ansatz, self.initial_parameters, optimizer=SPSA(maxiter=0, learning_rate=0.1, perturbation=0.01), ) with self.assertRaises(ValueError): _ = pvqd.evolve(problem) class TestPVQDUtils(QiskitTestCase): """Test some utility functions for PVQD.""" def setUp(self): super().setUp() self.hamiltonian = 0.1 * SparsePauliOp([Pauli("ZZ"), Pauli("IX"), Pauli("XI")]) self.ansatz = EfficientSU2(2, reps=1) def test_gradient_supported(self): """Test the gradient support is correctly determined.""" # gradient supported here wrapped = EfficientSU2(2) # a circuit wrapped into a big instruction plain = wrapped.decompose() # a plain circuit with already supported instructions # gradients not supported on the following circuits x = Parameter("x") duplicated = QuantumCircuit(2) duplicated.rx(x, 0) duplicated.rx(x, 1) needs_chainrule = QuantumCircuit(2) needs_chainrule.rx(2 * x, 0) custom_gate = WhatAmI(x) unsupported = QuantumCircuit(2) unsupported.append(custom_gate, [0, 1]) tests = [ (wrapped, True), # tuple: (circuit, gradient support) (plain, True), (duplicated, False), (needs_chainrule, False), (unsupported, False), ] # used to store the info if a gradient callable is passed into the # optimizer of not info = {"has_gradient": None} optimizer = partial(gradient_supplied, info=info) sampler = Sampler() estimator = Estimator() fidelity_primitive = ComputeUncompute(sampler) pvqd = PVQD( fidelity=fidelity_primitive, ansatz=None, initial_parameters=np.array([]), estimator=estimator, optimizer=optimizer, ) problem = TimeEvolutionProblem(self.hamiltonian, time=0.01) for circuit, expected_support in tests: with self.subTest(circuit=circuit, expected_support=expected_support): pvqd.ansatz = circuit pvqd.initial_parameters = np.zeros(circuit.num_parameters) _ = pvqd.evolve(problem) self.assertEqual(info["has_gradient"], expected_support) if __name__ == "__main__": unittest.main()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit q = QuantumRegister(1) c = ClassicalRegister(1) qc = QuantumCircuit(q, c) qc.h(q) qc.measure(q, c) qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'})
https://github.com/qclib/qclib
qclib
# Copyright 2021 qclib project. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Implements the state preparation defined at https://arxiv.org/abs/1003.5760. """ import numpy as np from qiskit import QuantumRegister, QuantumCircuit from qclib.unitary import unitary from qclib.gates.initialize import Initialize from .topdown import TopDownInitialize class SVDInitialize(Initialize): """ https://arxiv.org/abs/1003.5760 This class implements a state preparation gate. """ def __init__(self, params, label=None): """ Parameters ---------- params: list of complex A unit vector representing a quantum state. Values are amplitudes. """ self._name = "svd" self._get_num_qubits(params) if label is None: label = "SVDSP" super().__init__(self._name, self.num_qubits, params, label=label) def _define(self): self.definition = self._define_initialize() def _define_initialize(self): """ State preparation using Schmidt decomposition arXiv:1003.5760 """ state = np.copy(self.params) n_qubits = self.num_qubits odd = n_qubits % 2 state.shape = (int(2 ** (n_qubits // 2)), int(2 ** (n_qubits // 2 + odd))) matrix_u, matrix_d, matrix_v = np.linalg.svd(state) matrix_d = matrix_d / np.linalg.norm(matrix_d) reg_a = QuantumRegister(n_qubits // 2 + odd) reg_b = QuantumRegister(n_qubits // 2) circuit = QuantumCircuit(reg_a, reg_b) if len(matrix_d) > 2: gate = SVDInitialize(matrix_d) circuit.append(gate, reg_b) else: gate = TopDownInitialize(matrix_d) circuit.append(gate, reg_b) for k in range(int(n_qubits // 2)): circuit.cx(reg_b[k], reg_a[k]) # apply gate U to the first register gate_u = unitary(matrix_u) circuit.append(gate_u, reg_b) # apply gate V to the second register gate_v = unitary(matrix_v.T) circuit.append(gate_v, reg_a) return circuit @staticmethod def initialize(q_circuit, state, qubits=None): """ Appends a SVDInitialize gate into the q_circuit """ if qubits is None: q_circuit.append(SVDInitialize(state), q_circuit.qubits) else: q_circuit.append(SVDInitialize(state), qubits)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the Unroller pass""" from numpy import pi from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.extensions.simulator import Snapshot from qiskit.transpiler.passes import Unroller from qiskit.converters import circuit_to_dag, dag_to_circuit from qiskit.quantum_info import Operator from qiskit.test import QiskitTestCase from qiskit.exceptions import QiskitError from qiskit.circuit import Parameter, Qubit, Clbit from qiskit.circuit.library import U1Gate, U2Gate, U3Gate, CU1Gate, CU3Gate from qiskit.transpiler.target import Target class TestUnroller(QiskitTestCase): """Tests the Unroller pass.""" def test_basic_unroll(self): """Test decompose a single H into u2.""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.h(qr[0]) dag = circuit_to_dag(circuit) pass_ = Unroller(["u2"]) unrolled_dag = pass_.run(dag) op_nodes = unrolled_dag.op_nodes() self.assertEqual(len(op_nodes), 1) self.assertEqual(op_nodes[0].name, "u2") def test_basic_unroll_target(self): """Test decompose a single H into U2 from target.""" qc = QuantumCircuit(1) qc.h(0) target = Target(num_qubits=1) phi = Parameter("phi") lam = Parameter("lam") target.add_instruction(U2Gate(phi, lam)) dag = circuit_to_dag(qc) pass_ = Unroller(target=target) unrolled_dag = pass_.run(dag) op_nodes = unrolled_dag.op_nodes() self.assertEqual(len(op_nodes), 1) self.assertEqual(op_nodes[0].name, "u2") def test_unroll_toffoli(self): """Test unroll toffoli on multi regs to h, t, tdg, cx.""" qr1 = QuantumRegister(2, "qr1") qr2 = QuantumRegister(1, "qr2") circuit = QuantumCircuit(qr1, qr2) circuit.ccx(qr1[0], qr1[1], qr2[0]) dag = circuit_to_dag(circuit) pass_ = Unroller(["h", "t", "tdg", "cx"]) unrolled_dag = pass_.run(dag) op_nodes = unrolled_dag.op_nodes() self.assertEqual(len(op_nodes), 15) for node in op_nodes: self.assertIn(node.name, ["h", "t", "tdg", "cx"]) def test_unroll_1q_chain_conditional(self): """Test unroll chain of 1-qubit gates interrupted by conditional.""" qr = QuantumRegister(1, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.h(qr) circuit.tdg(qr) circuit.z(qr) circuit.t(qr) circuit.ry(0.5, qr) circuit.rz(0.3, qr) circuit.rx(0.1, qr) circuit.measure(qr, cr) circuit.x(qr).c_if(cr, 1) circuit.y(qr).c_if(cr, 1) circuit.z(qr).c_if(cr, 1) dag = circuit_to_dag(circuit) pass_ = Unroller(["u1", "u2", "u3"]) unrolled_dag = pass_.run(dag) # Pick up -1 * 0.3 / 2 global phase for one RZ -> U1. ref_circuit = QuantumCircuit(qr, cr, global_phase=-0.3 / 2) ref_circuit.append(U2Gate(0, pi), [qr[0]]) ref_circuit.append(U1Gate(-pi / 4), [qr[0]]) ref_circuit.append(U1Gate(pi), [qr[0]]) ref_circuit.append(U1Gate(pi / 4), [qr[0]]) ref_circuit.append(U3Gate(0.5, 0, 0), [qr[0]]) ref_circuit.append(U1Gate(0.3), [qr[0]]) ref_circuit.append(U3Gate(0.1, -pi / 2, pi / 2), [qr[0]]) ref_circuit.measure(qr[0], cr[0]) ref_circuit.append(U3Gate(pi, 0, pi), [qr[0]]).c_if(cr, 1) ref_circuit.append(U3Gate(pi, pi / 2, pi / 2), [qr[0]]).c_if(cr, 1) ref_circuit.append(U1Gate(pi), [qr[0]]).c_if(cr, 1) ref_dag = circuit_to_dag(ref_circuit) self.assertEqual(unrolled_dag, ref_dag) def test_unroll_no_basis(self): """Test when a given gate has no decompositions.""" qr = QuantumRegister(1, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.h(qr) dag = circuit_to_dag(circuit) pass_ = Unroller(basis=[]) with self.assertRaises(QiskitError): pass_.run(dag) def test_simple_unroll_parameterized_without_expressions(self): """Verify unrolling parameterized gates without expressions.""" qr = QuantumRegister(1) qc = QuantumCircuit(qr) theta = Parameter("theta") qc.rz(theta, qr[0]) dag = circuit_to_dag(qc) unrolled_dag = Unroller(["u1", "u3", "cx"]).run(dag) expected = QuantumCircuit(qr, global_phase=-theta / 2) expected.append(U1Gate(theta), [qr[0]]) self.assertEqual(circuit_to_dag(expected), unrolled_dag) def test_simple_unroll_parameterized_with_expressions(self): """Verify unrolling parameterized gates with expressions.""" qr = QuantumRegister(1) qc = QuantumCircuit(qr) theta = Parameter("theta") phi = Parameter("phi") sum_ = theta + phi qc.rz(sum_, qr[0]) dag = circuit_to_dag(qc) unrolled_dag = Unroller(["u1", "u3", "cx"]).run(dag) expected = QuantumCircuit(qr, global_phase=-sum_ / 2) expected.append(U1Gate(sum_), [qr[0]]) self.assertEqual(circuit_to_dag(expected), unrolled_dag) def test_definition_unroll_parameterized(self): """Verify that unrolling complex gates with parameters does not raise.""" qr = QuantumRegister(2) qc = QuantumCircuit(qr) theta = Parameter("theta") qc.append(CU1Gate(theta), [qr[1], qr[0]]) qc.append(CU1Gate(theta * theta), [qr[0], qr[1]]) dag = circuit_to_dag(qc) out_dag = Unroller(["u1", "cx"]).run(dag) self.assertEqual(out_dag.count_ops(), {"u1": 6, "cx": 4}) def test_unrolling_parameterized_composite_gates(self): """Verify unrolling circuits with parameterized composite gates.""" qr1 = QuantumRegister(2) subqc = QuantumCircuit(qr1) theta = Parameter("theta") subqc.rz(theta, qr1[0]) subqc.cx(qr1[0], qr1[1]) subqc.rz(theta, qr1[1]) # Expanding across register with shared parameter qr2 = QuantumRegister(4) qc = QuantumCircuit(qr2) qc.append(subqc.to_instruction(), [qr2[0], qr2[1]]) qc.append(subqc.to_instruction(), [qr2[2], qr2[3]]) dag = circuit_to_dag(qc) out_dag = Unroller(["u1", "u3", "cx"]).run(dag) # Pick up -1 * theta / 2 global phase four twice (once for each RZ -> P # in each of the two sub_instr instructions). expected = QuantumCircuit(qr2, global_phase=-1 * 4 * theta / 2.0) expected.append(U1Gate(theta), [qr2[0]]) expected.cx(qr2[0], qr2[1]) expected.append(U1Gate(theta), [qr2[1]]) expected.append(U1Gate(theta), [qr2[2]]) expected.cx(qr2[2], qr2[3]) expected.append(U1Gate(theta), [qr2[3]]) self.assertEqual(circuit_to_dag(expected), out_dag) # Expanding across register with shared parameter qc = QuantumCircuit(qr2) phi = Parameter("phi") gamma = Parameter("gamma") qc.append(subqc.to_instruction({theta: phi}), [qr2[0], qr2[1]]) qc.append(subqc.to_instruction({theta: gamma}), [qr2[2], qr2[3]]) dag = circuit_to_dag(qc) out_dag = Unroller(["u1", "u3", "cx"]).run(dag) expected = QuantumCircuit(qr2, global_phase=-1 * (2 * phi + 2 * gamma) / 2.0) expected.append(U1Gate(phi), [qr2[0]]) expected.cx(qr2[0], qr2[1]) expected.append(U1Gate(phi), [qr2[1]]) expected.append(U1Gate(gamma), [qr2[2]]) expected.cx(qr2[2], qr2[3]) expected.append(U1Gate(gamma), [qr2[3]]) self.assertEqual(circuit_to_dag(expected), out_dag) def test_unrolling_preserves_qregs_order(self): """Test unrolling a gate preseveres it's definition registers order""" qr = QuantumRegister(2, "qr1") qc = QuantumCircuit(qr) qc.cx(1, 0) gate = qc.to_gate() qr2 = QuantumRegister(2, "qr2") qc2 = QuantumCircuit(qr2) qc2.append(gate, qr2) dag = circuit_to_dag(qc2) out_dag = Unroller(["cx"]).run(dag) expected = QuantumCircuit(qr2) expected.cx(1, 0) self.assertEqual(circuit_to_dag(expected), out_dag) def test_unrolling_nested_gates_preserves_qregs_order(self): """Test unrolling a nested gate preseveres it's definition registers order.""" qr = QuantumRegister(2, "qr1") qc = QuantumCircuit(qr) qc.cx(1, 0) gate_level_1 = qc.to_gate() qr2 = QuantumRegister(2, "qr2") qc2 = QuantumCircuit(qr2) qc2.append(gate_level_1, [1, 0]) qc2.cp(pi, 1, 0) gate_level_2 = qc2.to_gate() qr3 = QuantumRegister(2, "qr3") qc3 = QuantumCircuit(qr3) qc3.append(gate_level_2, [1, 0]) qc3.cu(pi, pi, pi, 0, 1, 0) gate_level_3 = qc3.to_gate() qr4 = QuantumRegister(2, "qr4") qc4 = QuantumCircuit(qr4) qc4.append(gate_level_3, [0, 1]) dag = circuit_to_dag(qc4) out_dag = Unroller(["cx", "cp", "cu"]).run(dag) expected = QuantumCircuit(qr4) expected.cx(1, 0) expected.cp(pi, 0, 1) expected.cu(pi, pi, pi, 0, 1, 0) self.assertEqual(circuit_to_dag(expected), out_dag) def test_unrolling_global_phase_1q(self): """Test unrolling a circuit with global phase in a composite gate.""" circ = QuantumCircuit(1, global_phase=pi / 2) circ.x(0) circ.h(0) v = circ.to_gate() qc = QuantumCircuit(1) qc.append(v, [0]) dag = circuit_to_dag(qc) out_dag = Unroller(["cx", "x", "h"]).run(dag) qcd = dag_to_circuit(out_dag) self.assertEqual(Operator(qc), Operator(qcd)) def test_unrolling_global_phase_nested_gates(self): """Test unrolling a nested gate preseveres global phase.""" qc = QuantumCircuit(1, global_phase=pi) qc.x(0) gate = qc.to_gate() qc = QuantumCircuit(1) qc.append(gate, [0]) gate = qc.to_gate() qc = QuantumCircuit(1) qc.append(gate, [0]) dag = circuit_to_dag(qc) out_dag = Unroller(["x", "u"]).run(dag) qcd = dag_to_circuit(out_dag) self.assertEqual(Operator(qc), Operator(qcd)) def test_if_simple(self): """Test a simple if statement unrolls correctly.""" qubits = [Qubit(), Qubit()] clbits = [Clbit(), Clbit()] qc = QuantumCircuit(qubits, clbits) qc.h(0) qc.measure(0, 0) with qc.if_test((clbits[0], 0)): qc.x(0) qc.h(0) qc.measure(0, 1) with qc.if_test((clbits[1], 0)): qc.h(1) qc.cx(1, 0) dag = circuit_to_dag(qc) unrolled_dag = Unroller(["u", "cx"]).run(dag) expected = QuantumCircuit(qubits, clbits) expected.u(pi / 2, 0, pi, 0) expected.measure(0, 0) with expected.if_test((clbits[0], 0)): expected.u(pi, 0, pi, 0) expected.u(pi / 2, 0, pi, 0) expected.measure(0, 1) with expected.if_test((clbits[1], 0)): expected.u(pi / 2, 0, pi, 1) expected.cx(1, 0) expected_dag = circuit_to_dag(expected) self.assertEqual(unrolled_dag, expected_dag) def test_if_else_simple(self): """Test a simple if-else statement unrolls correctly.""" qubits = [Qubit(), Qubit()] clbits = [Clbit(), Clbit()] qc = QuantumCircuit(qubits, clbits) qc.h(0) qc.measure(0, 0) with qc.if_test((clbits[0], 0)) as else_: qc.x(0) with else_: qc.z(0) qc.h(0) qc.measure(0, 1) with qc.if_test((clbits[1], 0)) as else_: qc.h(1) qc.cx(1, 0) with else_: qc.h(0) qc.cx(0, 1) dag = circuit_to_dag(qc) unrolled_dag = Unroller(["u", "cx"]).run(dag) expected = QuantumCircuit(qubits, clbits) expected.u(pi / 2, 0, pi, 0) expected.measure(0, 0) with expected.if_test((clbits[0], 0)) as else_: expected.u(pi, 0, pi, 0) with else_: expected.u(0, 0, pi, 0) expected.u(pi / 2, 0, pi, 0) expected.measure(0, 1) with expected.if_test((clbits[1], 0)) as else_: expected.u(pi / 2, 0, pi, 1) expected.cx(1, 0) with else_: expected.u(pi / 2, 0, pi, 0) expected.cx(0, 1) expected_dag = circuit_to_dag(expected) self.assertEqual(unrolled_dag, expected_dag) def test_nested_control_flow(self): """Test unrolling nested control flow blocks.""" qr = QuantumRegister(2) cr1 = ClassicalRegister(1) cr2 = ClassicalRegister(1) cr3 = ClassicalRegister(1) qc = QuantumCircuit(qr, cr1, cr2, cr3) with qc.for_loop(range(3)): with qc.while_loop((cr1, 0)): qc.x(0) with qc.while_loop((cr2, 0)): qc.y(0) with qc.while_loop((cr3, 0)): qc.z(0) dag = circuit_to_dag(qc) unrolled_dag = Unroller(["u", "cx"]).run(dag) expected = QuantumCircuit(qr, cr1, cr2, cr3) with expected.for_loop(range(3)): with expected.while_loop((cr1, 0)): expected.u(pi, 0, pi, 0) with expected.while_loop((cr2, 0)): expected.u(pi, pi / 2, pi / 2, 0) with expected.while_loop((cr3, 0)): expected.u(0, 0, pi, 0) expected_dag = circuit_to_dag(expected) self.assertEqual(unrolled_dag, expected_dag) def test_parameterized_angle(self): """Test unrolling with parameterized angle""" qc = QuantumCircuit(1) index = Parameter("index") with qc.for_loop((0, 0.5 * pi), index) as param: qc.rx(param, 0) dag = circuit_to_dag(qc) unrolled_dag = Unroller(["u", "cx"]).run(dag) expected = QuantumCircuit(1) with expected.for_loop((0, 0.5 * pi), index) as param: expected.u(param, -pi / 2, pi / 2, 0) expected_dag = circuit_to_dag(expected) self.assertEqual(unrolled_dag, expected_dag) class TestUnrollAllInstructions(QiskitTestCase): """Test unrolling a circuit containing all standard instructions.""" def setUp(self): super().setUp() qr = self.qr = QuantumRegister(3, "qr") cr = self.cr = ClassicalRegister(3, "cr") self.circuit = QuantumCircuit(qr, cr) self.ref_circuit = QuantumCircuit(qr, cr) self.pass_ = Unroller(basis=["u3", "cx", "id"]) def compare_dags(self): """compare dags in class tests""" dag = circuit_to_dag(self.circuit) unrolled_dag = self.pass_.run(dag) ref_dag = circuit_to_dag(self.ref_circuit) self.assertEqual(unrolled_dag, ref_dag) def test_unroll_crx(self): """test unroll crx""" # qr_1: ─────■───── qr_1: ─────────────────■─────────────────────■───────────────────── # ┌────┴────┐ = ┌─────────────┐┌─┴─┐┌───────────────┐┌─┴─┐┌─────────────────┐ # qr_2: ┤ Rx(0.5) ├ qr_2: ┤ U3(0,0,π/2) ├┤ X ├┤ U3(-0.25,0,0) ├┤ X ├┤ U3(0.25,-π/2,0) ├ # └─────────┘ └─────────────┘└───┘└───────────────┘└───┘└─────────────────┘ self.circuit.crx(0.5, 1, 2) self.ref_circuit.append(U3Gate(0, 0, pi / 2), [2]) self.ref_circuit.cx(1, 2) self.ref_circuit.append(U3Gate(-0.25, 0, 0), [2]) self.ref_circuit.cx(1, 2) self.ref_circuit.append(U3Gate(0.25, -pi / 2, 0), [2]) self.compare_dags() def test_unroll_cry(self): """test unroll cry""" # qr_1: ─────■───── qr_1: ──────────────────■─────────────────────■── # ┌────┴────┐ = ┌──────────────┐┌─┴─┐┌───────────────┐┌─┴─┐ # qr_2: ┤ Ry(0.5) ├ qr_2: ┤ U3(0.25,0,0) ├┤ X ├┤ U3(-0.25,0,0) ├┤ X ├ # └─────────┘ └──────────────┘└───┘└───────────────┘└───┘ self.circuit.cry(0.5, 1, 2) self.ref_circuit.append(U3Gate(0.25, 0, 0), [2]) self.ref_circuit.cx(1, 2) self.ref_circuit.append(U3Gate(-0.25, 0, 0), [2]) self.ref_circuit.cx(1, 2) self.compare_dags() def test_unroll_ccx(self): """test unroll ccx""" # qr_0: ──■── qr_0: ──────────────────────────────────────■──────────────────────» # │ │ » # qr_1: ──■── = qr_1: ─────────────────■────────────────────┼───────────────────■──» # ┌─┴─┐ ┌─────────────┐┌─┴─┐┌──────────────┐┌─┴─┐┌─────────────┐┌─┴─┐» # qr_2: ┤ X ├ qr_2: ┤ U3(π/2,0,π) ├┤ X ├┤ U3(0,0,-π/4) ├┤ X ├┤ U3(0,0,π/4) ├┤ X ├» # └───┘ └─────────────┘└───┘└──────────────┘└───┘└─────────────┘└───┘» # « ┌─────────────┐ # «qr_0: ──────────────────■─────────■───────┤ U3(0,0,π/4) ├───■── # « ┌─────────────┐ │ ┌─┴─┐ ├─────────────┴┐┌─┴─┐ # «qr_1: ┤ U3(0,0,π/4) ├───┼───────┤ X ├─────┤ U3(0,0,-π/4) ├┤ X ├ # « ├─────────────┴┐┌─┴─┐┌────┴───┴────┐├─────────────┬┘└───┘ # «qr_2: ┤ U3(0,0,-π/4) ├┤ X ├┤ U3(0,0,π/4) ├┤ U3(π/2,0,π) ├────── # « └──────────────┘└───┘└─────────────┘└─────────────┘ self.circuit.ccx(0, 1, 2) self.ref_circuit.append(U3Gate(pi / 2, 0, pi), [2]) self.ref_circuit.cx(1, 2) self.ref_circuit.append(U3Gate(0, 0, -pi / 4), [2]) self.ref_circuit.cx(0, 2) self.ref_circuit.append(U3Gate(0, 0, pi / 4), [2]) self.ref_circuit.cx(1, 2) self.ref_circuit.append(U3Gate(0, 0, pi / 4), [1]) self.ref_circuit.append(U3Gate(0, 0, -pi / 4), [2]) self.ref_circuit.cx(0, 2) self.ref_circuit.cx(0, 1) self.ref_circuit.append(U3Gate(0, 0, pi / 4), [0]) self.ref_circuit.append(U3Gate(0, 0, -pi / 4), [1]) self.ref_circuit.cx(0, 1) self.ref_circuit.append(U3Gate(0, 0, pi / 4), [2]) self.ref_circuit.append(U3Gate(pi / 2, 0, pi), [2]) self.compare_dags() def test_unroll_ch(self): """test unroll ch""" # qr_0: ──■── qr_0: ───────────────────────────────────────────────■──────────────────» # ┌─┴─┐ = ┌─────────────┐┌─────────────┐┌─────────────┐┌─┴─┐┌──────────────┐» # qr_2: ┤ H ├ qr_2: ┤ U3(0,0,π/2) ├┤ U3(π/2,0,π) ├┤ U3(0,0,π/4) ├┤ X ├┤ U3(0,0,-π/4) ├» # └───┘ └─────────────┘└─────────────┘└─────────────┘└───┘└──────────────┘» # « # «qr_0: ─────────────────────────────── # « ┌─────────────┐┌──────────────┐ # «qr_2: ┤ U3(π/2,0,π) ├┤ U3(0,0,-π/2) ├ # « └─────────────┘└──────────────┘ self.circuit.ch(0, 2) self.ref_circuit.append(U3Gate(0, 0, pi / 2), [2]) self.ref_circuit.append(U3Gate(pi / 2, 0, pi), [2]) self.ref_circuit.append(U3Gate(0, 0, pi / 4), [2]) self.ref_circuit.cx(0, 2) self.ref_circuit.append(U3Gate(0, 0, -pi / 4), [2]) self.ref_circuit.append(U3Gate(pi / 2, 0, pi), [2]) self.ref_circuit.append(U3Gate(0, 0, -pi / 2), [2]) self.compare_dags() def test_unroll_crz(self): """test unroll crz""" # qr_1: ─────■───── qr_1: ──────────────────■─────────────────────■── # ┌────┴────┐ = ┌──────────────┐┌─┴─┐┌───────────────┐┌─┴─┐ # qr_2: ┤ Rz(0.5) ├ qr_2: ┤ U3(0,0,0.25) ├┤ X ├┤ U3(0,0,-0.25) ├┤ X ├ # └─────────┘ └──────────────┘└───┘└───────────────┘└───┘ self.circuit.crz(0.5, 1, 2) self.ref_circuit.append(U3Gate(0, 0, 0.25), [2]) self.ref_circuit.cx(1, 2) self.ref_circuit.append(U3Gate(0, 0, -0.25), [2]) self.ref_circuit.cx(1, 2) def test_unroll_cswap(self): """test unroll cswap""" # ┌───┐ » # qr_0: ─X─ qr_0: ┤ X ├─────────────────■────────────────────────────────────────■──» # │ └─┬─┘ │ │ » # qr_1: ─■─ = qr_1: ──┼───────────────────┼────────────────────■───────────────────┼──» # │ │ ┌─────────────┐┌─┴─┐┌──────────────┐┌─┴─┐┌─────────────┐┌─┴─┐» # qr_2: ─X─ qr_2: ──■──┤ U3(π/2,0,π) ├┤ X ├┤ U3(0,0,-π/4) ├┤ X ├┤ U3(0,0,π/4) ├┤ X ├» # └─────────────┘└───┘└──────────────┘└───┘└─────────────┘└───┘» # « ┌─────────────┐ ┌───┐ ┌──────────────┐┌───┐┌───┐ # «qr_0: ┤ U3(0,0,π/4) ├───────────┤ X ├─────┤ U3(0,0,-π/4) ├┤ X ├┤ X ├ # « └─────────────┘ └─┬─┘ ├─────────────┬┘└─┬─┘└─┬─┘ # «qr_1: ──────────────────■─────────■───────┤ U3(0,0,π/4) ├───■────┼── # « ┌──────────────┐┌─┴─┐┌─────────────┐├─────────────┤ │ # «qr_2: ┤ U3(0,0,-π/4) ├┤ X ├┤ U3(0,0,π/4) ├┤ U3(π/2,0,π) ├────────■── # « └──────────────┘└───┘└─────────────┘└─────────────┘ self.circuit.cswap(1, 0, 2) self.ref_circuit.cx(2, 0) self.ref_circuit.append(U3Gate(pi / 2, 0, pi), [2]) self.ref_circuit.cx(0, 2) self.ref_circuit.append(U3Gate(0, 0, -pi / 4), [2]) self.ref_circuit.cx(1, 2) self.ref_circuit.append(U3Gate(0, 0, pi / 4), [2]) self.ref_circuit.cx(0, 2) self.ref_circuit.append(U3Gate(0, 0, pi / 4), [0]) self.ref_circuit.append(U3Gate(0, 0, -pi / 4), [2]) self.ref_circuit.cx(1, 2) self.ref_circuit.cx(1, 0) self.ref_circuit.append(U3Gate(0, 0, -pi / 4), [0]) self.ref_circuit.append(U3Gate(0, 0, pi / 4), [1]) self.ref_circuit.cx(1, 0) self.ref_circuit.append(U3Gate(0, 0, pi / 4), [2]) self.ref_circuit.append(U3Gate(pi / 2, 0, pi), [2]) self.ref_circuit.cx(2, 0) self.compare_dags() def test_unroll_cu1(self): """test unroll cu1""" # ┌──────────────┐ # qr_0: ─■──────── qr_0: ┤ U3(0,0,0.05) ├──■─────────────────────■────────────────── # │U1(0.1) = └──────────────┘┌─┴─┐┌───────────────┐┌─┴─┐┌──────────────┐ # qr_2: ─■──────── qr_2: ────────────────┤ X ├┤ U3(0,0,-0.05) ├┤ X ├┤ U3(0,0,0.05) ├ # └───┘└───────────────┘└───┘└──────────────┘ self.circuit.append(CU1Gate(0.1), [0, 2]) self.ref_circuit.append(U3Gate(0, 0, 0.05), [0]) self.ref_circuit.cx(0, 2) self.ref_circuit.append(U3Gate(0, 0, -0.05), [2]) self.ref_circuit.cx(0, 2) self.ref_circuit.append(U3Gate(0, 0, 0.05), [2]) self.compare_dags() def test_unroll_cu3(self): """test unroll cu3""" # ┌──────────────┐ # q_1: ────────■──────── q_1: ─┤ U3(0,0,0.05) ├──■────────────────────────■─────────────────── # ┌───────┴───────┐ = ┌┴──────────────┤┌─┴─┐┌──────────────────┐┌─┴─┐┌───────────────┐ # q_2: ┤ U3(0.2,0.1,0) ├ q_2: ┤ U3(0,0,-0.05) ├┤ X ├┤ U3(-0.1,0,-0.05) ├┤ X ├┤ U3(0.1,0.1,0) ├ # └───────────────┘ └───────────────┘└───┘└──────────────────┘└───┘└───────────────┘ self.circuit.append(CU3Gate(0.2, 0.1, 0.0), [1, 2]) self.ref_circuit.append(U3Gate(0, 0, 0.05), [1]) self.ref_circuit.append(U3Gate(0, 0, -0.05), [2]) self.ref_circuit.cx(1, 2) self.ref_circuit.append(U3Gate(-0.1, 0, -0.05), [2]) self.ref_circuit.cx(1, 2) self.ref_circuit.append(U3Gate(0.1, 0.1, 0), [2]) self.compare_dags() def test_unroll_cx(self): """test unroll cx""" self.circuit.cx(1, 0) self.ref_circuit.cx(1, 0) self.compare_dags() def test_unroll_cy(self): """test unroll cy""" # qr_1: ──■── qr_1: ──────────────────■───────────────── # ┌─┴─┐ = ┌──────────────┐┌─┴─┐┌─────────────┐ # qr_2: ┤ Y ├ qr_2: ┤ U3(0,0,-π/2) ├┤ X ├┤ U3(0,0,π/2) ├ # └───┘ └──────────────┘└───┘└─────────────┘ self.circuit.cy(1, 2) self.ref_circuit.append(U3Gate(0, 0, -pi / 2), [2]) self.ref_circuit.cx(1, 2) self.ref_circuit.append(U3Gate(0, 0, pi / 2), [2]) self.compare_dags() def test_unroll_cz(self): """test unroll cz""" # ┌─────────────┐┌───┐┌─────────────┐ # qr_0: ─■─ qr_0: ┤ U3(π/2,0,π) ├┤ X ├┤ U3(π/2,0,π) ├ # │ = └─────────────┘└─┬─┘└─────────────┘ # qr_2: ─■─ qr_2: ─────────────────■───────────────── self.circuit.cz(2, 0) self.ref_circuit.append(U3Gate(pi / 2, 0, pi), [0]) self.ref_circuit.cx(2, 0) self.ref_circuit.append(U3Gate(pi / 2, 0, pi), [0]) self.compare_dags() def test_unroll_h(self): """test unroll h""" self.circuit.h(1) self.ref_circuit.append(U3Gate(pi / 2, 0, pi), [1]) self.compare_dags() def test_unroll_i(self): """test unroll i""" self.circuit.i(0) self.ref_circuit.i(0) self.compare_dags() def test_unroll_rx(self): """test unroll rx""" self.circuit.rx(0.1, 0) self.ref_circuit.append(U3Gate(0.1, -pi / 2, pi / 2), [0]) self.compare_dags() def test_unroll_ry(self): """test unroll ry""" self.circuit.ry(0.2, 1) self.ref_circuit.append(U3Gate(0.2, 0, 0), [1]) self.compare_dags() def test_unroll_rz(self): """test unroll rz""" self.circuit.rz(0.3, 2) self.ref_circuit.global_phase = -1 * 0.3 / 2 self.ref_circuit.append(U3Gate(0, 0, 0.3), [2]) self.compare_dags() def test_unroll_rzz(self): """test unroll rzz""" # global phase: 5.9832 # ┌───┐┌─────────────┐┌───┐ # qr_0: ─■──────── qr_0: ┤ X ├┤ U3(0,0,0.6) ├┤ X ├ # │ZZ(0.6) = └─┬─┘└─────────────┘└─┬─┘ # qr_1: ─■──────── qr_1: ──■───────────────────■── self.circuit.rzz(0.6, 1, 0) self.ref_circuit.global_phase = -1 * 0.6 / 2 self.ref_circuit.cx(1, 0) self.ref_circuit.append(U3Gate(0, 0, 0.6), [0]) self.ref_circuit.cx(1, 0) self.compare_dags() def test_unroll_s(self): """test unroll s""" self.circuit.s(0) self.ref_circuit.append(U3Gate(0, 0, pi / 2), [0]) self.compare_dags() def test_unroll_sdg(self): """test unroll sdg""" self.circuit.sdg(1) self.ref_circuit.append(U3Gate(0, 0, -pi / 2), [1]) self.compare_dags() def test_unroll_swap(self): """test unroll swap""" # ┌───┐ # qr_1: ─X─ qr_1: ──■──┤ X ├──■── # │ = ┌─┴─┐└─┬─┘┌─┴─┐ # qr_2: ─X─ qr_2: ┤ X ├──■──┤ X ├ # └───┘ └───┘ self.circuit.swap(1, 2) self.ref_circuit.cx(1, 2) self.ref_circuit.cx(2, 1) self.ref_circuit.cx(1, 2) self.compare_dags() def test_unroll_t(self): """test unroll t""" self.circuit.t(2) self.ref_circuit.append(U3Gate(0, 0, pi / 4), [2]) self.compare_dags() def test_unroll_tdg(self): """test unroll tdg""" self.circuit.tdg(0) self.ref_circuit.append(U3Gate(0, 0, -pi / 4), [0]) self.compare_dags() def test_unroll_u1(self): """test unroll u1""" self.circuit.append(U1Gate(0.1), [1]) self.ref_circuit.append(U3Gate(0, 0, 0.1), [1]) self.compare_dags() def test_unroll_u2(self): """test unroll u2""" self.circuit.append(U2Gate(0.2, -0.1), [0]) self.ref_circuit.append(U3Gate(pi / 2, 0.2, -0.1), [0]) self.compare_dags() def test_unroll_u3(self): """test unroll u3""" self.circuit.append(U3Gate(0.3, 0.0, -0.1), [2]) self.ref_circuit.append(U3Gate(0.3, 0.0, -0.1), [2]) self.compare_dags() def test_unroll_x(self): """test unroll x""" self.circuit.x(2) self.ref_circuit.append(U3Gate(pi, 0, pi), [2]) self.compare_dags() def test_unroll_y(self): """test unroll y""" self.circuit.y(1) self.ref_circuit.append(U3Gate(pi, pi / 2, pi / 2), [1]) self.compare_dags() def test_unroll_z(self): """test unroll z""" self.circuit.z(0) self.ref_circuit.append(U3Gate(0, 0, pi), [0]) self.compare_dags() def test_unroll_snapshot(self): """test unroll snapshot""" num_qubits = self.circuit.num_qubits instr = Snapshot("0", num_qubits=num_qubits) self.circuit.append(instr, range(num_qubits)) self.ref_circuit.append(instr, range(num_qubits)) self.compare_dags() def test_unroll_measure(self): """test unroll measure""" self.circuit.measure(self.qr, self.cr) self.ref_circuit.measure(self.qr, self.cr) self.compare_dags()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit qc = QuantumCircuit(1, 1) qc.h(0) qc.measure(0,0) qc.x(0).c_if(0, 0) qc.draw(output='mpl') from qiskit import QuantumRegister, ClassicalRegister q = QuantumRegister(3, 'q') c = ClassicalRegister(3, 'c') qc = QuantumCircuit(q, c) qc.h([0, 1, 2]) qc.barrier() qc.measure(q, c) qc.draw('mpl') print(bin(3)) print(bin(7)) qc.x(2).c_if(c, 3) # for the 011 case qc.x(2).c_if(c, 7) # for the 111 case qc.draw(output='mpl') nq = 2 m = 2 q = QuantumRegister(nq, 'q') c = ClassicalRegister(m, 'c') qc_S = QuantumCircuit(q,c) qc_S.h(0) qc_S.x(1) qc_S.draw('mpl') from math import pi cu_circ = QuantumCircuit(2) cu_circ.cp(pi/2, 0, 1) cu_circ.draw('mpl') for _ in range(2 ** (m - 1)): qc_S.cp(pi/2, 0, 1) qc_S.draw('mpl') def x_measurement(qc, qubit, cbit): """Measure 'qubit' in the X-basis, and store the result in 'cbit'""" qc.h(qubit) qc.measure(qubit, cbit) x_measurement(qc_S, q[0], c[0]) qc_S.draw('mpl') qc_S.reset(0) qc_S.h(0) qc_S.draw('mpl') qc_S.p(-pi/2, 0).c_if(c, 1) qc_S.draw('mpl') ## 2^t c-U operations (with t=m-2) for _ in range(2 ** (m - 2)): qc_S.cp(pi/2, 0, 1) x_measurement(qc_S, q[0], c[1]) qc_S.draw('mpl') import matplotlib.pyplot as plt from qiskit.tools.visualization import plot_histogram from qiskit_aer.primitives import Sampler sampler = Sampler() job = sampler.run(qc_S) result = job.result() dist0 = result.quasi_dists[0] key_new = [str(key/2**m) for key in list(dist0.keys())] dist1 = dict(zip(key_new, dist0.values())) fig, ax = plt.subplots(1,2) plot_histogram(dist0, ax=ax[0]) plot_histogram(dist1, ax=ax[1]) plt.tight_layout() nq = 3 # number of qubits m = 3 # number of classical bits q = QuantumRegister(nq,'q') c = ClassicalRegister(m,'c') qc = QuantumCircuit(q,c) qc.h(0) qc.x([1, 2]) qc.draw('mpl') cu_circ = QuantumCircuit(nq) cu_circ.mcp(pi/4, [0, 1], 2) cu_circ.draw('mpl') for _ in range(2 ** (m - 1)): qc.mcp(pi/4, [0, 1], 2) qc.draw('mpl') x_measurement(qc, q[0], c[0]) qc.draw('mpl') qc.reset(0) qc.h(0) qc.draw('mpl') qc.p(-pi/2, 0).c_if(c, 1) qc.draw('mpl') for _ in range(2 ** (m - 2)): qc.mcp(pi/4, [0, 1], 2) x_measurement(qc, q[0], c[1]) qc.draw('mpl') # initialization of qubit q0 qc.reset(0) qc.h(0) # phase correction qc.p(-pi/4, 0).c_if(c, 1) qc.p(-pi/2, 0).c_if(c, 2) qc.p(-3*pi/2, 0).c_if(c, 3) # c-U operations for _ in range(2 ** (m - 3)): qc.mcp(pi/4, [0, 1], 2) # X measurement qc.h(0) qc.measure(0, 2) qc.draw('mpl') result = sampler.run(qc).result() dist0 = result.quasi_dists[0] key_new = [str(key/2**m) for key in list(dist0.keys())] dist1 = dict(zip(key_new, dist0.values())) fig, ax = plt.subplots(1,2) plot_histogram(dist0, ax=ax[0]) plot_histogram(dist1, ax=ax[1]) plt.tight_layout() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Gate cancellation pass testing""" import unittest import numpy as np from qiskit.test import QiskitTestCase from qiskit import QuantumRegister, QuantumCircuit from qiskit.circuit.library import U1Gate, RZGate, PhaseGate, CXGate, SXGate from qiskit.circuit.parameter import Parameter from qiskit.transpiler.target import Target from qiskit.transpiler import PassManager, PropertySet from qiskit.transpiler.passes import CommutationAnalysis, CommutativeCancellation, FixedPoint, Size from qiskit.quantum_info import Operator class TestCommutativeCancellation(QiskitTestCase): """Test the CommutativeCancellation pass.""" def setUp(self): super().setUp() self.com_pass_ = CommutationAnalysis() self.pass_ = CommutativeCancellation() self.pset = self.pass_.property_set = PropertySet() def test_all_gates(self): """Test all gates on 1 and 2 qubits q0:-[H]-[H]--[x]-[x]--[y]-[y]--[rz]-[rz]--[u1]-[u1]-[rx]-[rx]---.--.--.--.--.--.- | | | | | | q1:-------------------------------------------------------------X--X--Y--Y--.--.- = qr0:---[u1]--- qr1:---------- """ qr = QuantumRegister(2, "q") circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.h(qr[0]) circuit.x(qr[0]) circuit.x(qr[0]) circuit.y(qr[0]) circuit.y(qr[0]) circuit.rz(0.5, qr[0]) circuit.rz(0.5, qr[0]) circuit.append(U1Gate(0.5), [qr[0]]) # TODO this should work with Phase gates too circuit.append(U1Gate(0.5), [qr[0]]) circuit.rx(0.5, qr[0]) circuit.rx(0.5, qr[0]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cy(qr[0], qr[1]) circuit.cy(qr[0], qr[1]) circuit.cz(qr[0], qr[1]) circuit.cz(qr[0], qr[1]) passmanager = PassManager() passmanager.append(CommutativeCancellation()) new_circuit = passmanager.run(circuit) expected = QuantumCircuit(qr) expected.append(RZGate(2.0), [qr[0]]) expected.rx(1.0, qr[0]) self.assertEqual(expected, new_circuit) def test_commutative_circuit1(self): """A simple circuit where three CNOTs commute, the first and the last cancel. qr0:----.---------------.-- qr0:------------ | | qr1:---(+)-----(+)-----(+)- = qr1:-------(+)-- | | qr2:---[H]------.---------- qr2:---[H]--.--- """ qr = QuantumRegister(3, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.h(qr[2]) circuit.cx(qr[2], qr[1]) circuit.cx(qr[0], qr[1]) passmanager = PassManager() passmanager.append(CommutativeCancellation()) new_circuit = passmanager.run(circuit) expected = QuantumCircuit(qr) expected.h(qr[2]) expected.cx(qr[2], qr[1]) self.assertEqual(expected, new_circuit) def test_consecutive_cnots(self): """A simple circuit equals identity qr0:----.- ----.-- qr0:------------ | | qr1:---(+)----(+)- = qr1:------------ """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) new_pm = PassManager(CommutativeCancellation()) new_circuit = new_pm.run(circuit) expected = QuantumCircuit(qr) self.assertEqual(expected, new_circuit) def test_consecutive_cnots2(self): """ Two CNOTs that equals identity, with rotation gates inserted. """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.rx(np.pi, qr[0]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.rx(np.pi, qr[0]) passmanager = PassManager() passmanager.append( [CommutationAnalysis(), CommutativeCancellation(), Size(), FixedPoint("size")], do_while=lambda property_set: not property_set["size_fixed_point"], ) new_circuit = passmanager.run(circuit) expected = QuantumCircuit(qr) self.assertEqual(expected, new_circuit) def test_2_alternating_cnots(self): """A simple circuit where nothing should be cancelled. qr0:----.- ---(+)- qr0:----.----(+)- | | | | qr1:---(+)-----.-- = qr1:---(+)----.-- """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[0]) new_pm = PassManager(CommutativeCancellation()) new_circuit = new_pm.run(circuit) expected = QuantumCircuit(qr) expected.cx(qr[0], qr[1]) expected.cx(qr[1], qr[0]) self.assertEqual(expected, new_circuit) def test_control_bit_of_cnot(self): """A simple circuit where nothing should be cancelled. qr0:----.------[X]------.-- qr0:----.------[X]------.-- | | | | qr1:---(+)-------------(+)- = qr1:---(+)-------------(+)- """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.x(qr[0]) circuit.cx(qr[0], qr[1]) new_pm = PassManager(CommutativeCancellation()) new_circuit = new_pm.run(circuit) expected = QuantumCircuit(qr) expected.cx(qr[0], qr[1]) expected.x(qr[0]) expected.cx(qr[0], qr[1]) self.assertEqual(expected, new_circuit) def test_control_bit_of_cnot1(self): """A simple circuit where the two cnots shoule be cancelled. qr0:----.------[Z]------.-- qr0:---[Z]--- | | qr1:---(+)-------------(+)- = qr1:--------- """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.z(qr[0]) circuit.cx(qr[0], qr[1]) new_pm = PassManager(CommutativeCancellation()) new_circuit = new_pm.run(circuit) expected = QuantumCircuit(qr) expected.z(qr[0]) self.assertEqual(expected, new_circuit) def test_control_bit_of_cnot2(self): """A simple circuit where the two cnots shoule be cancelled. qr0:----.------[T]------.-- qr0:---[T]--- | | qr1:---(+)-------------(+)- = qr1:--------- """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.t(qr[0]) circuit.cx(qr[0], qr[1]) new_pm = PassManager(CommutativeCancellation()) new_circuit = new_pm.run(circuit) expected = QuantumCircuit(qr) expected.t(qr[0]) self.assertEqual(expected, new_circuit) def test_control_bit_of_cnot3(self): """A simple circuit where the two cnots shoule be cancelled. qr0:----.------[Rz]------.-- qr0:---[Rz]--- | | qr1:---(+)-------- -----(+)- = qr1:---------- """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.rz(np.pi / 3, qr[0]) circuit.cx(qr[0], qr[1]) new_pm = PassManager(CommutativeCancellation()) new_circuit = new_pm.run(circuit) expected = QuantumCircuit(qr) expected.rz(np.pi / 3, qr[0]) self.assertEqual(expected, new_circuit) def test_control_bit_of_cnot4(self): """A simple circuit where the two cnots shoule be cancelled. qr0:----.------[T]------.-- qr0:---[T]--- | | qr1:---(+)-------------(+)- = qr1:--------- """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.t(qr[0]) circuit.cx(qr[0], qr[1]) new_pm = PassManager(CommutativeCancellation()) new_circuit = new_pm.run(circuit) expected = QuantumCircuit(qr) expected.t(qr[0]) self.assertEqual(expected, new_circuit) def test_target_bit_of_cnot(self): """A simple circuit where nothing should be cancelled. qr0:----.---------------.-- qr0:----.---------------.-- | | | | qr1:---(+)-----[Z]-----(+)- = qr1:---(+)----[Z]------(+)- """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.z(qr[1]) circuit.cx(qr[0], qr[1]) new_pm = PassManager(CommutativeCancellation()) new_circuit = new_pm.run(circuit) expected = QuantumCircuit(qr) expected.cx(qr[0], qr[1]) expected.z(qr[1]) expected.cx(qr[0], qr[1]) self.assertEqual(expected, new_circuit) def test_target_bit_of_cnot1(self): """A simple circuit where nothing should be cancelled. qr0:----.---------------.-- qr0:----.---------------.-- | | | | qr1:---(+)-----[T]-----(+)- = qr1:---(+)----[T]------(+)- """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.t(qr[1]) circuit.cx(qr[0], qr[1]) new_pm = PassManager(CommutativeCancellation()) new_circuit = new_pm.run(circuit) expected = QuantumCircuit(qr) expected.cx(qr[0], qr[1]) expected.t(qr[1]) expected.cx(qr[0], qr[1]) self.assertEqual(expected, new_circuit) def test_target_bit_of_cnot2(self): """A simple circuit where nothing should be cancelled. qr0:----.---------------.-- qr0:----.---------------.-- | | | | qr1:---(+)-----[Rz]----(+)- = qr1:---(+)----[Rz]-----(+)- """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.rz(np.pi / 3, qr[1]) circuit.cx(qr[0], qr[1]) new_pm = PassManager(CommutativeCancellation()) new_circuit = new_pm.run(circuit) expected = QuantumCircuit(qr) expected.cx(qr[0], qr[1]) expected.rz(np.pi / 3, qr[1]) expected.cx(qr[0], qr[1]) self.assertEqual(expected, new_circuit) def test_commutative_circuit2(self): """ A simple circuit where three CNOTs commute, the first and the last cancel, also two X gates cancel and two Rz gates combine. qr0:----.---------------.-------- qr0:------------- | | qr1:---(+)---(+)--[X]--(+)--[X]-- = qr1:--------(+)-- | | qr2:---[Rz]---.---[Rz]-[T]--[S]-- qr2:--[U1]---.--- """ qr = QuantumRegister(3, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.rz(np.pi / 3, qr[2]) circuit.cx(qr[2], qr[1]) circuit.rz(np.pi / 3, qr[2]) circuit.t(qr[2]) circuit.s(qr[2]) circuit.x(qr[1]) circuit.cx(qr[0], qr[1]) circuit.x(qr[1]) passmanager = PassManager() passmanager.append(CommutativeCancellation()) new_circuit = passmanager.run(circuit) expected = QuantumCircuit(qr) expected.append(RZGate(np.pi * 17 / 12), [qr[2]]) expected.cx(qr[2], qr[1]) expected.global_phase = (np.pi * 17 / 12 - (2 * np.pi / 3)) / 2 self.assertEqual(expected, new_circuit) def test_commutative_circuit3(self): """ A simple circuit where three CNOTs commute, the first and the last cancel, also two X gates cancel and two Rz gates combine. qr0:-------.------------------.------------- qr0:------------- | | qr1:------(+)------(+)--[X]--(+)-------[X]-- = qr1:--------(+)-- | | qr2:------[Rz]--.---.----.---[Rz]-[T]--[S]-- qr2:--[U1]---.--- | | qr3:-[Rz]--[X]-(+)------(+)--[X]-[Rz]------- qr3:--[Rz]------- """ qr = QuantumRegister(4, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.rz(np.pi / 3, qr[2]) circuit.rz(np.pi / 3, qr[3]) circuit.x(qr[3]) circuit.cx(qr[2], qr[3]) circuit.cx(qr[2], qr[1]) circuit.cx(qr[2], qr[3]) circuit.rz(np.pi / 3, qr[2]) circuit.t(qr[2]) circuit.x(qr[3]) circuit.rz(np.pi / 3, qr[3]) circuit.s(qr[2]) circuit.x(qr[1]) circuit.cx(qr[0], qr[1]) circuit.x(qr[1]) passmanager = PassManager() passmanager.append( [CommutationAnalysis(), CommutativeCancellation(), Size(), FixedPoint("size")], do_while=lambda property_set: not property_set["size_fixed_point"], ) new_circuit = passmanager.run(circuit) expected = QuantumCircuit(qr) expected.append(RZGate(np.pi * 17 / 12), [qr[2]]) expected.append(RZGate(np.pi * 2 / 3), [qr[3]]) expected.cx(qr[2], qr[1]) self.assertEqual( expected, new_circuit, msg=f"expected:\n{expected}\nnew_circuit:\n{new_circuit}" ) def test_cnot_cascade(self): """ A cascade of CNOTs that equals identity. """ qr = QuantumRegister(10, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[2]) circuit.cx(qr[2], qr[3]) circuit.cx(qr[3], qr[4]) circuit.cx(qr[4], qr[5]) circuit.cx(qr[5], qr[6]) circuit.cx(qr[6], qr[7]) circuit.cx(qr[7], qr[8]) circuit.cx(qr[8], qr[9]) circuit.cx(qr[8], qr[9]) circuit.cx(qr[7], qr[8]) circuit.cx(qr[6], qr[7]) circuit.cx(qr[5], qr[6]) circuit.cx(qr[4], qr[5]) circuit.cx(qr[3], qr[4]) circuit.cx(qr[2], qr[3]) circuit.cx(qr[1], qr[2]) circuit.cx(qr[0], qr[1]) passmanager = PassManager() # passmanager.append(CommutativeCancellation()) passmanager.append( [CommutationAnalysis(), CommutativeCancellation(), Size(), FixedPoint("size")], do_while=lambda property_set: not property_set["size_fixed_point"], ) new_circuit = passmanager.run(circuit) expected = QuantumCircuit(qr) self.assertEqual(expected, new_circuit) def test_cnot_cascade1(self): """ A cascade of CNOTs that equals identity, with rotation gates inserted. """ qr = QuantumRegister(10, "qr") circuit = QuantumCircuit(qr) circuit.rx(np.pi, qr[0]) circuit.rx(np.pi, qr[1]) circuit.rx(np.pi, qr[2]) circuit.rx(np.pi, qr[3]) circuit.rx(np.pi, qr[4]) circuit.rx(np.pi, qr[5]) circuit.rx(np.pi, qr[6]) circuit.rx(np.pi, qr[7]) circuit.rx(np.pi, qr[8]) circuit.rx(np.pi, qr[9]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[2]) circuit.cx(qr[2], qr[3]) circuit.cx(qr[3], qr[4]) circuit.cx(qr[4], qr[5]) circuit.cx(qr[5], qr[6]) circuit.cx(qr[6], qr[7]) circuit.cx(qr[7], qr[8]) circuit.cx(qr[8], qr[9]) circuit.cx(qr[8], qr[9]) circuit.cx(qr[7], qr[8]) circuit.cx(qr[6], qr[7]) circuit.cx(qr[5], qr[6]) circuit.cx(qr[4], qr[5]) circuit.cx(qr[3], qr[4]) circuit.cx(qr[2], qr[3]) circuit.cx(qr[1], qr[2]) circuit.cx(qr[0], qr[1]) circuit.rx(np.pi, qr[0]) circuit.rx(np.pi, qr[1]) circuit.rx(np.pi, qr[2]) circuit.rx(np.pi, qr[3]) circuit.rx(np.pi, qr[4]) circuit.rx(np.pi, qr[5]) circuit.rx(np.pi, qr[6]) circuit.rx(np.pi, qr[7]) circuit.rx(np.pi, qr[8]) circuit.rx(np.pi, qr[9]) passmanager = PassManager() # passmanager.append(CommutativeCancellation()) passmanager.append( [CommutationAnalysis(), CommutativeCancellation(), Size(), FixedPoint("size")], do_while=lambda property_set: not property_set["size_fixed_point"], ) new_circuit = passmanager.run(circuit) expected = QuantumCircuit(qr) self.assertEqual(expected, new_circuit) def test_conditional_gates_dont_commute(self): """Conditional gates do not commute and do not cancel""" # ┌───┐┌─┐ # q_0: ┤ H ├┤M├───────────── # └───┘└╥┘ ┌─┐ # q_1: ──■───╫────■───┤M├─── # ┌─┴─┐ ║ ┌─┴─┐ └╥┘┌─┐ # q_2: ┤ X ├─╫──┤ X ├──╫─┤M├ # └───┘ ║ └─╥─┘ ║ └╥┘ # ║ ┌──╨──┐ ║ ║ # c: 2/══════╩═╡ 0x0 ╞═╩══╩═ # 0 └─────┘ 0 1 circuit = QuantumCircuit(3, 2) circuit.h(0) circuit.measure(0, 0) circuit.cx(1, 2) circuit.cx(1, 2).c_if(circuit.cregs[0], 0) circuit.measure([1, 2], [0, 1]) new_pm = PassManager(CommutativeCancellation()) new_circuit = new_pm.run(circuit) self.assertEqual(circuit, new_circuit) def test_basis_01(self): """Test basis priority change, phase gate""" circuit = QuantumCircuit(1) circuit.s(0) circuit.z(0) circuit.t(0) circuit.rz(np.pi, 0) passmanager = PassManager() passmanager.append(CommutativeCancellation(basis_gates=["cx", "p", "sx"])) new_circuit = passmanager.run(circuit) expected = QuantumCircuit(1) expected.rz(11 * np.pi / 4, 0) expected.global_phase = 11 * np.pi / 4 / 2 - np.pi / 2 self.assertEqual(new_circuit, expected) def test_target_basis_01(self): """Test basis priority change, phase gate, with target.""" circuit = QuantumCircuit(1) circuit.s(0) circuit.z(0) circuit.t(0) circuit.rz(np.pi, 0) theta = Parameter("theta") target = Target(num_qubits=2) target.add_instruction(CXGate()) target.add_instruction(PhaseGate(theta)) target.add_instruction(SXGate()) passmanager = PassManager() passmanager.append(CommutativeCancellation(target=target)) new_circuit = passmanager.run(circuit) expected = QuantumCircuit(1) expected.rz(11 * np.pi / 4, 0) expected.global_phase = 11 * np.pi / 4 / 2 - np.pi / 2 self.assertEqual(new_circuit, expected) def test_basis_02(self): """Test basis priority change, Rz gate""" circuit = QuantumCircuit(1) circuit.s(0) circuit.z(0) circuit.t(0) passmanager = PassManager() passmanager.append(CommutativeCancellation(basis_gates=["cx", "rz", "sx"])) new_circuit = passmanager.run(circuit) expected = QuantumCircuit(1) expected.rz(7 * np.pi / 4, 0) expected.global_phase = 7 * np.pi / 4 / 2 self.assertEqual(new_circuit, expected) def test_basis_03(self): """Test no specified basis""" circuit = QuantumCircuit(1) circuit.s(0) circuit.z(0) circuit.t(0) passmanager = PassManager() passmanager.append(CommutativeCancellation()) new_circuit = passmanager.run(circuit) expected = QuantumCircuit(1) expected.s(0) expected.z(0) expected.t(0) self.assertEqual(new_circuit, expected) def test_basis_global_phase_01(self): """Test no specified basis, rz""" circ = QuantumCircuit(1) circ.rz(np.pi / 2, 0) circ.p(np.pi / 2, 0) circ.p(np.pi / 2, 0) passmanager = PassManager() passmanager.append(CommutativeCancellation()) ccirc = passmanager.run(circ) self.assertEqual(Operator(circ), Operator(ccirc)) def test_basis_global_phase_02(self): """Test no specified basis, p""" circ = QuantumCircuit(1) circ.p(np.pi / 2, 0) circ.rz(np.pi / 2, 0) circ.p(np.pi / 2, 0) passmanager = PassManager() passmanager.append(CommutativeCancellation()) ccirc = passmanager.run(circ) self.assertEqual(Operator(circ), Operator(ccirc)) def test_basis_global_phase_03(self): """Test global phase preservation if cummulative z-rotation is 0""" circ = QuantumCircuit(1) circ.rz(np.pi / 2, 0) circ.p(np.pi / 2, 0) circ.z(0) passmanager = PassManager() passmanager.append(CommutativeCancellation()) ccirc = passmanager.run(circ) self.assertEqual(Operator(circ), Operator(ccirc)) def test_basic_classical_wires(self): """Test that transpile runs without internal errors when dealing with commutable operations with classical controls. Regression test for gh-8553.""" original = QuantumCircuit(2, 1) original.x(0).c_if(original.cregs[0], 0) original.x(1).c_if(original.cregs[0], 0) # This transpilation shouldn't change anything, but it should succeed. At one point it was # triggering an internal logic error and crashing. transpiled = PassManager([CommutativeCancellation()]).run(original) self.assertEqual(original, transpiled) def test_simple_if_else(self): """Test that the pass is not confused by if-else.""" base_test1 = QuantumCircuit(3, 3) base_test1.x(1) base_test1.cx(0, 1) base_test1.x(1) base_test2 = QuantumCircuit(3, 3) base_test2.rz(0.1, 1) base_test2.rz(0.1, 1) test = QuantumCircuit(3, 3) test.h(0) test.x(0) test.rx(0.2, 0) test.measure(0, 0) test.x(0) test.if_else( (test.clbits[0], True), base_test1.copy(), base_test2.copy(), test.qubits, test.clbits ) expected = QuantumCircuit(3, 3) expected.h(0) expected.rx(np.pi + 0.2, 0) expected.measure(0, 0) expected.x(0) expected_test1 = QuantumCircuit(3, 3) expected_test1.cx(0, 1) expected_test2 = QuantumCircuit(3, 3) expected_test2.rz(0.2, 1) expected.if_else( (expected.clbits[0], True), expected_test1.copy(), expected_test2.copy(), expected.qubits, expected.clbits, ) passmanager = PassManager([CommutationAnalysis(), CommutativeCancellation()]) new_circuit = passmanager.run(test) self.assertEqual(new_circuit, expected) def test_nested_control_flow(self): """Test that the pass does not add barrier into nested control flow.""" level2_test = QuantumCircuit(2, 1) level2_test.cz(0, 1) level2_test.cz(0, 1) level2_test.cz(0, 1) level2_test.measure(0, 0) level1_test = QuantumCircuit(2, 1) level1_test.for_loop((0,), None, level2_test.copy(), level1_test.qubits, level1_test.clbits) level1_test.h(0) level1_test.h(0) level1_test.measure(0, 0) test = QuantumCircuit(2, 1) test.while_loop((test.clbits[0], True), level1_test.copy(), test.qubits, test.clbits) test.measure(0, 0) level2_expected = QuantumCircuit(2, 1) level2_expected.cz(0, 1) level2_expected.measure(0, 0) level1_expected = QuantumCircuit(2, 1) level1_expected.for_loop( (0,), None, level2_expected.copy(), level1_expected.qubits, level1_expected.clbits ) level1_expected.measure(0, 0) expected = QuantumCircuit(2, 1) expected.while_loop( (expected.clbits[0], True), level1_expected.copy(), expected.qubits, expected.clbits ) expected.measure(0, 0) passmanager = PassManager([CommutationAnalysis(), CommutativeCancellation()]) new_circuit = passmanager.run(test) self.assertEqual(new_circuit, expected) def test_cancellation_not_crossing_block_boundary(self): """Test that the pass does cancel gates across control flow op block boundaries.""" test1 = QuantumCircuit(2, 2) test1.x(1) with test1.if_test((0, False)): test1.cx(0, 1) test1.x(1) passmanager = PassManager([CommutationAnalysis(), CommutativeCancellation()]) new_circuit = passmanager.run(test1) self.assertEqual(new_circuit, test1) def test_cancellation_not_crossing_between_blocks(self): """Test that the pass does cancel gates in different control flow ops.""" test2 = QuantumCircuit(2, 2) with test2.if_test((0, True)): test2.x(1) with test2.if_test((0, True)): test2.cx(0, 1) test2.x(1) passmanager = PassManager([CommutationAnalysis(), CommutativeCancellation()]) new_circuit = passmanager.run(test2) self.assertEqual(new_circuit, test2) if __name__ == "__main__": unittest.main()
https://github.com/sergiogh/qpirates-qiskit-notebooks
sergiogh
# Playing with models from qiskit.aqua.algorithms import VQC from qiskit.aqua.components.optimizers import SPSA import matplotlib.pyplot as plt import matplotlib.patches as mpatches from qiskit.ml.datasets import ad_hoc_data, wine # Data to play with # ad_hoc_data - returns ad hoc dataset - ad_hoc_data(training_size, test_size, n, gap, plot_data=False) # sample_ad_hoc_data - returns sample ad hoc data # breast_cancer - returns breast cancer dataset # digits - returns digits dataset # gaussian - returns gaussian dataset # iris - returns iris dataset # wine - returns wine dataset - wine(training_size, test_size, n, plot_data=False) _, training_data, test_data, _ = ad_hoc_data(10, 10, 2, 0.2) markers = ['o', '^'] plt.figure(figsize=(12,6)) plt.title('Training (full) and test (hollow) data') for marker, (label, data) in zip(markers, training_data.items()): plt.scatter(data[:,0], data[:,1], color='tab:blue', label=label, s=60, marker=marker) for marker, (label, data) in zip(markers, test_data.items()): plt.scatter(data[:,0], data[:,1], facecolor='', edgecolor='tab:blue', s=60, marker=marker) plt.legend(loc='best'); _, wine_training_data, wine_data, _ = wine(20, 20, 3) markers = ['o', '^'] plt.figure(figsize=(12,6)) plt.title('Training (full) and test (hollow) data') for marker, (label, data) in zip(markers, wine_training_data.items()): plt.scatter(data[:,0], data[:,1], color='tab:blue', label=label, s=60, marker=marker) for marker, (label, data) in zip(markers, wine_data.items()): plt.scatter(data[:,0], data[:,1], facecolor='', edgecolor='tab:blue', s=60, marker=marker) plt.legend(loc='best'); # Choose which trainint data test_data = wine_data training_data = wine_training_data from qiskit.circuit.library.data_preparation import ZZFeatureMap # can also drop .data_preparation data_preparation = ZZFeatureMap(2) data_preparation.draw(output='mpl') from qiskit.circuit.library.n_local import RealAmplitudes # can also drop .n_local classifier = RealAmplitudes(2) classifier.draw(output='mpl') optimizer = SPSA(max_trials=200) vqc = VQC(optimizer, data_preparation, classifier, training_data) from qiskit import Aer from qiskit.aqua import QuantumInstance backend = Aer.get_backend('qasm_simulator') result = vqc.run(backend) print('Loss:', result['training_loss']) points_a = test_data['A'] points_b = test_data['B'] _, predicted_a = vqc.predict(points_a) _, predicted_b = vqc.predict(points_b) print('Score:', sum(predicted_a == 0) + sum(predicted_b == 1), '/', (len(predicted_a) + len(predicted_b))) plt.figure(figsize=(12,6)) plt.title('Correctly predicted') plt.scatter(points_a[:,0], points_a[:,1], s=60, marker='o', color=['tab:green' if label == 0 else 'tab:red' for label in predicted_a]) plt.scatter(points_b[:,0], points_b[:,1], s=60, marker='^', color=['tab:green' if label == 1 else 'tab:red' for label in predicted_b]) for marker, (label, data) in zip(markers, training_data.items()): plt.scatter(data[:,0], data[:,1], color='tab:blue', label=label, s=60, marker=marker) train = mpatches.Patch(color='tab:blue', label='training data') correct = mpatches.Patch(color='tab:green', label='correctly labeled') wrong = mpatches.Patch(color='tab:red', label='wrongly labeled') plt.legend(handles=[train, correct, wrong])
https://github.com/victor-onofre/Quantum_Algorithms
victor-onofre
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ, BasicAer import math from qiskit.visualization import plot_histogram backend = BasicAer.get_backend('statevector_simulator') from wordcloud import WordCloud import numpy as np import pandas as pd # primary data structure library import matplotlib.pyplot as plt reg = QuantumRegister(8, name='reg') # The quantum register of the qubits, in this case 8 qubits reg_c = ClassicalRegister(8, name='regc') # Where the measurements of the qubits will be saved qc = QuantumCircuit(reg, reg_c) qc.h(reg) # Apply Hadamard gate to put it into a superposition of 0 and 1 all the qubits qc.measure(reg, reg_c) # read the result as a digital bit job = execute(qc, backend) # Execute the circuit in the statevector_simulator result = job.result() outputstate = result.get_statevector(qc, decimals=5) counts = result.get_counts(qc) #print(outputstate) qc.draw() state, value = list(counts.items())[0] # key is de state of the system after the measuremnt, for example '11100001' state number = int(state, 2) # The state is converted into a number ASCII_Character = chr(number) # The number in ASCII character print('The random number is:',number) print('The random ASCII character:',ASCII_Character) def Quantum_random_number_and_ASCII_Character_generator(n): reg = QuantumRegister(n, name='reg') # The quantum register of the n qubits reg_c = ClassicalRegister(n, name='regc')# Where the measurements of the qubits will be saved qc = QuantumCircuit(reg, reg_c) qc.h(reg) # put it into a superposition of 0 and 1 qc.measure(reg, reg_c) # read the result as a digital bit job = execute(qc, backend) result = job.result() counts = result.get_counts(qc) key, value = list(counts.items())[0] number = int(key, 2) ASCII_Character = chr(number) return ASCII_Character, number Quantum_random_number_and_ASCII_Character_generator(8)[0] # Resturns the ASCII Character Quantum_random_number_and_ASCII_Character_generator(8)[1] # Resturns the Random number L = [] num = [] counter = [] for x in range(800): string = Quantum_random_number_and_ASCII_Character_generator(8)[0] # ASCII_Character number = Quantum_random_number_and_ASCII_Character_generator(8)[1] # Random_number L.append(string) # Save the ASCII_Character in a the list "L" num.append(number) # Save the Random_number in a the list "number" counter.append(x) # Convert the list to a dataframe df1 = pd.DataFrame(counter, columns=['Counter']) df2 = pd.DataFrame(L, columns=['Random_Character']) df3 = pd.DataFrame(num, columns=['Random_Number']) #Join the results in a dataframe re = df1.join(df2) Quantum_Random = re.join(df3) Quantum_Random.head() Quantum_Random.plot(x='Counter', y='Random_Number', figsize=(25,6.5), xlabel='Iteration', ylabel='Randon Number', legend = False, grid = True, fontsize = 14) Quantum_Random['Random_Number'].describe() #generate the word cloud wordcloud = WordCloud(background_color='white').generate(' '.join(Quantum_Random['Random_Character'])) # display the word cloud fig = plt.figure() fig.set_figwidth(14) fig.set_figheight(18) plt.imshow(wordcloud, interpolation='bilinear') plt.axis('off') plt.show()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit q = QuantumRegister(1) c = ClassicalRegister(1) qc = QuantumCircuit(q, c) qc.h(q) qc.measure(q, c) qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'})
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ This module contains the definition of a base class for quantum fourier transforms. """ from abc import abstractmethod from qiskit import QuantumRegister, QuantumCircuit from qiskit.aqua import Pluggable, AquaError class QFT(Pluggable): """Base class for QFT. This method should initialize the module and its configuration, and use an exception if a component of the module is available. Args: configuration (dict): configuration dictionary """ @abstractmethod def __init__(self, *args, **kwargs): super().__init__() @classmethod def init_params(cls, params): qft_params = params.get(Pluggable.SECTION_KEY_QFT) kwargs = {k: v for k, v in qft_params.items() if k != 'name'} return cls(**kwargs) @abstractmethod def _build_matrix(self): raise NotImplementedError @abstractmethod def _build_circuit(self, qubits=None, circuit=None, do_swaps=True): raise NotImplementedError def construct_circuit(self, mode='circuit', qubits=None, circuit=None, do_swaps=True): """Construct the circuit. Args: mode (str): 'matrix' or 'circuit' qubits (QuantumRegister or qubits): register or qubits to build the circuit on. circuit (QuantumCircuit): circuit for construction. do_swaps (bool): include the swaps. Returns: The matrix or circuit depending on the specified mode. """ if mode == 'circuit': return self._build_circuit(qubits=qubits, circuit=circuit, do_swaps=do_swaps) elif mode == 'matrix': return self._build_matrix() else: raise AquaError('Unrecognized mode: {}.'.format(mode))
https://github.com/ShabaniLab/qiskit-hackaton-2019
ShabaniLab
import numpy as np from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister from ising_kitaev import initialize_chain, move_chain, rotate_to_measurement_basis, add_measurement zeeman_ferro = 0.01 zeeman_para = 10 initial_config = np.array([zeeman_ferro, zeeman_ferro, zeeman_ferro, zeeman_para]) final_config = np.array([zeeman_para, zeeman_ferro, zeeman_ferro, zeeman_ferro]) qreg = QuantumRegister(4) creg = ClassicalRegister(3) qcirc = QuantumCircuit(qreg, creg) initialize_chain(qcirc, qreg, initial_config, 'logical_one') qcirc.draw() move_chain(qcirc, qreg, initial_config, final_config, 0, 0.25, 0.25, 1, 5, method='both') qcirc.depth() rotate_to_measurement_basis(qcirc, qreg, [1, 2, 3]) add_measurement(qcirc, qreg, creg, [1, 2, 3]) from qiskit import Aer, execute backend = Aer.get_backend('qasm_simulator') job = execute(qcirc, backend, shots=2000) job.status() result = job.result() print(result.get_counts())
https://github.com/Wasiq-Malik/MaxCut-QAOA
Wasiq-Malik
# useful additional packages import matplotlib.pyplot as plt import matplotlib.axes as axes %matplotlib inline import numpy as np import networkx as nx import random from scipy.optimize import minimize try: import cirq except ImportError: print("installing cirq...") !pip install --quiet cirq import cirq print("installed cirq.") # Utility function to print a graph 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) edge_labels = nx.get_edge_attributes(G, 'weight') nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=edge_labels) n=5 # Number of nodes in graph # create a graph of n nodes G=nx.Graph() G.add_nodes_from(np.arange(0,n,1)) # edge are in the form (vertex u, vertex v, edge weight) edges=[(0,1,1.0),(0,2,5.0),(1,2,7.0),(1,3,2.0),(2,3,4.0), (3,4,3.0)] G.add_weighted_edges_from(edges) # create weighted edges in the graph # setup an example graph colors = ['r' for node in G.nodes()] pos = nx.spring_layout(G) draw_graph(G, colors, pos) # Computing the weight matrix for the example graph weight_matrix = np.zeros([n,n]) for i in range(n): for j in range(n): edge = G.get_edge_data(i,j,default=0) if edge != 0: weight_matrix[i,j] = edge['weight'] # running the brute force algorithm to find the max cut for the example graph best_cost_brute = best_sol_brute = 0 for bit_string in range(2**n): solution = [int(t) for t in reversed(list(bin(bit_string)[2:].zfill(n)))] # generate bit strings representing the possible cuts cost = 0 # calculate the cut value for current cut set for i in range(n): for j in range(n): cost = cost + weight_matrix[i,j]*solution[i]*(1-solution[j]) # if better solution found, save it if best_cost_brute < cost: best_cost_brute = cost best_sol_brute = solution print('bit string = ' + str(solution) + ' cut value = ' + str(cost)) # display the max cut solution colors = ['r' if best_sol_brute[i] == 0 else 'c' for i in range(n)] draw_graph(G, colors, pos) print('\nBest solution = ' + str(best_sol_brute) + ' cost = ' + str(best_cost_brute)) n=5 # Number of nodes in graph qubits = [cirq.GridQubit(0, i) for i in range(0, n)] G=nx.Graph() G.add_nodes_from(qubits) edges=[(qubits[0],qubits[1],1.0),(qubits[0],qubits[2],5.0),(qubits[1],qubits[2],7.0),(qubits[1],qubits[3],2.0),(qubits[2],qubits[3],4.0), (qubits[3],qubits[4],3.0)] G.add_weighted_edges_from(edges) colors = ['r' for node in G.nodes()] pos = nx.spring_layout(G) draw_graph(G, colors, pos) from cirq.contrib.svg import SVGCircuit import sympy # Depth for the QAOA m=2 # Number of qubits n=5 # repitions count for running the circuit rep=10_000 def create_circuit(params): m = len(params)//2 alphas = params[0:m] betas = params[m::] # Prepare equal superposition of qubits qaoa_circuit = cirq.Circuit(cirq.H.on_each(G.nodes())) # iterate over depth factor for qaoa for i in range(m): # insert the cost unitary for u, v, w in G.edges(data=True): qaoa_circuit.append(cirq.ZZ(u, v) ** (alphas[i] * w['weight'])) # insert the mixer unitary qaoa_circuit.append(cirq.Moment(cirq.X(qubit) ** betas[i] for qubit in G.nodes())) # apply measurements at the end of the circuit for qubit in G.nodes(): qaoa_circuit.append(cirq.measure(qubit)) return qaoa_circuit # create a circuit with random parameters qaoa_circuit = create_circuit(params=[float(random.randint(-314, 314))/float(100) for i in range(0, m*2)]) # display the qaoa circuit SVGCircuit(qaoa_circuit) from cirq.contrib.svg import SVGCircuit import sympy # Symbols for the rotation angles in the QAOA circuit. alpha = sympy.Symbol('alpha') beta = sympy.Symbol('beta') qaoa_circuit = cirq.Circuit( # Prepare equal superposition of qubits cirq.H.on_each(G.nodes()), # Do ZZ operations between neighbors u, v in the graph. Here, u is a qubit, # v is its neighboring qubit, and w is the weight between these qubits. (cirq.ZZ(u, v) ** (alpha * w['weight']) for (u, v, w) in G.edges(data=True)), # Apply X operations along all nodes of the graph. Again working_graph's # nodes are the working_qubits. Note here we use a moment # which will force all of the gates into the same line. cirq.Moment(cirq.X(qubit) ** beta for qubit in G.nodes()), # All relevant things can be computed in the computational basis. (cirq.measure(qubit) for qubit in G.nodes()), ) SVGCircuit(qaoa_circuit) def estimate_cost(graph, samples): """Estimate the cost function of the QAOA on the given graph using the provided computational basis bitstrings.""" cost_value = 0.0 # Loop over edge pairs and compute contribution. for u, v, w in graph.edges(data=True): u_samples = samples[str(u)] v_samples = samples[str(v)] # Determine if it was a +1 or -1 eigenvalue. u_signs = (-1)**u_samples v_signs = (-1)**v_samples term_signs = u_signs * v_signs # Add scaled term to total cost. term_val = np.mean(term_signs) * w['weight'] cost_value += term_val return -cost_value alpha_value = np.pi / 4 beta_value = np.pi / 2 sim = cirq.Simulator() sample_results = sim.sample( qaoa_circuit, params={alpha: alpha_value, beta: beta_value}, repetitions=20_000 ) print(f'Alpha = {round(alpha_value, 3)} Beta = {round(beta_value, 3)}') print(f'Estimated cost: {estimate_cost(G, sample_results)}') # Set the grid size = number of points in the interval [0, 2π). grid_size = 5 exp_values = np.empty((grid_size, grid_size)) par_values = np.empty((grid_size, grid_size, 2)) for i, alpha_value in enumerate(np.linspace(0, 2 * np.pi, grid_size)): for j, beta_value in enumerate(np.linspace(0, 2 * np.pi, grid_size)): samples = sim.sample( qaoa_circuit, params={alpha: alpha_value, beta: beta_value}, repetitions=20000 ) exp_values[i][j] = estimate_cost(G, samples) par_values[i][j] = alpha_value, beta_value def output_cut(S_partition): """Plot and output the graph cut information.""" # Generate the colors. coloring = [] for node in G: if node in S_partition: coloring.append('blue') else: coloring.append('red') # Get the weights edges = G.edges(data=True) weights = [w['weight'] for (u,v, w) in edges] nx.draw_circular( G, node_color=coloring, node_size=1000, with_labels=True, width=weights) plt.show() size = nx.cut_size(G, S_partition, weight='weight') print(f'Cut size: {size}') best_exp_index = np.unravel_index(np.argmax(exp_values), exp_values.shape) best_parameters = par_values[best_exp_index] print(f'Best control parameters: {best_parameters}') # Number of candidate cuts to sample. num_cuts = 100 candidate_cuts = sim.sample( qaoa_circuit, params={alpha: best_parameters[0], beta: best_parameters[1]}, repetitions=num_cuts ) # Variables to store best cut partitions and cut size. best_qaoa_S_partition = set() best_qaoa_T_partition = set() best_qaoa_cut_size = -np.inf # Analyze each candidate cut. for i in range(num_cuts): candidate = candidate_cuts.iloc[i] one_qubits = set(candidate[candidate==1].index) S_partition = set() T_partition = set() for node in G: if str(node) in one_qubits: # If a one was measured add node to S partition. S_partition.add(node) else: # Otherwise a zero was measured so add to T partition. T_partition.add(node) cut_size = nx.cut_size( G, S_partition, T_partition, weight='weight') # If you found a better cut update best_qaoa_cut variables. if cut_size > best_qaoa_cut_size: best_qaoa_cut_size = cut_size best_qaoa_S_partition = S_partition best_qaoa_T_partition = T_partition best_random_S_partition = set() best_random_T_partition = set() best_random_cut_size = -9999 # Randomly build candidate sets. for i in range(num_cuts): S_partition = set() T_partition = set() for node in G: if random.random() > 0.5: # If we flip heads add to S. S_partition.add(node) else: # Otherwise add to T. T_partition.add(node) cut_size = nx.cut_size( G, S_partition, T_partition, weight='weight') # If you found a better cut update best_random_cut variables. if cut_size > best_random_cut_size: best_random_cut_size = cut_size best_random_S_partition = S_partition best_random_T_partition = T_partition print('-----QAOA-----') output_cut(best_qaoa_S_partition) print('\n\n-----RANDOM-----') output_cut(best_random_S_partition)
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
mmetcalf14
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Advanced Clifford operations needed for randomized benchmarking """ import numpy as np import qiskit from . import Clifford try: import cPickle as pickle except ImportError: import pickle # ---------------------------------------------------------------------------------------- # Functions that convert to/from a Clifford object # ---------------------------------------------------------------------------------------- def compose_gates(cliff, gatelist): """ Add gates to a Clifford object from a list of gates. Args: cliff: A Clifford class object. gatelist: a list of gates. Returns: A Clifford class object. """ for op in gatelist: split = op.split() q1 = int(split[1]) if split[0] == 'v': cliff.v(q1) elif split[0] == 'w': cliff.w(q1) elif split[0] == 'x': cliff.x(q1) elif split[0] == 'y': cliff.y(q1) elif split[0] == 'z': cliff.z(q1) elif split[0] == 'cx': cliff.cx(q1, int(split[2])) elif split[0] == 'h': cliff.h(q1) elif split[0] == 's': cliff.s(q1) elif split[0] == 'sdg': cliff.sdg(q1) else: raise ValueError("Unknown gate type: ", op) return cliff def clifford_from_gates(num_qubits, gatelist): """ Generates a Clifford object from a list of gates. Args: num_qubits: the number of qubits for the Clifford. gatelist: a list of gates. Returns: A num-qubit Clifford class object. """ cliff = Clifford(num_qubits) new_cliff = compose_gates(cliff, gatelist) return new_cliff # -------------------------------------------------------- # Add gates to Cliffords # -------------------------------------------------------- def pauli_gates(gatelist, q, pauli): """adds a pauli gate on qubit q""" if pauli == 2: gatelist.append('x ' + str(q)) elif pauli == 3: gatelist.append('y ' + str(q)) elif pauli == 1: gatelist.append('z ' + str(q)) def h_gates(gatelist, q, h): """adds a hadamard gate or not on qubit q""" if h == 1: gatelist.append('h ' + str(q)) def v_gates(gatelist, q, v): """adds an axis-swap-gates on qubit q""" # rotation is V=HSHS = [[0,1],[1,1]] tableau # takes Z->X->Y->Z # V is of order 3, and two V-gates is W-gate, so: W=VV and WV=I if v == 1: gatelist.append('v ' + str(q)) elif v == 2: gatelist.append('w ' + str(q)) def cx_gates(gatelist, ctrl, tgt): """adds a controlled=x gates""" gatelist.append('cx ' + str(ctrl) + ' ' + str(tgt)) # -------------------------------------------------------- # Create a 1 or 2 Qubit Clifford based on a unique index # -------------------------------------------------------- def clifford1_gates(idx: int): """ Make a single qubit Clifford gate. Args: idx: the index (mod 24) of a single qubit Clifford. Returns: A single qubit Clifford gate. """ gatelist = [] # Cannonical Ordering of Cliffords 0,...,23 cannonicalorder = idx % 24 pauli = np.mod(cannonicalorder, 4) rotation = np.mod(cannonicalorder // 4, 3) h_or_not = np.mod(cannonicalorder // 12, 2) h_gates(gatelist, 0, h_or_not) v_gates(gatelist, 0, rotation) # do the R-gates pauli_gates(gatelist, 0, pauli) return gatelist def clifford2_gates(idx: int): """ Make a 2-qubit Clifford gate. Args: idx: the index (mod 11520) of a two-qubit Clifford. Returns: A 2-qubit Clifford gate. """ gatelist = [] cannon = idx % 11520 pauli = np.mod(cannon, 16) symp = cannon // 16 if symp < 36: # 1-qubit Cliffords Class r0 = np.mod(symp, 3) r1 = np.mod(symp // 3, 3) h0 = np.mod(symp // 9, 2) h1 = np.mod(symp // 18, 2) h_gates(gatelist, 0, h0) h_gates(gatelist, 1, h1) v_gates(gatelist, 0, r0) v_gates(gatelist, 1, r1) elif symp < 360: # CNOT-like Class symp = symp - 36 r0 = np.mod(symp, 3) r1 = np.mod(symp // 3, 3) r2 = np.mod(symp // 9, 3) r3 = np.mod(symp // 27, 3) h0 = np.mod(symp // 81, 2) h1 = np.mod(symp // 162, 2) h_gates(gatelist, 0, h0) h_gates(gatelist, 1, h1) v_gates(gatelist, 0, r0) v_gates(gatelist, 1, r1) cx_gates(gatelist, 0, 1) v_gates(gatelist, 0, r2) v_gates(gatelist, 1, r3) elif symp < 684: # iSWAP-like Class symp = symp - 360 r0 = np.mod(symp, 3) r1 = np.mod(symp // 3, 3) r2 = np.mod(symp // 9, 3) r3 = np.mod(symp // 27, 3) h0 = np.mod(symp // 81, 2) h1 = np.mod(symp // 162, 2) h_gates(gatelist, 0, h0) h_gates(gatelist, 1, h1) v_gates(gatelist, 0, r0) v_gates(gatelist, 1, r1) cx_gates(gatelist, 0, 1) cx_gates(gatelist, 1, 0) v_gates(gatelist, 0, r2) v_gates(gatelist, 1, r3) else: # SWAP Class symp = symp - 684 r0 = np.mod(symp, 3) r1 = np.mod(symp // 3, 3) h0 = np.mod(symp // 9, 2) h1 = np.mod(symp // 18, 2) h_gates(gatelist, 0, h0) h_gates(gatelist, 1, h1) v_gates(gatelist, 0, r0) v_gates(gatelist, 1, r1) cx_gates(gatelist, 0, 1) cx_gates(gatelist, 1, 0) cx_gates(gatelist, 0, 1) pauli_gates(gatelist, 0, np.mod(pauli, 4)) pauli_gates(gatelist, 1, pauli // 4) return gatelist # -------------------------------------------------------- # Create a 1 or 2 Qubit Clifford tables # -------------------------------------------------------- def clifford2_gates_table(): """ Generate a table of all 2-qubit Clifford gates. Args: None. Returns: A table of all 2-qubit Clifford gates. """ cliffords2 = {} for i in range(11520): circ = clifford2_gates(i) key = clifford_from_gates(2, circ).index() cliffords2[key] = circ return cliffords2 def clifford1_gates_table(): """ Generate a table of all 1-qubit Clifford gates. Args: None. Returns: A table of all 1-qubit Clifford gates. """ cliffords1 = {} for i in range(24): circ = clifford1_gates(i) key = clifford_from_gates(1, circ).index() cliffords1[key] = circ return cliffords1 def pickle_clifford_table(picklefile='cliffords2.pickle', num_qubits=2): """ Create pickled versions of the 1 and 2 qubit Clifford tables. Args: picklefile - pickle file name. num_qubits - number of qubits. Returns: A pickle file with the 1 and 2 qubit Clifford tables. """ cliffords = {} if num_qubits == 1: cliffords = clifford1_gates_table() elif num_qubits == 2: cliffords = clifford2_gates_table() else: raise ValueError( "number of qubits bigger than is not supported for pickle") with open(picklefile, "wb") as pf: pickle.dump(cliffords, pf) def load_clifford_table(picklefile='cliffords2.pickle'): """ Load pickled files of the tables of 1 and 2 qubit Clifford tables. Args: picklefile - pickle file name. Returns: A table of 1 and 2 qubit Clifford gates. """ with open(picklefile, "rb") as pf: return pickle.load(pf) # -------------------------------------------------------- # Main function that generates a random clifford gate # -------------------------------------------------------- def random_clifford_gates(num_qubits): """ Pick a random Clifford gate. Args: num_qubits: dimension of the Clifford. Returns: A 1 or 2 qubit Clifford gate. """ if num_qubits == 1: return clifford1_gates(np.random.randint(0, 24)) if num_qubits == 2: return clifford2_gates(np.random.randint(0, 11520)) raise ValueError("The number of qubits should be only 1 or 2") # -------------------------------------------------------- # Main function that calculates an inverse of a clifford gate # -------------------------------------------------------- def find_inverse_clifford_gates(num_qubits, gatelist): """ Find the inverse of a Clifford gate. Args: num_qubits: the dimension of the Clifford. gatelist: a Clifford gate. Returns: An inverse Clifford gate. """ if num_qubits in (1, 2): inv_gatelist = gatelist.copy() inv_gatelist.reverse() # replace v by w and w by v for i, _ in enumerate(inv_gatelist): split = inv_gatelist[i].split() if split[0] == 'v': inv_gatelist[i] = 'w ' + split[1] elif split[0] == 'w': inv_gatelist[i] = 'v ' + split[1] return inv_gatelist raise ValueError("The number of qubits should be only 1 or 2") # -------------------------------------------------------- # Returns the Clifford circuit in the form of a QuantumCircuit object # -------------------------------------------------------- def get_quantum_circuit(gatelist, num_qubits): """ Returns the Clifford circuit in the form of a QuantumCircuit object. Args: num_qubits: the dimension of the Clifford. gatelist: a Clifford gate. Returns: A QuantumCircuit object. """ qr = qiskit.QuantumRegister(num_qubits) qc = qiskit.QuantumCircuit(qr) for op in gatelist: split = op.split() op_names = [split[0]] # temporary correcting the ops name since QuantumCircuit has no # attributes 'v' or 'w' yet: if op_names == ['v']: op_names = ['sdg', 'h'] elif op_names == ['w']: op_names = ['h', 's'] qubits = [qr[int(x)] for x in split[1:]] for sub_op in op_names: operation = eval('qiskit.QuantumCircuit.' + sub_op) operation(qc, *qubits) return qc
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
mmetcalf14
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/qiskit-community/qiskit-translations-staging
qiskit-community
# If you introduce a list with less colors than bars, the color of the bars will # alternate following the sequence from the list. import numpy as np from qiskit.quantum_info import DensityMatrix from qiskit import QuantumCircuit from qiskit.visualization import plot_state_paulivec qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc = QuantumCircuit(2) qc.h([0, 1]) qc.cz(0, 1) qc.ry(np.pi/3, 0) qc.rx(np.pi/5, 1) matrix = DensityMatrix(qc) plot_state_paulivec(matrix, color=['crimson', 'midnightblue', 'seagreen'])
https://github.com/Qiskit/qiskit-transpiler-service
Qiskit
# -*- coding: utf-8 -*- # (C) Copyright 2024 IBM. All Rights Reserved. # # 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. """Routing and Layout selection with AI""" # import torch # torch.set_num_threads(1) import numpy as np from qiskit import ClassicalRegister, QuantumCircuit from qiskit.converters import circuit_to_dag, dag_to_circuit from qiskit.transpiler import CouplingMap, TranspilerError from qiskit.transpiler.basepasses import TransformationPass from qiskit.transpiler.layout import Layout from qiskit_transpiler_service.wrappers import AIRoutingAPI class AIRouting(TransformationPass): """AIRouting(backend_name: str | None = None, coupling_map: list[list[int]] | None = None, optimization_level: int = 2, layout_mode: str = "OPTIMIZE") The `AIRouting` pass acts both as a layout stage and a routing stage. :param backend_name: Name of the backend used for doing the transpilation. :type backend_name: str, optional :param coupling_map: A list of pairs that represents physical links between qubits. :type coupling_map: list[list[int]], optional :param optimization_level: With a range from 1 to 3, determines the computational effort to spend in the process (higher usually gives better results but takes longer), defaults to 2. :type optimization_level: int :param layout_mode: Specifies how to handle the layout selection. There are 3 layout modes: keep (respects the layout set by the previous transpiler passes), improve (uses the layout set by the previous transpiler passes as a starting point) and optimize (ignores previous layout selections), defaults to `OPTIMIZE`. :type layout_mode: str """ def __init__( self, backend_name=None, coupling_map=None, optimization_level: int = 2, layout_mode: str = "OPTIMIZE", ): super().__init__() if backend_name is not None and coupling_map is not None: raise ValueError( f"ERROR. Both backend_name and coupling_map were specified as options. Please just use one of them." ) if backend_name is not None: self.backend = backend_name elif coupling_map is not None: if isinstance(coupling_map, CouplingMap): self.backend = list(coupling_map.get_edges()) elif isinstance(coupling_map, list): self.backend = coupling_map else: raise ValueError( f"ERROR. coupling_map should either be a list of int tuples or a Qiskit CouplingMap object." ) else: raise ValueError(f"ERROR. Either backend_name OR coupling_map must be set.") self.optimization_level = optimization_level if layout_mode is not None and layout_mode.upper() not in [ "KEEP", "OPTIMIZE", "IMPROVE", ]: raise ValueError( f"ERROR. Unknown ai_layout_mode: {layout_mode}. Valid modes: 'KEEP', 'OPTIMIZE', 'IMPROVE'" ) self.layout_mode = layout_mode.upper() self.service = AIRoutingAPI() def run(self, dag): """Run the AIRouting pass on `dag`. Args: dag (DAGCircuit): the directed acyclic graph to be mapped. Returns: DAGCircuit: A dag mapped to be compatible with the coupling_map. Raises: TranspilerError: if the coupling map or the layout are not compatible with the DAG, or if the coupling_map=None """ if len(dag.qregs) != 1 or dag.qregs.get("q", None) is None: raise TranspilerError("AIRouting runs on physical circuits only") # Pass dag to circuit for sending to AIRouting qc = dag_to_circuit(dag) # Remove measurements before sending to AIRouting # TODO: Fix this for mid-circuit measurements cregs = [] measurements = [] if len(qc.cregs) > 0: cregs = qc.cregs.copy() measurements = [g for g in qc if g.operation.name == "measure"] qc.remove_final_measurements(inplace=True) routed_qc, init_layout, final_layout = self.service.routing( qc, self.backend, self.optimization_level, False, self.layout_mode, ) # TODO: Improve this nq = max(init_layout) + 1 routed_qc = QuantumCircuit(nq).compose( routed_qc, qubits=range(routed_qc.num_qubits) ) # Restore final measurements if they were removed if len(measurements) > 0: meas_qubits = [final_layout[g.qubits[0]._index] for g in measurements] routed_qc.barrier(meas_qubits) for creg in cregs: routed_qc.add_register(creg) for g, q in zip(measurements, meas_qubits): routed_qc.append(g.operation, qargs=(q,), cargs=g.clbits) # Pass routed circuit to dag # TODO: Improve this routed_dag = circuit_to_dag(routed_qc) if routed_qc.num_qubits > dag.num_qubits(): new_dag = copy_dag_metadata(dag, routed_dag) else: new_dag = dag.copy_empty_like() new_dag.compose(routed_dag) qubits = new_dag.qubits input_qubit_mapping = {q: i for i, q in enumerate(qubits)} full_initial_layout = init_layout + sorted( set(range(len(qubits))) - set(init_layout) ) full_final_layout = final_layout + list(range(len(final_layout), len(qubits))) full_final_layout_p = [ full_final_layout[i] for i in np.argsort(full_initial_layout) ] initial_layout_qiskit = Layout(dict(zip(full_initial_layout, qubits))) final_layout_qiskit = Layout(dict(zip(full_final_layout_p, qubits))) self.property_set["layout"] = initial_layout_qiskit self.property_set["original_qubit_indices"] = input_qubit_mapping self.property_set["final_layout"] = final_layout_qiskit return new_dag def add_measurements(circ, qubits): circ.add_register(ClassicalRegister(len(qubits))) circ.barrier() for i, q in enumerate(qubits): circ.measure(q, i) return circ def copy_dag_metadata(dag, target_dag): """Return a copy of self with the same structure but empty. That structure includes: * name and other metadata * global phase * duration * all the qubits and clbits, including the registers. Returns: DAGCircuit: An empty copy of self. """ target_dag.name = dag.name target_dag._global_phase = dag._global_phase target_dag.duration = dag.duration target_dag.unit = dag.unit target_dag.metadata = dag.metadata target_dag._key_cache = dag._key_cache return target_dag
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import random from qiskit.quantum_info import Statevector secret = random.randint(0,7) # the owner is randomly picked secret_string = format(secret, '03b') # format the owner in 3-bit string oracle = Statevector.from_label(secret_string) # let the oracle know the owner from qiskit.algorithms import AmplificationProblem problem = AmplificationProblem(oracle, is_good_state=secret_string) from qiskit.algorithms import Grover grover_circuits = [] for iteration in range(1,3): grover = Grover(iterations=iteration) circuit = grover.construct_circuit(problem) circuit.measure_all() grover_circuits.append(circuit) # Grover's circuit with 1 iteration grover_circuits[0].draw() # Grover's circuit with 2 iterations grover_circuits[1].draw() from qiskit_ibm_runtime import QiskitRuntimeService service = QiskitRuntimeService() backend = "ibmq_qasm_simulator" # use the simulator from qiskit_ibm_runtime import Sampler, Session with Session(service=service, backend=backend): sampler = Sampler() job = sampler.run(circuits=grover_circuits, shots=1000) result = job.result() print(result) from qiskit.tools.visualization import plot_histogram # Extract bit string with highest probability from results as the answer result_dict = result.quasi_dists[1].binary_probabilities() answer = max(result_dict, key=result_dict.get) print(f"As you can see, the quantum computer returned '{answer}' as the answer with highest probability.\n" "And the results with 2 iterations have higher probability than the results with 1 iteration." ) # Plot the results plot_histogram(result.quasi_dists, legend=['1 iteration', '2 iterations']) # Print the results and the correct answer. print(f"Quantum answer: {answer}") print(f"Correct answer: {secret_string}") print('Success!' if answer == secret_string else 'Failure!') import qiskit_ibm_runtime qiskit_ibm_runtime.version.get_version_info() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/ronitd2002/IBM-Quantum-challenge-2024
ronitd2002
import networkx as nx import numpy as np import plotly.graph_objects as go import matplotlib as mpl import pandas as pd from IPython.display import clear_output from plotly.subplots import make_subplots from matplotlib import pyplot as plt from qiskit import Aer from qiskit import QuantumCircuit from qiskit.visualization import plot_state_city from qiskit.algorithms.optimizers import COBYLA, SLSQP, ADAM from time import time from copy import copy from typing import List from qc_grader.graph_util import display_maxcut_widget, QAOA_widget, graphs mpl.rcParams['figure.dpi'] = 300 from qiskit.circuit import Parameter, ParameterVector #Parameters are initialized with a simple string identifier parameter_0 = Parameter('θ[0]') parameter_1 = Parameter('θ[1]') circuit = QuantumCircuit(1) #We can then pass the initialized parameters as the rotation angle argument to the Rx and Ry gates circuit.ry(theta = parameter_0, qubit = 0) circuit.rx(theta = parameter_1, qubit = 0) circuit.draw('mpl') parameter = Parameter('θ') circuit = QuantumCircuit(1) circuit.ry(theta = parameter, qubit = 0) circuit.rx(theta = parameter, qubit = 0) circuit.draw('mpl') #Set the number of layers and qubits n=3 num_layers = 2 #ParameterVectors are initialized with a string identifier and an integer specifying the vector length parameters = ParameterVector('θ', n*(num_layers+1)) circuit = QuantumCircuit(n, n) for layer in range(num_layers): #Appending the parameterized Ry gates using parameters from the vector constructed above for i in range(n): circuit.ry(parameters[n*layer+i], i) circuit.barrier() #Appending the entangling CNOT gates for i in range(n): for j in range(i): circuit.cx(j,i) circuit.barrier() #Appending one additional layer of parameterized Ry gates for i in range(n): circuit.ry(parameters[n*num_layers+i], i) circuit.barrier() circuit.draw('mpl') print(circuit.parameters) #Create parameter dictionary with random values to bind param_dict = {parameter: np.random.random() for parameter in parameters} print(param_dict) #Assign parameters using the assign_parameters method bound_circuit = circuit.assign_parameters(parameters = param_dict) bound_circuit.draw('mpl') new_parameters = ParameterVector('Ψ',9) new_circuit = circuit.assign_parameters(parameters = [k*new_parameters[i] for k in range(9)]) new_circuit.draw('mpl') #Run the circuit with assigned parameters on Aer's statevector simulator simulator = Aer.get_backend('statevector_simulator') result = simulator.run(bound_circuit).result() statevector = result.get_statevector(bound_circuit) plot_state_city(statevector) #The following line produces an error when run because 'circuit' still contains non-assigned parameters #result = simulator.run(circuit).result() for key in graphs.keys(): print(key) graph = nx.Graph() #Add nodes and edges graph.add_nodes_from(np.arange(0,6,1)) edges = [(0,1,2.0),(0,2,3.0),(0,3,2.0),(0,4,4.0),(0,5,1.0),(1,2,4.0),(1,3,1.0),(1,4,1.0),(1,5,3.0),(2,4,2.0),(2,5,3.0),(3,4,5.0),(3,5,1.0)] graph.add_weighted_edges_from(edges) graphs['custom'] = graph #Display widget display_maxcut_widget(graphs['custom']) def maxcut_cost_fn(graph: nx.Graph, bitstring: List[int]) -> float: """ Computes the maxcut cost function value for a given graph and cut represented by some bitstring Args: graph: The graph to compute cut values for bitstring: A list of integer values '0' or '1' specifying a cut of the graph Returns: The value of the cut """ #Get the weight matrix of the graph weight_matrix = nx.adjacency_matrix(graph).toarray() size = weight_matrix.shape[0] value = 0. #INSERT YOUR CODE TO COMPUTE THE CUT VALUE HERE for i in range(size): for j in range(size): value+= weight_matrix[i,j]*bitstring[i]*(1-bitstring[j]) return value def plot_maxcut_histogram(graph: nx.Graph) -> None: """ Plots a bar diagram with the values for all possible cuts of a given graph. Args: graph: The graph to compute cut values for """ num_vars = graph.number_of_nodes() #Create list of bitstrings and corresponding cut values bitstrings = ['{:b}'.format(i).rjust(num_vars, '0')[::-1] for i in range(2**num_vars)] values = [maxcut_cost_fn(graph = graph, bitstring = [int(x) for x in bitstring]) for bitstring in bitstrings] #Sort both lists by largest cut value values, bitstrings = zip(*sorted(zip(values, bitstrings))) #Plot bar diagram bar_plot = go.Bar(x = bitstrings, y = values, marker=dict(color=values, colorscale = 'plasma', colorbar=dict(title='Cut Value'))) fig = go.Figure(data=bar_plot, layout = dict(xaxis=dict(type = 'category'), width = 1500, height = 600)) fig.show() plot_maxcut_histogram(graph = graphs['custom']) from qc_grader import grade_lab2_ex1 bitstring = [1, 0, 1, 1, 0, 0] #DEFINE THE CORRECT MAXCUT BITSTRING HERE # Note that the grading function is expecting a list of integers '0' and '1' grade_lab2_ex1(bitstring) from qiskit_optimization import QuadraticProgram quadratic_program = QuadraticProgram('sample_problem') print(quadratic_program.export_as_lp_string()) quadratic_program.binary_var(name = 'x_0') quadratic_program.integer_var(name = 'x_1') quadratic_program.continuous_var(name = 'x_2', lowerbound = -2.5, upperbound = 1.8) quadratic = [[0,1,2],[3,4,5],[0,1,2]] linear = [10,20,30] quadratic_program.minimize(quadratic = quadratic, linear = linear, constant = -5) print(quadratic_program.export_as_lp_string()) def quadratic_program_from_graph(graph: nx.Graph) -> QuadraticProgram: """Constructs a quadratic program from a given graph for a MaxCut problem instance. Args: graph: Underlying graph of the problem. Returns: QuadraticProgram """ #Get weight matrix of graph weight_matrix = nx.adjacency_matrix(graph) shape = weight_matrix.shape size = shape[0] #Build qubo matrix Q from weight matrix W qubo_matrix = np.zeros((size, size)) qubo_vector = np.zeros(size) for i in range(size): for j in range(size): qubo_matrix[i, j] -= weight_matrix[i, j] for i in range(size): for j in range(size): qubo_vector[i] += weight_matrix[i,j] #INSERT YOUR CODE HERE quadratic_program=QuadraticProgram('sample_problem') for i in range(size): quadratic_program.binary_var(name='x_{}'.format(i)) quadratic_program.maximize(quadratic =qubo_matrix, linear = qubo_vector) return quadratic_program quadratic_program = quadratic_program_from_graph(graphs['custom']) print(quadratic_program.export_as_lp_string()) from qc_grader import grade_lab2_ex2 # Note that the grading function is expecting a quadratic program grade_lab2_ex2(quadratic_program) def qaoa_circuit(qubo: QuadraticProgram, p: int = 1): """ Given a QUBO instance and the number of layers p, constructs the corresponding parameterized QAOA circuit with p layers. Args: qubo: The quadratic program instance p: The number of layers in the QAOA circuit Returns: The parameterized QAOA circuit """ size = len(qubo.variables) qubo_matrix = qubo.objective.quadratic.to_array(symmetric=True) qubo_linearity = qubo.objective.linear.to_array() #Prepare the quantum and classical registers qaoa_circuit = QuantumCircuit(size,size) #Apply the initial layer of Hadamard gates to all qubits qaoa_circuit.h(range(size)) #Create the parameters to be used in the circuit gammas = ParameterVector('gamma', p) betas = ParameterVector('beta', p) #Outer loop to create each layer for i in range(p): #Apply R_Z rotational gates from cost layer #INSERT YOUR CODE HERE for j in range(size): qubo_matrix_sum_of_col = 0 for k in range(size): qubo_matrix_sum_of_col+= qubo_matrix[j][k] qaoa_circuit.rz(gammas[i]*(qubo_linearity[j]+qubo_matrix_sum_of_col),j) #Apply R_ZZ rotational gates for entangled qubit rotations from cost layer #INSERT YOUR CODE HERE for j in range(size): for k in range(size): if j!=k: qaoa_circuit.rzz(gammas[i]*qubo_matrix[j][k]*0.5,j,k) # Apply single qubit X - rotations with angle 2*beta_i to all qubits #INSERT YOUR CODE HERE for j in range(size): qaoa_circuit.rx(2*betas[i],j) return qaoa_circuit quadratic_program = quadratic_program_from_graph(graphs['custom']) custom_circuit = qaoa_circuit(qubo = quadratic_program) test = custom_circuit.assign_parameters(parameters=[1.0]*len(custom_circuit.parameters)) from qc_grader import grade_lab2_ex3 # Note that the grading function is expecting a quantum circuit grade_lab2_ex3(test) from qiskit.algorithms import QAOA from qiskit_optimization.algorithms import MinimumEigenOptimizer backend = Aer.get_backend('statevector_simulator') qaoa = QAOA(optimizer = ADAM(), quantum_instance = backend, reps=1, initial_point = [0.1,0.1]) eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa) quadratic_program = quadratic_program_from_graph(graphs['custom']) result = eigen_optimizer.solve(quadratic_program) print(result) def plot_samples(samples): """ Plots a bar diagram for the samples of a quantum algorithm Args: samples """ #Sort samples by probability samples = sorted(samples, key = lambda x: x.probability) #Get list of probabilities, function values and bitstrings probabilities = [sample.probability for sample in samples] values = [sample.fval for sample in samples] bitstrings = [''.join([str(int(i)) for i in sample.x]) for sample in samples] #Plot bar diagram sample_plot = go.Bar(x = bitstrings, y = probabilities, marker=dict(color=values, colorscale = 'plasma',colorbar=dict(title='Function Value'))) fig = go.Figure( data=sample_plot, layout = dict( xaxis=dict( type = 'category' ) ) ) fig.show() plot_samples(result.samples) graph_name = 'custom' quadratic_program = quadratic_program_from_graph(graph=graphs[graph_name]) trajectory={'beta_0':[], 'gamma_0':[], 'energy':[]} offset = 1/4*quadratic_program.objective.quadratic.to_array(symmetric = True).sum() + 1/2*quadratic_program.objective.linear.to_array().sum() def callback(eval_count, params, mean, std_dev): trajectory['beta_0'].append(params[1]) trajectory['gamma_0'].append(params[0]) trajectory['energy'].append(-mean + offset) optimizers = { 'cobyla': COBYLA(), 'slsqp': SLSQP(), 'adam': ADAM() } qaoa = QAOA(optimizer = optimizers['cobyla'], quantum_instance = backend, reps=1, initial_point = [6.2,1.8],callback = callback) eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa) result = eigen_optimizer.solve(quadratic_program) fig = QAOA_widget(landscape_file=f'./resources/energy_landscapes/{graph_name}.csv', trajectory = trajectory, samples = result.samples) fig.show() graph_name = 'custom' quadratic_program = quadratic_program_from_graph(graphs[graph_name]) #Create callback to record total number of evaluations max_evals = 0 def callback(eval_count, params, mean, std_dev): global max_evals max_evals = eval_count #Create empty lists to track values energies = [] runtimes = [] num_evals=[] #Run QAOA for different values of p for p in range(1,10): print(f'Evaluating for p = {p}...') qaoa = QAOA(optimizer = optimizers['cobyla'], quantum_instance = backend, reps=p, callback=callback) eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa) start = time() result = eigen_optimizer.solve(quadratic_program) runtimes.append(time()-start) num_evals.append(max_evals) #Calculate energy of final state from samples avg_value = 0. for sample in result.samples: avg_value += sample.probability*sample.fval energies.append(avg_value) #Create and display plots energy_plot = go.Scatter(x = list(range(1,10)), y =energies, marker=dict(color=energies, colorscale = 'plasma')) runtime_plot = go.Scatter(x = list(range(1,10)), y =runtimes, marker=dict(color=runtimes, colorscale = 'plasma')) num_evals_plot = go.Scatter(x = list(range(1,10)), y =num_evals, marker=dict(color=num_evals, colorscale = 'plasma')) fig = make_subplots(rows = 1, cols = 3, subplot_titles = ['Energy value', 'Runtime', 'Number of evaluations']) fig.update_layout(width=1800,height=600, showlegend=False) fig.add_trace(energy_plot, row=1, col=1) fig.add_trace(runtime_plot, row=1, col=2) fig.add_trace(num_evals_plot, row=1, col=3) clear_output() fig.show() def plot_qaoa_energy_landscape(graph: nx.Graph, cvar: float = None): num_shots = 1000 seed = 42 simulator = Aer.get_backend('qasm_simulator') simulator.set_options(seed_simulator = 42) #Generate circuit circuit = qaoa_circuit(qubo = quadratic_program_from_graph(graph), p=1) circuit.measure(range(graph.number_of_nodes()),range(graph.number_of_nodes())) #Create dictionary with precomputed cut values for all bitstrings cut_values = {} size = graph.number_of_nodes() for i in range(2**size): bitstr = '{:b}'.format(i).rjust(size, '0')[::-1] x = [int(bit) for bit in bitstr] cut_values[bitstr] = maxcut_cost_fn(graph, x) #Perform grid search over all parameters data_points = [] max_energy = None for beta in np.linspace(0,np.pi, 50): for gamma in np.linspace(0, 4*np.pi, 50): bound_circuit = circuit.assign_parameters([beta, gamma]) result = simulator.run(bound_circuit, shots = num_shots).result() statevector = result.get_counts(bound_circuit) energy = 0 measured_cuts = [] for bitstring, count in statevector.items(): measured_cuts = measured_cuts + [cut_values[bitstring]]*count if cvar is None: #Calculate the mean of all cut values energy = sum(measured_cuts)/num_shots else: #raise NotImplementedError() #INSERT YOUR CODE HERE measured_cuts = sorted(measured_cuts, reverse = True) for w in range(int(cvar*num_shots)): energy += measured_cuts[w]/int((cvar*num_shots)) #Update optimal parameters if max_energy is None or energy > max_energy: max_energy = energy optimum = {'beta': beta, 'gamma': gamma, 'energy': energy} #Update data data_points.append({'beta': beta, 'gamma': gamma, 'energy': energy}) #Create and display surface plot from data_points df = pd.DataFrame(data_points) df = df.pivot(index='beta', columns='gamma', values='energy') matrix = df.to_numpy() beta_values = df.index.tolist() gamma_values = df.columns.tolist() surface_plot = go.Surface( x=gamma_values, y=beta_values, z=matrix, coloraxis = 'coloraxis' ) fig = go.Figure(data = surface_plot) fig.show() #Return optimum return optimum graph = graphs['custom'] optimal_parameters = plot_qaoa_energy_landscape(graph = graph) print('Optimal parameters:') print(optimal_parameters) optimal_parameters = plot_qaoa_energy_landscape(graph = graph, cvar = 0.2) print(optimal_parameters) from qc_grader import grade_lab2_ex4 # Note that the grading function is expecting a python dictionary # with the entries 'beta', 'gamma' and 'energy' grade_lab2_ex4(optimal_parameters)
https://github.com/SunilBoopalan/quantum-chess-Qiskit
SunilBoopalan
import qiskit from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import Aer, execute from qiskit.quantum_info.operators import Operator from qiskit.extensions import UnitaryGate, Initialize from qiskit import IBMQ import math backend = Aer.get_backend('qasm_simulator') class quantum_obj: def __init__(self, pos, piece): self.piece = piece self.qnum = { '0': [pos, 1] } self.ent = [] def split(self, i_add, pos1, pos2): ## i_pos = self.qnum[i_add][0] self.qnum[i_add + '0'] = ["", 0] self.qnum[i_add + '1'] = ["", 0] self.qnum[i_add + '0'][0] = pos1 self.qnum[i_add + '1'][0] = pos2 self.qnum[i_add + '0'][1] = self.qnum[i_add][1]/2.0 #probability of split piece is half of original piece self.qnum[i_add + '1'][1] = self.qnum[i_add][1]/2.0 del self.qnum[i_add] def entangle_oneblock(self, i_add, pos1, obj, obj_add): # return quantumobj, pos of quantumobj from in_bw_pieces ''' 1 2 3 a | P Q _ b | _ _ _ c | _ _ _ a1 to a3 If Q is classical, move cannot be made. If Q is not classical, P and Q get entangled. Let P[P at a1] = x Let P[Q at a2] = y After the move, P[P at a3] = x * (1 - y) P[P at a1] = x * y ''' prob_blocked_piece = self.qnum[i_add][1] prob_blocking_piece = obj.qnum[obj_add][1] x = prob_blocked_piece y = prob_blocking_piece a = x*y # prob_not_moved = prob_blocked*prob_blocking b = x*(1-y) # prob_moved = prob_blocked_piece*(1-prob_blocking_piece) self.qnum[i_add + '0'] = ["", 0] self.qnum[i_add + '1'] = ["", 0] self.qnum[i_add + '0'][0] = self.qnum[i_add][0] self.qnum[i_add + '1'][0] = pos1 self.qnum[i_add + '0'][1] = a self.qnum[i_add + '1'][1] = b del self.qnum[i_add] last_state = obj_add[:-1] + str(int(not(int(obj_add[-1])))) obj.ent += [(self, i_add+'1', obj_add), (self, i_add+'0', last_state)] # make sure that obj is quantumobj while calling! self.ent += [(obj, obj_add, i_add+'1'), (obj, last_state, i_add+'0')] def entangle_twoblock(self, i_add, pos1, pos2, obj1, obj1_add, obj2, obj2_add): #change pos parameter to address # Applicable when # - both positions are blocked, so entanglement with 2 pieces # obj1 is blocking pos1 and obj2 is blocking pos2 # return quantumobj, pos of quantumobj from in_bw_pieces ''' 1 2 3 a | P Y R b | X _ _ c | Q _ _ a1 to split (c1, a3) If both Q and R are classical, no move. Else, weighted split. Let P[P at a1] = x Let P[Y at a2] = y Let P[X at b1] = z After the move, P[P at a1] = x * P[both Q and R are there] = x*y*z P[P at a3] = x * ( P[Q not at a2, R at b1] + 0.5 * P[Q, R not there] ) = x*(1-y)*z + 0.5*x*(1-y)*(1-z) P[P at c1] = x * ( P[Q at a2, R not at b1] + 0.5 * P[Q, R not there] ) = x*y*(1-z) + 0.5*x*(1-y)*(1-z) #check Total prob = xyz + xz - xyz + xy - xyz + x - xy - xz + xyz = x # These hold up even if P, Q, R are classical ''' ''' 1. ob1 there, ob2 there - not possible (0) 2. ob1 there, ob2 not there - p(ob1) 3. ob1 not there, ob2 there - p(ob2) 4. ob1 not there, ob2 not there - (1-p(ob1))(1-p(ob2)) at pos1 when ob1 not there - c3 + 0.5*c4 at pos2 when ob2 not there - c2 + 0.5*c4 at ipos when ob1, ob2 there - c1 ''' prob_i_pos = self.qnum[i_add][1] prob_ob1 = obj1.qnum[obj1_add][1] prob_ob2 = obj2.qnum[obj2_add][1] if obj1 == obj2: prob_pos1 = prob_i_pos*prob_ob2 + 0.5*prob_i_pos*(1 - prob_ob1 - prob_ob2) prob_pos2 = prob_i_pos*prob_ob1 + 0.5*prob_i_pos*(1 - prob_ob1 - prob_ob2) self.qnum[i_add + '0'] = ["", 0] self.qnum[i_add + '1'] = ["", 0] self.qnum[i_add + '0'][0] = pos1 self.qnum[i_add + '0'][1] = prob_pos1 self.qnum[i_add + '1'][0] = pos2 self.qnum[i_add + '1'][1] = prob_pos2 last_state1 = obj1_add[:-1] + str(int(not(int(obj1_add[-1])))) last_state2 = obj2_add[:-1] + str(int(not(int(obj2_add[-1])))) obj1.ent += [(self, i_add+'0', obj1_add), (self, i_add+'1', last_state1)] # obj1 cannot coexist with i_add+'0' obj2.ent += [(self, i_add+'1', obj2_add), (self, i_add+'0', last_state2)] # obj2 cannot coexist with i_add+'1' self.ent += [(obj1, obj1_add, i_add+'0'), (obj1, last_state1, i_add+'1'), (obj2, obj2_add, i_add+'1'), (obj2, last_state2, i_add+'0')] else: prob_unmoved = prob_i_pos*prob_ob1*prob_ob2 prob_pos1 = prob_i_pos*(1-prob_ob1)*prob_ob2 + 0.5*prob_i_pos*(1-prob_ob1)*(1-prob_ob2) prob_pos2 = prob_i_pos*prob_ob1*(1-prob_ob2) + 0.5*prob_i_pos*(1-prob_ob1)*(1-prob_ob2) # a(bc+c-bc+b-bc+1-b-c+bc) = a self.qnum[i_add + '00'] = ["", 0] self.qnum[i_add + '01'] = ["", 0] self.qnum[i_add + '10'] = ["", 0] self.qnum[i_add + '00'][0] = self.qnum[i_add][0] self.qnum[i_add + '01'][0] = pos1 self.qnum[i_add + '10'][0] = pos2 self.qnum[i_add + '00'][1] = prob_unmoved self.qnum[i_add + '01'][1] = prob_pos1 self.qnum[i_add + '10'][1] = prob_pos2 last_state1 = obj1_add[:-1] + str(int(not(int(obj1_add[-1])))) last_state2 = obj2_add[:-1] + str(int(not(int(obj2_add[-1])))) obj1.ent += [(self, i_add+'01', obj1_add), (self, i_add+'00', last_state1)] # obj1 cannot coexist with i_add+'01' obj2.ent += [(self, i_add+'10', obj2_add), (self, i_add+'00', last_state2)] # obj2 cannot coexist with i_add+'10' self.ent += [(obj1, obj1_add, i_add+'01'), (obj1, last_state1, i_add+'00'), (obj2, obj2_add, i_add+'10'), (obj2, last_state2, i_add+'00')] del self.qnum[i_add] # classical cases matter here ''' Scaling up probabilities: A - 0.5 - found to not exist B - 0.25 --> (after killing A) 0.5 = 0.25/(0.25+0.25) = B/(B+C) C - 0.25 --> (after killing A) 0.5 ''' def detangle(self, add, obj): probs = 0 all_states = list(self.qnum.keys()) for i in all_states: if i.startswith(add): print('delete', i) del self.qnum[i] else: probs += self.qnum[i][1] for i in self.qnum: self.qnum[i][1] /= probs # for i in range(len(self.ent)): # # nested entanglement to be handled here # if self.ent[i][0] == obj: # self.ent.remove(self.ent[i]) # 2block fixage # peek at nested entanglement (>2 degrees of ent across >2 pieces) def meas(self): ''' 1 2 3 a | X Q Y b | R _ _ c | Z _ W PIECE1 P(b2, 0) - 1 P.split(a2, b1) # final Q(a2, 00) - 0.5 R(b1, 01) - 0.5 PIECE2 W(c3, 00) - 1/2 X(a1, 01) - 1/2 X.split(a3, c1) # final W(c3, 00) - 1/2 X(a1, 0100) - 1/8 Y(a3, 0101) - 3/16 Z(c1, 0110) - 3/16 PIECE2 is killer How to measure? Cannot pad 00 with zeroes, last 2 qubits can be anything (don't care condition) 0000 - 1/4*1/2 0001 - 1/4*1/2 0010 - 1/4*1/2 0011 - 1/4*1/2 0100 - 1/8 0101 - 3/16 0110 - 3/16 0111 - 0 1 2 3 4 0 1 1/2 9/16 9/16 1 0 1/2 7/16 7/16 ''' level = 0 for i in self.qnum: if len(i) > level: level = len(i) # probs = [(0,0)]*level # for i in self.qnum: # for j in range(0, len(i)): # if self.qnum[j][0] == '0': # probs[j][0] += 1 # else: # probs[j][1] += 1 # all_add = self.qnum.keys() # n = len(all_add) # for i in range(0, n): # if all_add[i] ## print(level) ''' states: 000 001 010 011 100 101 110 111 poss_states: 00 01 11 100 101 ''' params = [0+0.j]*(2**(level-1)) states = [bin(i)[2:].zfill(level-1) for i in range(0, 2**(level-1))] poss_states = list(self.qnum.keys()) poss_states = [poss_states[i][1:] for i in range(0, len(poss_states))] for i in range(0, len(poss_states)): if(len(poss_states[i]) < level): index = states.index(poss_states[i] + '0'*(level - 1 - len(poss_states[i]))) params[index] = self.qnum['0'+poss_states[i]][1]**0.5 + 0.j #Initializing: qr = QuantumRegister(level-1) cr = ClassicalRegister(level-1) ckt = QuantumCircuit(qr, cr) ckt.initialize(params, [qr[i] for i in range(level-1)]) # init_gate = Initialize(params) # init_gate.label = "init" # ckt.append(init_gate, [i for i in range(level-1)]) ckt.measure_all() ## print(ckt) job = execute(ckt, backend, shots = 1) res = job.result() # print(res.get_counts()) final_state = list(res.get_counts().keys())[0][:(level-1)] ## print(final_state) ## print(all_add) while(True): if(final_state in poss_states): break final_state = final_state[:-1] final_state = '0' + final_state print('Final state of piece2 : ', final_state) ## detangle print("Piece2 ent list : ", self.ent) for i in range(len(self.ent)): if final_state.startswith(self.ent[i][2]): print("Piece1 ent list : ", self.ent[i][0].ent) print("Entangled guy's states : ", self.ent[i][0].qnum) self.ent[i][0].detangle(self.ent[i][1], self) print("Entangled guy's states : ", self.ent[i][0].qnum) final_pos = self.qnum[final_state][0] self.qnum.clear() self.ent.clear() self.qnum['0'] = [final_pos, 1] print("States of piece2 after measuring : ", self.qnum) # Test cases # ''' # 1 2 3 # a | _ _ Q # b | P R _ # c | _ S _ # P - 00 (0.5) # Q - 010 (0.25) # R - 0110 (0.125) # S - 0111 (0.125) # ''' # piece1 = quantum_obj("a2") # piece1.split("0", "b1", "b2") # piece1.split("01", "a3", "c1") # piece1.split("011", "b2", "c2") # ''' # 1 2 3 # a | Z _ Q # b | P R _ # c | X S Y # P - 00 (0.5) # Q - 010 (0.25) # R - 0110 (0.125) # S - 0111 (0.125) # X - 000 (1/16 = 0.0625) [ignore X since obj1==obj2 for this test case] # Y - 00 (0.5 + 0.5*(1-0.5-0.125) = 0.6875) # Z - 01 (0.125 + 0.5*(1-0.5-0.125) = 0.3125) # piece1.ent - [piece2, "0", "00"] # piece2.ent - [piece1, "00", "0"] # ''' # piece2 = quantum_obj("c1") # piece2.entangle_twoblock("0", "c3", "a1", piece1, "0111", piece1, "00") # piece2.meas() # ''' # to-do # - restore old addresses after detangle (reduce level) # - ent_twoblock obj1 = obj2 case: prob (both being there) = 0 [done] # - integrate with main code # '''
https://github.com/urwin419/QiskitChecker
urwin419
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) ### removed cx gate ### return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).issubset({0,1}): raise ValueError(f"message '{msg}' is invalid") if msg[1] == "1": qc.x(qubit) if msg[0] == "1": qc.z(qubit) return qc def decode_message(qc): qc.cx(1, 0) qc.h(1) return qc
https://github.com/urwin419/QiskitChecker
urwin419
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) qc.cx(1, 0) return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).issubset({0,1}): raise ValueError(f"message '{msg}' is invalid") if msg[1] == "1": qc.x(qubit) if msg[0] == "1": qc.z(qubit) ### added x gate ### qc.x(qubit) return qc def decode_message(qc): qc.cx(1, 0) ### added z gate ### qc.z(1) qc.h(1) return qc
https://github.com/quantumyatra/quantum_computing
quantumyatra
import numpy as np #from qiskit import * from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.visualization import plot_histogram, plot_gate_map, plot_circuit_layout from qiskit.tools.monitor import job_monitor import matplotlib.pyplot as plt %matplotlib inline IBMQ.load_account() provider = IBMQ.get_provider(group='open') ghz = QuantumCircuit(5,5) ghz.h(0) for idx in range(1,5): ghz.cx(0,idx) ghz.barrier(range(5)) ghz.measure(range(5), range(5)) ghz.draw(output='mpl') from qiskit import transpile import inspect inspect.signature(transpile) provider = IBMQ.get_provider(group='open') provider.backends(simulator=False) backend = provider.get_backend('ibmqx2') backend.configuration().basis_gates qc = QuantumCircuit(2,1) qc.h(0) qc.x(1) qc.cu1(np.pi/4, 0, 1) # cu1 is controlled u1 just like CNOT is controlled NOT qc.h(0) qc.measure([0], [0]) qc.draw(output='mpl') qc_basis = qc.decompose() qc_basis.draw(output='mpl') print(qc.depth(), ',', qc_basis.depth()) swap_circ = QuantumCircuit(2) display ( swap_circ.draw(output='mpl') ) swap_circ.swap(0, 1) display ( swap_circ.decompose().draw(output='mpl') ) ccx_circ = QuantumCircuit(3) ccx_circ.ccx(0, 1, 2) ccx_circ.decompose().draw(output='mpl') backend = provider.get_backend('ibmq_16_melbourne') plot_gate_map(backend, plot_directed=True) new_circ_lv0 = transpile(ghz, backend=backend, optimization_level=0) plot_circuit_layout(new_circ_lv0, backend ) backend = provider.get_backend('ibmq_16_melbourne') new_circ_lv3 = transpile(ghz, backend=backend, optimization_level=3) print('Depth:', new_circ_lv3.depth()) plot_circuit_layout(new_circ_lv3, backend) #job1 = execute(new_circ_lv3, backend) #job_monitor(job1) # Virtual -> physical # 0 -> 11 # 1 -> 12 # 2 -> 10 # 3 -> 2 # 4 -> 4 good_ghz = transpile(ghz, backend, initial_layout=[11,12,10,2,4]) print('Depth:', good_ghz.depth()) plot_circuit_layout(good_ghz, backend)
https://github.com/QPong/qpong-livestream
QPong
import numpy as np import pygame import qiskit from . import globals, resources, node_types GRID_WIDTH = 66 GRID_HEIGHT = 66 GATE_TILE_WIDTH = 43 GATE_TILE_HEIGHT = 45 LINE_WIDTH = 1 # navigation MOVE_LEFT = 1 MOVE_RIGHT = 2 MOVE_UP = 3 MOVE_DOWN = 4 class CircuitGrid(pygame.sprite.RenderPlain): """Enables interaction with circuit""" def __init__(self, xpos, ypos): self.xpos = xpos self.ypos = ypos self.selected_wire = 0 self.selected_column = 0 self.model = CircuitGridModel(globals.NUM_QUBITS,16) self.circuit_grid_background = CircuitGridBackground(self.model) self.circuit_grid_cursor = CircuitGridCursor() self.gate_tiles = np.empty((self.model.max_wires, self.model.max_columns), dtype = CircuitGridGate) for row_idx in range(self.model.max_wires): for col_idx in range(self.model.max_columns): self.gate_tiles[row_idx][col_idx] = \ CircuitGridGate(self.model, row_idx, col_idx) pygame.sprite.RenderPlain.__init__(self, self.circuit_grid_background, self.gate_tiles, self.circuit_grid_cursor) self.update() def update(self, *args): sprite_list = self.sprites() for sprite in sprite_list: sprite.update() self.circuit_grid_background.rect.left = self.xpos self.circuit_grid_background.rect.top = self.ypos for row_idx in range(self.model.max_wires): for col_idx in range(self.model.max_columns): self.gate_tiles[row_idx][col_idx].rect.centerx = \ self.xpos + GRID_WIDTH * (col_idx + 1.5) self.gate_tiles[row_idx][col_idx].rect.centery = \ self.ypos + GRID_HEIGHT * (row_idx + 1.0) self.highlight_selected_node(self.selected_wire, self.selected_column) def highlight_selected_node(self, wire_num, column_num): self.selected_wire = wire_num self.selected_column = column_num self.circuit_grid_cursor.rect.left = self.xpos + GRID_WIDTH * (self.selected_column + 1) self.circuit_grid_cursor.rect.top = self.ypos + GRID_HEIGHT * (self.selected_wire + 0.5) def move_to_adjacent_node(self, direction): if direction == MOVE_LEFT and self.selected_column > 0: self.selected_column -= 1 elif direction == MOVE_RIGHT and self.selected_column < self.model.max_columns - 1: self.selected_column += 1 elif direction == MOVE_UP and self.selected_wire > 0: self.selected_wire -= 1 elif direction == MOVE_DOWN and self.selected_wire < self.model.max_wires - 1: self.selected_wire += 1 self.highlight_selected_node(self.selected_wire, self.selected_column) def get_selected_node_gate_part(self): return self.model.get_node_gate_part(self.selected_wire, self.selected_column) def handle_input(self, key): match (key): case pygame.K_a: self.move_to_adjacent_node(MOVE_LEFT), case pygame.K_d: self.move_to_adjacent_node(MOVE_RIGHT), case pygame.K_w: self.move_to_adjacent_node(MOVE_UP), case pygame.K_s: self.move_to_adjacent_node(MOVE_DOWN), case pygame.K_x: self.handle_input_x(), case pygame.K_y: self.handle_input_y(), case pygame.K_z: self.handle_input_z(), case pygame.K_h: self.handle_input_h(), case pygame.K_SPACE: self.handle_input_delete(), case pygame.K_c: self.handle_input_ctrl(), case pygame.K_UP: self.handle_input_move_ctrl(MOVE_UP), case pygame.K_DOWN: self.handle_input_move_ctrl(MOVE_DOWN), case pygame.K_LEFT: self.handle_input_rotate(-np.pi / 8), case pygame.K_RIGHT: self.handle_input_rotate(np.pi / 8) def handle_input_x(self): selected_node_gate_part = self.get_selected_node_gate_part() if selected_node_gate_part == node_types.EMPTY: circuit_grid_node = CircuitGridNode(node_types.X) self.model.set_node(self.selected_wire, self.selected_column, circuit_grid_node) self.update() def handle_input_y(self): selected_node_gate_part = self.get_selected_node_gate_part() if selected_node_gate_part == node_types.EMPTY: circuit_grid_node = CircuitGridNode(node_types.Y) self.model.set_node(self.selected_wire, self.selected_column, circuit_grid_node) self.update() def handle_input_z(self): selected_node_gate_part = self.get_selected_node_gate_part() if selected_node_gate_part == node_types.EMPTY: circuit_grid_node = CircuitGridNode(node_types.Z) self.model.set_node(self.selected_wire, self.selected_column, circuit_grid_node) self.update() def handle_input_h(self): selected_node_gate_part = self.get_selected_node_gate_part() if selected_node_gate_part == node_types.EMPTY: circuit_grid_node = CircuitGridNode(node_types.H) self.model.set_node(self.selected_wire, self.selected_column, circuit_grid_node) self.update() def handle_input_delete(self): selected_node_gate_part = self.get_selected_node_gate_part() if selected_node_gate_part == node_types.X or \ selected_node_gate_part == node_types.Y or \ selected_node_gate_part == node_types.Z or \ selected_node_gate_part == node_types.H: self.delete_controls_for_gate(self.selected_wire, self.selected_column) if selected_node_gate_part == node_types.CTRL: gate_wire_num = \ self.model.get_gate_wire_for_control_node(self.selected_wire, self.selected_column) if gate_wire_num >= 0: self.delete_controls_for_gate(gate_wire_num, self.selected_column) elif selected_node_gate_part != node_types.SWAP and \ selected_node_gate_part != node_types.CTRL and \ selected_node_gate_part != node_types.TRACE: circuit_grid_node = CircuitGridNode(node_types.EMPTY) self.model.set_node(self.selected_wire, self.selected_column, circuit_grid_node) self.update() def handle_input_ctrl(self): selected_node_gate_part = self.get_selected_node_gate_part() if selected_node_gate_part == node_types.X or \ selected_node_gate_part == node_types.Y or \ selected_node_gate_part == node_types.Z or \ selected_node_gate_part == node_types.H: circuit_grid_node = self.model.get_node(self.selected_wire, self.selected_column) if circuit_grid_node.ctrl_a >= 0: # Gate already has a control qubit so remove it orig_ctrl_a = circuit_grid_node.ctrl_a circuit_grid_node.ctrl_a = -1 self.model.set_node(self.selected_wire, self.selected_column, circuit_grid_node) # Remove TRACE nodes for wire_num in range(min(self.selected_wire, orig_ctrl_a) + 1, max(self.selected_wire, orig_ctrl_a)): if self.model.get_node_gate_part(wire_num, self.selected_column) == node_types.TRACE: self.model.set_node(wire_num, self.selected_column, CircuitGridNode(node_types.EMPTY)) self.update() else: # Attempt to place a control qubit beginning with the wire above if self.selected_wire >= 0: if self.place_ctrl_qubit(self.selected_wire, self.selected_wire - 1) == -1: if self.selected_wire < self.model.max_wires: if self.place_ctrl_qubit(self.selected_wire, self.selected_wire + 1) == -1: print("Can't place control qubit") self.display_exceptional_condition() def handle_input_move_ctrl(self, direction): selected_node_gate_part = self.get_selected_node_gate_part() if selected_node_gate_part == node_types.X or \ selected_node_gate_part == node_types.Y or \ selected_node_gate_part == node_types.Z or \ selected_node_gate_part == node_types.H: circuit_grid_node = self.model.get_node(self.selected_wire, self.selected_column) if 0 <= circuit_grid_node.ctrl_a < self.model.max_wires: # Gate already has a control qubit so try to move it if direction == MOVE_UP: candidate_wire_num = circuit_grid_node.ctrl_a - 1 if candidate_wire_num == self.selected_wire: candidate_wire_num -= 1 else: candidate_wire_num = circuit_grid_node.ctrl_a + 1 if candidate_wire_num == self.selected_wire: candidate_wire_num += 1 if 0 <= candidate_wire_num < self.model.max_wires: if self.place_ctrl_qubit(self.selected_wire, candidate_wire_num) == candidate_wire_num: print("control qubit successfully placed on wire ", candidate_wire_num) if direction == MOVE_UP and candidate_wire_num < self.selected_wire: if self.model.get_node_gate_part(candidate_wire_num + 1, self.selected_column) == node_types.EMPTY: self.model.set_node(candidate_wire_num + 1, self.selected_column, CircuitGridNode(node_types.TRACE)) elif direction == MOVE_DOWN and candidate_wire_num > self.selected_wire: if self.model.get_node_gate_part(candidate_wire_num - 1, self.selected_column) == node_types.EMPTY: self.model.set_node(candidate_wire_num - 1, self.selected_column, CircuitGridNode(node_types.TRACE)) self.update() else: print("control qubit could not be placed on wire ", candidate_wire_num) def handle_input_rotate(self, radians): selected_node_gate_part = self.get_selected_node_gate_part() if selected_node_gate_part == node_types.X or \ selected_node_gate_part == node_types.Y or \ selected_node_gate_part == node_types.Z: circuit_grid_node = self.model.get_node(self.selected_wire, self.selected_column) circuit_grid_node.radians = (circuit_grid_node.radians + radians) % (2 * np.pi) self.model.set_node(self.selected_wire, self.selected_column, circuit_grid_node) self.update() def place_ctrl_qubit(self, gate_wire_num, candidate_ctrl_wire_num): """Attempt to place a control qubit on a wire. If successful, return the wire number. If not, return -1 """ if candidate_ctrl_wire_num < 0 or candidate_ctrl_wire_num >= self.model.max_wires: return -1 candidate_wire_gate_part = \ self.model.get_node_gate_part(candidate_ctrl_wire_num, self.selected_column) if candidate_wire_gate_part == node_types.EMPTY or \ candidate_wire_gate_part == node_types.TRACE: circuit_grid_node = self.model.get_node(gate_wire_num, self.selected_column) circuit_grid_node.ctrl_a = candidate_ctrl_wire_num self.model.set_node(gate_wire_num, self.selected_column, circuit_grid_node) self.model.set_node(candidate_ctrl_wire_num, self.selected_column, CircuitGridNode(node_types.EMPTY)) self.update() return candidate_ctrl_wire_num else: print("Can't place control qubit on wire: ", candidate_ctrl_wire_num) return -1 def delete_controls_for_gate(self, gate_wire_num, column_num): control_a_wire_num = self.model.get_node(gate_wire_num, column_num).ctrl_a control_b_wire_num = self.model.get_node(gate_wire_num, column_num).ctrl_b # Choose the control wire (if any exist) furthest away from the gate wire control_a_wire_distance = 0 control_b_wire_distance = 0 if control_a_wire_num >= 0: control_a_wire_distance = abs(control_a_wire_num - gate_wire_num) if control_b_wire_num >= 0: control_b_wire_distance = abs(control_b_wire_num - gate_wire_num) control_wire_num = -1 if control_a_wire_distance > control_b_wire_distance: control_wire_num = control_a_wire_num elif control_a_wire_distance < control_b_wire_distance: control_wire_num = control_b_wire_num if control_wire_num >= 0: for wire_idx in range(min(gate_wire_num, control_wire_num), max(gate_wire_num, control_wire_num) + 1): print("Replacing wire ", wire_idx, " in column ", column_num) circuit_grid_node = CircuitGridNode(node_types.EMPTY) self.model.set_node(wire_idx, column_num, circuit_grid_node) class CircuitGridBackground(pygame.sprite.Sprite): """Background for circuit grid""" def __init__(self, circuit_grid_model): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface([GRID_WIDTH * (circuit_grid_model.max_columns + 2), GRID_HEIGHT * (circuit_grid_model.max_wires + 1)]) self.image.convert() self.image.fill(globals.WHITE) self.rect = self.image.get_rect() pygame.draw.rect(self.image, globals.BLACK, self.rect, LINE_WIDTH) for wire_num in range(circuit_grid_model.max_wires): pygame.draw.line(self.image, globals.BLACK, (GRID_WIDTH * 0.5, (wire_num + 1) * GRID_HEIGHT), (self.rect.width - (GRID_WIDTH * 0.5), (wire_num + 1) * GRID_HEIGHT), LINE_WIDTH) class CircuitGridGate(pygame.sprite.Sprite): """Images for nodes""" def __init__(self, circuit_grid_model, wire_num, column_num): pygame.sprite.Sprite.__init__(self) self.circuit_grid_model = circuit_grid_model self.wire_num = wire_num self.column_num = column_num self.update() def update(self): node_type = self.circuit_grid_model.get_node_gate_part(self.wire_num, self.column_num) if node_type == node_types.H: self.image, self.rect = resources.load_image('gates/h_gate.png', -1) elif node_type == node_types.X: node = self.circuit_grid_model.get_node(self.wire_num, self.column_num) if node.ctrl_a >= 0 or node.ctrl_b >= 0: if self.wire_num > max(node.ctrl_a, node.ctrl_b): self.image, self.rect = resources.load_image('gates/not_gate_below_ctrl.png', -1) else: self.image, self.rect = resources.load_image('gates/not_gate_above_ctrl.png', -1) elif node.radians != 0: self.image, self.rect = resources.load_image('gates/rx_gate.png', -1) self.rect = self.image.get_rect() pygame.draw.arc(self.image, globals.MAGENTA, self.rect, 0, node.radians % (2 * np.pi), 6) pygame.draw.arc(self.image, globals.MAGENTA, self.rect, node.radians % (2 * np.pi), 2 * np.pi, 1) else: self.image, self.rect = resources.load_image('gates/x_gate.png', -1) elif node_type == node_types.Y: node = self.circuit_grid_model.get_node(self.wire_num, self.column_num) if node.radians != 0: self.image, self.rect = resources.load_image('gates/ry_gate.png', -1) self.rect = self.image.get_rect() pygame.draw.arc(self.image, globals.MAGENTA, self.rect, 0, node.radians % (2 * np.pi), 6) pygame.draw.arc(self.image, globals.MAGENTA, self.rect, node.radians % (2 * np.pi), 2 * np.pi, 1) else: self.image, self.rect = resources.load_image('gates/y_gate.png', -1) elif node_type == node_types.Z: node = self.circuit_grid_model.get_node(self.wire_num, self.column_num) if node.radians != 0: self.image, self.rect = resources.load_image('gates/rz_gate.png', -1) self.rect = self.image.get_rect() pygame.draw.arc(self.image, globals.MAGENTA, self.rect, 0, node.radians % (2 * np.pi), 6) pygame.draw.arc(self.image, globals.MAGENTA, self.rect, node.radians % (2 * np.pi), 2 * np.pi, 1) else: self.image, self.rect = resources.load_image('gates/z_gate.png', -1) elif node_type == node_types.S: self.image, self.rect = resources.load_image('gates/s_gate.png', -1) elif node_type == node_types.SDG: self.image, self.rect = resources.load_image('gates/sdg_gate.png', -1) elif node_type == node_types.T: self.image, self.rect = resources.load_image('gates/t_gate.png', -1) elif node_type == node_types.TDG: self.image, self.rect = resources.load_image('gates/tdg_gate.png', -1) elif node_type == node_types.IDEN: self.image, self.rect = resources.load_image('gates/iden_gate.png', -1) elif node_type == node_types.CTRL: if self.wire_num > \ self.circuit_grid_model.get_gate_wire_for_control_node(self.wire_num, self.column_num): self.image, self.rect = resources.load_image('gates/ctrl_gate_bottom_wire.png', -1) else: self.image, self.rect = resources.load_image('gates/ctrl_gate_top_wire.png', -1) elif node_type == node_types.TRACE: self.image, self.rect = resources.load_image('gates/trace_gate.png', -1) elif node_type == node_types.SWAP: self.image, self.rect = resources.load_image('gates/swap_gate.png', -1) else: self.image = pygame.Surface([GATE_TILE_WIDTH, GATE_TILE_HEIGHT]) self.image.set_alpha(0) self.rect = self.image.get_rect() self.image.convert() class CircuitGridCursor(pygame.sprite.Sprite): """Cursor to highlight current grid node""" def __init__(self): pygame.sprite.Sprite.__init__(self) self.image, self.rect = resources.load_image('circuit-grid-cursor.png') self.image.convert_alpha() class CircuitGridModel(): """Grid-based model that is built when user interacts with circuit""" def __init__(self, max_wires, max_columns): self.max_wires = max_wires self.max_columns = max_columns self.nodes = np.empty((max_wires, max_columns), dtype = CircuitGridNode) def __str__(self): retval = '' for wire_num in range(self.max_wires): retval += '\n' for column_num in range(self.max_columns): retval += str(self.get_node_gate_part(wire_num, column_num)) + ', ' return 'CircuitGridModel: ' + retval def set_node(self, wire_num, column_num, circuit_grid_node): self.nodes[wire_num][column_num] = \ CircuitGridNode(circuit_grid_node.node_type, circuit_grid_node.radians, circuit_grid_node.ctrl_a, circuit_grid_node.ctrl_b, circuit_grid_node.swap) def get_node(self, wire_num, column_num): return self.nodes[wire_num][column_num] def get_node_gate_part(self, wire_num, column_num): requested_node = self.nodes[wire_num][column_num] if requested_node and requested_node.node_type != node_types.EMPTY: # Node is occupied so return its gate return requested_node.node_type else: # Check for control nodes from gates in other nodes in this column nodes_in_column = self.nodes[:, column_num] for idx in range(self.max_wires): if idx != wire_num: other_node = nodes_in_column[idx] if other_node: if other_node.ctrl_a == wire_num or other_node.ctrl_b == wire_num: return node_types.CTRL elif other_node.swap == wire_num: return node_types.SWAP return node_types.EMPTY def get_gate_wire_for_control_node(self, control_wire_num, column_num): """Get wire for gate that belongs to a control node on the given wire""" gate_wire_num = -1 nodes_in_column = self.nodes[:, column_num] for wire_idx in range(self.max_wires): if wire_idx != control_wire_num: other_node = nodes_in_column[wire_idx] if other_node: if other_node.ctrl_a == control_wire_num or \ other_node.ctrl_b == control_wire_num: gate_wire_num = wire_idx print("Found gate: ", self.get_node_gate_part(gate_wire_num, column_num), " on wire: " , gate_wire_num) return gate_wire_num def compute_circuit(self): qr = qiskit.QuantumRegister(self.max_wires, 'q') qc = qiskit.QuantumCircuit(qr) for column_num in range(self.max_columns): for wire_num in range(self.max_wires): node = self.nodes[wire_num][column_num] if node: if node.node_type == node_types.IDEN: # Identity gate qc.i(qr[wire_num]) elif node.node_type == node_types.X: if node.radians == 0: if node.ctrl_a != -1: if node.ctrl_b != -1: # Toffoli gate qc.ccx(qr[node.ctrl_a], qr[node.ctrl_b], qr[wire_num]) else: # Controlled X gate qc.cx(qr[node.ctrl_a], qr[wire_num]) else: # Pauli-X gate qc.x(qr[wire_num]) else: # Rotation around X axis qc.rx(node.radians, qr[wire_num]) elif node.node_type == node_types.Y: if node.radians == 0: if node.ctrl_a != -1: # Controlled Y gate qc.cy(qr[node.ctrl_a], qr[wire_num]) else: # Pauli-Y gate qc.y(qr[wire_num]) else: # Rotation around Y axis qc.ry(node.radians, qr[wire_num]) elif node.node_type == node_types.Z: if node.radians == 0: if node.ctrl_a != -1: # Controlled Z gate qc.cz(qr[node.ctrl_a], qr[wire_num]) else: # Pauli-Z gate qc.z(qr[wire_num]) else: if node.ctrl_a != -1: # Controlled rotation around the Z axis qc.crz(node.radians, qr[node.ctrl_a], qr[wire_num]) else: # Rotation around Z axis qc.rz(node.radians, qr[wire_num]) elif node.node_type == node_types.S: # S gate qc.s(qr[wire_num]) elif node.node_type == node_types.SDG: # S dagger gate qc.sdg(qr[wire_num]) elif node.node_type == node_types.T: # T gate qc.t(qr[wire_num]) elif node.node_type == node_types.TDG: # T dagger gate qc.tdg(qr[wire_num]) elif node.node_type == node_types.H: if node.ctrl_a != -1: # Controlled Hadamard qc.ch(qr[node.ctrl_a], qr[wire_num]) else: # Hadamard gate qc.h(qr[wire_num]) elif node.node_type == node_types.SWAP: if node.ctrl_a != -1: # Controlled Swap qc.cswap(qr[node.ctrl_a], qr[wire_num], qr[node.swap]) else: # Swap gate qc.swap(qr[wire_num], qr[node.swap]) return qc class CircuitGridNode(): """Represents a node in the circuit grid""" def __init__(self, node_type, radians=0.0, ctrl_a=-1, ctrl_b=-1, swap=-1): self.node_type = node_type self.radians = radians self.ctrl_a = ctrl_a self.ctrl_b = ctrl_b self.swap = swap def __str__(self): string = 'type: ' + str(self.node_type) string += ', radians: ' + str(self.radians) if self.radians != 0 else '' string += ', ctrl_a: ' + str(self.ctrl_a) if self.ctrl_a != -1 else '' string += ', ctrl_b: ' + str(self.ctrl_b) if self.ctrl_b != -1 else '' return string
https://github.com/zapata-engineering/orquestra-qiskit
zapata-engineering
################################################################################ # © Copyright 2020-2022 Zapata Computing Inc. ################################################################################ from typing import Dict, Optional, Tuple import numpy as np import qiskit.providers.aer.noise as AerNoise from qiskit.providers.aer.noise import ( NoiseModel, amplitude_damping_error, pauli_error, phase_amplitude_damping_error, phase_damping_error, ) from qiskit.quantum_info import Kraus from qiskit.transpiler import CouplingMap from .._get_provider import get_provider def get_qiskit_noise_model( device_name: str, hub: str = "ibm-q", group: str = "open", project: str = "main", api_token: Optional[str] = None, ) -> Tuple[NoiseModel, list]: """Get a qiskit noise model to use noisy simulations with a qiskit simulator Args: device_name: The name of the device trying to be emulated hub: The ibmq hub (see qiskit documentation) group: The ibmq group (see qiskit documentation) project: The ibmq project (see qiskit documentation) api_token: The ibmq api token (see qiskit documentation) """ # Get qiskit noise model from qiskit provider = get_provider(api_token=api_token, hub=hub, group=group, project=project) noisy_device = provider.get_backend(device_name) noise_model = AerNoise.NoiseModel.from_backend(noisy_device) return noise_model, noisy_device.configuration().coupling_map def create_amplitude_damping_noise(T_1: float, t_step: float = 10e-9) -> NoiseModel: """Creates an amplitude damping noise model Args: T_1: Relaxation time (seconds) t_step: Discretized time step over which the relaxation occurs over (seconds) """ gamma = 1 - pow(np.e, -1 / T_1 * t_step) error = amplitude_damping_error(gamma) gate_error = error.tensor(error) noise_model = NoiseModel() noise_model.add_all_qubit_quantum_error(error, ["id", "u3"]) noise_model.add_all_qubit_quantum_error(gate_error, ["cx"]) return noise_model def create_phase_damping_noise(T_2: float, t_step: float = 10e-9) -> NoiseModel: """Creates a dephasing noise model Args: T_2: dephasing time (seconds) t_step: Discretized time step over which the relaxation occurs over (seconds) """ gamma = 1 - pow(np.e, -1 / T_2 * t_step) error = phase_damping_error(gamma) gate_error = error.tensor(error) noise_model = NoiseModel() noise_model.add_all_qubit_quantum_error(error, ["id", "u3"]) noise_model.add_all_qubit_quantum_error(gate_error, ["cx"]) return noise_model def create_phase_and_amplitude_damping_error( T_1: float, T_2: float, t_step: float = 10e-9 ) -> NoiseModel: """Creates a noise model that does both phase and amplitude damping Args: T_1: Relaxation time (seconds) T_2: dephasing time (seonds) t_step: Discretized time step over which the relaxation occurs over (seconds) """ param_amp = 1 - pow(np.e, -1 / T_1 * t_step) param_phase = 1 - pow(np.e, -1 / T_2 * t_step) error = phase_amplitude_damping_error(param_amp, param_phase) gate_error = error.tensor(error) noise_model = NoiseModel() noise_model.add_all_qubit_quantum_error(error, ["id", "u3"]) noise_model.add_all_qubit_quantum_error(gate_error, ["cx"]) return noise_model def create_pta_channel(T_1: float, T_2: float, t_step: float = 10e-9) -> NoiseModel: """Creates a noise model that does both phase and amplitude damping but in the Pauli Twirling Approximation discussed the following reference https://arxiv.org/pdf/1305.2021.pdf Args: T_1: Relaxation time (seconds) T_2: dephasing time (seconds) t_step: Discretized time step over which the relaxation occurs over (seconds) """ p_x = 0.25 * (1 - pow(np.e, -t_step / T_1)) p_y = 0.25 * (1 - pow(np.e, -t_step / T_1)) exp_1 = pow(np.e, -t_step / (2 * T_1)) exp_2 = pow(np.e, -t_step / T_2) p_z = 0.5 - p_x - 0.5 * exp_1 * exp_2 p_i = 1 - p_x - p_y - p_z errors = [("X", p_x), ("Y", p_y), ("Z", p_z), ("I", p_i)] pta_error = pauli_error(errors) noise_model = NoiseModel() noise_model.add_all_qubit_quantum_error(pta_error, ["id", "u3"]) gate_error = pta_error.tensor(pta_error) noise_model.add_all_qubit_quantum_error(gate_error, ["cx"]) return noise_model def get_kraus_matrices_from_ibm_noise_model(noise_model: NoiseModel) -> Dict: """Gets the kraus operators from a pre defined noise model Args: noise_model: Noise model for circuit Return dict_of_kraus_operators: A dictionary labelled by keys which are the basis gates and values are the list of kraus operators """ retrieved_quantum_error_dict = noise_model._default_quantum_errors dict_of_kraus_operators = { gate: Kraus(retrieved_quantum_error_dict[gate]).data for gate in retrieved_quantum_error_dict } return dict_of_kraus_operators
https://github.com/qiskit-community/qiskit-device-benchmarking
qiskit-community
import numpy as np import rustworkx as rx import matplotlib.pyplot as plt from qiskit_ibm_runtime import QiskitRuntimeService from qiskit import QuantumCircuit from qiskit_experiments.framework import ParallelExperiment, BatchExperiment, ExperimentData from qiskit_experiments.library import StandardRB from qiskit_device_benchmarking.bench_code.prb import PurityRB from qiskit_device_benchmarking.utilities import graph_utils as gu #enter your device hub/group/project here #and device hgp = 'ibm-q/open/main' service = QiskitRuntimeService() backend_real=service.backend('ibm_kyiv',instance=hgp) nq = backend_real.configuration().n_qubits coupling_map = backend_real.configuration().coupling_map #build a set of gates G = gu.build_sys_graph(nq, coupling_map) #get all length 2 paths in the device paths = rx.all_pairs_all_simple_paths(G,2,2) #flatten those paths into a list from the rustwork x iterator paths = gu.paths_flatten(paths) #remove permutations paths = gu.remove_permutations(paths) #convert to the coupling map of the device paths = gu.path_to_edges(paths,coupling_map) #make into separate sets sep_sets = gu.get_separated_sets(G, paths, min_sep=2) #rb of all the edges in parallel rb_batch_list = [] prb_batch_list = [] #RB options lengths = [1, 10, 20, 50, 100, 150, 250, 400] num_samples = 5 #also do purity (optional) #use less samples because we need 9 circuits per length per sample #also less lengths because they decay faster do_purity = True lengths_pur = [1, 5, 10, 25, 50, 100, 175, 250] num_samples_pur = 3 if 'ecr' in backend_real.configuration().basis_gates: twoq_gate='ecr' elif 'cz' in backend_real.configuration().basis_gates: twoq_gate='cz' #go through for each of the edge sets for ii in range(len(sep_sets)): rb_list = [] prb_list = [] for two_i, two_set in enumerate(sep_sets[ii]): exp1 = StandardRB(two_set, lengths, num_samples=num_samples) rb_list.append(exp1) rb_exp_p = ParallelExperiment(rb_list, backend = backend_real) rb_batch_list.append(rb_exp_p) if do_purity: for two_i, two_set in enumerate(sep_sets[ii]): exp1 = PurityRB(two_set, lengths_pur, num_samples=num_samples_pur) prb_list.append(exp1) rb_exp_p = ParallelExperiment(prb_list, backend = backend_real) prb_batch_list.append(rb_exp_p) #batch all of them together #put the purity ones last full_rb_exp = BatchExperiment(rb_batch_list + prb_batch_list, backend = backend_real) full_rb_exp.set_experiment_options(max_circuits=100) full_rb_exp.set_run_options(shots=200) #run rb_data = full_rb_exp.run() print(rb_data.job_ids) #Run this cell if you want to reload data from a previous job(s) if (0): # List of job IDs for the experiment job_ids= [''] rb_data = ExperimentData(experiment = full_rb_exp) rb_data.add_jobs([service.job(job_id) for job_id in job_ids]) full_rb_exp.analysis.run(rb_data, replace_results=True) # Block execution of subsequent code until analysis is complete rb_data.block_for_results() rb_data.analysis_status() #Plot the data #Input the edge to plot here fig_edge = [26,16] fig_id = [] for i in range(len(sep_sets)): for j in range(len(sep_sets[i])): if fig_edge==sep_sets[i][j]: fig_id = [i,j] rb_data.child_data()[fig_id[0]].child_data()[fig_id[1]].figure(0) #Plot the PURITY data #Input the edge to plot here if not do_purity: print("No Purity data was run!") fig_edge = [26,16] fig_id = [] for i in range(len(sep_sets)): for j in range(len(sep_sets[i])): if fig_edge==sep_sets[i][j]: fig_id = [i,j] rb_data.child_data()[len(sep_sets)+fig_id[0]].child_data()[fig_id[1]].figure(0) #Load the RB Error into a list set_list = [] rb_err = [] pur_rb_err = [] gate_err = [] back_prop = backend_real.properties() for i in range(len(sep_sets)): for j in range(len(sep_sets[i])): set_list.append(sep_sets[i][j]) rb_err.append(rb_data.child_data()[i].child_data()[j].analysis_results()[2].value.nominal_value/1.5) if do_purity: #sometimes the purity doesn't fit if len(rb_data.child_data()[len(sep_sets)+i].child_data()[j].analysis_results())==1: pur_rb_err.append(1.) else: pur_rb_err.append(rb_data.child_data()[len(sep_sets)+i].child_data()[j].analysis_results()[2].value.nominal_value/1.5) gate_err.append(back_prop.gate_error(twoq_gate,set_list[-1])) if do_purity: print('Q%s, rb error (purity) %.2e (%.2e)/ reported err %.2e'%(sep_sets[i][j], rb_err[-1], pur_rb_err[-1], gate_err[-1])) else: print('Q%s, rb error %.2e (%.2e)/ reported err %.2e'%(sep_sets[i][j], rb_err[-1], gate_err[-1])) #plot the data ordered by Bell state fidelity (need to run the cell above first) plt.figure(dpi=150,figsize=[15,5]) argind = np.argsort(rb_err) plt.semilogy(range(len(set_list)),np.array(gate_err)[argind],label='Gate Err (Reported)', marker='.', color='grey') plt.semilogy(range(len(set_list)),np.array(rb_err)[argind],label='RB Err (Measured)', marker='.') if do_purity: plt.semilogy(range(len(set_list)),np.array(pur_rb_err)[argind],label='Pur RB Err (Measured)', marker='x') plt.xticks(range(len(set_list)),np.array(set_list)[argind],rotation=90,fontsize=5); plt.ylim([1e-3,1]) plt.grid(True) plt.legend() plt.title('Device Gate Errors for %s, job %s'%(backend_real.name, rb_data.job_ids[0])) import datetime from IPython.display import HTML, display def qiskit_copyright(line="", cell=None): """IBM copyright""" now = datetime.datetime.now() html = "<div style='width: 100%; background-color:#d5d9e0;" html += "padding-left: 10px; padding-bottom: 10px; padding-right: 10px; padding-top: 5px'>" html += "<p>&copy; Copyright IBM 2017, %s.</p>" % now.year html += "<p>This code is licensed under the Apache License, Version 2.0. You may<br>" html += "obtain a copy of this license in the LICENSE.txt file in the root directory<br> " html += "of this source tree or at http://www.apache.org/licenses/LICENSE-2.0." html += "<p>Any modifications or derivative works of this code must retain this<br>" html += "copyright notice, and modified files need to carry a notice indicating<br>" html += "that they have been altered from the originals.</p>" html += "</div>" return display(HTML(html)) qiskit_copyright()
https://github.com/kurtchahn/QiskitPrx
kurtchahn
import qiskit as qk import qiskit_aer as qaer import numpy as np import math sSimulator = qaer.Aer.backends(name="statevector_simulator")[0] mSimulator = qaer.Aer.backends(name="qasm_simulator")[0] qr = qk.QuantumRegister(2, name="qr") cr = qk.ClassicalRegister(2, name="cr") qc = qk.QuantumCircuit(qr, cr, name="qc") qc.h(qr[0]) qc.cx(qr[0], qr[1]) qr1 = qk.QuantumRegister(2, name="qr1") cr1 = qk.ClassicalRegister(2, name="cr1") qc1 = qk.QuantumCircuit(qr1, cr1, name="qc1") qr2 = qk.QuantumRegister(2, name="qr2") cr2 = qk.ClassicalRegister(2, name="cr2") qc2 = qk.QuantumCircuit(qr2, cr2, name="qc2") qc1.h(qr1[0]) qc1.id(qr1[1]) qc2.id(qr2[0]) qc2.h(qr2[1]) qc3 = qc1.compose(qc2) qc1.draw("mpl") qc2.draw("mpl") qc3.draw("mpl")
https://github.com/PacktPublishing/Quantum-Computing-in-Practice-with-Qiskit-and-IBM-Quantum-Experience
PacktPublishing
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created Nov 2020 @author: hassi """ from qiskit import QuantumCircuit, Aer, execute from qiskit.tools.visualization import plot_histogram from IPython.core.display import display print("Ch 4: Cheating quantum coin toss") print("--------------------------------") qc = QuantumCircuit(2, 2) qc.h(0) qc.cx(0,1) qc.measure([0,1],[0,1]) display(qc.draw('mpl')) backend = Aer.get_backend('qasm_simulator') counts = execute(qc, backend, shots=1000).result().get_counts(qc) display(plot_histogram(counts))
https://github.com/MonitSharma/Learn-Quantum-Computing-with-Qiskit
MonitSharma
import matplotlib.pyplot as plt import time # Function with constant runtime complexity: O(1) def constant_time(): return 42 # Function with linear runtime complexity: O(n) def linear_time(n): result = 0 for i in range(n): result += i return result # Function with quadratic runtime complexity: O(n^2) def quadratic_time(n): result = 0 for i in range(n): for j in range(n): result += i * j return result # Function with exponential runtime complexity: O(2^n) def exponential_time(n): if n <= 1: return n return exponential_time(n-1) + exponential_time(n-2) # Function to measure the execution time of a function def measure_time(func, *args): start_time = time.time() result = func(*args) end_time = time.time() execution_time = end_time - start_time return execution_time # Input sizes input_sizes = list(range(1, 11)) # Adjust the input sizes as desired # Measure execution times for different complexities constant_times = [measure_time(constant_time) for _ in input_sizes] linear_times = [measure_time(linear_time, n) for n in input_sizes] quadratic_times = [measure_time(quadratic_time, n) for n in input_sizes] exponential_times = [measure_time(exponential_time, n) for n in input_sizes] # Plotting the graph plt.plot(input_sizes, constant_times, label='O(1)') plt.plot(input_sizes, linear_times, label='O(n)') plt.plot(input_sizes, quadratic_times, label='O(n^2)') plt.plot(input_sizes, exponential_times, label='O(2^n)') plt.xlabel('Input Size (n)') plt.ylabel('Execution Time (s)') plt.title('Runtime Complexity Comparison') plt.legend() plt.show() # Python implementation of Karatsuba algorithm for bit string multiplication. # Helper method: given two unequal sized bit strings, converts them to # same length by adding leading 0s in the smaller string. Returns the # the new length def make_equal_length(str1, str2): len1 = len(str1) len2 = len(str2) if len1 < len2: for i in range(len2 - len1): str1 = '0' + str1 return len2 elif len1 > len2: for i in range(len1 - len2): str2 = '0' + str2 return len1 # If len1 >= len2 # The main function that adds two bit sequences and returns the addition def add_bit_strings(first, second): result = "" # To store the sum bits # make the lengths same before adding length = make_equal_length(first, second) carry = 0 # Initialize carry # Add all bits one by one for i in range(length-1, -1, -1): first_bit = int(first[i]) second_bit = int(second[i]) # boolean expression for sum of 3 bits sum = (first_bit ^ second_bit ^ carry) + ord('0') result = chr(sum) + result # boolean expression for 3-bit addition carry = (first_bit & second_bit) | (second_bit & carry) | (first_bit & carry) # if overflow, then add a leading 1 if carry: result = '1' + result return result # A utility function to multiply single bits of strings a and b def multiply_single_bit(a, b): return int(a[0]) * int(b[0]) # The main function that multiplies two bit strings X and Y and returns # result as long integer def multiply(X, Y): # Find the maximum of lengths of x and Y and make length # of smaller string same as that of larger string n = max(len(X), len(Y)) X = X.zfill(n) Y = Y.zfill(n) # Base cases if n == 0: return 0 if n == 1: return int(X[0])*int(Y[0]) fh = n//2 # First half of string sh = n - fh # Second half of string # Find the first half and second half of first string. Xl = X[:fh] Xr = X[fh:] # Find the first half and second half of second string Yl = Y[:fh] Yr = Y[fh:] # Recursively calculate the three products of inputs of size n/2 P1 = multiply(Xl, Yl) P2 = multiply(Xr, Yr) P3 = multiply(str(int(Xl, 2) + int(Xr, 2)), str(int(Yl, 2) + int(Yr, 2))) # Combine the three products to get the final result. return P1*(1<<(2*sh)) + (P3 - P1 - P2)*(1<<sh) + P2 if __name__ == '__main__': print(multiply("1100", "1010")) print(multiply("110", "1010")) print(multiply("11", "1010")) print(multiply("1", "1010")) print(multiply("0", "1010")) print(multiply("111", "111")) print(multiply("11", "11")) # Python 3 program to find a prime factor of composite using # Pollard's Rho algorithm import random import math # Function to calculate (base^exponent)%modulus def modular_pow(base, exponent,modulus): # initialize result result = 1 while (exponent > 0): # if y is odd, multiply base with result if (exponent & 1): result = (result * base) % modulus # exponent = exponent/2 exponent = exponent >> 1 # base = base * base base = (base * base) % modulus return result # method to return prime divisor for n def PollardRho( n): # no prime divisor for 1 if (n == 1): return n # even number means one of the divisors is 2 if (n % 2 == 0): return 2 # we will pick from the range [2, N) x = (random.randint(0, 2) % (n - 2)) y = x # the constant in f(x). # Algorithm can be re-run with a different c # if it throws failure for a composite. c = (random.randint(0, 1) % (n - 1)) # Initialize candidate divisor (or result) d = 1 # until the prime factor isn't obtained. # If n is prime, return n while (d == 1): # Tortoise Move: x(i+1) = f(x(i)) x = (modular_pow(x, 2, n) + c + n)%n # Hare Move: y(i+1) = f(f(y(i))) y = (modular_pow(y, 2, n) + c + n)%n y = (modular_pow(y, 2, n) + c + n)%n # check gcd of |x-y| and n d = math.gcd(abs(x - y), n) # retry if the algorithm fails to find prime factor # with chosen x and c if (d == n): return PollardRho(n) return d # Driver function if __name__ == "__main__": n = 10967535067 print("One of the divisors for", n , "is ",PollardRho(n)) # This code is contributed by chitranayal rsa_250 = 2140324650240744961264423072839333563008614715144755017797754920881418023447140136643345519095804679610992851872470914587687396261921557363047454770520805119056493106687691590019759405693457452230589325976697471681738069364894699871578494975937497937 p = 64135289477071580278790190170577389084825014742943447208116859632024532344630238623598752668347708737661925585694639798853367 q = 33372027594978156556226010605355114227940760344767554666784520987023841729210037080257448673296881877565718986258036932062711 p*q
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit import QuantumCircuit from qiskit.providers.fake_provider import FakeVigoV2 backend = FakeVigoV2() qc = QuantumCircuit(2, 1) qc.h(0) qc.x(1) qc.cp(np.pi/4, 0, 1) qc.h(0) qc.measure([0], [0]) qc.draw(output='mpl')
https://github.com/abhik-99/Qiskit-Summer-School
abhik-99
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() import numpy as np; pi = np.pi from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram from copy import deepcopy as make_copy def prepare_hets_circuit(depth, angle1, angle2): hets_circ = QuantumCircuit(depth) hets_circ.ry(angle1, 0) hets_circ.rz(angle1, 0) hets_circ.ry(angle1, 1) hets_circ.rz(angle1, 1) for ii in range(depth): hets_circ.cx(0,1) hets_circ.ry(angle2,0) hets_circ.rz(angle2,0) hets_circ.ry(angle2,1) hets_circ.rz(angle2,1) return hets_circ hets_circuit = prepare_hets_circuit(2, pi/2, pi/2) hets_circuit.draw() def measure_zz_circuit(given_circuit): zz_meas = make_copy(given_circuit) zz_meas.measure_all() return zz_meas zz_meas = measure_zz_circuit(hets_circuit) zz_meas.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(zz_meas, backend = simulator, shots=10000).result() counts = result.get_counts(zz_meas) plot_histogram(counts) def measure_zz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zz = counts['00'] + counts['11'] - counts['01'] - counts['10'] zz = zz / total_counts return zz zz = measure_zz(hets_circuit) print("<ZZ> =", str(zz)) def measure_zi(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zi = counts['00'] - counts['11'] + counts['01'] - counts['10'] zi = zi / total_counts return zi def measure_iz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] iz = counts['00'] - counts['11'] - counts['01'] + counts['10'] iz = iz / total_counts return iz zi = measure_zi(hets_circuit) print("<ZI> =", str(zi)) iz = measure_iz(hets_circuit) print("<IZ> =", str(iz)) def measure_xx_circuit(given_circuit): xx_meas = make_copy(given_circuit) ### WRITE YOUR CODE BETWEEN THESE LINES - START xx_meas.h(0) xx_meas.h(1) xx_meas.measure_all() ### WRITE YOUR CODE BETWEEN THESE LINES - END return xx_meas xx_meas = measure_xx_circuit(hets_circuit) xx_meas.draw() def measure_xx(given_circuit, num_shots = 10000): xx_meas = measure_xx_circuit(given_circuit) result = execute(xx_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(xx_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] xx = counts['00'] + counts['11'] - counts['01'] - counts['10'] xx = xx / total_counts return xx xx = measure_xx(hets_circuit) print("<XX> =", str(xx)) def get_energy(given_circuit, num_shots = 10000): zz = measure_zz(given_circuit, num_shots = num_shots) iz = measure_iz(given_circuit, num_shots = num_shots) zi = measure_zi(given_circuit, num_shots = num_shots) xx = measure_xx(given_circuit, num_shots = num_shots) energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx return energy energy = get_energy(hets_circuit) print("The energy of the trial state is", str(energy)) hets_circuit_plus = None hets_circuit_minus = None ### WRITE YOUR CODE BETWEEN THESE LINES - START hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2) hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2) ### WRITE YOUR CODE BETWEEN THESE LINES - END energy_plus = get_energy(hets_circuit_plus, num_shots=100000) energy_minus = get_energy(hets_circuit_minus, num_shots=100000) print(energy_plus, energy_minus) name = 'Pon Rahul M' email = 'ponrahul.21it@licet.ac.in' ### Do not change the lines below from grading_tools import grade grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1') grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2') grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3') energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0 energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0 ### WRITE YOUR CODE BETWEEN THESE LINES - START energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100) energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100) energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000) energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000) energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000) energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000) ### WRITE YOUR CODE BETWEEN THESE LINES - END print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100) print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000) print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000) ### WRITE YOUR CODE BETWEEN THESE LINES - START I = np.array([ [1, 0], [0, 1] ]) X = np.array([ [0, 1], [1, 0] ]) Z = np.array([ [1, 0], [0, -1] ]) h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \ (0.39793742) * np.kron(I, Z) + \ (-0.3979374) * np.kron(Z, I) + \ (-0.0112801) * np.kron(Z, Z) + \ (0.18093119) * np.kron(X, X) from numpy import linalg as LA eigenvalues, eigenvectors = LA.eig(h2_hamiltonian) for ii, eigenvalue in enumerate(eigenvalues): print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}") exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)] exact_eigenvalue = np.min(eigenvalues) print() print("Minimum energy is", exact_eigenvalue) ### WRITE YOUR CODE BETWEEN THESE LINES - END
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.circuit.random import random_circuit circuit = random_circuit(2, 2, seed=0).decompose(reps=1) display(circuit.draw("mpl")) from qiskit.quantum_info import SparsePauliOp observable = SparsePauliOp("XZ") print(f">>> Observable: {observable.paulis}") from qiskit.primitives import Estimator estimator = Estimator() job = estimator.run(circuit, observable) print(f">>> Job ID: {job.job_id()}") print(f">>> Job Status: {job.status()}") result = job.result() print(f">>> {result}") print(f" > Expectation value: {result.values[0]}") circuit = random_circuit(2, 2, seed=1).decompose(reps=1) observable = SparsePauliOp("IY") job = estimator.run(circuit, observable) result = job.result() display(circuit.draw("mpl")) print(f">>> Observable: {observable.paulis}") print(f">>> Expectation value: {result.values[0]}") circuits = ( random_circuit(2, 2, seed=0).decompose(reps=1), random_circuit(2, 2, seed=1).decompose(reps=1), ) observables = ( SparsePauliOp("XZ"), SparsePauliOp("IY"), ) job = estimator.run(circuits, observables) result = job.result() [display(cir.draw("mpl")) for cir in circuits] print(f">>> Observables: {[obs.paulis for obs in observables]}") print(f">>> Expectation values: {result.values.tolist()}") from qiskit.circuit.library import RealAmplitudes circuit = RealAmplitudes(num_qubits=2, reps=2).decompose(reps=1) observable = SparsePauliOp("ZI") parameter_values = [0, 1, 2, 3, 4, 5] job = estimator.run(circuit, observable, parameter_values) result = job.result() display(circuit.draw("mpl")) print(f">>> Observable: {observable.paulis}") print(f">>> Parameter values: {parameter_values}") print(f">>> Expectation value: {result.values[0]}") from qiskit_ibm_runtime import QiskitRuntimeService service = QiskitRuntimeService(channel="ibm_quantum") backend = service.backend("ibmq_qasm_simulator") from qiskit.circuit.random import random_circuit from qiskit.quantum_info import SparsePauliOp circuit = random_circuit(2, 2, seed=0).decompose(reps=1) display(circuit.draw("mpl")) observable = SparsePauliOp("XZ") print(f">>> Observable: {observable.paulis}") from qiskit_ibm_runtime import Estimator estimator = Estimator(session=backend) job = estimator.run(circuit, observable) print(f">>> Job ID: {job.job_id()}") print(f">>> Job Status: {job.status()}") result = job.result() print(f">>> {result}") print(f" > Expectation value: {result.values[0]}") print(f" > Metadata: {result.metadata[0]}") from qiskit_ibm_runtime import Options options = Options(optimization_level=3, environment={"log_level": "INFO"}) from qiskit_ibm_runtime import Options options = Options() options.resilience_level = 1 options.execution.shots = 2048 estimator = Estimator(session=backend, options=options) result = estimator.run(circuit, observable).result() print(f">>> Metadata: {result.metadata[0]}") estimator = Estimator(session=backend, options=options) result = estimator.run(circuit, observable, shots=1024).result() print(f">>> Metadata: {result.metadata[0]}") from qiskit_ibm_runtime import Options # optimization_level=3 adds dynamical decoupling # resilience_level=1 adds readout error mitigation options = Options(optimization_level=3, resilience_level=1) estimator = Estimator(session=backend, options=options) result = estimator.run(circuit, observable).result() print(f">>> Expectation value: {result.values[0]}") print(f">>> Metadata: {result.metadata[0]}") from qiskit_ibm_runtime import Session, Estimator with Session(backend=backend, max_time="1h"): estimator = Estimator() result = estimator.run(circuit, observable).result() print(f">>> Expectation value from the first run: {result.values[0]}") result = estimator.run(circuit, observable).result() print(f">>> Expectation value from the second run: {result.values[0]}") from qiskit.circuit.random import random_circuit sampler_circuit = random_circuit(2, 2, seed=0).decompose(reps=1) sampler_circuit.measure_all() display(circuit.draw("mpl")) from qiskit_ibm_runtime import Session, Sampler, Estimator with Session(backend=backend): sampler = Sampler() estimator = Estimator() result = sampler.run(sampler_circuit).result() print(f">>> Quasi Distribution from the sampler job: {result.quasi_dists[0]}") result = estimator.run(circuit, observable).result() print(f">>> Expectation value from the estimator job: {result.values[0]}") from qiskit_ibm_runtime import Session, Sampler, Estimator with Session(backend=backend): sampler = Sampler() estimator = Estimator() sampler_job = sampler.run(sampler_circuit) estimator_job = estimator.run(circuit, observable) print(f">>> Quasi Distribution from the sampler job: {sampler_job.result().quasi_dists[0]}") print(f">>> Expectation value from the estimator job: {estimator_job.result().values[0]}") from qiskit_ibm_runtime import QiskitRuntimeService, Session, Sampler, Estimator, Options # 1. Initialize account service = QiskitRuntimeService(channel="ibm_quantum") # 2. Specify options, such as enabling error mitigation options = Options(resilience_level=1) # 3. Select a backend. backend = service.backend("ibmq_qasm_simulator") # 4. Create a session with Session(backend=backend): # 5. Create primitive instances sampler = Sampler(options=options) estimator = Estimator(options=options) # 6. Submit jobs sampler_job = sampler.run(sampler_circuit) estimator_job = estimator.run(circuit, observable) # 7. Get results print(f">>> Quasi Distribution from the sampler job: {sampler_job.result().quasi_dists[0]}") print(f">>> Expectation value from the estimator job: {estimator_job.result().values[0]}") import qiskit_ibm_runtime qiskit_ibm_runtime.version.get_version_info() from qiskit.tools.jupyter import * %qiskit_version_table %qiskit_copyright
https://github.com/NirupamKhanal/Qiskit1
NirupamKhanal
from qiskit import QuantumCircuit qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc.draw(output = 'mpl') from qiskit.quantum_info import Pauli ZZ = Pauli('ZZ') ZI = Pauli('ZI') IZ = Pauli('IZ') XX = Pauli('XX') XI = Pauli('XI') IX = Pauli('IX') observables = (ZZ, ZI, IZ, XX, XI, IX) from qiskit_aer.primitives import Estimator estimator = Estimator() job = estimator.run([qc] * len(observables), observables) job.result() import matplotlib.pyplot as plt data = ['ZZ', 'ZI', 'IZ', 'XX', 'XI', 'IX'] values = job.result().values plt.plot(data, values, '-o') plt.xlabel('Observables') plt.ylabel('Expectation value') plt.show() def get_qc_for_n_qubit_GHZ_state(n): qc = QuantumCircuit(n) qc.h(0) for i in range(n-1): qc.cx(i, i+1) return qc n = 100 qc = get_qc_for_n_qubit_GHZ_state(n) qc.draw(output='mpl') #map operators from qiskit.quantum_info import SparsePauliOp operator_strings = ['Z' + 'I' * i + 'Z' + 'I' * (n-2-i) for i in range(n-1)] print(operator_strings) print(len(operator_strings)) operators = [SparsePauliOp(operator_string) for operator_string in operator_strings] #optimization from qiskit_ibm_runtime import QiskitRuntimeService from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager backend_name = "ibm_brisbane" backend = QiskitRuntimeService().get_backend(backend_name) pass_manager = generate_preset_pass_manager(optimization_level=1, backend=backend) qc_transpiled = pass_manager.run(qc) operators_transpiled_list = [op.apply_layout(qc_transpiled.layout) for op in operators] #execute on the backend from qiskit_ibm_runtime import EstimatorV2 as Estimator from qiskit_ibm_runtime import EstimatorOptions options = EstimatorOptions() options.resilience_level = 1 options.optimization_level = 0 options.dynamical_decoupling.enable = True options.dynamical_decoupling.sequence_type = "XY4" estimator = Estimator(backend, options=options) job = estimator.run([(qc_transpiled, operators_transpiled_list)]) job_id = job.job_id() print(job_id) #Post-processing and plotting job_id = 'csg4nzzp7n0g0086qpa0' service = QiskitRuntimeService() job = service.job(job_id) import matplotlib.pyplot as plt date = list(range(1, len(operators)+1)) result = job.result()[0] values = result.data.evs values = [v / values[0] for v in values] plt.scatter(data, values, marker='o', label='100-qubit GHZ State') plt.xlabel('Distance between qubits $i$') plt.ylabel(r'\langle Z_0 Z_i \rangle / \langle Z_0 Z_1 \rangle$') plt.legend() plt.show()
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
mmetcalf14
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ This trial wavefunction is a Unitary Coupled-Cluster Single and Double excitations variational form. For more information, see https://arxiv.org/abs/1805.04340 """ import logging import sys import numpy as np from qiskit import QuantumRegister, QuantumCircuit from qiskit.tools import parallel_map from qiskit.tools.events import TextProgressBar from qiskit.aqua import Operator, aqua_globals from qiskit.aqua.components.variational_forms import VariationalForm from qiskit.chemistry.fermionic_operator import FermionicOperator from qiskit.chemistry import MP2Info from qiskit.chemistry import QMolecule as qm logger = logging.getLogger(__name__) class UCCSD(VariationalForm): """ This trial wavefunction is a Unitary Coupled-Cluster Single and Double excitations variational form. For more information, see https://arxiv.org/abs/1805.04340 """ CONFIGURATION = { 'name': 'UCCSD', 'description': 'UCCSD Variational Form', 'input_schema': { '$schema': 'http://json-schema.org/schema#', 'id': 'uccsd_schema', 'type': 'object', 'properties': { 'depth': { 'type': 'integer', 'default': 1, 'minimum': 1 }, 'num_orbitals': { 'type': 'integer', 'default': 4, 'minimum': 1 }, 'num_particles': { 'type': 'integer', 'default': 2, 'minimum': 1 }, 'active_occupied': { 'type': ['array', 'null'], 'default': None }, 'active_unoccupied': { 'type': ['array', 'null'], 'default': None }, 'qubit_mapping': { 'type': 'string', 'default': 'parity', 'oneOf': [ {'enum': ['jordan_wigner', 'parity', 'bravyi_kitaev']} ] }, 'two_qubit_reduction': { 'type': 'boolean', 'default': False }, 'mp2_reduction': { 'type': 'boolean', 'default': False }, 'num_time_slices': { 'type': 'integer', 'default': 1, 'minimum': 1 }, }, 'additionalProperties': False }, 'depends': [ { 'pluggable_type': 'initial_state', 'default': { 'name': 'HartreeFock', } }, ], } def __init__(self, num_qubits, depth, num_orbitals, num_particles, active_occupied=None, active_unoccupied=None, initial_state=None, qubit_mapping='parity', two_qubit_reduction=False, mp2_reduction=False, num_time_slices=1, cliffords=None, sq_list=None, tapering_values=None, symmetries=None, shallow_circuit_concat=True): """Constructor. Args: num_orbitals (int): number of spin orbitals depth (int): number of replica of basic module num_particles (int): number of particles active_occupied (list): list of occupied orbitals to consider as active space active_unoccupied (list): list of unoccupied orbitals to consider as active space initial_state (InitialState): An initial state object. qubit_mapping (str): qubit mapping type. two_qubit_reduction (bool): two qubit reduction is applied or not. num_time_slices (int): parameters for dynamics. cliffords ([Operator]): list of unitary Clifford transformation sq_list ([int]): position of the single-qubit operators that anticommute with the cliffords tapering_values ([int]): array of +/- 1 used to select the subspace. Length has to be equal to the length of cliffords and sq_list symmetries ([Pauli]): represent the Z2 symmetries shallow_circuit_concat (bool): indicate whether to use shallow (cheap) mode for circuit concatenation """ self.validate(locals()) super().__init__() self._cliffords = cliffords self._sq_list = sq_list self._tapering_values = tapering_values self._symmetries = symmetries if self._cliffords is not None and self._sq_list is not None and \ self._tapering_values is not None and self._symmetries is not None: self._qubit_tapering = True else: self._qubit_tapering = False self._num_qubits = num_orbitals if not two_qubit_reduction else num_orbitals - 2 self._num_qubits = self._num_qubits if not self._qubit_tapering else self._num_qubits - len(sq_list) if self._num_qubits != num_qubits: raise ValueError('Computed num qubits {} does not match actual {}' .format(self._num_qubits, num_qubits)) self._depth = depth self._num_orbitals = num_orbitals self._num_particles = num_particles if self._num_particles > self._num_orbitals: raise ValueError('# of particles must be less than or equal to # of orbitals.') self._initial_state = initial_state self._qubit_mapping = qubit_mapping self._two_qubit_reduction = two_qubit_reduction self._num_time_slices = num_time_slices self._shallow_circuit_concat = shallow_circuit_concat self._single_excitations, self._double_excitations = \ UCCSD.compute_excitation_lists(num_particles, num_orbitals, active_occupied, active_unoccupied) self._single_excitations = [] print('{} are the old doubles'.format(self._double_excitations)) print(mp2_reduction) if mp2_reduction: print('Getting new doubles') self._double_excitations = get_mp2_doubles(self._single_excitations,self._double_excitations) print('{} are the new doubles'.format(self._double_excitations)) self._hopping_ops, self._num_parameters = self._build_hopping_operators() self._bounds = [(-np.pi, np.pi) for _ in range(self._num_parameters)] self._logging_construct_circuit = True def _build_hopping_operators(self): from .uccsd import UCCSD hopping_ops = [] if logger.isEnabledFor(logging.DEBUG): TextProgressBar(sys.stderr) results = parallel_map(UCCSD._build_hopping_operator, self._single_excitations + self._double_excitations, task_args=(self._num_orbitals, self._num_particles, self._qubit_mapping, self._two_qubit_reduction, self._qubit_tapering, self._symmetries, self._cliffords, self._sq_list, self._tapering_values), num_processes=aqua_globals.num_processes) hopping_ops = [qubit_op for qubit_op in results if qubit_op is not None] num_parameters = len(hopping_ops) * self._depth return hopping_ops, num_parameters @staticmethod def _build_hopping_operator(index, num_orbitals, num_particles, qubit_mapping, two_qubit_reduction, qubit_tapering, symmetries, cliffords, sq_list, tapering_values): def check_commutativity(op_1, op_2): com = op_1 * op_2 - op_2 * op_1 com.zeros_coeff_elimination() return True if com.is_empty() else False h1 = np.zeros((num_orbitals, num_orbitals)) h2 = np.zeros((num_orbitals, num_orbitals, num_orbitals, num_orbitals)) if len(index) == 2: i, j = index h1[i, j] = 1.0 h1[j, i] = -1.0 elif len(index) == 4: i, j, k, m = index h2[i, j, k, m] = 1.0 h2[m, k, j, i] = -1.0 dummpy_fer_op = FermionicOperator(h1=h1, h2=h2) qubit_op = dummpy_fer_op.mapping(qubit_mapping) qubit_op = qubit_op.two_qubit_reduced_operator(num_particles) \ if two_qubit_reduction else qubit_op if qubit_tapering: for symmetry in symmetries: symmetry_op = Operator(paulis=[[1.0, symmetry]]) symm_commuting = check_commutativity(symmetry_op, qubit_op) if not symm_commuting: break if qubit_tapering: if symm_commuting: qubit_op = Operator.qubit_tapering(qubit_op, cliffords, sq_list, tapering_values) else: qubit_op = None if qubit_op is None: logger.debug('Excitation ({}) is skipped since it is not commuted ' 'with symmetries'.format(','.join([str(x) for x in index]))) return qubit_op def construct_circuit(self, parameters, q=None): """ Construct the variational form, given its parameters. Args: parameters (numpy.ndarray): circuit parameters q (QuantumRegister): Quantum Register for the circuit. Returns: QuantumCircuit: a quantum circuit with given `parameters` Raises: ValueError: the number of parameters is incorrect. """ from .uccsd import UCCSD if len(parameters) != self._num_parameters: raise ValueError('The number of parameters has to be {}'.format(self._num_parameters)) if q is None: q = QuantumRegister(self._num_qubits, name='q') if self._initial_state is not None: circuit = self._initial_state.construct_circuit('circuit', q) else: circuit = QuantumCircuit(q) if logger.isEnabledFor(logging.DEBUG) and self._logging_construct_circuit: logger.debug("Evolving hopping operators:") TextProgressBar(sys.stderr) self._logging_construct_circuit = False num_excitations = len(self._hopping_ops) results = parallel_map(UCCSD._construct_circuit_for_one_excited_operator, [(self._hopping_ops[index % num_excitations], parameters[index]) for index in range(self._depth * num_excitations)], task_args=(q, self._num_time_slices), num_processes=aqua_globals.num_processes) for qc in results: if self._shallow_circuit_concat: circuit.data += qc.data else: circuit += qc return circuit @staticmethod def _construct_circuit_for_one_excited_operator(qubit_op_and_param, qr, num_time_slices): qubit_op, param = qubit_op_and_param qc = qubit_op.evolve(None, param * -1j, 'circuit', num_time_slices, qr) return qc @property def preferred_init_points(self): """Getter of preferred initial points based on the given initial state.""" if self._initial_state is None: return None else: bitstr = self._initial_state.bitstr if bitstr is not None: return np.zeros(self._num_parameters, dtype=np.float) else: return None @staticmethod def compute_excitation_lists(num_particles, num_orbitals, active_occ_list=None, active_unocc_list=None, same_spin_doubles=True): """ Computes single and double excitation lists Args: num_particles: Total number of particles num_orbitals: Total number of spin orbitals active_occ_list: List of occupied orbitals to include, indices are 0 to n where n is num particles // 2 active_unocc_list: List of unoccupied orbitals to include, indices are 0 to m where m is (num_orbitals - num particles) // 2 same_spin_doubles: True to include alpha,alpha and beta,beta double excitations as well as alpha,beta pairings. False includes only alpha,beta Returns: Single and double excitation lists """ if num_particles < 2 or num_particles % 2 != 0: raise ValueError('Invalid number of particles {}'.format(num_particles)) if num_orbitals < 4 or num_orbitals % 2 != 0: raise ValueError('Invalid number of orbitals {}'.format(num_orbitals)) if num_orbitals <= num_particles: raise ValueError('No unoccupied orbitals') if active_occ_list is not None: active_occ_list = [i if i >= 0 else i + num_particles // 2 for i in active_occ_list] for i in active_occ_list: if i >= num_particles // 2: raise ValueError('Invalid index {} in active active_occ_list {}' .format(i, active_occ_list)) if active_unocc_list is not None: active_unocc_list = [i + num_particles // 2 if i >= 0 else i + num_orbitals // 2 for i in active_unocc_list] for i in active_unocc_list: if i < 0 or i >= num_orbitals // 2: raise ValueError('Invalid index {} in active active_unocc_list {}' .format(i, active_unocc_list)) if active_occ_list is None or len(active_occ_list) <= 0: active_occ_list = [i for i in range(0, num_particles // 2)] if active_unocc_list is None or len(active_unocc_list) <= 0: active_unocc_list = [i for i in range(num_particles // 2, num_orbitals // 2)] single_excitations = [] double_excitations = [] logger.debug('active_occ_list {}'.format(active_occ_list)) logger.debug('active_unocc_list {}'.format(active_unocc_list)) beta_idx = num_orbitals // 2 for occ_alpha in active_occ_list: for unocc_alpha in active_unocc_list: single_excitations.append([occ_alpha, unocc_alpha]) for occ_beta in [i + beta_idx for i in active_occ_list]: for unocc_beta in [i + beta_idx for i in active_unocc_list]: single_excitations.append([occ_beta, unocc_beta]) for occ_alpha in active_occ_list: for unocc_alpha in active_unocc_list: for occ_beta in [i + beta_idx for i in active_occ_list]: for unocc_beta in [i + beta_idx for i in active_unocc_list]: double_excitations.append([occ_alpha, unocc_alpha, occ_beta, unocc_beta]) if same_spin_doubles and len(active_occ_list) > 1 and len(active_unocc_list) > 1: for i, occ_alpha in enumerate(active_occ_list[:-1]): for j, unocc_alpha in enumerate(active_unocc_list[:-1]): for occ_alpha_1 in active_occ_list[i + 1:]: for unocc_alpha_1 in active_unocc_list[j + 1:]: double_excitations.append([occ_alpha, unocc_alpha, occ_alpha_1, unocc_alpha_1]) up_active_occ_list = [i + beta_idx for i in active_occ_list] up_active_unocc_list = [i + beta_idx for i in active_unocc_list] for i, occ_beta in enumerate(up_active_occ_list[:-1]): for j, unocc_beta in enumerate(up_active_unocc_list[:-1]): for occ_beta_1 in up_active_occ_list[i + 1:]: for unocc_beta_1 in up_active_unocc_list[j + 1:]: double_excitations.append([occ_beta, unocc_beta, occ_beta_1, unocc_beta_1]) logger.debug('single_excitations ({}) {}'.format(len(single_excitations), single_excitations)) logger.debug('double_excitations ({}) {}'.format(len(double_excitations), double_excitations)) return single_excitations, double_excitations def get_mp2_doubles(single_excitations, double_excitations): print('Is the class still populated with the correct info: ', qm.nuclear_repulsion_energy) mp2 = MP2Info(qm, single_excitations, double_excitations, threshold=1e-3) mp2_doubles = mp2._mp2_doubles return mp2_doubles
https://github.com/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/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) qc.cx(1, 0) return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).issubset({0,1}): raise ValueError(f"message '{msg}' is invalid") if msg[1] == "1": ### removed x gate ### pass if msg[0] == "1": qc.z(qubit) return qc def decode_message(qc): qc.cx(1, 0) qc.h(1) return qc
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test library of n-local circuits.""" import unittest from test import combine import numpy as np from ddt import ddt, data, unpack from qiskit.test.base import QiskitTestCase from qiskit import transpile from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector, ParameterExpression from qiskit.circuit.library import ( NLocal, TwoLocal, RealAmplitudes, ExcitationPreserving, XGate, CRXGate, CCXGate, SwapGate, RXGate, RYGate, EfficientSU2, RZGate, RXXGate, RYYGate, CXGate, ) from qiskit.circuit.random.utils import random_circuit from qiskit.converters.circuit_to_dag import circuit_to_dag from qiskit.quantum_info import Operator @ddt class TestNLocal(QiskitTestCase): """Test the n-local circuit class.""" def test_if_reps_is_negative(self): """Test to check if error is raised for negative value of reps""" with self.assertRaises(ValueError): _ = NLocal(reps=-1) def test_if_reps_is_str(self): """Test to check if proper error is raised for str value of reps""" with self.assertRaises(TypeError): _ = NLocal(reps="3") def test_if_reps_is_float(self): """Test to check if proper error is raised for float value of reps""" with self.assertRaises(TypeError): _ = NLocal(reps=5.6) def test_if_reps_is_npint32(self): """Equality test for reps with int value and np.int32 value""" self.assertEqual(NLocal(reps=3), NLocal(reps=np.int32(3))) def test_if_reps_is_npint64(self): """Equality test for reps with int value and np.int64 value""" self.assertEqual(NLocal(reps=3), NLocal(reps=np.int64(3))) def test_reps_setter_when_negative(self): """Test to check if setter raises error for reps < 0""" nlocal = NLocal(reps=1) with self.assertRaises(ValueError): nlocal.reps = -1 def assertCircuitEqual(self, qc1, qc2, visual=False, transpiled=True): """An equality test specialized to circuits.""" if transpiled: basis_gates = ["id", "u1", "u3", "cx"] qc1_transpiled = transpile(qc1, basis_gates=basis_gates, optimization_level=0) qc2_transpiled = transpile(qc2, basis_gates=basis_gates, optimization_level=0) qc1, qc2 = qc1_transpiled, qc2_transpiled if visual: self.assertEqual(qc1.draw(), qc2.draw()) else: self.assertEqual(qc1, qc2) def test_empty_nlocal(self): """Test the creation of an empty NLocal.""" nlocal = NLocal() self.assertEqual(nlocal.num_qubits, 0) self.assertEqual(nlocal.num_parameters_settable, 0) self.assertEqual(nlocal.reps, 1) self.assertEqual(nlocal, QuantumCircuit()) for attribute in [nlocal.rotation_blocks, nlocal.entanglement_blocks]: self.assertEqual(len(attribute), 0) @data( (XGate(), [[0], [2], [1]]), (XGate(), [[0]]), (CRXGate(-0.2), [[2, 0], [1, 3]]), ) @unpack def test_add_layer_to_empty_nlocal(self, block, entangler_map): """Test appending gates to an empty nlocal.""" nlocal = NLocal() nlocal.add_layer(block, entangler_map) max_num_qubits = max(max(indices) for indices in entangler_map) reference = QuantumCircuit(max_num_qubits + 1) for indices in entangler_map: reference.append(block, indices) self.assertCircuitEqual(nlocal, reference) @data([5, 3], [1, 5], [1, 1], [1, 2, 3, 10]) def test_append_circuit(self, num_qubits): """Test appending circuits to an nlocal works normally.""" # fixed depth of 3 gates per circuit depth = 3 # keep track of a reference circuit reference = QuantumCircuit(max(num_qubits)) # construct the NLocal from the first circuit first_circuit = random_circuit(num_qubits[0], depth, seed=4200) # TODO Terra bug: if this is to_gate it fails, since the QC adds an instruction not gate nlocal = NLocal(max(num_qubits), entanglement_blocks=first_circuit.to_instruction(), reps=1) reference.append(first_circuit, list(range(num_qubits[0]))) # append the rest for num in num_qubits[1:]: circuit = random_circuit(num, depth, seed=4200) nlocal.append(circuit, list(range(num))) reference.append(circuit, list(range(num))) self.assertCircuitEqual(nlocal, reference) @data([5, 3], [1, 5], [1, 1], [1, 2, 3, 10]) def test_add_nlocal(self, num_qubits): """Test adding an nlocal to an nlocal (using add_layer).""" # fixed depth of 3 gates per circuit depth = 3 # keep track of a reference circuit reference = QuantumCircuit(max(num_qubits)) # construct the NLocal from the first circuit first_circuit = random_circuit(num_qubits[0], depth, seed=4220) # TODO Terra bug: if this is to_gate it fails, since the QC adds an instruction not gate nlocal = NLocal(max(num_qubits), entanglement_blocks=first_circuit.to_instruction(), reps=1) nlocal2 = nlocal.copy() _ = nlocal2.data reference.append(first_circuit, list(range(num_qubits[0]))) # append the rest for num in num_qubits[1:]: circuit = random_circuit(num, depth, seed=4220) layer = NLocal(num, entanglement_blocks=circuit, reps=1) nlocal.add_layer(layer) nlocal2.add_layer(layer) reference.append(circuit, list(range(num))) self.assertCircuitEqual(nlocal, reference) self.assertCircuitEqual(nlocal2, reference) @unittest.skip("Feature missing") def test_iadd_overload(self): """Test the overloaded + operator.""" num_qubits, depth = 2, 2 # construct two circuits for adding first_circuit = random_circuit(num_qubits, depth, seed=4242) circuit = random_circuit(num_qubits, depth, seed=4242) # get a reference reference = first_circuit + circuit # convert the object to be appended to different types others = [circuit, circuit.to_instruction(), circuit.to_gate(), NLocal(circuit)] # try adding each type for other in others: nlocal = NLocal(num_qubits, entanglement_blocks=first_circuit, reps=1) nlocal += other with self.subTest(msg=f"type: {type(other)}"): self.assertCircuitEqual(nlocal, reference) def test_parameter_getter_from_automatic_repetition(self): """Test getting and setting of the nlocal parameters.""" circuit = QuantumCircuit(2) circuit.ry(Parameter("a"), 0) circuit.crx(Parameter("b"), 0, 1) # repeat circuit and check that parameters are duplicated reps = 3 nlocal = NLocal(2, entanglement_blocks=circuit, reps=reps) self.assertTrue(nlocal.num_parameters, 6) self.assertTrue(len(nlocal.parameters), 6) @data(list(range(6)), ParameterVector("θ", length=6), [0, 1, Parameter("theta"), 3, 4, 5]) def test_parameter_setter_from_automatic_repetition(self, params): """Test getting and setting of the nlocal parameters.""" circuit = QuantumCircuit(2) circuit.ry(Parameter("a"), 0) circuit.crx(Parameter("b"), 0, 1) # repeat circuit and check that parameters are duplicated reps = 3 nlocal = NLocal(2, entanglement_blocks=circuit, reps=reps) nlocal.assign_parameters(params, inplace=True) param_set = {p for p in params if isinstance(p, ParameterExpression)} with self.subTest(msg="Test the parameters of the non-transpiled circuit"): # check the parameters of the final circuit self.assertEqual(nlocal.parameters, param_set) with self.subTest(msg="Test the parameters of the transpiled circuit"): basis_gates = ["id", "u1", "u2", "u3", "cx"] transpiled_circuit = transpile(nlocal, basis_gates=basis_gates) self.assertEqual(transpiled_circuit.parameters, param_set) @data(list(range(6)), ParameterVector("θ", length=6), [0, 1, Parameter("theta"), 3, 4, 5]) def test_parameters_setter(self, params): """Test setting the parameters via list.""" # construct circuit with some parameters initial_params = ParameterVector("p", length=6) circuit = QuantumCircuit(1) for i, initial_param in enumerate(initial_params): circuit.ry(i * initial_param, 0) # create an NLocal from the circuit and set the new parameters nlocal = NLocal(1, entanglement_blocks=circuit, reps=1) nlocal.assign_parameters(params, inplace=True) param_set = {p for p in params if isinstance(p, ParameterExpression)} with self.subTest(msg="Test the parameters of the non-transpiled circuit"): # check the parameters of the final circuit self.assertEqual(nlocal.parameters, param_set) with self.subTest(msg="Test the parameters of the transpiled circuit"): basis_gates = ["id", "u1", "u2", "u3", "cx"] transpiled_circuit = transpile(nlocal, basis_gates=basis_gates) self.assertEqual(transpiled_circuit.parameters, param_set) def test_repetetive_parameter_setting(self): """Test alternate setting of parameters and circuit construction.""" x = Parameter("x") circuit = QuantumCircuit(1) circuit.rx(x, 0) nlocal = NLocal(1, entanglement_blocks=circuit, reps=3, insert_barriers=True) with self.subTest(msg="immediately after initialization"): self.assertEqual(len(nlocal.parameters), 3) with self.subTest(msg="after circuit construction"): self.assertEqual(len(nlocal.parameters), 3) q = Parameter("q") nlocal.assign_parameters([x, q, q], inplace=True) with self.subTest(msg="setting parameter to Parameter objects"): self.assertEqual(nlocal.parameters, set({x, q})) nlocal.assign_parameters([0, -1], inplace=True) with self.subTest(msg="setting parameter to numbers"): self.assertEqual(nlocal.parameters, set()) def test_skip_unentangled_qubits(self): """Test skipping the unentangled qubits.""" num_qubits = 6 entanglement_1 = [[0, 1, 3], [1, 3, 5], [0, 1, 5]] skipped_1 = [2, 4] entanglement_2 = [entanglement_1, [[0, 1, 2], [2, 3, 5]]] skipped_2 = [4] for entanglement, skipped in zip([entanglement_1, entanglement_2], [skipped_1, skipped_2]): with self.subTest(entanglement=entanglement, skipped=skipped): nlocal = NLocal( num_qubits, rotation_blocks=XGate(), entanglement_blocks=CCXGate(), entanglement=entanglement, reps=3, skip_unentangled_qubits=True, ) decomposed = nlocal.decompose() skipped_set = {decomposed.qubits[i] for i in skipped} dag = circuit_to_dag(decomposed) idle = set(dag.idle_wires()) self.assertEqual(skipped_set, idle) @data( "linear", "full", "circular", "sca", "reverse_linear", ["linear", "full"], ["reverse_linear", "full"], ["circular", "linear", "sca"], ) def test_entanglement_by_str(self, entanglement): """Test setting the entanglement of the layers by str.""" reps = 3 nlocal = NLocal( 5, rotation_blocks=XGate(), entanglement_blocks=CCXGate(), entanglement=entanglement, reps=reps, ) def get_expected_entangler_map(rep_num, mode): if mode == "linear": return [(0, 1, 2), (1, 2, 3), (2, 3, 4)] elif mode == "reverse_linear": return [(2, 3, 4), (1, 2, 3), (0, 1, 2)] elif mode == "full": return [ (0, 1, 2), (0, 1, 3), (0, 1, 4), (0, 2, 3), (0, 2, 4), (0, 3, 4), (1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4), ] else: circular = [(3, 4, 0), (0, 1, 2), (1, 2, 3), (2, 3, 4)] if mode == "circular": return circular sca = circular[-rep_num:] + circular[:-rep_num] if rep_num % 2 == 1: sca = [tuple(reversed(indices)) for indices in sca] return sca for rep_num in range(reps): entangler_map = nlocal.get_entangler_map(rep_num, 0, 3) if isinstance(entanglement, list): mode = entanglement[rep_num % len(entanglement)] else: mode = entanglement expected = get_expected_entangler_map(rep_num, mode) with self.subTest(rep_num=rep_num): # using a set here since the order does not matter self.assertEqual(entangler_map, expected) def test_pairwise_entanglement(self): """Test pairwise entanglement.""" nlocal = NLocal( 5, rotation_blocks=XGate(), entanglement_blocks=CXGate(), entanglement="pairwise", reps=1, ) entangler_map = nlocal.get_entangler_map(0, 0, 2) pairwise = [(0, 1), (2, 3), (1, 2), (3, 4)] self.assertEqual(pairwise, entangler_map) def test_pairwise_entanglement_raises(self): """Test choosing pairwise entanglement raises an error for too large blocks.""" nlocal = NLocal(3, XGate(), CCXGate(), entanglement="pairwise", reps=1) # pairwise entanglement is only defined if the entangling gate has 2 qubits with self.assertRaises(ValueError): print(nlocal.draw()) def test_entanglement_by_list(self): """Test setting the entanglement by list. This is the circuit we test (times 2, with final X layer) ┌───┐ ┌───┐┌───┐ ┌───┐ q_0: |0>┤ X ├──■────■───X────┤ X ├┤ X ├──■───X─────── .. ┤ X ├ ├───┤ │ │ │ ├───┤└─┬─┘ │ │ ├───┤ q_1: |0>┤ X ├──■────┼───┼──X─┤ X ├──■────┼───X──X──── .. ┤ X ├ ├───┤┌─┴─┐ │ │ │ ├───┤ │ │ │ x2 ├───┤ q_2: |0>┤ X ├┤ X ├──■───┼──X─┤ X ├──■────■──────X──X─ .. ┤ X ├ ├───┤└───┘┌─┴─┐ │ ├───┤ ┌─┴─┐ │ ├───┤ q_3: |0>┤ X ├─────┤ X ├─X────┤ X ├─────┤ X ├───────X─ .. ┤ X ├ └───┘ └───┘ └───┘ └───┘ └───┘ """ circuit = QuantumCircuit(4) for _ in range(2): circuit.x([0, 1, 2, 3]) circuit.barrier() circuit.ccx(0, 1, 2) circuit.ccx(0, 2, 3) circuit.swap(0, 3) circuit.swap(1, 2) circuit.barrier() circuit.x([0, 1, 2, 3]) circuit.barrier() circuit.ccx(2, 1, 0) circuit.ccx(0, 2, 3) circuit.swap(0, 1) circuit.swap(1, 2) circuit.swap(2, 3) circuit.barrier() circuit.x([0, 1, 2, 3]) layer_1_ccx = [(0, 1, 2), (0, 2, 3)] layer_1_swap = [(0, 3), (1, 2)] layer_1 = [layer_1_ccx, layer_1_swap] layer_2_ccx = [(2, 1, 0), (0, 2, 3)] layer_2_swap = [(0, 1), (1, 2), (2, 3)] layer_2 = [layer_2_ccx, layer_2_swap] entanglement = [layer_1, layer_2] nlocal = NLocal( 4, rotation_blocks=XGate(), entanglement_blocks=[CCXGate(), SwapGate()], reps=4, entanglement=entanglement, insert_barriers=True, ) self.assertCircuitEqual(nlocal, circuit) def test_initial_state_as_circuit_object(self): """Test setting `initial_state` to `QuantumCircuit` object""" # ┌───┐ ┌───┐ # q_0: ──■──┤ X ├───────■──┤ X ├ # ┌─┴─┐├───┤┌───┐┌─┴─┐├───┤ # q_1: ┤ X ├┤ H ├┤ X ├┤ X ├┤ X ├ # └───┘└───┘└───┘└───┘└───┘ ref = QuantumCircuit(2) ref.cx(0, 1) ref.x(0) ref.h(1) ref.x(1) ref.cx(0, 1) ref.x(0) ref.x(1) qc = QuantumCircuit(2) qc.cx(0, 1) qc.h(1) expected = NLocal( num_qubits=2, rotation_blocks=XGate(), entanglement_blocks=CXGate(), initial_state=qc, reps=1, ) self.assertCircuitEqual(ref, expected) @ddt class TestTwoLocal(QiskitTestCase): """Tests for the TwoLocal circuit.""" def assertCircuitEqual(self, qc1, qc2, visual=False, transpiled=True): """An equality test specialized to circuits.""" if transpiled: basis_gates = ["id", "u1", "u3", "cx"] qc1_transpiled = transpile(qc1, basis_gates=basis_gates, optimization_level=0) qc2_transpiled = transpile(qc2, basis_gates=basis_gates, optimization_level=0) qc1, qc2 = qc1_transpiled, qc2_transpiled if visual: self.assertEqual(qc1.draw(), qc2.draw()) else: self.assertEqual(qc1, qc2) def test_skip_final_rotation_layer(self): """Test skipping the final rotation layer works.""" two = TwoLocal(3, ["ry", "h"], ["cz", "cx"], reps=2, skip_final_rotation_layer=True) self.assertEqual(two.num_parameters, 6) # would be 9 with a final rotation layer @data( (5, "rx", "cx", "full", 2, 15), (3, "x", "z", "linear", 1, 0), (3, "rx", "cz", "linear", 0, 3), (3, ["rx", "ry"], ["cry", "cx"], "circular", 2, 24), ) @unpack def test_num_parameters(self, num_qubits, rot, ent, ent_mode, reps, expected): """Test the number of parameters.""" two = TwoLocal( num_qubits, rotation_blocks=rot, entanglement_blocks=ent, entanglement=ent_mode, reps=reps, ) with self.subTest(msg="num_parameters_settable"): self.assertEqual(two.num_parameters_settable, expected) with self.subTest(msg="num_parameters"): self.assertEqual(two.num_parameters, expected) def test_empty_two_local(self): """Test the setup of an empty two-local circuit.""" two = TwoLocal() with self.subTest(msg="0 qubits"): self.assertEqual(two.num_qubits, 0) with self.subTest(msg="no blocks are set"): self.assertListEqual(two.rotation_blocks, []) self.assertListEqual(two.entanglement_blocks, []) with self.subTest(msg="equal to empty circuit"): self.assertEqual(two, QuantumCircuit()) @data("rx", RXGate(Parameter("p")), RXGate, "circuit") def test_various_block_types(self, rot): """Test setting the rotation blocks to various type and assert the output type is RX.""" if rot == "circuit": rot = QuantumCircuit(1) rot.rx(Parameter("angle"), 0) two = TwoLocal(3, rot, reps=0) self.assertEqual(len(two.rotation_blocks), 1) rotation = two.rotation_blocks[0] # decompose self.assertIsInstance(rotation.data[0].operation, RXGate) def test_parameter_setters(self): """Test different possibilities to set parameters.""" two = TwoLocal(3, rotation_blocks="rx", entanglement="cz", reps=2) params = [0, 1, 2, Parameter("x"), Parameter("y"), Parameter("z"), 6, 7, 0] params_set = {param for param in params if isinstance(param, Parameter)} with self.subTest(msg="dict assign and copy"): ordered = two.ordered_parameters bound = two.assign_parameters(dict(zip(ordered, params)), inplace=False) self.assertEqual(bound.parameters, params_set) self.assertEqual(two.num_parameters, 9) with self.subTest(msg="list assign and copy"): ordered = two.ordered_parameters bound = two.assign_parameters(params, inplace=False) self.assertEqual(bound.parameters, params_set) self.assertEqual(two.num_parameters, 9) with self.subTest(msg="list assign inplace"): ordered = two.ordered_parameters two.assign_parameters(params, inplace=True) self.assertEqual(two.parameters, params_set) self.assertEqual(two.num_parameters, 3) self.assertEqual(two.num_parameters_settable, 9) def test_parameters_settable_is_constant(self): """Test the attribute num_parameters_settable does not change on parameter change.""" two = TwoLocal(3, rotation_blocks="rx", entanglement="cz", reps=2) ordered_params = two.ordered_parameters x = Parameter("x") two.assign_parameters(dict(zip(ordered_params, [x] * two.num_parameters)), inplace=True) with self.subTest(msg="num_parameters collapsed to 1"): self.assertEqual(two.num_parameters, 1) with self.subTest(msg="num_parameters_settable remained constant"): self.assertEqual(two.num_parameters_settable, len(ordered_params)) def test_compose_inplace_to_circuit(self): """Test adding a two-local to an existing circuit.""" two = TwoLocal(3, ["ry", "rz"], "cz", "full", reps=1, insert_barriers=True) circuit = QuantumCircuit(3) circuit.compose(two, inplace=True) # ┌──────────┐┌──────────┐ ░ ░ ┌──────────┐ ┌──────────┐ # q_0: ┤ Ry(θ[0]) ├┤ Rz(θ[3]) ├─░──■──■─────░─┤ Ry(θ[6]) ├─┤ Rz(θ[9]) ├ # ├──────────┤├──────────┤ ░ │ │ ░ ├──────────┤┌┴──────────┤ # q_1: ┤ Ry(θ[1]) ├┤ Rz(θ[4]) ├─░──■──┼──■──░─┤ Ry(θ[7]) ├┤ Rz(θ[10]) ├ # ├──────────┤├──────────┤ ░ │ │ ░ ├──────────┤├───────────┤ # q_2: ┤ Ry(θ[2]) ├┤ Rz(θ[5]) ├─░─────■──■──░─┤ Ry(θ[8]) ├┤ Rz(θ[11]) ├ # └──────────┘└──────────┘ ░ ░ └──────────┘└───────────┘ reference = QuantumCircuit(3) param_iter = iter(two.ordered_parameters) for i in range(3): reference.ry(next(param_iter), i) for i in range(3): reference.rz(next(param_iter), i) reference.barrier() reference.cz(0, 1) reference.cz(0, 2) reference.cz(1, 2) reference.barrier() for i in range(3): reference.ry(next(param_iter), i) for i in range(3): reference.rz(next(param_iter), i) self.assertCircuitEqual(circuit.decompose(), reference) def test_composing_two(self): """Test adding two two-local circuits.""" entangler_map = [[0, 3], [0, 2]] two = TwoLocal(4, [], "cry", entangler_map, reps=1) circuit = two.compose(two) reference = QuantumCircuit(4) params = two.ordered_parameters for _ in range(2): reference.cry(params[0], 0, 3) reference.cry(params[1], 0, 2) self.assertCircuitEqual(reference, circuit) def test_ry_blocks(self): """Test that the RealAmplitudes circuit is instantiated correctly.""" two = RealAmplitudes(4) with self.subTest(msg="test rotation gate"): self.assertEqual(len(two.rotation_blocks), 1) self.assertIsInstance(two.rotation_blocks[0].data[0].operation, RYGate) with self.subTest(msg="test parameter bounds"): expected = [(-np.pi, np.pi)] * two.num_parameters np.testing.assert_almost_equal(two.parameter_bounds, expected) def test_ry_circuit_reverse_linear(self): """Test a RealAmplitudes circuit with entanglement = "reverse_linear".""" num_qubits = 3 reps = 2 entanglement = "reverse_linear" parameters = ParameterVector("theta", num_qubits * (reps + 1)) param_iter = iter(parameters) expected = QuantumCircuit(3) for _ in range(reps): for i in range(num_qubits): expected.ry(next(param_iter), i) expected.cx(1, 2) expected.cx(0, 1) for i in range(num_qubits): expected.ry(next(param_iter), i) library = RealAmplitudes( num_qubits, reps=reps, entanglement=entanglement ).assign_parameters(parameters) self.assertCircuitEqual(library, expected) def test_ry_circuit_full(self): """Test a RealAmplitudes circuit with entanglement = "full".""" num_qubits = 3 reps = 2 entanglement = "full" parameters = ParameterVector("theta", num_qubits * (reps + 1)) param_iter = iter(parameters) # ┌──────────┐ ┌──────────┐ ┌──────────┐ # q_0: ┤ Ry(θ[0]) ├──■────■──┤ Ry(θ[3]) ├──────────────■────■──┤ Ry(θ[6]) ├──────────── # ├──────────┤┌─┴─┐ │ └──────────┘┌──────────┐┌─┴─┐ │ └──────────┘┌──────────┐ # q_1: ┤ Ry(θ[1]) ├┤ X ├──┼─────────■────┤ Ry(θ[4]) ├┤ X ├──┼─────────■────┤ Ry(θ[7]) ├ # ├──────────┤└───┘┌─┴─┐ ┌─┴─┐ ├──────────┤└───┘┌─┴─┐ ┌─┴─┐ ├──────────┤ # q_2: ┤ Ry(θ[2]) ├─────┤ X ├─────┤ X ├──┤ Ry(θ[5]) ├─────┤ X ├─────┤ X ├──┤ Ry(θ[8]) ├ # └──────────┘ └───┘ └───┘ └──────────┘ └───┘ └───┘ └──────────┘ expected = QuantumCircuit(3) for _ in range(reps): for i in range(num_qubits): expected.ry(next(param_iter), i) expected.cx(0, 1) expected.cx(0, 2) expected.cx(1, 2) for i in range(num_qubits): expected.ry(next(param_iter), i) library = RealAmplitudes( num_qubits, reps=reps, entanglement=entanglement ).assign_parameters(parameters) self.assertCircuitEqual(library, expected) def test_ryrz_blocks(self): """Test that the EfficientSU2 circuit is instantiated correctly.""" two = EfficientSU2(3) with self.subTest(msg="test rotation gate"): self.assertEqual(len(two.rotation_blocks), 2) self.assertIsInstance(two.rotation_blocks[0].data[0].operation, RYGate) self.assertIsInstance(two.rotation_blocks[1].data[0].operation, RZGate) with self.subTest(msg="test parameter bounds"): expected = [(-np.pi, np.pi)] * two.num_parameters np.testing.assert_almost_equal(two.parameter_bounds, expected) def test_ryrz_circuit(self): """Test an EfficientSU2 circuit.""" num_qubits = 3 reps = 2 entanglement = "circular" parameters = ParameterVector("theta", 2 * num_qubits * (reps + 1)) param_iter = iter(parameters) # ┌──────────┐┌──────────┐┌───┐ ┌──────────┐┌──────────┐ » # q_0: ┤ Ry(θ[0]) ├┤ Rz(θ[3]) ├┤ X ├──■──┤ Ry(θ[6]) ├┤ Rz(θ[9]) ├─────────────» # ├──────────┤├──────────┤└─┬─┘┌─┴─┐└──────────┘├──────────┤┌───────────┐» # q_1: ┤ Ry(θ[1]) ├┤ Rz(θ[4]) ├──┼──┤ X ├─────■──────┤ Ry(θ[7]) ├┤ Rz(θ[10]) ├» # ├──────────┤├──────────┤ │ └───┘ ┌─┴─┐ ├──────────┤├───────────┤» # q_2: ┤ Ry(θ[2]) ├┤ Rz(θ[5]) ├──■──────────┤ X ├────┤ Ry(θ[8]) ├┤ Rz(θ[11]) ├» # └──────────┘└──────────┘ └───┘ └──────────┘└───────────┘» # « ┌───┐ ┌───────────┐┌───────────┐ # «q_0: ┤ X ├──■──┤ Ry(θ[12]) ├┤ Rz(θ[15]) ├───────────── # « └─┬─┘┌─┴─┐└───────────┘├───────────┤┌───────────┐ # «q_1: ──┼──┤ X ├──────■──────┤ Ry(θ[13]) ├┤ Rz(θ[16]) ├ # « │ └───┘ ┌─┴─┐ ├───────────┤├───────────┤ # «q_2: ──■───────────┤ X ├────┤ Ry(θ[14]) ├┤ Rz(θ[17]) ├ # « └───┘ └───────────┘└───────────┘ expected = QuantumCircuit(3) for _ in range(reps): for i in range(num_qubits): expected.ry(next(param_iter), i) for i in range(num_qubits): expected.rz(next(param_iter), i) expected.cx(2, 0) expected.cx(0, 1) expected.cx(1, 2) for i in range(num_qubits): expected.ry(next(param_iter), i) for i in range(num_qubits): expected.rz(next(param_iter), i) library = EfficientSU2(num_qubits, reps=reps, entanglement=entanglement).assign_parameters( parameters ) self.assertCircuitEqual(library, expected) def test_swaprz_blocks(self): """Test that the ExcitationPreserving circuit is instantiated correctly.""" two = ExcitationPreserving(5) with self.subTest(msg="test rotation gate"): self.assertEqual(len(two.rotation_blocks), 1) self.assertIsInstance(two.rotation_blocks[0].data[0].operation, RZGate) with self.subTest(msg="test entanglement gate"): self.assertEqual(len(two.entanglement_blocks), 1) block = two.entanglement_blocks[0] self.assertEqual(len(block.data), 2) self.assertIsInstance(block.data[0].operation, RXXGate) self.assertIsInstance(block.data[1].operation, RYYGate) with self.subTest(msg="test parameter bounds"): expected = [(-np.pi, np.pi)] * two.num_parameters np.testing.assert_almost_equal(two.parameter_bounds, expected) def test_swaprz_circuit(self): """Test a ExcitationPreserving circuit in iswap mode.""" num_qubits = 3 reps = 2 entanglement = "linear" parameters = ParameterVector("theta", num_qubits * (reps + 1) + reps * (num_qubits - 1)) param_iter = iter(parameters) # ┌──────────┐┌────────────┐┌────────────┐ ┌──────────┐ » # q_0: ┤ Rz(θ[0]) ├┤0 ├┤0 ├─┤ Rz(θ[5]) ├───────────────» # ├──────────┤│ Rxx(θ[3]) ││ Ryy(θ[3]) │┌┴──────────┴┐┌────────────┐» # q_1: ┤ Rz(θ[1]) ├┤1 ├┤1 ├┤0 ├┤0 ├» # ├──────────┤└────────────┘└────────────┘│ Rxx(θ[4]) ││ Ryy(θ[4]) │» # q_2: ┤ Rz(θ[2]) ├────────────────────────────┤1 ├┤1 ├» # └──────────┘ └────────────┘└────────────┘» # « ┌────────────┐┌────────────┐┌───────────┐ » # «q_0: ────────────┤0 ├┤0 ├┤ Rz(θ[10]) ├───────────────» # « ┌──────────┐│ Rxx(θ[8]) ││ Ryy(θ[8]) │├───────────┴┐┌────────────┐» # «q_1: ┤ Rz(θ[6]) ├┤1 ├┤1 ├┤0 ├┤0 ├» # « ├──────────┤└────────────┘└────────────┘│ Rxx(θ[9]) ││ Ryy(θ[9]) │» # «q_2: ┤ Rz(θ[7]) ├────────────────────────────┤1 ├┤1 ├» # « └──────────┘ └────────────┘└────────────┘» # « # «q_0: ───────────── # « ┌───────────┐ # «q_1: ┤ Rz(θ[11]) ├ # « ├───────────┤ # «q_2: ┤ Rz(θ[12]) ├ # « └───────────┘ expected = QuantumCircuit(3) for _ in range(reps): for i in range(num_qubits): expected.rz(next(param_iter), i) shared_param = next(param_iter) expected.rxx(shared_param, 0, 1) expected.ryy(shared_param, 0, 1) shared_param = next(param_iter) expected.rxx(shared_param, 1, 2) expected.ryy(shared_param, 1, 2) for i in range(num_qubits): expected.rz(next(param_iter), i) library = ExcitationPreserving( num_qubits, reps=reps, entanglement=entanglement ).assign_parameters(parameters) self.assertCircuitEqual(library, expected) def test_fsim_circuit(self): """Test a ExcitationPreserving circuit in fsim mode.""" num_qubits = 3 reps = 2 entanglement = "linear" # need the parameters in the entanglement blocks to be the same because the order # can get mixed up in ExcitationPreserving (since parameters are not ordered in circuits) parameters = [1] * (num_qubits * (reps + 1) + reps * (1 + num_qubits)) param_iter = iter(parameters) # ┌───────┐┌─────────┐┌─────────┐ ┌───────┐ » # q_0: ┤ Rz(1) ├┤0 ├┤0 ├─■──────┤ Rz(1) ├───────────────────» # ├───────┤│ Rxx(1) ││ Ryy(1) │ │P(1) ┌┴───────┴┐┌─────────┐ » # q_1: ┤ Rz(1) ├┤1 ├┤1 ├─■─────┤0 ├┤0 ├─■─────» # ├───────┤└─────────┘└─────────┘ │ Rxx(1) ││ Ryy(1) │ │P(1) » # q_2: ┤ Rz(1) ├─────────────────────────────┤1 ├┤1 ├─■─────» # └───────┘ └─────────┘└─────────┘ » # « ┌─────────┐┌─────────┐ ┌───────┐ » # «q_0: ─────────┤0 ├┤0 ├─■──────┤ Rz(1) ├───────────────────» # « ┌───────┐│ Rxx(1) ││ Ryy(1) │ │P(1) ┌┴───────┴┐┌─────────┐ » # «q_1: ┤ Rz(1) ├┤1 ├┤1 ├─■─────┤0 ├┤0 ├─■─────» # « ├───────┤└─────────┘└─────────┘ │ Rxx(1) ││ Ryy(1) │ │P(1) » # «q_2: ┤ Rz(1) ├─────────────────────────────┤1 ├┤1 ├─■─────» # « └───────┘ └─────────┘└─────────┘ » # « # «q_0: ───────── # « ┌───────┐ # «q_1: ┤ Rz(1) ├ # « ├───────┤ # «q_2: ┤ Rz(1) ├ # « └───────┘ expected = QuantumCircuit(3) for _ in range(reps): for i in range(num_qubits): expected.rz(next(param_iter), i) shared_param = next(param_iter) expected.rxx(shared_param, 0, 1) expected.ryy(shared_param, 0, 1) expected.cp(next(param_iter), 0, 1) shared_param = next(param_iter) expected.rxx(shared_param, 1, 2) expected.ryy(shared_param, 1, 2) expected.cp(next(param_iter), 1, 2) for i in range(num_qubits): expected.rz(next(param_iter), i) library = ExcitationPreserving( num_qubits, reps=reps, mode="fsim", entanglement=entanglement ).assign_parameters(parameters) self.assertCircuitEqual(library, expected) def test_circular_on_same_block_and_circuit_size(self): """Test circular entanglement works correctly if the circuit and block sizes match.""" two = TwoLocal(2, "ry", "cx", entanglement="circular", reps=1) parameters = np.arange(two.num_parameters) # ┌───────┐ ┌───────┐ # q_0: ┤ Ry(0) ├──■──┤ Ry(2) ├ # ├───────┤┌─┴─┐├───────┤ # q_1: ┤ Ry(1) ├┤ X ├┤ Ry(3) ├ # └───────┘└───┘└───────┘ ref = QuantumCircuit(2) ref.ry(parameters[0], 0) ref.ry(parameters[1], 1) ref.cx(0, 1) ref.ry(parameters[2], 0) ref.ry(parameters[3], 1) self.assertCircuitEqual(two.assign_parameters(parameters), ref) def test_circuit_with_numpy_integers(self): """Test if TwoLocal can be made from numpy integers""" num_qubits = 6 reps = 3 expected_np32 = [ (i, j) for i in np.arange(num_qubits, dtype=np.int32) for j in np.arange(num_qubits, dtype=np.int32) if i < j ] expected_np64 = [ (i, j) for i in np.arange(num_qubits, dtype=np.int64) for j in np.arange(num_qubits, dtype=np.int64) if i < j ] two_np32 = TwoLocal(num_qubits, "ry", "cx", entanglement=expected_np32, reps=reps) two_np64 = TwoLocal(num_qubits, "ry", "cx", entanglement=expected_np64, reps=reps) expected_cx = reps * num_qubits * (num_qubits - 1) / 2 self.assertEqual(two_np32.decompose().count_ops()["cx"], expected_cx) self.assertEqual(two_np64.decompose().count_ops()["cx"], expected_cx) @combine(num_qubits=[4, 5]) def test_full_vs_reverse_linear(self, num_qubits): """Test that 'full' and 'reverse_linear' provide the same unitary element.""" reps = 2 full = RealAmplitudes(num_qubits=num_qubits, entanglement="full", reps=reps) num_params = (reps + 1) * num_qubits np.random.seed(num_qubits) params = np.random.rand(num_params) reverse = RealAmplitudes(num_qubits=num_qubits, entanglement="reverse_linear", reps=reps) full.assign_parameters(params, inplace=True) reverse.assign_parameters(params, inplace=True) self.assertEqual(Operator(full), Operator(reverse)) if __name__ == "__main__": unittest.main()
https://github.com/qBraid/qBraid
qBraid
# Copyright (C) 2024 qBraid # # This file is part of the qBraid-SDK # # The qBraid-SDK is free software released under the GNU General Public License v3 # or later. You can redistribute and/or modify it under the terms of the GPL v3. # See the LICENSE file in the project root or <https://www.gnu.org/licenses/gpl-3.0.html>. # # THERE IS NO WARRANTY for the qBraid-SDK, as per Section 15 of the GPL v3. """ Unit tests for qbraid.programs.qiskit.QiskitCircuit """ import pytest from qiskit import QuantumCircuit from qbraid.programs.circuits.qiskit import QiskitCircuit from qbraid.programs.exceptions import ProgramTypeError def test_reverse_qubit_order(): """Test reversing ordering of qubits in qiskit circuit""" circ = QuantumCircuit(3) circ.h(0) circ.cx(0, 2) qprogram = QiskitCircuit(circ) qprogram.reverse_qubit_order() reversed_circ = qprogram.program expected_circ = QuantumCircuit(3) expected_circ.h(2) expected_circ.cx(2, 0) assert ( reversed_circ == expected_circ ), "The reversed circuit does not match the expected output." def test_remove_idle_qubits_qiskit(): """Test convert_to_contigious on qiskit circuit""" circuit = QuantumCircuit(3) circuit.h(0) circuit.cx(0, 1) qprogram = QiskitCircuit(circuit) qprogram.remove_idle_qubits() contig_circuit = qprogram.program assert contig_circuit.num_qubits == 2 def test_raise_program_type_error(): """Test raising ProgramTypeError""" with pytest.raises(ProgramTypeError): QiskitCircuit("OPENQASM 2.0;qreg q[2];h q[0];cx q[0],q[1];") def test_circuit_properties(): """Test properties of QiskitCircuit""" circuit = QuantumCircuit(2) circuit.h(0) circuit.cx(0, 1) qprogram = QiskitCircuit(circuit) assert len(qprogram.qubits) == 2 assert qprogram.num_qubits == 2 assert qprogram.num_clbits == 0 assert qprogram.depth == 2
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/lynnlangit/learning-quantum
lynnlangit
try: import cirq except ImportError: print("installing cirq...") !pip install --quiet cirq print("installed cirq.") import fractions import math import random import matplotlib.pyplot as plt import numpy as np import sympy from typing import Callable, List, Optional, Sequence, Union import cirq #import cirq_google print(cirq.google.Foxtail) # verify cirq, should print a circuit as shown belown # (0, 0)───(0, 1)───(0, 2)───(0, 3)───(0, 4)───(0, 5)───(0, 6)───(0, 7)───(0, 8)───(0, 9)───(0, 10) # │ │ │ │ │ │ │ │ │ │ │ # │ │ │ │ │ │ │ │ │ │ │ # (1, 0)───(1, 1)───(1, 2)───(1, 3)───(1, 4)───(1, 5)───(1, 6)───(1, 7)───(1, 8)───(1, 9)───(1, 10) def classical_order_finder(x: int, n: int) -> Optional[int]: # Make sure x is both valid and in Z_n. if x < 2 or x >= n or math.gcd(x, n) > 1: raise ValueError(f"Invalid x={x} for modulus n={n}.") # Determine the order. r, y = 1, x while y != 1: y = (x * y) % n r += 1 return r n = 15 # The multiplicative group is [1, 2, 4, 7, 8, 11, 13, 14]. x = 8 r = classical_order_finder(x, n) # Check that the order is indeed correct. print(f"x^r mod n = {x}^{r} mod {n} = {x**r % n}") class ModularExp(cirq.ArithmeticOperation): def __init__( self, target: Sequence[cirq.Qid], exponent: Union[int, Sequence[cirq.Qid]], base: int, modulus: int ) -> None: if len(target) < modulus.bit_length(): raise ValueError(f'Register with {len(target)} qubits is too small ' f'for modulus {modulus}') self.target = target self.exponent = exponent self.base = base self.modulus = modulus def registers(self) -> Sequence[Union[int, Sequence[cirq.Qid]]]: return self.target, self.exponent, self.base, self.modulus def with_registers( self, *new_registers: Union[int, Sequence['cirq.Qid']], ) -> cirq.ArithmeticOperation: if len(new_registers) != 4: raise ValueError(f'Expected 4 registers (target, exponent, base, ' f'modulus), but got {len(new_registers)}') target, exponent, base, modulus = new_registers if not isinstance(target, Sequence): raise ValueError( f'Target must be a qubit register, got {type(target)}') if not isinstance(base, int): raise ValueError( f'Base must be a classical constant, got {type(base)}') if not isinstance(modulus, int): raise ValueError( f'Modulus must be a classical constant, got {type(modulus)}') return ModularExp(target, exponent, base, modulus) def apply(self, *register_values: int) -> int: assert len(register_values) == 4 target, exponent, base, modulus = register_values if target >= modulus: return target return (target * base**exponent) % modulus def _circuit_diagram_info_( self, args: cirq.CircuitDiagramInfoArgs, ) -> cirq.CircuitDiagramInfo: assert args.known_qubits is not None wire_symbols: List[str] = [] t, e = 0, 0 for qubit in args.known_qubits: if qubit in self.target: if t == 0: if isinstance(self.exponent, Sequence): e_str = 'e' else: e_str = str(self.exponent) wire_symbols.append( f'ModularExp(t*{self.base}**{e_str} % {self.modulus})') else: wire_symbols.append('t' + str(t)) t += 1 if isinstance(self.exponent, Sequence) and qubit in self.exponent: wire_symbols.append('e' + str(e)) e += 1 return cirq.CircuitDiagramInfo(wire_symbols=tuple(wire_symbols)) n = 15 L = n.bit_length() # The target register has L qubits. target = cirq.LineQubit.range(L) # The exponent register has 2L + 3 qubits. exponent = cirq.LineQubit.range(L, 3 * L + 3) # Display the total number of qubits to factor this n. print(f"To factor n = {n} which has L = {L} bits, we need 3L + 3 = {3 * L + 3} qubits.") def make_order_finding_circuit(x: int, n: int) -> cirq.Circuit: L = n.bit_length() target = cirq.LineQubit.range(L) exponent = cirq.LineQubit.range(L, 3 * L + 3) return cirq.Circuit( cirq.X(target[L - 1]), cirq.H.on_each(*exponent), ModularExp(target, exponent, x, n), cirq.qft(*exponent, inverse=True), cirq.measure(*exponent, key='exponent'), ) n = 15 x = 7 circuit = make_order_finding_circuit(x, n) print(circuit) circuit = make_order_finding_circuit(x=5, n=6) res = cirq.sample(circuit, repetitions=8) print("Raw measurements:") print(res) print("\nInteger in exponent register:") print(res.data) def binary_labels(num_qubits): return [bin(x)[2:].zfill(num_qubits) for x in range(2 ** num_qubits)] # Refactor this plot to use this cell's output # q = cirq.LineQubit.range(3) # circuit = cirq.Circuit([cirq.H.on_each(*q), cirq.measure(*q)]) # result = cirq.Simulator().run(circuit, repetitions=100) # _ = cirq.vis.plot_state_histogram(result, plt.subplot(), title = 'Integer in exponent Register', xlabel = 'Integer', ylabel = 'Count', tick_label=binary_labels(3)) def process_measurement(result: cirq.Result, x: int, n: int) -> Optional[int]: # Read the output integer of the exponent register. exponent_as_integer = result.data["exponent"][0] exponent_num_bits = result.measurements["exponent"].shape[1] eigenphase = float(exponent_as_integer / 2**exponent_num_bits) # Run the continued fractions algorithm to determine f = s / r. f = fractions.Fraction.from_float(eigenphase).limit_denominator(n) if f.numerator == 0: return None r = f.denominator if x**r % n != 1: return None return r n = 6 x = 5 print(f"Finding the order of x = {x} modulo n = {n}\n") measurement = cirq.sample(circuit, repetitions=1) print("Raw measurements:") print(measurement) print("\nInteger in exponent register:") print(measurement.data) r = process_measurement(measurement, x, n) print("\nOrder r =", r) if r is not None: print(f"x^r mod n = {x}^{r} mod {n} = {x**r % n}") def quantum_order_finder(x: int, n: int) -> Optional[int]: if x < 2 or n <= x or math.gcd(x, n) > 1: raise ValueError(f'Invalid x={x} for modulus n={n}.') circuit = make_order_finding_circuit(x, n) measurement = cirq.sample(circuit) return process_measurement(measurement, x, n) def find_factor_of_prime_power(n: int) -> Optional[int]: for k in range(2, math.floor(math.log2(n)) + 1): c = math.pow(n, 1 / k) c1 = math.floor(c) if c1**k == n: return c1 c2 = math.ceil(c) if c2**k == n: return c2 return None def find_factor( n: int, order_finder: Callable[[int, int], Optional[int]] = quantum_order_finder, max_attempts: int = 30 ) -> Optional[int]: if sympy.isprime(n): print("n is prime!") return None if n % 2 == 0: return 2 c = find_factor_of_prime_power(n) if c is not None: return c for _ in range(max_attempts): x = random.randint(2, n - 1) c = math.gcd(x, n) if 1 < c < n: return c r = order_finder(x, n) if r is None: continue if r % 2 != 0: continue y = x**(r // 2) % n assert 1 < y < n c = math.gcd(y - 1, n) if 1 < c < n: return c print(f"Failed to find a non-trivial factor in {max_attempts} attempts.") # return None # test with non-prime numbers only n = 184572 p = find_factor(n, order_finder=classical_order_finder) q = n // p p * q == n print("If p * q == n is True, then this answer is correct.") print("The result of " + str(p) + " * " + str(q) + " = "+ str(n) + " is " + str(p * q == n)) # 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.
https://github.com/IvanIsCoding/Quantum
IvanIsCoding
# initialization import numpy as np # importing Qiskit from qiskit import IBMQ, Aer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, transpile # import basic plot tools from qiskit.visualization import plot_histogram # set the length of the n-bit input string. n = 3 # set the length of the n-bit input string. n = 3 const_oracle = QuantumCircuit(n+1) output = np.random.randint(2) if output == 1: const_oracle.x(n) const_oracle.draw() balanced_oracle = QuantumCircuit(n+1) b_str = "101" balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) balanced_oracle.draw() balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Use barrier as divider balanced_oracle.barrier() # Controlled-NOT gates for qubit in range(n): balanced_oracle.cx(qubit, n) balanced_oracle.barrier() balanced_oracle.draw() balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Use barrier as divider balanced_oracle.barrier() # Controlled-NOT gates for qubit in range(n): balanced_oracle.cx(qubit, n) balanced_oracle.barrier() # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Show oracle balanced_oracle.draw() dj_circuit = QuantumCircuit(n+1, n) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) dj_circuit.draw() dj_circuit = QuantumCircuit(n+1, n) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) # Add oracle dj_circuit = dj_circuit.compose(balanced_oracle) dj_circuit.draw() dj_circuit = QuantumCircuit(n+1, n) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) # Add oracle dj_circuit = dj_circuit.compose(balanced_oracle) # Repeat H-gates for qubit in range(n): dj_circuit.h(qubit) dj_circuit.barrier() # Measure for i in range(n): dj_circuit.measure(i, i) # Display circuit dj_circuit.draw() # use local simulator aer_sim = Aer.get_backend('aer_simulator') results = aer_sim.run(dj_circuit).result() answer = results.get_counts() plot_histogram(answer) # ...we have a 0% chance of measuring 000. assert answer.get('000', 0) == 0 def dj_oracle(case, n): # We need to make a QuantumCircuit object to return # This circuit has n+1 qubits: the size of the input, # plus one output qubit oracle_qc = QuantumCircuit(n+1) # First, let's deal with the case in which oracle is balanced if case == "balanced": # First generate a random number that tells us which CNOTs to # wrap in X-gates: b = np.random.randint(1,2**n) # Next, format 'b' as a binary string of length 'n', padded with zeros: b_str = format(b, '0'+str(n)+'b') # Next, we place the first X-gates. Each digit in our binary string # corresponds to a qubit, if the digit is 0, we do nothing, if it's 1 # we apply an X-gate to that qubit: for qubit in range(len(b_str)): if b_str[qubit] == '1': oracle_qc.x(qubit) # Do the controlled-NOT gates for each qubit, using the output qubit # as the target: for qubit in range(n): oracle_qc.cx(qubit, n) # Next, place the final X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': oracle_qc.x(qubit) # Case in which oracle is constant if case == "constant": # First decide what the fixed output of the oracle will be # (either always 0 or always 1) output = np.random.randint(2) if output == 1: oracle_qc.x(n) oracle_gate = oracle_qc.to_gate() oracle_gate.name = "Oracle" # To show when we display the circuit return oracle_gate def dj_algorithm(oracle, n): dj_circuit = QuantumCircuit(n+1, n) # Set up the output qubit: dj_circuit.x(n) dj_circuit.h(n) # And set up the input register: for qubit in range(n): dj_circuit.h(qubit) # Let's append the oracle gate to our circuit: dj_circuit.append(oracle, range(n+1)) # Finally, perform the H-gates again and measure: for qubit in range(n): dj_circuit.h(qubit) for i in range(n): dj_circuit.measure(i, i) return dj_circuit n = 4 oracle_gate = dj_oracle('balanced', n) dj_circuit = dj_algorithm(oracle_gate, n) dj_circuit.draw() transpiled_dj_circuit = transpile(dj_circuit, aer_sim) results = aer_sim.run(transpiled_dj_circuit).result() answer = results.get_counts() plot_histogram(answer) # Load our saved IBMQ accounts and get the least busy backend device with greater than or equal to (n+1) qubits IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (n+1) and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) # Run our circuit on the least busy backend. Monitor the execution of the job in the queue from qiskit.tools.monitor import job_monitor transpiled_dj_circuit = transpile(dj_circuit, backend, optimization_level=3) job = backend.run(transpiled_dj_circuit) job_monitor(job, interval=2) # Get the results of the computation results = job.result() answer = results.get_counts() plot_histogram(answer) # ...the most likely result is 1111. assert max(answer, key=answer.get) == '1111' from qiskit_textbook.problems import dj_problem_oracle oracle = dj_problem_oracle(1) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/tomtuamnuq/compare-qiskit-ocean
tomtuamnuq
from collections import OrderedDict import time import os import logging from qiskit.optimization.algorithms import CplexOptimizer from qiskit.optimization.algorithms.optimization_algorithm import OptimizationResultStatus from dwave.system import DWaveCliqueSampler, LeapHybridSampler from random_lp.lp_random_gen import create_models from utilities.helpers import create_dwave_meo TEST_DIR = 'TEST_DATA' + "/" + time.strftime("%d_%m_%Y") + "/DENSE/" RES_DIR = 'RESULTS' + "/" + time.strftime("%d_%m_%Y") + "/DENSE/" os.makedirs(RES_DIR, exist_ok=True) TEST_DIR logger = logging.getLogger() logger.setLevel(logging.INFO) qps = create_models(TEST_DIR) # init Optimizers cplex = CplexOptimizer() hybrid = create_dwave_meo(LeapHybridSampler()) clique = create_dwave_meo(DWaveCliqueSampler()) dwave_auto = create_dwave_meo() results = OrderedDict() for qp_name, qp in qps.items() : print(qp_name) print("number of qubits: ", qp.qubo.get_num_vars()) output_file_handler = logging.FileHandler(filename=RES_DIR + qp.name + ".log") logger.addHandler(output_file_handler) if qp.qubo.get_num_vars() > clique.min_eigen_solver.sampler.largest_clique_size: dwave = dwave_auto else: dwave = clique with open(RES_DIR + qp.name + '.res', 'w') as file: file.write(str("Start " + qp.name + "\n " + str(qp.qubo.get_num_vars()) + " qubits needed")) file.write("\n Leap: \n") logger.info("\n Leap: \n ") res_classic = cplex.solve(qp) res_hybrid = hybrid.solve(qp) logger.info(str(res_hybrid.min_eigen_solver_result.sampleset.info)) if res_hybrid.status != OptimizationResultStatus.SUCCESS: file.write("No solution found with DWave Hybrid Sampler Leap.") file.write("\n CPLEX:\n") file.write(str(res_classic)) break else: print("Leap successful!") if res_hybrid.fval == res_classic.fval: file.write("\n Leap found optimal solution\n") else: print("\n optimal value Leap "+str(res_hybrid.fval) + " , cplex:"+ str(res_classic.fval)) file.write("\n Leap: \n") file.write(str(res_hybrid)) file.write("\n CPLEX:\n") file.write(str(res_classic)) file.write("\n DWave Quantum: \n") logger.info("\n DWave Quantum: \n ") try: res_quantum = dwave.solve(qp) problem_id = str(res_quantum.min_eigen_solver_result.sampleset.info['problem_id']) logger.info("\n problem id " + problem_id) file.write("\n problem id: " + problem_id) if res_quantum.status != OptimizationResultStatus.SUCCESS: print("Dwave quantum solver found no solution.") file.write("\n No solution found with DWave Quantum Solver \n") else: print("Dwave Quantum successful!") if res_quantum.fval == res_classic.fval: file.write("\n DWave quantum solver found optimal solution\n") else: print("\n optimal value Dwave quantum "+str(res_quantum.fval) + " , cplex:"+ str(res_classic.fval)) file.write("\n DWave quantum solver:\n") file.write(str(res_quantum)) file.write("\n CPLEX:\n") file.write(str(res_classic)) except Exception as ex: print(qp_name, " ", type(ex).__name__, " : ", ex) file.write("\n DWave Solver produced an exception:\n") file.write(str(ex)) logger.removeHandler(output_file_handler) # see Class SubstituteVariables in https://qiskit.org/documentation/_modules/qiskit/optimization/problems/quadratic_program.html#QuadraticProgram # for logger warning constraint A0_leb0 is infeasible due to substitution # Afterwards a check for feasability of substituted solution is done to set OptimizationResultStatus res_hybrid.min_eigen_solver_result.sampleset
https://github.com/LauraGentini/QRL
LauraGentini
# General imports import numpy as np import matplotlib.pyplot as plt # Qiskit imports import qiskit as qk from qiskit.utils import QuantumInstance # Qiskit Machine Learning imports import qiskit_machine_learning as qkml from qiskit_machine_learning.neural_networks import CircuitQNN from qiskit_machine_learning.connectors import TorchConnector # PyTorch imports import torch from torch import Tensor # OpenAI Gym import import gym # Custom Deep Q-Learning code import from dqn_definitions import * # Fix seed for reproducibility seed = 42 np.random.seed(seed) torch.manual_seed(seed); # To get smooth animations on Jupyter Notebooks. # Note: these plotting function are taken from https://github.com/ageron/handson-ml2 import matplotlib as mpl import matplotlib.animation as animation mpl.rc('animation', html='jshtml') def update_scene(num, frames, patch): patch.set_data(frames[num]) return patch, def plot_animation(frames, repeat=False, interval=40): fig = plt.figure() patch = plt.imshow(frames[0]) plt.axis('off') anim = animation.FuncAnimation( fig, update_scene, fargs=(frames, patch), frames=len(frames), repeat=repeat, interval=interval) plt.close() return anim # Select the number of qubits (one qubit per state variable of the environment) num_qubits = 4 # Generate the Parametrized Quantum Circuit (note the reuploading and repetitions flags) qc = parametrized_circuit(num_qubits = num_qubits, reuploading = True, reps = 6) # Fetch the Parameters from the circuit and divide them in Inputs (X) and Trainable Parameters (params) # The first four parameters are for the inputs X = list(qc.parameters)[: num_qubits] # The remaining ones are the trainable weights of the quantum neural network params = list(qc.parameters)[num_qubits:] qc.draw() # Define the quantum instance to be used for simulating the quantum circuit qi = QuantumInstance(qk.Aer.get_backend('statevector_simulator')) # Create the QNN from the parametrized quantum circuit defined above qnn = CircuitQNN(qc, input_params=X, weight_params=params, quantum_instance = qi) # Interface the QNN with PyTorch initial_weights = (2*np.random.rand(qnn.num_weights) - 1) # <---Initialization weights at random quantum_nn = TorchConnector(qnn, initial_weights) env = gym.make("CartPole-v1") input_shape = [4] # == env.observation_space.shape n_outputs = 2 # == env.action_space.n # Classical trainable preprocessing (encoding) encoding = encoding_layer() # Classical trainable postprocessing exp_val = exp_val_layer() # Stack the classical and quantum layers together model = torch.nn.Sequential(encoding, quantum_nn, exp_val) # Load pre-trained weights (check if the file exists): try: model.load_state_dict(torch.load("./model_best_weights_6reps_longtrain.pth")) except: print("No pre-trained weights found. Looks like you have to train from scratch...") # Print the optimal weights of the agent model.state_dict() # Set the environment seed for reproducibility env.seed(42) # 200 is the target score for considering the environment solved max_reward = 200 # Run the quantum agent frames = [] state = env.reset() for step in range(max_reward): # Select action with torch.no_grad(): Q_values = model(Tensor(state)).numpy() action = np.argmax(Q_values) # Perform the action state, reward, done, info = env.step(action) if done: print("End at step:", step) break print(f"Step {step}, Q-values {Q_values}, Action {action}", end = "\r") img = env.render(mode="rgb_array") frames.append(img) plot_animation(frames) # Choose the number of shots used to estimate the expectation values in the QNN circuit n_shots = 1024 # Define the quantum instance for the qasm_simulator qi_qasm = QuantumInstance(qk.Aer.get_backend('qasm_simulator'), shots = n_shots) noisy_qnn = CircuitQNN(qc, input_params=X, weight_params=params, quantum_instance = qi_qasm) initial_weights = (2*np.random.rand(qnn.num_weights) - 1) noisy_quantum_nn = TorchConnector(noisy_qnn, initial_weights) # Exactly as before... encoding = encoding_layer() exp_val = exp_val_layer() noisy_model = torch.nn.Sequential(encoding, noisy_quantum_nn, exp_val) # Load pre-trained weights: try: noisy_model.load_state_dict(torch.load("./model_best_weights_6reps_longtrain.pth")) except: print("No pre-trained weights found. Looks like you have to train from scratch...") noisy_model.state_dict() env.seed(42) number_of_episodes = 5 print(f"Number of shots = {n_shots}") print("-----------------------") final_step = [] for i in range(number_of_episodes): state = env.reset() for step in range(200): print(f"\r Episode = {i}, Step = {step}", end = "") with torch.no_grad(): Q_values = noisy_model(Tensor(state[np.newaxis])).numpy() action = np.argmax(Q_values[0]) state, reward, done, info = env.step(action) # print(action, state, model(Tensor([state]))) if done: print(", End at step:", step) break final_step.append(step+1) final_steps = np.array(final_step) mean_score = np.mean(final_steps) std_score = np.std(final_steps) print(f"Mean reward = {mean_score} ± {std_score}") num_shots = [1024, 2048, 4096, 8192] mean_reward = [115.1, 191, 195, 199.7] std_reward = [49.9, 27.2, 10.9, 0.3] import seaborn as sns sns.set_theme() cmap = plt.get_cmap('tab20c') fig = plt.figure(figsize=(8,5)) plt.axhline([200], ls = 'dashed', c=cmap(9)) plt.text(6000,205, s='Max reward', c=cmap(8)) plt.axhline([195], ls = 'dashed', c=cmap(13)) plt.text(6000,175, s='Min reward for\nsolving environment', c=cmap(12)) plt.errorbar(num_shots, mean_reward, yerr=std_reward, fmt='o', c = cmap(4), capsize=5, ecolor = cmap(5)) plt.ylim([0,230]) plt.xticks([1024, 2048, 4096, 8192]) plt.xlabel("Number of shots") plt.ylabel("Final reward") plt.tight_layout() plt.show()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit top = QuantumCircuit(1) top.x(0); bottom = QuantumCircuit(2) bottom.cry(0.2, 0, 1); tensored = bottom.tensor(top) tensored.draw('mpl')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import pulse from qiskit.providers.fake_provider import FakeArmonk backend = FakeArmonk() with pulse.build(backend) as drive_sched: d0 = pulse.drive_channel(0) a0 = pulse.acquire_channel(0) pulse.play(pulse.library.Constant(10, 1.0), d0) pulse.delay(20, d0) pulse.shift_phase(3.14/2, d0) pulse.set_phase(3.14, d0) pulse.shift_frequency(1e7, d0) pulse.set_frequency(5e9, d0) with pulse.build() as temp_sched: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), d0) pulse.play(pulse.library.Gaussian(20, -1.0, 3.0), d0) pulse.call(temp_sched) pulse.acquire(30, a0, pulse.MemorySlot(0)) drive_sched.draw()
https://github.com/55blabs/grovers-algothrim
55blabs
#Classical vs Quantum Computer #!/usr/bin/env python # coding: utf-8 # In[2]: #simple unordered list of elements my_list = [1, 3, 5, 2, 4, 9, 5, 8, 0, 7] # In[4]: #defining my varibale #set wining number you would like def the_oracle(my_input): winner=7 if my_input is winner: response = True else: response = False return response # In[25]: #Classical computer enumeration on a winning number for index, trial_number in enumerate(my_list): if the_oracle(trial_number) is True: print('winner winner found at index %i'%index) print('%i calls to the oracle used' % (index+1)) break # In[26]: #Transistion to Qiskit Aer #import dependencies from qiskit import * import matplotlib.pyplot as plt import numpy as np # In[11]: #define the oracle circuit oracle = QuantumCircuit(2, name='oracle') oracle.cz(0,1) oracle.to_gate() oracle.draw() # In[13]: backend = Aer.get_backend('statevector_simulator') grover_circ = QuantumCircuit(2,2) grover_circ.h([0, 1]) grover_circ.append(oracle, [0, 1]) grover_circ.draw() # In[15]: job = execute(grover_circ, backend) result = job.result() # In[16]: sv = result.get_statevector() np.around(sv, 2) # In[18]: #Grovers Diffusion Operator [Operator] + [Reflection] reflection = QuantumCircuit(2, name='reflection') reflection.h([0, 1]) reflection.z([0,1]) reflection.cz(0,1) reflection.h([0,1]) reflection.to_gate() # In[20]: reflection.draw() # In[22]: backend = Aer.get_backend('qasm_simulator') grover_circ = QuantumCircuit(2, 2) grover_circ.h([0,1]) grover_circ.append(oracle, [0, 1]) grover_circ.append(reflection, [0, 1]) grover_circ.measure([0, 1], [0,1]) # In[23]: grover_circ.draw() # In[24]: job=execute(grover_circ,backend,shots=1) result=job.result() result.get_counts() # In[ ]:
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from random import randrange dimension = 7 # create u and v as empty list u = [] v = [] for i in range(dimension): u.append(randrange(-10,11)) # add a randomly picked number to the list u v.append(randrange(-10,11)) # add a randomly picked number to the list v # print both lists print("u is",u) print("v is",v) # let's create a result list # the first method result=[] # fill it with zeros for i in range(dimension): result.append(0) print("result is initialized by the first method to ",result) # the second method # alternative and shorter solution for creating a list with zeros result = [0] * 7 print("result is initialized by the second method to",result) # let's calculate 3u-2v for i in range(dimension): result[i] = 3 * u[i] - 2 * v[i] # print all lists print("u is",u) print("v is",v) print("3u-2v is",result) u = [1,-2,-4,2] fouru=[4,-8,-16,8] len_u = 0 len_fouru = 0 for i in range(len(u)): len_u = len_u + u[i]**2 # adding square of each value len_fouru = len_fouru + fouru[i]**2 # adding sqaure of each value len_u = len_u ** 0.5 # taking square root of the summation len_fouru = len_fouru ** 0.5 # taking square root of the summation # print the lengths print("length of u is",len_u) print("4 * length of u is",4 * len_u) print("length of 4u is",len_fouru) from random import randrange u = [1,-2,-4,2] print("u is",u) r = randrange(9) # r is a number in {0,...,8} r = r + 1 # r is a number in {1,...,9} r = r/10 # r is a number in {1/10,...,9/10} print() print("r is",r) newu=[] for i in range(len(u)): newu.append(-1*r*u[i]) print() print("-ru is",newu) print() length = 0 for i in range(len(newu)): length = length + newu[i]**2 # adding square of each number print(newu[i],"->[square]->",newu[i]**2) print() print("the summation of squares is",length) length = length**0.5 # taking square root print("the length of",newu,"is",length)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit qr = QuantumRegister(3, 'q') anc = QuantumRegister(1, 'ancilla') cr = ClassicalRegister(3, 'c') qc = QuantumCircuit(qr, anc, cr) qc.x(anc[0]) qc.h(anc[0]) qc.h(qr[0:3]) qc.cx(qr[0:3], anc[0]) qc.h(qr[0:3]) qc.barrier(qr) qc.measure(qr, cr) qc.draw('mpl')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, QuantumRegister from qiskit.circuit.library.standard_gates import HGate qr = QuantumRegister(3) qc = QuantumCircuit(qr) c3h_gate = HGate().control(2) qc.append(c3h_gate, qr) qc.draw('mpl')
https://github.com/Chibikuri/qwopt
Chibikuri
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.3.1 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import numpy as np import matplotlib.pyplot as plt import seaborn as sns import copy import itertools from qiskit import transpile from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister from qiskit import Aer, execute from qiskit.tools.visualization import plot_histogram from torch import optim # qiskit AQUA from qiskit.aqua.components.optimizers import ADAM from qiskit.aqua.components.uncertainty_models import UniformDistribution, UnivariateVariationalDistribution from qiskit.aqua.components.variational_forms import RY from qiskit.aqua.algorithms.adaptive import QGAN from qiskit.aqua.components.neural_networks.quantum_generator import QuantumGenerator from qiskit.aqua.components.neural_networks.numpy_discriminator import NumpyDiscriminator from qiskit.aqua import aqua_globals, QuantumInstance from qiskit.aqua.components.initial_states import Custom # + code_folding=[6] alpha = 0.85 target_graph = np.array([[0, 1, 0, 1], [0, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]) E = np.array([[1/4, 1/2, 0, 1/2], [1/4, 0, 1/2, 0], [1/4, 1/2, 0, 1/2], [1/4, 0, 1/2, 0]]) # use google matrix prob_dist = alpha*E + ((1-alpha)/4)*np.ones((4, 4)) init_state = 1/2*np.array([np.sqrt(prob_dist[j][i]) for i in range(4) for j in range(4)]) # - # Check data format # + # Number training data samples N = 1000 # Load data samples from log-normal distribution with mean=1 and standard deviation=1 mu = 1 sigma = 1 real_data = np.random.lognormal(mean = mu, sigma=sigma, size=N) # Set the data resolution # Set upper and lower data values as list of k min/max data values [[min_0,max_0],...,[min_k-1,max_k-1]] bounds = np.array([0.,3.]) # Set number of qubits per data dimension as list of k qubit values[#q_0,...,#q_k-1] num_qubits = [2] k = len(num_qubits) print(real_data) plt.hist(real_data) # - # ## Not generalized 4node # + # QGAN # Set number of training epochs # Note: The algorithm's runtime can be shortened by reducing the number of training epochs. num_epochs = 3000 # Batch size batch_size = 100 # Initialize qGAN qgan = QGAN(real_data, bounds, num_qubits, batch_size, num_epochs, snapshot_dir=None) qgan.seed = 1 # Set quantum instance to run the quantum generator quantum_instance = QuantumInstance(backend=Aer.get_backend('statevector_simulator')) # Set entangler map entangler_map = [[0, 1]] # Set an initial state for the generator circuit init_dist = UniformDistribution(sum(num_qubits), low=bounds[0], high=bounds[1]) print(init_dist.probabilities) q = QuantumRegister(sum(num_qubits), name='q') qc = QuantumCircuit(q) init_dist.build(qc, q) init_distribution = Custom(num_qubits=sum(num_qubits), circuit=qc) var_form = RY(int(np.sum(num_qubits)), depth=1, initial_state = init_distribution, entangler_map=entangler_map, entanglement_gate='cz') # Set generator's initial parameters init_params = aqua_globals.random.rand(var_form._num_parameters) * 2 * np.pi # Set generator circuit g_circuit = UnivariateVariationalDistribution(int(sum(num_qubits)), var_form, init_params, low=bounds[0], high=bounds[1]) # Set quantum generator qgan.set_generator(generator_circuit=g_circuit) # Set classical discriminator neural network discriminator = NumpyDiscriminator(len(num_qubits)) qgan.set_discriminator(discriminator) # - # Run qGAN qgan.run(quantum_instance) # + # Plot progress w.r.t the generator's and the discriminator's loss function t_steps = np.arange(num_epochs) plt.figure(figsize=(6,5)) plt.title("Progress in the loss function") plt.plot(t_steps, qgan.g_loss, label = "Generator loss function", color = 'mediumvioletred', linewidth = 2) plt.plot(t_steps, qgan.d_loss, label = "Discriminator loss function", color = 'rebeccapurple', linewidth = 2) plt.grid() plt.legend(loc = 'best') plt.xlabel('time steps') plt.ylabel('loss') plt.show() # Plot progress w.r.t relative entropy plt.figure(figsize=(6,5)) plt.title("Relative Entropy ") plt.plot(np.linspace(0, num_epochs, len(qgan.rel_entr)), qgan.rel_entr, color ='mediumblue', lw=4, ls=':') plt.grid() plt.xlabel('time steps') plt.ylabel('relative entropy') plt.show() #Plot the PDF of the resulting distribution against the target distribution, i.e. log-normal log_normal = np.random.lognormal(mean=1, sigma=1, size=100000) log_normal = np.round(log_normal) log_normal = log_normal[log_normal <= bounds[1]] temp = [] for i in range(int(bounds[1]+1)): temp += [np.sum(log_normal==i)] log_normal = np.array(temp / sum(temp)) plt.figure(figsize=(6,5)) plt.title("CDF") samples_g, prob_g = qgan.generator.get_output(qgan.quantum_instance, shots=10000) samples_g = np.array(samples_g) samples_g = samples_g.flatten() num_bins = len(prob_g) print(prob_g) print(samples_g) plt.bar(samples_g, np.cumsum(prob_g), color='royalblue', width= 0.8, label='simulation') plt.plot( np.cumsum(log_normal),'-o', label='log-normal', color='deepskyblue', linewidth=4, markersize=12) plt.xticks(np.arange(min(samples_g), max(samples_g)+1, 1.0)) plt.grid() plt.xlabel('x') plt.ylabel('p(x)') plt.legend(loc='best') plt.show() # - print(len(qgan._ret['params_g'])) for i in qgan._ret['params_g']: print(i) gp = qgan._ret['params_g'] # + q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.h(q) qc.ry(gp[0], q[0]) qc.ry(gp[1], q[1]) qc.cz(q[0], q[1]) qc.ry(gp[2], q[0]) qc.ry(gp[3], q[1]) job = execute(qc, backend=Aer.get_backend('statevector_simulator')) vec = job.result().get_statevector(qc) print(vec) qc.measure(q[0], c[1]) qc.measure(q[1], c[0]) shots = 10000 job = execute(qc, backend=Aer.get_backend('qasm_simulator'), shots=shots) count = job.result().get_counts(qc) bins = [format(i, "0%db"%num_qubits[0]) for i in range(2**num_qubits[0])] pros = itertools.accumulate([count.get(i, 0)/shots for i in bins]) print(list(pros)) # plot_histogram(pros) # + # Circuit # Hardcoded now! num_qubits = [2] bins = [format(i, "0%db"%num_qubits[0]) for i in range(2**num_qubits[0])] def four_node(step): rotation = np.radians(31.788) cq = QuantumRegister(2, 'control') tq = QuantumRegister(2, 'target') c = ClassicalRegister(2, 'classical') anc = QuantumRegister(2, 'ancilla') qc = QuantumCircuit(cq, tq, anc, c) # initialize with probability distribution matrix initial = 1/2*np.array([np.sqrt(prob_dist[j][i]) for i in range(4) for j in range(4)]) qc.initialize(initial, [*cq, *tq]) for t in range(step): # Ti operation qc.x(cq[1]) qc.ccx(cq[0], cq[1], tq[1]) qc.x(cq[1]) qc.barrier() # Kdg operation qc.x(cq) qc.rccx(cq[0], cq[1], anc[0]) qc.barrier() qc.ch(anc[0], tq[0]) qc.ch(anc[0], tq[1]) qc.x(anc[0]) qc.cry(-rotation, anc[0], tq[1]) qc.ch(anc[0], tq[0]) qc.barrier() # D operation qc.x(tq) qc.cz(tq[0], tq[1]) qc.x(tq) qc.barrier() # K operation qc.ch(anc[0], tq[0]) qc.cry(rotation, anc[0], tq[1]) qc.x(anc[0]) qc.ch(anc[0], tq[1]) qc.ch(anc[0], tq[0]) qc.rccx(cq[0], cq[1], anc[0]) qc.x(cq) qc.barrier() # Tidg operation qc.x(cq[1]) qc.ccx(cq[0], cq[1], tq[1]) qc.x(cq[1]) qc.barrier() # swap qc.swap(tq[0], cq[0]) qc.swap(tq[1], cq[1]) qc.measure(tq, c) return qc # - step = 1 qwqc = four_node(step) shots = 10000 job = execute(qwqc, backend=Aer.get_backend("qasm_simulator"), shots=shots) counts = job.result().get_counts(qwqc) probs = np.array(([0] * counts.get('00'), [1]* counts.get('01'), [2] * counts.get('10'), [3] * counts.get('11'))) real_data = [] for i in probs: for j in i: real_data.append(j) bounds = np.array([0.,3.]) # Set number of qubits per data dimension as list of k qubit values[#q_0,...,#q_k-1] num_qubits = [2] k = len(num_qubits) # + # QGAN # Set number of training epochs # Note: The algorithm's runtime can be shortened by reducing the number of training epochs. num_epochs = 3000 # Batch size batch_size = 100 # Initialize qGAN qgan = QGAN(real_data, bounds, num_qubits, batch_size, num_epochs, snapshot_dir=None) qgan.seed = 1 # Set quantum instance to run the quantum generator quantum_instance = QuantumInstance(backend=Aer.get_backend('statevector_simulator')) # Set entangler map entangler_map = [[0, 1]] # Set an initial state for the generator circuit init_dist = UniformDistribution(sum(num_qubits), low=bounds[0], high=bounds[1]) print(init_dist.probabilities) q = QuantumRegister(sum(num_qubits), name='q') qc = QuantumCircuit(q) init_dist.build(qc, q) init_distribution = Custom(num_qubits=sum(num_qubits), circuit=qc) var_form = RY(int(np.sum(num_qubits)), depth=1, initial_state = init_distribution, entangler_map=entangler_map, entanglement_gate='cz') # Set generator's initial parameters init_params = aqua_globals.random.rand(var_form._num_parameters) * 2 * np.pi # Set generator circuit g_circuit = UnivariateVariationalDistribution(int(sum(num_qubits)), var_form, init_params, low=bounds[0], high=bounds[1]) # Set quantum generator qgan.set_generator(generator_circuit=g_circuit) # Set classical discriminator neural network discriminator = NumpyDiscriminator(len(num_qubits)) qgan.set_discriminator(discriminator) # - # Run qGAN qgan.run(quantum_instance)
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
""" Variational Quantum Eigensolver Benchmark Program - QSim """ import json import os import sys import time import numpy as np from qiskit import QuantumCircuit, QuantumRegister from qiskit.opflow import PauliTrotterEvolution, Suzuki from qiskit.opflow.primitive_ops import PauliSumOp sys.path[1:1] = ["_common", "_common/qsim"] sys.path[1:1] = ["../../_common", "../../_common/qsim"] import execute as ex import metrics as metrics from execute import BenchmarkResult # Benchmark Name benchmark_name = "VQE Simulation" verbose= False # saved circuits for display QC_ = None Hf_ = None CO_ = None ################### Circuit Definition ####################################### # Construct a Qiskit circuit for VQE Energy evaluation with UCCSD ansatz # param: n_spin_orbs - The number of spin orbitals. # return: return a Qiskit circuit for this VQE ansatz def VQEEnergy(n_spin_orbs, na, nb, circuit_id=0, method=1): # number of alpha spin orbitals norb_a = int(n_spin_orbs / 2) # construct the Hamiltonian qubit_op = ReadHamiltonian(n_spin_orbs) # allocate qubits num_qubits = n_spin_orbs qr = QuantumRegister(num_qubits) qc = QuantumCircuit(qr, name=f"vqe-ansatz({method})-{num_qubits}-{circuit_id}") # initialize the HF state Hf = HartreeFock(num_qubits, na, nb) qc.append(Hf, qr) # form the list of single and double excitations excitationList = [] for occ_a in range(na): for vir_a in range(na, norb_a): excitationList.append((occ_a, vir_a)) for occ_b in range(norb_a, norb_a+nb): for vir_b in range(norb_a+nb, n_spin_orbs): excitationList.append((occ_b, vir_b)) for occ_a in range(na): for vir_a in range(na, norb_a): for occ_b in range(norb_a, norb_a+nb): for vir_b in range(norb_a+nb, n_spin_orbs): excitationList.append((occ_a, vir_a, occ_b, vir_b)) # get cluster operators in Paulis pauli_list = readPauliExcitation(n_spin_orbs, circuit_id) # loop over the Pauli operators for index, PauliOp in enumerate(pauli_list): # get circuit for exp(-iP) cluster_qc = ClusterOperatorCircuit(PauliOp, excitationList[index]) # add to ansatz qc.append(cluster_qc, [i for i in range(cluster_qc.num_qubits)]) # method 1, only compute the last term in the Hamiltonian if method == 1: # last term in Hamiltonian qc_with_mea, is_diag = ExpectationCircuit(qc, qubit_op[1], num_qubits) # return the circuit return qc_with_mea # now we need to add the measurement parts to the circuit # circuit list qc_list = [] diag = [] off_diag = [] global normalization normalization = 0.0 # add the first non-identity term identity_qc = qc.copy() identity_qc.measure_all() qc_list.append(identity_qc) # add to circuit list diag.append(qubit_op[1]) normalization += abs(qubit_op[1].coeffs[0]) # add to normalization factor diag_coeff = abs(qubit_op[1].coeffs[0]) # add to coefficients of diagonal terms # loop over rest of terms for index, p in enumerate(qubit_op[2:]): # get the circuit with expectation measurements qc_with_mea, is_diag = ExpectationCircuit(qc, p, num_qubits) # accumulate normalization normalization += abs(p.coeffs[0]) # add to circuit list if non-diagonal if not is_diag: qc_list.append(qc_with_mea) else: diag_coeff += abs(p.coeffs[0]) # diagonal term if is_diag: diag.append(p) # off-diagonal term else: off_diag.append(p) # modify the name of diagonal circuit qc_list[0].name = qubit_op[1].primitive.to_list()[0][0] + " " + str(np.real(diag_coeff)) normalization /= len(qc_list) return qc_list # Function that constructs the circuit for a given cluster operator def ClusterOperatorCircuit(pauli_op, excitationIndex): # compute exp(-iP) exp_ip = pauli_op.exp_i() # Trotter approximation qc_op = PauliTrotterEvolution(trotter_mode=Suzuki(order=1, reps=1)).convert(exp_ip) # convert to circuit qc = qc_op.to_circuit(); qc.name = f'Cluster Op {excitationIndex}' global CO_ if CO_ == None or qc.num_qubits <= 4: if qc.num_qubits < 7: CO_ = qc # return this circuit return qc # Function that adds expectation measurements to the raw circuits def ExpectationCircuit(qc, pauli, nqubit, method=2): # copy the unrotated circuit raw_qc = qc.copy() # whether this term is diagonal is_diag = True # primitive Pauli string PauliString = pauli.primitive.to_list()[0][0] # coefficient coeff = pauli.coeffs[0] # basis rotation for i, p in enumerate(PauliString): target_qubit = nqubit - i - 1 if (p == "X"): is_diag = False raw_qc.h(target_qubit) elif (p == "Y"): raw_qc.sdg(target_qubit) raw_qc.h(target_qubit) is_diag = False # perform measurements raw_qc.measure_all() # name of this circuit raw_qc.name = PauliString + " " + str(np.real(coeff)) # save circuit global QC_ if QC_ == None or nqubit <= 4: if nqubit < 7: QC_ = raw_qc return raw_qc, is_diag # Function that implements the Hartree-Fock state def HartreeFock(norb, na, nb): # initialize the quantum circuit qc = QuantumCircuit(norb, name="Hf") # alpha electrons for ia in range(na): qc.x(ia) # beta electrons for ib in range(nb): qc.x(ib+int(norb/2)) # Save smaller circuit global Hf_ if Hf_ == None or norb <= 4: if norb < 7: Hf_ = qc # return the circuit return qc ################ Helper Functions # Function that converts a list of single and double excitation operators to Pauli operators def readPauliExcitation(norb, circuit_id=0): # load pre-computed data filename = os.path.join(os.path.dirname(__file__), f'./ansatzes/{norb}_qubit_{circuit_id}.txt') with open(filename) as f: data = f.read() ansatz_dict = json.loads(data) # initialize Pauli list pauli_list = [] # current coefficients cur_coeff = 1e5 # current Pauli list cur_list = [] # loop over excitations for ext in ansatz_dict: if cur_coeff > 1e4: cur_coeff = ansatz_dict[ext] cur_list = [(ext, ansatz_dict[ext])] elif abs(abs(ansatz_dict[ext]) - abs(cur_coeff)) > 1e-4: pauli_list.append(PauliSumOp.from_list(cur_list)) cur_coeff = ansatz_dict[ext] cur_list = [(ext, ansatz_dict[ext])] else: cur_list.append((ext, ansatz_dict[ext])) # add the last term pauli_list.append(PauliSumOp.from_list(cur_list)) # return Pauli list return pauli_list # Get the Hamiltonian by reading in pre-computed file def ReadHamiltonian(nqubit): # load pre-computed data filename = os.path.join(os.path.dirname(__file__), f'./Hamiltonians/{nqubit}_qubit.txt') with open(filename) as f: data = f.read() ham_dict = json.loads(data) # pauli list pauli_list = [] for p in ham_dict: pauli_list.append( (p, ham_dict[p]) ) # build Hamiltonian ham = PauliSumOp.from_list(pauli_list) # return Hamiltonian return ham ################ Result Data Analysis ## Analyze and print measured results ## Compute the quality of the result based on measured probability distribution for each state def analyze_and_print_result(qc, result, num_qubits, references, num_shots): # total circuit name (pauli string + coefficient) total_name = qc.name # pauli string pauli_string = total_name.split()[0] if result.backend_name == 'dm_simulator': benchmark_result = BenchmarkResult(result, num_shots) probs = benchmark_result.get_probs(num_shots) # get results as measured probability else: probs = result.get_counts(qc) # get results as measured counts # probs = {key: round(value, 3) for key, value in probs.items()} #to avoid exponential probability values which leads to nan value # # setting the threhold value to avoid getting exponential values which leads to nan values # threshold = 3e-3 # probs = {key: value if value > threshold else 0.0 for key, value in probs.items()} # print("probability ======= ", probs) # get the correct measurement if (len(total_name.split()) == 2): correct_dist = references[pauli_string] else: circuit_id = int(total_name.split()[2]) correct_dist = references[f"Qubits - {num_qubits} - {circuit_id}"] # compute fidelity fidelity = metrics.polarization_fidelity(probs, correct_dist) # modify fidelity based on the coefficient if (len(total_name.split()) == 2): fidelity *= ( abs(float(total_name.split()[1])) / normalization ) return fidelity ################ Benchmark Loop # Max qubits must be 12 since the referenced files only go to 12 qubits MAX_QUBITS = 12 # Execute program with default parameters def run(min_qubits=4, max_qubits=8, skip_qubits=1, max_circuits=3, num_shots=4092, method=1, backend_id="dm_simulator", provider_backend=None, #hub="ibm-q", group="open", project="main", exec_options=None, context=None): print(f"{benchmark_name} ({method}) Benchmark Program - QSim") max_qubits = max(max_qubits, min_qubits) # max must be >= min # validate parameters (smallest circuit is 4 qubits and largest is 10 qubitts) max_qubits = min(max_qubits, MAX_QUBITS) min_qubits = min(max(4, min_qubits), max_qubits) if min_qubits % 2 == 1: min_qubits += 1 # min_qubits must be even skip_qubits = max(1, skip_qubits) if method == 2: max_circuits = 1 if max_qubits < 4: print(f"Max number of qubits {max_qubits} is too low to run method {method} of VQE algorithm") return # create context identifier if context is None: context = f"{benchmark_name} ({method}) Benchmark" ########## # Initialize the metrics module metrics.init_metrics() # Define custom result handler def execution_handler(qc, result, num_qubits, type, num_shots): # load pre-computed data if len(qc.name.split()) == 2: filename = os.path.join(os.path.dirname(__file__), f'../_common/precalculated_data_{num_qubits}_qubit.json') with open(filename) as f: references = json.load(f) else: filename = os.path.join(os.path.dirname(__file__), f'../_common/precalculated_data_{num_qubits}_qubit_method2.json') with open(filename) as f: references = json.load(f) fidelity = analyze_and_print_result(qc, result, num_qubits, references, num_shots) if len(qc.name.split()) == 2: metrics.store_metric(num_qubits, qc.name.split()[0], 'fidelity', fidelity) else: metrics.store_metric(num_qubits, qc.name.split()[2], 'fidelity', fidelity) # Initialize execution module using the execution result handler above and specified backend_id ex.init_execution(execution_handler) ex.set_execution_target(backend_id, provider_backend=provider_backend, #hub=hub, group=group, project=project, exec_options=exec_options, context=context) ########## # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for input_size in range(min_qubits, max_qubits + 1, 2): # reset random seed np.random.seed(0) # determine the number of circuits to execute for this group num_circuits = min(3, max_circuits) num_qubits = input_size # decides number of electrons na = int(num_qubits/4) nb = int(num_qubits/4) # random seed np.random.seed(0) # create the circuit for given qubit size and simulation parameters, store time metric ts = time.time() # circuit list qc_list = [] # Method 1 (default) if method == 1: # loop over circuits for circuit_id in range(num_circuits): # construct circuit qc_single = VQEEnergy(num_qubits, na, nb, circuit_id, method).reverse_bits() # reverse_bits() is applying to handle the change in endianness qc_single.name = qc_single.name + " " + str(circuit_id) # add to list qc_list.append(qc_single) # method 2 elif method == 2: # construct all circuits qc_list = VQEEnergy(num_qubits, na, nb, 0, method) print(f"************\nExecuting [{len(qc_list)}] circuits with num_qubits = {num_qubits}") for qc in qc_list: # get circuit id if method == 1: circuit_id = qc.name.split()[2] else: circuit_id = qc.name.split()[0] # record creation time metrics.store_metric(input_size, circuit_id, 'create_time', time.time() - ts) # collapse the sub-circuits used in this benchmark (for qiskit) qc2 = qc.decompose() # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc2, input_size, circuit_id, num_shots) # Wait for some active circuits to complete; report metrics when group complete ex.throttle_execution(metrics.finalize_group) # Wait for all active circuits to complete; report metrics when groups complete ex.finalize_execution(metrics.finalize_group) ########## # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") print("\nHartree Fock Generator 'Hf' ="); print(Hf_ if Hf_ != None else " ... too large!") print("\nCluster Operator Example 'Cluster Op' ="); print(CO_ if CO_ != None else " ... too large!") # Plot metrics for all circuit sizes metrics.plot_metrics(f"Benchmark Results - {benchmark_name} ({method}) - QSim") # if main, execute methods if __name__ == "__main__": ex.local_args() # calling local_args() needed while taking noise parameters through command line arguments (for individual benchmarks) run()
https://github.com/murogrande/IBM-cert-exam-study-questions
murogrande
## import some libraries from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, execute, BasicAer, IBMQ from math import sqrt import qiskit print(qiskit.__qiskit_version__) qc =QuantumCircuit(3,3) qc.h(0) qc.cx(0,1) qc.cx(0,2) qc.h(2) qc.cx(2,0) print(qc.depth()) qc = QuantumCircuit(1) qc.h(0) qc.t(0) simulator = Aer.get_backend('statevector_simulator') result = execute(qc,simulator).result() from qiskit.visualization import plot_bloch_multivector plot_bloch_multivector(result.get_statevector()) qc = QuantumCircuit(2) qc.cx(0,1) ## you won't see the next line in the exam. qc.draw('mpl') #Answer is D qc.draw('mpl',filename='test.png') ## check the folder where the notebook is located qc = QuantumCircuit(2,2) qc.h(0) qc.x(1) qc.measure([0,1],[0,1]) simulator=Aer.get_backend('qasm_simulator') ## Answer C ## here is the check from qiskit.visualization import plot_histogram job = execute(qc,simulator).result() counts = job.get_counts() print(counts) plot_histogram(counts) qreg_a = QuantumRegister(2) qreg_b = QuantumRegister(2) creg = ClassicalRegister(4) qc = QuantumCircuit(qreg_a,qreg_b,creg) qc.x(qreg_a[0]) qc.measure(qreg_a,creg[0:2]) qc.measure(qreg_b,creg[2:4]) simulator= BasicAer.get_backend('qasm_simulator') result= execute(qc,simulator).result() counts = result.get_counts(qc) ## check the answer print(counts) print("The answer is C ") qc.draw('mpl') from qiskit import QuantumCircuit qc = QuantumCircuit(2) qc.h(0) qc.cx(0,1) ##Answer is C qc.draw('png') # import image module from IPython.display import Image ### you won't see the following lines in the exam just the plot # get the image Image(url="random-unitary.png", width=600, height=600) ### in the exam you will just see the image # import image module from IPython.display import Image # get the image Image(url="circui1.png", width=300, height=300) ### in the exam you will just see the image # A. '''OPENQASM 2.0; include "qelib1.inc"; qreg q[2]; creg c[2]; h.q[0]; barrier (q[0],q[1]); z.q[1]; barrier (q[0], q[1]); measure (q[0], c[0]); measure (q[1], c[1]); ''' # B qc = QuantumCircuit(2,2) qc.h(q[0]) qc.barrier(q[0],q[1]) qc.z(q[1]) qc.barrier(q[0],q[1]) m = measure(q[0] -> c[0]) m += measure(q[1] -> c[1]) qc=qc+m # C qc = QuantumCircuit(2,2) qc.h(0) qc.barrier(0,1) qc.z(1) qc.barrier(0,1) qc.measure([0,1],[0,1]) #D qc = QuantumCircuit(2,2) qc.h(q[0]) qc.barrier(q[0],q[1]) qc.z(q[1]) qc.barrier(q[0],q[1]) m = measure(q[0], c[0]) m = measure(q[1], c[1]) qc=qc+m ### you won't see the following lines of code in the exam from IPython.display import Image Image(url="circui2.png", width=150, height=150) # A qr = QuantumRegister(2,'q') a = QuantumRegister(1,'a') cr = ClassicalRegister(3,'c') qc = QuantumCircuit(qr,a,cr) qc.h(qr[0:2]) qc.x(a[0]) # B qr = QuantumRegister(2,'q') a = QuantumRegister (1,'a') cr = ClassicalRegister(3,'c') qc = QuantumCircuit(cr,a,qr) qc.h(qr[0:2]) qc.x(a[0]) #C qr = QuantumRegister(2,'q') a = QuantumRegister (1,'a') cr = ClassicalRegister(3,'c') qc = QuantumCircuit(qr,a,cr) qc.h(qr[0:1]) qc.x(a[0]) #D qr = QReg(2,'q') a = QReg (1,'a') cr = CReg(3,'c') qc = QuantumCircuit(qr,a,cr) qc.h(qr[0:2]) qc.x(a[0]) from qiskit.tools.monitor import * provider = IBMQ.load_account() #provider.backends() ## this line of code can be important becuase it could be a question of your exam. #In other words, how do you know the backends of the provider? backend= provider.get_backend('ibmq_qasm_simulator') qr = QuantumRegister(2) cr= ClassicalRegister(2) qc = QuantumCircuit(qr,cr) qc.h(qr[0]) qc.cx(qr[0],qr[1]) qc.measure(qr,cr) job = execute(qc,backend) job.status() job_monitor(job) #### another could be job_watcher for jupyternoote book from qiskit.tools.jupyter import job_watcher %qiskit_job_watcher job = backend.retrieve_job('61f20ee81faa0605383485a7') result = job.result() counts = result.get_counts() print(counts) qc = QuantumCircuit(3) qc.initialize('01',[0,2]) qc.draw() print(qc.decompose()) from qiskit.visualization import plot_error_map, plot_gate_map backend = provider.get_backend('ibmq_quito') plot_error_map(backend) plot_gate_map(backend) #A from qiskit import QuantumCircuit, Aer, execute from math import pi qc = QuantumCircuit(2) qc.crz(pi,0,1) qc.crz(-pi,0,1) u_sim = Aer.get_backend('unitary_simulator') unitary = execute(qc,u_sim).result().get_unitary() print(unitary) #B from qiskit import QuantumCircuit, Aer, execute from math import pi qc = QuantumCircuit(2) qc.crz(pi,0,1) qc.cp(pi,0,1) u_sim = Aer.get_backend('unitary_simulator') unitary = execute(qc,u_sim).result().get_unitary() print(unitary) #C from qiskit import QuantumCircuit, Aer, execute from math import pi qc = QuantumCircuit(2) qc.cz(0,1) qc.cz(1,0) u_sim = Aer.get_backend('unitary_simulator') unitary = execute(qc,u_sim).result().get_unitary() print(unitary) qc.draw() #D from qiskit import QuantumCircuit, Aer, execute from math import pi qc = QuantumCircuit(2) qc.cz(0,1) qc.cp(pi,0,1) u_sim = Aer.get_backend('unitary_simulator') unitary = execute(qc,u_sim).result().get_unitary() print(unitary) import qiskit.tools.jupyter %qiskit_backend_overview from qiskit import QuantumCircuit qc = QuantumCircuit(3) #insert code fragment here #Output ### you won't see the following lines of code in the exam, just focus on the figure from IPython.display import Image Image(url="imageassesment1.png", width=350, height=350) #A qc.measure_all() #B qc = QuantumCircuit(3) qc.measure() #C qc = QuantumCircuit(3) qc.measure(0,0) qc.measure(1,1) qc.measure(2,2) #D qc = QuantumCircuit(3) for n in range(len(qc.qubits)): qc.measure(n,n) qc.qubits ## here you need to display each line or lines of code before each barrier in the Qsphere, the question is about #to put in order the sequence of states that will appear in the Qsphere. qc = QuantumCircuit(3) qc.x(1) qc.barrier() qc.h(0) qc.h(1) qc.h(2) qc.barrier() qc.z(1) qc.barrier() qc.h(0) qc.h(1) qc.h(2) qc.draw('mpl') from qiskit.visualization import plot_state_qsphere simulator= Aer.get_backend('statevector_simulator') result = execute(qc,simulator).result() statevector = result.get_statevector(qc) plot_state_qsphere(statevector) from qiskit import BasicAer, Aer, execute qc = QuantumCircuit(1) qc.h(0) #insert code fragment here print(unitary) #A simulator = BasicAer.get_backend('unitary_simulator') unitary = execute(qc,simulator).get_unitary(qc) #B simulator = Aer.get_backend('unitary_simulator') result = execute(qc,simulator).result() unitary = result.get_unitary(qc) #C simulator = Aer.get_backend('statevector_simulator') result = execute(qc,simulator).result() unitary = result.get_matrix_result(qc) #D simulator = BasicAer.get_backend('statevector_simulator') result = execute(qc,simulator).result() unitary = result.get_unitary(qc) #E simulator = BasicAer.get_backend('unitary_simulator') result = execute(qc,simulator).result() unitary = result.get_unitary() from qiskit.visualization import plot_bloch_vector from math import pi, sqrt plot_bloch_vector(vector) #A vector = [1,-1,0] #B vector = [pi/2,-pi/4,0] #C vector = [1/sqrt(2),-1/sqrt(2),0] #D vector = [1/sqrt(2),-1/sqrt(2),-1] from qiskit.visualization import plot_state_qsphere qc = QuantumCircuit(3) qc.h(0) #qc.z(0) qc.x(1) qc.cx(0,1) qc.x(2) qc.cx(1,2) backend = BasicAer.get_backend('statevector_simulator') job = execute(qc, backend).result() statevector= job.get_statevector() plot_state_qsphere(statevector) qc = QuantumCircuit(1) qc.x(0) qc.h(0) simulator = Aer.get_backend('unitary_simulator') job = execute(qc,simulator) result = job.result() outputstate = result.get_unitary(qc,1) print(outputstate) qc = QuantumCircuit(3,3) qc.h([0,1,2]) qc.barrier() qc.measure([0,1,2],range(3)) qc.draw() print(qc.qasm()) qasm_sim = Aer.get_backend('qasm_simulator') qc= QuantumCircuit(3) qc.x([0,1,2]) qc.ccx(0,1,2) qc.measure_all() result = execute(qc,qasm_sim).result() counts = result.get_counts() print(counts) qc= QuantumCircuit(3) qc.ct() from qiskit.quantum_info import DensityMatrix matrix1 = [ [1,0],[0,0] ] matrix2 = [ [0.5,0.5],[0.5,0.5] ] #A result= DensityMatrix.tensor(matrix1,matrix2) print(result) #B matrix1 = DensityMatrix(matrix1) print(matrix1.tensor(matrix2)) #C print(matrix1.tensor(matrix2)) #D print(DensityMatrix.tensor(matrix1,matrix2)) from qiskit.visualization import plot_state_city qc = QuantumCircuit(2) qc.h(0) qc.x(1) qc.cx(0,1) qc.z(0) simulator = BasicAer.get_backend('statevector_simulator') job = execute(qc,simulator).result() statevector = job.get_statevector() plot_state_city(statevector) qc = QuantumCircuit(1) #A #qc.ry(pi/2,0) #qc.s(0) #qc.rx(pi/2,0) #B #qc.ry(pi/2,0) #qc.rx(pi/2,0) #qc.s(0) #C #qc.s(0) #qc.ry(pi/2,0) #qc.rx(pi/2,0) #D qc.rx(pi/2,0) qc.s(0) qc.ry(pi/2,0) qc.measure_all() simulator = BasicAer.get_backend('qasm_simulator') job = execute(qc,simulator).result() counts = job.get_counts() print(counts) from qiskit.quantum_info import DensityMatrix qc = QuantumCircuit(2) qc.h(0) qc.cx(0,1) qc1= QuantumCircuit(2) qc1.h(0) qc1.x(1) qc1.cx(0,1) #qc.draw('mpl') rho_qc=DensityMatrix.from_instruction(qc) rho_qc.draw() rho1= DensityMatrix.from_instruction(qc1) rho1.draw() qc1new = qc1.decompose() qc1new.draw() #tensor1 = DensityMatrix.from_label('[[0,1],[1,0]]') qc = QuantumCircuit(2) #v1,v2 = [0,1],[0,1] v = [1/sqrt(2),0,0,1/sqrt(2)] qc.initialize(v,[0,1]) qc.draw(output='mpl') simulator = Aer.get_backend('statevector_simulator') result = execute(qc, simulator).result() statevector = result.get_statevector() print(statevector) from qiskit.circuit.library import CXGate ccx = CXGate().control() qc = QuantumCircuit(3) qc.append(ccx,[0,1,2]) qc.draw() from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, execute qc= QuantumCircuit(3) qc.barrier() qc.barrier([0]) qc.draw() qc = QuantumCircuit.from_qasm_file('myfile.qasm') qc.measure_all() qc.draw(output='latex_source') from qiskit.quantum_info import Statevector from qiskit.visualization import plot_state_qsphere, plot_state_paulivec, plot_state_city, plot_bloch_vector, plot_state_hinton, plot_bloch_multivector stavec = Statevector.from_label('001') plot_state_paulivec(stavec) import qiskit.tools.jupyter %qiskit_version_table import qiskit.tools.jupyter %qiskit_backend_overview
https://github.com/adamg0709/QiskitFun
adamg0709
import numpy as np from numpy import pi # importing Qiskit from qiskit import QuantumCircuit, transpile, assemble, Aer, IBMQ from qiskit.providers.ibmq import least_busy from qiskit.tools.monitor import job_monitor from qiskit.visualization import plot_histogram, plot_bloch_multivector # Qiskit's way of implementing QFT: def qft_rotations(circuit, n): """Performs qft on the first n qubits in circuit (without swaps)""" if n == 0: return circuit n -= 1 circuit.h(n) for qubit in range(n): circuit.cp(pi/2**(n-qubit), qubit, n) # At the end of our function, we call the same function again on # the next qubits (we reduced n by one earlier in the function) qft_rotations(circuit, n) def swap_registers(circuit, n): for qubit in range(n//2): circuit.swap(qubit, n-qubit-1) return circuit def qft(circuit, n): """QFT on the first n qubits in circuit""" qft_rotations(circuit, n) swap_registers(circuit, n) return circuit # See network archetechture for 4 qubits. There's a clear pattern with the Hadamard gates and CROT gates. qc = QuantumCircuit(4) qc = qft(qc,4) qc.draw() # My way, which doesn't use recursion: def qft_new(circuit, n): for qubit in range(n): idx = n-qubit-1 circuit.h(idx) for i in range(idx): circuit.cp(pi/2**(idx-i), i, idx) for j in range(n//2): circuit.swap(j, n-j-1) return circuit # Outputs the same circuit for 4 qubits as the original way. qc = QuantumCircuit(4) qc = qft_new(qc,4) qc.draw() # Inverse QFT can be be found by simply using the .inverse() method: qft_circ = qft_new(QuantumCircuit(4), 4) inv = qft_circ.inverse() inv.draw() # The following example was given in the textbook: qc = QuantumCircuit(3) # Encode the state |1,0,1> qc.x(0) qc.x(2) sim = Aer.get_backend("aer_simulator") qc_init = qc.copy() qc_init.save_statevector() statevector = sim.run(qc_init).result().get_statevector() plot_bloch_multivector(statevector) # Perform QFT, then see the transformed states qft_new(qc,3) qc.save_statevector() statevector = sim.run(qc).result().get_statevector() plot_bloch_multivector(statevector) # New example qc_new = QuantumCircuit(2) # Encode a custom entangled state qc_new.initialize([0,1/(2**0.5),0,-1/(2**0.5)]) qc_init = qc_new.copy() qc_init.save_statevector() statevector = sim.run(qc_init).result().get_statevector() plot_bloch_multivector(statevector) # Note: Bloch sphere images might not provide any insight into encoded state since the two qubits are entangled # Perform QFT qc_transformed = qft_new(qc_new,2) qc_final = qc_transformed.copy() qc_final.save_statevector() statevector = sim.run(qc_final).result().get_statevector() plot_bloch_multivector(statevector) # Note: once again, Bloch sphere images might not provide any insight
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the Stochastic Swap pass""" import unittest import numpy.random from ddt import ddt, data from qiskit.transpiler.passes import StochasticSwap from qiskit.transpiler import CouplingMap, PassManager, Layout from qiskit.transpiler.exceptions import TranspilerError from qiskit.converters import circuit_to_dag, dag_to_circuit from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.test import QiskitTestCase from qiskit.test._canonical import canonicalize_control_flow from qiskit.transpiler.passes.utils import CheckMap from qiskit.circuit.random import random_circuit from qiskit.providers.fake_provider import FakeMumbai, FakeMumbaiV2 from qiskit.compiler.transpiler import transpile from qiskit.circuit import ControlFlowOp, Clbit, CASE_DEFAULT from qiskit.circuit.classical import expr @ddt class TestStochasticSwap(QiskitTestCase): """ Tests the StochasticSwap pass. All of the tests use a fixed seed since the results may depend on it. """ def test_trivial_case(self): """ q0:--(+)-[H]-(+)- | | q1:---.-------|-- | q2:-----------.-- Coupling map: [1]--[0]--[2] """ coupling = CouplingMap([[0, 1], [0, 2]]) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.h(qr[0]) circuit.cx(qr[0], qr[2]) dag = circuit_to_dag(circuit) pass_ = StochasticSwap(coupling, 20, 13) after = pass_.run(dag) self.assertEqual(dag, after) def test_trivial_in_same_layer(self): """ q0:--(+)-- | q1:---.--- q2:--(+)-- | q3:---.--- Coupling map: [0]--[1]--[2]--[3] """ coupling = CouplingMap([[0, 1], [1, 2], [2, 3]]) qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[2], qr[3]) circuit.cx(qr[0], qr[1]) dag = circuit_to_dag(circuit) pass_ = StochasticSwap(coupling, 20, 13) after = pass_.run(dag) self.assertEqual(dag, after) def test_permute_wires_1(self): """ q0:-------- q1:---.---- | q2:--(+)--- Coupling map: [1]--[0]--[2] q0:--x-(+)- | | q1:--|--.-- | q2:--x----- """ coupling = CouplingMap([[0, 1], [0, 2]]) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[2]) dag = circuit_to_dag(circuit) pass_ = StochasticSwap(coupling, 20, 11) after = pass_.run(dag) expected = QuantumCircuit(qr) expected.swap(qr[0], qr[2]) expected.cx(qr[1], qr[0]) self.assertEqual(circuit_to_dag(expected), after) def test_permute_wires_2(self): """ qr0:---.---[H]-- | qr1:---|-------- | qr2:--(+)------- Coupling map: [0]--[1]--[2] qr0:----.---[H]- | qr1:-x-(+)------ | qr2:-x---------- """ coupling = CouplingMap([[1, 0], [1, 2]]) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[2]) circuit.h(qr[0]) dag = circuit_to_dag(circuit) pass_ = StochasticSwap(coupling, 20, 11) after = pass_.run(dag) expected = QuantumCircuit(qr) expected.swap(qr[1], qr[2]) expected.cx(qr[0], qr[1]) expected.h(qr[0]) self.assertEqual(expected, dag_to_circuit(after)) def test_permute_wires_3(self): """ qr0:--(+)---.-- | | qr1:---|----|-- | | qr2:---|----|-- | | qr3:---.---(+)- Coupling map: [0]--[1]--[2]--[3] qr0:-x------------ | qr1:-x--(+)---.--- | | qr2:-x---.---(+)-- | qr3:-x------------ """ coupling = CouplingMap([[0, 1], [1, 2], [2, 3]]) qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[3]) circuit.cx(qr[3], qr[0]) dag = circuit_to_dag(circuit) pass_ = StochasticSwap(coupling, 20, 13) after = pass_.run(dag) expected = QuantumCircuit(qr) expected.swap(qr[0], qr[1]) expected.swap(qr[2], qr[3]) expected.cx(qr[1], qr[2]) expected.cx(qr[2], qr[1]) self.assertEqual(circuit_to_dag(expected), after) def test_permute_wires_4(self): """No qubit label permutation occurs if the first layer has only single-qubit gates. This is suboptimal but seems to be the current behavior. qr0:------(+)-- | qr1:-------|--- | qr2:-------|--- | qr3:--[H]--.--- Coupling map: [0]--[1]--[2]--[3] qr0:------X--------- | qr1:------X-(+)----- | qr2:------X--.------ | qr3:-[H]--X--------- """ coupling = CouplingMap([[0, 1], [1, 2], [2, 3]]) qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.h(qr[3]) circuit.cx(qr[3], qr[0]) dag = circuit_to_dag(circuit) pass_ = StochasticSwap(coupling, 20, 13) after = pass_.run(dag) expected = QuantumCircuit(qr) expected.h(qr[3]) expected.swap(qr[2], qr[3]) expected.swap(qr[0], qr[1]) expected.cx(qr[2], qr[1]) self.assertEqual(circuit_to_dag(expected), after) def test_permute_wires_5(self): """This is the same case as permute_wires_4 except the single qubit gate is after the two-qubit gate, so the layout is adjusted. qr0:--(+)------ | qr1:---|------- | qr2:---|------- | qr3:---.--[H]-- Coupling map: [0]--[1]--[2]--[3] qr0:-x----------- | qr1:-x--(+)------ | qr2:-x---.--[H]-- | qr3:-x----------- """ coupling = CouplingMap([[0, 1], [1, 2], [2, 3]]) qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[3], qr[0]) circuit.h(qr[3]) dag = circuit_to_dag(circuit) pass_ = StochasticSwap(coupling, 20, 13) after = pass_.run(dag) expected = QuantumCircuit(qr) expected.swap(qr[0], qr[1]) expected.swap(qr[2], qr[3]) expected.cx(qr[2], qr[1]) expected.h(qr[2]) self.assertEqual(circuit_to_dag(expected), after) def test_all_single_qubit(self): """Test all trivial layers.""" coupling = CouplingMap([[0, 1], [1, 2], [1, 3]]) qr = QuantumRegister(4, "q") cr = ClassicalRegister(4, "c") circ = QuantumCircuit(qr, cr) circ.h(qr) circ.z(qr) circ.s(qr) circ.t(qr) circ.tdg(qr) circ.measure(qr[0], cr[0]) # intentional duplicate circ.measure(qr[0], cr[0]) circ.measure(qr[1], cr[1]) circ.measure(qr[2], cr[2]) circ.measure(qr[3], cr[3]) dag = circuit_to_dag(circ) pass_ = StochasticSwap(coupling, 20, 13) after = pass_.run(dag) self.assertEqual(dag, after) def test_overoptimization_case(self): """Check mapper overoptimization. The mapper should not change the semantics of the input. An overoptimization introduced issue #81: https://github.com/Qiskit/qiskit-terra/issues/81 """ coupling = CouplingMap([[0, 2], [1, 2], [2, 3]]) qr = QuantumRegister(4, "q") cr = ClassicalRegister(4, "c") circuit = QuantumCircuit(qr, cr) circuit.x(qr[0]) circuit.y(qr[1]) circuit.z(qr[2]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[2], qr[3]) circuit.s(qr[1]) circuit.t(qr[2]) circuit.h(qr[3]) circuit.cx(qr[1], qr[2]) circuit.measure(qr[0], cr[0]) circuit.measure(qr[1], cr[1]) circuit.measure(qr[2], cr[2]) circuit.measure(qr[3], cr[3]) dag = circuit_to_dag(circuit) # ┌───┐ ┌─┐ # q_0: | 0 >┤ X ├────────────■───────────────────────────┤M├───────── # └───┘┌───┐ ┌─┴─┐ ┌───┐ └╥┘┌─┐ # q_1: | 0 >─────┤ Y ├─────┤ X ├─────┤ S ├────────────■───╫─┤M├────── # └───┘┌───┐└───┘ └───┘┌───┐ ┌─┴─┐ ║ └╥┘┌─┐ # q_2: | 0 >──────────┤ Z ├───────■───────┤ T ├─────┤ X ├─╫──╫─┤M├─── # └───┘ ┌─┴─┐ └───┘┌───┐└───┘ ║ ║ └╥┘┌─┐ # q_3: | 0 >────────────────────┤ X ├──────────┤ H ├──────╫──╫──╫─┤M├ # └───┘ └───┘ ║ ║ ║ └╥┘ # c_0: 0 ══════════════════════════════════════════════╩══╬══╬══╬═ # ║ ║ ║ # c_1: 0 ═════════════════════════════════════════════════╩══╬══╬═ # ║ ║ # c_2: 0 ════════════════════════════════════════════════════╩══╬═ # ║ # c_3: 0 ═══════════════════════════════════════════════════════╩═ # expected = QuantumCircuit(qr, cr) expected.z(qr[2]) expected.y(qr[1]) expected.x(qr[0]) expected.swap(qr[0], qr[2]) expected.cx(qr[2], qr[1]) expected.swap(qr[0], qr[2]) expected.cx(qr[2], qr[3]) expected.s(qr[1]) expected.t(qr[2]) expected.h(qr[3]) expected.measure(qr[0], cr[0]) expected.cx(qr[1], qr[2]) expected.measure(qr[3], cr[3]) expected.measure(qr[1], cr[1]) expected.measure(qr[2], cr[2]) expected_dag = circuit_to_dag(expected) # ┌───┐ ┌─┐ # q_0: ┤ X ├─X───────X──────┤M├──────────────── # ├───┤ │ ┌───┐ │ ┌───┐└╥┘ ┌─┐ # q_1: ┤ Y ├─┼─┤ X ├─┼─┤ S ├─╫────────■──┤M├─── # ├───┤ │ └─┬─┘ │ └───┘ ║ ┌───┐┌─┴─┐└╥┘┌─┐ # q_2: ┤ Z ├─X───■───X───■───╫─┤ T ├┤ X ├─╫─┤M├ # └───┘ ┌─┴─┐ ║ ├───┤└┬─┬┘ ║ └╥┘ # q_3: ────────────────┤ X ├─╫─┤ H ├─┤M├──╫──╫─ # └───┘ ║ └───┘ └╥┘ ║ ║ # c: 4/══════════════════════╩════════╩═══╩══╩═ # 0 3 1 2 # # Layout -- # {qr[0]: 0, # qr[1]: 1, # qr[2]: 2, # qr[3]: 3} pass_ = StochasticSwap(coupling, 20, 19) after = pass_.run(dag) self.assertEqual(expected_dag, after) def test_already_mapped(self): """Circuit not remapped if matches topology. See: https://github.com/Qiskit/qiskit-terra/issues/342 """ coupling = CouplingMap( [ [1, 0], [1, 2], [2, 3], [3, 4], [3, 14], [5, 4], [6, 5], [6, 7], [6, 11], [7, 10], [8, 7], [9, 8], [9, 10], [11, 10], [12, 5], [12, 11], [12, 13], [13, 4], [13, 14], [15, 0], [15, 0], [15, 2], [15, 14], ] ) qr = QuantumRegister(16, "q") cr = ClassicalRegister(16, "c") circ = QuantumCircuit(qr, cr) circ.cx(qr[3], qr[14]) circ.cx(qr[5], qr[4]) circ.h(qr[9]) circ.cx(qr[9], qr[8]) circ.x(qr[11]) circ.cx(qr[3], qr[4]) circ.cx(qr[12], qr[11]) circ.cx(qr[13], qr[4]) for j in range(16): circ.measure(qr[j], cr[j]) dag = circuit_to_dag(circ) pass_ = StochasticSwap(coupling, 20, 13) after = pass_.run(dag) self.assertEqual(circuit_to_dag(circ), after) def test_congestion(self): """Test code path that falls back to serial layers.""" coupling = CouplingMap([[0, 1], [1, 2], [1, 3]]) qr = QuantumRegister(4, "q") cr = ClassicalRegister(4, "c") circ = QuantumCircuit(qr, cr) circ.cx(qr[1], qr[2]) circ.cx(qr[0], qr[3]) circ.measure(qr[0], cr[0]) circ.h(qr) circ.cx(qr[0], qr[1]) circ.cx(qr[2], qr[3]) circ.measure(qr[0], cr[0]) circ.measure(qr[1], cr[1]) circ.measure(qr[2], cr[2]) circ.measure(qr[3], cr[3]) dag = circuit_to_dag(circ) # Input: # ┌─┐┌───┐ ┌─┐ # q_0: |0>─────────────────■──────────────────┤M├┤ H ├──■─────┤M├ # ┌───┐ │ └╥┘└───┘┌─┴─┐┌─┐└╥┘ # q_1: |0>──■───────┤ H ├──┼───────────────────╫──────┤ X ├┤M├─╫─ # ┌─┴─┐┌───┐└───┘ │ ┌─┐ ║ └───┘└╥┘ ║ # q_2: |0>┤ X ├┤ H ├───────┼─────────■─────┤M├─╫────────────╫──╫─ # └───┘└───┘ ┌─┴─┐┌───┐┌─┴─┐┌─┐└╥┘ ║ ║ ║ # q_3: |0>───────────────┤ X ├┤ H ├┤ X ├┤M├─╫──╫────────────╫──╫─ # └───┘└───┘└───┘└╥┘ ║ ║ ║ ║ # c_0: 0 ═══════════════════════════════╬══╬══╩════════════╬══╩═ # ║ ║ ║ # c_1: 0 ═══════════════════════════════╬══╬═══════════════╩════ # ║ ║ # c_2: 0 ═══════════════════════════════╬══╩════════════════════ # ║ # c_3: 0 ═══════════════════════════════╩═══════════════════════ # # Expected output (with seed 999): # ┌───┐ ┌─┐ # q_0: ───────X──┤ H ├─────────────────X──────┤M├────── # │ └───┘ ┌─┐ ┌───┐ │ ┌───┐└╥┘ ┌─┐ # q_1: ──■────X────■───────┤M├─X─┤ X ├─X─┤ X ├─╫────┤M├ # ┌─┴─┐┌───┐ │ └╥┘ │ └─┬─┘┌─┐└─┬─┘ ║ └╥┘ # q_2: ┤ X ├┤ H ├──┼────────╫──┼───■──┤M├──┼───╫─────╫─ # └───┘└───┘┌─┴─┐┌───┐ ║ │ ┌───┐└╥┘ │ ║ ┌─┐ ║ # q_3: ──────────┤ X ├┤ H ├─╫──X─┤ H ├─╫───■───╫─┤M├─╫─ # └───┘└───┘ ║ └───┘ ║ ║ └╥┘ ║ # c: 4/═════════════════════╩══════════╩═══════╩══╩══╩═ # 0 2 3 0 1 # # Target coupling graph: # 2 # | # 0 - 1 - 3 expected = QuantumCircuit(qr, cr) expected.cx(qr[1], qr[2]) expected.h(qr[2]) expected.swap(qr[0], qr[1]) expected.h(qr[0]) expected.cx(qr[1], qr[3]) expected.h(qr[3]) expected.measure(qr[1], cr[0]) expected.swap(qr[1], qr[3]) expected.cx(qr[2], qr[1]) expected.h(qr[3]) expected.swap(qr[0], qr[1]) expected.measure(qr[2], cr[2]) expected.cx(qr[3], qr[1]) expected.measure(qr[0], cr[3]) expected.measure(qr[3], cr[0]) expected.measure(qr[1], cr[1]) expected_dag = circuit_to_dag(expected) pass_ = StochasticSwap(coupling, 20, 999) after = pass_.run(dag) self.assertEqual(expected_dag, after) def test_only_output_cx_and_swaps_in_coupling_map(self): """Test that output DAG contains only 2q gates from the the coupling map.""" coupling = CouplingMap([[0, 1], [1, 2], [2, 3]]) qr = QuantumRegister(4, "q") cr = ClassicalRegister(4, "c") circuit = QuantumCircuit(qr, cr) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[2]) circuit.cx(qr[0], qr[3]) circuit.measure(qr, cr) dag = circuit_to_dag(circuit) pass_ = StochasticSwap(coupling, 20, 5) after = pass_.run(dag) valid_couplings = [{qr[a], qr[b]} for (a, b) in coupling.get_edges()] for _2q_gate in after.two_qubit_ops(): self.assertIn(set(_2q_gate.qargs), valid_couplings) def test_len_cm_vs_dag(self): """Test error if the coupling map is smaller than the dag.""" coupling = CouplingMap([[0, 1], [1, 2]]) qr = QuantumRegister(4, "q") cr = ClassicalRegister(4, "c") circuit = QuantumCircuit(qr, cr) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[2]) circuit.cx(qr[0], qr[3]) circuit.measure(qr, cr) dag = circuit_to_dag(circuit) pass_ = StochasticSwap(coupling) with self.assertRaises(TranspilerError): _ = pass_.run(dag) def test_single_gates_omitted(self): """Test if single qubit gates are omitted.""" coupling_map = [[0, 1], [1, 0], [1, 2], [1, 3], [2, 1], [3, 1], [3, 4], [4, 3]] # q_0: ──■────────────────── # │ # q_1: ──┼─────────■──────── # │ ┌─┴─┐ # q_2: ──┼───────┤ X ├────── # │ ┌────┴───┴─────┐ # q_3: ──┼──┤ U(1,1.5,0.7) ├ # ┌─┴─┐└──────────────┘ # q_4: ┤ X ├──────────────── # └───┘ qr = QuantumRegister(5, "q") cr = ClassicalRegister(5, "c") circuit = QuantumCircuit(qr, cr) circuit.cx(qr[0], qr[4]) circuit.cx(qr[1], qr[2]) circuit.u(1, 1.5, 0.7, qr[3]) # q_0: ─────────────────X────── # │ # q_1: ───────■─────────X───■── # ┌─┴─┐ │ # q_2: ─────┤ X ├───────────┼── # ┌────┴───┴─────┐ ┌─┴─┐ # q_3: ┤ U(1,1.5,0.7) ├─X─┤ X ├ # └──────────────┘ │ └───┘ # q_4: ─────────────────X────── expected = QuantumCircuit(qr, cr) expected.cx(qr[1], qr[2]) expected.u(1, 1.5, 0.7, qr[3]) expected.swap(qr[0], qr[1]) expected.swap(qr[3], qr[4]) expected.cx(qr[1], qr[3]) expected_dag = circuit_to_dag(expected) stochastic = StochasticSwap(CouplingMap(coupling_map), seed=0) after = PassManager(stochastic).run(circuit) after = circuit_to_dag(after) self.assertEqual(expected_dag, after) @ddt class TestStochasticSwapControlFlow(QiskitTestCase): """Tests for control flow in stochastic swap.""" def test_pre_if_else_route(self): """test swap with if else controlflow construct""" num_qubits = 5 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap.from_line(num_qubits) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.cx(0, 2) qc.measure(2, 2) true_body = QuantumCircuit(qreg, creg[[2]]) true_body.x(3) false_body = QuantumCircuit(qreg, creg[[2]]) false_body.x(4) qc.if_else((creg[2], 0), true_body, false_body, qreg, creg[[2]]) qc.barrier(qreg) qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = StochasticSwap(coupling, seed=82).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) expected.h(0) expected.swap(0, 1) expected.cx(1, 2) expected.measure(2, 2) etrue_body = QuantumCircuit(qreg[[3, 4]], creg[[2]]) etrue_body.x(0) efalse_body = QuantumCircuit(qreg[[3, 4]], creg[[2]]) efalse_body.x(1) new_order = [1, 0, 2, 3, 4] expected.if_else((creg[2], 0), etrue_body, efalse_body, qreg[[3, 4]], creg[[2]]) expected.barrier(qreg) expected.measure(qreg, creg[new_order]) self.assertEqual(dag_to_circuit(cdag), expected) def test_pre_if_else_route_post_x(self): """test swap with if else controlflow construct; pre-cx and post x""" num_qubits = 5 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap([(i, i + 1) for i in range(num_qubits - 1)]) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.cx(0, 2) qc.measure(2, 2) true_body = QuantumCircuit(qreg, creg[[0]]) true_body.x(3) false_body = QuantumCircuit(qreg, creg[[0]]) false_body.x(4) qc.if_else((creg[2], 0), true_body, false_body, qreg, creg[[0]]) qc.x(1) qc.barrier(qreg) qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = StochasticSwap(coupling, seed=431).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) expected.h(0) expected.swap(1, 2) expected.cx(0, 1) expected.measure(1, 2) new_order = [0, 2, 1, 3, 4] etrue_body = QuantumCircuit(qreg[[3, 4]], creg[[0]]) etrue_body.x(0) efalse_body = QuantumCircuit(qreg[[3, 4]], creg[[0]]) efalse_body.x(1) expected.if_else((creg[2], 0), etrue_body, efalse_body, qreg[[3, 4]], creg[[0]]) expected.x(2) expected.barrier(qreg) expected.measure(qreg, creg[new_order]) self.assertEqual(dag_to_circuit(cdag), expected) def test_post_if_else_route(self): """test swap with if else controlflow construct; post cx""" num_qubits = 5 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap([(i, i + 1) for i in range(num_qubits - 1)]) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.measure(0, 0) true_body = QuantumCircuit(qreg, creg[[0]]) true_body.x(3) false_body = QuantumCircuit(qreg, creg[[0]]) false_body.x(4) qc.barrier(qreg) qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]]) qc.barrier(qreg) qc.cx(0, 2) qc.barrier(qreg) qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = StochasticSwap(coupling, seed=6508).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) expected.h(0) expected.measure(0, 0) etrue_body = QuantumCircuit(qreg[[3, 4]], creg[[0]]) etrue_body.x(0) efalse_body = QuantumCircuit(qreg[[3, 4]], creg[[0]]) efalse_body.x(1) expected.barrier(qreg) expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg[[3, 4]], creg[[0]]) expected.barrier(qreg) expected.swap(0, 1) expected.cx(1, 2) expected.barrier(qreg) expected.measure(qreg, creg[[1, 0, 2, 3, 4]]) self.assertEqual(dag_to_circuit(cdag), expected) def test_pre_if_else2(self): """test swap with if else controlflow construct; cx in if statement""" num_qubits = 5 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap([(i, i + 1) for i in range(num_qubits - 1)]) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.cx(0, 2) qc.x(1) qc.measure(0, 0) true_body = QuantumCircuit(qreg, creg[[0]]) true_body.x(0) false_body = QuantumCircuit(qreg, creg[[0]]) qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]]) qc.barrier(qreg) qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = StochasticSwap(coupling, seed=38).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) expected.h(0) expected.x(1) expected.swap(0, 1) expected.cx(1, 2) expected.measure(1, 0) etrue_body = QuantumCircuit(qreg[[1]], creg[[0]]) etrue_body.x(0) efalse_body = QuantumCircuit(qreg[[1]], creg[[0]]) new_order = [1, 0, 2, 3, 4] expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg[[1]], creg[[0]]) expected.barrier(qreg) expected.measure(qreg, creg[new_order]) self.assertEqual(dag_to_circuit(cdag), expected) def test_intra_if_else_route(self): """test swap with if else controlflow construct""" num_qubits = 5 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap([(i, i + 1) for i in range(num_qubits - 1)]) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.x(1) qc.measure(0, 0) true_body = QuantumCircuit(qreg, creg[[0]]) true_body.cx(0, 2) false_body = QuantumCircuit(qreg, creg[[0]]) false_body.cx(0, 4) qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]]) qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = StochasticSwap(coupling, seed=8).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) expected.h(0) expected.x(1) expected.measure(0, 0) etrue_body = QuantumCircuit(qreg, creg[[0]]) etrue_body.swap(0, 1) etrue_body.cx(1, 2) etrue_body.swap(1, 2) etrue_body.swap(3, 4) efalse_body = QuantumCircuit(qreg, creg[[0]]) efalse_body.swap(0, 1) efalse_body.swap(1, 2) efalse_body.swap(3, 4) efalse_body.cx(2, 3) expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg, creg[[0]]) new_order = [1, 2, 0, 4, 3] expected.measure(qreg, creg[new_order]) self.assertEqual(dag_to_circuit(cdag), expected) def test_pre_intra_if_else(self): """test swap with if else controlflow construct; cx in if statement""" num_qubits = 5 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap([(i, i + 1) for i in range(num_qubits - 1)]) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.cx(0, 2) qc.x(1) qc.measure(0, 0) true_body = QuantumCircuit(qreg, creg[[0]]) true_body.cx(0, 2) false_body = QuantumCircuit(qreg, creg[[0]]) false_body.cx(0, 4) qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]]) qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = StochasticSwap(coupling, seed=2, trials=20).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) etrue_body = QuantumCircuit(qreg[[1, 2, 3, 4]], creg[[0]]) efalse_body = QuantumCircuit(qreg[[1, 2, 3, 4]], creg[[0]]) expected.h(0) expected.x(1) expected.swap(0, 1) expected.cx(1, 2) expected.measure(1, 0) etrue_body.cx(0, 1) etrue_body.swap(2, 3) etrue_body.swap(0, 1) efalse_body.swap(0, 1) efalse_body.swap(2, 3) efalse_body.cx(1, 2) expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg[[1, 2, 3, 4]], creg[[0]]) expected.measure(qreg, creg[[1, 2, 0, 4, 3]]) self.assertEqual(dag_to_circuit(cdag), expected) def test_pre_intra_post_if_else(self): """test swap with if else controlflow construct; cx before, in, and after if statement""" num_qubits = 5 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap.from_line(num_qubits) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.cx(0, 2) qc.x(1) qc.measure(0, 0) true_body = QuantumCircuit(qreg, creg[[0]]) true_body.cx(0, 2) false_body = QuantumCircuit(qreg, creg[[0]]) false_body.cx(0, 4) qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]]) qc.h(3) qc.cx(3, 0) qc.barrier() qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = StochasticSwap(coupling, seed=1).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) expected.h(0) expected.x(1) expected.swap(1, 2) expected.cx(0, 1) expected.measure(0, 0) etrue_body = QuantumCircuit(qreg, creg[[0]]) etrue_body.cx(0, 1) etrue_body.swap(0, 1) etrue_body.swap(4, 3) etrue_body.swap(2, 3) efalse_body = QuantumCircuit(qreg, creg[[0]]) efalse_body.swap(0, 1) efalse_body.swap(3, 4) efalse_body.swap(2, 3) efalse_body.cx(1, 2) expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg[[0, 1, 2, 3, 4]], creg[[0]]) expected.swap(1, 2) expected.h(4) expected.swap(3, 4) expected.cx(3, 2) expected.barrier() expected.measure(qreg, creg[[2, 4, 0, 3, 1]]) self.assertEqual(dag_to_circuit(cdag), expected) def test_if_expr(self): """Test simple if conditional with an `Expr` condition.""" coupling = CouplingMap.from_line(4) body = QuantumCircuit(4) body.cx(0, 1) body.cx(0, 2) body.cx(0, 3) qc = QuantumCircuit(4, 2) qc.if_test(expr.logic_and(qc.clbits[0], qc.clbits[1]), body, [0, 1, 2, 3], []) dag = circuit_to_dag(qc) cdag = StochasticSwap(coupling, seed=58).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) def test_if_else_expr(self): """Test simple if/else conditional with an `Expr` condition.""" coupling = CouplingMap.from_line(4) true = QuantumCircuit(4) true.cx(0, 1) true.cx(0, 2) true.cx(0, 3) false = QuantumCircuit(4) false.cx(3, 0) false.cx(3, 1) false.cx(3, 2) qc = QuantumCircuit(4, 2) qc.if_else(expr.logic_and(qc.clbits[0], qc.clbits[1]), true, false, [0, 1, 2, 3], []) dag = circuit_to_dag(qc) cdag = StochasticSwap(coupling, seed=58).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) def test_no_layout_change(self): """test controlflow with no layout change needed""" num_qubits = 5 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap.from_line(num_qubits) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.cx(0, 2) qc.x(1) qc.measure(0, 0) true_body = QuantumCircuit(qreg, creg[[0]]) true_body.x(2) false_body = QuantumCircuit(qreg, creg[[0]]) false_body.x(4) qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]]) qc.barrier(qreg) qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = StochasticSwap(coupling, seed=23).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) expected.h(0) expected.x(1) expected.swap(1, 2) expected.cx(0, 1) expected.measure(0, 0) etrue_body = QuantumCircuit(qreg[[1, 4]], creg[[0]]) etrue_body.x(0) efalse_body = QuantumCircuit(qreg[[1, 4]], creg[[0]]) efalse_body.x(1) expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg[[1, 4]], creg[[0]]) expected.barrier(qreg) expected.measure(qreg, creg[[0, 2, 1, 3, 4]]) self.assertEqual(dag_to_circuit(cdag), expected) @data(1, 2, 3) def test_for_loop(self, nloops): """test stochastic swap with for_loop""" # if the loop has only one iteration it isn't necessary for the pass # to swap back to the starting layout. This test would check that # optimization. num_qubits = 3 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap.from_line(num_qubits) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.x(1) for_body = QuantumCircuit(qreg) for_body.cx(0, 2) loop_parameter = None qc.for_loop(range(nloops), loop_parameter, for_body, qreg, []) qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = StochasticSwap(coupling, seed=687).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) expected.h(0) expected.x(1) efor_body = QuantumCircuit(qreg) efor_body.swap(0, 1) efor_body.cx(1, 2) efor_body.swap(0, 1) loop_parameter = None expected.for_loop(range(nloops), loop_parameter, efor_body, qreg, []) expected.measure(qreg, creg) self.assertEqual(dag_to_circuit(cdag), expected) def test_while_loop(self): """test while loop""" num_qubits = 4 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(len(qreg)) coupling = CouplingMap.from_line(num_qubits) qc = QuantumCircuit(qreg, creg) while_body = QuantumCircuit(qreg, creg) while_body.reset(qreg[2:]) while_body.h(qreg[2:]) while_body.cx(0, 3) while_body.measure(qreg[3], creg[3]) qc.while_loop((creg, 0), while_body, qc.qubits, qc.clbits) qc.barrier() qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = StochasticSwap(coupling, seed=58).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) ewhile_body = QuantumCircuit(qreg, creg[:]) ewhile_body.reset(qreg[2:]) ewhile_body.h(qreg[2:]) ewhile_body.swap(0, 1) ewhile_body.swap(2, 3) ewhile_body.cx(1, 2) ewhile_body.measure(qreg[2], creg[3]) ewhile_body.swap(1, 0) ewhile_body.swap(3, 2) expected.while_loop((creg, 0), ewhile_body, expected.qubits, expected.clbits) expected.barrier() expected.measure(qreg, creg) self.assertEqual(dag_to_circuit(cdag), expected) def test_while_loop_expr(self): """Test simple while loop with an `Expr` condition.""" coupling = CouplingMap.from_line(4) body = QuantumCircuit(4) body.cx(0, 1) body.cx(0, 2) body.cx(0, 3) qc = QuantumCircuit(4, 2) qc.while_loop(expr.logic_and(qc.clbits[0], qc.clbits[1]), body, [0, 1, 2, 3], []) dag = circuit_to_dag(qc) cdag = StochasticSwap(coupling, seed=58).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) def test_switch_single_case(self): """Test routing of 'switch' with just a single case.""" qreg = QuantumRegister(5, "q") creg = ClassicalRegister(3, "c") qc = QuantumCircuit(qreg, creg) case0 = QuantumCircuit(qreg[[0, 1, 2]], creg[:]) case0.cx(0, 1) case0.cx(1, 2) case0.cx(2, 0) qc.switch(creg, [(0, case0)], qreg[[0, 1, 2]], creg) coupling = CouplingMap.from_line(len(qreg)) pass_ = StochasticSwap(coupling, seed=58) test = pass_(qc) check = CheckMap(coupling) check(test) self.assertTrue(check.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) case0 = QuantumCircuit(qreg[[0, 1, 2]], creg[:]) case0.cx(0, 1) case0.cx(1, 2) case0.swap(0, 1) case0.cx(2, 1) case0.swap(0, 1) expected.switch(creg, [(0, case0)], qreg[[0, 1, 2]], creg[:]) self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected)) def test_switch_nonexhaustive(self): """Test routing of 'switch' with several but nonexhaustive cases.""" qreg = QuantumRegister(5, "q") creg = ClassicalRegister(3, "c") qc = QuantumCircuit(qreg, creg) case0 = QuantumCircuit(qreg, creg[:]) case0.cx(0, 1) case0.cx(1, 2) case0.cx(2, 0) case1 = QuantumCircuit(qreg, creg[:]) case1.cx(1, 2) case1.cx(2, 3) case1.cx(3, 1) case2 = QuantumCircuit(qreg, creg[:]) case2.cx(2, 3) case2.cx(3, 4) case2.cx(4, 2) qc.switch(creg, [(0, case0), ((1, 2), case1), (3, case2)], qreg, creg) coupling = CouplingMap.from_line(len(qreg)) pass_ = StochasticSwap(coupling, seed=58) test = pass_(qc) check = CheckMap(coupling) check(test) self.assertTrue(check.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) case0 = QuantumCircuit(qreg, creg[:]) case0.cx(0, 1) case0.cx(1, 2) case0.swap(0, 1) case0.cx(2, 1) case0.swap(0, 1) case1 = QuantumCircuit(qreg, creg[:]) case1.cx(1, 2) case1.cx(2, 3) case1.swap(1, 2) case1.cx(3, 2) case1.swap(1, 2) case2 = QuantumCircuit(qreg, creg[:]) case2.cx(2, 3) case2.cx(3, 4) case2.swap(3, 4) case2.cx(3, 2) case2.swap(3, 4) expected.switch(creg, [(0, case0), ((1, 2), case1), (3, case2)], qreg, creg) self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected)) @data((0, 1, 2, 3), (CASE_DEFAULT,)) def test_switch_exhaustive(self, labels): """Test routing of 'switch' with exhaustive cases; we should not require restoring the layout afterwards.""" qreg = QuantumRegister(5, "q") creg = ClassicalRegister(2, "c") qc = QuantumCircuit(qreg, creg) case0 = QuantumCircuit(qreg[[0, 1, 2]], creg[:]) case0.cx(0, 1) case0.cx(1, 2) case0.cx(2, 0) qc.switch(creg, [(labels, case0)], qreg[[0, 1, 2]], creg) coupling = CouplingMap.from_line(len(qreg)) pass_ = StochasticSwap(coupling, seed=58) test = pass_(qc) check = CheckMap(coupling) check(test) self.assertTrue(check.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) case0 = QuantumCircuit(qreg[[0, 1, 2]], creg[:]) case0.cx(0, 1) case0.cx(1, 2) case0.swap(0, 1) case0.cx(2, 1) expected.switch(creg, [(labels, case0)], qreg[[0, 1, 2]], creg) self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected)) def test_switch_nonexhaustive_expr(self): """Test routing of 'switch' with an `Expr` target and several but nonexhaustive cases.""" qreg = QuantumRegister(5, "q") creg = ClassicalRegister(3, "c") qc = QuantumCircuit(qreg, creg) case0 = QuantumCircuit(qreg, creg[:]) case0.cx(0, 1) case0.cx(1, 2) case0.cx(2, 0) case1 = QuantumCircuit(qreg, creg[:]) case1.cx(1, 2) case1.cx(2, 3) case1.cx(3, 1) case2 = QuantumCircuit(qreg, creg[:]) case2.cx(2, 3) case2.cx(3, 4) case2.cx(4, 2) qc.switch(expr.bit_or(creg, 5), [(0, case0), ((1, 2), case1), (3, case2)], qreg, creg) coupling = CouplingMap.from_line(len(qreg)) pass_ = StochasticSwap(coupling, seed=58) test = pass_(qc) check = CheckMap(coupling) check(test) self.assertTrue(check.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) case0 = QuantumCircuit(qreg, creg[:]) case0.cx(0, 1) case0.cx(1, 2) case0.swap(0, 1) case0.cx(2, 1) case0.swap(0, 1) case1 = QuantumCircuit(qreg, creg[:]) case1.cx(1, 2) case1.cx(2, 3) case1.swap(1, 2) case1.cx(3, 2) case1.swap(1, 2) case2 = QuantumCircuit(qreg, creg[:]) case2.cx(2, 3) case2.cx(3, 4) case2.swap(3, 4) case2.cx(3, 2) case2.swap(3, 4) expected.switch(expr.bit_or(creg, 5), [(0, case0), ((1, 2), case1), (3, case2)], qreg, creg) self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected)) @data((0, 1, 2, 3), (CASE_DEFAULT,)) def test_switch_exhaustive_expr(self, labels): """Test routing of 'switch' with exhaustive cases on an `Expr` target; we should not require restoring the layout afterwards.""" qreg = QuantumRegister(5, "q") creg = ClassicalRegister(2, "c") qc = QuantumCircuit(qreg, creg) case0 = QuantumCircuit(qreg[[0, 1, 2]], creg[:]) case0.cx(0, 1) case0.cx(1, 2) case0.cx(2, 0) qc.switch(expr.bit_or(creg, 3), [(labels, case0)], qreg[[0, 1, 2]], creg) coupling = CouplingMap.from_line(len(qreg)) pass_ = StochasticSwap(coupling, seed=58) test = pass_(qc) check = CheckMap(coupling) check(test) self.assertTrue(check.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) case0 = QuantumCircuit(qreg[[0, 1, 2]], creg[:]) case0.cx(0, 1) case0.cx(1, 2) case0.swap(0, 1) case0.cx(2, 1) expected.switch(expr.bit_or(creg, 3), [(labels, case0)], qreg[[0, 1, 2]], creg) self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected)) def test_nested_inner_cnot(self): """test swap in nested if else controlflow construct; swap in inner""" seed = 1 num_qubits = 3 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap.from_line(num_qubits) check_map_pass = CheckMap(coupling) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.x(1) qc.measure(0, 0) true_body = QuantumCircuit(qreg, creg[[0]]) true_body.x(0) for_body = QuantumCircuit(qreg) for_body.delay(10, 0) for_body.barrier(qreg) for_body.cx(0, 2) loop_parameter = None true_body.for_loop(range(3), loop_parameter, for_body, qreg, []) false_body = QuantumCircuit(qreg, creg[[0]]) false_body.y(0) qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]]) qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = StochasticSwap(coupling, seed=seed).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) expected.h(0) expected.x(1) expected.measure(0, 0) etrue_body = QuantumCircuit(qreg, creg[[0]]) etrue_body.x(0) efor_body = QuantumCircuit(qreg) efor_body.delay(10, 0) efor_body.barrier(qreg) efor_body.swap(1, 2) efor_body.cx(0, 1) efor_body.swap(1, 2) etrue_body.for_loop(range(3), loop_parameter, efor_body, qreg, []) efalse_body = QuantumCircuit(qreg, creg[[0]]) efalse_body.y(0) expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg, creg[[0]]) expected.measure(qreg, creg) self.assertEqual(dag_to_circuit(cdag), expected) def test_nested_outer_cnot(self): """test swap with nested if else controlflow construct; swap in outer""" seed = 200 num_qubits = 5 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap.from_line(num_qubits) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.x(1) qc.measure(0, 0) true_body = QuantumCircuit(qreg, creg[[0]]) true_body.cx(0, 2) true_body.x(0) for_body = QuantumCircuit(qreg) for_body.delay(10, 0) for_body.barrier(qreg) for_body.cx(1, 3) loop_parameter = None true_body.for_loop(range(3), loop_parameter, for_body, qreg, []) false_body = QuantumCircuit(qreg, creg[[0]]) false_body.y(0) qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]]) qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = StochasticSwap(coupling, seed=seed).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) expected.h(0) expected.x(1) expected.measure(0, 0) etrue_body = QuantumCircuit(qreg, creg[[0]]) etrue_body.swap(1, 2) etrue_body.cx(0, 1) etrue_body.x(0) efor_body = QuantumCircuit(qreg) efor_body.delay(10, 0) efor_body.barrier(qreg) efor_body.cx(2, 3) etrue_body.for_loop(range(3), loop_parameter, efor_body, qreg[[0, 1, 2, 3, 4]], []) efalse_body = QuantumCircuit(qreg, creg[[0]]) efalse_body.y(0) efalse_body.swap(1, 2) expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg, creg[[0]]) expected.measure(qreg, creg[[0, 2, 1, 3, 4]]) self.assertEqual(dag_to_circuit(cdag), expected) def test_disjoint_looping(self): """Test looping controlflow on different qubit register""" num_qubits = 4 cm = CouplingMap.from_line(num_qubits) qr = QuantumRegister(num_qubits, "q") qc = QuantumCircuit(qr) loop_body = QuantumCircuit(2) loop_body.cx(0, 1) qc.for_loop((0,), None, loop_body, [0, 2], []) cqc = StochasticSwap(cm, seed=0)(qc) expected = QuantumCircuit(qr) efor_body = QuantumCircuit(qr[[0, 1, 2]]) efor_body.swap(1, 2) efor_body.cx(0, 1) efor_body.swap(1, 2) expected.for_loop((0,), None, efor_body, [0, 1, 2], []) self.assertEqual(cqc, expected) def test_disjoint_multiblock(self): """Test looping controlflow on different qubit register""" num_qubits = 4 cm = CouplingMap.from_line(num_qubits) qr = QuantumRegister(num_qubits, "q") cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr) true_body = QuantumCircuit(3, 1) true_body.cx(0, 1) false_body = QuantumCircuit(3, 1) false_body.cx(0, 2) qc.if_else((cr[0], 1), true_body, false_body, [0, 1, 2], [0]) cqc = StochasticSwap(cm, seed=353)(qc) expected = QuantumCircuit(qr, cr) etrue_body = QuantumCircuit(qr[[0, 1, 2]], cr[[0]]) etrue_body.cx(0, 1) etrue_body.swap(0, 1) efalse_body = QuantumCircuit(qr[[0, 1, 2]], cr[[0]]) efalse_body.swap(0, 1) efalse_body.cx(1, 2) expected.if_else((cr[0], 1), etrue_body, efalse_body, [0, 1, 2], cr[[0]]) self.assertEqual(cqc, expected) def test_multiple_ops_per_layer(self): """Test circuits with multiple operations per layer""" num_qubits = 6 coupling = CouplingMap.from_line(num_qubits) check_map_pass = CheckMap(coupling) qr = QuantumRegister(num_qubits, "q") qc = QuantumCircuit(qr) # This cx and the for_loop are in the same layer. qc.cx(0, 2) with qc.for_loop((0,)): qc.cx(3, 5) cqc = StochasticSwap(coupling, seed=0)(qc) check_map_pass(cqc) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qr) expected.swap(0, 1) expected.cx(1, 2) efor_body = QuantumCircuit(qr[[3, 4, 5]]) efor_body.swap(1, 2) efor_body.cx(0, 1) efor_body.swap(2, 1) expected.for_loop((0,), None, efor_body, [3, 4, 5], []) self.assertEqual(cqc, expected) def test_if_no_else_restores_layout(self): """Test that an if block with no else branch restores the initial layout. If there is an else branch, we don't need to guarantee this.""" qc = QuantumCircuit(8, 1) with qc.if_test((qc.clbits[0], False)): # Just some arbitrary gates with no perfect layout. qc.cx(3, 5) qc.cx(4, 6) qc.cx(1, 4) qc.cx(7, 4) qc.cx(0, 5) qc.cx(7, 3) qc.cx(1, 3) qc.cx(5, 2) qc.cx(6, 7) qc.cx(3, 2) qc.cx(6, 2) qc.cx(2, 0) qc.cx(7, 6) coupling = CouplingMap.from_line(8) pass_ = StochasticSwap(coupling, seed=2022_10_13) transpiled = pass_(qc) # Check the pass claims to have done things right. initial_layout = Layout.generate_trivial_layout(*qc.qubits) self.assertEqual(initial_layout, pass_.property_set["final_layout"]) # Check that pass really did do it right. inner_block = transpiled.data[0].operation.blocks[0] running_layout = initial_layout.copy() for instruction in inner_block: if instruction.operation.name == "swap": running_layout.swap(*instruction.qubits) self.assertEqual(initial_layout, running_layout) @ddt class TestStochasticSwapRandomCircuitValidOutput(QiskitTestCase): """Assert the output of a transpilation with stochastic swap is a physical circuit.""" @classmethod def setUpClass(cls): super().setUpClass() cls.backend = FakeMumbai() cls.coupling_edge_set = {tuple(x) for x in cls.backend.configuration().coupling_map} cls.basis_gates = set(cls.backend.configuration().basis_gates) cls.basis_gates.update(["for_loop", "while_loop", "if_else"]) def assert_valid_circuit(self, transpiled): """Assert circuit complies with constraints of backend.""" self.assertIsInstance(transpiled, QuantumCircuit) self.assertIsNotNone(getattr(transpiled, "_layout", None)) def _visit_block(circuit, qubit_mapping=None): for instruction in circuit: if instruction.operation.name in {"barrier", "measure"}: continue self.assertIn(instruction.operation.name, self.basis_gates) qargs = tuple(qubit_mapping[x] for x in instruction.qubits) if not isinstance(instruction.operation, ControlFlowOp): if len(qargs) > 2 or len(qargs) < 0: raise Exception("Invalid number of qargs for instruction") if len(qargs) == 2: self.assertIn(qargs, self.coupling_edge_set) else: self.assertLessEqual(qargs[0], 26) else: for block in instruction.operation.blocks: self.assertEqual(block.num_qubits, len(instruction.qubits)) self.assertEqual(block.num_clbits, len(instruction.clbits)) new_mapping = { inner: qubit_mapping[outer] for outer, inner in zip(instruction.qubits, block.qubits) } _visit_block(block, new_mapping) # Assert routing ran. _visit_block( transpiled, qubit_mapping={qubit: index for index, qubit in enumerate(transpiled.qubits)}, ) @data(*range(1, 27)) def test_random_circuit_no_control_flow(self, size): """Test that transpiled random circuits without control flow are physical circuits.""" circuit = random_circuit(size, 3, measure=True, seed=12342) tqc = transpile( circuit, self.backend, routing_method="stochastic", layout_method="dense", seed_transpiler=12342, ) self.assert_valid_circuit(tqc) @data(*range(1, 27)) def test_random_circuit_no_control_flow_target(self, size): """Test that transpiled random circuits without control flow are physical circuits.""" circuit = random_circuit(size, 3, measure=True, seed=12342) tqc = transpile( circuit, routing_method="stochastic", layout_method="dense", seed_transpiler=12342, target=FakeMumbaiV2().target, ) self.assert_valid_circuit(tqc) @data(*range(4, 27)) def test_random_circuit_for_loop(self, size): """Test that transpiled random circuits with nested for loops are physical circuits.""" circuit = random_circuit(size, 3, measure=False, seed=12342) for_block = random_circuit(3, 2, measure=False, seed=12342) inner_for_block = random_circuit(2, 1, measure=False, seed=12342) with circuit.for_loop((1,)): with circuit.for_loop((1,)): circuit.append(inner_for_block, [0, 3]) circuit.append(for_block, [1, 0, 2]) circuit.measure_all() tqc = transpile( circuit, self.backend, basis_gates=list(self.basis_gates), routing_method="stochastic", layout_method="dense", seed_transpiler=12342, ) self.assert_valid_circuit(tqc) @data(*range(6, 27)) def test_random_circuit_if_else(self, size): """Test that transpiled random circuits with if else blocks are physical circuits.""" circuit = random_circuit(size, 3, measure=True, seed=12342) if_block = random_circuit(3, 2, measure=True, seed=12342) else_block = random_circuit(2, 1, measure=True, seed=12342) rng = numpy.random.default_rng(seed=12342) inner_clbit_count = max((if_block.num_clbits, else_block.num_clbits)) if inner_clbit_count > circuit.num_clbits: circuit.add_bits([Clbit() for _ in [None] * (inner_clbit_count - circuit.num_clbits)]) clbit_indices = list(range(circuit.num_clbits)) rng.shuffle(clbit_indices) with circuit.if_test((circuit.clbits[0], True)) as else_: circuit.append(if_block, [0, 2, 1], clbit_indices[: if_block.num_clbits]) with else_: circuit.append(else_block, [2, 5], clbit_indices[: else_block.num_clbits]) tqc = transpile( circuit, self.backend, basis_gates=list(self.basis_gates), routing_method="stochastic", layout_method="dense", seed_transpiler=12342, ) self.assert_valid_circuit(tqc) if __name__ == "__main__": unittest.main()
https://github.com/Tojarieh97/VQE
Tojarieh97
import numpy as np from qiskit.opflow import X, Z, I from qiskit.algorithms.optimizers import L_BFGS_B from qiskit.circuit.library import EfficientSU2 bfgs_optimizer = L_BFGS_B(maxiter=60) a_1 = np.random.random_sample() a_2 = np.random.random_sample() J_21 = np.random.random_sample() H_transverse_ising = a_1*(I^X) + a_2*(X^I) + J_21*(Z^Z) print("========== Transverse Ising Model Hamiltonian for Two Qubits ==========\n") print(H_transverse_ising.to_matrix()) print() H2_molecule_Hamiltonian = -0.5053051899926562*(I^I) + \ -0.3277380754984016*(Z^I) + \ 0.15567463610622564*(Z^Z) + \ -0.3277380754984016*(I^Z) print("========== H2 Molecule Hamiltonian for Two Qubits ==========\n") print(H2_molecule_Hamiltonian.to_matrix()) print() def vqe(hamiltonian, anzatz, optimazer, min_dist): # Create the initial parameters params = np.random.rand(3) ret = optimizer.optimize(num_vars=3, objective_function=objective_function, initial_point=params) # Obtain the output distribution using the final parameters qc = get_var_form(ret[0]) t_qc = transpile(qc, backend) qobj = assemble(t_qc, shots=NUM_SHOTS) counts = backend.run(qobj).result().get_counts(qc) output_distr = get_probability_distribution(counts) #calculate the target function old_res = old_state.dagger * hamiltonian * old_state print(old_res) #minimaize the target function #iterate the process vqe((I^I).to_matrix(),) (I^I).to_matrix()
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) qc.cx(1, 0) return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).issubset({0,1}): raise ValueError(f"message '{msg}' is invalid") if msg[1] == "1": qc.x(qubit) if msg[0] == "1": ### removed z gate ### pass return qc def decode_message(qc): ### removed cx gate ### qc.h(1) return qc
https://github.com/matheusmtta/Quantum-Machine-Learning
matheusmtta
#Assign these values as per your requirements. global min_qubits,max_qubits,skip_qubits,max_circuits,num_shots,Noise_Inclusion min_qubits=4 max_qubits=15 #reference files are upto 12 Qubits only skip_qubits=2 max_circuits=3 num_shots=4092 gate_counts_plots = True Noise_Inclusion = False saveplots = False Memory_utilization_plot = True Type_of_Simulator = "built_in" #Inputs are "built_in" or "FAKE" or "FAKEV2" backend_name = "FakeGuadalupeV2" #Can refer to the README files for the available backends #Change your Specification of Simulator in Declaring Backend Section #By Default : built_in -> qasm_simulator and FAKE -> FakeSantiago() and FAKEV2 -> FakeSantiagoV2() import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, transpile, execute from qiskit.opflow import PauliTrotterEvolution, Suzuki from qiskit.opflow.primitive_ops import PauliSumOp import time,os,json import matplotlib.pyplot as plt # Import from Qiskit Aer noise module from qiskit_aer.noise import (NoiseModel, QuantumError, ReadoutError,pauli_error, depolarizing_error, thermal_relaxation_error,reset_error) # Benchmark Name benchmark_name = "VQE Simulation" # Selection of basis gate set for transpilation # Note: selector 1 is a hardware agnostic gate set basis_selector = 1 basis_gates_array = [ [], ['rx', 'ry', 'rz', 'cx'], # a common basis set, default ['cx', 'rz', 'sx', 'x'], # IBM default basis set ['rx', 'ry', 'rxx'], # IonQ default basis set ['h', 'p', 'cx'], # another common basis set ['u', 'cx'] # general unitaries basis gates ] np.random.seed(0) def get_QV(backend): import json # Assuming backend.conf_filename is the filename and backend.dirname is the directory path conf_filename = backend.dirname + "/" + backend.conf_filename # Open the JSON file with open(conf_filename, 'r') as file: # Load the JSON data data = json.load(file) # Extract the quantum_volume parameter QV = data.get('quantum_volume', None) return QV def checkbackend(backend_name,Type_of_Simulator): if Type_of_Simulator == "built_in": available_backends = [] for i in Aer.backends(): available_backends.append(i.name) if backend_name in available_backends: platform = backend_name return platform else: print(f"incorrect backend name or backend not available. Using qasm_simulator by default !!!!") print(f"available backends are : {available_backends}") platform = "qasm_simulator" return platform elif Type_of_Simulator == "FAKE" or Type_of_Simulator == "FAKEV2": import qiskit.providers.fake_provider as fake_backends if hasattr(fake_backends,backend_name) is True: print(f"Backend {backend_name} is available for type {Type_of_Simulator}.") backend_class = getattr(fake_backends,backend_name) backend_instance = backend_class() return backend_instance else: print(f"Backend {backend_name} is not available or incorrect for type {Type_of_Simulator}. Executing with FakeSantiago!!!") if Type_of_Simulator == "FAKEV2": backend_class = getattr(fake_backends,"FakeSantiagoV2") else: backend_class = getattr(fake_backends,"FakeSantiago") backend_instance = backend_class() return backend_instance if Type_of_Simulator == "built_in": platform = checkbackend(backend_name,Type_of_Simulator) #By default using "Qasm Simulator" backend = Aer.get_backend(platform) QV_=None print(f"{platform} device is capable of running {backend.num_qubits}") print(f"backend version is {backend.backend_version}") elif Type_of_Simulator == "FAKE": basis_selector = 0 backend = checkbackend(backend_name,Type_of_Simulator) QV_ = get_QV(backend) platform = backend.properties().backend_name +"-"+ backend.properties().backend_version #Replace this string with the backend Provider's name as this is used for Plotting. max_qubits=backend.configuration().n_qubits print(f"{platform} device is capable of running {backend.configuration().n_qubits}") print(f"{platform} has QV={QV_}") if max_qubits > 30: print(f"Device is capable with max_qubits = {max_qubits}") max_qubit = 30 print(f"Using fake backend {platform} with max_qubits {max_qubits}") elif Type_of_Simulator == "FAKEV2": basis_selector = 0 if "V2" not in backend_name: backend_name = backend_name+"V2" backend = checkbackend(backend_name,Type_of_Simulator) QV_ = get_QV(backend) platform = backend.name +"-" +backend.backend_version max_qubits=backend.num_qubits print(f"{platform} device is capable of running {backend.num_qubits}") print(f"{platform} has QV={QV_}") if max_qubits > 30: print(f"Device is capable with max_qubits = {max_qubits}") max_qubit = 30 print(f"Using fake backend {platform} with max_qubits {max_qubits}") else: print("Enter valid Simulator.....") # saved circuits for display QC_ = None Hf_ = None CO_ = None ################### Circuit Definition ####################################### # Construct a Qiskit circuit for VQE Energy evaluation with UCCSD ansatz # param: n_spin_orbs - The number of spin orbitals. # return: return a Qiskit circuit for this VQE ansatz def VQEEnergy(n_spin_orbs, na, nb, circuit_id=0, method=1): # number of alpha spin orbitals norb_a = int(n_spin_orbs / 2) # construct the Hamiltonian qubit_op = ReadHamiltonian(n_spin_orbs) # allocate qubits num_qubits = n_spin_orbs qr = QuantumRegister(num_qubits) qc = QuantumCircuit(qr, name=f"vqe-ansatz({method})-{num_qubits}-{circuit_id}") # initialize the HF state Hf = HartreeFock(num_qubits, na, nb) qc.append(Hf, qr) # form the list of single and double excitations excitationList = [] for occ_a in range(na): for vir_a in range(na, norb_a): excitationList.append((occ_a, vir_a)) for occ_b in range(norb_a, norb_a+nb): for vir_b in range(norb_a+nb, n_spin_orbs): excitationList.append((occ_b, vir_b)) for occ_a in range(na): for vir_a in range(na, norb_a): for occ_b in range(norb_a, norb_a+nb): for vir_b in range(norb_a+nb, n_spin_orbs): excitationList.append((occ_a, vir_a, occ_b, vir_b)) # get cluster operators in Paulis pauli_list = readPauliExcitation(n_spin_orbs, circuit_id) # loop over the Pauli operators for index, PauliOp in enumerate(pauli_list): # get circuit for exp(-iP) cluster_qc = ClusterOperatorCircuit(PauliOp, excitationList[index]) # add to ansatz qc.append(cluster_qc, [i for i in range(cluster_qc.num_qubits)]) # method 1, only compute the last term in the Hamiltonian if method == 1: # last term in Hamiltonian qc_with_mea, is_diag = ExpectationCircuit(qc, qubit_op[1], num_qubits) # return the circuit return qc_with_mea # now we need to add the measurement parts to the circuit # circuit list qc_list = [] diag = [] off_diag = [] global normalization normalization = 0.0 # add the first non-identity term identity_qc = qc.copy() identity_qc.measure_all() qc_list.append(identity_qc) # add to circuit list diag.append(qubit_op[1]) normalization += abs(qubit_op[1].coeffs[0]) # add to normalization factor diag_coeff = abs(qubit_op[1].coeffs[0]) # add to coefficients of diagonal terms # loop over rest of terms for index, p in enumerate(qubit_op[2:]): # get the circuit with expectation measurements qc_with_mea, is_diag = ExpectationCircuit(qc, p, num_qubits) # accumulate normalization normalization += abs(p.coeffs[0]) # add to circuit list if non-diagonal if not is_diag: qc_list.append(qc_with_mea) else: diag_coeff += abs(p.coeffs[0]) # diagonal term if is_diag: diag.append(p) # off-diagonal term else: off_diag.append(p) # modify the name of diagonal circuit qc_list[0].name = qubit_op[1].primitive.to_list()[0][0] + " " + str(np.real(diag_coeff)) normalization /= len(qc_list) return qc_list # Function that constructs the circuit for a given cluster operator def ClusterOperatorCircuit(pauli_op, excitationIndex): # compute exp(-iP) exp_ip = pauli_op.exp_i() # Trotter approximation qc_op = PauliTrotterEvolution(trotter_mode=Suzuki(order=1, reps=1)).convert(exp_ip) # convert to circuit qc = qc_op.to_circuit(); qc.name = f'Cluster Op {excitationIndex}' global CO_ if CO_ == None or qc.num_qubits <= 4: if qc.num_qubits < 7: CO_ = qc # return this circuit return qc # Function that adds expectation measurements to the raw circuits def ExpectationCircuit(qc, pauli, nqubit, method=2): # copy the unrotated circuit raw_qc = qc.copy() # whether this term is diagonal is_diag = True # primitive Pauli string PauliString = pauli.primitive.to_list()[0][0] # coefficient coeff = pauli.coeffs[0] # basis rotation for i, p in enumerate(PauliString): target_qubit = nqubit - i - 1 if (p == "X"): is_diag = False raw_qc.h(target_qubit) elif (p == "Y"): raw_qc.sdg(target_qubit) raw_qc.h(target_qubit) is_diag = False # perform measurements raw_qc.measure_all() # name of this circuit raw_qc.name = PauliString + " " + str(np.real(coeff)) # save circuit global QC_ if QC_ == None or nqubit <= 4: if nqubit < 7: QC_ = raw_qc return raw_qc, is_diag # Function that implements the Hartree-Fock state def HartreeFock(norb, na, nb): # initialize the quantum circuit qc = QuantumCircuit(norb, name="Hf") # alpha electrons for ia in range(na): qc.x(ia) # beta electrons for ib in range(nb): qc.x(ib+int(norb/2)) # Save smaller circuit global Hf_ if Hf_ == None or norb <= 4: if norb < 7: Hf_ = qc # return the circuit return qc ################ Helper Functions # Function that converts a list of single and double excitation operators to Pauli operators def readPauliExcitation(norb, circuit_id=0): # load pre-computed data filename = os.path.join(f'ansatzes/{norb}_qubit_{circuit_id}.txt') with open(filename) as f: data = f.read() ansatz_dict = json.loads(data) # initialize Pauli list pauli_list = [] # current coefficients cur_coeff = 1e5 # current Pauli list cur_list = [] # loop over excitations for ext in ansatz_dict: if cur_coeff > 1e4: cur_coeff = ansatz_dict[ext] cur_list = [(ext, ansatz_dict[ext])] elif abs(abs(ansatz_dict[ext]) - abs(cur_coeff)) > 1e-4: pauli_list.append(PauliSumOp.from_list(cur_list)) cur_coeff = ansatz_dict[ext] cur_list = [(ext, ansatz_dict[ext])] else: cur_list.append((ext, ansatz_dict[ext])) # add the last term pauli_list.append(PauliSumOp.from_list(cur_list)) # return Pauli list return pauli_list # Get the Hamiltonian by reading in pre-computed file def ReadHamiltonian(nqubit): # load pre-computed data filename = os.path.join(f'Hamiltonians/{nqubit}_qubit.txt') with open(filename) as f: data = f.read() ham_dict = json.loads(data) # pauli list pauli_list = [] for p in ham_dict: pauli_list.append( (p, ham_dict[p]) ) # build Hamiltonian ham = PauliSumOp.from_list(pauli_list) # return Hamiltonian return ham # Create an empty noise model noise_parameters = NoiseModel() if Type_of_Simulator == "built_in": # Add depolarizing error to all single qubit gates with error rate 0.05% and to all two qubit gates with error rate 0.5% depol_one_qb_error = 0.05 depol_two_qb_error = 0.005 noise_parameters.add_all_qubit_quantum_error(depolarizing_error(depol_one_qb_error, 1), ['rx', 'ry', 'rz']) noise_parameters.add_all_qubit_quantum_error(depolarizing_error(depol_two_qb_error, 2), ['cx']) # Add amplitude damping error to all single qubit gates with error rate 0.0% and to all two qubit gates with error rate 0.0% amp_damp_one_qb_error = 0.0 amp_damp_two_qb_error = 0.0 noise_parameters.add_all_qubit_quantum_error(depolarizing_error(amp_damp_one_qb_error, 1), ['rx', 'ry', 'rz']) noise_parameters.add_all_qubit_quantum_error(depolarizing_error(amp_damp_two_qb_error, 2), ['cx']) # Add reset noise to all single qubit resets reset_to_zero_error = 0.005 reset_to_one_error = 0.005 noise_parameters.add_all_qubit_quantum_error(reset_error(reset_to_zero_error, reset_to_one_error),["reset"]) # Add readout error p0given1_error = 0.000 p1given0_error = 0.000 error_meas = ReadoutError([[1 - p1given0_error, p1given0_error], [p0given1_error, 1 - p0given1_error]]) noise_parameters.add_all_qubit_readout_error(error_meas) #print(noise_parameters) elif Type_of_Simulator == "FAKE"or"FAKEV2": noise_parameters = NoiseModel.from_backend(backend) #print(noise_parameters) ### Analysis methods to be expanded and eventually compiled into a separate analysis.py file import math, functools def hellinger_fidelity_with_expected(p, q): """ p: result distribution, may be passed as a counts distribution q: the expected distribution to be compared against References: `Hellinger Distance @ wikipedia <https://en.wikipedia.org/wiki/Hellinger_distance>`_ Qiskit Hellinger Fidelity Function """ p_sum = sum(p.values()) q_sum = sum(q.values()) if q_sum == 0: print("ERROR: polarization_fidelity(), expected distribution is invalid, all counts equal to 0") return 0 p_normed = {} for key, val in p.items(): p_normed[key] = val/p_sum # if p_sum != 0: # p_normed[key] = val/p_sum # else: # p_normed[key] = 0 q_normed = {} for key, val in q.items(): q_normed[key] = val/q_sum total = 0 for key, val in p_normed.items(): if key in q_normed.keys(): total += (np.sqrt(val) - np.sqrt(q_normed[key]))**2 del q_normed[key] else: total += val total += sum(q_normed.values()) # in some situations (error mitigation) this can go negative, use abs value if total < 0: print(f"WARNING: using absolute value in fidelity calculation") total = abs(total) dist = np.sqrt(total)/np.sqrt(2) fidelity = (1-dist**2)**2 return fidelity def polarization_fidelity(counts, correct_dist, thermal_dist=None): """ Combines Hellinger fidelity and polarization rescaling into fidelity calculation used in every benchmark counts: the measurement outcomes after `num_shots` algorithm runs correct_dist: the distribution we expect to get for the algorithm running perfectly thermal_dist: optional distribution to pass in distribution from a uniform superposition over all states. If `None`: generated as `uniform_dist` with the same qubits as in `counts` returns both polarization fidelity and the hellinger fidelity Polarization from: `https://arxiv.org/abs/2008.11294v1` """ num_measured_qubits = len(list(correct_dist.keys())[0]) #print(num_measured_qubits) counts = {k.zfill(num_measured_qubits): v for k, v in counts.items()} # calculate hellinger fidelity between measured expectation values and correct distribution hf_fidelity = hellinger_fidelity_with_expected(counts,correct_dist) # to limit cpu and memory utilization, skip noise correction if more than 16 measured qubits if num_measured_qubits > 16: return { 'fidelity':hf_fidelity, 'hf_fidelity':hf_fidelity } # if not provided, generate thermal dist based on number of qubits if thermal_dist == None: thermal_dist = uniform_dist(num_measured_qubits) # set our fidelity rescaling value as the hellinger fidelity for a depolarized state floor_fidelity = hellinger_fidelity_with_expected(thermal_dist, correct_dist) # rescale fidelity result so uniform superposition (random guessing) returns fidelity # rescaled to 0 to provide a better measure of success of the algorithm (polarization) new_floor_fidelity = 0 fidelity = rescale_fidelity(hf_fidelity, floor_fidelity, new_floor_fidelity) return { 'fidelity':fidelity, 'hf_fidelity':hf_fidelity } ## Uniform distribution function commonly used def rescale_fidelity(fidelity, floor_fidelity, new_floor_fidelity): """ Linearly rescales our fidelities to allow comparisons of fidelities across benchmarks fidelity: raw fidelity to rescale floor_fidelity: threshold fidelity which is equivalent to random guessing new_floor_fidelity: what we rescale the floor_fidelity to Ex, with floor_fidelity = 0.25, new_floor_fidelity = 0.0: 1 -> 1; 0.25 -> 0; 0.5 -> 0.3333; """ rescaled_fidelity = (1-new_floor_fidelity)/(1-floor_fidelity) * (fidelity - 1) + 1 # ensure fidelity is within bounds (0, 1) if rescaled_fidelity < 0: rescaled_fidelity = 0.0 if rescaled_fidelity > 1: rescaled_fidelity = 1.0 return rescaled_fidelity def uniform_dist(num_state_qubits): dist = {} for i in range(2**num_state_qubits): key = bin(i)[2:].zfill(num_state_qubits) dist[key] = 1/(2**num_state_qubits) return dist from matplotlib.patches import Rectangle import matplotlib.cm as cm from matplotlib.colors import ListedColormap, LinearSegmentedColormap, Normalize from matplotlib.patches import Circle ############### Color Map functions # Create a selection of colormaps from which to choose; default to custom_spectral cmap_spectral = plt.get_cmap('Spectral') cmap_greys = plt.get_cmap('Greys') cmap_blues = plt.get_cmap('Blues') cmap_custom_spectral = None # the default colormap is the spectral map cmap = cmap_spectral cmap_orig = cmap_spectral # current cmap normalization function (default None) cmap_norm = None default_fade_low_fidelity_level = 0.16 default_fade_rate = 0.7 # Specify a normalization function here (default None) def set_custom_cmap_norm(vmin, vmax): global cmap_norm if vmin == vmax or (vmin == 0.0 and vmax == 1.0): print("... setting cmap norm to None") cmap_norm = None else: print(f"... setting cmap norm to [{vmin}, {vmax}]") cmap_norm = Normalize(vmin=vmin, vmax=vmax) # Remake the custom spectral colormap with user settings def set_custom_cmap_style( fade_low_fidelity_level=default_fade_low_fidelity_level, fade_rate=default_fade_rate): #print("... set custom map style") global cmap, cmap_custom_spectral, cmap_orig cmap_custom_spectral = create_custom_spectral_cmap( fade_low_fidelity_level=fade_low_fidelity_level, fade_rate=fade_rate) cmap = cmap_custom_spectral cmap_orig = cmap_custom_spectral # Create the custom spectral colormap from the base spectral def create_custom_spectral_cmap( fade_low_fidelity_level=default_fade_low_fidelity_level, fade_rate=default_fade_rate): # determine the breakpoint from the fade level num_colors = 100 breakpoint = round(fade_low_fidelity_level * num_colors) # get color list for spectral map spectral_colors = [cmap_spectral(v/num_colors) for v in range(num_colors)] #print(fade_rate) # create a list of colors to replace those below the breakpoint # and fill with "faded" color entries (in reverse) low_colors = [0] * breakpoint #for i in reversed(range(breakpoint)): for i in range(breakpoint): # x is index of low colors, normalized 0 -> 1 x = i / breakpoint # get color at this index bc = spectral_colors[i] r0 = bc[0] g0 = bc[1] b0 = bc[2] z0 = bc[3] r_delta = 0.92 - r0 #print(f"{x} {bc} {r_delta}") # compute saturation and greyness ratio sat_ratio = 1 - x #grey_ratio = 1 - x ''' attempt at a reflective gradient if i >= breakpoint/2: xf = 2*(x - 0.5) yf = pow(xf, 1/fade_rate)/2 grey_ratio = 1 - (yf + 0.5) else: xf = 2*(0.5 - x) yf = pow(xf, 1/fade_rate)/2 grey_ratio = 1 - (0.5 - yf) ''' grey_ratio = 1 - math.pow(x, 1/fade_rate) #print(f" {xf} {yf} ") #print(f" {sat_ratio} {grey_ratio}") r = r0 + r_delta * sat_ratio g_delta = r - g0 b_delta = r - b0 g = g0 + g_delta * grey_ratio b = b0 + b_delta * grey_ratio #print(f"{r} {g} {b}\n") low_colors[i] = (r,g,b,z0) #print(low_colors) # combine the faded low colors with the regular spectral cmap to make a custom version cmap_custom_spectral = ListedColormap(low_colors + spectral_colors[breakpoint:]) #spectral_colors = [cmap_custom_spectral(v/10) for v in range(10)] #for i in range(10): print(spectral_colors[i]) #print("") return cmap_custom_spectral # Make the custom spectral color map the default on module init set_custom_cmap_style() # Arrange the stored annotations optimally and add to plot def anno_volumetric_data(ax, depth_base=2, label='Depth', labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True): # sort all arrays by the x point of the text (anno_offs) global x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos all_annos = sorted(zip(x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos)) x_anno_offs = [a for a,b,c,d,e in all_annos] y_anno_offs = [b for a,b,c,d,e in all_annos] anno_labels = [c for a,b,c,d,e in all_annos] x_annos = [d for a,b,c,d,e in all_annos] y_annos = [e for a,b,c,d,e in all_annos] #print(f"{x_anno_offs}") #print(f"{y_anno_offs}") #print(f"{anno_labels}") for i in range(len(anno_labels)): x_anno = x_annos[i] y_anno = y_annos[i] x_anno_off = x_anno_offs[i] y_anno_off = y_anno_offs[i] label = anno_labels[i] if i > 0: x_delta = abs(x_anno_off - x_anno_offs[i - 1]) y_delta = abs(y_anno_off - y_anno_offs[i - 1]) if y_delta < 0.7 and x_delta < 2: y_anno_off = y_anno_offs[i] = y_anno_offs[i - 1] - 0.6 #x_anno_off = x_anno_offs[i] = x_anno_offs[i - 1] + 0.1 ax.annotate(label, xy=(x_anno+0.0, y_anno+0.1), arrowprops=dict(facecolor='black', shrink=0.0, width=0.5, headwidth=4, headlength=5, edgecolor=(0.8,0.8,0.8)), xytext=(x_anno_off + labelpos[0], y_anno_off + labelpos[1]), rotation=labelrot, horizontalalignment='left', verticalalignment='baseline', color=(0.2,0.2,0.2), clip_on=True) if saveplots == True: plt.savefig("VolumetricPlotSample.jpg") # Plot one group of data for volumetric presentation def plot_volumetric_data(ax, w_data, d_data, f_data, depth_base=2, label='Depth', labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True, w_max=18, do_label=False, do_border=True, x_size=1.0, y_size=1.0, zorder=1, offset_flag=False, max_depth=0, suppress_low_fidelity=False): # since data may come back out of order, save point at max y for annotation i_anno = 0 x_anno = 0 y_anno = 0 # plot data rectangles low_fidelity_count = True last_y = -1 k = 0 # determine y-axis dimension for one pixel to use for offset of bars that start at 0 (_, dy) = get_pixel_dims(ax) # do this loop in reverse to handle the case where earlier cells are overlapped by later cells for i in reversed(range(len(d_data))): x = depth_index(d_data[i], depth_base) y = float(w_data[i]) f = f_data[i] # each time we star a new row, reset the offset counter # DEVNOTE: this is highly specialized for the QA area plots, where there are 8 bars # that represent time starting from 0 secs. We offset by one pixel each and center the group if y != last_y: last_y = y; k = 3 # hardcoded for 8 cells, offset by 3 #print(f"{i = } {x = } {y = }") if max_depth > 0 and d_data[i] > max_depth: #print(f"... excessive depth (2), skipped; w={y} d={d_data[i]}") break; # reject cells with low fidelity if suppress_low_fidelity and f < suppress_low_fidelity_level: if low_fidelity_count: break else: low_fidelity_count = True # the only time this is False is when doing merged gradation plots if do_border == True: # this case is for an array of x_sizes, i.e. each box has different width if isinstance(x_size, list): # draw each of the cells, with no offset if not offset_flag: ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size[i], y_size=y_size, zorder=zorder)) # use an offset for y value, AND account for x and width to draw starting at 0 else: ax.add_patch(box_at((x/2 + x_size[i]/4), y + k*dy, f, type=type, fill=fill, x_size=x+ x_size[i]/2, y_size=y_size, zorder=zorder)) # this case is for only a single cell else: ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size, y_size=y_size)) # save the annotation point with the largest y value if y >= y_anno: x_anno = x y_anno = y i_anno = i # move the next bar down (if using offset) k -= 1 # if no data rectangles plotted, no need for a label if x_anno == 0 or y_anno == 0: return x_annos.append(x_anno) y_annos.append(y_anno) anno_dist = math.sqrt( (y_anno - 1)**2 + (x_anno - 1)**2 ) # adjust radius of annotation circle based on maximum width of apps anno_max = 10 if w_max > 10: anno_max = 14 if w_max > 14: anno_max = 18 scale = anno_max / anno_dist # offset of text from end of arrow if scale > 1: x_anno_off = scale * x_anno - x_anno - 0.5 y_anno_off = scale * y_anno - y_anno else: x_anno_off = 0.7 y_anno_off = 0.5 x_anno_off += x_anno y_anno_off += y_anno # print(f"... {xx} {yy} {anno_dist}") x_anno_offs.append(x_anno_off) y_anno_offs.append(y_anno_off) anno_labels.append(label) if do_label: ax.annotate(label, xy=(x_anno+labelpos[0], y_anno+labelpos[1]), rotation=labelrot, horizontalalignment='left', verticalalignment='bottom', color=(0.2,0.2,0.2)) x_annos = [] y_annos = [] x_anno_offs = [] y_anno_offs = [] anno_labels = [] # init arrays to hold annotation points for label spreading def vplot_anno_init (): global x_annos, y_annos, x_anno_offs, y_anno_offs, anno_labels x_annos = [] y_annos = [] x_anno_offs = [] y_anno_offs = [] anno_labels = [] # Number of ticks on volumetric depth axis max_depth_log = 22 # average transpile factor between base QV depth and our depth based on results from QV notebook QV_transpile_factor = 12.7 # format a number using K,M,B,T for large numbers, optionally rounding to 'digits' decimal places if num > 1 # (sign handling may be incorrect) def format_number(num, digits=0): if isinstance(num, str): num = float(num) num = float('{:.3g}'.format(abs(num))) sign = '' metric = {'T': 1000000000000, 'B': 1000000000, 'M': 1000000, 'K': 1000, '': 1} for index in metric: num_check = num / metric[index] if num_check >= 1: num = round(num_check, digits) sign = index break numstr = f"{str(num)}" if '.' in numstr: numstr = numstr.rstrip('0').rstrip('.') return f"{numstr}{sign}" # Return the color associated with the spcific value, using color map norm def get_color(value): # if there is a normalize function installed, scale the data if cmap_norm: value = float(cmap_norm(value)) if cmap == cmap_spectral: value = 0.05 + value*0.9 elif cmap == cmap_blues: value = 0.00 + value*1.0 else: value = 0.0 + value*0.95 return cmap(value) # Return the x and y equivalent to a single pixel for the given plot axis def get_pixel_dims(ax): # transform 0 -> 1 to pixel dimensions pixdims = ax.transData.transform([(0,1),(1,0)])-ax.transData.transform((0,0)) xpix = pixdims[1][0] ypix = pixdims[0][1] #determine x- and y-axis dimension for one pixel dx = (1 / xpix) dy = (1 / ypix) return (dx, dy) ############### Helper functions # return the base index for a circuit depth value # take the log in the depth base, and add 1 def depth_index(d, depth_base): if depth_base <= 1: return d if d == 0: return 0 return math.log(d, depth_base) + 1 # draw a box at x,y with various attributes def box_at(x, y, value, type=1, fill=True, x_size=1.0, y_size=1.0, alpha=1.0, zorder=1): value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.5,0.5,0.5) return Rectangle((x - (x_size/2), y - (y_size/2)), x_size, y_size, alpha=alpha, edgecolor = ec, facecolor = fc, fill=fill, lw=0.5*y_size, zorder=zorder) # draw a circle at x,y with various attributes def circle_at(x, y, value, type=1, fill=True): size = 1.0 value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.5,0.5,0.5) return Circle((x, y), size/2, alpha = 0.7, # DEVNOTE: changed to 0.7 from 0.5, to handle only one cell edgecolor = ec, facecolor = fc, fill=fill, lw=0.5) def box4_at(x, y, value, type=1, fill=True, alpha=1.0): size = 1.0 value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.3,0.3,0.3) ec = fc return Rectangle((x - size/8, y - size/2), size/4, size, alpha=alpha, edgecolor = ec, facecolor = fc, fill=fill, lw=0.1) # Draw a Quantum Volume rectangle with specified width and depth, and grey-scale value def qv_box_at(x, y, qv_width, qv_depth, value, depth_base): #print(f"{qv_width} {qv_depth} {depth_index(qv_depth, depth_base)}") return Rectangle((x - 0.5, y - 0.5), depth_index(qv_depth, depth_base), qv_width, edgecolor = (value,value,value), facecolor = (value,value,value), fill=True, lw=1) def bkg_box_at(x, y, value=0.9): size = 0.6 return Rectangle((x - size/2, y - size/2), size, size, edgecolor = (.75,.75,.75), facecolor = (value,value,value), fill=True, lw=0.5) def bkg_empty_box_at(x, y): size = 0.6 return Rectangle((x - size/2, y - size/2), size, size, edgecolor = (.75,.75,.75), facecolor = (1.0,1.0,1.0), fill=True, lw=0.5) # Plot the background for the volumetric analysis def plot_volumetric_background(max_qubits=11, QV=32, depth_base=2, suptitle=None, avail_qubits=0, colorbar_label="Avg Result Fidelity"): if suptitle == None: suptitle = f"Volumetric Positioning\nCircuit Dimensions and Fidelity Overlaid on Quantum Volume = {QV}" QV0 = QV qv_estimate = False est_str = "" if QV == 0: # QV = 0 indicates "do not draw QV background or label" QV = 2048 elif QV < 0: # QV < 0 indicates "add est. to label" QV = -QV qv_estimate = True est_str = " (est.)" if avail_qubits > 0 and max_qubits > avail_qubits: max_qubits = avail_qubits max_width = 13 if max_qubits > 11: max_width = 18 if max_qubits > 14: max_width = 20 if max_qubits > 16: max_width = 24 if max_qubits > 24: max_width = 33 #print(f"... {avail_qubits} {max_qubits} {max_width}") plot_width = 6.8 plot_height = 0.5 + plot_width * (max_width / max_depth_log) #print(f"... {plot_width} {plot_height}") # define matplotlib figure and axis; use constrained layout to fit colorbar to right fig, ax = plt.subplots(figsize=(plot_width, plot_height), constrained_layout=True) plt.suptitle(suptitle) plt.xlim(0, max_depth_log) plt.ylim(0, max_width) # circuit depth axis (x axis) xbasis = [x for x in range(1,max_depth_log)] xround = [depth_base**(x-1) for x in xbasis] xlabels = [format_number(x) for x in xround] ax.set_xlabel('Circuit Depth') ax.set_xticks(xbasis) plt.xticks(xbasis, xlabels, color='black', rotation=45, ha='right', va='top', rotation_mode="anchor") # other label options #plt.xticks(xbasis, xlabels, color='black', rotation=-60, ha='left') #plt.xticks(xbasis, xlabels, color='black', rotation=-45, ha='left', va='center', rotation_mode="anchor") # circuit width axis (y axis) ybasis = [y for y in range(1,max_width)] yround = [1,2,3,4,5,6,7,8,10,12,15] # not used now ylabels = [str(y) for y in yround] # not used now #ax.set_ylabel('Circuit Width (Number of Qubits)') ax.set_ylabel('Circuit Width') ax.set_yticks(ybasis) #create simple line plot (not used right now) #ax.plot([0, 10],[0, 10]) log2QV = math.log2(QV) QV_width = log2QV QV_depth = log2QV * QV_transpile_factor # show a quantum volume rectangle of QV = 64 e.g. (6 x 6) if QV0 != 0: ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.87, depth_base)) else: ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.91, depth_base)) # the untranspiled version is commented out - we do not show this by default # also show a quantum volume rectangle un-transpiled # ax.add_patch(qv_box_at(1, 1, QV_width, QV_width, 0.80, depth_base)) # show 2D array of volumetric cells based on this QV_transpiled # DEVNOTE: we use +1 only to make the visuals work; s/b without # Also, the second arg of the min( below seems incorrect, needs correction maxprod = (QV_width + 1) * (QV_depth + 1) for w in range(1, min(max_width, round(QV) + 1)): # don't show VB squares if width greater than known available qubits if avail_qubits != 0 and w > avail_qubits: continue i_success = 0 for d in xround: # polarization factor for low circuit widths maxtest = maxprod / ( 1 - 1 / (2**w) ) # if circuit would fail here, don't draw box if d > maxtest: continue if w * d > maxtest: continue # guess for how to capture how hardware decays with width, not entirely correct # # reduce maxtext by a factor of number of qubits > QV_width # # just an approximation to account for qubit distances # if w > QV_width: # over = w - QV_width # maxtest = maxtest / (1 + (over/QV_width)) # draw a box at this width and depth id = depth_index(d, depth_base) # show vb rectangles; if not showing QV, make all hollow (or less dark) if QV0 == 0: #ax.add_patch(bkg_empty_box_at(id, w)) ax.add_patch(bkg_box_at(id, w, 0.95)) else: ax.add_patch(bkg_box_at(id, w, 0.9)) # save index of last successful depth i_success += 1 # plot empty rectangle after others d = xround[i_success] id = depth_index(d, depth_base) ax.add_patch(bkg_empty_box_at(id, w)) # Add annotation showing quantum volume if QV0 != 0: t = ax.text(max_depth_log - 2.0, 1.5, f"QV{est_str}={QV}", size=12, horizontalalignment='right', verticalalignment='center', color=(0.2,0.2,0.2), bbox=dict(boxstyle="square,pad=0.3", fc=(.9,.9,.9), ec="grey", lw=1)) # add colorbar to right of plot plt.colorbar(cm.ScalarMappable(cmap=cmap), cax=None, ax=ax, shrink=0.6, label=colorbar_label, panchor=(0.0, 0.7)) return ax # Function to calculate circuit depth def calculate_circuit_depth(qc): # Calculate the depth of the circuit depth = qc.depth() return depth def calculate_transpiled_depth(qc,basis_selector): # use either the backend or one of the basis gate sets if basis_selector == 0: qc = transpile(qc, backend) else: basis_gates = basis_gates_array[basis_selector] qc = transpile(qc, basis_gates=basis_gates, seed_transpiler=0) transpiled_depth = qc.depth() return transpiled_depth,qc def plot_fidelity_data(fidelity_data, Hf_fidelity_data, title): avg_fidelity_means = [] avg_Hf_fidelity_means = [] avg_num_qubits_values = list(fidelity_data.keys()) # Calculate the average fidelity and Hamming fidelity for each unique number of qubits for num_qubits in avg_num_qubits_values: avg_fidelity = np.average(fidelity_data[num_qubits]) avg_fidelity_means.append(avg_fidelity) avg_Hf_fidelity = np.mean(Hf_fidelity_data[num_qubits]) avg_Hf_fidelity_means.append(avg_Hf_fidelity) return avg_fidelity_means,avg_Hf_fidelity_means list_of_gates = [] def list_of_standardgates(): import qiskit.circuit.library as lib from qiskit.circuit import Gate import inspect # List all the attributes of the library module gate_list = dir(lib) # Filter out non-gate classes (like functions, variables, etc.) gates = [gate for gate in gate_list if isinstance(getattr(lib, gate), type) and issubclass(getattr(lib, gate), Gate)] # Get method names from QuantumCircuit circuit_methods = inspect.getmembers(QuantumCircuit, inspect.isfunction) method_names = [name for name, _ in circuit_methods] # Map gate class names to method names gate_to_method = {} for gate in gates: gate_class = getattr(lib, gate) class_name = gate_class.__name__.replace('Gate', '').lower() # Normalize class name for method in method_names: if method == class_name or method == class_name.replace('cr', 'c-r'): gate_to_method[gate] = method break # Add common operations that are not strictly gates additional_operations = { 'Measure': 'measure', 'Barrier': 'barrier', } gate_to_method.update(additional_operations) for k,v in gate_to_method.items(): list_of_gates.append(v) def update_counts(gates,custom_gates): operations = {} for key, value in gates.items(): operations[key] = value for key, value in custom_gates.items(): if key in operations: operations[key] += value else: operations[key] = value return operations def get_gate_counts(gates,custom_gate_defs): result = gates.copy() # Iterate over the gate counts in the quantum circuit for gate, count in gates.items(): if gate in custom_gate_defs: custom_gate_ops = custom_gate_defs[gate] # Multiply custom gate operations by the count of the custom gate in the circuit for _ in range(count): result = update_counts(result, custom_gate_ops) # Remove the custom gate entry as we have expanded it del result[gate] return result dict_of_qc = dict() custom_gates_defs = dict() # Function to count operations recursively def count_operations(qc): dict_of_qc.clear() circuit_traverser(qc) operations = dict() operations = dict_of_qc[qc.name] del dict_of_qc[qc.name] # print("operations :",operations) # print("dict_of_qc :",dict_of_qc) for keys in operations.keys(): if keys not in list_of_gates: for k,v in dict_of_qc.items(): if k in operations.keys(): custom_gates_defs[k] = v operations=get_gate_counts(operations,custom_gates_defs) custom_gates_defs.clear() return operations def circuit_traverser(qc): dict_of_qc[qc.name]=dict(qc.count_ops()) for i in qc.data: if str(i.operation.name) not in list_of_gates: qc_1 = i.operation.definition circuit_traverser(qc_1) def get_memory(): import resource usage = resource.getrusage(resource.RUSAGE_SELF) max_mem = usage.ru_maxrss/1024 #in MB return max_mem def analyzer(qc,references,num_qubits): # total circuit name (pauli string + coefficient) total_name = qc.name # pauli string pauli_string = total_name.split()[0] # get the correct measurement if (len(total_name.split()) == 2): correct_dist = references[pauli_string] else: circuit_id = int(total_name.split()[2]) correct_dist = references[f"Qubits - {num_qubits} - {circuit_id}"] return correct_dist,total_name # Max qubits must be 12 since the referenced files only go to 12 qubits MAX_QUBITS = 12 method = 1 def run (min_qubits=min_qubits, max_qubits=max_qubits, skip_qubits=2, max_circuits=max_circuits, num_shots=num_shots): creation_times = [] elapsed_times = [] quantum_times = [] circuit_depths = [] transpiled_depths = [] fidelity_data = {} Hf_fidelity_data = {} numckts = [] mem_usage = [] algorithmic_1Q_gate_counts = [] algorithmic_2Q_gate_counts = [] transpiled_1Q_gate_counts = [] transpiled_2Q_gate_counts = [] print(f"{benchmark_name} Benchmark Program - {platform}") #defining all the standard gates supported by qiskit in a list if gate_counts_plots == True: list_of_standardgates() max_qubits = max(max_qubits, min_qubits) # max must be >= min # validate parameters (smallest circuit is 4 qubits and largest is 10 qubits) max_qubits = min(max_qubits, MAX_QUBITS) min_qubits = min(max(4, min_qubits), max_qubits) if min_qubits % 2 == 1: min_qubits += 1 # min_qubits must be even skip_qubits = max(1, skip_qubits) if method == 2: max_circuits = 1 if max_qubits < 4: print(f"Max number of qubits {max_qubits} is too low to run method {method} of VQE algorithm") return global max_ckts max_ckts = max_circuits global min_qbits,max_qbits,skp_qubits min_qbits = min_qubits max_qbits = max_qubits skp_qubits = skip_qubits print(f"min, max qubits = {min_qubits} {max_qubits}") # Execute Benchmark Program N times for multiple circuit sizes for input_size in range(min_qubits, max_qubits + 1, skip_qubits): # reset random seed np.random.seed(0) # determine the number of circuits to execute for this group num_circuits = min(3, max_circuits) num_qubits = input_size fidelity_data[num_qubits] = [] Hf_fidelity_data[num_qubits] = [] # decides number of electrons na = int(num_qubits/4) nb = int(num_qubits/4) # random seed np.random.seed(0) numckts.append(num_circuits) # create the circuit for given qubit size and simulation parameters, store time metric ts = time.time() # circuit list qc_list = [] # Method 1 (default) if method == 1: # loop over circuits for circuit_id in range(num_circuits): # construct circuit qc_single = VQEEnergy(num_qubits, na, nb, circuit_id, method) qc_single.name = qc_single.name + " " + str(circuit_id) # add to list qc_list.append(qc_single) # method 2 elif method == 2: # construct all circuits qc_list = VQEEnergy(num_qubits, na, nb, 0, method) print(qc_list) print(f"************\nExecuting [{len(qc_list)}] circuits with num_qubits = {num_qubits}") for qc in qc_list: print("*********************************************") #print(f"qc of {qc} qubits for qc_list value: {qc_list}") # get circuit id if method == 1: circuit_id = qc.name.split()[2] else: circuit_id = qc.name.split()[0] #creation time creation_time = time.time() - ts creation_times.append(creation_time) #print(qc) print(f"creation time = {creation_time*1000} ms") # Calculate gate count for the algorithmic circuit (excluding barriers and measurements) if gate_counts_plots == True: operations = count_operations(qc) n1q = 0; n2q = 0 if operations != None: for key, value in operations.items(): if key == "measure": continue if key == "barrier": continue if key.startswith("c") or key.startswith("mc"): n2q += value else: n1q += value print("operations: ",operations) algorithmic_1Q_gate_counts.append(n1q) algorithmic_2Q_gate_counts.append(n2q) # collapse the sub-circuit levels used in this benchmark (for qiskit) qc=qc.decompose() #print(qc) # Calculate circuit depth depth = calculate_circuit_depth(qc) circuit_depths.append(depth) # Calculate transpiled circuit depth transpiled_depth,qc = calculate_transpiled_depth(qc,basis_selector) transpiled_depths.append(transpiled_depth) #print(qc) print(f"Algorithmic Depth = {depth} and Normalized Depth = {transpiled_depth}") if gate_counts_plots == True: # Calculate gate count for the transpiled circuit (excluding barriers and measurements) tr_ops = qc.count_ops() #print("tr_ops = ",tr_ops) tr_n1q = 0; tr_n2q = 0 if tr_ops != None: for key, value in tr_ops.items(): if key == "measure": continue if key == "barrier": continue if key.startswith("c"): tr_n2q += value else: tr_n1q += value transpiled_1Q_gate_counts.append(tr_n1q) transpiled_2Q_gate_counts.append(tr_n2q) print(f"Algorithmic 1Q gates = {n1q} ,Algorithmic 2Q gates = {n2q}") print(f"Normalized 1Q gates = {tr_n1q} ,Normalized 2Q gates = {tr_n2q}") #execution if Type_of_Simulator == "built_in": #To check if Noise is required if Noise_Inclusion == True: noise_model = noise_parameters else: noise_model = None ts = time.time() job = execute(qc, backend, shots=num_shots, noise_model=noise_model) elif Type_of_Simulator == "FAKE" or Type_of_Simulator == "FAKEV2" : ts = time.time() job = backend.run(qc,shots=num_shots, noise_model=noise_parameters) #retrieving the result result = job.result() #print(result) #calculating elapsed time elapsed_time = time.time() - ts elapsed_times.append(elapsed_time) # Calculate quantum processing time quantum_time = result.time_taken quantum_times.append(quantum_time) print(f"Elapsed time = {elapsed_time*1000} ms and Quantum Time = {quantum_time*1000} ms") #counts in result object counts = result.get_counts() # load pre-computed data if len(qc.name.split()) == 2: filename = os.path.join(f'_common/precalculated_data_{num_qubits}_qubit.json') with open(filename) as f: references = json.load(f) else: filename = os.path.join(f'_common/precalculated_data_{num_qubits}_qubit_method2.json') with open(filename) as f: references = json.load(f) #Correct distribution to compare with counts correct_dist,total_name = analyzer(qc,references,num_qubits) #fidelity calculation comparision of counts and correct_dist fidelity_dict = polarization_fidelity(counts, correct_dist) print(fidelity_dict) # modify fidelity based on the coefficient if (len(total_name.split()) == 2): fidelity_dict *= ( abs(float(total_name.split()[1])) / normalization ) fidelity_data[num_qubits].append(fidelity_dict['fidelity']) Hf_fidelity_data[num_qubits].append(fidelity_dict['hf_fidelity']) #maximum memory utilization (if required) if Memory_utilization_plot == True: max_mem = get_memory() print(f"Maximum Memory Utilized: {max_mem} MB") mem_usage.append(max_mem) print("*********************************************") ########## # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") print("\nHartree Fock Generator 'Hf' ="); print(Hf_ if Hf_ != None else " ... too large!") print("\nCluster Operator Example 'Cluster Op' ="); print(CO_ if CO_ != None else " ... too large!") return (creation_times, elapsed_times, quantum_times, circuit_depths, transpiled_depths, fidelity_data, Hf_fidelity_data, numckts , algorithmic_1Q_gate_counts, algorithmic_2Q_gate_counts, transpiled_1Q_gate_counts, transpiled_2Q_gate_counts,mem_usage) # Execute the benchmark program, accumulate metrics, and calculate circuit depths (creation_times, elapsed_times, quantum_times, circuit_depths,transpiled_depths, fidelity_data, Hf_fidelity_data, numckts, algorithmic_1Q_gate_counts, algorithmic_2Q_gate_counts, transpiled_1Q_gate_counts, transpiled_2Q_gate_counts,mem_usage) = run() # Define the range of qubits for the x-axis num_qubits_range = range(min_qbits, max_qbits+1,skp_qubits) print("num_qubits_range =",num_qubits_range) # Calculate average creation time, elapsed time, quantum processing time, and circuit depth for each number of qubits avg_creation_times = [] avg_elapsed_times = [] avg_quantum_times = [] avg_circuit_depths = [] avg_transpiled_depths = [] avg_1Q_algorithmic_gate_counts = [] avg_2Q_algorithmic_gate_counts = [] avg_1Q_Transpiled_gate_counts = [] avg_2Q_Transpiled_gate_counts = [] max_memory = [] start = 0 for num in numckts: avg_creation_times.append(np.mean(creation_times[start:start+num])) avg_elapsed_times.append(np.mean(elapsed_times[start:start+num])) avg_quantum_times.append(np.mean(quantum_times[start:start+num])) avg_circuit_depths.append(np.mean(circuit_depths[start:start+num])) avg_transpiled_depths.append(np.mean(transpiled_depths[start:start+num])) if gate_counts_plots == True: avg_1Q_algorithmic_gate_counts.append(int(np.mean(algorithmic_1Q_gate_counts[start:start+num]))) avg_2Q_algorithmic_gate_counts.append(int(np.mean(algorithmic_2Q_gate_counts[start:start+num]))) avg_1Q_Transpiled_gate_counts.append(int(np.mean(transpiled_1Q_gate_counts[start:start+num]))) avg_2Q_Transpiled_gate_counts.append(int(np.mean(transpiled_2Q_gate_counts[start:start+num]))) if Memory_utilization_plot == True:max_memory.append(np.max(mem_usage[start:start+num])) start += num # Calculate the fidelity data avg_f, avg_Hf = plot_fidelity_data(fidelity_data, Hf_fidelity_data, "Fidelity Comparison") # Plot histograms for average creation time, average elapsed time, average quantum processing time, and average circuit depth versus the number of qubits # Add labels to the bars def autolabel(rects,ax,str='{:.3f}',va='top',text_color="black"): for rect in rects: height = rect.get_height() ax.annotate(str.format(height), # Formatting to two decimal places xy=(rect.get_x() + rect.get_width() / 2, height / 2), xytext=(0, 0), textcoords="offset points", ha='center', va=va,color=text_color,rotation=90) bar_width = 0.3 # Determine the number of subplots and their arrangement if Memory_utilization_plot and gate_counts_plots: fig, (ax1, ax2, ax3, ax4, ax5, ax6, ax7) = plt.subplots(7, 1, figsize=(18, 30)) # Plotting for both memory utilization and gate counts # ax1, ax2, ax3, ax4, ax5, ax6, ax7 are available elif Memory_utilization_plot: fig, (ax1, ax2, ax3, ax6, ax7) = plt.subplots(5, 1, figsize=(18, 30)) # Plotting for memory utilization only # ax1, ax2, ax3, ax6, ax7 are available elif gate_counts_plots: fig, (ax1, ax2, ax3, ax4, ax5, ax6) = plt.subplots(6, 1, figsize=(18, 30)) # Plotting for gate counts only # ax1, ax2, ax3, ax4, ax5, ax6 are available else: fig, (ax1, ax2, ax3, ax6) = plt.subplots(4, 1, figsize=(18, 30)) # Default plotting # ax1, ax2, ax3, ax6 are available fig.suptitle(f"General Benchmarks : {platform} - {benchmark_name}", fontsize=16) for i in range(len(avg_creation_times)): #converting seconds to milli seconds by multiplying 1000 avg_creation_times[i] *= 1000 ax1.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) x = ax1.bar(num_qubits_range, avg_creation_times, color='deepskyblue') autolabel(ax1.patches, ax1) ax1.set_xlabel('Number of Qubits') ax1.set_ylabel('Average Creation Time (ms)') ax1.set_title('Average Creation Time vs Number of Qubits',fontsize=14) ax2.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) for i in range(len(avg_elapsed_times)): #converting seconds to milli seconds by multiplying 1000 avg_elapsed_times[i] *= 1000 for i in range(len(avg_quantum_times)): #converting seconds to milli seconds by multiplying 1000 avg_quantum_times[i] *= 1000 Elapsed= ax2.bar(np.array(num_qubits_range) - bar_width / 2, avg_elapsed_times, width=bar_width, color='cyan', label='Elapsed Time') Quantum= ax2.bar(np.array(num_qubits_range) + bar_width / 2, avg_quantum_times,width=bar_width, color='deepskyblue',label ='Quantum Time') autolabel(Elapsed,ax2,str='{:.1f}') autolabel(Quantum,ax2,str='{:.1f}') ax2.set_xlabel('Number of Qubits') ax2.set_ylabel('Average Time (ms)') ax2.set_title('Average Time vs Number of Qubits') ax2.legend() ax3.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Normalized = ax3.bar(np.array(num_qubits_range) - bar_width / 2, avg_transpiled_depths, color='cyan', label='Normalized Depth', width=bar_width) # Adjust width here Algorithmic = ax3.bar(np.array(num_qubits_range) + bar_width / 2,avg_circuit_depths, color='deepskyblue', label='Algorithmic Depth', width=bar_width) # Adjust width here autolabel(Normalized,ax3,str='{:.2f}') autolabel(Algorithmic,ax3,str='{:.2f}') ax3.set_xlabel('Number of Qubits') ax3.set_ylabel('Average Circuit Depth') ax3.set_title('Average Circuit Depth vs Number of Qubits') ax3.legend() if gate_counts_plots == True: ax4.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Normalized_1Q_counts = ax4.bar(np.array(num_qubits_range) - bar_width / 2, avg_1Q_Transpiled_gate_counts, color='cyan', label='Normalized Gate Counts', width=bar_width) # Adjust width here Algorithmic_1Q_counts = ax4.bar(np.array(num_qubits_range) + bar_width / 2, avg_1Q_algorithmic_gate_counts, color='deepskyblue', label='Algorithmic Gate Counts', width=bar_width) # Adjust width here autolabel(Normalized_1Q_counts,ax4,str='{}') autolabel(Algorithmic_1Q_counts,ax4,str='{}') ax4.set_xlabel('Number of Qubits') ax4.set_ylabel('Average 1-Qubit Gate Counts') ax4.set_title('Average 1-Qubit Gate Counts vs Number of Qubits') ax4.legend() ax5.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Normalized_2Q_counts = ax5.bar(np.array(num_qubits_range) - bar_width / 2, avg_2Q_Transpiled_gate_counts, color='cyan', label='Normalized Gate Counts', width=bar_width) # Adjust width here Algorithmic_2Q_counts = ax5.bar(np.array(num_qubits_range) + bar_width / 2, avg_2Q_algorithmic_gate_counts, color='deepskyblue', label='Algorithmic Gate Counts', width=bar_width) # Adjust width here autolabel(Normalized_2Q_counts,ax5,str='{}') autolabel(Algorithmic_2Q_counts,ax5,str='{}') ax5.set_xlabel('Number of Qubits') ax5.set_ylabel('Average 2-Qubit Gate Counts') ax5.set_title('Average 2-Qubit Gate Counts vs Number of Qubits') ax5.legend() ax6.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Hellinger = ax6.bar(np.array(num_qubits_range) - bar_width / 2, avg_Hf, width=bar_width, label='Hellinger Fidelity',color='cyan') # Adjust width here Normalized = ax6.bar(np.array(num_qubits_range) + bar_width / 2, avg_f, width=bar_width, label='Normalized Fidelity', color='deepskyblue') # Adjust width here autolabel(Hellinger,ax6,str='{:.2f}') autolabel(Normalized,ax6,str='{:.2f}') ax6.set_xlabel('Number of Qubits') ax6.set_ylabel('Average Value') ax6.set_title("Fidelity Comparison") ax6.legend() if Memory_utilization_plot == True: ax7.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) x = ax7.bar(num_qubits_range, max_memory, color='turquoise', width=bar_width, label="Memory Utilizations") autolabel(ax7.patches, ax7) ax7.set_xlabel('Number of Qubits') ax7.set_ylabel('Maximum Memory Utilized (MB)') ax7.set_title('Memory Utilized vs Number of Qubits',fontsize=14) plt.tight_layout(rect=[0, 0, 1, 0.96]) if saveplots == True: plt.savefig("ParameterPlotsSample.jpg") plt.show() # Quantum Volume Plot Suptitle = f"Volumetric Positioning - {platform}" appname=benchmark_name if QV_ == None: QV=2048 else: QV=QV_ depth_base =2 ax = plot_volumetric_background(max_qubits=max_qbits, QV=QV,depth_base=depth_base, suptitle=Suptitle, colorbar_label="Avg Result Fidelity") w_data = num_qubits_range # determine width for circuit w_max = 0 for i in range(len(w_data)): y = float(w_data[i]) w_max = max(w_max, y) d_tr_data = avg_transpiled_depths f_data = avg_f plot_volumetric_data(ax, w_data, d_tr_data, f_data, depth_base, fill=True,label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, w_max=w_max) anno_volumetric_data(ax, depth_base,label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, fill=False)
https://github.com/lockwo/Paper-Review
lockwo
from qiskit.providers.ibmq.runtime import UserMessenger from qiskit import Aer, IBMQ import numpy as np from runtime_test import main import matplotlib.pyplot as plt provider = IBMQ.load_account() provider = IBMQ.get_provider(group='deployed') def interim_result_callback(job_id, interim_result): print(interim_result) import uuid meta = { "name": #"grad_paper-{}".format(uuid.uuid4()), "grad_paper-lima", "description": "A sample gradient program.", "max_execution_time": 10000, } meta["parameters"] = [ {"name": "shots", "description": "Number of shots", "type": "int", "required": True}, {"name": "init_point", "description": "Initial parameters", "type": "ndarray", "required": True}, ] meta['return_values'] = [ {"name": "result", "description": "Final result in list.", "type": "list"} ] meta["interim_results"] = [ {"name": "vals", "description": "Iteration, value at current optimization step", "type": "list"}, ] #backend = provider.backend.ibmq_qasm_simulator backend = provider.backend.ibmq_lima #backend = provider.backend.ibmq_manila options = {'backend_name': backend.name()} program_id = provider.runtime.upload_program(data='runtime_test.py', metadata=meta) initial_point = np.random.uniform(0, 2 * np.pi, 5) inputs = {} inputs['init_point'] = initial_point shots = [10, 100, 1000] fig, (ax1, ax2) = plt.subplots(1, 2) fig.tight_layout() for s in shots: print(s) inputs['shots'] = s job = provider.runtime.run(program_id, options=options, inputs=inputs, callback=interim_result_callback) gd_loss, x_values = job.result() cir_evals = np.array([i for i in range(len(gd_loss))]) cir_evals *= (2 * len(initial_point) * s) ax1.plot(cir_evals, gd_loss, label='Shots %d'%s) ax2.plot(x_values[:,0], x_values[:,1], label='Shots %d'%s) # Make the graph look nice #ax1.axhline(-1, ls='--', c='tab:red', label='Target') ax1.set_ylabel('Cost') ax1.set_xlabel('Circuit Evaluations') ax1.set_xscale('log') ax1.legend() ax2.set_ylim(0, np.pi) ax2.set_xlim(-np.pi/2, np.pi/2) ax2.set_ylabel('Theta 2') ax2.set_xlabel('Theta 1') #ax2.legend() plt.show()
https://github.com/sebasmos/QuantumVE
sebasmos
import os MODEL_METADATA = "XGBoost" model_name = "convnext_base" EXPERIMENT_NAME = f"{model_name}_embeddings" results_path = f"{EXPERIMENT_NAME}/{MODEL_METADATA}" os.makedirs(results_path, exist_ok = True) os.makedirs(EXPERIMENT_NAME, exist_ok = True) train_path = f"{EXPERIMENT_NAME}/train" val_path = f"{EXPERIMENT_NAME}/val" os.makedirs(train_path, exist_ok = True) os.makedirs(val_path, exist_ok=True) import sys sys.path.insert(0,'../') # from __future__ import print_function import argparse import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.optim.lr_scheduler import StepLR from torch.utils.data import random_split from torch.utils.data import Subset, DataLoader, random_split import torch.optim as optim from torch.optim.lr_scheduler import StepLR import matplotlib.pyplot as plt import numpy as np from sklearn.metrics import confusion_matrix, classification_report import pandas as pd import argparse import argparse import datetime import json import numpy as np import os import time from pathlib import Path import torch import torch.backends.cudnn as cudnn from torch.utils.tensorboard import SummaryWriter # import models_vit import sys import os import torch import numpy as np import matplotlib.pyplot as plt from PIL import Image # import models_mae import torch; print(f'numpy version: {np.__version__}\nCUDA version: {torch.version.cuda} - Torch versteion: {torch.__version__} - device count: {torch.cuda.device_count()}') from sklearn.metrics import confusion_matrix, classification_report import seaborn as sns from sklearn.preprocessing import LabelBinarizer from sklearn.metrics import roc_curve, auc import matplotlib.pyplot as plt from itertools import cycle import numpy as np from sklearn.metrics import precision_score, recall_score, f1_score import torch.optim as optim import torch.nn as nn import torch import PIL import pandas as pd import torch import numpy as np import pandas as pd from tqdm import tqdm import os import pandas as pd from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, fbeta_score from sklearn.metrics import precision_score, recall_score, f1_score, fbeta_score import numpy as np from torchvision import datasets, transforms from timm.data import create_transform # from timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD IMAGENET_DEFAULT_MEAN = np.array([0.485, 0.456, 0.406]) IMAGENET_DEFAULT_STD = np.array([0.229, 0.224, 0.225]) def show_image(image, title=''): # image is [H, W, 3] assert image.shape[2] == 3 plt.imshow(torch.clip((image * IMAGENET_DEFAULT_STD + IMAGENET_DEFAULT_MEAN) * 255, 0, 255).int()) plt.title(title, fontsize=16) plt.axis('off') return def plot_multiclass_roc_curve(all_labels, all_predictions, results_path="."): # Step 1: Label Binarization label_binarizer = LabelBinarizer() y_onehot = label_binarizer.fit_transform(all_labels) all_predictions_hot = label_binarizer.transform(all_predictions) # Step 2: Calculate ROC curves fpr = dict() tpr = dict() roc_auc = dict() unique_classes = range(y_onehot.shape[1]) for i in unique_classes: fpr[i], tpr[i], _ = roc_curve(y_onehot[:, i], all_predictions_hot[:, i]) roc_auc[i] = auc(fpr[i], tpr[i]) # Step 3: Plot ROC curves fig, ax = plt.subplots(figsize=(8, 8)) # Micro-average ROC curve fpr_micro, tpr_micro, _ = roc_curve(y_onehot.ravel(), all_predictions_hot.ravel()) roc_auc_micro = auc(fpr_micro, tpr_micro) plt.plot( fpr_micro, tpr_micro, label=f"micro-average ROC curve (AUC = {roc_auc_micro:.2f})", color="deeppink", linestyle=":", linewidth=4, ) # Macro-average ROC curve all_fpr = np.unique(np.concatenate([fpr[i] for i in unique_classes])) mean_tpr = np.zeros_like(all_fpr) for i in unique_classes: mean_tpr += np.interp(all_fpr, fpr[i], tpr[i]) mean_tpr /= len(unique_classes) fpr_macro = all_fpr tpr_macro = mean_tpr roc_auc_macro = auc(fpr_macro, tpr_macro) plt.plot( fpr_macro, tpr_macro, label=f"macro-average ROC curve (AUC = {roc_auc_macro:.2f})", color="navy", linestyle=":", linewidth=4, ) # Individual class ROC curves with unique colors colors = plt.cm.rainbow(np.linspace(0, 1, len(unique_classes))) for class_id, color in zip(unique_classes, colors): plt.plot( fpr[class_id], tpr[class_id], color=color, label=f"ROC curve for Class {class_id} (AUC = {roc_auc[class_id]:.2f})", linewidth=2, ) plt.plot([0, 1], [0, 1], color='gray', linestyle='--', linewidth=2) # Add diagonal line for reference plt.axis("equal") plt.xlabel("False Positive Rate") plt.ylabel("True Positive Rate") plt.title("Extension of Receiver Operating Characteristic\n to One-vs-Rest multiclass") plt.legend() plt.savefig(f'{results_path}/roc_curve.png') plt.show() def build_dataset(is_train, args): transform = build_transform(is_train, args) root = os.path.join(args.data_path, 'train' if is_train else 'val') dataset = datasets.ImageFolder(root, transform=transform) print(dataset) return dataset def build_transform(is_train, args): mean = IMAGENET_DEFAULT_MEAN std = IMAGENET_DEFAULT_STD # train transform if is_train: # this should always dispatch to transforms_imagenet_train transform = create_transform( input_size=args.input_size, is_training=True, color_jitter=args.color_jitter, auto_augment=args.aa, interpolation='bicubic', re_prob=args.reprob, re_mode=args.remode, re_count=args.recount, mean=mean, std=std, ) return transform # eval transform t = [] if args.input_size <= 224: crop_pct = 224 / 256 else: crop_pct = 1.0 size = int(args.input_size / crop_pct) t.append( transforms.Resize(size, interpolation=PIL.Image.BICUBIC), # to maintain same ratio w.r.t. 224 images ) t.append(transforms.CenterCrop(args.input_size)) t.append(transforms.ToTensor()) t.append(transforms.Normalize(mean, std)) return transforms.Compose(t) # Set the seed for PyTorch torch.manual_seed(42) import pandas as pd import xgboost as xgb from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, fbeta_score from sklearn.model_selection import train_test_split # Read embeddings CSV files train_embeddings = pd.read_csv(f'{train_path}/train_embeddings.csv') val_embeddings = pd.read_csv(f'{val_path}/val_embeddings.csv') print("Reading embeddings from:", train_path) # Prepare data for training X_train = train_embeddings.iloc[:, :-1].values # Features y_train = train_embeddings.iloc[:, -1].values # Labels X_val = val_embeddings.iloc[:, :-1].values # Features y_val = val_embeddings.iloc[:, -1].values # Labels # # Split train data for validation # X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.2, random_state=42) # Train XGBoost Classifier xgb_classifier = xgb.XGBClassifier(objective='multi:softmax', num_class=len(set(y_train)), random_state=42) xgb_classifier.fit(X_train, y_train) # Predict on validation data y_pred = xgb_classifier.predict(X_val) # Calculate evaluation metrics accuracy = accuracy_score(y_val, y_pred) precision = precision_score(y_val, y_pred, average='weighted') recall = recall_score(y_val, y_pred, average='weighted') f1 = f1_score(y_val, y_pred, average='weighted') fbeta_75 = fbeta_score(y_val, y_pred, beta=0.75, average='weighted') print("Validation Accuracy:", accuracy) print("Precision:", precision) print("Recall:", recall) print("F1 Score:", f1) print("F0.75 Score:", fbeta_75) unique_classes = np.unique(np.concatenate(((y_pred, y_val)))) confusion_mat = confusion_matrix(y_pred, y_val, labels=unique_classes) conf_matrix = pd.DataFrame(confusion_mat, index=unique_classes, columns=unique_classes) # Plot the confusion matrix using seaborn plt.figure(figsize=(5, 4)) ax = sns.heatmap(conf_matrix, annot=True, fmt='.1f', cmap=sns.cubehelix_palette(as_cmap=True), linewidths=0.1, cbar=True) # Set labels and ticks ax.set_xlabel('Predicted Labels') ax.set_ylabel('True Labels') # Set x and y ticks using the unique classes ax.set_xticks(range(len(unique_classes))) ax.set_yticks(range(len(unique_classes))) # Set x and y ticks at the center of the cells ax.set_xticks([i + 0.5 for i in range(len(unique_classes))]) ax.set_yticks([i + 0.5 for i in range(len(unique_classes))]) plt.show() plot_multiclass_roc_curve(y_pred, y_val, results_path) report = classification_report(y_val,y_pred, target_names=unique_classes,output_dict=True)# Mostrar el informe de df = pd.DataFrame(report).transpose() df.to_csv(os.path.join(results_path, f"confusion_matrix_{MODEL_METADATA}.csv")) print(df) # Calculate precision, recall, and specificity (micro-averaged) precision = precision_score(y_val, y_pred, average='micro') recall = recall_score(y_val, y_pred, average='micro') # Calculate true negatives, false positives, and specificity (micro-averaged) tn = np.sum((y_val != 1) & (y_pred != 1)) fp = np.sum((y_val != 1) & (y_pred == 1)) specificity = tn / (tn + fp) # Calculate F1 score (weighted average) f1 = f1_score(y_val, y_pred, average='weighted') fbeta_75 = fbeta_score(y_val, y_pred, beta=0.75, average='weighted') evaluation_metrics = { "Accuracy": accuracy, "F1 Score": f1, "F0.75 Score": fbeta_75, "Precision": precision, "Recall": recall, "Specificity": specificity } print("Evaluation Metrics:") # for metric, value in evaluation_metrics.items(): # print(f"{metric}: {value}") # Create a DataFrame from the dictionary df = pd.DataFrame(evaluation_metrics, index=[0]) # # Save the DataFrame to a CSV file df.to_csv(f'{results_path}/evaluation_metrics_for_table_{MODEL_METADATA}.csv', index=False) df # from sklearn.model_selection import GridSearchCV # from sklearn.ensemble import RandomForestClassifier # from sklearn.preprocessing import StandardScaler # from sklearn.pipeline import Pipeline # from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, fbeta_score # # Define the parameter grid to search # param_grid = { # 'classifier__n_estimators': [50, 100, 150], # 'classifier__max_depth': [None, 10, 20], # 'classifier__min_samples_split': [2, 5, 10], # 'classifier__min_samples_leaf': [1, 2, 4] # } # # Create a pipeline with normalization and RandomForestClassifier # rf_pipeline = Pipeline([ # ('scaler', StandardScaler()), # ('classifier', RandomForestClassifier(random_state=42)) # ]) # # Create GridSearchCV # grid_search = GridSearchCV(estimator=rf_pipeline, param_grid=param_grid, cv=3, scoring='accuracy') # # Fit the grid search to the data # grid_search.fit(X_train, y_train) # # Get the best parameters and best score # best_params = grid_search.best_params_ # best_score = grid_search.best_score_ # print("Best Parameters:", best_params) # print("Best Score:", best_score) # # Use the best estimator found by GridSearchCV # best_rf_classifier = grid_search.best_estimator_ # # Predict on validation data using the best model # y_pred = best_rf_classifier.predict(X_val) # # Calculate metrics # accuracy = accuracy_score(y_val, y_pred) # precision = precision_score(y_val, y_pred, average='weighted') # recall = recall_score(y_val, y_pred, average='weighted') # f1 = f1_score(y_val, y_pred, average='weighted') # fbeta_75 = fbeta_score(y_val, y_pred, beta=0.75, average='weighted') # print("Validation Accuracy:", accuracy) # print("Precision:", precision) # print("Recall:", recall) # print("F1 Score:", f1) # print("F0.75 Score:", fbeta_75)
https://github.com/qiskit-community/qgss-2024
qiskit-community
# required imports: from qiskit.visualization import array_to_latex from qiskit.quantum_info import Statevector, random_statevector from qiskit.quantum_info.operators import Operator, Pauli from qiskit import QuantumCircuit from qiskit.circuit.library import HGate, CXGate import numpy as np ket0 = [[1],[0]] array_to_latex(ket0) bra0 = [1,0] array_to_latex(bra0) ket1 = # put your answer answer here for |1⟩ bra1 = # put answer here for ⟨1| from qc_grader.challenges.qgss_2023 import grade_lab1_ex1 grade_lab1_ex1([ket1, bra1]) sv_bra0 = Statevector(bra0) sv_bra0 sv_bra0.draw('latex') sv_eq = Statevector([1/2, 3/4, 4/5, 6/8]) sv_eq.draw('latex') sv_eq.is_valid() sv_valid = # create your statevector here from qc_grader.challenges.qgss_2023 import grade_lab1_ex2 grade_lab1_ex2(sv_valid) op_bra0 = Operator(bra0) op_bra0 op_ket0 = Operator(ket0) op_bra0.tensor(op_ket0) braket = np.dot(op_bra0,op_ket0) array_to_latex(braket) ketbra = np.outer(ket0,bra0) array_to_latex(ketbra) braket = np.dot(op_bra0,op_ket0) array_to_latex(braket) bra1ket0 = # put your answer for ⟨1|0⟩ here bra0ket1 = # put your answer for ⟨0|1⟩ here bra1ket1 = # put your answer for ⟨1|1⟩ here ket1bra0 = # put your answer for |1⟩⟨0| here ket0bra1 = # put your answer for |0⟩⟨1| here ket1bra1 = # put your answer for |1⟩⟨1| here from qc_grader.challenges.qgss_2023 import grade_lab1_ex3 grade_lab1_ex3([bra1ket0, bra0ket1, bra1ket1, ket1bra0, ket0bra1, ket1bra1]) # add or remove your answer from this list answer = ['a', 'b', 'c'] from qc_grader.challenges.qgss_2023 import grade_lab1_ex4 grade_lab1_ex4(answer) m1 = Operator([[1,1],[0,0]]) array_to_latex(m1) m3 = Operator([[0,1],[1,0]]) array_to_latex(m3) array_to_latex(m1@ket0) m2 = # create an operator for m2 here m4 = # create and operator for m4 here from qc_grader.challenges.qgss_2023 import grade_lab1_ex5 grade_lab1_ex5([m2, m4]) cnot = CXGate() array_to_latex(cnot) m3.is_unitary() random = Operator(np.array([[ 0.50778085-0.44607116j, -0.1523741 +0.14128434j, 0.44607116+0.50778085j, -0.14128434-0.1523741j ], [ 0.16855994+0.12151822j, 0.55868196+0.38038841j, -0.12151822+0.16855994j, -0.38038841+0.55868196j], [ 0.50778085-0.44607116j, -0.1523741 +0.14128434j, -0.44607116-0.50778085j, 0.14128434+0.1523741j ], [ 0.16855994+0.12151822j, 0.55868196+0.38038841j, 0.12151822-0.16855994j, 0.38038841-0.55868196j]])) random.is_unitary() non_unitary_op = # create your operator here from qc_grader.challenges.qgss_2023 import grade_lab1_ex6 grade_lab1_ex6(non_unitary_op) pauli_x = Pauli('X') array_to_latex(pauli_x) pauli_y = Pauli('Y') array_to_latex(pauli_y) pauli_z = Pauli('Z') array_to_latex(pauli_z) op_x = Operator(pauli_x) op_x op_new = np.dot(op_x,ket0) array_to_latex(op_new) result = # do your operations here from qc_grader.challenges.qgss_2023 import grade_lab1_ex7 grade_lab1_ex7(result) hadamard = HGate() array_to_latex(hadamard) hop = Operator(hadamard) hop.is_unitary() bell = QuantumCircuit(2) bell.h(0) # apply an H gate to the circuit bell.cx(0,1) # apply a CNOT gate to the circuit bell.draw(output="mpl") bell_op = Operator(bell) array_to_latex(bell_op) ghz = QuantumCircuit(3) ############################## # add gates to your circuit here ############################## ghz.draw(output='mpl') from qc_grader.challenges.qgss_2023 import grade_lab1_ex8 grade_lab1_ex8(ghz) plus_state = Statevector.from_label("+") plus_state.draw('latex') plus_state plus_state.probabilities_dict() # run this cell multiple times to show collapsing into one state or the other res = plus_state.measure() res qc = QuantumCircuit(1,1) qc.h(0) qc.measure(0, 0) qc.draw(output="mpl") sv_bell = Statevector([np.sqrt(1/2), 0, 0, np.sqrt(1/2)]) sv_bell.draw('latex') sv_bell.probabilities_dict() sv_psi_plus = # create a statevector for |𝜓+⟩ here prob_psi_plus = # find the measurement probabilities for |𝜓+⟩ here sv_psi_minus = # create a statevector for |𝜓−⟩ here prob_psi_minus = # find the measurement probabilities for |𝜓−⟩ here sv_phi_minus = # create a statevector for |𝜙−⟩ here prob_phi_minus = # find the measurement probabilities for |𝜙−⟩ here from qc_grader.challenges.qgss_2023 import grade_lab1_ex9 grade_lab1_ex9([prob_psi_plus, prob_psi_minus, prob_phi_minus]) qft = QuantumCircuit(2) ############################## # add gates to your circuit here ############################## qft.draw(output='mpl') from qc_grader.challenges.qgss_2023 import grade_lab1_ex10 grade_lab1_ex10(qft) U = Operator(qft) array_to_latex(U)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile from qiskit.visualization import plot_circuit_layout from qiskit.providers.fake_provider import FakeVigo backend = FakeVigo() ghz = QuantumCircuit(3, 3) ghz.h(0) ghz.cx(0,range(1,3)) ghz.barrier() ghz.measure(range(3), range(3)) ghz.draw(output='mpl')
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/The-Singularity-Research/QISKit-Surface-Codes
The-Singularity-Research
from collections import Counter from typing import Tuple, List import numpy as np from networkx import MultiGraph from networkx import nx from sympy.combinatorics import Permutation import matplotlib.pyplot as plt # from SurfaceCodes.utilites import permlist_to_tuple class SurfaceCodeGraph(MultiGraph): def __init__(self, sigma: Tuple[Tuple[int]], alpha: Tuple[Tuple[int]]): super().__init__() self.sigma = sigma # should include singletons corresponding to fixed points self.alpha = alpha # should include singletons corresponding to fixed points f = self.compute_phi() self.phi = self.permlist_to_tuple(f) self.node_info = self.build_node_info() # print dictionary for [sigma, alpha, phi] self.code_graph = nx.MultiGraph() # Create black nodes for each cycle in sigma along with white nodes # representing "half edges" around the black nodes for cycle in self.sigma: self.code_graph.add_node(cycle, bipartite=1) for node in cycle: self.code_graph.add_node(node, bipartite=0) self.code_graph.add_edge(cycle, node) # Create black nodes for each cycle in phi along with white nodes # representing "half edges" around the black nodes for cycle in self.phi: self.code_graph.add_node(cycle, bipartite=1) for node in cycle: self.code_graph.add_edge(cycle, node) # Create nodes for each cycle in alpha then # glue the nodes corresponding to a the pairs for pair in self.alpha: self.code_graph.add_node(pair) self.code_graph = nx.contracted_nodes(self.code_graph, pair[0], pair[1], self_loops=True) # Now contract pair with pair[0] to make sure edges (white nodes) are labeled # by the pairs in alpha to keep track of the gluing from the previous step self.code_graph = nx.contracted_nodes(self.code_graph, pair, pair[0], self_loops=True) def permlist_to_tuple(self, perms): """ convert list of lists to tuple of tuples in order to have two level iterables that are hashable for the dictionaries used later """ return tuple(tuple(perm) for perm in perms) def compute_phi(self): """compute the list of lists full cyclic form of phi (faces of dessin [sigma, alpha, phi])""" s = Permutation(self.sigma) a = Permutation(self.alpha) f = ~(a * s) f = f.full_cyclic_form # prints permutation as a list of lists including all singletons (fixed points) return f def build_node_info(self): count = -1 self.sigma_dict = dict() for count, cycle in enumerate(self.sigma): self.sigma_dict[cycle] = count self.phi_dict = dict() for count, cycle in enumerate(self.phi, start=count + 1): self.phi_dict[cycle] = count self.alpha_dict = dict() for count, pair in enumerate(self.alpha, start=count + 1): self.alpha_dict[pair] = count return tuple([self.sigma_dict, self.alpha_dict, self.phi_dict]) def boundary_1(self, edge): """ compute boundary of a single edge given by a white node (cycle in alpha) """ # if len(self.code_graph.neighbors(edge)) < 2: # boundary1 = [] # else: boundary1 = Counter([x[1] for x in self.code_graph.edges(edge) if x[1] in self.sigma_dict]) odd_boundaries = [x for x in boundary1 if boundary1[x] % 2] # [node for node in self.code_graph.neighbors(edge) if node in self.sigma_dict] return odd_boundaries def del_1(self, edges: List[Tuple[int]]): """ boundary of a list of edges, i.e. an arbitrary 1-chain over Z/2Z """ boundary_list = [self.boundary_1(edge) for edge in edges] a = Counter([y for x in boundary_list for y in x]) boundary_list = [x[0] for x in a.items() if x[1] % 2 == 1] return boundary_list def boundary_2(self, face): """ compute boundary of a single face node """ # boundary2 = [node for node in self.code_graph.neighbors(face) if node in self.alpha_dict] boundary2 = Counter([x[1] for x in self.code_graph.edges(face) if x[1] in self.alpha_dict]) odd_boundaries = [x for x in boundary2 if boundary2[x] % 2] return odd_boundaries def del_2(self, faces: List[Tuple[int]]): """ boundary of a list of faces, i.e. an arbitrary 2-chain over Z/2Z """ boundary_list = [self.boundary_2(face) for face in faces] a = Counter([y for x in boundary_list for y in x]) boundary_list = [x[0] for x in a.items() if x[1] % 2 == 1] return boundary_list def coboundary_1(self, star): """ compute coboundary of a single star """ # coboundary = self.code_graph.neighbors(star) coboundary1 = Counter([x[1] for x in self.code_graph.edges(star)]) odd_coboundaries = [x for x in coboundary1 if coboundary1[x] % 2] return odd_coboundaries def delta_1(self, stars: List[Tuple[int]]): """ coboundary of a list of stars, i.e. an arbitrary 0-cochain over Z/2Z """ coboundary_list = [self.coboundary_1(star) for star in stars] a = Counter([y for x in coboundary_list for y in x]) coboundary_list = [x[0] for x in a.items() if x[1] % 2 == 1] return coboundary_list def coboundary_2(self, edge): """ compute coboundary of a single edge given by a white node (cycle in alpha) """ # coboundary2 = [node for node in self.code_graph.neighbors(edge) if node in self.phi_dict] coboundary2 = Counter([x[1] for x in self.code_graph.edges(edge) if x[1] in self.phi_dict]) odd_coboundaries = [x for x in coboundary2 if coboundary2[x] % 2] return odd_coboundaries def delta_2(self, edges: List[Tuple[int]]): """ coboundary of a list of edges, i.e. an arbitrary 1-cochain over Z/2Z given by a list of cycles in alpha """ coboundary_list = [self.coboundary_2(edge) for edge in edges] a = Counter([y for x in coboundary_list for y in x]) coboundary_list = [x[0] for x in a.items() if x[1] % 2 == 1] return coboundary_list def vertex_basis(self): self.v_basis_dict = dict() self.v_dict = dict() A = np.eye(len(self.sigma), dtype=np.uint8) for count, cycle in enumerate(self.sigma): self.v_dict[cycle] = count self.v_basis_dict[cycle] = A[count, :].T return (self.v_basis_dict) def edge_basis(self): self.e_basis_dict = dict() self.e_dict = dict() B = np.eye(len(self.alpha), dtype=np.uint8) for count, cycle in enumerate(self.alpha): self.e_dict[cycle] = count self.e_basis_dict[cycle] = B[count, :].T return (self.e_basis_dict) def face_basis(self): self.f_basis_dict = dict() self.f_dict = dict() C = np.eye(len(self.phi), dtype=np.uint8) for count, cycle in enumerate(self.phi): self.f_dict[cycle] = count self.f_basis_dict[cycle] = C[count, :].T return (self.f_basis_dict) def d_2(self): self.D2 = np.zeros(len(self.e_dict), dtype=np.uint8) for cycle in self.phi: bd = self.boundary_2(cycle) if bd != []: image = sum([self.e_basis_dict[edge] for edge in bd]) else: image = np.zeros(len(self.e_dict)) self.D2 = np.vstack((self.D2, image)) self.D2 = np.array(self.D2[1:, :]).T return self.D2, self.D2.shape def d_1(self): self.D1 = np.zeros(len(self.v_dict), dtype=np.uint8) for cycle in self.alpha: bd = self.boundary_1(cycle) if bd != []: image = sum([self.v_basis_dict[vertex] for vertex in bd]) else: bd = np.zeros(len(self.e_dict)) self.D1 = np.vstack((self.D1, image)) self.D1 = np.array(self.D1[1:, :]).T return self.D1, self.D1.shape def euler_characteristic(self): """ Compute the Euler characteristic of the surface in which the graph is embedded """ chi = len(self.phi) - len(self.alpha) + len(self.sigma) return (chi) def genus(self): """ Compute the genus of the surface in which the graph is embedded """ g = int(-(len(self.phi) - len(self.alpha) + len(self.sigma) - 2) / 2) return (g) def draw(self, node_type='', layout=''): """ Draw graph with vertices, edges, and faces labeled by colored nodes and their integer indices corresponding to the qubit indices for the surface code """ if node_type not in ['cycles', 'dict']: raise ValueError('node_type can be "cycles" or "dict"') elif layout == 'spring': pos = nx.spring_layout(self.code_graph) elif layout == 'spectral': pos = nx.spectral_layout(self.code_graph) elif layout == 'planar': pos = nx.planar_layout(self.code_graph) elif layout == 'shell': pos = nx.shell_layout(self.code_graph) elif layout == 'circular': pos = nx.circular_layout(self.code_graph) elif layout == 'spiral': pos = nx.spiral_layout(self.code_graph) elif layout == 'random': pos = nx.random_layout(self.code_graph) else: raise ValueError( "no layout defined: try one of these: " + "['spring','spectral','planar','shell','circular','spiral','random']") # white nodes nx.draw_networkx_nodes(self.code_graph, pos, nodelist=list(self.alpha), node_color='c', node_size=500, alpha=0.3) # vertex nodes nx.draw_networkx_nodes(self.code_graph, pos, nodelist=list(self.sigma), node_color='b', node_size=500, alpha=0.6) # face nodes nx.draw_networkx_nodes(self.code_graph, pos, nodelist=list(self.phi), node_color='r', node_size=500, alpha=0.6) # edges nx.draw_networkx_edges(self.code_graph, pos, width=1.0, alpha=0.5) labels = {} if node_type == 'cycles': ''' label nodes the cycles of sigma, alpha, and phi ''' for node in self.alpha_dict: # stuff = self.alpha_dict[node] labels[node] = f'$e$({node})' for node in self.sigma_dict: # something = self.sigma_dict[node] labels[node] = f'$v$({node})' for node in self.phi_dict: # something2 = self.phi_dict[node] labels[node] = f'$f$({node})' nx.draw_networkx_labels(self.code_graph, pos, labels, font_size=12) if node_type == 'dict': ''' label nodes with v, e, f and indices given by node_dict corresponding to qubit indices of surface code ''' for node in self.alpha_dict: # stuff = self.alpha_dict[node] labels[node] = f'$e$({self.alpha_dict[node]})' for node in self.sigma_dict: # something = self.sigma_dict[node] labels[node] = f'$v$({self.sigma_dict[node]})' for node in self.phi_dict: # something2 = self.phi_dict[node] labels[node] = f'$f$({self.phi_dict[node]})' nx.draw_networkx_labels(self.code_graph, pos, labels, font_size=12) # plt.axis('off') # plt.savefig("labels_and_colors.png") # save as png plt.show() # display sigma = ((0,1,2), (3,4,5), (6,7,8,9)) alpha = ((0,3),(1,4),(2,6),(5,7),(8,9)) SCG = SurfaceCodeGraph(sigma, alpha) SCG.draw('dict', layout = 'spring') SCG.draw('cycles', layout = 'spring') SCG.node_info SCG.genus() SCG.face_basis() SCG.vertex_basis() SCG.edge_basis() SCG.del_1([(0,3)]) SCG.boundary_1((0,3)) SCG.del_1([(1,4)]) SCG.boundary_1((1,4)) SCG.del_1([(2,6)]) SCG.boundary_1((2,6)) SCG.del_1([(5,7)]) SCG.boundary_1((5,7)) SCG.del_1([(8,9)]) SCG.boundary_1((8,9)) SCG.d_1() SCG.d_2() SCG.D1 SCG.D2 def rowSwap(A, i, j): temp = np.copy(A[i, :]) A[i, :] = A[j, :] A[j, :] = temp def colSwap(A, i, j): temp = np.copy(A[:, i]) A[:, i] = A[:, j] A[:, j] = temp def scaleCol(A, i, c): A[:, i] *= int(c) * np.ones(A.shape[0], dtype=np.int64) def scaleRow(A, i, c): A[i, :] = np.array(A[i, :], dtype=np.float64) * c * np.ones(A.shape[1], dtype=np.float64) def colCombine(A, addTo, scaleCol, scaleAmt): A[:, addTo] += scaleAmt * A[:, scaleCol] def rowCombine(A, addTo, scaleRow, scaleAmt): A[addTo, :] += scaleAmt * A[scaleRow, :] def simultaneousReduce(A, B): if A.shape[1] != B.shape[0]: raise Exception("Matrices have the wrong shape.") numRows, numCols = A.shape i, j = 0, 0 while True: if i >= numRows or j >= numCols: break if A[i, j] == 0: nonzeroCol = j while nonzeroCol < numCols and A[i, nonzeroCol] == 0: nonzeroCol += 1 if nonzeroCol == numCols: i += 1 continue colSwap(A, j, nonzeroCol) rowSwap(B, j, nonzeroCol) pivot = A[i, j] scaleCol(A, j, 1.0 / pivot) scaleRow(B, j, 1.0 / pivot) for otherCol in range(0, numCols): if otherCol == j: continue if A[i, otherCol] != 0: scaleAmt = -A[i, otherCol] colCombine(A, otherCol, j, scaleAmt) rowCombine(B, j, otherCol, -scaleAmt) i += 1; j += 1 return A%2, B%2 def finishRowReducing(B): numRows, numCols = B.shape i, j = 0, 0 while True: if i >= numRows or j >= numCols: break if B[i, j] == 0: nonzeroRow = i while nonzeroRow < numRows and B[nonzeroRow, j] == 0: nonzeroRow += 1 if nonzeroRow == numRows: j += 1 continue rowSwap(B, i, nonzeroRow) pivot = B[i, j] scaleRow(B, i, 1.0 / pivot) for otherRow in range(0, numRows): if otherRow == i: continue if B[otherRow, j] != 0: scaleAmt = -B[otherRow, j] rowCombine(B, otherRow, i, scaleAmt) i += 1; j += 1 return B%2 def numPivotCols(A): z = np.zeros(A.shape[0]) return [np.all(A[:, j] == z) for j in range(A.shape[1])].count(False) def numPivotRows(A): z = np.zeros(A.shape[1]) return [np.all(A[i, :] == z) for i in range(A.shape[0])].count(False) def bettiNumber(d_k, d_kplus1): A, B = np.copy(d_k), np.copy(d_kplus1) simultaneousReduce(A, B) finishRowReducing(B) dimKChains = A.shape[1] print("dim 1-chains:",dimKChains) kernelDim = dimKChains - numPivotCols(A) print("dim ker d_1:",kernelDim) imageDim = numPivotRows(B) print("dim im d_2:",imageDim) return "dim homology:",kernelDim - imageDim simultaneousReduce(SCG.D1.astype('float64'), SCG.D2.astype('float64')) finishRowReducing(SCG.D2.astype('float64')) numPivotCols(SCG.D2.astype('float64')) numPivotRows(SCG.D2.astype('float64')) bettiNumber(SCG.D1.astype('float64'), SCG.D2.astype('float64'))
https://github.com/pkaran57/quantum-computing-final-project
pkaran57
import logging from qiskit import Aer from qiskit.aqua import QuantumInstance from qiskit.aqua.algorithms import Shor logging.basicConfig(format="'%(asctime)s' %(name)s %(message)s'", level=logging.INFO) logger = logging.getLogger('main') # provider = IBMQ.load_account() # device = provider.get_backend('ibmq_qasm_simulator') device = Aer.get_backend('qasm_simulator') number_to_factorize = 15 shor = Shor(number_to_factorize) quantum_instance = QuantumInstance(device) result = shor.run(quantum_instance) print("The list of factors of {} as computed by Shor is {}.".format(number_to_factorize, result['factors'][0]))
https://github.com/rubenandrebarreiro/summer-school-on-quantum-computing-software-for-near-term-quantum-devices-2020
rubenandrebarreiro
# useful additional packages import matplotlib.pyplot as plt import matplotlib.axes as axes import numpy as np import networkx as nx from qiskit import Aer, execute, QuantumCircuit from qiskit.quantum_info import Statevector # auxilliary function to plot graphs def plot_result(G, x): colors = ['r' if x[i] == 0 else 'b' for i in range(n)] pos, default_axes = nx.spring_layout(G), plt.axes(frameon=True) nx.draw_networkx(G, node_color=colors, node_size=600, alpha=.8, pos=pos) # create graph G = nx.Graph() # add nodes n = 5 G.add_nodes_from(range(n)) # add edges: tuple is (i,j,weight) where (i,j) is the edge edges = [(0, 1, 1.0), (0, 2, 1.0), (0, 3, 1.0), (1, 2, 1.0), (2, 3, 1.0), (2, 4, 1.0), (3, 4, 1.0)] G.add_weighted_edges_from(edges) # plot graph plot_result(G, [0]*n) from docplex.mp.model import Model mdl = Model('MaxCut') x = mdl.binary_var_list('x{}'.format(i) for i in range(n)) objective = mdl.sum([ w * (x[i] + x[j] - 2*x[i]*x[j]) for (i, j, w) in edges]) mdl.maximize(objective) mdl.prettyprint() b = 2 mdl.add_constraint(mdl.sum(x) == b) mdl.prettyprint() conda install -c ibmdecisionoptimization cplex from qiskit.optimization import QuadraticProgram from qiskit.optimization.algorithms import CplexOptimizer # convert from DOcplex model to Qiskit Quadratic Program qp = QuadraticProgram() qp.from_docplex(mdl) # Solve Quadratic Program using CPLEX cplex = CplexOptimizer() result = cplex.solve(qp) print(result) plot_result(G, result.x) from qiskit.optimization.converters import ( InequalityToEquality, # converts inequality constraints to equality constraints by adding slack variables LinearEqualityToPenalty, # converts linear equality constraints to quadratic penalty terms IntegerToBinary, # converts integer variables to binary variables QuadraticProgramToQubo # combines the previous three converters ) lineq2penalty = LinearEqualityToPenalty(penalty=1) qp_wo_constr = lineq2penalty.convert(qp) qp_wo_constr # Solve converted Quadratic Program using CPLEX result = cplex.solve(qp_wo_constr) print(result) plot_result(G, result.x) H, offset = qp_wo_constr.to_ising() print('offset =', offset) print() print('H =', H) # print Ising Hamiltonian as matrix H_matrix = np.real(H.to_matrix()) print('dim(H):', H_matrix.shape) print(H_matrix) # plot diagonal of matrix opt_indices = list(np.where(H_matrix.diagonal() == min(H_matrix.diagonal())))[0] plt.figure(figsize=(12, 5)) plt.bar(range(2**n), H_matrix.diagonal()) plt.bar(opt_indices, H_matrix.diagonal()[opt_indices], color='g') plt.xticks(range(2**n), ['('+str(i)+') {0:05b}'.format(i) for i in range(2**n)], rotation=90, fontsize=14) plt.yticks(fontsize=14) plt.show() from qiskit.circuit.library import RealAmplitudes qc = RealAmplitudes(5, reps=1) qc.draw(fold=120) # run VQE from qiskit.aqua.algorithms import VQE vqe = VQE(H, qc, quantum_instance=Aer.get_backend('statevector_simulator')) result = vqe.run() print('optimal value:', np.round(result.eigenvalue, decimals=4)) # plot probabilities probabilities = np.abs(result.eigenstate)**2 plt.figure(figsize=(12, 5)) plt.bar(range(2**n), probabilities) plt.bar(opt_indices, probabilities[opt_indices], color='g') plt.xticks(range(2**n), ['('+str(i)+') {0:05b}'.format(i) for i in range(2**n)], rotation=90, fontsize=14) plt.yticks(fontsize=14) plt.show() from qiskit.circuit import Parameter gamma, beta = Parameter('gamma'), Parameter('beta') qc = QuantumCircuit(1) qc.h(0) qc.barrier() qc.rz(gamma, 0) qc.rx(beta, 0) qc.barrier() qc.draw() def construct_schedule(T, N): delta_t = T/N gammas, betas = [], [] # H_C, H_X parameters for i in range(N+1): t = i * delta_t gammas += [ 2 * delta_t * t/T ] # H_C betas += [ -2 * delta_t * (1 - t/T) ] # H_X return gammas, betas T = 5 N = 10 gammas, betas = construct_schedule(T, N) plt.figure(figsize=(10, 4)) plt.plot(np.linspace(0, T, N+1), gammas, label='gammas') plt.plot(np.linspace(0, T, N+1), betas, label='betas') plt.legend(fontsize=14) plt.xticks(fontsize=14) plt.xlabel('time', fontsize=14) plt.yticks(fontsize=14) plt.ylabel('parameters', fontsize=14); # track probabilities during trotterized annealing probabilities = np.zeros((2, N+1)) # construct circuit qc = QuantumCircuit(1) qc.h(0) qc.barrier() for i, (gamma, beta) in enumerate(zip(gammas, betas)): qc.rz(gamma, 0) qc.rx(beta, 0) qc.barrier() probabilities[:, i] = Statevector.from_instruction(qc).probabilities() qc.draw() plt.figure(figsize=(12, 7)) plt.plot(np.linspace(0, T, N+1), probabilities[1, :], 'gd-', label=r'$|1\rangle$') plt.plot(np.linspace(0, T, N+1), probabilities[0, :], 'bo-', label=r'$|0\rangle$') plt.legend(fontsize=14) plt.xticks(fontsize=14) plt.xlabel('time $t$', fontsize=14) plt.yticks(fontsize=14) plt.ylabel('probabilities', fontsize=14); plt.figure(figsize=(12, 7)) plt.plot(np.linspace(0, T, N+1), probabilities[0, :] - probabilities[1, :], 'gd-') plt.xticks(fontsize=14) plt.xlabel('time $t$', fontsize=14) plt.yticks(fontsize=14) plt.ylabel('objective value', fontsize=14); gamma = Parameter('gamma') qc1 = QuantumCircuit(2) qc1.cx(0, 1) qc1.rz(gamma, 1) qc1.cx(0, 1) qc1.draw() qc2 = QuantumCircuit(2) qc2.rzz(gamma, 0, 1) qc2.draw() from qiskit.aqua.algorithms.minimum_eigen_solvers.qaoa.var_form import QAOAVarForm # construct parameters from annealing schedule T = 10 N = 20 gammas, betas = construct_schedule(T, N) # construct variational form var_form = QAOAVarForm(H, N+1) # evaluate circuit qc = var_form.construct_circuit(gammas + betas) sv = Statevector.from_instruction(qc) # plot probabilities probabilities = sv.probabilities() plt.figure(figsize=(12, 5)) plt.bar(range(2**n), probabilities) plt.bar(opt_indices, probabilities[opt_indices], color='g') plt.xticks(range(2**n), ['('+str(i)+') {0:05b}'.format(i) for i in range(2**n)], rotation=90, fontsize=14) plt.yticks(fontsize=14); # draw trotterized annealing circuit for MaxCut qc.draw() from qiskit.aqua.components.optimizers import COBYLA # QAOA circuit for p = 1 gamma, beta = Parameter('gamma'), Parameter('beta') qc = QuantumCircuit(1) qc.h(0) qc.rz(gamma, 0) qc.rx(beta, 0) def objective(params): qc_ = qc.bind_parameters({gamma: params[0], beta: params[1]}) probs = Statevector.from_instruction(qc_).probabilities() return probs @ [1, -1] optimizer = COBYLA() result = optimizer.optimize(num_vars=2, objective_function=objective, initial_point=[0.5, 0.5]) print('optimal params:', np.round(result[0], decimals=4)) print('optimal value: ', np.round(result[1], decimals=4)) print('optimal state: ', np.round(Statevector.from_instruction(qc.bind_parameters( {gamma: result[0][0], beta: result[0][1]})).data, decimals=4)) # illustrating the QAOA var form p = 1 var_form = QAOAVarForm(H, p) var_form.construct_circuit([gamma, beta]).draw() from qiskit.aqua.algorithms import QAOA qaoa_mes = QAOA(H, p=1, optimizer=optimizer, quantum_instance=Aer.get_backend('statevector_simulator')) result = qaoa_mes.run() print('optimal params: ', result.optimal_parameters) print('optimal value: ', result.optimal_value) print('optimal probability: ', sum(np.abs(result.eigenstate[opt_indices])**2)) # plot probabilities probabilities = np.abs(result['eigenstate'])**2 plt.figure(figsize=(12, 5)) plt.bar(range(2**n), probabilities) plt.bar(opt_indices, probabilities[opt_indices], color='g') plt.xticks(range(2**n), ['('+str(i)+') {0:05b}'.format(i) for i in range(2**n)], rotation=90, fontsize=14) plt.yticks(fontsize=14) plt.show() from qiskit.optimization.algorithms import MinimumEigenOptimizer # construct QAOA as Minimum Eigensolver qaoa_mes = QAOA(p=1, optimizer=optimizer, quantum_instance=Aer.get_backend('statevector_simulator')) # construct Minimum Eigen Optimizer based on QAOA qaoa = MinimumEigenOptimizer(qaoa_mes) # solve Quadratic Program result = qaoa.solve(qp) print(result) plot_result(G, result.x) # converts two's complement bit string to corresponding integer def twos_complement(val, num_bits): val = int(val, 2) if (val & (1 << (num_bits - 1))) != 0: val = val - (1 << num_bits) return val print(twos_complement('0011', 4)) print(twos_complement('1011', 4)) from qiskit.circuit.library import QFT def encode(num_qubits, k): qc = QuantumCircuit(num_qubits, name='enc({})'.format(k)) for i in range(num_qubits): theta = 2*np.pi * 2**i / 2**num_qubits * k qc.rz(theta, i) return qc num_value_qubits = 4 qc = QuantumCircuit(num_value_qubits, num_value_qubits) qc.h(range(num_value_qubits)) qc.barrier() qc.append(encode(num_value_qubits, 2), range(num_value_qubits)) qc.barrier() qc.append(QFT(num_value_qubits, do_swaps=False).inverse(), qc.qubits) qc.measure(qc.qregs[0], qc.cregs[0][::-1]) qc.draw(fold=120) num_value_qubits = 4 qc = QuantumCircuit(num_value_qubits, num_value_qubits) qc.h(range(num_value_qubits)) qc.barrier() qc.extend(encode(num_value_qubits, 2)) # qc.extend(encode(num_value_qubits, -3)) # qc.extend(encode(num_value_qubits, 4)) qc.barrier() qc.append(QFT(num_value_qubits, do_swaps=False, inverse=True), qc.qubits) qc.measure(qc.qregs[0], qc.cregs[0][::-1]) qc.draw(fold=120) counts = execute(qc, Aer.get_backend('qasm_simulator')).result().get_counts() for key in counts: print(key, ' -->', twos_complement(key, num_value_qubits)) num_input_qubits = 3 num_total_qubits = num_input_qubits + num_value_qubits qc = QuantumCircuit(num_total_qubits) qc.h([0, 1, 2]) qc.barrier() qc.h(range(num_input_qubits, num_total_qubits)) qc.append(encode(num_value_qubits, 2).control(2), [0, 2] + list(range(num_input_qubits, num_total_qubits))) qc.append(encode(num_value_qubits, -3).control(), [1] + list(range(num_input_qubits, num_total_qubits))) qc.append(encode(num_value_qubits, 4).control(), [2] + list(range(num_input_qubits, num_total_qubits))) qc.append(QFT(num_value_qubits, do_swaps=False).inverse(), range(num_input_qubits, num_total_qubits)) qc.measure_all() qc.draw(fold=120) counts = execute(qc, Aer.get_backend('qasm_simulator')).result().get_counts() for key, value in counts.items(): x = key[num_value_qubits:] y_bin = key[:num_value_qubits][::-1] y_int = twos_complement(y_bin, num_value_qubits) print(x, '-->', y_bin, '-->', y_int, '\t(counts: {})'.format(value)) from qiskit.circuit.library import QuadraticForm # get quadratic / linear / constant part of quadratic program A = qp_wo_constr.objective.quadratic.to_array() b = qp_wo_constr.objective.linear.to_array() c = qp_wo_constr.objective.constant # set number of results qubits num_value_qubits = 5 # construct circuit to evaluate quadratic form qf = QuadraticForm(num_value_qubits, A, b, c) qf.draw(fold=115) qc = QuantumCircuit(n + num_value_qubits) qc.h(range(n)) qc.append(qf, range(n + num_value_qubits)) qc.measure_all() qc.draw() counts = execute(qc, backend=Aer.get_backend('qasm_simulator')).result().get_counts() for key, value in counts.items(): x_ = key[num_value_qubits:] x = [0 if x__ == '0' else 1 for x__ in x_][::-1] y_bin = key[:num_value_qubits] y_int = twos_complement(y_bin, num_value_qubits) qx = qp_wo_constr.objective.evaluate(x) print('x =', x_, '\ty_bin =', y_bin, '\ty_int =', y_int, '\tQ(x) =', qx, '\t(counts: {})'.format(value)) qc = QuantumCircuit(n + num_value_qubits, name='U_f') qc.append(qf, range(n + num_value_qubits)) # 1. compute Q(x) qc.z(qc.qubits[-1]) # 2. multiply all |x>|Q(x)> by -1 where Q(x) < 0. qc.append(qf.inverse(), range(n + num_value_qubits)) # 3. uncompute Q(x). qc.draw() qc_grover = QuantumCircuit(n + num_value_qubits) qc_grover.h(range(n)) qc_grover.append(qc, range(qc_grover.num_qubits)) qc_grover.draw() data = Statevector.from_instruction(qc_grover).data x = ['{0:05b}'.format(i) for i in range(2**n)] y = [qp_wo_constr.objective.evaluate([0 if x__ == '0' else 1 for x__ in reversed(x_)]) for x_ in x] plt.figure(figsize=(12, 5)) plt.bar(range(2**n), np.real(data[:2**n])) plt.xticks(range(2**n), ['{} $\leftarrow$ '.format(y[i]) + '{0:05b}'.format(i) for i in range(2**n)], rotation=90, fontsize=14) plt.yticks(fontsize=14) plt.show() reflection = QuantumCircuit(n, name='reflection') reflection.h(range(reflection.num_qubits)) reflection.barrier() reflection.x(range(reflection.num_qubits)) reflection.barrier() reflection.h(-1) reflection.mct(list(range(reflection.num_qubits - 1)), -1) reflection.h(-1) reflection.barrier() reflection.x(range(reflection.num_qubits)) reflection.barrier() reflection.h(range(reflection.num_qubits)) reflection.draw() qc_grover.append(reflection, range(n)) qc_grover.draw() data = Statevector.from_instruction(qc_grover).data x = ['{0:05b}'.format(i) for i in range(2**n)] y = [qp_wo_constr.objective.evaluate([0 if x__ == '0' else 1 for x__ in reversed(x_)]) for x_ in x] plt.figure(figsize=(12, 5)) plt.bar(range(2**n), -np.real(data[:2**n])) # multiply by -1, since reflection is implemented up to global phase -1 plt.xticks(range(2**n), ['{} $\leftarrow$ '.format(y[i]) + '{0:05b}'.format(i) for i in range(2**n)], rotation=90, fontsize=14) plt.yticks(fontsize=14) plt.show() from qiskit.optimization.algorithms import GroverOptimizer # set up Grover Optimizer grover = GroverOptimizer(num_value_qubits=5, quantum_instance=Aer.get_backend('statevector_simulator')) grover._qubo_converter.penalty = 1 # set to small value to reduce required number of value qubits # solver problem result = grover.solve(qp) print(result) plot_result(G, result.x) from qiskit.finance.applications.ising import portfolio # define tickers and number of assets n = 6 # set budget budget = n // 2 # sample expected returns and covariance matrix mu, sigma = portfolio.random_model(n, seed=4321) # plot mu/sigma plt.figure(figsize=(12, 5)) plt.subplot(1,2,1) plt.title('Expected Returns', fontsize=14) plt.bar(range(n), mu) plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.subplot(1,2,2) plt.title('Covariance Matrix', fontsize=14) plt.imshow(sigma, interpolation='nearest') plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.show() def get_qp(n, mu, sigma, budget, q): # create model with docplex mdl = Model('portfolio_optimization') # define variables: # # x_i in {0, 1} # x = mdl.binary_var_list(['x{}'.format(i) for i in range(n)]) # set objective function: # # maximize { mu^T * x - q * x^T * sigma * x } # objective = mdl.sum([mu[i] * x[i] for i in range(n)]) # mu^T * x objective -= q * mdl.sum([sigma[i][j]*x[i]*x[j] for i in range(n) for j in range(n)]) mdl.maximize(objective) # add budget constraint: # # 1^T * x == budget # cost = mdl.sum([x[i] for i in range(n)]) mdl.add_constraint(cost == budget, ctname='budget') # convert to quadratic program qp = QuadraticProgram() qp.from_docplex(mdl) return qp # track resulting risk and return mus = [] sigmas = [] # screen different risk factors for q in [0, 1, 10]: # solve the portfolio optimization problem using QAOA qp = get_qp(n, mu, sigma, budget, q) result = qaoa.solve(qp) # track risk and return mus += [portfolio.portfolio_expected_value(result.x, mu)] sigmas += [portfolio.portfolio_variance(result.x, sigma)] # print resulting portfolio print(result.x) # plot risk/return efficient frontier plt.figure(figsize=(8, 5)) plt.plot(sigmas, mus, '--', linewidth=2) plt.plot(sigmas, mus, 'rD', markersize=7) plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.xlabel('Risk (Variance)', fontsize=14) plt.ylabel('Return', fontsize=14) plt.title('Efficient Frontier', fontsize=14) plt.show()
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=missing-docstring import math from qiskit.circuit.library import ( RZGate, SXGate, XGate, CXGate, RYGate, RXGate, RXXGate, RGate, IGate, ECRGate, UGate, CCXGate, RZXGate, CZGate, ) from qiskit.circuit import IfElseOp, ForLoopOp, WhileLoopOp, SwitchCaseOp from qiskit.circuit.measure import Measure from qiskit.circuit.parameter import Parameter from qiskit import pulse from qiskit.pulse.instruction_schedule_map import InstructionScheduleMap from qiskit.pulse.calibration_entries import CalibrationPublisher, ScheduleDef from qiskit.transpiler.coupling import CouplingMap from qiskit.transpiler.instruction_durations import InstructionDurations from qiskit.transpiler.timing_constraints import TimingConstraints from qiskit.transpiler.exceptions import TranspilerError from qiskit.transpiler import Target from qiskit.transpiler import InstructionProperties from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider import ( FakeBackendV2, FakeMumbaiFractionalCX, FakeVigo, FakeNairobi, FakeGeneva, ) class TestTarget(QiskitTestCase): def setUp(self): super().setUp() self.fake_backend = FakeBackendV2() self.fake_backend_target = self.fake_backend.target self.theta = Parameter("theta") self.phi = Parameter("phi") self.ibm_target = Target() i_props = { (0,): InstructionProperties(duration=35.5e-9, error=0.000413), (1,): InstructionProperties(duration=35.5e-9, error=0.000502), (2,): InstructionProperties(duration=35.5e-9, error=0.0004003), (3,): InstructionProperties(duration=35.5e-9, error=0.000614), (4,): InstructionProperties(duration=35.5e-9, error=0.006149), } self.ibm_target.add_instruction(IGate(), i_props) rz_props = { (0,): InstructionProperties(duration=0, error=0), (1,): InstructionProperties(duration=0, error=0), (2,): InstructionProperties(duration=0, error=0), (3,): InstructionProperties(duration=0, error=0), (4,): InstructionProperties(duration=0, error=0), } self.ibm_target.add_instruction(RZGate(self.theta), rz_props) sx_props = { (0,): InstructionProperties(duration=35.5e-9, error=0.000413), (1,): InstructionProperties(duration=35.5e-9, error=0.000502), (2,): InstructionProperties(duration=35.5e-9, error=0.0004003), (3,): InstructionProperties(duration=35.5e-9, error=0.000614), (4,): InstructionProperties(duration=35.5e-9, error=0.006149), } self.ibm_target.add_instruction(SXGate(), sx_props) x_props = { (0,): InstructionProperties(duration=35.5e-9, error=0.000413), (1,): InstructionProperties(duration=35.5e-9, error=0.000502), (2,): InstructionProperties(duration=35.5e-9, error=0.0004003), (3,): InstructionProperties(duration=35.5e-9, error=0.000614), (4,): InstructionProperties(duration=35.5e-9, error=0.006149), } self.ibm_target.add_instruction(XGate(), x_props) cx_props = { (3, 4): InstructionProperties(duration=270.22e-9, error=0.00713), (4, 3): InstructionProperties(duration=305.77e-9, error=0.00713), (3, 1): InstructionProperties(duration=462.22e-9, error=0.00929), (1, 3): InstructionProperties(duration=497.77e-9, error=0.00929), (1, 2): InstructionProperties(duration=227.55e-9, error=0.00659), (2, 1): InstructionProperties(duration=263.11e-9, error=0.00659), (0, 1): InstructionProperties(duration=519.11e-9, error=0.01201), (1, 0): InstructionProperties(duration=554.66e-9, error=0.01201), } self.ibm_target.add_instruction(CXGate(), cx_props) measure_props = { (0,): InstructionProperties(duration=5.813e-6, error=0.0751), (1,): InstructionProperties(duration=5.813e-6, error=0.0225), (2,): InstructionProperties(duration=5.813e-6, error=0.0146), (3,): InstructionProperties(duration=5.813e-6, error=0.0215), (4,): InstructionProperties(duration=5.813e-6, error=0.0333), } self.ibm_target.add_instruction(Measure(), measure_props) self.aqt_target = Target(description="AQT Target") rx_props = { (0,): None, (1,): None, (2,): None, (3,): None, (4,): None, } self.aqt_target.add_instruction(RXGate(self.theta), rx_props) ry_props = { (0,): None, (1,): None, (2,): None, (3,): None, (4,): None, } self.aqt_target.add_instruction(RYGate(self.theta), ry_props) rz_props = { (0,): None, (1,): None, (2,): None, (3,): None, (4,): None, } self.aqt_target.add_instruction(RZGate(self.theta), rz_props) r_props = { (0,): None, (1,): None, (2,): None, (3,): None, (4,): None, } self.aqt_target.add_instruction(RGate(self.theta, self.phi), r_props) rxx_props = { (0, 1): None, (0, 2): None, (0, 3): None, (0, 4): None, (1, 0): None, (2, 0): None, (3, 0): None, (4, 0): None, (1, 2): None, (1, 3): None, (1, 4): None, (2, 1): None, (3, 1): None, (4, 1): None, (2, 3): None, (2, 4): None, (3, 2): None, (4, 2): None, (3, 4): None, (4, 3): None, } self.aqt_target.add_instruction(RXXGate(self.theta), rxx_props) measure_props = { (0,): None, (1,): None, (2,): None, (3,): None, (4,): None, } self.aqt_target.add_instruction(Measure(), measure_props) self.empty_target = Target() self.ideal_sim_target = Target(num_qubits=3, description="Ideal Simulator") self.lam = Parameter("lam") for inst in [ UGate(self.theta, self.phi, self.lam), RXGate(self.theta), RYGate(self.theta), RZGate(self.theta), CXGate(), ECRGate(), CCXGate(), Measure(), ]: self.ideal_sim_target.add_instruction(inst, {None: None}) def test_qargs(self): self.assertEqual(set(), self.empty_target.qargs) expected_ibm = { (0,), (1,), (2,), (3,), (4,), (3, 4), (4, 3), (3, 1), (1, 3), (1, 2), (2, 1), (0, 1), (1, 0), } self.assertEqual(expected_ibm, self.ibm_target.qargs) expected_aqt = { (0,), (1,), (2,), (3,), (4,), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (2, 0), (3, 0), (4, 0), (1, 2), (1, 3), (1, 4), (2, 1), (3, 1), (4, 1), (2, 3), (2, 4), (3, 2), (4, 2), (3, 4), (4, 3), } self.assertEqual(expected_aqt, self.aqt_target.qargs) expected_fake = { (0,), (1,), (0, 1), (1, 0), } self.assertEqual(expected_fake, self.fake_backend_target.qargs) self.assertEqual(None, self.ideal_sim_target.qargs) def test_qargs_for_operation_name(self): with self.assertRaises(KeyError): self.empty_target.qargs_for_operation_name("rz") self.assertEqual( self.ibm_target.qargs_for_operation_name("rz"), {(0,), (1,), (2,), (3,), (4,)} ) self.assertEqual( self.aqt_target.qargs_for_operation_name("rz"), {(0,), (1,), (2,), (3,), (4,)} ) self.assertEqual(self.fake_backend_target.qargs_for_operation_name("cx"), {(0, 1)}) self.assertEqual( self.fake_backend_target.qargs_for_operation_name("ecr"), { (1, 0), }, ) self.assertEqual(self.ideal_sim_target.qargs_for_operation_name("cx"), None) def test_instruction_names(self): self.assertEqual(self.empty_target.operation_names, set()) self.assertEqual(self.ibm_target.operation_names, {"rz", "id", "sx", "x", "cx", "measure"}) self.assertEqual(self.aqt_target.operation_names, {"rz", "ry", "rx", "rxx", "r", "measure"}) self.assertEqual( self.fake_backend_target.operation_names, {"u", "cx", "measure", "ecr", "rx_30", "rx"} ) self.assertEqual( self.ideal_sim_target.operation_names, {"u", "rz", "ry", "rx", "cx", "ecr", "ccx", "measure"}, ) def test_operations(self): self.assertEqual(self.empty_target.operations, []) ibm_expected = [RZGate(self.theta), IGate(), SXGate(), XGate(), CXGate(), Measure()] for gate in ibm_expected: self.assertIn(gate, self.ibm_target.operations) aqt_expected = [ RZGate(self.theta), RXGate(self.theta), RYGate(self.theta), RGate(self.theta, self.phi), RXXGate(self.theta), ] for gate in aqt_expected: self.assertIn(gate, self.aqt_target.operations) fake_expected = [ UGate(self.fake_backend._theta, self.fake_backend._phi, self.fake_backend._lam), CXGate(), Measure(), ECRGate(), RXGate(math.pi / 6), RXGate(self.fake_backend._theta), ] for gate in fake_expected: self.assertIn(gate, self.fake_backend_target.operations) ideal_sim_expected = [ UGate(self.theta, self.phi, self.lam), RXGate(self.theta), RYGate(self.theta), RZGate(self.theta), CXGate(), ECRGate(), CCXGate(), Measure(), ] for gate in ideal_sim_expected: self.assertIn(gate, self.ideal_sim_target.operations) def test_instructions(self): self.assertEqual(self.empty_target.instructions, []) ibm_expected = [ (IGate(), (0,)), (IGate(), (1,)), (IGate(), (2,)), (IGate(), (3,)), (IGate(), (4,)), (RZGate(self.theta), (0,)), (RZGate(self.theta), (1,)), (RZGate(self.theta), (2,)), (RZGate(self.theta), (3,)), (RZGate(self.theta), (4,)), (SXGate(), (0,)), (SXGate(), (1,)), (SXGate(), (2,)), (SXGate(), (3,)), (SXGate(), (4,)), (XGate(), (0,)), (XGate(), (1,)), (XGate(), (2,)), (XGate(), (3,)), (XGate(), (4,)), (CXGate(), (3, 4)), (CXGate(), (4, 3)), (CXGate(), (3, 1)), (CXGate(), (1, 3)), (CXGate(), (1, 2)), (CXGate(), (2, 1)), (CXGate(), (0, 1)), (CXGate(), (1, 0)), (Measure(), (0,)), (Measure(), (1,)), (Measure(), (2,)), (Measure(), (3,)), (Measure(), (4,)), ] self.assertEqual(ibm_expected, self.ibm_target.instructions) ideal_sim_expected = [ (UGate(self.theta, self.phi, self.lam), None), (RXGate(self.theta), None), (RYGate(self.theta), None), (RZGate(self.theta), None), (CXGate(), None), (ECRGate(), None), (CCXGate(), None), (Measure(), None), ] self.assertEqual(ideal_sim_expected, self.ideal_sim_target.instructions) def test_instruction_properties(self): i_gate_2 = self.ibm_target.instruction_properties(2) self.assertEqual(i_gate_2.error, 0.0004003) self.assertIsNone(self.ideal_sim_target.instruction_properties(4)) def test_get_instruction_from_name(self): with self.assertRaises(KeyError): self.empty_target.operation_from_name("measure") self.assertEqual(self.ibm_target.operation_from_name("measure"), Measure()) self.assertEqual(self.fake_backend_target.operation_from_name("rx_30"), RXGate(math.pi / 6)) self.assertEqual( self.fake_backend_target.operation_from_name("rx"), RXGate(self.fake_backend._theta), ) self.assertEqual(self.ideal_sim_target.operation_from_name("ccx"), CCXGate()) def test_get_instructions_for_qargs(self): with self.assertRaises(KeyError): self.empty_target.operations_for_qargs((0,)) expected = [RZGate(self.theta), IGate(), SXGate(), XGate(), Measure()] res = self.ibm_target.operations_for_qargs((0,)) for gate in expected: self.assertIn(gate, res) expected = [ECRGate()] res = self.fake_backend_target.operations_for_qargs((1, 0)) for gate in expected: self.assertIn(gate, res) expected = [CXGate()] res = self.fake_backend_target.operations_for_qargs((0, 1)) self.assertEqual(expected, res) ideal_sim_expected = [ UGate(self.theta, self.phi, self.lam), RXGate(self.theta), RYGate(self.theta), RZGate(self.theta), CXGate(), ECRGate(), CCXGate(), Measure(), ] for gate in ideal_sim_expected: self.assertIn(gate, self.ideal_sim_target.operations_for_qargs(None)) def test_get_operation_for_qargs_global(self): expected = [ RXGate(self.theta), RYGate(self.theta), RZGate(self.theta), RGate(self.theta, self.phi), Measure(), ] res = self.aqt_target.operations_for_qargs((0,)) self.assertEqual(len(expected), len(res)) for x in expected: self.assertIn(x, res) expected = [RXXGate(self.theta)] res = self.aqt_target.operations_for_qargs((0, 1)) self.assertEqual(len(expected), len(res)) for x in expected: self.assertIn(x, res) def test_get_invalid_operations_for_qargs(self): with self.assertRaises(KeyError): self.ibm_target.operations_for_qargs((0, 102)) with self.assertRaises(KeyError): self.ibm_target.operations_for_qargs(None) def test_get_operation_names_for_qargs(self): with self.assertRaises(KeyError): self.empty_target.operation_names_for_qargs((0,)) expected = {"rz", "id", "sx", "x", "measure"} res = self.ibm_target.operation_names_for_qargs((0,)) for gate in expected: self.assertIn(gate, res) expected = {"ecr"} res = self.fake_backend_target.operation_names_for_qargs((1, 0)) for gate in expected: self.assertIn(gate, res) expected = {"cx"} res = self.fake_backend_target.operation_names_for_qargs((0, 1)) self.assertEqual(expected, res) ideal_sim_expected = ["u", "rx", "ry", "rz", "cx", "ecr", "ccx", "measure"] for gate in ideal_sim_expected: self.assertIn(gate, self.ideal_sim_target.operation_names_for_qargs(None)) def test_get_operation_names_for_qargs_invalid_qargs(self): with self.assertRaises(KeyError): self.ibm_target.operation_names_for_qargs((0, 102)) with self.assertRaises(KeyError): self.ibm_target.operation_names_for_qargs(None) def test_get_operation_names_for_qargs_global_insts(self): expected = {"r", "rx", "rz", "ry", "measure"} self.assertEqual(self.aqt_target.operation_names_for_qargs((0,)), expected) expected = { "rxx", } self.assertEqual(self.aqt_target.operation_names_for_qargs((0, 1)), expected) def test_coupling_map(self): self.assertEqual( CouplingMap().get_edges(), self.empty_target.build_coupling_map().get_edges() ) self.assertEqual( set(CouplingMap.from_full(5).get_edges()), set(self.aqt_target.build_coupling_map().get_edges()), ) self.assertEqual( {(0, 1), (1, 0)}, set(self.fake_backend_target.build_coupling_map().get_edges()) ) self.assertEqual( { (3, 4), (4, 3), (3, 1), (1, 3), (1, 2), (2, 1), (0, 1), (1, 0), }, set(self.ibm_target.build_coupling_map().get_edges()), ) self.assertEqual(None, self.ideal_sim_target.build_coupling_map()) def test_coupling_map_mutations_do_not_propagate(self): cm = CouplingMap.from_line(5, bidirectional=False) cx_props = { edge: InstructionProperties(duration=270.22e-9, error=0.00713) for edge in cm.get_edges() } target = Target() target.add_instruction(CXGate(), cx_props) self.assertEqual(cm, target.build_coupling_map()) symmetric = target.build_coupling_map() symmetric.make_symmetric() self.assertNotEqual(cm, symmetric) # sanity check for the test. # Verify that mutating the output of `build_coupling_map` doesn't affect the target. self.assertNotEqual(target.build_coupling_map(), symmetric) def test_coupling_map_filtered_mutations_do_not_propagate(self): cm = CouplingMap.from_line(5, bidirectional=False) cx_props = { edge: InstructionProperties(duration=270.22e-9, error=0.00713) for edge in cm.get_edges() if 2 not in edge } target = Target() target.add_instruction(CXGate(), cx_props) symmetric = target.build_coupling_map(filter_idle_qubits=True) symmetric.make_symmetric() self.assertNotEqual(cm, symmetric) # sanity check for the test. # Verify that mutating the output of `build_coupling_map` doesn't affect the target. self.assertNotEqual(target.build_coupling_map(filter_idle_qubits=True), symmetric) def test_coupling_map_no_filter_mutations_do_not_propagate(self): cm = CouplingMap.from_line(5, bidirectional=False) cx_props = { edge: InstructionProperties(duration=270.22e-9, error=0.00713) for edge in cm.get_edges() } target = Target() target.add_instruction(CXGate(), cx_props) # The filter here does not actually do anything, because there's no idle qubits. This is # just a test that this path is also not cached. self.assertEqual(cm, target.build_coupling_map(filter_idle_qubits=True)) symmetric = target.build_coupling_map(filter_idle_qubits=True) symmetric.make_symmetric() self.assertNotEqual(cm, symmetric) # sanity check for the test. # Verify that mutating the output of `build_coupling_map` doesn't affect the target. self.assertNotEqual(target.build_coupling_map(filter_idle_qubits=True), symmetric) def test_coupling_map_2q_gate(self): cmap = self.fake_backend_target.build_coupling_map("ecr") self.assertEqual( [ (1, 0), ], cmap.get_edges(), ) def test_coupling_map_3q_gate(self): fake_target = Target() ccx_props = { (0, 1, 2): None, (1, 0, 2): None, (2, 1, 0): None, } fake_target.add_instruction(CCXGate(), ccx_props) with self.assertLogs("qiskit.transpiler.target", level="WARN") as log: cmap = fake_target.build_coupling_map() self.assertEqual( log.output, [ "WARNING:qiskit.transpiler.target:" "This Target object contains multiqubit gates that " "operate on > 2 qubits. This will not be reflected in " "the output coupling map." ], ) self.assertEqual([], cmap.get_edges()) with self.assertRaises(ValueError): fake_target.build_coupling_map("ccx") def test_coupling_map_mixed_ideal_global_1q_and_2q_gates(self): n_qubits = 3 target = Target() target.add_instruction(CXGate(), {(i, i + 1): None for i in range(n_qubits - 1)}) target.add_instruction(RXGate(Parameter("theta")), {None: None}) cmap = target.build_coupling_map() self.assertEqual([(0, 1), (1, 2)], cmap.get_edges()) def test_coupling_map_mixed_global_1q_and_2q_gates(self): n_qubits = 3 target = Target() target.add_instruction(CXGate(), {(i, i + 1): None for i in range(n_qubits - 1)}) target.add_instruction(RXGate(Parameter("theta"))) cmap = target.build_coupling_map() self.assertEqual([(0, 1), (1, 2)], cmap.get_edges()) def test_coupling_map_mixed_ideal_global_2q_and_real_2q_gates(self): n_qubits = 3 target = Target() target.add_instruction(CXGate(), {(i, i + 1): None for i in range(n_qubits - 1)}) target.add_instruction(ECRGate()) cmap = target.build_coupling_map() self.assertIsNone(cmap) def test_physical_qubits(self): self.assertEqual([], self.empty_target.physical_qubits) self.assertEqual(list(range(5)), self.ibm_target.physical_qubits) self.assertEqual(list(range(5)), self.aqt_target.physical_qubits) self.assertEqual(list(range(2)), self.fake_backend_target.physical_qubits) self.assertEqual(list(range(3)), self.ideal_sim_target.physical_qubits) def test_duplicate_instruction_add_instruction(self): target = Target() target.add_instruction(XGate(), {(0,): None}) with self.assertRaises(AttributeError): target.add_instruction(XGate(), {(1,): None}) def test_durations(self): empty_durations = self.empty_target.durations() self.assertEqual( empty_durations.duration_by_name_qubits, InstructionDurations().duration_by_name_qubits ) aqt_durations = self.aqt_target.durations() self.assertEqual(aqt_durations.duration_by_name_qubits, {}) ibm_durations = self.ibm_target.durations() expected = { ("cx", (0, 1)): (5.1911e-07, "s"), ("cx", (1, 0)): (5.5466e-07, "s"), ("cx", (1, 2)): (2.2755e-07, "s"), ("cx", (1, 3)): (4.9777e-07, "s"), ("cx", (2, 1)): (2.6311e-07, "s"), ("cx", (3, 1)): (4.6222e-07, "s"), ("cx", (3, 4)): (2.7022e-07, "s"), ("cx", (4, 3)): (3.0577e-07, "s"), ("id", (0,)): (3.55e-08, "s"), ("id", (1,)): (3.55e-08, "s"), ("id", (2,)): (3.55e-08, "s"), ("id", (3,)): (3.55e-08, "s"), ("id", (4,)): (3.55e-08, "s"), ("measure", (0,)): (5.813e-06, "s"), ("measure", (1,)): (5.813e-06, "s"), ("measure", (2,)): (5.813e-06, "s"), ("measure", (3,)): (5.813e-06, "s"), ("measure", (4,)): (5.813e-06, "s"), ("rz", (0,)): (0, "s"), ("rz", (1,)): (0, "s"), ("rz", (2,)): (0, "s"), ("rz", (3,)): (0, "s"), ("rz", (4,)): (0, "s"), ("sx", (0,)): (3.55e-08, "s"), ("sx", (1,)): (3.55e-08, "s"), ("sx", (2,)): (3.55e-08, "s"), ("sx", (3,)): (3.55e-08, "s"), ("sx", (4,)): (3.55e-08, "s"), ("x", (0,)): (3.55e-08, "s"), ("x", (1,)): (3.55e-08, "s"), ("x", (2,)): (3.55e-08, "s"), ("x", (3,)): (3.55e-08, "s"), ("x", (4,)): (3.55e-08, "s"), } self.assertEqual(ibm_durations.duration_by_name_qubits, expected) def test_mapping(self): with self.assertRaises(KeyError): _res = self.empty_target["cx"] expected = { (0,): None, (1,): None, (2,): None, (3,): None, (4,): None, } self.assertEqual(self.aqt_target["r"], expected) self.assertEqual(["rx", "ry", "rz", "r", "rxx", "measure"], list(self.aqt_target)) expected_values = [ { (0,): None, (1,): None, (2,): None, (3,): None, (4,): None, }, { (0,): None, (1,): None, (2,): None, (3,): None, (4,): None, }, { (0,): None, (1,): None, (2,): None, (3,): None, (4,): None, }, { (0,): None, (1,): None, (2,): None, (3,): None, (4,): None, }, { (0, 1): None, (0, 2): None, (0, 3): None, (0, 4): None, (1, 0): None, (2, 0): None, (3, 0): None, (4, 0): None, (1, 2): None, (1, 3): None, (1, 4): None, (2, 1): None, (3, 1): None, (4, 1): None, (2, 3): None, (2, 4): None, (3, 2): None, (4, 2): None, (3, 4): None, (4, 3): None, }, { (0,): None, (1,): None, (2,): None, (3,): None, (4,): None, }, ] self.assertEqual(expected_values, list(self.aqt_target.values())) expected_items = { "rx": { (0,): None, (1,): None, (2,): None, (3,): None, (4,): None, }, "ry": { (0,): None, (1,): None, (2,): None, (3,): None, (4,): None, }, "rz": { (0,): None, (1,): None, (2,): None, (3,): None, (4,): None, }, "r": { (0,): None, (1,): None, (2,): None, (3,): None, (4,): None, }, "rxx": { (0, 1): None, (0, 2): None, (0, 3): None, (0, 4): None, (1, 0): None, (2, 0): None, (3, 0): None, (4, 0): None, (1, 2): None, (1, 3): None, (1, 4): None, (2, 1): None, (3, 1): None, (4, 1): None, (2, 3): None, (2, 4): None, (3, 2): None, (4, 2): None, (3, 4): None, (4, 3): None, }, "measure": { (0,): None, (1,): None, (2,): None, (3,): None, (4,): None, }, } self.assertEqual(expected_items, dict(self.aqt_target.items())) self.assertIn("cx", self.ibm_target) self.assertNotIn("ecr", self.ibm_target) self.assertEqual(len(self.ibm_target), 6) def test_update_instruction_properties(self): self.aqt_target.update_instruction_properties( "rxx", (0, 1), InstructionProperties(duration=1e-6, error=1e-5), ) self.assertEqual(self.aqt_target["rxx"][(0, 1)].duration, 1e-6) self.assertEqual(self.aqt_target["rxx"][(0, 1)].error, 1e-5) def test_update_instruction_properties_invalid_instruction(self): with self.assertRaises(KeyError): self.ibm_target.update_instruction_properties("rxx", (0, 1), None) def test_update_instruction_properties_invalid_qarg(self): with self.assertRaises(KeyError): self.fake_backend_target.update_instruction_properties("ecr", (0, 1), None) def test_str(self): expected = """Target Number of qubits: 5 Instructions: id (0,): Duration: 3.55e-08 sec. Error Rate: 0.000413 (1,): Duration: 3.55e-08 sec. Error Rate: 0.000502 (2,): Duration: 3.55e-08 sec. Error Rate: 0.0004003 (3,): Duration: 3.55e-08 sec. Error Rate: 0.000614 (4,): Duration: 3.55e-08 sec. Error Rate: 0.006149 rz (0,): Duration: 0 sec. Error Rate: 0 (1,): Duration: 0 sec. Error Rate: 0 (2,): Duration: 0 sec. Error Rate: 0 (3,): Duration: 0 sec. Error Rate: 0 (4,): Duration: 0 sec. Error Rate: 0 sx (0,): Duration: 3.55e-08 sec. Error Rate: 0.000413 (1,): Duration: 3.55e-08 sec. Error Rate: 0.000502 (2,): Duration: 3.55e-08 sec. Error Rate: 0.0004003 (3,): Duration: 3.55e-08 sec. Error Rate: 0.000614 (4,): Duration: 3.55e-08 sec. Error Rate: 0.006149 x (0,): Duration: 3.55e-08 sec. Error Rate: 0.000413 (1,): Duration: 3.55e-08 sec. Error Rate: 0.000502 (2,): Duration: 3.55e-08 sec. Error Rate: 0.0004003 (3,): Duration: 3.55e-08 sec. Error Rate: 0.000614 (4,): Duration: 3.55e-08 sec. Error Rate: 0.006149 cx (3, 4): Duration: 2.7022e-07 sec. Error Rate: 0.00713 (4, 3): Duration: 3.0577e-07 sec. Error Rate: 0.00713 (3, 1): Duration: 4.6222e-07 sec. Error Rate: 0.00929 (1, 3): Duration: 4.9777e-07 sec. Error Rate: 0.00929 (1, 2): Duration: 2.2755e-07 sec. Error Rate: 0.00659 (2, 1): Duration: 2.6311e-07 sec. Error Rate: 0.00659 (0, 1): Duration: 5.1911e-07 sec. Error Rate: 0.01201 (1, 0): Duration: 5.5466e-07 sec. Error Rate: 0.01201 measure (0,): Duration: 5.813e-06 sec. Error Rate: 0.0751 (1,): Duration: 5.813e-06 sec. Error Rate: 0.0225 (2,): Duration: 5.813e-06 sec. Error Rate: 0.0146 (3,): Duration: 5.813e-06 sec. Error Rate: 0.0215 (4,): Duration: 5.813e-06 sec. Error Rate: 0.0333 """ self.assertEqual(expected, str(self.ibm_target)) aqt_expected = """Target: AQT Target Number of qubits: 5 Instructions: rx (0,) (1,) (2,) (3,) (4,) ry (0,) (1,) (2,) (3,) (4,) rz (0,) (1,) (2,) (3,) (4,) r (0,) (1,) (2,) (3,) (4,) rxx (0, 1) (0, 2) (0, 3) (0, 4) (1, 0) (2, 0) (3, 0) (4, 0) (1, 2) (1, 3) (1, 4) (2, 1) (3, 1) (4, 1) (2, 3) (2, 4) (3, 2) (4, 2) (3, 4) (4, 3) measure (0,) (1,) (2,) (3,) (4,) """ self.assertEqual(aqt_expected, str(self.aqt_target)) sim_expected = """Target: Ideal Simulator Number of qubits: 3 Instructions: u rx ry rz cx ecr ccx measure """ self.assertEqual(sim_expected, str(self.ideal_sim_target)) def test_extra_props_str(self): target = Target(description="Extra Properties") class ExtraProperties(InstructionProperties): """An example properties subclass.""" def __init__( self, duration=None, error=None, calibration=None, tuned=None, diamond_norm_error=None, ): super().__init__(duration=duration, error=error, calibration=calibration) self.tuned = tuned self.diamond_norm_error = diamond_norm_error cx_props = { (3, 4): ExtraProperties( duration=270.22e-9, error=0.00713, tuned=False, diamond_norm_error=2.12e-6 ), } target.add_instruction(CXGate(), cx_props) expected = """Target: Extra Properties Number of qubits: 5 Instructions: cx (3, 4): Duration: 2.7022e-07 sec. Error Rate: 0.00713 """ self.assertEqual(expected, str(target)) def test_timing_constraints(self): generated_constraints = self.aqt_target.timing_constraints() expected_constraints = TimingConstraints() for i in ["granularity", "min_length", "pulse_alignment", "acquire_alignment"]: self.assertEqual( getattr(generated_constraints, i), getattr(expected_constraints, i), f"Generated constraints differs from expected for attribute {i}" f"{getattr(generated_constraints, i)}!={getattr(expected_constraints, i)}", ) def test_get_non_global_operation_name_ideal_backend(self): self.assertEqual(self.aqt_target.get_non_global_operation_names(), []) self.assertEqual(self.ideal_sim_target.get_non_global_operation_names(), []) self.assertEqual(self.ibm_target.get_non_global_operation_names(), []) self.assertEqual(self.fake_backend_target.get_non_global_operation_names(), []) def test_get_non_global_operation_name_ideal_backend_strict_direction(self): self.assertEqual(self.aqt_target.get_non_global_operation_names(True), []) self.assertEqual(self.ideal_sim_target.get_non_global_operation_names(True), []) self.assertEqual(self.ibm_target.get_non_global_operation_names(True), []) self.assertEqual( self.fake_backend_target.get_non_global_operation_names(True), ["cx", "ecr"] ) def test_instruction_supported(self): self.assertTrue(self.aqt_target.instruction_supported("r", (0,))) self.assertFalse(self.aqt_target.instruction_supported("cx", (0, 1))) self.assertTrue(self.ideal_sim_target.instruction_supported("cx", (0, 1))) self.assertFalse(self.ideal_sim_target.instruction_supported("cx", (0, 524))) self.assertTrue(self.fake_backend_target.instruction_supported("cx", (0, 1))) self.assertFalse(self.fake_backend_target.instruction_supported("cx", (1, 0))) self.assertFalse(self.ideal_sim_target.instruction_supported("cx", (0, 1, 2))) def test_instruction_supported_parameters(self): mumbai = FakeMumbaiFractionalCX() self.assertTrue( mumbai.target.instruction_supported( qargs=(0, 1), operation_class=RZXGate, parameters=[math.pi / 4] ) ) self.assertTrue(mumbai.target.instruction_supported(qargs=(0, 1), operation_class=RZXGate)) self.assertTrue( mumbai.target.instruction_supported(operation_class=RZXGate, parameters=[math.pi / 4]) ) self.assertFalse(mumbai.target.instruction_supported("rzx", parameters=[math.pi / 4])) self.assertTrue(mumbai.target.instruction_supported("rz", parameters=[Parameter("angle")])) self.assertTrue( mumbai.target.instruction_supported("rzx_45", qargs=(0, 1), parameters=[math.pi / 4]) ) self.assertTrue(mumbai.target.instruction_supported("rzx_45", qargs=(0, 1))) self.assertTrue(mumbai.target.instruction_supported("rzx_45", parameters=[math.pi / 4])) self.assertFalse(mumbai.target.instruction_supported("rzx_45", parameters=[math.pi / 6])) self.assertFalse( mumbai.target.instruction_supported("rzx_45", parameters=[Parameter("angle")]) ) self.assertTrue( self.ideal_sim_target.instruction_supported( qargs=(0,), operation_class=RXGate, parameters=[Parameter("angle")] ) ) self.assertTrue( self.ideal_sim_target.instruction_supported( qargs=(0,), operation_class=RXGate, parameters=[math.pi] ) ) self.assertTrue( self.ideal_sim_target.instruction_supported( operation_class=RXGate, parameters=[math.pi] ) ) self.assertTrue( self.ideal_sim_target.instruction_supported( operation_class=RXGate, parameters=[Parameter("angle")] ) ) self.assertTrue( self.ideal_sim_target.instruction_supported( "rx", qargs=(0,), parameters=[Parameter("angle")] ) ) self.assertTrue( self.ideal_sim_target.instruction_supported("rx", qargs=(0,), parameters=[math.pi]) ) self.assertTrue(self.ideal_sim_target.instruction_supported("rx", parameters=[math.pi])) self.assertTrue( self.ideal_sim_target.instruction_supported("rx", parameters=[Parameter("angle")]) ) def test_instruction_supported_multiple_parameters(self): target = Target(1) target.add_instruction( UGate(self.theta, self.phi, self.lam), {(0,): InstructionProperties(duration=270.22e-9, error=0.00713)}, ) self.assertFalse(target.instruction_supported("u", parameters=[math.pi])) self.assertTrue(target.instruction_supported("u", parameters=[math.pi, math.pi, math.pi])) self.assertTrue( target.instruction_supported( operation_class=UGate, parameters=[math.pi, math.pi, math.pi] ) ) self.assertFalse( target.instruction_supported(operation_class=UGate, parameters=[Parameter("x")]) ) def test_instruction_supported_arg_len_mismatch(self): self.assertFalse( self.ideal_sim_target.instruction_supported(operation_class=UGate, parameters=[math.pi]) ) self.assertFalse(self.ideal_sim_target.instruction_supported("u", parameters=[math.pi])) def test_instruction_supported_class_not_in_target(self): self.assertFalse( self.ibm_target.instruction_supported(operation_class=CZGate, parameters=[math.pi]) ) def test_instruction_supported_no_args(self): self.assertFalse(self.ibm_target.instruction_supported()) def test_instruction_supported_no_operation(self): self.assertFalse(self.ibm_target.instruction_supported(qargs=(0,), parameters=[math.pi])) class TestPulseTarget(QiskitTestCase): def setUp(self): super().setUp() self.pulse_target = Target( dt=3e-7, granularity=2, min_length=4, pulse_alignment=8, acquire_alignment=8 ) with pulse.build(name="sx_q0") as self.custom_sx_q0: pulse.play(pulse.Constant(100, 0.1), pulse.DriveChannel(0)) with pulse.build(name="sx_q1") as self.custom_sx_q1: pulse.play(pulse.Constant(100, 0.2), pulse.DriveChannel(1)) sx_props = { (0,): InstructionProperties( duration=35.5e-9, error=0.000413, calibration=self.custom_sx_q0 ), (1,): InstructionProperties( duration=35.5e-9, error=0.000502, calibration=self.custom_sx_q1 ), } self.pulse_target.add_instruction(SXGate(), sx_props) def test_instruction_schedule_map(self): inst_map = self.pulse_target.instruction_schedule_map() self.assertIn("sx", inst_map.instructions) self.assertEqual(inst_map.qubits_with_instruction("sx"), [0, 1]) self.assertTrue("sx" in inst_map.qubit_instructions(0)) def test_instruction_schedule_map_ideal_sim_backend(self): ideal_sim_target = Target(num_qubits=3) theta = Parameter("theta") phi = Parameter("phi") lam = Parameter("lambda") for inst in [ UGate(theta, phi, lam), RXGate(theta), RYGate(theta), RZGate(theta), CXGate(), ECRGate(), CCXGate(), Measure(), ]: ideal_sim_target.add_instruction(inst, {None: None}) inst_map = ideal_sim_target.instruction_schedule_map() self.assertEqual(InstructionScheduleMap(), inst_map) def test_str(self): expected = """Target Number of qubits: 2 Instructions: sx (0,): Duration: 3.55e-08 sec. Error Rate: 0.000413 With pulse schedule calibration (1,): Duration: 3.55e-08 sec. Error Rate: 0.000502 With pulse schedule calibration """ self.assertEqual(expected, str(self.pulse_target)) def test_update_from_instruction_schedule_map_add_instruction(self): target = Target() inst_map = InstructionScheduleMap() inst_map.add("sx", 0, self.custom_sx_q0) inst_map.add("sx", 1, self.custom_sx_q1) target.update_from_instruction_schedule_map(inst_map, {"sx": SXGate()}) self.assertEqual(inst_map, target.instruction_schedule_map()) def test_update_from_instruction_schedule_map_with_schedule_parameter(self): self.pulse_target.dt = None inst_map = InstructionScheduleMap() duration = Parameter("duration") with pulse.build(name="sx_q0") as custom_sx: pulse.play(pulse.Constant(duration, 0.2), pulse.DriveChannel(0)) inst_map.add("sx", 0, custom_sx, ["duration"]) target = Target(dt=3e-7) target.update_from_instruction_schedule_map(inst_map, {"sx": SXGate()}) self.assertEqual(inst_map, target.instruction_schedule_map()) def test_update_from_instruction_schedule_map_update_schedule(self): self.pulse_target.dt = None inst_map = InstructionScheduleMap() with pulse.build(name="sx_q1") as custom_sx: pulse.play(pulse.Constant(1000, 0.2), pulse.DriveChannel(1)) inst_map.add("sx", 0, self.custom_sx_q0) inst_map.add("sx", 1, custom_sx) self.pulse_target.update_from_instruction_schedule_map(inst_map, {"sx": SXGate()}) self.assertEqual(inst_map, self.pulse_target.instruction_schedule_map()) # Calibration doesn't change for q0 self.assertEqual(self.pulse_target["sx"][(0,)].duration, 35.5e-9) self.assertEqual(self.pulse_target["sx"][(0,)].error, 0.000413) # Calibration is updated for q1 without error dict and gate time self.assertIsNone(self.pulse_target["sx"][(1,)].duration) self.assertIsNone(self.pulse_target["sx"][(1,)].error) def test_update_from_instruction_schedule_map_new_instruction_no_name_map(self): target = Target() inst_map = InstructionScheduleMap() inst_map.add("sx", 0, self.custom_sx_q0) inst_map.add("sx", 1, self.custom_sx_q1) target.update_from_instruction_schedule_map(inst_map) self.assertEqual(target["sx"][(0,)].calibration, self.custom_sx_q0) self.assertEqual(target["sx"][(1,)].calibration, self.custom_sx_q1) def test_update_from_instruction_schedule_map_new_qarg_raises(self): inst_map = InstructionScheduleMap() inst_map.add("sx", 0, self.custom_sx_q0) inst_map.add("sx", 1, self.custom_sx_q1) inst_map.add("sx", 2, self.custom_sx_q1) self.pulse_target.update_from_instruction_schedule_map(inst_map) self.assertFalse(self.pulse_target.instruction_supported("sx", (2,))) def test_update_from_instruction_schedule_map_with_dt_set(self): inst_map = InstructionScheduleMap() with pulse.build(name="sx_q1") as custom_sx: pulse.play(pulse.Constant(1000, 0.2), pulse.DriveChannel(1)) inst_map.add("sx", 0, self.custom_sx_q0) inst_map.add("sx", 1, custom_sx) self.pulse_target.dt = 1.0 self.pulse_target.update_from_instruction_schedule_map(inst_map, {"sx": SXGate()}) self.assertEqual(inst_map, self.pulse_target.instruction_schedule_map()) self.assertEqual(self.pulse_target["sx"][(1,)].duration, 1000.0) self.assertIsNone(self.pulse_target["sx"][(1,)].error) # This is an edge case. # System dt is read-only property and changing it will break all underlying calibrations. # duration of sx0 returns previous value since calibration doesn't change. self.assertEqual(self.pulse_target["sx"][(0,)].duration, 35.5e-9) self.assertEqual(self.pulse_target["sx"][(0,)].error, 0.000413) def test_update_from_instruction_schedule_map_with_error_dict(self): inst_map = InstructionScheduleMap() with pulse.build(name="sx_q1") as custom_sx: pulse.play(pulse.Constant(1000, 0.2), pulse.DriveChannel(1)) inst_map.add("sx", 0, self.custom_sx_q0) inst_map.add("sx", 1, custom_sx) self.pulse_target.dt = 1.0 error_dict = {"sx": {(1,): 1.0}} self.pulse_target.update_from_instruction_schedule_map( inst_map, {"sx": SXGate()}, error_dict=error_dict ) self.assertEqual(self.pulse_target["sx"][(1,)].error, 1.0) self.assertEqual(self.pulse_target["sx"][(0,)].error, 0.000413) def test_timing_constraints(self): generated_constraints = self.pulse_target.timing_constraints() expected_constraints = TimingConstraints(2, 4, 8, 8) for i in ["granularity", "min_length", "pulse_alignment", "acquire_alignment"]: self.assertEqual( getattr(generated_constraints, i), getattr(expected_constraints, i), f"Generated constraints differs from expected for attribute {i}" f"{getattr(generated_constraints, i)}!={getattr(expected_constraints, i)}", ) def test_default_instmap_has_no_custom_gate(self): backend = FakeGeneva() target = backend.target # This copies .calibraiton of InstructionProperties of each instruction # This must not convert PulseQobj to Schedule during this. # See qiskit-terra/#9595 inst_map = target.instruction_schedule_map() self.assertFalse(inst_map.has_custom_gate()) # Get pulse schedule. This generates Schedule provided by backend. sched = inst_map.get("sx", (0,)) self.assertEqual(sched.metadata["publisher"], CalibrationPublisher.BACKEND_PROVIDER) self.assertFalse(inst_map.has_custom_gate()) # Update target with custom instruction. This is user provided schedule. new_prop = InstructionProperties( duration=self.custom_sx_q0.duration, error=None, calibration=self.custom_sx_q0, ) target.update_instruction_properties(instruction="sx", qargs=(0,), properties=new_prop) inst_map = target.instruction_schedule_map() self.assertTrue(inst_map.has_custom_gate()) empty = InstructionProperties() target.update_instruction_properties(instruction="sx", qargs=(0,), properties=empty) inst_map = target.instruction_schedule_map() self.assertFalse(inst_map.has_custom_gate()) def test_get_empty_target_calibration(self): target = Target() properties = {(0,): InstructionProperties(duration=100, error=0.1)} target.add_instruction(XGate(), properties) self.assertIsNone(target["x"][(0,)].calibration) def test_loading_legacy_ugate_instmap(self): # This is typical IBM backend situation. # IBM provider used to have u1, u2, u3 in the basis gates and # these have been replaced with sx and rz. # However, IBM provider still provides calibration of these u gates, # and the inst map loads them as backend calibrations. # Target is implicitly updated with inst map when it is set in transpile. # If u gates are not excluded, they may appear in the transpiled circuit. # These gates are no longer supported by hardware. entry = ScheduleDef() entry.define(pulse.Schedule(name="fake_u3"), user_provided=False) # backend provided instmap = InstructionScheduleMap() instmap._add("u3", (0,), entry) # Today's standard IBM backend target with sx, rz basis target = Target() target.add_instruction(SXGate(), {(0,): InstructionProperties()}) target.add_instruction(RZGate(Parameter("θ")), {(0,): InstructionProperties()}) target.add_instruction(Measure(), {(0,): InstructionProperties()}) names_before = set(target.operation_names) target.update_from_instruction_schedule_map(instmap) names_after = set(target.operation_names) # Otherwise u3 and sx-rz basis conflict in 1q decomposition. self.assertSetEqual(names_before, names_after) class TestGlobalVariableWidthOperations(QiskitTestCase): def setUp(self): super().setUp() self.theta = Parameter("theta") self.phi = Parameter("phi") self.lam = Parameter("lambda") self.target_global_gates_only = Target(num_qubits=5) self.target_global_gates_only.add_instruction(CXGate()) self.target_global_gates_only.add_instruction(UGate(self.theta, self.phi, self.lam)) self.target_global_gates_only.add_instruction(Measure()) self.target_global_gates_only.add_instruction(IfElseOp, name="if_else") self.target_global_gates_only.add_instruction(ForLoopOp, name="for_loop") self.target_global_gates_only.add_instruction(WhileLoopOp, name="while_loop") self.target_global_gates_only.add_instruction(SwitchCaseOp, name="switch_case") self.ibm_target = Target() i_props = { (0,): InstructionProperties(duration=35.5e-9, error=0.000413), (1,): InstructionProperties(duration=35.5e-9, error=0.000502), (2,): InstructionProperties(duration=35.5e-9, error=0.0004003), (3,): InstructionProperties(duration=35.5e-9, error=0.000614), (4,): InstructionProperties(duration=35.5e-9, error=0.006149), } self.ibm_target.add_instruction(IGate(), i_props) rz_props = { (0,): InstructionProperties(duration=0, error=0), (1,): InstructionProperties(duration=0, error=0), (2,): InstructionProperties(duration=0, error=0), (3,): InstructionProperties(duration=0, error=0), (4,): InstructionProperties(duration=0, error=0), } self.ibm_target.add_instruction(RZGate(self.theta), rz_props) sx_props = { (0,): InstructionProperties(duration=35.5e-9, error=0.000413), (1,): InstructionProperties(duration=35.5e-9, error=0.000502), (2,): InstructionProperties(duration=35.5e-9, error=0.0004003), (3,): InstructionProperties(duration=35.5e-9, error=0.000614), (4,): InstructionProperties(duration=35.5e-9, error=0.006149), } self.ibm_target.add_instruction(SXGate(), sx_props) x_props = { (0,): InstructionProperties(duration=35.5e-9, error=0.000413), (1,): InstructionProperties(duration=35.5e-9, error=0.000502), (2,): InstructionProperties(duration=35.5e-9, error=0.0004003), (3,): InstructionProperties(duration=35.5e-9, error=0.000614), (4,): InstructionProperties(duration=35.5e-9, error=0.006149), } self.ibm_target.add_instruction(XGate(), x_props) cx_props = { (3, 4): InstructionProperties(duration=270.22e-9, error=0.00713), (4, 3): InstructionProperties(duration=305.77e-9, error=0.00713), (3, 1): InstructionProperties(duration=462.22e-9, error=0.00929), (1, 3): InstructionProperties(duration=497.77e-9, error=0.00929), (1, 2): InstructionProperties(duration=227.55e-9, error=0.00659), (2, 1): InstructionProperties(duration=263.11e-9, error=0.00659), (0, 1): InstructionProperties(duration=519.11e-9, error=0.01201), (1, 0): InstructionProperties(duration=554.66e-9, error=0.01201), } self.ibm_target.add_instruction(CXGate(), cx_props) measure_props = { (0,): InstructionProperties(duration=5.813e-6, error=0.0751), (1,): InstructionProperties(duration=5.813e-6, error=0.0225), (2,): InstructionProperties(duration=5.813e-6, error=0.0146), (3,): InstructionProperties(duration=5.813e-6, error=0.0215), (4,): InstructionProperties(duration=5.813e-6, error=0.0333), } self.ibm_target.add_instruction(Measure(), measure_props) self.ibm_target.add_instruction(IfElseOp, name="if_else") self.ibm_target.add_instruction(ForLoopOp, name="for_loop") self.ibm_target.add_instruction(WhileLoopOp, name="while_loop") self.ibm_target.add_instruction(SwitchCaseOp, name="switch_case") self.aqt_target = Target(description="AQT Target") rx_props = { (0,): None, (1,): None, (2,): None, (3,): None, (4,): None, } self.aqt_target.add_instruction(RXGate(self.theta), rx_props) ry_props = { (0,): None, (1,): None, (2,): None, (3,): None, (4,): None, } self.aqt_target.add_instruction(RYGate(self.theta), ry_props) rz_props = { (0,): None, (1,): None, (2,): None, (3,): None, (4,): None, } self.aqt_target.add_instruction(RZGate(self.theta), rz_props) r_props = { (0,): None, (1,): None, (2,): None, (3,): None, (4,): None, } self.aqt_target.add_instruction(RGate(self.theta, self.phi), r_props) rxx_props = { (0, 1): None, (0, 2): None, (0, 3): None, (0, 4): None, (1, 0): None, (2, 0): None, (3, 0): None, (4, 0): None, (1, 2): None, (1, 3): None, (1, 4): None, (2, 1): None, (3, 1): None, (4, 1): None, (2, 3): None, (2, 4): None, (3, 2): None, (4, 2): None, (3, 4): None, (4, 3): None, } self.aqt_target.add_instruction(RXXGate(self.theta), rxx_props) measure_props = { (0,): None, (1,): None, (2,): None, (3,): None, (4,): None, } self.aqt_target.add_instruction(Measure(), measure_props) self.aqt_target.add_instruction(IfElseOp, name="if_else") self.aqt_target.add_instruction(ForLoopOp, name="for_loop") self.aqt_target.add_instruction(WhileLoopOp, name="while_loop") self.aqt_target.add_instruction(SwitchCaseOp, name="switch_case") def test_qargs(self): expected_ibm = { (0,), (1,), (2,), (3,), (4,), (3, 4), (4, 3), (3, 1), (1, 3), (1, 2), (2, 1), (0, 1), (1, 0), } self.assertEqual(expected_ibm, self.ibm_target.qargs) expected_aqt = { (0,), (1,), (2,), (3,), (4,), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (2, 0), (3, 0), (4, 0), (1, 2), (1, 3), (1, 4), (2, 1), (3, 1), (4, 1), (2, 3), (2, 4), (3, 2), (4, 2), (3, 4), (4, 3), } self.assertEqual(expected_aqt, self.aqt_target.qargs) self.assertEqual(None, self.target_global_gates_only.qargs) def test_qargs_single_qarg(self): target = Target() target.add_instruction(XGate(), {(0,): None}) self.assertEqual( { (0,), }, target.qargs, ) def test_qargs_for_operation_name(self): self.assertEqual( self.ibm_target.qargs_for_operation_name("rz"), {(0,), (1,), (2,), (3,), (4,)} ) self.assertEqual( self.aqt_target.qargs_for_operation_name("rz"), {(0,), (1,), (2,), (3,), (4,)} ) self.assertIsNone(self.target_global_gates_only.qargs_for_operation_name("cx")) self.assertIsNone(self.ibm_target.qargs_for_operation_name("if_else")) self.assertIsNone(self.aqt_target.qargs_for_operation_name("while_loop")) self.assertIsNone(self.aqt_target.qargs_for_operation_name("switch_case")) def test_instruction_names(self): self.assertEqual( self.ibm_target.operation_names, { "rz", "id", "sx", "x", "cx", "measure", "if_else", "while_loop", "for_loop", "switch_case", }, ) self.assertEqual( self.aqt_target.operation_names, { "rz", "ry", "rx", "rxx", "r", "measure", "if_else", "while_loop", "for_loop", "switch_case", }, ) self.assertEqual( self.target_global_gates_only.operation_names, {"u", "cx", "measure", "if_else", "while_loop", "for_loop", "switch_case"}, ) def test_operations_for_qargs(self): expected = [ IGate(), RZGate(self.theta), SXGate(), XGate(), Measure(), IfElseOp, ForLoopOp, WhileLoopOp, SwitchCaseOp, ] res = self.ibm_target.operations_for_qargs((0,)) self.assertEqual(len(expected), len(res)) for x in expected: self.assertIn(x, res) expected = [ CXGate(), IfElseOp, ForLoopOp, WhileLoopOp, SwitchCaseOp, ] res = self.ibm_target.operations_for_qargs((0, 1)) self.assertEqual(len(expected), len(res)) for x in expected: self.assertIn(x, res) expected = [ RXGate(self.theta), RYGate(self.theta), RZGate(self.theta), RGate(self.theta, self.phi), Measure(), IfElseOp, ForLoopOp, WhileLoopOp, SwitchCaseOp, ] res = self.aqt_target.operations_for_qargs((0,)) self.assertEqual(len(expected), len(res)) for x in expected: self.assertIn(x, res) expected = [RXXGate(self.theta), IfElseOp, ForLoopOp, WhileLoopOp, SwitchCaseOp] res = self.aqt_target.operations_for_qargs((0, 1)) self.assertEqual(len(expected), len(res)) for x in expected: self.assertIn(x, res) def test_operation_names_for_qargs(self): expected = { "id", "rz", "sx", "x", "measure", "if_else", "for_loop", "while_loop", "switch_case", } self.assertEqual(expected, self.ibm_target.operation_names_for_qargs((0,))) expected = { "cx", "if_else", "for_loop", "while_loop", "switch_case", } self.assertEqual(expected, self.ibm_target.operation_names_for_qargs((0, 1))) expected = { "rx", "ry", "rz", "r", "measure", "if_else", "for_loop", "while_loop", "switch_case", } self.assertEqual(self.aqt_target.operation_names_for_qargs((0,)), expected) expected = {"rxx", "if_else", "for_loop", "while_loop", "switch_case"} self.assertEqual(self.aqt_target.operation_names_for_qargs((0, 1)), expected) def test_operations(self): ibm_expected = [ RZGate(self.theta), IGate(), SXGate(), XGate(), CXGate(), Measure(), WhileLoopOp, IfElseOp, ForLoopOp, SwitchCaseOp, ] for gate in ibm_expected: self.assertIn(gate, self.ibm_target.operations) aqt_expected = [ RZGate(self.theta), RXGate(self.theta), RYGate(self.theta), RGate(self.theta, self.phi), RXXGate(self.theta), ForLoopOp, IfElseOp, WhileLoopOp, SwitchCaseOp, ] for gate in aqt_expected: self.assertIn(gate, self.aqt_target.operations) fake_expected = [ UGate(self.theta, self.phi, self.lam), CXGate(), Measure(), ForLoopOp, WhileLoopOp, IfElseOp, SwitchCaseOp, ] for gate in fake_expected: self.assertIn(gate, self.target_global_gates_only.operations) def test_add_invalid_instruction(self): inst_props = {(0, 1, 2, 3): None} target = Target() with self.assertRaises(TranspilerError): target.add_instruction(CXGate(), inst_props) def test_instructions(self): ibm_expected = [ (IGate(), (0,)), (IGate(), (1,)), (IGate(), (2,)), (IGate(), (3,)), (IGate(), (4,)), (RZGate(self.theta), (0,)), (RZGate(self.theta), (1,)), (RZGate(self.theta), (2,)), (RZGate(self.theta), (3,)), (RZGate(self.theta), (4,)), (SXGate(), (0,)), (SXGate(), (1,)), (SXGate(), (2,)), (SXGate(), (3,)), (SXGate(), (4,)), (XGate(), (0,)), (XGate(), (1,)), (XGate(), (2,)), (XGate(), (3,)), (XGate(), (4,)), (CXGate(), (3, 4)), (CXGate(), (4, 3)), (CXGate(), (3, 1)), (CXGate(), (1, 3)), (CXGate(), (1, 2)), (CXGate(), (2, 1)), (CXGate(), (0, 1)), (CXGate(), (1, 0)), (Measure(), (0,)), (Measure(), (1,)), (Measure(), (2,)), (Measure(), (3,)), (Measure(), (4,)), (IfElseOp, None), (ForLoopOp, None), (WhileLoopOp, None), (SwitchCaseOp, None), ] self.assertEqual(ibm_expected, self.ibm_target.instructions) ideal_sim_expected = [ (CXGate(), None), (UGate(self.theta, self.phi, self.lam), None), (Measure(), None), (IfElseOp, None), (ForLoopOp, None), (WhileLoopOp, None), (SwitchCaseOp, None), ] self.assertEqual(ideal_sim_expected, self.target_global_gates_only.instructions) def test_instruction_supported(self): self.assertTrue(self.aqt_target.instruction_supported("r", (0,))) self.assertFalse(self.aqt_target.instruction_supported("cx", (0, 1))) self.assertTrue(self.target_global_gates_only.instruction_supported("cx", (0, 1))) self.assertFalse(self.target_global_gates_only.instruction_supported("cx", (0, 524))) self.assertFalse(self.target_global_gates_only.instruction_supported("cx", (0, 1, 2))) self.assertTrue(self.aqt_target.instruction_supported("while_loop", (0, 1, 2, 3))) self.assertTrue( self.aqt_target.instruction_supported(operation_class=WhileLoopOp, qargs=(0, 1, 2, 3)) ) self.assertTrue( self.aqt_target.instruction_supported(operation_class=SwitchCaseOp, qargs=(0, 1, 2, 3)) ) self.assertFalse( self.ibm_target.instruction_supported( operation_class=IfElseOp, qargs=(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10) ) ) self.assertFalse( self.ibm_target.instruction_supported(operation_class=IfElseOp, qargs=(0, 425)) ) self.assertFalse(self.ibm_target.instruction_supported("for_loop", qargs=(0, 425))) def test_coupling_map(self): self.assertIsNone(self.target_global_gates_only.build_coupling_map()) self.assertEqual( set(CouplingMap.from_full(5).get_edges()), set(self.aqt_target.build_coupling_map().get_edges()), ) self.assertEqual( { (3, 4), (4, 3), (3, 1), (1, 3), (1, 2), (2, 1), (0, 1), (1, 0), }, set(self.ibm_target.build_coupling_map().get_edges()), ) class TestInstructionProperties(QiskitTestCase): def test_empty_repr(self): properties = InstructionProperties() self.assertEqual( repr(properties), "InstructionProperties(duration=None, error=None, calibration=None)", ) class TestTargetFromConfiguration(QiskitTestCase): """Test the from_configuration() constructor.""" def test_basis_gates_qubits_only(self): """Test construction with only basis gates.""" target = Target.from_configuration(["u", "cx"], 3) self.assertEqual(target.operation_names, {"u", "cx"}) def test_basis_gates_no_qubits(self): target = Target.from_configuration(["u", "cx"]) self.assertEqual(target.operation_names, {"u", "cx"}) def test_basis_gates_coupling_map(self): """Test construction with only basis gates.""" target = Target.from_configuration( ["u", "cx"], 3, CouplingMap.from_ring(3, bidirectional=False) ) self.assertEqual(target.operation_names, {"u", "cx"}) self.assertEqual({(0,), (1,), (2,)}, target["u"].keys()) self.assertEqual({(0, 1), (1, 2), (2, 0)}, target["cx"].keys()) def test_properties(self): fake_backend = FakeVigo() config = fake_backend.configuration() properties = fake_backend.properties() target = Target.from_configuration( basis_gates=config.basis_gates, num_qubits=config.num_qubits, coupling_map=CouplingMap(config.coupling_map), backend_properties=properties, ) self.assertEqual(0, target["rz"][(0,)].error) self.assertEqual(0, target["rz"][(0,)].duration) def test_properties_with_durations(self): fake_backend = FakeVigo() config = fake_backend.configuration() properties = fake_backend.properties() durations = InstructionDurations([("rz", 0, 0.5)], dt=1.0) target = Target.from_configuration( basis_gates=config.basis_gates, num_qubits=config.num_qubits, coupling_map=CouplingMap(config.coupling_map), backend_properties=properties, instruction_durations=durations, dt=config.dt, ) self.assertEqual(0.5, target["rz"][(0,)].duration) def test_inst_map(self): fake_backend = FakeNairobi() config = fake_backend.configuration() properties = fake_backend.properties() defaults = fake_backend.defaults() constraints = TimingConstraints(**config.timing_constraints) target = Target.from_configuration( basis_gates=config.basis_gates, num_qubits=config.num_qubits, coupling_map=CouplingMap(config.coupling_map), backend_properties=properties, dt=config.dt, inst_map=defaults.instruction_schedule_map, timing_constraints=constraints, ) self.assertIsNotNone(target["sx"][(0,)].calibration) self.assertEqual(target.granularity, constraints.granularity) self.assertEqual(target.min_length, constraints.min_length) self.assertEqual(target.pulse_alignment, constraints.pulse_alignment) self.assertEqual(target.acquire_alignment, constraints.acquire_alignment) def test_concurrent_measurements(self): fake_backend = FakeVigo() config = fake_backend.configuration() target = Target.from_configuration( basis_gates=config.basis_gates, concurrent_measurements=config.meas_map, ) self.assertEqual(target.concurrent_measurements, config.meas_map) def test_custom_basis_gates(self): basis_gates = ["my_x", "cx"] custom_name_mapping = {"my_x": XGate()} target = Target.from_configuration( basis_gates=basis_gates, num_qubits=2, custom_name_mapping=custom_name_mapping ) self.assertEqual(target.operation_names, {"my_x", "cx"}) def test_missing_custom_basis_no_coupling(self): basis_gates = ["my_X", "cx"] with self.assertRaisesRegex(KeyError, "is not present in the standard gate names"): Target.from_configuration(basis_gates, num_qubits=4) def test_missing_custom_basis_with_coupling(self): basis_gates = ["my_X", "cx"] cmap = CouplingMap.from_line(3) with self.assertRaisesRegex(KeyError, "is not present in the standard gate names"): Target.from_configuration(basis_gates, 3, cmap) def test_over_two_qubit_gate_without_coupling(self): basis_gates = ["ccx", "cx", "swap", "u"] target = Target.from_configuration(basis_gates, 15) self.assertEqual(target.operation_names, {"ccx", "cx", "swap", "u"}) def test_over_two_qubits_with_coupling(self): basis_gates = ["ccx", "cx", "swap", "u"] cmap = CouplingMap.from_line(15) with self.assertRaisesRegex(TranspilerError, "This constructor method only supports"): Target.from_configuration(basis_gates, 15, cmap)
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
mmetcalf14
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Pauli tomography preparation and measurement basis """ # Needed for functions import numpy as np # Import QISKit classes from qiskit import QuantumCircuit from .tomographybasis import TomographyBasis ########################################################################### # Built-in circuit functions ########################################################################### def pauli_measurement_circuit(op, qubit, clbit): """ Return a qubit Pauli operator measurement circuit. Params: op (str): Pauli operator 'X', 'Y', 'Z'. qubit (QuantumRegister tuple): qubit to be measured. clbit (ClassicalRegister tuple): clbit for measurement outcome. Returns: A QuantumCircuit object. """ circ = QuantumCircuit(qubit[0], clbit[0]) if op == 'X': circ.h(qubit) circ.measure(qubit, clbit) if op == 'Y': circ.sdg(qubit) circ.h(qubit) circ.measure(qubit, clbit) if op == 'Z': circ.measure(qubit, clbit) return circ def pauli_preparation_circuit(op, qubit): """ Return a qubit Pauli eigenstate preparation circuit. This circuit assumes the qubit is initialized in the Zp eigenstate [1, 0]. Params: op (str): Pauli eigenstate 'Zp', 'Zm', 'Xp', 'Xm', 'Yp', or 'Ym'. qubit (QuantumRegister tuple): qubit to be prepared. Returns: A QuantumCircuit object. """ circ = QuantumCircuit(qubit[0]) if op == 'Xp': circ.h(qubit) if op == 'Xm': circ.x(qubit) circ.h(qubit) if op == 'Yp': circ.h(qubit) circ.s(qubit) if op == 'Ym': circ.x(qubit) circ.h(qubit) circ.s(qubit) if op == 'Zm': circ.x(qubit) return circ ########################################################################### # Matrix functions for built-in bases ########################################################################### def pauli_preparation_matrix(label): """ Return the matrix corresonding to a Pauli eigenstate preparation. Args: label (str): single-qubit Pauli eigenstate operator label. Returns: numpy.array: A Numpy array for the Pauli eigenstate. Allowed inputs and corresponding returned matrices are: 'Xp' : [[1, 1], [1, 1]] / sqrt(2) 'Xm' : [[1, -1], [1, -1]] / sqrt(2) 'Yp' : [[1, -1j], [1j, 1]] / sqrt(2) 'Ym' : [[1, 1j], [-1j, 1]] / sqrt(2) 'Zp' : [[1, 0], [0, 0]] 'Zm' : [[0, 0], [0, 1]] """ res = np.array([]) # Return matrix for allowed label if label == 'Xp': res = np.array([[0.5, 0.5], [0.5, 0.5]], dtype=complex) if label == 'Xm': res = np.array([[0.5, -0.5], [-0.5, 0.5]], dtype=complex) if label == 'Yp': res = np.array([[0.5, -0.5j], [0.5j, 0.5]], dtype=complex) if label == 'Ym': res = np.array([[0.5, 0.5j], [-0.5j, 0.5]], dtype=complex) if label == 'Zp': res = np.array([[1, 0], [0, 0]], dtype=complex) if label == 'Zm': res = np.array([[0, 0], [0, 1]], dtype=complex) return res def pauli_measurement_matrix(label, outcome): """ Return the matrix corresonding to a Pauli measurement outcome. Args: label (str): single-qubit Pauli measurement operator label. outcome (int): measurement outcome. Returns: numpy.array: A Numpy array for measurement outcome operator. Allowed inputs and corresponding returned matrices are: 'X', 0 : [[1, 1], [1, 1]] / sqrt(2) 'X', 1 : [[1, -1], [1, -1]] / sqrt(2) 'Y', 0 : [[1, -1j], [1j, 1]] / sqrt(2) 'Y', 1 : [[1, 1j], [-1j, 1]] / sqrt(2) 'Z', 0 : [[1, 0], [0, 0]] 'Z', 1 : [[0, 0], [0, 1]] """ res = np.array([]) # Return matrix if label == 'X': if outcome in ['0', 0]: res = pauli_preparation_matrix('Xp') if outcome in ['1', 1]: res = pauli_preparation_matrix('Xm') if label == 'Y': if outcome in ['0', 0]: res = pauli_preparation_matrix('Yp') if outcome in ['1', 1]: res = pauli_preparation_matrix('Ym') if label == 'Z': if outcome in ['0', 0]: res = pauli_preparation_matrix('Zp') if outcome in ['1', 1]: res = pauli_preparation_matrix('Zm') return res ########################################################################### # PauliBasis Object ########################################################################### PauliBasis = TomographyBasis('Pauli', measurement=(('X', 'Y', 'Z'), pauli_measurement_circuit, pauli_measurement_matrix), preparation=(('Xp', 'Xm', 'Yp', 'Ym', 'Zp', 'Zm'), pauli_preparation_circuit, pauli_preparation_matrix))
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.visualization.timeline import draw as timeline_draw from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeBoeblingen backend = FakeBoeblingen() ghz = QuantumCircuit(5) ghz.h(0) ghz.cx(0,range(1,5)) circ = transpile(ghz, backend, scheduling_method="asap") timeline_draw(circ)
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
mmetcalf14
# -*- 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. """Controlled rotation for the HHL algorithm based on partial table lookup""" import itertools import logging import numpy as np from qiskit import QuantumRegister, QuantumCircuit from qiskit.aqua.components.reciprocals import Reciprocal from qiskit.aqua.circuits.gates import mct logger = logging.getLogger(__name__) class LookupRotation(Reciprocal): """The Lookup Rotation for Reciprocals. A calculation of reciprocals of eigenvalues is performed and controlled rotation of ancillary qubit via a lookup method. It uses a partial table lookup of rotation angles to rotate an ancillary qubit by arcsin(C/lambda). Please refer to the HHL documentation for an explanation of this method. """ CONFIGURATION = { 'name': 'Lookup', 'description': 'approximate inversion for HHL based on table lookup', 'input_schema': { '$schema': 'http://json-schema.org/schema#', 'id': 'reciprocal_lookup_schema', 'type': 'object', 'properties': { 'pat_length': { 'type': ['integer', 'null'], 'default': None, }, 'subpat_length': { 'type': ['integer', 'null'], 'default': None, }, 'negative_evals': { 'type': 'boolean', 'default': False }, 'scale': { 'type': 'number', 'default': 0, 'minimum': 0, 'maximum': 1, }, 'evo_time': { 'type': ['number', 'null'], 'default': None }, 'lambda_min': { 'type': ['number', 'null'], 'default': None } }, 'additionalProperties': False }, } def __init__( self, pat_length=None, subpat_length=None, scale=0, negative_evals=False, evo_time=None, lambda_min=None ): """Constructor. Args: pat_length (int, optional): the number of qubits used for binning pattern subpat_length (int, optional): the number of qubits used for binning sub-pattern scale (float, optional): the scale of rotation angle, corresponds to HHL constant C negative_evals (bool, optional): indicate if negative eigenvalues need to be handled evo_time (float, optional): the evolution time lambda_min (float, optional): the smallest expected eigenvalue """ self.validate(locals()) super().__init__() self._pat_length = pat_length self._subpat_length = subpat_length self._negative_evals = negative_evals self._scale = scale self._evo_time = evo_time self._lambda_min = lambda_min self._anc = None self._workq = None self._msq = None self._ev = None self._circuit = None self._reg_size = 0 def sv_to_resvec(self, statevector, num_q): half = int(len(statevector) / 2) vec = statevector[half:half + 2 ** num_q] return vec def _classic_approx(k, n, m, negative_evals=False): """Approximate arcsin(1/x) for controlled-rotation. This method calculates the binning of arcsin(1/x) function using k bits fixed point numbers and n bit accuracy. Args: k (int): register length n (int): num bits following most-significant qubit taken into account m (int): length of sub string of n-qubit pattern negative_evals (bool): flag for using first qubit as sign bit Returns: Dictionary containing values of approximated and binned values. """ def bin_to_num(binary): """Convert to numeric""" num = np.sum([2 ** -(n + 1) for n, i in enumerate(reversed( binary)) if i == '1']) return num def get_est_lamb(pattern, fo, n, k): """Estimate the bin mid point and return the float value""" if fo - n > 0: remainder = sum([2 ** -i for i in range(k - (fo - n - 1), k + 1)]) return bin_to_num(pattern)+remainder/2 return bin_to_num(pattern) from collections import OrderedDict output = OrderedDict() fo = None for fo in range(k - 1, n - 1, -1): # skip first bit if negative ev are used if negative_evals and fo == k - 1: continue # init bit string vec = ['0'] * k # set most significant bit vec[fo] = '1' # iterate over all 2^m combinations = sub string in n-bit pattern for pattern_ in itertools.product('10', repeat=m): app_pattern_array = [] lambda_array = [] fo_array = [] # iterate over all 2^(n-m) combinations for appendpat in itertools.product('10', repeat=n - m): # combine both generated patterns pattern = pattern_ + appendpat vec[fo - n:fo] = pattern # estimate bin mid point e_l = get_est_lamb(vec.copy(), fo, n, k) lambda_array.append(e_l) fo_array.append(fo) app_pattern_array.append(list(reversed(appendpat))) # rewrite first-one to correct index in QuantumRegister fo_pos = k-fo-1 if fo_pos in list(output.keys()): prev_res = output[fo_pos] else: prev_res = [] output.update( {fo_pos: prev_res + [(list(reversed(pattern_)), app_pattern_array, lambda_array)]}) # last iterations, only last n bits != 0 last_fo = fo vec = ['0'] * k for pattern_ in itertools.product('10', repeat=m): app_pattern_array = [] lambda_array = [] fo_array = [] for appendpat in itertools.product('10', repeat=n - m): pattern = list(pattern_ + appendpat).copy() if '1' not in pattern and (not negative_evals): continue elif '1' not in pattern and negative_evals: e_l = 0.5 else: vec[last_fo - n:last_fo] = list(pattern) e_l = get_est_lamb(vec.copy(), last_fo, n, k) lambda_array.append(e_l) fo_array.append(last_fo - 1) app_pattern_array.append(list(reversed(appendpat))) fo_pos = k-last_fo if fo_pos in list(output.keys()): prev_res = output[fo_pos] else: prev_res = [] output.update({fo_pos: prev_res + [(list(reversed(pattern_)), app_pattern_array, lambda_array)]}) return output def _set_msq(self, msq, ev_reg, fo_pos, last_iteration=False): """Adds multi-controlled NOT gate to entangle |msq> qubit with states having the correct first-one qubit Args: msq (QuantumRegister): most-significant qubit, this is a garbage qubit ev_reg (QuantumRegister): register storing eigenvalues fo_pos (int): position of first-one bit last_iteration (bool): switch which is set for numbers where only the last n bits is different from 0 in the binary string """ qc = self._circuit ev = [ev_reg[i] for i in range(len(ev_reg))] # last_iteration = no MSQ set, only the n-bit long pattern if last_iteration: if fo_pos == 1: qc.x(ev[0]) qc.cx(ev[0], msq[0]) qc.x(ev[0]) elif fo_pos == 2: qc.x(ev[0]) qc.x(ev[1]) qc.ccx(ev[0], ev[1], msq[0]) qc.x(ev[1]) qc.x(ev[0]) elif fo_pos > 2: for idx in range(fo_pos): qc.x(ev[idx]) qc.mct(ev[:fo_pos], msq[0], None, mode='noancilla') for idx in range(fo_pos): qc.x(ev[idx]) else: qc.x(msq[0]) elif fo_pos == 0: qc.cx(ev[0], msq) elif fo_pos == 1: qc.x(ev[0]) qc.ccx(ev[0], ev[1], msq[0]) qc.x(ev[0]) elif fo_pos > 1: for idx in range(fo_pos): qc.x(ev[idx]) qc.mct(ev[:fo_pos + 1], msq[0], None, mode='noancilla') for idx in range(fo_pos): qc.x(ev[idx]) else: raise RuntimeError("first-one register index < 0") def _set_bit_pattern(self, pattern, tgt, offset): """Add multi-controlled NOT gate to circuit that has negated/normal controls according to the pattern specified Args: pattern (list): List of strings giving a bit string that negates controls if '0' tgt (QuantumRegister): target qubit offset (int): start index for the control qubits """ qc = self._circuit for c, i in enumerate(pattern): if i == '0': qc.x(self._ev[int(c + offset)]) if len(pattern) > 2: temp_reg = [self._ev[i] for i in range(offset, offset+len(pattern))] qc.mct(temp_reg, tgt, None, mode='noancilla') elif len(pattern) == 2: qc.ccx(self._ev[offset], self._ev[offset + 1], tgt) elif len(pattern) == 1: qc.cx(self._ev[offset], tgt) for c, i in enumerate(pattern): if i == '0': qc.x(self._ev[int(c + offset)]) def construct_circuit(self, mode, inreg): """Construct the Lookup Rotation circuit. Args: mode (str): consctruction mode, 'matrix' not supported inreg (QuantumRegister): input register, typically output register of Eigenvalues Returns: QuantumCircuit containing the Lookup Rotation circuit. """ # initialize circuit if mode == 'matrix': raise NotImplementedError('The matrix mode is not supported.') if self._lambda_min: self._scale = self._lambda_min/2/np.pi*self._evo_time if self._scale == 0: self._scale = 2**-len(inreg) self._ev = inreg self._workq = QuantumRegister(1, 'work') self._msq = QuantumRegister(1, 'msq') self._anc = QuantumRegister(1, 'anc') qc = QuantumCircuit(self._ev, self._workq, self._msq, self._anc) self._circuit = qc self._reg_size = len(inreg) if self._pat_length is None: if self._reg_size <= 6: self._pat_length = self._reg_size - \ (2 if self._negative_evals else 1) else: self._pat_length = 5 if self._reg_size <= self._pat_length: self._pat_length = self._reg_size - \ (2 if self._negative_evals else 1) if self._subpat_length is None: self._subpat_length = int(np.ceil(self._pat_length/2)) m = self._subpat_length n = self._pat_length k = self._reg_size neg_evals = self._negative_evals # get classically precomputed eigenvalue binning approx_dict = LookupRotation._classic_approx(k, n, m, negative_evals=neg_evals) fo = None old_fo = None # for negative EV, we pass a pseudo register ev[1:] ign. sign bit ev = [self._ev[i] for i in range(len(self._ev))] for _, fo in enumerate(list(approx_dict.keys())): # read m-bit and (n-m) bit patterns for current first-one and # correct Lambdas pattern_map = approx_dict[fo] # set most-significant-qbit register and uncompute previous if self._negative_evals: if old_fo != fo: if old_fo is not None: self._set_msq(self._msq, ev[1:], int(old_fo - 1)) old_fo = fo if fo + n == k: self._set_msq(self._msq, ev[1:], int(fo - 1), last_iteration=True) else: self._set_msq(self._msq, ev[1:], int(fo - 1), last_iteration=False) else: if old_fo != fo: if old_fo is not None: self._set_msq(self._msq, self._ev, int(old_fo)) old_fo = fo if fo + n == k: self._set_msq(self._msq, self._ev, int(fo), last_iteration=True) else: self._set_msq(self._msq, self._ev, int(fo), last_iteration=False) # offset = start idx for ncx gate setting and unsetting m-bit # long bitstring offset_mpat = fo + (n - m) if fo < k - n else fo + n - m - 1 for mainpat, subpat, lambda_ar in pattern_map: # set m-bit pattern in register workq self._set_bit_pattern(mainpat, self._workq[0], offset_mpat + 1) # iterate of all 2**(n-m) combinations for fixed m-bit for subpattern, lambda_ in zip(subpat, lambda_ar): # calculate rotation angle theta = 2*np.arcsin(min(1, self._scale / lambda_)) # offset for ncx gate checking subpattern offset = fo + 1 if fo < k - n else fo # rotation is happening here # 1. rotate by half angle qc.mcu3(theta / 2, 0, 0, [self._workq[0], self._msq[0]], self._anc[0]) # 2. mct gate to reverse rotation direction self._set_bit_pattern(subpattern, self._anc[0], offset) # 3. rotate by inverse of halfangle to uncompute / complete qc.mcu3(-theta / 2, 0, 0, [self._workq[0], self._msq[0]], self._anc[0]) # 4. mct gate to uncompute first mct gate self._set_bit_pattern(subpattern, self._anc[0], offset) # uncompute m-bit pattern self._set_bit_pattern(mainpat, self._workq[0], offset_mpat + 1) last_fo = fo # uncompute msq register if self._negative_evals: self._set_msq(self._msq, ev[1:], int(last_fo - 1), last_iteration=True) else: self._set_msq(self._msq, self._ev, int(last_fo), last_iteration=True) # rotate by pi to fix sign for negative evals if self._negative_evals: qc.cu3(2*np.pi, 0, 0, self._ev[0], self._anc[0]) self._circuit = qc return self._circuit
https://github.com/mcoggins96/Quantum-Computing-UK-Repository
mcoggins96
import math from qiskit import * from utils import bcolors, executeQFT, evolveQFTStateSum, inverseQFT pie = math.pi def sum(a, b, qc): n = len(a)-1 # Compute the Fourier transform of register a for i in range(n+1): executeQFT(qc, a, n-i, pie) # Add the two numbers by evolving the Fourier transform F(ψ(reg_a))> # to |F(ψ(reg_a+reg_b))> for i in range(n+1): evolveQFTStateSum(qc, a, b, n-i, pie) # Compute the inverse Fourier transform of register a for i in range(n+1): inverseQFT(qc, a, i, pie)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile, schedule from qiskit.visualization.timeline import draw, IQXSimple from qiskit.providers.fake_provider import FakeBoeblingen qc = QuantumCircuit(2) qc.h(0) qc.cx(0,1) qc = transpile(qc, FakeBoeblingen(), scheduling_method='alap', layout_method='trivial') draw(qc, style=IQXSimple())
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.wrapper import available_backends, get_backend from qiskit.wrapper import execute as q_execute q = QuantumRegister(2, name='q') c = ClassicalRegister(2, name='c') qc = QuantumCircuit(q,c) qc.h(q[0]) qc.h(q[1]) qc.cx(q[0], q[1]) qc.measure(q, c) z = 0.995004165 + 1j * 0.099833417 z = z / abs(z) u_error = np.array([[1, 0], [0, z]]) noise_params = {'U': {'gate_time': 1, 'p_depol': 0.001, 'p_pauli': [0, 0, 0.01], 'U_error': u_error } } config = {"noise_params": noise_params} ret = q_execute(qc, 'local_qasm_simulator_cpp', shots=1024, config=config) ret = ret.result() print(ret.get_counts())
https://github.com/peiyong-addwater/Hackathon-QNLP
peiyong-addwater
import collections import pickle import warnings warnings.filterwarnings("ignore") import os from random import shuffle import random from discopy.tensor import Tensor from discopy import Word from discopy.rigid import Functor from discopy import grammar import seaborn as sns import pandas as pd import matplotlib.pyplot as plt from jax import numpy as np import numpy from lambeq import AtomicType, IQPAnsatz, remove_cups, NumpyModel, spiders_reader from lambeq import BobcatParser, TreeReader, cups_reader, DepCCGParser, TreeReaderMode from lambeq import Dataset from lambeq import QuantumTrainer, SPSAOptimizer from lambeq import TketModel from lambeq import Rewriter from pytket.extensions.qiskit import AerBackend import seaborn as sns import matplotlib.pyplot as plt from pytket.circuit.display import render_circuit_jupyter pd.set_option('display.width', 1000) pd.options.display.max_colwidth=80 print(os.getcwd()) warnings.filterwarnings("ignore") os.environ["TOKENIZERS_PARALLELISM"] = "false" BATCH_SIZE = 50 EPOCHS = 200 SEED = 0 TRAIN_INDEX_RATIO = 0.08 VAL_INDEX_RATIO = TRAIN_INDEX_RATIO + 0.01 TEST_INDEX_RATIO = VAL_INDEX_RATIO + 0.01 assert TEST_INDEX_RATIO <= 1 def load_pickled_dict_to_df(filename): saved_dict = pickle.load(open(filename, 'rb')) df = pd.DataFrame.from_dict(saved_dict) df = df.sample(frac=1, random_state=SEED).reset_index(drop=True) sentiment = [] for i in df['target']: if i == "Positive": sentiment.append(1) else: sentiment.append(0) df["Sentiment"] = sentiment return df cleaned_qnlp_filename = os.path.join(os.getcwd(), 'cleaned_qnlp_data.pkl') cleaned_lemmatized_qnlp_filename = os.path.join(os.getcwd(), 'cleaned_qnlp_data_lematize.pkl') cleaned_lemmatized_stemmed_qnlp_filename = os.path.join(os.getcwd(), 'cleaned_qnlp_data_stem_lematize.pkl') cleaned_qnlp = load_pickled_dict_to_df(cleaned_qnlp_filename) cleaned_lemmatized_qnlp = load_pickled_dict_to_df(cleaned_lemmatized_qnlp_filename) cleaned__lemmatized_stemmed_qnlp = load_pickled_dict_to_df(cleaned_lemmatized_stemmed_qnlp_filename) cleaned_qnlp.head(10) cleaned_qnlp.info() sns.countplot(x = "target", data = cleaned_qnlp) cleaned_lemmatized_qnlp.head(10) cleaned_lemmatized_qnlp.info() sns.countplot(x='target', data = cleaned_lemmatized_qnlp) cleaned__lemmatized_stemmed_qnlp.head(10) cleaned__lemmatized_stemmed_qnlp.info() sns.countplot(x='target', data = cleaned__lemmatized_stemmed_qnlp) # parser = BobcatParser(verbose='text') # parser = DepCCGParser(root_cats=['S[dcl]']) # parser = spiders_reader parser = TreeReader(mode=TreeReaderMode.RULE_TYPE) NUM_DATA = 2578 loss = lambda y_hat, y: -np.sum(y * np.log(y_hat)) / len(y) # binary cross-entropy loss acc = lambda y_hat, y: np.sum(np.round(y_hat) == y) / len(y) / 2 # half due to double-counting rewriter = Rewriter(['prepositional_phrase', 'determiner', 'auxiliary', 'connector', 'coordination', 'object_rel_pronoun', 'subject_rel_pronoun', 'postadverb', 'preadverb']) def rewrite(diagram): # diagram = rewriter(diagram) return remove_cups(diagram) def create_diagrams_and_labels(total_df, NUM_DATA = 2578): total_text = total_df['data'].tolist() total_labels = total_df["Sentiment"].tolist() total_labels = [[t, 1-t] for t in total_labels] # [1, 0] for positive, [0, 1] for negative train_diagrams = parser.sentences2diagrams(total_text[:round(NUM_DATA*TRAIN_INDEX_RATIO)]) train_labels = total_labels[:round(NUM_DATA*TRAIN_INDEX_RATIO)] dev_diagrams = parser.sentences2diagrams(total_text[round(NUM_DATA*TRAIN_INDEX_RATIO):round(NUM_DATA*VAL_INDEX_RATIO)]) dev_labels = total_labels[round(NUM_DATA*TRAIN_INDEX_RATIO):round(NUM_DATA*VAL_INDEX_RATIO)] test_diagrams = parser.sentences2diagrams(total_text[round(NUM_DATA*VAL_INDEX_RATIO):round(NUM_DATA*TEST_INDEX_RATIO)]) test_labels = total_labels[round(NUM_DATA*VAL_INDEX_RATIO):round(NUM_DATA*TEST_INDEX_RATIO)] return train_diagrams, train_labels, dev_diagrams, dev_labels, test_diagrams, test_labels data = cleaned__lemmatized_stemmed_qnlp raw_train_diagrams_1, train_labels_1, raw_dev_diagrams_1, dev_labels_1, raw_test_diagrams_1, test_labels_1 = create_diagrams_and_labels(data) print(len(raw_train_diagrams_1)) raw_train_diagrams_1[0].draw(figsize=(12,3)) train_diagrams_1 = [rewrite(diagram) for diagram in raw_train_diagrams_1] dev_diagrams_1 = [rewrite(diagram) for diagram in raw_dev_diagrams_1] test_diagrams_1 = [rewrite(diagram) for diagram in raw_test_diagrams_1] train_diagrams_1[0].draw(figsize=(6,5)) alternate_parser = BobcatParser(verbose='text') dig_0 = alternate_parser.sentence2diagram(cleaned__lemmatized_stemmed_qnlp['data'].tolist()[0]) grammar.draw(dig_0, figsize=(14,3), fontsize=12) ansatz_1 = IQPAnsatz({AtomicType.NOUN: 1, AtomicType.SENTENCE: 1, AtomicType.PREPOSITIONAL_PHRASE: 1, AtomicType.NOUN_PHRASE:1, AtomicType.CONJUNCTION:1}, n_layers=1, n_single_qubit_params=3) train_circuits_1 = [ansatz_1(diagram) for diagram in train_diagrams_1] dev_circuits_1 = [ansatz_1(diagram) for diagram in dev_diagrams_1] test_circuits_1 = [ansatz_1(diagram) for diagram in test_diagrams_1] train_circuits_1[0].draw(figsize=(9, 12)) # train_circuits_1[0].draw(figsize=(9, 12)) render_circuit_jupyter(train_circuits_1[0].to_tk()) [(s, s.size) for s in train_circuits_1[0].free_symbols] all_circuits_1 = train_circuits_1 + dev_circuits_1 + test_circuits_1 model_1 = NumpyModel.from_diagrams(all_circuits_1, use_jit=True) # model_1 = TketModel.from_diagrams(all_circuits_1, backend_config=backend_config) trainer_1 = QuantumTrainer( model_1, loss_function=loss, epochs=EPOCHS, optimizer=SPSAOptimizer, optim_hyperparams={'a': 0.2, 'c': 0.06, 'A':0.01*EPOCHS}, evaluate_functions={'acc': acc}, evaluate_on_train=True, verbose = 'text', seed=0 ) train_dataset_1 = Dataset( train_circuits_1, train_labels_1, batch_size=BATCH_SIZE) val_dataset_1 = Dataset(dev_circuits_1, dev_labels_1, shuffle=False) trainer_1.fit(train_dataset_1, val_dataset_1, logging_step=1) fig, ((ax_tl, ax_tr), (ax_bl, ax_br)) = plt.subplots(2, 2, sharex=True, sharey='row', figsize=(12, 8)) ax_tl.set_title('Training set') ax_tr.set_title('Development set') ax_bl.set_xlabel('Iterations') ax_br.set_xlabel('Iterations') ax_bl.set_ylabel('Accuracy') ax_tl.set_ylabel('Loss') colours = iter(plt.rcParams['axes.prop_cycle'].by_key()['color']) ax_tl.plot(trainer_1.train_epoch_costs, color=next(colours)) ax_bl.plot(trainer_1.train_results['acc'], color=next(colours)) ax_tr.plot(trainer_1.val_costs, color=next(colours)) ax_br.plot(trainer_1.val_results['acc'], color=next(colours)) data = cleaned_lemmatized_qnlp raw_train_diagrams_1, train_labels_1, raw_dev_diagrams_1, dev_labels_1, raw_test_diagrams_1, test_labels_1 = create_diagrams_and_labels(data) print(len(raw_train_diagrams_1)) raw_train_diagrams_1[0].draw(figsize=(12,3)) train_diagrams_1 = [rewrite(diagram) for diagram in raw_train_diagrams_1] dev_diagrams_1 = [rewrite(diagram) for diagram in raw_dev_diagrams_1] test_diagrams_1 = [rewrite(diagram) for diagram in raw_test_diagrams_1] train_diagrams_1[0].draw(figsize=(6,5)) ansatz_1 = IQPAnsatz({AtomicType.NOUN: 1, AtomicType.SENTENCE: 1, AtomicType.PREPOSITIONAL_PHRASE: 1, AtomicType.NOUN_PHRASE:1, AtomicType.CONJUNCTION:1}, n_layers=1, n_single_qubit_params=3) train_circuits_1 = [ansatz_1(diagram) for diagram in train_diagrams_1] dev_circuits_1 = [ansatz_1(diagram) for diagram in dev_diagrams_1] test_circuits_1 = [ansatz_1(diagram) for diagram in test_diagrams_1] train_circuits_1[0].draw(figsize=(9, 12)) render_circuit_jupyter(train_circuits_1[0].to_tk()) all_circuits_1 = train_circuits_1 + dev_circuits_1 + test_circuits_1 model_1 = NumpyModel.from_diagrams(all_circuits_1, use_jit=True) trainer_1 = QuantumTrainer( model_1, loss_function=loss, epochs=EPOCHS, optimizer=SPSAOptimizer, optim_hyperparams={'a': 0.2, 'c': 0.06, 'A':0.01*EPOCHS}, evaluate_functions={'acc': acc}, evaluate_on_train=True, verbose = 'text', seed=0 ) train_dataset_1 = Dataset( train_circuits_1, train_labels_1, batch_size=BATCH_SIZE) val_dataset_1 = Dataset(dev_circuits_1, dev_labels_1, shuffle=False) trainer_1.fit(train_dataset_1, val_dataset_1, logging_step=1) fig, ((ax_tl, ax_tr), (ax_bl, ax_br)) = plt.subplots(2, 2, sharex=True, sharey='row', figsize=(12, 8)) ax_tl.set_title('Training set') ax_tr.set_title('Development set') ax_bl.set_xlabel('Iterations') ax_br.set_xlabel('Iterations') ax_bl.set_ylabel('Accuracy') ax_tl.set_ylabel('Loss') colours = iter(plt.rcParams['axes.prop_cycle'].by_key()['color']) ax_tl.plot(trainer_1.train_epoch_costs, color=next(colours)) ax_bl.plot(trainer_1.train_results['acc'], color=next(colours)) ax_tr.plot(trainer_1.val_costs, color=next(colours)) ax_br.plot(trainer_1.val_results['acc'], color=next(colours)) data = cleaned_qnlp raw_train_diagrams_1, train_labels_1, raw_dev_diagrams_1, dev_labels_1, raw_test_diagrams_1, test_labels_1 = create_diagrams_and_labels(data) print(len(raw_train_diagrams_1)) raw_train_diagrams_1[0].draw(figsize=(12,3)) train_diagrams_1 = [rewrite(diagram) for diagram in raw_train_diagrams_1] dev_diagrams_1 = [rewrite(diagram) for diagram in raw_dev_diagrams_1] test_diagrams_1 = [rewrite(diagram) for diagram in raw_test_diagrams_1] train_diagrams_1[0].draw(figsize=(6,5)) render_circuit_jupyter(train_circuits_1[0].to_tk()) all_circuits_1 = train_circuits_1 + dev_circuits_1 + test_circuits_1 model_1 = NumpyModel.from_diagrams(all_circuits_1, use_jit=True) trainer_1 = QuantumTrainer( model_1, loss_function=loss, epochs=EPOCHS, optimizer=SPSAOptimizer, optim_hyperparams={'a': 0.2, 'c': 0.06, 'A':0.01*EPOCHS}, evaluate_functions={'acc': acc}, evaluate_on_train=True, verbose = 'text', seed=0 ) train_dataset_1 = Dataset( train_circuits_1, train_labels_1, batch_size=BATCH_SIZE) val_dataset_1 = Dataset(dev_circuits_1, dev_labels_1, shuffle=False) trainer_1.fit(train_dataset_1, val_dataset_1, logging_step=1) fig, ((ax_tl, ax_tr), (ax_bl, ax_br)) = plt.subplots(2, 2, sharex=True, sharey='row', figsize=(12, 8)) ax_tl.set_title('Training set') ax_tr.set_title('Development set') ax_bl.set_xlabel('Iterations') ax_br.set_xlabel('Iterations') ax_bl.set_ylabel('Accuracy') ax_tl.set_ylabel('Loss') colours = iter(plt.rcParams['axes.prop_cycle'].by_key()['color']) ax_tl.plot(trainer_1.train_epoch_costs, color=next(colours)) ax_bl.plot(trainer_1.train_results['acc'], color=next(colours)) ax_tr.plot(trainer_1.val_costs, color=next(colours)) ax_br.plot(trainer_1.val_results['acc'], color=next(colours))
https://github.com/fvarchon/qiskit-intros
fvarchon
# 30 qubits = 16 GB num_qubits = 32 memoryneeded_GB = 16 * 2 ** (num_qubits - 30) print(memoryneeded_GB) # qiskit imports from qiskit import Aer from qiskit import IBMQ, execute from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.tools.visualization import plot_histogram, plot_state_city from qiskit.tools.monitor import job_monitor nqubits = 3 qr = QuantumRegister(nqubits, 'q') cr = ClassicalRegister(nqubits, 'c') GHZ3_circuit = QuantumCircuit(qr, cr) GHZ3_circuit.h(qr[0]) GHZ3_circuit.cx(qr[0], qr[1]) GHZ3_circuit.cx(qr[1], qr[2]) GHZ3_circuit.barrier(qr) GHZ3_circuit.measure(qr, cr) GHZ3_circuit.draw(output = 'mpl') # Select the QasmSimulator from the Aer provider simulator = Aer.get_backend('qasm_simulator') # Execute and get counts result = execute(GHZ3_circuit, simulator, shots=2048).result() counts = result.get_counts(GHZ3_circuit) print(counts) plot_histogram(counts, title='Ideal counts for 3-qubit GHZ state') # Execute and get memory result = execute(GHZ3_circuit, simulator, shots=10, memory=True).result() memory = result.get_memory(GHZ3_circuit) print(memory) IBMQ.load_accounts() IBMQ.backends() device = IBMQ.get_backend('ibmq_16_melbourne') job_device = execute(GHZ3_circuit, backend=device, shots=1024) job_monitor(job_device) result_device = job_device.result(timeout = 1800) counts_device = result_device.get_counts(GHZ3_circuit) plot_histogram(counts_device, title="Counts for 3-qubit GHZ state with a real device") from qiskit.providers.aer import noise device = IBMQ.get_backend('ibmq_16_melbourne') properties = device.properties() coupling_map = device.configuration().coupling_map print(properties) for qubit in properties.qubits: print(qubit) print('\n'.join(qubitprop.name + "=" + str(qubitprop.value) + " " + qubitprop.unit for qubitprop in qubit)) print() for gate in properties.gates: print('Gate = {}, Relevant Qubits = {}, Error = {}'.format( gate.gate, gate.qubits, gate.parameters[0].value, gate.parameters[0].unit )) print(coupling_map) import graphviz coupling_graph = graphviz.Graph() for edge in coupling_map: coupling_graph.edge('q'+str(edge[0]), 'q'+str(edge[1])) coupling_graph # List of gate times for ibmq_16_melbourne device # Note that the None parameter for u1, u2, u3 is because gate # times are the same for all qubits # Erick Winston gate_times = [ ('u1', None, 0), ('u2', None, 100), ('u3', None, 200), ('cx', [1, 0], 678), ('cx', [1, 2], 547), ('cx', [2, 3], 721), ('cx', [4, 3], 733), ('cx', [4, 10], 721), ('cx', [5, 4], 800), ('cx', [5, 6], 800), ('cx', [5, 9], 895), ('cx', [6, 8], 895), ('cx', [7, 8], 640), ('cx', [9, 8], 895), ('cx', [9, 10], 800), ('cx', [11, 10], 721), ('cx', [11, 3], 634), ('cx', [12, 2], 773), ('cx', [13, 1], 2286), ('cx', [13, 12], 1504), ('cx', [], 800) ] # Construct the noise model from backend properties # and custom gate times #noise_model = noise.device.basic_device_noise_model(properties, gate_times=gate_times) noise_model = noise.device.basic_device_noise_model(properties, gate_times = gate_times, temperature=10) print(noise_model) help(noise.device.basic_device_noise_model) # Get the basis gates for the noise model basis_gates = noise_model.basis_gates # Select the QasmSimulator from the Aer provider simulator = Aer.get_backend('qasm_simulator') # Execute noisy simulation and get corunts job_noise = execute(GHZ3_circuit, simulator, noise_model=noise_model, coupling_map=coupling_map, basis_gates=basis_gates) result_noise = job_noise.result() counts_noise = result_noise.get_counts(GHZ3_circuit) plot_histogram(counts_noise, title="Counts for 3-qubit GHZ state with a simulation containing depolarizing noise model") nqubits = 3 qr = QuantumRegister(nqubits, 'q') cr = ClassicalRegister(nqubits, 'c') GHZ3_circuit = QuantumCircuit(qr, cr) GHZ3_circuit.h(qr[0]) GHZ3_circuit.cx(qr[0], qr[1]) GHZ3_circuit.cx(qr[1], qr[2]) GHZ3_circuit.barrier(qr) #GHZ3_circuit.measure(qr, cr) GHZ3_circuit.draw(output = 'mpl') simulator = Aer.get_backend('statevector_simulator') # Execute and get counts result = execute(GHZ3_circuit, simulator).result() finalstate = result.get_statevector(GHZ3_circuit) print(finalstate) print() for statecoeff, statenum in zip(finalstate, range(2**len(qr))): print("({}) * |{}>".format(statecoeff, statenum)) plot_state_city(finalstate, title='3-qubit GHZ state') nqubits = 2 qr = QuantumRegister(nqubits, 'q') cz1 = QuantumCircuit(qr) cz1.h(qr[1]) cz1.cx(qr[0], qr[1]) cz1.h(qr[1]) cz1.draw(output = 'mpl') # Select the UnitarySimulator from the Aer provider simulator = Aer.get_backend('unitary_simulator') # Execute and get counts job_sim = execute(cz1, simulator) result = job_sim.result() unitary = result.get_unitary(cz1) print("Final Unitary:") print(unitary) nqubits = 2 qr = QuantumRegister(nqubits, 'q') cz2 = QuantumCircuit(qr) cz2.cz(qr[0], qr[1]) cz2.draw(output = 'mpl') # Select the UnitarySimulator from the Aer provider simulator = Aer.get_backend('unitary_simulator') # Execute and get counts job_sim = execute(cz2, simulator) result = job_sim.result() unitary = result.get_unitary(cz2) print("Final Unitary:") print(unitary)
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2023 # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring import io import math import os import pathlib import pickle import shutil import tempfile import unittest import ddt import qiskit.qasm2 from qiskit import qpy from qiskit.circuit import ( ClassicalRegister, Gate, Parameter, QuantumCircuit, QuantumRegister, Qubit, library as lib, ) from qiskit.test import QiskitTestCase from . import gate_builder class TestEmpty(QiskitTestCase): def test_allows_empty(self): self.assertEqual(qiskit.qasm2.loads(""), QuantumCircuit()) class TestVersion(QiskitTestCase): def test_complete_version(self): program = "OPENQASM 2.0;" parsed = qiskit.qasm2.loads(program) self.assertEqual(parsed, QuantumCircuit()) def test_incomplete_version(self): program = "OPENQASM 2;" parsed = qiskit.qasm2.loads(program) self.assertEqual(parsed, QuantumCircuit()) def test_after_comment(self): program = """ // hello, world OPENQASM 2.0; qreg q[2]; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(2, "q")) self.assertEqual(parsed, qc) class TestRegisters(QiskitTestCase): def test_qreg(self): program = "qreg q1[2]; qreg q2[1]; qreg q3[4];" parsed = qiskit.qasm2.loads(program) regs = [QuantumRegister(2, "q1"), QuantumRegister(1, "q2"), QuantumRegister(4, "q3")] self.assertEqual(list(parsed.qregs), regs) self.assertEqual(list(parsed.cregs), []) def test_creg(self): program = "creg c1[2]; creg c2[1]; creg c3[4];" parsed = qiskit.qasm2.loads(program) regs = [ClassicalRegister(2, "c1"), ClassicalRegister(1, "c2"), ClassicalRegister(4, "c3")] self.assertEqual(list(parsed.cregs), regs) self.assertEqual(list(parsed.qregs), []) def test_interleaved_registers(self): program = "qreg q1[3]; creg c1[2]; qreg q2[1]; creg c2[1];" parsed = qiskit.qasm2.loads(program) qregs = [QuantumRegister(3, "q1"), QuantumRegister(1, "q2")] cregs = [ClassicalRegister(2, "c1"), ClassicalRegister(1, "c2")] self.assertEqual(list(parsed.qregs), qregs) self.assertEqual(list(parsed.cregs), cregs) def test_registers_after_gate(self): program = "qreg before[2]; CX before[0], before[1]; qreg after[2]; CX after[0], after[1];" parsed = qiskit.qasm2.loads(program) before = QuantumRegister(2, "before") after = QuantumRegister(2, "after") qc = QuantumCircuit(before, after) qc.cx(before[0], before[1]) qc.cx(after[0], after[1]) self.assertEqual(parsed, qc) def test_empty_registers(self): program = "qreg q[0]; creg c[0];" parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(0, "q"), ClassicalRegister(0, "c")) self.assertEqual(parsed, qc) @ddt.ddt class TestGateApplication(QiskitTestCase): def test_builtin_single(self): program = """ qreg q[2]; U(0, 0, 0) q[0]; CX q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.u(0, 0, 0, 0) qc.cx(0, 1) self.assertEqual(parsed, qc) def test_builtin_1q_broadcast(self): program = "qreg q[2]; U(0, 0, 0) q;" parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.u(0, 0, 0, 0) qc.u(0, 0, 0, 1) self.assertEqual(parsed, qc) def test_builtin_2q_broadcast(self): program = """ qreg q1[2]; qreg q2[2]; CX q1[0], q2; barrier; CX q1, q2[1]; barrier; CX q1, q2; """ parsed = qiskit.qasm2.loads(program) q1 = QuantumRegister(2, "q1") q2 = QuantumRegister(2, "q2") qc = QuantumCircuit(q1, q2) qc.cx(q1[0], q2[0]) qc.cx(q1[0], q2[1]) qc.barrier() qc.cx(q1[0], q2[1]) qc.cx(q1[1], q2[1]) qc.barrier() qc.cx(q1[0], q2[0]) qc.cx(q1[1], q2[1]) self.assertEqual(parsed, qc) def test_3q_broadcast(self): program = """ include "qelib1.inc"; qreg q1[2]; qreg q2[2]; qreg q3[2]; ccx q1, q2[0], q3[1]; ccx q1[1], q2, q3[0]; ccx q1[0], q2[1], q3; barrier; ccx q1, q2, q3[1]; ccx q1[1], q2, q3; ccx q1, q2[1], q3; barrier; ccx q1, q2, q3; """ parsed = qiskit.qasm2.loads(program) q1 = QuantumRegister(2, "q1") q2 = QuantumRegister(2, "q2") q3 = QuantumRegister(2, "q3") qc = QuantumCircuit(q1, q2, q3) qc.ccx(q1[0], q2[0], q3[1]) qc.ccx(q1[1], q2[0], q3[1]) qc.ccx(q1[1], q2[0], q3[0]) qc.ccx(q1[1], q2[1], q3[0]) qc.ccx(q1[0], q2[1], q3[0]) qc.ccx(q1[0], q2[1], q3[1]) qc.barrier() qc.ccx(q1[0], q2[0], q3[1]) qc.ccx(q1[1], q2[1], q3[1]) qc.ccx(q1[1], q2[0], q3[0]) qc.ccx(q1[1], q2[1], q3[1]) qc.ccx(q1[0], q2[1], q3[0]) qc.ccx(q1[1], q2[1], q3[1]) qc.barrier() qc.ccx(q1[0], q2[0], q3[0]) qc.ccx(q1[1], q2[1], q3[1]) self.assertEqual(parsed, qc) @ddt.data(True, False) def test_broadcast_against_empty_register(self, conditioned): cond = "if (cond == 0) " if conditioned else "" program = f""" OPENQASM 2; include "qelib1.inc"; qreg q1[1]; qreg q2[1]; qreg empty1[0]; qreg empty2[0]; qreg empty3[0]; creg cond[1]; // None of the following statements should produce any gate applications. {cond}h empty1; {cond}cx q1[0], empty1; {cond}cx empty1, q2[0]; {cond}cx empty1, empty2; {cond}ccx empty1, q1[0], q2[0]; {cond}ccx q1[0], empty2, q2[0]; {cond}ccx q1[0], q2[0], empty3; {cond}ccx empty1, empty2, q1[0]; {cond}ccx empty1, q1[0], empty2; {cond}ccx q1[0], empty1, empty2; {cond}ccx empty1, empty2, empty3; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit( QuantumRegister(1, "q1"), QuantumRegister(1, "q2"), QuantumRegister(0, "empty1"), QuantumRegister(0, "empty2"), QuantumRegister(0, "empty3"), ClassicalRegister(1, "cond"), ) self.assertEqual(parsed, qc) def test_conditioned(self): program = """ qreg q[2]; creg cond[1]; if (cond == 0) U(0, 0, 0) q[0]; if (cond == 1) CX q[1], q[0]; """ parsed = qiskit.qasm2.loads(program) cond = ClassicalRegister(1, "cond") qc = QuantumCircuit(QuantumRegister(2, "q"), cond) qc.u(0, 0, 0, 0).c_if(cond, 0) qc.cx(1, 0).c_if(cond, 1) self.assertEqual(parsed, qc) def test_conditioned_broadcast(self): program = """ qreg q1[2]; qreg q2[2]; creg cond[1]; if (cond == 0) U(0, 0, 0) q1; if (cond == 1) CX q1[0], q2; """ parsed = qiskit.qasm2.loads(program) cond = ClassicalRegister(1, "cond") q1 = QuantumRegister(2, "q1") q2 = QuantumRegister(2, "q2") qc = QuantumCircuit(q1, q2, cond) qc.u(0, 0, 0, q1[0]).c_if(cond, 0) qc.u(0, 0, 0, q1[1]).c_if(cond, 0) qc.cx(q1[0], q2[0]).c_if(cond, 1) qc.cx(q1[0], q2[1]).c_if(cond, 1) self.assertEqual(parsed, qc) def test_constant_folding(self): # Most expression-related things are tested in `test_expression.py` instead. program = """ qreg q[1]; U(4 + 3 * 2 ^ 2, cos(pi) * (1 - ln(1)), 2 ^ 3 ^ 2) q[0]; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.u(16.0, -1.0, 512.0, 0) self.assertEqual(parsed, qc) def test_call_defined_gate(self): program = """ gate my_gate a { U(0, 0, 0) a; } qreg q[2]; my_gate q[0]; my_gate q; """ parsed = qiskit.qasm2.loads(program) my_gate_def = QuantumCircuit([Qubit()]) my_gate_def.u(0, 0, 0, 0) my_gate = gate_builder("my_gate", [], my_gate_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(my_gate(), [0]) qc.append(my_gate(), [0]) qc.append(my_gate(), [1]) self.assertEqual(parsed, qc) def test_parameterless_gates_accept_parentheses(self): program = """ qreg q[2]; CX q[0], q[1]; CX() q[1], q[0]; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.cx(0, 1) qc.cx(1, 0) self.assertEqual(parsed, qc) class TestGateDefinition(QiskitTestCase): def test_simple_definition(self): program = """ gate not_bell a, b { U(0, 0, 0) a; CX a, b; } qreg q[2]; not_bell q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) not_bell_def = QuantumCircuit([Qubit(), Qubit()]) not_bell_def.u(0, 0, 0, 0) not_bell_def.cx(0, 1) not_bell = gate_builder("not_bell", [], not_bell_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(not_bell(), [0, 1]) self.assertEqual(parsed, qc) def test_conditioned(self): program = """ gate not_bell a, b { U(0, 0, 0) a; CX a, b; } qreg q[2]; creg cond[1]; if (cond == 0) not_bell q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) not_bell_def = QuantumCircuit([Qubit(), Qubit()]) not_bell_def.u(0, 0, 0, 0) not_bell_def.cx(0, 1) not_bell = gate_builder("not_bell", [], not_bell_def) cond = ClassicalRegister(1, "cond") qc = QuantumCircuit(QuantumRegister(2, "q"), cond) qc.append(not_bell().c_if(cond, 0), [0, 1]) self.assertEqual(parsed, qc) def test_constant_folding_in_definition(self): program = """ gate bell a, b { U(pi/2, 0, pi) a; CX a, b; } qreg q[2]; bell q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) bell_def = QuantumCircuit([Qubit(), Qubit()]) bell_def.u(math.pi / 2, 0, math.pi, 0) bell_def.cx(0, 1) bell = gate_builder("bell", [], bell_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(bell(), [0, 1]) self.assertEqual(parsed, qc) def test_parameterised_gate(self): # Most of the tests of deep parameter expressions are in `test_expression.py`. program = """ gate my_gate(a, b) c { U(a, b, a + 2 * b) c; } qreg q[1]; my_gate(0.25, 0.5) q[0]; my_gate(0.5, 0.25) q[0]; """ parsed = qiskit.qasm2.loads(program) a, b = Parameter("a"), Parameter("b") my_gate_def = QuantumCircuit([Qubit()]) my_gate_def.u(a, b, a + 2 * b, 0) my_gate = gate_builder("my_gate", [a, b], my_gate_def) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.append(my_gate(0.25, 0.5), [0]) qc.append(my_gate(0.5, 0.25), [0]) self.assertEqual(parsed, qc) # Also check the decomposition has come out exactly as expected. The floating-point # assertions are safe as exact equality checks because there are no lossy operations with # these parameters, and the answer should be exact. decomposed = qc.decompose() self.assertEqual(decomposed.data[0].operation.name, "u") self.assertEqual(list(decomposed.data[0].operation.params), [0.25, 0.5, 1.25]) self.assertEqual(decomposed.data[1].operation.name, "u") self.assertEqual(list(decomposed.data[1].operation.params), [0.5, 0.25, 1.0]) def test_parameterless_gate_with_parentheses(self): program = """ gate my_gate() a { U(0, 0, 0) a; } qreg q[1]; my_gate q[0]; my_gate() q[0]; """ parsed = qiskit.qasm2.loads(program) my_gate_def = QuantumCircuit([Qubit()]) my_gate_def.u(0, 0, 0, 0) my_gate = gate_builder("my_gate", [], my_gate_def) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.append(my_gate(), [0]) qc.append(my_gate(), [0]) self.assertEqual(parsed, qc) def test_access_includes_in_definition(self): program = """ include "qelib1.inc"; gate bell a, b { h a; cx a, b; } qreg q[2]; bell q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) bell_def = QuantumCircuit([Qubit(), Qubit()]) bell_def.h(0) bell_def.cx(0, 1) bell = gate_builder("bell", [], bell_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(bell(), [0, 1]) self.assertEqual(parsed, qc) def test_access_previous_defined_gate(self): program = """ include "qelib1.inc"; gate bell a, b { h a; cx a, b; } gate second_bell a, b { bell b, a; } qreg q[2]; second_bell q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) bell_def = QuantumCircuit([Qubit(), Qubit()]) bell_def.h(0) bell_def.cx(0, 1) bell = gate_builder("bell", [], bell_def) second_bell_def = QuantumCircuit([Qubit(), Qubit()]) second_bell_def.append(bell(), [1, 0]) second_bell = gate_builder("second_bell", [], second_bell_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(second_bell(), [0, 1]) self.assertEqual(parsed, qc) def test_qubits_lookup_differently_to_gates(self): # The spec is somewhat unclear on this, and this leads to super weird text, but it's # technically unambiguously resolvable and this is more permissive. program = """ include "qelib1.inc"; gate bell h, cx { h h; cx h, cx; } qreg q[2]; bell q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) bell_def = QuantumCircuit([Qubit(), Qubit()]) bell_def.h(0) bell_def.cx(0, 1) bell = gate_builder("bell", [], bell_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(bell(), [0, 1]) self.assertEqual(parsed, qc) def test_parameters_lookup_differently_to_gates(self): # The spec is somewhat unclear on this, and this leads to super weird text, but it's # technically unambiguously resolvable and this is more permissive. program = """ include "qelib1.inc"; gate shadow(rx, rz) a { rz(rz) a; rx(rx) a; } qreg q[1]; shadow(0.5, 2.0) q[0]; """ parsed = qiskit.qasm2.loads(program) rx, rz = Parameter("rx"), Parameter("rz") shadow_def = QuantumCircuit([Qubit()]) shadow_def.rz(rz, 0) shadow_def.rx(rx, 0) shadow = gate_builder("shadow", [rx, rz], shadow_def) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.append(shadow(0.5, 2.0), [0]) self.assertEqual(parsed, qc) def test_unused_parameters_convert_correctly(self): # The main risk here is that there might be lazy application in the gate definition # bindings, and we might accidentally try and bind parameters that aren't actually in the # definition. program = """ gate my_gate(p) q { U(0, 0, 0) q; } qreg q[1]; my_gate(0.5) q[0]; """ parsed = qiskit.qasm2.loads(program) # No top-level circuit equality test here, because all the internals of gate application are # an implementation detail, and we don't want to tie the tests and implementation together # too closely. self.assertEqual(list(parsed.qregs), [QuantumRegister(1, "q")]) self.assertEqual(list(parsed.cregs), []) self.assertEqual(len(parsed.data), 1) self.assertEqual(parsed.data[0].qubits, (parsed.qubits[0],)) self.assertEqual(parsed.data[0].clbits, ()) self.assertEqual(parsed.data[0].operation.name, "my_gate") self.assertEqual(list(parsed.data[0].operation.params), [0.5]) decomposed = QuantumCircuit(QuantumRegister(1, "q")) decomposed.u(0, 0, 0, 0) self.assertEqual(parsed.decompose(), decomposed) def test_qubit_barrier_in_definition(self): program = """ gate my_gate a, b { barrier a; barrier b; barrier a, b; } qreg q[2]; my_gate q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) my_gate_def = QuantumCircuit([Qubit(), Qubit()]) my_gate_def.barrier(0) my_gate_def.barrier(1) my_gate_def.barrier([0, 1]) my_gate = gate_builder("my_gate", [], my_gate_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(my_gate(), [0, 1]) self.assertEqual(parsed, qc) def test_bare_barrier_in_definition(self): program = """ gate my_gate a, b { barrier; } qreg q[2]; my_gate q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) my_gate_def = QuantumCircuit([Qubit(), Qubit()]) my_gate_def.barrier(my_gate_def.qubits) my_gate = gate_builder("my_gate", [], my_gate_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(my_gate(), [0, 1]) self.assertEqual(parsed, qc) def test_duplicate_barrier_in_definition(self): program = """ gate my_gate a, b { barrier a, a; barrier b, a, b; } qreg q[2]; my_gate q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) my_gate_def = QuantumCircuit([Qubit(), Qubit()]) my_gate_def.barrier(0) my_gate_def.barrier([1, 0]) my_gate = gate_builder("my_gate", [], my_gate_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(my_gate(), [0, 1]) self.assertEqual(parsed, qc) def test_pickleable(self): program = """ include "qelib1.inc"; gate my_gate(a) b, c { rz(2 * a) b; h b; cx b, c; } qreg q[2]; my_gate(0.5) q[0], q[1]; my_gate(0.25) q[1], q[0]; """ parsed = qiskit.qasm2.loads(program) a = Parameter("a") my_gate_def = QuantumCircuit([Qubit(), Qubit()]) my_gate_def.rz(2 * a, 0) my_gate_def.h(0) my_gate_def.cx(0, 1) my_gate = gate_builder("my_gate", [a], my_gate_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(my_gate(0.5), [0, 1]) qc.append(my_gate(0.25), [1, 0]) self.assertEqual(parsed, qc) with io.BytesIO() as fptr: pickle.dump(parsed, fptr) fptr.seek(0) loaded = pickle.load(fptr) self.assertEqual(parsed, loaded) def test_qpy_single_call_roundtrip(self): program = """ include "qelib1.inc"; gate my_gate(a) b, c { rz(2 * a) b; h b; cx b, c; } qreg q[2]; my_gate(0.5) q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) # QPY won't persist custom gates by design choice, so instead let us check against the # explicit form it uses. my_gate_def = QuantumCircuit([Qubit(), Qubit()]) my_gate_def.rz(1.0, 0) my_gate_def.h(0) my_gate_def.cx(0, 1) my_gate = Gate("my_gate", 2, [0.5]) my_gate.definition = my_gate_def qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(my_gate, [0, 1]) with io.BytesIO() as fptr: qpy.dump(parsed, fptr) fptr.seek(0) loaded = qpy.load(fptr)[0] self.assertEqual(loaded, qc) # See https://github.com/Qiskit/qiskit-terra/issues/8941 @unittest.expectedFailure def test_qpy_double_call_roundtrip(self): program = """ include "qelib1.inc"; gate my_gate(a) b, c { rz(2 * a) b; h b; cx b, c; } qreg q[2]; my_gate(0.5) q[0], q[1]; my_gate(0.25) q[1], q[0]; """ parsed = qiskit.qasm2.loads(program) my_gate1_def = QuantumCircuit([Qubit(), Qubit()]) my_gate1_def.rz(1.0, 0) my_gate1_def.h(0) my_gate1_def.cx(0, 1) my_gate1 = Gate("my_gate", 2, [0.5]) my_gate1.definition = my_gate1_def my_gate2_def = QuantumCircuit([Qubit(), Qubit()]) my_gate2_def.rz(0.5, 0) my_gate2_def.h(0) my_gate2_def.cx(0, 1) my_gate2 = Gate("my_gate", 2, [0.25]) my_gate2.definition = my_gate2_def qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(my_gate1, [0, 1]) qc.append(my_gate2, [1, 0]) with io.BytesIO() as fptr: qpy.dump(parsed, fptr) fptr.seek(0) loaded = qpy.load(fptr)[0] self.assertEqual(loaded, qc) class TestOpaque(QiskitTestCase): def test_simple(self): program = """ opaque my_gate a; opaque my_gate2() a; qreg q[2]; my_gate q[0]; my_gate() q[1]; my_gate2 q[0]; my_gate2() q[1]; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(Gate("my_gate", 1, []), [0]) qc.append(Gate("my_gate", 1, []), [1]) qc.append(Gate("my_gate2", 1, []), [0]) qc.append(Gate("my_gate2", 1, []), [1]) self.assertEqual(parsed, qc) def test_parameterised(self): program = """ opaque my_gate(a, b) c, d; qreg q[2]; my_gate(0.5, 0.25) q[1], q[0]; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(Gate("my_gate", 2, [0.5, 0.25]), [1, 0]) self.assertEqual(parsed, qc) class TestBarrier(QiskitTestCase): def test_single_register_argument(self): program = """ qreg first[3]; qreg second[3]; barrier first; barrier second; """ parsed = qiskit.qasm2.loads(program) first = QuantumRegister(3, "first") second = QuantumRegister(3, "second") qc = QuantumCircuit(first, second) qc.barrier(first) qc.barrier(second) self.assertEqual(parsed, qc) def test_single_qubit_argument(self): program = """ qreg first[3]; qreg second[3]; barrier first[1]; barrier second[0]; """ parsed = qiskit.qasm2.loads(program) first = QuantumRegister(3, "first") second = QuantumRegister(3, "second") qc = QuantumCircuit(first, second) qc.barrier(first[1]) qc.barrier(second[0]) self.assertEqual(parsed, qc) def test_empty_circuit_empty_arguments(self): program = "barrier;" parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit() self.assertEqual(parsed, qc) def test_one_register_circuit_empty_arguments(self): program = "qreg q1[2]; barrier;" parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(2, "q1")) qc.barrier(qc.qubits) self.assertEqual(parsed, qc) def test_multi_register_circuit_empty_arguments(self): program = "qreg q1[2]; qreg q2[3]; qreg q3[1]; barrier;" parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit( QuantumRegister(2, "q1"), QuantumRegister(3, "q2"), QuantumRegister(1, "q3") ) qc.barrier(qc.qubits) self.assertEqual(parsed, qc) def test_include_empty_register(self): program = """ qreg q[2]; qreg empty[0]; barrier empty; barrier q, empty; barrier; """ parsed = qiskit.qasm2.loads(program) q = QuantumRegister(2, "q") qc = QuantumCircuit(q, QuantumRegister(0, "empty")) qc.barrier(q) qc.barrier(qc.qubits) self.assertEqual(parsed, qc) def test_allows_duplicate_arguments(self): # There's nothing in the paper that implies this should be forbidden. program = """ qreg q1[3]; qreg q2[2]; barrier q1, q1; barrier q1[0], q1; barrier q1, q1[0]; barrier q1, q2, q1; """ parsed = qiskit.qasm2.loads(program) q1 = QuantumRegister(3, "q1") q2 = QuantumRegister(2, "q2") qc = QuantumCircuit(q1, q2) qc.barrier(q1) qc.barrier(q1) qc.barrier(q1) qc.barrier(q1, q2) self.assertEqual(parsed, qc) class TestMeasure(QiskitTestCase): def test_single(self): program = """ qreg q[1]; creg c[1]; measure q[0] -> c[0]; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(1, "q"), ClassicalRegister(1, "c")) qc.measure(0, 0) self.assertEqual(parsed, qc) def test_broadcast(self): program = """ qreg q[2]; creg c[2]; measure q -> c; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(2, "q"), ClassicalRegister(2, "c")) qc.measure(0, 0) qc.measure(1, 1) self.assertEqual(parsed, qc) def test_conditioned(self): program = """ qreg q[2]; creg c[2]; creg cond[1]; if (cond == 0) measure q[0] -> c[0]; if (cond == 1) measure q -> c; """ parsed = qiskit.qasm2.loads(program) cond = ClassicalRegister(1, "cond") qc = QuantumCircuit(QuantumRegister(2, "q"), ClassicalRegister(2, "c"), cond) qc.measure(0, 0).c_if(cond, 0) qc.measure(0, 0).c_if(cond, 1) qc.measure(1, 1).c_if(cond, 1) self.assertEqual(parsed, qc) def test_broadcast_against_empty_register(self): program = """ qreg q_empty[0]; creg c_empty[0]; measure q_empty -> c_empty; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(0, "q_empty"), ClassicalRegister(0, "c_empty")) self.assertEqual(parsed, qc) def test_conditioned_broadcast_against_empty_register(self): program = """ qreg q_empty[0]; creg c_empty[0]; creg cond[1]; if (cond == 0) measure q_empty -> c_empty; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit( QuantumRegister(0, "q_empty"), ClassicalRegister(0, "c_empty"), ClassicalRegister(1, "cond"), ) self.assertEqual(parsed, qc) class TestReset(QiskitTestCase): def test_single(self): program = """ qreg q[1]; reset q[0]; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.reset(0) self.assertEqual(parsed, qc) def test_broadcast(self): program = """ qreg q[2]; reset q; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.reset(0) qc.reset(1) self.assertEqual(parsed, qc) def test_conditioned(self): program = """ qreg q[2]; creg cond[1]; if (cond == 0) reset q[0]; if (cond == 1) reset q; """ parsed = qiskit.qasm2.loads(program) cond = ClassicalRegister(1, "cond") qc = QuantumCircuit(QuantumRegister(2, "q"), cond) qc.reset(0).c_if(cond, 0) qc.reset(0).c_if(cond, 1) qc.reset(1).c_if(cond, 1) self.assertEqual(parsed, qc) def test_broadcast_against_empty_register(self): program = """ qreg empty[0]; reset empty; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(0, "empty")) self.assertEqual(parsed, qc) def test_conditioned_broadcast_against_empty_register(self): program = """ qreg empty[0]; creg cond[1]; if (cond == 0) reset empty; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(0, "empty"), ClassicalRegister(1, "cond")) self.assertEqual(parsed, qc) class TestInclude(QiskitTestCase): def setUp(self): super().setUp() self.tmp_dir = pathlib.Path(tempfile.mkdtemp()) def tearDown(self): # Doesn't really matter if the removal fails, since this was a tempdir anyway; it'll get # cleaned up by the OS at some point. shutil.rmtree(self.tmp_dir, ignore_errors=True) super().tearDown() def test_qelib1_include(self): program = """ include "qelib1.inc"; qreg q[3]; u3(0.5, 0.25, 0.125) q[0]; u2(0.5, 0.25) q[0]; u1(0.5) q[0]; cx q[0], q[1]; id q[0]; x q[0]; y q[0]; z q[0]; h q[0]; s q[0]; sdg q[0]; t q[0]; tdg q[0]; rx(0.5) q[0]; ry(0.5) q[0]; rz(0.5) q[0]; cz q[0], q[1]; cy q[0], q[1]; ch q[0], q[1]; ccx q[0], q[1], q[2]; crz(0.5) q[0], q[1]; cu1(0.5) q[0], q[1]; cu3(0.5, 0.25, 0.125) q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(3, "q")) qc.append(lib.U3Gate(0.5, 0.25, 0.125), [0]) qc.append(lib.U2Gate(0.5, 0.25), [0]) qc.append(lib.U1Gate(0.5), [0]) qc.append(lib.CXGate(), [0, 1]) qc.append(lib.UGate(0, 0, 0), [0]) # Stand-in for id. qc.append(lib.XGate(), [0]) qc.append(lib.YGate(), [0]) qc.append(lib.ZGate(), [0]) qc.append(lib.HGate(), [0]) qc.append(lib.SGate(), [0]) qc.append(lib.SdgGate(), [0]) qc.append(lib.TGate(), [0]) qc.append(lib.TdgGate(), [0]) qc.append(lib.RXGate(0.5), [0]) qc.append(lib.RYGate(0.5), [0]) qc.append(lib.RZGate(0.5), [0]) qc.append(lib.CZGate(), [0, 1]) qc.append(lib.CYGate(), [0, 1]) qc.append(lib.CHGate(), [0, 1]) qc.append(lib.CCXGate(), [0, 1, 2]) qc.append(lib.CRZGate(0.5), [0, 1]) qc.append(lib.CU1Gate(0.5), [0, 1]) qc.append(lib.CU3Gate(0.5, 0.25, 0.125), [0, 1]) self.assertEqual(parsed, qc) def test_qelib1_after_gate_definition(self): program = """ gate bell a, b { U(pi/2, 0, pi) a; CX a, b; } include "qelib1.inc"; qreg q[2]; bell q[0], q[1]; rx(0.5) q[0]; bell q[1], q[0]; """ parsed = qiskit.qasm2.loads(program) bell_def = QuantumCircuit([Qubit(), Qubit()]) bell_def.u(math.pi / 2, 0, math.pi, 0) bell_def.cx(0, 1) bell = gate_builder("bell", [], bell_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(bell(), [0, 1]) qc.rx(0.5, 0) qc.append(bell(), [1, 0]) self.assertEqual(parsed, qc) def test_include_can_define_version(self): include = """ OPENQASM 2.0; qreg inner_q[2]; """ with open(self.tmp_dir / "include.qasm", "w") as fp: fp.write(include) program = """ OPENQASM 2.0; include "include.qasm"; """ parsed = qiskit.qasm2.loads(program, include_path=(self.tmp_dir,)) qc = QuantumCircuit(QuantumRegister(2, "inner_q")) self.assertEqual(parsed, qc) def test_can_define_gates(self): include = """ gate bell a, b { h a; cx a, b; } """ with open(self.tmp_dir / "include.qasm", "w") as fp: fp.write(include) program = """ OPENQASM 2.0; include "qelib1.inc"; include "include.qasm"; qreg q[2]; bell q[0], q[1]; """ parsed = qiskit.qasm2.loads(program, include_path=(self.tmp_dir,)) bell_def = QuantumCircuit([Qubit(), Qubit()]) bell_def.h(0) bell_def.cx(0, 1) bell = gate_builder("bell", [], bell_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(bell(), [0, 1]) self.assertEqual(parsed, qc) def test_nested_include(self): inner = "creg c[2];" with open(self.tmp_dir / "inner.qasm", "w") as fp: fp.write(inner) outer = """ qreg q[2]; include "inner.qasm"; """ with open(self.tmp_dir / "outer.qasm", "w") as fp: fp.write(outer) program = """ OPENQASM 2.0; include "outer.qasm"; """ parsed = qiskit.qasm2.loads(program, include_path=(self.tmp_dir,)) qc = QuantumCircuit(QuantumRegister(2, "q"), ClassicalRegister(2, "c")) self.assertEqual(parsed, qc) def test_first_hit_is_used(self): empty = self.tmp_dir / "empty" empty.mkdir() first = self.tmp_dir / "first" first.mkdir() with open(first / "include.qasm", "w") as fp: fp.write("qreg q[1];") second = self.tmp_dir / "second" second.mkdir() with open(second / "include.qasm", "w") as fp: fp.write("qreg q[2];") program = 'include "include.qasm";' parsed = qiskit.qasm2.loads(program, include_path=(empty, first, second)) qc = QuantumCircuit(QuantumRegister(1, "q")) self.assertEqual(parsed, qc) def test_qelib1_ignores_search_path(self): with open(self.tmp_dir / "qelib1.inc", "w") as fp: fp.write("qreg not_used[2];") program = 'include "qelib1.inc";' parsed = qiskit.qasm2.loads(program, include_path=(self.tmp_dir,)) qc = QuantumCircuit() self.assertEqual(parsed, qc) def test_include_from_current_directory(self): include = """ qreg q[2]; """ with open(self.tmp_dir / "include.qasm", "w") as fp: fp.write(include) program = """ OPENQASM 2.0; include "include.qasm"; """ prevdir = os.getcwd() os.chdir(self.tmp_dir) try: parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(2, "q")) self.assertEqual(parsed, qc) finally: os.chdir(prevdir) def test_load_searches_source_directory(self): with open(self.tmp_dir / "include.qasm", "w") as fp: fp.write("qreg q[2];") program = 'include "include.qasm";' with open(self.tmp_dir / "program.qasm", "w") as fp: fp.write(program) parsed = qiskit.qasm2.load(self.tmp_dir / "program.qasm") qc = QuantumCircuit(QuantumRegister(2, "q")) self.assertEqual(parsed, qc) def test_load_searches_source_directory_last(self): first = self.tmp_dir / "first" first.mkdir() with open(first / "include.qasm", "w") as fp: fp.write("qreg q[2];") with open(self.tmp_dir / "include.qasm", "w") as fp: fp.write("qreg not_used[2];") program = 'include "include.qasm";' with open(self.tmp_dir / "program.qasm", "w") as fp: fp.write(program) parsed = qiskit.qasm2.load(self.tmp_dir / "program.qasm", include_path=(first,)) qc = QuantumCircuit(QuantumRegister(2, "q")) self.assertEqual(parsed, qc) def test_load_searches_source_directory_prepend(self): first = self.tmp_dir / "first" first.mkdir() with open(first / "include.qasm", "w") as fp: fp.write("qreg not_used[2];") with open(self.tmp_dir / "include.qasm", "w") as fp: fp.write("qreg q[2];") program = 'include "include.qasm";' with open(self.tmp_dir / "program.qasm", "w") as fp: fp.write(program) parsed = qiskit.qasm2.load( self.tmp_dir / "program.qasm", include_path=(first,), include_input_directory="prepend" ) qc = QuantumCircuit(QuantumRegister(2, "q")) self.assertEqual(parsed, qc) def test_load_can_ignore_source_directory(self): with open(self.tmp_dir / "include.qasm", "w") as fp: fp.write("qreg q[2];") program = 'include "include.qasm";' with open(self.tmp_dir / "program.qasm", "w") as fp: fp.write(program) with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "unable to find 'include.qasm'"): qiskit.qasm2.load(self.tmp_dir / "program.qasm", include_input_directory=None) @ddt.ddt class TestCustomInstructions(QiskitTestCase): def test_qelib1_include_overridden(self): program = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[3]; u3(0.5, 0.25, 0.125) q[0]; u2(0.5, 0.25) q[0]; u1(0.5) q[0]; cx q[0], q[1]; id q[0]; x q[0]; y q[0]; z q[0]; h q[0]; s q[0]; sdg q[0]; t q[0]; tdg q[0]; rx(0.5) q[0]; ry(0.5) q[0]; rz(0.5) q[0]; cz q[0], q[1]; cy q[0], q[1]; ch q[0], q[1]; ccx q[0], q[1], q[2]; crz(0.5) q[0], q[1]; cu1(0.5) q[0], q[1]; cu3(0.5, 0.25, 0.125) q[0], q[1]; """ parsed = qiskit.qasm2.loads( program, custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS ) qc = QuantumCircuit(QuantumRegister(3, "q")) qc.append(lib.U3Gate(0.5, 0.25, 0.125), [0]) qc.append(lib.U2Gate(0.5, 0.25), [0]) qc.append(lib.U1Gate(0.5), [0]) qc.append(lib.CXGate(), [0, 1]) qc.append(lib.IGate(), [0]) qc.append(lib.XGate(), [0]) qc.append(lib.YGate(), [0]) qc.append(lib.ZGate(), [0]) qc.append(lib.HGate(), [0]) qc.append(lib.SGate(), [0]) qc.append(lib.SdgGate(), [0]) qc.append(lib.TGate(), [0]) qc.append(lib.TdgGate(), [0]) qc.append(lib.RXGate(0.5), [0]) qc.append(lib.RYGate(0.5), [0]) qc.append(lib.RZGate(0.5), [0]) qc.append(lib.CZGate(), [0, 1]) qc.append(lib.CYGate(), [0, 1]) qc.append(lib.CHGate(), [0, 1]) qc.append(lib.CCXGate(), [0, 1, 2]) qc.append(lib.CRZGate(0.5), [0, 1]) qc.append(lib.CU1Gate(0.5), [0, 1]) qc.append(lib.CU3Gate(0.5, 0.25, 0.125), [0, 1]) self.assertEqual(parsed, qc) # Also test that the output matches what Qiskit puts out. from_qiskit = QuantumCircuit.from_qasm_str(program) self.assertEqual(parsed, from_qiskit) def test_qelib1_sparse_overrides(self): """Test that the qelib1 special import still works as expected when a couple of gates in the middle of it are custom. As long as qelib1 is handled specially, there is a risk that this handling will break in weird ways when custom instructions overlap it.""" program = """ include "qelib1.inc"; qreg q[3]; u3(0.5, 0.25, 0.125) q[0]; u2(0.5, 0.25) q[0]; u1(0.5) q[0]; cx q[0], q[1]; id q[0]; x q[0]; y q[0]; z q[0]; h q[0]; s q[0]; sdg q[0]; t q[0]; tdg q[0]; rx(0.5) q[0]; ry(0.5) q[0]; rz(0.5) q[0]; cz q[0], q[1]; cy q[0], q[1]; ch q[0], q[1]; ccx q[0], q[1], q[2]; crz(0.5) q[0], q[1]; cu1(0.5) q[0], q[1]; cu3(0.5, 0.25, 0.125) q[0], q[1]; """ parsed = qiskit.qasm2.loads( program, custom_instructions=[ qiskit.qasm2.CustomInstruction("id", 0, 1, lib.IGate), qiskit.qasm2.CustomInstruction("h", 0, 1, lib.HGate), qiskit.qasm2.CustomInstruction("crz", 1, 2, lib.CRZGate), ], ) qc = QuantumCircuit(QuantumRegister(3, "q")) qc.append(lib.U3Gate(0.5, 0.25, 0.125), [0]) qc.append(lib.U2Gate(0.5, 0.25), [0]) qc.append(lib.U1Gate(0.5), [0]) qc.append(lib.CXGate(), [0, 1]) qc.append(lib.IGate(), [0]) qc.append(lib.XGate(), [0]) qc.append(lib.YGate(), [0]) qc.append(lib.ZGate(), [0]) qc.append(lib.HGate(), [0]) qc.append(lib.SGate(), [0]) qc.append(lib.SdgGate(), [0]) qc.append(lib.TGate(), [0]) qc.append(lib.TdgGate(), [0]) qc.append(lib.RXGate(0.5), [0]) qc.append(lib.RYGate(0.5), [0]) qc.append(lib.RZGate(0.5), [0]) qc.append(lib.CZGate(), [0, 1]) qc.append(lib.CYGate(), [0, 1]) qc.append(lib.CHGate(), [0, 1]) qc.append(lib.CCXGate(), [0, 1, 2]) qc.append(lib.CRZGate(0.5), [0, 1]) qc.append(lib.CU1Gate(0.5), [0, 1]) qc.append(lib.CU3Gate(0.5, 0.25, 0.125), [0, 1]) self.assertEqual(parsed, qc) def test_user_gate_after_overidden_qelib1(self): program = """ include "qelib1.inc"; qreg q[1]; opaque my_gate q; my_gate q[0]; """ parsed = qiskit.qasm2.loads( program, custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS ) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.append(Gate("my_gate", 1, []), [0]) self.assertEqual(parsed, qc) def test_qiskit_extra_builtins(self): program = """ qreg q[5]; u(0.5 ,0.25, 0.125) q[0]; p(0.5) q[0]; sx q[0]; sxdg q[0]; swap q[0], q[1]; cswap q[0], q[1], q[2]; crx(0.5) q[0], q[1]; cry(0.5) q[0], q[1]; cp(0.5) q[0], q[1]; csx q[0], q[1]; cu(0.5, 0.25, 0.125, 0.0625) q[0], q[1]; rxx(0.5) q[0], q[1]; rzz(0.5) q[0], q[1]; rccx q[0], q[1], q[2]; rc3x q[0], q[1], q[2], q[3]; c3x q[0], q[1], q[2], q[3]; c3sqrtx q[0], q[1], q[2], q[3]; c4x q[0], q[1], q[2], q[3], q[4]; """ parsed = qiskit.qasm2.loads( program, custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS ) qc = QuantumCircuit(QuantumRegister(5, "q")) qc.append(lib.UGate(0.5, 0.25, 0.125), [0]) qc.append(lib.PhaseGate(0.5), [0]) qc.append(lib.SXGate(), [0]) qc.append(lib.SXdgGate(), [0]) qc.append(lib.SwapGate(), [0, 1]) qc.append(lib.CSwapGate(), [0, 1, 2]) qc.append(lib.CRXGate(0.5), [0, 1]) qc.append(lib.CRYGate(0.5), [0, 1]) qc.append(lib.CPhaseGate(0.5), [0, 1]) qc.append(lib.CSXGate(), [0, 1]) qc.append(lib.CUGate(0.5, 0.25, 0.125, 0.0625), [0, 1]) qc.append(lib.RXXGate(0.5), [0, 1]) qc.append(lib.RZZGate(0.5), [0, 1]) qc.append(lib.RCCXGate(), [0, 1, 2]) qc.append(lib.RC3XGate(), [0, 1, 2, 3]) qc.append(lib.C3XGate(), [0, 1, 2, 3]) qc.append(lib.C3SXGate(), [0, 1, 2, 3]) qc.append(lib.C4XGate(), [0, 1, 2, 3, 4]) self.assertEqual(parsed, qc) # There's also the 'u0' gate, but this is weird so we don't wildly care what its definition # is and it has no Qiskit equivalent, so we'll just test that it using it doesn't produce an # error. parsed = qiskit.qasm2.loads( "qreg q[1]; u0(1) q[0];", custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS ) self.assertEqual(parsed.data[0].operation.name, "u0") def test_qiskit_override_delay_opaque(self): program = """ opaque delay(t) q; qreg q[1]; delay(1) q[0]; """ parsed = qiskit.qasm2.loads( program, custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS ) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.delay(1, 0, unit="dt") self.assertEqual(parsed, qc) def test_qiskit_override_u0_opaque(self): program = """ opaque u0(n) q; qreg q[1]; u0(2) q[0]; """ parsed = qiskit.qasm2.loads( program, custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS ) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.id(0) qc.id(0) self.assertEqual(parsed.decompose(), qc) def test_can_override_u(self): program = """ qreg q[1]; U(0.5, 0.25, 0.125) q[0]; """ class MyGate(Gate): def __init__(self, a, b, c): super().__init__("u", 1, [a, b, c]) parsed = qiskit.qasm2.loads( program, custom_instructions=[qiskit.qasm2.CustomInstruction("U", 3, 1, MyGate, builtin=True)], ) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.append(MyGate(0.5, 0.25, 0.125), [0]) self.assertEqual(parsed, qc) def test_can_override_cx(self): program = """ qreg q[2]; CX q[0], q[1]; """ class MyGate(Gate): def __init__(self): super().__init__("cx", 2, []) parsed = qiskit.qasm2.loads( program, custom_instructions=[qiskit.qasm2.CustomInstruction("CX", 0, 2, MyGate, builtin=True)], ) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(MyGate(), [0, 1]) self.assertEqual(parsed, qc) @ddt.data(lambda x: x, reversed) def test_can_override_both_builtins_with_other_gates(self, order): program = """ gate unimportant q {} qreg q[2]; U(0.5, 0.25, 0.125) q[0]; CX q[0], q[1]; """ class MyUGate(Gate): def __init__(self, a, b, c): super().__init__("u", 1, [a, b, c]) class MyCXGate(Gate): def __init__(self): super().__init__("cx", 2, []) custom = [ qiskit.qasm2.CustomInstruction("unused", 0, 1, lambda: Gate("unused", 1, [])), qiskit.qasm2.CustomInstruction("U", 3, 1, MyUGate, builtin=True), qiskit.qasm2.CustomInstruction("CX", 0, 2, MyCXGate, builtin=True), ] custom = order(custom) parsed = qiskit.qasm2.loads(program, custom_instructions=custom) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(MyUGate(0.5, 0.25, 0.125), [0]) qc.append(MyCXGate(), [0, 1]) self.assertEqual(parsed, qc) def test_custom_builtin_gate(self): program = """ qreg q[1]; builtin(0.5) q[0]; """ class MyGate(Gate): def __init__(self, a): super().__init__("builtin", 1, [a]) parsed = qiskit.qasm2.loads( program, custom_instructions=[ qiskit.qasm2.CustomInstruction("builtin", 1, 1, MyGate, builtin=True) ], ) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.append(MyGate(0.5), [0]) self.assertEqual(parsed, qc) def test_can_define_builtin_as_gate(self): program = """ qreg q[1]; gate builtin(t) q {} builtin(0.5) q[0]; """ class MyGate(Gate): def __init__(self, a): super().__init__("builtin", 1, [a]) parsed = qiskit.qasm2.loads( program, custom_instructions=[ qiskit.qasm2.CustomInstruction("builtin", 1, 1, MyGate, builtin=True) ], ) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.append(MyGate(0.5), [0]) self.assertEqual(parsed, qc) def test_can_define_builtin_as_opaque(self): program = """ qreg q[1]; opaque builtin(t) q; builtin(0.5) q[0]; """ class MyGate(Gate): def __init__(self, a): super().__init__("builtin", 1, [a]) parsed = qiskit.qasm2.loads( program, custom_instructions=[ qiskit.qasm2.CustomInstruction("builtin", 1, 1, MyGate, builtin=True) ], ) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.append(MyGate(0.5), [0]) self.assertEqual(parsed, qc) def test_can_define_custom_as_gate(self): program = """ qreg q[1]; gate my_gate(t) q {} my_gate(0.5) q[0]; """ class MyGate(Gate): def __init__(self, a): super().__init__("my_gate", 1, [a]) parsed = qiskit.qasm2.loads( program, custom_instructions=[qiskit.qasm2.CustomInstruction("my_gate", 1, 1, MyGate)] ) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.append(MyGate(0.5), [0]) self.assertEqual(parsed, qc) def test_can_define_custom_as_opaque(self): program = """ qreg q[1]; opaque my_gate(t) q; my_gate(0.5) q[0]; """ class MyGate(Gate): def __init__(self, a): super().__init__("my_gate", 1, [a]) parsed = qiskit.qasm2.loads( program, custom_instructions=[qiskit.qasm2.CustomInstruction("my_gate", 1, 1, MyGate)] ) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.append(MyGate(0.5), [0]) self.assertEqual(parsed, qc) class TestCustomClassical(QiskitTestCase): def test_qiskit_extensions(self): program = """ include "qelib1.inc"; qreg q[1]; rx(asin(0.3)) q[0]; ry(acos(0.3)) q[0]; rz(atan(0.3)) q[0]; """ parsed = qiskit.qasm2.loads(program, custom_classical=qiskit.qasm2.LEGACY_CUSTOM_CLASSICAL) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.rx(math.asin(0.3), 0) qc.ry(math.acos(0.3), 0) qc.rz(math.atan(0.3), 0) self.assertEqual(parsed, qc) def test_zero_parameter_custom(self): program = """ qreg q[1]; U(f(), 0, 0) q[0]; """ parsed = qiskit.qasm2.loads( program, custom_classical=[qiskit.qasm2.CustomClassical("f", 0, lambda: 0.2)] ) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.u(0.2, 0, 0, 0) self.assertEqual(parsed, qc) def test_multi_parameter_custom(self): program = """ qreg q[1]; U(f(0.2), g(0.4, 0.1), h(1, 2, 3)) q[0]; """ parsed = qiskit.qasm2.loads( program, custom_classical=[ qiskit.qasm2.CustomClassical("f", 1, lambda x: 1 + x), qiskit.qasm2.CustomClassical("g", 2, math.atan2), qiskit.qasm2.CustomClassical("h", 3, lambda x, y, z: z - y + x), ], ) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.u(1.2, math.atan2(0.4, 0.1), 2, 0) self.assertEqual(parsed, qc) def test_use_in_gate_definition(self): # pylint: disable=invalid-name program = """ gate my_gate(a, b) q { U(f(a, b), g(f(b, f(b, a))), b) q; } qreg q[1]; my_gate(0.5, 0.25) q[0]; my_gate(0.25, 0.5) q[0]; """ f = lambda x, y: x - y g = lambda x: 2 * x parsed = qiskit.qasm2.loads( program, custom_classical=[ qiskit.qasm2.CustomClassical("f", 2, f), qiskit.qasm2.CustomClassical("g", 1, g), ], ) first_gate = parsed.data[0].operation second_gate = parsed.data[1].operation self.assertEqual(list(first_gate.params), [0.5, 0.25]) self.assertEqual(list(second_gate.params), [0.25, 0.5]) self.assertEqual( list(first_gate.definition.data[0].operation.params), [ f(0.5, 0.25), g(f(0.25, f(0.25, 0.5))), 0.25, ], ) self.assertEqual( list(second_gate.definition.data[0].operation.params), [ f(0.25, 0.5), g(f(0.5, f(0.5, 0.25))), 0.5, ], ) @ddt.ddt class TestStrict(QiskitTestCase): @ddt.data( "gate my_gate(p0, p1$) q0, q1 {}", "gate my_gate(p0, p1) q0, q1$ {}", "opaque my_gate(p0, p1$) q0, q1;", "opaque my_gate(p0, p1) q0, q1$;", 'include "qelib1.inc"; qreg q[2]; cu3(0.5, 0.25, 0.125$) q[0], q[1];', 'include "qelib1.inc"; qreg q[2]; cu3(0.5, 0.25, 0.125) q[0], q[1]$;', "qreg q[2]; barrier q[0], q[1]$;", 'include "qelib1.inc"; qreg q[1]; rx(sin(pi$)) q[0];', ) def test_trailing_comma(self, program): without = qiskit.qasm2.loads("OPENQASM 2.0;\n" + program.replace("$", ""), strict=True) with_ = qiskit.qasm2.loads(program.replace("$", ","), strict=False) self.assertEqual(with_, without) def test_trailing_semicolon_after_gate(self): program = """ include "qelib1.inc"; gate bell a, b { h a; cx a, b; }; // <- the important bit of the test qreg q[2]; bell q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) bell_def = QuantumCircuit([Qubit(), Qubit()]) bell_def.h(0) bell_def.cx(0, 1) bell = gate_builder("bell", [], bell_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(bell(), [0, 1]) self.assertEqual(parsed, qc) def test_empty_statement(self): # This is allowed more as a side-effect of allowing the trailing semicolon after gate # definitions. program = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[2]; h q[0]; ; cx q[0], q[1]; ;;;; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.h(0) qc.cx(0, 1) self.assertEqual(parsed, qc) def test_single_quoted_path(self): program = """ include 'qelib1.inc'; qreg q[1]; h q[0]; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.h(0) self.assertEqual(parsed, qc)
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../utils/") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) # Pauli Twirling print("created zne_qcs (length:", len(zne_qcs), ")") # optimization_level must be 0 # feed initial_layout here to see the picture of the circuits before casting the job t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") t3_zne_qcs[-3].draw("mpl") # from qiskit.test.mock import FakeJakarta # backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') print("provider:", provider) backend = provider.get_backend("ibmq_jakarta") print(str(backend)) shots = 1 << 13 reps = 8 # unused jobs = [] for _ in range(reps): #! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits, name="calq") meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # we have to feed initial_layout to calibration matrix cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) meas_calibs[0].draw("mpl") dt_now = datetime.datetime.now() print(dt_now) filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl" print(filename) with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) with open(filename, "wb") as f: pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump(backend.properties(), f) filename = "job_ids_ibmq_jakarta_100step_20220413_030821_.pkl" # change here with open(filename, "rb") as f: job_ids_dict = pickle.load(f) job_ids = job_ids_dict["job_ids"] cal_job_id = job_ids_dict["cal_job_id"] retrieved_jobs = [] for job_id in job_ids: retrieved_jobs.append(backend.retrieve_job(job_id)) retrieved_cal_job = backend.retrieve_job(cal_job_id) cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in retrieved_jobs: mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors) rho = expvals_to_valid_rho(num_qubits, zne_expvals) fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids))) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/Qiskit/qiskit-neko
Qiskit
# This code is part of Qiskit. # # (C) Copyright IBM 2022, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for quantum neural networks.""" import numpy as np from ddt import ddt, data, unpack from qiskit import QuantumCircuit from qiskit.circuit import Parameter from qiskit.primitives import Sampler as ReferenceSampler, Estimator as ReferenceEstimator from qiskit.quantum_info import SparsePauliOp from qiskit_aer.primitives import Sampler as AerSampler, Estimator as AerEstimator from qiskit_machine_learning.neural_networks import SamplerQNN, EstimatorQNN from qiskit_neko import decorators from qiskit_neko.tests import base @ddt class TestNeuralNetworksOnPrimitives(base.BaseTestCase): """Test adapted from the qiskit_machine_learning tutorials.""" def setUp(self): super().setUp() self.input_params = [Parameter("x")] self.weight_params = [Parameter("w")] self.circuit = QuantumCircuit(1) self.circuit.ry(self.input_params[0], 0) self.circuit.rx(self.weight_params[0], 0) self.samplers = dict(reference=ReferenceSampler(), aer=AerSampler(run_options={"seed": 42})) self.estimators = dict( reference=ReferenceEstimator(), aer=AerEstimator(run_options={"seed": 42}) ) @decorators.component_attr("terra", "aer", "machine_learning") @data(["reference", 4], ["aer", 1]) @unpack def test_sampler_qnn(self, implementation, decimal): """Test the execution of quantum neural networks using SamplerQNN.""" sampler = self.samplers[implementation] qnn = SamplerQNN( circuit=self.circuit, input_params=self.input_params, weight_params=self.weight_params, input_gradients=True, sampler=sampler, ) input_data = np.ones(len(self.input_params)) weights = np.ones(len(self.weight_params)) probabilities = qnn.forward(input_data, weights) np.testing.assert_array_almost_equal(probabilities, [[0.6460, 0.3540]], decimal) input_grad, weight_grad = qnn.backward(input_data, weights) np.testing.assert_array_almost_equal(input_grad, [[[-0.2273], [0.2273]]], decimal) np.testing.assert_array_almost_equal(weight_grad, [[[-0.2273], [0.2273]]], decimal) @decorators.component_attr("terra", "aer", "machine_learning") @data(["reference", 4], ["aer", 1]) @unpack def test_estimator_qnn(self, implementation, decimal): """Test the execution of quantum neural networks using EstimatorQNN.""" estimator = self.estimators[implementation] qnn = EstimatorQNN( circuit=self.circuit, observables=SparsePauliOp.from_list([("Z", 1)]), input_params=self.input_params, weight_params=self.weight_params, input_gradients=True, estimator=estimator, ) input_data = np.ones(len(self.input_params)) weights = np.ones(len(self.weight_params)) expectations = qnn.forward(input_data, weights) np.testing.assert_array_almost_equal(expectations, [[0.2919]], decimal) input_grad, weight_grad = qnn.backward(input_data, weights) np.testing.assert_array_almost_equal(input_grad, [[[-0.4546]]], decimal) np.testing.assert_array_almost_equal(weight_grad, [[[-0.4546]]], decimal)
https://github.com/Andres8bit/IBMQ-Quantum-Qiskit
Andres8bit
# There exists a theorem in Quantum mechanics called the # No-Cloning Theorem: which states that you cannot simply # make an exact copy of an unknown quantum state. # However by taking advatange of two classical bits and an # entangled qubit pair, we can transfer states. # We call this Teleportation. # To transfer a quantum bit, we must use a third prst to send them # an entangled qubit pair. %matplotlib inline # Importing standard Qiskit libraries and configuring account from qiskit import QuantumCircuit, QuantumRegister,ClassicalRegister,execute, BasicAer, IBMQ from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * from qiskit_textbook.tools import random_state, array_to_latex from qiskit.extensions import Initialize import numpy as np # Loading your IBM Q account(s) provider = IBMQ.load_account() #Ex: #creating our circuit: qr = QuantumRegister(3) # three qubit system crz = ClassicalRegister(1) # two different calssi crx = ClassicalRegister(1) teleportation_Circuit = QuantumCircuit(qr,crz,crx) #STEP1: # creating an entangled pair of qubits. # This pair creates a special pair called a Bell pair. # This is done by first placing one qubit into the X-basis: # \+> and |->, using a Hadamard gate, then applying a CNOT # gate onto the other qubit controlled by the on in the X-basis. def create_bell_pair(qc,a,b): """ Creates a bell pair in qc using qubits a and b""" qc.h(a) #puts a into |+> qc.cx(a,b) #CNOT with a as control #creating our bell pair: create_bell_pair(teleportation_Circuit,1,2) teleportation_Circuit.draw() #STEP2: # We must apply a CNOT gate to the qubit being sent. Then we apply a Hadamard # gate. def teleportation_bit(qc,psi,a): qc.cx(psi,a) qc.h(psi) #applying teleportation bit to our cicuit; teleportation_Circuit.barrier() teleportation_bit(teleportation_Circuit,0,1) teleportation_Circuit.draw() #STEP3: # Measure both qubits and store the result in two classical bits. def measure_and_send(qc,a,b): """Measures qubits a & b and 'sends' the results to bob""" qc.barrier() qc.measure(a,0) qc.measure(b,1) measure_and_send(teleportation_Circuit,0,1) teleportation_Circuit.draw() #STEP4: # Apply gates bepending on the sate of the classical bits: # 00 -> Do nothing. # 01 -> Apply X gate. # 10 -> Apply Z gate. # 11 -> Apply ZX gate. def reciever_gates(qc,qubit,crz,crx): # apply the correct gates if the registers are in the state '1' qc.x(qubit).c_if(crx,1) qc.z(qubit).c_if(crz,1) #Applying reciever gates: teleportation_Circuit.barrier() reciever_gates(teleportation_Circuit,2,crz,crx) teleportation_Circuit.draw() #============================== Begining of testing Protocol ========================================= psi = random_state(1) # create a random 1 qubitstate # Display our random qubit state: array_to_latex(psi,pretext="|\\psi\\rangle =") # Show Block Sphere: plot_bloch_multivector(psi) # gate initialiazation: if the circuit is working correctly then q2 will be in this state at the end init_gate = Initialize(psi) init_gate.label = "init" ## setup: qr = QuantumRegister(3) crz = ClassicalRegister(1) crx = ClassicalRegister(1) qc = QuantumCircuit(qr,crz,crx) # initial step: 0: # Initialise q0 qc.append(init_gate,[0]) qc.barrier() # step 1: # begin teleportation protocol create_bell_pair(qc,1,2) qc.barrier() # step 2: # send q1 to q0 and q2 to q1 teleportation_bit(qc,0,1) # step 3: #send classical bits from q0 to q1 measure_and_send(qc,0,1) # step 4: #q1 decodes qubits reciever_gates(qc,2,crz,crx) backend = BasicAer.get_backend('statevector_simulator') out_vector = execute(qc, backend).result().get_statevector() plot_bloch_multivector(out_vector) # step 5: # takes advantafe of the reversablilty of quantum circuits to reverse randomization: inverse_init_gate = init_gate.gates_to_uncompute() qc.append(inverse_init_gate, [2]) #Display circuit: qc.draw() # final step: get result using classical bit: cr_result = ClassicalRegister(1) qc.add_register(cr_result) qc.measure(2,2) qc.draw() # testing the circuit: backend = BasicAer.get_backend('qasm_simulator') counts = execute(qc,backend,shots=1024).result().get_counts() plot_histogram(counts) # IBM Quantum computers fo not support instructions after measurements # however we can use the deferred measurement principle, to postpone # measurements until the end of our circuit. # To do this we rewrite our reciever_gates: def new_reciever_gate(qc,a,b,c): qc.cz(a,c) qc.cx(b,c) # Using our new reciever function: qc = QuantumCircuit(3,1) # First, let's initialise Alice's q0 qc.append(init_gate, [0]) qc.barrier() # Now begins the teleportation protocol create_bell_pair(qc, 1, 2) qc.barrier() # Send q1 to Alice and q2 to Bob teleportation_bit(qc, 0, 1) qc.barrier() # Alice sends classical bits to Bob new_reciever_gate(qc, 0, 1, 2) # We undo the initialisation process qc.append(inverse_init_gate, [2]) # See the results, we only care about the state of qubit 2 qc.measure(2,0) # View the results: qc.draw() # now we will use quantum hardware: IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') provider.backends() # get the least-busy backend at IBM and run the quantum circuit there from qiskit.providers.ibmq import least_busy backend = least_busy(provider.backends(filters=lambda b: b.configuration().n_qubits >= 3 and not b.configuration().simulator and b.status().operational==True)) job_exp = execute(qc, backend=backend, shots=8192) # Get results and display: exp_result = job_exp.result() exp_measurement_result = exp_result.get_counts(qc) print(exp_measurement_results) plot_histogram(exp_measurement_results)
https://github.com/mnp-club/Quantum_Computing_Workshop_2020
mnp-club
!pip install tabulate %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 * from tabulate import tabulate # Loading your IBM Q account(s) provider = IBMQ.load_account() #Get the library to check the answers %pip install -I git+https://github.com/mnp-club/MnP_QC_Workshop.git from mnp_qc_workshop_2020.discrete_logarithm import qft_dagger, oracle, check_answer n_qubits = 3 #Number of qubits for the registers of |x1> and |x2> #For figuring out you would just need 2*n_qubits classical bits qc_disc_log = QuantumCircuit(4+n_qubits+n_qubits, n_qubits+n_qubits) for i in range(2*n_qubits): qc_disc_log.h(i) qc_disc_log.x(9) qc_disc_log.append(oracle(), range(10)) qc_disc_log.append(qft_dagger(3), range(3)) qc_disc_log.append(qft_dagger(3) ,[3,4,5]) qc_disc_log.measure(range(2*n_qubits), range(2*n_qubits)) qc_disc_log.draw('text') backend = Aer.get_backend('qasm_simulator') results = execute(qc_disc_log, backend, shots=8192).result() counts = results.get_counts() plot_histogram(counts) rows_x_1, eigenvalues_x_1 = [], [] for output in counts: decimal = int(output, 2)//8 eigenvalue = decimal/(2**3) eigenvalues_x_1.append(eigenvalue) rows_x_1.append(["%s(bin) = %i(dec)" % (output[0:3], decimal), "%i/%i = %.2f" % (decimal, 2**3, eigenvalue)]) print(tabulate(rows_x_1, headers=["Register Output", "Phase"])) rows_x_2, eigenvalues_x_2 = [], [] for output in counts: decimal = int(output, 2) - ((int(output, 2)//8)*8) eigenvalue = decimal/(2**3) eigenvalues_x_2.append(eigenvalue) rows_x_2.append(["%s(bin) = %i(dec)" % (output[3:6], decimal), "%i/%i = %.2f" % (decimal, 2**3, eigenvalue)]) print(tabulate(rows_x_2, headers=["Register Output", "Phase"])) #Store your value for s here s = 3 #Do analysis of oracle here qc = QuantumCircuit(10, 4) qc.x(0) qc.x(9) qc.append(oracle(), range(10)) qc.measure([6,7,8,9], range(4)) backend = Aer.get_backend('qasm_simulator') results = execute(qc, backend, shots=8192).result() counts = results.get_counts() plot_histogram(counts) # On x1=1, ans = 2 and on x2=1, ans = 8 #Store values of a and b here a, b = 2, 8 check_answer(s,a,b)
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer q = QuantumRegister(2, "q") c = ClassicalRegister(2, "c") qc = QuantumCircuit(q,c) qc.x(q[1]) qc.cx(q[1],q[0]) # Returning control qubit to the initial state qc.x(q[1]) job = execute(qc,Aer.get_backend('unitary_simulator'), shots = 1) U=job.result().get_unitary(qc,decimals=3) print("CNOT(0) = ") for row in U: s = "" for value in row: s = s + str(round(value.real,2)) + " " print(s) qc.draw(output="mpl", reverse_bits=True) # # your solution is here # from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer q = QuantumRegister(3,"q") c = ClassicalRegister(3,"c") qc = QuantumCircuit(q,c) qc.x(q[2]) qc.x(q[1]) qc.ccx(q[2],q[1],q[0]) qc.x(q[2]) qc.x(q[1]) job = execute(qc,Aer.get_backend('unitary_simulator'), shots = 1) U=job.result().get_unitary(qc,decimals=3) print("CCNOT(00) = ") for row in U: s = "" for value in row: s = s + str(round(value.real,2)) + " " print(s) qc.draw(output="mpl",reverse_bits=True) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer q = QuantumRegister(3,"q") c = ClassicalRegister(3,"c") qc = QuantumCircuit(q,c) qc.x(q[2]) qc.ccx(q[2],q[1],q[0]) qc.x(q[2]) job = execute(qc,Aer.get_backend('unitary_simulator'), shots = 1) U=job.result().get_unitary(qc,decimals=3) print("CCNOT(01) = ") for row in U: s = "" for value in row: s = s + str(round(value.real,2)) + " " print(s) qc.draw(output="mpl",reverse_bits=True) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer q = QuantumRegister(3,"q") c = ClassicalRegister(3,"c") qc = QuantumCircuit(q,c) qc.x(q[1]) qc.ccx(q[2],q[1],q[0]) qc.x(q[1]) job = execute(qc,Aer.get_backend('unitary_simulator'), shots = 1) U=job.result().get_unitary(qc,decimals=3) print("CCNOT(10) = ") for row in U: s = "" for value in row: s = s + str(round(value.real,2)) + " " print(s) qc.draw(output="mpl",reverse_bits=True) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer qaux = QuantumRegister(1,"qaux") q = QuantumRegister(4,"q") c = ClassicalRegister(4,"c") qc = QuantumCircuit(q,qaux,c) # step 1: set qaux to |1> if both q3 and q2 are in |1> qc.ccx(q[3],q[2],qaux[0]) # step 2: apply NOT gate to q0 if both qaux and q1 are in |1> qc.ccx(qaux[0],q[1],q[0]) # step 3: set qaux to |0> if both q3 and q2 are in |1> by reversing the affect of step 1 qc.ccx(q[3],q[2],qaux[0]) qc.draw(output="mpl",reverse_bits=True) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer all_inputs=[] for q3 in ['0','1']: for q2 in ['0','1']: for q1 in ['0','1']: for q0 in ['0','1']: all_inputs.append(q3+q2+q1+q0) # print(all_inputs) print("input --> output") for the_input in all_inputs: # create the circuit qaux = QuantumRegister(1,"qaux") q = QuantumRegister(4,"q") c = ClassicalRegister(4,"c") qc = QuantumCircuit(q,qaux,c) # set the initial value of the circuit w.r.t. the input if the_input[0] =='1': qc.x(q[3]) if the_input[1] =='1': qc.x(q[2]) if the_input[2] =='1': qc.x(q[1]) if the_input[3] =='1': qc.x(q[0]) # implement the CCNOT gates qc.ccx(q[3],q[2],qaux[0]) qc.ccx(qaux[0],q[1],q[0]) qc.ccx(q[3],q[2],qaux[0]) # measure the main quantum register qc.measure(q,c) # execute the circuit job = execute(qc,Aer.get_backend('qasm_simulator'),shots=1) counts = job.result().get_counts(qc) for key in counts: the_output = key printed_str = the_input[0:3]+" "+the_input[3]+" --> "+the_output[0:3]+" "+the_output[3] if (the_input!=the_output): printed_str = printed_str + " the output is different than the input" print(printed_str) # # your solution is here # from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer qaux = QuantumRegister(2,"qaux") q = QuantumRegister(5,"q") c = ClassicalRegister(5,"c") qc = QuantumCircuit(q,qaux,c) qc.ccx(q[4],q[3],qaux[1]) qc.ccx(q[2],q[1],qaux[0]) qc.ccx(qaux[1],qaux[0],q[0]) qc.ccx(q[4],q[3],qaux[1]) qc.ccx(q[2],q[1],qaux[0]) qc.draw(output="mpl",reverse_bits=True) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer all_inputs=[] for q4 in ['0','1']: for q3 in ['0','1']: for q2 in ['0','1']: for q1 in ['0','1']: for q0 in ['0','1']: all_inputs.append(q4+q3+q2+q1+q0) #print(all_inputs) print("input --> output") for the_input in all_inputs: # create the circuit qaux = QuantumRegister(2,"qaux") q = QuantumRegister(5,"q") c = ClassicalRegister(5,"c") qc = QuantumCircuit(q,qaux,c) # set the initial value of the circuit w.r.t. the input if the_input[0] =='1': qc.x(q[4]) if the_input[1] =='1': qc.x(q[3]) if the_input[2] =='1': qc.x(q[2]) if the_input[3] =='1': qc.x(q[1]) if the_input[4] =='1': qc.x(q[0]) # implement the CCNOT gates qc.ccx(q[4],q[3],qaux[1]) qc.ccx(q[2],q[1],qaux[0]) qc.ccx(qaux[1],qaux[0],q[0]) qc.ccx(q[4],q[3],qaux[1]) qc.ccx(q[2],q[1],qaux[0]) # measure the main quantum register qc.measure(q,c) # execute the circuit job = execute(qc,Aer.get_backend('qasm_simulator'),shots=1) counts = job.result().get_counts(qc) for key in counts: the_output = key printed_str = the_input[0:4]+" "+the_input[4]+" --> "+the_output[0:4]+" "+the_output[4] if (the_input!=the_output): printed_str = printed_str + " the output is different than the input" print(printed_str) # # your solution is here # from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer qaux = QuantumRegister(2,"qaux") q = QuantumRegister(5,"q") c = ClassicalRegister(5,"c") qc = QuantumCircuit(q,qaux,c) qc.x(q[3]) qc.x(q[1]) qc.ccx(q[4],q[3],qaux[1]) qc.ccx(q[2],q[1],qaux[0]) qc.ccx(qaux[1],qaux[0],q[0]) qc.ccx(q[4],q[3],qaux[1]) qc.ccx(q[2],q[1],qaux[0]) qc.x(q[3]) qc.x(q[1]) qc.draw(output="mpl",reverse_bits=True) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer all_inputs=[] for q4 in ['0','1']: for q3 in ['0','1']: for q2 in ['0','1']: for q1 in ['0','1']: for q0 in ['0','1']: all_inputs.append(q4+q3+q2+q1+q0) #print(all_inputs) print("input --> output") for the_input in all_inputs: # create the circuit qaux = QuantumRegister(2,"qaux") q = QuantumRegister(5,"q") c = ClassicalRegister(5,"c") qc = QuantumCircuit(q,qaux,c) # set the initial value of the circuit w.r.t. the input if the_input[0] =='1': qc.x(q[4]) if the_input[1] =='1': qc.x(q[3]) if the_input[2] =='1': qc.x(q[2]) if the_input[3] =='1': qc.x(q[1]) if the_input[4] =='1': qc.x(q[0]) # implement the CCNOT gates qc.x(q[3]) qc.x(q[1]) qc.ccx(q[4],q[3],qaux[1]) qc.ccx(q[2],q[1],qaux[0]) qc.ccx(qaux[1],qaux[0],q[0]) qc.ccx(q[4],q[3],qaux[1]) qc.ccx(q[2],q[1],qaux[0]) qc.x(q[3]) qc.x(q[1]) # measure the main quantum register qc.measure(q,c) # execute the circuit job = execute(qc,Aer.get_backend('qasm_simulator'),shots=1) counts = job.result().get_counts(qc) for key in counts: the_output = key printed_str = the_input[0:4]+" "+the_input[4]+" --> "+the_output[0:4]+" "+the_output[4] if (the_input!=the_output): printed_str = printed_str + " the output is different than the input" print(printed_str) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer all_inputs=[] for q4 in ['0','1']: for q3 in ['0','1']: for q2 in ['0','1']: for q1 in ['0','1']: for q0 in ['0','1']: all_inputs.append(q4+q3+q2+q1+q0) #print(all_inputs) def c4not(control_state='1111'): # # drawing the circuit # print("Control state is",control_state) print("Drawing the circuit:") qaux = QuantumRegister(2,"qaux") q = QuantumRegister(5,"q") c = ClassicalRegister(5,"c") qc = QuantumCircuit(q,qaux,c) for b in range(4): if control_state[b] == '0': qc.x(q[4-b]) qc.ccx(q[4],q[3],qaux[1]) qc.ccx(q[2],q[1],qaux[0]) qc.ccx(qaux[1],qaux[0],q[0]) qc.ccx(q[4],q[3],qaux[1]) qc.ccx(q[2],q[1],qaux[0]) for b in range(4): if control_state[b] == '0': qc.x(q[4-b]) display(qc.draw(output="mpl",reverse_bits=True)) # # executing the operator on all possible inputs # print("Control state is",control_state) print("input --> output") for the_input in all_inputs: # create the circuit qaux = QuantumRegister(2,"qaux") q = QuantumRegister(5,"q") c = ClassicalRegister(5,"c") qc = QuantumCircuit(q,qaux,c) # set the initial value of the circuit w.r.t. the input if the_input[0] =='1': qc.x(q[4]) if the_input[1] =='1': qc.x(q[3]) if the_input[2] =='1': qc.x(q[2]) if the_input[3] =='1': qc.x(q[1]) if the_input[4] =='1': qc.x(q[0]) # implement the CCNOT gates for b in range(4): if control_state[b] == '0': qc.x(q[4-b]) qc.ccx(q[4],q[3],qaux[1]) qc.ccx(q[2],q[1],qaux[0]) qc.ccx(qaux[1],qaux[0],q[0]) qc.ccx(q[4],q[3],qaux[1]) qc.ccx(q[2],q[1],qaux[0]) for b in range(4): if control_state[b] == '0': qc.x(q[4-b]) # measure the main quantum register qc.measure(q,c) # execute the circuit job = execute(qc,Aer.get_backend('qasm_simulator'),shots=1) counts = job.result().get_counts(qc) for key in counts: the_output = key printed_str = the_input[0:4]+" "+the_input[4]+" --> "+the_output[0:4]+" "+the_output[4] if (the_input!=the_output): printed_str = printed_str + " the output is different than the input" print(printed_str) # try different values #c4not() #c4not('1001') c4not('0011') #c4not('1101') #c4not('0000')