repo
stringclasses
900 values
file
stringclasses
754 values
content
stringlengths
4
215k
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
!pip install qiskit[visualization] # Imports for Qiskit from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * from qiskit import * from qiskit import IBMQ, Aer from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit.visualization import plot_histogram import numpy as np # Various imports import numpy as np from copy import deepcopy from matplotlib import pyplot as plt # IBMQ.save_account('Put your token') # provider = IBMQ.load_account() # IBMQ.get_provider(hub='ibm-q', group='open', project = 'main') # Create the various registers needed clock = QuantumRegister(2, name='clock') input = QuantumRegister(1, name='b') ancilla = QuantumRegister(1, name='ancilla') measurement = ClassicalRegister(2, name='c') # Create an empty circuit with the specified registers circuit = QuantumCircuit(ancilla, clock, input, measurement) circuit.barrier() circuit.draw(output='mpl') def qft_dagger(circ, q, n): circ.h(clock[1]); for j in reversed(range(n)): for k in reversed(range(j+1,n)): circ.cu1(-np.pi/float(2**(k-j)), q[k], q[j]); circ.h(clock[0]); circ.swap(clock[0], clock[1]); def qft(circ, q, n): circ.swap(clock[0], clock[1]); circ.h(clock[0]); for j in reversed(range(n)): for k in reversed(range(j+1,n)): circ.cu1(np.pi/float(2**(k-j)), q[k], q[j]); circ.h(clock[1]); def qpe(circ, clock, target): circuit.barrier() # e^{i*A*t} circuit.cu(np.pi/2, -np.pi/2, np.pi/2, 3*np.pi/4, clock[0], input, label='U'); # e^{i*A*t*2} circuit.cu(np.pi, np.pi, 0, 0, clock[1], input, label='U2'); circuit.barrier(); # Perform an inverse QFT on the register holding the eigenvalues qft_dagger(circuit, clock, 2) def inv_qpe(circ, clock, target): # Perform a QFT on the register holding the eigenvalues qft(circuit, clock, 2) circuit.barrier() # e^{i*A*t*2} circuit.cu(np.pi, np.pi, 0, 0, clock[1], input, label='U2'); #circuit.barrier(); # e^{i*A*t} circuit.cu(np.pi/2, np.pi/2, -np.pi/2, -3*np.pi/4, clock[0], input, label='U'); circuit.barrier() def hhl(circ, ancilla, clock, input, measurement): qpe(circ, clock, input) circuit.barrier() # This section is to test and implement C = 1 circuit.cry(np.pi, clock[0], ancilla) circuit.cry(np.pi/3, clock[1], ancilla) circuit.barrier() circuit.measure(ancilla, measurement[0]) circuit.barrier() inv_qpe(circ, clock, input) # State preparation. (various initial values) # (restart from the second cell if changed) intial_state = [0,1] # intial_state = [1,0] # intial_state = [1/np.sqrt(2),1/np.sqrt(2)] # intial_state = [np.sqrt(0.9),np.sqrt(0.1)] circuit.initialize(intial_state, 3) circuit.barrier() # Perform a Hadamard Transform circuit.h(clock) hhl(circuit, ancilla, clock, input, measurement) # Perform a Hadamard Transform circuit.h(clock) circuit.barrier() circuit.measure(input, measurement[1]) circuit.draw('mpl',scale=1) #print(circuit) # Execute the circuit using the simulator simulator = qiskit.BasicAer.get_backend('qasm_simulator') job = execute(circuit, backend=simulator, shots=1000) #Get the result of the execution result = job.result() # Get the counts, the frequency of each answer counts = result.get_counts(circuit) # Display the results plot_histogram(counts) bcknd = Aer.get_backend('statevector_simulator') job_sim = execute(circuit, bcknd) result = job_sim.result() o_state_result = result.get_statevector(circuit, decimals=3) print(o_state_result) provider.backends() # Choose the backend on which to run the circuit backend = provider.get_backend('ibmq_santiago') from qiskit.tools.monitor import job_monitor # Execute the job job_exp = execute(circuit, backend=backend, shots=8192) # Monitor the job to know where we are in the queue job_monitor(job_exp, interval = 2) # Get the results from the computation results = job_exp.result() # Get the statistics answer = results.get_counts(circuit) # Plot the results plot_histogram(answer) # Auto generated circuit (almost) matching the form from the Wong paper (using cu gates) from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister beta = 0 cycle_time = 0.5 qr = QuantumRegister(4) cr = ClassicalRegister(4) qc = QuantumCircuit(qr, cr, name="main") intial_state = [0,1] qc.initialize(intial_state, qr[3]) qc.barrier(qr[0], qr[1], qr[2], qr[3]) qc.h(qr[1]) qc.h(qr[2]) qc.barrier(qr[0], qr[1], qr[2], qr[3]) # e^{i*A*t} qc.cu(np.pi/2, -np.pi/2, np.pi/2, 3*np.pi/4, qr[1], qr[3], label='U'); # e^{i*A*t*2} qc.cu(np.pi, np.pi, 0, 0, qr[2], qr[3], label='U2'); qc.barrier(qr[0], qr[1], qr[2], qr[3]) qc.h(qr[2]) qc.cu1(-3.14159/2, qr[1], qr[2]) qc.h(qr[1]) qc.swap(qr[2], qr[1]) qc.barrier(qr[0], qr[1], qr[2], qr[3]) qc.cry(3.14159, qr[1], qr[0]) qc.cry(3.14159/3, qr[2], qr[0]) qc.barrier(qr[0], qr[1], qr[2], qr[3]) qc.swap(qr[2], qr[1]) qc.h(qr[1]) qc.cu1(3.14159/2, qr[1], qr[2]) qc.h(qr[2]) qc.barrier(qr[0], qr[1], qr[2], qr[3]) # e^{i*A*t*2} qc.cu(np.pi, np.pi, 0, 0, qr[2], qr[3], label='U2'); # e^{i*A*t} qc.cu(np.pi/2, np.pi/2, -np.pi/2, -3*np.pi/4, qr[1], qr[3], label='U'); qc.barrier(qr[0], qr[1], qr[2], qr[3]) qc.h(qr[1]) qc.h(qr[2]) qc.barrier(qr[0], qr[1], qr[2], qr[3]) qc.measure(qr[0], cr[0]) qc.measure(qr[3], cr[3]) from qiskit import execute, Aer backend = Aer.get_backend("qasm_simulator") # Use Aer qasm_simulator job = execute(qc, backend, shots=1000) result = job.result() counts = result.get_counts(qc) print("Total counts are:", counts) # Draw the circuit print(qc) #qc.draw('mpl',scale=1) # Plot a histogram from qiskit.visualization import plot_histogram plot_histogram(counts) qc.draw('mpl',scale=1) # Same example as above but using the U3 and U1 gates instead of U1 # Initialize with RY instead of "initialize()" from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister beta = 1 qr = QuantumRegister(4) cr = ClassicalRegister(4) qc = QuantumCircuit(qr, cr, name="main") # intial_state = [0,1] # qc.initialize(intial_state, qr[3]) qc.ry(3.14159*beta, qr[3]) qc.barrier(qr[0], qr[1], qr[2], qr[3]) qc.h(qr[1]) qc.h(qr[2]) qc.barrier(qr[0], qr[1], qr[2], qr[3]) # e^{i*A*t} # qc.cu(np.pi/2, -np.pi/2, np.pi/2, 3*np.pi/4, qr[1], qr[3], label='U'); # The CU gate is equivalent to a CU1 on the control bit followed by a CU3 qc.u1(3*3.14159/4, qr[1]) qc.cu3(3.14159/2, -3.14159/2, 3.14159/2, qr[1], qr[3]) # e^{i*A*t*2} # qc.cu(np.pi, np.pi, 0, 0, qr[2], qr[3], label='U2'); qc.cu3(3.14159, 3.14159, 0, qr[2], qr[3]) qc.barrier(qr[0], qr[1], qr[2], qr[3]) qc.h(qr[2]) qc.cu1(-3.14159/2, qr[1], qr[2]) qc.h(qr[1]) qc.swap(qr[2], qr[1]) qc.barrier(qr[0], qr[1], qr[2], qr[3]) qc.cry(3.14159, qr[1], qr[0]) qc.cry(3.14159/3, qr[2], qr[0]) qc.barrier(qr[0], qr[1], qr[2], qr[3]) qc.swap(qr[2], qr[1]) qc.h(qr[1]) qc.cu1(3.14159/2, qr[1], qr[2]) qc.h(qr[2]) qc.barrier(qr[0], qr[1], qr[2], qr[3]) # e^{i*A*t*2} # qc.cu(np.pi, np.pi, 0, 0, qr[2], qr[3], label='U2'); qc.cu3(3.14159, 3.14159, 0, qr[2], qr[3]) # e^{i*A*t} # qc.cu(np.pi/2, np.pi/2, -np.pi/2, -3*np.pi/4, qr[1], qr[3], label='U'); # The CU gate is equivalent to a CU1 on the control bit follwed by a CU3 qc.u1(-3*3.14159/4, qr[1]) qc.cu3(3.14159/2, 3.14159/2, -3.14159/2, qr[1], qr[3]) qc.barrier(qr[0], qr[1], qr[2], qr[3]) qc.h(qr[1]) qc.h(qr[2]) qc.barrier(qr[0], qr[1], qr[2], qr[3]) qc.measure(qr[0], cr[0]) qc.measure(qr[3], cr[3]) # qc.measure(qr, cr) from qiskit import execute, Aer backend = Aer.get_backend("qasm_simulator") # Use Aer qasm_simulator job = execute(qc, backend, shots=1000) result = job.result() counts = result.get_counts(qc) print("Total counts are:", counts) # Draw the circuit print(qc) # Plot a histogram from qiskit.visualization import plot_histogram plot_histogram(counts) qc.draw('mpl',scale=1)
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
# -*- coding: utf-8 -*- """ sparse Hamiltonian simulation """ from math import pi import numpy as np from scipy.linalg import expm from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import Aer, execute def Ham_sim(H, t): """ H : sparse matrix t : time parameter returns : QuantumCircuit for e^(-i*H*t) """ # read in number of qubits N = len(H) n = int(np.log2(N)) # read in matrix elements #diag_el = H[0,0] for j in range(1,N): if H[0,j] != 0: off_diag_el = H[0,j] break j_bin = np.binary_repr(j, width=n) sign = (-1)**((j_bin.count('1'))%2) # create registers qreg_a = QuantumRegister(n, name='q_a') creg = ClassicalRegister(n, name='c') qreg_b = QuantumRegister(n, name='q_b') # ancilla register anc_reg = QuantumRegister(1, name='q_anc') qc = QuantumCircuit(qreg_a, qreg_b, anc_reg, creg) # apply sparse H oracle gate qc = V_gate(qc, H, qreg_a, qreg_b) # apply W gate that diagonalizes SWAP operator and Toffoli for q in range(n): qc = W_gate(qc, qreg_a[q], qreg_b[q]) qc.x(qreg_b[q]) qc.ccx(qreg_a[q], qreg_b[q], anc_reg[0]) # phase qc.p(sign*2*t*off_diag_el, anc_reg[0]) # uncompute for q in range(n): j = n-1-q qc.ccx(qreg_a[j], qreg_b[j], anc_reg[0]) qc.x(qreg_b[j]) qc = W_gate(qc, qreg_a[j], qreg_b[j]) # sparse H oracle gate is its own inverse qc = V_gate(qc, H, qreg_a, qreg_b) # measure #qc.barrier() #qc.measure(qreg_a[0:], creg[0:]) return qc def control_Ham_sim(n, H, t): """ H : sparse matrix t : time parameter returns : QuantumCircuit for control-e^(-i*H*t) """ qreg = QuantumRegister(n) qreg_b = QuantumRegister(n) control_reg = QuantumRegister(1) anc_reg = QuantumRegister(1) qc = QuantumCircuit(qreg, qreg_b, control_reg, anc_reg) control = control_reg[0] anc = anc_reg[0] # read in number of qubits N = len(H) n = int(np.log2(N)) # read in matrix elements diag_el = H[0,0] for j in range(1,N): if H[0,j] != 0: off_diag_el = H[0,j] break j_bin = np.binary_repr(j, width=n) sign = (-1)**((j_bin.count('1'))%2) # use ancilla for phase kickback to simulate diagonal part of H qc.x(anc) qc.cp(-t*(diag_el+sign*off_diag_el), control, anc) qc.x(anc) # apply sparse H oracle gate qc = V_gate(qc, H, qreg, qreg_b) # apply W gate that diagonalizes SWAP operator and Toffoli for q in range(n): qc = W_gate(qc, qreg[q], qreg_b[q]) qc.x(qreg_b[q]) qc.ccx(qreg[q], qreg_b[q], anc) # phase qc.cp((sign*2*t*off_diag_el), control, anc) # uncompute for q in range(n): j = n-1-q qc.ccx(qreg[j], qreg_b[j], anc) qc.x(qreg_b[j]) qc = W_gate(qc, qreg[j], qreg_b[j]) # sparse H oracle gate is its own inverse qc = V_gate(qc, H, qreg, qreg_b) return qc def V_gate(qc, H, qreg_a, qreg_b): """ Hamiltonian oracle V|a,b> = |a,b+v(a)> """ # index of non-zero off diagonal in first row of H n = qreg_a.size N = len(H) for i in range(1,N): if H[0,i] != 0: break i_bin = np.binary_repr(i, width=n) for q in range(n): a, b = qreg_a[q], qreg_b[q] if i_bin[n-1-q] == '1': qc.x(a) qc.cx(a,b) qc.x(a) else: qc.cx(a,b) return qc def W_gate(qc, q0, q1): """ W : |00> -> |00> |01> -> |01> + |10> |10> -> |01> - |10> |11> -> |11> """ qc.rz(-pi,q1) qc.rz(-3*pi/2,q0) qc.ry(-pi/2,q1) qc.ry(-pi/2,q0) qc.rz(-pi,q1) qc.rz(-3*pi/2,q0) qc.cx(q0,q1) qc.rz(-7*pi/4,q1) qc.rx(-pi/2,q0) qc.rx(-pi,q1) qc.rz(-3*pi/2,q0) qc.cx(q0,q1) qc.ry(-pi/2,q1) qc.rx(-pi/4,q1) qc.cx(q1,q0) qc.rz(-3*pi/2,q0) return qc def qc_unitary(qc): simulator = Aer.get_backend('unitary_simulator') result = execute(qc, simulator).result() U = np.array(result.get_unitary(qc)) return U def sim_circuit(qc, shots): simulator = Aer.get_backend('qasm_simulator') result = execute(qc, simulator, shots=shots).result() outcomes = result.get_counts(qc) return outcomes def true_distr(H, t, psi0=0): N = len(H) n = int(np.log2(N)) U = expm(-1j*H*t) psi = U[:,psi0] probs = np.array([np.abs(amp)**2 for amp in psi]) probs_bin = {} for j, p in enumerate(probs): if p > 0: j_bin = np.binary_repr(j, width=n) probs_bin[j_bin] = p return probs_bin def generate_sparse_H(n, k, diag_el=0.75, off_diag_el=-0.25): """ n (int) : number of qubits. H will be 2^n by 2^n k (int) : between 1,...,2^n-1. determines which H will be generated in class of matrices generates 2-sparse H with 1.5 on diagonal and 0.5 on off diagonal """ N = 2**n k_bin = np.binary_repr(k, width=n) # initialize H H = np.diag(diag_el*np.ones(N)) pairs = [] tot_indices = [] for i in range(N): i_bin = np.binary_repr(i, width=n) j_bin = '' for q in range(n): if i_bin[q] == k_bin[q]: j_bin += '0' else: j_bin += '1' j = int(j_bin,2) if i not in tot_indices and j not in tot_indices: pairs.append([i,j]) tot_indices.append(i) tot_indices.append(j) # fill in H for pair in pairs: i, j = pair[0], pair[1] H[i,j] = off_diag_el H[j,i] = off_diag_el return H def condition_number(A): evals = np.linalg.eigh(A)[0] abs_evals = [abs(e) for e in evals] if min(abs_evals) == 0.0: return 'inf' else: k = max(abs_evals)/min(abs_evals) return k
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
""" Uniformly controlled rotation from arXiv:0407010 """ import numpy as np from sympy.combinatorics.graycode import GrayCode from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import Aer, execute def dot_product(str1, str2): """ dot product between 2 binary string """ prod = 0 for j in range(len(str1)): if str1[j] == '1' and str2[j] == '1': prod = (prod + 1)%2 return prod def conversion_matrix(N): M = np.zeros((N,N)) n = int(np.log2(N)) gc_list = list(GrayCode(n).generate_gray()) # list of gray code strings for i in range(N): g_i = gc_list[i] for j in range(N): b_j = np.binary_repr(j, width=n)[::-1] M[i,j] = (-1)**dot_product(g_i, b_j)/(2**n) return M def alpha2theta(alpha): """ alpha : list of angles that get applied controlled on 0,...,2^n-1 theta : list of angles occuring in circuit construction """ N = len(alpha) M = conversion_matrix(N) theta = M @ np.array(alpha) return theta def uni_con_rot_recursive_step(qc, qubits, anc, theta): """ qc : qiskit QuantumCircuit object qubits : qiskit QuantumRegister object anc : ancilla qubit register on which rotation acts theta : list of angles specifying rotations for 0, ..., 2^(n-1) """ if type(qubits) == list: n = len(qubits) else: n = qubits.size # lowest level of recursion if n == 1: qc.ry(theta[0], anc[0]) qc.cx(qubits[0], anc[0]) qc.ry(theta[1], anc[0]) elif n > 1: qc = uni_con_rot_recursive_step(qc, qubits[1:], anc, theta[0:int(len(theta)/2)]) qc.cx(qubits[0], anc[0]) qc = uni_con_rot_recursive_step(qc, qubits[1:], anc, theta[int(len(theta)/2):]) return qc def uniformly_controlled_rot(n, theta): qubits = QuantumRegister(n) anc_reg = QuantumRegister(1) qc = QuantumCircuit(qubits, anc_reg, name = 'INV_ROT') qc = uni_con_rot_recursive_step(qc, qubits, anc_reg, theta) qc.cx(qubits[0], anc_reg[0]) return qc # def uniformly_controlled_rot(qc, qubits, anc, theta): # """ # qc : qiskit QuantumCircuit object # qubits : qiskit QuantumRegister object # anc : ancilla qubit register on which rotation acts # theta : list of angles specifying rotations for 0, ..., 2^(n-1) # """ # qc = uni_con_rot_recursive_step(qc, qubits, anc, theta) # qc.cx(qubits[0], anc[0]) # return qc def test_circuit(n): shots = 10000 C = 0.25 N = 2**n # make list of rotation angles alpha = [2*np.arcsin(C)] for j in range(1,N): j_rev = int(np.binary_repr(j, width=n)[::-1],2) alpha.append(2*np.arcsin(C*N/j_rev)) theta = alpha2theta(alpha) for x in range(N): # state prep #x_bin = np.binary_repr(x, width=n) qubits = QuantumRegister(n) anc = QuantumRegister(1) cr = ClassicalRegister(1) qc = QuantumCircuit(qubits, anc, cr) # state prep x_bin = np.binary_repr(x, width=n) for q in range(n): if x_bin[n-1-q] == '1': qc.x(q) qc.barrier() qc = uniformly_controlled_rot(qc, qubits, anc, theta) qc.barrier() qc.measure(anc[0], cr[0]) outcomes = sim_circuit(qc, shots) print(round(outcomes['1']/shots, 4)) def sim_circuit(qc, shots): simulator = Aer.get_backend('qasm_simulator') result = execute(qc, simulator, shots=shots).result() outcomes = result.get_counts(qc) return outcomes
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
!pip install qiskit[visualization] # Imports for Qiskit from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * from qiskit import * from qiskit import IBMQ, Aer from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit.visualization import plot_histogram import numpy as np # Various imports import numpy as np from copy import deepcopy from matplotlib import pyplot as plt # IBMQ.save_account('Put your token') # provider = IBMQ.load_account() # IBMQ.get_provider(hub='ibm-q', group='open', project = 'main') # Create the various registers needed clock = QuantumRegister(2, name='clock') input = QuantumRegister(1, name='b') ancilla = QuantumRegister(1, name='ancilla') measurement = ClassicalRegister(2, name='c') # Create an empty circuit with the specified registers circuit = QuantumCircuit(ancilla, clock, input, measurement) circuit.barrier() circuit.draw(output='mpl') def qft_dagger(circ, q, n): circ.h(clock[1]); for j in reversed(range(n)): for k in reversed(range(j+1,n)): circ.cu1(-np.pi/float(2**(k-j)), q[k], q[j]); circ.h(clock[0]); circ.swap(clock[0], clock[1]); def qft(circ, q, n): circ.swap(clock[0], clock[1]); circ.h(clock[0]); for j in reversed(range(n)): for k in reversed(range(j+1,n)): circ.cu1(np.pi/float(2**(k-j)), q[k], q[j]); circ.h(clock[1]); def qpe(circ, clock, target): circuit.barrier() # e^{i*A*t} circuit.cu(np.pi/2, -np.pi/2, np.pi/2, 3*np.pi/4, clock[0], input, label='U'); # e^{i*A*t*2} circuit.cu(np.pi, np.pi, 0, 0, clock[1], input, label='U2'); circuit.barrier(); # Perform an inverse QFT on the register holding the eigenvalues qft_dagger(circuit, clock, 2) def inv_qpe(circ, clock, target): # Perform a QFT on the register holding the eigenvalues qft(circuit, clock, 2) circuit.barrier() # e^{i*A*t*2} circuit.cu(np.pi, np.pi, 0, 0, clock[1], input, label='U2'); #circuit.barrier(); # e^{i*A*t} circuit.cu(np.pi/2, np.pi/2, -np.pi/2, -3*np.pi/4, clock[0], input, label='U'); circuit.barrier() def hhl(circ, ancilla, clock, input, measurement): qpe(circ, clock, input) circuit.barrier() # This section is to test and implement C = 1 circuit.cry(np.pi, clock[0], ancilla) circuit.cry(np.pi/3, clock[1], ancilla) circuit.barrier() circuit.measure(ancilla, measurement[0]) circuit.barrier() inv_qpe(circ, clock, input) # State preparation. (various initial values) # (restart from second cell if changed) intial_state = [0,1] # intial_state = [1,0] # intial_state = [1/np.sqrt(2),1/np.sqrt(2)] # intial_state = [np.sqrt(0.9),np.sqrt(0.1)] circuit.initialize(intial_state, 3) circuit.barrier() # Perform a Hadamard Transform circuit.h(clock) hhl(circuit, ancilla, clock, input, measurement) # Perform a Hadamard Transform circuit.h(clock) circuit.barrier() circuit.measure(input, measurement[1]) circuit.draw('mpl',scale=1) #print(circuit) # Execute the circuit using the simulator simulator = qiskit.BasicAer.get_backend('qasm_simulator') job = execute(circuit, backend=simulator, shots=1000) #Get the result of the execution result = job.result() # Get the counts, the frequency of each answer counts = result.get_counts(circuit) # Display the results plot_histogram(counts) bcknd = Aer.get_backend('statevector_simulator') job_sim = execute(circuit, bcknd) result = job_sim.result() o_state_result = result.get_statevector(circuit, decimals=3) print(o_state_result) provider.backends() # Choose the backend on which to run the circuit backend = provider.get_backend('ibmq_santiago') from qiskit.tools.monitor import job_monitor # Execute the job job_exp = execute(circuit, backend=backend, shots=8192) # Monitor the job to know where we are in the queue job_monitor(job_exp, interval = 2) # Get the results from the computation results = job_exp.result() # Get the statistics answer = results.get_counts(circuit) # Plot the results plot_histogram(answer) # Auto generated circuit (almost) matching the form from the Wong paper (using cu gates) from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister beta = 0 cycle_time = 0.5 qr = QuantumRegister(4) cr = ClassicalRegister(4) qc = QuantumCircuit(qr, cr, name="main") intial_state = [0,1] qc.initialize(intial_state, qr[3]) qc.barrier(qr[0], qr[1], qr[2], qr[3]) qc.h(qr[1]) qc.h(qr[2]) qc.barrier(qr[0], qr[1], qr[2], qr[3]) # e^{i*A*t} qc.cu(np.pi/2, -np.pi/2, np.pi/2, 3*np.pi/4, qr[1], qr[3], label='U'); # e^{i*A*t*2} qc.cu(np.pi, np.pi, 0, 0, qr[2], qr[3], label='U2'); qc.barrier(qr[0], qr[1], qr[2], qr[3]) qc.h(qr[2]) qc.cu1(-3.14159/2, qr[1], qr[2]) qc.h(qr[1]) qc.swap(qr[2], qr[1]) qc.barrier(qr[0], qr[1], qr[2], qr[3]) qc.cry(3.14159, qr[1], qr[0]) qc.cry(3.14159/3, qr[2], qr[0]) qc.barrier(qr[0], qr[1], qr[2], qr[3]) qc.swap(qr[2], qr[1]) qc.h(qr[1]) qc.cu1(3.14159/2, qr[1], qr[2]) qc.h(qr[2]) qc.barrier(qr[0], qr[1], qr[2], qr[3]) # e^{i*A*t*2} qc.cu(np.pi, np.pi, 0, 0, qr[2], qr[3], label='U2'); # e^{i*A*t} qc.cu(np.pi/2, np.pi/2, -np.pi/2, -3*np.pi/4, qr[1], qr[3], label='U'); qc.barrier(qr[0], qr[1], qr[2], qr[3]) qc.h(qr[1]) qc.h(qr[2]) qc.barrier(qr[0], qr[1], qr[2], qr[3]) qc.measure(qr[0], cr[0]) qc.measure(qr[3], cr[3]) from qiskit import execute, Aer backend = Aer.get_backend("qasm_simulator") # Use Aer qasm_simulator job = execute(qc, backend, shots=1000) result = job.result() counts = result.get_counts(qc) print("Total counts are:", counts) # Draw the circuit print(qc) #qc.draw('mpl',scale=1) # Plot a histogram from qiskit.visualization import plot_histogram plot_histogram(counts) qc.draw('mpl',scale=1) # Same example as above but using the U3 and U1 gates instead of U1 # Initialize with RY instead of "initialize()" from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister beta = 1 qr = QuantumRegister(4) cr = ClassicalRegister(4) qc = QuantumCircuit(qr, cr, name="main") # intial_state = [0,1] # qc.initialize(intial_state, qr[3]) qc.ry(3.14159*beta, qr[3]) qc.barrier(qr[0], qr[1], qr[2], qr[3]) qc.h(qr[1]) qc.h(qr[2]) qc.barrier(qr[0], qr[1], qr[2], qr[3]) # e^{i*A*t} # qc.cu(np.pi/2, -np.pi/2, np.pi/2, 3*np.pi/4, qr[1], qr[3], label='U'); # The CU gate is equivalent to a CU1 on the control bit followed by a CU3 qc.u1(3*3.14159/4, qr[1]) qc.cu3(3.14159/2, -3.14159/2, 3.14159/2, qr[1], qr[3]) # e^{i*A*t*2} # qc.cu(np.pi, np.pi, 0, 0, qr[2], qr[3], label='U2'); qc.cu3(3.14159, 3.14159, 0, qr[2], qr[3]) qc.barrier(qr[0], qr[1], qr[2], qr[3]) qc.h(qr[2]) qc.cu1(-3.14159/2, qr[1], qr[2]) qc.h(qr[1]) qc.swap(qr[2], qr[1]) qc.barrier(qr[0], qr[1], qr[2], qr[3]) qc.cry(3.14159, qr[1], qr[0]) qc.cry(3.14159/3, qr[2], qr[0]) qc.barrier(qr[0], qr[1], qr[2], qr[3]) qc.swap(qr[2], qr[1]) qc.h(qr[1]) qc.cu1(3.14159/2, qr[1], qr[2]) qc.h(qr[2]) qc.barrier(qr[0], qr[1], qr[2], qr[3]) # e^{i*A*t*2} # qc.cu(np.pi, np.pi, 0, 0, qr[2], qr[3], label='U2'); qc.cu3(3.14159, 3.14159, 0, qr[2], qr[3]) # e^{i*A*t} # qc.cu(np.pi/2, np.pi/2, -np.pi/2, -3*np.pi/4, qr[1], qr[3], label='U'); # The CU gate is equivalent to a CU1 on the control bit follwed by a CU3 qc.u1(-3*3.14159/4, qr[1]) qc.cu3(3.14159/2, 3.14159/2, -3.14159/2, qr[1], qr[3]) qc.barrier(qr[0], qr[1], qr[2], qr[3]) qc.h(qr[1]) qc.h(qr[2]) qc.barrier(qr[0], qr[1], qr[2], qr[3]) qc.measure(qr[0], cr[0]) qc.measure(qr[3], cr[3]) # qc.measure(qr, cr) from qiskit import execute, Aer backend = Aer.get_backend("qasm_simulator") # Use Aer qasm_simulator job = execute(qc, backend, shots=1000) result = job.result() counts = result.get_counts(qc) print("Total counts are:", counts) # Draw the circuit print(qc) # Plot a histogram from qiskit.visualization import plot_histogram plot_histogram(counts) qc.draw('mpl',scale=1)
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
""" Hidden Shift Benchmark Program - QSim """ import sys import time import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister 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 = "Hidden Shift" np.random.seed(0) verbose = False # saved circuits for display QC_ = None Uf_ = None Ug_ = None ############### Circuit Definition # Uf oracle where Uf|x> = f(x)|x>, f(x) = {-1,1} def Uf_oracle(num_qubits, secret_int): # Initialize qubits qubits qr = QuantumRegister(num_qubits) qc = QuantumCircuit(qr, name=f"Uf") # Perform X on each qubit that matches a bit in secret string s = ('{0:0'+str(num_qubits)+'b}').format(secret_int) for i_qubit in range(num_qubits): if s[num_qubits-1-i_qubit]=='1': qc.x(qr[i_qubit]) for i_qubit in range(0,num_qubits-1,2): qc.cz(qr[i_qubit], qr[i_qubit+1]) # Perform X on each qubit that matches a bit in secret string s = ('{0:0'+str(num_qubits)+'b}').format(secret_int) for i_qubit in range(num_qubits): if s[num_qubits-1-i_qubit]=='1': qc.x(qr[i_qubit]) return qc # Generate Ug oracle where Ug|x> = g(x)|x>, g(x) = f(x+s) def Ug_oracle(num_qubits): # Initialize first n qubits qr = QuantumRegister(num_qubits) qc = QuantumCircuit(qr, name=f"Ug") for i_qubit in range(0,num_qubits-1,2): qc.cz(qr[i_qubit], qr[i_qubit+1]) return qc def HiddenShift (num_qubits, secret_int): # allocate qubits qr = QuantumRegister(num_qubits); cr = ClassicalRegister(num_qubits); qc = QuantumCircuit(qr, cr, name=f"hs-{num_qubits}-{secret_int}") # Start with Hadamard on all input qubits for i_qubit in range(num_qubits): qc.h(qr[i_qubit]) qc.barrier() # Generate Uf oracle where Uf|x> = f(x)|x>, f(x) = {-1,1} Uf = Uf_oracle(num_qubits, secret_int) qc.append(Uf,qr) qc.barrier() # Again do Hadamard on all qubits for i_qubit in range(num_qubits): qc.h(qr[i_qubit]) qc.barrier() # Generate Ug oracle where Ug|x> = g(x)|x>, g(x) = f(x+s) Ug = Ug_oracle(num_qubits) qc.append(Ug,qr) qc.barrier() # End with Hadamard on all qubits for i_qubit in range(num_qubits): qc.h(qr[i_qubit]) qc.barrier() # measure all qubits qc.measure(qr, cr) # save smaller circuit example for display global QC_, Uf_, Ug_ if QC_ == None or num_qubits <= 6: if num_qubits < 9: QC_ = qc if Uf_ == None or num_qubits <= 6: if num_qubits < 9: Uf_ = Uf if Ug_ == None or num_qubits <= 6: if num_qubits < 9: Ug_ = Ug # return a handle on the circuit return qc ############### Circuit end # Analyze and print measured results # Expected result is always the secret_int, so fidelity calc is simple def analyze_and_print_result (qc, result, num_qubits, secret_int, num_shots): 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 if verbose: print(f"For secret int {secret_int} measured: {probs}") # create the key that is expected to have all the measurements (for this circuit) key = format(secret_int, f"0{num_qubits}b") # correct distribution is measuring the key 100% of the time correct_dist = {key: 1.0} # use our polarization fidelity rescaling fidelity = metrics.polarization_fidelity(probs, correct_dist) return probs, fidelity ################ Benchmark Loop # Execute program with default parameters def run (min_qubits=2, max_qubits=6, skip_qubits=2, max_circuits=3, num_shots=100, backend_id='dm_simulator', provider_backend=None, # hub="ibm-q", group="open", project="main", exec_options=None, context=None): print(f"{benchmark_name} Benchmark Program - QSim") # validate parameters (smallest circuit is 2 qubits) max_qubits = max(2, max_qubits) min_qubits = min(max(2, min_qubits), max_qubits) if min_qubits % 2 == 1: min_qubits += 1 # min_qubits must be even skip_qubits = max(2, skip_qubits) #print(f"min, max qubits = {min_qubits} {max_qubits}") # create context identifier if context is None: context = f"{benchmark_name} Benchmark" ########## # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler (qc, result, num_qubits, s_int, num_shots): # determine fidelity of result set num_qubits = int(num_qubits) counts, fidelity = analyze_and_print_result(qc, result, num_qubits, int(s_int), num_shots) metrics.store_metric(num_qubits, s_int, '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 num_qubits in range(min_qubits, max_qubits + 1, 2): # determine number of circuits to execute for this group num_circuits = min(2 ** (num_qubits), max_circuits) print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") # determine range of secret strings to loop over if 2**(num_qubits) <= max_circuits: s_range = list(range(num_circuits)) else: s_range = np.random.choice(2**(num_qubits), num_circuits, False) # loop over limited # of secret strings for this for s_int in s_range: # create the circuit for given qubit size and secret string, store time metric ts = time.time() qc = HiddenShift(num_qubits, s_int).reverse_bits() #reverse_bits() is to change the endianness metrics.store_metric(num_qubits, s_int, 'create_time', time.time()-ts) # collapse the sub-circuit levels used in this benchmark (for qiskit) qc2 = qc.decompose() # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc2, num_qubits, s_int, shots=num_shots) # Wait for some active circuits to complete; report metrics when groups 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("\nQuantum Oracle 'Uf' ="); print(Uf_ if Uf_ != None else " ... too large!") print("\nQuantum Oracle 'Ug' ="); print(Ug_ if Ug_ != None else " ... too large!") # Plot metrics for all circuit sizes metrics.plot_metrics(f"Benchmark Results - {benchmark_name} - QSim") # if main, execute method 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/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
min_qubits=2 max_qubits=8 max_circuits=1 num_shots=1000 backend_id="qasm_simulator" hub="ibm-q"; group="open"; project="main" provider_backend = None exec_options = {} # # ========================== # # *** If using IBMQ hardware, run this once to authenticate # from qiskit import IBMQ # IBMQ.save_account('YOUR_API_TOKEN_HERE') # # *** If you are part of an IBMQ group, set hub, group, and project name here # hub="YOUR_HUB_NAME"; group="YOUR_GROUP_NAME"; project="YOUR_PROJECT_NAME" # # *** This example shows how to specify an IBMQ backend using a known "backend_id" # exec_options = { "optimization_level":3, "use_sessions":True, "resilience_level":1} # backend_id="ibmq_belem" # # ========================== # # *** If using Azure Quantum, use this hub identifier and specify the desired backend_id # # Identify your resources with env variables AZURE_QUANTUM_RESOURCE_ID and AZURE_QUANTUM_LOCATION # hub="azure-quantum"; group="open"; project="QED-C App-Oriented Benchmarks - Qiskit Version" # backend_id="<YOUR_BACKEND_NAME_HERE>" # # ========================== # The remaining examples create a provider instance and get a backend from it # # An example using IonQ provider # from qiskit_ionq import IonQProvider # provider = IonQProvider() # Be sure to set the QISKIT_IONQ_API_TOKEN environment variable # provider_backend = provider.get_backend("ionq_qpu") # backend_id="ionq_qpu" # # An example using BlueQubit provider # import sys # sys.path.insert(1, "../..") # import os, bluequbit, _common.executors.bluequbit_executor as bluequbit_executor # provider_backend = bluequbit.init() # backend_id="BlueQubit-CPU" # exec_options = { "executor": bluequbit_executor.run, "device":'cpu' } # # *** Here's an example of using a typical custom provider backend (e.g. AQT simulator) # import os # from qiskit_aqt_provider import AQTProvider # provider = AQTProvider(os.environ.get('AQT_ACCESS_KEY')) # get your key from environment # provider_backend = provider.backends.aqt_qasm_simulator_noise_1 # backend_id="aqt_qasm_simulator_noise_1" import os, hydrogen_lattice_benchmark #backend_id="qasm_simulator" # Additional arguments specific to Hydrogen Lattice benchmark method 2 plotting hl_app_args = dict( # display options for line plots (pairwise) line_y_metrics=['energy', 'accuracy_ratio_error'], # + 'solution_quality', 'accuracy_ratio', 'solution_quality_error' line_x_metrics=['iteration_count', 'cumulative_exec_time'], # + 'cumulative_elapsed_time' plot_layout_style='grid', # plot layout, can be 'grid', 'stacked', or 'individual' # display options for bar plots (exec time, accuracy ratio) bar_y_metrics=["average_exec_times", "accuracy_ratio_error"], bar_x_metrics=["num_qubits"], use_logscale_for_times=False, # use log scale for cumulative exec time bar chart show_elapsed_times=True, # include elapsed time in average_exec_times plot # display options for area plots (multiplicative) score_metric=['accuracy_ratio'], # + 'solution_quality' x_metric=['cumulative_exec_time', 'cumulative_elapsed_time'], # + 'cumulative_opt_exec_time', ) hydrogen_lattice_benchmark.load_data_and_plot(os.path.join('__data', backend_id, ''), backend_id=backend_id, **hl_app_args) import sys sys.path.insert(1, "hydrogen-lattice/qiskit") import hydrogen_lattice_benchmark # define a custom Nelder-Mead minimizer function from scipy.optimize import minimize tol=0.01 max_iter=30 def my_minimizer(objective_function, initial_parameters, callback): ret = minimize(objective_function, x0=initial_parameters, # a custom minimizer method='nelder-mead', options={'xatol':tol, 'fatol':tol, 'maxiter': max_iter, 'maxfev': max_iter, 'disp': False}, callback=callback) print(f"\n... my_minimizer completed, return = \n{ret}") return ret # Additional arguments specific to Hydrogen Lattice benchmark method 2 hl_app_args = dict( max_iter=30, # maximum minimizer iterations to perform comfort=True, # show 'comfort dots' during execution minimizer_function=my_minimizer, # use custom minimizer function ) # Run the benchmark in method 2 hydrogen_lattice_benchmark.run( min_qubits=min_qubits, max_qubits=max_qubits, max_circuits=max_circuits, num_shots=num_shots, method=2, backend_id=backend_id, provider_backend=provider_backend, hub=hub, group=group, project=project, exec_options=exec_options, **hl_app_args ) import sys sys.path.insert(1, "hydrogen-lattice/qiskit") import hydrogen_lattice_benchmark # Arguments specific to execution of single instance of the Hydrogen Lattice objective function hl_app_args = dict( num_qubits=4, # problem size, dexscribed by number of qubits num_shots=1000, # number of shots to perform radius=1.0, # select single problem radius, None = use first radius parameter_mode=1, # 1 - use single theta parameter, 2 - map multiple thetas to pairs thetas_array=[ 0.0 ], # use custom thetas_array backend_id=backend_id, provider_backend=provider_backend, hub=hub, group=group, project=project, exec_options=exec_options, ) # Execute the objective function once with the given arguments energy, key_metrics = hydrogen_lattice_benchmark.run_objective_function(**hl_app_args) # Print the return value of energy print(f"Final Energy value = {energy}") # Print key metrics from execution print(f"Key Metrics = {key_metrics}") import sys sys.path.insert(1, "hydrogen-lattice/qiskit") import hydrogen_lattice_benchmark # Arguments specific to Hydrogen Lattice benchmark method (2) hl_app_args = dict( min_qubits=2, # configure min, max widths, and shots here max_qubits=4, num_shots=1000, max_circuits=4, # number of 'restarts' to perform at same radius radius=0.75, # select single problem radius for multiple execution of same circuit thetas_array=None, # specify a custom thetas_array parameter_mode=1, # 1 - use single theta parameter, 2 - map multiple thetas to pairs parameterized=False, # use Parameter objects in circuit, cache transpiled circuits for performance max_iter=30, # maximum minimizer iterations to perform minimizer_tolerance=0.001, # tolerance passed to the minimizer comfort=True, # show 'comfort dots' during execution # disable print of results at every iteration show_results_summary=False, # display options for bar plots (exec time, accuracy ratio) bar_y_metrics=["average_exec_times", "accuracy_ratio_error"], bar_x_metrics=["num_qubits"], use_logscale_for_times=True, # use log scale for cumulative exec time bar chart show_elapsed_times=True, # include elapsed time in average_exec_times plot # disable options for line plots and area plots line_y_metrics=None, score_metric=None, ) # Run the benchmark in method 2 hydrogen_lattice_benchmark.run(method=2, backend_id=backend_id, provider_backend=provider_backend, hub=hub, group=group, project=project, exec_options=exec_options, **hl_app_args)
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
min_qubits=2 max_qubits=8 max_circuits=1 num_shots=1000 backend_id="qasm_simulator" #backend_id="statevector_simulator" hub="ibm-q"; group="open"; project="main" provider_backend = None exec_options = {} # # ========================== # # *** If using IBMQ hardware, run this once to authenticate # from qiskit import IBMQ # IBMQ.save_account('YOUR_API_TOKEN_HERE') # # *** If you are part of an IBMQ group, set hub, group, and project name here # hub="YOUR_HUB_NAME"; group="YOUR_GROUP_NAME"; project="YOUR_PROJECT_NAME" # # *** This example shows how to specify an IBMQ backend using a known "backend_id" # exec_options = { "optimization_level":3, "use_sessions":True, "resilience_level":1} # backend_id="ibmq_belem" # # ========================== # # *** If using Azure Quantum, use this hub identifier and specify the desired backend_id # # Identify your resources with env variables AZURE_QUANTUM_RESOURCE_ID and AZURE_QUANTUM_LOCATION # hub="azure-quantum"; group="open"; project="QED-C App-Oriented Benchmarks - Qiskit Version" # backend_id="<YOUR_BACKEND_NAME_HERE>" # # ========================== # The remaining examples create a provider instance and get a backend from it # # An example using IonQ provider # from qiskit_ionq import IonQProvider # provider = IonQProvider() # Be sure to set the QISKIT_IONQ_API_TOKEN environment variable # provider_backend = provider.get_backend("ionq_qpu") # backend_id="ionq_qpu" # # An example using BlueQubit provider # import sys # sys.path.insert(1, "../..") # import os, bluequbit, _common.executors.bluequbit_executor as bluequbit_executor # provider_backend = bluequbit.init() # backend_id="BlueQubit-CPU" # exec_options = { "executor": bluequbit_executor.run, "device":'cpu' } # # *** Here's an example of using a typical custom provider backend (e.g. AQT simulator) # import os # from qiskit_aqt_provider import AQTProvider # provider = AQTProvider(os.environ.get('AQT_ACCESS_KEY')) # get your key from environment # provider_backend = provider.backends.aqt_qasm_simulator_noise_1 # backend_id="aqt_qasm_simulator_noise_1" # Custom optimization options can be specified in this cell (below is an example) import sys sys.path.insert(1, "../../") # # Example of pytket Transformer # import _common.transformers.tket_optimiser as tket_optimiser # exec_options.update({ "optimization_level": 0, "layout_method":'sabre', "routing_method":'sabre', "transformer": tket_optimiser.high_optimisation }) # # Define a custom noise model to be used during execution # import _common.custom.custom_qiskit_noise_model as custom_qiskit_noise_model # exec_options.update({ "noise_model": custom_qiskit_noise_model.my_noise_model() }) # # Example of mthree error mitigation # import _common.postprocessors.mthree.mthree_em as mthree_em # exec_options.update({ "postprocessor": mthree_em.get_mthree_handlers(backend_id, provider_backend) }) ################## # Addition options for exploring Hydrogen Lattice import sys sys.path.insert(1, "../../_common") sys.path.insert(1, "../../_common/qiskit") # Set these True to enable verbose and verbose_time execution import execute execute.verbose=False execute.verbose_time=False # Set noise model to None. This way the Sampler version uses same noise model as Estimator version execute.noise=None # Appendage for storing the data files and identifying the plots import metrics metrics.data_suffix="" import sys sys.path.insert(1, "hydrogen-lattice/qiskit") import hydrogen_lattice_benchmark # Arguments applicable to Hydrogen Lattice benchmark method (1) hl_app_args = dict( radius=0.75, # select single problem radius, None = use max_circuits problem thetas_array=None, # specify a custom thetas_array parameter_mode=1, # 1 - use single theta parameter, 2 - map multiple thetas to pairs parameterized=True, # use Parameter objects in circuit, cache transpiled circuits for performance use_estimator=False, # use the Estimator for execution of objective function ) # Run the benchmark in method 1 hydrogen_lattice_benchmark.run( min_qubits=min_qubits, max_qubits=max_qubits, max_circuits=max_circuits, num_shots=num_shots, method=1, backend_id=backend_id, provider_backend=provider_backend, hub=hub, group=group, project=project, exec_options=exec_options, **hl_app_args) import sys sys.path.insert(1, "hydrogen-lattice/qiskit") import hydrogen_lattice_benchmark # Arguments specific to Hydrogen Lattice benchmark method (2) hl_app_args = dict( radius=0.75, # select single problem radius, None = use max_circuits problems thetas_array=None, # specify a custom thetas_array parameter_mode=1, # 1 - use single theta parameter, 2 - map multiple thetas to pairs parameterized=False, # use Parameter objects in circuit, cache transpiled circuits for performance use_estimator=False, # use the Estimator for execution of objective function max_iter=30, # maximum minimizer iterations to perform minimizer_tolerance=0.001, # tolerance passed to the minimizer comfort=True, # show 'comfort dots' during execution ) # Run the benchmark in method 2 hydrogen_lattice_benchmark.run( min_qubits=min_qubits, max_qubits=max_qubits, max_circuits=max_circuits, num_shots=num_shots, method=2, backend_id=backend_id, provider_backend=provider_backend, hub=hub, group=group, project=project, exec_options=exec_options, **hl_app_args) import sys sys.path.insert(1, "hydrogen-lattice/qiskit") import hydrogen_lattice_benchmark # DEVNOTE: Estimator is using no noise by default import execute execute.noise = None # Arguments specific to Hydrogen Lattice benchmark method (2) hl_app_args = dict( radius=0.75, # select single problem radius, None = use max_circuits problems thetas_array=None, # specify a custom thetas_array parameter_mode=1, # 1 - use single theta parameter, 2 - map multiple thetas to pairs parameterized=False, # use Parameter objects in circuit, cache transpiled circuits for performance use_estimator=True, # use the Estimator for execution of objective function max_iter=30, # maximum minimizer iterations to perform minimizer_tolerance=0.001, # tolerance passed to the minimizer comfort=True, # show 'comfort dots' during execution ) # Run the benchmark in method 2 hydrogen_lattice_benchmark.run( min_qubits=min_qubits, max_qubits=max_qubits, max_circuits=max_circuits, num_shots=num_shots, method=2, backend_id=backend_id, provider_backend=provider_backend, hub=hub, group=group, project=project, exec_options=exec_options, **hl_app_args)
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
""" Hydogen Lattice Benchmark Program - Qiskit """ import datetime import json import logging import os import re import sys import time from collections import namedtuple from typing import Optional import numpy as np from scipy.optimize import minimize from qiskit import Aer, QuantumCircuit, execute from qiskit.circuit import ParameterVector from qiskit.exceptions import QiskitError from qiskit.quantum_info import SparsePauliOp from qiskit.result import sampled_expectation_value sys.path[1:1] = ["_common", "_common/qiskit", "hydrogen-lattice/_common"] sys.path[1:1] = ["../../_common", "../../_common/qiskit", "../../hydrogen-lattice/_common/"] # benchmark-specific imports import common import execute as ex import metrics as metrics # import h-lattice_metrics from _common folder import h_lattice_metrics as h_metrics # DEVNOTE: this logging feature should be moved to common level logger = logging.getLogger(__name__) fname, _, ext = os.path.basename(__file__).partition(".") log_to_file = False try: if log_to_file: logging.basicConfig( # filename=f"{fname}_{datetime.datetime.now().strftime('%Y_%m_%d_%S')}.log", filename=f"{fname}.log", filemode="w", encoding="utf-8", level=logging.INFO, format="%(asctime)s %(name)s - %(levelname)s:%(message)s", ) else: logging.basicConfig( level=logging.WARNING, format='%(asctime)s %(name)s - %(levelname)s:%(message)s') except Exception as e: print(f"Exception {e} occured while configuring logger: bypassing logger config to prevent data loss") pass # Benchmark Name benchmark_name = "Hydrogen Lattice" np.random.seed(0) # Hydrogen Lattice inputs ( Here input is Hamiltonian matrix --- Need to change) hl_inputs = dict() # inputs to the run method verbose = False print_sample_circuit = True # Indicates whether to perform the (expensive) pre compute of expectations do_compute_expectation = True # Array of energy values collected during iterations of VQE lowest_energy_values = [] # Key metrics collected on last iteration of VQE key_metrics = {} # saved circuits for display QC_ = None Uf_ = None # #theta parameters vqe_parameter = namedtuple("vqe_parameter", "theta") # DEBUG prints # give argument to the python script as "debug" or "true" or "1" to enable debug prints if len(sys.argv) > 1: DEBUG = sys.argv[1].lower() in ["debug", "true", "1"] else: DEBUG = False # Add custom metric names to metrics module def add_custom_metric_names(): metrics.known_x_labels.update( { "iteration_count": "Iterations" } ) metrics.known_score_labels.update( { "solution_quality": "Solution Quality", "accuracy_volume": "Accuracy Volume", "accuracy_ratio": "Accuracy Ratio", "energy": "Energy (Hartree)", "standard_error": "Std Error", } ) metrics.score_label_save_str.update( { "solution_quality": "solution_quality", "accuracy_volume": "accuracy_volume", "accuracy_ratio": "accuracy_ratio", "energy": "energy", } ) ################################### # HYDROGEN LATTICE CIRCUIT # parameter mode to control length of initial thetas_array (global during dev phase) # 1 - length 1 # 2 - length N, where N is number of excitation pairs saved_parameter_mode = 1 def get_initial_parameters(num_qubits: int, thetas_array): """ Generate an initial set of parameters given the number of qubits and user-provided thetas_array. If thetas_array is None, generate random array of parameters based on the parameter_mode If thetas_array is of length 1, repeat to the required length based on parameter_mode Otherwise, use the provided thetas_array. Parameters ---------- num_qubits : int number of qubits in circuit thetas_array : array of floats user-supplied array of initial values Returns ------- initial_parameters : array array of parameter values required """ # compute required size of array based on number of occupation pairs size = 1 if saved_parameter_mode > 1: num_occ_pairs = (num_qubits // 2) size = num_occ_pairs**2 # if None passed in, create array of random values if thetas_array is None: initial_parameters = np.random.random(size=size) # if single value passed in, extend to required size elif size > 1 and len(thetas_array) == 1: initial_parameters = np.repeat(thetas_array, size) # otherwise, use what user provided else: if len(thetas_array) != size: print(f"WARNING: length of thetas_array {len(thetas_array)} does not equal required length {size}") print(" Generating random values instead.") initial_parameters = get_initial_parameters(num_qubits, None) else: initial_parameters = np.array(thetas_array) if verbose: print(f"... get_initial_parameters(num_qubits={num_qubits}, mode={saved_parameter_mode})") print(f" --> initial_parameter[{size}]={initial_parameters}") return initial_parameters # Create the ansatz quantum circuit for the VQE algorithm. def VQE_ansatz(num_qubits: int, thetas_array, parameterized, num_occ_pairs: Optional[int] = None, *args, **kwargs) -> QuantumCircuit: if verbose: print(f" ... VQE_ansatz(num_qubits={num_qubits}, thetas_array={thetas_array}") # Generate the ansatz circuit for the VQE algorithm. if num_occ_pairs is None: num_occ_pairs = (num_qubits // 2) # e.g., half-filling, which is a reasonable chemical case # do all possible excitations if not passed a list of excitations directly excitation_pairs = [] for i in range(num_occ_pairs): for a in range(num_occ_pairs, num_qubits): excitation_pairs.append([i, a]) # create circuit of num_qubits circuit = QuantumCircuit(num_qubits) # Hartree Fock initial state for occ in range(num_occ_pairs): circuit.x(occ) # if parameterized flag set, create a ParameterVector parameter_vector = None if parameterized: parameter_vector = ParameterVector("t", length=len(excitation_pairs)) # for parameter mode 1, make all thetas the same as the first if saved_parameter_mode == 1: thetas_array = np.repeat(thetas_array, len(excitation_pairs)) # create a Hartree Fock initial state for idx, pair in enumerate(excitation_pairs): # if parameterized, use ParamterVector, otherwise raw theta value theta = parameter_vector[idx] if parameterized else thetas_array[idx] # apply excitation i, a = pair[0], pair[1] # implement the magic gate circuit.s(i) circuit.s(a) circuit.h(a) circuit.cx(a, i) # Ry rotation circuit.ry(theta, i) circuit.ry(theta, a) # implement M^-1 circuit.cx(a, i) circuit.h(a) circuit.sdg(a) circuit.sdg(i) """ TMI ... if verbose: print(f" --> thetas_array={thetas_array}") print(f" --> parameter_vector={str(parameter_vector)}") """ return circuit, parameter_vector, thetas_array # Create the benchmark program circuit array, for the given operator def HydrogenLattice (num_qubits, operator, secret_int = 000000, thetas_array = None, parameterized = None, use_estimator=False): if verbose: print(f"... HydrogenLattice(num_qubits={num_qubits}, thetas_array={thetas_array}") # if no thetas_array passed in, create defaults if thetas_array is None: thetas_array = [1.0] # create parameters in the form expected by the ansatz generator # this is an array of betas followed by array of gammas, each of length = rounds global _qc global theta # create the circuit the first time, add measurements if ex.do_transpile_for_execute: logger.info(f"*** Constructing parameterized circuit for {num_qubits = } {secret_int}") _qc, parameter_vector, thetas_array = VQE_ansatz( num_qubits=num_qubits, thetas_array=thetas_array, parameterized=parameterized, num_occ_pairs=None ) # create a binding of Parameter values params = {parameter_vector: thetas_array} if parameterized else None if verbose: print(f" --> params={params}") logger.info(f"Create binding parameters for {thetas_array} {params}") # for estimator, save the ansatz circuit to be used an example for display purposes if use_estimator: qc = _qc # Prepare an array of circuits from the ansatz, with measurements in different bases # save the first circuit in the array returned from prepare_circuits (with appendage) # to be used an example for display purposes else: _qc_array, _formatted_observables = prepare_circuits(_qc, operator) qc = _qc_array[0] # print(qc) # save small circuit example for display global QC_ if QC_ is None or num_qubits <= 4: if num_qubits <= 7: QC_ = qc # for estimator, return the ansatz circuit, operator, and parameters if use_estimator: return _qc, operator, params # for single circuit execution, return a handle on the circuit array, the observables, and parameters else: return _qc_array, _formatted_observables, params ############### Prepare Circuits from Observables # ---- classical Pauli sum operator from list of Pauli operators and coefficients ---- # Below function is to reduce some dependency on qiskit ( String data type issue) ---- # def pauli_sum_op(ops, coefs): # if len(ops) != len(coefs): # raise ValueError("The number of Pauli operators and coefficients must be equal.") # pauli_sum_op_list = [(op, coef) for op, coef in zip(ops, coefs)] # return pauli_sum_op_list # ---- classical Pauli sum operator from list of Pauli operators and coefficients ---- def prepare_circuits(base_circuit, operator): """ Prepare the qubit-wise commuting circuits for a given operator. Parameters ---------- base_circuit : QuantumCircuit Initial quantum circuit without basis rotations. operator : SparsePauliOp Sparse Pauli operator / Hamiltonian. Returns ------- list Array of QuantumCircuits with applied basis change. list Array of observables formatted as SparsePauliOps. """ # Mapping from Pauli operators to basis change gates basis_change_map = {"X": ["h"], "Y": ["sdg", "h"], "Z": [], "I": []} # Group commuting Pauli operators commuting_ops = operator.group_commuting(qubit_wise=True) # Initialize empty lists for storing output quantum circuits and formatted observables qc_list = [] formatted_obs = [] # Loop over each group of commuting operators for comm_op in commuting_ops: basis = "" pauli_labels = np.array([list(pauli_label) for pauli_label in comm_op.paulis.to_labels()]) for qubit in range(pauli_labels.shape[1]): # return the pauli operations on qubits that aren't identity so we can rotate them qubit_ops = "".join(filter(lambda x: x != "I", pauli_labels[:, qubit])) basis += qubit_ops[0] if qubit_ops else "Z" # Separate terms and coefficients term_coeff_list = comm_op.to_list() terms, coeffs = zip(*term_coeff_list) # Initialize list for storing new terms new_terms = [] # Loop to transform terms from 'X' and 'Y' to 'Z' for term in terms: new_term = "" for c in term: new_term += "Z" if c in "XY" else c new_terms.append(new_term) # Create and store new SparsePauliOp new_op = SparsePauliOp.from_list(list(zip(new_terms, coeffs))) formatted_obs.append(new_op) # Create single quantum circuit for each group of commuting operators basis_circuit = QuantumCircuit(len(basis)) basis_circuit.barrier() for idx, pauli in enumerate(reversed(basis)): for gate in basis_change_map[pauli]: getattr(basis_circuit, gate)(idx) composed_qc = base_circuit.compose(basis_circuit) composed_qc.measure_all() qc_list.append(composed_qc) return qc_list, formatted_obs def compute_energy(result_array, formatted_observables, num_qubits): """ Compute the expectation value of the circuit with respect to the Hamiltonian for optimization """ _probabilities = list() for _res in result_array: _counts = _res.get_counts() _probs = normalize_counts(_counts, num_qubits=num_qubits) _probabilities.append(_probs) _expectation_values = calculate_expectation_values(_probabilities, formatted_observables) energy = sum(_expectation_values) # now get <H^2>, assuming Cov[si,si'] = 0 formatted_observables_sq = [(obs @ obs).simplify(atol=0) for obs in formatted_observables] _expectation_values_sq = calculate_expectation_values(_probabilities, formatted_observables_sq) # now since Cov is assumed to be zero, we compute each term's variance and sum the result. # see Eq 5, e.g. in https://arxiv.org/abs/2004.06252 variance = sum([exp_sq - exp**2 for exp_sq, exp in zip(_expectation_values_sq, _expectation_values)]) return energy, variance def calculate_expectation_values(probabilities, observables): """ Return the expectation values for an operator given the probabilities. """ expectation_values = list() for idx, op in enumerate(observables): expectation_value = sampled_expectation_value(probabilities[idx], op) expectation_values.append(expectation_value) return expectation_values def normalize_counts(counts, num_qubits=None): """ Normalize the counts to get probabilities and convert to bitstrings. """ normalizer = sum(counts.values()) try: dict({str(int(key, 2)): value for key, value in counts.items()}) if num_qubits is None: num_qubits = max(len(key) for key in counts) bitstrings = {key.zfill(num_qubits): value for key, value in counts.items()} except ValueError: bitstrings = counts probabilities = dict({key: value / normalizer for key, value in bitstrings.items()}) assert abs(sum(probabilities.values()) - 1) < 1e-9 return probabilities ############### Prepare Circuits for Execution def get_operator_for_problem(instance_filepath): """ Return an operator object for the problem. Argument: instance_filepath : problem defined by instance_filepath (but should be num_qubits + radius) Returns: operator : an object encapsulating the Hamiltoian for the problem """ # operator is paired hamiltonian for each instance in the loop ops, coefs = common.read_paired_instance(instance_filepath) operator = SparsePauliOp.from_list(list(zip(ops, coefs))) return operator # A dictionary of random energy filename, obtained once random_energies_dict = None def get_random_energy(instance_filepath): """ Get the 'random_energy' associated with the problem """ # read precomputed energies file from the random energies path global random_energies_dict # get the list of random energy filenames once # (DEVNOTE: probably don't want an exception here, should just return 0) if not random_energies_dict: try: random_energies_dict = common.get_random_energies_dict() except ValueError as err: logger.error(err) print("Error reading precomputed random energies json file. Please create the file by running the script 'compute_random_energies.py' in the _common/random_sampler directory") raise # get the filename from the instance_filepath and get the random energy from the dictionary filename = os.path.basename(instance_filepath) filename = filename.split(".")[0] random_energy = random_energies_dict[filename] return random_energy def get_classical_solutions(instance_filepath): """ Get a list of the classical solutions for this problem """ # solution has list of classical solutions for each instance in the loop sol_file_name = instance_filepath[:-5] + ".sol" method_names, values = common.read_puccd_solution(sol_file_name) solution = list(zip(method_names, values)) return solution # Return the file identifier (path) for the problem at this width, radius, and instance def get_problem_identifier(num_qubits, radius, instance_num): # if radius is given we should do same radius for max_circuits times if radius is not None: try: instance_filepath = common.get_instance_filepaths(num_qubits, radius) except ValueError as err: logger.error(err) instance_filepath = None # if radius is not given we should do all the radius for max_circuits times else: instance_filepath_list = common.get_instance_filepaths(num_qubits) try: if len(instance_filepath_list) >= instance_num: instance_filepath = instance_filepath_list[instance_num - 1] else: instance_filepath = None except ValueError as err: logger.error(err) instance_filepath = None return instance_filepath ################################################# # EXPECTED RESULT TABLES (METHOD 1) ############### Expectation Tables Created using State Vector Simulator # DEVNOTE: We are building these tables on-demand for now, but for larger circuits # this will need to be pre-computed ahead of time and stored in a data file to avoid run-time delays. # dictionary used to store pre-computed expectations, keyed by num_qubits and secret_string # these are created at the time the circuit is created, then deleted when results are processed expectations = {} # Compute array of expectation values in range 0.0 to 1.0 # Use statevector_simulator to obtain exact expectation def compute_expectation(qc, num_qubits, secret_int, backend_id="statevector_simulator", params=None): # ts = time.time() # to execute on Aer state vector simulator, need to remove measurements qc = qc.remove_final_measurements(inplace=False) if params is not None: qc = qc.bind_parameters(params) # execute statevector simulation sv_backend = Aer.get_backend(backend_id) sv_result = execute(qc, sv_backend, params=params).result() # get the probability distribution counts = sv_result.get_counts() # print(f"... statevector expectation = {counts}") # store in table until circuit execution is complete id = f"_{num_qubits}_{secret_int}" expectations[id] = counts #print(f" ... time to execute statevector simulator: {time.time() - ts}") # Return expected measurement array scaled to number of shots executed def get_expectation(num_qubits, secret_int, num_shots): # find expectation counts for the given circuit id = f"_{num_qubits}_{secret_int}" if id in expectations: counts = expectations[id] # scale probabilities to number of shots to obtain counts for k, v in counts.items(): counts[k] = round(v * num_shots) # delete from the dictionary del expectations[id] return counts else: return None ################################################# # RESULT DATA ANALYSIS (METHOD 1) expected_dist = {} # Compare the measurement results obtained with the expected measurements to determine fidelity def analyze_and_print_result(qc, result, num_qubits, secret_int, num_shots): global expected_dist # obtain counts from the result object counts = result.get_counts(qc) # retrieve pre-computed expectation values for the circuit that just completed expected_dist = get_expectation(num_qubits, secret_int, num_shots) # if the expectation is not being calculated (only need if we want to compute fidelity) # assume that the expectation is the same as measured counts, yielding fidelity = 1 if expected_dist is None: expected_dist = counts if verbose: print(f"For width {num_qubits} measured: {counts}\n expected: {expected_dist}") # if verbose: print(f"For width {num_qubits} problem {secret_int}\n measured: {counts}\n expected: {expected_dist}") # use our polarization fidelity rescaling fidelity = metrics.polarization_fidelity(counts, expected_dist) # if verbose: print(f"For secret int {secret_int} fidelity: {fidelity}") return counts, fidelity ##### METHOD 2 function to compute application-specific figures of merit def calculate_quality_metric(energy=None, fci_energy=0, random_energy=0, precision = 4, num_electrons = 2): """ Returns the quality metrics, namely solution quality, accuracy volume, and accuracy ratio. Solution quality is a value between zero and one. The other two metrics can take any value. Parameters ---------- energy : list list of energies calculated for each iteration. fci_energy : float FCI energy for the problem. random_energy : float Random energy for the problem, precomputed and stored and read from json file precision : float precision factor used in solution quality calculation changes the behavior of the monotonic arctan function num_electrons : int number of electrons in the problem """ _delta_energy_fci = np.absolute(np.subtract( np.array(energy), fci_energy)) _delta_random_fci = np.absolute(np.subtract( np.array(random_energy), fci_energy)) _relative_energy = np.absolute( np.divide( np.subtract( np.array(energy), fci_energy), fci_energy) ) #scale the solution quality to 0 to 1 using arctan _solution_quality = np.subtract( 1, np.divide( np.arctan( np.multiply(precision,_relative_energy) ), np.pi/2) ) # define accuracy volume as the absolute energy difference between the FCI energy and the energy of the solution normalized per electron _accuracy_volume = np.divide( np.absolute( np.subtract( np.array(energy), fci_energy) ), num_electrons ) # define accuracy ratio as 1.0 minus the error in energy over the error in random energy: # accuracy_ratio = 1.0 - abs(energy - FCI) ) / abs(random - FCI) _accuracy_ratio = np.subtract(1.0, np.divide(_delta_energy_fci,_delta_random_fci)) return _solution_quality, _accuracy_volume, _accuracy_ratio ################################################# # DATA SAVE FUNCTIONS # Create a folder where the results will be saved. # For every circuit width, metrics will be stored the moment the results are obtained # In addition to the metrics, the parameter values obtained by the optimizer, as well as the counts # measured for the final circuit will be stored. def create_data_folder(save_res_to_file, detailed_save_names, backend_id): global parent_folder_save # if detailed filenames requested, use directory name with timestamp if detailed_save_names: start_time_str = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S") parent_folder_save = os.path.join("__data", f"{backend_id}{metrics.data_suffix}", f"run_start_{start_time_str}") # otherwise, just put all json files under __data/backend_id else: parent_folder_save = os.path.join("__data", f"{backend_id}{metrics.data_suffix}") # create the folder if it doesn't exist already if save_res_to_file and not os.path.exists(parent_folder_save): os.makedirs(os.path.join(parent_folder_save)) # Function to save final iteration data to file def store_final_iter_to_metrics_json( backend_id, num_qubits, radius, instance_num, num_shots, converged_thetas_list, energy, detailed_save_names, dict_of_inputs, save_final_counts, save_res_to_file, _instances=None, ): """ For a given problem (specified by num_qubits and instance), 1. For a given restart, store properties of the final minimizer iteration to metrics.circuit_metrics_final_iter, and 2. Store various properties for all minimizer iterations for each restart to a json file. """ # In order to compare with uniform random sampling, get some samples # Store properties of the final iteration, the converged theta values, # as well as the known optimal value for the current problem, # in metrics.circuit_metrics_final_iter. metrics.store_props_final_iter(num_qubits, instance_num, "energy", energy) metrics.store_props_final_iter(num_qubits, instance_num, "converged_thetas_list", converged_thetas_list) # Save final iteration data to metrics.circuit_metrics_final_iter # This data includes final counts, cuts, etc. if save_res_to_file: # Save data to a json file dump_to_json( parent_folder_save, num_qubits, radius, instance_num, dict_of_inputs, converged_thetas_list, energy, save_final_counts=save_final_counts, ) def dump_to_json( parent_folder_save, num_qubits, radius, instance_num, dict_of_inputs, converged_thetas_list, energy, save_final_counts=False, ): """ For a given problem (specified by number of qubits and instance_number), save the evolution of various properties in a json file. Items stored in the json file: Data from all iterations (iterations), inputs to run program ('general properties'), converged theta values ('converged_thetas_list'), computes results. if save_final_counts is True, then also store the distribution counts """ # print(f"... saving data for width={num_qubits} radius={radius} instance={instance_num}") if not os.path.exists(parent_folder_save): os.makedirs(parent_folder_save) store_loc = os.path.join(parent_folder_save, "width_{}_instance_{}.json".format(num_qubits, instance_num)) # Obtain dictionary with iterations data corresponding to given instance_num all_restart_ids = list(metrics.circuit_metrics[str(num_qubits)].keys()) ids_this_restart = [r_id for r_id in all_restart_ids if int(r_id) // 1000 == instance_num] iterations_dict_this_restart = {r_id: metrics.circuit_metrics[str(num_qubits)][r_id] for r_id in ids_this_restart} # Values to be stored in json file dict_to_store = {"iterations": iterations_dict_this_restart} dict_to_store["general_properties"] = dict_of_inputs dict_to_store["converged_thetas_list"] = converged_thetas_list dict_to_store["energy"] = energy # dict_to_store['unif_dict'] = unif_dict # Also store the value of counts obtained for the final counts """ if save_final_counts: dict_to_store['final_counts'] = iter_dist #iter_dist.get_counts() """ # Now write the data fo;e with open(store_loc, "w") as outfile: json.dump(dict_to_store, outfile) ################################################# # DATA LOAD FUNCTIONS # %% Loading saved data (from json files) def load_data_and_plot(folder=None, backend_id=None, **kwargs): """ The highest level function for loading stored data from a previous run and plotting optgaps and area metrics Parameters ---------- folder : string Directory where json files are saved. """ _gen_prop = load_all_metrics(folder, backend_id=backend_id) if _gen_prop is not None: gen_prop = {**_gen_prop, **kwargs} plot_results_from_data(**gen_prop) def load_all_metrics(folder=None, backend_id=None): """ Load all data that was saved in a folder. The saved data will be in json files in this folder Parameters ---------- folder : string Directory where json files are saved. Returns ------- gen_prop : dict of inputs that were used in maxcut_benchmark.run method """ # if folder not passed in, create its name using standard format if folder is None: folder = f"__data/{metrics.get_backend_label(backend_id=backend_id)}" # Note: folder here should be the folder where only the width=... files are stored, and not a folder higher up in the directory assert os.path.isdir(folder), f"Specified folder ({folder}) does not exist." metrics.init_metrics() list_of_files = os.listdir(folder) # print(list_of_files) # list with elements that are tuples->(width,restartInd,filename) width_restart_file_tuples = [ (*get_width_restart_tuple_from_filename(fileName), fileName) for (ind, fileName) in enumerate(list_of_files) if fileName.startswith("width") ] # sort first by width, and then by restartInd width_restart_file_tuples = sorted(width_restart_file_tuples, key=lambda x: (x[0], x[1])) distinct_widths = list(set(it[0] for it in width_restart_file_tuples)) list_of_files = [[tup[2] for tup in width_restart_file_tuples if tup[0] == width] for width in distinct_widths] # connot continue without at least one dataset if len(list_of_files) < 1: print("ERROR: No result files found") return None for width_files in list_of_files: # For each width, first load all the restart files for fileName in width_files: gen_prop = load_from_width_restart_file(folder, fileName) # next, do processing for the width method = gen_prop["method"] if method == 2: num_qubits, _ = get_width_restart_tuple_from_filename(width_files[0]) metrics.process_circuit_metrics_2_level(num_qubits) metrics.finalize_group(num_qubits) # override device name with the backend_id if supplied by caller if backend_id is not None: metrics.set_plot_subtitle(f"Device = {backend_id}") return gen_prop # # load data from a specific file def load_from_width_restart_file(folder, fileName): """ Given a folder name and a file in it, load all the stored data and store the values in metrics.circuit_metrics. Also return the converged values of thetas, the final counts and general properties. Parameters ---------- folder : string folder where the json file is located fileName : string name of the json file Returns ------- gen_prop : dict of inputs that were used in maxcut_benchmark.run method """ # Extract num_qubits and s from file name num_qubits, restart_ind = get_width_restart_tuple_from_filename(fileName) print(f"Loading from {fileName}, corresponding to {num_qubits} qubits and restart index {restart_ind}") with open(os.path.join(folder, fileName), "r") as json_file: data = json.load(json_file) gen_prop = data["general_properties"] converged_thetas_list = data["converged_thetas_list"] energy = data["energy"] if gen_prop["save_final_counts"]: # Distribution of measured cuts final_counts = data["final_counts"] backend_id = gen_prop.get("backend_id") metrics.set_plot_subtitle(f"Device = {backend_id}") # Update circuit metrics for circuit_id in data["iterations"]: # circuit_id = restart_ind * 1000 + minimizer_loop_ind for metric, value in data["iterations"][circuit_id].items(): metrics.store_metric(num_qubits, circuit_id, metric, value) method = gen_prop["method"] if method == 2: metrics.store_props_final_iter(num_qubits, restart_ind, "energy", energy) metrics.store_props_final_iter(num_qubits, restart_ind, "converged_thetas_list", converged_thetas_list) if gen_prop["save_final_counts"]: metrics.store_props_final_iter(num_qubits, restart_ind, None, final_counts) return gen_prop def get_width_restart_tuple_from_filename(fileName): """ Given a filename, extract the corresponding width and degree it corresponds to For example the file "width=4_degree=3.json" corresponds to 4 qubits and degree 3 Parameters ---------- fileName : TYPE DESCRIPTION. Returns ------- num_qubits : int circuit width degree : int graph degree. """ pattern = "width_([0-9]+)_instance_([0-9]+).json" match = re.search(pattern, fileName) # print(match) # assert match is not None, f"File {fileName} found inside folder. All files inside specified folder must be named in the format 'width_int_restartInd_int.json" num_qubits = int(match.groups()[0]) degree = int(match.groups()[1]) return (num_qubits, degree) ################################################ # PLOT METHODS def plot_results_from_data( num_shots=100, radius=0.75, max_iter=30, max_circuits=1, method=2, line_x_metrics=["iteration_count", "cumulative_exec_time"], line_y_metrics=["energy", "accuracy_ratio_error"], plot_layout_style="grid", bar_y_metrics=["average_exec_times", "accuracy_ratio_error"], bar_x_metrics=["num_qubits"], show_elapsed_times=True, use_logscale_for_times=False, score_metric=["accuracy_ratio"], y_metric=["num_qubits"], x_metric=["cumulative_exec_time", "cumulative_elapsed_time"], fixed_metrics={}, num_x_bins=15, y_size=None, x_size=None, x_min=None, x_max=None, detailed_save_names=False, **kwargs, ): """ Plot results from the data contained in metrics tables. """ # Add custom metric names to metrics module (in case this is run outside of run()) add_custom_metric_names() # handle single string form of score metrics if type(score_metric) == str: score_metric = [score_metric] # for hydrogen lattice, objective function is always 'Energy' obj_str = "Energy" suffix = "" # If detailed names are desired for saving plots, put date of creation, etc. if detailed_save_names: cur_time = datetime.datetime.now() dt = cur_time.strftime("%Y-%m-%d_%H-%M-%S") suffix = f"s{num_shots}_r{radius}_mi{max_iter}_{dt}" suptitle = f"Benchmark Results - {benchmark_name} ({method}) - Qiskit" backend_id = metrics.get_backend_id() options = {"shots": num_shots, "radius": radius, "restarts": max_circuits} # plot all line metrics, including solution quality and accuracy ratio # vs iteration count and cumulative execution time h_metrics.plot_all_line_metrics( suptitle, line_x_metrics=line_x_metrics, line_y_metrics=line_y_metrics, plot_layout_style=plot_layout_style, backend_id=backend_id, options=options, ) # plot all cumulative metrics, including average_execution_time and accuracy ratio # over number of qubits h_metrics.plot_all_cumulative_metrics( suptitle, bar_y_metrics=bar_y_metrics, bar_x_metrics=bar_x_metrics, show_elapsed_times=show_elapsed_times, use_logscale_for_times=use_logscale_for_times, plot_layout_style=plot_layout_style, backend_id=backend_id, options=options, ) # plot all area metrics metrics.plot_all_area_metrics( suptitle, score_metric=score_metric, x_metric=x_metric, y_metric=y_metric, fixed_metrics=fixed_metrics, num_x_bins=num_x_bins, x_size=x_size, y_size=y_size, x_min=x_min, x_max=x_max, options=options, suffix=suffix, which_metric="solution_quality", ) ################################################ ################################################ # RUN METHOD MAX_QUBITS = 16 def run( min_qubits=2, max_qubits=4, skip_qubits=2, max_circuits=3, num_shots=100, method=2, radius=None, thetas_array=None, parameterized=False, parameter_mode=1, use_estimator=False, do_fidelities=True, minimizer_function=None, minimizer_tolerance=1e-3, max_iter=30, comfort=False, line_x_metrics=["iteration_count", "cumulative_exec_time"], line_y_metrics=["energy", "accuracy_ratio_error"], bar_y_metrics=["average_exec_times", "accuracy_ratio_error"], bar_x_metrics=["num_qubits"], score_metric=["accuracy_ratio"], x_metric=["cumulative_exec_time", "cumulative_elapsed_time"], y_metric="num_qubits", fixed_metrics={}, num_x_bins=15, y_size=None, x_size=None, show_results_summary=True, plot_results=True, plot_layout_style="grid", show_elapsed_times=True, use_logscale_for_times=False, save_res_to_file=True, save_final_counts=False, detailed_save_names=False, backend_id="qasm_simulator", provider_backend=None, hub="ibm-q", group="open", project="main", exec_options=None, context=None, _instances=None, ): """ Parameters ---------- min_qubits : int, optional The smallest circuit width for which benchmarking will be done The default is 3. max_qubits : int, optional The largest circuit width for which benchmarking will be done. The default is 6. max_circuits : int, optional Number of restarts. The default is None. num_shots : int, optional Number of times the circut will be measured, for each iteration. The default is 100. method : int, optional If 1, then do standard metrics, if 2, implement iterative algo metrics. The default is 1. thetas_array : list, optional list or ndarray of theta values. The default is None. N : int, optional For the max % counts metric, choose the highest N% counts. The default is 10. alpha : float, optional Value between 0 and 1. The default is 0.1. parameterized : bool, optional Whether to use parameter objects in circuits or not. The default is False. parameter_mode : bool, optional If True, use thetas_array of length 1, otherwise (num_qubits//2)**2, to match excitation pairs use_estimator : bool, optional If True, use the estimator within the objective function, instead of multiple circuits do_fidelities : bool, optional Compute circuit fidelity. The default is True. minimizer_function : function custom function used for minimizer minimizer_tolerance : float tolerance for minimizer, default is 1e-3, max_iter : int, optional Number of iterations for the minimizer routine. The default is 30. plot_layout_style : str, optional Style of plot layout, 'grid', 'stacked', or 'individual', default = 'grid' line_x_metrics : list or string, optional Which metrics are to be plotted on x-axis in line metrics plots. line_y_metrics : list or string, optional Which metrics are to be plotted on y-axis in line metrics plots. show_elapsed_times : bool, optional In execution times bar chart, include elapsed times if True use_logscale_for_times : bool, optional In execution times bar plot, use a log scale to show data score_metric : list or string, optional Which metrics are to be plotted in area metrics plots. The default is 'fidelity'. x_metric : list or string, optional Horizontal axis for area plots. The default is 'cumulative_exec_time'. y_metric : list or string, optional Vertical axis for area plots. The default is 'num_qubits'. fixed_metrics : TYPE, optional DESCRIPTION. The default is {}. num_x_bins : int, optional DESCRIPTION. The default is 15. y_size : TYPint, optional DESCRIPTION. The default is None. x_size : string, optional DESCRIPTION. The default is None. backend_id : string, optional DESCRIPTION. The default is 'qasm_simulator'. provider_backend : string, optional DESCRIPTION. The default is None. hub : string, optional DESCRIPTION. The default is "ibm-q". group : string, optional DESCRIPTION. The default is "open". project : string, optional DESCRIPTION. The default is "main". exec_options : string, optional DESCRIPTION. The default is None. plot_results : bool, optional Plot results only if True. The default is True. save_res_to_file : bool, optional Save results to json files. The default is True. save_final_counts : bool, optional If True, also save the counts from the final iteration for each problem in the json files. The default is True. detailed_save_names : bool, optional If true, the data and plots will be saved with more detailed names. Default is False confort : bool, optional If true, print comfort dots during execution """ # Store all the input parameters into a dictionary. # This dictionary will later be stored in a json file # It will also be used for sending parameters to the plotting function dict_of_inputs = locals() thetas = [] # a default empty list of thetas # Update the dictionary of inputs dict_of_inputs = {**dict_of_inputs, **{"thetas_array": thetas, "max_circuits": max_circuits}} # Delete some entries from the dictionary; they may contain secrets or function pointers for key in ["hub", "group", "project", "provider_backend", "exec_options", "minimizer_function"]: dict_of_inputs.pop(key) global hydrogen_lattice_inputs hydrogen_lattice_inputs = dict_of_inputs ########################### # Benchmark Initializeation global QC_ global circuits_done global minimizer_loop_index global opt_ts print(f"{benchmark_name} ({method}) Benchmark Program - Qiskit") QC_ = None # validate parameters max_qubits = max(2, max_qubits) max_qubits = min(MAX_QUBITS, max_qubits) min_qubits = min(max(2, min_qubits), max_qubits) skip_qubits = max(2, skip_qubits) # create context identifier if context is None: context = f"{benchmark_name} ({method}) Benchmark" try: print("Validating user inputs...") # raise an exception if either min_qubits or max_qubits is not even if min_qubits % 2 != 0 or max_qubits % 2 != 0: raise ValueError( "min_qubits and max_qubits must be even. min_qubits = {}, max_qubits = {}".format( min_qubits, max_qubits ) ) except ValueError as err: # display error message and stop execution if min_qubits or max_qubits is not even logger.error(err) if min_qubits % 2 != 0: min_qubits += 1 if max_qubits % 2 != 0: max_qubits -= 1 max_qubits = min(max_qubits, MAX_QUBITS) print(err.args[0] + "\n Running for for values min_qubits = {}, max_qubits = {}".format(min_qubits, max_qubits)) # don't compute exectation unless fidelity is is needed global do_compute_expectation do_compute_expectation = do_fidelities # save the desired parameter mode globally (for now, during dev) global saved_parameter_mode saved_parameter_mode = parameter_mode # given that this benchmark does every other width, set y_size default to 1.5 if y_size is None: y_size = 1.5 ########## # Initialize metrics module with empty metrics arrays metrics.init_metrics() # Add custom metric names to metrics module add_custom_metric_names() # Define custom result handler def execution_handler(qc, result, num_qubits, s_int, num_shots): # determine fidelity of result set num_qubits = int(num_qubits) counts, fidelity = analyze_and_print_result(qc, result, num_qubits, int(s_int), num_shots) metrics.store_metric(num_qubits, s_int, "solution_quality", fidelity) def execution_handler2(qc, result, num_qubits, s_int, num_shots): # Stores the results to the global saved_result variable global saved_result saved_result = result # Initialize execution module using the execution result handler above and specified backend_id # for method=2 we need to set max_jobs_active to 1, so each circuit completes before continuing if method == 2: ex.max_jobs_active = 1 ex.init_execution(execution_handler2) else: ex.init_execution(execution_handler) # initialize the execution module with target information ex.set_execution_target(backend_id, provider_backend=provider_backend, hub=hub, group=group, project=project, exec_options=exec_options, context=context ) # create a data folder for the results create_data_folder(save_res_to_file, detailed_save_names, backend_id) ########################### # Benchmark Execution Loop # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete # DEVNOTE: increment by 2 for paired electron circuits for num_qubits in range(min_qubits, max_qubits + 1, 2): if method == 1: print(f"************\nExecuting [{max_circuits}] circuits for num_qubits = {num_qubits}") else: print(f"************\nExecuting [{max_circuits}] restarts for num_qubits = {num_qubits}") # # If radius is negative, # if radius < 0 : # radius = max(3, (num_qubits + radius)) # loop over all instance files according to max_circuits given # instance_num index starts from 1 for instance_num in range(1, max_circuits + 1): # get the file identifier (path) for the problem at this width, radius, and instance # DEVNOTE: this identifier should NOT be the filepath, use another method instance_filepath = get_problem_identifier(num_qubits, radius, instance_num) if instance_filepath is None: print( f"WARNING: cannot find problem file for num_qubits={num_qubits}, radius={radius}, instance={instance_num}\n" ) break # if radius given, each instance will use this same radius if radius is not None: current_radius = radius # else find current radius from the filename found for this num_qubits and instance_num # DEVNOTE: klunky, improve later else: current_radius = float(os.path.basename(instance_filepath).split("_")[2]) current_radius += float(os.path.basename(instance_filepath).split("_")[3][:2]) * 0.01 if verbose: print(f"... executing problem num_qubits={num_qubits}, radius={radius}, instance={instance_num}") # obtain the Hamiltonian operator object for the current problem # if the problem is not pre-defined, we are done with this number of qubits operator = get_operator_for_problem(instance_filepath) if operator is None: print(f" ... problem not found.") break # get a list of the classical solutions for this problem solution = get_classical_solutions(instance_filepath) # get the 'random_energy' associated with the problem random_energy = get_random_energy(instance_filepath) # create an intial thetas_array, given the circuit width and user input thetas_array_0 = get_initial_parameters(num_qubits, thetas_array) ############### if method == 1: # create the circuit(s) for given qubit size and secret string, store time metric ts = time.time() # create the circuits to be tested # for Estimator, we only need circuit and params, we have operator if use_estimator: qc, _, params = HydrogenLattice( num_qubits=num_qubits, secret_int=instance_num, thetas_array=thetas_array, parameterized=parameterized, operator=operator, use_estimator=use_estimator ) # for single circuit execution, we need an array of ciruiits and observables else: qc_array, frmt_obs, params = HydrogenLattice( num_qubits=num_qubits, secret_int=instance_num, thetas_array=thetas_array, parameterized=parameterized, operator=operator, use_estimator=use_estimator ) # We only execute one of the circuits created, the last one. which is in the # z-basis. This is the one that is most illustrative of a device's fidelity. # DEVNOTE: maybe we should do all three, and aggregate, just as in method 2? qc = qc_array[-1] """ TMI ... # for testing and debugging ... #if using parameter objects, bind before printing if verbose: print(qc.bind_parameters(params) if parameterized else qc) """ # store the creation time for these circuits metrics.store_metric(num_qubits, instance_num, "create_time", time.time() - ts) # classically pre-compute and cache an array of expected measurement counts # for comparison against actual measured counts for fidelity calc (in analysis) if do_compute_expectation: logger.info("Computing expectation") # pass parameters as they are used during execution compute_expectation(qc, num_qubits, instance_num, params=params) # submit circuit for execution on target, with parameters ex.submit_circuit(qc, num_qubits, instance_num, shots=num_shots, params=params) ############### if method == 2: logger.info(f"=============== Begin method 2 loop, enabling transpile") # a unique circuit index used inside the inner minimizer loop as identifier # Value of 0 corresponds to the 0th iteration of the minimizer minimizer_loop_index = 0 # Always start by enabling transpile ... ex.set_tranpilation_flags(do_transpile_metrics=True, do_transpile_for_execute=True) # get the classically computed expected energy variables from solution object doci_energy = float(next(value for key, value in solution if key == "doci_energy")) fci_energy = float(next(value for key, value in solution if key == "fci_energy")) hf_energy = float(next(value for key, value in solution if key == "hf_energy")) # begin timer accumulation cumlative_iter_time = [0] start_iters_t = time.time() ######################################### #### Objective function to compute energy def objective_function(thetas_array): """ Objective function that calculates the expected energy for the given parameterized circuit Parameters ---------- thetas_array : list list of theta values. """ # Every circuit needs a unique id; add unique_circuit_index instead of s_int global minimizer_loop_index unique_id = instance_num * 1000 + minimizer_loop_index # variables used to aggregate metrics for all terms result_array = [] quantum_execution_time = 0.0 quantum_elapsed_time = 0.0 # create ansatz from the operator, in multiple circuits, one for each measured basis # call the HydrogenLattice ansatz to generate a parameterized hamiltonian ts = time.time() # for Estimator, we only need circuit and params, we have operator if use_estimator: qc, _, params = HydrogenLattice( num_qubits=num_qubits, secret_int=unique_id, thetas_array=thetas_array, parameterized=parameterized, operator=operator, use_estimator=use_estimator ) # for single circuit execution, we need an array of ciruiits and observables else: qc_array, frmt_obs, params = HydrogenLattice( num_qubits=num_qubits, secret_int=unique_id, thetas_array=thetas_array, parameterized=parameterized, operator=operator, use_estimator=use_estimator ) # store the time it took to create the circuit metrics.store_metric(num_qubits, unique_id, "create_time", time.time() - ts) ##################### # loop over each of the circuits that are generated with basis measurements and execute if verbose: print(f"... ** compute energy for num_qubits={num_qubits}, circuit={unique_id}, parameters={params}, thetas_array={thetas_array}") # If using Estimator, pass the ansatz to Estimator with operator and get result energy if use_estimator: # submit the ansatz circuit to the Estimator for execution result = submit_to_estimator(qc, num_qubits, unique_id, parameterized, params, operator, num_shots, backend_id, provider_backend) # after first execution and thereafter, no need for transpilation if parameterized if parameterized: # DEVNOTE: since Hydro uses 3 circuits inside this loop, and execute.py can only # cache 1 at a time, we cannot yet implement caching. Transpile every time for now. cached_circuits = False if cached_circuits: ex.set_tranpilation_flags(do_transpile_metrics=False, do_transpile_for_execute=False) logger.info(f"**** First execution complete, disabling transpile") # result array stores the multiple results we measure along different Pauli basis. #global saved_result # Aggregate execution and elapsed time for running all three circuits # corresponding to different measurements along the different Pauli bases quantum_execution_time = ( quantum_execution_time + metrics.get_metric(num_qubits, unique_id, "exec_time") ) quantum_elapsed_time = ( quantum_elapsed_time + metrics.get_metric(num_qubits, unique_id, "elapsed_time") ) # with single circuit mode, execute array of circuits and computer energy from observables else: # loop over each circuit and execute for qc in qc_array: # bind parameters to circuit before execution if parameterized: qc.bind_parameters(params) # submit circuit for execution on target with the current parameters ex.submit_circuit(qc, num_qubits, unique_id, shots=num_shots, params=params) # wait for circuit to complete by calling finalize ... # finalize execution of group (each circuit in loop accumulates metrics) ex.finalize_execution(None, report_end=False) # after first execution and thereafter, no need for transpilation if parameterized if parameterized: # DEVNOTE: since Hydro uses 3 circuits inside this loop, and execute.py can only # cache 1 at a time, we cannot yet implement caching. Transpile every time for now. cached_circuits = False if cached_circuits: ex.set_tranpilation_flags(do_transpile_metrics=False, do_transpile_for_execute=False) logger.info(f"**** First execution complete, disabling transpile") # result array stores the multiple results we measure along different Pauli basis. global saved_result result_array.append(saved_result) # Aggregate execution and elapsed time for running all three circuits # corresponding to different measurements along the different Pauli bases quantum_execution_time = ( quantum_execution_time + metrics.get_metric(num_qubits, unique_id, "exec_time") ) quantum_elapsed_time = ( quantum_elapsed_time + metrics.get_metric(num_qubits, unique_id, "elapsed_time") ) ##################### # classical processing of results global opt_ts global cumulative_iter_time cumlative_iter_time.append(cumlative_iter_time[-1] + quantum_execution_time) # store the new exec time and elapsed time back to metrics metrics.store_metric(num_qubits, unique_id, "exec_time", quantum_execution_time) metrics.store_metric(num_qubits, unique_id, "elapsed_time", quantum_elapsed_time) # increment the minimizer loop index, the index is increased by one # for the group of three circuits created ( three measurement basis circuits) minimizer_loop_index += 1 # print "comfort dots" (newline before the first iteration) if comfort: if minimizer_loop_index == 1: print("") print(".", end="") if verbose: print("") # Start counting classical optimizer time here again tc1 = time.time() # compute energy for this combination of observables and measurements global energy global variance global standard_error # for Estimator, energy and variance are returned directly if use_estimator: energy = result.values[0] variance = result.metadata[0]['variance'] # for single circuit execution, need to compute energy from results and observables else: energy, variance = compute_energy( result_array=result_array, formatted_observables=frmt_obs, num_qubits=num_qubits ) # calculate std error from the variance -- identically zero if using statevector simulator if backend_id.lower() != "statevector_simulator": standard_error = np.sqrt(variance/num_shots) else: standard_error = 0.0 if verbose: print(f" ... energy={energy:.5f} +/- stderr={standard_error:.5f}") # append the most recent energy value to the list lowest_energy_values.append(energy) # calculate the solution quality, accuracy volume and accuracy ratio global solution_quality, accuracy_volume, accuracy_ratio solution_quality, accuracy_volume, accuracy_ratio = calculate_quality_metric( energy=energy, fci_energy=fci_energy, random_energy=random_energy, precision=0.5, num_electrons=num_qubits, ) # store the metrics for the current iteration metrics.store_metric(num_qubits, unique_id, "energy", energy) metrics.store_metric(num_qubits, unique_id, "variance", variance) metrics.store_metric(num_qubits, unique_id, "standard_error", standard_error) metrics.store_metric(num_qubits, unique_id, "random_energy", random_energy) metrics.store_metric(num_qubits, unique_id, "solution_quality", solution_quality) metrics.store_metric(num_qubits, unique_id, "accuracy_volume", accuracy_volume) metrics.store_metric(num_qubits, unique_id, "accuracy_ratio", accuracy_ratio) metrics.store_metric(num_qubits, unique_id, "fci_energy", fci_energy) metrics.store_metric(num_qubits, unique_id, "doci_energy", doci_energy) metrics.store_metric(num_qubits, unique_id, "hf_energy", hf_energy) metrics.store_metric(num_qubits, unique_id, "radius", current_radius) metrics.store_metric(num_qubits, unique_id, "iteration_count", minimizer_loop_index) # store most recent metrics for export key_metrics["radius"] = current_radius key_metrics["fci_energy"] = fci_energy key_metrics["doci_energy"] = doci_energy key_metrics["hf_energy"] = hf_energy key_metrics["random_energy"] = random_energy key_metrics["iteration_count"] = minimizer_loop_index key_metrics["energy"] = energy key_metrics["variance"] = variance key_metrics["standard_error"] = standard_error key_metrics["accuracy_ratio"] = accuracy_ratio key_metrics["solution_quality"] = solution_quality key_metrics["accuracy_volume"] = accuracy_volume return energy # callback for each iteration (currently unused) def callback_thetas_array(thetas_array): pass ########################### # End of Objective Function # if in verbose mode, comfort dots need a newline before optimizer gets going # if comfort and verbose: # print("") # Initialize an empty list to store the energy values from each iteration lowest_energy_values.clear() # execute COPYLA classical optimizer to minimize the objective function # objective function is called repeatedly with varying parameters # until the lowest energy found if minimizer_function is None: ret = minimize( objective_function, x0=thetas_array_0.ravel(), # note: revel not really needed for this ansatz method="COBYLA", tol=minimizer_tolerance, options={"maxiter": max_iter, "disp": False}, callback=callback_thetas_array, ) # or, execute a custom minimizer else: ret = minimizer_function( objective_function=objective_function, initial_parameters=thetas_array_0.ravel(), # note: revel not really needed for this ansatz callback=callback_thetas_array, ) # if verbose: # print(f"\nEnergies for problem of {num_qubits} qubits and radius {current_radius} of paired hamiltionians") # print(f" PUCCD calculated energy : {ideal_energy}") if comfort: print("") # show results to console if show_results_summary: print( f"Classically Computed Energies from solution file for {num_qubits} qubits and radius {current_radius}" ) print(f" DOCI calculated energy : {doci_energy}") print(f" FCI calculated energy : {fci_energy}") print(f" Hartree-Fock calculated energy : {hf_energy}") print(f" Random Solution calculated energy : {random_energy}") print(f"Computed Energies for {num_qubits} qubits and radius {current_radius}") print(f" Solution Energy : {lowest_energy_values[-1]}") print(f" Accuracy Ratio : {accuracy_ratio}, Solution Quality : {solution_quality}") # pLotting each instance of qubit count given cumlative_iter_time = cumlative_iter_time[1:] # save the data for this qubit width, and instance number store_final_iter_to_metrics_json( backend_id=backend_id, num_qubits=num_qubits, radius=radius, instance_num=instance_num, num_shots=num_shots, converged_thetas_list=ret.x.tolist(), energy=lowest_energy_values[-1], # iter_size_dist=iter_size_dist, iter_dist=iter_dist, detailed_save_names=detailed_save_names, dict_of_inputs=dict_of_inputs, save_final_counts=save_final_counts, save_res_to_file=save_res_to_file, _instances=_instances, ) ###### End of instance processing # for method 2, need to aggregate the detail metrics appropriately for each group # Note that this assumes that all iterations of the circuit have completed by this point if method == 2: metrics.process_circuit_metrics_2_level(num_qubits) metrics.finalize_group(num_qubits) # Wait for some active circuits to complete; report metrics when groups 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 if print_sample_circuit: if method == 1: print("Sample Circuit:") print(QC_ if QC_ is not None else " ... too large!") # Plot metrics for all circuit sizes if method == 1: metrics.plot_metrics(f"Benchmark Results - {benchmark_name} ({method}) - Qiskit", options=dict(shots=num_shots)) elif method == 2: if plot_results: plot_results_from_data(**dict_of_inputs) def get_final_results(): """ Return the energy and dict of key metrics of the last run(). """ # find the final energy value and return it energy=lowest_energy_values[-1] if len(lowest_energy_values) > 0 else None return energy, key_metrics ################################### # DEVNOTE: This function should be re-implemented as just the objective function # as it is defined in the run loop above with the necessary parameters def run_objective_function(**kwargs): """ Define a function to perform one iteration of the objective function. These argruments are preset to single execution: method=2, max_circuits=1, max+iter=1 """ # Fix arguments required to execute of single instance hl_single_args = dict( method=2, # method 2 defines the objective function max_circuits=1, # only one repetition max_iter=1, # maximum minimizer iterations to perform, set to 1 # disable display options for line plots line_y_metrics=None, line_x_metrics=None, # disable display options for bar plots bar_y_metrics=None, bar_x_metrics=None, # disable display options for area plots score_metric=None, x_metric=None, ) # get the num_qubits are so we can force min and max to it. num_qubits = kwargs.pop("num_qubits") # Run the benchmark in method 2 at just one qubit size run(min_qubits=num_qubits, max_qubits=num_qubits, **kwargs, **hl_single_args) # find the final energy value and return it energy=lowest_energy_values[-1] if len(lowest_energy_values) > 0 else None return energy, key_metrics ################################# # QISKit ESTIMATOR EXECUTION # DEVNOTE: This code will be moved to common/qiskit/execute.py so it can be used elsewhere def submit_to_estimator(qc=None, num_qubits=1, unique_id=-1, parameterized=False, params=None, operator=None, num_shots=100, backend_id=None, provider_backend=None): #print(f"... *** using Estimator") from qiskit.primitives import BackendEstimator, Estimator # start timing of estimator here ts_launch = time.time() # bind parameters to circuit before execution if parameterized: qc_bound = qc.assign_parameters(params, inplace=False) else: qc_bound = qc if backend_id.lower() == "statevector_simulator": estimator = Estimator() # statevector doesn't work w/ vanilla BackendEstimator else: estimator = BackendEstimator(backend=Aer.get_backend(backend_id)) # FIXME: won't work for vendor QPUs #estimator = BackendEstimator(backend=provider_backend) ts_start = time.time() #print(operator) job = estimator.run(qc_bound, operator, shots=num_shots) #print(job) #print(job.metrics()) result = job.result() ts_done = time.time() exec_time = ts_done - ts_start elapsed_time = ts_done - ts_launch #print(f"... elapsed, exec = {elapsed_time}, {exec_time}") metrics.store_metric(num_qubits, unique_id, "exec_time", exec_time) metrics.store_metric(num_qubits, unique_id, "elapsed_time", elapsed_time) return result ################################# # MAIN # # if main, execute method if __name__ == "__main__": run() # # %% # run()
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
from __future__ import annotations import json import numpy as np from qiskit.opflow.primitive_ops import PauliSumOp from qiskit.quantum_info import SparsePauliOp from qiskit_nature.second_q.drivers import PySCFDriver from qiskit_nature.second_q.formats.molecule_info import MoleculeInfo from qiskit_nature.second_q.problems import ElectronicStructureProblem from qiskit_nature.second_q.mappers import JordanWignerMapper from qiskit_nature.second_q.hamiltonians import ElectronicEnergy from qiskit_nature_pyscf import PySCFGroundStateSolver import time import qiskit_nature import pyscf from pyscf.doci import doci_slow def chain( n: int = 4, r: float = 1.0, ) -> tuple[list[str], np.ndarray, str]: """ Generate the xyz coordinates of a chain of hydrogen atoms. """ xyz = np.zeros((n, 3)) atoms = ["H"] * n z = np.arange(-(n - 1) / 2, (n) / 2) * r assert len(z) == n assert sum(z) == 0.0 xyz[:, 2] = z description = "H" + str(n) + " 1D chain, " + str(r) + " Angstroms\n" return atoms, xyz, description def as_xyz(atoms, xyz, description="\n"): # format as .XYZ n = len(atoms) pretty_xyz = str(n) + "\n" pretty_xyz += description for i in range(n): pretty_xyz += "{0:s} {1:10.4f} {2:10.4f} {3:10.4f}\n".format( atoms[i], xyz[i, 0], xyz[i, 1], xyz[i, 2] ) return pretty_xyz def molecule_to_problem( atoms: list[str], xyz: np.ndarray, ) -> ElectronicStructureProblem: """ Creates an ElectronicEnergy object corresponding to a list of atoms and xyz positions. This object can be used to access hamiltonian information. """ # define the molecular structure hydrogen_molecule = MoleculeInfo(atoms, xyz, charge=0, multiplicity=1) # Prepare and run the initial Hartree-Fock calculation on molecule molecule_driver = PySCFDriver.from_molecule(hydrogen_molecule, basis="sto3g") quantum_molecule = molecule_driver.run() # acquire fermionic hamiltonian return quantum_molecule def generate_jordan_wigner_hamiltonian(hamiltonian: ElectronicEnergy) -> PauliSumOp: """ Returns an ElectronicEnergy hamiltonian in the Jordan Wigner encoding basis. """ fermionic_hamiltonian = hamiltonian.second_q_op() # create mapper from fermionic to spin basis mapper = JordanWignerMapper() # create qubit hamiltonian from fermionic one qubit_hamiltonian = mapper.map(fermionic_hamiltonian) # hamiltonian does not include scalar nuclear energy constant, so we add it back here for consistency in benchmarks qubit_hamiltonian += PauliSumOp( SparsePauliOp( "I" * qubit_hamiltonian.num_qubits, coeffs=hamiltonian.nuclear_repulsion_energy, ) ) return qubit_hamiltonian.reduce() def generate_paired_qubit_hamiltonian(hamiltonian: ElectronicEnergy) -> PauliSumOp: """ Returns an ElectronicEnergy hamiltonian in the efficient paired electronic basis. """ one_body_integrals = hamiltonian.electronic_integrals.alpha["+-"] two_body_integrals = hamiltonian.electronic_integrals.alpha["++--"].transpose( (0, 3, 2, 1) ) core_energy = hamiltonian.nuclear_repulsion_energy num_orbitals = len(one_body_integrals) def I(): return "I" * num_orbitals def Z(p): Zp = ["I"] * num_orbitals Zp[p] = "Z" return "".join(Zp)[::-1] def ZZ(p, q): ZpZq = ["I"] * num_orbitals ZpZq[p] = "Z" ZpZq[q] = "Z" return "".join(ZpZq)[::-1] def XX(p, q): XpXq = ["I"] * num_orbitals XpXq[p] = "X" XpXq[q] = "X" return "".join(XpXq)[::-1] def YY(p, q): YpYq = ["I"] * num_orbitals YpYq[p] = "Y" YpYq[q] = "Y" return "".join(YpYq)[::-1] terms = [((I(), core_energy))] # nuclear repulsion is a constant # loop to create paired electron Hamiltonian # last term is from p = p case in (I - Zp) * (I - Zp)* (pp|qq) gpq = ( one_body_integrals - 0.5 * np.einsum("prrq->pq", two_body_integrals) + np.einsum("ppqq->pq", two_body_integrals) ) for p in range(num_orbitals): terms.append((I(), gpq[p, p])) terms.append((Z(p), -gpq[p, p])) for q in range(num_orbitals): if p != q: terms.append( ( I(), 0.5 * two_body_integrals[p, p, q, q] + 0.25 * two_body_integrals[p, q, q, p], ) ) terms.append( ( Z(p), -0.5 * two_body_integrals[p, p, q, q] - 0.25 * two_body_integrals[p, q, q, p], ) ) terms.append( ( Z(q), -0.5 * two_body_integrals[p, p, q, q] + 0.25 * two_body_integrals[p, q, q, p], ) ) terms.append( ( ZZ(p, q), 0.5 * two_body_integrals[p, p, q, q] - 0.25 * two_body_integrals[p, q, q, p], ) ) terms.append((XX(p, q), 0.25 * two_body_integrals[p, q, p, q])) terms.append((YY(p, q), 0.25 * two_body_integrals[p, q, p, q])) qubit_hamiltonian = PauliSumOp.from_list(terms) # pass in list of terms return qubit_hamiltonian.reduce() # Qiskit can collect and simplify terms def make_pauli_dict(hamiltonian): op = hamiltonian.primitive.to_list() n_terms = len(op) coeffs = [] paulis = [] for i in range(n_terms): coeffs.append(complex(op[i][1]).real) paulis.append(op[i][0]) pauli_dict = dict(zip(paulis, coeffs)) return pauli_dict def make_energy_orbital_dict(hamiltonian): d = { "hf_energy": float(hamiltonian.reference_energy), "nuclear_repulsion_energy": float(hamiltonian.nuclear_repulsion_energy), "spatial_orbitals": int(hamiltonian.num_spatial_orbitals), "alpha_electrons": int(hamiltonian.num_alpha), "beta_electrons": int(hamiltonian.num_beta), } return d def fci(problem: ElectronicStructureProblem): solver = PySCFGroundStateSolver(pyscf.fci.direct_spin0.FCI()) result = solver.solve(problem).total_energies[0] return result def doci(problem: ElectronicStructureProblem): solver = PySCFGroundStateSolver(doci_slow.DOCI()) result = solver.solve(problem).total_energies[0] return result if __name__ == "__main__": """ generate various hydrogen lattice pUCCD hamiltonians """ for shape in [chain]: for n in [2,4,6,8,10,12,14,16]: for r in [0.75, 1.00, 1.25]: file_name = f"h{n:03}_{shape.__name__}_{r:06.2f}" file_name = file_name.replace(".", "_") file_name = file_name + ".json" #start timing to check scaling of problem + solution generation start_time = time.time() print(f"Working on {shape.__name__} for n={n} and r={r}") print("First working on Json file creation.") # get lattice info from a particular shape atoms, xyz, description = shape(n, r) # print to console the lattice info print(as_xyz(atoms, xyz, description)) # create hamiltonian from lattice info electronic_problem = molecule_to_problem(atoms, xyz) fermionic_hamiltonian = electronic_problem.hamiltonian # generate information on number of orbitals and nuclear + HF energies orbital_energy_info = make_energy_orbital_dict(electronic_problem) paired_qubit_hamiltonian = generate_paired_qubit_hamiltonian( fermionic_hamiltonian ) jordan_wigner_hamiltonian = generate_jordan_wigner_hamiltonian( fermionic_hamiltonian ) # generate hamiltonian in paired basis (i.e., hard-core boson) paired_hamiltonian_dict = make_pauli_dict(paired_qubit_hamiltonian) # generate hamiltonian in spin-orbital (Jordan-Wigner) basis jordan_wigner_hamiltonian_dict = make_pauli_dict( jordan_wigner_hamiltonian ) # begin JSON file creation # this JSON file format can be changed to add/remove categories in the future # create a dict and merge it with the orbital energy dict d = { "atoms": atoms, "x": xyz[:, 0].tolist(), "y": xyz[:, 1].tolist(), "z": xyz[:, 2].tolist(), "paired_hamiltonian": paired_hamiltonian_dict, "jordan_wigner_hamiltonian": jordan_wigner_hamiltonian_dict, } d = {**d, **orbital_energy_info} # save file in the working directory with open(file_name, "w") as f: json.dump(d, f, indent=4) # end JSON file creation print("Json file generated! Moving onto generating solution.") solution_path = file_name.replace(".json", ".sol") print("Solutions will be stored at ", solution_path) print("Starting work on solution generation.") fci_time_start = time.time() fci_energy = fci(electronic_problem) fci_time_end = time.time() print(f"FCI solution generation took {fci_time_end-fci_time_start}") doci_time_start = time.time() doci_energy = doci(electronic_problem) doci_time_end = time.time() print(f"DOCI solution generation took {doci_time_end-doci_time_end}") print(f"Generation done. Acquired FCI energy of {fci_energy} and DOCI energy of {doci_energy}.") with open(solution_path, "w") as file: file.write(f"doci_energy: {doci_energy}\n") file.write(f"fci_energy: {fci_energy}\n") file.write(f"hf_energy: {d['hf_energy']}\n") print("All done writing .sol file- now looking for next file or done. \n \n \n")
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
min_qubits=4 max_qubits=8 max_circuits=1 num_shots=1 backend_id="dm_simulator" #hub="ibm-q"; group="open"; project="main" provider_backend = None exec_options = {} # # ========================== # # *** If using IBMQ hardware, run this once to authenticate # from qiskit import IBMQ # IBMQ.save_account('YOUR_API_TOKEN_HERE') # # *** If you are part of an IBMQ group, set hub, group, and project name here # hub="YOUR_HUB_NAME"; group="YOUR_GROUP_NAME"; project="YOUR_PROJECT_NAME" # # *** This example shows how to specify an IBMQ backend using a known "backend_id" # exec_options = { "optimization_level":3, "use_sessions":True, "resilience_level":1} # backend_id="ibmq_belem" # # ========================== # # *** If using Azure Quantum, use this hub identifier and specify the desired backend_id # # Identify your resources with env variables AZURE_QUANTUM_RESOURCE_ID and AZURE_QUANTUM_LOCATION # hub="azure-quantum"; group="open"; project="QED-C App-Oriented Benchmarks - Qiskit Version" # backend_id="<YOUR_BACKEND_NAME_HERE>" # # ========================== # The remaining examples create a provider instance and get a backend from it # # An example using IonQ provider # from qiskit_ionq import IonQProvider # provider = IonQProvider() # Be sure to set the QISKIT_IONQ_API_TOKEN environment variable # provider_backend = provider.get_backend("ionq_qpu") # backend_id="ionq_qpu" # # An example using BlueQubit provider # import sys # sys.path.insert(1, "../..") # import os, bluequbit, _common.executors.bluequbit_executor as bluequbit_executor # provider_backend = bluequbit.init() # backend_id="BlueQubit-CPU" # exec_options = { "executor": bluequbit_executor.run, "device":'cpu' } # # *** Here's an example of using a typical custom provider backend (e.g. AQT simulator) # import os # from qiskit_aqt_provider import AQTProvider # provider = AQTProvider(os.environ.get('AQT_ACCESS_KEY')) # get your key from environment # provider_backend = provider.backends.aqt_qasm_simulator_noise_1 # backend_id="aqt_qasm_simulator_noise_1" # Custom optimization options can be specified in this cell (below is an example) import sys sys.path.insert(1, "../../") # # Example of pytket Transformer # import _common.transformers.tket_optimiser as tket_optimiser # exec_options.update({ "optimization_level": 0, "layout_method":'sabre', "routing_method":'sabre', "transformer": tket_optimiser.high_optimisation }) # # Define a custom noise model to be used during execution # import _common.custom.custom_qiskit_noise_model as custom_qiskit_noise_model # exec_options.update({ "noise_model": custom_qiskit_noise_model.my_noise_model() }) # # Example of mthree error mitigation # import _common.postprocessors.mthree.mthree_em as mthree_em # exec_options.update({ "postprocessor": mthree_em.get_mthree_handlers(backend_id, provider_backend) }) import sys sys.path.insert(1, "maxcut/qsim") import maxcut_benchmark # set noise to None for testing # import execute # execute.set_noise_model(None) maxcut_benchmark.run( min_qubits=min_qubits, max_qubits=max_qubits, max_circuits=max_circuits, num_shots=num_shots, method=1, rounds=1, backend_id=backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options ) import sys sys.path.insert(1, "maxcut/qsim") import maxcut_benchmark # # set noise to None for testing # import execute # execute.set_noise_model(None) # execute and display options objective_func_type = 'approx_ratio' score_metric=['approx_ratio', 'cvar_ratio'] x_metric=['cumulative_elapsed_time', 'cumulative_exec_time', 'cumulative_opt_exec_time'] # Note: the plots produced by this benchmark only use the last of the problems at each width maxcut_benchmark.run( min_qubits=min_qubits, max_qubits=max_qubits, max_circuits=max_circuits, num_shots=num_shots, method=2, rounds=2, degree=3, do_fidelities=True, parameterized=False, use_fixed_angles=False, score_metric=score_metric, x_metric=x_metric, save_res_to_file=True, comfort=True, objective_func_type = objective_func_type, backend_id=backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options ) import os, maxcut_benchmark backend_id = "dm_simulator" maxcut_benchmark.load_data_and_plot(os.path.join('__results', backend_id, 'approx_ratio'), score_metric=['approx_ratio', 'cvar_ratio'], x_metric=['cumulative_elapsed_time', 'cumulative_exec_time', 'cumulative_opt_exec_time']) import sys sys.path.insert(1, "maxcut/qsim") import maxcut_benchmark # set noise to None for testing import execute execute.set_noise_model(None) objective_func_type = 'cvar_ratio' score_metric=[objective_func_type] x_metric=['cumulative_exec_time'] # Note: the plots produced by this benchmark only use the last of the problems at each width maxcut_benchmark.run( min_qubits=min_qubits, max_qubits=max_qubits, max_circuits=max_circuits, num_shots=num_shots, method=2, rounds=2, degree=3, alpha = 0.1, objective_func_type = objective_func_type, do_fidelities = False, score_metric=score_metric, x_metric=x_metric, num_x_bins=15, max_iter=30, backend_id=backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options ) import sys sys.path.insert(1, "maxcut/qsim") import maxcut_benchmark # set noise to None for testing import execute execute.set_noise_model(None) objective_func_type = 'gibbs_ratio' score_metric=[objective_func_type] #, 'fidelity' x_metric=['cumulative_exec_time'] #, , 'cumulative_create_time' 'cumulative_opt_exec_time' # Note: the plots produced by this benchmark only use the last of the problems at each width maxcut_benchmark.run( min_qubits=min_qubits, max_qubits=max_qubits, max_circuits=max_circuits, num_shots=num_shots, method=2, rounds=2, degree=3, eta=0.5, score_metric=score_metric, x_metric=x_metric, num_x_bins=15, max_iter=30, objective_func_type = objective_func_type, do_fidelities = False, backend_id=backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options ) import sys sys.path.insert(1, "maxcut/qsim") import maxcut_benchmark # set noise to None for testing import execute execute.set_noise_model(None) score_metric=['approx_ratio', 'fidelity'] x_metric=['cumulative_create_time', 'cumulative_exec_time', 'cumulative_opt_exec_time'] # Note: the plots produced by this benchmark only use the last of the problems at each width maxcut_benchmark.run( min_qubits=min_qubits, max_qubits=max_qubits, max_circuits=max_circuits, num_shots=num_shots, method=2, rounds=1, degree=-3, score_metric=score_metric, x_metric=x_metric, num_x_bins=15, max_iter=30, backend_id=backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options ) from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister beta = 0.08 gamma = -0.094 cycle_time = 0 qr = QuantumRegister(4) cr = ClassicalRegister(4) qc = QuantumCircuit(qr, cr, name="main") qc.h(qr[0]) qc.h(qr[1]) qc.h(qr[2]) qc.h(qr[3]) qc.cx(qr[0], qr[1]) qc.rz(2*3.14159*gamma, qr[1]) qc.cx(qr[0], qr[1]) qc.cx(qr[0], qr[3]) qc.rz(2*3.14159*gamma, qr[3]) qc.cx(qr[0], qr[3]) qc.cx(qr[0], qr[2]) qc.rz(2*3.14159*gamma, qr[2]) qc.cx(qr[0], qr[2]) qc.cx(qr[1], qr[2]) qc.rz(2*3.14159*gamma, qr[2]) qc.cx(qr[1], qr[2]) qc.cx(qr[1], qr[3]) qc.rz(2*3.14159*gamma, qr[3]) qc.cx(qr[1], qr[3]) qc.cx(qr[2], qr[3]) qc.rz(2*3.14159*gamma, qr[3]) qc.cx(qr[2], qr[3]) qc.rx(2*3.14159*beta, qr[0]) qc.rx(2*3.14159*beta, qr[1]) qc.rx(2*3.14159*beta, qr[2]) qc.rx(2*3.14159*beta, qr[3]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) qc.measure(qr[2], cr[2]) qc.measure(qr[3], cr[3]) from qiskit import execute, BasicAer backend = BasicAer.get_backend("dm_simulator") # Use BasicAer dm_simulator job = execute(qc, backend, shots=1000) result = job.result() if result.backend_name == 'dm_simulator': try: probs = result.results[0].data.partial_probability # get results as measured probability except AttributeError: try: probs = result.results[0].data.ensemble_probability except AttributeError: probs = None else: probs = result.get_counts(qc) # get results as measured counts print("\nprobability ===== ",probs) # Draw the circuit print(qc) # Plot a histogram from qiskit.visualization import plot_histogram plot_histogram(probs)
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
""" MaxCut Benchmark Program - QSim """ import datetime import json import logging import math import os import re import sys import time from collections import namedtuple import numpy as np from scipy.optimize import minimize from qiskit import (BasicAer, ClassicalRegister, # for computing expectation tables QuantumCircuit, QuantumRegister, execute, transpile) from qiskit.circuit import ParameterVector sys.path[1:1] = [ "_common", "_common/qsim", "maxcut/_common" ] sys.path[1:1] = [ "../../_common", "../../_common/qsim", "../../maxcut/_common/" ] import common import execute as ex import metrics as metrics from execute import BenchmarkResult # DEVNOTE: this logging feature should be moved to common level logger = logging.getLogger(__name__) fname, _, ext = os.path.basename(__file__).partition(".") log_to_file = False try: if log_to_file: logging.basicConfig( # filename=f"{fname}_{datetime.datetime.now().strftime('%Y_%m_%d_%S')}.log", filename=f"{fname}.log", filemode='w', encoding='utf-8', level=logging.INFO, format='%(asctime)s %(name)s - %(levelname)s:%(message)s' ) else: logging.basicConfig( level=logging.WARNING, format='%(asctime)s %(name)s - %(levelname)s:%(message)s') except Exception as e: print(f'Exception {e} occured while configuring logger: bypassing logger config to prevent data loss') pass # Benchmark Name benchmark_name = "MaxCut" np.random.seed(0) maxcut_inputs = dict() #inputs to the run method verbose = False print_sample_circuit = True # Indicates whether to perform the (expensive) pre compute of expectations do_compute_expectation = True # saved circuits for display QC_ = None Uf_ = None # based on examples from https://qiskit.org/textbook/ch-applications/qaoa.html QAOA_Parameter = namedtuple('QAOA_Parameter', ['beta', 'gamma']) # Qiskit uses the little-Endian convention. Hence, measured bit-strings need to be reversed while evaluating cut sizes reverseStep = -1 #%% MaxCut circuit creation and fidelity analaysis functions def create_qaoa_circ(nqubits, edges, parameters): qc = QuantumCircuit(nqubits) # initial_state for i in range(0, nqubits): qc.h(i) for par in parameters: #print(f"... gamma, beta = {par.gamma} {par.beta}") # problem unitary for i,j in edges: qc.rzz(- par.gamma, i, j) qc.barrier() # mixer unitary for i in range(0, nqubits): qc.rx(2 * par.beta, i) return qc def MaxCut (num_qubits, secret_int, edges, rounds, thetas_array, parameterized, measured = True): if parameterized: return MaxCut_param(num_qubits, secret_int, edges, rounds, thetas_array) # if no thetas_array passed in, create defaults if thetas_array is None: thetas_array = 2*rounds*[1.0] #print(f"... incoming thetas_array={thetas_array} rounds={rounds}") # get number of qaoa rounds (p) from length of incoming array p = len(thetas_array)//2 # if rounds passed in is less than p, truncate array if rounds < p: p = rounds thetas_array = thetas_array[:2*rounds] # if more rounds requested than in thetas_array, give warning (can fill array later) elif rounds > p: rounds = p print(f"WARNING: rounds is greater than length of thetas_array/2; using rounds={rounds}") logger.info(f'*** Constructing NON-parameterized circuit for num_qubits = {num_qubits} secret_int = {secret_int}') # create parameters in the form expected by the ansatz generator # this is an array of betas followed by array of gammas, each of length = rounds betas = thetas_array[:p] gammas = thetas_array[p:] parameters = [QAOA_Parameter(*t) for t in zip(betas,gammas)] # and create the circuit, without measurements qc = create_qaoa_circ(num_qubits, edges, parameters) # pre-compute and save an array of expected measurements if do_compute_expectation: logger.info('Computing expectation') compute_expectation(qc, num_qubits, secret_int) # add the measure here if measured: qc.measure_all() # save small circuit example for display global QC_ if QC_ == None or num_qubits <= 6: if num_qubits < 9: QC_ = qc # return a handle on the circuit return qc, None ############### Circuit Definition - Parameterized version # Create ansatz specific to this problem, defined by G = nodes, edges, and the given parameters # Do not include the measure operation, so we can pre-compute statevector def create_qaoa_circ_param(nqubits, edges, betas, gammas): qc = QuantumCircuit(nqubits) # initial_state for i in range(0, nqubits): qc.h(i) for beta, gamma in zip(betas, gammas): #print(f"... gamma, beta = {gammas}, {betas}") # problem unitary for i,j in edges: qc.rzz(- gamma, i, j) qc.barrier() # mixer unitary for i in range(0, nqubits): qc.rx(2 * beta, i) return qc _qc = None beta_params = [] gamma_params = [] # Create the benchmark program circuit # Accepts optional rounds and array of thetas (betas and gammas) def MaxCut_param (num_qubits, secret_int, edges, rounds, thetas_array): # if no thetas_array passed in, create defaults if thetas_array is None: thetas_array = 2*rounds*[1.0] #print(f"... incoming thetas_array={thetas_array} rounds={rounds}") # get number of qaoa rounds (p) from length of incoming array p = len(thetas_array)//2 # if rounds passed in is less than p, truncate array if rounds < p: p = rounds thetas_array = thetas_array[:2*rounds] # if more rounds requested than in thetas_array, give warning (can fill array later) elif rounds > p: rounds = p print(f"WARNING: rounds is greater than length of thetas_array/2; using rounds={rounds}") #print(f"... actual thetas_array={thetas_array}") # create parameters in the form expected by the ansatz generator # this is an array of betas followed by array of gammas, each of length = rounds global _qc global betas global gammas # create the circuit the first time, add measurements if ex.do_transpile_for_execute: logger.info(f'*** Constructing parameterized circuit for num_qubits = {num_qubits} secret_int = {secret_int}') betas = ParameterVector("𝞫", p) gammas = ParameterVector("𝞬", p) _qc = create_qaoa_circ_param(num_qubits, edges, betas, gammas) # add the measure here, only after circuit is created _qc.measure_all() params = {betas: thetas_array[:p], gammas: thetas_array[p:]} #logger.info(f"Binding parameters {params = }") logger.info(f"Create binding parameters for {thetas_array}") qc = _qc #print(qc) # pre-compute and save an array of expected measurements if do_compute_expectation: logger.info('Computing expectation') compute_expectation(qc, num_qubits, secret_int, params=params) # save small circuit example for display global QC_ if QC_ == None or num_qubits <= 6: if num_qubits < 9: QC_ = qc # return a handle on the circuit return qc, params ############### Expectation Tables # DEVNOTE: We are building these tables on-demand for now, but for larger circuits # this will need to be pre-computed ahead of time and stored in a data file to avoid run-time delays. # dictionary used to store pre-computed expectations, keyed by num_qubits and secret_string # these are created at the time the circuit is created, then deleted when results are processed expectations = {} # Compute array of expectation values in range 0.0 to 1.0 # Use statevector_simulator to obtain exact expectation def compute_expectation(qc, num_qubits, secret_int, backend_id='statevector_simulator', params=None): #ts = time.time() if params != None: qc = qc.bind_parameters(params) #execute statevector simulation sv_backend = BasicAer.get_backend(backend_id) sv_result = execute(qc, sv_backend).result() # get the probability distribution counts = sv_result.get_counts() #print(f"... statevector expectation = {counts}") # store in table until circuit execution is complete id = f"_{num_qubits}_{secret_int}" expectations[id] = counts #print(f" ... time to execute statevector simulator: {time.time() - ts}") # Return expected measurement array scaled to number of shots executed def get_expectation(num_qubits, degree, num_shots): # find expectation counts for the given circuit id = f"_{num_qubits}_{degree}" if id in expectations: counts = expectations[id] # scale to number of shots for k, v in counts.items(): # counts[k] = round(v * num_shots) counts[k] = v * num_shots # delete from the dictionary del expectations[id] return counts else: return None ############### Result Data Analysis expected_dist = {} # Compare the measurement results obtained with the expected measurements to determine fidelity def analyze_and_print_result (qc, result, num_qubits, secret_int, num_shots): global expected_dist # print(result) if result.backend_name == 'dm_simulator': try: probs = result.results[0].data.partial_probability # get results as measured probability except AttributeError: try: probs = result.results[0].data.ensemble_probability except AttributeError: probs = None else: probs = result.get_counts(qc) # get results as measured counts # retrieve pre-computed expectation values for the circuit that just completed expected_dist = get_expectation(num_qubits, secret_int, num_shots) # if the expectation is not being calculated (only need if we want to compute fidelity) # assume that the expectation is the same as measured probability, yielding fidelity = 1 if expected_dist == None: expected_dist = probs # print("\nexpected_dist ====== ", expected_dist) if verbose: print(f"For width {num_qubits} problem {secret_int}\n measured: {probs}\n expected: {expected_dist}") # use our polarization fidelity rescaling fidelity = metrics.polarization_fidelity(probs, expected_dist) if verbose: print(f"For secret int {secret_int} fidelity: {fidelity}") return probs, fidelity #%% Computation of various metrics, such as approximation ratio, etc. def compute_cutsizes(results, nodes, edges): """ Given a result object, extract the values of meaasured cuts and the corresponding counts into ndarrays. Also compute and return the corresponding cut sizes. Returns ------- cuts : list of strings each element is a bitstring denoting a cut counts : ndarray of ints measured counts corresponding to cuts sizes : ndarray of ints cut sizes (i.e. number of edges crossing the cut) """ cuts = list(results.results[0].data.partial_probability.keys()) counts = list(results.results[0].data.partial_probability.values()) sizes = [common.eval_cut(nodes, edges, cut, reverseStep) for cut in cuts] return cuts, counts, sizes def get_size_dist(counts, sizes): """ For given measurement outcomes, i.e. combinations of cuts, counts and sizes, return counts corresponding to each cut size. """ unique_sizes = list(set(sizes)) unique_counts = [0] * len(unique_sizes) for i, size in enumerate(unique_sizes): corresp_counts = [counts[ind] for ind,s in enumerate(sizes) if s == size] unique_counts[i] = sum(corresp_counts) # Make sure that the scores are in ascending order s_and_c_list = [[a,b] for (a,b) in zip(unique_sizes, unique_counts)] s_and_c_list = sorted(s_and_c_list, key = lambda x : x[0]) unique_sizes = [x[0] for x in s_and_c_list] unique_counts = [x[1] for x in s_and_c_list] cumul_counts = np.cumsum(unique_counts) return unique_counts, unique_sizes, cumul_counts.tolist() # Compute the objective function on a given sample def compute_sample_mean(counts, sizes, **kwargs): """ Compute the mean of cut sizes (i.e. the weighted average of sizes weighted by counts) This approximates the expectation value of the state at the end of the circuit Parameters ---------- counts : ndarray of ints measured counts corresponding to cuts sizes : ndarray of ints cut sizes (i.e. number of edges crossing the cut) **kwargs : optional arguments will be ignored Returns ------- float """ # Convert counts and sizes to ndarrays, if they are lists counts, sizes = np.array(counts), np.array(sizes) return - np.sum(counts * sizes) / np.sum(counts) def compute_cvar(counts, sizes, alpha = 0.1, **kwargs): """ Obtains the Conditional Value at Risk or CVaR for samples measured at the end of the variational circuit. Reference: Barkoutsos, P. K., Nannicini, G., Robert, A., Tavernelli, I. & Woerner, S. Improving Variational Quantum Optimization using CVaR. Quantum 4, 256 (2020). Parameters ---------- counts : ndarray of ints measured counts corresponding to cuts sizes : ndarray of ints cut sizes (i.e. number of edges crossing the cut) alpha : float, optional Confidence interval value for CVaR. The default is 0.1. Returns ------- float CVaR value """ # Convert counts and sizes to ndarrays, if they are lists counts, sizes = np.array(counts), np.array(sizes) # Sort the negative of the cut sizes in a non-decreasing order. # Sort counts in the same order as sizes, so that i^th element of each correspond to each other sort_inds = np.argsort(-sizes) sizes = sizes[sort_inds] counts = counts[sort_inds] # Choose only the top num_avgd = ceil(alpha * num_shots) cuts. These will be averaged over. num_avgd = math.ceil(alpha * np.sum(counts)) # Compute cvar cvar_sum = 0 counts_so_far = 0 for c, s in zip(counts, sizes): if counts_so_far + c >= num_avgd: cts_to_consider = num_avgd - counts_so_far cvar_sum += cts_to_consider * s break else: counts_so_far += c cvar_sum += c * s return - cvar_sum / num_avgd def compute_gibbs(counts, sizes, eta = 0.5, **kwargs): """ Compute the Gibbs objective function for given measurements Parameters ---------- counts : ndarray of ints measured counts corresponding to cuts sizes : ndarray of ints cut sizes (i.e. number of edges crossing the cut) eta : float, optional Inverse Temperature Returns ------- float - Gibbs objective function value / optimal value """ # Convert counts and sizes to ndarrays, if they are lists counts, sizes = np.array(counts), np.array(sizes) ls = max(sizes)#largest size shifted_sizes = sizes - ls # gibbs = - np.log( np.sum(counts * np.exp(eta * sizes)) / np.sum(counts)) gibbs = - eta * ls - np.log(np.sum (counts / np.sum(counts) * np.exp(eta * shifted_sizes))) return gibbs def compute_best_cut_from_measured(counts, sizes, **kwargs): """From the measured cuts, return the size of the largest cut """ return - np.max(sizes) def compute_quartiles(counts, sizes): """ Compute and return the sizes of the cuts at the three quartile values (i.e. 0.25, 0.5 and 0.75) Parameters ---------- counts : ndarray of ints measured counts corresponding to cuts sizes : ndarray of ints cut sizes (i.e. number of edges crossing the cut) Returns ------- quantile_sizes : ndarray of of 3 floats sizes of cuts corresponding to the three quartile values. """ # Convert counts and sizes to ndarrays, if they are lists counts, sizes = np.array(counts), np.array(sizes) # Sort sizes and counts in the sequence of non-decreasing values of sizes sort_inds = np.argsort(sizes) sizes = sizes[sort_inds] counts = counts[sort_inds] num_shots = np.sum(counts) q_vals = [0.25, 0.5, 0.75] ct_vals = [math.floor(q * num_shots) for q in q_vals] cumsum_counts = np.cumsum(counts) locs = np.searchsorted(cumsum_counts, ct_vals) quantile_sizes = sizes[locs] return quantile_sizes def uniform_cut_sampling(num_qubits, degree, num_shots, _instances=None): """ For a given problem, i.e. num_qubits and degree values, sample cuts uniformly at random from all possible cuts, num_shots number of times. Return the corresponding cuts, counts and cut sizes. """ # First, load the nodes and edges corresponding to the problem instance_filename = os.path.join(os.path.dirname(__file__), "..", "_common", common.INSTANCE_DIR, f"mc_{num_qubits:03d}_{degree:03d}_000.txt") nodes, edges = common.read_maxcut_instance(instance_filename, _instances) # Obtain num_shots number of uniform random samples between 0 and 2 ** num_qubits unif_cuts = np.random.randint(2 ** num_qubits, size=num_shots).tolist() unif_cuts_uniq = list(set(unif_cuts)) # Get counts corresponding to each sampled int/cut unif_counts = [unif_cuts.count(cut) for cut in unif_cuts_uniq] unif_cuts = list(set(unif_cuts)) def int_to_bs(numb): # Function for converting from an integer to (bit)strings of length num_qubits strr = format(numb, "b") #convert to binary strr = '0' * (num_qubits - len(strr)) + strr return strr unif_cuts = [int_to_bs(i) for i in unif_cuts] unif_sizes = [common.eval_cut(nodes, edges, cut, reverseStep) for cut in unif_cuts] # Also get the corresponding distribution of cut sizes unique_counts_unif, unique_sizes_unif, cumul_counts_unif = get_size_dist(unif_counts, unif_sizes) return unif_cuts, unif_counts, unif_sizes, unique_counts_unif, unique_sizes_unif, cumul_counts_unif def get_random_angles(rounds, restarts): """Create max_circuit number of random initial conditions Args: rounds (int): number of rounds in QAOA restarts (int): number of random initial conditions Returns: restarts (list of lists of floats): list of length restarts. Each list element is a list of angles """ # restarts = min(10, restarts) # Create random angles theta_min = [0] * 2 * rounds # Upper limit for betas=pi; upper limit for gammas=2pi theta_max = [np.pi] * rounds + [2 * np.pi] * rounds thetas = np.random.uniform( low=theta_min, high=theta_max, size=(restarts, 2 * rounds) ) thetas = thetas.tolist() return thetas def get_restart_angles(thetas_array, rounds, restarts): """ Create random initial conditions for the restart loop. thetas_array takes precedence over restarts. If the user inputs valid thetas_array, restarts will be inferred accordingly. If thetas_array is None and restarts is 1, return all 1's as initial angles. If thetas_array is None and restarts >1, generate restarts number of random initial conditions If only one set of random angles are desired, then the user needs to create them and send as thetas_array Args: thetas_array (list of lists of floats): list of initial angles. restarts (int): number of random initial conditions rounds (int): of QAOA Returns: thetas (list of lists. Shape = (max_circuits, 2 * rounds)) restarts : int """ assert type(restarts) == int and restarts > 0, "max_circuits must be an integer greater than 0" default_angles = [[1] * 2 * rounds] default_restarts = 1 if thetas_array is None: if restarts == 1: # if the angles are none, but restarts equals 1, use default of all 1's return default_angles, default_restarts else: # restarts can only be greater than 1. return get_random_angles(rounds, restarts), restarts if type(thetas_array) != list: # thetas_array is not None, but is also not a list. print("thetas_array is not a list. Using random angles.") return get_random_angles(rounds, restarts), restarts # At this point, thetas_array is a list. check if thetas_array is a list of lists if not all([type(item) == list for item in thetas_array]): # if every list element is not a list, return random angles print("thetas_array is not a list of lists. Using random angles.") return get_random_angles(rounds, restarts), restarts if not all([len(item) == 2 * rounds for item in thetas_array]): # If not all list elements are lists of the correct length... print("Each element of thetas_array must be a list of length 2 * rounds. Using random angles.") return get_random_angles(rounds, restarts), restarts # At this point, thetas_array is a list of lists of length 2*rounds. All conditions are satisfied. Return inputted angles. return thetas_array, len(thetas_array) #%% Storing final iteration data to json file, and to metrics.circuit_metrics_final_iter def save_runtime_data(result_dict): # This function will need changes, since circuit metrics dictionaries are now different cm = result_dict.get('circuit_metrics') detail = result_dict.get('circuit_metrics_detail', None) detail_2 = result_dict.get('circuit_metrics_detail_2', None) benchmark_inputs = result_dict.get('benchmark_inputs', None) final_iter_metrics = result_dict.get('circuit_metrics_final_iter') backend_id = result_dict.get('benchmark_inputs').get('backend_id') metrics.circuit_metrics_detail_2 = detail_2 for width in detail_2: # unique_id = restart_ind * 1000 + minimizer_iter_ind restart_ind_list = list(detail_2.get(width).keys()) for restart_ind in restart_ind_list: degree = cm[width]['1']['degree'] opt = final_iter_metrics[width]['1']['optimal_value'] instance_filename = os.path.join(os.path.dirname(__file__), "..", "_common", common.INSTANCE_DIR, f"mc_{int(width):03d}_{int(degree):03d}_000.txt") metrics.circuit_metrics[width] = detail.get(width) metrics.circuit_metrics['subtitle'] = cm.get('subtitle') finIterDict = final_iter_metrics[width][restart_ind] if benchmark_inputs['save_final_counts']: # if the final iteration cut counts were stored, retrieve them iter_dist = {'cuts' : finIterDict['cuts'], 'counts' : finIterDict['counts'], 'sizes' : finIterDict['sizes']} else: # The value of iter_dist does not matter otherwise iter_dist = None # Retrieve the distribution of cut sizes for the final iteration for this width and degree iter_size_dist = {'unique_sizes' : finIterDict['unique_sizes'], 'unique_counts' : finIterDict['unique_counts'], 'cumul_counts' : finIterDict['cumul_counts']} converged_thetas_list = finIterDict.get('converged_thetas_list') parent_folder_save = os.path.join('__data', f'{metrics.get_backend_label(backend_id)}') store_final_iter_to_metrics_json( num_qubits=int(width), degree = int(degree), restart_ind=int(restart_ind), num_shots=int(benchmark_inputs['num_shots']), converged_thetas_list=converged_thetas_list, opt=opt, iter_size_dist=iter_size_dist, iter_dist = iter_dist, dict_of_inputs=benchmark_inputs, parent_folder_save=parent_folder_save, save_final_counts=False, save_res_to_file=True, _instances=None ) def store_final_iter_to_metrics_json(num_qubits, degree, restart_ind, num_shots, converged_thetas_list, opt, iter_size_dist, iter_dist, parent_folder_save, dict_of_inputs, save_final_counts, save_res_to_file, _instances=None): """ For a given graph (specified by num_qubits and degree), 1. For a given restart, store properties of the final minimizer iteration to metrics.circuit_metrics_final_iter, and 2. Store various properties for all minimizer iterations for each restart to a json file. Parameters ---------- num_qubits, degree, restarts, num_shots : ints parent_folder_save : string (location where json file will be stored) dict_of_inputs : dictionary of inputs that were given to run() save_final_counts: bool. If true, save counts, cuts and sizes for last iteration to json file. save_res_to_file: bool. If False, do not save data to json file. iter_size_dist : dictionary containing distribution of cut sizes. Keys are 'unique_sizes', 'unique_counts' and 'cumul_counts' opt (int) : Max Cut value """ # In order to compare with uniform random sampling, get some samples unif_cuts, unif_counts, unif_sizes, unique_counts_unif, unique_sizes_unif, cumul_counts_unif = uniform_cut_sampling( num_qubits, degree, num_shots, _instances) unif_dict = {'unique_counts_unif': unique_counts_unif, 'unique_sizes_unif': unique_sizes_unif, 'cumul_counts_unif': cumul_counts_unif} # store only the distribution of cut sizes, and not the cuts themselves # Store properties such as (cuts, counts, sizes) of the final iteration, the converged theta values, as well as the known optimal value for the current problem, in metrics.circuit_metrics_final_iter. Also store uniform cut sampling results metrics.store_props_final_iter(num_qubits, restart_ind, 'optimal_value', opt) metrics.store_props_final_iter(num_qubits, restart_ind, None, iter_size_dist) metrics.store_props_final_iter(num_qubits, restart_ind, 'converged_thetas_list', converged_thetas_list) metrics.store_props_final_iter(num_qubits, restart_ind, None, unif_dict) # metrics.store_props_final_iter(num_qubits, restart_ind, None, iter_dist) # do not store iter_dist, since it takes a lot of memory for larger widths, instead, store just iter_size_dist if save_res_to_file: # Save data to a json file dump_to_json(parent_folder_save, num_qubits, degree, restart_ind, iter_size_dist, iter_dist, dict_of_inputs, converged_thetas_list, opt, unif_dict, save_final_counts=save_final_counts) def dump_to_json(parent_folder_save, num_qubits, degree, restart_ind, iter_size_dist, iter_dist, dict_of_inputs, converged_thetas_list, opt, unif_dict, save_final_counts=False): """ For a given problem (specified by number of qubits and graph degree) and restart_index, save the evolution of various properties in a json file. Items stored in the json file: Data from all iterations (iterations), inputs to run program ('general properties'), converged theta values ('converged_thetas_list'), max cut size for the graph (optimal_value), distribution of cut sizes for random uniform sampling (unif_dict), and distribution of cut sizes for the final iteration (final_size_dist) if save_final_counts is True, then also store the distribution of cuts """ if not os.path.exists(parent_folder_save): os.makedirs(parent_folder_save) store_loc = os.path.join(parent_folder_save,'width_{}_restartInd_{}.json'.format(num_qubits, restart_ind)) # Obtain dictionary with iterations data corresponding to given restart_ind all_restart_ids = list(metrics.circuit_metrics[str(num_qubits)].keys()) ids_this_restart = [r_id for r_id in all_restart_ids if int(r_id) // 1000 == restart_ind] iterations_dict_this_restart = {r_id : metrics.circuit_metrics[str(num_qubits)][r_id] for r_id in ids_this_restart} # Values to be stored in json file dict_to_store = {'iterations' : iterations_dict_this_restart} dict_to_store['general_properties'] = dict_of_inputs dict_to_store['converged_thetas_list'] = converged_thetas_list dict_to_store['optimal_value'] = opt dict_to_store['unif_dict'] = unif_dict dict_to_store['final_size_dist'] = iter_size_dist # Also store the value of counts obtained for the final counts if save_final_counts: dict_to_store['final_counts'] = iter_dist #iter_dist.get_counts() # Now save the output with open(store_loc, 'w') as outfile: json.dump(dict_to_store, outfile) #%% Loading saved data (from json files) def load_data_and_plot(folder=None, backend_id=None, **kwargs): """ The highest level function for loading stored data from a previous run and plotting optgaps and area metrics Parameters ---------- folder : string Directory where json files are saved. """ _gen_prop = load_all_metrics(folder, backend_id=backend_id) if _gen_prop != None: gen_prop = {**_gen_prop, **kwargs} plot_results_from_data(**gen_prop) def load_all_metrics(folder=None, backend_id=None): """ Load all data that was saved in a folder. The saved data will be in json files in this folder Parameters ---------- folder : string Directory where json files are saved. Returns ------- gen_prop : dict of inputs that were used in maxcut_benchmark.run method """ # if folder not passed in, create its name using standard format if folder is None: folder = f"__data/{metrics.get_backend_label(backend_id)}" # Note: folder here should be the folder where only the width=... files are stored, and not a folder higher up in the directory assert os.path.isdir(folder), f"Specified folder ({folder}) does not exist." metrics.init_metrics() list_of_files = os.listdir(folder) width_restart_file_tuples = [(*get_width_restart_tuple_from_filename(fileName), fileName) for (ind, fileName) in enumerate(list_of_files) if fileName.startswith("width")] # list with elements that are tuples->(width,restartInd,filename) width_restart_file_tuples = sorted(width_restart_file_tuples, key=lambda x:(x[0], x[1])) #sort first by width, and then by restartInd distinct_widths = list(set(it[0] for it in width_restart_file_tuples)) list_of_files = [ [tup[2] for tup in width_restart_file_tuples if tup[0] == width] for width in distinct_widths ] # connot continue without at least one dataset if len(list_of_files) < 1: print("ERROR: No result files found") return None for width_files in list_of_files: # For each width, first load all the restart files for fileName in width_files: gen_prop = load_from_width_restart_file(folder, fileName) # next, do processing for the width method = gen_prop['method'] if method == 2: num_qubits, _ = get_width_restart_tuple_from_filename(width_files[0]) metrics.process_circuit_metrics_2_level(num_qubits) metrics.finalize_group(str(num_qubits)) # override device name with the backend_id if supplied by caller if backend_id != None: metrics.set_plot_subtitle(f"Device = {backend_id}") return gen_prop def load_from_width_restart_file(folder, fileName): """ Given a folder name and a file in it, load all the stored data and store the values in metrics.circuit_metrics. Also return the converged values of thetas, the final counts and general properties. Parameters ---------- folder : string folder where the json file is located fileName : string name of the json file Returns ------- gen_prop : dict of inputs that were used in maxcut_benchmark.run method """ # Extract num_qubits and s from file name num_qubits, restart_ind = get_width_restart_tuple_from_filename(fileName) print(f"Loading from {fileName}, corresponding to {num_qubits} qubits and restart index {restart_ind}") with open(os.path.join(folder, fileName), 'r') as json_file: data = json.load(json_file) gen_prop = data['general_properties'] converged_thetas_list = data['converged_thetas_list'] unif_dict = data['unif_dict'] opt = data['optimal_value'] if gen_prop['save_final_counts']: # Distribution of measured cuts final_counts = data['final_counts'] final_size_dist = data['final_size_dist'] backend_id = gen_prop.get('backend_id') metrics.set_plot_subtitle(f"Device = {backend_id}") # Update circuit metrics for circuit_id in data['iterations']: # circuit_id = restart_ind * 1000 + minimizer_loop_ind for metric, value in data['iterations'][circuit_id].items(): metrics.store_metric(num_qubits, circuit_id, metric, value) method = gen_prop['method'] if method == 2: metrics.store_props_final_iter(num_qubits, restart_ind, 'optimal_value', opt) metrics.store_props_final_iter(num_qubits, restart_ind, None, final_size_dist) metrics.store_props_final_iter(num_qubits, restart_ind, 'converged_thetas_list', converged_thetas_list) metrics.store_props_final_iter(num_qubits, restart_ind, None, unif_dict) if gen_prop['save_final_counts']: metrics.store_props_final_iter(num_qubits, restart_ind, None, final_counts) return gen_prop def get_width_restart_tuple_from_filename(fileName): """ Given a filename, extract the corresponding width and degree it corresponds to For example the file "width=4_degree=3.json" corresponds to 4 qubits and degree 3 Parameters ---------- fileName : TYPE DESCRIPTION. Returns ------- num_qubits : int circuit width degree : int graph degree. """ pattern = 'width_([0-9]+)_restartInd_([0-9]+).json' match = re.search(pattern, fileName) # assert match is not None, f"File {fileName} found inside folder. All files inside specified folder must be named in the format 'width_int_restartInd_int.json" num_qubits = int(match.groups()[0]) degree = int(match.groups()[1]) return (num_qubits,degree) #%% Run method: Benchmarking loop MAX_QUBITS = 24 iter_dist = {'cuts' : [], 'counts' : [], 'sizes' : []} # (list of measured bitstrings, list of corresponding counts, list of corresponding cut sizes) iter_size_dist = {'unique_sizes' : [], 'unique_counts' : [], 'cumul_counts' : []} # for the iteration being executed, stores the distribution for cut sizes saved_result = { } instance_filename = None def run (min_qubits=3, max_qubits=8, skip_qubits=2, max_circuits=1, num_shots=1, # for dm-simulator num_shots=1 method=1, rounds=1, degree=3, alpha=0.1, thetas_array=None, parameterized= False, do_fidelities=True, max_iter=30, score_metric='fidelity', x_metric='cumulative_exec_time', y_metric='num_qubits', fixed_metrics={}, num_x_bins=15, y_size=None, x_size=None, use_fixed_angles=False, objective_func_type = 'approx_ratio', plot_results = True, save_res_to_file = False, save_final_counts = False, detailed_save_names = False, comfort=False, backend_id='dm_simulator', provider_backend=None, eta=0.5, #hub="ibm-q", group="open", project="main", exec_options=None, context=None, _instances=None): """ Parameters ---------- min_qubits : int, optional The smallest circuit width for which benchmarking will be done The default is 3. max_qubits : int, optional The largest circuit width for which benchmarking will be done. The default is 6. skip_qubits : int, optional Skip at least this many qubits during run loop. The default is 2. max_circuits : int, optional Number of restarts. The default is None. num_shots : int, optional Number of times the circut will be measured, for each iteration. The default is 100. method : int, optional If 1, then do standard metrics, if 2, implement iterative algo metrics. The default is 1. rounds : int, optional number of QAOA rounds. The default is 1. degree : int, optional degree of graph. The default is 3. thetas_array : list, optional list or ndarray of beta and gamma values. The default is None. use_fixed_angles : bool, optional use betas and gammas obtained from a 'fixed angles' table, specific to degree and rounds N : int, optional For the max % counts metric, choose the highest N% counts. The default is 10. alpha : float, optional Value between 0 and 1. The default is 0.1. parameterized : bool, optional Whether to use parametrized circuits or not. The default is False. do_fidelities : bool, optional Compute circuit fidelity. The default is True. max_iter : int, optional Number of iterations for the minimizer routine. The default is 30. score_metric : list or string, optional Which metrics are to be plotted in area metrics plots. The default is 'fidelity'. x_metric : list or string, optional Horizontal axis for area plots. The default is 'cumulative_exec_time'. y_metric : list or string, optional Vertical axis for area plots. The default is 'num_qubits'. fixed_metrics : TYPE, optional DESCRIPTION. The default is {}. num_x_bins : int, optional DESCRIPTION. The default is 15. y_size : TYPint, optional DESCRIPTION. The default is None. x_size : string, optional DESCRIPTION. The default is None. backend_id : string, optional DESCRIPTION. The default is 'qasm_simulator'. provider_backend : string, optional DESCRIPTION. The default is None. hub : string, optional DESCRIPTION. The default is "ibm-q". group : string, optional DESCRIPTION. The default is "open". project : string, optional DESCRIPTION. The default is "main". exec_options : string, optional DESCRIPTION. The default is None. objective_func_type : string, optional Objective function to be used by the classical minimizer algorithm. The default is 'approx_ratio'. plot_results : bool, optional Plot results only if True. The default is True. save_res_to_file : bool, optional Save results to json files. The default is True. save_final_counts : bool, optional If True, also save the counts from the final iteration for each problem in the json files. The default is True. detailed_save_names : bool, optional If true, the data and plots will be saved with more detailed names. Default is False confort : bool, optional If true, print comfort dots during execution """ # Store all the input parameters into a dictionary. # This dictionary will later be stored in a json file # It will also be used for sending parameters to the plotting function dict_of_inputs = locals() # Get angles for restarts. Thetas = list of lists. Lengths are max_circuits and 2*rounds thetas, max_circuits = get_restart_angles(thetas_array, rounds, max_circuits) # Update the dictionary of inputs dict_of_inputs = {**dict_of_inputs, **{'thetas_array': thetas, 'max_circuits' : max_circuits}} # Delete some entries from the dictionary # for key in ["hub", "group", "project", "provider_backend", "exec_options"]: # dict_of_inputs.pop(key) global maxcut_inputs maxcut_inputs = dict_of_inputs global QC_ global circuits_done global minimizer_loop_index global opt_ts print(f"{benchmark_name} ({method}) Benchmark Program - QSim") QC_ = None # Create a folder where the results will be saved. Folder name=time of start of computation # In particular, for every circuit width, the metrics will be stored the moment the results are obtained # In addition to the metrics, the (beta,gamma) values obtained by the optimizer, as well as the counts # measured for the final circuit will be stored. # Use the following parent folder, for a more detailed if detailed_save_names: start_time_str = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S") parent_folder_save = os.path.join('__results', f'{backend_id}', objective_func_type, f'run_start_{start_time_str}') else: parent_folder_save = os.path.join('__results', f'{backend_id}', objective_func_type) if save_res_to_file and not os.path.exists(parent_folder_save): os.makedirs(os.path.join(parent_folder_save)) # validate parameters max_qubits = max(4, max_qubits) max_qubits = min(MAX_QUBITS, max_qubits) min_qubits = min(max(4, min_qubits), max_qubits) skip_qubits = max(2, skip_qubits) # create context identifier if context is None: context = f"{benchmark_name} ({method}) Benchmark" degree = max(3, degree) rounds = max(1, rounds) # don't compute exectation unless fidelity is is needed global do_compute_expectation do_compute_expectation = do_fidelities # given that this benchmark does every other width, set y_size default to 1.5 if y_size == None: y_size = 1.5 # Choose the objective function to minimize, based on values of the parameters possible_approx_ratios = {'cvar_ratio', 'approx_ratio', 'gibbs_ratio', 'bestcut_ratio'} non_objFunc_ratios = possible_approx_ratios - { objective_func_type } function_mapper = {'cvar_ratio' : compute_cvar, 'approx_ratio' : compute_sample_mean, 'gibbs_ratio' : compute_gibbs, 'bestcut_ratio' : compute_best_cut_from_measured} # if using fixed angles, get thetas array from table if use_fixed_angles: # Load the fixed angle tables from data file fixed_angles = common.read_fixed_angles( os.path.join(os.path.dirname(__file__), '..', '_common', 'angles_regular_graphs.json'), _instances) thetas_array = common.get_fixed_angles_for(fixed_angles, degree, rounds) if thetas_array == None: print(f"ERROR: no fixed angles for rounds = {rounds}") return ########## # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler (qc, result, num_qubits, s_int, num_shots): # determine fidelity of result set num_qubits = int(num_qubits) counts, fidelity = analyze_and_print_result(qc, result, num_qubits, int(s_int), num_shots) metrics.store_metric(num_qubits, s_int, 'fidelity', fidelity) def execution_handler2 (qc, result, num_qubits, s_int, num_shots): # Stores the results to the global saved_result variable global saved_result saved_result = result # Initialize execution module using the execution result handler above and specified backend_id # for method=2 we need to set max_jobs_active to 1, so each circuit completes before continuing if method == 2: ex.max_jobs_active = 1 ex.init_execution(execution_handler2) else: ex.init_execution(execution_handler) # initialize the execution module with target information ex.set_execution_target(backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options, context=context ) # for noiseless simulation, set noise model to be None # ex.set_noise_model(None) ########## # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete # DEVNOTE: increment by 2 to match the collection of problems in 'instance' folder for num_qubits in range(min_qubits, max_qubits + 1, 2): if method == 1: print(f"************\nExecuting [{max_circuits}] circuits for num_qubits = {num_qubits}") else: print(f"************\nExecuting [{max_circuits}] restarts for num_qubits = {num_qubits}") # If degree is negative, if degree < 0 : degree = max(3, (num_qubits + degree)) # Load the problem and its solution global instance_filename instance_filename = os.path.join( os.path.dirname(__file__), "..", "_common", common.INSTANCE_DIR, f"mc_{num_qubits:03d}_{degree:03d}_000.txt", ) nodes, edges = common.read_maxcut_instance(instance_filename, _instances) opt, _ = common.read_maxcut_solution( instance_filename[:-4] + ".sol", _instances ) # if the file does not exist, we are done with this number of qubits if nodes == None: print(f" ... problem not found.") break for restart_ind in range(1, max_circuits + 1): # restart index should start from 1 # Loop over restarts for a given graph # if not using fixed angles, get initial or random thetas from array saved earlier # otherwise use random angles (if restarts > 1) or [1] * 2 * rounds if not use_fixed_angles: thetas_array = thetas[restart_ind - 1] if method == 1: # create the circuit for given qubit size and secret string, store time metric ts = time.time() # if using fixed angles in method 1, need to access first element # DEVNOTE: eliminate differences between method 1 and 2 and handling of thetas_array thetas_array_0 = thetas_array if use_fixed_angles: thetas_array_0 = thetas_array[0] qc, params = MaxCut(num_qubits, restart_ind, edges, rounds, thetas_array_0, parameterized) qc = qc.reverse_bits() # to reverse the endianness metrics.store_metric(num_qubits, restart_ind, 'create_time', time.time()-ts) # collapse the sub-circuit levels used in this benchmark (for qiskit) qc2 = qc.decompose() # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc2, num_qubits, restart_ind, shots=num_shots, params=params) if method == 2: # a unique circuit index used inside the inner minimizer loop as identifier minimizer_loop_index = 0 # Value of 0 corresponds to the 0th iteration of the minimizer start_iters_t = time.time() # Always start by enabling transpile ... ex.set_tranpilation_flags(do_transpile_metrics=True, do_transpile_for_execute=True) logger.info(f'=============== Begin method 2 loop, enabling transpile') def expectation(thetas_array): # Every circuit needs a unique id; add unique_circuit_index instead of s_int global minimizer_loop_index unique_id = restart_ind * 1000 + minimizer_loop_index # store thetas_array metrics.store_metric(num_qubits, unique_id, 'thetas_array', thetas_array.tolist()) #************************************************ #*** Circuit Creation and Decomposition start *** # create the circuit for given qubit size, secret string and params, store time metric ts = time.time() qc, params = MaxCut(num_qubits, unique_id, edges, rounds, thetas_array, parameterized) # qc = qc.reverse_bits() # to reverse the endianness metrics.store_metric(num_qubits, unique_id, 'create_time', time.time()-ts) # also store the 'rounds' and 'degree' for each execution # DEVNOTE: Currently, this is stored for each iteration. Reduce this redundancy metrics.store_metric(num_qubits, unique_id, 'rounds', rounds) metrics.store_metric(num_qubits, unique_id, 'degree', degree) # collapse the sub-circuit levels used in this benchmark (for qiskit) qc2 = qc.decompose() # Circuit Creation and Decomposition end #************************************************ #************************************************ #*** Quantum Part: Execution of Circuits *** # submit circuit for execution on target with the current parameters ex.submit_circuit(qc2, num_qubits, unique_id, shots=num_shots, params=params) # Must wait for circuit to complete #ex.throttle_execution(metrics.finalize_group) ex.finalize_execution(None, report_end=False) # don't finalize group until all circuits done # after first execution and thereafter, no need for transpilation if parameterized if parameterized: ex.set_tranpilation_flags(do_transpile_metrics=False, do_transpile_for_execute=False) logger.info(f'**** First execution complete, disabling transpile') #************************************************ global saved_result # Fidelity Calculation and Storage _, fidelity = analyze_and_print_result(qc, saved_result, num_qubits, unique_id, num_shots) metrics.store_metric(num_qubits, unique_id, 'fidelity', fidelity) #************************************************ #*** Classical Processing of Results - essential to optimizer *** global opt_ts dict_of_vals = dict() # Start counting classical optimizer time here again tc1 = time.time() cuts, counts, sizes = compute_cutsizes(saved_result, nodes, edges) # Compute the value corresponding to the objective function first dict_of_vals[objective_func_type] = function_mapper[objective_func_type](counts, sizes, alpha = alpha) # Store the optimizer time as current time- tc1 + ts - opt_ts, since the time between tc1 and ts is not time used by the classical optimizer. metrics.store_metric(num_qubits, unique_id, 'opt_exec_time', time.time() - tc1 + ts - opt_ts) # Note: the first time it is stored it is just the initialization time for optimizer #************************************************ #************************************************ #*** Classical Processing of Results - not essential for optimizer. Used for tracking metrics *** # Compute the distribution of cut sizes; store them under metrics unique_counts, unique_sizes, cumul_counts = get_size_dist(counts, sizes) global iter_size_dist iter_size_dist = {'unique_sizes' : unique_sizes, 'unique_counts' : unique_counts, 'cumul_counts' : cumul_counts} metrics.store_metric(num_qubits, unique_id, None, iter_size_dist) # Compute and the other metrics (eg. cvar, gibbs and max N % if the obj function was set to approx ratio) for s in non_objFunc_ratios: dict_of_vals[s] = function_mapper[s](counts, sizes, alpha = alpha) # Store the ratios dict_of_ratios = { key : -1 * val / opt for (key, val) in dict_of_vals.items()} dict_of_ratios['gibbs_ratio'] = dict_of_ratios['gibbs_ratio'] / eta metrics.store_metric(num_qubits, unique_id, None, dict_of_ratios) # Get the best measurement and store it best = - compute_best_cut_from_measured(counts, sizes) metrics.store_metric(num_qubits, unique_id, 'bestcut_ratio', best / opt) # Also compute and store the weights of cuts at three quantile values quantile_sizes = compute_quartiles(counts, sizes) # Store quantile_optgaps as a list (allows storing in json files) metrics.store_metric(num_qubits, unique_id, 'quantile_optgaps', (1 - quantile_sizes / opt).tolist()) # Also store the cuts, counts and sizes in a global variable, to allow access elsewhere global iter_dist iter_dist = {'cuts' : cuts, 'counts' : counts, 'sizes' : sizes} minimizer_loop_index += 1 #************************************************ if comfort: if minimizer_loop_index == 1: print("") print(".", end ="") # reset timer for optimizer execution after each iteration of quantum program completes opt_ts = time.time() return dict_of_vals[objective_func_type] # after first execution and thereafter, no need for transpilation if parameterized # DEVNOTE: this appears to NOT be needed, as we can turn these off after def callback(xk): if parameterized: ex.set_tranpilation_flags(do_transpile_metrics=False, do_transpile_for_execute=False) opt_ts = time.time() # perform the complete algorithm; minimizer invokes 'expectation' function iteratively ##res = minimize(expectation, thetas_array, method='COBYLA', options = { 'maxiter': max_iter}, callback=callback) res = minimize(expectation, thetas_array, method='COBYLA', options = { 'maxiter': max_iter}) # To-do: Set bounds for the minimizer unique_id = restart_ind * 1000 + 0 metrics.store_metric(num_qubits, unique_id, 'opt_exec_time', time.time()-opt_ts) if comfort: print("") # Save final iteration data to metrics.circuit_metrics_final_iter # This data includes final counts, cuts, etc. store_final_iter_to_metrics_json(num_qubits=num_qubits, degree=degree, restart_ind=restart_ind, num_shots=num_shots, converged_thetas_list=res.x.tolist(), opt=opt, iter_size_dist=iter_size_dist, iter_dist=iter_dist, parent_folder_save=parent_folder_save, dict_of_inputs=dict_of_inputs, save_final_counts=save_final_counts, save_res_to_file=save_res_to_file, _instances=_instances) # for method 2, need to aggregate the detail metrics appropriately for each group # Note that this assumes that all iterations of the circuit have completed by this point if method == 2: metrics.process_circuit_metrics_2_level(num_qubits) metrics.finalize_group(str(num_qubits)) # Wait for some active circuits to complete; report metrics when groups 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) ########## global print_sample_circuit if print_sample_circuit: # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") #if method == 1: print("\nQuantum Oracle 'Uf' ="); print(Uf_ if Uf_ != None else " ... too large!") # Plot metrics for all circuit sizes if method == 1: metrics.plot_metrics(f"Benchmark Results - {benchmark_name} ({method}) - QSim", options=dict(shots=num_shots,rounds=rounds)) elif method == 2: #metrics.print_all_circuit_metrics() if plot_results: plot_results_from_data(**dict_of_inputs) # ****************************** def plot_results_from_data(num_shots=100, rounds=1, degree=3, max_iter=30, max_circuits = 1, objective_func_type='approx_ratio', method=2, use_fixed_angles=False, score_metric='fidelity', x_metric='cumulative_exec_time', y_metric='num_qubits', fixed_metrics={}, num_x_bins=15, y_size=None, x_size=None, x_min=None, x_max=None, offset_flag=False, # default is False for QAOA detailed_save_names=False, **kwargs): """ Plot results """ if detailed_save_names: # If detailed names are desired for saving plots, put date of creation, etc. cur_time=datetime.datetime.now() dt = cur_time.strftime("%Y-%m-%d_%H-%M-%S") short_obj_func_str = metrics.score_label_save_str[objective_func_type] suffix = f'-s{num_shots}_r{rounds}_d{degree}_mi{max_iter}_of-{short_obj_func_str}_{dt}' #of=objective function else: short_obj_func_str = metrics.score_label_save_str[objective_func_type] suffix = f'of-{short_obj_func_str}' #of=objective function obj_str = metrics.known_score_labels[objective_func_type] options = {'shots' : num_shots, 'rounds' : rounds, 'degree' : degree, 'restarts' : max_circuits, 'fixed_angles' : use_fixed_angles, '\nObjective Function' : obj_str} suptitle = f"Benchmark Results - MaxCut ({method}) - QSim" metrics.plot_all_area_metrics(f"Benchmark Results - MaxCut ({method}) - QSim", score_metric=score_metric, x_metric=x_metric, y_metric=y_metric, fixed_metrics=fixed_metrics, num_x_bins=num_x_bins, x_size=x_size, y_size=y_size, x_min=x_min, x_max=x_max, offset_flag=offset_flag, options=options, suffix=suffix) metrics.plot_metrics_optgaps(suptitle, options=options, suffix=suffix, objective_func_type = objective_func_type) # this plot is deemed less useful #metrics.plot_ECDF(suptitle=suptitle, options=options, suffix=suffix) all_widths = list(metrics.circuit_metrics_final_iter.keys()) all_widths = [int(ii) for ii in all_widths] list_of_widths = [all_widths[-1]] metrics.plot_cutsize_distribution(suptitle=suptitle,options=options, suffix=suffix, list_of_widths = list_of_widths) metrics.plot_angles_polar(suptitle = suptitle, options = options, suffix = suffix) # if main, execute method 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/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
# parameterized execution algorithm example from qiskit import Aer, QuantumCircuit, transpile from qiskit.circuit import ParameterVector from qiskit.visualization import plot_histogram # Set to true for more text output detailing execution steps VERBOSE = True # set target backend and number of shots BACKEND = Aer.get_backend("qasm_simulator") NUM_SHOTS = 1000 # Fake function to update parameters based on the measurement results def update_params_from_measurement_results(thetas_array, result): """Update theta parameters with max count value divided by NUM_SHOTS.""" update = 0.1 * max(result.values()) / NUM_SHOTS return list(map(lambda theta: round(theta+update, 3), thetas_array)) # create initial set of 3 'theta' parameters thetas = [1.0, 2.0, 3.0] len_thetas = len(thetas) params = ParameterVector("θ", len_thetas) # create quantum circuit with these parameters as arguments to the gates qc = QuantumCircuit(len_thetas) for qidx, param in enumerate(params): qc.rx(param, qidx) qc.measure_all() if VERBOSE: print(qc.draw(output='text', fold=-1)) # execute this circuit ten times (and solve all the world's energy problems!) energy_value = 0 for rep in range(0, 10): # first time, do transpile to backend if rep == 0: if VERBOSE: print("\nTranspiling circuit") qc_trans = transpile(qc, BACKEND) # bind parameters to the saved and already transpiled circuit if VERBOSE: print(f"\nBinding {thetas = } to qc_exec") qc_exec = qc_trans.bind_parameters({params: thetas}) # execute this transpiled and bound circuit on the backend job = BACKEND.run(qc_exec, shots=NUM_SHOTS) # get results from completed joband counts = job.result().get_counts() # Plot a histogram plot_histogram(counts) if VERBOSE: print(f'{counts = }\nwith {thetas = }') # compute new params from the original ones and the measurement results obtained # NOTE: this is highly app-specific as in VQE/QAOA cost function calcs # Kludgy mimic: Do not update thetas on last iteration as circuit will not be ran again if rep != 9: thetas = update_params_from_measurement_results(thetas, counts) # Example of energy_value update function, actual calculation is problem specific energy_value += min(counts.values()) print(f'\n----------------------') print(f'Final {energy_value = }') print(f'Final {counts = }\nwith {thetas = }') # Uncomment below to visualize results from qiskit.visualization import plot_histogram import matplotlib.pyplot as plt plot_histogram(counts) plt.show()
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
import maxcut_benchmark import auxiliary_functions as aux_fun import execute execute.set_noise_model(noise_model = None) maxcut_benchmark.verbose = False backend_id = "qasm_simulator" hub = "ibm-q" group = "open" project = "main" provider_backend = None exec_options = None num_qubits = 4 num_shots = 1000 restarts = 10 rounds = 2 degree = 3 max_circuits = 1 objective_func_type = 'approx_ratio' score_metric = [objective_func_type] # , 'fidelity' x_metric = ['cumulative_exec_time'] maxcut_benchmark.print_sample_circuit = False maxcut_benchmark.run(min_qubits=num_qubits, max_qubits=num_qubits, max_circuits=restarts, num_shots=num_shots, method=2, rounds=rounds, degree=degree, alpha=0.1, N=10, parameterized=False, score_metric=score_metric, x_metric=x_metric, num_x_bins=15, max_iter=30, backend_id=backend_id, provider_backend=provider_backend, hub=hub, group=group, project=project, exec_options=exec_options, objective_func_type=objective_func_type, do_fidelities=True, save_res_to_file=False, save_final_counts=False, plot_results=False, detailed_save_names=False) aux_fun.plot_effects_of_initial_conditions() min_qubits = 4 max_qubits = 6 num_shots = 1000 restarts = 25 rounds = 1 degree = 3 objective_func_type = 'approx_ratio' score_metric = [objective_func_type] # , 'fidelity' x_metric = ['cumulative_exec_time'] aux_fun.radar_plot(min_qubits=min_qubits, max_qubits=max_qubits, num_shots=num_shots, restarts=restarts,rounds=rounds, degree=degree) degree = 3 # degree of graph rounds = 2 # number of rounds # Import modules and packages import maxcut_benchmark import time import sys sys.path[1:1] = [ "_common", "_common/qiskit", "maxcut/_common" ] sys.path[1:1] = [ "../../_common", "../../_common/qiskit", "../../maxcut/_common/" ] import common import execute as ex import metrics as metrics import os import numpy as np import json from qiskit import (Aer, execute) import matplotlib.pyplot as plt ex.set_noise_model(None) # Load the fixed angles from angles_regular_graphs.json taken from https://github.com/danlkv/fixed-angle-QAOA with open(os.path.join('..','_common','angles_regular_graphs.json'), 'r') as json_file: fixed_angles_orig = json.load(json_file) #'thetas_array', 'approx_ratio_list', 'num_qubits_list' deg_3_p_2 = fixed_angles_orig[str(degree)][str(rounds)] thetas_list = deg_3_p_2['beta'] + deg_3_p_2['gamma'] # betas are first followed by gammas for ind in range(rounds, rounds * 2): thetas_list[ind] *= 1 def ar_svs(num_qubits = 4, rounds = 2, degree = 3): """ For a given problem (num nodes + degree), obtain the fixed angle approximation ratio using the state vector simulator """ start = time.time() # Retrieve graph edges and optimal solution unique_id = i = 3 # degree instance_filename = os.path.join("..", "_common", common.INSTANCE_DIR, f"mc_{num_qubits:03d}_{i:03d}_000.txt") nodes, edges = common.read_maxcut_instance(instance_filename) opt, _ = common.read_maxcut_solution(instance_filename[:-4]+'.sol') ## Get the approximation ratio from the state vector simulator parameterized = False qc = maxcut_benchmark.MaxCut(num_qubits, i, edges, rounds, thetas_list, parameterized, measured = False) # qc2 = qc.decompose() backend_id='statevector_simulator' sv_backend = Aer.get_backend(backend_id) sv_result = execute(qc, sv_backend).result() # get the probability distribution cuts, counts, sizes = maxcut_benchmark.compute_cutsizes(sv_result, nodes, edges) sv_ar = np.sum([c * s for (c,s) in zip(counts, sizes)]) / opt end = time.time() # print("SVS for width={} took {} mins".format(num_qubits, (end-start)/60)) return sv_ar def ar_qasmSim(num_qubits = 4, rounds = 2, degree = 3, num_shots = 5000): """ For a given problem (num nodes + degree), obtain the fixed angle approximation ratio using the qasm simulator """ start = time.time() # Retrieve graph edges and optimal solution unique_id = i = 3 # degree instance_filename = os.path.join("..", "_common", common.INSTANCE_DIR, f"mc_{num_qubits:03d}_{i:03d}_000.txt") nodes, edges = common.read_maxcut_instance(instance_filename) opt, _ = common.read_maxcut_solution(instance_filename[:-4]+'.sol') ## Get the approximation ratio from qasm_simulator provider_backend=None hub="ibm-q" group="open" project="main" exec_options=None def execution_handler2 (qc, result, num_qubits, s_int, num_shots): # Stores the results to the global saved_result variable global saved_result saved_result = result ex.max_jobs_active = 1 backend_id='qasm_simulator' ex.init_execution(execution_handler2) ex.set_execution_target(backend_id, provider_backend=provider_backend, hub=hub, group=group, project=project, exec_options=exec_options) # submit circuit for execution on target (simulator, cloud simulator, or hardware) qc = maxcut_benchmark.MaxCut(num_qubits, i, edges, rounds, thetas_list, parameterized = False, measured = True) qc2 = qc.decompose() ex.submit_circuit(qc2, num_qubits, unique_id, shots=num_shots) # Must wait for circuit to complete ex.finalize_execution(None, report_end=False) # ex.throttle_execution(metrics.finalize_group) # ex.finalize_execution(None, report_end=False) # print(saved_result) cuts, counts, sizes = maxcut_benchmark.compute_cutsizes(saved_result, nodes, edges) ar = - maxcut_benchmark.compute_sample_mean(counts, sizes) / opt end= time.time() # print("QASM Simulation for width={} took {} mins".format(num_qubits, (end-start)/60)) return ar degree = 3 num_shots = 1000 num_qubits_list = list(range(4,17,2)) svs_list = [0] * len(num_qubits_list) qsm_list = [0] * len(num_qubits_list) for ind, num_qubits in enumerate(num_qubits_list): svs_list[ind] = ar_svs(num_qubits = num_qubits, rounds = rounds, degree = degree) qsm_list[ind] = ar_qasmSim(num_qubits = num_qubits, rounds = rounds, degree = degree, num_shots = num_shots) print("Simulation for size {} done.".format(num_qubits)) maxcut_style = os.path.join(os.path.join('..','..', '_common','maxcut.mplstyle')) with plt.style.context(maxcut_style): fig, axs = plt.subplots(1, 1) suptitle = "Approximation Ratio for Fixed Angle Simulation\n rounds$={}$, degree=${}$ \n".format(rounds, degree) angle_str = "" for ind in range(rounds): angle_str += r"($\beta_{}={:.3f}$,".format(ind + 1, deg_3_p_2['beta'][ind]) angle_str += r" $\gamma_{}={:.3f}$) ".format(ind + 1, deg_3_p_2['gamma'][ind]) + "\n" angle_str = angle_str[:-2] # and add the title to the plot plt.suptitle(suptitle + angle_str) axs.plot(num_qubits_list, svs_list, marker='o', ls = '-', label = f"State Vector Simulation") axs.plot(num_qubits_list, qsm_list, marker='o', ls = '-', label = f"QASM Simulation") axs.axhline(y = deg_3_p_2['AR'], ls = 'dashed', label = f"Performance Guarantee") axs.set_ylabel('Approximation Ratio') axs.set_xlabel('Problem Size') axs.grid() axs.legend() fig.tight_layout() if not os.path.exists("__images"): os.mkdir("__images") plt.savefig(os.path.join("__images", "fixed_angle_ARs.png")) plt.savefig(os.path.join("__images", "fixed_angle_ARs.pdf"))
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
""" Monte Carlo Sampling Benchmark Program via Amplitude Estimation- QSim """ import copy import functools import sys import time import numpy as np from numpy.polynomial.polynomial import Polynomial from numpy.polynomial.polynomial import polyfit from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.circuit.library.standard_gates.ry import RYGate sys.path[1:1] = ["_common", "_common/qsim", "monte-carlo/_common", "quantum-fourier-transform/qsim"] sys.path[1:1] = ["../../_common", "../../_common/qsim", "../../monte-carlo/_common", "../../quantum-fourier-transform/qsim"] import execute as ex import mc_utils as mc_utils import metrics as metrics from qft_benchmark import inv_qft_gate from execute import BenchmarkResult # Benchmark Name benchmark_name = "Monte Carlo Sampling" np.random.seed(0) # default function is f(x) = x^2 f_of_X = functools.partial(mc_utils.power_f, power=2) # default distribution is gaussian distribution p_distribution = mc_utils.gaussian_dist verbose = False # saved circuits and subcircuits for display A_ = None Q_ = None cQ_ = None QC_ = None R_ = None F_ = None QFTI_ = None ############### Circuit Definition def MonteCarloSampling(target_dist, f, num_state_qubits, num_counting_qubits, epsilon=0.05, degree=2, method=2): A_qr = QuantumRegister(num_state_qubits+1) A = QuantumCircuit(A_qr, name=f"A") num_qubits = num_state_qubits + 1 + num_counting_qubits # initialize R and F circuits R_qr = QuantumRegister(num_state_qubits+1) F_qr = QuantumRegister(num_state_qubits+1) R = QuantumCircuit(R_qr, name=f"R") F = QuantumCircuit(F_qr, name=f"F") # method 1 takes in the abitrary function f and arbitrary dist if method == 1: state_prep(R, R_qr, target_dist, num_state_qubits) f_on_objective(F, F_qr, f, epsilon=epsilon, degree=degree) # method 2 chooses to have lower circuit depth by choosing specific f and dist elif method == 2: uniform_prep(R, R_qr, num_state_qubits) square_on_objective(F, F_qr) # append R and F circuits to A A.append(R.to_gate(), A_qr) A.append(F.to_gate(), A_qr) # run AE subroutine given our A composed of R and F qc = AE_Subroutine(num_state_qubits, num_counting_qubits, A, method) # save smaller circuit example for display global QC_, R_, F_ if QC_ == None or num_qubits <= 5: if num_qubits < 9: QC_ = qc if (R_ and F_) == None or num_state_qubits <= 3: if num_state_qubits < 5: R_ = R; F_ = F return qc ############### def f_on_objective(qc, qr, f, epsilon=0.05, degree=2): """ Assume last qubit is the objective. Function f is evaluated on first n-1 qubits """ num_state_qubits = qc.num_qubits - 1 c_star = (2*epsilon)**(1/(degree+1)) f_ = functools.partial(f, num_state_qubits=num_state_qubits) zeta_ = functools.partial(mc_utils.zeta_from_f, func=f_, epsilon=epsilon, degree=degree, c=c_star) x_eval = np.linspace(0.0, 2**(num_state_qubits) - 1, num= degree+1) poly = Polynomial(polyfit(x_eval, zeta_(x_eval), degree)) b_exp = mc_utils.binary_expansion(num_state_qubits, poly) for controls in b_exp.keys(): theta = 2*b_exp[controls] controls = list(controls) if len(controls)==0: qc.ry(-theta, qr[num_state_qubits]) else: # define a MCRY gate: # this does the same thing as qc.mcry, but is clearer in the circuit printing MCRY = RYGate(-theta).control(len(controls)) qc.append(MCRY, [*(qr[i] for i in controls), qr[num_state_qubits]]) def square_on_objective(qc, qr): """ Assume last qubit is the objective. Shifted square wave function: if x is even, f(x) = 0; if x i s odd, f(x) = 1 """ num_state_qubits = qc.num_qubits - 1 for control in range(num_state_qubits): qc.cx(control, num_state_qubits) def state_prep(qc, qr, target_dist, num_state_qubits): """ Use controlled Ry gates to construct the superposition Sum \sqrt{p_i} |i> """ r_probs = mc_utils.region_probs(target_dist, num_state_qubits) regions = r_probs.keys() r_norm = {} for r in regions: num_controls = len(r) - 1 super_key = r[:num_controls] if super_key=='': r_norm[super_key] = 1 elif super_key == '1': r_norm[super_key] = r_probs[super_key] r_norm['0'] = 1-r_probs[super_key] else: try: r_norm[super_key] = r_probs[super_key] except KeyError: r_norm[super_key] = r_norm[super_key[:num_controls-1]] - r_probs[super_key[:num_controls-1] + '1'] norm = r_norm[super_key] p = 0 if norm != 0: p = r_probs[r] / norm theta = 2*np.arcsin(np.sqrt(p)) if r == '1': qc.ry(-theta, num_state_qubits-1) else: controls = [qr[num_state_qubits-1 - i] for i in range(num_controls)] # define a MCRY gate: # this does the same thing as qc.mcry, but is clearer in the circuit printing MCRY = RYGate(-theta).control(num_controls, ctrl_state=r[:-1]) qc.append(MCRY, [*controls, qr[num_state_qubits-1 - num_controls]]) def uniform_prep(qc, qr, num_state_qubits): """ Generates a uniform distribution over all states """ for i in range(num_state_qubits): qc.h(i) def AE_Subroutine(num_state_qubits, num_counting_qubits, A_circuit, method): num_qubits = num_state_qubits + num_counting_qubits qr_state = QuantumRegister(num_state_qubits+1) qr_counting = QuantumRegister(num_counting_qubits) cr = ClassicalRegister(num_counting_qubits) qc = QuantumCircuit(qr_state, qr_counting, cr, name=f"qmc({method})-{num_qubits}-{0}") A = A_circuit cQ, Q = Ctrl_Q(num_state_qubits, A) # save small example subcircuits for visualization global A_, Q_, cQ_, QFTI_ if (cQ_ and Q_) == None or num_state_qubits <= 6: if num_state_qubits < 9: cQ_ = cQ; Q_ = Q if A_ == None or num_state_qubits <= 3: if num_state_qubits < 5: A_ = A if QFTI_ == None or num_counting_qubits <= 3: if num_counting_qubits < 4: QFTI_ = inv_qft_gate(num_counting_qubits) # Prepare state from A, and counting qubits with H transform qc.append(A, qr_state) for i in range(num_counting_qubits): qc.h(qr_counting[i]) repeat = 1 for j in reversed(range(num_counting_qubits)): for _ in range(repeat): qc.append(cQ, [qr_counting[j]] + [qr_state[l] for l in range(num_state_qubits+1)]) repeat *= 2 qc.barrier() # inverse quantum Fourier transform only on counting qubits qc.append(inv_qft_gate(num_counting_qubits), qr_counting) qc.barrier() qc.measure([qr_counting[m] for m in range(num_counting_qubits)], list(range(num_counting_qubits))) return qc ############################### # Construct the grover-like operator and a controlled version of it def Ctrl_Q(num_state_qubits, A_circ): # index n is the objective qubit, and indexes 0 through n-1 are state qubits qc = QuantumCircuit(num_state_qubits+1, name=f"Q") temp_A = copy.copy(A_circ) A_gate = temp_A.to_gate() A_gate_inv = temp_A.inverse().to_gate() ### Each cycle in Q applies in order: -S_chi, A_circ_inverse, S_0, A_circ # -S_chi qc.x(num_state_qubits) qc.z(num_state_qubits) qc.x(num_state_qubits) # A_circ_inverse qc.append(A_gate_inv, [i for i in range(num_state_qubits+1)]) # S_0 for i in range(num_state_qubits+1): qc.x(i) qc.h(num_state_qubits) qc.mcx([x for x in range(num_state_qubits)], num_state_qubits) qc.h(num_state_qubits) for i in range(num_state_qubits+1): qc.x(i) # A_circ qc.append(A_gate, [i for i in range(num_state_qubits+1)]) # Create a gate out of the Q operator qc.to_gate(label='Q') # and also a controlled version of it Ctrl_Q_ = qc.control(1) # and return both return Ctrl_Q_, qc ######################################### # Analyze and print measured results # Expected result is always the secret_int, so fidelity calc is simple def analyze_and_print_result(qc, result, num_counting_qubits, mu, num_shots, method, num_state_qubits): # generate exact value for the expectation value given our function and dist target_dist = p_distribution(num_state_qubits, mu) f = functools.partial(f_of_X, num_state_qubits=num_state_qubits) if method == 1: exact = mc_utils.estimated_value(target_dist, f) elif method == 2: exact = 0.5 # hard coded exact value from uniform dist and square function 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 # calculate the expected output histogram correct_dist = a_to_bitstring(exact, num_counting_qubits) # generate thermal_dist with amplitudes instead, to be comparable to correct_dist thermal_dist = metrics.uniform_dist(num_counting_qubits) # convert counts, expectation, and thermal_dist to app form for visibility # app form of correct distribution is measuring the input a 100% of the time # convert bit_counts into expectation values counts according to Quantum Risk Analysis paper app_counts = expectation_from_bits(probs, num_counting_qubits, num_shots, method) app_correct_dist = mc_utils.mc_dist(num_counting_qubits, exact, c_star, method) app_thermal_dist = expectation_from_bits(thermal_dist, num_counting_qubits, num_shots, method) if verbose: print(f"For expected value {exact}, expected: {correct_dist} measured: {probs}") print(f" ... For expected value {exact} thermal_dist: {thermal_dist}") print(f"For expected value {exact}, app expected: {app_correct_dist} measured: {app_counts}") print(f" ... For expected value {exact} app_thermal_dist: {app_thermal_dist}") # use polarization fidelity with rescaling fidelity = metrics.polarization_fidelity(probs, correct_dist, thermal_dist) #fidelity = metrics.polarization_fidelity(app_counts, app_correct_dist, app_thermal_dist) hf_fidelity = metrics.hellinger_fidelity_with_expected(probs, correct_dist) ########################################################################### # NOTE: in this benchmark, we are testing how well the amplitude estimation routine # works according to theory, and we do not measure the difference between # the reported answer and the correct answer; the below code just helps # demonstrate that we do approximate the expectation value accurately. # the max in the counts is what the algorithm would report as the correct answer a, _ = mc_utils.value_and_max_prob_from_dist(probs) if verbose: print(f"For expected value {exact} measured: {a}") ########################################################################### if verbose: print(f"Solution counts: {probs}") if verbose: print(f" ... fidelity: {fidelity} hf_fidelity: {hf_fidelity}") return probs, fidelity def a_to_bitstring(a, num_counting_qubits): m = num_counting_qubits # solution 1 num1 = round(np.arcsin(np.sqrt(a)) / np.pi * 2**m) num2 = round( (np.pi - np.arcsin(np.sqrt(a))) / np.pi * 2**m) if num1 != num2 and num2 < 2**m and num1 < 2**m: counts = {format(num1, "0"+str(m)+"b"): 0.5, format(num2, "0"+str(m)+"b"): 0.5} else: counts = {format(num1, "0"+str(m)+"b"): 1} return counts def expectation_from_bits(bits, num_qubits, num_shots, method): amplitudes = {} for b in bits.keys(): precision = int(num_qubits / (np.log2(10))) + 2 r = bits[b] a_meas = pow(np.sin(np.pi*int(b,2)/pow(2,num_qubits)),2) if method == 1: a = ((a_meas - 0.5)/c_star) + 0.5 if method == 2: a = a_meas a = round(a, precision) if a not in amplitudes.keys(): amplitudes[a] = 0 amplitudes[a] += r return amplitudes ################ Benchmark Loop MIN_QUBITS = 4 # must be at least MIN_STATE_QUBITS + 3 MIN_STATE_QUBITS = 1 # set minimums for method 1 MIN_QUBITS_M1 = 5 # must be at least MIN_STATE_QUBITS + 3 MIN_STATE_QUBITS_M1 = 2 # Because circuit size grows significantly with num_qubits # limit the max_qubits here ... MAX_QUBITS=10 # Execute program with default parameters def run(min_qubits=MIN_QUBITS, max_qubits=7, skip_qubits=1, max_circuits=1, num_shots=100, epsilon=0.05, degree=2, num_state_qubits=MIN_STATE_QUBITS, method = 2, # default, not exposed to users 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") # Clamp the maximum number of qubits if max_qubits > MAX_QUBITS: print(f"INFO: {benchmark_name} benchmark is limited to a maximum of {MAX_QUBITS} qubits.") max_qubits = MAX_QUBITS if (method == 2): if max_qubits < MIN_QUBITS: print(f"INFO: {benchmark_name} benchmark method ({method}) requires a minimum of {MIN_QUBITS} qubits.") return if min_qubits < MIN_QUBITS: min_qubits = MIN_QUBITS elif (method == 1): if max_qubits < MIN_QUBITS_M1: print(f"INFO: {benchmark_name} benchmark method ({method}) requires a minimum of {MIN_QUBITS_M1} qubits.") return if min_qubits < MIN_QUBITS_M1: min_qubits = MIN_QUBITS_M1 if (method == 1) and (num_state_qubits == MIN_STATE_QUBITS): num_state_qubits = MIN_STATE_QUBITS_M1 skip_qubits = max(1, skip_qubits) ### TODO: need to do more validation of arguments, e.g. min_state_qubits and min_qubits # create context identifier if context is None: context = f"{benchmark_name} ({method}) Benchmark" ########## # Initialize metrics module metrics.init_metrics() global c_star c_star = (2*epsilon)**(1/(degree+1)) # Define custom result handler def execution_handler(qc, result, num_qubits, mu, num_shots): # determine fidelity of result set num_counting_qubits = int(num_qubits) - num_state_qubits -1 counts, fidelity = analyze_and_print_result(qc, result, num_counting_qubits, float(mu), num_shots, method=method, num_state_qubits=num_state_qubits) metrics.store_metric(num_qubits, mu, '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 num_qubits in range(min_qubits, max_qubits + 1, skip_qubits): # reset random seed np.random.seed(0) input_size = num_qubits - 1 # TODO: keep using inputsize? only used in num_circuits # as circuit width grows, the number of counting qubits is increased num_counting_qubits = num_qubits - num_state_qubits - 1 # determine number of circuits to execute for this group num_circuits = min(2 ** (input_size), max_circuits) #print(num_circuits) print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") # determine range of circuits to loop over for method 1 if 2**(input_size) <= max_circuits: mu_range = [i/2**(input_size) for i in range(num_circuits)] else: mu_range = [i/2**(input_size) for i in np.random.choice(2**(input_size), num_circuits, False)] #print(mu_range) # loop over limited # of mu values for this for mu in mu_range: target_dist = p_distribution(num_state_qubits, mu) f_to_estimate = functools.partial(f_of_X, num_state_qubits=num_state_qubits) #print(mu) # create the circuit for given qubit size and secret string, store time metric ts = time.time() qc = MonteCarloSampling(target_dist, f_to_estimate, num_state_qubits, num_counting_qubits, epsilon, degree, method=method).reverse_bits() # reverse_bits() is applying to handle the change in endianness metrics.store_metric(num_qubits, mu, 'create_time', time.time() - ts) # collapse the 4 sub-circuit levels used in this benchmark (for qiskit) qc2 = qc.decompose().decompose().decompose().decompose() # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc2, num_qubits, mu, num_shots) # if method is 2, we only have one type of circuit, so break out of loop #if method == 2: # break # Wait for some active circuits to complete; report metrics when groups 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("\nControlled Quantum Operator 'cQ' ="); print(cQ_ if cQ_ != None else " ... too large!") print("\nQuantum Operator 'Q' ="); print(Q_ if Q_ != None else " ... too large!") print("\nAmplitude Generator 'A' ="); print(A_ if A_ != None else " ... too large!") print("\nDistribution Generator 'R' ="); print(R_ if R_ != None else " ... too large!") print("\nFunction Generator 'F' ="); print(F_ if F_ != None else " ... too large!") print("\nInverse QFT Circuit ="); print(QFTI_ if QFTI_ != None else " ... too large!") # Plot metrics for all circuit sizes metrics.plot_metrics(f"Benchmark Results - {benchmark_name} ({method}) - QSim") # if main, execute method 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/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
from numpy.polynomial.polynomial import Polynomial from numpy.polynomial.polynomial import polyfit import matplotlib.pyplot as plt import numpy as np import copy from qiskit.circuit.library import QFT from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from collections.abc import Iterable def hellinger_fidelity(p, q): p_sum = sum(p.values()) q_sum = sum(q.values()) p_normed = {} for key, val in p.items(): p_normed[key] = val/p_sum 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()) dist = np.sqrt(total)/np.sqrt(2) return 1-dist from numpy.polynomial.polynomial import Polynomial from numpy.polynomial.polynomial import polyfit from collections.abc import Iterable import functools import math import random import numpy as np import copy ########## Classical math functions 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 def power_f(i, num_state_qubits, power): if isinstance(i, Iterable): out = [] for val in i: out.append((val / ((2**num_state_qubits) - 1))**power) return np.array(out) else: return (i / ((2**num_state_qubits) - 1))**power def estimated_value(target_dist, f): avg = 0 for key in target_dist.keys(): x = int(key,2) avg += target_dist[key]*f(x) return avg def zeta_from_f(i, func, epsilon, degree, c): """ Intermediate polynomial derived from f to serve as angle for controlled Ry gates. """ rad = np.sqrt(c*(func(i) - 0.5) + 0.5) return np.arcsin(rad) def simplex(n, k): """ Get all ordered combinations of n integers (zero inclusive) which add up to k; the n-dimensional k simplex. """ if k == 0: z = [0]*n return [z] l = [] for p in simplex(n,k-1): for i in range(n): a = p[i]+1 ns = copy.copy(p) ns[i] = a if ns not in l: l.append(ns) return l def binary_expansion(num_state_qubits, poly): """ Convert a polynomial into expression replacing x with its binary decomposition x_0 + 2 x_1 + 4 x_2 + ... Simplify using (x_i)^p = x_i for all integer p > 0 and collect coefficients of equivalent expression """ n = num_state_qubits if isinstance(poly, Polynomial): poly_c = poly.coef else: poly_c = poly out_front = {} out_front[()] = poly_c[0] for k in range(1,len(poly_c)): for pow_list in simplex(n,k): two_exp, denom, t = 0, 1, 0 for power in pow_list: two_exp += t*power denom *= np.math.factorial(power) t+=1 nz = np.nonzero(pow_list)[0] key = tuple(nz) if key not in out_front.keys(): out_front[key] = 0 out_front[key] += poly_c[k]*((np.math.factorial(k) / denom) * (2**(two_exp))) return out_front def starting_regions(num_state_qubits): """ For use in bisection search for state preparation subroutine. Fill out the necessary region labels for num_state_qubits. """ sub_regions = [] sub_regions.append(['1']) for d in range(1,num_state_qubits): region = [] for i in range(2**d): key = bin(i)[2:].zfill(d) + '1' region.append(key) sub_regions.append(region) return sub_regions def region_probs(target_dist, num_state_qubits): """ Fetch bisected region probabilities for the desired probability distribution {[p1], [p01, p11], [p001, p011, p101, p111], ...}. """ regions = starting_regions(num_state_qubits) probs = {} n = len(regions) for k in range(n): for string in regions[k]: p = 0 b = n-k-1 for i in range(2**b): subkey = bin(i)[2:].zfill(b) if b == 0: subkey = '' try: p += target_dist[string+subkey] except KeyError: pass probs[string] = p return probs %run mc_benchmark.py def arcsin_approx(f, x, epsilon, degree, c_star): zeta_ = functools.partial(zeta_from_f, func=f_, epsilon=epsilon, degree=degree, c=c_star) poly = Polynomial(polyfit(x, zeta_(x), degree)) return poly num_state_qubits_=2 epsilon_=0.05 degree_= 3 power = 2 c_star_ = (2*epsilon_)**(1/(degree_+1)) x_plot = np.linspace(0.0, 2**(num_state_qubits_) - 1, num=100) x_eval = np.linspace(0.0, 2**(num_state_qubits_) - 1, num= degree_+1) f_ = functools.partial(power_f, num_state_qubits=num_state_qubits_, power=power) poly_ = arcsin_approx(f_, x_eval, epsilon_, degree_, c_star_) def corrected_amplitudes(x): #return poly_(x) #return (np.sin(poly_(x))**2) return (((np.sin(poly_(x))**2) - 0.5) / c_star_) + 0.5 ######## plt.plot(x_plot, f_(x_plot), label="f") plt.plot(x_plot, corrected_amplitudes(x_plot), label=f"degree={degree_}") # Test coefficient list in the increasing degree; i.e. [a, b, c, ... {z}] for a + b x + c x^2 ... {z} x^n num_q = 2 coef_list = [3, 1, 1] poly = Polynomial(coef_list) print(poly.coef) print(binary_expansion(num_q, poly)) num_q = 3 t_d = {'101': 0, '000': 0.25, '011': 0.125, '100': 0.125, '001': 0.0, '010': 0.25, '110': 0.125, '111': 0.125} u_d = uniform_dist(num_q) m_d = {'000': 0.5, '001': 0.25, '010':0.25} # Change to whatever distribution you like dist = m_d qr_ = QuantumRegister(num_q) cr_ = ClassicalRegister(num_q) qc_ = QuantumCircuit(qr_, cr_) state_prep(qc_, qr_, dist, num_state_qubits=num_q) qc_.measure(qr_, cr_) from qiskit import execute, BasicAer backend = BasicAer.get_backend("dm_simulator") job = execute(qc_, backend, shots=1000) result = job.result() counts = result.get_counts() print('') print(dist) print(counts) print(hellinger_fidelity(dist,counts)) def state_prep(qc, qr, target_dist, num_state_qubits): """ Use controlled Ry gates to construct the superposition Sum \sqrt{p_i} |i> """ r_probs = region_probs(target_dist, num_state_qubits) regions = r_probs.keys() r_norm = {} for r in regions: num_controls = len(r) - 1 super_key = r[:num_controls] if super_key=='': r_norm[super_key] = 1 elif super_key == '1': r_norm[super_key] = r_probs[super_key] r_norm['0'] = 1-r_probs[super_key] else: try: r_norm[super_key] = r_probs[super_key] except KeyError: r_norm[super_key] = r_norm[super_key[:num_controls-1]] - r_probs[super_key[:num_controls-1] + '1'] norm = r_norm[super_key] p = 0 if norm != 0: p = r_probs[r] / norm theta = -2*np.arcsin(np.sqrt(p)) if r == '1': qc.ry(theta, num_state_qubits-1) else: for k in range(num_controls): if r[k] == '0': qc.x(num_state_qubits-1 - k) controls = [qr[num_state_qubits-1 - i] for i in range(num_controls)] qc.mcry(theta, controls, qr[num_state_qubits-1 - num_controls], q_ancillae=None) for k in range(num_controls): if r[k] == '0': qc.x(num_state_qubits-1 - k) def f_on_objective(qc, qr, f, epsilon=0.05, degree=3): """ Assume last qubit is the objective. Function f is evaluated on first n-1 qubits """ num_state_qubits = qc.num_qubits - 1 c_star = (2*epsilon)**(1/(degree+1)) f_ = functools.partial(f, num_state_qubits=num_state_qubits) zeta_ = functools.partial(zeta_from_f, func=f_, epsilon=epsilon, degree=degree, c=c_star) x_eval = np.linspace(0.0, 2**(num_state_qubits) - 1, num= degree+1) poly = Polynomial(polyfit(x_eval, zeta_(x_eval), degree)) b_exp = binary_expansion(num_state_qubits, poly) for controls in b_exp.keys(): theta = 2*b_exp[controls] controls = list(controls) if len(controls)==0: qc.ry(-theta, qr[num_state_qubits]) else: qc.mcry(-theta, [qr[i] for i in controls], qr[num_state_qubits], q_ancillae=None) from qiskit import execute, BasicAer backend = Aer.get_backend("dm_simulator") num_state_qubits_=4 epsilon_ = 0.05 degree_= 3 power = 1 c_star_ = (2*epsilon_)**(1/(degree_+1)) f_ = functools.partial(power_f, power=power) x_vals = list(range(2**num_state_qubits_)) y_vals = [] f_vals = f_(x_vals, num_state_qubits_) for i in x_vals: qr_ = QuantumRegister(num_state_qubits_+1) cr_ = ClassicalRegister(num_state_qubits_+1) qc_ = QuantumCircuit(qr_, cr_) b = bin(i)[2:].zfill(num_state_qubits_)[::-1] for q in range(len(b)): if b[q]=='1': qc_.x(q) f_on_objective(qc_, qr_, f_, epsilon_, degree_) qc_.measure(qr_, cr_) job = execute(qc_, backend, shots=1000) result = job.result() counts = result.get_counts() print(counts) try: print(i, '', b, '', counts['1'+b[::-1]]/1000) y_vals.append(counts['1'+b[::-1]]/1000) except KeyError: print(i, '', b, '', 0) y_vals.append(0) y_corrected = [] for y in y_vals: y_corrected.append(((y - 0.5) / c_star_) + 0.5) #plt.plot(x_vals, y_vals) plt.plot(x_vals, y_corrected) plt.plot(x_vals, f_vals) print('') plt.show() dist = u_d print(u_d) num_state_qubits_= 3 num_ancillas = 6 epsilon_=0.05 degree_= 2 power = 2 c_star_ = (2*epsilon_)**(1/(degree_+1)) p = uniform_dist dist = p(num_state_qubits_) f_ = functools.partial(power_f, power=power) qc_ = MonteCarloSampling(dist, f_, num_state_qubits_, num_ancillas, epsilon_, degree_) backend = Aer.get_backend("dm_simulator") job = execute(qc_, backend, shots=1000) result = job.result() counts = result.get_counts(qc_) v_string = max(counts, key=counts.get) v = int(v_string,2) #print(v, v_string) a = pow(np.sin(np.pi*v/pow(2,num_ancillas)),2) a_est = ((a - 0.5)/c_star_) + 0.5 a_exact = actual_(dist, f_, num_state_qubits_) print(a_est, a_exact) best_result = max(counts, key=counts.get) v = int(best_result,2) print(v, best_result) #a_ = pow(np.cos(2*np.pi*v/pow(2,num_ancillas)),2) #a_est = a_ best_result = max(counts, key=counts.get) v = int(best_result,2) a_int = pow(np.sin(np.pi*v/pow(2,num_ancillas)),2) a_est = ((a_int - 0.5) / c_star_) + 0.5 a_exact = actual_(dist,f_,num_state_qubits_) a_ex = ((a_exact - 0.5) * c_star_) + 0.5 print(a_est, a_exact) print(a_int, a_ex) print(counts) def actual_(dist, f_, num_state_qubits): s = 0 _f = functools.partial(f_, num_state_qubits=num_state_qubits) for key in dist.keys(): x = int(key,2) s += dist[key]*_f(x) return s def MonteCarloSampling(target_dist, f, num_state_qubits, num_ancillas, epsilon=0.05, degree=2): A_qr = QuantumRegister(num_state_qubits+1) A = QuantumCircuit(A_qr) state_prep(A, A_qr, target_dist, num_state_qubits) f_on_objective(A, A_qr, f, epsilon=epsilon, degree=degree) qc = AE_Subroutine(num_state_qubits, num_ancillas, A) return qc # Construct the grover-like operator and a controlled version of it def Ctrl_Q(num_state_qubits, A_circ): # index n is the objective qubit, and indexes 0 through n-1 are state qubits qc = QuantumCircuit(num_state_qubits+1, name=f"Q") temp_A = copy.copy(A_circ) A_gate = temp_A.to_gate() A_gate_inv = temp_A.inverse().to_gate() ### Each cycle in Q applies in order: -S_chi, A_circ_inverse, S_0, A_circ # -S_chi qc.x(num_state_qubits) qc.z(num_state_qubits) qc.x(num_state_qubits) # A_circ_inverse qc.append(A_gate_inv, [i for i in range(num_state_qubits+1)]) # S_0 for i in range(num_state_qubits+1): qc.x(i) qc.h(num_state_qubits) qc.mcx([x for x in range(num_state_qubits)], num_state_qubits) qc.h(num_state_qubits) for i in range(num_state_qubits+1): qc.x(i) # A_circ qc.append(A_gate, [i for i in range(num_state_qubits+1)]) # Create a gate out of the Q operator qc.to_gate(label='Q') # and also a controlled version of it Ctrl_Q_ = qc.control(1) # and return both return Ctrl_Q_, qc def AE_Subroutine(num_state_qubits, num_ancillas, A_circuit): ctr, unctr = Ctrl_Q(num_state_qubits, A_circuit) qr_state = QuantumRegister(num_state_qubits+1) qr_ancilla = QuantumRegister(num_ancillas) cr = ClassicalRegister(num_ancillas) qc_full = QuantumCircuit(qr_ancilla, qr_state, cr) qc_full.append(A_circuit, [qr_state[i] for i in range(num_state_qubits+1)]) repeat = 1 for j in range(num_ancillas): qc_full.h(qr_ancilla[j]) for k in range(repeat): qc_full.append(ctr, [qr_ancilla[j]] + [qr_state[l] for l in range(num_state_qubits+1)]) repeat *= 2 qc_full.barrier() qc_full.append(QFT(num_qubits=num_ancillas, inverse=True), qr_ancilla) qc_full.barrier() qc_full.measure([qr_ancilla[m] for m in range(num_ancillas)], list(range(num_ancillas))) return qc_full
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
""" Phase Estimation Benchmark Program - QSim """ import sys import time import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister sys.path[1:1] = ["_common", "_common/qsim", "quantum-fourier-transform/qsim"] sys.path[1:1] = ["../../_common", "../../_common/qsim", "../../quantum-fourier-transform/qsim"] import execute as ex import metrics as metrics from qft_benchmark import inv_qft_gate from execute import BenchmarkResult # Benchmark Name benchmark_name = "Phase Estimation" np.random.seed(0) verbose = False # saved subcircuits circuits for printing QC_ = None QFTI_ = None U_ = None ############### Circuit Definition def PhaseEstimation(num_qubits, theta): qr = QuantumRegister(num_qubits) num_counting_qubits = num_qubits - 1 # only 1 state qubit cr = ClassicalRegister(num_counting_qubits) qc = QuantumCircuit(qr, cr, name=f"qpe-{num_qubits}-{theta}") # initialize counting qubits in superposition for i in range(num_counting_qubits): qc.h(qr[i]) # change to |1> in state qubit, so phase will be applied by cphase gate qc.x(num_counting_qubits) qc.barrier() repeat = 1 for j in reversed(range(num_counting_qubits)): # controlled operation: adds phase exp(i*2*pi*theta*repeat) to the state |1> # does nothing to state |0> cp, _ = CPhase(2*np.pi*theta, repeat) qc.append(cp, [j, num_counting_qubits]) repeat *= 2 #Define global U operator as the phase operator _, U = CPhase(2*np.pi*theta, 1) qc.barrier() # inverse quantum Fourier transform only on counting qubits qc.append(inv_qft_gate(num_counting_qubits), qr[:num_counting_qubits]) qc.barrier() # measure counting qubits qc.measure([qr[m] for m in range(num_counting_qubits)], list(range(num_counting_qubits))) # save smaller circuit example for display global QC_, U_, QFTI_ if QC_ == None or num_qubits <= 5: if num_qubits < 9: QC_ = qc if U_ == None or num_qubits <= 5: if num_qubits < 9: U_ = U if QFTI_ == None or num_qubits <= 5: if num_qubits < 9: QFTI_ = inv_qft_gate(num_counting_qubits) return qc #Construct the phase gates and include matching gate representation as readme circuit def CPhase(angle, exponent): qc = QuantumCircuit(1, name=f"U^{exponent}") qc.p(angle*exponent, 0) phase_gate = qc.to_gate().control(1) return phase_gate, qc # Analyze and print measured results # Expected result is always theta, so fidelity calc is simple def analyze_and_print_result(qc, result, num_counting_qubits, theta, num_shots): 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 counts = probs # calculate expected output histogram correct_dist = theta_to_bitstring(theta, num_counting_qubits) # generate thermal_dist to be comparable to correct_dist thermal_dist = metrics.uniform_dist(num_counting_qubits) # convert counts, expectation, and thermal_dist to app form for visibility # app form of correct distribution is measuring theta correctly 100% of the time app_counts = bitstring_to_theta(counts, num_counting_qubits) app_correct_dist = {theta: 1.0} app_thermal_dist = bitstring_to_theta(thermal_dist, num_counting_qubits) if verbose: print(f"For theta {theta}, expected: {correct_dist} measured: {counts}") print(f" ... For theta {theta} thermal_dist: {thermal_dist}") print(f"For theta {theta}, app expected: {app_correct_dist} measured: {app_counts}") print(f" ... For theta {theta} app_thermal_dist: {app_thermal_dist}") # use polarization fidelity with rescaling fidelity = metrics.polarization_fidelity(counts, correct_dist, thermal_dist) # use polarization fidelity with rescaling fidelity = metrics.polarization_fidelity(counts, correct_dist, thermal_dist) #fidelity = metrics.polarization_fidelity(app_counts, app_correct_dist, app_thermal_dist) hf_fidelity = metrics.hellinger_fidelity_with_expected(counts, correct_dist) if verbose: print(f" ... fidelity: {fidelity} hf_fidelity: {hf_fidelity}") return counts, fidelity # Convert theta to a bitstring distribution def theta_to_bitstring(theta, num_counting_qubits): counts = {format( int(theta * (2**num_counting_qubits)), "0"+str(num_counting_qubits)+"b"): 1.0} return counts # Convert bitstring to theta representation, useful for debugging def bitstring_to_theta(counts, num_counting_qubits): theta_counts = {} for key in counts.keys(): r = counts[key] theta = int(key,2) / (2**num_counting_qubits) if theta not in theta_counts.keys(): theta_counts[theta] = 0 theta_counts[theta] += r return theta_counts ################ Benchmark Loop # Execute program with default parameters def run(min_qubits=3, max_qubits=8, skip_qubits=1, max_circuits=3, num_shots=100, backend_id='dm_simulator', provider_backend=None, #hub="ibm-q", group="open", project="main", exec_options=None, context=None): print(f"{benchmark_name} Benchmark Program - QSim") num_state_qubits = 1 # default, not exposed to users, cannot be changed in current implementation # validate parameters (smallest circuit is 3 qubits) num_state_qubits = max(1, num_state_qubits) if max_qubits < num_state_qubits + 2: print(f"ERROR: PE Benchmark needs at least {num_state_qubits + 2} qubits to run") return min_qubits = max(max(3, min_qubits), num_state_qubits + 2) skip_qubits = max(1, skip_qubits) #print(f"min, max, state = {min_qubits} {max_qubits} {num_state_qubits}") # create context identifier if context is None: context = f"{benchmark_name} Benchmark" ########## # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler(qc, result, num_qubits, theta, num_shots): # determine fidelity of result set num_counting_qubits = int(num_qubits) - 1 counts, fidelity = analyze_and_print_result(qc, result, num_counting_qubits, float(theta), num_shots) metrics.store_metric(num_qubits, theta, '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 num_qubits in range(min_qubits, max_qubits + 1, skip_qubits): # reset random seed np.random.seed(0) # as circuit width grows, the number of counting qubits is increased num_counting_qubits = num_qubits - num_state_qubits - 1 # determine number of circuits to execute for this group num_circuits = min(2 ** (num_counting_qubits), max_circuits) print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") # determine range of secret strings to loop over if 2**(num_counting_qubits) <= max_circuits: theta_range = [i/(2**(num_counting_qubits)) for i in list(range(num_circuits))] else: theta_range = [i/(2**(num_counting_qubits)) for i in np.random.choice(2**(num_counting_qubits), num_circuits, False)] # loop over limited # of random theta choices for theta in theta_range: # create the circuit for given qubit size and theta, store time metric ts = time.time() qc = PhaseEstimation(num_qubits, theta).reverse_bits() # to change the endianness metrics.store_metric(num_qubits, theta, 'create_time', time.time() - ts) # collapse the 3 sub-circuit levels used in this benchmark (for qiskit) qc2 = qc.decompose().decompose().decompose() # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc2, num_qubits, theta, num_shots) # Wait for some active circuits to complete; report metrics when groups 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("\nPhase Operator 'U' = "); print(U_ if U_ != None else " ... too large!") print("\nInverse QFT Circuit ="); print(QFTI_ if QFTI_ != None else " ... too large!") # Plot metrics for all circuit sizes metrics.plot_metrics(f"Benchmark Results - {benchmark_name} - QSim") # if main, execute method 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/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
""" Quantum Fourier Transform Benchmark Program - QSim """ import math import sys import time import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.circuit.library import QFT 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 = "Quantum Fourier Transform" np.random.seed(0) verbose = False # saved circuits for display num_gates = 0 depth = 0 QC_ = None QFT_ = None QFTI_ = None ############### Circuit Definition def QuantumFourierTransform (num_qubits, secret_int, method=1): global num_gates, depth # Size of input is one less than available qubits input_size = num_qubits num_gates = 0 depth = 0 # allocate qubits qr = QuantumRegister(num_qubits); cr = ClassicalRegister(num_qubits); qc = QuantumCircuit(qr, cr, name=f"qft({method})-{num_qubits}-{secret_int}") if method==1: # Perform X on each qubit that matches a bit in the secret string s = ('{0:0'+str(input_size)+'b}').format(secret_int) for i_qubit in range(input_size): if s[input_size-1-i_qubit]=='1': qc.x(qr[i_qubit]) num_gates += 1 depth += 1 qc.barrier() # perform QFT on the input qc.append(qft_gate(input_size).to_instruction(), qr) # End with Hadamard on all qubits (to measure the z rotations) ''' don't do this unless NOT doing the inverse afterwards for i_qubit in range(input_size): qc.h(qr[i_qubit]) qc.barrier() ''' qc.barrier() # some compilers recognize the QFT and IQFT in series and collapse them to identity; # perform a set of rotations to add one to the secret_int to avoid this collapse for i_q in range(0, num_qubits): divisor = 2 ** (i_q) qc.rz( 1 * math.pi / divisor , qr[i_q]) num_gates+=1 qc.barrier() # to revert back to initial state, apply inverse QFT qc.append(inv_qft_gate(input_size).to_instruction(), qr) qc.barrier() elif method == 2: for i_q in range(0, num_qubits): qc.h(qr[i_q]) num_gates += 1 for i_q in range(0, num_qubits): divisor = 2 ** (i_q) qc.rz(secret_int * math.pi / divisor, qr[i_q]) num_gates += 1 depth += 1 qc.append(inv_qft_gate(input_size).to_instruction(), qr) # This method is a work in progress elif method==3: for i_q in range(0, secret_int): qc.h(qr[i_q]) num_gates+=1 for i_q in range(secret_int, num_qubits): qc.x(qr[i_q]) num_gates+=1 depth += 1 qc.append(inv_qft_gate(input_size).to_instruction(), qr) else: exit("Invalid QFT method") # measure all qubits qc.measure(qr, cr) # to get the partial_probability # qc.measure(qr, cr, basis='Ensemble', add_param='Z') # to get the ensemble_probability # However, Qiskit's measure method might not directly support the 'Ensemble' basis with 'Z' parameter. # The basis parameter is typically used for different bases such as 'X', 'Y', or 'Z', but 'Ensemble' might not be directly supported. num_gates += num_qubits depth += 1 # save smaller circuit example for display global QC_ if QC_ == None or num_qubits <= 5: if num_qubits < 9: QC_ = qc # return a handle on the circuit return qc ############### QFT Circuit def qft_gate(input_size): global QFT_, num_gates, depth qr = QuantumRegister(input_size); qc = QuantumCircuit(qr, name="qft") # Generate multiple groups of diminishing angle CRZs and H gate for i_qubit in range(0, input_size): # start laying out gates from highest order qubit (the hidx) hidx = input_size - i_qubit - 1 # if not the highest order qubit, add multiple controlled RZs of decreasing angle if hidx < input_size - 1: num_crzs = i_qubit for j in range(0, num_crzs): divisor = 2 ** (num_crzs - j) qc.crz( math.pi / divisor , qr[hidx], qr[input_size - j - 1]) num_gates += 1 depth += 1 # followed by an H gate (applied to all qubits) qc.h(qr[hidx]) num_gates += 1 depth += 1 qc.barrier() if QFT_ == None or input_size <= 8: if input_size < 9: QFT_ = qc return qc ############### Inverse QFT Circuit def inv_qft_gate(input_size): global QFTI_, num_gates, depth qr = QuantumRegister(input_size); qc = QuantumCircuit(qr, name="inv_qft") # Generate multiple groups of diminishing angle CRZs and H gate for i_qubit in reversed(range(0, input_size)): # start laying out gates from highest order qubit (the hidx) hidx = input_size - i_qubit - 1 # precede with an H gate (applied to all qubits) qc.h(qr[hidx]) num_gates += 1 depth += 1 # if not the highest order qubit, add multiple controlled RZs of decreasing angle if hidx < input_size - 1: num_crzs = i_qubit for j in reversed(range(0, num_crzs)): divisor = 2 ** (num_crzs - j) qc.crz( -math.pi / divisor , qr[hidx], qr[input_size - j - 1]) num_gates += 1 depth += 1 qc.barrier() if QFTI_ == None or input_size <= 8: if input_size < 9: QFTI_= qc return qc # Define expected distribution calculated from applying the iqft to the prepared secret_int state def expected_dist(num_qubits, secret_int, counts): dist = {} s = num_qubits - secret_int for key in counts.keys(): if key[(num_qubits-secret_int):] == ''.zfill(secret_int): dist[key] = 1/(2**s) return dist ############### Result Data Analysis # Analyze and print measured results def analyze_and_print_result (qc, result, num_qubits, secret_int, num_shots, method): # obtain probs from the result object 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 # For method 1, expected result is always the secret_int if method==1: # add one to the secret_int to compensate for the extra rotations done between QFT and IQFT secret_int_plus_one = (secret_int + 1) % (2 ** num_qubits) # print("secret_int_plus_one =====", secret_int_plus_one) # create the key that is expected to have all the measurements (for this circuit) key = format(secret_int_plus_one, f"0{num_qubits}b") # format is in big-endian since it was for counts # print(f"keys ===== {key}") # correct distribution is measuring the key 100% of the time correct_dist = {key: 1.0} # For method 2, expected result is always the secret_int elif method==2: # create the key that is expected to have all the measurements (for this circuit) key = format(secret_int, f"0{num_qubits}b") # correct distribution is measuring the key 100% of the time correct_dist = {key: 1.0} # For method 3, correct_dist is a distribution with more than one value elif method==3: # correct_dist is from the expected dist correct_dist = expected_dist(num_qubits, secret_int, probs) # print(f"\ncorrect_dist ===== {correct_dist}") # print(f"\nsecret_int ====== {secret_int} ") # use our polarization fidelity rescaling fidelity = metrics.polarization_fidelity(probs, correct_dist) if verbose: print(f"For secret int {secret_int} measured: {probs} fidelity: {fidelity}") print(f"Fidelity :::::::: {fidelity}") return probs, fidelity ################ Benchmark Loop # Execute program with default parameters (try for both with and without noise by changing in execute.py) def run (min_qubits = 2, max_qubits = 8, max_circuits = 3, skip_qubits=1, num_shots = 100, # increasing max_circuits to ensure a better exploration of the possibilities. 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") # validate parameters (smallest circuit is 2 qubits) max_qubits = max(3, max_qubits) min_qubits = min(max(2, min_qubits), max_qubits) skip_qubits = max(1, skip_qubits) #print(f"min, max qubits = {min_qubits} {max_qubits}") # create context identifier if context is None: context = f"{benchmark_name} ({method}) Benchmark" ########## # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler (qc, result, input_size, s_int, num_shots): # determine fidelity of result set num_qubits = int(input_size) counts, fidelity = analyze_and_print_result(qc, result, num_qubits, int(s_int), num_shots, method) metrics.store_metric(input_size, s_int, '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, skip_qubits): # reset random seed np.random.seed(0) # when you need reproducibility, for example, when debugging or testing algorithms where you want the same sequence of random numbers for consistency. num_qubits = input_size # determine number of circuits to execute for this group # and determine range of secret strings to loop over if method == 1 or method == 2: num_circuits = min(2**(input_size), max_circuits) if 2**(input_size) <= max_circuits: s_range = list(range(num_circuits)) # print("if ============ if") else: s_range = np.random.choice(range(2**(input_size)), num_circuits, False) # print("else ============== else") print(f"s_range === {s_range}") elif method == 3: num_circuits = min(input_size, max_circuits) if input_size <= max_circuits: s_range = list(range(num_circuits)) else: s_range = np.random.choice(range(input_size), num_circuits, False) else: sys.exit("Invalid QFT method") print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") # loop over limited # of secret strings for this for s_int in s_range: # create the circuit for given qubit size and secret string, store time metric ts = time.time() qc = QuantumFourierTransform(num_qubits, s_int, method=method).reverse_bits() #check qiskit-aakash/releasenotes/notes/0.17/qft-little-endian-d232c93e044f0063.yaml metrics.store_metric(input_size, s_int, '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, s_int, num_shots) print(qc) print(f"... number of gates, depth = {num_gates}, {depth}") # Wait for some active circuits to complete; report metrics when groups 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 created (if not too large) print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") if method==1: print("\nQFT Circuit ="); print(QFT_) print("\nInverse QFT Circuit ="); print(QFTI_) # Plot metrics for all circuit sizes metrics.plot_metrics(f"Benchmark Results - {benchmark_name} ({method}) - QSim") # if main, execute method 1 if __name__ == '__main__': run()
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
""" Quantum Fourier Transform Benchmark Program - QSim """ import math import sys import time import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister sys.path[1:1] = [ "_common", "_common/qsim" ] sys.path[1:1] = [ "../../_common", "../../_common/qsim" ] import execute as ex import metrics as metrics from qiskit.circuit.library import QFT from execute import BenchmarkResult # Benchmark Name benchmark_name = "Quantum Fourier Transform" np.random.seed(0) verbose = False # saved circuits for display num_gates = 0 depth = 0 QC_ = None QFT_ = None QFTI_ = None ############### Circuit Definition def QuantumFourierTransform (num_qubits, secret_int, method=1): global num_gates, depth # Size of input is one less than available qubits input_size = num_qubits num_gates = 0 depth = 0 # allocate qubits qr = QuantumRegister(num_qubits); cr = ClassicalRegister(num_qubits); qc = QuantumCircuit(qr, cr, name=f"qft({method})-{num_qubits}-{secret_int}") if method==1: # Perform X on each qubit that matches a bit in secret string s = ('{0:0'+str(input_size)+'b}').format(secret_int) for i_qubit in range(input_size): if s[input_size-1-i_qubit]=='1': qc.x(qr[i_qubit]) num_gates += 1 depth += 1 qc.barrier() # perform QFT on the input qc.append(qft_gate(input_size).to_instruction(), qr) # End with Hadamard on all qubits (to measure the z rotations) ''' don't do this unless NOT doing the inverse afterwards for i_qubit in range(input_size): qc.h(qr[i_qubit]) qc.barrier() ''' qc.barrier() # some compilers recognize the QFT and IQFT in series and collapse them to identity; # perform a set of rotations to add one to the secret_int to avoid this collapse for i_q in range(0, num_qubits): divisor = 2 ** (i_q) qc.rz( 1 * math.pi / divisor , qr[i_q]) num_gates+=1 qc.barrier() # to revert back to initial state, apply inverse QFT qc.append(inv_qft_gate(input_size).to_instruction(), qr) qc.barrier() elif method == 2: for i_q in range(0, num_qubits): qc.h(qr[i_q]) num_gates += 1 for i_q in range(0, num_qubits): divisor = 2 ** (i_q) qc.rz(secret_int * math.pi / divisor, qr[i_q]) num_gates += 1 depth += 1 qc.append(inv_qft_gate(input_size).to_instruction(), qr) # This method is a work in progress elif method==3: for i_q in range(0, secret_int): qc.h(qr[i_q]) num_gates+=1 for i_q in range(secret_int, num_qubits): qc.x(qr[i_q]) num_gates+=1 depth += 1 qc.append(inv_qft_gate(input_size).to_instruction(), qr) else: exit("Invalid QFT method") # measure all qubits qc.measure(qr, cr) num_gates += num_qubits depth += 1 # save smaller circuit example for display global QC_ if QC_ == None or num_qubits <= 5: if num_qubits < 9: QC_ = qc # return a handle on the circuit return qc ############### QFT Circuit def qft_gate(input_size): global QFT_, num_gates, depth qr = QuantumRegister(input_size); qc = QuantumCircuit(qr, name="qft") # Generate multiple groups of diminishing angle CRZs and H gate for i_qubit in range(0, input_size): # start laying out gates from highest order qubit (the hidx) hidx = input_size - i_qubit - 1 # if not the highest order qubit, add multiple controlled RZs of decreasing angle if hidx < input_size - 1: num_crzs = i_qubit for j in range(0, num_crzs): divisor = 2 ** (num_crzs - j) qc.crz( math.pi / divisor , qr[hidx], qr[input_size - j - 1]) num_gates += 1 depth += 1 # followed by an H gate (applied to all qubits) qc.h(qr[hidx]) num_gates += 1 depth += 1 qc.barrier() if QFT_ == None or input_size <= 5: if input_size < 9: QFT_ = qc return qc ############### Inverse QFT Circuit def inv_qft_gate(input_size): global QFTI_, num_gates, depth qr = QuantumRegister(input_size); qc = QuantumCircuit(qr, name="inv_qft") # Generate multiple groups of diminishing angle CRZs and H gate for i_qubit in reversed(range(0, input_size)): # start laying out gates from highest order qubit (the hidx) hidx = input_size - i_qubit - 1 # precede with an H gate (applied to all qubits) qc.h(qr[hidx]) num_gates += 1 depth += 1 # if not the highest order qubit, add multiple controlled RZs of decreasing angle if hidx < input_size - 1: num_crzs = i_qubit for j in reversed(range(0, num_crzs)): divisor = 2 ** (num_crzs - j) qc.crz( -math.pi / divisor , qr[hidx], qr[input_size - j - 1]) num_gates += 1 depth += 1 qc.barrier() if QFTI_ == None or input_size <= 5: if input_size < 9: QFTI_= qc return qc # Define expected distribution calculated from applying the iqft to the prepared secret_int state def expected_dist(num_qubits, secret_int, probs): dist = {} s = num_qubits - secret_int for key in probs.keys(): if key[(num_qubits-secret_int):] == ''.zfill(secret_int): dist[key] = 1/(2**s) return dist ############### Result Data Analysis # Analyze and print measured results def analyze_and_print_result (qc, result, num_qubits, secret_int, num_shots, method): # obtain probs from the result object 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 # For method 1, expected result is always the secret_int if method==1: # add one to the secret_int to compensate for the extra rotations done between QFT and IQFT secret_int_plus_one = (secret_int + 1) % (2 ** num_qubits) # create the key that is expected to have all the measurements (for this circuit) key = format(secret_int_plus_one, f"0{num_qubits}b") # correct distribution is measuring the key 100% of the time correct_dist = {key: 1.0} # For method 2, expected result is always the secret_int elif method==2: # create the key that is expected to have all the measurements (for this circuit) key = format(secret_int, f"0{num_qubits}b") # correct distribution is measuring the key 100% of the time correct_dist = {key: 1.0} # For method 3, correct_dist is a distribution with more than one value elif method==3: # correct_dist is from the expected dist correct_dist = expected_dist(num_qubits, secret_int, probs) # use our polarization fidelity rescaling fidelity = metrics.polarization_fidelity(probs, correct_dist) if verbose: print(f"For secret int {secret_int} measured: {probs} fidelity: {fidelity}") return probs, fidelity ################ Benchmark Loop # Execute program with default parameters def run (min_qubits = 2, max_qubits = 8, max_circuits = 3, skip_qubits=1, num_shots = 100, 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") # validate parameters (smallest circuit is 2 qubits) max_qubits = max(2, max_qubits) min_qubits = min(max(2, min_qubits), max_qubits) skip_qubits = max(1, skip_qubits) #print(f"min, max qubits = {min_qubits} {max_qubits}") # create context identifier if context is None: context = f"{benchmark_name} ({method}) Benchmark" ########## # Initialize metrics module metrics.init_metrics() # Define custom result handler def execution_handler (qc, result, input_size, s_int, num_shots): # determine fidelity of result set num_qubits = int(input_size) probs, fidelity = analyze_and_print_result(qc, result, num_qubits, int(s_int), num_shots, method) metrics.store_metric(input_size, s_int, '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, skip_qubits): # reset random seed np.random.seed(0) num_qubits = input_size # determine number of circuits to execute for this group # and determine range of secret strings to loop over if method == 1 or method == 2: num_circuits = min(2 ** (input_size), max_circuits) if 2**(input_size) <= max_circuits: s_range = list(range(num_circuits)) else: s_range = np.random.choice(2**(input_size), num_circuits, False) elif method == 3: num_circuits = min(input_size, max_circuits) if input_size <= max_circuits: s_range = list(range(num_circuits)) else: s_range = np.random.choice(range(input_size), num_circuits, False) else: sys.exit("Invalid QFT method") print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") # loop over limited # of secret strings for this for s_int in s_range: # create the circuit for given qubit size and secret string, store time metric ts = time.time() qc = QuantumFourierTransform(num_qubits, s_int, method=method).reverse_bits() metrics.store_metric(input_size, s_int, '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, s_int, num_shots) print(f"... number of gates, depth = {num_gates}, {depth}") # Wait for some active circuits to complete; report metrics when groups 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 created (if not too large) print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") if method==1: print("\nQFT Circuit ="); print(QFT_) print("\nInverse QFT Circuit ="); print(QFTI_) # Plot metrics for all circuit sizes metrics.plot_metrics(f"Benchmark Results - {benchmark_name} ({method}) - QSim") # if main, execute method 1 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/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
""" Shor's Order Finding Algorithm Benchmark - QSim """ import math import sys import time import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister sys.path[1:1] = ["_common", "_common/qsim", "shors/_common", "quantum-fourier-transform/qsim"] sys.path[1:1] = ["../../_common", "../../_common/qsim", "../../shors/_common", "../../quantum-fourier-transform/qsim"] import execute as ex import metrics as metrics from shors_utils import getAngles, getAngle, modinv, generate_base, verify_order from qft_benchmark import inv_qft_gate from qft_benchmark import qft_gate from execute import BenchmarkResult # Benchmark Name benchmark_name = "Shor's Order Finding" np.random.seed(0) verbose = False QC_ = None PHIADD_ = None CCPHIADDMODN_ = None CMULTAMODN_ = None CUA_ = None QFT_ = None ############### Circuit Definition #Creation of the circuit that performs addition by a in Fourier Space #Can also be used for subtraction by setting the parameter inv to a value different from 0 def phiADD(num_qubits, a): qc = QuantumCircuit(num_qubits, name = "\u03C6ADD") angle = getAngles(a, num_qubits) for i in range(0, num_qubits): # addition qc.p(angle[i], i) global PHIADD_ if PHIADD_ == None or num_qubits <= 3: if num_qubits < 4: PHIADD_ = qc return qc #Single controlled version of the phiADD circuit def cphiADD(num_qubits, a): phiadd_gate = phiADD(num_qubits,a).to_gate() cphiadd_gate = phiadd_gate.control(1) return cphiadd_gate #Doubly controlled version of the phiADD circuit def ccphiADD(num_qubits, a): phiadd_gate = phiADD(num_qubits,a).to_gate() ccphiadd_gate = phiadd_gate.control(2) return ccphiadd_gate # Circuit that implements doubly controlled modular addition by a (num qubits should be bit count for number N) def ccphiADDmodN(num_qubits, a, N): qr_ctl = QuantumRegister(2) qr_main = QuantumRegister(num_qubits+1) qr_ancilla = QuantumRegister(1) qc = QuantumCircuit(qr_ctl, qr_main,qr_ancilla, name = "cc\u03C6ADDmodN") # Generate relevant gates for circuit ccphiadda_gate = ccphiADD(num_qubits+1, a) ccphiadda_inv_gate = ccphiADD(num_qubits+1, a).inverse() phiaddN_inv_gate = phiADD(num_qubits+1, N).inverse(); phiaddN_inv_gate.name = "inv_\u03C6ADD" cphiaddN_gate = cphiADD(num_qubits+1, N) # Create relevant temporary qubit lists ctl_main_qubits = [i for i in qr_ctl]; ctl_main_qubits.extend([i for i in qr_main]) anc_main_qubits = [qr_ancilla[0]]; anc_main_qubits.extend([i for i in qr_main]) #Create circuit qc.append(ccphiadda_gate, ctl_main_qubits) qc.append(phiaddN_inv_gate, qr_main) qc.append(inv_qft_gate(num_qubits+1), qr_main) qc.cx(qr_main[-1], qr_ancilla[0]) qc.append(qft_gate(num_qubits+1), qr_main) qc.append(cphiaddN_gate, anc_main_qubits) qc.append(ccphiadda_inv_gate, ctl_main_qubits) qc.append(inv_qft_gate(num_qubits+1), qr_main) qc.x(qr_main[-1]) qc.cx(qr_main[-1], qr_ancilla[0]) qc.x(qr_main[-1]) qc.append(qft_gate(num_qubits+1), qr_main) qc.append(ccphiadda_gate, ctl_main_qubits) global CCPHIADDMODN_ if CCPHIADDMODN_ == None or num_qubits <= 2: if num_qubits < 3: CCPHIADDMODN_ = qc return qc # Circuit that implements the inverse of doubly controlled modular addition by a def ccphiADDmodN_inv(num_qubits, a, N): cchpiAddmodN_circ = ccphiADDmodN(num_qubits, a, N) cchpiAddmodN_inv_circ = cchpiAddmodN_circ.inverse() cchpiAddmodN_inv_circ.name = "inv_cchpiAddmodN" return cchpiAddmodN_inv_circ # Creates circuit that implements single controlled modular multiplication by a. n represents the number of bits # needed to represent the integer number N def cMULTamodN(n, a, N): qr_ctl = QuantumRegister(1) qr_x = QuantumRegister(n) qr_main = QuantumRegister(n+1) qr_ancilla = QuantumRegister(1) qc = QuantumCircuit(qr_ctl, qr_x, qr_main,qr_ancilla, name = "cMULTamodN") # quantum Fourier transform only on auxillary qubits qc.append(qft_gate(n+1), qr_main) for i in range(n): ccphiADDmodN_gate = ccphiADDmodN(n, (2**i)*a % N, N) # Create relevant temporary qubit list qubits = [qr_ctl[0]]; qubits.extend([qr_x[i]]) qubits.extend([i for i in qr_main]); qubits.extend([qr_ancilla[0]]) qc.append(ccphiADDmodN_gate, qubits) # inverse quantum Fourier transform only on auxillary qubits qc.append(inv_qft_gate(n+1), qr_main) global CMULTAMODN_ if CMULTAMODN_ == None or n <= 2: if n < 3: CMULTAMODN_ = qc return qc # Creates circuit that implements single controlled Ua gate. n represents the number of bits # needed to represent the integer number N def controlled_Ua(n,a,exponent,N): qr_ctl = QuantumRegister(1) qr_x = QuantumRegister(n) qr_main = QuantumRegister(n) qr_ancilla = QuantumRegister(2) qc = QuantumCircuit(qr_ctl, qr_x, qr_main,qr_ancilla, name = f"C-U^{a**exponent}") # Generate Gates a_inv = modinv(a**exponent,N) cMULTamodN_gate = cMULTamodN(n, a**exponent, N) cMULTamodN_inv_gate = cMULTamodN(n, a_inv, N).inverse(); cMULTamodN_inv_gate.name = "inv_cMULTamodN" # Create relevant temporary qubit list qubits = [i for i in qr_ctl]; qubits.extend([i for i in qr_x]); qubits.extend([i for i in qr_main]) qubits.extend([i for i in qr_ancilla]) qc.append(cMULTamodN_gate, qubits) for i in range(n): qc.cswap(qr_ctl, qr_x[i], qr_main[i]) qc.append(cMULTamodN_inv_gate, qubits) global CUA_ if CUA_ == None or n <= 2: if n < 3: CUA_ = qc return qc # Execute Shor's Order Finding Algorithm given a 'number' to factor, # the 'base' of exponentiation, and the number of qubits required 'input_size' def ShorsAlgorithm(number, base, method, verbose=verbose): # Create count of qubits to use to represent the number to factor # NOTE: this should match the number of bits required to represent (number) n = int(math.ceil(math.log(number, 2))) # Standard Shors Algorithm if method == 1: num_qubits = 4*n + 2 if verbose: print(f"... running Shors to find order of [ {base}^x mod {number} ] using num_qubits={num_qubits}") # Create a circuit and allocate necessary qubits qr_counting = QuantumRegister(2*n) # Register for sequential QFT qr_mult = QuantumRegister(n) # Register for multiplications qr_aux = QuantumRegister(n+2) # Register for addition and multiplication cr_data = ClassicalRegister(2*n) # Register for measured values of QFT qc = QuantumCircuit(qr_counting, qr_mult, qr_aux, cr_data, name=f"qmc({method})-{num_qubits}-{number}") # Initialize multiplication register to 1 and counting register to superposition state qc.h(qr_counting) qc.x(qr_mult[0]) qc.barrier() # Apply Multiplication Gates for exponentiation for i in reversed(range(2*n)): cUa_gate = controlled_Ua(n,int(base),2**(2*n-1-i),number) # Create relevant temporary qubit list qubits = [qr_counting[i]]; qubits.extend([i for i in qr_mult]);qubits.extend([i for i in qr_aux]) qc.append(cUa_gate, qubits) qc.barrier() qc.append(inv_qft_gate(2*n),qr_counting) # Measure counting register qc.measure(qr_counting, cr_data) elif method == 2: # Create a circuit and allocate necessary qubits num_qubits = 2*n + 3 if verbose: print(f"... running Shors to find order of [ {base}^x mod {number} ] using num_qubits={num_qubits}") qr_counting = QuantumRegister(1) # Single qubit for sequential QFT qr_mult = QuantumRegister(n) # Register for multiplications qr_aux = QuantumRegister(n+2) # Register for addition and multiplication cr_data = ClassicalRegister(2*n) # Register for measured values of QFT cr_aux = ClassicalRegister(1) # Register to reset the state of the up register based on previous measurements qc = QuantumCircuit(qr_counting, qr_mult, qr_aux, cr_data, cr_aux, name="main") # Initialize mult register to 1 qc.x(qr_mult[0]) # perform modular exponentiation 2*n times for k in range(2*n): qc.barrier() # Reset the counting qubit to 0 if the previous measurement was 1 qc.x(qr_counting).c_if(cr_aux,1) qc.h(qr_counting) cUa_gate = controlled_Ua(n, base,2**(2*n-1-k), number) # Create relevant temporary qubit list qubits = [qr_counting[0]]; qubits.extend([i for i in qr_mult]);qubits.extend([i for i in qr_aux]) qc.append(cUa_gate, qubits) # perform inverse QFT --> Rotations conditioned on previous outcomes for i in range(2**k): qc.p(getAngle(i, k), qr_counting[0]).c_if(cr_data, i) qc.h(qr_counting) qc.measure(qr_counting[0], cr_data[k]) qc.measure(qr_counting[0], cr_aux[0]) global QC_, QFT_ if QC_ == None or n <= 2: if n < 3: QC_ = qc if QFT_ == None or n <= 2: if n < 3: QFT_ = qft_gate(n+1) return qc ############### Circuit end def expected_shor_dist(num_bits, order, num_shots): # num_bits represent the number of bits to represent the number N in question # Qubits measureed always 2 * num_bits for the three methods implemented in this benchmark qubits_measured = 2 * num_bits dist = {} #Conver float to int r = int(order) #Generate expected distribution q = int(2 ** (qubits_measured)) for i in range(r): key = bin(int(q*(i/r)))[2:].zfill(qubits_measured) dist[key] = num_shots/r ''' for c in range(2 ** qubits_measured): key = bin(c)[2:].zfill(qubits_measured) amp = 0 for i in range(int(q/r) - 1): amp += np.exp(2*math.pi* 1j * i * (r * c % q)/q ) amp = amp * np.sqrt(r) / q dist[key] = abs(amp) ** 2 ''' return dist # Print analyzed results # Analyze and print measured results # Expected result is always the order r, so fidelity calc is simple def analyze_and_print_result(qc, result, num_qubits, order, num_shots, method): if method == 1: num_bits = int((num_qubits - 2) / 4) elif method == 2: num_bits = int((num_qubits - 3) / 2) elif method == 3: num_bits = int((num_qubits - 2) / 2) 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 # Only classical data qubits are important and removing first auxiliary qubit from count if method == 2: temp_probs = {} for key, item in probs.items(): temp_probs[key[2:]] = item probs = temp_probs # generate correct distribution correct_dist = expected_shor_dist(num_bits, order, num_shots) if verbose: print(f"For order value {order}, measured: {probs}") print(f"For order value {order}, correct_dist: {correct_dist}") # use our polarization fidelity rescaling fidelity = metrics.polarization_fidelity(probs, correct_dist) return probs, fidelity #################### Benchmark Loop # Execute program with default parameters def run (min_qubits=3, max_circuits=1, max_qubits=10, num_shots=100, method = 1, verbose=verbose, 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 - QSim") # Each method has a different minimum amount of qubits to run and a certain multiple of qubits that can be run qubit_multiple = 2 #Standard for Method 2 and 3 max_qubits = max(max_qubits, min_qubits) # max must be >= min if method == 1: min_qubits = max(min_qubits, 10) # need min of 10 qubit_multiple = 4 elif method ==2: min_qubits = max(min_qubits, 7) # need min of 7 elif method == 3: min_qubits = max(min_qubits,6) # need min of 6 #skip_qubits = max(1, skip_qubits) if max_qubits < min_qubits: print(f"Max number of qubits {max_qubits} is too low to run method {method} of {benchmark_name}") return # create context identifier if context is None: context = f"{benchmark_name} ({method}) Benchmark" ########## # Initialize metrics module metrics.init_metrics() # Define custom result handler # number_order contains an array of length 2 with the number and order def execution_handler(qc, result, num_qubits, number_order, num_shots): # determine fidelity of result set num_qubits = int(num_qubits) #Must convert number_order from string to array order = eval(number_order)[1] probs, fidelity = analyze_and_print_result(qc, result, num_qubits, order, num_shots, method) metrics.store_metric(num_qubits, number_order, '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 num_qubits in range(min_qubits, max_qubits + 1, qubit_multiple): input_size = num_qubits - 1 if method == 1: num_bits = int((num_qubits -2)/4) elif method == 2: num_bits = int((num_qubits -3)/2) elif method == 3: num_bits = int((num_qubits -2)/2) # determine number of circuits to execute for this group num_circuits = min(2 ** (input_size), max_circuits) print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") for _ in range(num_circuits): base = 1 while base == 1: # Ensure N is a number using the greatest bit number = np.random.randint(2 ** (num_bits - 1) + 1, 2 ** num_bits) order = np.random.randint(2, number) base = generate_base(number, order) # Checking if generated order can be reduced. Can also run through prime list in shors utils if order % 2 == 0: order = 2 if order % 3 == 0: order = 3 number_order = (number, order) if verbose: print(f"Generated {number=}, {base=}, {order=}") # create the circuit for given qubit size and order, store time metric ts = time.time() qc = ShorsAlgorithm(number, base, method=method, verbose=verbose).reverse_bits() # reverse_bits() is applying to handle the change in endianness metrics.store_metric(num_qubits, number_order, 'create_time', time.time()-ts) # collapse the 4 sub-circuit levels used in this benchmark (for qiskit) qc = qc.decompose().decompose().decompose().decompose() # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc, num_qubits, number_order, num_shots) # Wait for some active circuits to complete; report metrics when groups 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 the last circuit created print("***************************************************************************************************************************************") # print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") # print("\nControlled Ua Operator 'cUa' ="); print(CUA_ if CUA_ != None else " ... too large!") # print("\nControlled Multiplier Operator 'cMULTamodN' ="); print(CMULTAMODN_ if CMULTAMODN_!= None else " ... too large!") # print("\nControlled Modular Adder Operator 'ccphiamodN' ="); print(CCPHIADDMODN_ if CCPHIADDMODN_ != None else " ... too large!") # print("\nPhi Adder Operator '\u03C6ADD' ="); print(PHIADD_ if PHIADD_ != None else " ... too large!") # print("\nQFT Circuit ="); print(QFT_ if QFT_ != None else " ... too large!") # Plot metrics for all circuit sizes metrics.plot_metrics(f"Benchmark Results - {benchmark_name} ({method}) - QSim") # if main, execute method if __name__ == '__main__': run()
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
""" Shor's Order Finding Algorithm Benchmark - QSim """ import math import sys import time import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister sys.path[1:1] = ["_common", "_common/qsim", "shors/_common", "quantum-fourier-transform/qsim"] sys.path[1:1] = ["../../_common", "../../_common/qsim", "../../shors/_common", "../../quantum-fourier-transform/qsim"] import execute as ex import metrics as metrics from shors_utils import getAngles, getAngle, modinv, generate_base, verify_order from qft_benchmark import inv_qft_gate from qft_benchmark import qft_gate from execute import BenchmarkResult # Benchmark Name benchmark_name = "Shor's Order Finding" np.random.seed(0) verbose = False QC_ = None PHIADD_ = None CCPHIADDMODN_ = None CMULTAMODN_ = None CUA_ = None QFT_ = None ############### Circuit Definition #Creation of the circuit that performs addition by a in Fourier Space #Can also be used for subtraction by setting the parameter inv to a value different from 0 def phiADD(num_qubits, a): qc = QuantumCircuit(num_qubits, name = "\u03C6ADD") angle = getAngles(a, num_qubits) for i in range(0, num_qubits): # addition qc.p(angle[i], i) global PHIADD_ if PHIADD_ == None or num_qubits <= 3: if num_qubits < 4: PHIADD_ = qc return qc #Single controlled version of the phiADD circuit def cphiADD(num_qubits, a): phiadd_gate = phiADD(num_qubits,a).to_gate() cphiadd_gate = phiadd_gate.control(1) return cphiadd_gate #Doubly controlled version of the phiADD circuit def ccphiADD(num_qubits, a): phiadd_gate = phiADD(num_qubits,a).to_gate() ccphiadd_gate = phiadd_gate.control(2) return ccphiadd_gate # Circuit that implements doubly controlled modular addition by a (num qubits should be bit count for number N) def ccphiADDmodN(num_qubits, a, N): qr_ctl = QuantumRegister(2) qr_main = QuantumRegister(num_qubits+1) qr_ancilla = QuantumRegister(1) qc = QuantumCircuit(qr_ctl, qr_main,qr_ancilla, name = "cc\u03C6ADDmodN") # Generate relevant gates for circuit ccphiadda_gate = ccphiADD(num_qubits+1, a) ccphiadda_inv_gate = ccphiADD(num_qubits+1, a).inverse() phiaddN_inv_gate = phiADD(num_qubits+1, N).inverse(); phiaddN_inv_gate.name = "inv_\u03C6ADD" cphiaddN_gate = cphiADD(num_qubits+1, N) # Create relevant temporary qubit lists ctl_main_qubits = [i for i in qr_ctl]; ctl_main_qubits.extend([i for i in qr_main]) anc_main_qubits = [qr_ancilla[0]]; anc_main_qubits.extend([i for i in qr_main]) #Create circuit qc.append(ccphiadda_gate, ctl_main_qubits) qc.append(phiaddN_inv_gate, qr_main) qc.append(inv_qft_gate(num_qubits+1), qr_main) qc.cx(qr_main[-1], qr_ancilla[0]) qc.append(qft_gate(num_qubits+1), qr_main) qc.append(cphiaddN_gate, anc_main_qubits) qc.append(ccphiadda_inv_gate, ctl_main_qubits) qc.append(inv_qft_gate(num_qubits+1), qr_main) qc.x(qr_main[-1]) qc.cx(qr_main[-1], qr_ancilla[0]) qc.x(qr_main[-1]) qc.append(qft_gate(num_qubits+1), qr_main) qc.append(ccphiadda_gate, ctl_main_qubits) global CCPHIADDMODN_ if CCPHIADDMODN_ == None or num_qubits <= 2: if num_qubits < 3: CCPHIADDMODN_ = qc return qc # Circuit that implements the inverse of doubly controlled modular addition by a def ccphiADDmodN_inv(num_qubits, a, N): cchpiAddmodN_circ = ccphiADDmodN(num_qubits, a, N) cchpiAddmodN_inv_circ = cchpiAddmodN_circ.inverse() cchpiAddmodN_inv_circ.name = "inv_cchpiAddmodN" return cchpiAddmodN_inv_circ # Creates circuit that implements single controlled modular multiplication by a. n represents the number of bits # needed to represent the integer number N def cMULTamodN(n, a, N): qr_ctl = QuantumRegister(1) qr_x = QuantumRegister(n) qr_main = QuantumRegister(n+1) qr_ancilla = QuantumRegister(1) qc = QuantumCircuit(qr_ctl, qr_x, qr_main,qr_ancilla, name = "cMULTamodN") # quantum Fourier transform only on auxillary qubits qc.append(qft_gate(n+1), qr_main) for i in range(n): ccphiADDmodN_gate = ccphiADDmodN(n, (2**i)*a % N, N) # Create relevant temporary qubit list qubits = [qr_ctl[0]]; qubits.extend([qr_x[i]]) qubits.extend([i for i in qr_main]); qubits.extend([qr_ancilla[0]]) qc.append(ccphiADDmodN_gate, qubits) # inverse quantum Fourier transform only on auxillary qubits qc.append(inv_qft_gate(n+1), qr_main) global CMULTAMODN_ if CMULTAMODN_ == None or n <= 2: if n < 3: CMULTAMODN_ = qc return qc # Creates circuit that implements single controlled Ua gate. n represents the number of bits # needed to represent the integer number N def controlled_Ua(n,a,exponent,N): qr_ctl = QuantumRegister(1) qr_x = QuantumRegister(n) qr_main = QuantumRegister(n) qr_ancilla = QuantumRegister(2) qc = QuantumCircuit(qr_ctl, qr_x, qr_main,qr_ancilla, name = f"C-U^{a**exponent}") # Generate Gates a_inv = modinv(a**exponent,N) cMULTamodN_gate = cMULTamodN(n, a**exponent, N) cMULTamodN_inv_gate = cMULTamodN(n, a_inv, N).inverse(); cMULTamodN_inv_gate.name = "inv_cMULTamodN" # Create relevant temporary qubit list qubits = [i for i in qr_ctl]; qubits.extend([i for i in qr_x]); qubits.extend([i for i in qr_main]) qubits.extend([i for i in qr_ancilla]) qc.append(cMULTamodN_gate, qubits) for i in range(n): qc.cswap(qr_ctl, qr_x[i], qr_main[i]) qc.append(cMULTamodN_inv_gate, qubits) global CUA_ if CUA_ == None or n <= 2: if n < 3: CUA_ = qc return qc # Execute Shor's Order Finding Algorithm given a 'number' to factor, # the 'base' of exponentiation, and the number of qubits required 'input_size' def ShorsAlgorithm(number, base, method, verbose=verbose): # Create count of qubits to use to represent the number to factor # NOTE: this should match the number of bits required to represent (number) n = int(math.ceil(math.log(number, 2))) # Standard Shors Algorithm if method == 1: num_qubits = 4*n + 2 if verbose: print(f"... running Shors to find order of [ {base}^x mod {number} ] using num_qubits={num_qubits}") # Create a circuit and allocate necessary qubits qr_counting = QuantumRegister(2*n) # Register for sequential QFT qr_mult = QuantumRegister(n) # Register for multiplications qr_aux = QuantumRegister(n+2) # Register for addition and multiplication cr_data = ClassicalRegister(2*n) # Register for measured values of QFT qc = QuantumCircuit(qr_counting, qr_mult, qr_aux, cr_data, name=f"qmc({method})-{num_qubits}-{number}") # Initialize multiplication register to 1 and counting register to superposition state qc.h(qr_counting) qc.x(qr_mult[0]) qc.barrier() # Apply Multiplication Gates for exponentiation for i in reversed(range(2*n)): cUa_gate = controlled_Ua(n,int(base),2**(2*n-1-i),number) # Create relevant temporary qubit list qubits = [qr_counting[i]]; qubits.extend([i for i in qr_mult]);qubits.extend([i for i in qr_aux]) qc.append(cUa_gate, qubits) qc.barrier() qc.append(inv_qft_gate(2*n),qr_counting) # Measure counting register qc.measure(qr_counting, cr_data) elif method == 2: # Create a circuit and allocate necessary qubits num_qubits = 2*n + 3 if verbose: print(f"... running Shors to find order of [ {base}^x mod {number} ] using num_qubits={num_qubits}") qr_counting = QuantumRegister(1) # Single qubit for sequential QFT qr_mult = QuantumRegister(n) # Register for multiplications qr_aux = QuantumRegister(n+2) # Register for addition and multiplication cr_data = ClassicalRegister(2*n) # Register for measured values of QFT cr_aux = ClassicalRegister(1) # Register to reset the state of the up register based on previous measurements qc = QuantumCircuit(qr_counting, qr_mult, qr_aux, cr_data, cr_aux, name="main") # Initialize mult register to 1 qc.x(qr_mult[0]) # perform modular exponentiation 2*n times for k in range(2*n): qc.barrier() # Reset the counting qubit to 0 if the previous measurement was 1 qc.x(qr_counting).c_if(cr_aux,1) qc.h(qr_counting) cUa_gate = controlled_Ua(n, base,2**(2*n-1-k), number) # Create relevant temporary qubit list qubits = [qr_counting[0]]; qubits.extend([i for i in qr_mult]);qubits.extend([i for i in qr_aux]) qc.append(cUa_gate, qubits) # perform inverse QFT --> Rotations conditioned on previous outcomes for i in range(2**k): qc.p(getAngle(i, k), qr_counting[0]).c_if(cr_data, i) qc.h(qr_counting) qc.measure(qr_counting[0], cr_data[k]) qc.measure(qr_counting[0], cr_aux[0]) global QC_, QFT_ if QC_ == None or n <= 2: if n < 3: QC_ = qc if QFT_ == None or n <= 2: if n < 3: QFT_ = qft_gate(n+1) return qc ############### Circuit end def expected_shor_dist(num_bits, order, num_shots): # num_bits represent the number of bits to represent the number N in question # Qubits measureed always 2 * num_bits for the three methods implemented in this benchmark qubits_measured = 2 * num_bits dist = {} #Conver float to int r = int(order) #Generate expected distribution q = int(2 ** (qubits_measured)) for i in range(r): key = bin(int(q*(i/r)))[2:].zfill(qubits_measured) dist[key] = num_shots/r ''' for c in range(2 ** qubits_measured): key = bin(c)[2:].zfill(qubits_measured) amp = 0 for i in range(int(q/r) - 1): amp += np.exp(2*math.pi* 1j * i * (r * c % q)/q ) amp = amp * np.sqrt(r) / q dist[key] = abs(amp) ** 2 ''' return dist # Print analyzed results # Analyze and print measured results # Expected result is always the order r, so fidelity calc is simple def analyze_and_print_result(qc, result, num_qubits, order, num_shots, method): if method == 1: num_bits = int((num_qubits - 2) / 4) elif method == 2: num_bits = int((num_qubits - 3) / 2) elif method == 3: num_bits = int((num_qubits - 2) / 2) 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 # Only classical data qubits are important and removing first auxiliary qubit from count if method == 2: temp_probs = {} for key, item in probs.items(): temp_probs[key[2:]] = item probs = temp_probs # generate correct distribution correct_dist = expected_shor_dist(num_bits, order, num_shots) if verbose: print(f"For order value {order}, measured: {probs}") print(f"For order value {order}, correct_dist: {correct_dist}") # use our polarization fidelity rescaling fidelity = metrics.polarization_fidelity(probs, correct_dist) return probs, fidelity #################### Benchmark Loop # Execute program with default parameters def run (min_qubits=3, max_circuits=1, max_qubits=10, num_shots=100, method = 1, verbose=verbose, 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 - QSim") # Each method has a different minimum amount of qubits to run and a certain multiple of qubits that can be run qubit_multiple = 2 #Standard for Method 2 and 3 max_qubits = max(max_qubits, min_qubits) # max must be >= min if method == 1: min_qubits = max(min_qubits, 10) # need min of 10 qubit_multiple = 4 elif method ==2: min_qubits = max(min_qubits, 7) # need min of 7 elif method == 3: min_qubits = max(min_qubits,6) # need min of 6 #skip_qubits = max(1, skip_qubits) if max_qubits < min_qubits: print(f"Max number of qubits {max_qubits} is too low to run method {method} of {benchmark_name}") return # create context identifier if context is None: context = f"{benchmark_name} ({method}) Benchmark" ########## # Initialize metrics module metrics.init_metrics() # Define custom result handler # number_order contains an array of length 2 with the number and order def execution_handler(qc, result, num_qubits, number_order, num_shots): # determine fidelity of result set num_qubits = int(num_qubits) #Must convert number_order from string to array order = eval(number_order)[1] probs, fidelity = analyze_and_print_result(qc, result, num_qubits, order, num_shots, method) metrics.store_metric(num_qubits, number_order, '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 num_qubits in range(min_qubits, max_qubits + 1, qubit_multiple): input_size = num_qubits - 1 if method == 1: num_bits = int((num_qubits -2)/4) elif method == 2: num_bits = int((num_qubits -3)/2) elif method == 3: num_bits = int((num_qubits -2)/2) # determine number of circuits to execute for this group num_circuits = min(2 ** (input_size), max_circuits) print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}") for _ in range(num_circuits): base = 1 while base == 1: # Ensure N is a number using the greatest bit number = np.random.randint(2 ** (num_bits - 1) + 1, 2 ** num_bits) order = np.random.randint(2, number) base = generate_base(number, order) # Checking if generated order can be reduced. Can also run through prime list in shors utils if order % 2 == 0: order = 2 if order % 3 == 0: order = 3 number_order = (number, order) if verbose: print(f"Generated {number=}, {base=}, {order=}") # create the circuit for given qubit size and order, store time metric ts = time.time() qc = ShorsAlgorithm(number, base, method=method, verbose=verbose).reverse_bits() # reverse_bits() is applying to handle the change in endianness metrics.store_metric(num_qubits, number_order, 'create_time', time.time()-ts) # collapse the 4 sub-circuit levels used in this benchmark (for qiskit) qc = qc.decompose().decompose().decompose().decompose() # submit circuit for execution on target (simulator, cloud simulator, or hardware) ex.submit_circuit(qc, num_qubits, number_order, num_shots) # Wait for some active circuits to complete; report metrics when groups 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 the last circuit created print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") print("\nControlled Ua Operator 'cUa' ="); print(CUA_ if CUA_ != None else " ... too large!") print("\nControlled Multiplier Operator 'cMULTamodN' ="); print(CMULTAMODN_ if CMULTAMODN_!= None else " ... too large!") print("\nControlled Modular Adder Operator 'ccphiamodN' ="); print(CCPHIADDMODN_ if CCPHIADDMODN_ != None else " ... too large!") print("\nPhi Adder Operator '\u03C6ADD' ="); print(PHIADD_ if PHIADD_ != None else " ... too large!") print("\nQFT Circuit ="); print(QFT_ if QFT_ != None else " ... too large!") # Plot metrics for all circuit sizes metrics.plot_metrics(f"Benchmark Results - {benchmark_name} ({method}) - QSim") # if main, execute method if __name__ == '__main__': ex.local_args() # calling local_args() needed while taking noise parameters through command line arguments (for individual benchmarks) run() #max_qubits = 6, max_circuits = 5, num_shots=100)
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
import math number = 3 int(math.ceil(math.log(number, 2))) import math import sys import time import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister sys.path[1:1] = ["_common", "_common/qsim", "shors/_common", "quantum-fourier-transform/qsim"] sys.path[1:1] = ["../../_common", "../../_common/qsim", "../../shors/_common", "../../quantum-fourier-transform/qsim"] from qiskit import * from shors_utils import getAngles, getAngle, modinv, generate_base n=2 num_qubits = 2*n + 3 qr_counting = QuantumRegister(1) qr_mult = QuantumRegister(n) # Register for multiplications qr_aux = QuantumRegister(n+2) # Register for addition and multiplication cr_data = ClassicalRegister(2*n) # Register for measured values of QFT cr_aux = ClassicalRegister(1) print(qr_counting) print(qr_mult,qr_aux,cr_data,cr_aux) qc = QuantumCircuit(qr_counting, qr_mult, qr_aux, cr_data, cr_aux, name="main") print(qc) qc.x(qr_mult[0]) print(qc) num_gates = 0 depth = 0 ############### QFT Circuit def qft_gate(input_size): global QFT_, num_gates, depth qr = QuantumRegister(input_size); qc = QuantumCircuit(qr, name="qft") # Generate multiple groups of diminishing angle CRZs and H gate for i_qubit in range(0, input_size): # start laying out gates from highest order qubit (the hidx) hidx = input_size - i_qubit - 1 # if not the highest order qubit, add multiple controlled RZs of decreasing angle if hidx < input_size - 1: num_crzs = i_qubit for j in range(0, num_crzs): divisor = 2 ** (num_crzs - j) qc.crz( math.pi / divisor , qr[hidx], qr[input_size - j - 1]) num_gates += 1 depth += 1 # followed by an H gate (applied to all qubits) qc.h(qr[hidx]) num_gates += 1 depth += 1 qc.barrier() if QFT_ == None or input_size <= 5: if input_size < 9: QFT_ = qc return qc ############### Inverse QFT Circuit def inv_qft_gate(input_size): global QFTI_, num_gates, depth qr = QuantumRegister(input_size); qc = QuantumCircuit(qr, name="inv_qft") # Generate multiple groups of diminishing angle CRZs and H gate for i_qubit in reversed(range(0, input_size)): # start laying out gates from highest order qubit (the hidx) hidx = input_size - i_qubit - 1 # precede with an H gate (applied to all qubits) qc.h(qr[hidx]) num_gates += 1 depth += 1 # if not the highest order qubit, add multiple controlled RZs of decreasing angle if hidx < input_size - 1: num_crzs = i_qubit for j in reversed(range(0, num_crzs)): divisor = 2 ** (num_crzs - j) qc.crz( -math.pi / divisor , qr[hidx], qr[input_size - j - 1]) num_gates += 1 depth += 1 qc.barrier() if QFTI_ == None or input_size <= 5: if input_size < 9: QFTI_= qc return qc base=2 QC_ = None PHIADD_ = None CCPHIADDMODN_ = None CMULTAMODN_ = None CUA_ = None QFT_ = None QFTI_ = None def phiADD(num_qubits, a): qc = QuantumCircuit(num_qubits, name = "\u03C6ADD") angle = getAngles(a, num_qubits) for i in range(0, num_qubits): # addition qc.p(angle[i], i) global PHIADD_ if PHIADD_ == None or num_qubits <= 3: if num_qubits < 4: PHIADD_ = qc return qc #Single controlled version of the phiADD circuit def cphiADD(num_qubits, a): phiadd_gate = phiADD(num_qubits,a).to_gate() cphiadd_gate = phiadd_gate.control(1) return cphiadd_gate #Doubly controlled version of the phiADD circuit def ccphiADD(num_qubits, a): phiadd_gate = phiADD(num_qubits,a).to_gate() ccphiadd_gate = phiadd_gate.control(2) return ccphiadd_gate # Circuit that implements doubly controlled modular addition by a (num qubits should be bit count for number N) def ccphiADDmodN(num_qubits, a, N): qr_ctl = QuantumRegister(2) qr_main = QuantumRegister(num_qubits+1) qr_ancilla = QuantumRegister(1) qc = QuantumCircuit(qr_ctl, qr_main,qr_ancilla, name = "cc\u03C6ADDmodN") # Generate relevant gates for circuit ccphiadda_gate = ccphiADD(num_qubits+1, a) ccphiadda_inv_gate = ccphiADD(num_qubits+1, a).inverse() phiaddN_inv_gate = phiADD(num_qubits+1, N).inverse(); phiaddN_inv_gate.name = "inv_\u03C6ADD" cphiaddN_gate = cphiADD(num_qubits+1, N) # Create relevant temporary qubit lists ctl_main_qubits = [i for i in qr_ctl]; ctl_main_qubits.extend([i for i in qr_main]) anc_main_qubits = [qr_ancilla[0]]; anc_main_qubits.extend([i for i in qr_main]) #Create circuit qc.append(ccphiadda_gate, ctl_main_qubits) qc.append(phiaddN_inv_gate, qr_main) qc.append(inv_qft_gate(num_qubits+1), qr_main) qc.cx(qr_main[-1], qr_ancilla[0]) qc.append(qft_gate(num_qubits+1), qr_main) qc.append(cphiaddN_gate, anc_main_qubits) qc.append(ccphiadda_inv_gate, ctl_main_qubits) qc.append(inv_qft_gate(num_qubits+1), qr_main) qc.x(qr_main[-1]) qc.cx(qr_main[-1], qr_ancilla[0]) qc.x(qr_main[-1]) qc.append(qft_gate(num_qubits+1), qr_main) qc.append(ccphiadda_gate, ctl_main_qubits) global CCPHIADDMODN_ if CCPHIADDMODN_ == None or num_qubits <= 2: if num_qubits < 3: CCPHIADDMODN_ = qc return qc def ccphiADDmodN_inv(num_qubits, a, N): cchpiAddmodN_circ = ccphiADDmodN(num_qubits, a, N) cchpiAddmodN_inv_circ = cchpiAddmodN_circ.inverse() cchpiAddmodN_inv_circ.name = "inv_cchpiAddmodN" return cchpiAddmodN_inv_circ # Creates circuit that implements single controlled modular multiplication by a. n represents the number of bits # needed to represent the integer number N def cMULTamodN(n, a, N): qr_ctl = QuantumRegister(1) qr_x = QuantumRegister(n) qr_main = QuantumRegister(n+1) qr_ancilla = QuantumRegister(1) qc = QuantumCircuit(qr_ctl, qr_x, qr_main,qr_ancilla, name = "cMULTamodN") # quantum Fourier transform only on auxillary qubits qc.append(qft_gate(n+1), qr_main) for i in range(n): ccphiADDmodN_gate = ccphiADDmodN(n, (2**i)*a % N, N) # Create relevant temporary qubit list qubits = [qr_ctl[0]]; qubits.extend([qr_x[i]]) qubits.extend([i for i in qr_main]); qubits.extend([qr_ancilla[0]]) qc.append(ccphiADDmodN_gate, qubits) # inverse quantum Fourier transform only on auxillary qubits qc.append(inv_qft_gate(n+1), qr_main) global CMULTAMODN_ if CMULTAMODN_ == None or n <= 2: if n < 3: CMULTAMODN_ = qc return qc def controlled_Ua(n,a,exponent,N): qr_ctl = QuantumRegister(1) qr_x = QuantumRegister(n) qr_main = QuantumRegister(n) qr_ancilla = QuantumRegister(2) qc = QuantumCircuit(qr_ctl, qr_x, qr_main,qr_ancilla, name = f"C-U^{a**exponent}") # Generate Gates a_inv = modinv(a**exponent,N) cMULTamodN_gate = cMULTamodN(n, a**exponent, N) cMULTamodN_inv_gate = cMULTamodN(n, a_inv, N).inverse(); cMULTamodN_inv_gate.name = "inv_cMULTamodN" # Create relevant temporary qubit list qubits = [i for i in qr_ctl]; qubits.extend([i for i in qr_x]); qubits.extend([i for i in qr_main]) qubits.extend([i for i in qr_ancilla]) qc.append(cMULTamodN_gate, qubits) for i in range(n): qc.cswap(qr_ctl, qr_x[i], qr_main[i]) qc.append(cMULTamodN_inv_gate, qubits) global CUA_ if CUA_ == None or n <= 2: if n < 3: CUA_ = qc return qc # perform modular exponentiation 2*n times for k in range(2*n): qc.barrier() # Reset the counting qubit to 0 if the previous measurement was 1 qc.x(qr_counting).c_if(cr_aux,1) qc.h(qr_counting) cUa_gate = controlled_Ua(n, base,2**(2*n-1-k), number) # Create relevant temporary qubit list qubits = [qr_counting[0]]; qubits.extend([i for i in qr_mult]);qubits.extend([i for i in qr_aux]) qc.append(cUa_gate, qubits) # perform inverse QFT --> Rotations conditioned on previous outcomes for i in range(2**k): qc.p(getAngle(i, k), qr_counting[0]).c_if(cr_data, i) qc.h(qr_counting) qc.measure(qr_counting[0], cr_data[k]) qc.measure(qr_counting[0], cr_aux[0]) print(qc) num_shots=100 backend = BasicAer.get_backend('dm_simulator') options={} job = execute(qc, backend, shots=num_shots, **options) result = job.result() print(result) qc= qc.decompose()#.decompose().decompose().decompose() print(qc) num_shots=100 backend = BasicAer.get_backend('dm_simulator') options={} job = execute(qc, backend, shots=num_shots, **options) result = job.result() print(result)
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
""" This file contains quantum code in support of Shor's Algorithm """ """ Imports from qiskit""" from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister import sys import math import numpy as np """ ********* QFT Functions *** """ """ Function to create QFT """ def create_QFT(circuit,up_reg,n,with_swaps): i=n-1 """ Apply the H gates and Cphases""" """ The Cphases with |angle| < threshold are not created because they do nothing. The threshold is put as being 0 so all CPhases are created, but the clause is there so if wanted just need to change the 0 of the if-clause to the desired value """ while i>=0: circuit.h(up_reg[i]) j=i-1 while j>=0: if (np.pi)/(pow(2,(i-j))) > 0: circuit.cu1( (np.pi)/(pow(2,(i-j))) , up_reg[i] , up_reg[j] ) j=j-1 i=i-1 """ If specified, apply the Swaps at the end """ if with_swaps==1: i=0 while i < ((n-1)/2): circuit.swap(up_reg[i], up_reg[n-1-i]) i=i+1 """ Function to create inverse QFT """ def create_inverse_QFT(circuit,up_reg,n,with_swaps): """ If specified, apply the Swaps at the beginning""" if with_swaps==1: i=0 while i < ((n-1)/2): circuit.swap(up_reg[i], up_reg[n-1-i]) i=i+1 """ Apply the H gates and Cphases""" """ The Cphases with |angle| < threshold are not created because they do nothing. The threshold is put as being 0 so all CPhases are created, but the clause is there so if wanted just need to change the 0 of the if-clause to the desired value """ i=0 while i<n: circuit.h(up_reg[i]) if i != n-1: j=i+1 y=i while y>=0: if (np.pi)/(pow(2,(j-y))) > 0: circuit.cu1( - (np.pi)/(pow(2,(j-y))) , up_reg[j] , up_reg[y] ) y=y-1 i=i+1 """ ********* Arithmetic Functions *** """ """ Helper Functions """ def egcd(a, b): if a == 0: return (b, 0, 1) else: g, y, x = egcd(b % a, a) return (g, x - (b // a) * y, y) def modinv(a, m): g, x, y = egcd(a, m) if g != 1: raise Exception('modular inverse does not exist') else: return x % m """Function that calculates the angle of a phase shift in the sequential QFT based on the binary digits of a.""" """a represents a possible value of the classical register""" def getAngle(a, N): """convert the number a to a binary string with length N""" s=bin(int(a))[2:].zfill(N) angle = 0 for i in range(0, N): """if the digit is 1, add the corresponding value to the angle""" if s[N-1-i] == '1': angle += math.pow(2, -(N-i)) angle *= np.pi return angle """Function that calculates the array of angles to be used in the addition in Fourier Space""" def getAngles(a,N): s=bin(int(a))[2:].zfill(N) angles=np.zeros([N]) for i in range(0, N): for j in range(i,N): if s[j]=='1': angles[N-i-1]+=math.pow(2, -(j-i)) angles[N-i-1]*=np.pi return angles """Creation of a doubly controlled phase gate""" def ccphase(circuit, angle, ctl1, ctl2, tgt): circuit.cu1(angle/2,ctl1,tgt) circuit.cx(ctl2,ctl1) circuit.cu1(-angle/2,ctl1,tgt) circuit.cx(ctl2,ctl1) circuit.cu1(angle/2,ctl2,tgt) """Creation of the circuit that performs addition by a in Fourier Space""" """Can also be used for subtraction by setting the parameter inv to a value different from 0""" def phiADD(circuit, q, a, N, inv): angle=getAngles(a,N) for i in range(0,N): if inv==0: circuit.u1(angle[i],q[i]) """addition""" else: circuit.u1(-angle[i],q[i]) """subtraction""" """Single controlled version of the phiADD circuit""" def cphiADD(circuit, q, ctl, a, n, inv): angle=getAngles(a,n) for i in range(0,n): if inv==0: circuit.cu1(angle[i],ctl,q[i]) else: circuit.cu1(-angle[i],ctl,q[i]) """Doubly controlled version of the phiADD circuit""" def ccphiADD(circuit,q,ctl1,ctl2,a,n,inv): angle=getAngles(a,n) for i in range(0,n): if inv==0: ccphase(circuit,angle[i],ctl1,ctl2,q[i]) else: ccphase(circuit,-angle[i],ctl1,ctl2,q[i]) """Circuit that implements doubly controlled modular addition by a""" def ccphiADDmodN(circuit, q, ctl1, ctl2, aux, a, N, n): ccphiADD(circuit, q, ctl1, ctl2, a, n, 0) phiADD(circuit, q, N, n, 1) create_inverse_QFT(circuit, q, n, 0) circuit.cx(q[n-1],aux) create_QFT(circuit,q,n,0) cphiADD(circuit, q, aux, N, n, 0) ccphiADD(circuit, q, ctl1, ctl2, a, n, 1) create_inverse_QFT(circuit, q, n, 0) circuit.x(q[n-1]) circuit.cx(q[n-1], aux) circuit.x(q[n-1]) create_QFT(circuit,q,n,0) ccphiADD(circuit, q, ctl1, ctl2, a, n, 0) """Circuit that implements the inverse of doubly controlled modular addition by a""" def ccphiADDmodN_inv(circuit, q, ctl1, ctl2, aux, a, N, n): ccphiADD(circuit, q, ctl1, ctl2, a, n, 1) create_inverse_QFT(circuit, q, n, 0) circuit.x(q[n-1]) circuit.cx(q[n-1],aux) circuit.x(q[n-1]) create_QFT(circuit, q, n, 0) ccphiADD(circuit, q, ctl1, ctl2, a, n, 0) cphiADD(circuit, q, aux, N, n, 1) create_inverse_QFT(circuit, q, n, 0) circuit.cx(q[n-1], aux) create_QFT(circuit, q, n, 0) phiADD(circuit, q, N, n, 0) ccphiADD(circuit, q, ctl1, ctl2, a, n, 1) """Circuit that implements single controlled modular multiplication by a""" def cMULTmodN(circuit, ctl, q, aux, a, N, n): create_QFT(circuit,aux,n+1,0) for i in range(0, n): ccphiADDmodN(circuit, aux, q[i], ctl, aux[n+1], (2**i)*a % N, N, n+1) create_inverse_QFT(circuit, aux, n+1, 0) for i in range(0, n): circuit.cswap(ctl,q[i],aux[i]) a_inv = modinv(a, N) create_QFT(circuit, aux, n+1, 0) i = n-1 while i >= 0: ccphiADDmodN_inv(circuit, aux, q[i], ctl, aux[n+1], math.pow(2,i)*a_inv % N, N, n+1) i -= 1 create_inverse_QFT(circuit, aux, n+1, 0)
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
""" This is the final implementation of Shor's Algorithm using the circuit presented in section 2.3 of the report about the first simplification introduced by the base paper used. As the circuit is completely general, it is a rather long circuit, with a lot of QASM instructions in the generated Assembly code, which makes that for high values of N the code is not able to run in IBM Q Experience because IBM has a very low restriction on the number os QASM instructions it can run. For N=15, it can run on IBM. But, for example, for N=21 it already may not, because it exceeds the restriction of QASM instructions. The user can try to use n qubits on top register instead of 2n to get more cases working on IBM. This will, however and naturally, diminish the probabilty of success. For a small number of qubits (about until 20), the code can be run on a local simulator. This makes it to be a little slow even for the factorization of small numbers N. Because of this, although all is general and we ask the user to introduce the number N and if he agrees with the 'a' value selected or not, we after doing that force N=15 and a=4, because that is a case where the simulation, although slow, can be run in local simulator and does not last 'forever' to end. If the user wants he can just remove the 2 lines of code where that is done, and put bigger N (that will be slow) or can try to run on the ibm simulator (for that, the user should introduce its IBM Q Experience Token and be aware that for high values of N it will just receive a message saying the size of the circuit is too big) """ """ Imports from qiskit""" from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute, IBMQ from qiskit import BasicAer import sys """ Imports to Python functions """ import math import array import fractions import numpy as np import time """ Local Imports """ from cfunctions import check_if_power, get_value_a from cfunctions import get_factors from qfunctions import create_QFT, create_inverse_QFT from qfunctions import cMULTmodN """ Main program """ if __name__ == '__main__': """ Ask for analysis number N """ N = int(input('Please insert integer number N: ')) print('input number was: {0}\n'.format(N)) """ Check if N==1 or N==0""" if N==1 or N==0: print('Please put an N different from 0 and from 1') exit() """ Check if N is even """ if (N%2)==0: print('N is even, so does not make sense!') exit() """ Check if N can be put in N=p^q, p>1, q>=2 """ """ Try all numbers for p: from 2 to sqrt(N) """ if check_if_power(N)==True: exit() print('Not an easy case, using the quantum circuit is necessary\n') """ To login to IBM Q experience the following functions should be called """ """ IBMQ.delete_accounts() IBMQ.save_account('insert token here') IBMQ.load_accounts() """ """ Get an integer a that is coprime with N """ a = get_value_a(N) """ If user wants to force some values, he can do that here, please make sure to update the print and that N and a are coprime""" print('Forcing N=15 and a=4 because its the fastest case, please read top of source file for more info') N=15 a=4 """ Get n value used in Shor's algorithm, to know how many qubits are used """ n = math.ceil(math.log(N,2)) print('Total number of qubits used: {0}\n'.format(4*n+2)) ts = time.time() """ Create quantum and classical registers """ """auxilliary quantum register used in addition and multiplication""" aux = QuantumRegister(n+2) """quantum register where the sequential QFT is performed""" up_reg = QuantumRegister(2*n) """quantum register where the multiplications are made""" down_reg = QuantumRegister(n) """classical register where the measured values of the QFT are stored""" up_classic = ClassicalRegister(2*n) """ Create Quantum Circuit """ circuit = QuantumCircuit(down_reg , up_reg , aux, up_classic) """ Initialize down register to 1 and create maximal superposition in top register """ circuit.h(up_reg) circuit.x(down_reg[0]) """ Apply the multiplication gates as showed in the report in order to create the exponentiation """ for i in range(0, 2*n): cMULTmodN(circuit, up_reg[i], down_reg, aux, int(pow(a, pow(2, i))), N, n) """ Apply inverse QFT """ create_inverse_QFT(circuit, up_reg, 2*n ,1) """ Measure the top qubits, to get x value""" circuit.measure(up_reg,up_classic) """ show results of circuit creation """ create_time = round(time.time()-ts, 3) #if n < 8: print(circuit) print(f"... circuit creation time = {create_time}") ts = time.time() """ Select how many times the circuit runs""" number_shots=int(input('Number of times to run the circuit: ')) if number_shots < 1: print('Please run the circuit at least one time...') exit() if number_shots > 1: print('\nIf the circuit takes too long to run, consider running it less times\n') """ Print info to user """ print('Executing the circuit {0} times for N={1} and a={2}\n'.format(number_shots,N,a)) """ Simulate the created Quantum Circuit """ simulation = execute(circuit, backend=BasicAer.get_backend('qasm_simulator'),shots=number_shots) """ to run on IBM, use backend=IBMQ.get_backend('ibmq_qasm_simulator') in execute() function """ """ to run locally, use backend=BasicAer.get_backend('qasm_simulator') in execute() function """ """ Get the results of the simulation in proper structure """ sim_result=simulation.result() counts_result = sim_result.get_counts(circuit) """ show execution time """ exec_time = round(time.time()-ts, 3) print(f"... circuit execute time = {exec_time}") """ Print info to user from the simulation results """ print('Printing the various results followed by how many times they happened (out of the {} cases):\n'.format(number_shots)) i=0 while i < len(counts_result): print('Result \"{0}\" happened {1} times out of {2}'.format(list(sim_result.get_counts().keys())[i],list(sim_result.get_counts().values())[i],number_shots)) i=i+1 """ An empty print just to have a good display in terminal """ print(' ') """ Initialize this variable """ prob_success=0 """ For each simulation result, print proper info to user and try to calculate the factors of N""" i=0 while i < len(counts_result): """ Get the x_value from the final state qubits """ output_desired = list(sim_result.get_counts().keys())[i] x_value = int(output_desired, 2) prob_this_result = 100 * ( int( list(sim_result.get_counts().values())[i] ) ) / (number_shots) print("------> Analysing result {0}. This result happened in {1:.4f} % of all cases\n".format(output_desired,prob_this_result)) """ Print the final x_value to user """ print('In decimal, x_final value for this result is: {0}\n'.format(x_value)) """ Get the factors using the x value obtained """ success=get_factors(int(x_value),int(2*n),int(N),int(a)) if success==True: prob_success = prob_success + prob_this_result i=i+1 print("\nUsing a={0}, found the factors of N={1} in {2:.4f} % of the cases\n".format(a,N,prob_success))
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
""" This is the final implementation of Shor's Algorithm using the circuit presented in section 2.3 of the report about the second simplification introduced by the base paper used. The circuit is general, so, in a good computer that can support simulations infinite qubits, it can factorize any number N. The only limitation is the capacity of the computer when running in local simulator and the limits on the IBM simulator (in the number of qubits and in the number of QASM instructions the simulations can have when sent to IBM simulator). The user may try N=21, which is an example that runs perfectly fine even just in local simulator because, as in explained in report, this circuit, because implements the QFT sequentially, uses less qubits then when using a "normal"n QFT. """ """ Imports from qiskit""" from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute, IBMQ from qiskit import BasicAer import sys """ Imports to Python functions """ import math import array import fractions import numpy as np import time """ Local Imports """ from cfunctions import check_if_power, get_value_a from cfunctions import get_factors from qfunctions import create_QFT, create_inverse_QFT from qfunctions import getAngle, cMULTmodN """ Main program """ if __name__ == '__main__': """ Ask for analysis number N """ N = int(input('Please insert integer number N: ')) print('input number was: {0}\n'.format(N)) """ Check if N==1 or N==0""" if N==1 or N==0: print('Please put an N different from 0 and from 1') exit() """ Check if N is even """ if (N%2)==0: print('N is even, so does not make sense!') exit() """ Check if N can be put in N=p^q, p>1, q>=2 """ """ Try all numbers for p: from 2 to sqrt(N) """ if check_if_power(N)==True: exit() print('Not an easy case, using the quantum circuit is necessary\n') """ To login to IBM Q experience the following functions should be called """ """ IBMQ.delete_accounts() IBMQ.save_account('insert token here') IBMQ.load_accounts()""" """ Get an integer a that is coprime with N """ a = get_value_a(N) """ If user wants to force some values, can do that here, please make sure to update print and that N and a are coprime""" """print('Forcing N=15 and a=4 because its the fastest case, please read top of source file for more info') N=15 a=2""" """ Get n value used in Shor's algorithm, to know how many qubits are used """ n = math.ceil(math.log(N,2)) print('Total number of qubits used: {0}\n'.format(2*n+3)) ts = time.time() """ Create quantum and classical registers """ """auxilliary quantum register used in addition and multiplication""" aux = QuantumRegister(n+2) """single qubit where the sequential QFT is performed""" up_reg = QuantumRegister(1) """quantum register where the multiplications are made""" down_reg = QuantumRegister(n) """classical register where the measured values of the sequential QFT are stored""" up_classic = ClassicalRegister(2*n) """classical bit used to reset the state of the top qubit to 0 if the previous measurement was 1""" c_aux = ClassicalRegister(1) """ Create Quantum Circuit """ circuit = QuantumCircuit(down_reg , up_reg , aux, up_classic, c_aux) """ Initialize down register to 1""" circuit.x(down_reg[0]) """ Cycle to create the Sequential QFT, measuring qubits and applying the right gates according to measurements """ for i in range(0, 2*n): """reset the top qubit to 0 if the previous measurement was 1""" circuit.x(up_reg).c_if(c_aux, 1) circuit.h(up_reg) cMULTmodN(circuit, up_reg[0], down_reg, aux, a**(2**(2*n-1-i)), N, n) """cycle through all possible values of the classical register and apply the corresponding conditional phase shift""" for j in range(0, 2**i): """the phase shift is applied if the value of the classical register matches j exactly""" circuit.u1(getAngle(j, i), up_reg[0]).c_if(up_classic, j) circuit.h(up_reg) circuit.measure(up_reg[0], up_classic[i]) circuit.measure(up_reg[0], c_aux[0]) """ show results of circuit creation """ create_time = round(time.time()-ts, 3) #if n < 8: print(circuit) print(f"... circuit creation time = {create_time}") ts = time.time() """ Select how many times the circuit runs""" number_shots=int(input('Number of times to run the circuit: ')) if number_shots < 1: print('Please run the circuit at least one time...') exit() """ Print info to user """ print('Executing the circuit {0} times for N={1} and a={2}\n'.format(number_shots,N,a)) """ Simulate the created Quantum Circuit """ simulation = execute(circuit, backend=BasicAer.get_backend('qasm_simulator'),shots=number_shots) """ to run on IBM, use backend=IBMQ.get_backend('ibmq_qasm_simulator') in execute() function """ """ to run locally, use backend=BasicAer.get_backend('qasm_simulator') in execute() function """ """ Get the results of the simulation in proper structure """ sim_result=simulation.result() counts_result = sim_result.get_counts(circuit) """ show execution time """ exec_time = round(time.time()-ts, 3) print(f"... circuit execute time = {exec_time}") """ Print info to user from the simulation results """ print('Printing the various results followed by how many times they happened (out of the {} cases):\n'.format(number_shots)) i=0 while i < len(counts_result): print('Result \"{0}\" happened {1} times out of {2}'.format(list(sim_result.get_counts().keys())[i],list(sim_result.get_counts().values())[i],number_shots)) i=i+1 """ An empty print just to have a good display in terminal """ print(' ') """ Initialize this variable """ prob_success=0 """ For each simulation result, print proper info to user and try to calculate the factors of N""" i=0 while i < len(counts_result): """ Get the x_value from the final state qubits """ all_registers_output = list(sim_result.get_counts().keys())[i] output_desired = all_registers_output.split(" ")[1] x_value = int(output_desired, 2) prob_this_result = 100 * ( int( list(sim_result.get_counts().values())[i] ) ) / (number_shots) print("------> Analysing result {0}. This result happened in {1:.4f} % of all cases\n".format(output_desired,prob_this_result)) """ Print the final x_value to user """ print('In decimal, x_final value for this result is: {0}\n'.format(x_value)) """ Get the factors using the x value obtained """ success = get_factors(int(x_value),int(2*n),int(N),int(a)) if success==True: prob_success = prob_success + prob_this_result i=i+1 print("\nUsing a={0}, found the factors of N={1} in {2:.4f} % of the cases\n".format(a,N,prob_success))
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
""" This file allows to test the Multiplication blocks Ua. This blocks, when put together as explain in the report, do the exponentiation. The user can change N, n, a and the input state, to create the circuit: up_reg |+> ---------------------|----------------------- |+> | | | -------|--------- ------------ | | ------------ down_reg |x> ------------ | Mult | ------------ |(x*a) mod N> ------------ | | ------------ ----------------- Where |x> has n qubits and is the input state, the user can change it to whatever he wants This file uses as simulator the local simulator 'statevector_simulator' because this simulator saves the quantum state at the end of the circuit, which is exactly the goal of the test file. This simulator supports sufficient qubits to the size of the QFTs that are going to be used in Shor's Algorithm because the IBM simulator only supports up to 32 qubits """ """ Imports from qiskit""" from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute, IBMQ, BasicAer """ Imports to Python functions """ import math import time """ Local Imports """ from qfunctions import create_QFT, create_inverse_QFT from qfunctions import cMULTmodN """ Function to properly get the final state, it prints it to user """ """ This is only possible in this way because the program uses the statevector_simulator """ def get_final(results, number_aux, number_up, number_down): i=0 """ Get total number of qubits to go through all possibilities """ total_number = number_aux + number_up + number_down max = pow(2,total_number) print('|aux>|top_register>|bottom_register>\n') while i<max: binary = bin(i)[2:].zfill(total_number) number = results.item(i) number = round(number.real, 3) + round(number.imag, 3) * 1j """ If the respective state is not zero, then print it and store the state of the register where the result we are looking for is. This works because that state is the same for every case where number !=0 """ if number!=0: print('|{0}>|{1}>|{2}>'.format(binary[0:number_aux],binary[number_aux:(number_aux+number_up)],binary[(number_aux+number_up):(total_number)]),number) if binary[number_aux:(number_aux+number_up)]=='1': store = binary[(number_aux+number_up):(total_number)] i=i+1 print(' ') return int(store, 2) """ Main program """ if __name__ == '__main__': """ Select number N to do modN""" N = int(input('Please insert integer number N: ')) print(' ') """ Get n value used in QFT, to know how many qubits are used """ n = math.ceil(math.log(N,2)) """ Select the value for 'a' """ a = int(input('Please insert integer number a: ')) print(' ') """ Please make sure the a and N are coprime""" if math.gcd(a,N)!=1: print('Please make sure the a and N are coprime. Exiting program.') exit() print('Total number of qubits used: {0}\n'.format(2*n+3)) print('Please check source file to change input quantum state. By default is |2>.\n') ts = time.time() """ Create quantum and classical registers """ aux = QuantumRegister(n+2) up_reg = QuantumRegister(1) down_reg = QuantumRegister(n) aux_classic = ClassicalRegister(n+2) up_classic = ClassicalRegister(1) down_classic = ClassicalRegister(n) """ Create Quantum Circuit """ circuit = QuantumCircuit(down_reg , up_reg , aux, down_classic, up_classic, aux_classic) """ Initialize with |+> to also check if the control is working""" circuit.h(up_reg[0]) """ Put the desired input state in the down quantum register. By default we put |2> """ circuit.x(down_reg[1]) """ Apply multiplication""" cMULTmodN(circuit, up_reg[0], down_reg, aux, int(a), N, n) """ show results of circuit creation """ create_time = round(time.time()-ts, 3) if n < 8: print(circuit) print(f"... circuit creation time = {create_time}") ts = time.time() """ Simulate the created Quantum Circuit """ simulation = execute(circuit, backend=BasicAer.get_backend('statevector_simulator'),shots=1) """ Get the results of the simulation in proper structure """ sim_result=simulation.result() """ Get the statevector of the final quantum state """ outputstate = sim_result.get_statevector(circuit, decimals=3) """ Show the final state after the multiplication """ after_exp = get_final(outputstate, n+2, 1, n) """ show execution time """ exec_time = round(time.time()-ts, 3) print(f"... circuit execute time = {exec_time}") """ Print final quantum state to user """ print('When control=1, value after exponentiation is in bottom quantum register: |{0}>'.format(after_exp))
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
""" This file allows to test the various QFT implemented. The user must specify: 1) The number of qubits it wants the QFT to be implemented on 2) The kind of QFT want to implement, among the options: -> Normal QFT with SWAP gates at the end -> Normal QFT without SWAP gates at the end -> Inverse QFT with SWAP gates at the end -> Inverse QFT without SWAP gates at the end The user must can also specify, in the main function, the input quantum state. By default is a maximal superposition state This file uses as simulator the local simulator 'statevector_simulator' because this simulator saves the quantum state at the end of the circuit, which is exactly the goal of the test file. This simulator supports sufficient qubits to the size of the QFTs that are going to be used in Shor's Algorithm because the IBM simulator only supports up to 32 qubits """ """ Imports from qiskit""" from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute, IBMQ, BasicAer """ Imports to Python functions """ import time """ Local Imports """ from qfunctions import create_QFT, create_inverse_QFT """ Function to properly print the final state of the simulation """ """ This is only possible in this way because the program uses the statevector_simulator """ def show_good_coef(results, n): i=0 max = pow(2,n) if max > 100: max = 100 """ Iterate to all possible states """ while i<max: binary = bin(i)[2:].zfill(n) number = results.item(i) number = round(number.real, 3) + round(number.imag, 3) * 1j """ Print the respective component of the state if it has a non-zero coefficient """ if number!=0: print('|{}>'.format(binary),number) i=i+1 """ Main program """ if __name__ == '__main__': """ Select how many qubits want to apply the QFT on """ n = int(input('\nPlease select how many qubits want to apply the QFT on: ')) """ Select the kind of QFT to apply using the variable what_to_test: what_to_test = 0: Apply normal QFT with the SWAP gates at the end what_to_test = 1: Apply normal QFT without the SWAP gates at the end what_to_test = 2: Apply inverse QFT with the SWAP gates at the end what_to_test = 3: Apply inverse QFT without the SWAP gates at the end """ print('\nSelect the kind of QFT to apply:') print('Select 0 to apply normal QFT with the SWAP gates at the end') print('Select 1 to apply normal QFT without the SWAP gates at the end') print('Select 2 to apply inverse QFT with the SWAP gates at the end') print('Select 3 to apply inverse QFT without the SWAP gates at the end\n') what_to_test = int(input('Select your option: ')) if what_to_test<0 or what_to_test>3: print('Please select one of the options') exit() print('\nTotal number of qubits used: {0}\n'.format(n)) print('Please check source file to change input quantum state. By default is a maximal superposition state with |+> in every qubit.\n') ts = time.time() """ Create quantum and classical registers """ quantum_reg = QuantumRegister(n) classic_reg = ClassicalRegister(n) """ Create Quantum Circuit """ circuit = QuantumCircuit(quantum_reg, classic_reg) """ Create the input state desired Please change this as you like, by default we put H gates in every qubit, initializing with a maximimal superposition state """ #circuit.h(quantum_reg) """ Test the right QFT according to the variable specified before""" if what_to_test == 0: create_QFT(circuit,quantum_reg,n,1) elif what_to_test == 1: create_QFT(circuit,quantum_reg,n,0) elif what_to_test == 2: create_inverse_QFT(circuit,quantum_reg,n,1) elif what_to_test == 3: create_inverse_QFT(circuit,quantum_reg,n,0) else: print('Noting to implement, exiting program') exit() """ show results of circuit creation """ create_time = round(time.time()-ts, 3) if n < 8: print(circuit) print(f"... circuit creation time = {create_time}") ts = time.time() """ Simulate the created Quantum Circuit """ simulation = execute(circuit, backend=BasicAer.get_backend('statevector_simulator'),shots=1) """ Get the results of the simulation in proper structure """ sim_result=simulation.result() """ Get the statevector of the final quantum state """ outputstate = sim_result.get_statevector(circuit, decimals=3) """ show execution time """ exec_time = round(time.time()-ts, 3) print(f"... circuit execute time = {exec_time}") """ Print final quantum state to user """ print('The final state after applying the QFT is:\n') show_good_coef(outputstate,n)
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
""" Shor's Factoring Algorithm Benchmark - Qiskit """ import sys sys.path[1:1] = ["_common", "_common/qiskit", "shors/_common", "quantum-fourier-transform/qiskit"] sys.path[1:1] = ["../../_common", "../../_common/qiskit", "../../shors/_common", "../../quantum-fourier-transform/qiskit"] from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister import math from math import gcd from fractions import Fraction import time import random import numpy as np np.random.seed(0) import execute as ex import metrics as metrics from qft_benchmark import inv_qft_gate from qft_benchmark import qft_gate import copy from utils import getAngles, getAngle, modinv, generate_numbers, choose_random_base, determine_factors verbose = True ############### Circuit Definition # Creation of the circuit that performs addition by a in Fourier Space # Can also be used for subtraction by setting the parameter inv to a value different from 0 def phiADD(num_qubits, a): qc = QuantumCircuit(num_qubits, name="\u03C6ADD") angle = getAngles(a, num_qubits) for i in range(0, num_qubits): # addition qc.u1(angle[i], i) global PHIADD_ if PHIADD_ == None or num_qubits <= 3: if num_qubits < 4: PHIADD_ = qc return qc # Single controlled version of the phiADD circuit def cphiADD(num_qubits, a): phiadd_gate = phiADD(num_qubits, a).to_gate() cphiadd_gate = phiadd_gate.control(1) return cphiadd_gate # Doubly controlled version of the phiADD circuit def ccphiADD(num_qubits, a): phiadd_gate = phiADD(num_qubits, a).to_gate() ccphiadd_gate = phiadd_gate.control(2) return ccphiadd_gate # Circuit that implements doubly controlled modular addition by a (num qubits should be bit count for number N) def ccphiADDmodN(num_qubits, a, N): qr_ctl = QuantumRegister(2) qr_main = QuantumRegister(num_qubits + 1) qr_ancilla = QuantumRegister(1) qc = QuantumCircuit(qr_ctl, qr_main, qr_ancilla, name="cc\u03C6ADDmodN") # Generate relevant gates for circuit ccphiadda_gate = ccphiADD(num_qubits + 1, a) ccphiadda_inv_gate = ccphiADD(num_qubits + 1, a).inverse() phiaddN_inv_gate = phiADD(num_qubits + 1, N).inverse() cphiaddN_gate = cphiADD(num_qubits + 1, N) # Create relevant temporary qubit lists ctl_main_qubits = [i for i in qr_ctl]; ctl_main_qubits.extend([i for i in qr_main]) anc_main_qubits = [qr_ancilla[0]]; anc_main_qubits.extend([i for i in qr_main]) # Create circuit qc.append(ccphiadda_gate, ctl_main_qubits) qc.append(phiaddN_inv_gate, qr_main) qc.append(inv_qft_gate(num_qubits + 1), qr_main) qc.cx(qr_main[-1], qr_ancilla[0]) qc.append(qft_gate(num_qubits + 1), qr_main) qc.append(cphiaddN_gate, anc_main_qubits) qc.append(ccphiadda_inv_gate, ctl_main_qubits) qc.append(inv_qft_gate(num_qubits + 1), qr_main) qc.x(qr_main[-1]) qc.cx(qr_main[-1], qr_ancilla[0]) qc.x(qr_main[-1]) qc.append(qft_gate(num_qubits + 1), qr_main) qc.append(ccphiadda_gate, ctl_main_qubits) global CCPHIADDMODN_ if CCPHIADDMODN_ == None or num_qubits <= 2: if num_qubits < 3: CCPHIADDMODN_ = qc return qc # Circuit that implements the inverse of doubly controlled modular addition by a def ccphiADDmodN_inv(num_qubits, a, N): cchpiAddmodN_circ = ccphiADDmodN(num_qubits, a, N) cchpiAddmodN_inv_circ = cchpiAddmodN_circ.inverse() return cchpiAddmodN_inv_circ # Creates circuit that implements single controlled modular multiplication by a. n represents the number of bits # needed to represent the integer number N def cMULTamodN(n, a, N): qr_ctl = QuantumRegister(1) qr_x = QuantumRegister(n) qr_main = QuantumRegister(n + 1) qr_ancilla = QuantumRegister(1) qc = QuantumCircuit(qr_ctl, qr_x, qr_main, qr_ancilla, name="cMULTamodN") # quantum Fourier transform only on auxillary qubits qc.append(qft_gate(n + 1), qr_main) for i in range(n): ccphiADDmodN_gate = ccphiADDmodN(n, (2 ** i) * a % N, N) # Create relevant temporary qubit list qubits = [qr_ctl[0]]; qubits.extend([qr_x[i]]) qubits.extend([i for i in qr_main]); qubits.extend([qr_ancilla[0]]) qc.append(ccphiADDmodN_gate, qubits) # inverse quantum Fourier transform only on auxillary qubits qc.append(inv_qft_gate(n + 1), qr_main) global CMULTAMODN_ if CMULTAMODN_ == None or n <= 2: if n < 3: CMULTAMODN_ = qc return qc # Creates circuit that implements single controlled Ua gate. n represents the number of bits # needed to represent the integer number N def controlled_Ua(n, a, exponent, N): qr_ctl = QuantumRegister(1) qr_x = QuantumRegister(n) qr_main = QuantumRegister(n) qr_ancilla = QuantumRegister(2) qc = QuantumCircuit(qr_ctl, qr_x, qr_main, qr_ancilla, name=f"C-U^{a}^{exponent}") # Generate Gates a_inv = modinv(a ** exponent, N) cMULTamodN_gate = cMULTamodN(n, a ** exponent, N) cMULTamodN_inv_gate = cMULTamodN(n, a_inv, N).inverse() # Create relevant temporary qubit list qubits = [i for i in qr_ctl]; qubits.extend([i for i in qr_x]); qubits.extend([i for i in qr_main]) qubits.extend([i for i in qr_ancilla]) qc.append(cMULTamodN_gate, qubits) for i in range(n): qc.cswap(qr_ctl, qr_x[i], qr_main[i]) qc.append(cMULTamodN_inv_gate, qubits) global CUA_ if CUA_ == None or n <= 2: if n < 3: CUA_ = qc return qc # Execute Shor's Order Finding Algorithm given a 'number' to factor, # the 'base' of exponentiation, and the number of qubits required 'input_size' def ShorsAlgorithm(number, base, method, verbose=verbose): # Create count of qubits to use to represent the number to factor # NOTE: this should match the number of bits required to represent (number) n = int(math.ceil(math.log(number, 2))) # this will hold the 2n measurement results measurements = [0] * (2 * n) # Standard Shors Algorithm if method == 1: num_qubits = 4 * n + 2 if verbose: print( f"... running Shors to factor number [ {number} ] with base={base} using num_qubits={n}") # Create a circuit and allocate necessary qubits qr_up = QuantumRegister(2 * n) # Register for sequential QFT qr_down = QuantumRegister(n) # Register for multiplications qr_aux = QuantumRegister(n + 2) # Register for addition and multiplication cr_data = ClassicalRegister(2 * n) # Register for measured values of QFT qc = QuantumCircuit(qr_up, qr_down, qr_aux, cr_data, name="main") # Initialize down register to 1 and up register to superposition state qc.h(qr_up) qc.x(qr_down[0]) qc.barrier() # Apply Multiplication Gates for exponentiation for i in range(2 * n): cUa_gate = controlled_Ua(n, int(base), 2 ** i, number) # Create relevant temporary qubit list qubits = [qr_up[i]]; qubits.extend([i for i in qr_down]); qubits.extend([i for i in qr_aux]) qc.append(cUa_gate, qubits) qc.barrier() i = 0 while i < ((qr_up.size - 1) / 2): qc.swap(qr_up[i], qr_up[2 * n - 1 - i]) i = i + 1 qc.append(inv_qft_gate(2 * n), qr_up) # Measure up register qc.measure(qr_up, cr_data) elif method == 2: # Create a circuit and allocate necessary qubits num_qubits = 2 * n + 3 if verbose: print(f"... running Shors to factor number [ {number} ] with base={base} using num_qubits={n}") qr_up = QuantumRegister(1) # Single qubit for sequential QFT qr_down = QuantumRegister(n) # Register for multiplications qr_aux = QuantumRegister(n + 2) # Register for addition and multiplication cr_data = ClassicalRegister(2 * n) # Register for measured values of QFT cr_aux = ClassicalRegister(1) # Register to reset the state of the up register based on previous measurements qc = QuantumCircuit(qr_down, qr_up, qr_aux, cr_data, cr_aux, name="main") # Initialize down register to 1 qc.x(qr_down[0]) # perform modular exponentiation 2*n times for k in range(2 * n): # one iteration of 1-qubit QPE # Reset the top qubit to 0 if the previous measurement was 1 qc.x(qr_up).c_if(cr_aux, 1) qc.h(qr_up) cUa_gate = controlled_Ua(n, base ** (2 ** (2 * n - 1 - k)), number) qc.append(cUa_gate, [qr_up[0], qr_down, qr_aux]) # perform inverse QFT --> Rotations conditioned on previous outcomes for i in range(2 ** k): qc.u1(getAngle(i, k), qr_up[0]).c_if(cr_data, i) qc.h(qr_up) qc.measure(qr_up[0], cr_data[k]) qc.measure(qr_up[0], cr_aux[0]) global QC_, QFT_ if QC_ == None or n <= 2: if n < 3: QC_ = qc if QFT_ == None or n <= 2: if n < 3: QFT_ = qft_gate(n + 1) # turn the measured values into a number in [0,1) by summing their binary values ma = [(measurements[2 * n - 1 - i]*1. / (1 << (i + 1))) for i in range(2 * n)] y = sum(ma) y = 0.833 # continued fraction expansion to get denominator (the period?) r = Fraction(y).limit_denominator(number - 1).denominator f = Fraction(y).limit_denominator(number - 1) if verbose: print(f" ... y = {y} fraction = {f.numerator} / {f.denominator} r = {f.denominator}") # return the (potential) period return r # DEVNOTE: need to resolve this; currently not using the standard 'execute module' # measure and flush are taken care of in other methods; do not add here return qc # Execute Shor's Factoring Algorithm given a 'number' to factor, # the 'base' of exponentiation, and the number of qubits required 'input_size' # Filter function, which defines the gate set for the first optimization # (don't decompose QFTs and iQFTs to make cancellation easier) ''' def high_level_gates(eng, cmd): g = cmd.gate if g == QFT or get_inverse(g) == QFT or g == Swap: return True if isinstance(g, BasicMathGate): #return False return True print("***************** should never get here !") if isinstance(g, AddConstant): return True elif isinstance(g, AddConstantModN): return True return False return eng.next_engine.is_available(cmd) ''' # Attempt to execute Shor's Algorithm to find factors, up to a max number of tries # Returns number of failures, 0 if success def attempt_factoring(input_size, number, verbose): max_tries = 5 trials = 0 failures = 0 while trials < max_tries: trials += 1 # choose a base at random base = choose_random_base(number) if base == 0: break # execute the algorithm which determines the period given this base r = ShorsAlgorithm(input_size, number, base, verbose=verbose) # try to determine the factors from the period 'r' f1, f2 = determine_factors(r, base, number) # Success! if these are the factors and both are greater than 1 if (f1 * f2) == number and f1 > 1 and f2 > 1: if verbose: print(f" ==> Factors found :-) : {f1} * {f2} = {number}") break else: failures += 1 if verbose: print(f" ==> Bad luck: Found {f1} and {f2} which are not the factors") print(f" ... trying again ...") return failures ############### Circuit end # Print analyzed results # Analyze and print measured results # Expected result is always the secret_int, so fidelity calc is simple def analyze_and_print_result(qc, result, num_qubits, marked_item, num_shots): if verbose: print(f"For marked item {marked_item} measured: {result}") key = format(marked_item, f"0{num_qubits}b")[::-1] fidelity = result[key] return fidelity # Define custom result handler def execution_handler(result, num_qubits, number, num_shots): # determine fidelity of result set num_qubits = int(num_qubits) fidelity = analyze_and_print_result(result, num_qubits - 1, int(number), num_shots) metrics.store_metric(num_qubits, number, 'fidelity', fidelity) #################### Benchmark Loop # Execute program with default parameters def run(min_qubits=5, max_circuits=3, max_qubits=10, num_shots=100, verbose=verbose, interactive=False, backend_id='qasm_simulator', provider_backend=None, hub="ibm-q", group="open", project="main"): print("Shor's Factoring Algorithm Benchmark - Qiskit") # Generate array of numbers to factor numbers = generate_numbers() min_qubits = max(min_qubits, 5) # need min of 5 max_qubits = max(max_qubits, min_qubits) # max must be >= min max_qubits = min(max_qubits, len(numbers)) # max cannot exceed available numbers # Initialize metrics module metrics.init_metrics() # 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) if interactive: do_interactive_test(verbose=verbose) return; # Execute Benchmark Program N times for multiple circuit sizes # Accumulate metrics asynchronously as circuits complete for num_qubits in range(min_qubits, max_qubits + 1): input_size = num_qubits - 1 # determine number of circuits to execute for this group num_circuits = min(2 ** (input_size), max_circuits) print( f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}, input_size = {input_size}") ##print(f"... choices at {input_size} = {numbers[input_size]}") # determine array of numbers to factor numbers_to_factor = np.random.choice(numbers[input_size], num_circuits, False) ##print(f"... numbers = {numbers_to_factor}") # Number of times the factoring attempts failed for each qubit size failures = 0 # loop over all of the numbers to factor for number in numbers_to_factor: # convert from np form (created by np.random) number = int(number) # create the circuit for given qubit size and secret string, store time metric ts = time.time() # not currently used # n_iterations = int(np.pi * np.sqrt(2 ** input_size) / 4) # attempt to execute Shor's Algorithm to find factors failures += attempt_factoring(input_size, number, verbose) metrics.store_metric(num_qubits, number, 'create_time', time.time() - ts) metrics.store_metric(num_qubits, number, 'exec_time', time.time() - ts) # submit circuit for execution on target (simulator, cloud simulator, or hardware) # ex.submit_circuit(eng, qureg, num_qubits, number, num_shots) # Report how many factoring failures occurred if failures > 0: print(f"*** Factoring attempts failed {failures} times!") # execute all circuits for this group, aggregate and report metrics when complete # ex.execute_circuits() metrics.aggregate_metrics_for_group(num_qubits) metrics.report_metrics_for_group(num_qubits) # Alternatively, execute all circuits, aggregate and report metrics # ex.execute_circuits() # metrics.aggregate_metrics_for_group(num_qubits) # metrics.report_metrics_for_group(num_qubits) # print the last circuit created # print(qc) # Plot metrics for all circuit sizes metrics.plot_metrics("Benchmark Results - Shor's Factoring Algorithm - Qiskit") # For interactive_shors_factoring testing def do_interactive_test(verbose): done = False while not done: s = input('\nEnter the number to factor: ') if len(s) < 1: break number = int(s) print(f"Factoring number = {number}\n") input_size = int(math.ceil(math.log(number, 2))) # attempt to execute Shor's Algorithm to find factors failures = attempt_factoring(input_size, number, verbose) # Report how many factoring failures occurred if failures > 0: print(f"*** Factoring attempts failed {failures} times!") print("... exiting") # if main, execute method if __name__ == '__main__': run() # max_qubits = 6, max_circuits = 5, num_shots=100)
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/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
import sys sys.path[1:1] = ["_common", "_common/qiskit"] sys.path[1:1] = ["../../_common", "../../_common/qiskit"] from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister import time import math import os import numpy as np np.random.seed(0) import execute as ex import metrics as metrics from collections import defaultdict from qiskit_nature.drivers import PySCFDriver, UnitsType, Molecule from qiskit_nature.circuit.library import HartreeFock as HF from qiskit_nature.problems.second_quantization.electronic import ElectronicStructureProblem from qiskit_nature.mappers.second_quantization import JordanWignerMapper from qiskit_nature.converters.second_quantization import QubitConverter from qiskit_nature.transformers import ActiveSpaceTransformer from qiskit_nature.operators.second_quantization import FermionicOp from qiskit.opflow import PauliTrotterEvolution, CircuitStateFn, Suzuki from qiskit.opflow.primitive_ops import PauliSumOp # 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.getcwd(), f'../qiskit/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.getcwd(), f'../qiskit/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 def VQEEnergy(n_spin_orbs, na, nb, circuit_id=0, method=1): ''' 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 ''' # allocate qubits num_qubits = n_spin_orbs qr = QuantumRegister(num_qubits); cr = ClassicalRegister(num_qubits); qc = QuantumCircuit(qr, cr, name="main") # number of alpha spin orbitals norb_a = int(n_spin_orbs / 2) # number of beta spin orbitals norb_b = norb_a # construct the Hamiltonian qubit_op = ReadHamiltonian(n_spin_orbs) # initialize the HF state qc = HartreeFock(n_spin_orbs, na, nb) # form the list of single and double excitations singles = [] doubles = [] for occ_a in range(na): for vir_a in range(na, norb_a): singles.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): singles.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): doubles.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) # add to ansatz qc.compose(cluster_qc, inplace=True) # method 2, only compute the last term in the Hamiltonian if method == 2: # 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 = [] for p in qubit_op: # get the circuit with expectation measurements qc_with_mea, is_diag = ExpectationCircuit(qc, p, num_qubits) # add to circuit list qc_list.append(qc_with_mea) # diagonal term if is_diag: diag.append(p) # off-diagonal term else: off_diag.append(p) return qc_list def ClusterOperatorCircuit(pauli_op): # 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() # return this circuit return qc # Function that adds expectation measurements to the raw circuits def ExpectationCircuit(qc, pauli, nqubit, method=1): # a flag that tells whether we need to perform rotation need_rotate = False # 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"): need_rotate = True is_diag = False raw_qc.h(target_qubit) elif (p == "Y"): raw_qc.sdg(target_qubit) raw_qc.h(target_qubit) need_rotate = True is_diag = False # perform measurements raw_qc.measure_all() # name of this circuit raw_qc.name = PauliString + " " + str(np.real(coeff)) return raw_qc, is_diag # Function that implements the Hartree-Fock state def HartreeFock(norb, na, nb): # initialize the quantum circuit qc = QuantumCircuit(norb) # alpha electrons for ia in range(na): qc.x(ia) # beta electrons for ib in range(nb): qc.x(ib+int(norb/2)) # return the circuit return qc import json from qiskit import execute, Aer backend = Aer.get_backend("qasm_simulator") precalculated_data = {} def run(min_qubits=4, max_qubits=4, max_circuits=3, num_shots=4092 * 2**8, method=2): print(f"... using circuit method {method}") # validate parameters (smallest circuit is 4 qubits) max_qubits = max(4, max_qubits) min_qubits = min(max(4, min_qubits), max_qubits) if min_qubits % 2 == 1: min_qubits += 1 # min_qubits must be even if method == 1: max_circuits = 1 # 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): # determine the number of circuits to execute fo this group num_circuits = max_circuits num_qubits = input_size # decides number of electrons na = int(num_qubits/4) nb = int(num_qubits/4) # decides number of unoccupied orbitals nvira = int(num_qubits/2) - na nvirb = int(num_qubits/2) - nb # determine the size of t1 and t2 amplitudes t1_size = na * nvira + nb * nvirb t2_size = na * nb * nvira * nvirb # 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: # sample t1 and t2 amplitude t1 = np.random.normal(size=t1_size) t2 = np.random.normal(size=t2_size) # construct all circuits qc_list = VQEEnergy(num_qubits, na, nb, 0, method) else: # loop over circuits for circuit_id in range(num_circuits): # sample t1 and t2 amplitude t1 = np.random.normal(size=t1_size) t2 = np.random.normal(size=t2_size) # 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) print(f"************\nExecuting VQE with num_qubits {num_qubits}") for qc in qc_list: # get circuit id if method == 1: circuit_id = qc.name.split()[0] else: circuit_id = qc.name.split()[2] # collapse the sub-circuits used in this benchmark (for qiskit) qc2 = qc.decompose() # submit circuit for execution on target (simulator, cloud simulator, or hardware) job = execute(qc, backend, shots=num_shots) # executation result result = job.result() # get measurement counts counts = result.get_counts(qc) # initialize empty dictionary dist = {} for key in counts.keys(): prob = counts[key] / num_shots dist[key] = prob # add dist values to precalculated data for use in fidelity calculation precalculated_data[f"{circuit_id}"] = dist with open(f'precalculated_data_qubit_{num_qubits}_method1.json', 'w') as f: f.write(json.dumps( precalculated_data, sort_keys=True, indent=4, separators=(',', ': ') )) run()
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
# (C) Quantum Economic Development Consortium (QED-C) 2021. # Technical Advisory Committee on Standards and Benchmarks (TAC) # # 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. # ########################### # Execute Module - Qiskit # # This module provides a way to submit a series of circuits to be executed in a batch. # When the batch is executed, each circuit is launched as a 'job' to be executed on the target system. # Upon completion, the results from each job are processed in a custom 'result handler' function # in order to calculate metrics such as fidelity. Relevant benchmark metrics are stored for each circuit # execution, so they can be aggregated and presented to the user. # import sys import os import time import copy import importlib import traceback from collections import Counter import logging import numpy as np from datetime import datetime, timedelta from qiskit import execute, Aer, transpile from qiskit.providers.jobstatus import JobStatus # QED-C modules import metrics from metrics import metrics.finalize_group metrics.finalize_group(group) # Noise from qiskit.providers.aer.noise import NoiseModel, ReadoutError from qiskit.providers.aer.noise import depolarizing_error, reset_error ########################## # JOB MANAGEMENT VARIABLES # these are defined globally currently, but will become class variables later #### these variables are currently accessed as globals from user code # maximum number of active jobs max_jobs_active = 3 # job mode: False = wait, True = submit multiple jobs job_mode = False # Print progress of execution verbose = False # Print additional time metrics for each stage of execution verbose_time = False #### the following variables are accessed only through functions ... # Specify whether to execute using sessions (and currently using Sampler only) use_sessions = False # Session counter for use in creating session name session_count = 0 # internal session variables: users do not access session = None sampler = None # IBM-Q Service save here if created service = None # Azure Quantum Provider saved here if created azure_provider = None # logger for this module logger = logging.getLogger(__name__) # Use Aer qasm_simulator by default backend = Aer.get_backend("qasm_simulator") # Execution options, passed to transpile method backend_exec_options = None # Create array of batched circuits and a dict of active circuits batched_circuits = [] active_circuits = {} # Cached transpiled circuit, used for parameterized execution cached_circuits = {} # Configure a handler for processing circuits on completion # user-supplied result handler result_handler = None # Option to compute normalized depth during execution (can disable to reduce overhead in large circuits) use_normalized_depth = True # Option to perform explicit transpile to collect depth metrics # (disabled after first circuit in iterative algorithms) do_transpile_metrics = True # Option to perform transpilation prior to execution # (disabled after first circuit in iterative algorithms) do_transpile_for_execute = True # Intercept function to post-process results result_processor = None width_processor = None # 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 ] ####################### # SUPPORTING CLASSES # class BenchmarkResult is made for sessions runs. This is because # qiskit primitive job result instances don't have a get_counts method # like backend results do. As such, a get counts method is calculated # from the quasi distributions and shots taken. class BenchmarkResult(object): def __init__(self, qiskit_result): super().__init__() self.qiskit_result = qiskit_result self.metadata = qiskit_result.metadata def get_counts(self, qc=0): counts= self.qiskit_result.quasi_dists[0].binary_probabilities() for key in counts.keys(): counts[key] = int(counts[key] * self.qiskit_result.metadata[0]['shots']) return counts # Special Job object class to hold job information for custom executors class Job: local_job = True unique_job_id = 1001 executor_result = None def __init__(self): Job.unique_job_id = Job.unique_job_id + 1 self.this_job_id = Job.unique_job_id def job_id(self): return self.this_job_id def status(self): return JobStatus.DONE def result(self): return self.executor_result ##################### # DEFAULT NOISE MODEL # default noise model, can be overridden using set_noise_model() def default_noise_model(): noise = NoiseModel() # 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.0005 depol_two_qb_error = 0.005 noise.add_all_qubit_quantum_error(depolarizing_error(depol_one_qb_error, 1), ['rx', 'ry', 'rz']) noise.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.add_all_qubit_quantum_error(depolarizing_error(amp_damp_one_qb_error, 1), ['rx', 'ry', 'rz']) noise.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.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.add_all_qubit_readout_error(error_meas) # assign a quantum volume (measured using the values below) noise.QV = 2048 return noise noise = default_noise_model() ###################################################################### # INITIALIZATION METHODS # Initialize the execution module, with a custom result handler def init_execution(handler): global batched_circuits, result_handler batched_circuits.clear() active_circuits.clear() result_handler = handler cached_circuits.clear() # On initialize, always set trnaspilation for metrics and execute to True set_tranpilation_flags(do_transpile_metrics=True, do_transpile_for_execute=True) # Set the backend for execution def set_execution_target(backend_id='qasm_simulator', provider_module_name=None, provider_name=None, provider_backend=None, hub=None, group=None, project=None, exec_options=None, context=None): """ Used to run jobs on a real hardware :param backend_id: device name. List of available devices depends on the provider :param hub: hub identifier, currently "ibm-q" for IBM Quantum, "azure-quantum" for Azure Quantum :param group: group identifier, used with IBM-Q accounts. :param project: project identifier, used with IBM-Q accounts. :param provider_module_name: If using a provider other than IBM-Q, the string of the module that contains the Provider class. For example, for Quantinuum, this would be 'qiskit.providers.quantinuum' :param provider_name: If using a provider other than IBMQ, the name of the provider class. :param context: context for execution, used to create session names For example, for Quantinuum, this would be 'Quantinuum'. :provider_backend: a custom backend object created and passed in, use backend_id as identifier example usage. set_execution_target(backend_id='quantinuum_device_1', provider_module_name='qiskit.providers.quantinuum', provider_name='Quantinuum') """ global backend global session global use_sessions global session_count authentication_error_msg = "No credentials for {0} backend found. Using the simulator instead." # if a custom provider backend is given, use it ... # Note: in this case, the backend_id is an identifier that shows up in plots if provider_backend != None: backend = provider_backend # The hub variable is used to identify an Azure Quantum backend if hub == "azure-quantum": from azure.quantum.job.session import Session, SessionJobFailurePolicy # increment session counter session_count += 1 # create session name if context is not None: session_name = context else: session_name = f"QED-C Benchmark Session {session_count}" if verbose: print(f"... creating session {session_name} on Azure backend {backend_id}") # open a session on the backend session = backend.open_session(name=session_name, job_failure_policy=SessionJobFailurePolicy.CONTINUE) backend.latest_session = session # handle QASM simulator specially elif backend_id == 'qasm_simulator': backend = Aer.get_backend("qasm_simulator") # handle Statevector simulator specially elif backend_id == 'statevector_simulator': backend = Aer.get_backend("statevector_simulator") # handle 'fake' backends here elif 'fake' in backend_id: backend = getattr( importlib.import_module( f'qiskit.providers.fake_provider.backends.{backend_id.split("_")[-1]}.{backend_id}' ), backend_id.title().replace('_', '') ) backend = backend() logger.info(f'Set {backend = }') # otherwise use the given providername or backend_id to find the backend else: # if provider_module name and provider_name are provided, obtain a custom provider if provider_module_name and provider_name: provider = getattr(importlib.import_module(provider_module_name), provider_name) try: # try, since not all custom providers have the .stored_account() method provider.load_account() backend = provider.get_backend(backend_id) except: print(authentication_error_msg.format(provider_name)) # If hub variable indicates an Azure Quantum backend elif hub == "azure-quantum": global azure_provider from azure.quantum.qiskit import AzureQuantumProvider from azure.quantum.job.session import Session, SessionJobFailurePolicy # create an Azure Provider only the first time it is needed if azure_provider is None: if verbose: print("... creating Azure provider") azure_provider = AzureQuantumProvider( resource_id = os.getenv("AZURE_QUANTUM_RESOURCE_ID"), location = os.getenv("AZURE_QUANTUM_LOCATION") ) # List the available backends in the workspace if verbose: print(" Available backends:") for backend in azure_provider.backends(): print(f" {backend}") # increment session counter session_count += 1 # create session name if context is not None: session_name = context else: session_name = f"QED-C Benchmark Session {session_count}" if verbose: print(f"... creating Azure backend {backend_id} and session {session_name}") # then find backend from the backend_id # we should cache this and only change if backend_id changes backend = azure_provider.get_backend(backend_id) # open a session on the backend session = backend.open_session(name=session_name, job_failure_policy=SessionJobFailurePolicy.CONTINUE) backend.latest_session = session # otherwise, assume the backend_id is given only and assume it is IBMQ device else: from qiskit import IBMQ if IBMQ.stored_account(): # load a stored account IBMQ.load_account() # set use_sessions in provided by user - NOTE: this will modify the global setting this_use_sessions = exec_options.get("use_sessions", None) if this_use_sessions != None: use_sessions = this_use_sessions # if use sessions, setup runtime service, Session, and Sampler if use_sessions: from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Session, Options global service global sampler service = QiskitRuntimeService() session_count += 1 backend = service.backend(backend_id) session = Session(service=service, backend=backend_id) # get Sampler resilience level and transpiler optimization level from exec_options options = Options() options.resilience_level = exec_options.get("resilience_level", 1) options.optimization_level = exec_options.get("optimization_level", 3) # special handling for ibmq_qasm_simulator to set noise model if backend_id == "ibmq_qasm_simulator": this_noise = noise # get noise model from options; used only in simulator for now if "noise_model" in exec_options: this_noise = exec_options.get("noise_model", None) if verbose: print(f"... using custom noise model: {this_noise}") # attach to backend if not None if this_noise != None: options.simulator = {"noise_model": this_noise} metrics.QV = this_noise.QV if verbose: print(f"... setting noise model, QV={this_noise.QV} on {backend_id}") if verbose: print(f"... execute using Sampler on backend_id {backend_id} with options = {options}") # create the Qiskit Sampler with these options sampler = Sampler(session=session, options=options) # otherwise, use provider and old style backend # for IBM, create backend from IBMQ provider and given backend_id else: if verbose: print(f"... execute using Circuit Runner on backend_id {backend_id}") provider = IBMQ.get_provider(hub=hub, group=group, project=project) backend = provider.get_backend(backend_id) else: print(authentication_error_msg.format("IBMQ")) # create an informative device name for plots device_name = backend_id metrics.set_plot_subtitle(f"Device = {device_name}") #metrics.set_properties( { "api":"qiskit", "backend_id":backend_id } ) # save execute options with backend global backend_exec_options backend_exec_options = exec_options # Set the state of the transpilation flags def set_tranpilation_flags(do_transpile_metrics = True, do_transpile_for_execute = True): globals()['do_transpile_metrics'] = do_transpile_metrics globals()['do_transpile_for_execute'] = do_transpile_for_execute def set_noise_model(noise_model = None): """ See reference on NoiseModel here https://qiskit.org/documentation/stubs/qiskit.providers.aer.noise.NoiseModel.html Need to pass in a qiskit noise model object, i.e. for amplitude_damping_error: ``` from qiskit.providers.aer.noise import amplitude_damping_error noise = NoiseModel() one_qb_error = 0.005 noise.add_all_qubit_quantum_error(amplitude_damping_error(one_qb_error), ['u1', 'u2', 'u3']) two_qb_error = 0.05 noise.add_all_qubit_quantum_error(amplitude_damping_error(two_qb_error).tensor(amplitude_damping_error(two_qb_error)), ['cx']) set_noise_model(noise_model=noise) ``` Can also be used to remove noisy simulation by setting `noise_model = None`: ``` set_noise_model() ``` """ global noise noise = noise_model # set flag to control use of sessions def set_use_sessions(val = False): global use_sessions use_sessions = val ###################################################################### # CIRCUIT EXECUTION METHODS # Submit circuit for execution # Execute immediately if possible or put into the list of batched circuits def submit_circuit(qc, group_id, circuit_id, shots=100, params=None): # create circuit object with submission time and circuit info circuit = { "qc": qc, "group": str(group_id), "circuit": str(circuit_id), "submit_time": time.time(), "shots": shots, "params": params } if verbose: print(f'... submit circuit - group={circuit["group"]} id={circuit["circuit"]} shots={circuit["shots"]} params={circuit["params"]}') ''' if params != None: for param in params.items(): print(f"{param}") print([param[1] for param in params.items()]) ''' # logger doesn't like unicode, so just log the array values for now #logger.info(f'Submitting circuit - group={circuit["group"]} id={circuit["circuit"]} shots={circuit["shots"]} params={str(circuit["params"])}') logger.info(f'Submitting circuit - group={circuit["group"]} id={circuit["circuit"]} shots={circuit["shots"]} params={[param[1] for param in params.items()] if params else None}') # immediately post the circuit for execution if active jobs < max if len(active_circuits) < max_jobs_active: execute_circuit(circuit) # or just add it to the batch list for execution after others complete else: batched_circuits.append(circuit) if verbose: print(" ... added circuit to batch") # Launch execution of one job (circuit) def execute_circuit(circuit): logging.info('Entering execute_circuit') active_circuit = copy.copy(circuit) active_circuit["launch_time"] = time.time() active_circuit["pollcount"] = 0 shots = circuit["shots"] qc = circuit["qc"] # do the decompose before obtaining circuit metrics so we expand subcircuits to 2 levels # Comment this out here; ideally we'd generalize it here, but it is intended only to # 'flatten out' circuits with subcircuits; we do it in the benchmark code for now so # it only affects circuits with subcircuits (e.g. QFT, AE ...) # qc = qc.decompose() # qc = qc.decompose() # obtain initial circuit metrics qc_depth, qc_size, qc_count_ops, qc_xi, qc_n2q = get_circuit_metrics(qc) # default the normalized transpiled metrics to the same, in case exec fails qc_tr_depth = qc_depth qc_tr_size = qc_size qc_tr_count_ops = qc_count_ops qc_tr_xi = qc_xi; qc_tr_n2q = qc_n2q #print(f"... before tp: {qc_depth} {qc_size} {qc_count_ops}") backend_name = get_backend_name(backend) try: # transpile the circuit to obtain size metrics using normalized basis if do_transpile_metrics and use_normalized_depth: qc_tr_depth, qc_tr_size, qc_tr_count_ops, qc_tr_xi, qc_tr_n2q = transpile_for_metrics(qc) # we want to ignore elapsed time contribution of transpile for metrics (normalized depth) active_circuit["launch_time"] = time.time() # use noise model from execution options if given for simulator this_noise = noise # make a clone of the backend options so we can remove elements that we use, then pass to .run() global backend_exec_options backend_exec_options_copy = copy.copy(backend_exec_options) # get noise model from options; used only in simulator for now if backend_exec_options_copy != None and "noise_model" in backend_exec_options_copy: this_noise = backend_exec_options_copy["noise_model"] #print(f"... using custom noise model: {this_noise}") # extract execution options if set if backend_exec_options_copy == None: backend_exec_options_copy = {} # used in Sampler setup, here remove it for execution this_use_sessions = backend_exec_options_copy.pop("use_sessions", None) resilience_level = backend_exec_options_copy.pop("resilience_level", None) # standard Qiskit transpiler options optimization_level = backend_exec_options_copy.pop("optimization_level", None) layout_method = backend_exec_options_copy.pop("layout_method", None) routing_method = backend_exec_options_copy.pop("routing_method", None) # option to transpile multiple times to find best one transpile_attempt_count = backend_exec_options_copy.pop("transpile_attempt_count", None) # gneeralized transformer method, custom to user transformer = backend_exec_options_copy.pop("transformer", None) global result_processor, width_processor postprocessors = backend_exec_options_copy.pop("postprocessor", None) if postprocessors: result_processor, width_processor = postprocessors ############## # if 'executor' is provided, perform all execution there and return # the executor returns a result object that implements get_counts(qc) executor = None if backend_exec_options_copy != None: executor = backend_exec_options_copy.pop("executor", None) # NOTE: the executor does not perform any other optional processing # Also, the result_handler is called before elapsed_time processing which is not correct if executor: st = time.time() # invoke custom executor function with backend options qc = circuit["qc"] result = executor(qc, backend_name, backend, shots=shots, **backend_exec_options_copy) if verbose_time: print(f" *** executor() time = {round(time.time() - st,4)}") # create a pseudo-job to perform metrics processing upon return job = Job() # store the result object on the job for processing in job_complete job.executor_result = result ############## # normal execution processing is performed here else: logger.info(f"Executing on backend: {backend_name}") #************************************************ # Initiate execution (with noise if specified and this is a simulator backend) if this_noise is not None and not use_sessions and backend_name.endswith("qasm_simulator"): logger.info(f"Performing noisy simulation, shots = {shots}") # if the noise model has associated QV value, copy it to metrics module for plotting if hasattr(this_noise, "QV"): metrics.QV = this_noise.QV simulation_circuits = circuit["qc"] # we already have the noise model, just need to remove it from the options # (only for simulator; for other backends, it is treaded like keyword arg) dummy = backend_exec_options_copy.pop("noise_model", None) # transpile and bind circuit with parameters; use cache if flagged trans_qc = transpile_and_bind_circuit(circuit["qc"], circuit["params"], backend) simulation_circuits = trans_qc # apply transformer pass if provided if transformer: logger.info("applying transformer to noisy simulator") simulation_circuits, shots = invoke_transformer(transformer, trans_qc, backend=backend, shots=shots) # Indicate number of qubits about to be executed if width_processor: width_processor(qc) # for noisy simulator, use execute() which works; # no need for transpile above unless there are options like transformer logger.info(f'Running circuit on noisy simulator, shots={shots}') st = time.time() ''' some circuits, like Grover's behave incorrectly if we use run() job = backend.run(simulation_circuits, shots=shots, noise_model=this_noise, basis_gates=this_noise.basis_gates, **backend_exec_options_copy) ''' job = execute(simulation_circuits, backend, shots=shots, noise_model=this_noise, basis_gates=this_noise.basis_gates, **backend_exec_options_copy) logger.info(f'Finished Running on noisy simulator - {round(time.time() - st, 5)} (ms)') if verbose_time: print(f" *** qiskit.execute() time = {round(time.time() - st, 5)}") #************************************************ # Initiate execution for all other backends and noiseless simulator else: # if set, transpile many times and pick shortest circuit # DEVNOTE: this does not handle parameters yet, or optimizations if transpile_attempt_count: trans_qc = transpile_multiple_times(circuit["qc"], circuit["params"], backend, transpile_attempt_count, optimization_level=None, layout_method=None, routing_method=None) # transpile and bind circuit with parameters; use cache if flagged else: trans_qc = transpile_and_bind_circuit(circuit["qc"], circuit["params"], backend, optimization_level=optimization_level, layout_method=layout_method, routing_method=routing_method) # apply transformer pass if provided if transformer: trans_qc, shots = invoke_transformer(transformer, trans_qc, backend=backend, shots=shots) # Indicate number of qubits about to be executed if width_processor: width_processor(qc) # to execute on Aer state vector simulator, need to remove measurements if backend_name.lower() == "statevector_simulator": trans_qc = trans_qc.remove_final_measurements(inplace=False) #************************************* # perform circuit execution on backend logger.info(f'Running trans_qc, shots={shots}') st = time.time() if use_sessions: job = sampler.run(trans_qc, shots=shots, **backend_exec_options_copy) else: job = backend.run(trans_qc, shots=shots, **backend_exec_options_copy) logger.info(f'Finished Running trans_qc - {round(time.time() - st, 5)} (ms)') if verbose_time: print(f" *** qiskit.run() time = {round(time.time() - st, 5)}") except Exception as e: print(f'ERROR: Failed to execute circuit {active_circuit["group"]} {active_circuit["circuit"]}') print(f"... exception = {e}") if verbose: print(traceback.format_exc()) return # print("Job status is ", job.status() ) # put job into the active circuits with circuit info active_circuits[job] = active_circuit # print("... active_circuit = ", str(active_circuit)) # store circuit dimensional metrics metrics.store_metric(active_circuit["group"], active_circuit["circuit"], 'depth', qc_depth) metrics.store_metric(active_circuit["group"], active_circuit["circuit"], 'size', qc_size) metrics.store_metric(active_circuit["group"], active_circuit["circuit"], 'xi', qc_xi) metrics.store_metric(active_circuit["group"], active_circuit["circuit"], 'n2q', qc_n2q) metrics.store_metric(active_circuit["group"], active_circuit["circuit"], 'tr_depth', qc_tr_depth) metrics.store_metric(active_circuit["group"], active_circuit["circuit"], 'tr_size', qc_tr_size) metrics.store_metric(active_circuit["group"], active_circuit["circuit"], 'tr_xi', qc_tr_xi) metrics.store_metric(active_circuit["group"], active_circuit["circuit"], 'tr_n2q', qc_tr_n2q) # also store the job_id for future reference metrics.store_metric(active_circuit["group"], active_circuit["circuit"], 'job_id', job.job_id()) if verbose: print(f" ... executing job {job.job_id()}") # special handling when only runnng one job at a time: wait for result here # so the status check called later immediately returns done and avoids polling if max_jobs_active <= 1: wait_on_job_result(job, active_circuit) # return, so caller can do other things while waiting for jobs to complete # Utility function to obtain name of backend # This is needed because some backends support backend.name and others backend.name() def get_backend_name(backend): if callable(backend.name): name = backend.name() else: name = backend.name return name # block and wait for the job result to be returned # handle network timeouts by doing up to 40 retries once every 15 seconds def wait_on_job_result(job, active_circuit): retry_count = 0 result = None while retry_count < 40: try: retry_count += 1 result = job.result() break except Exception as e: print(f'... error occurred during job.result() for circuit {active_circuit["group"]} {active_circuit["circuit"]} -- retry {retry_count}') if verbose: print(traceback.format_exc()) time.sleep(15) continue if result == None: print(f'ERROR: during job.result() for circuit {active_circuit["group"]} {active_circuit["circuit"]}') raise ValueError("Failed to execute job") else: #print(f"... job.result() is done, with result data, continuing") pass # Check and return job_status # handle network timeouts by doing up to 40 retries once every 15 seconds def get_job_status(job, active_circuit): retry_count = 0 status = None while retry_count < 3: try: retry_count += 1 #print(f"... calling job.status()") status = job.status() break except Exception as e: print(f'... error occurred during job.status() for circuit {active_circuit["group"]} {active_circuit["circuit"]} -- retry {retry_count}') if verbose: print(traceback.format_exc()) time.sleep(15) continue if status == None: print(f'ERROR: during job.status() for circuit {active_circuit["group"]} {active_circuit["circuit"]}') raise ValueError("Failed to get job status") else: #print(f"... job.result() is done, with result data, continuing") pass return status # Get circuit metrics fom the circuit passed in def get_circuit_metrics(qc): logger.info('Entering get_circuit_metrics') #print(qc) # obtain initial circuit size metrics qc_depth = qc.depth() qc_size = qc.size() qc_count_ops = qc.count_ops() qc_xi = 0 qc_n2q = 0 # iterate over the ordereddict to determine xi (ratio of 2 qubit gates to one qubit gates) n1q = 0; n2q = 0 if qc_count_ops != None: for key, value in qc_count_ops.items(): if key == "measure": continue if key == "barrier": continue if key.startswith("c") or key.startswith("mc"): n2q += value else: n1q += value qc_xi = n2q / (n1q + n2q) qc_n2q = n2q return qc_depth, qc_size, qc_count_ops, qc_xi, qc_n2q # Transpile the circuit to obtain normalized size metrics against a common basis gate set def transpile_for_metrics(qc): logger.info('Entering transpile_for_metrics') #print("*** Before transpile ...") #print(qc) st = time.time() # use either the backend or one of the basis gate sets if basis_selector == 0: logger.info(f"Start transpile with {basis_selector = }") qc = transpile(qc, backend) logger.info(f"End transpile with {basis_selector = }") else: basis_gates = basis_gates_array[basis_selector] logger.info(f"Start transpile with basis_selector != 0") qc = transpile(qc, basis_gates=basis_gates, seed_transpiler=0) logger.info(f"End transpile with basis_selector != 0") #print(qc) qc_tr_depth = qc.depth() qc_tr_size = qc.size() qc_tr_count_ops = qc.count_ops() #print(f"*** after transpile: {qc_tr_depth} {qc_tr_size} {qc_tr_count_ops}") # iterate over the ordereddict to determine xi (ratio of 2 qubit gates to one qubit gates) n1q = 0; n2q = 0 if qc_tr_count_ops != None: for key, value in qc_tr_count_ops.items(): if key == "measure": continue if key == "barrier": continue if key.startswith("c"): n2q += value else: n1q += value qc_tr_xi = n2q / (n1q + n2q) qc_tr_n2q = n2q #print(f"... qc_tr_xi = {qc_tr_xi} {n1q} {n2q}") logger.info(f'transpile_for_metrics - {round(time.time() - st, 5)} (ms)') if verbose_time: print(f" *** transpile_for_metrics() time = {round(time.time() - st, 5)}") return qc_tr_depth, qc_tr_size, qc_tr_count_ops, qc_tr_xi, qc_tr_n2q # Return a transpiled and bound circuit # Cache the transpiled circuit, and use it if do_transpile_for_execute not set # DEVNOTE: this approach does not permit passing of untranspiled circuit through # DEVNOTE: currently this only caches a single circuit def transpile_and_bind_circuit(circuit, params, backend, optimization_level=None, layout_method=None, routing_method=None): logger.info(f'transpile_and_bind_circuit()') st = time.time() if do_transpile_for_execute: logger.info('transpiling for execute') trans_qc = transpile(circuit, backend, optimization_level=optimization_level, layout_method=layout_method, routing_method=routing_method) # cache this transpiled circuit cached_circuits["last_circuit"] = trans_qc else: logger.info('use cached transpiled circuit for execute') if verbose_time: print(f" ... using cached circuit, no transpile") ##trans_qc = circuit["qc"] # for now, use this cached transpiled circuit (should be separate flag to pass raw circuit) trans_qc = cached_circuits["last_circuit"] #print(trans_qc) #print(f"... trans_qc name = {trans_qc.name}") # obtain name of the transpiled or cached circuit trans_qc_name = trans_qc.name # if parameters provided, bind them to circuit if params != None: # Note: some loggers cannot handle unicode in param names, so only show the values #logger.info(f"Binding parameters to circuit: {str(params)}") logger.info(f"Binding parameters to circuit: {[param[1] for param in params.items()]}") if verbose_time: print(f" ... binding parameters") trans_qc = trans_qc.bind_parameters(params) #print(trans_qc) # store original name in parameterized circuit, so it can be found with get_result() trans_qc.name = trans_qc_name #print(f"... trans_qc name = {trans_qc.name}") logger.info(f'transpile_and_bind_circuit - {trans_qc_name} {round(time.time() - st, 5)} (ms)') if verbose_time: print(f" *** transpile_and_bind() time = {round(time.time() - st, 5)}") return trans_qc # Transpile a circuit multiple times for optimal results # DEVNOTE: this does not handle parameters yet def transpile_multiple_times(circuit, params, backend, transpile_attempt_count, optimization_level=None, layout_method=None, routing_method=None): logger.info(f"transpile_multiple_times({transpile_attempt_count})") st = time.time() # array of circuits that have been transpile trans_qc_list = [ transpile( circuit, backend, optimization_level=optimization_level, layout_method=layout_method, routing_method=routing_method ) for _ in range(transpile_attempt_count) ] best_op_count = [] for circ in trans_qc_list: # check if there are cx in transpiled circs if 'cx' in circ.count_ops().keys(): # get number of operations best_op_count.append( circ.count_ops()['cx'] ) # check if there are sx in transpiled circs elif 'sx' in circ.count_ops().keys(): # get number of operations best_op_count.append( circ.count_ops()['sx'] ) # print(f"{best_op_count = }") if best_op_count: # pick circuit with lowest number of operations best_idx = np.where(best_op_count == np.min(best_op_count))[0][0] trans_qc = trans_qc_list[best_idx] else: # otherwise just pick the first in the list best_idx = 0 trans_qc = trans_qc_list[0] logger.info(f'transpile_multiple_times - {best_idx} {round(time.time() - st, 5)} (ms)') if verbose_time: print(f" *** transpile_multiple_times() time = {round(time.time() - st, 5)}") return trans_qc # Invoke a circuit transformer, returning modifed circuit (array) and modifed shots def invoke_transformer(transformer, circuit, backend=backend, shots=100): logger.info('Invoking Transformer') st = time.time() # apply the transformer and get back either a single circuit or a list of circuits tr_circuit = transformer(circuit, backend=backend) # if transformer results in multiple circuits, divide shot count # results will be accumulated in job_complete # NOTE: this will need to set a flag to distinguish from multiple circuit execution if isinstance(tr_circuit, list) and len(tr_circuit) > 1: shots = int(shots / len(tr_circuit)) logger.info(f'Transformer - {round(time.time() - st, 5)} (ms)') if verbose_time:print(f" *** transformer() time = {round(time.time() - st, 5)} (ms)") return tr_circuit, shots ########################################################################### # Process a completed job def job_complete(job): active_circuit = active_circuits[job] if verbose: print(f'\n... job complete - group={active_circuit["group"]} id={active_circuit["circuit"]} shots={active_circuit["shots"]}') logger.info(f'job complete - group={active_circuit["group"]} id={active_circuit["circuit"]} shots={active_circuit["shots"]}') # compute elapsed time for circuit; assume exec is same, unless obtained from result elapsed_time = time.time() - active_circuit["launch_time"] # report exec time as 0 unless valid measure returned exec_time = 0.0 # store these initial time measures now, in case job had error metrics.store_metric(active_circuit["group"], active_circuit["circuit"], 'elapsed_time', elapsed_time) metrics.store_metric(active_circuit["group"], active_circuit["circuit"], 'exec_time', exec_time) ###### executor completion # If job has the 'local_job' attr, execution was done by the executor, and all work is done # we process it here, as the subsequent processing has too much time-specific detail if hasattr(job, 'local_job'): # get the result object directly from the pseudo-job object result = job.result() if hasattr(result, 'exec_time'): exec_time = result.exec_time # assume the exec time is the elapsed time, since we don't have more detail metrics.store_metric(active_circuit["group"], active_circuit["circuit"], 'exec_time', exec_time) # invoke the result handler with the result object if result != None and result_handler: try: result_handler(active_circuit["qc"], result, active_circuit["group"], active_circuit["circuit"], active_circuit["shots"] ) except Exception as e: print(f'ERROR: failed to execute result_handler for circuit {active_circuit["group"]} {active_circuit["circuit"]}') print(f"... exception = {e}") if verbose: print(traceback.format_exc()) # remove from list of active circuits del active_circuits[job] return ###### normal completion # get job result (DEVNOTE: this might be different for diff targets) result = None if job.status() == JobStatus.DONE: result = job.result() # print("... result = ", str(result)) # for Azure Quantum, need to obtain execution time from sessions object # Since there may be multiple jobs, need to find the one that matches the current job_id if azure_provider is not None and session is not None: details = job._azure_job.details # print("... session_job.details = ", details) exec_time = (details.end_execution_time - details.begin_execution_time).total_seconds() # DEVNOTE: startup time is not currently used or stored # it seesm to include queue time, so it has no added value over the elapsed time we currently store startup_time = (details.begin_execution_time - details.creation_time).total_seconds() # counts = result.get_counts(qc) # print("Total counts are:", counts) # if we are using sessions, structure of result object is different; # use a BenchmarkResult object to hold session result and provide a get_counts() # that returns counts to the benchmarks in the same form as without sessions if use_sessions: result = BenchmarkResult(result) #counts = result.get_counts() actual_shots = result.metadata[0]['shots'] result_obj = result.metadata[0] results_obj = result.metadata[0] else: result_obj = result.to_dict() results_obj = result.to_dict()['results'][0] # get the actual shots and convert to int if it is a string # DEVNOTE: this summation currently applies only to randomized compiling # and may cause problems with other use cases (needs review) actual_shots = 0 for experiment in result_obj["results"]: actual_shots += experiment["shots"] #print(f"result_obj = {result_obj}") #print(f"results_obj = {results_obj}") #print(f'shots = {results_obj["shots"]}') # convert actual_shots to int if it is a string if type(actual_shots) is str: actual_shots = int(actual_shots) # check for mismatch of requested shots and actual shots if actual_shots != active_circuit["shots"]: print(f'WARNING: requested shots not equal to actual shots: {active_circuit["shots"]} != {actual_shots} ') # allow processing to continue, but use the requested shot count actual_shots = active_circuit["shots"] # obtain timing info from the results object # the data has been seen to come from both places below if "time_taken" in result_obj: exec_time = result_obj["time_taken"] elif "time_taken" in results_obj: exec_time = results_obj["time_taken"] # override the initial value with exec_time returned from successful execution metrics.store_metric(active_circuit["group"], active_circuit["circuit"], 'exec_time', exec_time) # process additional detailed step times, if they exist (this might override exec_time too) process_step_times(job, result, active_circuit) # remove from list of active circuits del active_circuits[job] # If a result handler has been established, invoke it here with result object if result != None and result_handler: # invoke a result processor if specified in exec_options if result_processor: logger.info(f'result_processor(...)') result = result_processor(result) # The following computes the counts by summing them up, allowing for the case where # <result> contains results from multiple circuits # DEVNOTE: This will need to change; currently the only case where we have multiple result counts # is when using randomly_compile; later, there will be other cases if not use_sessions and type(result.get_counts()) == list: total_counts = dict() for count in result.get_counts(): total_counts = dict(Counter(total_counts) + Counter(count)) # make a copy of the result object so we can return a modified version orig_result = result result = copy.copy(result) # replace the results array with an array containing only the first results object # then populate other required fields results = copy.copy(result.results[0]) results.header.name = active_circuit["qc"].name # needed to identify the original circuit results.shots = actual_shots results.data.counts = total_counts result.results = [ results ] try: result_handler(active_circuit["qc"], result, active_circuit["group"], active_circuit["circuit"], active_circuit["shots"] ) except Exception as e: print(f'ERROR: failed to execute result_handler for circuit {active_circuit["group"]} {active_circuit["circuit"]}') print(f"... exception = {e}") if verbose: print(traceback.format_exc()) # Process detailed step times, if they exist def process_step_times(job, result, active_circuit): #print("... processing step times") exec_creating_time = 0 exec_validating_time = 0 exec_queued_time = 0 exec_running_time = 0 # get breakdown of execution time, if method exists # this attribute not available for some providers and only for circuit-runner model; if not use_sessions and "time_per_step" in dir(job) and callable(job.time_per_step): time_per_step = job.time_per_step() if verbose: print(f"... job.time_per_step() = {time_per_step}") creating_time = time_per_step.get("CREATING") validating_time = time_per_step.get("VALIDATING") queued_time = time_per_step.get("QUEUED") running_time = time_per_step.get("RUNNING") completed_time = time_per_step.get("COMPLETED") # for testing, since hard to reproduce on some systems #running_time = None # make these all slightly non-zero so averaging code is triggered (> 0.001 required) exec_creating_time = 0.001 exec_validating_time = 0.001 exec_queued_time = 0.001 exec_running_time = 0.001 # this is note used exec_quantum_classical_time = 0.001 # compute the detailed time metrics if validating_time and creating_time: exec_creating_time = (validating_time - creating_time).total_seconds() if queued_time and validating_time: exec_validating_time = (queued_time - validating_time).total_seconds() if running_time and queued_time: exec_queued_time = (running_time - queued_time).total_seconds() if completed_time and running_time: exec_running_time = (completed_time - running_time).total_seconds() # when sessions and sampler used, we obtain metrics differently if use_sessions: job_timestamps = job.metrics()['timestamps'] job_metrics = job.metrics() # print(f"... usage = {job_metrics['usage']} {job_metrics['executions']}") if verbose: print(f"... job.metrics() = {job.metrics()}") print(f"... job.result().metadata[0] = {result.metadata[0]}") # occasionally, these metrics come back as None, so try to use them try: created_time = datetime.strptime(job_timestamps['created'][11:-1],"%H:%M:%S.%f") created_time_delta = timedelta(hours=created_time.hour, minutes=created_time.minute, seconds=created_time.second, microseconds = created_time.microsecond) finished_time = datetime.strptime(job_timestamps['finished'][11:-1],"%H:%M:%S.%f") finished_time_delta = timedelta(hours=finished_time.hour, minutes=finished_time.minute, seconds=finished_time.second, microseconds = finished_time.microsecond) running_time = datetime.strptime(job_timestamps['running'][11:-1],"%H:%M:%S.%f") running_time_delta = timedelta(hours=running_time.hour, minutes=running_time.minute, seconds=running_time.second, microseconds = running_time.microsecond) # compute the total seconds for creating and running the circuit exec_creating_time = (running_time_delta - created_time_delta).total_seconds() exec_running_time = (finished_time_delta - running_time_delta).total_seconds() # these do not seem to be avaiable exec_validating_time = 0.001 exec_queued_time = 0.001 # when using sessions, the 'running_time' is the 'quantum exec time' - override it here. metrics.store_metric(active_circuit["group"], active_circuit["circuit"], 'exec_time', exec_running_time) # use the data in usage field if it is returned, usually by hardware # here we use the executions field to indicate we are on hardware if "usage" in job_metrics and "executions" in job_metrics: if job_metrics['executions'] > 0: exec_time = job_metrics['usage']['quantum_seconds'] # and use this one as it seems to be valid for this case metrics.store_metric(active_circuit["group"], active_circuit["circuit"], 'exec_time', exec_time) # DEVNOTE: we do not compute this yet # exec_quantum_classical_time = job.metrics()['bss'] # metrics.store_metric(active_circuit["group"], active_circuit["circuit"], 'exec_quantum_classical_time', exec_quantum_classical_time) except Exception as e: if verbose: print(f'WARNING: incomplete time metrics for circuit {active_circuit["group"]} {active_circuit["circuit"]}') print(f"... job = {job.job_id()} exception = {e}") # In metrics, we use > 0.001 to indicate valid data; need to floor these values to 0.001 exec_creating_time = max(0.001, exec_creating_time) exec_validating_time = max(0.001, exec_validating_time) exec_queued_time = max(0.001, exec_queued_time) exec_running_time = max(0.001, exec_running_time) metrics.store_metric(active_circuit["group"], active_circuit["circuit"], 'exec_creating_time', exec_creating_time) metrics.store_metric(active_circuit["group"], active_circuit["circuit"], 'exec_validating_time', 0.001) metrics.store_metric(active_circuit["group"], active_circuit["circuit"], 'exec_queued_time', 0.001) metrics.store_metric(active_circuit["group"], active_circuit["circuit"], 'exec_running_time', exec_running_time) #print("... time_per_step = ", str(time_per_step)) if verbose: print(f"... computed exec times: queued = {exec_queued_time}, creating/transpiling = {exec_creating_time}, validating = {exec_validating_time}, running = {exec_running_time}") # Process a job, whose status cannot be obtained def job_status_failed(job): active_circuit = active_circuits[job] if verbose: print(f'\n... job status failed - group={active_circuit["group"]} id={active_circuit["circuit"]} shots={active_circuit["shots"]}') # compute elapsed time for circuit; assume exec is same, unless obtained from result elapsed_time = time.time() - active_circuit["launch_time"] # report exec time as 0 unless valid measure returned exec_time = 0.0 # remove from list of active circuits del active_circuits[job] metrics.store_metric(active_circuit["group"], active_circuit["circuit"], 'elapsed_time', elapsed_time) metrics.store_metric(active_circuit["group"], active_circuit["circuit"], 'exec_time', exec_time) ###################################################################### # JOB MANAGEMENT METHODS # Job management involves coordinating the batching, queueing, # and completion processing of circuits that are submitted for execution. # Throttle the execution of active and batched jobs. # Wait for active jobs to complete. As each job completes, # check if there are any batched circuits waiting to be executed. # If so, execute them, removing them from the batch. # Execute the user-supplied completion handler to allow user to # check if a group of circuits has been completed and report on results. # Then, if there are no more circuits remaining in batch, exit, # otherwise continue to wait for additional active circuits to complete. def throttle_execution(completion_handler=metrics.finalize_group): logger.info('Entering throttle_execution') #if verbose: #print(f"... throttling execution, active={len(active_circuits)}, batched={len(batched_circuits)}") # check and sleep if not complete done = False pollcount = 0 while not done: # check if any jobs complete check_jobs(completion_handler) # return only when all jobs complete if len(batched_circuits) < 1: break # delay a bit, increasing the delay periodically sleeptime = 0.25 if pollcount > 6: sleeptime = 0.5 if pollcount > 60: sleeptime = 1.0 time.sleep(sleeptime) pollcount += 1 if verbose: if pollcount > 0: print("") #print(f"... throttling execution(2), active={len(active_circuits)}, batched={len(batched_circuits)}") # Wait for all active and batched circuits to complete. # Execute the user-supplied completion handler to allow user to # check if a group of circuits has been completed and report on results. # Return when there are no more active circuits. # This is used as a way to complete all groups of circuits and report results. def finalize_execution(completion_handler=metrics.finalize_group, report_end=True): #if verbose: #print("... finalize_execution") # check and sleep if not complete done = False pollcount = 0 while not done: # check if any jobs complete check_jobs(completion_handler) # return only when all jobs complete if len(active_circuits) < 1: break # delay a bit, increasing the delay periodically sleeptime = 0.10 # was 0.25 if pollcount > 6: sleeptime = 0.20 # 0.5 if pollcount > 60: sleeptime = 0.5 # 1.0 time.sleep(sleeptime) pollcount += 1 if verbose: if pollcount > 0: print("") # indicate we are done collecting metrics (called once at end of app) if report_end: metrics.end_metrics() # also, close any active session at end of the app global session if report_end and session != None: if verbose: print(f"... closing active session: {session_count}\n") session.close() session = None # Check if any active jobs are complete - process if so # Before returning, launch any batched jobs that will keep active circuits < max # When any job completes, aggregate and report group metrics if all circuits in group are done # then return, don't sleep def check_jobs(completion_handler=None): for job, circuit in active_circuits.items(): try: #status = job.status() status = get_job_status(job, circuit) # use this version, robust to network failure #print("Job status is ", status) except Exception as e: print(f'ERROR: Unable to retrieve job status for circuit {circuit["group"]} {circuit["circuit"]}') print(f"... job = {job.job_id()} exception = {e}") # finish the job by removing from active list job_status_failed(job) break circuit["pollcount"] += 1 # if job not complete, provide comfort ... if status == JobStatus.QUEUED: if verbose: if circuit["pollcount"] < 32 or (circuit["pollcount"] % 15 == 0): print('.', end='') continue elif status == JobStatus.INITIALIZING: if verbose: print('i', end='') continue elif status == JobStatus.VALIDATING: if verbose: print('v', end='') continue elif status == JobStatus.RUNNING: if verbose: print('r', end='') continue # when complete, canceled, or failed, process the job if status == JobStatus.CANCELLED: print(f"... circuit execution cancelled.") if status == JobStatus.ERROR: print(f"... circuit execution failed.") if hasattr(job, "error_message"): print(f" job = {job.job_id()} {job.error_message()}") if status == JobStatus.DONE or status == JobStatus.CANCELLED or status == JobStatus.ERROR: #if verbose: print("Job status is ", job.status() ) active_circuit = active_circuits[job] group = active_circuit["group"] # process the job and its result data job_complete(job) # call completion handler with the group id if completion_handler != None: completion_handler(group) break # if not at maximum jobs and there are jobs in batch, then execute another if len(active_circuits) < max_jobs_active and len(batched_circuits) > 0: # pop the first circuit in the batch and launch execution circuit = batched_circuits.pop(0) if verbose: print(f'... pop and submit circuit - group={circuit["group"]} id={circuit["circuit"]} shots={circuit["shots"]}') execute_circuit(circuit) # Test circuit execution def test_execution(): pass ######################################## # DEPRECATED METHODS # these methods are retained for reference and in case needed later # Wait for active and batched circuits to complete # This is used as a way to complete a group of circuits and report # results before continuing to create more circuits. # Deprecated: maintained for compatibility until all circuits are modified # to use throttle_execution(0 and finalize_execution() def execute_circuits(): # deprecated code ... ''' for batched_circuit in batched_circuits: execute_circuit(batched_circuit) batched_circuits.clear() ''' # wait for all jobs to complete wait_for_completion() # Wait for all active and batched jobs to complete # deprecated version, with no completion handler def wait_for_completion(): if verbose: print("... waiting for completion") # check and sleep if not complete done = False pollcount = 0 while not done: # check if any jobs complete check_jobs() # return only when all jobs complete if len(active_circuits) < 1: break # delay a bit, increasing the delay periodically sleeptime = 0.25 if pollcount > 6: sleeptime = 0.5 if pollcount > 60: sleeptime = 1.0 time.sleep(sleeptime) pollcount += 1 if verbose: if pollcount > 0: print("") # Wait for a single job to complete, return when done # (replaced by wait_for_completion, which handle multiple jobs) def job_wait_for_completion(job): done=False pollcount = 0 while not done: status = job.status() #print("Job status is ", status) if status == JobStatus.DONE: break if status == JobStatus.CANCELLED: break if status == JobStatus.ERROR: break if status == JobStatus.QUEUED: if verbose: if pollcount < 44 or (pollcount % 15 == 0): print('.', end='') elif status == JobStatus.INITIALIZING: if verbose: print('i', end='') elif status == JobStatus.VALIDATING: if verbose: print('v', end='') elif status == JobStatus.RUNNING: if verbose: print('r', end='') pollcount += 1 # delay a bit, increasing the delay periodically sleeptime = 0.25 if pollcount > 8: sleeptime = 0.5 if pollcount > 100: sleeptime = 1.0 time.sleep(sleeptime) if pollcount > 0: if verbose: print("") #if verbose: print("Job status is ", job.status() ) if job.status() == JobStatus.CANCELLED: print(f"\n... circuit execution cancelled.") if job.status() == JobStatus.ERROR: print(f"\n... circuit execution failed.")
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
# all libraries used by some part of the VQLS-implementation from qiskit import ( QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, execute, transpile, assemble ) from qiskit.circuit import Gate, Instruction from qiskit.quantum_info.operators import Operator from qiskit.extensions import ZGate, YGate, XGate, IGate from scipy.optimize import ( minimize, basinhopping, differential_evolution, shgo, dual_annealing ) import random import numpy as np import cmath from typing import List, Set, Dict, Tuple, Optional, Union # import the params object of the GlobalParameters class # this provides the parameters used to desribed and model # the problem the minimizer is supposed to use. from GlobalParameters import params # import the vqls algorithm and corresponding code from vqls import ( generate_ansatz, hadamard_test, calculate_beta, calculate_delta, calculate_local_cost_function, minimize_local_cost_function, postCorrection, _format_alpha, _calculate_expectationValue_HadamardTest, _U_primitive ) # The user input for the VQLS-algorithm has to be given # when params is initialized within GlobalParameters.py # The decomposition for $A$ has to be manually # inserted into the code of # the class GlobalParameters. print( "This program will execute a simulation of the VQLS-algorithm " + "with 4 qubits, 4 layers in the Ansatz and a single Id-gate acting" + " on the second qubit.\n" + "To simulate another problem, one can either alter _U_primitive " + "in vqls.py to change |x_0>, GlobalParameters.py to change A " + "or its decomposition respectively." ) # Executing the VQLS-algorithm alpha_min = minimize_local_cost_function(params.method_minimization) """ Circuit with the $\vec{alpha}$ generated by the minimizer. """ # Create a circuit for the vqls-result qr_min = QuantumRegister(params.n_qubits) circ_min = QuantumCircuit(qr_min) # generate $V(\vec{alpha})$ and copy $A$ ansatz = generate_ansatz(alpha_min).to_gate() A_copy = params.A.copy() if isinstance(params.A, Operator): A_copy = A_copy.to_instruction() # apply $V(\vec{alpha})$ and $A$ to the circuit # this results in a state that is approximately $\ket{b}$ circ_min.append(ansatz, qr_min) circ_min.append(A_copy, qr_min) # apply post correction to fix for sign errors and a "mirroring" # of the result circ_min = postCorrection(circ_min) """ Reference circuit based on the definition of $\ket{b}$. """ circ_ref = _U_primitive() """ Simulate both circuits. """ # the minimizations result backend = Aer.get_backend( 'statevector_simulator') t_circ = transpile(circ_min, backend) qobj = assemble(t_circ) job = backend.run(qobj) result = job.result() print( "This is the result of the simulation.\n" + "Reminder: 4 qubits and an Id-gate on the second qubit." + "|x_0> was defined by Hadamard gates acting on qubits 0 and 3.\n" + "The return value of the minimizer (alpha_min):\n" + str(alpha_min) + "\nThe resulting statevector for a circuit to which " + "V(alpha_min) and A and the post correction were applied:\n" + str(result.get_statevector()) ) t_circ = transpile(circ_ref, backend) qobj = assemble(t_circ) job = backend.run(qobj) result = job.result() print( "And this is the statevector for the reference circuit: A |x_0>\n" + str(result.get_statevector()) ) print("these were Id gates and in U y on 0 and 1")
https://github.com/ughyper3/grover-quantum-algorithm
ughyper3
import numpy as np import networkx as nx import qiskit from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, assemble from qiskit.quantum_info import Statevector from qiskit.aqua.algorithms import NumPyEigensolver from qiskit.quantum_info import Pauli from qiskit.aqua.operators import op_converter from qiskit.aqua.operators import WeightedPauliOperator from qiskit.visualization import plot_histogram from qiskit.providers.aer.extensions.snapshot_statevector import * from thirdParty.classical import rand_graph, classical, bitstring_to_path, calc_cost from utils import mapeo_grafo from collections import defaultdict from operator import itemgetter from scipy.optimize import minimize import matplotlib.pyplot as plt LAMBDA = 10 SEED = 10 SHOTS = 10000 # returns the bit index for an alpha and j def bit(i_city, l_time, num_cities): return i_city * num_cities + l_time # e^(cZZ) def append_zz_term(qc, q_i, q_j, gamma, constant_term): qc.cx(q_i, q_j) qc.rz(2*gamma*constant_term,q_j) qc.cx(q_i, q_j) # e^(cZ) def append_z_term(qc, q_i, gamma, constant_term): qc.rz(2*gamma*constant_term, q_i) # e^(cX) def append_x_term(qc,qi,beta): qc.rx(-2*beta, qi) def get_not_edge_in(G): N = G.number_of_nodes() not_edge = [] for i in range(N): for j in range(N): if i != j: buffer_tupla = (i,j) in_edges = False for edge_i, edge_j in G.edges(): if ( buffer_tupla == (edge_i, edge_j) or buffer_tupla == (edge_j, edge_i)): in_edges = True if in_edges == False: not_edge.append((i, j)) return not_edge def get_classical_simplified_z_term(G, _lambda): # recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos N = G.number_of_nodes() E = G.edges() # z term # z_classic_term = [0] * N**2 # first term for l in range(N): for i in range(N): z_il_index = bit(i, l, N) z_classic_term[z_il_index] += -1 * _lambda # second term for l in range(N): for j in range(N): for i in range(N): if i < j: # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 2 # z_jl z_jl_index = bit(j, l, N) z_classic_term[z_jl_index] += _lambda / 2 # third term for i in range(N): for l in range(N): for j in range(N): if l < j: # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 2 # z_ij z_ij_index = bit(i, j, N) z_classic_term[z_ij_index] += _lambda / 2 # fourth term not_edge = get_not_edge_in(G) # include order tuples ej = (1,0), (0,1) for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 4 # z_j(l+1) l_plus = (l+1) % N z_jlplus_index = bit(j, l_plus, N) z_classic_term[z_jlplus_index] += _lambda / 4 # fifthy term weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # z_il z_il_index = bit(edge_i, l, N) z_classic_term[z_il_index] += weight_ij / 4 # z_jlplus l_plus = (l+1) % N z_jlplus_index = bit(edge_j, l_plus, N) z_classic_term[z_jlplus_index] += weight_ij / 4 # add order term because G.edges() do not include order tuples # # z_i'l z_il_index = bit(edge_j, l, N) z_classic_term[z_il_index] += weight_ji / 4 # z_j'lplus l_plus = (l+1) % N z_jlplus_index = bit(edge_i, l_plus, N) z_classic_term[z_jlplus_index] += weight_ji / 4 return z_classic_term def tsp_obj_2(x, G,_lambda): # obtenemos el valor evaluado en f(x_1, x_2,... x_n) not_edge = get_not_edge_in(G) N = G.number_of_nodes() tsp_cost=0 #Distancia weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # x_il x_il_index = bit(edge_i, l, N) # x_jlplus l_plus = (l+1) % N x_jlplus_index = bit(edge_j, l_plus, N) tsp_cost+= int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ij # add order term because G.edges() do not include order tuples # # x_i'l x_il_index = bit(edge_j, l, N) # x_j'lplus x_jlplus_index = bit(edge_i, l_plus, N) tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ji #Constraint 1 for l in range(N): penal1 = 1 for i in range(N): x_il_index = bit(i, l, N) penal1 -= int(x[x_il_index]) tsp_cost += _lambda * penal1**2 #Contstraint 2 for i in range(N): penal2 = 1 for l in range(N): x_il_index = bit(i, l, N) penal2 -= int(x[x_il_index]) tsp_cost += _lambda*penal2**2 #Constraint 3 for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # x_il x_il_index = bit(i, l, N) # x_j(l+1) l_plus = (l+1) % N x_jlplus_index = bit(j, l_plus, N) tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * _lambda return tsp_cost def get_classical_simplified_zz_term(G, _lambda): # recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos N = G.number_of_nodes() E = G.edges() # zz term # zz_classic_term = [[0] * N**2 for i in range(N**2) ] # first term for l in range(N): for j in range(N): for i in range(N): if i < j: # z_il z_il_index = bit(i, l, N) # z_jl z_jl_index = bit(j, l, N) zz_classic_term[z_il_index][z_jl_index] += _lambda / 2 # second term for i in range(N): for l in range(N): for j in range(N): if l < j: # z_il z_il_index = bit(i, l, N) # z_ij z_ij_index = bit(i, j, N) zz_classic_term[z_il_index][z_ij_index] += _lambda / 2 # third term not_edge = get_not_edge_in(G) for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # z_il z_il_index = bit(i, l, N) # z_j(l+1) l_plus = (l+1) % N z_jlplus_index = bit(j, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += _lambda / 4 # fourth term weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # z_il z_il_index = bit(edge_i, l, N) # z_jlplus l_plus = (l+1) % N z_jlplus_index = bit(edge_j, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += weight_ij / 4 # add order term because G.edges() do not include order tuples # # z_i'l z_il_index = bit(edge_j, l, N) # z_j'lplus l_plus = (l+1) % N z_jlplus_index = bit(edge_i, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += weight_ji / 4 return zz_classic_term def get_classical_simplified_hamiltonian(G, _lambda): # z term # z_classic_term = get_classical_simplified_z_term(G, _lambda) # zz term # zz_classic_term = get_classical_simplified_zz_term(G, _lambda) return z_classic_term, zz_classic_term def get_cost_circuit(G, gamma, _lambda): N = G.number_of_nodes() N_square = N**2 qc = QuantumCircuit(N_square,N_square) z_classic_term, zz_classic_term = get_classical_simplified_hamiltonian(G, _lambda) # z term for i in range(N_square): if z_classic_term[i] != 0: append_z_term(qc, i, gamma, z_classic_term[i]) # zz term for i in range(N_square): for j in range(N_square): if zz_classic_term[i][j] != 0: append_zz_term(qc, i, j, gamma, zz_classic_term[i][j]) return qc def get_mixer_operator(G,beta): N = G.number_of_nodes() qc = QuantumCircuit(N**2,N**2) for n in range(N**2): append_x_term(qc, n, beta) return qc def get_QAOA_circuit(G, beta, gamma, _lambda): assert(len(beta)==len(gamma)) N = G.number_of_nodes() qc = QuantumCircuit(N**2,N**2) # init min mix state qc.h(range(N**2)) p = len(beta) for i in range(p): qc = qc.compose(get_cost_circuit(G, gamma[i], _lambda)) qc = qc.compose(get_mixer_operator(G, beta[i])) qc.barrier(range(N**2)) qc.snapshot_statevector("final_state") qc.measure(range(N**2),range(N**2)) return qc def invert_counts(counts): return {k[::-1] :v for k,v in counts.items()} # Sample expectation value def compute_tsp_energy_2(counts, G): energy = 0 get_counts = 0 total_counts = 0 for meas, meas_count in counts.items(): obj_for_meas = tsp_obj_2(meas, G, LAMBDA) energy += obj_for_meas*meas_count total_counts += meas_count mean = energy/total_counts return mean def get_black_box_objective_2(G,p): backend = Aer.get_backend('qasm_simulator') sim = Aer.get_backend('aer_simulator') # function f costo def f(theta): beta = theta[:p] gamma = theta[p:] # Anzats qc = get_QAOA_circuit(G, beta, gamma, LAMBDA) result = execute(qc, backend, seed_simulator=SEED, shots= SHOTS).result() final_state_vector = result.data()["snapshots"]["statevector"]["final_state"][0] state_vector = Statevector(final_state_vector) probabilities = state_vector.probabilities() probabilities_states = invert_counts(state_vector.probabilities_dict()) expected_value = 0 for state,probability in probabilities_states.items(): cost = tsp_obj_2(state, G, LAMBDA) expected_value += cost*probability counts = result.get_counts() mean = compute_tsp_energy_2(invert_counts(counts),G) return mean return f def crear_grafo(cantidad_ciudades): pesos, conexiones = None, None mejor_camino = None while not mejor_camino: pesos, conexiones = rand_graph(cantidad_ciudades) mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False) G = mapeo_grafo(conexiones, pesos) return G, mejor_costo, mejor_camino def run_QAOA(p,ciudades, grafo): if grafo == None: G, mejor_costo, mejor_camino = crear_grafo(ciudades) print("Mejor Costo") print(mejor_costo) print("Mejor Camino") print(mejor_camino) print("Bordes del grafo") print(G.edges()) print("Nodos") print(G.nodes()) print("Pesos") labels = nx.get_edge_attributes(G,'weight') print(labels) else: G = grafo intial_random = [] # beta, mixer Hammiltonian for i in range(p): intial_random.append(np.random.uniform(0,np.pi)) # gamma, cost Hammiltonian for i in range(p): intial_random.append(np.random.uniform(0,2*np.pi)) init_point = np.array(intial_random) obj = get_black_box_objective_2(G,p) res_sample = minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True}) print(res_sample) if __name__ == '__main__': # Run QAOA parametros: profundidad p, numero d ciudades, run_QAOA(5, 3, None)
https://github.com/RicardoBBS/ShorAlgo
RicardoBBS
import sys import numpy as np from matplotlib import pyplot as plt from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, visualization from random import randint def to_binary(N,n_bit): Nbin = np.zeros(n_bit, dtype=bool) for i in range(1,n_bit+1): bit_state = (N % (2**i) != 0) if bit_state: N -= 2**(i-1) Nbin[n_bit-i] = bit_state return Nbin def modular_multiplication(qc,a,N): """ applies the unitary operator that implements modular multiplication function x -> a*x(modN) Only works for the particular case x -> 7*x(mod15)! """ for i in range(0,3): qc.x(i) qc.cx(2,1) qc.cx(1,2) qc.cx(2,1) qc.cx(1,0) qc.cx(0,1) qc.cx(1,0) qc.cx(3,0) qc.cx(0,1) qc.cx(1,0) def quantum_period(a, N, n_bit): # Quantum part print(" Searching the period for N =", N, "and a =", a) qr = QuantumRegister(n_bit) cr = ClassicalRegister(n_bit) qc = QuantumCircuit(qr,cr) simulator = Aer.get_backend('qasm_simulator') s0 = randint(1, N-1) # Chooses random int sbin = to_binary(s0,n_bit) # Turns to binary print("\n Starting at \n s =", s0, "=", "{0:b}".format(s0), "(bin)") # Quantum register is initialized with s (in binary) for i in range(0,n_bit): if sbin[n_bit-i-1]: qc.x(i) s = s0 r=-1 # makes while loop run at least 2 times # Applies modular multiplication transformation until we come back to initial number s while s != s0 or r <= 0: r+=1 # sets up circuit structure qc.measure(qr, cr) modular_multiplication(qc,a,N) qc.draw('mpl') # runs circuit and processes data job = execute(qc,simulator, shots=10) result_counts = job.result().get_counts(qc) result_histogram_key = list(result_counts)[0] # https://qiskit.org/documentation/stubs/qiskit.result.Result.get_counts.html#qiskit.result.Result.get_counts s = int(result_histogram_key, 2) print(" ", result_counts) plt.show() print("\n Found period r =", r) return r if __name__ == '__main__': a = 7 N = 15 n_bit=5 r = quantum_period(a, N, n_bit)
https://github.com/shufan-mct/IBM_quantum_challenge_2020
shufan-mct
%matplotlib inline # Importing standard Qiskit libraries and configuring account from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * # Loading your IBM Q account(s) provider = IBMQ.load_account() #initialization import matplotlib.pyplot as plt import numpy as np # importing Qiskit from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.providers.ibmq import least_busy from qiskit.quantum_info import Statevector # import basic plot tools from qiskit.visualization import plot_histogram lightout4=[[1, 1, 1, 0, 0, 0, 1, 0, 0],[1, 0, 1, 0, 0, 0, 1, 1, 0],[1, 0, 1, 1, 1, 1, 0, 0, 1],[1, 0, 0, 0, 0, 0, 1, 0, 0]] def qRAM(ad,tile): qc = QuantumCircuit(ad, tile) ##address 00->tile lightsout[0] qc.x([ad[0],ad[1]]) i=0 for lightout in lightout4[0]: if lightout==1: qc.ccx(ad[0],ad[1],tile[i]) i=i+1 qc.x([ad[0],ad[1]]) ##address 01->tile lightsout[1] qc.x(ad[1]) i=0 for lightout in lightout4[1]: if lightout==1: qc.ccx(ad[0],ad[1],tile[i]) i=i+1 qc.x(ad[1]) ##address 10->tile lightsout[2] qc.x(ad[0]) i=0 for lightout in lightout4[2]: if lightout==1: qc.ccx(ad[0],ad[1],tile[i]) i=i+1 qc.x(ad[0]) ##address 11->tile lightsout[3] i=0 for lightout in lightout4[3]: if lightout==1: qc.ccx(ad[0],ad[1],tile[i]) i=i+1 U_s = qc.to_gate() U_s.name = "$U_qram$" return U_s def nine_mct(control_qubits,ancilla_qubits,output_qubit): qc = QuantumCircuit(control_qubits, ancilla_qubits, output_qubit) qc.mct([control_qubits[0],control_qubits[1],control_qubits[2]],ancilla_qubits[0],mode='noancilla') qc.mct([control_qubits[3],control_qubits[4],control_qubits[5]],ancilla_qubits[1],mode='noancilla') qc.mct([control_qubits[6],control_qubits[7],control_qubits[8]],ancilla_qubits[2],mode='noancilla') qc.mct([ancilla_qubits[0],ancilla_qubits[1],ancilla_qubits[2]],output_qubit[0],mode='noancilla') qc.mct([control_qubits[6],control_qubits[7],control_qubits[8]],ancilla_qubits[2],mode='noancilla') qc.mct([control_qubits[3],control_qubits[4],control_qubits[5]],ancilla_qubits[1],mode='noancilla') qc.mct([control_qubits[0],control_qubits[1],control_qubits[2]],ancilla_qubits[0],mode='noancilla') U_s = qc.to_gate() U_s.name = "$U_9mct$" return U_s def oracle_2a(tile,flip,flag_a,ancilla): qc = QuantumCircuit(tile,flip,flag_a,ancilla) #build lightsout_oracle switch_list=[[1,3],[0,2,4],[1,5],[0,4,6],[1,3,5,7],[2,4,8],[3,7],[4,6,8],[5,7]] i=0 for clights in switch_list: qc.cx(flip[8-i],tile[i]) for clight in clights: qc.cx(flip[8-i],tile[clight]) i=i+1 for i in range(9): qc.x(tile[i]) qc.append(nine_mct(tile,ancilla,flag_a),[*range(9),*range(19,25),18]) for i in range(9): qc.x(tile[i]) i=0 for clights in switch_list: qc.cx(flip[8-i],tile[i]) for clight in clights: qc.cx(flip[8-i],tile[clight]) i=i+1 U_s = qc.to_gate() U_s.name = "$U_ora2a$" return U_s def eight_mct_in(in_qubits,ancilla_qubits): qc = QuantumCircuit(in_qubits, ancilla_qubits) qc.mct([in_qubits[0],in_qubits[1],in_qubits[2]],ancilla_qubits[0],mode='noancilla') qc.mct([in_qubits[3],in_qubits[4],in_qubits[5]],ancilla_qubits[1],mode='noancilla') qc.ccx(in_qubits[6],in_qubits[7],ancilla_qubits[2]) qc.mct([ancilla_qubits[0],ancilla_qubits[1],ancilla_qubits[2]],in_qubits[8],mode='noancilla') qc.ccx(in_qubits[6],in_qubits[7],ancilla_qubits[2]) qc.mct([in_qubits[3],in_qubits[4],in_qubits[5]],ancilla_qubits[1],mode='noancilla') qc.mct([in_qubits[0],in_qubits[1],in_qubits[2]],ancilla_qubits[0],mode='noancilla') U_s = qc.to_gate() U_s.name = "$U_8mct$" return U_s def nine_diffuser(flip_qubits,ancilla_qubits): qc = QuantumCircuit(flip_qubits,ancilla_qubits) # Apply transformation |s> -> |00..0> (H-gates) for qubit in range(9): qc.h(qubit) # Apply transformation |00..0> -> |11..1> (X-gates) for qubit in range(9): qc.x(qubit) # Do multi-controlled-Z gate qc.h(8) qc.append(eight_mct_in(flip_qubits,ancilla_qubits),[*range(15)]) qc.h(8) # Apply transformation |11..1> -> |00..0> for qubit in range(9): qc.x(qubit) # Apply transformation |00..0> -> |s> for qubit in range(9): qc.h(qubit) # We will return the diffuser as a gate U_s = qc.to_gate() U_s.name = "$U_9diff$" return U_s def u2a(tile,flip,flag_a,ancilla): qc = QuantumCircuit(tile,flip,flag_a,ancilla) for i in range(17): #Oracle qc.append(oracle_2a(tile,flip,flag_a,ancilla),[*range(25)]) # Diffuser qc.append(nine_diffuser(flip,ancilla),[*range(9,18),*range(19,25)]) U_s = qc.to_gate() U_s.name = "$U_2a$" return U_s def u2ad(tile,flip,flag_a,ancilla): qc = QuantumCircuit(tile,flip,flag_a,ancilla) for i in range(17): # Diffuser qc.append(nine_diffuser(flip,ancilla),[*range(9,18),*range(19,25)]) #Oracle qc.append(oracle_2a(tile,flip,flag_a,ancilla),[*range(25)]) U_s = qc.to_gate() U_s.name = "$U_2ad$" return U_s def counter(flip,flag_b,ancilla): qc = QuantumCircuit(flip,flag_b,ancilla) for i in range(9): qc.mct([flip[i],ancilla[0],ancilla[1],ancilla[2]],ancilla[3],mode='noancilla') qc.mct([flip[i],ancilla[0],ancilla[1]],ancilla[2],mode='noancilla') qc.ccx(flip[i],ancilla[0],ancilla[1]) qc.cx(flip[i],ancilla[0]) qc.x([ancilla[2],ancilla[3]]) qc.ccx(ancilla[2],ancilla[3],flag_b[0]) qc.x([ancilla[2],ancilla[3]]) for i in range(9): qc.cx(flip[8-i],ancilla[0]) qc.ccx(flip[8-i],ancilla[0],ancilla[1]) qc.mct([flip[8-i],ancilla[0],ancilla[1]],ancilla[2],mode='noancilla') qc.mct([flip[8-i],ancilla[0],ancilla[1],ancilla[2]],ancilla[3],mode='noancilla') U_s = qc.to_gate() U_s.name = "$U_counter$" return U_s ####Circuit Implement ad = QuantumRegister(2, name='ad') tile = QuantumRegister(9, name='tile') flip = QuantumRegister(9, name='flip') flag_a = QuantumRegister(1, name='f_a') flag_b = QuantumRegister(1, name='f_b') ancilla = QuantumRegister(6, name='a') cbits = ClassicalRegister(2, name='cbits') qc = QuantumCircuit(ad, tile,flip,flag_a,flag_b,ancilla,cbits) ####Initialize qc.h(ad) qc.h(flip) qc.x(flag_a) qc.h(flag_a) qc.x(flag_b) qc.h(flag_b) ####qRAM qc.append(qRAM(ad,tile),[*range(11)]) ####u2a block qc.append(u2a(tile,flip,flag_a,ancilla),[*range(2,21),*range(22,28)]) ####counter qc.append(counter(flip,flag_b,ancilla),[*range(11,20),*range(21,28)]) ####u2ad block qc.append(u2ad(tile,flip,flag_a,ancilla),[*range(2,21),*range(22,28)]) ####qRAM qc.append(qRAM(ad,tile),[*range(11)]) ####2 qubit diffusion qc.h(ad) qc.z(ad) qc.cz(ad[0],ad[1]) qc.h(ad) # Measure the variable qubits qc.measure(ad, cbits) qc.draw() ####Circuit Implement ad = QuantumRegister(2, name='ad') tile = QuantumRegister(9, name='tile') flip = QuantumRegister(9, name='flip') flag_a = QuantumRegister(1, name='f_a') flag_b = QuantumRegister(1, name='f_b') ancilla = QuantumRegister(6, name='a') cbits = ClassicalRegister(2, name='cbits') qc = QuantumCircuit(ad, tile,flip,flag_a,flag_b,ancilla,cbits) ####Initialize qc.h(ad) qc.h(flip) qc.x(flag_a) qc.h(flag_a) qc.x(flag_b) qc.h(flag_b) ####qRAM qc.append(qRAM(ad,tile),[*range(11)]) ####u2a block qc.append(u2a(tile,flip,flag_a,ancilla),[*range(2,21),*range(22,28)]) ####counter qc.append(counter(flip,flag_b,ancilla),[*range(11,20),*range(21,28)]) ####u2ad block qc.append(u2ad(tile,flip,flag_a,ancilla),[*range(2,21),*range(22,28)]) ####qRAM qc.append(qRAM(ad,tile),[*range(11)]) ####2 qubit diffusion qc.h(ad) qc.z(ad) qc.cz(ad[0],ad[1]) qc.h(ad) # Measure the variable qubits qc.measure(ad, cbits) qasm_simulator = Aer.get_backend('qasm_simulator') result = execute(qc, backend=qasm_simulator, shots=1024).result() plot_histogram(result.get_counts())
https://github.com/shufan-mct/IBM_quantum_challenge_2020
shufan-mct
%matplotlib inline # Importing standard Qiskit libraries and configuring account from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * # Loading your IBM Q account(s) provider = IBMQ.load_account() #initialization import matplotlib.pyplot as plt import numpy as np # importing Qiskit from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.providers.ibmq import least_busy from qiskit.quantum_info import Statevector # import basic plot tools from qiskit.visualization import plot_histogram problem_set = \ [[['0', '2'], ['1', '0'], ['1', '2'], ['1', '3'], ['2', '0'], ['3', '3']], [['0', '0'], ['0', '1'], ['1', '2'], ['2', '2'], ['3', '0'], ['3', '3']], [['0', '0'], ['1', '1'], ['1', '3'], ['2', '0'], ['3', '2'], ['3', '3']], [['0', '0'], ['0', '1'], ['1', '1'], ['1', '3'], ['3', '2'], ['3', '3']], [['0', '2'], ['1', '0'], ['1', '3'], ['2', '0'], ['3', '2'], ['3', '3']], [['1', '1'], ['1', '2'], ['2', '0'], ['2', '1'], ['3', '1'], ['3', '3']], [['0', '2'], ['0', '3'], ['1', '2'], ['2', '0'], ['2', '1'], ['3', '3']], [['0', '0'], ['0', '3'], ['1', '2'], ['2', '2'], ['2', '3'], ['3', '0']], [['0', '3'], ['1', '1'], ['1', '2'], ['2', '0'], ['2', '1'], ['3', '3']], [['0', '0'], ['0', '1'], ['1', '3'], ['2', '1'], ['2', '3'], ['3', '0']], [['0', '1'], ['0', '3'], ['1', '2'], ['1', '3'], ['2', '0'], ['3', '2']], [['0', '0'], ['1', '3'], ['2', '0'], ['2', '1'], ['2', '3'], ['3', '1']], [['0', '1'], ['0', '2'], ['1', '0'], ['1', '2'], ['2', '2'], ['2', '3']], [['0', '3'], ['1', '0'], ['1', '3'], ['2', '1'], ['2', '2'], ['3', '0']], [['0', '2'], ['0', '3'], ['1', '2'], ['2', '3'], ['3', '0'], ['3', '1']], [['0', '1'], ['1', '0'], ['1', '2'], ['2', '2'], ['3', '0'], ['3', '1']]] bi_16=\ [ [0,0,0,0],[0,0,0,1],[0,0,1,0],[0,0,1,1], [0,1,0,0],[0,1,0,1],[0,1,1,0],[0,1,1,1], [1,0,0,0],[1,0,0,1],[1,0,1,0],[1,0,1,1], [1,1,0,0],[1,1,0,1],[1,1,1,0],[1,1,1,1] ] ad= QuantumRegister(4, name='ad') ad_sw = QuantumRegister(1, name='ad_sw') row = QuantumRegister(4, name='row') column = QuantumRegister(4, name='column') flag = QuantumRegister(2, name='flag') flag2=QuantumRegister(1, name='flag2') ancilla = QuantumRegister(7, name='a') cbits = ClassicalRegister(4,name='c') #qc = QuantumCircuit(ad,ad_sw,row,column,flag,cbits) problem_set = \ [[['0', '2'], ['1', '0'], ['1', '2'], ['1', '3'], ['2', '0'], ['3', '3']], [['0', '0'], ['0', '1'], ['1', '2'], ['2', '2'], ['3', '0'], ['3', '3']], [['0', '0'], ['1', '1'], ['1', '3'], ['2', '0'], ['3', '2'], ['3', '3']], [['0', '0'], ['0', '1'], ['1', '1'], ['1', '3'], ['3', '2'], ['3', '3']], [['0', '2'], ['1', '0'], ['1', '3'], ['2', '0'], ['3', '2'], ['3', '3']], [['1', '1'], ['1', '2'], ['2', '0'], ['2', '1'], ['3', '1'], ['3', '3']], [['0', '2'], ['0', '3'], ['1', '2'], ['2', '0'], ['2', '1'], ['3', '3']], [['0', '0'], ['0', '3'], ['1', '2'], ['2', '2'], ['2', '3'], ['3', '0']], [['0', '3'], ['1', '1'], ['1', '2'], ['2', '0'], ['2', '1'], ['3', '3']], [['0', '0'], ['0', '1'], ['1', '3'], ['2', '1'], ['2', '3'], ['3', '0']], [['0', '1'], ['0', '3'], ['1', '2'], ['1', '3'], ['2', '0'], ['3', '2']], [['0', '0'], ['1', '3'], ['2', '0'], ['2', '1'], ['2', '3'], ['3', '1']], [['0', '1'], ['0', '2'], ['1', '0'], ['1', '2'], ['2', '2'], ['2', '3']], [['0', '3'], ['1', '0'], ['1', '3'], ['2', '1'], ['2', '2'], ['3', '0']], [['0', '2'], ['0', '3'], ['1', '2'], ['2', '3'], ['3', '0'], ['3', '1']], [['0', '1'], ['1', '0'], ['1', '2'], ['2', '2'], ['3', '0'], ['3', '1']]] def diffuser(nqubits): qc = QuantumCircuit(nqubits) # Apply transformation |s> -> |00..0> (H-gates) for qubit in range(nqubits): qc.h(qubit) # Apply transformation |00..0> -> |11..1> (X-gates) for qubit in range(nqubits): qc.x(qubit) # Do multi-controlled-Z gate qc.h(nqubits-1) qc.mct(list(range(nqubits-1)), nqubits-1) # multi-controlled-toffoli qc.h(nqubits-1) # Apply transformation |11..1> -> |00..0> for qubit in range(nqubits): qc.x(qubit) # Apply transformation |00..0> -> |s> for qubit in range(nqubits): qc.h(qubit) # We will return the diffuser as a gate U_s = qc.to_gate() U_s.name = "$U_diff$" return U_s qc = QuantumCircuit(ad,ad_sw,row,column,flag,flag2,ancilla,cbits) qc.h(ad) qc.x(flag2) qc.h(flag2) a=0 for problem in problem_set: #x gate for b in range(4): if bi_16[a][b]==0: qc.x(ad[3-b]) #ad--mct-->ad_sw qc.mct(ad,ad_sw[0],ancilla,mode='basic') #address set up------------------------------------------ for i in range(5): for j in range(i+1,6): for k in range(0,6): if(k!=i and k!=j): m=int(problem[k][0]) n=int(problem[k][1]) qc.cx(ad_sw,row[m]) qc.cx(ad_sw,column[n]) qc.mct([row[0],row[1],row[2],row[3],column[0],column[1],column[2],column[3],flag[0]],flag[1],ancilla,mode='basic') qc.mct([row[0],row[1],row[2],row[3],column[0],column[1],column[2],column[3]],flag[1],ancilla,mode='basic') for k in range(0,6): if(k!=i and k!=j): m=int(problem[k][0]) n=int(problem[k][1]) qc.cx(ad_sw,row[m]) qc.cx(ad_sw,column[n]) qc.x(flag[0]) qc.ccx(flag[0],flag[1],flag2[0]) qc.x(flag[0]) for i in range(5): for j in range(i+1,6): for k in range(0,6): if(k!=i and k!=j): m=int(problem[k][0]) n=int(problem[k][1]) qc.cx(ad_sw,row[m]) qc.cx(ad_sw,column[n]) qc.mct([row[0],row[1],row[2],row[3],column[0],column[1],column[2],column[3],flag[0]],flag[1],ancilla,mode='basic') qc.mct([row[0],row[1],row[2],row[3],column[0],column[1],column[2],column[3]],flag[1],ancilla,mode='basic') for k in range(0,6): if(k!=i and k!=j): m=int(problem[k][0]) n=int(problem[k][1]) qc.cx(ad_sw,row[m]) qc.cx(ad_sw,column[n]) #address set up----------------------------------------- qc.mct(ad,ad_sw[0],ancilla,mode='basic') #x gate for b in range(4): if bi_16[a][b]==0: qc.x(ad[3-b]) a=a+1 qc.append(diffuser(4),[0,1,2,3]) qc.measure(ad,cbits) qasm_simulator = Aer.get_backend('qasm_simulator') result = execute(qc, backend=qasm_simulator, shots=1024).result() plot_histogram(result.get_counts()) #qc.draw() qc.measure(flag,cbits) qasm_simulator = Aer.get_backend('qasm_simulator') result = execute(qc, backend=qasm_simulator, shots=1024).result() plot_histogram(result.get_counts()) def counter(qc,r_or_c,auxiliary): for i in range(len(r_or_c)): qc.mct([r_or_c[i],auxiliary[0],auxiliary[1]],auxiliary[2],mode='noancilla') qc.ccx(r_or_c[i],auxiliary[0],auxiliary[1]) qc.cx(r_or_c[i],auxiliary[0]) def counterd(qc,r_or_c,auxiliary): for i in range(len(r_or_c)): qc.cx(r_or_c[3-i],auxiliary[0]) qc.ccx(r_or_c[3-i],auxiliary[0],auxiliary[1]) qc.mct([r_or_c[3-i],auxiliary[0],auxiliary[1]],auxiliary[2],mode='noancilla') def diffuser(nqubits): qc = QuantumCircuit(nqubits) # Apply transformation |s> -> |00..0> (H-gates) for qubit in range(nqubits): qc.h(qubit) # Apply transformation |00..0> -> |11..1> (X-gates) for qubit in range(nqubits): qc.x(qubit) # Do multi-controlled-Z gate qc.h(nqubits-1) qc.mct(list(range(nqubits-1)), nqubits-1) # multi-controlled-toffoli qc.h(nqubits-1) # Apply transformation |11..1> -> |00..0> for qubit in range(nqubits): qc.x(qubit) # Apply transformation |00..0> -> |s> for qubit in range(nqubits): qc.h(qubit) # We will return the diffuser as a gate U_s = qc.to_gate() U_s.name = "$U_diff$" return U_s qc.h(ad) qc.x(flag) qc.h(flag) i=0 for problem in problem_set: #x gate for j in range(4): if bi_16[i][j]==0: qc.x(ad[3-j]) #ad--mct-->ad_sw qc.mct(ad,ad_sw[0],mode='noancilla') #address set up------------------------------------------ for area in problem: j=int(area[0]) k=int(area[1]) qc.cx(ad_sw[0],row[j]) qc.cx(ad_sw[0],column[k]) qc.barrier() counter(qc,row,ct_r) counter(qc,column,ct_c) #------flip 1 qc.x(ct_r[0]) qc.x(ct_r[2]) qc.x(ct_c[0]) qc.x(ct_c[2]) qc.mct([ct_r[:],ct_c[:]]) qc.x(ct_r[0]) qc.x(ct_r[2]) qc.x(ct_c[0]) qc.x(ct_c[2]) #-------flip 2 #-------flip 3 counter(qc,column,ct_c) counter(qc,row,ct_r) qc.barrier() for area in problem: j=int(area[0]) k=int(area[1]) qc.cx(ad_sw[0],row[j]) qc.cx(ad_sw[0],column[k]) #address set up------------------------------------------ qc.mct(ad,ad_sw[0],mode='noancilla') #x gate for j in range(4): if bi_16[i][j]==0: qc.x(ad[3-j]) i=i+1 qc.append(diffuser(4),[0,1,2,3]) qc.measure(ad,cbits) qasm_simulator = Aer.get_backend('qasm_simulator') result = execute(qc, backend=qasm_simulator, shots=1024).result() plot_histogram(result.get_counts()) qc.draw() ad= QuantumRegister(4, name='ad') ad_sw = QuantumRegister(1, name='ad_sw') row = QuantumRegister(4, name='row') column = QuantumRegister(4, name='column') ct = QuantumRegister(3, name='ct') flag = QuantumRegister(1, name='flag') cbits = ClassicalRegister(3,name='c') problem_set = \ [[['0', '2'], ['1', '0'], ['1', '2'], ['1', '3'], ['2', '0'], ['3', '3']], [['0', '0'], ['0', '1'], ['1', '2'], ['2', '2'], ['3', '0'], ['3', '3']], [['0', '0'], ['1', '1'], ['1', '3'], ['2', '0'], ['3', '2'], ['3', '3']], [['0', '0'], ['0', '1'], ['1', '1'], ['1', '3'], ['3', '2'], ['3', '3']], [['0', '2'], ['1', '0'], ['1', '3'], ['2', '0'], ['3', '2'], ['3', '3']], [['1', '1'], ['1', '2'], ['2', '0'], ['2', '1'], ['3', '1'], ['3', '3']], [['0', '2'], ['0', '3'], ['1', '2'], ['2', '0'], ['2', '1'], ['3', '3']], [['0', '0'], ['0', '3'], ['1', '2'], ['2', '2'], ['2', '3'], ['3', '0']], [['0', '3'], ['1', '1'], ['1', '2'], ['2', '0'], ['2', '1'], ['3', '3']], [['0', '0'], ['0', '1'], ['1', '3'], ['2', '1'], ['2', '3'], ['3', '0']], [['0', '1'], ['0', '3'], ['1', '2'], ['1', '3'], ['2', '0'], ['3', '2']], [['0', '0'], ['1', '3'], ['2', '0'], ['2', '1'], ['2', '3'], ['3', '1']], [['0', '1'], ['0', '2'], ['1', '0'], ['1', '2'], ['2', '2'], ['2', '3']], [['0', '3'], ['1', '0'], ['1', '3'], ['2', '1'], ['2', '2'], ['3', '0']], [['0', '2'], ['0', '3'], ['1', '2'], ['2', '3'], ['3', '0'], ['3', '1']], [['0', '1'], ['1', '0'], ['1', '2'], ['2', '2'], ['3', '0'], ['3', '1']]] problem=[['0', '2'], ['1', '0'], ['1', '2'], ['1', '3'], ['2', '0'], ['3', '3']] qc = QuantumCircuit(ad,ad_sw,row,column,ct,flag, cbits) qc.x(ad_sw) for area in problem: j=int(area[0]) k=int(area[1]) qc.cx(ad_sw[0],row[j]) qc.cx(ad_sw[0],column[k]) qc.barrier() counter(qc,row,column,ct) qc.measure(ct,cbits) """ qc.x(ct[0]) qc.ccx(ct[0],ct[2],flag) qc.x(ct[0]) counterd(qc,row,column,ct) qc.barrier() for area in problem: j=int(area[0]) k=int(area[1]) qc.cx(ad_sw[0],row[j]) qc.cx(ad_sw[0],column[k]) qc.measure(flag,cbits) """ qasm_simulator = Aer.get_backend('qasm_simulator') result = execute(qc, backend=qasm_simulator, shots=1024).result() plot_histogram(result.get_counts()) qc.draw()
https://github.com/coder-bean/kisskitqiskit
coder-bean
from qiskit import QuantumCircuit, execute, Aer from qiskit.visualization import plot_histogram import numpy as np #prepares the initial quantum states for the BB84 protocol by generating a list of quantum states and their associated bases. def prepare_bb84_states(num_qubits): states = [] bases = [] for _ in range(num_qubits): state, basis = generate_bb84_state() states.append(state) bases.append(basis) return states, bases #generates a single BB84 quantum state and its associated measurement basis. def generate_bb84_state(): basis = np.random.randint(2) # 0 for rectilinear basis, 1 for diagonal basis if np.random.rand() < 0.5: state = QuantumCircuit(1, 1) if basis == 0: state.h(0) else: state.s(0) state.h(0) else: state = QuantumCircuit(1, 1) if basis == 0: state.x(0) state.h(0) else: state.x(0) state.s(0) state.h(0) return state, basis #measures the quantum states with the appropriate basis and returns the measurement results def measure_bb84_states(states, bases): measurements = [] for state, basis in zip(states, bases): if basis == 0: state.measure(0, 0) else: state.h(0) state.measure(0, 0) measurements.append(state) return measurements #sifts the keys by comparing Alice and Bob's measurement bases and bits. It checks if the measurement bases match (the same basis) and appends the corresponding bits to the sifted keys def sift_keys(alice_bases, bob_bases, alice_bits, bob_bits): sifted_alice_bits = [] sifted_bob_bits = [] for a_basis, b_basis, a_bit, b_bit in zip(alice_bases, bob_bases, alice_bits, bob_bits): if a_basis == b_basis: sifted_alice_bits.append(a_bit) sifted_bob_bits.append(b_bit) return sifted_alice_bits, sifted_bob_bits #calculates the error rate between Alice's and Bob's sifted bits def error_rate(alice_bits, bob_bits): errors = sum([1 for a, b in zip(alice_bits, bob_bits) if a != b]) return errors / len(alice_bits) # simulates the BB84 protocol num_qubits = 100 num_qubits = 100 alice_states, alice_bases = prepare_bb84_states(num_qubits) bob_bases = np.random.randint(2, size=num_qubits) bob_measurements = measure_bb84_states(alice_states, bob_bases) alice_bits = [] for state in alice_states: result = execute(state, Aer.get_backend('qasm_simulator')).result() counts = result.get_counts(state) max_count = max(counts, key=counts.get) alice_bits.append(int(max_count)) bob_bits = [] for state in bob_measurements: result = execute(state, Aer.get_backend('qasm_simulator')).result() counts = result.get_counts(state) max_count = max(counts, key=counts.get) bob_bits.append(int(max_count)) sifted_alice_bits, sifted_bob_bits = sift_keys(alice_bases, bob_bases, alice_bits, bob_bits) error = error_rate(sifted_alice_bits, sifted_bob_bits) final_key = privacy_amplification(sifted_alice_bits) print("Sifted key length:", len(sifted_alice_bits)) print("Error rate:", error) print("Final secret key:", final_key)
https://github.com/muehlhausen/vqls-bachelor-thesis
muehlhausen
# all libraries used by some part of the VQLS-implementation from qiskit import ( QuantumCircuit, QuantumRegister, ClassicalRegister, IBMQ, Aer, execute, transpile, assemble ) from qiskit.circuit import Gate, Instruction from qiskit.quantum_info.operators import Operator from qiskit.extensions import ZGate, YGate, XGate, IGate from scipy.optimize import ( minimize, basinhopping, differential_evolution, shgo, dual_annealing ) import random import numpy as np import cmath from typing import List, Set, Dict, Tuple, Optional, Union # import the params object of the GlobalParameters class # this provides the parameters used to desribed and model # the problem the minimizer is supposed to use. from GlobalParameters_IBMQ import params # import the vqls algorithm and corresponding code from vqls_IBMQ import ( generate_ansatz, hadamard_test, calculate_beta, calculate_delta, calculate_local_cost_function, minimize_local_cost_function, postCorrection, _format_alpha, _calculate_expectationValue_HadamardTest, _U_YZ, _U_adjoint_YZ ) # The user input for the VQLS-algorithm has to be given # when params is initialized within GlobalParameters.py # The decomposition for $A$ has to be manually # inserted into the code of # the class GlobalParameters. print( "This program will execute the VQLS-algorithm on the IBMQ-Manila quantum computer " + "with 4 qubits, 2 layers in the Ansatz and an Id gate acting" + " on the third qubit (qubit_2).\n" + "|x_0> is defined by Hadamard gates acting on qubits 0, 2, 3." ) # Executing the actual VQLS-algorithm alpha_min = minimize_local_cost_function(params.method_minimization) """ Circuit with the $\vec{alpha}$ generated by the minimizer. """ # Create a circuit for the vqls-result qr_min = QuantumRegister(params.n_qubits) circ_min = QuantumCircuit(qr_min) # generate $V(\vec{alpha})$ ansatz = generate_ansatz(alpha_min).to_gate() # apply $V(\vec{alpha})$ and $A$ to the circuit # this results in the state $\ket{b}$ circ_min.append(ansatz, qr_min) # as $A$ is Id nothing happens # apply post correction to fix for sign errors and a "mirroring" # of the result circ_min = postCorrection(circ_min) """ Reference circuit based on the definition of $\ket{b}$. """ circ_ref = _U_YZ() """ Simulate both circuits. """ # the minimizations result backend = Aer.get_backend( 'statevector_simulator') t_circ = transpile(circ_min, backend) qobj = assemble(t_circ) job = backend.run(qobj) result = job.result() print( "This is the result of the execution on a real quantum computer.\n" + "Reminder: 4 qubits and an Id-gate on the third qubit." + "|x_0> was defined by Hadamard gates acting on qubits 0, 2 and 3.\n" + "The list returned by the minimizer (alpha_min):\n" + str(alpha_min) + "\nWith it a circuit is built and simulated. The resulting statevector is" + ", with V(alpha_min) and A and the post correction applied:\n" + str(result.get_statevector()) ) # the reference t_circ = transpile(circ_ref, backend) qobj = assemble(t_circ) job = backend.run(qobj) result = job.result() print( "And this is the statevector for the reference circuit: A |x_0>\n" + str(result.get_statevector()) )
https://github.com/muehlhausen/vqls-bachelor-thesis
muehlhausen
from qiskit import ( QuantumCircuit, QuantumRegister, ClassicalRegister, IBMQ, Aer, execute, transpile, assemble ) from qiskit.circuit import Gate, Instruction from qiskit.quantum_info.operators import Operator from qiskit.extensions import ZGate, YGate, XGate, IGate from scipy.optimize import ( minimize, basinhopping, differential_evolution, shgo, dual_annealing ) import random import numpy as np import cmath from typing import List, Set, Dict, Tuple, Optional, Union """ ######### Global Parameters Those parameters are required by almost all functions but do not need to be changed during runtime. As one might want to change them between program executions it is sensible to have them accesible and in one place. """ class GlobalParameters: def _init_alpha_randomly(self) -> List[float]: """ This function initalizes alpha randomly. """ # how many parameters are required n_alpha_i = self.n_qubits + self.n_layers * (self.n_qubits-1) * 2 alpha_rand = [float(random.randint(0, 6283))/1000 for _ in range(n_alpha_i)] return alpha_rand def _decompose_asGate(self, gate: str) -> List[Gate]: """ This function returns a list of Gate-Objects of length n_qubits. The first item is the Gate applied to the first qubit, the last item is the Gate applied to the last qubit. """ dec_asGate: List[Gate] = [] for i in range(self.n_qubits): temp = QuantumCircuit(self.n_qubits) if gate == "Z": temp.z(i) elif gate == "Y": temp.y(i) elif gate == "X": temp.x(i) elif gate == "Id": temp.x(i) temp.x(i) elif gate == "ZY": temp.z(i) temp.y(i) elif gate == "YZ": temp.y(i) temp.z(i) temp.to_gate() dec_asGate.append(temp) return dec_asGate def _decompositions(self): """ This helper function is used to prepare some lists with standard decompositions that might be used to set together A. Those lists are stored in the class. """ # ZY Gates self.decomposition_asGate_YZ = self._decompose_asGate("YZ") self.decomposition_adjoint_YZ = self._decompose_asGate("ZY") # Identity Gates self.decomposition_asGate_Id = self._decompose_asGate("Id") self.decomposition_adjoint_Id = self.decomposition_asGate_Id def __init__(self, n_qubits: int, n_layers: int, coefficients: List[complex], IBMQ_TOKEN: str, COBYLA_maxiter: int = 150, IBMQ_shots: int = 4096, IBMQ_backend: str = 'statevector_simulator', method_minimization: str = 'COBYLA', ): self.n_qubits = n_qubits # alpha has form: [[0th sublayer], [1st sublayer], [2nd sublayer], ... ] self.n_layers = n_layers self.n_sublayers = 1 + 2 * self.n_layers self.coefficients = coefficients self.coefficients_conjugate = [np.conjugate(coeff) for coeff in self.coefficients] self.COBYLA_maxiter = COBYLA_maxiter self.method_minimization = method_minimization """ Preparing IBMQ """ self.IBMQ_load_account = IBMQ.enable_account(IBMQ_TOKEN) self.IBMQ_account = IBMQ.save_account(IBMQ_TOKEN) self.IBMQ_provider = IBMQ.load_account() self.IBMQ_backend = self.IBMQ_provider.backend.ibmq_manila self.IBMQ_shots = IBMQ_shots # initialize the parameters for the Ansatz randomly self.alpha_0 = self._init_alpha_randomly() self._decompositions() """ Only things below this line require user interaction in the classes code (normally). """ """ The following lines present an example on how to define A and its decomposition. """ self.decomposition_asGate = self.decomposition_asGate_Id self.decomposition_adjoint = self.decomposition_adjoint_Id # This instance of the class is imported and used by all other modules. # Use it to model your physcal problem. # To change A or its decomposition you have to modify the code of the class itself. params = GlobalParameters( n_qubits=4, n_layers=2, coefficients=[complex(0, 0), complex(0, 0), complex(1, 0), complex(0, 0)], IBMQ_TOKEN="Insert your token here!", COBYLA_maxiter=100, IBMQ_shots=8192 )
https://github.com/muehlhausen/vqls-bachelor-thesis
muehlhausen
""" Import all required libraries. """ from qiskit import ( QuantumCircuit, QuantumRegister, ClassicalRegister, IBMQ, Aer, execute, transpile, assemble ) from qiskit.circuit import Gate, Instruction from qiskit.quantum_info.operators import Operator from qiskit.extensions import ZGate, YGate, XGate, IGate from scipy.optimize import ( minimize, basinhopping, differential_evolution, shgo, dual_annealing ) import random import numpy as np import cmath from typing import List, Set, Dict, Tuple, Optional, Union # import the params object of the GlobalParameters class # this provides the parameters used to desribed and model # the problem the minimizer is supposed to use. from GlobalParameters_IBMQ import params """ This program provides an implementation of the Variational Quantum Linear Solver as presented by Bravo-Prieto et al. It is implemented for the QISKIT Quantum SDK. This version of the program uses the local cost function. Author: Alexander Cornelius Muehlhausen ######################################################################### ######### Core functions The core functions of the VQLS algorithm. """ def generate_ansatz(alpha: List[float]) -> QuantumCircuit: """ This function returns a circuit that implements the Ansatz V(alpha). """ qr_ansatz = QuantumRegister(params.n_qubits) circ_ansatz = QuantumCircuit(qr_ansatz) if not any(isinstance(item, list) for item in alpha): # this will reformat the list alpha to the required format (if needed) # this is necessary as the minimizer returns a list without sublists alpha = _format_alpha(alpha) # 0th sublayer for qubit in range(0, params.n_qubits): circ_ansatz.ry(alpha[0][qubit], qr_ansatz[qubit]) if params.n_qubits % 2 == 0: # all other sublayers for sublayer in range(1, 2 * params.n_layers, 2): # first sublayer of the current layer # controlled Z-Gate pairs for qubit_a, qubit_b in zip(qr_ansatz[::2], qr_ansatz[1::2]): circ_ansatz.cz(qubit_a, qubit_b) for rotation_param, qubit in zip(alpha[sublayer], qr_ansatz): circ_ansatz.ry(rotation_param, qubit) # second sublayer of the current layer for qubit_a, qubit_b in zip(qr_ansatz[1::2], qr_ansatz[2::2]): circ_ansatz.cz(qubit_a, qubit_b) # and Ry to each qubit except the first and last one for rotation_param, qubit in zip(alpha[sublayer+1], qr_ansatz[1::]): circ_ansatz.ry(rotation_param, qubit) else: # all other sublayers for sublayer in range(1, 2 * params.n_layers, 2): # first sublayer of the current layer for qubit_a, qubit_b in zip(qr_ansatz[:params.n_qubits-1:2], qr_ansatz[1:params.n_qubits-1:2]): circ_ansatz.cz(qubit_a, qubit_b) for rotation_param, qubit in zip(alpha[sublayer], qr_ansatz[:params.n_qubits-1:]): circ_ansatz.ry(rotation_param, qubit) # second sublayer for qubit_a, qubit_b in zip(qr_ansatz[1::2], qr_ansatz[2::2]): circ_ansatz.cz(qubit_a, qubit_b) for rotation_param, qubit in zip(alpha[sublayer+1], qr_ansatz[1::]): circ_ansatz.ry(rotation_param, qubit) return circ_ansatz def hadamard_test( *, ansatz: Union[Gate, Operator] = None, first: Union[Gate, Operator] = None, first_uncontrolled: Union[Gate, Operator] = None, j: int = None, second_uncontrolled: Union[Gate, Operator] = None, second: Union[Gate, Operator] = None, im=None ): """ This function returns a circuit that implements the Hadamard Test. The ancilliary qubit is the last qubit; a measurement is applied to it. """ # prep of QuantumCircuit qr_had = QuantumRegister(params.n_qubits) circ_had = QuantumCircuit(qr_had) ancilla = QuantumRegister(1, name="ancilla") cr_had = ClassicalRegister(1) circ_had.add_register(ancilla) circ_had.add_register(cr_had) qubits_designation_control = [i for i in range(params.n_qubits)] qubits_designation_control.insert(0, params.n_qubits) def append_ifExists(obj: Union[Gate, Operator], control=False): """ Append gates to a circuit. Convert them to instructions if necessary. Control them if necessary. """ if isinstance(obj, (Gate, Operator, Instruction, QuantumCircuit)): _obj = obj.copy() if isinstance(_obj, Operator): _obj = _obj.to_instruction() if control is True: _obj = _obj.control(1) circ_had.append(_obj, qubits_designation_control) else: circ_had.append(_obj, qr_had) # act on the ancilla circ_had.h(ancilla) # if Im(<>) shall be calculated if im is not None: circ_had.sdg(ancilla) append_ifExists(ansatz) # clean up the circuit circ_had.barrier() # use this for $A_l$ append_ifExists(first, True) # use this for $U^{\dagger} append_ifExists(first_uncontrolled) # $Z_j$ if j is not None: circ_had.cz(params.n_qubits, qr_had[j]) # use this for $U$ append_ifExists(second_uncontrolled) # use this for $A^{\dagger}_m$ append_ifExists(second, True) # clean up the circuit circ_had.barrier() # last operation on the ancilla & measurement circ_had.h(ancilla) circ_had.measure(ancilla, cr_had) return circ_had def calculate_beta(alpha: List[float]) -> List[List[complex]]: """ This function calculates all parameters $\beta_{lm}$ that are required, i.e. all parameters with l, m so that $c_l$ and $c^{*}_m$ are not equal to 0. """ # preparation of the result list beta = [[complex(0, 0) for _ in params.coefficients] for _ in params.coefficients_conjugate] # generate Ansatz outside the loops for better performance V = generate_ansatz(alpha).to_gate() # $A_l, (l, c_l)$ for gate_l, (l, coeff_l) in zip(params.decomposition_asGate, enumerate(params.coefficients)): if coeff_l == 0: continue # increase perfomance by ommiting unused $\beta$ # $A^{\dagger}_m, (m, c^{*}_m)$ for gate_m_adj, (m, coeff_m) in zip(params.decomposition_adjoint, enumerate(params.coefficients_conjugate)): if coeff_m == 0: continue # increase perfomance by ommiting unused $\beta$ # circuit for Re ( <0| V(alpha)(+) A_m(+) A_l V(alpha) |0>) circ_had_re = hadamard_test(ansatz=V, first=gate_l, second=gate_m_adj) # circuit for Im ( <0| V(alpha)(+) A_m(+) A_l V(alpha) |0>) circ_had_im = hadamard_test(ansatz=V, first=gate_l, second=gate_m_adj, im=1) # calculate Re and Im of $\beta_{lm}$ / simulate circuits expV_had_re = _calculate_expectationValue_HadamardTest(circ_had_re) expV_had_im = _calculate_expectationValue_HadamardTest(circ_had_im) # set together $\beta_{lm}$ from its real and imaginary part expV_had = complex(expV_had_re, expV_had_im) beta[l][m] = expV_had return beta def calculate_delta(alpha: List[float], beta: List[List[complex]]) -> List[List[complex]]: """ This function calculates all $\delta_{lm}$ that are required, i.e. all parameters with l, m so that $c_l$ and $c^{*}_m$ are not equal to 0. """ # initialize the list for the results delta = [[complex(0, 0) for _ in params.coefficients] for _ in params.coefficients_conjugate] # prepare $V(\vec{alpha})$, $U$ and $U^{\dagger}$ V = generate_ansatz(alpha).to_gate() U = _U_Id().to_gate() U_dagger = _U_Id().to_gate() # $A_l, (l, c_l)$ for gate_l, (l, coeff_l) in zip(params.decomposition_asGate, enumerate(params.coefficients)): if coeff_l == 0: continue # increase perfomance by ommiting unused $\delta$ # $A^{\dagger}_m, (m, c^{*}_m)$ for gate_m_adj, (m, coeff_m) in zip( params.decomposition_adjoint, enumerate(params.coefficients_conjugate) ): if coeff_m == 0: continue # increase perfomance by ommiting unused $\delta$ temp = beta[l][m] # 1/n_qubits sum_j <0| V(+) A_m(+) U (Z_j * 1_{j-bar}) U(+) A_l V |0> for j in range(params.n_qubits): # Re(<0| V(+) A_m(+) U (Z_j * 1_{j-bar}) U(+) A_l V |0>) circ_had_re = hadamard_test( ansatz=V, first=gate_l, first_uncontrolled=U_dagger, j=j, second_uncontrolled=U, second=gate_m_adj) # Im(<0| V(+) A_m(+) U (Z_j * 1_{j-bar}) U(+) A_l V |0>) circ_had_im = hadamard_test( ansatz=V, first=gate_l, first_uncontrolled=U_dagger, j=j, second_uncontrolled=U, second=gate_m_adj, im=1) # calculate Re and Im of $\delta_{lm}$ / simulate circuits expV_had_re = _calculate_expectationValue_HadamardTest(circ_had_re) expV_had_im = _calculate_expectationValue_HadamardTest(circ_had_im) # set together $\delta_{lm}$ from its real and imaginary part # and execute the summation expV_had = complex(expV_had_re, expV_had_im) temp += 1/params.n_qubits * expV_had delta[l][m] = temp return delta def calculate_local_cost_function(alpha: List[float]) -> Union[complex, float]: """ returns cost = <x| H_local |x> / <psi|psi> with <x| H_local |x> = Sum_l_m c_l c_m(*) delta <psi|psi> = Sum_l_m c_l c_m(*) beta """ beta = calculate_beta(alpha) delta = calculate_delta(alpha, beta) xHx = 0 psipsi = 0 for l, coeff_l in enumerate(params.coefficients): for m, coeff_m_conj in enumerate(params.coefficients_conjugate): xHx += coeff_l * coeff_m_conj * delta[l][m] psipsi += coeff_l * coeff_m_conj * beta[l][m] # cost = xHx / psipsi cost = abs(xHx/psipsi) print(alpha) print("local cost function " + str(cost)) return cost def minimize_local_cost_function(method: str) -> List[float]: """ This function minimizes the local cost function. It returns the alpha for which the approximation A V(alpha_out) |0> approx |b> is optimal. Implements scipy.optimize.minimize . """ min = minimize(calculate_local_cost_function, x0=params.alpha_0, method=method, options={'maxiter': params.COBYLA_maxiter}) print(min) alpha_out = min['x'] print(alpha_out) return alpha_out """ Fix the result. """ def postCorrection(qc: QuantumCircuit) -> QuantumCircuit: """ This function is used to apply post correction to the circuit generated by applying V(alpha) and A as the result is not identical to |b>. The result of a circuit built using the functions presented above returns the reverse of b with random sign errors. """ for i in range(params.n_qubits): qc.x(i) qc.z(i) return qc """ ######### Helper functions Functions that do not add to the logic of the algorithm but instead implement often used features or need to be changed sometimes. """ def _format_alpha(alpha_unformated: List[float]) -> List[List[float]]: """ This function formats a list to be in the correct form for the function that builds V(alpha). This means it will format the list to be of the form: [[0th sublayer], [1st sublayer], [2nd sublayer], ...] So for e.g. 4 qubits it will return (- stands for some random value): [[-,-,-,-],[-,-,-,-],[-,-],[-,-,-,-],[-,-]] and for e.g. 3 qubits: [[-,-],[-,-],[-,-],[-,-],[-,-]] """ alpha_formated = [] if any(isinstance(item, list) for item in alpha_unformated): return alpha_unformated else: if (params.n_qubits % 2) == 0: start = 0 end = params.n_qubits alpha_formated.append(alpha_unformated[start:params.n_qubits]) for _ in range(params.n_layers): start = end end = start + params.n_qubits alpha_formated.append(alpha_unformated[start:end]) start = end end = start + params.n_qubits - 2 alpha_formated.append(alpha_unformated[start:end]) else: start = 0 end = params.n_qubits alpha_formated.append(alpha_unformated[start:end]) for _ in range(params.n_layers): start = end end = start + params.n_qubits-1 alpha_formated.append(alpha_unformated[start:end]) start = end end = start + params.n_qubits - 1 alpha_formated.append(alpha_unformated[start:end]) return alpha_formated def _calculate_expectationValue_HadamardTest(circ_had: QuantumCircuit) -> float: """ Will return the expectation value for a given circuit for a Hadamard test. Supports different backends. Based on the IBM Quantum and the Qiskit documentations. """ backend = params.IBMQ_backend transpiled_circ = transpile(circ_had, backend) job = backend.run(transpiled_circ) result = job.result() counts = result.get_counts(circ_had) p_0 = counts.get('0', 0) p_1 = counts.get('1', 0) return ((p_0 - p_1) / params.IBMQ_shots) def _U_YZ() -> QuantumCircuit: """ This function generates a circuit that resembles a U gate that fulfills: U |0> = |b> . Hadamard Gates on qubits 0, 2 and 3; y and then z Gate on qubit 2. """ qr_U_primitive = QuantumRegister(params.n_qubits) circ_U_primitive = QuantumCircuit(qr_U_primitive) circ_U_primitive.h(0) # circ_U_primitive.h(1) circ_U_primitive.h(2) circ_U_primitive.h(3) circ_U_primitive.y(2) circ_U_primitive.z(2) return circ_U_primitive def _U_adjoint_YZ() -> QuantumCircuit: """ This function generates a circuit that resembles $U^{\dagger}$ for: U |0> = |b> . U was: Hadamard Gates on qubits 0, 2 and 3; y and then z Gate on qubit 2. """ qr_U_primitive = QuantumRegister(params.n_qubits) circ_U_primitive = QuantumCircuit(qr_U_primitive) circ_U_primitive.z(2) circ_U_primitive.y(2) circ_U_primitive.h(0) # circ_U_primitive.h(1) circ_U_primitive.h(2) circ_U_primitive.h(3) return circ_U_primitive def _U_Id() -> QuantumCircuit: """ This function generates a circuit that resembles a U gate that fulfills: U |0> = |b> . Hadamard Gates on qubits 0, 2 and 3. """ qr_U_primitive = QuantumRegister(params.n_qubits) circ_U_primitive = QuantumCircuit(qr_U_primitive) circ_U_primitive.h(0) # circ_U_primitive.h(1) circ_U_primitive.h(2) circ_U_primitive.h(3) return circ_U_primitive
https://github.com/muehlhausen/vqls-bachelor-thesis
muehlhausen
# all libraries used by some part of the VQLS-implementation from qiskit import ( QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, execute, transpile, assemble ) from qiskit.circuit import Gate, Instruction from qiskit.quantum_info.operators import Operator from qiskit.extensions import ZGate, YGate, XGate, IGate from scipy.optimize import ( minimize, basinhopping, differential_evolution, shgo, dual_annealing ) import random import numpy as np import cmath from typing import List, Set, Dict, Tuple, Optional, Union # import the params object of the GlobalParameters class # this provides the parameters used to desribed and model # the problem the minimizer is supposed to use. from GlobalParameters import params # import the vqls algorithm and corresponding code from vqls import ( generate_ansatz, hadamard_test, calculate_beta, calculate_delta, calculate_local_cost_function, minimize_local_cost_function, postCorrection, _format_alpha, _calculate_expectationValue_HadamardTest, _U_primitive ) # The user input for the VQLS-algorithm has to be given # when params is initialized within GlobalParameters.py # The decomposition for $A$ has to be manually # inserted into the code of # the class GlobalParameters. print( "This program will execute a simulation of the VQLS-algorithm " + "with 4 qubits, 4 layers in the Ansatz and a single Id-gate acting" + " on the second qubit.\n" + "To simulate another problem, one can either alter _U_primitive " + "in vqls.py to change |x_0>, GlobalParameters.py to change A " + "or its decomposition respectively." ) # Executing the VQLS-algorithm alpha_min = minimize_local_cost_function(params.method_minimization) """ Circuit with the $\vec{alpha}$ generated by the minimizer. """ # Create a circuit for the vqls-result qr_min = QuantumRegister(params.n_qubits) circ_min = QuantumCircuit(qr_min) # generate $V(\vec{alpha})$ and copy $A$ ansatz = generate_ansatz(alpha_min).to_gate() A_copy = params.A.copy() if isinstance(params.A, Operator): A_copy = A_copy.to_instruction() # apply $V(\vec{alpha})$ and $A$ to the circuit # this results in a state that is approximately $\ket{b}$ circ_min.append(ansatz, qr_min) circ_min.append(A_copy, qr_min) # apply post correction to fix for sign errors and a "mirroring" # of the result circ_min = postCorrection(circ_min) """ Reference circuit based on the definition of $\ket{b}$. """ circ_ref = _U_primitive() """ Simulate both circuits. """ # the minimizations result backend = Aer.get_backend( 'statevector_simulator') t_circ = transpile(circ_min, backend) qobj = assemble(t_circ) job = backend.run(qobj) result = job.result() print( "This is the result of the simulation.\n" + "Reminder: 4 qubits and an Id-gate on the second qubit." + "|x_0> was defined by Hadamard gates acting on qubits 0 and 3.\n" + "The return value of the minimizer (alpha_min):\n" + str(alpha_min) + "\nThe resulting statevector for a circuit to which " + "V(alpha_min) and A and the post correction were applied:\n" + str(result.get_statevector()) ) t_circ = transpile(circ_ref, backend) qobj = assemble(t_circ) job = backend.run(qobj) result = job.result() print( "And this is the statevector for the reference circuit: A |x_0>\n" + str(result.get_statevector()) ) print("these were Id gates and in U y on 0 and 1")
https://github.com/muehlhausen/vqls-bachelor-thesis
muehlhausen
from qiskit import ( QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, execute, transpile, assemble ) from qiskit.circuit import Gate, Instruction from qiskit.quantum_info.operators import Operator from qiskit.extensions import ZGate, YGate, XGate, IGate from scipy.optimize import ( minimize, basinhopping, differential_evolution, shgo, dual_annealing ) import random import numpy as np import cmath from typing import List, Set, Dict, Tuple, Optional, Union """ ######### Global Parameters Those parameters are required by almost all functions but do not need to be changed during runtime. As one might want to change them between program executions it is very helpful to have them accesible and in one place. """ class GlobalParameters: def _init_alpha_randomly(self) -> List[float]: """ This function initalizes alpha randomly. """ # how many parameters are required n_alpha_i = self.n_qubits + self.n_layers * (self.n_qubits-1) * 2 alpha_rand = [float(random.randint(0, 6283))/1000 for _ in range(n_alpha_i)] return alpha_rand def _decompose_asOperator(self, gate: str) -> List[Operator]: """ This function returns a list of Operator-Objects of length n_qubits. The first item is the Operator representing a Z gate acting on the first qubit. The last item is the Operator representing a Z gate acting on the last qubit. """ if gate == "Z": Op = Operator(ZGate()) elif gate == "X": Op = Operator(XGate()) elif gate == "Y": Op = Operator(YGate()) elif gate == "Id": Op = Operator(IGate()) Id = Operator(IGate()) dec_asOperator: List[Operator] = [] # Operator acting on the last qubit temp1 = Op.copy() for _ in range(self.n_qubits - 1): temp1 = temp1.tensor(Id) dec_asOperator.insert(0, temp1) # all other qubits for x in range(self.n_qubits - 1): i = x+1 temp = Id for j in range(i-1): temp = temp.tensor(Id) temp = temp.tensor(Op) for j in range(self.n_qubits - i - 1): temp = temp.tensor(Id) dec_asOperator.insert(0, temp) return dec_asOperator def _decompose_asGate(self, gate: str) -> List[Gate]: """ This function returns a list of Gate-Objects of length n_qubits. The first item is the Gate applied to the first qubit, the last item is the Gate applied to the last qubit. """ dec_asGate: List[Gate] = [] for i in range(self.n_qubits): temp = QuantumCircuit(self.n_qubits) if gate == "Z": temp.z(i) elif gate == "Y": temp.y(i) elif gate == "X": temp.x(i) elif gate == "Id": temp.x(i) temp.x(i) temp.to_gate() dec_asGate.append(temp) return dec_asGate def _decompositions(self): """ This helper function is used to prepare some lists with standard decompositions that might be used to set together A. Those lists are stored in the class. """ # Z Gates self.decomposition_asGate_Z = self._decompose_asGate("Z") self.decomposition_asOperator_Z = self._decompose_asOperator("Z") # [A_0(+), A_1(+), ...] self.decomposition_adjoint_asOperator_Z = [op.adjoint() for op in self.decomposition_asOperator_Z] # Y Gates self.decomposition_asGate_Y = self._decompose_asGate("Y") self.decomposition_asOperator_Y = self._decompose_asOperator("Y") # [A_0(+), A_1(+), ...] self.decomposition_adjoint_asOperator_Y = [operator.adjoint() for operator in self.decomposition_asOperator_Y] # X Gates self.decomposition_asGate_X = self._decompose_asGate("X") self.decomposition_asOperator_X = self._decompose_asOperator("X") # [A_0(+), A_1(+), ...] self.decomposition_adjoint_asOperator_X = [operator.adjoint() for operator in self.decomposition_asOperator_X] # Identity Gates self.decomposition_asGate_Id = self._decompose_asGate("Id") self.decomposition_asOperator_Id = self._decompose_asOperator("Id") # [A_0(+), A_1(+), ...] self.decomposition_adjoint_asOperator_Id = [operator.adjoint() for operator in self.decomposition_asOperator_Id] def __init__(self, n_qubits: int, n_layers: int, coefficients: List[complex], COBYLA_maxiter: int = 150, qiskit_simulation_shots: int = 10**3, qiskit_simulation_backend: str = 'qasm_simulator', method_minimization: str = 'COBYLA'): self.n_qubits = n_qubits # alpha has form: [[0th sublayer], [1st sublayer], [2nd sublayer], ... ] self.n_layers = n_layers self.n_sublayers = 1 + 2 * self.n_layers self.coefficients = coefficients self.coefficients_conjugate = [np.conjugate(coeff) for coeff in self.coefficients] self.COBYLA_maxiter = COBYLA_maxiter self.qiskit_simulation_backend = qiskit_simulation_backend self.qiskit_simulation_shots = qiskit_simulation_shots self.method_minimization = method_minimization # initialize the parameters for the Ansatz randomly self.alpha_0 = self._init_alpha_randomly() self._decompositions() """ Only things below this line require user interaction in the classes code (normally). """ """ The following lines present an example on how to define A and its decomposition. """ self.decomposition_asGate = self.decomposition_asGate_Id self.decomposition_asOperator = self.decomposition_adjoint_asOperator_Id self.decomposition_adjoint_asOperator = self.decomposition_adjoint_asOperator_Id # the Operator A self.A = self.coefficients[0] * self.decomposition_asOperator[0] for coeff, op in zip(self.coefficients[1:], self.decomposition_asOperator[1:]): self.A += coeff * op # This instance of the class is imported and used by all other modules. # Use it to model your physcal problem. # To change A or its decomposition you have to modify the code of the class itself. params = GlobalParameters( n_qubits=4, n_layers=4, coefficients=[complex(0, 0), complex(1, 0), complex(0, 0), complex(0, 0)], COBYLA_maxiter=400, qiskit_simulation_shots=8192, qiskit_simulation_backend="qasm_simulator" )
https://github.com/muehlhausen/vqls-bachelor-thesis
muehlhausen
""" Import all required libraries. """ from qiskit import ( QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, execute, transpile, assemble ) from qiskit.circuit import Gate, Instruction from qiskit.quantum_info.operators import Operator from qiskit.extensions import ZGate, YGate, XGate, IGate from scipy.optimize import ( minimize, basinhopping, differential_evolution, shgo, dual_annealing ) import random import numpy as np import cmath from typing import List, Set, Dict, Tuple, Optional, Union # import the params object of the GlobalParameters class # this provides the parameters used to desribed and model # the problem the minimizer is supposed to use. from GlobalParameters import params """ This program provides an implementation of the Variational Quantum Linear Solver as presented by Bravo-Prieto et al. It is implemented for the QISKIT Quantum SDK. This version of the program uses the local cost function. Author: Alexander Cornelius Muehlhausen ######################################################################### ######### Core functions The core functions of the VQLS algorithm. """ def generate_ansatz(alpha: List[float]) -> QuantumCircuit: """ This function returns a circuit that implements the Ansatz V(alpha). """ qr_ansatz = QuantumRegister(params.n_qubits) circ_ansatz = QuantumCircuit(qr_ansatz) if not any(isinstance(item, list) for item in alpha): # this will reformat the list alpha to the required format (if needed) # this is necessary as the minimizer returns a list without sublists alpha = _format_alpha(alpha) # 0th sublayer for qubit in range(0, params.n_qubits): circ_ansatz.ry(alpha[0][qubit], qr_ansatz[qubit]) if params.n_qubits % 2 == 0: # all other sublayers for sublayer in range(1, 2 * params.n_layers, 2): # first sublayer of the current layer # controlled Z-Gate pairs for qubit_a, qubit_b in zip(qr_ansatz[::2], qr_ansatz[1::2]): circ_ansatz.cz(qubit_a, qubit_b) for rotation_param, qubit in zip(alpha[sublayer], qr_ansatz): circ_ansatz.ry(rotation_param, qubit) # second sublayer of the current layer for qubit_a, qubit_b in zip(qr_ansatz[1::2], qr_ansatz[2::2]): circ_ansatz.cz(qubit_a, qubit_b) # and Ry to each qubit except the first and last one for rotation_param, qubit in zip(alpha[sublayer+1], qr_ansatz[1::]): circ_ansatz.ry(rotation_param, qubit) else: # all other sublayers for sublayer in range(1, 2 * params.n_layers, 2): # first sublayer of the current layer for qubit_a, qubit_b in zip(qr_ansatz[:params.n_qubits-1:2], qr_ansatz[1:params.n_qubits-1:2]): circ_ansatz.cz(qubit_a, qubit_b) for rotation_param, qubit in zip(alpha[sublayer], qr_ansatz[:params.n_qubits-1:]): circ_ansatz.ry(rotation_param, qubit) # second sublayer for qubit_a, qubit_b in zip(qr_ansatz[1::2], qr_ansatz[2::2]): circ_ansatz.cz(qubit_a, qubit_b) for rotation_param, qubit in zip(alpha[sublayer+1], qr_ansatz[1::]): circ_ansatz.ry(rotation_param, qubit) return circ_ansatz def hadamard_test( *, ansatz: Union[Gate, Operator] = None, first: Union[Gate, Operator] = None, first_uncontrolled: Union[Gate, Operator] = None, j: int = None, second_uncontrolled: Union[Gate, Operator] = None, second: Union[Gate, Operator] = None, im=None ): """ This function returns a circuit that implements the Hadamard Test. The ancilliary qubit is the last qubit; a measurement is applied to it. """ # prep of QuantumCircuit qr_had = QuantumRegister(params.n_qubits) circ_had = QuantumCircuit(qr_had) ancilla = QuantumRegister(1, name="ancilla") cr_had = ClassicalRegister(1) circ_had.add_register(ancilla) circ_had.add_register(cr_had) qubits_designation_control = [i for i in range(params.n_qubits)] qubits_designation_control.insert(0, params.n_qubits) def append_ifExists(obj: Union[Gate, Operator], control=False): """ Append gates to a circuit. Convert them to instructions if necessary. Control them if necessary. """ if isinstance(obj, (Gate, Operator)): _obj = obj.copy() if isinstance(_obj, Operator): _obj = _obj.to_instruction() if control is True: _obj = _obj.control(1) circ_had.append(_obj, qubits_designation_control) else: circ_had.append(_obj, qr_had) # act on the ancilla circ_had.h(ancilla) # if Im(<>) shall be calculated if im is not None: circ_had.sdg(ancilla) append_ifExists(ansatz) # clean up the circuit circ_had.barrier() # use this for $A_l$ append_ifExists(first, True) # use this for $U^{\dagger} append_ifExists(first_uncontrolled) # $Z_j$ if j is not None: circ_had.cz(params.n_qubits, qr_had[j]) # use this for $U$ append_ifExists(second_uncontrolled) # use this for $A^{\dagger}_m$ append_ifExists(second, True) # clean up the circuit circ_had.barrier() # last operation on the ancilla & measurement circ_had.h(ancilla) circ_had.measure(ancilla, cr_had) return circ_had def calculate_beta(alpha: List[float]) -> List[List[complex]]: """ This function calculates all parameters $\beta_{lm}$ that are required, i.e. all parameters with l, m so that $c_l$ and $c^{*}_m$ are not equal to 0. """ # preparation of the result list beta = [[complex(0, 0) for _ in params.coefficients] for _ in params.coefficients_conjugate] # generate Ansatz outside the loops for better performance V = generate_ansatz(alpha).to_gate() # $A^{\dagger}_m, (m, c^{*}_m)$ for gate_l, (l, coeff_l) in zip(params.decomposition_asGate, enumerate(params.coefficients)): if coeff_l == 0: continue # increase perfomance by ommiting unused $\beta$ # $A^{\dagger}_m, (m, c^{*}_m)$ for gate_m_adj, (m, coeff_m) in zip(params.decomposition_adjoint_asOperator, enumerate(params.coefficients_conjugate)): if coeff_m == 0: continue # increase perfomance by ommiting unused $\beta$ # circuit for Re ( <0| V(alpha)(+) A_m(+) A_l V(alpha) |0>) circ_had_re = hadamard_test(ansatz=V, first=gate_l, second=gate_m_adj) # circ_had_re.draw(output='mpl') # circuit for Im ( <0| V(alpha)(+) A_m(+) A_l V(alpha) |0>) circ_had_im = hadamard_test(ansatz=V, first=gate_l, second=gate_m_adj, im=1) # calculate Re and Im of $\beta_{lm}$ / simulate circuits expV_had_re = _calculate_expectationValue_HadamardTest(circ_had_re) expV_had_im = _calculate_expectationValue_HadamardTest(circ_had_im) # set together $\beta_{lm}$ from its real and imaginary part expV_had = complex(expV_had_re, expV_had_im) beta[l][m] = expV_had return beta def calculate_delta(alpha: List[float], beta: List[List[complex]]) -> List[List[complex]]: """ This function calculates all $\delta_{lm}$ that are required, i.e. all parameters with l, m so that $c_l$ and $c^{*}_m$ are not equal to 0. """ # initialize the list for the results delta = [[complex(0, 0) for _ in params.coefficients] for _ in params.coefficients_conjugate] # prepare $V(\vec{alpha})$, $U$ and $U^{\dagger}$ V = generate_ansatz(alpha).to_gate() U = _U_primitive().to_gate() U_dagger = U.copy() U_dagger = Operator(U_dagger) U_dagger = U_dagger.adjoint() # $A_l, (l, c_l)$ for gate_l, (l, coeff_l) in zip(params.decomposition_asGate, enumerate(params.coefficients)): if coeff_l == 0: continue # increase perfomance by ommiting unused $\delta$ # $A^{\dagger}_m, (m, c^{*}_m)$ for gate_m_adj, (m, coeff_m) in zip( params.decomposition_adjoint_asOperator, enumerate(params.coefficients_conjugate) ): if coeff_m == 0: continue # increase perfomance by ommiting unused $\delta$ temp = beta[l][m] # 1/n_qubits sum_j <0| V(+) A_m(+) U (Z_j * 1_{j-bar}) U(+) A_l V |0> for j in range(params.n_qubits): # Re(<0| V(+) A_m(+) U (Z_j * 1_{j-bar}) U(+) A_l V |0>) circ_had_re = hadamard_test( ansatz=V, first=gate_l, first_uncontrolled=U_dagger, j=j, second_uncontrolled=U, second=gate_m_adj) # Im(<0| V(+) A_m(+) U (Z_j * 1_{j-bar}) U(+) A_l V |0>) circ_had_im = hadamard_test( ansatz=V, first=gate_l, first_uncontrolled=U_dagger, j=j, second_uncontrolled=U, second=gate_m_adj, im=1) # calculate Re and Im of $\delta_{lm}$ / simulate circuits expV_had_re = _calculate_expectationValue_HadamardTest(circ_had_re) expV_had_im = _calculate_expectationValue_HadamardTest(circ_had_im) # set together $\delta_{lm}$ from its real and imaginary part # and execute the summation expV_had = complex(expV_had_re, expV_had_im) temp += 1/params.n_qubits * expV_had delta[l][m] = temp return delta def calculate_local_cost_function(alpha: List[float]) -> Union[complex, float]: """ returns cost = <x| H_local |x> / <psi|psi> with <x| H_local |x> = Sum_l_m c_l c_m(*) delta <psi|psi> = Sum_l_m c_l c_m(*) beta """ beta = calculate_beta(alpha) delta = calculate_delta(alpha, beta) xHx = 0 psipsi = 0 for l, coeff_l in enumerate(params.coefficients): for m, coeff_m_conj in enumerate(params.coefficients_conjugate): xHx += coeff_l * coeff_m_conj * delta[l][m] psipsi += coeff_l * coeff_m_conj * beta[l][m] # cost = xHx / psipsi cost = abs(xHx/psipsi) print(alpha) print("local cost function " + str(cost)) return cost def minimize_local_cost_function(method: str) -> List[float]: """ This function minimizes the local cost function. It returns the alpha for which the approximation A V(alpha_out) |0> approx |b> is optimal. Implements scipy.optimize.minimize . It provides several methods to minimize the cost function: Locally using scipy.optimize.minimize Basinhopping Differential evolution SHGO dual annealing """ # accepted methods for the minimizer # those deliver decent results, but COBYLA was favored minimization_methods = ["COBYLA", "Nelder-Mead", "Powell"] """ # some methods for the minimizer that were tested but failed to # deliver decent results minimization_methods_unsatisfactory = [ "CG", "BFGS", "L-BFGS-B", "TNC", "SLSQP", "trust-constr" ] """ # use minimize and the methods to find a local minimum if method in minimization_methods: min = minimize(calculate_local_cost_function, x0=params.alpha_0, method=method, options={'maxiter': params.COBYLA_maxiter}) # use basinhopping to find the global minimum # another decent minimiziation approach elif method == "basinhopping": min = basinhopping(calculate_local_cost_function, x0=params.alpha_0, niter=params.COBYLA_maxiter, minimizer_kwargs = {'method': "COBYLA"}) else: print("No valid method for the minimization was given!") return 0 print(min) alpha_out = min['x'] print(alpha_out) return alpha_out """ Fix the result. """ def postCorrection(qc: QuantumCircuit) -> QuantumCircuit: """ This function is used to apply post correction to the circuit generated by applying V(alpha) and A as the result is not identical to |b>. The result of a circuit built using the functions presented above returns the reverse of b with random sign errors. """ for i in range(params.n_qubits): qc.x(i) qc.z(i) return qc """ ######### Helper functions Functions that do not add to the logic of the algorithm but instead implement often used features or need to be changed sometimes. """ def _format_alpha(alpha_unformated: List[float]) -> List[List[float]]: """ This function formats a list to be in the correct form for the function that builds V(alpha). This means it will format the list to be of the form: [[0th sublayer], [1st sublayer], [2nd sublayer], ...] So for e.g. 4 qubits it will return (- stands for some random value): [[-,-,-,-],[-,-,-,-],[-,-],[-,-,-,-],[-,-]] and for e.g. 3 qubits: [[-,-],[-,-],[-,-],[-,-],[-,-]] """ alpha_formated = [] if any(isinstance(item, list) for item in alpha_unformated): return alpha_unformated else: if (params.n_qubits % 2) == 0: start = 0 end = params.n_qubits alpha_formated.append(alpha_unformated[start:params.n_qubits]) for _ in range(params.n_layers): start = end end = start + params.n_qubits alpha_formated.append(alpha_unformated[start:end]) start = end end = start + params.n_qubits - 2 alpha_formated.append(alpha_unformated[start:end]) else: start = 0 end = params.n_qubits alpha_formated.append(alpha_unformated[start:end]) for _ in range(params.n_layers): start = end end = start + params.n_qubits-1 alpha_formated.append(alpha_unformated[start:end]) start = end end = start + params.n_qubits - 1 alpha_formated.append(alpha_unformated[start:end]) return alpha_formated def _calculate_expectationValue_HadamardTest(circ_had: QuantumCircuit) -> float: """ Will return the expectation value for a given circuit for a Hadamard test. Supports different backends. Code snippets and best practices taken from Qiskit tutorials and documentation, e.g. https://qiskit.org/textbook/ch-paper-implementations/vqls.html . """ if params.qiskit_simulation_backend == 'statevector_simulator': backend = Aer.get_backend('statevector_simulator') t_circ = transpile(circ_had, backend) qobj = assemble(t_circ) p_0 = 0 p_1 = 0 for _ in range(params.qiskit_simulation_shots): job = backend.run(qobj) result = job.result() counts = result.get_counts(circ_had) p_0 += counts.get('0', 0) p_1 += counts.get('1', 0) return ((p_0 - p_1) / params.qiskit_simulation_shots) if params.qiskit_simulation_backend == 'qasm_simulator': backend = Aer.get_backend('qasm_simulator') job = execute(circ_had, backend, shots=params.qiskit_simulation_shots) result = job.result() counts = result.get_counts(circ_had) number = counts.get('1', 0) + counts.get('0', 0) p_0 = counts.get('0', 0)/number p_1 = counts.get('1', 0)/number return (p_0 - p_1) def _U_primitive() -> QuantumCircuit: """ This function generates a circuit that resembles a U gate that fulfills: U |0> = |b> . This is primitive because this circuit calculates / defines |b> as: |b> = U |0> = A H(0, 3) |0> """ qr_U_primitive = QuantumRegister(params.n_qubits) circ_U_primitive = QuantumCircuit(qr_U_primitive) """ for i in range(n_qubits): circ_U_primitive.h(i) """ circ_U_primitive.h(0) # optional # circ_U_primitive.h(1) # circ_U_primitive.h(1) # circ_U_primitive.h(2) circ_U_primitive.h(3) A_copy = params.A.copy() if isinstance(params.A, Operator): A_copy = A_copy.to_instruction() circ_U_primitive.append(A_copy, qr_U_primitive) return circ_U_primitive
https://github.com/tanmaybisen31/Quantum-Teleportation
tanmaybisen31
from qiskit import* # Loading your IBM Quantum account(s) provider = IBMQ.load_account() qc=QuantumCircuit(1,1) from qiskit.tools.visualization import plot_bloch_multivector qc.x(0) sim=Aer.get_backend('statevector_simulator') result=execute(qc,backend=sim).result() sv=result.get_statevector() print(sv) qc.draw() plot_bloch_multivector(sv) qc.measure(range(1),range(1)) backend=Aer.get_backend('qasm_simulator') result=execute(qc,backend=backend).result() count=result.get_counts() from qiskit.tools.visualization import plot_histogram plot_histogram(count) s=Aer.get_backend('unitary_simulator') result=execute(qc,backend=s).result() unitary=result.get_unitary() print(unitary)
https://github.com/tanmaybisen31/Quantum-Teleportation
tanmaybisen31
import sys sys.path.append('../') from circuits import sampleCircuitA, sampleCircuitB1, sampleCircuitB2,\ sampleCircuitB3, sampleCircuitC, sampleCircuitD, sampleCircuitE,\ sampleCircuitF from entanglement import Ent import warnings warnings.filterwarnings('ignore') labels = [ 'Circuit A', 'Circuit B1', 'Circuit B2', 'Circuit B3', 'Circuit C', 'Circuit D', 'Circuit E', 'Circuit F' ] samplers = [ sampleCircuitA, sampleCircuitB1, sampleCircuitB2, sampleCircuitB3, sampleCircuitC, sampleCircuitD, sampleCircuitE, sampleCircuitF ] q = 4 for layer in range(1, 4): print(f'qubtis: {q}') print('-' * 25) for (label, sampler) in zip(labels, samplers): expr = Ent(sampler, layer=layer, epoch=3000) print(f'{label}(layer={layer}): {expr}') print()
https://github.com/tanmaybisen31/Quantum-Teleportation
tanmaybisen31
from qiskit import * IBMQ.load_account() cr=ClassicalRegister(2) qr=QuantumRegister(2) circuit=QuantumCircuit(qr,cr) %matplotlib inline circuit.draw() circuit.h(qr[0]) circuit.draw(output='mpl') circuit.cx(qr[0],qr[1]) circuit.draw(output='mpl') circuit.measure(qr,cr) circuit.draw() simulator=Aer.get_backend('qasm_simulator') result=execute(circuit,backend=simulator).result() from qiskit.tools.visualization import plot_histogram plot_histogram(result.get_counts(circuit)) from qiskit.visualization import plot_state_qsphere from qiskit.visualization import plot_bloch_multivector statevector_simulator = Aer.get_backend('statevector_simulator') result=execute(circuit,statevector_simulator).result() statevector_results=result.get_statevector(circuit) plot_bloch_multivector(statevector_results) plot_state_qsphere(statevector_results)
https://github.com/tanmaybisen31/Quantum-Teleportation
tanmaybisen31
# Do the necessary imports import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import IBMQ, Aer, transpile, assemble from qiskit.visualization import plot_histogram, plot_bloch_multivector, array_to_latex from qiskit.extensions import Initialize from qiskit.ignis.verification import marginal_counts from qiskit.quantum_info import random_statevector # Loading your IBM Quantum account(s) provider = IBMQ.load_account() ## SETUP # Protocol uses 3 qubits and 2 classical bits in 2 different registers qr = QuantumRegister(3, name="q") # Protocol uses 3 qubits crz = ClassicalRegister(1, name="crz") # and 2 classical bits crx = ClassicalRegister(1, name="crx") # in 2 different registers teleportation_circuit = QuantumCircuit(qr, crz, crx) def create_bell_pair(qc, a, b): qc.h(a) qc.cx(a,b) qr = QuantumRegister(3, name="q") crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx") teleportation_circuit = QuantumCircuit(qr, crz, crx) create_bell_pair(teleportation_circuit, 1, 2) teleportation_circuit.draw() def alice_gates(qc, psi, a): qc.cx(psi, a) qc.h(psi) qr = QuantumRegister(3, name="q") crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx") teleportation_circuit = QuantumCircuit(qr, crz, crx) ## STEP 1 create_bell_pair(teleportation_circuit, 1, 2) ## STEP 2 teleportation_circuit.barrier() # Use barrier to separate steps alice_gates(teleportation_circuit, 0, 1) teleportation_circuit.draw() def measure_and_send(qc, a, b): """Measures qubits a & b and 'sends' the results to Bob""" qc.barrier() qc.measure(a,0) qc.measure(b,1) qr = QuantumRegister(3, name="q") crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx") teleportation_circuit = QuantumCircuit(qr, crz, crx) create_bell_pair(teleportation_circuit, 1, 2) teleportation_circuit.barrier() # Use barrier to separate steps alice_gates(teleportation_circuit, 0, 1) measure_and_send(teleportation_circuit, 0 ,1) teleportation_circuit.draw() def bob_gates(qc, qubit, crz, crx): qc.x(qubit).c_if(crx, 1) # Apply gates if the registers qc.z(qubit).c_if(crz, 1) # are in the state '1' qr = QuantumRegister(3, name="q") crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx") teleportation_circuit = QuantumCircuit(qr, crz, crx) ## STEP 1 create_bell_pair(teleportation_circuit, 1, 2) ## STEP 2 teleportation_circuit.barrier() # Use barrier to separate steps alice_gates(teleportation_circuit, 0, 1) ## STEP 3 measure_and_send(teleportation_circuit, 0, 1) ## STEP 4 teleportation_circuit.barrier() # Use barrier to separate steps bob_gates(teleportation_circuit, 2, crz, crx) teleportation_circuit.draw() # Create random 1-qubit state psi = random_statevector(2) # Display it nicely display(array_to_latex(psi, prefix="|\\psi\\rangle =")) # Show it on a Bloch sphere plot_bloch_multivector(psi) init_gate = Initialize(psi) init_gate.label = "init" ## SETUP qr = QuantumRegister(3, name="q") # Protocol uses 3 qubits crz = ClassicalRegister(1, name="crz") # and 2 classical registers crx = ClassicalRegister(1, name="crx") qc = QuantumCircuit(qr, crz, crx) ## STEP 0 # First, let's initialize Alice's q0 qc.append(init_gate, [0]) qc.barrier() ## STEP 1 # Now begins the teleportation protocol create_bell_pair(qc, 1, 2) qc.barrier() ## STEP 2 # Send q1 to Alice and q2 to Bob alice_gates(qc, 0, 1) ## STEP 3 # Alice then sends her classical bits to Bob measure_and_send(qc, 0, 1) ## STEP 4 # Bob decodes qubits bob_gates(qc, 2, crz, crx) # Display the circuit qc.draw() sim = Aer.get_backend('aer_simulator') qc.save_statevector() out_vector = sim.run(qc).result().get_statevector() plot_bloch_multivector(out_vector)
https://github.com/tanmaybisen31/Quantum-Teleportation
tanmaybisen31
from qiskit import * # Loading your IBM Quantum account(s) provider = IBMQ.load_account() circuit = QuantumCircuit(3,3) %matplotlib inline circuit.x(0) circuit.barrier() circuit.h(1) circuit.cx(1,2) circuit.barrier() circuit.cx(0,1) circuit.h(0) circuit.barrier() circuit.measure([0, 1], [0, 1]) circuit.barrier() circuit.cx(1, 2) circuit.cz(0, 2) circuit.measure([2], [2]) circuit.draw(output='mpl') simulator = Aer.get_backend('qasm_simulator') result = execute(circuit, backend=simulator, shots=1024).result() from qiskit.visualization import plot_histogram plot_histogram(result.get_counts(circuit)) print(circuit.qasm()) statevector_simulator = Aer.get_backend('statevector_simulator') result=execute(circuit,statevector_simulator).result() statevector_results=result.get_statevector(circuit) plot_bloch_multivector(statevector_results) plot_state_qsphere(statevector_results)
https://github.com/tanmaybisen31/Quantum-Teleportation
tanmaybisen31
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit,execute, 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.visualization import plot_state_qsphere from qiskit.visualization import plot_bloch_multivector qc=QuantumCircuit(1) statevector_simulator = Aer.get_backend('statevector_simulator') result=execute(qc,statevector_simulator).result() statevector_results=result.get_statevector(qc) plot_bloch_multivector(statevector_results) plot_state_qsphere(statevector_results) qc.x(0) result=execute(qc,statevector_simulator).result() statevector_results=result.get_statevector(qc) plot_bloch_multivector(statevector_results) plot_state_qsphere(statevector_results) qc.h(0) result=execute(qc,statevector_simulator).result() statevector_results=result.get_statevector(qc) plot_bloch_multivector(statevector_results) plot_state_qsphere(statevector_results)
https://github.com/victor-onofre/Tutorial_QAOA_maxcut_Qiskit_FallFest
victor-onofre
import numpy as np import networkx as nx import matplotlib.pyplot as plt from scipy.optimize import minimize from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer style = {'backgroundcolor': 'lightyellow'} # Style of the drawing of the quantum circuit Graph_Example_1 = nx.Graph() Graph_Example_1.add_edges_from([[1,2],[2,3],[1,3]]) nx.draw(Graph_Example_1,with_labels=True,font_weight='bold') nx.draw(Graph_Example_1,node_color = ['b','b','r']) Graph_Example_2 = nx.Graph() Graph_Example_2.add_edges_from([[1,2],[1,3],[4,2],[4,3]]) nx.draw(Graph_Example_2,with_labels=True,font_weight='bold') nx.draw(Graph_Example_2,node_color = ['r','b','b','r']) Graph_Example_3 = nx.Graph() Graph_Example_3.add_edges_from([[1,4],[1,2],[2,5],[4,5],[5,3],[2,3]]) nx.draw(Graph_Example_3,with_labels=True,font_weight='bold') nx.draw(Graph_Example_3,node_color = ['r','b','b','r','b']) Graph = nx.Graph() Graph.add_edges_from([[0,1],[0,3],[3,4],[1,4],[1,2],[4,2]]) nx.draw(Graph,with_labels=True) Graph.edges() N = Graph.number_of_nodes() # The number of nodes in the graph qc = QuantumCircuit(N,N) # Quantum circuit with N qubits and N classical register gamma = np.pi/8 # parameter gamma for the cost function (maxcut hamiltonian) #Apply the operator to each edge for i, j in Graph.edges(): qc.cx(i,j) qc.rz(2*gamma, j) qc.cx(i,j) qc.barrier() qc.draw(output='mpl', style=style) # Draw the quantum circuit beta = np.pi/8 # parameter for the mixer hamiltonian for n in Graph.nodes(): qc.rx(2*beta, n) # measure the result qc.barrier(range(N)) qc.measure(range(N), range(N)) qc.draw(output='mpl', style=style,fold= 35) def qaoa_circuit(G, theta,p): r""" ############################################ # Compute the QAOA circuit for the graph G # # |psi(theta) > = |psi(beta,gamma) > = e^{-i*beta_p*B} e^{-i*gamma_p*C}... e^{-i*beta_1*B} e^{-i*gamma_1*C} H^{otimes n}|0> # # where C is the Maxcut hamiltonian, B is the mixer hamiltonian. # # G: graph # theta: parameters,first half is betas, second half is gammas # p: number of QAOA steps # return: The QAOA circuit ########################################### """ beta = theta[:p] #Parameters beta for the mixer hamiltonian gamma = theta[p:]#Parameters gamma for the maxcut hamiltonian N = G.number_of_nodes()#Number of nodes of the graph G qc = QuantumCircuit(N,N)# Quantum circuit wiht N qubits and N classical register qc.h(range(N))# Apply the Hadamard gate to all the qubits # Apply p operators for k in range(p): for i, j in G.edges(): #Representation of the maxcut hamiltonian qc.cx(i,j) qc.rz(2*gamma[k], j) qc.cx(i,j) qc.barrier() for n in G.nodes(): # Representation of the mixer hamiltonian qc.rx(2*beta[k], n) # Measurement in all the qubits qc.barrier(range(N)) qc.measure(range(N), range(N)) return qc #Returns the quantum circuit # p is the number of QAOA alternating operators p = 1 theta = np.array([np.pi/8,np.pi/8]) circuit = qaoa_circuit(Graph, theta,p) circuit.draw(output='mpl', style=style,fold= 35) # Draw the quantum circuit #Qiskit uses the least significant bit in the bistring, we need to invert this string def invert_counts(counts): r""" ############################################ # Inverted the binary string # # counts: The result of running the quantum circuit # return: The results with binary string inverted ########################################### """ inv_counts = {} for k, v in counts.items(): inv_counts[k[::-1]] = v return inv_counts def maxcut_objective_function(x,G): r""" ############################################ # Compute the maxcut objective function for the binary string x and graph G # # G: graph # x: binary string # return: The cost of the binary string x ########################################### """ cut = 0 for i, j in G.edges(): if x[i] != x[j]: cut -= 1# the edge is cut return cut # Sum of all the edges that are cut def function_to_minimize(G,p): r""" ############################################ # Define the function to minimize given the graph G and the number of parameters # # G: graph # p: number of parameters # return: The function to minimize ########################################### """ backend = Aer.get_backend('qasm_simulator') def f(theta): r""" ############################################ # Function that gives the energy for parameters theta # # theta: parameters # return: Energy ########################################### """ qc = qaoa_circuit(G,theta,p) # Gives the circuit of QAOA fot a graph G, parameters theta and p operators counts = execute(qc, backend, seed_simulator=10).result().get_counts()# Run the circuit and get the results using the backedn "qasm_simulator" E = 0 # Initial energy total_counts = 0 # Initial counts #Qiskit uses the least significant bit in the bistring, we need to invert this string InvertedCounts = invert_counts(counts) #Inverted the binary string # meas is the binary string measure # meas_count is the number of times that the binary string has been measure for meas, meas_count in InvertedCounts.items(): objective_function = maxcut_objective_function(meas, G)#Compute the maxcut objetive function fot the binary string meas E += objective_function*meas_count # Define the energy as the value of the objective functions times the counts of that measure total_counts += meas_count # The total number of measures in the system return E/total_counts # Returns the energy given the parameters theta return f p = 5 # p is the number of QAOA alternating operators objective_function = function_to_minimize(Graph, p) x0=np.random.randn(10)#Initial parameters minim_solution = minimize(objective_function, x0) # Minimization of scalar function of one or more variable from scipy minim_solution optimal_theta = minim_solution['x'] # The optimal parameters to use optimal_theta backend = Aer.get_backend('qasm_simulator') qc = qaoa_circuit(Graph, optimal_theta,p) # Define the quantum circuit with the optimal parameters counts = invert_counts(execute(qc, backend).result().get_counts()) # Get the results #energies = {bs: maxcut_objective_function(bs, Graph) for bs, _ in counts.items()} #energies_sorted = {bs: en for bs, en in sorted(energies.items(), key=lambda item: item[1])} #print(energies_sorted) #print({bs: counts[bs] for bs, energy in energies_sorted.items()}) # Compute the maxcut objective function for the optimal parameters results = [] for x in counts.keys(): results.append([maxcut_objective_function(x,Graph),x]) # Get the best solution given the results of the maxcut objective function best_cut, best_solution = min(results) print(f"Best string: {best_solution} with cut: {-best_cut}") # Define the colors of the nodes for the best solution colors = ['r' if best_solution[node] == '0' else 'b' for node in Graph] nx.draw(Graph,node_color = colors) def solution_max_cut(G): r""" ############################################ # Compute the solution for the maxcut problem given a graph G # # G: graph # return:The draw of the best solution with two colors. Print the solution in the binary string form and the number of cuts ############### """ p = 5 # p is the number of QAOA alternating operators objective_function = function_to_minimize(G, p) x0=np.random.randn(10)#Initial parameters new_parameters = minimize(objective_function, x0) # Minimization of scalar function of one or more variable from scipy optimal_theta = new_parameters['x']# The optimal parameters to use qc = qaoa_circuit(G, optimal_theta,p) # Define the quantum circuit with the optimal parameters counts = invert_counts(execute(qc, backend).result().get_counts()) # Get the results # Compute the maxcut objective function for the optimal parameters results = [] for x in counts.keys(): results.append([maxcut_objective_function(x,G),x]) best_cut, best_solution = min(results) # Get the best solution given the results of the maxcut objective function colors = ['r' if best_solution[node] == '0' else 'b' for node in G] # Define the colors of the nodes for the best solution return nx.draw(G,node_color = colors),print(f"Best string: {best_solution} with cut: {-best_cut}") Graph1 = nx.Graph() Graph1.add_edges_from([[0,1],[0,2],[2,1]]) nx.draw(Graph1,with_labels=True) solution_max_cut(Graph1) graph2 = nx.random_regular_graph(3, 4, seed=1234) nx.draw(graph2) #drawing the graph plt.show() #plotting the graph solution_max_cut(graph2) graph3 = nx.random_regular_graph(3, 12, seed=1234) nx.draw(graph3) #drawing the graph plt.show() #plotting the graph solution_max_cut(graph3)
https://github.com/DavidFitzharris/EmergingTechnologies
DavidFitzharris
# initialization import numpy as np # importing Qiskit from qiskit import IBMQ, Aer 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 # Constant Oracle const_oracle = QuantumCircuit(n+1) # Random output output = np.random.randint(2) if output == 1: const_oracle.x(n) const_oracle.draw() # Balanced Oracle balanced_oracle = QuantumCircuit(n+1) # Binary string length b_str = "101" # For each qubit in our circuit # we place an X-gate if the corresponding digit in b_str is 1 # or do nothing if the digit is 0 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() # Creating the controlled-NOT gates # using each input qubit as a control # and the output as a target 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() # Wrapping the controls in X-gates # 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) # 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() # Viewing the output # use local simulator aer_sim = Aer.get_backend('aer_simulator') results = aer_sim.run(dj_circuit).result() answer = results.get_counts() plot_histogram(answer)
https://github.com/DavidFitzharris/EmergingTechnologies
DavidFitzharris
import numpy as np from qiskit import QuantumCircuit # Building the circuit # Create a Quantum Circuit acting on a quantum register of three qubits circ = QuantumCircuit(3) # Add a H gate on qubit 0, putting this qubit in superposition. circ.h(0) # Add a CX (CNOT) gate on control qubit 0 and target qubit 1, putting # the qubits in a Bell state. circ.cx(0, 1) # Add a CX (CNOT) gate on control qubit 0 and target qubit 2, putting # the qubits in a GHZ state. circ.cx(0, 2) # We can visualise the circuit using QuantumCircuit.draw() circ.draw('mpl') from qiskit.quantum_info import Statevector # Set the initial state of the simulator to the ground state using from_int state = Statevector.from_int(0, 2**3) # Evolve the state by the quantum circuit state = state.evolve(circ) #draw using latex state.draw('latex') from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * # Build #------ # Create a Quantum Circuit acting on the q register circuit = QuantumCircuit(2, 2) # Add a H gate on qubit 0 circuit.h(0) # Add a CX (CNOT) gate on control qubit 0 and target qubit 1 circuit.cx(0, 1) # Map the quantum measurement to the classical bits circuit.measure([0,1], [0,1]) # END # Execute #-------- # Use Aer's qasm_simulator simulator = Aer.get_backend('qasm_simulator') # Execute the circuit on the qasm simulator job = execute(circuit, simulator, shots=1000) # Grab results from the job result = job.result() # Return counts counts = result.get_counts(circuit) print("\nTotal count for 00 and 11 are:",counts) # END # Visualize #---------- # Using QuantumCircuit.draw(), as in previous example circuit.draw('mpl') # Analyze #-------- # Plot a histogram plot_histogram(counts) # END <h3 style="color: rgb(0, 125, 65)"><i>References</i></h3> https://qiskit.org/documentation/tutorials.html https://www.youtube.com/watch?v=P5cGeDKOIP0 https://qiskit.org/documentation/tutorials/circuits/01_circuit_basics.html https://docs.quantum-computing.ibm.com/lab/first-circuit
https://github.com/DavidFitzharris/EmergingTechnologies
DavidFitzharris
# initialization import numpy as np # importing Qiskit from qiskit import IBMQ, Aer 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 # Constant Oracle const_oracle = QuantumCircuit(n+1) # Random output output = np.random.randint(2) if output == 1: const_oracle.x(n) const_oracle.draw() # Balanced Oracle balanced_oracle = QuantumCircuit(n+1) # Binary string length b_str = "101" # For each qubit in our circuit # we place an X-gate if the corresponding digit in b_str is 1 # or do nothing if the digit is 0 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() # Creating the controlled-NOT gates # using each input qubit as a control # and the output as a target 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() # Wrapping the controls in X-gates # 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) # 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() # Viewing the output # use local simulator aer_sim = Aer.get_backend('aer_simulator') results = aer_sim.run(dj_circuit).result() answer = results.get_counts() plot_histogram(answer)
https://github.com/DavidFitzharris/EmergingTechnologies
DavidFitzharris
import pennylane as qml import numpy as np from pennylane.optimize import AdamOptimizer import matplotlib.pyplot as plt def loadData(filename): return_data = [] return_label = [] with open(filename, 'r') as file: for row in file: data = row.split(' ')[:-1] data = [ float(d) for d in data ] label = int(row.split(' ')[-1]) return_data.append(data) return_label.append(label) return np.array(return_data), np.array(return_label) X_train, Y_train = loadData('./data/training_set.txt') X_test, Y_test = loadData('./data/testing_set.txt') print(X_train[:10]) print(Y_train[:10]) plt.scatter(X_train[:, 0], X_train[:, 1], c=Y_train) plt.show() print(f'total datas: {len(X_train)}') print(f'label 0 datas: {len(list(filter(lambda x: x==0, Y_train)))}') print(f'label 0 datas: {len(list(filter(lambda x: x==1, Y_train)))}') def rotateDatas(X, Y): gen_X = [] gen_Y = [] for i, data in enumerate(X): gen_X.append(list(reversed(data))) gen_Y.append(Y[i]) return np.array(gen_X), np.array(gen_Y) X_train_rotate, Y_train_rotate = rotateDatas(X_train, Y_train) plt.scatter(X_train_rotate[:, 0], X_train_rotate[:, 1], c=Y_train_rotate) plt.show() # Concat datas X_temp = np.zeros((X_train.shape[0] * 2, len(X_train[0]))) X_temp[0:40,:] = X_train X_temp[40:80,] = X_train_rotate Y_temp = np.zeros((Y_train.shape[0] * 2)) Y_temp[0:40] = Y_train Y_temp[40:80] = Y_train_rotate plt.scatter(X_temp[:, 0], X_temp[:, 1], c=Y_temp) plt.show() X_train = X_temp Y_train = Y_temp print(f'total datas: {len(X_train)}') print(f'label 0 datas: {len(list(filter(lambda x: x==0, Y_train)))}') print(f'label 0 datas: {len(list(filter(lambda x: x==1, Y_train)))}') Z_train = (X_train[:, 0] ** 2 + X_train[:, 1] ** 2) ** 0.5 # Z_train = (X_train[:, 0] ** 2 + X_train[:, 1] ** 2) temp = np.zeros((X_train.shape[0], len(X_train[0]) + 1)) temp[:, :-1] = X_train temp[:, -1] = Z_train X_train2 = temp print(X_train2[:10]) Z_test = (X_test[:, 0] ** 2 + X_test[:, 1] ** 2) ** 0.5 # Z_test = (X_test[:, 0] ** 2 + X_test[:, 1] ** 2) temp = np.zeros((X_test.shape[0], len(X_test[0]) + 1)) temp[:, :-1] = X_test temp[:, -1] = Z_test X_test2 = temp print(X_test2[:10]) def plot3D(X, Y): fig = plt.figure(figsize=(10, 10)) ax = fig.add_subplot(111, projection='3d') ax.scatter( X[:, 0], X[:, 1], X[:, 2], zdir='z', s=30, c=Y, depthshade=True ) plt.show() plot3D(X_train2, Y_train) print(f'total datas: {len(X_train2)}') print(f'label 0 datas: {len(list(filter(lambda x: x==0, Y_train)))}') print(f'label 0 datas: {len(list(filter(lambda x: x==1, Y_train)))}') qubits_num = 3 layers_num = 2 dev = qml.device("default.qubit",wires=qubits_num) class VQC: def __init__(self): # 3 => U3(theta, phi, lambda) self.params = (0.01 * np.random.randn(layers_num, qubits_num, 3)) self.bestparams = self.params self.bestcost = 10 self.opt = AdamOptimizer(0.205) self.weights = [] self.costs = [] self.accuracies = [] def fit(self, X_train, Y_train, epoch=300): batch_size = 20 for turn in range(epoch): # Update the weights by one optimizer step batch_index = np.random.randint(0, len(X_train), (batch_size,)) X_train_batch = X_train[batch_index] Y_train_batch = Y_train[batch_index] self.params = self.opt.step(lambda v: cost(v, X_train_batch, Y_train_batch), self.params) cost_now = cost(self.params, X_train, Y_train) acc_now = accuracy(self.params, X_train, Y_train) if cost_now < self.bestcost: self.bestcost = cost_now self.bestparams = self.params self.weights.append(self.params) self.costs.append(cost_now) self.accuracies.append(acc_now) print( "Turn: {:5d} | Cost: {:0.7f} | Accuracy: {:0.2f}% ".format( turn + 1, cost_now, acc_now * 100 )) def score(self, X_test, Y_test): predictions = [ predict(self.bestparams, data) for data in X_test ] acc = accuracy(self.bestparams, X_test, Y_test) print("FINAL ACCURACY: {:0.2f}%".format(acc * 100)) @qml.qnode(dev) def circuit(params, data): angles = [ i * np.pi for i in data ] for i in range(qubits_num): qml.RX(angles[i], wires=i) qml.Rot( *params[0, i], wires=i ) qml.CZ(wires=[1, 0]) qml.CZ(wires=[1, 2]) qml.CZ(wires=[0, 2]) for i in range(qubits_num): qml.Rot( *params[1, i], wires=i ) # PauliZ measure => 1 -> |0> while -1 -> |1> return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1)), qml.expval(qml.PauliZ(2)) import qiskit import numpy as np from qiskit import QuantumCircuit from qiskit import Aer, execute unitary_backend = Aer.get_backend('unitary_simulator') qasm_backend = Aer.get_backend('qasm_simulator') def predict(params, data): qcircuit = QuantumCircuit(3, 3) qubits = qcircuit.qubits for i, d in enumerate(data): qcircuit.rx(d * np.pi, qubits[i]) for i in range(qubits_num): qcircuit.u3(*params[0][i], qubits[i]) qcircuit.cz(qubits[0], qubits[1]) qcircuit.cz(qubits[1], qubits[2]) qcircuit.cz(qubits[0], qubits[2]) for i in range(qubits_num): qcircuit.u3(*params[1][i], qubits[i]) # the measurement qcircuit.measure([0, 1, 2], [0, 1, 2]) # job execution shots = 1000 job_sim = execute(qcircuit, qasm_backend, shots=shots) result_sim = job_sim.result() counts = result_sim.get_counts(qcircuit) p1 = (counts.get('100', 0) + counts.get('111', 0) + counts.get('101', 0) + counts.get('110',0)) / shots if p1 > 0.5: return 1 else: return 0 def cost(weights, datas, labels): loss = 0 for i, data in enumerate(datas): # like [-1, 1, 1] measured = circuit(weights, data) p = measured[2] if labels[i] == 0: loss += (1 - p) ** 2 else: loss += (-1 - p) ** 2 return loss / len(datas) def accuracy(weights, datas, labels): predictions = [ predict(weights, data) for data in datas ] acc = 0 for i, p in enumerate(predictions): if p == labels[i]: acc += 1 return acc / len(predictions) vqc = VQC() vqc.fit(X_train2, Y_train, epoch=200)
https://github.com/rishikhurana2/FourQuantumAlgorithms
rishikhurana2
from qiskit import QuantumCircuit from QCLG_lvl3.oracles.secret_number_oracle import SecretNUmberOracle class BernsteinVazirani: @classmethod def bernstein_vazirani(cls, random_binary, eval_mode: bool) -> QuantumCircuit: # Construct secret number oracle secret_number_oracle = SecretNUmberOracle.create_secret_number_oracle(random_binary=random_binary, eval_mode=eval_mode) num_of_qubits = secret_number_oracle.num_qubits # Construct circuit according to the length of the number dj_circuit = QuantumCircuit(num_of_qubits, num_of_qubits - 1) dj_circuit_before_oracle = QuantumCircuit(num_of_qubits, num_of_qubits - 1) # Apply H-gates for qubit in range(num_of_qubits - 1): dj_circuit_before_oracle.h(qubit) # Put output qubit in state |-> dj_circuit_before_oracle.x(num_of_qubits - 1) dj_circuit_before_oracle.h(num_of_qubits - 1) dj_circuit += dj_circuit_before_oracle # Add oracle dj_circuit += secret_number_oracle dj_circuit_after_oracle = QuantumCircuit(num_of_qubits, num_of_qubits - 1) # Repeat H-gates for qubit in range(num_of_qubits - 1): dj_circuit_after_oracle.h(qubit) dj_circuit_after_oracle.barrier() # Measure for i in range(num_of_qubits - 1): dj_circuit_after_oracle.measure(i, i) dj_circuit += dj_circuit_after_oracle if not eval_mode: print("Circuit before the oracle\n") print(QuantumCircuit.draw(dj_circuit_before_oracle)) print("Circuit after the oracle\n") print(QuantumCircuit.draw(dj_circuit_after_oracle)) print(dj_circuit) return dj_circuit
https://github.com/rishikhurana2/FourQuantumAlgorithms
rishikhurana2
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Sep 19 19:13:26 2023 @author: abdullahalshihry """ #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Sep 18 19:15:12 2023 @author: abdullahalshihry """ import qiskit as qs import qiskit.visualization as qv import random import qiskit.circuit as qf def Deutsch_Jozsa(circuit): qr = qs.QuantumRegister(5,'q') cr = qs.ClassicalRegister(4,'c') qc = qs.QuantumCircuit(qr,cr) qc.x(qr[4]) qc.barrier(range(5)) qc.h(qr[0]) qc.h(qr[1]) qc.h(qr[2]) qc.h(qr[3]) qc.h(qr[4]) qc.barrier(range(5)) qc = qc.compose(circuit) qc.barrier(range(5)) qc.h(qr[0]) qc.h(qr[1]) qc.h(qr[2]) qc.h(qr[3]) qc.barrier(range(5)) qc.measure(0,0) qc.measure(1,1) qc.measure(2,2) qc.measure(3,3) job1 = qs.execute(qc, qs.Aer.get_backend('aer_simulator'), shots = 1024) output1 = job1.result().get_counts() print(output1) qc.draw('mpl') def Oracle(): qr = qs.QuantumRegister(5,'q') cr = qs.ClassicalRegister(4,'c') qc = qs.QuantumCircuit(qr,cr) qq = qs.QuantumCircuit(5,name='Uf') v = random.randint(1, 2) if v == 1: qc.cx(0,4) qc.cx(1,4) qc.cx(2,4) qc.cx(3,4) print('Balanced (1)') elif v == 2: qq.i(qr[0]) qq.i(qr[1]) qq.i(qr[2]) qq.i(qr[3]) print('Constant (0)') qq =qq.to_gate() qc.append(qq,[0,1,2,3,4]) return qc Deutsch_Jozsa(Oracle())
https://github.com/rishikhurana2/FourQuantumAlgorithms
rishikhurana2
"""Python implementation of Grovers algorithm through use of the Qiskit library to find the value 3 (|11>) out of four possible values.""" #import numpy and plot library import matplotlib.pyplot as plt import numpy as np # importing Qiskit from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.providers.ibmq import least_busy from qiskit.quantum_info import Statevector # import basic plot tools from qiskit.visualization import plot_histogram # define variables, 1) initialize qubits to zero n = 2 grover_circuit = QuantumCircuit(n) #define initialization function def initialize_s(qc, qubits): '''Apply a H-gate to 'qubits' in qc''' for q in qubits: qc.h(q) return qc ### begin grovers circuit ### #2) Put qubits in equal state of superposition grover_circuit = initialize_s(grover_circuit, [0,1]) # 3) Apply oracle reflection to marked instance x_0 = 3, (|11>) grover_circuit.cz(0,1) statevec = job_sim.result().get_statevector() from qiskit_textbook.tools import vector2latex vector2latex(statevec, pretext="|\\psi\\rangle =") # 4) apply additional reflection (diffusion operator) grover_circuit.h([0,1]) grover_circuit.z([0,1]) grover_circuit.cz(0,1) grover_circuit.h([0,1]) # 5) measure the qubits grover_circuit.measure_all() # Load IBM Q account and get the least busy backend device provider = IBMQ.load_account() device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and not x.configuration().simulator and x.status().operational==True)) print("Running on current least busy device: ", device) from qiskit.tools.monitor import job_monitor job = execute(grover_circuit, backend=device, shots=1024, optimization_level=3) job_monitor(job, interval = 2) results = job.result() answer = results.get_counts(grover_circuit) plot_histogram(answer) #highest amplitude should correspond with marked value x_0 (|11>)
https://github.com/rishikhurana2/FourQuantumAlgorithms
rishikhurana2
"""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/anish-ku/Deutsch-Jozsa-Algorithm-Qiskit
anish-ku
import numpy as np from qiskit import QuantumCircuit as QC from qiskit import execute from qiskit import IBMQ, BasicAer from qiskit.providers.ibmq import least_busy from qiskit.tools.jupyter import * provider = IBMQ.load_account() from qiskit.visualization import plot_histogram def oracle(case, n): ##creating an oracle oracle_qc = QC(n+1) if case=="balanced": for i in range(n): oracle_qc.cx(i,n) if case=="constant": pass ##converting circuit to a indivsual gate oracle_gate = oracle_qc.to_gate() oracle_gate.name = "Oracle" return oracle_gate def dj_algo(n, case="random"): dj_crc = QC(n+1,n) for i in range(n): dj_crc.h(i) dj_crc.x(n) dj_crc.h(n) if case=="random": rnd = np.random.randint(2) if rnd == 0: case = "constant" else: case = "balanced" dj_oracle = oracle(case, n) dj_crc.append(dj_oracle, range(n+1)) for i in range(n): dj_crc.h(i) dj_crc.measure(i,i) return dj_crc n = 3 dj_crc = dj_algo(n) dj_crc.draw('mpl') #simulating backend=BasicAer.get_backend('qasm_simulator') shots = 1024 dj_circuit = dj_algo(n, "balanced") results = execute(dj_circuit, backend=backend, shots=shots).result() answer = results.get_counts() plot_histogram(answer) #running on real quantum computer 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("Using least busy backend: ", backend) %qiskit_job_watcher dj_circuit = dj_algo(n, "balanced") job = execute(dj_circuit, backend=backend, shots=shots, optimization_level=3) result = job.result() answer = result.get_counts() plot_histogram(answer)
https://github.com/nahumsa/volta
nahumsa
import sys sys.path.append('../') import numpy as np import matplotlib.pyplot as plt # Qiskit from qiskit.aqua.operators import I, X, Y, Z from qiskit import BasicAer from qiskit.aqua.components.optimizers import COBYLA # VOLTA from VOLTA.VQD import VQD from VOLTA.utils import classical_solver from VOLTA.Hamiltonians import BCS_hamiltonian %load_ext autoreload %autoreload 2 def SPT_hamiltonian(g:float): gzz = 2*(1 - g**2) gx = (1 + g)**2 gzxz = (g - 1)**2 return - (gzz*(Z^Z^I^I^I) + gzz*(I^Z^Z^I^I) + gzz*(I^I^Z^Z^I) + gzz*(I^I^I^Z^Z)) - (gx*(X^I^I^I^I) + gx*(I^X^I^I^I) + gx*(I^I^X^I^I) + gx*(I^I^I^X^I) + gx*(I^I^I^I^X)) + (gzxz*(Z^X^Z^I^I) + gzxz*(I^Z^X^Z^I) + gzxz*(I^I^Z^X^Z)) g = 1 hamiltonian = SPT_hamiltonian(g) print(hamiltonian) eigenvalues, _ = classical_solver(hamiltonian) print(f"Energy Density: {eigenvalues[0]/3}") print(f"Expected Energy: {-2*(1 + g**2)}") energy = [] n_points = 10 x = np.linspace(-1, 1, n_points) for g in x: hamiltonian = SPT_hamiltonian(g) eigenvalues, _ = classical_solver(hamiltonian) energy.append(eigenvalues[0]) plt.plot(x, np.array(energy)/5, label='energy') ideal = lambda g:-2*(1 + g**2) plt.plot(x, ideal(x), label='expected') plt.legend() plt.show() import numpy as np from VOLTA.Observables import sample_hamiltonian from tqdm import tqdm optimizer = COBYLA() backend = BasicAer.get_backend('qasm_simulator') def simulation(n_points:int, backend, optimizer) -> (np.array, np.array): g = np.linspace(-1, 1, n_points) result = [] for g_val in tqdm(g): hamiltonian = SPT_hamiltonian(g_val) Algo = VQD(hamiltonian=hamiltonian, n_excited_states=0, beta=0., optimizer=optimizer, backend=backend) Algo.run(0) vqd_energies = Algo.energies vqd_states = Algo.states string_order = Z^Y^X^Y^Z res = sample_hamiltonian(hamiltonian=string_order, backend=backend, ansatz=vqd_states[0]) result.append(res) return g, np.array(result) g, result = simulation(n_points=10, backend=backend, optimizer=optimizer) plt.plot(g, result, 'o'); from qiskit.aqua import QuantumInstance from qiskit.circuit.library import TwoLocal optimizer = COBYLA(maxiter=10000) backend = QuantumInstance(backend=BasicAer.get_backend('qasm_simulator'), shots=10000) # Define ansatz ansatz = TwoLocal(hamiltonian.num_qubits, ['ry','rz'], 'cx', reps=2) # Run algorithm Algo = VQD(hamiltonian=hamiltonian, ansatz=ansatz, n_excited_states=0, beta=0., optimizer=optimizer, backend=backend) Algo.run(0) vqd_energies = Algo.energies vqd_states = Algo.states print(f'Energy: {vqd_energies[0]}') from VOLTA.Observables import sample_hamiltonian #string_order = Z^Y^X^Y^Z string_order = I^I^X^I^I sample_hamiltonian(hamiltonian=string_order, backend=backend, ansatz=vqd_states[0]) 4*np.abs(g)/(1 + np.abs(g))**2
https://github.com/nahumsa/volta
nahumsa
import sys sys.path.append('../../') # Python imports import numpy as np import matplotlib.pyplot as plt import seaborn as sns sns.set() # Qiskit from qiskit import BasicAer from qiskit.aqua.components.optimizers import COBYLA, SPSA, L_BFGS_B from qiskit.circuit.library import TwoLocal # VOLTA from volta.vqd import VQD from volta.utils import classical_solver from volta.hamiltonians import BCS_hamiltonian %load_ext autoreload %autoreload 2 EPSILONS = [3., 3., 3., 4., 3.] V = -2 hamiltonian = BCS_hamiltonian(EPSILONS, V) print(f"Hamiltonian: {hamiltonian}\n") eigenvalues, eigenvectors = classical_solver(hamiltonian) print(f"Eigenvalues: {eigenvalues}") from itertools import product # Get the ideal count ideal_dict = {} bin_combinations = list(product(['0','1'], repeat=hamiltonian.num_qubits)) for i, eigvect in enumerate(np.abs(eigenvectors)**2): dic = {} for ind, val in enumerate(bin_combinations): val = ''.join(val) dic[val] = eigvect[ind] ideal_dict[i] = dic from qiskit.aqua import QuantumInstance # Define Optimizer # optimizer = COBYLA() optimizer = SPSA(maxiter=250, c1=.7, last_avg=25) # optimizer = L_BFGS_B() # Define Backend # backend = BasicAer.get_backend('qasm_simulator') backend = QuantumInstance(backend=BasicAer.get_backend('qasm_simulator'), shots=10000) # Define ansatz ansatz = TwoLocal(hamiltonian.num_qubits, ['ry','rz'], 'cx', reps=3) # Run algorithm Algo = VQD(hamiltonian=hamiltonian, ansatz=ansatz, n_excited_states=3, beta=10., optimizer=optimizer, backend=backend) Algo.run() vqd_energies = Algo.energies vqd_states = Algo.states from copy import copy # Create states and measure them states = [] for ind, state in enumerate(vqd_states): states.append(copy(state)) states[ind].measure_all() from qiskit import execute from qiskit.visualization import plot_histogram fig, axs = plt.subplots(2, 2, figsize=(30,15)) for i, ax in zip(range(len(states)), axs.flat): count = execute(states[i], backend=backend, shots=10000).result().get_counts() plot_histogram([ideal_dict[i], count],legend=['Ideal','Result'], ax=ax) print(f'Ideal eigenvalues: {eigenvalues}') print(f'Obtained eigenvalues: {vqd_energies}') n_1_sim, n_2_sim = 1, 2 n_1_vqd, n_2_vqd = 1, 2 print(f"Gap Exact: {(eigenvalues[n_2_sim] - eigenvalues[n_1_sim])/2}") print(f"Gap VQD: {(vqd_energies[n_2_vqd] - vqd_energies[n_1_vqd])/2}") from qiskit.providers.aer.noise import depolarizing_error from qiskit.providers.aer.noise import thermal_relaxation_error from qiskit.providers.aer.noise import NoiseModel from qiskit.providers.aer.noise import depolarizing_error from qiskit.providers.aer.noise import thermal_relaxation_error from qiskit.providers.aer.noise import NoiseModel # T1 and T2 values for qubits 0-n n_qubits = 4 T1s = np.random.normal(50e3, 10e3, n_qubits) # Sampled from normal distribution mean 50 microsec T2s = np.random.normal(70e3, 10e3, n_qubits) # Sampled from normal distribution mean 50 microsec T1s = [30e3]*n_qubits T2s = [20e3]*n_qubits # Truncate random T2s <= T1s T2s = np.array([min(T2s[j], 2 * T1s[j]) for j in range(n_qubits)]) # Instruction times (in nanoseconds) time_u1 = 0 # virtual gate time_u2 = 50 # (single X90 pulse) time_u3 = 100 # (two X90 pulses) time_cx = 300 time_reset = 1000 # 1 microsecond time_measure = 1000 # 1 microsecond # QuantumError objects errors_reset = [thermal_relaxation_error(t1, t2, time_reset) for t1, t2 in zip(T1s, T2s)] errors_measure = [thermal_relaxation_error(t1, t2, time_measure) for t1, t2 in zip(T1s, T2s)] errors_u1 = [thermal_relaxation_error(t1, t2, time_u1) for t1, t2 in zip(T1s, T2s)] errors_u2 = [thermal_relaxation_error(t1, t2, time_u2) for t1, t2 in zip(T1s, T2s)] errors_u3 = [thermal_relaxation_error(t1, t2, time_u3) for t1, t2 in zip(T1s, T2s)] errors_cx = [[thermal_relaxation_error(t1a, t2a, time_cx).expand( thermal_relaxation_error(t1b, t2b, time_cx)) for t1a, t2a in zip(T1s, T2s)] for t1b, t2b in zip(T1s, T2s)] # Add errors to noise model noise_thermal = NoiseModel() for j in range(n_qubits): noise_thermal.add_quantum_error(errors_reset[j], "reset", [j]) noise_thermal.add_quantum_error(errors_measure[j], "measure", [j]) noise_thermal.add_quantum_error(errors_u1[j], "u1", [j]) noise_thermal.add_quantum_error(errors_u2[j], "u2", [j]) noise_thermal.add_quantum_error(errors_u3[j], "u3", [j]) for k in range(n_qubits): noise_thermal.add_quantum_error(errors_cx[j][k], "cx", [j, k]) print(noise_thermal) from qiskit.aqua import QuantumInstance from qiskit import Aer # Define Optimizer # optimizer = COBYLA() optimizer = SPSA(maxiter=250, c1=.7, last_avg=25) # Define Backend backend = QuantumInstance(backend=Aer.get_backend('qasm_simulator'), noise_model=noise_thermal, shots=10000) # Define ansatz ansatz = TwoLocal(hamiltonian.num_qubits, ['ry','rz'], 'cx', reps=3) # Run algorithm Algo = VQD(hamiltonian=hamiltonian, ansatz=ansatz, n_excited_states=3, beta=10., optimizer=optimizer, backend=backend) Algo.run() vqd_energies = Algo.energies vqd_states = Algo.states from copy import copy # Create states and measure them states = [] for ind, state in enumerate(vqd_states): states.append(copy(state)) states[ind].measure_all() from qiskit import execute from qiskit.visualization import plot_histogram import seaborn as sns sns.set() fig, axs = plt.subplots(2, 2, figsize=(30,15)) backend = QuantumInstance(backend=Aer.get_backend('qasm_simulator'), noise_model=noise_thermal, shots=10000) for i, ax in zip(range(len(states)), axs.flat): count = backend.execute(states[i]).get_counts() plot_histogram([ideal_dict[i], count],legend=['Ideal','Result'], ax=ax) print(f'Ideal eigenvalues: {eigenvalues}') print(f'Obtained eigenvalues: {vqd_energies}') n_1_sim, n_2_sim = 1, 2 n_1_vqd, n_2_vqd = 1, 2 print(f"Gap Exact: {(eigenvalues[n_2_sim] - eigenvalues[n_1_sim])/2}") print(f"Gap VQD: {(vqd_energies[n_2_vqd] - vqd_energies[n_1_vqd])/2}") from tqdm import tqdm from qiskit.aqua import QuantumInstance es_1 = [] es_2 = [] n = 50 for _ in tqdm(range(n)): # Define Optimizer optimizer = COBYLA() # Define Backend # backend = BasicAer.get_backend('qasm_simulator') backend = QuantumInstance(backend=BasicAer.get_backend('qasm_simulator'), shots=10000) # Define ansatz ansatz = TwoLocal(hamiltonian.num_qubits, ['ry','rz'], 'cx', reps=2) # Run algorithm Algo = VQD(hamiltonian=hamiltonian, ansatz=ansatz, n_excited_states=2, beta=10., optimizer=optimizer, backend=backend) Algo.run(0) vqd_energies = Algo.energies es_1.append(vqd_energies[1]) es_2.append(vqd_energies[2]) np.savetxt("groundstate.txt", es_1) np.savetxt("excitedstate.txt", es_2) print(f"Ground State: {np.round(np.mean(es_1),3)} +/- {np.round(np.std(es_1),3)} | Expected: {eigenvalues[1]}") print(f"Excited State: {np.round(np.mean(es_2),3)} +/- {np.round(np.std(es_2),3)} | Expected: {eigenvalues[2]}") np.round(np.mean(es_2) - np.mean(es_1), 3)/2 import seaborn as sns sns.boxplot(x=es_1) ax=sns.swarmplot(x=es_1, color="0.25") ax.set_title("1st Excited State") ax.vlines(x=eigenvalues[1], ymin=-10, ymax=10, label='Expected Eigenvalue',color='r') plt.legend() plt.show() sns.boxplot(x=es_2) ax=sns.swarmplot(x=es_2, color="0.25") ax.set_title("2nd Excited State") ax.vlines(x=eigenvalues[2], ymin=-10, ymax=10, label='Expected Eigenvalue',color='r') plt.legend() plt.show() sns.boxplot(x=(np.array(es_2)- np.array(es_1))/2) ax=sns.swarmplot(x=(np.array(es_2)- np.array(es_1))/2, color="0.25") ax.set_title("Gap") ax.vlines(x=(eigenvalues[2] - eigenvalues[1])/2, ymin=-10, ymax=10, label='Expected value',color='r') plt.legend() plt.show() v_dependence =[] v_values = np.linspace(0, 5, 20) for v in v_values: EPSILONS = [3., 3., 3., 4., 3.] hamiltonian = BCS_hamiltonian(EPSILONS, -float(v)) eigenvalues, eigenvectors = classical_solver(hamiltonian) v_dependence.append(eigenvalues[1] - eigenvalues[0]) plt.plot(v_values, v_dependence, 'o');
https://github.com/nahumsa/volta
nahumsa
import sys sys.path.append('../../') # Python imports import numpy as np import matplotlib.pyplot as plt # Qiskit from qiskit import BasicAer from qiskit.aqua.components.optimizers import COBYLA, SPSA from qiskit.circuit.library import TwoLocal # VOLTA from volta.vqd import VQD from volta.utils import classical_solver from volta.hamiltonians import BCS_hamiltonian %load_ext autoreload %autoreload 2 EPSILONS = [3., 3., 3., 4., 3.] V = -2 hamiltonian = BCS_hamiltonian(EPSILONS, V) print(hamiltonian) eigenvalues, eigenvectors = classical_solver(hamiltonian) print(f"Eigenvalues: {eigenvalues}") from tqdm import tqdm from qiskit.utils import QuantumInstance # Parameters Variables n_trials = 50 max_depth = 7 # Auxiliary Variables solution_dict = {} # Define Optimizer # optimizer = COBYLA() optimizer = SPSA(maxiter=250, c1=.7, last_avg=25) # Define Backend backend = QuantumInstance(backend=BasicAer.get_backend('qasm_simulator'), shots=10000) for depth in range(1,max_depth): # Ansatz with diferent depth ansatz = TwoLocal(hamiltonian.num_qubits, ['ry','rz'], 'cx', reps=depth) es_1 = [] es_2 = [] for _ in tqdm(range(n_trials), desc=f"Depth {depth}"): # Run algorithm Algo = VQD(hamiltonian=hamiltonian, ansatz=ansatz, n_excited_states=1, beta=10., optimizer=optimizer, backend=backend, overlap_method="amplitude", ) Algo.run(0) vqd_energies = Algo.energies es_1.append(vqd_energies[0]) es_2.append(vqd_energies[1]) es_1 = np.array(es_1) es_2 = np.array(es_2) # Maybe use a pd.dataframe solution_dict[depth] = {'mean':np.mean(es_2 - es_1), 'std':np.std(es_2 - es_1)} mean = [] std = [] for i in range(1,max_depth): mean.append(solution_dict[i]['mean']) std.append(solution_dict[i]['std']) solution_dict ed_eig= (eigenvalues[1] - eigenvalues[0])/2 import seaborn as sns sns.set() from matplotlib.ticker import MaxNLocator x_axis = [i for i in range(1,max_depth)] plt.errorbar(x_axis, np.array(mean)/2, yerr=np.array(std)/2, fmt='ro', ecolor='green') plt.hlines(y=ed_eig, xmin=0.5, xmax=6.5, label='Expected value',color='b') plt.title('Varying Depth SPSA', size=18) plt.xlabel('Depth', size= 14) plt.ylabel('Gap', size=14) plt.xticks(x_axis) plt.legend() plt.show() from matplotlib.ticker import MaxNLocator x_axis = [i for i in range(1,max_depth)] plt.errorbar(x_axis, np.array(mean)/2, yerr=np.array(std)/2, fmt='ro', ecolor='green') plt.hlines(y=ed_eig, xmin=0.5, xmax=6.5, label='Expected value',color='b') plt.title('Varying Depth', size=18) plt.xlabel('Depth', size= 14) plt.ylabel('Gap', size=14) plt.xticks(x_axis) plt.legend() plt.show() max_depth = 7 spsa_dict = {1: {'mean': 7.63536, 'std': 2.024100436737268}, 2: {'mean': 6.421452, 'std': 3.009174019443874}, 3: {'mean': 5.842042, 'std': 3.040774217602484}, 4: {'mean': 5.632112000000001, 'std': 3.7485136763063838}, 5: {'mean': 5.302354, 'std': 4.1340626645086065}, 6: {'mean': 4.079198, 'std': 3.6543650323135477}} spsa_dict = {1: {'mean': 5.335038, 'std': 1.708178187062462}, 2: {'mean': 4.527469999999999, 'std': 1.756017706431231}, 3: {'mean': 3.160082, 'std': 1.587476022331046}, 4: {'mean': 2.16104, 'std': 1.5474551641970113}, 5: {'mean': 1.3676439999999996, 'std': 1.5716504103852103}, 6: {'mean': 0.19817400000000002, 'std': 1.071217238623427}} cobyla_dict = {1: {'mean': 3.1321660000000002, 'std': 0.24530721278429674}, 2: {'mean': 2.94829, 'std': 1.0438090011587366}, 3: {'mean': 2.912668, 'std': 0.9325122996379187}, 4: {'mean': 3.16006, 'std': 0.38378217728289615}, 5: {'mean': 3.048998, 'std': 0.8419937475991135}, 6: {'mean': 2.630514, 'std': 1.029439954734612}} mean_spsa = [] std_spsa = [] mean_cobyla = [] std_cobyla = [] for i in range(1,max_depth): mean_spsa.append(spsa_dict[i]['mean']) std_spsa.append(spsa_dict[i]['std']) mean_cobyla.append(cobyla_dict[i]['mean']) std_cobyla.append(cobyla_dict[i]['std']) from matplotlib.ticker import MaxNLocator x_axis = [i for i in range(1,max_depth)] plt.errorbar(x_axis, np.array(mean_spsa)/2, yerr=np.array(std_spsa)/2, fmt='o', color='black', ecolor='gray', elinewidth=2, label='SPSA') plt.errorbar(x_axis, np.array(mean_cobyla)/2, yerr=np.array(std_cobyla)/2, fmt='o', color='red', ecolor='green', elinewidth=2, label='COBYLA') plt.hlines(y=ed_eig, xmin=0.5, xmax=6.5, label='Expected value',color='b') plt.title('Varying Depth', size=18) plt.xlabel('Depth', size= 14) plt.ylabel('Gap', size=14) plt.ylim(0., 4.1) plt.xticks(x_axis) plt.legend(loc="upper left") plt.savefig('Depth.png') plt.show() plt.plot(x_axis, np.array(mean_spsa)/2, 'or') plt.fill_between(x_axis, np.array(mean_spsa)/2 - np.array(std_spsa)/2 , np.array(mean_spsa)/2 + np.array(std_spsa)/2, color='gray', alpha=0.2) plt.show()
https://github.com/nahumsa/volta
nahumsa
import sys sys.path.append('../../') # Python imports import numpy as np import matplotlib.pyplot as plt # Qiskit from qiskit import BasicAer, Aer from qiskit.aqua.components.optimizers import COBYLA, SPSA from qiskit.circuit.library import TwoLocal # VOLTA from volta.vqd import VQD from volta.utils import classical_solver from volta.hamiltonians import BCS_hamiltonian %load_ext autoreload %autoreload 2 EPSILONS = [3., 3.] V = -2 hamiltonian = BCS_hamiltonian(EPSILONS, V) print(hamiltonian) eigenvalues, eigenvectors = classical_solver(hamiltonian) print(f"Eigenvalues: {eigenvalues}") from qiskit.providers.aer.noise import depolarizing_error from qiskit.providers.aer.noise import thermal_relaxation_error from qiskit.providers.aer.noise import NoiseModel # Defining noise model # T1 and T2 values for qubits 0-n n_qubits = 2*len(EPSILONS) # T1s = np.random.normal(50e3, 10e3, n_qubits) # Sampled from normal distribution mean 50 microsec # T2s = np.random.normal(70e3, 10e3, n_qubits) # Sampled from normal distribution mean 50 microsec T1s = [30e3]*n_qubits T2s = [20e3]*n_qubits # Truncate random T2s <= T1s T2s = np.array([min(T2s[j], 2 * T1s[j]) for j in range(n_qubits)]) # Instruction times (in nanoseconds) time_u1 = 0 # virtual gate time_u2 = 50 # (single X90 pulse) time_u3 = 100 # (two X90 pulses) time_cx = 300 time_reset = 1000 # 1 microsecond time_measure = 1000 # 1 microsecond # QuantumError objects errors_reset = [thermal_relaxation_error(t1, t2, time_reset) for t1, t2 in zip(T1s, T2s)] errors_measure = [thermal_relaxation_error(t1, t2, time_measure) for t1, t2 in zip(T1s, T2s)] errors_u1 = [thermal_relaxation_error(t1, t2, time_u1) for t1, t2 in zip(T1s, T2s)] errors_u2 = [thermal_relaxation_error(t1, t2, time_u2) for t1, t2 in zip(T1s, T2s)] errors_u3 = [thermal_relaxation_error(t1, t2, time_u3) for t1, t2 in zip(T1s, T2s)] errors_cx = [[thermal_relaxation_error(t1a, t2a, time_cx).expand( thermal_relaxation_error(t1b, t2b, time_cx)) for t1a, t2a in zip(T1s, T2s)] for t1b, t2b in zip(T1s, T2s)] # Add errors to noise model noise_thermal = NoiseModel() for j in range(n_qubits): noise_thermal.add_quantum_error(errors_reset[j], "reset", [j]) noise_thermal.add_quantum_error(errors_measure[j], "measure", [j]) noise_thermal.add_quantum_error(errors_u1[j], "u1", [j]) noise_thermal.add_quantum_error(errors_u2[j], "u2", [j]) noise_thermal.add_quantum_error(errors_u3[j], "u3", [j]) for k in range(n_qubits): noise_thermal.add_quantum_error(errors_cx[j][k], "cx", [j, k]) print(noise_thermal) from tqdm import tqdm from qiskit.aqua import QuantumInstance # Parameters Variables n_trials = 50 max_depth = 7 # Auxiliary Variables solution_dict = {} # Define Optimizer #optimizer = COBYLA() optimizer = SPSA(maxiter=250, c1=1.5, last_avg=25) # Define Backend backend = QuantumInstance(backend= Aer.get_backend('qasm_simulator'), noise_model=noise_thermal, shots=10000) for depth in range(1,max_depth): # Ansatz with diferent depth ansatz = TwoLocal(hamiltonian.num_qubits, ['ry','rz'], 'cx', reps=depth) es_1 = [] es_2 = [] for _ in tqdm(range(n_trials), desc=f"Depth {depth}"): # Run algorithm Algo = VQD(hamiltonian=hamiltonian, ansatz=ansatz, n_excited_states=2, beta=10., optimizer=optimizer, backend=backend) Algo.run(0) vqd_energies = Algo.energies es_1.append(vqd_energies[1]) es_2.append(vqd_energies[2]) es_1 = np.array(es_1) es_2 = np.array(es_2) # Maybe use a pd.dataframe solution_dict[depth] = {'mean':np.mean(es_2 - es_1), 'std':np.std(es_2 - es_1)} mean = [] std = [] for i in range(1,max_depth): mean.append(solution_dict[i]['mean']) std.append(solution_dict[i]['std']) solution_dict import seaborn as sns sns.set() from matplotlib.ticker import MaxNLocator x_axis = [i for i in range(1,max_depth)] plt.errorbar(x_axis, np.array(mean)/2, yerr=np.array(std)/2, fmt='ro', ecolor='green') plt.hlines(y=2, xmin=0.5, xmax=6.5, label='Expected value',color='b') plt.title('Varying Depth', size=18) plt.xlabel('Depth', size= 14) plt.ylabel('Gap', size=14) plt.xticks(x_axis) plt.legend() plt.show() spsa_dict = {1: {'mean': 4.540763883482028, 'std': 0.2166500619449026}, 2: {'mean': 3.6292261939489365, 'std': 1.3793621699692478}, 3: {'mean': 3.5182758038620277, 'std': 0.8910628276050163}, 4: {'mean': 3.292976405037763, 'std': 1.3966224263108362}, 5: {'mean': 3.5144598497611055, 'std': 1.0963827019837287}, 6: {'mean': 2.6975338496665677, 'std': 1.3507496759669415}} cobyla_dict = {1: {'mean': 2.3633300482974127, 'std': 2.1367566366817043}, 2: {'mean': 4.113586221793872, 'std': 0.7316145547992721}, 3: {'mean': 4.321305470168272, 'std': 0.4919574179280678}, 4: {'mean': 4.3014277420825975, 'std': 0.4023952320110141}, 5: {'mean': 4.157595644181709, 'std': 0.33724862839247316}, 6: {'mean': 3.968890438601869, 'std': 0.29850260762472425}} mean_spsa = [] std_spsa = [] mean_cobyla = [] std_cobyla = [] for i in range(1,max_depth): mean_spsa.append(spsa_dict[i]['mean']) std_spsa.append(spsa_dict[i]['std']) mean_cobyla.append(cobyla_dict[i]['mean']) std_cobyla.append(cobyla_dict[i]['std']) from matplotlib.ticker import MaxNLocator x_axis = [i for i in range(1,max_depth)] plt.errorbar(x_axis, np.array(mean_spsa)/2, yerr=np.array(std_spsa)/2, fmt='o', color='black', ecolor='gray', elinewidth=2, label='SPSA') plt.errorbar(x_axis, np.array(mean_cobyla)/2, yerr=np.array(std_cobyla)/2, fmt='o', color='red', ecolor='green', elinewidth=2, label='COBYLA') plt.hlines(y=2, xmin=0.5, xmax=6.5, label='Expected value',color='b') plt.title('Varying Depth', size=18) plt.xlabel('Depth', size= 14) plt.ylabel('Gap', size=14) plt.ylim(0., 4.5) plt.xticks(x_axis) plt.legend() plt.savefig('Depth.png') plt.show()
https://github.com/nahumsa/volta
nahumsa
import sys sys.path.append('../../') # Python imports import numpy as np import matplotlib.pyplot as plt # Qiskit from qiskit import BasicAer from qiskit.aqua.components.optimizers import COBYLA, SPSA, L_BFGS_B from qiskit.circuit.library import TwoLocal # VOLTA from volta.vqd import VQD from volta.utils import classical_solver from volta.hamiltonians import BCS_hamiltonian %load_ext autoreload %autoreload 2 EPSILONS = [3, 3] V = -2 hamiltonian = BCS_hamiltonian(EPSILONS, V) print(hamiltonian) eigenvalues, eigenvectors = classical_solver(hamiltonian) print(f"Eigenvalues: {eigenvalues}") from tqdm import tqdm from qiskit.aqua import QuantumInstance # Parameters Variables n_trials = 50 # Auxiliary Variables solution_dict = {} # Define Optimizer optimizers = [COBYLA(), SPSA(maxiter=250, c1=.7, last_avg=25), #L_BFGS_B(), ] optimizer_names = ['COBYLA', 'SPSA', #'L_BFGS_B' ] # Define Backend backend = QuantumInstance(backend=BasicAer.get_backend('qasm_simulator'), shots=10_000) # Ansatz with diferent depth ansatz = TwoLocal(hamiltonian.num_qubits, ['ry','rz'], 'cx', reps=3) for i, optimizer in enumerate(optimizers): es_1 = [] es_2 = [] for _ in tqdm(range(n_trials), desc=f"Optimizer {optimizer_names[i]}"): # Run algorithm Algo = VQD(hamiltonian=hamiltonian, ansatz=ansatz, n_excited_states=2, beta=10., optimizer=optimizer, backend=backend) Algo.run(0) vqd_energies = Algo.energies es_1.append(vqd_energies[1]) es_2.append(vqd_energies[2]) es_1 = np.array(es_1) es_2 = np.array(es_2) # Maybe use a pd.dataframe solution_dict[i] = {'mean': np.mean(es_2 - es_1), 'std':np.std(es_2 - es_1), } solution_dict mean = [] std = [] for i in range(len(optimizers)): mean.append(solution_dict[i]['mean']) std.append(solution_dict[i]['std']) import seaborn as sns sns.set() from matplotlib.ticker import MaxNLocator x_axis = optimizer_names plt.errorbar(x_axis, np.array(mean)/2, yerr=np.array(std)/2, fmt='ro', ecolor='green') plt.hlines(y=2, xmin=0., xmax=len(optimizers)+ 0.25, label='Expected value',color='b') plt.title('Optimizers', size=18) plt.xlabel('Optimizer', size= 14) plt.ylabel('Gap', size=14) plt.xticks(x_axis) plt.legend() plt.show()
https://github.com/nahumsa/volta
nahumsa
import sys sys.path.append('../../') # Python imports import numpy as np import matplotlib.pyplot as plt # Qiskit from qiskit import BasicAer, Aer from qiskit.aqua import QuantumInstance from qiskit.aqua.components.optimizers import COBYLA, SPSA from qiskit.circuit.library import TwoLocal # VOLTA from volta.vqd import VQD from volta.utils import classical_solver from volta.hamiltonians import BCS_hamiltonian %load_ext autoreload %autoreload 2 EPSILONS = [3, 3] V = -2. hamiltonian = BCS_hamiltonian(EPSILONS, V) print(hamiltonian) eigenvalues, eigenvectors = classical_solver(hamiltonian) print(f"Eigenvalues: {eigenvalues}") from tqdm import tqdm def hamiltonian_varying_V(min_V, max_V, points, epsilons, n_trials): solution_VQD = {} energies_Classical = [] V = np.linspace(min_V, max_V, points) backend = QuantumInstance(backend=BasicAer.get_backend('qasm_simulator'), shots=10000) optimizer = SPSA(maxiter=250, c1=.7, last_avg=25) #optimizer = COBYLA() for v in tqdm(V): hamiltonian = BCS_hamiltonian(epsilons, v) ansatz = TwoLocal(hamiltonian.num_qubits, ['ry','rz'], 'cx', reps=3) es_1 = [] es_2 = [] for _ in tqdm(range(n_trials), desc=f"V= {v}"): # Run algorithm Algo = VQD(hamiltonian=hamiltonian, ansatz=ansatz, n_excited_states=2, beta=10., optimizer=optimizer, backend=backend) Algo.run(0) vqd_energies = Algo.energies es_1.append(vqd_energies[1]) es_2.append(vqd_energies[2]) es_1 = np.array(es_1) es_2 = np.array(es_2) solution_VQD[v] = {'mean':np.mean(es_2 - es_1), 'std':np.std(es_2 - es_1)} classical, _ = classical_solver(hamiltonian) energies_Classical.append(classical[2]- classical[1]) return solution_VQD, np.array(energies_Classical), V min_V = -0. max_V = -2. points = 5 epsilons = [3,3] n_trials = 50 solution_VQD, energy_classical, V = hamiltonian_varying_V(min_V, max_V, points, epsilons, n_trials) solution_VQD import seaborn as sns sns.set() mean = [] std = [] for _, sol in solution_VQD.items(): mean.append(sol['mean']) std.append(sol['std']) plt.errorbar(V, np.array(mean)/2, yerr=np.array(std)/2, fmt='ro', ecolor='green', label='VQD') plt.plot(V, energy_classical/2, 'b-', label="Exact") plt.xlabel('V') plt.ylabel('Gap') plt.legend() plt.savefig('Var_V.png') plt.show() V spsa_dict = {-0.0: {'mean': 2.2544600000000004, 'std': 3.6059371187529052}, -0.5: {'mean': 2.201132, 'std': 3.5924339523749076}, -1.0: {'mean': 2.3685160000000005, 'std': 3.2362400972956262}, -1.5: {'mean': 2.262069, 'std': 3.6215824729514305}, -2.0: {'mean': 2.151896, 'std': 3.285247713884601}} cobyla_dict = {-0.0: {'mean': 0.2738039999999999, 'std': 0.5017597014348602}, -0.5: {'mean': 1.1608589999999999, 'std': 0.7228235554884747}, -1.0: {'mean': 2.0350799999999993, 'std': 0.8327042377699295}, -1.5: {'mean': 3.137112, 'std': 0.6724548732487554}, -2.0: {'mean': 4.314758, 'std': 0.5284894406097439}} mean_spsa = [] std_spsa = [] mean_cobyla = [] std_cobyla = [] x_axis = np.array([-0. , -0.5, -1. , -1.5, -2. ]) for sol in x_axis: mean_spsa.append(spsa_dict[sol]['mean']) std_spsa.append(spsa_dict[sol]['std']) mean_cobyla.append(cobyla_dict[sol]['mean']) std_cobyla.append(cobyla_dict[sol]['std']) from matplotlib.ticker import MaxNLocator x_axis = np.array([-0. , -0.5, -1. , -1.5, -2. ]) energy_classical = np.array([0., 1., 2., 3., 4.]) plt.errorbar(x_axis, np.array(mean_spsa)/2, yerr=np.array(std_spsa)/2, fmt='o', color='black', ecolor='gray', elinewidth=2, label='SPSA') plt.errorbar(x_axis, np.array(mean_cobyla)/2, yerr=np.array(std_cobyla)/2, fmt='o', color='red', ecolor='green', elinewidth=2, label='COBYLA') plt.plot(V, energy_classical/2, 'b-', label="Exact") plt.xlabel('V') plt.ylabel('Gap') plt.legend() plt.savefig('Var_V_optimizers.png') plt.show()
https://github.com/nahumsa/volta
nahumsa
import sys sys.path.append('../../') # Python imports import numpy as np import matplotlib.pyplot as plt # Qiskit from qiskit import BasicAer, Aer from qiskit.aqua import QuantumInstance from qiskit.aqua.components.optimizers import COBYLA, SPSA from qiskit.circuit.library import TwoLocal # VOLTA from volta.vqd import VQD from volta.utils import classical_solver from volta.hamiltonians import BCS_hamiltonian %load_ext autoreload %autoreload 2 EPSILONS = [3, 3] V = -2. hamiltonian = BCS_hamiltonian(EPSILONS, V) print(hamiltonian) eigenvalues, eigenvectors = classical_solver(hamiltonian) print(f"Eigenvalues: {eigenvalues}") from qiskit.providers.aer.noise import depolarizing_error from qiskit.providers.aer.noise import thermal_relaxation_error from qiskit.providers.aer.noise import NoiseModel # Defining noise model # T1 and T2 values for qubits 0-n n_qubits = 2*len(EPSILONS) # T1s = np.random.normal(50e3, 10e3, n_qubits) # Sampled from normal distribution mean 50 microsec # T2s = np.random.normal(70e3, 10e3, n_qubits) # Sampled from normal distribution mean 50 microsec T1s = [30e3]*n_qubits T2s = [20e3]*n_qubits # Truncate random T2s <= T1s T2s = np.array([min(T2s[j], 2 * T1s[j]) for j in range(n_qubits)]) # Instruction times (in nanoseconds) time_u1 = 0 # virtual gate time_u2 = 50 # (single X90 pulse) time_u3 = 100 # (two X90 pulses) time_cx = 300 time_reset = 1000 # 1 microsecond time_measure = 1000 # 1 microsecond # QuantumError objects errors_reset = [thermal_relaxation_error(t1, t2, time_reset) for t1, t2 in zip(T1s, T2s)] errors_measure = [thermal_relaxation_error(t1, t2, time_measure) for t1, t2 in zip(T1s, T2s)] errors_u1 = [thermal_relaxation_error(t1, t2, time_u1) for t1, t2 in zip(T1s, T2s)] errors_u2 = [thermal_relaxation_error(t1, t2, time_u2) for t1, t2 in zip(T1s, T2s)] errors_u3 = [thermal_relaxation_error(t1, t2, time_u3) for t1, t2 in zip(T1s, T2s)] errors_cx = [[thermal_relaxation_error(t1a, t2a, time_cx).expand( thermal_relaxation_error(t1b, t2b, time_cx)) for t1a, t2a in zip(T1s, T2s)] for t1b, t2b in zip(T1s, T2s)] # Add errors to noise model noise_thermal = NoiseModel() for j in range(n_qubits): noise_thermal.add_quantum_error(errors_reset[j], "reset", [j]) noise_thermal.add_quantum_error(errors_measure[j], "measure", [j]) noise_thermal.add_quantum_error(errors_u1[j], "u1", [j]) noise_thermal.add_quantum_error(errors_u2[j], "u2", [j]) noise_thermal.add_quantum_error(errors_u3[j], "u3", [j]) for k in range(n_qubits): noise_thermal.add_quantum_error(errors_cx[j][k], "cx", [j, k]) print(noise_thermal) from tqdm import tqdm def hamiltonian_varying_V(min_V, max_V, points, epsilons, n_trials): solution_VQD = {} energies_Classical = [] V = np.linspace(min_V, max_V, points) backend = QuantumInstance(backend= Aer.get_backend('qasm_simulator'), noise_model=noise_thermal, shots=10000) optimizer = SPSA(maxiter=250, c1=1.2, last_avg=25) #optimizer = COBYLA() for v in tqdm(V): hamiltonian = BCS_hamiltonian(epsilons, v) ansatz = TwoLocal(hamiltonian.num_qubits, ['ry','rz'], 'cx', reps=3) es_1 = [] es_2 = [] for _ in tqdm(range(n_trials), desc=f"V= {v}"): # Run algorithm Algo = VQD(hamiltonian=hamiltonian, ansatz=ansatz, n_excited_states=2, beta=10., optimizer=optimizer, backend=backend) Algo.run(0) vqd_energies = Algo.energies es_1.append(vqd_energies[1]) es_2.append(vqd_energies[2]) es_1 = np.array(es_1) es_2 = np.array(es_2) solution_VQD[v] = {'mean':np.mean(es_2 - es_1), 'std':np.std(es_2 - es_1)} classical, _ = classical_solver(hamiltonian) energies_Classical.append(classical[2]- classical[1]) return solution_VQD, np.array(energies_Classical), V min_V = -0. max_V = -2. points = 5 epsilons = [3,3] n_trials = 50 solution_VQD, energy_classical, V = hamiltonian_varying_V(min_V, max_V, points, epsilons, n_trials) solution_VQD import seaborn as sns sns.set() mean = [] std = [] for _, sol in solution_VQD.items(): mean.append(sol['mean']) std.append(sol['std']) plt.errorbar(V, np.array(mean)/2, yerr=np.array(std)/2, fmt='ro', ecolor='green', label='VQD') plt.plot(V, energy_classical/2, 'b-', label="Exact") plt.xlabel('V') plt.ylabel('Gap') plt.legend() plt.savefig('Var_V.png') plt.show() V spsa_dict = {-0.0: {'mean': 2.2544600000000004, 'std': 3.6059371187529052}, -0.5: {'mean': 2.201132, 'std': 3.5924339523749076}, -1.0: {'mean': 2.3685160000000005, 'std': 3.2362400972956262}, -1.5: {'mean': 2.262069, 'std': 3.6215824729514305}, -2.0: {'mean': 2.151896, 'std': 3.285247713884601}} cobyla_dict = {-0.0: {'mean': 0.2738039999999999, 'std': 0.5017597014348602}, -0.5: {'mean': 1.1608589999999999, 'std': 0.7228235554884747}, -1.0: {'mean': 2.0350799999999993, 'std': 0.8327042377699295}, -1.5: {'mean': 3.137112, 'std': 0.6724548732487554}, -2.0: {'mean': 4.314758, 'std': 0.5284894406097439}} mean_spsa = [] std_spsa = [] mean_cobyla = [] std_cobyla = [] x_axis = np.array([-0. , -0.5, -1. , -1.5, -2. ]) for sol in x_axis: mean_spsa.append(spsa_dict[sol]['mean']) std_spsa.append(spsa_dict[sol]['std']) mean_cobyla.append(cobyla_dict[sol]['mean']) std_cobyla.append(cobyla_dict[sol]['std']) from matplotlib.ticker import MaxNLocator x_axis = np.array([-0. , -0.5, -1. , -1.5, -2. ]) energy_classical = np.array([0., 1., 2., 3., 4.]) plt.errorbar(x_axis, np.array(mean_spsa)/2, yerr=np.array(std_spsa)/2, fmt='o', color='black', ecolor='gray', elinewidth=2, label='SPSA') plt.errorbar(x_axis, np.array(mean_cobyla)/2, yerr=np.array(std_cobyla)/2, fmt='o', color='red', ecolor='green', elinewidth=2, label='COBYLA') plt.plot(V, energy_classical/2, 'b-', label="Exact") plt.xlabel('V') plt.ylabel('Gap') plt.legend() plt.savefig('Var_V_optimizers.png') plt.show()
https://github.com/nahumsa/volta
nahumsa
import sys sys.path.append('../../') # Python imports import numpy as np import matplotlib.pyplot as plt # Qiskit from qiskit import BasicAer from qiskit.aqua.components.optimizers import COBYLA, SPSA from qiskit.circuit.library import TwoLocal # VOLTA from volta.vqd import VQD from volta.utils import classical_solver from volta.hamiltonians import BCS_hamiltonian %load_ext autoreload %autoreload 2 EPSILONS = [3, 3] V = -2 hamiltonian = BCS_hamiltonian(EPSILONS, V) print(hamiltonian) eigenvalues, eigenvectors = classical_solver(hamiltonian) print(f"Eigenvalues: {eigenvalues}") from itertools import product # Get the ideal count ideal_dict = {} bin_combinations = list(product(['0','1'], repeat=hamiltonian.num_qubits)) for i, eigvect in enumerate(np.abs(eigenvectors)**2): dic = {} for ind, val in enumerate(bin_combinations): val = ''.join(val) dic[val] = eigvect[ind] ideal_dict[i] = dic from qiskit.aqua import QuantumInstance # Define Optimizer # optimizer = COBYLA() optimizer = SPSA(maxiter=1000) # Define Backend # backend = BasicAer.get_backend('qasm_simulator') backend = QuantumInstance(backend=BasicAer.get_backend('qasm_simulator'), shots=10000) # Define ansatz ansatz = TwoLocal(hamiltonian.num_qubits, ['ry','rz'], 'cx', reps=2) # Run algorithm Algo = VQD(hamiltonian=hamiltonian, ansatz=ansatz, n_excited_states=3, beta=10., optimizer=optimizer, backend=backend) Algo.run() vqd_energies = Algo.energies vqd_states = Algo.states from copy import copy # Create states and measure them states = [] for ind, state in enumerate(vqd_states): states.append(copy(state)) states[ind].measure_all() from qiskit import execute from qiskit.visualization import plot_histogram backend = BasicAer.get_backend('qasm_simulator') count = execute(states[0], backend=backend, shots=10000).result().get_counts() plot_histogram([ideal_dict[0], count],legend=['Ideal','Result']) count = execute(states[1], backend=backend, shots=10000).result().get_counts() plot_histogram([ideal_dict[1], count],legend=['Ideal','Result']) count = execute(states[2], backend=backend, shots=10000).result().get_counts() plot_histogram([ideal_dict[2], count],legend=['Ideal','Result']) count = execute(states[3], backend=backend, shots=10000).result().get_counts() plot_histogram([ideal_dict[3], count],legend=['Ideal','Result']) eigenvalues vqd_energies n_1_sim, n_2_sim = 1, 2 n_1_vqd, n_2_vqd = 1, 2 print(f"Gap Exact: {(eigenvalues[n_2_sim] - eigenvalues[n_1_sim])/2}") print(f"Gap VQD: {(vqd_energies[n_2_vqd] - vqd_energies[n_1_vqd])/2}") from tqdm import tqdm def hamiltonian_varying_eps(eps, V): energies_VQD = [] energies_Classical = [] for epsilons in tqdm(eps): hamiltonian = BCS_hamiltonian(epsilons, V) optimizer = COBYLA(maxiter=10000) backend = BasicAer.get_backend('qasm_simulator') Algo = VQD(hamiltonian=hamiltonian, n_excited_states=1, beta=3., optimizer=optimizer, backend=backend) Algo.run(0) uantum = Algo.energies energies_VQD.append([quantum[1], quantum[2]]) classical = classical_solver(hamiltonian) energies_Classical.append([classical[1], classical[2]]) return energies_VQD, energies_Classical eps = [[1, 1.5], [1, 2.], [1, 2.5]] V = -1. energy_vqd, energy_classical = hamiltonian_varying_eps(eps, V) plt.plot([str(v) for v in eps], [value[1] - value[0] for value in energy_vqd], 'ro', label="VQD") plt.plot([str(v) for v in eps], [value[1] - value[0] for value in energy_classical], 'go', label="Exact") plt.xlabel('$\epsilon$') plt.ylabel('Gap') plt.legend() plt.show()
https://github.com/nahumsa/volta
nahumsa
import numpy as np from qiskit.aqua.operators import I, X, Y, Z import matplotlib.pyplot as plt %load_ext autoreload %autoreload 2 def BCS_hamiltonian(epsilons, V): return ((1/2*epsilons[0]*I^Z) + (1/2*epsilons[1]*Z^I) + V*(1/2*(X^X) + 1/2*(Y^Y))) EPSILONS = [1,1] V = 2 hamiltonian = BCS_hamiltonian(EPSILONS, V) print(hamiltonian) from qiskit.aqua.operators import PauliTrotterEvolution, CircuitSampler, MatrixEvolution, Suzuki from qiskit.aqua.operators import StateFn, Plus, Zero, One, Minus, PauliExpectation, CX from qiskit.circuit import Parameter from qiskit import BasicAer # Initial State init_state = (Plus^Zero) # Time evolution operator evolution_param = Parameter("t") evolution_op = (evolution_param * hamiltonian).exp_i() # Measurement of the Hamiltonian with the time evolved state evo_and_meas = StateFn(hamiltonian).adjoint() @ evolution_op @ init_state # Trotterization trotterized_op = PauliTrotterEvolution(trotter_mode=Suzuki(order=2, reps=1)).convert(evo_and_meas) # Diagonalize the measurement diagonalized_meas_op = PauliExpectation().convert(trotterized_op) # Create an array to represent time and apply to the circuit n_points = 10 time_array = list(np.linspace(0, 1/V, n_points)) expectations = diagonalized_meas_op.bind_parameters({evolution_param: time_array}) # Define Backend backend = BasicAer.get_backend("statevector_simulator") # Use CircuitSampler for getting energy values sampler = CircuitSampler(backend=backend) sampled_expectations = sampler.convert(expectations) sampled_energies = sampled_expectations.eval() print(f"Time:\n {time_array}") print(f"Sampled energies after Trotterization:\n {np.real(sampled_energies)}") plt.plot(time_array, np.real(sampled_energies)) plt.show()
https://github.com/nahumsa/volta
nahumsa
import qiskit import numpy as np from qiskit.aqua.operators import PauliExpectation, CircuitSampler, ExpectationFactory from qiskit.aqua.operators import CircuitStateFn, StateFn, ListOp import sys sys.path.append('../../') from typing import Union import qiskit import numpy as np from qiskit import Aer, execute from qiskit.aqua.utils.backend_utils import is_aer_provider from qiskit.aqua.operators import (PauliExpectation, CircuitSampler, ExpectationFactory, CircuitStateFn, StateFn, ListOp) import sys sys.path.append('../') def sample_hamiltonian(hamiltonian: qiskit.aqua.operators.OperatorBase, backend: Union[qiskit.providers.BaseBackend, qiskit.aqua.QuantumInstance], ansatz: qiskit.QuantumCircuit): if qiskit.aqua.quantum_instance.QuantumInstance == type(backend): sampler = CircuitSampler(backend, param_qobj=is_aer_provider(backend.backend)) else: sampler = CircuitSampler(backend) expectation = ExpectationFactory.build(operator=hamiltonian,backend=backend) observable_meas = expectation.convert(StateFn(hamiltonian, is_measurement=True)) ansatz_circuit_op = CircuitStateFn(ansatz) expect_op = observable_meas.compose(ansatz_circuit_op).reduce() sampled_expect_op = sampler.convert(expect_op) return np.real(sampled_expect_op.eval()) from VOLTA.Ansatz import get_num_parameters, get_var_form from qiskit.aqua.operators import I, X, Y, Z from qiskit.aqua import QuantumInstance n_qubits = 2 n_params = get_num_parameters(n_qubits) params = [0.]*n_params wavefunction = get_var_form(params, n_qubits) hamiltonian = 1/2*((Z^Z) + (Z^I) + (X^X)) hamiltonian = X^X backend = QuantumInstance(backend=qiskit.BasicAer.get_backend('qasm_simulator'), shots=10000) sample_hamiltonian(hamiltonian, backend, wavefunction) # Variational Form backend = qiskit.BasicAer.get_backend('qasm_simulator') sampler = CircuitSampler(backend=backend) expectation = ExpectationFactory.build(operator=hamiltonian,backend=backend) observable_meas = expectation.convert(StateFn(hamiltonian, is_measurement=True)) print(observable_meas) ansatz_circuit_op = CircuitStateFn(wavefunction) expect_op = observable_meas.compose(ansatz_circuit_op).reduce() sampled_expect_op = sampler.convert(expect_op) means = np.real(sampled_expect_op.eval()) means
https://github.com/nahumsa/volta
nahumsa
import sys sys.path.append('../../') import numpy as np from qiskit import QuantumCircuit from qiskit.opflow import I, X, Y, Z import matplotlib.pyplot as plt from volta.observables import sample_hamiltonian from volta.hamiltonians import BCS_hamiltonian EPSILONS = [3, 3] V = -2 hamiltonian = BCS_hamiltonian(EPSILONS, V) print(hamiltonian) eigenvalues, _ = np.linalg.eigh(hamiltonian.to_matrix()) print(f"Eigenvalues: {eigenvalues}") def create_circuit(n: int) -> list: return [QuantumCircuit(n) for _ in range(2)] n = hamiltonian.num_qubits init_states = create_circuit(n) def copy_unitary(list_states: list) -> list: out_states = [] for state in list_states: out_states.append(state.copy()) return out_states import textwrap def apply_initialization(list_states: list) -> None: for ind, state in enumerate(list_states): b = bin(ind)[2:] if len(b) != n: b = '0'*(n - len(b)) + b spl = textwrap.wrap(b, 1) for qubit, val in enumerate(spl): if val == '1': state.x(qubit) apply_initialization(init_states) initialization = copy_unitary(init_states) from qiskit.circuit.library import TwoLocal ansatz = TwoLocal(hamiltonian.num_qubits, ['ry','rz'], 'cx', reps=2) def apply_ansatz(ansatz: QuantumCircuit, list_states: list) -> None: for states in list_states: states.append(ansatz, range(n)) apply_ansatz(ansatz, init_states) init_states[1].draw('mpl') w = np.arange(n, 0, -1) w def _apply_varform_params(ansatz, params: list): """Get an hardware-efficient ansatz for n_qubits given parameters. """ # Define variational Form var_form = ansatz # Get Parameters from the variational form var_form_params = sorted(var_form.parameters, key=lambda p: p.name) # Check if the number of parameters is compatible assert len(var_form_params) == len(params), "The number of parameters don't match" # Create a dictionary with the parameters and values param_dict = dict(zip(var_form_params, params)) # Assing those values for the ansatz wave_function = var_form.assign_parameters(param_dict) return wave_function from qiskit import BasicAer from qiskit.utils import QuantumInstance def cost_function(params:list) -> float: backend = BasicAer.get_backend('qasm_simulator') backend = QuantumInstance(backend, shots=10000) cost = 0 # Define Ansatz for i, state in enumerate(init_states): qc = _apply_varform_params(state, params) # Hamiltonian hamiltonian_eval = sample_hamiltonian(hamiltonian=hamiltonian, ansatz=qc, backend=backend) cost += w[i] * hamiltonian_eval return cost from qiskit.aqua.components.optimizers import COBYLA optimizer = COBYLA(maxiter=1000) n_parameters = len(init_states[0].parameters) params = np.random.rand(n_parameters) optimal_params, mean_energy, n_iters = optimizer.optimize(num_vars=n_parameters, objective_function=cost_function, initial_point=params) mean_energy # Optimized first ansatz ansatz_1 = _apply_varform_params(ansatz, optimal_params) ansatz_1.name = 'U(θ)' apply_ansatz(ansatz_1, init_states) init_states[2].draw() from qiskit.aqua import QuantumInstance def cost_function_ind(ind: int, params:list) -> float: backend = BasicAer.get_backend('qasm_simulator') backend = QuantumInstance(backend, shots=10000) cost = 0 # Define Ansatz qc = _apply_varform_params(init_states[ind], params) # Hamiltonian hamiltonian_eval = sample_hamiltonian(hamiltonian=hamiltonian, ansatz=qc, backend=backend) cost += hamiltonian_eval return - cost from functools import partial cost = partial(cost_function_ind, 2) n_parameters = len(init_states[0].parameters) params = np.random.rand(n_parameters) optimal_params, energy_gs, n_iters = optimizer.optimize(num_vars=n_parameters, objective_function=cost, initial_point=params) energy_gs eigenvalues # Optimized second ansatz ansatz_2 = _apply_varform_params(ansatz, optimal_params) ansatz_2.name = 'V(ϕ)'
https://github.com/nahumsa/volta
nahumsa
def dswap_test_circuit(qc1: QuantumCircuit, qc2: QuantumCircuit) -> QuantumCircuit: """ Construct the destructive SWAP test circuit given two circuits. Args: qc1(qiskit.QuantumCircuit): Quantum circuit for the first state. qc2(qiskit.QuantumCircuit): Quantum circuit for the second state. Output: (qiskit.QuantumCircuit): swap test circuit. """ # Helper variables n_total = qc1.num_qubits + qc2.num_qubits range_qc1 = [i for i in range(qc1.num_qubits)] range_qc2 = [i + qc1.num_qubits for i in range(qc2.num_qubits)] # Constructing the SWAP test circuit qc_swap = QuantumCircuit(n_total , n_total) qc_swap.append(qc1, range_qc1) qc_swap.append(qc2, range_qc2) for index, qubit in enumerate(range_qc1): qc_swap.cx(qubit, range_qc2[index]) qc_swap.h(qubit) for index, qubit in enumerate(range_qc1): qc_swap.measure(qubit, 2*index) for index, qubit in enumerate(range_qc2): qc_swap.measure(range_qc2[index] , 2*index + 1) return qc_swap import textwrap import qiskit from qiskit import QuantumCircuit, execute from typing import Union from qiskit.aqua import QuantumInstance from qiskit.providers import BaseBackend def measure_dswap_test(qc1: QuantumCircuit, qc2: QuantumCircuit, backend: Union[BaseBackend,QuantumInstance], num_shots: int=10000) -> float: """Returns the fidelity from a destructive SWAP test. Args: qc1 (QuantumCircuit): Quantum Circuit for the first state. qc2 (QuantumCircuit): Quantum Circuit for the second state. backend (Union[BaseBackend,QuantumInstance]): Backend. num_shots (int, optional): Number of shots. Defaults to 10000. Returns: float: result of the overlap betweeen the first and second state. """ n = qc1.num_qubits swap_circuit = dswap_test_circuit(qc1, qc2) # Check if the backend is a quantum instance. if qiskit.aqua.quantum_instance.QuantumInstance == type(backend): count = backend.execute(swap_circuit).get_counts() else: count = execute(swap_circuit, backend=backend, shots=num_shots).result().get_counts() result = 0 for meas, counts in count.items(): split_meas = textwrap.wrap(meas, 2) for m in split_meas: if m == '11': result -= counts else: result += counts total = sum(count.values()) return result/(n*total) from qiskit import QuantumCircuit, execute qc1 = QuantumCircuit(n) qc2 = QuantumCircuit(n) backend = BasicAer.get_backend('qasm_simulator') measure_dswap_test(qc1, qc2, backend) from qiskit import BasicAer backend = BasicAer.get_backend('qasm_simulator') num_shots = 10000 count = execute(swap_circuit, backend=backend, shots=num_shots).result().get_counts() import textwrap result = 0 for meas, counts in count.items(): split_meas = textwrap.wrap(meas, 2) for m in split_meas: if m == '11': result -= counts else: result += counts total = sum(count.values()) result/(n*total)
https://github.com/nahumsa/volta
nahumsa
import numpy as np import qiskit from qiskit.aqua.operators import OperatorBase, ListOp, PrimitiveOp, PauliOp from qiskit.aqua.operators import I, X, Y, Z from qiskit.quantum_info import Pauli from qiskit.aqua.algorithms import VQE, NumPyEigensolver import matplotlib.pyplot as plt # hamiltonian = 0.5*(Z^I) + 0.5*(Z^Z) hamiltonian = 1/2*((I^Z) + (Z^I) + 2*( (X^X) + (Y^Y))) print(hamiltonian) eigenvalues, _ = np.linalg.eigh(hamiltonian.to_matrix()) print(f"Eigenvalues: {eigenvalues}") from qiskit.circuit.library import TwoLocal def _get_ansatz(n_qubits): return TwoLocal(n_qubits, ['ry','rz'], 'cx', reps=1) def get_num_parameters(n_qubits): return len(_get_ansatz(n_qubits).parameters) def get_var_form(params, n_qubits=2): """Get an hardware-efficient ansatz for n_qubits given parameters. """ # Define variational Form var_form = _get_ansatz(n_qubits) # Get Parameters from the variational form var_form_params = sorted(var_form.parameters, key=lambda p: p.name) # Check if the number of parameters is compatible assert len(var_form_params) == len(params), "The number of parameters don't match" # Create a dictionary with the parameters and values param_dict = dict(zip(var_form_params, params)) # Assing those values for the ansatz wave_function = var_form.assign_parameters(param_dict) return wave_function from qiskit import Aer, execute def _measure_zz_circuit(qc: qiskit.QuantumCircuit) -> qiskit.QuantumCircuit: """ Construct the circuit to measure """ zz_circuit = qc.copy() zz_circuit.measure_all() return zz_circuit def _clear_counts(count: dict) -> dict: if '00' not in count: count['00'] = 0 if '01' not in count: count['01'] = 0 if '10' not in count: count['10'] = 0 if '11' not in count: count['11'] = 0 return count def measure_zz(qc, backend, shots=10000): """ Measure the ZZ expectation value for a given circuit. """ zz_circuit = _measure_zz_circuit(qc) count = execute(zz_circuit, backend=backend, shots=shots).result().get_counts() count = _clear_counts(count) # Get total counts in order to obtain the probability total_counts = count['00'] + count['11'] + count['01'] + count['10'] # Get counts for expected value zz_meas = count['00'] + count['11'] - count['01'] - count['10'] return zz_meas / total_counts def measure_zi(qc, backend, shots=10000): """ Measure the ZI expectation value for a given circuit. """ zi_circuit = _measure_zz_circuit(qc) count = execute(zi_circuit, backend=backend, shots=shots).result().get_counts() count = _clear_counts(count) # Get total counts in order to obtain the probability total_counts = count['00'] + count['11'] + count['01'] + count['10'] # Get counts for expected value zi_meas = count['00'] - count['11'] + count['01'] - count['10'] return zi_meas / total_counts def measure_iz(qc, backend, shots=10000): """ Measure the IZ expectation value for a given circuit. """ iz_circuit = _measure_zz_circuit(qc) count = execute(iz_circuit, backend=backend, shots=shots).result().get_counts() count = _clear_counts(count) # Get total counts in order to obtain the probability total_counts = count['00'] + count['11'] + count['01'] + count['10'] # Get counts for expected value iz_meas = count['00'] - count['11'] - count['01'] + count['10'] return iz_meas / total_counts def _measure_xx_circuit(qc: qiskit.QuantumCircuit) -> qiskit.QuantumCircuit: """ Construct the circuit to measure """ xx_circuit = qc.copy() xx_circuit.h(xx_circuit.qregs[0]) xx_circuit.measure_all() return xx_circuit def measure_xx(qc, backend, shots=10000): """ Measure the XX expectation value for a given circuit. """ xx_circuit = _measure_xx_circuit(qc) count = execute(xx_circuit, backend=backend, shots=shots).result().get_counts() count = _clear_counts(count) # Get total counts in order to obtain the probability total_counts = count['00'] + count['11'] + count['01'] + count['10'] # Get counts for expected value xx_meas = count['00'] + count['11'] - count['01'] - count['10'] return xx_meas / total_counts def _measure_yy_circuit(qc: qiskit.QuantumCircuit) -> qiskit.QuantumCircuit: """ Construct the circuit to measure """ yy_meas = qc.copy() yy_meas.barrier(range(2)) yy_meas.sdg(range(2)) yy_meas.h(range(2)) yy_meas.measure_all() return yy_meas def measure_yy(qc, backend, shots=10000): """ Measure the YY expectation value for a given circuit. """ yy_circuit = _measure_yy_circuit(qc) count = execute(yy_circuit, backend=backend, shots=shots).result().get_counts() count = _clear_counts(count) # Get total counts in order to obtain the probability total_counts = count['00'] + count['11'] + count['01'] + count['10'] # Get counts for expected value xx_meas = count['00'] + count['11'] - count['01'] - count['10'] return xx_meas / total_counts import unittest class TestStringMethods(unittest.TestCase): def setUp(self): # Simulator self.backend = Aer.get_backend("qasm_simulator") # ZZ expectation value of 1 self.qcZ = qiskit.QuantumCircuit(2) # XX expectation value of 1 self.qcX = qiskit.QuantumCircuit(2) self.qcX.h(range(2)) # YY expectation value of 1 self.qcY = qiskit.QuantumCircuit(2) self.qcY.h(range(2)) self.qcY.s(range(2)) def test_ZZ(self): want = 1. got = measure_zz(self.qcZ, self.backend) decimalPlace = 2 message = "ZZ measurement not working for state Zero^Zero." self.assertAlmostEqual(want, got, decimalPlace, message) def test_XX(self): want = 1. got = measure_xx(self.qcX, self.backend) decimalPlace = 2 message = "XX measurement not working for state Plus^Plus." self.assertAlmostEqual(want, got, decimalPlace, message) def test_YY(self): want = 1. got = measure_yy(self.qcY, self.backend) decimalPlace = 2 message = "YY measurement not working for state iPlus^iPlus." self.assertAlmostEqual(want, got, decimalPlace, message) unittest.main(argv=[''], verbosity=2, exit=False); from Observables import * def get_hamiltonian(qc, backend, num_shots): # Hamiltonian BCS hamiltonian = .5*(measure_iz(qc, backend, num_shots) + measure_zi(qc, backend, num_shots) + 2*(measure_xx(qc, backend, num_shots) + measure_yy(qc, backend, num_shots))) # hamiltonian = 0.5*(measure_zi(qc, backend, num_shots) + measure_zz(qc, backend, num_shots)) return hamiltonian def objective_function(params): # Parameters backend = Aer.get_backend("qasm_simulator") NUM_SHOTS = 10000 n_qubits = 2 # Define Ansatz qc = get_var_form(params, n_qubits) # Hamiltonian hamiltonian = get_hamiltonian(qc, backend, NUM_SHOTS) # Get the cost function cost = hamiltonian return cost from qiskit.aqua.components.optimizers import COBYLA, NELDER_MEAD, SLSQP optimizer = COBYLA(maxiter=1000, disp=False, rhobeg=1.0, tol=None) # optimizer = NELDER_MEAD(maxiter=1000, maxfev=1000, disp=False, # xatol=0.0001, tol=None, adaptive=True) # optimizer = SLSQP(maxiter=100, disp=False, # ftol=1e-06, tol=None) # Create the initial parameters (noting that our single qubit variational form has 3 parameters) n_qubits = 2 n_parameters = get_num_parameters(n_qubits) params = np.random.rand(n_parameters) optimal_params, energy_gs, n_iters = optimizer.optimize(num_vars=n_parameters, objective_function=objective_function, initial_point=params) # Obtain the output distribution using the final parameters ground_state = get_var_form(optimal_params) print(f"Energy obtained: {energy_gs}") ground_state.draw('mpl') import qiskit from qiskit import QuantumCircuit def swap_test_circuit(qc1: qiskit.QuantumCircuit, qc2: qiskit.QuantumCircuit) -> qiskit.QuantumCircuit: """ Construct the SWAP test circuit given two circuits. Args: qc1(qiskit.QuantumCircuit): Quantum circuit for the first state. qc2(qiskit.QuantumCircuit): Quantum circuit for the second state. Output: (qiskit.QuantumCircuit): swap test circuit. """ # Helper variables n_total = qc1.num_qubits + qc2.num_qubits range_qc1 = [i + 1 for i in range(qc1.num_qubits)] range_qc2 = [i + qc1.num_qubits + 1 for i in range(qc2.num_qubits)] # Constructing the SWAP test circuit qc_swap = QuantumCircuit(n_total + 1, 1) qc_swap.append(qc1, range_qc1) qc_swap.append(qc2, range_qc2) # Swap Test qc_swap.h(0) for index, qubit in enumerate(range_qc1): qc_swap.cswap(0, qubit, range_qc2[index] ) qc_swap.h(0) # Measurement on the auxiliary qubit qc_swap.measure(0,0) return qc_swap def measure_swap_test(qc1: qiskit.QuantumCircuit, qc2: qiskit.QuantumCircuit, backend: qiskit.providers.aer.backends, num_shots: int=10000) -> float: """ Returns the fidelity from a SWAP test. """ swap_circuit = swap_test_circuit(qc1, qc2) count = execute(swap_circuit, backend=backend, shots=num_shots).result().get_counts() if '0' not in count: count['0'] = 0 if '1' not in count: count['1'] = 0 total_counts = count['0'] + count['1'] fid_meas = count['0'] p_0 = fid_meas / total_counts return 2*(p_0 - 1/2) import unittest from qiskit import QuantumCircuit, Aer class TestStringMethods(unittest.TestCase): def setUp(self): self.qc1 = QuantumCircuit(1) self.qc1.x(0) self.qc2 = QuantumCircuit(1) self.backend = Aer.get_backend("qasm_simulator") def test_01states(self): want = 0. got = measure_swap_test(self.qc1, self.qc2, self.backend) decimalPlace = 1 message = "Swap test not working for states 0 and 1." self.assertAlmostEqual(want, got, decimalPlace, message) def test_00states(self): want = 1. got = measure_swap_test(self.qc2, self.qc2, self.backend) decimalPlace = 2 message = "Swap test not working for states 0 and 0." self.assertAlmostEqual(want, got, decimalPlace, message) def test_11states(self): want = 1. got = measure_swap_test(self.qc1, self.qc1, self.backend) decimalPlace = 2 message = "Swap test not working for states 1 and 1." self.assertAlmostEqual(want, got, decimalPlace, message) unittest.main(argv=[''], verbosity=2, exit=False); import unittest unittest.assertAlmostEqual(0.5, measure_swap_test(qc1,qc2, backend)) qc1 = QuantumCircuit(1) qc1.x(0) qc2 = QuantumCircuit(1) measure_swap_test(qc1, qc2, backend) measure_swap_test(ground_state, ground_state, backend) import qiskit from qiskit import QuantumCircuit def dswap_test_circuit(qc1: qiskit.QuantumCircuit, qc2: qiskit.QuantumCircuit) -> qiskit.QuantumCircuit: """ Construct the destructive SWAP test circuit given two circuits. Args: qc1(qiskit.QuantumCircuit): Quantum circuit for the first state. qc2(qiskit.QuantumCircuit): Quantum circuit for the second state. Output: (qiskit.QuantumCircuit): destructive swap test circuit. """ # Helper variables n_total = qc1.num_qubits + qc2.num_qubits range_qc1 = [i for i in range(qc1.num_qubits)] range_qc2 = [i + qc1.num_qubits for i in range(qc2.num_qubits)] # Constructing the Destructive SWAP TEST qc_swap = QuantumCircuit(n_total) qc_swap.append(qc1, range_qc1) qc_swap.append(qc2, range_qc2) for index, qubit in enumerate(range_qc1): qc_swap.cx(qubit,range_qc2[index]) # Haddamard in the first state qc_swap.h(range_qc1) qc_swap.measure_all() return qc_swap qc = get_var_form([0]*n_parameters) dswap_circuit = dswap_test_circuit(qc, ground_state) backend = Aer.get_backend("qasm_simulator") NUM_SHOTS = 10000 count = execute(dswap_circuit, backend, shots=NUM_SHOTS).result().get_counts() print(count) from SWAPTest import measure_swap_test def objective_function_es(params): # Parameters backend = Aer.get_backend("qasm_simulator") NUM_SHOTS = 10000 BETA = 1. # Define Ansatz qc = get_var_form(params) # Hamiltonian hamiltonian = get_hamiltonian(qc, backend, NUM_SHOTS) # Swap Test fidelity = measure_swap_test(qc, ground_state, backend) # Get the cost function cost = hamiltonian + BETA*fidelity return cost # Create the initial parameters params = np.random.rand(n_parameters) optimal_params, energy_es, n_iters = optimizer.optimize(num_vars=n_parameters, objective_function=objective_function_es, initial_point=params) # Obtain the output state excited_state = get_var_form(optimal_params) print(f"Energy obtained: {energy_es}") excited_state.draw('mpl') backend = Aer.get_backend("qasm_simulator") print(f"Fidelity between the Ground state and the Excited state {measure_swap_test(excited_state, ground_state, backend)}") print("Energies") print(f"Ground State\nExpected: {eigenvalues[0]} | Got: {np.round(energy_gs,4)}") print(f"Ground State\nExpected: {eigenvalues[1]} | Got: {np.round(energy_es,4)}")
https://github.com/nahumsa/volta
nahumsa
import sys sys.path.append('../../') import numpy as np from qiskit import QuantumCircuit from qiskit.opflow import I, X, Y, Z import matplotlib.pyplot as plt from volta.observables import sample_hamiltonian from volta.hamiltonians import BCS_hamiltonian EPSILONS = [3, 3, 3, 3] V = -2 hamiltonian = 1 / 2 * (Z ^ I) + 1 / 2 * (Z ^ Z) #BCS_hamiltonian(EPSILONS, V) print(hamiltonian) eigenvalues, _ = np.linalg.eigh(hamiltonian.to_matrix()) print(f"Eigenvalues: {eigenvalues}") def create_circuit(n: int) -> list: return [QuantumCircuit(n) for _ in range(2)] n = hamiltonian.num_qubits init_states = create_circuit(n) def copy_unitary(list_states: list) -> list: out_states = [] for state in list_states: out_states.append(state.copy()) return out_states import textwrap def apply_initialization(list_states: list) -> None: for ind, state in enumerate(list_states): b = bin(ind)[2:] if len(b) != n: b = '0'*(n - len(b)) + b spl = textwrap.wrap(b, 1) for qubit, val in enumerate(spl): if val == '1': state.x(qubit) apply_initialization(init_states) initialization = copy_unitary(init_states) from qiskit.circuit.library import TwoLocal ansatz = TwoLocal(hamiltonian.num_qubits, ['ry','rz'], 'cx', reps=2) def apply_ansatz(ansatz: QuantumCircuit, list_states: list) -> None: for states in list_states: states.append(ansatz, range(n)) apply_ansatz(ansatz, init_states) init_states[-1].draw('mpl') def _apply_varform_params(ansatz, params: list): """Get an hardware-efficient ansatz for n_qubits given parameters. """ # Define variational Form var_form = ansatz # Get Parameters from the variational form var_form_params = sorted(var_form.parameters, key=lambda p: p.name) # Check if the number of parameters is compatible assert len(var_form_params) == len(params), "The number of parameters don't match" # Create a dictionary with the parameters and values param_dict = dict(zip(var_form_params, params)) # Assing those values for the ansatz wave_function = var_form.assign_parameters(param_dict) return wave_function from qiskit import BasicAer from qiskit.utils import QuantumInstance def cost_function(params:list) -> float: backend = BasicAer.get_backend('qasm_simulator') backend = QuantumInstance(backend, shots=10000) cost = 0 w = np.arange(len(init_states), 0, -1) for i, state in enumerate(init_states): qc = _apply_varform_params(state, params) # Hamiltonian hamiltonian_eval = sample_hamiltonian(hamiltonian=hamiltonian, ansatz=qc, backend=backend) cost += w[i] * hamiltonian_eval return cost from qiskit.aqua.components.optimizers import COBYLA optimizer = COBYLA() n_parameters = len(init_states[0].parameters) params = np.random.rand(n_parameters) optimal_params, mean_energy, n_iters = optimizer.optimize(num_vars=n_parameters, objective_function=cost_function, initial_point=params) mean_energy, sum(eigenvalues[:2]) # Optimized first ansatz ansatz_1 = _apply_varform_params(ansatz, optimal_params) ansatz_1.name = 'U(θ)' def cost_function_ind(ind: int, params:list) -> float: backend = BasicAer.get_backend('qasm_simulator') backend = QuantumInstance(backend, shots=10000) cost = 0 # Define Ansatz qc = _apply_varform_params(init_states[ind], params) # Hamiltonian hamiltonian_eval = sample_hamiltonian(hamiltonian=hamiltonian, ansatz=qc, backend=backend) cost += hamiltonian_eval return cost energies = [] for i in range(len(init_states)): energies.append(cost_function_ind(ind=i, params=optimal_params)) energies = np.array(energies) for i in range(len(init_states)): print(f"Value for the {i} state: {energies[i]}\t expected energy {eigenvalues[i]}")
https://github.com/nahumsa/volta
nahumsa
# This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. import unittest import qiskit from qiskit import BasicAer from qiskit.opflow import X, Y, Z from qiskit.utils import QuantumInstance from volta.observables import sample_hamiltonian class TestObservables(unittest.TestCase): def setUp(self): # Simulator self.backend = QuantumInstance( backend=BasicAer.get_backend("qasm_simulator"), shots=10000 ) # ZZ expectation value of 1 self.qcZ = qiskit.QuantumCircuit(2) # XX expectation value of 1 self.qcX = qiskit.QuantumCircuit(2) self.qcX.h(range(2)) # YY expectation value of 1 self.qcY = qiskit.QuantumCircuit(2) self.qcY.h(range(2)) self.qcY.s(range(2)) def test_ZZ(self): want = 1.0 # observables made by hand # got = measure_zz(self.qcZ, self.backend) hamiltonian = Z ^ Z got = sample_hamiltonian(hamiltonian, self.backend, self.qcZ) decimalPlace = 2 message = "ZZ measurement not working for state Zero^Zero." self.assertAlmostEqual(want, got, decimalPlace, message) def test_XX(self): want = 1.0 # observables made by hand # got = measure_xx(self.qcX, self.backend) hamiltonian = X ^ X got = sample_hamiltonian(hamiltonian, self.backend, self.qcX) decimalPlace = 2 message = "XX measurement not working for state Plus^Plus." self.assertAlmostEqual(want, got, decimalPlace, message) def test_YY(self): want = 1.0 # observables made by hand # got = measure_yy(self.qcY, self.backend) hamiltonian = Y ^ Y got = sample_hamiltonian(hamiltonian, self.backend, self.qcY) decimalPlace = 2 message = "YY measurement not working for state iPlus^iPlus." self.assertAlmostEqual(want, got, decimalPlace, message) if __name__ == "__main__": unittest.main(argv=[""], verbosity=2, exit=False)
https://github.com/nahumsa/volta
nahumsa
# This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. import unittest import qiskit from qiskit.circuit.library import TwoLocal from qiskit import QuantumCircuit, Aer from qiskit.utils import QuantumInstance from qiskit.opflow import Z, I from volta.ssvqe import SSVQE from volta.utils import classical_solver class TestSSVQD(unittest.TestCase): def setUp(self): optimizer = qiskit.algorithms.optimizers.COBYLA() backend = QuantumInstance( backend=Aer.get_backend("qasm_simulator"), shots=10000 ) hamiltonian = 1 / 2 * (Z ^ I) + 1 / 2 * (Z ^ Z) ansatz = TwoLocal(hamiltonian.num_qubits, ["ry", "rz"], "cx", reps=2) self.Algo = SSVQE( hamiltonian=hamiltonian, ansatz=ansatz, optimizer=optimizer, n_excited=2, backend=backend, ) self.energy = [] self.energy.append(self.Algo.run(index=0)[0]) self.energy.append(self.Algo.run(index=1)[0]) self.eigenvalues, _ = classical_solver(hamiltonian) def test_energies(self): want = self.eigenvalues[0] got = self.energy[0] decimalPlace = 1 message = "SSVQE not working for the ground state of 1/2*((Z^I) + (Z^Z))" self.assertAlmostEqual(want, got, decimalPlace, message) decimalPlace = 1 want = self.eigenvalues[1] got = self.energy[1] message = "SSVQE not working for the first excited state of 1/2*((Z^I) + (Z^Z))" self.assertAlmostEqual(want, got, decimalPlace, message) if __name__ == "__main__": unittest.main(argv=[""], verbosity=2, exit=False)
https://github.com/nahumsa/volta
nahumsa
# This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. import unittest from qiskit import QuantumCircuit, BasicAer from qiskit.utils import QuantumInstance from volta.swaptest import ( measure_swap_test, measure_dswap_test, measure_amplitude_transition_test, ) class TestSWAPTest(unittest.TestCase): def setUp(self): self.qc1 = QuantumCircuit(1) self.qc1.x(0) self.qc2 = QuantumCircuit(1) # self.backend = BasicAer.get_backend("qasm_simulator") self.backend = QuantumInstance( backend=BasicAer.get_backend("qasm_simulator"), shots=10000 ) def test_10states(self): want = 0.0 got = measure_swap_test(self.qc2, self.qc1, self.backend) decimalPlace = 1 message = "Swap test not working for states 0 and 1." self.assertAlmostEqual(want, got, decimalPlace, message) def test_01states(self): want = 0.0 got = measure_swap_test(self.qc1, self.qc2, self.backend) decimalPlace = 1 message = "Swap test not working for states 0 and 1." self.assertAlmostEqual(want, got, decimalPlace, message) def test_00states(self): want = 1.0 got = measure_swap_test(self.qc2, self.qc2, self.backend) decimalPlace = 2 message = "Swap test not working for states 0 and 0." self.assertAlmostEqual(want, got, decimalPlace, message) def test_11states(self): want = 1.0 got = measure_swap_test(self.qc1, self.qc1, self.backend) decimalPlace = 2 message = "Swap test not working for states 1 and 1." self.assertAlmostEqual(want, got, decimalPlace, message) class TestDestructiveSWAPTest(unittest.TestCase): def setUp(self): self.qc1 = QuantumCircuit(1) self.qc1.x(0) self.qc2 = QuantumCircuit(1) # self.backend = BasicAer.get_backend("qasm_simulator") self.backend = QuantumInstance( backend=BasicAer.get_backend("qasm_simulator"), shots=10000 ) def test_10states(self): want = 0.0 got = measure_dswap_test(self.qc2, self.qc1, self.backend) decimalPlace = 1 message = "Swap test not working for states 0 and 1." self.assertAlmostEqual(want, got, decimalPlace, message) def test_01states(self): want = 0.0 got = measure_dswap_test(self.qc1, self.qc2, self.backend) decimalPlace = 1 message = "Swap test not working for states 0 and 1." self.assertAlmostEqual(want, got, decimalPlace, message) def test_00states(self): want = 1.0 got = measure_dswap_test(self.qc2, self.qc2, self.backend) decimalPlace = 2 message = "Swap test not working for states 0 and 0." self.assertAlmostEqual(want, got, decimalPlace, message) def test_11states(self): want = 1.0 got = measure_dswap_test(self.qc1, self.qc1, self.backend) decimalPlace = 2 message = "Swap test not working for states 1 and 1." self.assertAlmostEqual(want, got, decimalPlace, message) class TestAmplitudeTransitionTest(unittest.TestCase): def setUp(self): self.qc1 = QuantumCircuit(1) self.qc1.x(0) self.qc2 = QuantumCircuit(1) self.backend = QuantumInstance( backend=BasicAer.get_backend("qasm_simulator"), shots=10000 ) def test_10states(self): want = 0.0 got = measure_amplitude_transition_test(self.qc2, self.qc1, self.backend) decimalPlace = 1 message = "Swap test not working for states 0 and 1." self.assertAlmostEqual(want, got, decimalPlace, message) def test_01states(self): want = 0.0 got = measure_amplitude_transition_test(self.qc1, self.qc2, self.backend) decimalPlace = 1 message = "Swap test not working for states 0 and 1." self.assertAlmostEqual(want, got, decimalPlace, message) def test_00states(self): want = 1.0 got = measure_amplitude_transition_test(self.qc2, self.qc2, self.backend) decimalPlace = 2 message = "Swap test not working for states 0 and 0." self.assertAlmostEqual(want, got, decimalPlace, message) def test_11states(self): want = 1.0 got = measure_amplitude_transition_test(self.qc1, self.qc1, self.backend) decimalPlace = 2 message = "Swap test not working for states 1 and 1." self.assertAlmostEqual(want, got, decimalPlace, message) if __name__ == "__main__": unittest.main(argv=[""], verbosity=2, exit=False)
https://github.com/nahumsa/volta
nahumsa
# This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. import unittest import qiskit from qiskit.circuit.library import TwoLocal from qiskit import BasicAer from qiskit.utils import QuantumInstance from qiskit.opflow import Z, I from volta.vqd import VQD from volta.utils import classical_solver class TestVQDSWAP(unittest.TestCase): def setUp(self): optimizer = qiskit.algorithms.optimizers.COBYLA() backend = QuantumInstance( backend=BasicAer.get_backend("qasm_simulator"), shots=50000, seed_simulator=42, seed_transpiler=42, ) hamiltonian = 1 / 2 * (Z ^ I) + 1 / 2 * (Z ^ Z) ansatz = TwoLocal(hamiltonian.num_qubits, ["ry", "rz"], "cx", reps=2) self.Algo = VQD( hamiltonian=hamiltonian, ansatz=ansatz, n_excited_states=1, beta=1.0, optimizer=optimizer, backend=backend, overlap_method="swap", ) self.Algo.run(verbose=0) self.eigenvalues, _ = classical_solver(hamiltonian) def test_energies_0(self): decimal_place = 1 want = self.eigenvalues[0] got = self.Algo.energies[0] message = ( "VQD with SWAP not working for the ground state of 1/2*((Z^I) + (Z^Z))" ) self.assertAlmostEqual(want, got, decimal_place, message) def test_energies_1(self): decimal_place = 1 want = self.eigenvalues[1] got = self.Algo.energies[1] message = "VQD with SWAP not working for the first excited state of 1/2*((Z^I) + (Z^Z))" self.assertAlmostEqual(want, got, decimal_place, message) class TestVQDDSWAP(unittest.TestCase): def setUp(self): optimizer = qiskit.algorithms.optimizers.COBYLA() # backend = BasicAer.get_backend("qasm_simulator") backend = QuantumInstance( backend=BasicAer.get_backend("qasm_simulator"), shots=50000, seed_simulator=42, seed_transpiler=42, ) hamiltonian = 1 / 2 * (Z ^ I) + 1 / 2 * (Z ^ Z) ansatz = TwoLocal(hamiltonian.num_qubits, ["ry", "rz"], "cx", reps=1) self.Algo = VQD( hamiltonian=hamiltonian, ansatz=ansatz, n_excited_states=1, beta=1.0, optimizer=optimizer, backend=backend, overlap_method="dswap", ) self.Algo.run(verbose=0) self.eigenvalues, _ = classical_solver(hamiltonian) def test_energies_0(self): decimal_place = 1 want = self.eigenvalues[0] got = self.Algo.energies[0] self.assertAlmostEqual( want, got, decimal_place, "VQD with DSWAP not working for the ground state of 1/2*((Z^I) + (Z^Z))", ) def test_energies_1(self): decimal_place = 1 want = self.eigenvalues[1] got = self.Algo.energies[1] self.assertAlmostEqual( want, got, decimal_place, "VQD with DSWAP not working for the first excited state of 1/2*((Z^I) + (Z^Z))", ) class TestVQDAmplitude(unittest.TestCase): def setUp(self): optimizer = qiskit.algorithms.optimizers.COBYLA() backend = QuantumInstance( backend=BasicAer.get_backend("qasm_simulator"), shots=50000, seed_simulator=42, seed_transpiler=42, ) hamiltonian = 1 / 2 * (Z ^ I) + 1 / 2 * (Z ^ Z) ansatz = TwoLocal(hamiltonian.num_qubits, ["ry", "rz"], "cx", reps=1) self.Algo = VQD( hamiltonian=hamiltonian, ansatz=ansatz, n_excited_states=1, beta=1.0, optimizer=optimizer, backend=backend, overlap_method="amplitude", ) self.Algo.run(verbose=0) self.eigenvalues, _ = classical_solver(hamiltonian) def test_energies_0(self): decimal_place = 1 want = self.eigenvalues[0] got = self.Algo.energies[0] self.assertAlmostEqual( want, got, decimal_place, "VQD with Excitation Amplitude not working for the ground state of 1/2*((Z^I) + (Z^Z))", ) def test_energies_1(self): decimal_place = 1 want = self.eigenvalues[1] got = self.Algo.energies[1] self.assertAlmostEqual( want, got, decimal_place, "VQD with Excitation Amplitude not working for the first excited state of 1/2*((Z^I) + (Z^Z))", ) class VQDRaiseError(unittest.TestCase): def test_not_implemented_overlapping_method(self): optimizer = qiskit.algorithms.optimizers.COBYLA() backend = QuantumInstance( backend=BasicAer.get_backend("qasm_simulator"), shots=50000 ) hamiltonian = 1 / 2 * (Z ^ I) + 1 / 2 * (Z ^ Z) ansatz = TwoLocal(hamiltonian.num_qubits, ["ry", "rz"], "cx", reps=2) with self.assertRaises(NotImplementedError): VQD( hamiltonian=hamiltonian, ansatz=ansatz, n_excited_states=1, beta=1.0, optimizer=optimizer, backend=backend, overlap_method="test", ), if __name__ == "__main__": unittest.main(argv=[""], verbosity=2, exit=False)
https://github.com/nahumsa/volta
nahumsa
# This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. from qiskit.circuit.library import TwoLocal from qiskit import QuantumCircuit import numpy as np def _get_ansatz(n_qubits: int, reps: int = 1) -> QuantumCircuit: """Create a TwoLocal ansatz for `n_qubits`. Args: n_qubits (int, optional): number of qubits for the ansatz Returns: QuantumCircuit: TwoLocal circuit. defaults to 1. """ return TwoLocal(n_qubits, ["ry", "rz"], "cx", reps=reps) def get_num_parameters(n_qubits: int) -> int: """Get the number of parameters for a TwoLocal Ansatz. Args: n_qubits (int): number of qubits Returns: int: number of parameters """ return len(_get_ansatz(n_qubits).parameters) def get_var_form(params: np.array, n_qubits: int = 2, reps: int = 1) -> QuantumCircuit: """Get an hardware-efficient ansatz for n_qubits given parameters. Args: params (np.array): parameters to be applied on the circuit. n_qubits (int, optional): number of qubits. Defaults to 2. reps (int, optional): repetition for the ansatz. Defaults to 1. Returns: QuantumCircuit: Circuit with parameters applied """ # Define variational Form var_form = _get_ansatz(n_qubits, reps) # Get Parameters from the variational form var_form_params = sorted(var_form.parameters, key=lambda p: p.name) # Check if the number of parameters is compatible assert len(var_form_params) == len(params), "The number of parameters don't match" # Create a dictionary with the parameters and values param_dict = dict(zip(var_form_params, params)) # Assing those values for the ansatz wave_function = var_form.assign_parameters(param_dict) return wave_function
https://github.com/nahumsa/volta
nahumsa
# This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. import qiskit from qiskit import execute # Observables made by hand, those observables are changed # for the more general function sample_hamiltonian def _measure_zz_circuit(qc: qiskit.QuantumCircuit) -> qiskit.QuantumCircuit: """Construct the circuit to measure""" zz_circuit = qc.copy() zz_circuit.measure_all() return zz_circuit def _clear_counts(count: dict) -> dict: if "00" not in count: count["00"] = 0 if "01" not in count: count["01"] = 0 if "10" not in count: count["10"] = 0 if "11" not in count: count["11"] = 0 return count def measure_zz(qc, backend, shots=10000): """Measure the ZZ expectation value for a given circuit.""" zz_circuit = _measure_zz_circuit(qc) count = execute(zz_circuit, backend=backend, shots=shots).result().get_counts() count = _clear_counts(count) # Get total counts in order to obtain the probability total_counts = count["00"] + count["11"] + count["01"] + count["10"] # Get counts for expected value zz_meas = count["00"] + count["11"] - count["01"] - count["10"] return zz_meas / total_counts def measure_zi(qc, backend, shots=10000): """Measure the ZI expectation value for a given circuit.""" zi_circuit = _measure_zz_circuit(qc) count = execute(zi_circuit, backend=backend, shots=shots).result().get_counts() count = _clear_counts(count) # Get total counts in order to obtain the probability total_counts = count["00"] + count["11"] + count["01"] + count["10"] # Get counts for expected value zi_meas = count["00"] - count["11"] + count["01"] - count["10"] return zi_meas / total_counts def measure_iz(qc, backend, shots=10000): """Measure the IZ expectation value for a given circuit.""" iz_circuit = _measure_zz_circuit(qc) count = execute(iz_circuit, backend=backend, shots=shots).result().get_counts() count = _clear_counts(count) # Get total counts in order to obtain the probability total_counts = count["00"] + count["11"] + count["01"] + count["10"] # Get counts for expected value iz_meas = count["00"] - count["11"] - count["01"] + count["10"] return iz_meas / total_counts def measure_xx(qc, backend, shots=10000): """Measure the XX expectation value for a given circuit.""" def _measure_xx_circuit( qc: qiskit.QuantumCircuit, ) -> qiskit.QuantumCircuit: """Construct the circuit to measure""" xx_circuit = qc.copy() xx_circuit.h(xx_circuit.qregs[0]) xx_circuit.measure_all() return xx_circuit xx_circuit = _measure_xx_circuit(qc) count = execute(xx_circuit, backend=backend, shots=shots).result().get_counts() count = _clear_counts(count) # Get total counts in order to obtain the probability total_counts = count["00"] + count["11"] + count["01"] + count["10"] # Get counts for expected value xx_meas = count["00"] + count["11"] - count["01"] - count["10"] return xx_meas / total_counts def measure_yy(qc, backend, shots=10000): """Measure the YY expectation value for a given circuit.""" def _measure_yy_circuit( qc: qiskit.QuantumCircuit, ) -> qiskit.QuantumCircuit: """Construct the circuit to measure""" yy_meas = qc.copy() yy_meas.barrier(range(2)) yy_meas.sdg(range(2)) yy_meas.h(range(2)) yy_meas.measure_all() return yy_meas yy_circuit = _measure_yy_circuit(qc) count = execute(yy_circuit, backend=backend, shots=shots).result().get_counts() count = _clear_counts(count) # Get total counts in order to obtain the probability total_counts = count["00"] + count["11"] + count["01"] + count["10"] # Get counts for expected value xx_meas = count["00"] + count["11"] - count["01"] - count["10"] return xx_meas / total_counts
https://github.com/nahumsa/volta
nahumsa
# This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. from typing import Union import qiskit import numpy as np from qiskit.utils.backend_utils import is_aer_provider from qiskit.opflow import ( CircuitSampler, ExpectationFactory, CircuitStateFn, StateFn, ) def sample_hamiltonian( hamiltonian: qiskit.opflow.OperatorBase, backend: Union[qiskit.providers.BaseBackend, qiskit.utils.QuantumInstance], ansatz: qiskit.QuantumCircuit, ) -> float: """Samples a hamiltonian given an ansatz, which is a Quantum circuit and outputs the expected value given the hamiltonian. Args: hamiltonian (qiskit.opflow.OperatorBase): Hamiltonian that you want to get the expected value. backend (Union[qiskit.providers.BaseBackend, qiskit.utils.QuantumInstance]): Backend that you want to run. ansatz (qiskit.QuantumCircuit): Quantum circuit that you want to get the expectation value. Returns: float: Expected value """ if qiskit.utils.quantum_instance.QuantumInstance == type(backend): sampler = CircuitSampler(backend, param_qobj=is_aer_provider(backend.backend)) else: sampler = CircuitSampler(backend) expectation = ExpectationFactory.build(operator=hamiltonian, backend=backend) observable_meas = expectation.convert(StateFn(hamiltonian, is_measurement=True)) ansatz_circuit_op = CircuitStateFn(ansatz) expect_op = observable_meas.compose(ansatz_circuit_op).reduce() sampled_expect_op = sampler.convert(expect_op) return np.real(sampled_expect_op.eval())
https://github.com/nahumsa/volta
nahumsa
# This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. import numpy as np import textwrap from typing import Union from functools import partial from qiskit import QuantumCircuit from qiskit.opflow import OperatorBase, ListOp, PrimitiveOp, PauliOp from qiskit.opflow import I, Z from qiskit.circuit.library import TwoLocal from qiskit.algorithms.optimizers import Optimizer from qiskit.utils import QuantumInstance from qiskit.providers import BaseBackend from volta.observables import sample_hamiltonian class SSVQE(object): """Subspace-search variational quantum eigensolver for excited states algorithm class. Based on https://arxiv.org/abs/1810.09434 """ def __init__( self, hamiltonian: Union[OperatorBase, ListOp, PrimitiveOp, PauliOp], ansatz: QuantumCircuit, backend: Union[BaseBackend, QuantumInstance], optimizer: Optimizer, n_excited: int, debug: bool = False, ) -> None: """Initialize the class. Args: hamiltonian (Union[OperatorBase, ListOp, PrimitiveOp, PauliOp]): Hamiltonian constructed using qiskit's aqua operators. ansatz (QuantumCircuit): Anstaz that you want to run VQD. optimizer (qiskit.aqua.components.optimizers.Optimizer): Classical Optimizers from aqua components. backend (Union[BaseBackend, QuantumInstance]): Backend for running the algorithm. """ # Input parameters self.hamiltonian = hamiltonian self.n_qubits = hamiltonian.num_qubits self.optimizer = optimizer self.backend = backend # Helper Parameters self.ansatz = ansatz self.n_parameters = self._get_num_parameters self._debug = debug self._ansatz_1_params = None self._first_optimization = False self._n_excited = n_excited # Running inate functions self._inate_optimizer_run() def _create_blank_circuit(self) -> list: return [QuantumCircuit(self.n_qubits) for _ in range(self._n_excited)] def _copy_unitary(self, list_states: list) -> list: out_states = [] for state in list_states: out_states.append(state.copy()) return out_states def _apply_initialization(self, list_states: list) -> None: for ind, state in enumerate(list_states): b = bin(ind)[2:] if len(b) != self.n_qubits: b = "0" * (self.n_qubits - len(b)) + b spl = textwrap.wrap(b, 1) for qubit, val in enumerate(spl): if val == "1": state.x(qubit) @property def _get_num_parameters(self) -> int: """Get the number of parameters in a given ansatz. Returns: int: Number of parameters of the given ansatz. """ return len(self.ansatz.parameters) def _apply_varform_params(self, ansatz, params: list): """Get an hardware-efficient ansatz for n_qubits given parameters. """ # Define variational Form var_form = ansatz # Get Parameters from the variational form var_form_params = sorted(var_form.parameters, key=lambda p: p.name) # Check if the number of parameters is compatible assert len(var_form_params) == len( params ), "The number of parameters don't match" # Create a dictionary with the parameters and values param_dict = dict(zip(var_form_params, params)) # Assing those values for the ansatz wave_function = var_form.assign_parameters(param_dict) return wave_function def _apply_ansatz(self, list_states: list, name: str = None) -> None: for states in list_states: if name: self.ansatz.name = name states.append(self.ansatz, range(self.n_qubits)) def _construct_states(self): circuit = self._create_blank_circuit() self._apply_initialization(circuit) self._apply_ansatz(circuit) return circuit def _cost_function_1(self, params: list) -> float: """Evaluate the first cost function of SSVQE. Args: params (list): Parameter values for the ansatz. Returns: float: Cost function value. """ # Construct states states = self._construct_states() cost = 0 w = np.arange(len(states), 0, -1) for i, state in enumerate(states): qc = self._apply_varform_params(state, params) # Hamiltonian hamiltonian_eval = sample_hamiltonian( hamiltonian=self.hamiltonian, ansatz=qc, backend=self.backend ) cost += w[i] * hamiltonian_eval return cost def _inate_optimizer_run(self): # Random initialization params = np.random.rand(self.n_parameters) optimal_params, energy, n_iters = self.optimizer.optimize( num_vars=self.n_parameters, objective_function=self._cost_function_1, initial_point=params, ) self._ansatz_1_params = optimal_params self._first_optimization = True def _cost_excited_state(self, ind: int, params: list): cost = 0 # Construct states states = self._construct_states() # Define Ansatz qc = self._apply_varform_params(states[ind], params) # Hamiltonian hamiltonian_eval = sample_hamiltonian( hamiltonian=self.hamiltonian, ansatz=qc, backend=self.backend ) cost += hamiltonian_eval return cost, qc def run(self, index: int) -> (float, QuantumCircuit): """Run SSVQE for a given index. Args: index(int): Index of the given excited state. Returns: Energy: Energy of such excited state. State: State for such energy. """ energy, state = self._cost_excited_state(index, self._ansatz_1_params) return energy, state if __name__ == "__main__": import qiskit from qiskit import BasicAer optimizer = qiskit.algorithms.optimizers.COBYLA(maxiter=100) backend = QuantumInstance( backend=BasicAer.get_backend("qasm_simulator"), shots=10000 ) hamiltonian = 1 / 2 * (Z ^ I) + 1 / 2 * (Z ^ Z) ansatz = TwoLocal(hamiltonian.num_qubits, ["ry", "rz"], "cx", reps=1) algo = SSVQE(hamiltonian, ansatz, backend, optimizer) energy, state = algo.run(1) print(energy) print(state)
https://github.com/nahumsa/volta
nahumsa
# This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. import qiskit from qiskit import QuantumCircuit, execute from qiskit.utils import QuantumInstance from qiskit.providers import BaseBackend from typing import Union import textwrap def swap_test_circuit(qc1: QuantumCircuit, qc2: QuantumCircuit) -> QuantumCircuit: """Construct the SWAP test circuit given two circuits. Args: qc1(qiskit.QuantumCircuit): Quantum circuit for the first state. qc2(qiskit.QuantumCircuit): Quantum circuit for the second state. Output: (qiskit.QuantumCircuit): swap test circuit. """ # Helper variables n_total = qc1.num_qubits + qc2.num_qubits range_qc1 = [i + 1 for i in range(qc1.num_qubits)] range_qc2 = [i + qc1.num_qubits + 1 for i in range(qc2.num_qubits)] # Constructing the SWAP test circuit qc_swap = QuantumCircuit(n_total + 1, 1) qc_swap.append(qc1, range_qc1) qc_swap.append(qc2, range_qc2) # Swap Test qc_swap.h(0) for index, qubit in enumerate(range_qc1): qc_swap.cswap(0, qubit, range_qc2[index]) qc_swap.h(0) # Measurement on the auxiliary qubit qc_swap.measure(0, 0) return qc_swap def measure_swap_test( qc1: QuantumCircuit, qc2: QuantumCircuit, backend: Union[BaseBackend, QuantumInstance], num_shots: int = 10000, ) -> float: """Returns the fidelity from a SWAP test. Args: qc1 (QuantumCircuit): Quantum Circuit for the first state. qc2 (QuantumCircuit): Quantum Circuit for the second state. backend (Union[BaseBackend,QuantumInstance]): Backend. num_shots (int, optional): Number of shots. Defaults to 10000. Returns: float: result of the overlap betweeen the first and second state. """ swap_circuit = swap_test_circuit(qc1, qc2) # Check if the backend is a quantum instance. if qiskit.utils.quantum_instance.QuantumInstance == type(backend): count = backend.execute(swap_circuit).get_counts() else: count = ( execute(swap_circuit, backend=backend, shots=num_shots) .result() .get_counts() ) if "0" not in count: count["0"] = 0 if "1" not in count: count["1"] = 0 total_counts = count["0"] + count["1"] fid_meas = count["0"] p_0 = fid_meas / total_counts return 2 * (p_0 - 1 / 2) def dswap_test_circuit(qc1: QuantumCircuit, qc2: QuantumCircuit) -> QuantumCircuit: """Construct the destructive SWAP test circuit given two circuits. Args: qc1(qiskit.QuantumCircuit): Quantum circuit for the first state. qc2(qiskit.QuantumCircuit): Quantum circuit for the second state. Output: (qiskit.QuantumCircuit): swap test circuit. """ # Helper variables n_total = qc1.num_qubits + qc2.num_qubits range_qc1 = [i for i in range(qc1.num_qubits)] range_qc2 = [i + qc1.num_qubits for i in range(qc2.num_qubits)] # Constructing the SWAP test circuit qc_swap = QuantumCircuit(n_total, n_total) qc_swap.append(qc1, range_qc1) qc_swap.append(qc2, range_qc2) for index, qubit in enumerate(range_qc1): qc_swap.cx(qubit, range_qc2[index]) qc_swap.h(qubit) for index, qubit in enumerate(range_qc1): qc_swap.measure(qubit, 2 * index) for index, qubit in enumerate(range_qc2): qc_swap.measure(range_qc2[index], 2 * index + 1) return qc_swap def measure_dswap_test( qc1: QuantumCircuit, qc2: QuantumCircuit, backend: Union[BaseBackend, QuantumInstance], num_shots: int = 10000, ) -> float: """Returns the fidelity from a destructive SWAP test. Args: qc1 (QuantumCircuit): Quantum Circuit for the first state. qc2 (QuantumCircuit): Quantum Circuit for the second state. backend (Union[BaseBackend,QuantumInstance]): Backend. num_shots (int, optional): Number of shots. Defaults to 10000. Returns: float: result of the overlap betweeen the first and second state. """ n = qc1.num_qubits swap_circuit = dswap_test_circuit(qc1, qc2) # Check if the backend is a quantum instance. if qiskit.utils.quantum_instance.QuantumInstance == type(backend): count = backend.execute(swap_circuit).get_counts() else: count = ( execute(swap_circuit, backend=backend, shots=num_shots) .result() .get_counts() ) result = 0 for meas, counts in count.items(): split_meas = textwrap.wrap(meas, 2) for m in split_meas: if m == "11": result -= counts else: result += counts total = sum(count.values()) return result / (n * total) def amplitude_transition_test_circuit( qc1: QuantumCircuit, qc2: QuantumCircuit ) -> QuantumCircuit: """Construct the SWAP test circuit given two circuits using amplitude transition. Args: qc1(qiskit.QuantumCircuit): Quantum circuit for the first state. qc2(qiskit.QuantumCircuit): Quantum circuit for the second state. Output: (qiskit.QuantumCircuit): swap test circuit. """ # Constructing the SWAP test circuit n_qubits = qc1.num_qubits qc_swap = QuantumCircuit(n_qubits) qc_swap.append(qc1, range(n_qubits)) qc_swap.append(qc2.inverse(), range(n_qubits)) # Measurement on the auxiliary qubit qc_swap.measure_all() return qc_swap def measure_amplitude_transition_test( qc1: QuantumCircuit, qc2: QuantumCircuit, backend, num_shots: int = 10000, ) -> float: """Returns the fidelity from a SWAP test using amplitude transition. Args: qc1 (QuantumCircuit): Quantum Circuit for the first state. qc2 (QuantumCircuit): Quantum Circuit for the second state. backend (Union[BaseBackend,QuantumInstance]): Backend. num_shots (int, optional): Number of shots. Defaults to 10000. Returns: float: result of the overlap betweeen the first and second state. """ swap_circuit = amplitude_transition_test_circuit(qc1, qc2) # Check if the backend is a quantum instance. if qiskit.utils.quantum_instance.QuantumInstance == type(backend): count = backend.execute(swap_circuit).get_counts() else: count = ( execute(swap_circuit, backend=backend, shots=num_shots) .result() .get_counts() ) if "0" * qc1.num_qubits not in count: count["0" * qc1.num_qubits] = 0 total_counts = sum(count.values()) fid_meas = count["0" * qc1.num_qubits] p_0 = fid_meas / total_counts return p_0
https://github.com/nahumsa/volta
nahumsa
# This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. import numpy as np from typing import Union from qiskit import QuantumCircuit from qiskit.opflow import OperatorBase, ListOp, PrimitiveOp, PauliOp from qiskit.algorithms.optimizers import Optimizer from qiskit.aqua import QuantumInstance from qiskit.providers import BaseBackend from volta.observables import sample_hamiltonian from volta.swaptest import ( measure_swap_test, measure_dswap_test, measure_amplitude_transition_test, ) class VQD(object): """Variational Quantum Deflation algorithm class. Based on https://arxiv.org/abs/1805.08138 """ def __init__( self, hamiltonian: Union[OperatorBase, ListOp, PrimitiveOp, PauliOp], ansatz: QuantumCircuit, n_excited_states: int, beta: float, optimizer: Optimizer, backend: Union[BaseBackend, QuantumInstance], overlap_method: str = "swap", num_shots: int = 10000, debug: bool = False, ) -> None: """Initialize the class. Args: hamiltonian (Union[OperatorBase, ListOp, PrimitiveOp, PauliOp]): Hamiltonian constructed using qiskit's aqua operators. ansatz (QuantumCircuit): Anstaz that you want to run VQD. n_excited_states (int): Number of excited states that you want to find the energy if you use 0, then it is the same as using a VQE. beta (float): Strenght parameter for the swap test. optimizer (qiskit.algorithms.optimizers.Optimizer): Classical Optimizers from Terra. backend (Union[BaseBackend, QuantumInstance]): Backend for running the algorithm. overlap_method (str): State overlap method. Methods available: swap, dswap, amplitude (Default: swap) num_shots (int): Number of shots. (Default: 10000) """ # Input parameters self.hamiltonian = hamiltonian self.n_qubits = hamiltonian.num_qubits self.optimizer = optimizer self.backend = backend self.NUM_SHOTS = num_shots self.BETA = beta self.overlap_method = overlap_method IMPLEMENTED_OVERLAP_METHODS = ["swap", "dswap", "amplitude"] if self.overlap_method not in IMPLEMENTED_OVERLAP_METHODS: raise NotImplementedError( f"overlapping method not implemented. Available implementing methods: {IMPLEMENTED_OVERLAP_METHODS}" ) # Helper Parameters self.n_excited_states = n_excited_states + 1 self.ansatz = ansatz self.n_parameters = self._get_num_parameters self._debug = debug # Logs self._states = [] self._energies = [] @property def energies(self) -> list: """Returns a list with energies. Returns: list: list with energies """ return self._energies @property def states(self) -> list: """Returns a list with states associated with each energy. Returns: list: list with states. """ return self._states @property def _get_num_parameters(self) -> int: """Get the number of parameters in a given ansatz. Returns: int: Number of parameters of the given ansatz. """ return len(self.ansatz.parameters) def _apply_varform_params(self, params: list): """Get an hardware-efficient ansatz for n_qubits given parameters. """ # Define variational Form var_form = self.ansatz # Get Parameters from the variational form var_form_params = sorted(var_form.parameters, key=lambda p: p.name) # Check if the number of parameters is compatible assert len(var_form_params) == len( params ), "The number of parameters don't match" # Create a dictionary with the parameters and values param_dict = dict(zip(var_form_params, params)) # Assing those values for the ansatz wave_function = var_form.assign_parameters(param_dict) return wave_function def cost_function(self, params: list) -> float: """Evaluate the cost function of VQD. Args: params (list): Parameter values for the ansatz. Returns: float: Cost function value. """ # Define Ansatz qc = self._apply_varform_params(params) # Hamiltonian hamiltonian_eval = sample_hamiltonian( hamiltonian=self.hamiltonian, ansatz=qc, backend=self.backend ) # Fidelity fidelity = 0.0 if len(self.states) != 0: for state in self.states: if self.overlap_method == "dswap": swap = measure_dswap_test(qc, state, self.backend, self.NUM_SHOTS) elif self.overlap_method == "swap": swap = measure_swap_test(qc, state, self.backend, self.NUM_SHOTS) elif self.overlap_method == "amplitude": swap = measure_amplitude_transition_test( qc, state, self.backend, self.NUM_SHOTS ) fidelity += swap if self._debug: print(fidelity) # Get the cost function cost = hamiltonian_eval + self.BETA * fidelity return cost def optimizer_run(self): # Random initialization params = np.random.rand(self.n_parameters) optimal_params, energy, n_iters = self.optimizer.optimize( num_vars=self.n_parameters, objective_function=self.cost_function, initial_point=params, ) # Logging the energies and states # TODO: Change to an ordered list. self._energies.append(energy) self._states.append(self._apply_varform_params(optimal_params)) def _reset(self): """Resets the energies and states helper variables.""" self._energies = [] self._states = [] def run(self, verbose: int = 1): self._reset() for i in range(self.n_excited_states): if verbose == 1: print(f"Calculating excited state {i}") self.optimizer_run()
https://github.com/brhn-4/CMSC457
brhn-4
from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit, execute from qiskit import Aer import numpy as np import sys N=int(sys.argv[1]) filename = sys.argv[2] backend = Aer.get_backend('unitary_simulator') def GHZ(n): if n<=0: return None circ = QuantumCircuit(n) # Put your code below # ---------------------------- circ.h(0) for x in range(1,n): circ.cx(x-1,x) # ---------------------------- return circ circuit = GHZ(N) job = execute(circuit, backend, shots=8192) result = job.result() array = result.get_unitary(circuit,3) np.savetxt(filename, array, delimiter=",", fmt = "%0.3f")
https://github.com/brhn-4/CMSC457
brhn-4
# Do the necessary imports import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import Aer from qiskit.extensions import Initialize from qiskit.quantum_info import random_statevector, Statevector,partial_trace def trace01(out_vector): return Statevector([sum([out_vector[i] for i in range(0,4)]), sum([out_vector[i] for i in range(4,8)])]) def teleportation(): # Create random 1-qubit state psi = random_statevector(2) print(psi) init_gate = Initialize(psi) init_gate.label = "init" ## SETUP qr = QuantumRegister(3, name="q") # Protocol uses 3 qubits crz = ClassicalRegister(1, name="crz") # and 2 classical registers crx = ClassicalRegister(1, name="crx") qc = QuantumCircuit(qr, crz, crx) # Don't modify the code above ## Put your code below # ---------------------------- qc.initialize(psi, qr[0]) qc.h(qr[1]) qc.cx(qr[1],qr[2]) qc.cx(qr[0],qr[1]) qc.h(qr[0]) qc.measure(qr[0],crz[0]) qc.measure(qr[1],crx[0]) qc.x(qr[2]).c_if(crx[0], 1) qc.z(qr[2]).c_if(crz[0], 1) # ---------------------------- # Don't modify the code below sim = Aer.get_backend('aer_simulator') qc.save_statevector() out_vector = sim.run(qc).result().get_statevector() result = trace01(out_vector) return psi, result # (psi,res) = teleportation() # print(psi) # print(res) # if psi == res: # print('1') # else: # print('0')
https://github.com/brhn-4/CMSC457
brhn-4
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit.transpiler import PassManager from qiskit.transpiler.passes import Unroller def diffusion(qc,flip): qc.h(flip) qc.x(flip) qc.h(flip[8]) qc.mct(flip[0:8], flip[8]) qc.h(flip[8]) qc.x(flip) qc.h(flip) def oracle(qc,flip,tile,oracle): flip_tile(qc,flip,tile) qc.x(tile[0:9]) qc.mct(tile[0:9],oracle[0]) qc.x(tile[0:9]) flip_tile(qc,flip,tile) # Subroutine for oracle # Calculate what the light state in `tile` will be after pressing each solution candidate in `flip`. def flip_tile(qc,flip,tile): #For tile 0,0 qc.cx(flip[0], tile[0]) qc.cx(flip[0], tile[1]) qc.cx(flip[0], tile[3]) #For tile 0,1 qc.cx(flip[1], tile[0]) qc.cx(flip[1], tile[1]) qc.cx(flip[1], tile[2]) qc.cx(flip[1], tile[4]) #For tile 0,2 qc.cx(flip[2], tile[1]) qc.cx(flip[2], tile[2]) qc.cx(flip[2], tile[5]) #For tile 1,0 qc.cx(flip[3], tile[0]) qc.cx(flip[3], tile[3]) qc.cx(flip[3], tile[4]) qc.cx(flip[3], tile[6]) #For tile 1,1 qc.cx(flip[4], tile[1]) qc.cx(flip[4], tile[3]) qc.cx(flip[4], tile[4]) qc.cx(flip[4], tile[5]) qc.cx(flip[4], tile[7]) #For tile 1,2 qc.cx(flip[5], tile[2]) qc.cx(flip[5], tile[4]) qc.cx(flip[5], tile[5]) qc.cx(flip[5], tile[8]) #For tile 2,0 qc.cx(flip[6], tile[3]) qc.cx(flip[6], tile[6]) qc.cx(flip[6], tile[7]) #For tile 2,1 qc.cx(flip[7], tile[4]) qc.cx(flip[7], tile[6]) qc.cx(flip[7], tile[7]) qc.cx(flip[7], tile[8]) #For tile 2,2 qc.cx(flip[8], tile[5]) qc.cx(flip[8], tile[7]) qc.cx(flip[8], tile[8]) def light_out_grover(lights, N): tile = QuantumRegister(9) flip = QuantumRegister(9) oracle_output = QuantumRegister(1) result = ClassicalRegister(9) qc = QuantumCircuit(tile, flip, oracle_output, result) # ----------------------------------------------------- # Do not modify the code of this function above # Initialization counter = 0 for i in lights: if i==1: qc.x(tile[counter]) counter+=1 else: counter+=1 qc.h(flip[0:9]) qc.x(oracle_output[0]) qc.h(oracle_output[0]) # Grover Iteration for i in range(N): # Apply the oracle oracle(qc,flip,tile,oracle_output) # diffusion diffusion(qc,flip) pass # Remember to do some uncomputation qc.h(oracle_output[0]) qc.x(oracle_output[0]) # Do not modify the code below # ------------------------------------------------------ # Measuremnt qc.measure(flip,result) # Make the Out put order the same as the input. qc = qc.reverse_bits() from qiskit import execute, Aer backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend=backend, shots=50, seed_simulator=12345) result = job.result() count = result.get_counts() score_sorted = sorted(count.items(), key=lambda x:x[1], reverse=True) final_score = score_sorted[0:40] solution = final_score[0][0] return solution # For local test, your program should print 110010101 110010101 lights = [0, 1, 1, 1, 0, 0, 1, 1, 1] print(light_out_grover(lights,17))
https://github.com/brhn-4/CMSC457
brhn-4
from qutip import * # 5-qubit system N = 5 identity = qeye(2) X = sigmax() Y = sigmay() Z = sigmaz() def pauli_i(N, i, pauli): # pauli: X Y Z tmp = [identity for m in range(N)] tmp[i]=pauli return tensor(tmp) n=3 paulix_n = pauli_i(N, n, X) H0 = 0 for n in range(N): H0 += pauli_i(N, n, X) H0 = -0.5*H0 H1 = 0 for n in range(N-1): H1 += 0.1 * pauli_i(N, n, Z) * pauli_i(N, n+1, Y) import numpy as np def H1_coeff(t, args): return 9 * np.exp(-(t / 5.) ** 2) H = [H0, [H1, H1_coeff]] t = [0.5, 0.6] psi0 = tensor([basis(2, 1)] + [basis(2,0) for i in range(N-1)]) # Define initial state output = mesolve(H, psi0, t) print(output)
https://github.com/bertolinocastro/quantum-computing-algorithms
bertolinocastro
# A Quantum Circuit to Construct All Maximal Cliques Using Grover’s Search Algorithm ## Chu Ryang Wie ### DOI: https://arxiv.org/abs/1711.06146v2 from sympy import * #import sympy.physics.quantum as qp # quantum physics from sympy.physics.quantum.qubit import * from sympy.physics.quantum import Dagger, TensorProduct from sympy.physics.quantum.gate import * from sympy.physics.quantum.qapply import * N = Symbol('N', integer=True) #N = 8 # base network G: # 1 <-> 2 <-> 3 # Nodes: 1, 2, 3 # Edges: (1,2), (2,3) # Adjacency matrix for network G A = Matrix([ [0, 1, 0], [1, 0, 1], [0, 1, 0] ]) # creating qubits for n=3 basis q = [Qubit(f'{dummy:03b}') for dummy in range(2**3)] q # creating psi state vector kpsi = 1/sqrt(N)*sum(q) bpsi = 1/sqrt(N)*Dagger(sum(q)) # TODO: create in terms of matrices the O operator perfectly as the circuit described in the paper O = Matrix([ [1, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0,-1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0,-1, 0], [0, 0, 0, 0, 0, 0, 0, 1], ]) # step: constructing the U operator basics using a network with n=3 # function to represent qubit as matrix: qubit_to_matrix() U = 2*kpsi*bpsi U = qubit_to_matrix(U)-Matrix.eye(2**3) Hm = Matrix([[1,1],[1,-1]]) Hc = 1/sqrt(2) H3 = Hc**3*kronecker_product(Hm,Hm,Hm) q000 = qubit_to_matrix(q[0]) Ualt = H3*(2*q000*Dagger(q000)-Matrix.eye(8))*H3 def G(kpsi): return matrix_to_qubit(U*O*qubit_to_matrix(kpsi)) # working with a network made by two nodes # n = 2 # Nodes: 0, 1 # Edges: (0,1) A = Matrix([ [0,1], [1,0] ]) # tentando reescrever as contas utilizando seno e cosseno theta = Symbol('theta') # creating psi state vector kpsi = sin(theta/2)*1/sqrt(1)*(Qubit(1,1)) + cos(theta/2)*1/sqrt(3)*(Qubit(0,0)+Qubit(0,1)+Qubit(1,0)) bpsi = sin(theta/2)*1/sqrt(1)*Dagger(Qubit(1,1)) + cos(theta/2)*1/sqrt(3)*Dagger(Qubit(0,0)+Qubit(0,1)+Qubit(1,0)) U = 2*kpsi*bpsi U = qubit_to_matrix(U)-Matrix.eye(2**2) O = Matrix([ [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0,-1] ]) # Creating Oracle based on paper algorithm def O_operator(ket): pass # teste Matrix.eye(8) - 2 * qubit_to_matrix(Qubit(0,0,0)*Dagger(Qubit(0,0,0))) X = Matrix([ [0,1], [1,0] ]) X Z = Matrix([ [1,0], [0,-1] ]) Tp = TensorProduct X3 = Tp(Tp(Matrix.eye(2),Matrix.eye(2)),X) Z3 = Matrix([ [1,0,0,0,0,0,0,0], [0,-1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0], [0,0,0,1,0,0,0,0], [0,0,0,0,1,0,0,0], [0,0,0,0,0,1,0,0], [0,0,0,0,0,0,1,0], [0,0,0,0,0,0,0,1], ]) X3*Z3*X3 a= H3*4/sqrt(2) p=sqrt(2)/4*a*Matrix([1,1,1,-1,1,1,-1,1]) sqrt(2)/4*a*Matrix([1,0,-1,0,0,-1,0,1]) X.as_matrix() Tp = TensorProduct XX = Tp(Tp(Matrix([[0,1],[1,0]]),Matrix([[0,1],[1,0]])),Matrix([[0,1],[1,0]])) Z3 = Matrix([ [1,0,0,0,0,0,0,0], [0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0], [0,0,0,1,0,0,0,0], [0,0,0,0,1,0,0,0], [0,0,0,0,0,1,0,0], [0,0,0,0,0,0,1,0], [0,0,0,0,0,0,0,-1], ]) XX*Z3*XX XX*Z3 Z3*XX HH = Tp(Tp(Matrix([[1,1],[1,-1]]),Matrix([[1,1],[1,-1]])),Matrix([[1,1],[1,-1]])) HH HH*XX*HH CX = Matrix([ [1,0,0,0,0,0,0,0], [0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0], [0,0,0,1,0,0,0,0], [0,0,0,0,1,0,0,0], [0,0,0,0,0,1,0,0], [0,0,0,0,0,0,0,1], [0,0,0,0,0,0,1,0], ]) XX*HH*CX*HH*XX HH*(2*Matrix([1,0,0,0,0,0,0,0])*Dagger(Matrix([1,0,0,0,0,0,0,0]))-Matrix.eye(8))*HH CZ = Matrix([ [1,0,0,0,0,0,0,0], [0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0], [0,0,0,1,0,0,0,0], [0,0,0,0,1,0,0,0], [0,0,0,0,0,1,0,0], [0,0,0,0,0,0,1,0], [0,0,0,0,0,0,0,-1] ]) XX*CZ*XX HH*CX*HH HH*XX*CZ*XX*HH CZ CX H3 = kronecker_product(Matrix.eye(2),Matrix.eye(2),Matrix([[1,1],[1,-1]])) H3 HH*XX*H3*CX*H3*XX*HH
https://github.com/bertolinocastro/quantum-computing-algorithms
bertolinocastro
# A Quantum Circuit to Construct All Maximal Cliques Using Grover’s Search Algorithm ## Chu Ryang Wie ### DOI: https://arxiv.org/abs/1711.06146v2 import matplotlib #matplotlib.use('Agg') import matplotlib.pyplot as plt from qiskit import * # IBMQ.load_account() from qiskit.visualization import * n = 3 # size of network psi = QuantumRegister(n, name='psi') # cliques states data = QuantumRegister(n**2, name='data') # data A+I states ancl = QuantumRegister(n**2, name='ancl') # ancilla states cpsi = ClassicalRegister(n, name='cpsi') # classical register for measurement cdata = ClassicalRegister(n**2, name='cdata') # classical register for measurement cancl = ClassicalRegister(n**2, name='cancl') # classical register for measurement #extra_ancl = QuantumRegister(n**2, name='extra_ancl') qc = QuantumCircuit(psi, data, ancl, cpsi, cdata, cancl, name='maximal cliques') import numpy as np A = np.array([ # creating adjacency matrix [0,1,0], [1,0,1], [0,1,0] ], dtype=np.int) AI = A+ np.eye(n, dtype=np.int) # setting network structure on data qubits for ij, cij in enumerate(AI.flatten()): if cij: qc.x(data[ij]) # putting cliques on uniform superposition for j in range(n): qc.h(psi[j]) def V(): for j in range(n): for i in range(n): # applying 'intersect operator' as defined in paper qc.barrier() # standard toffoli qc.ccx(psi[j], data[j*n+i], ancl[j*n+i]) # toffoli variant - 1st ctrl qbit works when 0 qc.x(psi[j]) qc.ccx(psi[j], data[j*n+i], ancl[j*n+i]) # toffoli variant - 1st & 2nd ctrl qbit work when 0 qc.x(data[j*n+i]) qc.ccx(psi[j], data[j*n+i], ancl[j*n+i]) # undoing NOT operations qc.x(psi[j]) qc.x(data[j*n+i]) def W(): for j in range(n): # trying to use multi-controlled toffoli gate available in qiskit (not sure if it works) #qc.mct(ancl[j::n], psi[j], extra_ancl) #QuantumCircuit.mct(q_controls, q_target, q_ancilla, mode='basic') qc.barrier() qc.mct(ancl[j::n], psi[j], None, mode='noancilla') def flip_ket_0(): for j in range(n): qc.x(psi[j]) qc.h(psi[n-1]) qc.barrier() qc.mct(psi[:-1], psi[-1], None, mode='noancilla') qc.barrier() qc.h(psi[n-1]) for j in range(n): qc.x(psi[j]) def O(): qc.barrier() V() qc.barrier() W() qc.barrier() flip_ket_0() qc.barrier() W() qc.barrier() V() def G(): qc.barrier() for j in range(n): qc.h(psi[j]) qc.barrier() for j in range(n): qc.x(psi[j]) qc.barrier() qc.h(psi[-1]) qc.barrier() qc.mct(psi[:-1],psi[-1],None,mode='noancilla') qc.barrier() qc.h(psi[-1]) qc.barrier() for j in range(n): qc.x(psi[j]) qc.barrier() for j in range(n): qc.h(psi[j]) O() G() qc.barrier() qc.measure(psi, cpsi) qc.measure(data, cdata) qc.measure(ancl, cancl) fig = circuit_drawer(qc, output='mpl', filename='circuit.pdf', fold=300) #fig res = execute(qc, Aer.get_backend('qasm_simulator'), shots=4096).result() print(res) print(res.get_counts()) plot_histogram(res.get_counts()) # Running on IBMQ Experience # saving account credentials first #IBMQ.save_account('MY_TOKEN_ID') # loading IBMQ session provider = IBMQ.load_account() backend = provider.backends(simulator=True,operational=True)[0] res = execute(qc, backend, shots=8192).result() plot_histogram(res.get_counts()) # TODO: create circuit for n=2 network and test it on melbourne qpu.
https://github.com/bertolinocastro/quantum-computing-algorithms
bertolinocastro
# A Quantum Circuit to Construct All Maximal Cliques Using Grover’s Search Algorithm ## Chu Ryang Wie ### DOI: https://arxiv.org/abs/1711.06146v2 from sympy import * #import sympy.physics.quantum as qp # quantum physics from sympy.physics.quantum.qubit import * from sympy.physics.quantum import Dagger, TensorProduct from sympy.physics.quantum.gate import * from sympy.physics.quantum.qapply import * N = Symbol('N', integer=True) #N = 8 # base network G: # 1 <-> 2 <-> 3 # Nodes: 1, 2, 3 # Edges: (1,2), (2,3) # Adjacency matrix for network G A = Matrix([ [0, 1, 0], [1, 0, 1], [0, 1, 0] ]) # creating qubits for n=3 basis q = [Qubit(f'{dummy:03b}') for dummy in range(2**3)] q # creating psi state vector kpsi = 1/sqrt(N)*sum(q) bpsi = 1/sqrt(N)*Dagger(sum(q)) # TODO: create in terms of matrices the O operator perfectly as the circuit described in the paper O = Matrix([ [1, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0,-1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0,-1, 0], [0, 0, 0, 0, 0, 0, 0, 1], ]) # step: constructing the U operator basics using a network with n=3 # function to represent qubit as matrix: qubit_to_matrix() U = 2*kpsi*bpsi U = qubit_to_matrix(U)-Matrix.eye(2**3) Hm = Matrix([[1,1],[1,-1]]) Hc = 1/sqrt(2) H3 = Hc**3*kronecker_product(Hm,Hm,Hm) q000 = qubit_to_matrix(q[0]) Ualt = H3*(2*q000*Dagger(q000)-Matrix.eye(8))*H3 def G(kpsi): return matrix_to_qubit(U*O*qubit_to_matrix(kpsi)) # working with a network made by two nodes # n = 2 # Nodes: 0, 1 # Edges: (0,1) A = Matrix([ [0,1], [1,0] ]) # tentando reescrever as contas utilizando seno e cosseno theta = Symbol('theta') # creating psi state vector kpsi = sin(theta/2)*1/sqrt(1)*(Qubit(1,1)) + cos(theta/2)*1/sqrt(3)*(Qubit(0,0)+Qubit(0,1)+Qubit(1,0)) bpsi = sin(theta/2)*1/sqrt(1)*Dagger(Qubit(1,1)) + cos(theta/2)*1/sqrt(3)*Dagger(Qubit(0,0)+Qubit(0,1)+Qubit(1,0)) U = 2*kpsi*bpsi U = qubit_to_matrix(U)-Matrix.eye(2**2) O = Matrix([ [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0,-1] ]) # Creating Oracle based on paper algorithm def O_operator(ket): pass # teste Matrix.eye(8) - 2 * qubit_to_matrix(Qubit(0,0,0)*Dagger(Qubit(0,0,0))) X = Matrix([ [0,1], [1,0] ]) X Z = Matrix([ [1,0], [0,-1] ]) Tp = TensorProduct X3 = Tp(Tp(Matrix.eye(2),Matrix.eye(2)),X) Z3 = Matrix([ [1,0,0,0,0,0,0,0], [0,-1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0], [0,0,0,1,0,0,0,0], [0,0,0,0,1,0,0,0], [0,0,0,0,0,1,0,0], [0,0,0,0,0,0,1,0], [0,0,0,0,0,0,0,1], ]) X3*Z3*X3 a= H3*4/sqrt(2) p=sqrt(2)/4*a*Matrix([1,1,1,-1,1,1,-1,1]) sqrt(2)/4*a*Matrix([1,0,-1,0,0,-1,0,1]) X.as_matrix() Tp = TensorProduct XX = Tp(Tp(Matrix([[0,1],[1,0]]),Matrix([[0,1],[1,0]])),Matrix([[0,1],[1,0]])) Z3 = Matrix([ [1,0,0,0,0,0,0,0], [0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0], [0,0,0,1,0,0,0,0], [0,0,0,0,1,0,0,0], [0,0,0,0,0,1,0,0], [0,0,0,0,0,0,1,0], [0,0,0,0,0,0,0,-1], ]) XX*Z3*XX XX*Z3 Z3*XX HH = Tp(Tp(Matrix([[1,1],[1,-1]]),Matrix([[1,1],[1,-1]])),Matrix([[1,1],[1,-1]])) HH HH*XX*HH CX = Matrix([ [1,0,0,0,0,0,0,0], [0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0], [0,0,0,1,0,0,0,0], [0,0,0,0,1,0,0,0], [0,0,0,0,0,1,0,0], [0,0,0,0,0,0,0,1], [0,0,0,0,0,0,1,0], ]) CX
https://github.com/bertolinocastro/quantum-computing-algorithms
bertolinocastro
# A Quantum Circuit to Construct All Maximal Cliques Using Grover’s Search Algorithm ## Chu Ryang Wie ### DOI: https://arxiv.org/abs/1711.06146v2 import matplotlib #matplotlib.use('Agg') import matplotlib.pyplot as plt from qiskit import * # IBMQ.load_account() from qiskit.visualization import * n = 3 # size of network psi = QuantumRegister(n, name='psi') # cliques states data = QuantumRegister(n**2, name='data') # data A+I states ancl = QuantumRegister(n**2, name='ancl') # ancilla states cpsi = ClassicalRegister(n, name='cpsi') # classical register for measurement cdata = ClassicalRegister(n**2, name='cdata') # classical register for measurement cancl = ClassicalRegister(n**2, name='cancl') # classical register for measurement #extra_ancl = QuantumRegister(n**2, name='extra_ancl') qc = QuantumCircuit(psi, data, ancl, cpsi, cdata, cancl, name='maximal cliques') import numpy as np A = np.array([ # creating adjacency matrix [0,1,0], [1,0,1], [0,1,0] ], dtype=np.int) AI = A+ np.eye(n, dtype=np.int) # setting network structure on data qubits for ij, cij in enumerate(AI.flatten()): if cij: qc.x(data[ij]) # putting cliques on uniform superposition for j in range(n): qc.h(psi[j]) def V(): for j in range(n): for i in range(n): # applying 'intersect operator' as defined in paper qc.barrier() # standard toffoli qc.ccx(psi[j], data[j*n+i], ancl[j*n+i]) # toffoli variant - 1st ctrl qbit works when 0 qc.x(psi[j]) qc.ccx(psi[j], data[j*n+i], ancl[j*n+i]) # toffoli variant - 1st & 2nd ctrl qbit work when 0 qc.x(data[j*n+i]) qc.ccx(psi[j], data[j*n+i], ancl[j*n+i]) # undoing NOT operations qc.x(psi[j]) qc.x(data[j*n+i]) def W(): for j in range(n): # trying to use multi-controlled toffoli gate available in qiskit (not sure if it works) #qc.mct(ancl[j::n], psi[j], extra_ancl) #QuantumCircuit.mct(q_controls, q_target, q_ancilla, mode='basic') qc.barrier() qc.mct(ancl[j::n], psi[j], None, mode='noancilla') def flip_ket_0(): for j in range(n): qc.x(psi[j]) qc.h(psi[n-1]) qc.barrier() qc.mct(psi[:-1], psi[-1], None, mode='noancilla') qc.barrier() qc.h(psi[n-1]) for j in range(n): qc.x(psi[j]) def O(): qc.barrier() V() qc.barrier() W() qc.barrier() flip_ket_0() qc.barrier() W() qc.barrier() V() def G(): qc.barrier() for j in range(n): qc.h(psi[j]) qc.barrier() for j in range(n): qc.x(psi[j]) qc.barrier() qc.h(psi[-1]) qc.barrier() qc.mct(psi[:-1],psi[-1],None,mode='noancilla') qc.barrier() qc.h(psi[-1]) qc.barrier() for j in range(n): qc.x(psi[j]) qc.barrier() for j in range(n): qc.h(psi[j]) O() G() qc.barrier() qc.measure(psi, cpsi) qc.measure(data, cdata) qc.measure(ancl, cancl) fig = circuit_drawer(qc, output='mpl', filename='circuit.pdf', fold=300) #fig res = execute(qc, Aer.get_backend('qasm_simulator'), shots=4096).result() print(res) print(res.get_counts()) plot_histogram(res.get_counts()) # Running on IBMQ Experience # saving account credentials first #IBMQ.save_account('MY_TOKEN_ID') # loading IBMQ session provider = IBMQ.load_account() backend = provider.backends(simulator=True,operational=True)[0] res = execute(qc, backend, shots=8192).result() plot_histogram(res.get_counts()) # TODO: create circuit for n=2 network and test it on melbourne qpu.
https://github.com/AMevans12/Quantum-Codes-Qiskit-Module-
AMevans12
from qiskit import * qr = QuantumRegister(2) cr = ClassicalRegister(2) circuit = QuantumCircuit(qr, cr) %matplotlib inline circuit.draw(output='mpl') # the quantum circuit has two qubits. they are indexed as qubits 0 and 1 circuit.h(0) circuit.cx(0,1) # order is control, target circuit.measure([0,1], [0,1]) # qubits [0,1] are measured and results are stored in classical bits [0,1] in order circuit.draw(output='mpl') simulator = Aer.get_backend('qasm_simulator') result = execute(circuit, backend=simulator, shots=1024).result() from qiskit.visualization import plot_histogram import qiskit.quantum_info as qi plot_histogram(result.get_counts(circuit)) from qiskit import IBMQ IBMQ.save_account('e9857a49c124d22110b0c577754d160e984ce3f01e5ef110ae6295f3f6c4a6f337a129dfdcb5a1191a9b8c69317e9ae32ed4d196b744571d45453db7fb56d933') IBMQ.load_account() provider = IBMQ.get_provider(hub = 'ibm-q') qcomp = provider.get_backend('ibm_brisbane') import qiskit.tools.jupyter %qiskit_job_watcher job = execute(circuit, backend=qcomp) result = job.result() plot_histogram(result.get_counts(circuit))
https://github.com/AMevans12/Quantum-Codes-Qiskit-Module-
AMevans12
my_list = [1,3,5,2,4,2,5,8,0,7,6] #classical computation method def oracle(my_input): winner =7 if my_input is winner: response = True else: response = False return response for index, trial_number in enumerate(my_list): if oracle(trial_number) is True: print("Winner is found at index %i" %index) print("%i calls to the oracle used " %(index +1)) break #quantum implemenation from qiskit import * import matplotlib.pyplot as plt import numpy as np from qiskit.tools import job_monitor # oracle circuit oracle = QuantumCircuit(2, name='oracle') oracle.cz(0,1) oracle.to_gate() oracle.draw(output='mpl') backend = Aer.get_backend('statevector_simulator') grover_circuit = QuantumCircuit(2,2) grover_circuit.h([0,1]) grover_circuit.append(oracle,[0,1]) grover_circuit.draw(output='mpl') job= execute(grover_circuit, backend=backend) result= job.result() sv= result.get_statevector() np.around(sv,2) #amplitude amplification reflection = QuantumCircuit(2, name='reflection') reflection.h([0,1]) reflection.z([0,1]) reflection.cz(0,1) reflection.h([0,1]) reflection.to_gate() reflection.draw(output='mpl') #testing circuit on simulator simulator = Aer.get_backend('qasm_simulator') grover_circuit = QuantumCircuit(2,2) grover_circuit.h([0,1]) grover_circuit.append(oracle,[0,1]) grover_circuit.append(reflection, [0,1]) grover_circuit.barrier() grover_circuit.measure([0,1],[0,1]) grover_circuit.draw(output='mpl') job= execute(grover_circuit,backend=simulator,shots=1) result=job.result() result.get_counts() #testing on real backend system IBMQ.load_account() provider= IBMQ.get_provider('ibm-q') qcomp= provider.get_backend('ibmq_manila') job = execute(grover_circuit,backend=qcomp) job_monitor(job) result=job.result() counts=result.get_counts(grover_circuit) from qiskit.visualization import plot_histogram plot_histogram(counts) counts['11']
https://github.com/AMevans12/Quantum-Codes-Qiskit-Module-
AMevans12
import qiskit.quantum_info as qi from qiskit.circuit.library import FourierChecking from qiskit.visualization import plot_histogram f=[1,-1,-1,-1] g=[1,1,-1,-1] circ = FourierChecking(f=f, g=g) circ.draw(output='mpl') zero=qi.Statevector.from_label('00') sv=zero.evolve(circ) probs=sv.probabilities_dict() plot_histogram(probs) import qiskit.quantum_info as qi from qiskit.circuit.library import FourierChecking from qiskit.visualization import plot_histogram f=[1,-1,-1,-1] g=[1,1,-1,-1] circ = FourierChecking(f=f, g=g) circ.draw(output='mpl') zero=qi.Statevector.from_label('00') sv=zero.evolve(circ) probs=sv.probabilities_dict() plot_histogram(probs)
https://github.com/AMevans12/Quantum-Codes-Qiskit-Module-
AMevans12
from qiskit import * circuit = QuantumCircuit(3,3) %matplotlib inline circuit.draw(output='mpl') circuit.x(0) circuit.barrier() circuit.draw(output='mpl') circuit.h(1) circuit.cx(1,2) circuit.barrier() circuit.draw(output='mpl') circuit.cx(0,1) circuit.h(0) circuit.barrier() circuit.draw(output='mpl') circuit.measure([0, 1], [0, 1]) circuit.barrier() circuit.draw(output='mpl') circuit.cx(1, 2) circuit.cz(0, 2) circuit.measure([2], [2]) circuit.draw(output='mpl') simulator = Aer.get_backend('qasm_simulator') result = execute(circuit, backend=simulator, shots=1024).result() from qiskit.visualization import plot_histogram plot_histogram(result.get_counts(circuit)) # Quantum Computer from qiskit import IBMQ IBMQ.save_account('e9857a49c124d22110b0c577754d160e984ce3f01e5ef110ae6295f3f6c4a6f337a129dfdcb5a1191a9b8c69317e9ae32ed4d196b744571d45453db7fb56d933') IBMQ.load_account() provider = IBMQ.get_provider(hub = 'ibm-q') qcomp = provider.get_backend('ibm_brisbane') import qiskit.tools.jupyter %qiskit_job_watcher job = execute(circuit, backend=qcomp) result = job.result() plot_histogram(result.get_counts(circuit)) from qiskit import * circuit = QuantumCircuit(3,3) %matplotlib inline circuit.draw(output='mpl') circuit.x(0) circuit.barrier() circuit.draw(output='mpl') circuit.h(1) circuit.cx(1,2) circuit.barrier() circuit.draw(output='mpl') circuit.cx(0,1) circuit.h(0) circuit.barrier() circuit.draw(output='mpl') circuit.measure([0, 1], [0, 1]) circuit.barrier() circuit.draw(output='mpl') circuit.cx(1, 2) circuit.cz(0, 2) circuit.measure([2], [2]) circuit.draw(output='mpl') simulator = Aer.get_backend('qasm_simulator') result = execute(circuit, backend=simulator, shots=1024).result() from qiskit.visualization import plot_histogram plot_histogram(result.get_counts(circuit)) # Quantum Computer from qiskit import IBMQ IBMQ.save_account('e9857a49c124d22110b0c577754d160e984ce3f01e5ef110ae6295f3f6c4a6f337a129dfdcb5a1191a9b8c69317e9ae32ed4d196b744571d45453db7fb56d933') IBMQ.load_account() provider = IBMQ.get_provider(hub = 'ibm-q') qcomp = provider.get_backend('ibm_brisbane') import qiskit.tools.jupyter %qiskit_job_watcher job = execute(circuit, backend=qcomp) result = job.result() plot_histogram(result.get_counts(circuit))
https://github.com/Rodri-rf/playing_with_quantum_computing
Rodri-rf
# Author: Khaled Alam(khaledalam.net@gmail.com) ''' Guess binary string (secret) of length N in 1 shot only using quantum computing circuit! ~ by using clasical computers we need at least N shots to guess string (secret) of length N ~ by using quantum computer we need 1 shot to guess string (secret) of ANY length ( cool isn't it! ^^ ) ''' secret = '01000001' # `01000001` = `A` from qiskit import * n = len(secret) qCircuit = QuantumCircuit(n+1, n) # n+1 qubits and n classical bits qCircuit.x(n) qCircuit.barrier() qCircuit.h(range(n+1)) qCircuit.barrier() for ii, OZ in enumerate(reversed(secret)): if OZ == '1': qCircuit.cx(ii, n) qCircuit.barrier() qCircuit.h(range(n+1)) qCircuit.barrier() qCircuit.measure(range(n), range(n)) %matplotlib inline qCircuit.draw(output='mpl') # run on simulator simulator = Aer.get_backend('qasm_simulator') result = execute(qCircuit, backend=simulator, shots=1).result() # only 1 shot from qiskit.visualization import plot_histogram plot_histogram( result.get_counts(qCircuit) )
https://github.com/Rodri-rf/playing_with_quantum_computing
Rodri-rf
"""Example usage of the Quantum Inspire backend with the Qiskit SDK. A simple example that demonstrates how to use the SDK to create a circuit to demonstrate conditional gate execution. For documentation on how to use Qiskit we refer to [https://qiskit.org/](https://qiskit.org/). Specific to Quantum Inspire is the creation of the QI instance, which is used to set the authentication of the user and provides a Quantum Inspire backend that is used to execute the circuit. Copyright 2018-19 QuTech Delft. Licensed under the Apache License, Version 2.0. """ import os from qiskit import BasicAer, execute from qiskit.circuit import QuantumRegister, ClassicalRegister, QuantumCircuit from quantuminspire.credentials import get_authentication from quantuminspire.qiskit import QI QI_URL = os.getenv('API_URL', 'https://api.quantum-inspire.com/') authentication = get_authentication() QI.set_authentication(authentication, QI_URL) qi_backend = QI.get_backend('QX single-node simulator') q = QuantumRegister(2, "q") c0 = ClassicalRegister(1, "c0") c1 = ClassicalRegister(1, "c1") qc = QuantumCircuit(3, name="conditional") qc.h([0, 2]) qc.cnot(q[0], q[1]) qc.measure_all() qi_job = execute(qc, backend=qi_backend, shots=1024) qi_result = qi_job.result() histogram = qi_result.get_counts(qc) print("\nResult from the remote Quantum Inspire backend:\n") print('State\tCounts') [print('{0}\t{1}'.format(state, counts)) for state, counts in histogram.items()] print("\nResult from the local Qiskit simulator backend:\n") backend = BasicAer.get_backend("qasm_simulator") job = execute(qc, backend=backend, shots=1024) result = job.result() print(result.get_counts(qc)) qc.draw(output="latex")
https://github.com/Rodri-rf/playing_with_quantum_computing
Rodri-rf
from qiskit.synthesis import QDrift from qiskit.circuit.library import PauliEvolutionGate from qiskit import QuantumCircuit from qiskit.quantum_info import Pauli # Define the Hamiltonian XX = Pauli('XX') YY = Pauli('YY') ZZ = Pauli('ZZ') a = 1 b = -1 c = 1 # A simple Hamiltonian: a XX + b YY + c ZZ. Use the appropriate Pauli compose method to do this. hamiltonian = a * XX.compose(b*ZZ) reps = 10 time = 1 evo_gate = PauliEvolutionGate(hamiltonian, time, synthesis=QDrift(reps=reps)) qc = QuantumCircuit(2) qc.append(evo_gate, [0, 1]) qc.draw('mpl')
https://github.com/Seanaventure/HighErrorRateRouting
Seanaventure
import matplotlib.pyplot as plt import networkx as nx import qiskit import HERR from qiskit.transpiler import CouplingMap from qiskit.transpiler.passes.routing import * from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.dagcircuit import DAGCircuit from qiskit.converters import circuit_to_dag from qiskit.converters import dag_to_circuit from math import pi from qiskit.compiler import transpile, assemble from qiskit.providers.aer.noise import NoiseModel import qiskit.providers.aer.noise as noise from qiskit.tools.visualization import dag_drawer import random from qiskit.circuit.instruction import Instruction import time def countTwoQubitGates(transpiledCircuit): num = 0 for gate in transpiledCircuit.data: # print(type(gate[0])) if issubclass(type(gate[0]), Instruction): if gate[0].name == "cx": num += 1 return num s = '1101' n = len(s) circuit = QuantumCircuit(8, n) # Step 0 circuit.x(n) # the n+1 qubits are indexed 0...n, so the last qubit is index n circuit.barrier() # just a visual aid for now # Step 1 # range(n+1) returns [0,1,2,...,n] in Python. This covers all the qubits circuit.h(range(n+1)) circuit.barrier() # just a visual aid for now # Step 2 for ii, yesno in enumerate(reversed(s)): if yesno == '1': circuit.cx(ii, n) circuit.barrier() # just a visual aid for now # Step 3 # range(n+1) returns [0,1,2,...,n] in Python. This covers all the qubits circuit.h(range(n+1)) circuit.barrier() # just a visual aid for now # measure the qubits indexed from 0 to n-1 and store them into the classical bits indexed 0 to n- circuit.measure(range(n), range(n)) provider = IBMQ.load_account() backend = provider.get_backend('ibmq_lima') basis_gates = backend.configuration().basis_gates squareCouplingList = list() for i in range(4): for j in range(4): if i is not j: if abs(i-j) == 1: squareCouplingList.append([i, j]) squareCouplingList.append(([0, 3])) squareCouplingList.append(([3, 0])) squareCouplingMap = CouplingMap(squareCouplingList) gridCouplingList = list() for i in range(4): for j in range(4): if i is not j: if abs(i-j) == 1: gridCouplingList.append([i, j]) for i in range(4,8): for j in range(4,8): if i is not j: if abs(i-j) == 1: gridCouplingList.append([i, j]) gridCouplingList.append(([0, 4])) gridCouplingList.append(([4, 0])) gridCouplingList.append(([1, 5])) gridCouplingList.append(([5, 1])) gridCouplingList.append(([2, 6])) gridCouplingList.append(([6, 2])) gridCouplingList.append(([3, 7])) gridCouplingList.append(([7, 3])) gridCouplingMap = CouplingMap(gridCouplingList) jakatraCouplingList = [[0, 1], [1, 0], [1, 2], [2, 1], [1, 3], [3, 1], [3,5], [5,3], [4,5], [5,4], [6,5], [5,6]] jakatraCouplingMap = CouplingMap(jakatraCouplingList) circDag = circuit_to_dag(circuit) targetCouplingMap = squareCouplingMap bSwap = BasicSwap(targetCouplingMap) baseTime = time.perf_counter() bSwap.run(circDag) bSwapTime = time.perf_counter() - baseTime sabreSwap = SabreSwap(targetCouplingMap) baseTime = time.perf_counter() sabreSwap.run(circDag) sabreSwapTime = time.perf_counter() - baseTime stochasticSwap = StochasticSwap(targetCouplingMap) baseTime = time.perf_counter() stochasticSwap.run(circDag) stochasticSwapTime = time.perf_counter() - baseTime lookAheadSwap = LookaheadSwap(targetCouplingMap) baseTime = time.perf_counter() lookAheadSwap.run(circDag) lookAheadSwapTime = time.perf_counter() - baseTime for i in range(200): # Create a noise model for the simulations noise_model = noise.NoiseModel() errorRates = list() qiskitErrors = list() for i in range(len(squareCouplingList)//2): errorRates.append(random.randrange(1, 10, 1)/100.0) qiskitErrors.append(noise.depolarizing_error(errorRates[i], 2)) edges = targetCouplingMap.get_edges() uniqueEdges = set() for edge in edges: uniqueEdges.add(tuple(sorted(edge))) noiseGraph = nx.Graph() noiseGraph.add_nodes_from([0, 7]) errorIdex = 0 for edge in uniqueEdges: noise_model.add_quantum_error(qiskitErrors[errorIdex], ['cx'], edge) noiseGraph.add_edge(edge[0], edge[1], weight=1-errorRates[errorIdex]) errorIdex += 1 herr = HERR.HERR(targetCouplingMap, noiseGraph) basSwap = BasicSwap(targetCouplingMap) #print(gridCouplingMap) # Run HERR baseTime = time.perf_counter() HERRRes = herr.run(circDag) HERRSwapTime = time.perf_counter() - baseTime updatedCirc = dag_to_circuit(HERRRes) print(str(HERRSwapTime) + " " + str(bSwapTime) + " " + str(sabreSwapTime) + " " + str(stochasticSwapTime) + " " + str(lookAheadSwapTime))
https://github.com/Seanaventure/HighErrorRateRouting
Seanaventure
import matplotlib.pyplot as plt import networkx as nx import qiskit import HERR from qiskit.transpiler import CouplingMap from qiskit.transpiler.passes.routing import * from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.dagcircuit import DAGCircuit from qiskit.converters import circuit_to_dag from qiskit.converters import dag_to_circuit from math import pi from qiskit.compiler import transpile, assemble from qiskit.providers.aer.noise import NoiseModel import qiskit.providers.aer.noise as noise from qiskit.tools.visualization import dag_drawer import random from qiskit.circuit.instruction import Instruction import time couplingList = list() for i in range(4): for j in range(4): if i is not j: couplingList.append([i, j]) provider = IBMQ.load_account() backend = provider.get_backend('ibmq_lima') basis_gates = backend.configuration().basis_gates couplingMap = CouplingMap(couplingList) squareCouplingList = list() for i in range(4): for j in range(4): if i is not j: if abs(i-j) == 1: squareCouplingList.append([i, j]) squareCouplingList.append(([0, 3])) squareCouplingList.append(([3, 0])) squareCouplingMap = CouplingMap(squareCouplingList) gridCouplingList = list() for i in range(4): for j in range(4): if i is not j: if abs(i-j) == 1: gridCouplingList.append([i, j]) for i in range(4,8): for j in range(4,8): if i is not j: if abs(i-j) == 1: gridCouplingList.append([i, j]) gridCouplingList.append(([0, 4])) gridCouplingList.append(([4, 0])) gridCouplingList.append(([1, 5])) gridCouplingList.append(([5, 1])) gridCouplingList.append(([2, 6])) gridCouplingList.append(([6, 2])) gridCouplingList.append(([3, 7])) gridCouplingList.append(([7, 3])) gridCouplingMap = CouplingMap(gridCouplingList) jakatraCouplingList = [[0, 1], [1, 0], [1, 2], [2, 1], [1, 3], [3, 1], [3,5], [5,3], [4,5], [5,4], [6,5], [5,6]] jakatraCouplingMap = CouplingMap(jakatraCouplingList) 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 def inverse_qft(circuit, n): """Does the inverse QFT on the first n qubits in circuit""" # First we create a QFT circuit of the correct size: qft_circ = qft(QuantumCircuit(n), n) # Then we take the inverse of this circuit invqft_circ = qft_circ.inverse() # And add it to the first n qubits in our existing circuit circuit.append(invqft_circ, circuit.qubits[:n]) return circuit.decompose() # .decompose() allows us to see the individual gates def countTwoQubitGates(transpiledCircuit): num = 0 for gate in transpiledCircuit.data: # print(type(gate[0])) if issubclass(type(gate[0]), Instruction): if gate[0].name == "cx": num += 1 return num s = '10111011' n = len(s) # Let's see how it looks: circuit = QuantumCircuit(n) for ii, yesno in enumerate(reversed(s)): if yesno == '1': circuit.x(ii) qft(circuit, n) circuit = inverse_qft(circuit, n) circuit.measure_all() circDag = circuit_to_dag(circuit) targetCouplingMap = gridCouplingMap bSwap = BasicSwap(targetCouplingMap) baseTime = time.perf_counter() bSwap.run(circDag) bSwapTime = time.perf_counter() - baseTime sabreSwap = SabreSwap(targetCouplingMap) baseTime = time.perf_counter() sabreSwap.run(circDag) sabreSwapTime = time.perf_counter() - baseTime stochasticSwap = StochasticSwap(targetCouplingMap) baseTime = time.perf_counter() stochasticSwap.run(circDag) stochasticSwapTime = time.perf_counter() - baseTime lookAheadSwap = LookaheadSwap(targetCouplingMap) baseTime = time.perf_counter() lookAheadSwap.run(circDag) lookAheadSwapTime = time.perf_counter() - baseTime for i in range(200): # Create a noise model for the simulations noise_model = noise.NoiseModel() errorRates = list() qiskitErrors = list() for i in range(len(gridCouplingList)//2): errorRates.append(random.randrange(1, 10, 1)/100.0) qiskitErrors.append(noise.depolarizing_error(errorRates[i], 2)) edges = targetCouplingMap.get_edges() uniqueEdges = set() for edge in edges: uniqueEdges.add(tuple(sorted(edge))) noiseGraph = nx.Graph() noiseGraph.add_nodes_from([0, 7]) errorIdex = 0 for edge in uniqueEdges: noise_model.add_quantum_error(qiskitErrors[errorIdex], ['cx'], edge) noiseGraph.add_edge(edge[0], edge[1], weight=1-errorRates[errorIdex]) errorIdex += 1 herr = HERR.HERR(targetCouplingMap, noiseGraph) basSwap = BasicSwap(targetCouplingMap) #print(gridCouplingMap) # Run HERR baseTime = time.perf_counter() HERRRes = herr.run(circDag) HERRSwapTime = time.perf_counter() - baseTime updatedCirc = dag_to_circuit(HERRRes) print(str(HERRSwapTime) + " " + str(bSwapTime) + " " + str(sabreSwapTime) + " " + str(stochasticSwapTime) + " " + str(lookAheadSwapTime))
https://github.com/Seanaventure/HighErrorRateRouting
Seanaventure
import matplotlib.pyplot as plt import networkx as nx import qiskit import HERR from qiskit.transpiler import CouplingMap from qiskit.transpiler.passes.routing import BasicSwap from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.dagcircuit import DAGCircuit from qiskit.converters import circuit_to_dag from qiskit.converters import dag_to_circuit from math import pi from qiskit.compiler import transpile, assemble from qiskit.providers.aer.noise import NoiseModel import qiskit.providers.aer.noise as noise from qiskit.tools.visualization import dag_drawer import random from qiskit.circuit.instruction import Instruction from qiskit.transpiler.passes.routing import * import time def countTwoQubitGates(transpiledCircuit): num = 0 for gate in transpiledCircuit.data: # print(type(gate[0])) if issubclass(type(gate[0]), Instruction): if gate[0].name == "cx": num += 1 return num couplingList = list() for i in range(3): for j in range(3): if i is not j: couplingList.append([i, j]) squareCouplingList = list() for i in range(4): for j in range(4): if i is not j: if abs(i-j) == 1: squareCouplingList.append([i, j]) squareCouplingList.append(([0, 3])) squareCouplingList.append(([3, 0])) provider = IBMQ.load_account() backend = provider.get_backend('ibmq_lima') basis_gates = backend.configuration().basis_gates squareCouplingMap = CouplingMap(squareCouplingList) couplingMap = CouplingMap(couplingList) qcHERR = QuantumCircuit(4) qcHERR.x(0) qcHERR.x(1) qcHERR.ccx(0, 1, 2) qcHERR.measure_all() qcHERR = qcHERR.decompose() nonHERR = QuantumCircuit(4) nonHERR.x(0) nonHERR.x(1) nonHERR.ccx(0, 1, 2) nonHERR.measure_all() circDag = circuit_to_dag(qcHERR) targetCouplingMap = squareCouplingMap bSwap = BasicSwap(targetCouplingMap) baseTime = time.perf_counter() bSwap.run(circDag) bSwapTime = time.perf_counter() - baseTime sabreSwap = SabreSwap(targetCouplingMap) baseTime = time.perf_counter() sabreSwap.run(circDag) sabreSwapTime = time.perf_counter() - baseTime stochasticSwap = StochasticSwap(targetCouplingMap) baseTime = time.perf_counter() stochasticSwap.run(circDag) stochasticSwapTime = time.perf_counter() - baseTime lookAheadSwap = LookaheadSwap(targetCouplingMap) baseTime = time.perf_counter() lookAheadSwap.run(circDag) lookAheadSwapTime = time.perf_counter() - baseTime for i in range(200): # Create a noise model for the simulations noise_model = noise.NoiseModel() errorRates = list() qiskitErrors = list() for i in range(len(squareCouplingList)//2): errorRates.append(random.randrange(1, 10, 1)/100.0) qiskitErrors.append(noise.depolarizing_error(errorRates[i], 2)) edges = targetCouplingMap.get_edges() uniqueEdges = set() for edge in edges: uniqueEdges.add(tuple(sorted(edge))) noiseGraph = nx.Graph() noiseGraph.add_nodes_from([0, 7]) errorIdex = 0 for edge in uniqueEdges: noise_model.add_quantum_error(qiskitErrors[errorIdex], ['cx'], edge) noiseGraph.add_edge(edge[0], edge[1], weight=1-errorRates[errorIdex]) errorIdex += 1 herr = HERR.HERR(targetCouplingMap, noiseGraph) basSwap = BasicSwap(targetCouplingMap) #print(gridCouplingMap) # Run HERR baseTime = time.perf_counter() HERRRes = herr.run(circDag) HERRSwapTime = time.perf_counter() - baseTime updatedCirc = dag_to_circuit(HERRRes) print(str(HERRSwapTime) + " " + str(bSwapTime) + " " + str(sabreSwapTime) + " " + str(stochasticSwapTime) + " " + str(lookAheadSwapTime))