repo
stringclasses
900 values
file
stringclasses
754 values
content
stringlengths
4
215k
https://github.com/bagmk/Quantum_Machine_Learning_Express
bagmk
import numpy as np from qiskit.quantum_info import state_fidelity, Statevector def getStatevector(circuit): return Statevector(circuit).data import warnings warnings.filterwarnings('ignore') def P_haar(N, F): if F == 1: return 0 else: return (N - 1) * ((1 - F) ** (N - 2)) def KL(P, Q): epsilon = 1e-8 kl_divergence = 0.0 for p, q in zip(P, Q): kl_divergence += p * np.log( (p + epsilon) / (q + epsilon) ) return abs(kl_divergence) def expressibility(qubits, sampler, *, bins=100, epoch=3000, layer=1, encode=False, return_detail=False): unit = 1 / bins limits = [] probabilities = np.array([0] * bins) for i in range(1, bins + 1): limits.append(unit * i) for i in range(epoch): circuit_1 = sampler(layer=layer, qubits=qubits) circuit_2 = sampler(layer=layer, qubits=qubits) f = state_fidelity( getStatevector(circuit_1), getStatevector(circuit_2) ) for j in range(bins): if f <= limits[j]: probabilities[j] += 1 break pHaar_vqc = [ P_haar(2 ** qubits, f - (unit/2)) / bins for f in limits] probabilities = [ p / epoch for p in probabilities ] if return_detail: return pHaar_vqc, probabilities else: return KL(probabilities, pHaar_vqc)
https://github.com/bagmk/Quantum_Machine_Learning_Express
bagmk
from matplotlib import pyplot from qiskit import * from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import IBMQ, Aer, execute,assemble,QuantumCircuit, aqua from qiskit.visualization import plot_histogram, plot_bloch_vector, plot_bloch_multivector from qiskit.quantum_info import Statevector from qiskit.extensions import * provider = IBMQ.load_account() from qiskit.quantum_info import random_unitary from qiskit.providers.aer import QasmSimulator, StatevectorSimulator, UnitarySimulator import matplotlib.pyplot as plt %matplotlib inline import numpy as np import math from math import pi, sqrt from scipy.special import rel_entr from random import seed from random import random import cmath #Possible Bin bins_list=[]; for i in range(76): bins_list.append((i)/75) #Center of the Bean bins_x=[] for i in range(75): bins_x.append(bins_list[1]+bins_list[i]) def P_harr(l,u,N): return (1-l)**(N-1)-(1-u)**(N-1) #Harr historgram P_harr_hist=[] for i in range(75): P_harr_hist.append(P_harr(bins_list[i],bins_list[i+1],2)) #Imaginary j=(-1)**(1/2) backend = Aer.get_backend('qasm_simulator') for x in range(1,20,1): print() arr = [] for nsh in range(1,20,1): arr.append([]) for lp in range(1,10,1): nshot=int(round(1000*(nsh)**1.5,0)) nparam=1000*lp fidelity=[] for x in range(nparam): qr = QuantumRegister(1) cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr) u13=UnitaryGate(random_unitary(2)) qc.append(u13, [qr[0]] ) u13=UnitaryGate(random_unitary(2)) qc.append(u13, [qr[0]] ) qc.measure(qr[0],cr[0]) job = execute(qc, backend, shots=nshot) result = job.result() count =result.get_counts() if '0' in count and '1' in count: ratio=count['0']/nshot elif '0' in count and '1' not in count: ratio=count['0']/nshot else: ratio=0 fidelity.append(ratio) #Kullback Leibler divergence weights = np.ones_like(fidelity)/float(len(fidelity)) P_U_hist=np.histogram(fidelity, bins=bins_list, weights=weights, range=[0, 1])[0]; #Kullback Leibler divergence print(nshot,'shots per simulation',nparam,'distribution size') arr[nsh-1].append(sum(rel_entr(P_U_hist, P_harr_hist))) import sys import numpy qasm=arr numpy.set_printoptions(threshold=sys.maxsize) np.savetxt("KLDivg_qasm.txt",qasm,fmt='%.2f') backend = Aer.get_backend('statevector_simulator') for x in range(1,20,1): print() arr = [] for nsh in range(1,20,1): arr.append([]) for lp in range(1,10,1): nshot=int(round(1000*(nsh)**1.5,0)) nparam=1000*lp fidelity=[] for x in range(nparam): qr = QuantumRegister(1) cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr) u13=UnitaryGate(random_unitary(2)) qc.append(u13, [qr[0]] ) u13=UnitaryGate(random_unitary(2)) qc.append(u13, [qr[0]] ) qc.measure(qr[0],cr[0]) job = execute(qc, backend, shots=nshot) result = job.result() count =result.get_counts() if '0' in count and '1' in count: ratio=count['0']/nshot elif '0' in count and '1' not in count: ratio=count['0']/nshot else: ratio=0 fidelity.append(ratio) #Kullback Leibler divergence weights = np.ones_like(fidelity)/float(len(fidelity)) P_U_hist=np.histogram(fidelity, bins=bins_list, weights=weights, range=[0, 1])[0]; #Kullback Leibler divergence print(nshot,'shots per simulation',nparam,'distribution size') arr[nsh-1].append(sum(rel_entr(P_U_hist, P_harr_hist))) import sys import numpy statevector=arr numpy.set_printoptions(threshold=sys.maxsize) np.savetxt("KLDivg_statevector.txt",statevector,fmt='%.2f') ##Plot import pandas as pd import matplotlib.pyplot as plt #loading dataset x = [i+1 for i in range(19)] y = [i[0] for i in arr] plt.plot(x, y, 'o', color='red', label='L=1'); x = [i+1 for i in range(19)] y = [i[1] for i in arr] plt.plot(x, y, 'o', color='blue', label='L=2'); x = [i+1 for i in range(19)] y = [i[2] for i in arr] plt.plot(x, y, 'o', color='black', label='L=3'); x = [i+1 for i in range(19)] y = [i[3] for i in arr] plt.plot(x, y, 'o', color='green', label='L=4'); x = [i+1 for i in range(19)] y = [i[3] for i in arr] plt.plot(x, y, 'o', color='purple', label='L=5'); plt.legend(loc='upper right') plt.yscale('log',base=10) plt.xlabel('Circuit ID') plt.ylabel('Expressibility') # Create names on the x axis plt.xticks([i+1 for i in range(19)]) plt.show()
https://github.com/bagmk/Quantum_Machine_Learning_Express
bagmk
from matplotlib import pyplot from qiskit import * from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import IBMQ, Aer, execute,assemble,QuantumCircuit, aqua from qiskit.visualization import plot_histogram, plot_bloch_vector, plot_bloch_multivector from qiskit.quantum_info import Statevector from qiskit.extensions import * provider = IBMQ.load_account() from qiskit.quantum_info import random_unitary from qiskit.providers.aer import QasmSimulator, StatevectorSimulator, UnitarySimulator import matplotlib.pyplot as plt %matplotlib inline import numpy as np import math from math import pi, sqrt from scipy.special import rel_entr from random import seed from random import random import cmath #Possible Bin bins_list=[]; for i in range(76): bins_list.append((i)/75) #Center of the Bean bins_x=[] for i in range(75): bins_x.append(bins_list[1]+bins_list[i]) def P_harr(l,u,N): return (1-l)**(N-1)-(1-u)**(N-1) #Harr historgram P_harr_hist=[] for i in range(75): P_harr_hist.append(P_harr(bins_list[i],bins_list[i+1],2)) #Imaginary j=(-1)**(1/2) backend = Aer.get_backend('qasm_simulator') for x in range(1,20,1): print() arr = [] for nsh in range(1,20,1): arr.append([]) for lp in range(1,10,1): nshot=int(round(1000*(nsh)**1.5,0)) nparam=1000*lp fidelity=[] for x in range(nparam): qr = QuantumRegister(1) cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr) u13=UnitaryGate(random_unitary(2)) qc.append(u13, [qr[0]] ) u13=UnitaryGate(random_unitary(2)) qc.append(u13, [qr[0]] ) qc.measure(qr[0],cr[0]) job = execute(qc, backend, shots=nshot) result = job.result() count =result.get_counts() if '0' in count and '1' in count: ratio=count['0']/nshot elif '0' in count and '1' not in count: ratio=count['0']/nshot else: ratio=0 fidelity.append(ratio) #Kullback Leibler divergence weights = np.ones_like(fidelity)/float(len(fidelity)) P_U_hist=np.histogram(fidelity, bins=bins_list, weights=weights, range=[0, 1])[0]; #Kullback Leibler divergence print(nshot,'shots per simulation',nparam,'distribution size') arr[nsh-1].append(sum(rel_entr(P_U_hist, P_harr_hist))) import sys import numpy numpy.set_printoptions(threshold=sys.maxsize) np.savetxt("KLDivg_qasm.txt",qasm) qasm backend = QasmSimulator(method='density_matrix') for x in range(1,20,1): print() arr = [] for nsh in range(1,20,1): arr.append([]) for lp in range(1,10,1): nshot=int(round(1000*(nsh)**1.5,0)) nparam=1000*lp fidelity=[] for x in range(nparam): qr = QuantumRegister(1) cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr) u13=UnitaryGate(random_unitary(2)) qc.append(u13, [qr[0]] ) u13=UnitaryGate(random_unitary(2)) qc.append(u13, [qr[0]] ) qc.measure(qr[0],cr[0]) job = execute(qc, backend, shots=nshot) result = job.result() count =result.get_counts() if '0' in count and '1' in count: ratio=count['0']/nshot elif '0' in count and '1' not in count: ratio=count['0']/nshot else: ratio=0 fidelity.append(ratio) #Kullback Leibler divergence weights = np.ones_like(fidelity)/float(len(fidelity)) P_U_hist=np.histogram(fidelity, bins=bins_list, weights=weights, range=[0, 1])[0]; #Kullback Leibler divergence arr[nsh-1].append(sum(rel_entr(P_U_hist, P_harr_hist))) print(nshot,'shots per simulation',nparam,'distribution size KL=',sum(rel_entr(P_U_hist, P_harr_hist))) import sys import numpy density_mat=arr numpy.set_printoptions(threshold=sys.maxsize) np.savetxt("KLDivg_density_mat.txt",density_mat) density_mat backend = QasmSimulator(method='statevector') for x in range(1,20,1): print() arr = [] for nsh in range(1,20,1): arr.append([]) for lp in range(1,10,1): nshot=int(round(1000*(nsh)**1.5,0)) nparam=1000*lp fidelity=[] for x in range(nparam): qr = QuantumRegister(1) cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr) u13=UnitaryGate(random_unitary(2)) qc.append(u13, [qr[0]] ) u13=UnitaryGate(random_unitary(2)) qc.append(u13, [qr[0]] ) qc.measure(qr[0],cr[0]) job = execute(qc, backend, shots=nshot) result = job.result() count =result.get_counts() if '0' in count and '1' in count: ratio=count['0']/nshot elif '0' in count and '1' not in count: ratio=count['0']/nshot else: ratio=0 fidelity.append(ratio) #Kullback Leibler divergence weights = np.ones_like(fidelity)/float(len(fidelity)) P_U_hist=np.histogram(fidelity, bins=bins_list, weights=weights, range=[0, 1])[0]; #Kullback Leibler divergence arr[nsh-1].append(sum(rel_entr(P_U_hist, P_harr_hist))) print(nshot,'shots per simulation',nparam,'distribution size KL=',sum(rel_entr(P_U_hist, P_harr_hist))) import sys import numpy statevector1=arr numpy.set_printoptions(threshold=sys.maxsize) np.savetxt("KLDivg_statevector.txt",statevector1) statevector1 backend = QasmSimulator(method='matrix_product_state') for x in range(1,20,1): print() arr = [] for nsh in range(1,20,1): arr.append([]) for lp in range(1,10,1): nshot=int(round(1000*(nsh)**1.5,0)) nparam=1000*lp fidelity=[] for x in range(nparam): qr = QuantumRegister(1) cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr) u13=UnitaryGate(random_unitary(2)) qc.append(u13, [qr[0]] ) u13=UnitaryGate(random_unitary(2)) qc.append(u13, [qr[0]] ) qc.measure(qr[0],cr[0]) job = execute(qc, backend, shots=nshot) result = job.result() count =result.get_counts() if '0' in count and '1' in count: ratio=count['0']/nshot elif '0' in count and '1' not in count: ratio=count['0']/nshot else: ratio=0 fidelity.append(ratio) #Kullback Leibler divergence weights = np.ones_like(fidelity)/float(len(fidelity)) P_U_hist=np.histogram(fidelity, bins=bins_list, weights=weights, range=[0, 1])[0]; #Kullback Leibler divergence arr[nsh-1].append(sum(rel_entr(P_U_hist, P_harr_hist))) print(nshot,'shots per simulation',nparam,'distribution size KL=',sum(rel_entr(P_U_hist, P_harr_hist))) import sys import numpy matrix_product1=arr numpy.set_printoptions(threshold=sys.maxsize) np.savetxt("KLDivg_matrix_product1.txt",matrix_product1) matrix_product1 def plotdata(i,data): klll=np.transpose(data) x=[]; y=[]; for nsh in range(0,9,1): x.append(int(round(1000*(nsh)**1.5,0))) y.append(klll[nsh][i]) return [x,y] #loading dataset fig, axes = plt.subplots(nrows=1, ncols=4, figsize=(20, 5)) datalist=[density_mat,statevector1,matrix_product1,qasm] datalistn=['density_mat','statevector','matrix_product','qasm'] indx=0; for indx in range(4): data=datalist[indx]; axes[indx].plot(plotdata(0,data)[0],plotdata(0,data)[1], color='red', label='npram=1000'); axes[indx].plot(plotdata(1,data)[0],plotdata(1,data)[1], color='blue', label='npram=2000'); axes[indx].plot(plotdata(2,data)[0],plotdata(2,data)[1], color='black', label='npram=3000'); axes[indx].plot(plotdata(3,data)[0],plotdata(3,data)[1], color='green', label='npram=4000'); axes[indx].plot(plotdata(4,data)[0],plotdata(4,data)[1], color='purple', label='npram=5000'); axes[indx].plot(plotdata(5,data)[0],plotdata(5,data)[1], color='gray', label='npram=6000'); axes[indx].plot(plotdata(6,data)[0],plotdata(6,data)[1], color='black', label='npram=7000'); axes[indx].plot(plotdata(7,data)[0],plotdata(7,data)[1], color='yellow', label='npram=8000'); axes[indx].plot(plotdata(8,data)[0],plotdata(8,data)[1], color='pink', label='npram=9000'); axes[indx].set_ylim([0.003, 0.05]) axes[indx].legend(loc='upper right') axes[indx].set_title(datalistn[indx]) axes[indx].set_yscale('log',base=10) axes[indx].set_ylabel('Expressibility') from matplotlib import pyplot as plt fig.savefig('ExpressibilitybySimulator.png') fig, axes = plt.subplots(nrows=1, ncols=4, figsize=(20, 5)) indx=0 for indx in range(4): data=density_mat; axes[indx].plot(plotdata(indx,data)[0],plotdata(indx,data)[1], color='red', label='density_mat'); data=statevector1; axes[indx].plot(plotdata(indx,data)[0],plotdata(indx,data)[1], color='blue', label='statevector'); data=matrix_product1; axes[indx].plot(plotdata(indx,data)[0],plotdata(indx,data)[1], color='green', label='matrix_product1'); data=qasm; axes[indx].plot(plotdata(indx,data)[0],plotdata(indx,data)[1], color='pink', label='qasm'); axes[indx].set_title('nparam='+str((indx+1)*1000)) axes[indx].set_yscale('log',base=10) axes[indx].set_ylim([0.003, 0.05]) axes[indx].set_ylabel('Expressibility') axes[indx].legend(['density_mat','statevector','matrix_product1','qasm']) axes[indx].set_xlabel('iteration') fig.savefig('ExpressibilitybySimulatornparam1.png') fig, axes = plt.subplots(nrows=1, ncols=4, figsize=(20, 5)) indx=0 for indx1 in range(4,8,1): indx=indx1-4 data=density_mat; axes[indx].plot(plotdata(indx1,data)[0],plotdata(indx1,data)[1], color='red', label='density_mat'); data=statevector1; axes[indx].plot(plotdata(indx1,data)[0],plotdata(indx1,data)[1], color='blue', label='statevector'); data=matrix_product1; axes[indx].plot(plotdata(indx1,data)[0],plotdata(indx1,data)[1], color='green', label='matrix_product1'); data=qasm; axes[indx].plot(plotdata(indx1,data)[0],plotdata(indx1,data)[1], color='pink', label='qasm'); axes[indx].set_title('nparam='+str((indx1+1)*1000)) axes[indx].set_yscale('log',base=10) axes[indx].set_ylabel('Expressibility') axes[indx].set_ylim([0.003, 0.05]) axes[indx].legend(['density_mat','statevector','matrix_product1','qasm']) axes[indx].set_xlabel('iteration') fig.savefig('ExpressibilitybySimulatornparam2.png')
https://github.com/bagmk/Quantum_Machine_Learning_Express
bagmk
import numpy as np from sklearn.utils import shuffle import matplotlib.pyplot as plt data1Path = r'../../dataset/data0.txt' data1Label = r'../../dataset/data0label.txt' dataCoords = np.loadtxt(data1Path) dataLabels = np.loadtxt(data1Label) # Make a data structure which is easier to work with # for shuffling. # Also, notice we change the data labels from {0, 1} to {-1, +1} data = list(zip(dataCoords, 2*dataLabels-1)) shuffled_data = shuffle(data) fig = plt.figure() ax = fig.add_axes([0,0,1,1]) ax.plot(np.ravel(dataCoords[np.where(dataLabels == 0)])[::2], np.ravel(dataCoords[np.where(dataLabels == 0)])[1::2], ls='', marker='o') ax.plot(np.ravel(dataCoords[np.where(dataLabels == 1)])[::2], np.ravel(dataCoords[np.where(dataLabels == 1)])[1::2], ls='', marker='o') from IPython.display import Image import sys sys.path.append('../../Pyfiles') from circuits import * from qiskit.circuit import Parameter #circuit 1 qr = QuantumRegister(4) qc = QuantumCircuit(qr) theta=[] for i in range(62): theta.append((Parameter('θ'+str(i)))) qc=circuit1(qc,qr,theta,1,0) #load the simulation functcions from the quantumcircuit.py file from quantumcircuit import * #location,label,param,[circuit#,layer] loss_qubitF([0.5,0.5],-1,[0,0,0,-5,0,0,0,0],[0,1]) #load the SPSA optimizer from the optimizer.py file from optimizer import * c = 0.5 a = 0.5 # Do the updates lossList = [] coeffsList = [] paramsList = [] accuracyList = [] np.random.seed(2) currentParams = pi*np.random.uniform(size=8) for j in range(10): cj = c/(j+1)**(1/2) aj = a/(j+1) # Grab a subset of the data for minibatching #np.random.seed(j) np.random.seed(2) #data_ixs = np.random.choice(len(shuffled_data), size=len(shuffled_data)) data_ixs = np.random.choice(len(data), size=100) # Evaluate the loss over that subset # We include a regularization term at the end L = lambda x: np.sum([loss_qubitF(data[j][0],data[j][1],x,[0,1]) for j in data_ixs])/len(data_ixs) lossList.append(L(currentParams)) coeffsList.append((cj, aj)) paramsList.append(currentParams) accuracyList.append(np.sum([predict_qubitF(data[j][0],currentParams,[0,1]) ==data[j][1] for j in data_ixs])/len(data_ixs)) print(j,"th iteration L=",lossList[-1],"Accuracy =",accuracyList[-1]) currentParams = SPSA_update(L, currentParams, aj, cj) fig = plt.figure(figsize=(15, 10)) ax = fig.add_subplot(2, 2, 1) ax.plot(lossList) ax.set_title('Loss function\nStart {0} Finish {1}'.format(np.round(lossList[0], 3), np.round(lossList[-1], 3))) ax.set_yscale('log') ax = fig.add_subplot(2, 2, 2) ax.plot(accuracyList) ax.set_title('Classification accuracy \nStart {0} Finish {1}'.format(np.round(accuracyList[0], 3), np.round(accuracyList[-1], 3))) ax.set_yscale('log') ax = fig.add_subplot(2, 2, 3) ax.plot([c[0] for c in coeffsList], label='a') ax.plot([c[1] for c in coeffsList], label='c') ax.legend(loc=0) ax.set_title('Update coefficients') ax = fig.add_subplot(2, 2, 4) for j in range(4): ax.plot([X[j] for X in paramsList], label='x{0}'.format(j)) ax.legend(loc=0) ax.set_title('Parameter values') ax.legend(loc=0) fig = plt.figure() ax = fig.add_axes([0,0,1,1]) ax.plot(np.ravel(dataCoords[np.where(dataLabels == 0)])[::2], np.ravel(dataCoords[np.where(dataLabels == 0)])[1::2], ls='', marker='o') ax.plot(np.ravel(dataCoords[np.where(dataLabels == 1)])[::2], np.ravel(dataCoords[np.where(dataLabels == 1)])[1::2], ls='', marker='o') X = np.linspace(0, 1, num=10) Z = np.zeros((len(X), len(X))) # Contour map for j in range(len(X)): for k in range(len(X)): # Fill Z with the labels (numerical values) # the inner loop goes over the columns of Z, # which corresponds to sweeping x-values # Therefore, the role of j,k is flipped in the signature Z[j, k] = predict_qubitF( np.array([X[k], X[j]]),currentParams,[0,1]) ax.contourf(X, X, Z, cmap='bwr', levels=30) #circuit 2 qr = QuantumRegister(4) qc = QuantumCircuit(qr) theta=[] for i in range(62): theta.append((Parameter('θ'+str(i)))) qc=circuit3(qc,qr,theta,1,0) data1Path = r'../../dataset/data1a.txt' data1Label = r'../../dataset/data1alabel.txt' dataCoords = np.loadtxt(data1Path) dataLabels = np.loadtxt(data1Label) # Make a data structure which is easier to work with # for shuffling. # Also, notice we change the data labels from {0, 1} to {-1, +1} data = list(zip(dataCoords, 2*dataLabels-1)) shuffled_data = shuffle(data) fig = plt.figure() ax = fig.add_axes([0,0,1,1]) ax.plot(np.ravel(dataCoords[np.where(dataLabels == 0)])[::2], np.ravel(dataCoords[np.where(dataLabels == 0)])[1::2], ls='', marker='o') ax.plot(np.ravel(dataCoords[np.where(dataLabels == 1)])[::2], np.ravel(dataCoords[np.where(dataLabels == 1)])[1::2], ls='', marker='o') c = 1 a = 1 # Do the updates lossList = [] coeffsList = [] paramsList = [] accuracyList = [] np.random.seed(2) currentParams = pi*np.random.uniform(size=12) for j in range(10): cj = c/(j+1)**(1/2) aj = a/(j+1) # Grab a subset of the data for minibatching #np.random.seed(j) np.random.seed(3) #data_ixs = np.random.choice(len(shuffled_data), size=len(shuffled_data)) data_ixs = np.random.choice(len(data), size=100) # Evaluate the loss over that subset # We include a regularization term at the end L = lambda x: np.sum([loss_qubitF(data[j][0],data[j][1],x,[2,1]) for j in data_ixs])/len(data_ixs) lossList.append(L(currentParams)) coeffsList.append((cj, aj)) paramsList.append(currentParams) accuracyList.append(np.sum([predict_qubitF(data[j][0],currentParams,[2,1]) ==data[j][1] for j in data_ixs])/len(data_ixs)) print(j,"th iteration L=",lossList[-1],"Accuracy =",accuracyList[-1]) currentParams = SPSA_update(L, currentParams, aj, cj) fig = plt.figure(figsize=(15, 10)) ax = fig.add_subplot(2, 2, 1) ax.plot(lossList) ax.set_title('Loss function\nStart {0} Finish {1}'.format(np.round(lossList[0], 3), np.round(lossList[-1], 3))) ax.set_yscale('log') ax = fig.add_subplot(2, 2, 2) ax.plot(accuracyList) ax.set_title('Classification accuracy \nStart {0} Finish {1}'.format(np.round(accuracyList[0], 3), np.round(accuracyList[-1], 3))) ax.set_yscale('log') ax = fig.add_subplot(2, 2, 3) ax.plot([c[0] for c in coeffsList], label='a') ax.plot([c[1] for c in coeffsList], label='c') ax.legend(loc=0) ax.set_title('Update coefficients') ax = fig.add_subplot(2, 2, 4) for j in range(4): ax.plot([X[j] for X in paramsList], label='x{0}'.format(j)) ax.legend(loc=0) ax.set_title('Parameter values') ax.legend(loc=0) currentParams fig = plt.figure() ax = fig.add_axes([0,0,1,1]) ax.plot(np.ravel(dataCoords[np.where(dataLabels == 0)])[::2], np.ravel(dataCoords[np.where(dataLabels == 0)])[1::2], ls='', marker='o') ax.plot(np.ravel(dataCoords[np.where(dataLabels == 1)])[::2], np.ravel(dataCoords[np.where(dataLabels == 1)])[1::2], ls='', marker='o') X = np.linspace(0, 1, num=10) Z = np.zeros((len(X), len(X))) # Contour map for j in range(len(X)): for k in range(len(X)): # Fill Z with the labels (numerical values) # the inner loop goes over the columns of Z, # which corresponds to sweeping x-values # Therefore, the role of j,k is flipped in the signature Z[j, k] = predict_qubitF( np.array([X[k], X[j]]),currentParams,[1,1]) ax.contourf(X, X, Z, cmap='bwr', levels=30) #circuit 1 qr = QuantumRegister(4) qc = QuantumCircuit(qr) theta=[] for i in range(62): theta.append((Parameter('θ'+str(i)))) qc=circuit19(qc,qr,theta,2,0) data1Path = r'../../dataset/data2c.txt' data1Label = r'../../dataset/data2clabel.txt' dataCoords = np.loadtxt(data1Path) dataLabels = np.loadtxt(data1Label) # Make a data structure which is easier to work with # for shuffling. # Also, notice we change the data labels from {0, 1} to {-1, +1} data = list(zip(dataCoords, 2*dataLabels-1)) shuffled_data = shuffle(data) fig = plt.figure() ax = fig.add_axes([0,0,1,1]) ax.plot(np.ravel(dataCoords[np.where(dataLabels == 0)])[::2], np.ravel(dataCoords[np.where(dataLabels == 0)])[1::2], ls='', marker='o') ax.plot(np.ravel(dataCoords[np.where(dataLabels == 1)])[::2], np.ravel(dataCoords[np.where(dataLabels == 1)])[1::2], ls='', marker='o') c = 1 a = 1 # Do the updates lossList = [] coeffsList = [] paramsList = [] accuracyList = [] np.random.seed(2) currentParams = 2*np.random.uniform(size=40) for j in range(30): cj = c/(j+1)**(1/4) aj = a/(j+1) # Grab a subset of the data for minibatching #np.random.seed(j) np.random.seed(3) #data_ixs = np.random.choice(len(shuffled_data), size=len(shuffled_data)) data_ixs = np.random.choice(len(data), size=100) # Evaluate the loss over that subset # We include a regularization term at the end L = lambda x: np.sum([loss_qubitF(data[j][0],data[j][1],x,[18,2]) for j in data_ixs])/len(data_ixs) lossList.append(L(currentParams)) coeffsList.append((cj, aj)) paramsList.append(currentParams) accuracyList.append(np.sum([predict_qubitF(data[j][0],currentParams,[18,2]) ==data[j][1] for j in data_ixs])/len(data_ixs)) print(j,"th iteration L=",lossList[-1],"Accuracy =",accuracyList[-1]) currentParams = SPSA_update(L, currentParams, aj, cj) fig = plt.figure(figsize=(15, 10)) ax = fig.add_subplot(2, 2, 1) ax.plot(lossList) ax.set_title('Loss function\nStart {0} Finish {1}'.format(np.round(lossList[0], 3), np.round(lossList[-1], 3))) ax.set_yscale('log') ax = fig.add_subplot(2, 2, 2) ax.plot(accuracyList) ax.set_title('Classification accuracy \nStart {0} Finish {1}'.format(np.round(accuracyList[0], 3), np.round(accuracyList[-1], 3))) ax.set_yscale('log') ax = fig.add_subplot(2, 2, 3) ax.plot([c[0] for c in coeffsList], label='a') ax.plot([c[1] for c in coeffsList], label='c') ax.legend(loc=0) ax.set_title('Update coefficients') ax = fig.add_subplot(2, 2, 4) for j in range(4): ax.plot([X[j] for X in paramsList], label='x{0}'.format(j)) ax.legend(loc=0) ax.set_title('Parameter values') ax.legend(loc=0) fig = plt.figure() ax = fig.add_axes([0,0,1,1]) ax.plot(np.ravel(dataCoords[np.where(dataLabels == 0)])[::2], np.ravel(dataCoords[np.where(dataLabels == 0)])[1::2], ls='', marker='o') ax.plot(np.ravel(dataCoords[np.where(dataLabels == 1)])[::2], np.ravel(dataCoords[np.where(dataLabels == 1)])[1::2], ls='', marker='o') X = np.linspace(0, 1, num=10) Z = np.zeros((len(X), len(X))) # Contour map for j in range(len(X)): for k in range(len(X)): # Fill Z with the labels (numerical values) # the inner loop goes over the columns of Z, # which corresponds to sweeping x-values # Therefore, the role of j,k is flipped in the signature Z[j, k] = predict_qubitF( np.array([X[k], X[j]]),currentParams,[18,2]) ax.contourf(X, X, Z, cmap='bwr', levels=30) currentParams
https://github.com/bagmk/Quantum_Machine_Learning_Express
bagmk
The purpose of this notebook is to show how to use Qiskit's `Parameter` object to create and manipulated PQCs. import sys sys.path.append('../../Pyfiles') import qiskit qiskit.__qiskit_version__ from qiskit import QuantumCircuit, Aer from qiskit.circuit import Parameter import numpy as np from sklearn.utils import shuffle import matplotlib.pyplot as plt %matplotlib inline from optimizer import * dataID = '2a' dataPath = r'../../dataset/data{0}.txt'.format(dataID) dataLabel = r'../../dataset/data{0}label.txt'.format(dataID) dataCoords = np.loadtxt(dataPath) dataLabels = np.loadtxt(dataLabel) # Make a data structure which is easier to work with # for shuffling. # Also, notice we change the data labels from {0, 1} to {-1, +1} data = list(zip(dataCoords, 2*dataLabels-1)) shuffled_data = np.array(shuffle(data), dtype='object') fig = plt.figure() ax = fig.add_axes([0,0,1,1]) ax.plot(np.ravel(dataCoords[np.where(dataLabels == 0)])[::2], np.ravel(dataCoords[np.where(dataLabels == 0)])[1::2], ls='', marker='o') ax.plot(np.ravel(dataCoords[np.where(dataLabels == 1)])[::2], np.ravel(dataCoords[np.where(dataLabels == 1)])[1::2], ls='', marker='o') shuffled_data x0 = Parameter('x0') x1 = Parameter('x1') t0 = Parameter('t0') t1 = Parameter('t1') t2 = Parameter('t2') t3 = Parameter('t3') qc = QuantumCircuit(2) qc.rx(x0, 0) qc.rx(x1, 1) qc.ry(np.pi/4, range(qc.width())) qc.rz(np.pi/4, range(qc.width())) qc.rx(t0, 0) qc.rz(t1, 0) qc.rx(t2, 1) qc.rz(t3, 1) qc.draw() def calc_probs_from_results(counts, converter_dict): r'''Given a Qiskit `counts` object (i.e., a dictionary containing bitstrings and outcome probabilities), make an assignment to the probabilities of a +/- 1 label.''' probsPlus = 0 probsMinus = 0 for k in converter_dict.keys(): if converter_dict[k] == 1: probsPlus += counts[k] else: probsMinus += counts[k] return probsPlus, probsMinus def label_assignment(probsPlus, probsMinus): r'''Given the probabilities of +/- 1, declare the label which should be assigned''' if probsPlus > probsMinus: label = 1 elif probsMinus > probsPlus: label = -1 else: # An edge case: if the probs are equal, just return a random label label= 2*np.random.binomial(1, .5) -1 return label def prediction_loss(label, prediction): return np.abs(label - prediction) def loss(params, paramNames, dataCircuits, converter_dict): r'''Function which computes the loss. Inputs: params: The particular parameter values paramNames: The name of the parameters dataCircuits: List of partially-parameterized circuits converter_dict: A dictionary representing how to map from bitstrings to labels Outputs: The loss ''' # Bind the variables for the classifier part of the circuit fully_bound_qcs = [d.bind_parameters(dict(zip(paramNames, params)))for d in dataCircuits] # Run all the circuits job = be.run(fully_bound_qcs) # Get the counts counts = job.result().get_counts() # Now, calculate the probabilities of the +/- 1 outcome probsList = [calc_probs_from_results(C, converter_dict) for C in list(counts)] # Do the label assignment predictions_list = [label_assignment(P[0], P[1]) for P in probsList] # Calculate the loss on each data point prediction_loss_list = [prediction_loss(data[j][1], predictions_list[j]) for j in range(len(predictions_list))] # Sum it up and return return np.sum(prediction_loss_list) # Converter dictionary for 2-qubit circuit. two_q_converter_dict = {'00': 1, '01': -1, '10': -1, '11': 1} # We'll use the statevector simulator, to get the # exact outcome probabilities. be = Aer.get_backend('statevector_simulator') #load the SPSA optimizer from the optimizer.py file from optimizer import * c = 1 a = c/5 currentParams = np.random.uniform(-np.pi, np.pi, size=4) lossList = [] cList = [] aList = [] paramsList = [] for j in range(10): print(j) cj = c/(j+1)**(1/3) aj = a/(j+1) aList.append(aj) cList.append(cj) np.random.seed(j) data_ixs = np.random.choice(len(shuffled_data), size=750) data_set = shuffled_data[data_ixs] # Generate a list of circuits whose parameters are partially bound, # based on the data set. dataCircuits = [qc.bind_parameters({x0:X[0][0], x1:X[0][1]}) for X in data_set] # Use a lambda function to make a call to the loss function # where the only thing which changes is the parameter values # for the classification part of the circuit. L = lambda x: loss(x, [t0, t1, t2, t3], dataCircuits, two_q_converter_dict) lossList.append(L(currentParams)) # Update the parameters currentParams = SPSA_update(L, currentParams, aj, cj) paramsList.append(currentParams) lossList.append(L(currentParams)) fig = plt.figure(figsize=(15, 10)) ax = fig.add_subplot(2, 2, 1) ax.plot(lossList) ax = fig.add_subplot(2, 2, 2) ax.plot(aList, label='a') ax.plot(cList, label='c') ax.legend(loc=0) ax.set_yscale('log') ax = fig.add_subplot(2, 2, 4) for j in range(len(paramsList[0])): ax.plot([p[j] for p in paramsList], label='t{0}'.format(j)) ax.legend(loc=0)
https://github.com/bagmk/Quantum_Machine_Learning_Express
bagmk
import numpy as np import matplotlib.pyplot as plt from sklearn.utils import shuffle %matplotlib inline def SPSA_gradient(loss, currentParams, gradientCoefficient): r'''Computes an estimator of the gradient using the procedure described in the SPSA algorithm. Inputs: loss: The loss function currentParams: The current value for the parameters gradientCoefficient: The coefficient c_n, which controls how much the current parameters are perturbed when computing the gradient Returns: gradient: The SPSA-based gradient of the loss function at currentParams''' numParams = len(currentParams) # Generate a random perturbation using the Rademacher distribution randomPerturbation = 2*np.random.binomial(1, .5, size=numParams) - 1 gradient = (loss(currentParams + gradientCoefficient*randomPerturbation) - loss(currentParams - gradientCoefficient*randomPerturbation))\ /(gradientCoefficient*randomPerturbation) return gradient def SPSA_update(loss, currentParams, updateCoefficient, gradientCoefficient): r'''Performs a parameter update according to the SPSA approach. NOTE: This function isn't aware of the notion of iterations, or anything of that sort. Inputs: loss: The loss function currentParams: The current value for the parameters updateCoefficient: The coefficient a_n, which controls how the current parameters are updated when including the gradient gradientCoefficient: The coefficient c_n, which controls how much the current parameters are perturbed when computing the gradient Returns: The updated parameter values''' grad = SPSA_gradient(loss, currentParams, gradientCoefficient) return currentParams - updateCoefficient*grad def loss(x): r'''Compute the loss''' return np.linalg.norm(x - np.ones_like(x)) c = 2 a = 1 # Make some lists to keep track of things lossList = [] coeffsList = [] paramsList = [] # Set starting values for the parameters np.random.seed(0) currentParams = np.random.uniform(size=4) # Do the updates for j in range(50): cj = c/(j+1)**.5 aj = a/(j+1) lossList.append(loss(currentParams)) coeffsList.append((cj, aj)) paramsList.append(currentParams) currentParams = SPSA_update(loss, currentParams, aj, cj) fig = plt.figure(figsize=(15, 5)) ax = fig.add_subplot(1, 3, 1) ax.plot(lossList) ax.set_title('Value of the Loss') ax = fig.add_subplot(1, 3, 2) ax.plot([X[0] for X in coeffsList], label='c') ax.plot([X[1] for X in coeffsList], label='a') ax.set_title('Update Coefficients') ax.legend(loc=0) ax = fig.add_subplot(1, 3, 3) for j in range(4): ax.plot([X[j] for X in paramsList], label='x{0}'.format(j)) ax.legend(loc=0) ax.set_title('Parameter values') data1Path = r'../../dataset/data1a.txt' data1Label = r'../../dataset/data1alabel.txt' dataCoords = np.loadtxt(data1Path) dataLabels = np.loadtxt(data1Label) fig = plt.figure() ax = fig.add_axes([0,0,1,1]) ax.plot(np.ravel(dataCoords[np.where(dataLabels == 0)])[::2], np.ravel(dataCoords[np.where(dataLabels == 0)])[1::2], ls='', marker='o') ax.plot(np.ravel(dataCoords[np.where(dataLabels == 1)])[::2], np.ravel(dataCoords[np.where(dataLabels == 1)])[1::2], ls='', marker='o') def value(x, dataPoint): r'''Returns the value assigned to a datapoint by the SVM''' return np.dot(x[:2], dataPoint) - x[2] def loss(x, dataPoint, dataLabel): r'''The loss function we'll use is the hinge loss''' return max(0, 1-dataLabel*value(x, dataPoint)) # Make a data structure which is easier to work with # for shuffling. # Also, notice we change the data labels from {0, 1} to {-1, +1} data = list(zip(dataCoords, 2*dataLabels-1)) shuffled_data = shuffle(data) c = 5 a = 1 # Make some lists to keep track of things lossList = [] coeffsList = [] paramsList =[] accuracyList = [] # Set starting values for the parameters np.random.seed(2) currentParams = np.random.uniform(size=3) # Do the updates for j in range(10): cj = c/(j+1)**.5 aj = a/(j+1) # Grab a subset of the data for minibatching np.random.seed(j) data_ixs = np.random.choice(len(shuffled_data), size=len(shuffled_data)) # Evaluate the loss over that subset # We include a regularization term at the end L = lambda x: np.sum([loss(x, shuffled_data[j][0], shuffled_data[j][1]) for j in data_ixs])/len(data_ixs) + .05*np.linalg.norm(x[:2])**2 lossList.append(L(currentParams)) coeffsList.append((cj, aj)) paramsList.append(currentParams) accuracyList.append(np.sum([np.sign(value(currentParams,d[0])) == d[1] for d in data])/len(data)) currentParams = SPSA_update(L, currentParams, aj, cj) fig = plt.figure(figsize=(15, 10)) ax = fig.add_subplot(2, 2, 1) ax.plot(lossList) ax.set_title('Loss function\nStart {0} Finish {1}'.format(np.round(lossList[0], 3), np.round(lossList[-1], 3))) ax.set_yscale('log') ax = fig.add_subplot(2, 2, 2) ax.plot(accuracyList) ax.set_title('Classification accuracy \nStart {0} Finish {1}'.format(np.round(accuracyList[0], 3), np.round(accuracyList[-1], 3))) ax.set_yscale('log') ax = fig.add_subplot(2, 2, 3) ax.plot([c[0] for c in coeffsList], label='a') ax.plot([c[1] for c in coeffsList], label='c') ax.legend(loc=0) ax.set_title('Update coefficients') ax = fig.add_subplot(2, 2, 4) ax.plot([c[0] for c in paramsList], label='x') ax.plot([c[1] for c in paramsList], label='y') ax.plot([c[2] for c in paramsList], label='b') ax.set_yscale('log') ax.set_title('Model coefficients') ax.legend(loc=0) # A quick evaluation of the accuracy np.sum([np.sign(value(currentParams,d[0])) == d[1] for d in data])/len(data) fig = plt.figure() ax = fig.add_axes([0,0,1,1]) ax.plot(np.ravel(dataCoords[np.where(dataLabels == 0)])[::2], np.ravel(dataCoords[np.where(dataLabels == 0)])[1::2], ls='', marker='o') ax.plot(np.ravel(dataCoords[np.where(dataLabels == 1)])[::2], np.ravel(dataCoords[np.where(dataLabels == 1)])[1::2], ls='', marker='o') X = np.linspace(0, 1, num=100) Z = np.zeros((len(X), len(X))) # Contour map for j in range(len(X)): for k in range(len(X)): # Fill Z with the labels (numerical values) # the inner loop goes over the columns of Z, # which corresponds to sweeping x-values # Therefore, the role of j,k is flipped in the signature Z[j, k] = value(currentParams, np.array([X[k], X[j]])) ax.contourf(X, X, Z, cmap='bwr', levels=30)
https://github.com/bagmk/Quantum_Machine_Learning_Express
bagmk
import sys sys.path.append('../../Pyfiles') import numpy as np from sklearn.utils import shuffle import matplotlib.pyplot as plt data1Path = r'../../dataset/data0test.txt' data1Label = r'../../dataset/data0testlabel.txt' dataCoords = np.loadtxt(data1Path) dataLabels = np.loadtxt(data1Label) # Make a data structure which is easier to work with # for shuffling. # Also, notice we change the data labels from {0, 1} to {-1, +1} data = list(zip(dataCoords, 2*dataLabels-1)) shuffled_data = shuffle(data) fig = plt.figure() ax = fig.add_axes([0,0,1,1]) ax.plot(np.ravel(dataCoords[np.where(dataLabels == 0)])[::2], np.ravel(dataCoords[np.where(dataLabels == 0)])[1::2], ls='', marker='o') ax.plot(np.ravel(dataCoords[np.where(dataLabels == 1)])[::2], np.ravel(dataCoords[np.where(dataLabels == 1)])[1::2], ls='', marker='o') from IPython.display import Image from circuits import * from qiskit.circuit import Parameter #circuit 1 qr = QuantumRegister(4) qc = QuantumCircuit(qr) theta=[] for i in range(62): theta.append((Parameter('θ'+str(i)))) qc=circuit1(qc,qr,theta,1,0) qc.draw('mpl') #load the simulation functcions from the quantumcircuit.py file from quantumcircuit import * #location,label,param,[circuit#,layer] loss_qubitF([0.5,0.5],-1,[0,0,0,-5,0,0,0,0],[0,1]) #load the SPSA optimizer from the optimizer.py file from optimizer import * c = 0.5 a = 0.5 # Do the updates lossList = [] coeffsList = [] paramsList = [] accuracyList = [] np.random.seed(2) currentParams = pi*np.random.uniform(size=8) for j in range(10): cj = c/(j+1)**(1/2) aj = a/(j+1) # Grab a subset of the data for minibatching #np.random.seed(j) np.random.seed(2) #data_ixs = np.random.choice(len(shuffled_data), size=len(shuffled_data)) data_ixs = np.random.choice(len(data), size=100) # Evaluate the loss over that subset # We include a regularization term at the end L = lambda x: np.sum([loss_qubitF(data[j][0],data[j][1],x,[0,1]) for j in data_ixs])/len(data_ixs) lossList.append(L(currentParams)) coeffsList.append((cj, aj)) paramsList.append(currentParams) accuracyList.append(np.sum([predict_qubitF(data[j][0],currentParams,[0,1]) ==data[j][1] for j in data_ixs])/len(data_ixs)) print(j,"th iteration L=",lossList[-1],"Accuracy =",accuracyList[-1]) currentParams = SPSA_update(L, currentParams, aj, cj) fig = plt.figure(figsize=(15, 10)) ax = fig.add_subplot(2, 2, 1) ax.plot(lossList) ax.set_title('Loss function\nStart {0} Finish {1}'.format(np.round(lossList[0], 3), np.round(lossList[-1], 3))) ax.set_yscale('log') ax = fig.add_subplot(2, 2, 2) ax.plot(accuracyList) ax.set_title('Classification accuracy \nStart {0} Finish {1}'.format(np.round(accuracyList[0], 3), np.round(accuracyList[-1], 3))) ax.set_yscale('log') ax = fig.add_subplot(2, 2, 3) ax.plot([c[0] for c in coeffsList], label='a') ax.plot([c[1] for c in coeffsList], label='c') ax.legend(loc=0) ax.set_title('Update coefficients') ax = fig.add_subplot(2, 2, 4) for j in range(4): ax.plot([X[j] for X in paramsList], label='x{0}'.format(j)) ax.legend(loc=0) ax.set_title('Parameter values') ax.legend(loc=0) fig = plt.figure() ax = fig.add_axes([0,0,1,1]) ax.plot(np.ravel(dataCoords[np.where(dataLabels == 0)])[::2], np.ravel(dataCoords[np.where(dataLabels == 0)])[1::2], ls='', marker='o') ax.plot(np.ravel(dataCoords[np.where(dataLabels == 1)])[::2], np.ravel(dataCoords[np.where(dataLabels == 1)])[1::2], ls='', marker='o') X = np.linspace(0, 1, num=10) Z = np.zeros((len(X), len(X))) # Contour map for j in range(len(X)): for k in range(len(X)): # Fill Z with the labels (numerical values) # the inner loop goes over the columns of Z, # which corresponds to sweeping x-values # Therefore, the role of j,k is flipped in the signature Z[j, k] = predict_qubitF( np.array([X[k], X[j]]),currentParams,[0,1]) ax.contourf(X, X, Z, cmap='bwr', levels=30) #circuit 2 qr = QuantumRegister(4) qc = QuantumCircuit(qr) theta=[] for i in range(62): theta.append((Parameter('θ'+str(i)))) qc=circuit3(qc,qr,theta,1,0) qc.draw('mpl') data1Path = r'../../dataset/data1a.txt' data1Label = r'../../dataset/data1alabel.txt' dataCoords = np.loadtxt(data1Path) dataLabels = np.loadtxt(data1Label) # Make a data structure which is easier to work with # for shuffling. # Also, notice we change the data labels from {0, 1} to {-1, +1} data = list(zip(dataCoords, 2*dataLabels-1)) shuffled_data = shuffle(data) fig = plt.figure() ax = fig.add_axes([0,0,1,1]) ax.plot(np.ravel(dataCoords[np.where(dataLabels == 0)])[::2], np.ravel(dataCoords[np.where(dataLabels == 0)])[1::2], ls='', marker='o') ax.plot(np.ravel(dataCoords[np.where(dataLabels == 1)])[::2], np.ravel(dataCoords[np.where(dataLabels == 1)])[1::2], ls='', marker='o') c = 1 a = 1 # Do the updates lossList = [] coeffsList = [] paramsList = [] accuracyList = [] np.random.seed(2) currentParams = pi*np.random.uniform(size=12) for j in range(10): cj = c/(j+1)**(1/2) aj = a/(j+1) # Grab a subset of the data for minibatching #np.random.seed(j) np.random.seed(3) #data_ixs = np.random.choice(len(shuffled_data), size=len(shuffled_data)) data_ixs = np.random.choice(len(data), size=100) # Evaluate the loss over that subset # We include a regularization term at the end L = lambda x: np.sum([loss_qubitF(data[j][0],data[j][1],x,[2,1]) for j in data_ixs])/len(data_ixs) lossList.append(L(currentParams)) coeffsList.append((cj, aj)) paramsList.append(currentParams) accuracyList.append(np.sum([predict_qubitF(data[j][0],currentParams,[2,1]) ==data[j][1] for j in data_ixs])/len(data_ixs)) print(j,"th iteration L=",lossList[-1],"Accuracy =",accuracyList[-1]) currentParams = SPSA_update(L, currentParams, aj, cj) fig = plt.figure(figsize=(15, 10)) ax = fig.add_subplot(2, 2, 1) ax.plot(lossList) ax.set_title('Loss function\nStart {0} Finish {1}'.format(np.round(lossList[0], 3), np.round(lossList[-1], 3))) ax.set_yscale('log') ax = fig.add_subplot(2, 2, 2) ax.plot(accuracyList) ax.set_title('Classification accuracy \nStart {0} Finish {1}'.format(np.round(accuracyList[0], 3), np.round(accuracyList[-1], 3))) ax.set_yscale('log') ax = fig.add_subplot(2, 2, 3) ax.plot([c[0] for c in coeffsList], label='a') ax.plot([c[1] for c in coeffsList], label='c') ax.legend(loc=0) ax.set_title('Update coefficients') ax = fig.add_subplot(2, 2, 4) for j in range(4): ax.plot([X[j] for X in paramsList], label='x{0}'.format(j)) ax.legend(loc=0) ax.set_title('Parameter values') ax.legend(loc=0) currentParams fig = plt.figure() ax = fig.add_axes([0,0,1,1]) ax.plot(np.ravel(dataCoords[np.where(dataLabels == 0)])[::2], np.ravel(dataCoords[np.where(dataLabels == 0)])[1::2], ls='', marker='o') ax.plot(np.ravel(dataCoords[np.where(dataLabels == 1)])[::2], np.ravel(dataCoords[np.where(dataLabels == 1)])[1::2], ls='', marker='o') X = np.linspace(0, 1, num=10) Z = np.zeros((len(X), len(X))) # Contour map for j in range(len(X)): for k in range(len(X)): # Fill Z with the labels (numerical values) # the inner loop goes over the columns of Z, # which corresponds to sweeping x-values # Therefore, the role of j,k is flipped in the signature Z[j, k] = predict_qubitF( np.array([X[k], X[j]]),currentParams,[1,1]) ax.contourf(X, X, Z, cmap='bwr', levels=30) #circuit 1 qr = QuantumRegister(4) qc = QuantumCircuit(qr) theta=[] for i in range(62): theta.append((Parameter('θ'+str(i)))) qc=circuit19(qc,qr,theta,2,0) qc.draw('mpl') data1Path = r'../../dataset/data2c.txt' data1Label = r'../../dataset/data2clabel.txt' dataCoords = np.loadtxt(data1Path) dataLabels = np.loadtxt(data1Label) # Make a data structure which is easier to work with # for shuffling. # Also, notice we change the data labels from {0, 1} to {-1, +1} data = list(zip(dataCoords, 2*dataLabels-1)) shuffled_data = shuffle(data) fig = plt.figure() ax = fig.add_axes([0,0,1,1]) ax.plot(np.ravel(dataCoords[np.where(dataLabels == 0)])[::2], np.ravel(dataCoords[np.where(dataLabels == 0)])[1::2], ls='', marker='o') ax.plot(np.ravel(dataCoords[np.where(dataLabels == 1)])[::2], np.ravel(dataCoords[np.where(dataLabels == 1)])[1::2], ls='', marker='o') c = 1 a = 1 # Do the updates lossList = [] coeffsList = [] paramsList = [] accuracyList = [] np.random.seed(2) currentParams = 2*np.random.uniform(size=40) for j in range(30): cj = c/(j+1)**(1/4) aj = a/(j+1) # Grab a subset of the data for minibatching #np.random.seed(j) np.random.seed(3) #data_ixs = np.random.choice(len(shuffled_data), size=len(shuffled_data)) data_ixs = np.random.choice(len(data), size=100) # Evaluate the loss over that subset # We include a regularization term at the end L = lambda x: np.sum([loss_qubitF(data[j][0],data[j][1],x,[18,2]) for j in data_ixs])/len(data_ixs) lossList.append(L(currentParams)) coeffsList.append((cj, aj)) paramsList.append(currentParams) accuracyList.append(np.sum([predict_qubitF(data[j][0],currentParams,[18,2]) ==data[j][1] for j in data_ixs])/len(data_ixs)) print(j,"th iteration L=",lossList[-1],"Accuracy =",accuracyList[-1]) currentParams = SPSA_update(L, currentParams, aj, cj) fig = plt.figure(figsize=(15, 10)) ax = fig.add_subplot(2, 2, 1) ax.plot(lossList) ax.set_title('Loss function\nStart {0} Finish {1}'.format(np.round(lossList[0], 3), np.round(lossList[-1], 3))) ax.set_yscale('log') ax = fig.add_subplot(2, 2, 2) ax.plot(accuracyList) ax.set_title('Classification accuracy \nStart {0} Finish {1}'.format(np.round(accuracyList[0], 3), np.round(accuracyList[-1], 3))) ax.set_yscale('log') ax = fig.add_subplot(2, 2, 3) ax.plot([c[0] for c in coeffsList], label='a') ax.plot([c[1] for c in coeffsList], label='c') ax.legend(loc=0) ax.set_title('Update coefficients') ax = fig.add_subplot(2, 2, 4) for j in range(4): ax.plot([X[j] for X in paramsList], label='x{0}'.format(j)) ax.legend(loc=0) ax.set_title('Parameter values') ax.legend(loc=0) fig = plt.figure() ax = fig.add_axes([0,0,1,1]) ax.plot(np.ravel(dataCoords[np.where(dataLabels == 0)])[::2], np.ravel(dataCoords[np.where(dataLabels == 0)])[1::2], ls='', marker='o') ax.plot(np.ravel(dataCoords[np.where(dataLabels == 1)])[::2], np.ravel(dataCoords[np.where(dataLabels == 1)])[1::2], ls='', marker='o') X = np.linspace(0, 1, num=10) Z = np.zeros((len(X), len(X))) # Contour map for j in range(len(X)): for k in range(len(X)): # Fill Z with the labels (numerical values) # the inner loop goes over the columns of Z, # which corresponds to sweeping x-values # Therefore, the role of j,k is flipped in the signature Z[j, k] = predict_qubitF( np.array([X[k], X[j]]),currentParams,[18,2]) ax.contourf(X, X, Z, cmap='bwr', levels=30) currentParams
https://github.com/bagmk/Quantum_Machine_Learning_Express
bagmk
# The code below is a hack in case Travis' kernel fails. #import os #os.environ['KMP_DUPLICATE_LIB_OK'] ='True' import sys sys.path.append('../../Pyfiles') # Pull in the helper files. from experiments import * # Set up the experiment circuitID = 1 epochs = 20 import numpy as np import sys np.set_printoptions(threshold=sys.maxsize) lr_list=[round(((i+1)/10)**2,2) for i in range(20)] ds_list=['0','1a','2a','3c'] for dsID in ds_list: # Run the experiment print('--------dataset',dsID,'is initialized------') lr_acc=[] for lr in lr_list: # Load in the data data = load_data(dsID) # Generate the splittings train_X, train_y, validate_X, validate_y, test_X, test_y = generate_train_validate_test_data(data) # Make the feature map feature_map= make_embedding_circuit() # Make the classifier ansatz = make_classifer_circuit(circuitID) # Do the training model = train_model(feature_map, ansatz, epochs, lr, train_X, train_y) # Check the validation accuracy. val_accuracy = check_accuracy(model, validate_X, validate_y) lr_acc.append([lr,val_accuracy]) np.savetxt(r"Learning_Rate_Data\circuit{0}_data{1}.txt".format(circuitID,dsID),lr_acc,fmt='%.2f') # Set up the experiment circuitID = 1 epochs = 20 ds_list=['0','1a','2a','3c'] #selected learning rates lr_opt=[3.24,2.89,0.36,3.24] model_list=[] for i in range(4): data = load_data(ds_list[i]) # Generate the splittings train_X, train_y, validate_X, validate_y, test_X, test_y = generate_train_validate_test_data(data) # Make the feature map feature_map= make_embedding_circuit() # Make the classifier ansatz = make_classifer_circuit(circuitID) # Do the training model = train_model(feature_map, ansatz, epochs, lr_opt[i], train_X, train_y) model_list.append(model) # Check the validation accuracy. val_accuracy = check_accuracy(model, test_X, test_y) import matplotlib.pyplot as plt for lr in range(4): data = load_data(ds_list[lr]) # Generate the splittings train_X, train_y, validate_X, validate_y, test_X, test_y = generate_train_validate_test_data(data) fig = plt.figure(figsize=(15, 10)) ax = fig.add_subplot(4, 2, 2*lr+1) y_predict = [] for x in test_X: output = model_list[lr](Tensor(x)) y_predict += [np.argmax(output.detach().numpy())] print(check_accuracy(model_list[lr], test_X, test_y)) # plot results # red == wrongly classified for x, y_target, y_ in zip(test_X, test_y, y_predict): if y_target == 1: ax.plot(x[0], x[1], 'bo') else: ax.plot(x[0], x[1], 'go') if y_target != y_: ax.scatter(x[0], x[1], s=200, facecolors='none', edgecolors='r', linewidths=2) ax = fig.add_subplot(4, 2, 2*lr+2) for x, y_target, y_ in zip(test_X, test_y, y_predict): if y_target == 1: ax.plot(x[0], x[1], 'bo') else: ax.plot(x[0], x[1], 'go') X1 = np.linspace(0, 1, num=10) Z1 = np.zeros((len(X1), len(X1))) # Contour map for j in range(len(X1)): for k in range(len(X1)): # Fill Z with the labels (numerical values) # the inner loop goes over the columns of Z, # which corresponds to sweeping x-values # Therefore, the role of j,k is flipped in the signature Z1[j, k] = np.argmax(model_list[lr](Tensor([X1[k],X1[j],X1[k],X1[j]])).detach().numpy()) ax.contourf(X1, X1, Z1, cmap='bwr', levels=30)
https://github.com/bagmk/Quantum_Machine_Learning_Express
bagmk
# The code below is a hack in case Travis' kernel fails. #import os #os.environ['KMP_DUPLICATE_LIB_OK'] ='True' # Pull in the helper files. import sys sys.path.append('../../Pyfiles') # Pull in the helper files. from experiments import * # Set up the experiment circuitID = 14 epochs = 20 import numpy as np import sys np.set_printoptions(threshold=sys.maxsize) lr_list=[round(((i+1)/10)**2,2) for i in range(20)] ds_list=['0','1a','2a','3c'] for dsID in ds_list: # Run the experiment print('--------dataset',dsID,'is initialized------') lr_acc=[] for lr in lr_list: # Load in the data data = load_data(dsID) # Generate the splittings train_X, train_y, validate_X, validate_y, test_X, test_y = generate_train_validate_test_data(data) # Make the feature map feature_map= make_embedding_circuit() # Make the classifier ansatz = make_classifer_circuit(circuitID) # Do the training model = train_model(feature_map, ansatz, epochs, lr, train_X, train_y) # Check the validation accuracy. val_accuracy = check_accuracy(model, validate_X, validate_y) lr_acc.append([lr,val_accuracy]) np.savetxt(r"Learning_Rate_Data\circuit{0}_data{1}.txt".format(circuitID,dsID),lr_acc,fmt='%.2f') # Set up the experiment circuitID = 14 epochs = 20 ds_list=['0','1a','2a','3c'] #selected learning rates lr_opt=[0.01,3.61,0.04,0.25] model_list=[] for i in range(4): data = load_data(ds_list[i]) # Generate the splittings train_X, train_y, validate_X, validate_y, test_X, test_y = generate_train_validate_test_data(data) # Make the feature map feature_map= make_embedding_circuit() # Make the classifier ansatz = make_classifer_circuit(circuitID) # Do the training model = train_model(feature_map, ansatz, epochs, lr_opt[i], train_X, train_y) model_list.append(model) # Check the validation accuracy. val_accuracy = check_accuracy(model, test_X, test_y) import matplotlib.pyplot as plt for lr in range(4): data = load_data(ds_list[lr]) # Generate the splittings train_X, train_y, validate_X, validate_y, test_X, test_y = generate_train_validate_test_data(data) fig = plt.figure(figsize=(15, 10)) ax = fig.add_subplot(4, 2, 2*lr+1) y_predict = [] for x in test_X: output = model_list[lr](Tensor(x)) y_predict += [np.argmax(output.detach().numpy())] print(check_accuracy(model_list[lr], test_X, test_y)) # plot results # red == wrongly classified for x, y_target, y_ in zip(test_X, test_y, y_predict): if y_target == 1: ax.plot(x[0], x[1], 'bo') else: ax.plot(x[0], x[1], 'go') if y_target != y_: ax.scatter(x[0], x[1], s=200, facecolors='none', edgecolors='r', linewidths=2) ax = fig.add_subplot(4, 2, 2*lr+2) for x, y_target, y_ in zip(test_X, test_y, y_predict): if y_target == 1: ax.plot(x[0], x[1], 'bo') else: ax.plot(x[0], x[1], 'go') X1 = np.linspace(0, 1, num=10) Z1 = np.zeros((len(X1), len(X1))) # Contour map for j in range(len(X1)): for k in range(len(X1)): # Fill Z with the labels (numerical values) # the inner loop goes over the columns of Z, # which corresponds to sweeping x-values # Therefore, the role of j,k is flipped in the signature Z1[j, k] = np.argmax(model_list[lr](Tensor([X1[k],X1[j],X1[k],X1[j]])).detach().numpy()) ax.contourf(X1, X1, Z1, cmap='bwr', levels=30)
https://github.com/bagmk/Quantum_Machine_Learning_Express
bagmk
# The code below is a hack in case Travis' kernel fails. #import os #os.environ['KMP_DUPLICATE_LIB_OK'] ='True' # Pull in the helper files. import sys sys.path.append('../../Pyfiles') # Pull in the helper files. from experiments import * # Set up the experiment circuitID = 6 epochs = 20 import numpy as np import sys np.set_printoptions(threshold=sys.maxsize) lr_list=[round(((i+1)/10)**2,2) for i in range(20)] ds_list=['0','1a','2a','3c'] for dsID in ds_list: # Run the experiment print('--------dataset',dsID,'is initialized------') lr_acc=[] for lr in lr_list: # Load in the data data = load_data(dsID) # Generate the splittings train_X, train_y, validate_X, validate_y, test_X, test_y = generate_train_validate_test_data(data) # Make the feature map feature_map= make_embedding_circuit() # Make the classifier ansatz = make_classifer_circuit(circuitID) # Do the training model = train_model(feature_map, ansatz, epochs, lr, train_X, train_y) # Check the validation accuracy. val_accuracy = check_accuracy(model, validate_X, validate_y) lr_acc.append([lr,val_accuracy]) np.savetxt(r"Learning_Rate_Data\circuit{0}_data{1}.txt".format(circuitID,dsID),lr_acc,fmt='%.2f') import numpy as np import sys np.set_printoptions(threshold=sys.maxsize) lr_list=[round(((i+1)/10)**2,2) for i in range(20)] dsID='3c' print('--------dataset',dsID,'is initialized------') lr_acc=[] for lr in lr_list: # Load in the data data = load_data(dsID) # Generate the splittings train_X, train_y, validate_X, validate_y, test_X, test_y = generate_train_validate_test_data(data) # Make the feature map feature_map= make_embedding_circuit() # Make the classifier ansatz = make_classifer_circuit(circuitID) # Do the training model = train_model(feature_map, ansatz, epochs, lr, train_X, train_y) # Check the validation accuracy. val_accuracy = check_accuracy(model, validate_X, validate_y) lr_acc.append([lr,val_accuracy]) np.savetxt(r"Learning_Rate_Data\circuit{0}_data{1}.txt".format(circuitID,dsID),lr_acc,fmt='%.2f') # Set up the experiment circuitID = 6 epochs = 20 ds_list=['0','1a','2a','3c'] #selected learning rates lr_opt=[0.25,0.25,0.25,0.81] model_list=[] for i in range(4): data = load_data(ds_list[i]) # Generate the splittings train_X, train_y, validate_X, validate_y, test_X, test_y = generate_train_validate_test_data(data) # Make the feature map feature_map= make_embedding_circuit() # Make the classifier ansatz = make_classifer_circuit(circuitID) # Do the training model = train_model(feature_map, ansatz, epochs, lr_opt[i], train_X, train_y) model_list.append(model) import matplotlib.pyplot as plt for lr in range(4): \ data = load_data(ds_list[lr]) # Generate the splittings train_X, train_y, validate_X, validate_y, test_X, test_y = generate_train_validate_test_data(data) fig = plt.figure(figsize=(15, 10)) ax = fig.add_subplot(4, 2, 2*lr+1) y_predict = [] for x in test_X: output = model_list[lr](Tensor(x)) y_predict += [np.argmax(output.detach().numpy())] print(check_accuracy(model_list[lr], test_X, test_y)) # plot results # red == wrongly classified for x, y_target, y_ in zip(test_X, test_y, y_predict): if y_target == 1: ax.plot(x[0], x[1], 'bo') else: ax.plot(x[0], x[1], 'go') if y_target != y_: ax.scatter(x[0], x[1], s=200, facecolors='none', edgecolors='r', linewidths=2) ax = fig.add_subplot(4, 2, 2*lr+2) for x, y_target, y_ in zip(test_X, test_y, y_predict): if y_target == 1: ax.plot(x[0], x[1], 'bo') else: ax.plot(x[0], x[1], 'go') X1 = np.linspace(0, 1, num=10) Z1 = np.zeros((len(X1), len(X1))) # Contour map for j in range(len(X1)): for k in range(len(X1)): # Fill Z with the labels (numerical values) # the inner loop goes over the columns of Z, # which corresponds to sweeping x-values # Therefore, the role of j,k is flipped in the signature Z1[j, k] = np.argmax(model_list[lr](Tensor([X1[k],X1[j],X1[k],X1[j]])).detach().numpy()) ax.contourf(X1, X1, Z1, cmap='bwr', levels=30)
https://github.com/bagmk/Quantum_Machine_Learning_Express
bagmk
# The code below is a hack in case Travis' kernel fails. #import os #os.environ['KMP_DUPLICATE_LIB_OK'] ='True' # Pull in the helper files. import sys sys.path.append('../../Pyfiles') # Pull in the helper files. from experiments import * # Set up the experiment circuitID = 9 epochs = 20 import numpy as np import sys np.set_printoptions(threshold=sys.maxsize) lr_list=[round(((i+1)/10)**2,2) for i in range(20)] ds_list=['0','1a','2a','3c'] for dsID in ds_list: # Run the experiment print('--------dataset',dsID,'is initialized------') lr_acc=[] for lr in lr_list: # Load in the data data = load_data(dsID) # Generate the splittings train_X, train_y, validate_X, validate_y, test_X, test_y = generate_train_validate_test_data(data) # Make the feature map feature_map= make_embedding_circuit() # Make the classifier ansatz = make_classifer_circuit(circuitID) # Do the training model = train_model(feature_map, ansatz, epochs, lr, train_X, train_y) # Check the validation accuracy. val_accuracy = check_accuracy(model, validate_X, validate_y) lr_acc.append([lr,val_accuracy]) np.savetxt(r"Learning_Rate_Data\circuit{0}_data{1}.txt".format(circuitID,dsID),lr_acc,fmt='%.2f') import numpy import sys numpy.set_printoptions(threshold=sys.maxsize) lr_list=[round(((i+1)/10)**2,2) for i in range(20)] # Run the experiment lr_acc=[] for lr in lr_list: # Load in the data data = load_data('0') # Generate the splittings train_X, train_y, validate_X, validate_y, test_X, test_y = generate_train_validate_test_data(data) # Make the feature map feature_map= make_embedding_circuit() # Make the classifier ansatz = make_classifer_circuit(circuitID) # Do the training model = train_model(feature_map, ansatz, epochs, lr, train_X, train_y) # Check the validation accuracy. val_accuracy = check_accuracy(model, validate_X, validate_y) lr_acc.append([lr,val_accuracy]) np.savetxt(r"Learning_Rate_Data\circuit{0}_data{1}.txt".format(circuitID,dsID),lr_acc,fmt='%.2f') # Set up the experiment circuitID = 9 epochs = 20 ds_list=['0','1a','2a','3c'] #selected learning rates lr_opt=[2.89,0.16,0.09,2.25] model_list=[] for i in range(4): data = load_data(ds_list[i]) # Generate the splittings train_X, train_y, validate_X, validate_y, test_X, test_y = generate_train_validate_test_data(data) # Make the feature map feature_map= make_embedding_circuit() # Make the classifier ansatz = make_classifer_circuit(circuitID) # Do the training model = train_model(feature_map, ansatz, epochs, lr_opt[i], train_X, train_y) model_list.append(model) # Check the validation accuracy. val_accuracy = check_accuracy(model, test_X, test_y) import matplotlib.pyplot as plt for lr in range(4): data = load_data(ds_list[lr]) # Generate the splittings train_X, train_y, validate_X, validate_y, test_X, test_y = generate_train_validate_test_data(data) fig = plt.figure(figsize=(15, 10)) ax = fig.add_subplot(4, 2, 2*lr+1) y_predict = [] for x in test_X: output = model_list[lr](Tensor(x)) y_predict += [np.argmax(output.detach().numpy())] print(check_accuracy(model_list[lr], test_X, test_y)) # plot results # red == wrongly classified for x, y_target, y_ in zip(test_X, test_y, y_predict): if y_target == 1: ax.plot(x[0], x[1], 'bo') else: ax.plot(x[0], x[1], 'go') if y_target != y_: ax.scatter(x[0], x[1], s=200, facecolors='none', edgecolors='r', linewidths=2) ax = fig.add_subplot(4, 2, 2*lr+2) for x, y_target, y_ in zip(test_X, test_y, y_predict): if y_target == 1: ax.plot(x[0], x[1], 'bo') else: ax.plot(x[0], x[1], 'go') X1 = np.linspace(0, 1, num=10) Z1 = np.zeros((len(X1), len(X1))) # Contour map for j in range(len(X1)): for k in range(len(X1)): # Fill Z with the labels (numerical values) # the inner loop goes over the columns of Z, # which corresponds to sweeping x-values # Therefore, the role of j,k is flipped in the signature Z1[j, k] = np.argmax(model_list[lr](Tensor([X1[k],X1[j],X1[k],X1[j]])).detach().numpy()) ax.contourf(X1, X1, Z1, cmap='bwr', levels=30)
https://github.com/bagmk/Quantum_Machine_Learning_Express
bagmk
import qiskit from qiskit import Aer, QuantumCircuit from qiskit.utils import QuantumInstance from qiskit.opflow import AerPauliExpectation from qiskit.circuit import Parameter from qiskit_machine_learning.neural_networks import CircuitQNN from qiskit_machine_learning.connectors import TorchConnector qi = QuantumInstance(Aer.get_backend('statevector_simulator')) qiskit.__qiskit_version__ import numpy as np from numpy import pi import matplotlib.pyplot as plt from sklearn.utils import shuffle from pandas.core.common import flatten import torch from torch import Tensor from torch.nn import Linear, CrossEntropyLoss, MSELoss from torch.optim import LBFGS, SGD,Adam import torch.optim as optim torch.cuda.is_available() # import the example dataset from the folder # data = array([x1,y1],[x2,y2],[x3,y3],.....,[x1500,y1500]) # label = array([0,0,0,....,1,1,1]) data0Path = r'data.txt' data0Label = r'datalabel.txt' dataCoords = np.loadtxt(data0Path) dataLabels = np.loadtxt(data0Label) fig = plt.figure() ax = fig.add_axes([0,0,1,1]) ax.plot(np.ravel(dataCoords[np.where(dataLabels == 0)])[::2], np.ravel(dataCoords[np.where(dataLabels == 0)])[1::2], ls='', marker='o') ax.plot(np.ravel(dataCoords[np.where(dataLabels == 1)])[::2], np.ravel(dataCoords[np.where(dataLabels == 1)])[1::2], ls='', marker='o') # Change the data structure for shuffling # We are taking 100 data to train the model np.random.seed(2) data1 = list(zip(dataCoords, dataLabels)) data_ixs = np.random.choice(len(data1), size=100) # Transform the data to work with the pytorch optimizer. # data coordinate X is [x1,y1,x1,y1] to embed in four-qubit circuit. X= [np.array(list(flatten([data1[j][0],data1[j][0]]))) for j in data_ixs] y01 = [data1[j][1] for j in data_ixs] X_ = Tensor(X) y01_ = Tensor(y01).reshape(len(y01)).long() n=4; feature_map = QuantumCircuit(n, name='Embed') feature_map.rx(Parameter('x[0]'),0) feature_map.rx(Parameter('x[1]'),1) feature_map.rx(Parameter('x[2]'),2) feature_map.rx(Parameter('x[3]'),3) for i in range(n): feature_map.ry(pi/4,i) for i in range(n): feature_map.rz(pi/4,i) param_y=[]; for i in range(8): param_y.append((Parameter('θ'+str(i)))) ansatz = QuantumCircuit(n, name='PQC') for i in range(n): ansatz.ry(param_y[i],i) for i in range(n): ansatz.rz(param_y[i+4],i) def binary(x): return ('0'*(4-len('{:b}'.format(x) ))+'{:b}'.format(x)) def firsttwo(x): return x[:2] parity = lambda x: firsttwo(binary(x)).count('1') % 2 [parity(i) for i in range(16)] qc = QuantumCircuit(n) qc.append(feature_map, range(n)) qc.append(ansatz, range(n)) # Model for LBFGS # Combining the circuit together with CircuitQNN np.random.seed(3) qnn2 = CircuitQNN(qc, input_params=feature_map.parameters, weight_params=ansatz.parameters, interpret=parity, output_shape=2, quantum_instance=qi) initial_weights = 0.1*(2*np.random.rand(qnn2.num_weights) - 1) model2 = TorchConnector(qnn2, initial_weights) # Model for Adam np.random.seed(3) qnn3 = CircuitQNN(qc, input_params=feature_map.parameters, weight_params=ansatz.parameters, interpret=parity, output_shape=2, quantum_instance=qi) initial_weights = 0.1*(2*np.random.rand(qnn3.num_weights) - 1) model3 = TorchConnector(qnn3, initial_weights) # define optimizer and loss function optimizer = LBFGS(model2.parameters(),lr=0.01) f_loss = CrossEntropyLoss() # start training model2.train() # set model to training mode # define objective function def closure(): optimizer.zero_grad() # initialize gradient loss = 0.0 # initialize loss for x, y_target in zip(X, y01): # evaluate batch loss output = model2(Tensor(x)).reshape(1, 2) # forward pass loss += f_loss(output, Tensor([y_target]).long()) loss.backward() # backward pass print(loss.item()) # print loss return loss # run optimizer optimizer.step(closure) # evaluate model and compute accuracy y_predict = [] for x in X: output = model2(Tensor(x)) y_predict += [np.argmax(output.detach().numpy())] print('Accuracy:', sum(y_predict == np.array(y01))/len(np.array(y01))) # plot results # red == wrongly classified for x, y_target, y_ in zip(X, y01, y_predict): if y_target == 1: plt.plot(x[0], x[1], 'bo') else: plt.plot(x[0], x[1], 'go') if y_target != y_: plt.scatter(x[0], x[1], s=200, facecolors='none', edgecolors='r', linewidths=2) plt.show() for x, y_target, y_ in zip(X, y01, y_predict): if y_target == 1: plt.plot(x[0], x[1], 'bo') else: plt.plot(x[0], x[1], 'go') X1 = np.linspace(0, 1, num=10) Z1 = np.zeros((len(X1), len(X1))) # Contour map for j in range(len(X1)): for k in range(len(X1)): # Fill Z with the labels (numerical values) # the inner loop goes over the columns of Z, # which corresponds to sweeping x-values # Therefore, the role of j,k is flipped in the signature Z1[j, k] = np.argmax(model2(Tensor([X1[k],X1[j],X1[k],X1[j]])).detach().numpy()) plt.contourf(X1, X1, Z1, cmap='bwr', levels=30) # Converged paramter for the PQC for p in model2.parameters(): print(p.data) optimizer = optim.Adam(model3.parameters(),lr=0.05) f_loss = MSELoss(reduction='mean') model3.train() epochs = 10 # set number of epochs for epoch in range(epochs): optimizer.zero_grad() loss = 0.0 for x, y_target in zip(X, y01): output = model3(Tensor(x)).reshape(1, 2) targets=Tensor([y_target]).long() targets = targets.to(torch.float32) loss += f_loss(output, targets) loss.backward() print(loss.item()) optimizer.step() y_predict = [] for x in X: output = model3(Tensor(x)) y_predict += [np.argmax(output.detach().numpy())] print('Accuracy:', sum(y_predict == np.array(y01))/len(np.array(y01))) for x, y_target, y_ in zip(X, y01, y_predict): if y_target == 1: plt.plot(x[0], x[1], 'bo') else: plt.plot(x[0], x[1], 'go') if y_target != y_: plt.scatter(x[0], x[1], s=200, facecolors='none', edgecolors='r', linewidths=2) plt.show() for x, y_target, y_ in zip(X, y01, y_predict): if y_target == 1: plt.plot(x[0], x[1], 'bo') else: plt.plot(x[0], x[1], 'go') X1 = np.linspace(0, 1, num=10) Z1 = np.zeros((len(X1), len(X1))) for j in range(len(X1)): for k in range(len(X1)): Z1[j, k] = np.argmax(model3(Tensor([X1[k],X1[j],X1[k],X1[j]])).detach().numpy()) plt.contourf(X1, X1, Z1, cmap='bwr', levels=30) for p in model3.parameters(): print(p.data)
https://github.com/bagmk/Quantum_Machine_Learning_Express
bagmk
import qiskit from qiskit import Aer, QuantumCircuit from qiskit.utils import QuantumInstance from qiskit.opflow import AerPauliExpectation from qiskit.circuit import Parameter from qiskit_machine_learning.neural_networks import CircuitQNN from qiskit_machine_learning.connectors import TorchConnector qi = QuantumInstance(Aer.get_backend('statevector_simulator')) qiskit.__qiskit_version__ import numpy as np from numpy import pi import matplotlib.pyplot as plt from sklearn.utils import shuffle from pandas.core.common import flatten import torch from torch import Tensor from torch.nn import Linear, CrossEntropyLoss, MSELoss from torch.optim import LBFGS, SGD,Adam import torch.optim as optim torch.cuda.is_available() # import the example dataset from the folder # data = array([x1,y1],[x2,y2],[x3,y3],.....,[x1500,y1500]) # label = array([0,0,0,....,1,1,1]) data0Path = r'data.txt' data0Label = r'datalabel.txt' dataCoords = np.loadtxt(data0Path) dataLabels = np.loadtxt(data0Label) fig = plt.figure() ax = fig.add_axes([0,0,1,1]) ax.plot(np.ravel(dataCoords[np.where(dataLabels == 0)])[::2], np.ravel(dataCoords[np.where(dataLabels == 0)])[1::2], ls='', marker='o') ax.plot(np.ravel(dataCoords[np.where(dataLabels == 1)])[::2], np.ravel(dataCoords[np.where(dataLabels == 1)])[1::2], ls='', marker='o') # Change the data structure for shuffling # We are taking 100 data to train the model np.random.seed(2) data1 = list(zip(dataCoords, dataLabels)) data_ixs = np.random.choice(len(data1), size=100) # Transform the data to work with the pytorch optimizer. # data coordinate X is [x1,y1,x1,y1] to embed in four-qubit circuit. X= [np.array(list(flatten([data1[j][0],data1[j][0]]))) for j in data_ixs] y01 = [data1[j][1] for j in data_ixs] X_ = Tensor(X) y01_ = Tensor(y01).reshape(len(y01)).long() n=4; feature_map = QuantumCircuit(n, name='Embed') feature_map.rx(Parameter('x[0]'),0) feature_map.rx(Parameter('x[1]'),1) feature_map.rx(Parameter('x[2]'),2) feature_map.rx(Parameter('x[3]'),3) for i in range(n): feature_map.ry(pi/4,i) for i in range(n): feature_map.rz(pi/4,i) feature_map.draw('mpl') param_y=[]; for i in range(8): param_y.append((Parameter('θ'+str(i)))) ansatz = QuantumCircuit(n, name='PQC') for i in range(n): ansatz.ry(param_y[i],i) for i in range(n): ansatz.rz(param_y[i+4],i) ansatz.draw('mpl') def binary(x): return ('0'*(4-len('{:b}'.format(x) ))+'{:b}'.format(x)) def firsttwo(x): return x[:2] parity = lambda x: firsttwo(binary(x)).count('1') % 2 [parity(i) for i in range(16)] qc = QuantumCircuit(n) qc.append(feature_map, range(n)) qc.append(ansatz, range(n)) qc.draw('mpl') # Model for LBFGS # Combining the circuit together with CircuitQNN np.random.seed(3) qnn2 = CircuitQNN(qc, input_params=feature_map.parameters, weight_params=ansatz.parameters, interpret=parity, output_shape=2, quantum_instance=qi) initial_weights = 0.1*(2*np.random.rand(qnn2.num_weights) - 1) model2 = TorchConnector(qnn2, initial_weights) # Model for Adam np.random.seed(3) qnn3 = CircuitQNN(qc, input_params=feature_map.parameters, weight_params=ansatz.parameters, interpret=parity, output_shape=2, quantum_instance=qi) initial_weights = 0.1*(2*np.random.rand(qnn3.num_weights) - 1) model3 = TorchConnector(qnn3, initial_weights) # define optimizer and loss function optimizer = LBFGS(model2.parameters(),lr=0.01) f_loss = CrossEntropyLoss() # start training model2.train() # set model to training mode # define objective function def closure(): optimizer.zero_grad() # initialize gradient loss = 0.0 # initialize loss for x, y_target in zip(X, y01): # evaluate batch loss output = model2(Tensor(x)).reshape(1, 2) # forward pass loss += f_loss(output, Tensor([y_target]).long()) loss.backward() # backward pass print(loss.item()) # print loss return loss # run optimizer optimizer.step(closure) # evaluate model and compute accuracy y_predict = [] for x in X: output = model2(Tensor(x)) y_predict += [np.argmax(output.detach().numpy())] print('Accuracy:', sum(y_predict == np.array(y01))/len(np.array(y01))) # plot results # red == wrongly classified for x, y_target, y_ in zip(X, y01, y_predict): if y_target == 1: plt.plot(x[0], x[1], 'bo') else: plt.plot(x[0], x[1], 'go') if y_target != y_: plt.scatter(x[0], x[1], s=200, facecolors='none', edgecolors='r', linewidths=2) plt.show() for x, y_target, y_ in zip(X, y01, y_predict): if y_target == 1: plt.plot(x[0], x[1], 'bo') else: plt.plot(x[0], x[1], 'go') X1 = np.linspace(0, 1, num=10) Z1 = np.zeros((len(X1), len(X1))) # Contour map for j in range(len(X1)): for k in range(len(X1)): # Fill Z with the labels (numerical values) # the inner loop goes over the columns of Z, # which corresponds to sweeping x-values # Therefore, the role of j,k is flipped in the signature Z1[j, k] = np.argmax(model2(Tensor([X1[k],X1[j],X1[k],X1[j]])).detach().numpy()) plt.contourf(X1, X1, Z1, cmap='bwr', levels=30) # Converged paramter for the PQC for p in model2.parameters(): print(p.data) optimizer = optim.Adam(model3.parameters(),lr=0.05) f_loss = MSELoss(reduction='mean') model3.train() epochs = 10 # set number of epochs for epoch in range(epochs): optimizer.zero_grad() loss = 0.0 for x, y_target in zip(X, y01): output = model3(Tensor(x)).reshape(1, 2) targets=Tensor([y_target]).long() targets = targets.to(torch.float32) loss += f_loss(output, targets) loss.backward() print(loss.item()) optimizer.step() y_predict = [] for x in X: output = model3(Tensor(x)) y_predict += [np.argmax(output.detach().numpy())] print('Accuracy:', sum(y_predict == np.array(y01))/len(np.array(y01))) for x, y_target, y_ in zip(X, y01, y_predict): if y_target == 1: plt.plot(x[0], x[1], 'bo') else: plt.plot(x[0], x[1], 'go') if y_target != y_: plt.scatter(x[0], x[1], s=200, facecolors='none', edgecolors='r', linewidths=2) plt.show() for x, y_target, y_ in zip(X, y01, y_predict): if y_target == 1: plt.plot(x[0], x[1], 'bo') else: plt.plot(x[0], x[1], 'go') X1 = np.linspace(0, 1, num=10) Z1 = np.zeros((len(X1), len(X1))) for j in range(len(X1)): for k in range(len(X1)): Z1[j, k] = np.argmax(model3(Tensor([X1[k],X1[j],X1[k],X1[j]])).detach().numpy()) plt.contourf(X1, X1, Z1, cmap='bwr', levels=30) for p in model3.parameters(): print(p.data)
https://github.com/bagmk/Quantum_Machine_Learning_Express
bagmk
# Practical Implementation of a Quantum String Matching Algorithm # S. Faro, F.P. Marino, and A. Scardace # QUASAR 2024 %%capture !pip install ibm-cloud-sdk-core==3.18.2 !pip install qiskit==0.45.1 !pip install qiskit-aer==0.13.1 !pip install pylatexenc==2.10 from numpy import log2, sqrt from numpy import pi from qiskit.tools.visualization import plot_histogram from qiskit.circuit.gate import Gate from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import Aer from qiskit import transpile def run(circuit: QuantumCircuit, shots: int) -> dict: simulator = Aer.get_backend('aer_simulator') compiled_circuit = transpile(circuit, simulator) job = simulator.run(compiled_circuit, shots=shots) result = job.result() return result.get_counts(compiled_circuit) def init_register(bin_str: str) -> QuantumCircuit: data_qr = QuantumRegister(len(bin_str), 'data') qc = QuantumCircuit(data_qr) for i, bit in enumerate(bin_str): if bit == '1': qc.x(data_qr[i]) return qc classical_value = '1001' init_register(classical_value).draw(fold=255) def rot(n: int, s: int) -> QuantumCircuit: y_qr = QuantumRegister(n, 'y') qc = QuantumCircuit(y_qr, name='ROT_' + str(s)) for i in range(1, (int(log2(n)) - int(log2(s)) + 2)): for j in range(int(n / (s * (2**i)))): for q in range(j * s * (2**i), s * (j*2 ** i+1)): qc.swap(n - 1 - (q+s), n - 1 - (q+2 ** (i-1) * s + s)) return qc num_qubits = 8 shift_value = 2 rot(num_qubits, shift_value).draw(fold=255) def rot_gate(n: int, s: int) -> Gate: rot_circuit = rot(n, s) return rot_circuit.to_gate(label='ROT_' + str(s)) def parameterized_rot(n: int) -> QuantumCircuit: j_qr = QuantumRegister(int(log2(n)), 'j') y_qr = QuantumRegister(n, 'y') qc = QuantumCircuit(j_qr, y_qr) for i in range(int(log2(n))): crot = rot_gate(n, 2**i).control(1) qc = qc.compose(crot, [j_qr[i]] + y_qr[:]) return qc num_qubits = 8 parameterized_rot(num_qubits).draw(fold=255) text = '10110001' text_length = len(text) shift_qr = QuantumRegister(int(log2(text_length)), 'shift') text_qr = QuantumRegister(text_length, 'text') output_cr = ClassicalRegister(text_length, 'output_classic') circ = QuantumCircuit(shift_qr, text_qr, output_cr) circ.h(shift_qr) circ.append(init_register(text), text_qr[:]) circ.append(parameterized_rot(text_length), shift_qr[:] + text_qr[:]) circ.measure(text_qr, output_cr) counts = run(circ, 100) plot_histogram(counts, title='Rotate ' + text + ' Leftward in Superposition') def match(m: int) -> QuantumCircuit: x_qr = QuantumRegister(m, 'x') y_qr = QuantumRegister(m, 'y') out_qr = QuantumRegister(1, 'out') qc = QuantumCircuit(x_qr, y_qr, out_qr) for i in range(m): qc.cx(x_qr[i], y_qr[i]) qc.x(y_qr[i]) qc.mcx(y_qr[:], out_qr) for i in reversed(range(m)): qc.x(y_qr[i]) qc.cx(x_qr[i], y_qr[i]) return qc pattern_length = 4 match(pattern_length).draw(fold=255) text = '1011' text_length = len(text) pattern_qr = QuantumRegister(text_length, 'pattern') text_qr = QuantumRegister(text_length, 'text') output_qr = QuantumRegister(1, 'output') output_cr = ClassicalRegister(text_length + 1, 'output_classic') circ = QuantumCircuit(pattern_qr, text_qr, output_qr, output_cr) circ.h(pattern_qr) circ.append(init_register(text), text_qr[:]) circ.append(match(text_length), pattern_qr[:] + text_qr[:] + output_qr[:]) circ.measure(pattern_qr, output_cr[:-1]) circ.measure(output_qr, output_cr[-1]) counts = run(circ, 100) plot_histogram(counts, title='Matching ' + text) def match_gate(m: int) -> Gate: match_circuit = match(m) return match_circuit.to_gate(label='MATCH') def esm(m: int, n: int) -> QuantumCircuit: j_qr = QuantumRegister(int(log2(n)), 'j') x_qr = QuantumRegister(m, 'x') y_qr = QuantumRegister(n, 'y') out = QuantumRegister(1, 'out') qc = QuantumCircuit( j_qr, x_qr, y_qr, out ) qc = qc.compose(parameterized_rot(n), j_qr[:] + y_qr[:]) qc = qc.compose(match_gate(m), x_qr[:] + y_qr[:m] + out[:]) qc = qc.compose(parameterized_rot(n).inverse(), j_qr[:] + y_qr[:]) return qc pattern_length = 2 text_length = 4 esm(pattern_length, text_length).draw(fold=255) def esm_oracle(m: int, n: int): esm_circuit = esm(m, n) return esm_circuit.to_gate(label='ESMO') def diffuser(n: int) -> Gate: qc = QuantumCircuit(n) qc.h(range(n)) qc.x(range(n)) qc.h(n-1) qc.mcx(list(range(n-1)), n-1) qc.h(n-1) qc.x(range(n)) qc.h(range(n)) return qc.to_gate(label='DIFF') def grover(esmo: Gate, t: int, x: str, y: str) -> QuantumCircuit: n = len(y) m = len(x) logn = int(log2(n)) num_iterations = int(pi/4 * sqrt(n/t)) j_qr = QuantumRegister(logn, 'j') x_qr = QuantumRegister(m, 'x') y_qr = QuantumRegister(n, 'y') out_qr = QuantumRegister(2, 'out') out_cr = ClassicalRegister(logn+1, 'c') qc = QuantumCircuit(j_qr, x_qr, y_qr, out_qr, out_cr) qc.h(j_qr) qc.x(out_qr[0]) qc.h(out_qr[0]) qc = qc.compose(init_register(x), x_qr[:]) qc = qc.compose(init_register(y), y_qr[:]) for _ in range(num_iterations): qc = qc.compose(esmo) qc = qc.compose(diffuser(logn)) qc.measure(j_qr, out_cr[:-1]) qc = qc.compose(esmo, j_qr[:] + x_qr[:] + y_qr[:] + [out_qr[1]]) qc.measure(out_qr[1], out_cr[-1]) return qc x = '11' y = '10101100' esmo = esm_oracle(len(x), len(y)) grover(esmo, 1, x, y).draw(fold=255) x = '00' y = '01010101' esmo = esm_oracle(len(x), len(y)) counts = run(grover(esmo, 1, x, y), 100) plot_histogram(counts, title=f'Search for {x} in {y} - 0 occurrence(s)') x = '00' y = '11010011' esmo = esm_oracle(len(x), len(y)) counts = run(grover(esmo, 1, x, y), 100) plot_histogram(counts, title=f'Search for {x} in {y} - 1 occurrence(s)') x = '00' y = '00111001' esmo = esm_oracle(len(x), len(y)) counts = run(grover(esmo, 2, x, y), 100) plot_histogram(counts, title=f'Search for {x} in {y} - 2 occurrence(s)') def search(x: str, y: str) -> int: m = len(x) n = len(y) esmo = esm_oracle(m, n) for t in range(1, int(n/2) + 1): print('Trying with t =', t) results = run(grover(esmo, t, x, y), 1) results = list(results.keys())[0] outcome = int(results[0]) position = int(results[1:], 2) if outcome: return position else: print('Pattern not found in position', position) return -1 x = input('Enter the value of x: ') y = input('Enter the value of y: ') if len(x) > len(y): raise Exception('The length of x must be shorter than the length of y.') if x.count('0') + x.count('1') < len(x): raise Exception('The pattern must be a binary string.') if y.count('0') + y.count('1') < len(y): raise Exception('The text must be a binary string.') print('') position = search(x, y) if position >= 0: print('Pattern occurrence found in position', str(position)) else: print('Pattern occurrence not found.')
https://github.com/bagmk/Quantum_Machine_Learning_Express
bagmk
from qiskit import * from oracle_generation import generate_oracle get_bin = lambda x, n: format(x, 'b').zfill(n) def gen_circuits(min,max,size): circuits = [] secrets = [] ORACLE_SIZE = size for i in range(min,max+1): cur_str = get_bin(i,ORACLE_SIZE-1) (circuit, secret) = generate_oracle(ORACLE_SIZE,False,3,cur_str) circuits.append(circuit) secrets.append(secret) return (circuits, secrets)
https://github.com/bagmk/Quantum_Machine_Learning_Express
bagmk
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from math import pi def circuit1(qc,theta,L,repeat): #circuit 1 #theta is list of the parameters #theta length is 8L #L is the number of repeatation # repeat will conjugate the first part and add next the the circuit for expressibility # 0:No, 1: Repeat count=0 for l in range(L): for i in range(4): qc.rx(theta[count],i) count=count+1 for i in range(4): qc.rz(theta[count],i) count=count+1 if repeat!=0: for l in range(L): for i in range(4): qc.rz(theta[count],i) count=count+1 for i in range(4): qc.rx(theta[count],i) count=count+1 return qc def circuit2(qc,theta,L,repeat): #circuit 2 #theta is list of the parameters #theta length is 8L #L is the number of repeatation # repeat will conjugate the first part and add next the the circuit for expressibility # 0:No, 1: Repeat count=0 for l in range(L): for i in range(4): qc.rx(theta[count],i) count=count+1 for i in range(4): qc.rz(theta[count],i) count=count+1 qc.cx(3,2) qc.cx(2,1) qc.cx(1,0) if repeat!=0: for l in range(L): qc.cx(1,0) qc.cx(2,1) qc.cx(3,2) for i in range(4): qc.rz(theta[count],i) count=count+1 for i in range(4): qc.rx(theta[count],i) count=count+1 return qc def circuit3(qc,theta,L,repeat): #circuit 3 #theta is list of the parameters #theta length is (11)L #L is the number of repeatation # repeat will conjugate the first part and add next the the circuit for expressibility # 0:No, 1: Repeat count=0 for l in range(L): for i in range(4): qc.rx(theta[count],i) count=count+1 for i in range(4): qc.rz(theta[count],i) count=count+1 qc.crz(theta[count],3,2) count=count+1 qc.crz(theta[count],2,1) count=count+1 qc.crz(theta[count],1,0) count=count+1 if repeat!=0: for l in range(L): qc.crz(theta[count],1,0) count=count+1 qc.crz(theta[count],2,1) count=count+1 qc.crz(theta[count],3,2) count=count+1 for i in range(4): qc.rz(theta[count],i) count=count+1 for i in range(4): qc.rx(theta[count],i) count=count+1 return qc def circuit4(qc,theta,L,repeat): #circuit 4 #theta is list of the parameters #theta length is (11)L #L is the number of repeatation # repeat will conjugate the first part and add next the the circuit for expressibility # 0:No, 1: Repeat count=0 for l in range(L): for i in range(4): qc.rx(theta[count],i) count=count+1 for i in range(4): qc.rz(theta[count],i) count=count+1 qc.crx(theta[count],3,2) count=count+1 qc.crx(theta[count],2,1) count=count+1 qc.crx(theta[count],1,0) count=count+1 if repeat!=0: for l in range(L): qc.crx(theta[count],1,0) count=count+1 qc.crx(theta[count],2,1) count=count+1 qc.crx(theta[count],3,2) count=count+1 for i in range(4): qc.rz(theta[count],i) count=count+1 for i in range(4): qc.rx(theta[count],i) count=count+1 return qc def circuit5(qc,theta,L,repeat): #circuit 5 #theta is list of the parameters #theta length is (28)L #L is the number of repeatation # repeat will conjugate the first part and add next the the circuit for expressibility # 0:No, 1: Repeat count=0 for l in range(L): for i in range(4): qc.rx(theta[count],i) count=count+1 for i in range(4): qc.rz(theta[count],i) count=count+1 for j in range(4): for i in range(4): if i!=j: qc.crz(theta[count],3-j,3-i) count=count+1 for i in range(4): qc.rx(theta[count],i) count=count+1 for i in range(4): qc.rz(theta[count],i) count=count+1 if repeat!=0: for l in range(L): for i in range(4): qc.rz(theta[count],i) count=count+1 for i in range(4): qc.rx(theta[count],i) count=count+1 for j in range(4): for i in range(4): if i!=j: qc.crz(theta[count],j,i) count=count+1 for i in range(4): qc.rz(theta[count],i) count=count+1 for i in range(4): qc.rx(theta[count],i) count=count+1 return qc def circuit6(qc,theta,L,repeat): #circuit 6 #theta is list of the parameters #theta length is (28)L #L is the number of repeatation # repeat will conjugate the first part and add next the the circuit for expressibility # 0:No, 1: Repeat count=0 for l in range(L): for i in range(4): qc.rx(theta[count],i) count=count+1 for i in range(4): qc.rz(theta[count],i) count=count+1 for j in range(4): for i in range(4): if i!=j: qc.crx(theta[count],3-j,3-i) count=count+1 for i in range(4): qc.rx(theta[count],i) count=count+1 for i in range(4): qc.rz(theta[count],i) count=count+1 if repeat!=0: for l in range(L): for i in range(4): qc.rz(theta[count],i) count=count+1 for i in range(4): qc.rx(theta[count],i) count=count+1 for j in range(4): for i in range(4): if i!=j: qc.crx(theta[count],j,i) count=count+1 for i in range(4): qc.rz(theta[count],i) count=count+1 for i in range(4): qc.rx(theta[count],i) count=count+1 return qc def circuit7(qc,theta,L,repeat): #circuit 7 #theta is list of the parameters #theta length is (19)L #L is the number of repeatation # repeat will conjugate the first part and add next the the circuit for expressibility # 0:No, 1: Repeat count=0 for l in range(L): for i in range(4): qc.rx(theta[count],i) count=count+1 for i in range(4): qc.rz(theta[count],i) count=count+1 qc.crz(theta[count],1,0) count=count+1 qc.crz(theta[count],3,2) count=count+1 for i in range(4): qc.rx(theta[count],i) count=count+1 for i in range(4): qc.rz(theta[count],i) count=count+1 qc.crz(theta[count],2,1) count=count+1 if repeat!=0: for l in range(L): qc.crz(theta[count],2,1) count=count+1 for i in range(4): qc.rz(theta[count],i) count=count+1 for i in range(4): qc.rx(theta[count],i) count=count+1 qc.crz(theta[count],3,2) count=count+1 qc.crz(theta[count],1,0) count=count+1 for i in range(4): qc.rz(theta[count],i) count=count+1 for i in range(4): qc.rx(theta[count],i) count=count+1 return qc def circuit8(qc,theta,L,repeat): #circuit 8 #theta is list of the parameters #theta length is (19)L #L is the number of repeatation # repeat will conjugate the first part and add next the the circuit for expressibility # 0:No, 1: Repeat count=0 for l in range(L): for i in range(4): qc.rx(theta[count],i) count=count+1 for i in range(4): qc.rz(theta[count],i) count=count+1 qc.crx(theta[count],1,0) count=count+1 qc.crx(theta[count],3,2) count=count+1 for i in range(4): qc.rx(theta[count],i) count=count+1 for i in range(4): qc.rz(theta[count],i) count=count+1 qc.crx(theta[count],2,1) count=count+1 if repeat!=0: for l in range(L): qc.crx(theta[count],2,1) count=count+1 for i in range(4): qc.rz(theta[count],i) count=count+1 for i in range(4): qc.rx(theta[count],i) count=count+1 qc.crx(theta[count],3,2) count=count+1 qc.crx(theta[count],1,0) count=count+1 for i in range(4): qc.rz(theta[count],i) count=count+1 for i in range(4): qc.rx(theta[count],i) count=count+1 return qc def circuit9(qc,theta,L,repeat): #circuit 9 #theta is list of the parameters #theta length is (4)L #L is the number of repeatation # repeat will conjugate the first part and add next the the circuit for expressibility # 0:No, 1: Repeat count=0 for l in range(L): for i in range(4): qc.h(i) qc.cz(3,2) qc.cz(2,1) qc.cz(1,0) for i in range(4): qc.rx(theta[count],i) count=count+1 if repeat!=0: for l in range(L): for i in range(4): qc.rx(theta[count],i) count=count+1 qc.cz(1,0) qc.cz(2,1) qc.cz(3,2) for i in range(4): qc.h(i) return qc def circuit10(qc,theta,L,repeat): #circuit 10 #theta is list of the parameters #theta length is (4)L+4 #L is the number of repeatation # repeat will conjugate the first part and add next the the circuit for expressibility # 0:No, 1: Repeat count=0 for i in range(4): qc.ry(theta[count],i) count=count+1 for l in range(L): qc.cz(3,2) qc.cz(2,1) qc.cz(1,0) qc.cz(3,0) for i in range(4): qc.ry(theta[count],i) count=count+1 if repeat!=0: for l in range(L): for i in range(4): qc.ry(theta[count],i) count=count+1 qc.cz(3,0) qc.cz(1,0) qc.cz(2,1) qc.cz(3,2) for i in range(4): qc.ry(theta[count],i) count=count+1 return qc def circuit11(qc,theta,L,repeat): #circuit 11 #theta is list of the parameters #theta length is (12)L #L is the number of repeatation # repeat will conjugate the first part and add next the the circuit for expressibility # 0:No, 1: Repeat count=0 for l in range(L): for i in range(4): qc.ry(theta[count],i) count=count+1 for i in range(4): qc.rz(theta[count],i) count=count+1 qc.cx(1,0) qc.cx(3,2) qc.ry(theta[count],1) count=count+1 qc.ry(theta[count],2) count=count+1 qc.rz(theta[count],1) count=count+1 qc.rz(theta[count],2) count=count+1 qc.cx(2,1) if repeat!=0: for l in range(L): qc.cx(2,1) qc.rz(theta[count],2) count=count+1 qc.rz(theta[count],1) count=count+1 qc.ry(theta[count],2) count=count+1 qc.ry(theta[count],1) count=count+1 qc.cx(3,2) qc.cx(1,0) for i in range(4): qc.rz(theta[count],i) count=count+1 for i in range(4): qc.ry(theta[count],i) count=count+1 return qc def circuit12(qc,theta,L,repeat): #circuit 12 #theta is list of the parameters #theta length is (12)L #L is the number of repeatation # repeat will conjugate the first part and add next the the circuit for expressibility # 0:No, 1: Repeat count=0 for l in range(L): for i in range(4): qc.ry(theta[count],i) count=count+1 for i in range(4): qc.rz(theta[count],i) count=count+1 qc.cz(1,0) qc.cz(3,2) qc.ry(theta[count],1) count=count+1 qc.ry(theta[count],2) count=count+1 qc.rz(theta[count],1) count=count+1 qc.rz(theta[count],2) count=count+1 qc.cz(2,1) if repeat!=0: for l in range(L): qc.cz(2,1) qc.rz(theta[count],2) count=count+1 qc.rz(theta[count],1) count=count+1 qc.ry(theta[count],2) count=count+1 qc.ry(theta[count],1) count=count+1 qc.cz(3,2) qc.cz(1,0) for i in range(4): qc.rz(theta[count],i) count=count+1 for i in range(4): qc.ry(theta[count],i) count=count+1 return qc def circuit13(qc,theta,L,repeat): #circuit 13 #theta is list of the parameters #theta length is (16)L #L is the number of repeatation # repeat will conjugate the first part and add next the the circuit for expressibility # 0:No, 1: Repeat count=0 for l in range(L): for i in range(4): qc.ry(theta[count],i) count=count+1 qc.crz(theta[count],3,0) count=count+1 qc.crz(theta[count],2,3) count=count+1 qc.crz(theta[count],1,2) count=count+1 qc.crz(theta[count],0,1) count=count+1 for i in range(4): qc.ry(theta[count],i) count=count+1 qc.crz(theta[count],3,2) count=count+1 qc.crz(theta[count],0,3) count=count+1 qc.crz(theta[count],1,0) count=count+1 qc.crz(theta[count],2,1) count=count+1 if repeat!=0: for l in range(L): qc.crz(theta[count],2,1) count=count+1 qc.crz(theta[count],1,0) count=count+1 qc.crz(theta[count],0,3) count=count+1 qc.crz(theta[count],3,2) count=count+1 for i in range(4): qc.ry(theta[count],i) count=count+1 qc.crz(theta[count],0,1) count=count+1 qc.crz(theta[count],1,2) count=count+1 qc.crz(theta[count],2,3) count=count+1 qc.crz(theta[count],3,0) count=count+1 for i in range(4): qc.ry(theta[count],i) count=count+1 return qc def circuit14(qc,theta,L,repeat): #circuit 14 #theta is list of the parameters #theta length is (16)L #L is the number of repeatation # repeat will conjugate the first part and add next the the circuit for expressibility # 0:No, 1: Repeat count=0 for l in range(L): for i in range(4): qc.ry(theta[count],i) count=count+1 qc.crx(theta[count],3,0) count=count+1 qc.crx(theta[count],2,3) count=count+1 qc.crx(theta[count],1,2) count=count+1 qc.crx(theta[count],0,1) count=count+1 for i in range(4): qc.ry(theta[count],i) count=count+1 qc.crx(theta[count],3,2) count=count+1 qc.crx(theta[count],0,3) count=count+1 qc.crx(theta[count],1,0) count=count+1 qc.crx(theta[count],2,1) count=count+1 if repeat!=0: for l in range(L): qc.crx(theta[count],2,1) count=count+1 qc.crx(theta[count],1,0) count=count+1 qc.crx(theta[count],0,3) count=count+1 qc.crx(theta[count],3,2) count=count+1 for i in range(4): qc.ry(theta[count],i) count=count+1 qc.crx(theta[count],0,1) count=count+1 qc.crx(theta[count],1,2) count=count+1 qc.crx(theta[count],2,3) count=count+1 qc.crx(theta[count],3,0) count=count+1 for i in range(4): qc.ry(theta[count],i) count=count+1 return qc def circuit15(qc,theta,L,repeat): #circuit 15 #theta is list of the parameters #theta length is (8)L #L is the number of repeatation # repeat will conjugate the first part and add next the the circuit for expressibility # 0:No, 1: Repeat count=0 for l in range(L): for i in range(4): qc.ry(theta[count],i) count=count+1 qc.cx(3,0) qc.cx(2,3) qc.cx(1,2) qc.cx(0,1) for i in range(4): qc.ry(theta[count],i) count=count+1 qc.cx(3,2) qc.cx(0,3) qc.cx(1,0) qc.cx(2,1) if repeat!=0: for l in range(L): qc.cx(2,1) qc.cx(1,0) qc.cx(0,3) qc.cx(3,2) for i in range(4): qc.ry(theta[count],i) count=count+1 qc.cx(0,1) qc.cx(1,2) qc.cx(2,3) qc.cx(3,0) for i in range(4): qc.ry(theta[count],i) count=count+1 return qc def circuit16(qc,theta,L,repeat): #circuit 16 #theta is list of the parameters #theta length is (11)L #L is the number of repeatation # repeat will conjugate the first part and add next the the circuit for expressibility # 0:No, 1: Repeat count=0 for l in range(L): for i in range(4): qc.rx(theta[count],i) count=count+1 for i in range(4): qc.rz(theta[count],i) count=count+1 qc.crz(theta[count],1,0) count=count+1 qc.crz(theta[count],3,2) count=count+1 qc.crz(theta[count],2,1) count=count+1 if repeat!=0: for l in range(L): qc.crz(theta[count],2,1) count=count+1 qc.crz(theta[count],3,2) count=count+1 qc.crz(theta[count],1,0) count=count+1 for i in range(4): qc.rz(theta[count],i) count=count+1 for i in range(4): qc.rx(theta[count],i) count=count+1 return qc def circuit17(qc,theta,L,repeat): #circuit 17 #theta is list of the parameters #theta length is (11)L #L is the number of repeatation # repeat will conjugate the first part and add next the the circuit for expressibility # 0:No, 1: Repeat count=0 for l in range(L): for i in range(4): qc.rx(theta[count],i) count=count+1 for i in range(4): qc.rz(theta[count],i) count=count+1 qc.crx(theta[count],1,0) count=count+1 qc.crx(theta[count],3,2) count=count+1 qc.crx(theta[count],2,1) count=count+1 if repeat!=0: for l in range(L): qc.crx(theta[count],2,1) count=count+1 qc.crx(theta[count],3,2) count=count+1 qc.crx(theta[count],1,0) count=count+1 for i in range(4): qc.rz(theta[count],i) count=count+1 for i in range(4): qc.rx(theta[count],i) count=count+1 return qc def circuit18(qc,theta,L,repeat): #circuit 18 #theta is list of the parameters #theta length is (12)L #L is the number of repeatation # repeat will conjugate the first part and add next the the circuit for expressibility # 0:No, 1: Repeat count=0 for l in range(L): for i in range(4): qc.rx(theta[count],i) count=count+1 for i in range(4): qc.rz(theta[count],i) count=count+1 qc.crz(theta[count],3,0) count=count+1 qc.crz(theta[count],2,3) count=count+1 qc.crz(theta[count],1,2) count=count+1 qc.crz(theta[count],0,1) count=count+1 if repeat!=0: for l in range(L): qc.crz(theta[count],0,1) count=count+1 qc.crz(theta[count],1,2) count=count+1 qc.crz(theta[count],2,3) count=count+1 qc.crz(theta[count],3,0) count=count+1 for i in range(4): qc.rz(theta[count],i) count=count+1 for i in range(4): qc.rx(theta[count],i) count=count+1 return qc def circuit19(qc,theta,L,repeat): #circuit 1 #theta is list of the parameters #theta length is (12)L #L is the number of repeatation # repeat will conjugate the first part and add next the the circuit for expressibility # 0:No, 1: Repeat count=0 for l in range(L): for i in range(4): qc.rx(theta[count],i) count=count+1 for i in range(4): qc.rz(theta[count],i) count=count+1 qc.crx(theta[count],3,0) count=count+1 qc.crx(theta[count],2,3) count=count+1 qc.crx(theta[count],1,2) count=count+1 qc.crx(theta[count],0,1) count=count+1 if repeat!=0: for l in range(L): qc.crx(theta[count],0,1) count=count+1 qc.crx(theta[count],1,2) count=count+1 qc.crx(theta[count],2,3) count=count+1 qc.crx(theta[count],3,0) count=count+1 for i in range(4): qc.rz(theta[count],i) count=count+1 for i in range(4): qc.rx(theta[count],i) count=count+1 return qc
https://github.com/bagmk/Quantum_Machine_Learning_Express
bagmk
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=bad-docstring-quotes,invalid-name """Quantum circuit object.""" from __future__ import annotations import collections.abc import copy import itertools import multiprocessing as mp import string import re import warnings import typing from collections import OrderedDict, defaultdict, namedtuple from typing import ( Union, Optional, Tuple, Type, TypeVar, Sequence, Callable, Mapping, Iterable, Any, DefaultDict, Literal, overload, ) import numpy as np from qiskit.exceptions import QiskitError from qiskit.utils.multiprocessing import is_main_process from qiskit.circuit.instruction import Instruction from qiskit.circuit.gate import Gate from qiskit.circuit.parameter import Parameter from qiskit.circuit.exceptions import CircuitError from qiskit.utils import optionals as _optionals from . import _classical_resource_map from ._utils import sort_parameters from .classical import expr from .parameterexpression import ParameterExpression, ParameterValueType from .quantumregister import QuantumRegister, Qubit, AncillaRegister, AncillaQubit from .classicalregister import ClassicalRegister, Clbit from .parametertable import ParameterReferences, ParameterTable, ParameterView from .parametervector import ParameterVector from .instructionset import InstructionSet from .operation import Operation from .register import Register from .bit import Bit from .quantumcircuitdata import QuantumCircuitData, CircuitInstruction from .delay import Delay from .measure import Measure from .reset import Reset from .tools import pi_check if typing.TYPE_CHECKING: import qiskit # pylint: disable=cyclic-import from qiskit.transpiler.layout import TranspileLayout # pylint: disable=cyclic-import BitLocations = namedtuple("BitLocations", ("index", "registers")) # The following types are not marked private to avoid leaking this "private/public" abstraction out # into the documentation. They are not imported by circuit.__init__, nor are they meant to be. # Arbitrary type variables for marking up generics. S = TypeVar("S") T = TypeVar("T") # Types that can be coerced to a valid Qubit specifier in a circuit. QubitSpecifier = Union[ Qubit, QuantumRegister, int, slice, Sequence[Union[Qubit, int]], ] # Types that can be coerced to a valid Clbit specifier in a circuit. ClbitSpecifier = Union[ Clbit, ClassicalRegister, int, slice, Sequence[Union[Clbit, int]], ] # Generic type which is either :obj:`~Qubit` or :obj:`~Clbit`, used to specify types of functions # which operate on either type of bit, but not both at the same time. BitType = TypeVar("BitType", Qubit, Clbit) # Regex pattern to match valid OpenQASM identifiers VALID_QASM2_IDENTIFIER = re.compile("[a-z][a-zA-Z_0-9]*") QASM2_RESERVED = { "OPENQASM", "qreg", "creg", "include", "gate", "opaque", "U", "CX", "measure", "reset", "if", "barrier", } class QuantumCircuit: """Create a new circuit. A circuit is a list of instructions bound to some registers. Args: regs (list(:class:`~.Register`) or list(``int``) or list(list(:class:`~.Bit`))): The registers to be included in the circuit. * If a list of :class:`~.Register` objects, represents the :class:`.QuantumRegister` and/or :class:`.ClassicalRegister` objects to include in the circuit. For example: * ``QuantumCircuit(QuantumRegister(4))`` * ``QuantumCircuit(QuantumRegister(4), ClassicalRegister(3))`` * ``QuantumCircuit(QuantumRegister(4, 'qr0'), QuantumRegister(2, 'qr1'))`` * If a list of ``int``, the amount of qubits and/or classical bits to include in the circuit. It can either be a single int for just the number of quantum bits, or 2 ints for the number of quantum bits and classical bits, respectively. For example: * ``QuantumCircuit(4) # A QuantumCircuit with 4 qubits`` * ``QuantumCircuit(4, 3) # A QuantumCircuit with 4 qubits and 3 classical bits`` * If a list of python lists containing :class:`.Bit` objects, a collection of :class:`.Bit` s to be added to the circuit. name (str): the name of the quantum circuit. If not set, an automatically generated string will be assigned. global_phase (float or ParameterExpression): The global phase of the circuit in radians. metadata (dict): Arbitrary key value metadata to associate with the circuit. This gets stored as free-form data in a dict in the :attr:`~qiskit.circuit.QuantumCircuit.metadata` attribute. It will not be directly used in the circuit. Raises: CircuitError: if the circuit name, if given, is not valid. Examples: Construct a simple Bell state circuit. .. plot:: :include-source: from qiskit import QuantumCircuit qc = QuantumCircuit(2, 2) qc.h(0) qc.cx(0, 1) qc.measure([0, 1], [0, 1]) qc.draw('mpl') Construct a 5-qubit GHZ circuit. .. code-block:: from qiskit import QuantumCircuit qc = QuantumCircuit(5) qc.h(0) qc.cx(0, range(1, 5)) qc.measure_all() Construct a 4-qubit Bernstein-Vazirani circuit using registers. .. plot:: :include-source: from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit qr = QuantumRegister(3, 'q') anc = QuantumRegister(1, 'ancilla') cr = ClassicalRegister(3, 'c') qc = QuantumCircuit(qr, anc, cr) qc.x(anc[0]) qc.h(anc[0]) qc.h(qr[0:3]) qc.cx(qr[0:3], anc[0]) qc.h(qr[0:3]) qc.barrier(qr) qc.measure(qr, cr) qc.draw('mpl') """ instances = 0 prefix = "circuit" # Class variable OPENQASM header header = "OPENQASM 2.0;" extension_lib = 'include "qelib1.inc";' def __init__( self, *regs: Register | int | Sequence[Bit], name: str | None = None, global_phase: ParameterValueType = 0, metadata: dict | None = None, ): if any(not isinstance(reg, (list, QuantumRegister, ClassicalRegister)) for reg in regs): # check if inputs are integers, but also allow e.g. 2.0 try: valid_reg_size = all(reg == int(reg) for reg in regs) except (ValueError, TypeError): valid_reg_size = False if not valid_reg_size: raise CircuitError( "Circuit args must be Registers or integers. (%s '%s' was " "provided)" % ([type(reg).__name__ for reg in regs], regs) ) regs = tuple(int(reg) for reg in regs) # cast to int self._base_name = None if name is None: self._base_name = self.cls_prefix() self._name_update() elif not isinstance(name, str): raise CircuitError( "The circuit name should be a string (or None to auto-generate a name)." ) else: self._base_name = name self.name = name self._increment_instances() # Data contains a list of instructions and their contexts, # in the order they were applied. self._data: list[CircuitInstruction] = [] self._op_start_times = None # A stack to hold the instruction sets that are being built up during for-, if- and # while-block construction. These are stored as a stripped down sequence of instructions, # and sets of qubits and clbits, rather than a full QuantumCircuit instance because the # builder interfaces need to wait until they are completed before they can fill in things # like `break` and `continue`. This is because these instructions need to "operate" on the # full width of bits, but the builder interface won't know what bits are used until the end. self._control_flow_scopes: list[ "qiskit.circuit.controlflow.builder.ControlFlowBuilderBlock" ] = [] self.qregs: list[QuantumRegister] = [] self.cregs: list[ClassicalRegister] = [] self._qubits: list[Qubit] = [] self._clbits: list[Clbit] = [] # Dict mapping Qubit or Clbit instances to tuple comprised of 0) the # corresponding index in circuit.{qubits,clbits} and 1) a list of # Register-int pairs for each Register containing the Bit and its index # within that register. self._qubit_indices: dict[Qubit, BitLocations] = {} self._clbit_indices: dict[Clbit, BitLocations] = {} self._ancillas: list[AncillaQubit] = [] self._calibrations: DefaultDict[str, dict[tuple, Any]] = defaultdict(dict) self.add_register(*regs) # Parameter table tracks instructions with variable parameters. self._parameter_table = ParameterTable() # Cache to avoid re-sorting parameters self._parameters = None self._layout = None self._global_phase: ParameterValueType = 0 self.global_phase = global_phase self.duration = None self.unit = "dt" self.metadata = {} if metadata is None else metadata @staticmethod def from_instructions( instructions: Iterable[ CircuitInstruction | tuple[qiskit.circuit.Instruction] | tuple[qiskit.circuit.Instruction, Iterable[Qubit]] | tuple[qiskit.circuit.Instruction, Iterable[Qubit], Iterable[Clbit]] ], *, qubits: Iterable[Qubit] = (), clbits: Iterable[Clbit] = (), name: str | None = None, global_phase: ParameterValueType = 0, metadata: dict | None = None, ) -> "QuantumCircuit": """Construct a circuit from an iterable of CircuitInstructions. Args: instructions: The instructions to add to the circuit. qubits: Any qubits to add to the circuit. This argument can be used, for example, to enforce a particular ordering of qubits. clbits: Any classical bits to add to the circuit. This argument can be used, for example, to enforce a particular ordering of classical bits. name: The name of the circuit. global_phase: The global phase of the circuit in radians. metadata: Arbitrary key value metadata to associate with the circuit. Returns: The quantum circuit. """ circuit = QuantumCircuit(name=name, global_phase=global_phase, metadata=metadata) added_qubits = set() added_clbits = set() if qubits: qubits = list(qubits) circuit.add_bits(qubits) added_qubits.update(qubits) if clbits: clbits = list(clbits) circuit.add_bits(clbits) added_clbits.update(clbits) for instruction in instructions: if not isinstance(instruction, CircuitInstruction): instruction = CircuitInstruction(*instruction) qubits = [qubit for qubit in instruction.qubits if qubit not in added_qubits] clbits = [clbit for clbit in instruction.clbits if clbit not in added_clbits] circuit.add_bits(qubits) circuit.add_bits(clbits) added_qubits.update(qubits) added_clbits.update(clbits) circuit._append(instruction) return circuit @property def layout(self) -> Optional[TranspileLayout]: r"""Return any associated layout information about the circuit This attribute contains an optional :class:`~.TranspileLayout` object. This is typically set on the output from :func:`~.transpile` or :meth:`.PassManager.run` to retain information about the permutations caused on the input circuit by transpilation. There are two types of permutations caused by the :func:`~.transpile` function, an initial layout which permutes the qubits based on the selected physical qubits on the :class:`~.Target`, and a final layout which is an output permutation caused by :class:`~.SwapGate`\s inserted during routing. """ return self._layout @property def data(self) -> QuantumCircuitData: """Return the circuit data (instructions and context). Returns: QuantumCircuitData: a list-like object containing the :class:`.CircuitInstruction`\\ s for each instruction. """ return QuantumCircuitData(self) @data.setter def data(self, data_input: Iterable): """Sets the circuit data from a list of instructions and context. Args: data_input (Iterable): A sequence of instructions with their execution contexts. The elements must either be instances of :class:`.CircuitInstruction` (preferred), or a 3-tuple of ``(instruction, qargs, cargs)`` (legacy). In the legacy format, ``instruction`` must be an :class:`~.circuit.Instruction`, while ``qargs`` and ``cargs`` must be iterables of :class:`.Qubit` or :class:`.Clbit` specifiers (similar to the allowed forms in calls to :meth:`append`). """ # If data_input is QuantumCircuitData(self), clearing self._data # below will also empty data_input, so make a shallow copy first. data_input = list(data_input) self._data = [] self._parameter_table = ParameterTable() if not data_input: return if isinstance(data_input[0], CircuitInstruction): for instruction in data_input: self.append(instruction) else: for instruction, qargs, cargs in data_input: self.append(instruction, qargs, cargs) @property def op_start_times(self) -> list[int]: """Return a list of operation start times. This attribute is enabled once one of scheduling analysis passes runs on the quantum circuit. Returns: List of integers representing instruction start times. The index corresponds to the index of instruction in :attr:`QuantumCircuit.data`. Raises: AttributeError: When circuit is not scheduled. """ if self._op_start_times is None: raise AttributeError( "This circuit is not scheduled. " "To schedule it run the circuit through one of the transpiler scheduling passes." ) return self._op_start_times @property def calibrations(self) -> dict: """Return calibration dictionary. The custom pulse definition of a given gate is of the form ``{'gate_name': {(qubits, params): schedule}}`` """ return dict(self._calibrations) @calibrations.setter def calibrations(self, calibrations: dict): """Set the circuit calibration data from a dictionary of calibration definition. Args: calibrations (dict): A dictionary of input in the format ``{'gate_name': {(qubits, gate_params): schedule}}`` """ self._calibrations = defaultdict(dict, calibrations) def has_calibration_for(self, instruction: CircuitInstruction | tuple): """Return True if the circuit has a calibration defined for the instruction context. In this case, the operation does not need to be translated to the device basis. """ if isinstance(instruction, CircuitInstruction): operation = instruction.operation qubits = instruction.qubits else: operation, qubits, _ = instruction if not self.calibrations or operation.name not in self.calibrations: return False qubits = tuple(self.qubits.index(qubit) for qubit in qubits) params = [] for p in operation.params: if isinstance(p, ParameterExpression) and not p.parameters: params.append(float(p)) else: params.append(p) params = tuple(params) return (qubits, params) in self.calibrations[operation.name] @property def metadata(self) -> dict: """The user provided metadata associated with the circuit. The metadata for the circuit is a user provided ``dict`` of metadata for the circuit. It will not be used to influence the execution or operation of the circuit, but it is expected to be passed between all transforms of the circuit (ie transpilation) and that providers will associate any circuit metadata with the results it returns from execution of that circuit. """ return self._metadata @metadata.setter def metadata(self, metadata: dict | None): """Update the circuit metadata""" if metadata is None: metadata = {} warnings.warn( "Setting metadata to None was deprecated in Terra 0.24.0 and this ability will be " "removed in a future release. Instead, set metadata to an empty dictionary.", DeprecationWarning, stacklevel=2, ) elif not isinstance(metadata, dict): raise TypeError("Only a dictionary is accepted for circuit metadata") self._metadata = metadata def __str__(self) -> str: return str(self.draw(output="text")) def __eq__(self, other) -> bool: if not isinstance(other, QuantumCircuit): return False # TODO: remove the DAG from this function from qiskit.converters import circuit_to_dag return circuit_to_dag(self, copy_operations=False) == circuit_to_dag( other, copy_operations=False ) @classmethod def _increment_instances(cls): cls.instances += 1 @classmethod def cls_instances(cls) -> int: """Return the current number of instances of this class, useful for auto naming.""" return cls.instances @classmethod def cls_prefix(cls) -> str: """Return the prefix to use for auto naming.""" return cls.prefix def _name_update(self) -> None: """update name of instance using instance number""" if not is_main_process(): pid_name = f"-{mp.current_process().pid}" else: pid_name = "" self.name = f"{self._base_name}-{self.cls_instances()}{pid_name}" def has_register(self, register: Register) -> bool: """ Test if this circuit has the register r. Args: register (Register): a quantum or classical register. Returns: bool: True if the register is contained in this circuit. """ has_reg = False if isinstance(register, QuantumRegister) and register in self.qregs: has_reg = True elif isinstance(register, ClassicalRegister) and register in self.cregs: has_reg = True return has_reg def reverse_ops(self) -> "QuantumCircuit": """Reverse the circuit by reversing the order of instructions. This is done by recursively reversing all instructions. It does not invert (adjoint) any gate. Returns: QuantumCircuit: the reversed circuit. Examples: input: .. parsed-literal:: ┌───┐ q_0: ┤ H ├─────■────── └───┘┌────┴─────┐ q_1: ─────┤ RX(1.57) ├ └──────────┘ output: .. parsed-literal:: ┌───┐ q_0: ─────■──────┤ H ├ ┌────┴─────┐└───┘ q_1: ┤ RX(1.57) ├───── └──────────┘ """ reverse_circ = QuantumCircuit( self.qubits, self.clbits, *self.qregs, *self.cregs, name=self.name + "_reverse" ) for instruction in reversed(self.data): reverse_circ._append(instruction.replace(operation=instruction.operation.reverse_ops())) reverse_circ.duration = self.duration reverse_circ.unit = self.unit return reverse_circ def reverse_bits(self) -> "QuantumCircuit": """Return a circuit with the opposite order of wires. The circuit is "vertically" flipped. If a circuit is defined over multiple registers, the resulting circuit will have the same registers but with their order flipped. This method is useful for converting a circuit written in little-endian convention to the big-endian equivalent, and vice versa. Returns: QuantumCircuit: the circuit with reversed bit order. Examples: input: .. parsed-literal:: ┌───┐ a_0: ┤ H ├──■───────────────── └───┘┌─┴─┐ a_1: ─────┤ X ├──■──────────── └───┘┌─┴─┐ a_2: ──────────┤ X ├──■─────── └───┘┌─┴─┐ b_0: ───────────────┤ X ├──■── └───┘┌─┴─┐ b_1: ────────────────────┤ X ├ └───┘ output: .. parsed-literal:: ┌───┐ b_0: ────────────────────┤ X ├ ┌───┐└─┬─┘ b_1: ───────────────┤ X ├──■── ┌───┐└─┬─┘ a_0: ──────────┤ X ├──■─────── ┌───┐└─┬─┘ a_1: ─────┤ X ├──■──────────── ┌───┐└─┬─┘ a_2: ┤ H ├──■───────────────── └───┘ """ circ = QuantumCircuit( list(reversed(self.qubits)), list(reversed(self.clbits)), name=self.name, global_phase=self.global_phase, ) new_qubit_map = circ.qubits[::-1] new_clbit_map = circ.clbits[::-1] for reg in reversed(self.qregs): bits = [new_qubit_map[self.find_bit(qubit).index] for qubit in reversed(reg)] circ.add_register(QuantumRegister(bits=bits, name=reg.name)) for reg in reversed(self.cregs): bits = [new_clbit_map[self.find_bit(clbit).index] for clbit in reversed(reg)] circ.add_register(ClassicalRegister(bits=bits, name=reg.name)) for instruction in self.data: qubits = [new_qubit_map[self.find_bit(qubit).index] for qubit in instruction.qubits] clbits = [new_clbit_map[self.find_bit(clbit).index] for clbit in instruction.clbits] circ._append(instruction.replace(qubits=qubits, clbits=clbits)) return circ def inverse(self) -> "QuantumCircuit": """Invert (take adjoint of) this circuit. This is done by recursively inverting all gates. Returns: QuantumCircuit: the inverted circuit Raises: CircuitError: if the circuit cannot be inverted. Examples: input: .. parsed-literal:: ┌───┐ q_0: ┤ H ├─────■────── └───┘┌────┴─────┐ q_1: ─────┤ RX(1.57) ├ └──────────┘ output: .. parsed-literal:: ┌───┐ q_0: ──────■──────┤ H ├ ┌─────┴─────┐└───┘ q_1: ┤ RX(-1.57) ├───── └───────────┘ """ inverse_circ = QuantumCircuit( self.qubits, self.clbits, *self.qregs, *self.cregs, name=self.name + "_dg", global_phase=-self.global_phase, ) for instruction in reversed(self._data): inverse_circ._append(instruction.replace(operation=instruction.operation.inverse())) return inverse_circ def repeat(self, reps: int) -> "QuantumCircuit": """Repeat this circuit ``reps`` times. Args: reps (int): How often this circuit should be repeated. Returns: QuantumCircuit: A circuit containing ``reps`` repetitions of this circuit. """ repeated_circ = QuantumCircuit( self.qubits, self.clbits, *self.qregs, *self.cregs, name=self.name + f"**{reps}" ) # benefit of appending instructions: decomposing shows the subparts, i.e. the power # is actually `reps` times this circuit, and it is currently much faster than `compose`. if reps > 0: try: # try to append as gate if possible to not disallow to_gate inst: Instruction = self.to_gate() except QiskitError: inst = self.to_instruction() for _ in range(reps): repeated_circ._append(inst, self.qubits, self.clbits) return repeated_circ def power(self, power: float, matrix_power: bool = False) -> "QuantumCircuit": """Raise this circuit to the power of ``power``. If ``power`` is a positive integer and ``matrix_power`` is ``False``, this implementation defaults to calling ``repeat``. Otherwise, if the circuit is unitary, the matrix is computed to calculate the matrix power. Args: power (float): The power to raise this circuit to. matrix_power (bool): If True, the circuit is converted to a matrix and then the matrix power is computed. If False, and ``power`` is a positive integer, the implementation defaults to ``repeat``. Raises: CircuitError: If the circuit needs to be converted to a gate but it is not unitary. Returns: QuantumCircuit: A circuit implementing this circuit raised to the power of ``power``. """ if power >= 0 and isinstance(power, (int, np.integer)) and not matrix_power: return self.repeat(power) # attempt conversion to gate if self.num_parameters > 0: raise CircuitError( "Cannot raise a parameterized circuit to a non-positive power " "or matrix-power, please bind the free parameters: " "{}".format(self.parameters) ) try: gate = self.to_gate() except QiskitError as ex: raise CircuitError( "The circuit contains non-unitary operations and cannot be " "controlled. Note that no qiskit.circuit.Instruction objects may " "be in the circuit for this operation." ) from ex power_circuit = QuantumCircuit(self.qubits, self.clbits, *self.qregs, *self.cregs) power_circuit.append(gate.power(power), list(range(gate.num_qubits))) return power_circuit def control( self, num_ctrl_qubits: int = 1, label: str | None = None, ctrl_state: str | int | None = None, ) -> "QuantumCircuit": """Control this circuit on ``num_ctrl_qubits`` qubits. Args: num_ctrl_qubits (int): The number of control qubits. label (str): An optional label to give the controlled operation for visualization. ctrl_state (str or int): The control state in decimal or as a bitstring (e.g. '111'). If None, use ``2**num_ctrl_qubits - 1``. Returns: QuantumCircuit: The controlled version of this circuit. Raises: CircuitError: If the circuit contains a non-unitary operation and cannot be controlled. """ try: gate = self.to_gate() except QiskitError as ex: raise CircuitError( "The circuit contains non-unitary operations and cannot be " "controlled. Note that no qiskit.circuit.Instruction objects may " "be in the circuit for this operation." ) from ex controlled_gate = gate.control(num_ctrl_qubits, label, ctrl_state) control_qreg = QuantumRegister(num_ctrl_qubits) controlled_circ = QuantumCircuit( control_qreg, self.qubits, *self.qregs, name=f"c_{self.name}" ) controlled_circ.append(controlled_gate, controlled_circ.qubits) return controlled_circ def compose( self, other: Union["QuantumCircuit", Instruction], qubits: QubitSpecifier | Sequence[QubitSpecifier] | None = None, clbits: ClbitSpecifier | Sequence[ClbitSpecifier] | None = None, front: bool = False, inplace: bool = False, wrap: bool = False, ) -> Optional["QuantumCircuit"]: """Compose circuit with ``other`` circuit or instruction, optionally permuting wires. ``other`` can be narrower or of equal width to ``self``. Args: other (qiskit.circuit.Instruction or QuantumCircuit): (sub)circuit or instruction to compose onto self. If not a :obj:`.QuantumCircuit`, this can be anything that :obj:`.append` will accept. qubits (list[Qubit|int]): qubits of self to compose onto. clbits (list[Clbit|int]): clbits of self to compose onto. front (bool): If True, front composition will be performed. This is not possible within control-flow builder context managers. inplace (bool): If True, modify the object. Otherwise return composed circuit. wrap (bool): If True, wraps the other circuit into a gate (or instruction, depending on whether it contains only unitary instructions) before composing it onto self. Returns: QuantumCircuit: the composed circuit (returns None if inplace==True). Raises: CircuitError: if no correct wire mapping can be made between the two circuits, such as if ``other`` is wider than ``self``. CircuitError: if trying to emit a new circuit while ``self`` has a partially built control-flow context active, such as the context-manager forms of :meth:`if_test`, :meth:`for_loop` and :meth:`while_loop`. CircuitError: if trying to compose to the front of a circuit when a control-flow builder block is active; there is no clear meaning to this action. Examples: .. code-block:: python >>> lhs.compose(rhs, qubits=[3, 2], inplace=True) .. parsed-literal:: ┌───┐ ┌─────┐ ┌───┐ lqr_1_0: ───┤ H ├─── rqr_0: ──■──┤ Tdg ├ lqr_1_0: ───┤ H ├─────────────── ├───┤ ┌─┴─┐└─────┘ ├───┤ lqr_1_1: ───┤ X ├─── rqr_1: ┤ X ├─────── lqr_1_1: ───┤ X ├─────────────── ┌──┴───┴──┐ └───┘ ┌──┴───┴──┐┌───┐ lqr_1_2: ┤ U1(0.1) ├ + = lqr_1_2: ┤ U1(0.1) ├┤ X ├─────── └─────────┘ └─────────┘└─┬─┘┌─────┐ lqr_2_0: ─────■───── lqr_2_0: ─────■───────■──┤ Tdg ├ ┌─┴─┐ ┌─┴─┐ └─────┘ lqr_2_1: ───┤ X ├─── lqr_2_1: ───┤ X ├─────────────── └───┘ └───┘ lcr_0: 0 ═══════════ lcr_0: 0 ═══════════════════════ lcr_1: 0 ═══════════ lcr_1: 0 ═══════════════════════ """ # pylint: disable=cyclic-import from qiskit.circuit.controlflow.switch_case import SwitchCaseOp if inplace and front and self._control_flow_scopes: # If we're composing onto ourselves while in a stateful control-flow builder context, # there's no clear meaning to composition to the "front" of the circuit. raise CircuitError( "Cannot compose to the front of a circuit while a control-flow context is active." ) if not inplace and self._control_flow_scopes: # If we're inside a stateful control-flow builder scope, even if we successfully cloned # the partial builder scope (not simple), the scope wouldn't be controlled by an active # `with` statement, so the output circuit would be permanently broken. raise CircuitError( "Cannot emit a new composed circuit while a control-flow context is active." ) dest = self if inplace else self.copy() # As a special case, allow composing some clbits onto no clbits - normally the destination # has to be strictly larger. This allows composing final measurements onto unitary circuits. if isinstance(other, QuantumCircuit): if not self.clbits and other.clbits: dest.add_bits(other.clbits) for reg in other.cregs: dest.add_register(reg) if wrap and isinstance(other, QuantumCircuit): other = ( other.to_gate() if all(isinstance(ins.operation, Gate) for ins in other.data) else other.to_instruction() ) if not isinstance(other, QuantumCircuit): if qubits is None: qubits = self.qubits[: other.num_qubits] if clbits is None: clbits = self.clbits[: other.num_clbits] if front: # Need to keep a reference to the data for use after we've emptied it. old_data = list(dest.data) dest.clear() dest.append(other, qubits, clbits) for instruction in old_data: dest._append(instruction) else: dest.append(other, qargs=qubits, cargs=clbits) if inplace: return None return dest if other.num_qubits > dest.num_qubits or other.num_clbits > dest.num_clbits: raise CircuitError( "Trying to compose with another QuantumCircuit which has more 'in' edges." ) # number of qubits and clbits must match number in circuit or None edge_map: dict[Qubit | Clbit, Qubit | Clbit] = {} if qubits is None: edge_map.update(zip(other.qubits, dest.qubits)) else: mapped_qubits = dest.qbit_argument_conversion(qubits) if len(mapped_qubits) != len(other.qubits): raise CircuitError( f"Number of items in qubits parameter ({len(mapped_qubits)}) does not" f" match number of qubits in the circuit ({len(other.qubits)})." ) edge_map.update(zip(other.qubits, mapped_qubits)) if clbits is None: edge_map.update(zip(other.clbits, dest.clbits)) else: mapped_clbits = dest.cbit_argument_conversion(clbits) if len(mapped_clbits) != len(other.clbits): raise CircuitError( f"Number of items in clbits parameter ({len(mapped_clbits)}) does not" f" match number of clbits in the circuit ({len(other.clbits)})." ) edge_map.update(zip(other.clbits, dest.cbit_argument_conversion(clbits))) variable_mapper = _classical_resource_map.VariableMapper( dest.cregs, edge_map, dest.add_register ) mapped_instrs: list[CircuitInstruction] = [] for instr in other.data: n_qargs: list[Qubit] = [edge_map[qarg] for qarg in instr.qubits] n_cargs: list[Clbit] = [edge_map[carg] for carg in instr.clbits] n_op = instr.operation.copy() if (condition := getattr(n_op, "condition", None)) is not None: n_op.condition = variable_mapper.map_condition(condition) if isinstance(n_op, SwitchCaseOp): n_op.target = variable_mapper.map_target(n_op.target) mapped_instrs.append(CircuitInstruction(n_op, n_qargs, n_cargs)) if front: # adjust new instrs before original ones and update all parameters mapped_instrs += dest.data dest.clear() append = dest._control_flow_scopes[-1].append if dest._control_flow_scopes else dest._append for instr in mapped_instrs: append(instr) for gate, cals in other.calibrations.items(): dest._calibrations[gate].update(cals) dest.global_phase += other.global_phase if inplace: return None return dest def tensor(self, other: "QuantumCircuit", inplace: bool = False) -> Optional["QuantumCircuit"]: """Tensor ``self`` with ``other``. Remember that in the little-endian convention the leftmost operation will be at the bottom of the circuit. See also `the docs <qiskit.org/documentation/tutorials/circuits/3_summary_of_quantum_operations.html>`__ for more information. .. parsed-literal:: ┌────────┐ ┌─────┐ ┌─────┐ q_0: ┤ bottom ├ ⊗ q_0: ┤ top ├ = q_0: ─┤ top ├── └────────┘ └─────┘ ┌┴─────┴─┐ q_1: ┤ bottom ├ └────────┘ Args: other (QuantumCircuit): The other circuit to tensor this circuit with. inplace (bool): If True, modify the object. Otherwise return composed circuit. Examples: .. plot:: :include-source: from qiskit import QuantumCircuit top = QuantumCircuit(1) top.x(0); bottom = QuantumCircuit(2) bottom.cry(0.2, 0, 1); tensored = bottom.tensor(top) tensored.draw('mpl') Returns: QuantumCircuit: The tensored circuit (returns None if inplace==True). """ num_qubits = self.num_qubits + other.num_qubits num_clbits = self.num_clbits + other.num_clbits # If a user defined both circuits with via register sizes and not with named registers # (e.g. QuantumCircuit(2, 2)) then we have a naming collision, as the registers are by # default called "q" resp. "c". To still allow tensoring we define new registers of the # correct sizes. if ( len(self.qregs) == len(other.qregs) == 1 and self.qregs[0].name == other.qregs[0].name == "q" ): # check if classical registers are in the circuit if num_clbits > 0: dest = QuantumCircuit(num_qubits, num_clbits) else: dest = QuantumCircuit(num_qubits) # handle case if ``measure_all`` was called on both circuits, in which case the # registers are both named "meas" elif ( len(self.cregs) == len(other.cregs) == 1 and self.cregs[0].name == other.cregs[0].name == "meas" ): cr = ClassicalRegister(self.num_clbits + other.num_clbits, "meas") dest = QuantumCircuit(*other.qregs, *self.qregs, cr) # Now we don't have to handle any more cases arising from special implicit naming else: dest = QuantumCircuit( other.qubits, self.qubits, other.clbits, self.clbits, *other.qregs, *self.qregs, *other.cregs, *self.cregs, ) # compose self onto the output, and then other dest.compose(other, range(other.num_qubits), range(other.num_clbits), inplace=True) dest.compose( self, range(other.num_qubits, num_qubits), range(other.num_clbits, num_clbits), inplace=True, ) # Replace information from tensored circuit into self when inplace = True if inplace: self.__dict__.update(dest.__dict__) return None return dest @property def qubits(self) -> list[Qubit]: """ Returns a list of quantum bits in the order that the registers were added. """ return self._qubits @property def clbits(self) -> list[Clbit]: """ Returns a list of classical bits in the order that the registers were added. """ return self._clbits @property def ancillas(self) -> list[AncillaQubit]: """ Returns a list of ancilla bits in the order that the registers were added. """ return self._ancillas def __and__(self, rhs: "QuantumCircuit") -> "QuantumCircuit": """Overload & to implement self.compose.""" return self.compose(rhs) def __iand__(self, rhs: "QuantumCircuit") -> "QuantumCircuit": """Overload &= to implement self.compose in place.""" self.compose(rhs, inplace=True) return self def __xor__(self, top: "QuantumCircuit") -> "QuantumCircuit": """Overload ^ to implement self.tensor.""" return self.tensor(top) def __ixor__(self, top: "QuantumCircuit") -> "QuantumCircuit": """Overload ^= to implement self.tensor in place.""" self.tensor(top, inplace=True) return self def __len__(self) -> int: """Return number of operations in circuit.""" return len(self._data) @typing.overload def __getitem__(self, item: int) -> CircuitInstruction: ... @typing.overload def __getitem__(self, item: slice) -> list[CircuitInstruction]: ... def __getitem__(self, item): """Return indexed operation.""" return self._data[item] @staticmethod def cast(value: S, type_: Callable[..., T]) -> Union[S, T]: """Best effort to cast value to type. Otherwise, returns the value.""" try: return type_(value) except (ValueError, TypeError): return value def qbit_argument_conversion(self, qubit_representation: QubitSpecifier) -> list[Qubit]: """ Converts several qubit representations (such as indexes, range, etc.) into a list of qubits. Args: qubit_representation (Object): representation to expand Returns: List(Qubit): the resolved instances of the qubits. """ return _bit_argument_conversion( qubit_representation, self.qubits, self._qubit_indices, Qubit ) def cbit_argument_conversion(self, clbit_representation: ClbitSpecifier) -> list[Clbit]: """ Converts several classical bit representations (such as indexes, range, etc.) into a list of classical bits. Args: clbit_representation (Object): representation to expand Returns: List(tuple): Where each tuple is a classical bit. """ return _bit_argument_conversion( clbit_representation, self.clbits, self._clbit_indices, Clbit ) def _resolve_classical_resource(self, specifier): """Resolve a single classical resource specifier into a concrete resource, raising an error if the specifier is invalid. This is slightly different to :meth:`.cbit_argument_conversion`, because it should not unwrap :obj:`.ClassicalRegister` instances into lists, and in general it should not allow iterables or broadcasting. It is expected to be used as a callback for things like :meth:`.InstructionSet.c_if` to check the validity of their arguments. Args: specifier (Union[Clbit, ClassicalRegister, int]): a specifier of a classical resource present in this circuit. An ``int`` will be resolved into a :obj:`.Clbit` using the same conventions as measurement operations on this circuit use. Returns: Union[Clbit, ClassicalRegister]: the resolved resource. Raises: CircuitError: if the resource is not present in this circuit, or if the integer index passed is out-of-bounds. """ if isinstance(specifier, Clbit): if specifier not in self._clbit_indices: raise CircuitError(f"Clbit {specifier} is not present in this circuit.") return specifier if isinstance(specifier, ClassicalRegister): # This is linear complexity for something that should be constant, but QuantumCircuit # does not currently keep a hashmap of registers, and requires non-trivial changes to # how it exposes its registers publically before such a map can be safely stored so it # doesn't miss updates. (Jake, 2021-11-10). if specifier not in self.cregs: raise CircuitError(f"Register {specifier} is not present in this circuit.") return specifier if isinstance(specifier, int): try: return self._clbits[specifier] except IndexError: raise CircuitError(f"Classical bit index {specifier} is out-of-range.") from None raise CircuitError(f"Unknown classical resource specifier: '{specifier}'.") def _validate_expr(self, node: expr.Expr) -> expr.Expr: for var in expr.iter_vars(node): if isinstance(var.var, Clbit): if var.var not in self._clbit_indices: raise CircuitError(f"Clbit {var.var} is not present in this circuit.") elif isinstance(var.var, ClassicalRegister): if var.var not in self.cregs: raise CircuitError(f"Register {var.var} is not present in this circuit.") return node def append( self, instruction: Operation | CircuitInstruction, qargs: Sequence[QubitSpecifier] | None = None, cargs: Sequence[ClbitSpecifier] | None = None, ) -> InstructionSet: """Append one or more instructions to the end of the circuit, modifying the circuit in place. The ``qargs`` and ``cargs`` will be expanded and broadcast according to the rules of the given :class:`~.circuit.Instruction`, and any non-:class:`.Bit` specifiers (such as integer indices) will be resolved into the relevant instances. If a :class:`.CircuitInstruction` is given, it will be unwrapped, verified in the context of this circuit, and a new object will be appended to the circuit. In this case, you may not pass ``qargs`` or ``cargs`` separately. Args: instruction: :class:`~.circuit.Instruction` instance to append, or a :class:`.CircuitInstruction` with all its context. qargs: specifiers of the :class:`.Qubit`\\ s to attach instruction to. cargs: specifiers of the :class:`.Clbit`\\ s to attach instruction to. Returns: qiskit.circuit.InstructionSet: a handle to the :class:`.CircuitInstruction`\\ s that were actually added to the circuit. Raises: CircuitError: if the operation passed is not an instance of :class:`~.circuit.Instruction` . """ if isinstance(instruction, CircuitInstruction): operation = instruction.operation qargs = instruction.qubits cargs = instruction.clbits else: operation = instruction # Convert input to instruction if not isinstance(operation, Operation): if hasattr(operation, "to_instruction"): operation = operation.to_instruction() if not isinstance(operation, Operation): raise CircuitError("operation.to_instruction() is not an Operation.") else: if issubclass(operation, Operation): raise CircuitError( "Object is a subclass of Operation, please add () to " "pass an instance of this object." ) raise CircuitError( "Object to append must be an Operation or have a to_instruction() method." ) # Make copy of parameterized gate instances if hasattr(operation, "params"): is_parameter = any(isinstance(param, Parameter) for param in operation.params) if is_parameter: operation = copy.deepcopy(operation) expanded_qargs = [self.qbit_argument_conversion(qarg) for qarg in qargs or []] expanded_cargs = [self.cbit_argument_conversion(carg) for carg in cargs or []] if self._control_flow_scopes: appender = self._control_flow_scopes[-1].append requester = self._control_flow_scopes[-1].request_classical_resource else: appender = self._append requester = self._resolve_classical_resource instructions = InstructionSet(resource_requester=requester) if isinstance(operation, Instruction): for qarg, carg in operation.broadcast_arguments(expanded_qargs, expanded_cargs): self._check_dups(qarg) instruction = CircuitInstruction(operation, qarg, carg) appender(instruction) instructions.add(instruction) else: # For Operations that are non-Instructions, we use the Instruction's default method for qarg, carg in Instruction.broadcast_arguments( operation, expanded_qargs, expanded_cargs ): self._check_dups(qarg) instruction = CircuitInstruction(operation, qarg, carg) appender(instruction) instructions.add(instruction) return instructions # Preferred new style. @typing.overload def _append( self, instruction: CircuitInstruction, _qargs: None = None, _cargs: None = None ) -> CircuitInstruction: ... # To-be-deprecated old style. @typing.overload def _append( self, operation: Operation, qargs: Sequence[Qubit], cargs: Sequence[Clbit], ) -> Operation: ... def _append( self, instruction: CircuitInstruction | Instruction, qargs: Sequence[Qubit] | None = None, cargs: Sequence[Clbit] | None = None, ): """Append an instruction to the end of the circuit, modifying the circuit in place. .. warning:: This is an internal fast-path function, and it is the responsibility of the caller to ensure that all the arguments are valid; there is no error checking here. In particular, all the qubits and clbits must already exist in the circuit and there can be no duplicates in the list. .. note:: This function may be used by callers other than :obj:`.QuantumCircuit` when the caller is sure that all error-checking, broadcasting and scoping has already been performed, and the only reference to the circuit the instructions are being appended to is within that same function. In particular, it is not safe to call :meth:`QuantumCircuit._append` on a circuit that is received by a function argument. This is because :meth:`.QuantumCircuit._append` will not recognise the scoping constructs of the control-flow builder interface. Args: instruction: Operation instance to append qargs: Qubits to attach the instruction to. cargs: Clbits to attach the instruction to. Returns: Operation: a handle to the instruction that was just added :meta public: """ old_style = not isinstance(instruction, CircuitInstruction) if old_style: instruction = CircuitInstruction(instruction, qargs, cargs) self._data.append(instruction) if isinstance(instruction.operation, Instruction): self._update_parameter_table(instruction) # mark as normal circuit if a new instruction is added self.duration = None self.unit = "dt" return instruction.operation if old_style else instruction def _update_parameter_table(self, instruction: CircuitInstruction): for param_index, param in enumerate(instruction.operation.params): if isinstance(param, (ParameterExpression, QuantumCircuit)): # Scoped constructs like the control-flow ops use QuantumCircuit as a parameter. atomic_parameters = set(param.parameters) else: atomic_parameters = set() for parameter in atomic_parameters: if parameter in self._parameter_table: self._parameter_table[parameter].add((instruction.operation, param_index)) else: if parameter.name in self._parameter_table.get_names(): raise CircuitError(f"Name conflict on adding parameter: {parameter.name}") self._parameter_table[parameter] = ParameterReferences( ((instruction.operation, param_index),) ) # clear cache if new parameter is added self._parameters = None def add_register(self, *regs: Register | int | Sequence[Bit]) -> None: """Add registers.""" if not regs: return if any(isinstance(reg, int) for reg in regs): # QuantumCircuit defined without registers if len(regs) == 1 and isinstance(regs[0], int): # QuantumCircuit with anonymous quantum wires e.g. QuantumCircuit(2) if regs[0] == 0: regs = () else: regs = (QuantumRegister(regs[0], "q"),) elif len(regs) == 2 and all(isinstance(reg, int) for reg in regs): # QuantumCircuit with anonymous wires e.g. QuantumCircuit(2, 3) if regs[0] == 0: qregs: tuple[QuantumRegister, ...] = () else: qregs = (QuantumRegister(regs[0], "q"),) if regs[1] == 0: cregs: tuple[ClassicalRegister, ...] = () else: cregs = (ClassicalRegister(regs[1], "c"),) regs = qregs + cregs else: raise CircuitError( "QuantumCircuit parameters can be Registers or Integers." " If Integers, up to 2 arguments. QuantumCircuit was called" " with %s." % (regs,) ) for register in regs: if isinstance(register, Register) and any( register.name == reg.name for reg in self.qregs + self.cregs ): raise CircuitError('register name "%s" already exists' % register.name) if isinstance(register, AncillaRegister): for bit in register: if bit not in self._qubit_indices: self._ancillas.append(bit) if isinstance(register, QuantumRegister): self.qregs.append(register) for idx, bit in enumerate(register): if bit in self._qubit_indices: self._qubit_indices[bit].registers.append((register, idx)) else: self._qubits.append(bit) self._qubit_indices[bit] = BitLocations( len(self._qubits) - 1, [(register, idx)] ) elif isinstance(register, ClassicalRegister): self.cregs.append(register) for idx, bit in enumerate(register): if bit in self._clbit_indices: self._clbit_indices[bit].registers.append((register, idx)) else: self._clbits.append(bit) self._clbit_indices[bit] = BitLocations( len(self._clbits) - 1, [(register, idx)] ) elif isinstance(register, list): self.add_bits(register) else: raise CircuitError("expected a register") def add_bits(self, bits: Iterable[Bit]) -> None: """Add Bits to the circuit.""" duplicate_bits = set(self._qubit_indices).union(self._clbit_indices).intersection(bits) if duplicate_bits: raise CircuitError(f"Attempted to add bits found already in circuit: {duplicate_bits}") for bit in bits: if isinstance(bit, AncillaQubit): self._ancillas.append(bit) if isinstance(bit, Qubit): self._qubits.append(bit) self._qubit_indices[bit] = BitLocations(len(self._qubits) - 1, []) elif isinstance(bit, Clbit): self._clbits.append(bit) self._clbit_indices[bit] = BitLocations(len(self._clbits) - 1, []) else: raise CircuitError( "Expected an instance of Qubit, Clbit, or " "AncillaQubit, but was passed {}".format(bit) ) def find_bit(self, bit: Bit) -> BitLocations: """Find locations in the circuit which can be used to reference a given :obj:`~Bit`. Args: bit (Bit): The bit to locate. Returns: namedtuple(int, List[Tuple(Register, int)]): A 2-tuple. The first element (``index``) contains the index at which the ``Bit`` can be found (in either :obj:`~QuantumCircuit.qubits`, :obj:`~QuantumCircuit.clbits`, depending on its type). The second element (``registers``) is a list of ``(register, index)`` pairs with an entry for each :obj:`~Register` in the circuit which contains the :obj:`~Bit` (and the index in the :obj:`~Register` at which it can be found). Notes: The circuit index of an :obj:`~AncillaQubit` will be its index in :obj:`~QuantumCircuit.qubits`, not :obj:`~QuantumCircuit.ancillas`. Raises: CircuitError: If the supplied :obj:`~Bit` was of an unknown type. CircuitError: If the supplied :obj:`~Bit` could not be found on the circuit. """ try: if isinstance(bit, Qubit): return self._qubit_indices[bit] elif isinstance(bit, Clbit): return self._clbit_indices[bit] else: raise CircuitError(f"Could not locate bit of unknown type: {type(bit)}") except KeyError as err: raise CircuitError( f"Could not locate provided bit: {bit}. Has it been added to the QuantumCircuit?" ) from err def _check_dups(self, qubits: Sequence[Qubit]) -> None: """Raise exception if list of qubits contains duplicates.""" squbits = set(qubits) if len(squbits) != len(qubits): raise CircuitError("duplicate qubit arguments") def to_instruction( self, parameter_map: dict[Parameter, ParameterValueType] | None = None, label: str | None = None, ) -> Instruction: """Create an Instruction out of this circuit. Args: parameter_map(dict): For parameterized circuits, a mapping from parameters in the circuit to parameters to be used in the instruction. If None, existing circuit parameters will also parameterize the instruction. label (str): Optional gate label. Returns: qiskit.circuit.Instruction: a composite instruction encapsulating this circuit (can be decomposed back) """ from qiskit.converters.circuit_to_instruction import circuit_to_instruction return circuit_to_instruction(self, parameter_map, label=label) def to_gate( self, parameter_map: dict[Parameter, ParameterValueType] | None = None, label: str | None = None, ) -> Gate: """Create a Gate out of this circuit. Args: parameter_map(dict): For parameterized circuits, a mapping from parameters in the circuit to parameters to be used in the gate. If None, existing circuit parameters will also parameterize the gate. label (str): Optional gate label. Returns: Gate: a composite gate encapsulating this circuit (can be decomposed back) """ from qiskit.converters.circuit_to_gate import circuit_to_gate return circuit_to_gate(self, parameter_map, label=label) def decompose( self, gates_to_decompose: Type[Gate] | Sequence[Type[Gate]] | Sequence[str] | str | None = None, reps: int = 1, ) -> "QuantumCircuit": """Call a decomposition pass on this circuit, to decompose one level (shallow decompose). Args: gates_to_decompose (type or str or list(type, str)): Optional subset of gates to decompose. Can be a gate type, such as ``HGate``, or a gate name, such as 'h', or a gate label, such as 'My H Gate', or a list of any combination of these. If a gate name is entered, it will decompose all gates with that name, whether the gates have labels or not. Defaults to all gates in circuit. reps (int): Optional number of times the circuit should be decomposed. For instance, ``reps=2`` equals calling ``circuit.decompose().decompose()``. can decompose specific gates specific time Returns: QuantumCircuit: a circuit one level decomposed """ # pylint: disable=cyclic-import from qiskit.transpiler.passes.basis.decompose import Decompose from qiskit.transpiler.passes.synthesis import HighLevelSynthesis from qiskit.converters.circuit_to_dag import circuit_to_dag from qiskit.converters.dag_to_circuit import dag_to_circuit dag = circuit_to_dag(self) dag = HighLevelSynthesis().run(dag) pass_ = Decompose(gates_to_decompose) for _ in range(reps): dag = pass_.run(dag) return dag_to_circuit(dag) def qasm( self, formatted: bool = False, filename: str | None = None, encoding: str | None = None, ) -> str | None: """Return OpenQASM string. Args: formatted (bool): Return formatted Qasm string. filename (str): Save Qasm to file with name 'filename'. encoding (str): Optionally specify the encoding to use for the output file if ``filename`` is specified. By default this is set to the system's default encoding (ie whatever ``locale.getpreferredencoding()`` returns) and can be set to any valid codec or alias from stdlib's `codec module <https://docs.python.org/3/library/codecs.html#standard-encodings>`__ Returns: str: If formatted=False. Raises: MissingOptionalLibraryError: If pygments is not installed and ``formatted`` is ``True``. QASM2ExportError: If circuit has free parameters. QASM2ExportError: If an operation that has no OpenQASM 2 representation is encountered. """ from qiskit.qasm2 import QASM2ExportError # pylint: disable=cyclic-import if self.num_parameters > 0: raise QASM2ExportError( "Cannot represent circuits with unbound parameters in OpenQASM 2." ) existing_gate_names = { "barrier", "measure", "reset", "u3", "u2", "u1", "cx", "id", "u0", "u", "p", "x", "y", "z", "h", "s", "sdg", "t", "tdg", "rx", "ry", "rz", "sx", "sxdg", "cz", "cy", "swap", "ch", "ccx", "cswap", "crx", "cry", "crz", "cu1", "cp", "cu3", "csx", "cu", "rxx", "rzz", "rccx", "rc3x", "c3x", "c3sx", # This is the Qiskit gate name, but the qelib1.inc name is 'c3sqrtx'. "c4x", } # Mapping of instruction name to a pair of the source for a definition, and an OQ2 string # that includes the `gate` or `opaque` statement that defines the gate. gates_to_define: OrderedDict[str, tuple[Instruction, str]] = OrderedDict() regless_qubits = [bit for bit in self.qubits if not self.find_bit(bit).registers] regless_clbits = [bit for bit in self.clbits if not self.find_bit(bit).registers] dummy_registers: list[QuantumRegister | ClassicalRegister] = [] if regless_qubits: dummy_registers.append(QuantumRegister(name="qregless", bits=regless_qubits)) if regless_clbits: dummy_registers.append(ClassicalRegister(name="cregless", bits=regless_clbits)) register_escaped_names: dict[str, QuantumRegister | ClassicalRegister] = {} for regs in (self.qregs, self.cregs, dummy_registers): for reg in regs: register_escaped_names[ _make_unique(_qasm_escape_name(reg.name, "reg_"), register_escaped_names) ] = reg bit_labels: dict[Qubit | Clbit, str] = { bit: "%s[%d]" % (name, idx) for name, register in register_escaped_names.items() for (idx, bit) in enumerate(register) } register_definitions_qasm = "".join( f"{'qreg' if isinstance(reg, QuantumRegister) else 'creg'} {name}[{reg.size}];\n" for name, reg in register_escaped_names.items() ) instruction_calls = [] for instruction in self._data: operation = instruction.operation if operation.name == "measure": qubit = instruction.qubits[0] clbit = instruction.clbits[0] instruction_qasm = f"measure {bit_labels[qubit]} -> {bit_labels[clbit]};" elif operation.name == "reset": instruction_qasm = f"reset {bit_labels[instruction.qubits[0]]};" elif operation.name == "barrier": if not instruction.qubits: # Barriers with no operands are invalid in (strict) OQ2, and the statement # would have no meaning anyway. continue qargs = ",".join(bit_labels[q] for q in instruction.qubits) instruction_qasm = "barrier;" if not qargs else f"barrier {qargs};" else: instruction_qasm = _qasm2_custom_operation_statement( instruction, existing_gate_names, gates_to_define, bit_labels ) instruction_calls.append(instruction_qasm) instructions_qasm = "".join(f"{call}\n" for call in instruction_calls) gate_definitions_qasm = "".join(f"{qasm}\n" for _, qasm in gates_to_define.values()) out = "".join( ( self.header, "\n", self.extension_lib, "\n", gate_definitions_qasm, register_definitions_qasm, instructions_qasm, ) ) if filename: with open(filename, "w+", encoding=encoding) as file: file.write(out) if formatted: _optionals.HAS_PYGMENTS.require_now("formatted OpenQASM 2 output") import pygments from pygments.formatters import ( # pylint: disable=no-name-in-module Terminal256Formatter, ) from qiskit.qasm.pygments import OpenQASMLexer from qiskit.qasm.pygments import QasmTerminalStyle code = pygments.highlight( out, OpenQASMLexer(), Terminal256Formatter(style=QasmTerminalStyle) ) print(code) return None return out def draw( self, output: str | None = None, scale: float | None = None, filename: str | None = None, style: dict | str | None = None, interactive: bool = False, plot_barriers: bool = True, reverse_bits: bool = None, justify: str | None = None, vertical_compression: str | None = "medium", idle_wires: bool = True, with_layout: bool = True, fold: int | None = None, # The type of ax is matplotlib.axes.Axes, but this is not a fixed dependency, so cannot be # safely forward-referenced. ax: Any | None = None, initial_state: bool = False, cregbundle: bool = None, wire_order: list = None, ): """Draw the quantum circuit. Use the output parameter to choose the drawing format: **text**: ASCII art TextDrawing that can be printed in the console. **mpl**: images with color rendered purely in Python using matplotlib. **latex**: high-quality images compiled via latex. **latex_source**: raw uncompiled latex output. .. warning:: Support for :class:`~.expr.Expr` nodes in conditions and :attr:`.SwitchCaseOp.target` fields is preliminary and incomplete. The ``text`` and ``mpl`` drawers will make a best-effort attempt to show data dependencies, but the LaTeX-based drawers will skip these completely. Args: output (str): select the output method to use for drawing the circuit. Valid choices are ``text``, ``mpl``, ``latex``, ``latex_source``. By default the `text` drawer is used unless the user config file (usually ``~/.qiskit/settings.conf``) has an alternative backend set as the default. For example, ``circuit_drawer = latex``. If the output kwarg is set, that backend will always be used over the default in the user config file. scale (float): scale of image to draw (shrink if < 1.0). Only used by the `mpl`, `latex` and `latex_source` outputs. Defaults to 1.0. filename (str): file path to save image to. Defaults to None. style (dict or str): dictionary of style or file name of style json file. This option is only used by the `mpl` or `latex` output type. If `style` is a str, it is used as the path to a json file which contains a style dict. The file will be opened, parsed, and then any style elements in the dict will replace the default values in the input dict. A file to be loaded must end in ``.json``, but the name entered here can omit ``.json``. For example, ``style='iqx.json'`` or ``style='iqx'``. If `style` is a dict and the ``'name'`` key is set, that name will be used to load a json file, followed by loading the other items in the style dict. For example, ``style={'name': 'iqx'}``. If `style` is not a str and `name` is not a key in the style dict, then the default value from the user config file (usually ``~/.qiskit/settings.conf``) will be used, for example, ``circuit_mpl_style = iqx``. If none of these are set, the `default` style will be used. The search path for style json files can be specified in the user config, for example, ``circuit_mpl_style_path = /home/user/styles:/home/user``. See: :class:`~qiskit.visualization.qcstyle.DefaultStyle` for more information on the contents. interactive (bool): when set to true, show the circuit in a new window (for `mpl` this depends on the matplotlib backend being used supporting this). Note when used with either the `text` or the `latex_source` output type this has no effect and will be silently ignored. Defaults to False. reverse_bits (bool): when set to True, reverse the bit order inside registers for the output visualization. Defaults to False unless the user config file (usually ``~/.qiskit/settings.conf``) has an alternative value set. For example, ``circuit_reverse_bits = True``. plot_barriers (bool): enable/disable drawing barriers in the output circuit. Defaults to True. justify (string): options are ``left``, ``right`` or ``none``. If anything else is supplied, it defaults to left justified. It refers to where gates should be placed in the output circuit if there is an option. ``none`` results in each gate being placed in its own column. vertical_compression (string): ``high``, ``medium`` or ``low``. It merges the lines generated by the `text` output so the drawing will take less vertical room. Default is ``medium``. Only used by the `text` output, will be silently ignored otherwise. idle_wires (bool): include idle wires (wires with no circuit elements) in output visualization. Default is True. with_layout (bool): include layout information, with labels on the physical layout. Default is True. fold (int): sets pagination. It can be disabled using -1. In `text`, sets the length of the lines. This is useful when the drawing does not fit in the console. If None (default), it will try to guess the console width using ``shutil.get_terminal_size()``. However, if running in jupyter, the default line length is set to 80 characters. In `mpl`, it is the number of (visual) layers before folding. Default is 25. ax (matplotlib.axes.Axes): Only used by the `mpl` backend. An optional Axes object to be used for the visualization output. If none is specified, a new matplotlib Figure will be created and used. Additionally, if specified there will be no returned Figure since it is redundant. initial_state (bool): Optional. Adds ``|0>`` in the beginning of the wire. Default is False. cregbundle (bool): Optional. If set True, bundle classical registers. Default is True, except for when ``output`` is set to ``"text"``. wire_order (list): Optional. A list of integers used to reorder the display of the bits. The list must have an entry for every bit with the bits in the range 0 to (``num_qubits`` + ``num_clbits``). Returns: :class:`.TextDrawing` or :class:`matplotlib.figure` or :class:`PIL.Image` or :class:`str`: * `TextDrawing` (output='text') A drawing that can be printed as ascii art. * `matplotlib.figure.Figure` (output='mpl') A matplotlib figure object for the circuit diagram. * `PIL.Image` (output='latex') An in-memory representation of the image of the circuit diagram. * `str` (output='latex_source') The LaTeX source code for visualizing the circuit diagram. Raises: VisualizationError: when an invalid output method is selected ImportError: when the output methods requires non-installed libraries. Example: .. plot:: :include-source: from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit q = QuantumRegister(1) c = ClassicalRegister(1) qc = QuantumCircuit(q, c) qc.h(q) qc.measure(q, c) qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'}) """ # pylint: disable=cyclic-import from qiskit.visualization import circuit_drawer return circuit_drawer( self, scale=scale, filename=filename, style=style, output=output, interactive=interactive, plot_barriers=plot_barriers, reverse_bits=reverse_bits, justify=justify, vertical_compression=vertical_compression, idle_wires=idle_wires, with_layout=with_layout, fold=fold, ax=ax, initial_state=initial_state, cregbundle=cregbundle, wire_order=wire_order, ) def size( self, filter_function: Callable[..., int] = lambda x: not getattr( x.operation, "_directive", False ), ) -> int: """Returns total number of instructions in circuit. Args: filter_function (callable): a function to filter out some instructions. Should take as input a tuple of (Instruction, list(Qubit), list(Clbit)). By default filters out "directives", such as barrier or snapshot. Returns: int: Total number of gate operations. """ return sum(map(filter_function, self._data)) def depth( self, filter_function: Callable[..., int] = lambda x: not getattr( x.operation, "_directive", False ), ) -> int: """Return circuit depth (i.e., length of critical path). Args: filter_function (callable): A function to filter instructions. Should take as input a tuple of (Instruction, list(Qubit), list(Clbit)). Instructions for which the function returns False are ignored in the computation of the circuit depth. By default filters out "directives", such as barrier or snapshot. Returns: int: Depth of circuit. Notes: The circuit depth and the DAG depth need not be the same. """ # Assign each bit in the circuit a unique integer # to index into op_stack. bit_indices: dict[Qubit | Clbit, int] = { bit: idx for idx, bit in enumerate(self.qubits + self.clbits) } # If no bits, return 0 if not bit_indices: return 0 # A list that holds the height of each qubit # and classical bit. op_stack = [0] * len(bit_indices) # Here we are playing a modified version of # Tetris where we stack gates, but multi-qubit # gates, or measurements have a block for each # qubit or cbit that are connected by a virtual # line so that they all stacked at the same depth. # Conditional gates act on all cbits in the register # they are conditioned on. # The max stack height is the circuit depth. for instruction in self._data: levels = [] reg_ints = [] for ind, reg in enumerate(instruction.qubits + instruction.clbits): # Add to the stacks of the qubits and # cbits used in the gate. reg_ints.append(bit_indices[reg]) if filter_function(instruction): levels.append(op_stack[reg_ints[ind]] + 1) else: levels.append(op_stack[reg_ints[ind]]) # Assuming here that there is no conditional # snapshots or barriers ever. if getattr(instruction.operation, "condition", None): # Controls operate over all bits of a classical register # or over a single bit if isinstance(instruction.operation.condition[0], Clbit): condition_bits = [instruction.operation.condition[0]] else: condition_bits = instruction.operation.condition[0] for cbit in condition_bits: idx = bit_indices[cbit] if idx not in reg_ints: reg_ints.append(idx) levels.append(op_stack[idx] + 1) max_level = max(levels) for ind in reg_ints: op_stack[ind] = max_level return max(op_stack) def width(self) -> int: """Return number of qubits plus clbits in circuit. Returns: int: Width of circuit. """ return len(self.qubits) + len(self.clbits) @property def num_qubits(self) -> int: """Return number of qubits.""" return len(self.qubits) @property def num_ancillas(self) -> int: """Return the number of ancilla qubits.""" return len(self.ancillas) @property def num_clbits(self) -> int: """Return number of classical bits.""" return len(self.clbits) # The stringified return type is because OrderedDict can't be subscripted before Python 3.9, and # typing.OrderedDict wasn't added until 3.7.2. It can be turned into a proper type once 3.6 # support is dropped. def count_ops(self) -> "OrderedDict[Instruction, int]": """Count each operation kind in the circuit. Returns: OrderedDict: a breakdown of how many operations of each kind, sorted by amount. """ count_ops: dict[Instruction, int] = {} for instruction in self._data: count_ops[instruction.operation.name] = count_ops.get(instruction.operation.name, 0) + 1 return OrderedDict(sorted(count_ops.items(), key=lambda kv: kv[1], reverse=True)) def num_nonlocal_gates(self) -> int: """Return number of non-local gates (i.e. involving 2+ qubits). Conditional nonlocal gates are also included. """ multi_qubit_gates = 0 for instruction in self._data: if instruction.operation.num_qubits > 1 and not getattr( instruction.operation, "_directive", False ): multi_qubit_gates += 1 return multi_qubit_gates def get_instructions(self, name: str) -> list[CircuitInstruction]: """Get instructions matching name. Args: name (str): The name of instruction to. Returns: list(tuple): list of (instruction, qargs, cargs). """ return [match for match in self._data if match.operation.name == name] def num_connected_components(self, unitary_only: bool = False) -> int: """How many non-entangled subcircuits can the circuit be factored to. Args: unitary_only (bool): Compute only unitary part of graph. Returns: int: Number of connected components in circuit. """ # Convert registers to ints (as done in depth). bits = self.qubits if unitary_only else (self.qubits + self.clbits) bit_indices: dict[Qubit | Clbit, int] = {bit: idx for idx, bit in enumerate(bits)} # Start with each qubit or cbit being its own subgraph. sub_graphs = [[bit] for bit in range(len(bit_indices))] num_sub_graphs = len(sub_graphs) # Here we are traversing the gates and looking to see # which of the sub_graphs the gate joins together. for instruction in self._data: if unitary_only: args = instruction.qubits num_qargs = len(args) else: args = instruction.qubits + instruction.clbits num_qargs = len(args) + ( 1 if getattr(instruction.operation, "condition", None) else 0 ) if num_qargs >= 2 and not getattr(instruction.operation, "_directive", False): graphs_touched = [] num_touched = 0 # Controls necessarily join all the cbits in the # register that they use. if not unitary_only: for bit in instruction.operation.condition_bits: idx = bit_indices[bit] for k in range(num_sub_graphs): if idx in sub_graphs[k]: graphs_touched.append(k) break for item in args: reg_int = bit_indices[item] for k in range(num_sub_graphs): if reg_int in sub_graphs[k]: if k not in graphs_touched: graphs_touched.append(k) break graphs_touched = list(set(graphs_touched)) num_touched = len(graphs_touched) # If the gate touches more than one subgraph # join those graphs together and return # reduced number of subgraphs if num_touched > 1: connections = [] for idx in graphs_touched: connections.extend(sub_graphs[idx]) _sub_graphs = [] for idx in range(num_sub_graphs): if idx not in graphs_touched: _sub_graphs.append(sub_graphs[idx]) _sub_graphs.append(connections) sub_graphs = _sub_graphs num_sub_graphs -= num_touched - 1 # Cannot go lower than one so break if num_sub_graphs == 1: break return num_sub_graphs def num_unitary_factors(self) -> int: """Computes the number of tensor factors in the unitary (quantum) part of the circuit only. """ return self.num_connected_components(unitary_only=True) def num_tensor_factors(self) -> int: """Computes the number of tensor factors in the unitary (quantum) part of the circuit only. Notes: This is here for backwards compatibility, and will be removed in a future release of Qiskit. You should call `num_unitary_factors` instead. """ return self.num_unitary_factors() def copy(self, name: str | None = None) -> "QuantumCircuit": """Copy the circuit. Args: name (str): name to be given to the copied circuit. If None, then the name stays the same. Returns: QuantumCircuit: a deepcopy of the current circuit, with the specified name """ cpy = self.copy_empty_like(name) operation_copies = { id(instruction.operation): instruction.operation.copy() for instruction in self._data } cpy._parameter_table = ParameterTable( { param: ParameterReferences( (operation_copies[id(operation)], param_index) for operation, param_index in self._parameter_table[param] ) for param in self._parameter_table } ) cpy._data = [ instruction.replace(operation=operation_copies[id(instruction.operation)]) for instruction in self._data ] return cpy def copy_empty_like(self, name: str | None = None) -> "QuantumCircuit": """Return a copy of self with the same structure but empty. That structure includes: * name, calibrations and other metadata * global phase * all the qubits and clbits, including the registers Args: name (str): Name for the copied circuit. If None, then the name stays the same. Returns: QuantumCircuit: An empty copy of self. """ if not (name is None or isinstance(name, str)): raise TypeError( f"invalid name for a circuit: '{name}'. The name must be a string or 'None'." ) cpy = copy.copy(self) # copy registers correctly, in copy.copy they are only copied via reference cpy.qregs = self.qregs.copy() cpy.cregs = self.cregs.copy() cpy._qubits = self._qubits.copy() cpy._ancillas = self._ancillas.copy() cpy._clbits = self._clbits.copy() cpy._qubit_indices = self._qubit_indices.copy() cpy._clbit_indices = self._clbit_indices.copy() cpy._parameter_table = ParameterTable() cpy._data = [] cpy._calibrations = copy.deepcopy(self._calibrations) cpy._metadata = copy.deepcopy(self._metadata) if name: cpy.name = name return cpy def clear(self) -> None: """Clear all instructions in self. Clearing the circuits will keep the metadata and calibrations. """ self._data.clear() self._parameter_table.clear() def _create_creg(self, length: int, name: str) -> ClassicalRegister: """Creates a creg, checking if ClassicalRegister with same name exists""" if name in [creg.name for creg in self.cregs]: save_prefix = ClassicalRegister.prefix ClassicalRegister.prefix = name new_creg = ClassicalRegister(length) ClassicalRegister.prefix = save_prefix else: new_creg = ClassicalRegister(length, name) return new_creg def _create_qreg(self, length: int, name: str) -> QuantumRegister: """Creates a qreg, checking if QuantumRegister with same name exists""" if name in [qreg.name for qreg in self.qregs]: save_prefix = QuantumRegister.prefix QuantumRegister.prefix = name new_qreg = QuantumRegister(length) QuantumRegister.prefix = save_prefix else: new_qreg = QuantumRegister(length, name) return new_qreg def reset(self, qubit: QubitSpecifier) -> InstructionSet: """Reset the quantum bit(s) to their default state. Args: qubit: qubit(s) to reset. Returns: qiskit.circuit.InstructionSet: handle to the added instruction. """ return self.append(Reset(), [qubit], []) def measure(self, qubit: QubitSpecifier, cbit: ClbitSpecifier) -> InstructionSet: r"""Measure a quantum bit (``qubit``) in the Z basis into a classical bit (``cbit``). When a quantum state is measured, a qubit is projected in the computational (Pauli Z) basis to either :math:`\lvert 0 \rangle` or :math:`\lvert 1 \rangle`. The classical bit ``cbit`` indicates the result of that projection as a ``0`` or a ``1`` respectively. This operation is non-reversible. Args: qubit: qubit(s) to measure. cbit: classical bit(s) to place the measurement result(s) in. Returns: qiskit.circuit.InstructionSet: handle to the added instructions. Raises: CircuitError: if arguments have bad format. Examples: In this example, a qubit is measured and the result of that measurement is stored in the classical bit (usually expressed in diagrams as a double line): .. code-block:: from qiskit import QuantumCircuit circuit = QuantumCircuit(1, 1) circuit.h(0) circuit.measure(0, 0) circuit.draw() .. parsed-literal:: ┌───┐┌─┐ q: ┤ H ├┤M├ └───┘└╥┘ c: 1/══════╩═ 0 It is possible to call ``measure`` with lists of ``qubits`` and ``cbits`` as a shortcut for one-to-one measurement. These two forms produce identical results: .. code-block:: circuit = QuantumCircuit(2, 2) circuit.measure([0,1], [0,1]) .. code-block:: circuit = QuantumCircuit(2, 2) circuit.measure(0, 0) circuit.measure(1, 1) Instead of lists, you can use :class:`~qiskit.circuit.QuantumRegister` and :class:`~qiskit.circuit.ClassicalRegister` under the same logic. .. code-block:: from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister qreg = QuantumRegister(2, "qreg") creg = ClassicalRegister(2, "creg") circuit = QuantumCircuit(qreg, creg) circuit.measure(qreg, creg) This is equivalent to: .. code-block:: circuit = QuantumCircuit(qreg, creg) circuit.measure(qreg[0], creg[0]) circuit.measure(qreg[1], creg[1]) """ return self.append(Measure(), [qubit], [cbit]) def measure_active(self, inplace: bool = True) -> Optional["QuantumCircuit"]: """Adds measurement to all non-idle qubits. Creates a new ClassicalRegister with a size equal to the number of non-idle qubits being measured. Returns a new circuit with measurements if `inplace=False`. Args: inplace (bool): All measurements inplace or return new circuit. Returns: QuantumCircuit: Returns circuit with measurements when `inplace = False`. """ from qiskit.converters.circuit_to_dag import circuit_to_dag if inplace: circ = self else: circ = self.copy() dag = circuit_to_dag(circ) qubits_to_measure = [qubit for qubit in circ.qubits if qubit not in dag.idle_wires()] new_creg = circ._create_creg(len(qubits_to_measure), "measure") circ.add_register(new_creg) circ.barrier() circ.measure(qubits_to_measure, new_creg) if not inplace: return circ else: return None def measure_all( self, inplace: bool = True, add_bits: bool = True ) -> Optional["QuantumCircuit"]: """Adds measurement to all qubits. By default, adds new classical bits in a :obj:`.ClassicalRegister` to store these measurements. If ``add_bits=False``, the results of the measurements will instead be stored in the already existing classical bits, with qubit ``n`` being measured into classical bit ``n``. Returns a new circuit with measurements if ``inplace=False``. Args: inplace (bool): All measurements inplace or return new circuit. add_bits (bool): Whether to add new bits to store the results. Returns: QuantumCircuit: Returns circuit with measurements when ``inplace=False``. Raises: CircuitError: if ``add_bits=False`` but there are not enough classical bits. """ if inplace: circ = self else: circ = self.copy() if add_bits: new_creg = circ._create_creg(len(circ.qubits), "meas") circ.add_register(new_creg) circ.barrier() circ.measure(circ.qubits, new_creg) else: if len(circ.clbits) < len(circ.qubits): raise CircuitError( "The number of classical bits must be equal or greater than " "the number of qubits." ) circ.barrier() circ.measure(circ.qubits, circ.clbits[0 : len(circ.qubits)]) if not inplace: return circ else: return None def remove_final_measurements(self, inplace: bool = True) -> Optional["QuantumCircuit"]: """Removes final measurements and barriers on all qubits if they are present. Deletes the classical registers that were used to store the values from these measurements that become idle as a result of this operation, and deletes classical bits that are referenced only by removed registers, or that aren't referenced at all but have become idle as a result of this operation. Measurements and barriers are considered final if they are followed by no other operations (aside from other measurements or barriers.) Args: inplace (bool): All measurements removed inplace or return new circuit. Returns: QuantumCircuit: Returns the resulting circuit when ``inplace=False``, else None. """ # pylint: disable=cyclic-import from qiskit.transpiler.passes import RemoveFinalMeasurements from qiskit.converters import circuit_to_dag if inplace: circ = self else: circ = self.copy() dag = circuit_to_dag(circ) remove_final_meas = RemoveFinalMeasurements() new_dag = remove_final_meas.run(dag) kept_cregs = set(new_dag.cregs.values()) kept_clbits = set(new_dag.clbits) # Filter only cregs/clbits still in new DAG, preserving original circuit order cregs_to_add = [creg for creg in circ.cregs if creg in kept_cregs] clbits_to_add = [clbit for clbit in circ._clbits if clbit in kept_clbits] # Clear cregs and clbits circ.cregs = [] circ._clbits = [] circ._clbit_indices = {} # We must add the clbits first to preserve the original circuit # order. This way, add_register never adds clbits and just # creates registers that point to them. circ.add_bits(clbits_to_add) for creg in cregs_to_add: circ.add_register(creg) # Clear instruction info circ.data.clear() circ._parameter_table.clear() # Set circ instructions to match the new DAG for node in new_dag.topological_op_nodes(): # Get arguments for classical condition (if any) inst = node.op.copy() circ.append(inst, node.qargs, node.cargs) if not inplace: return circ else: return None @staticmethod def from_qasm_file(path: str) -> "QuantumCircuit": """Take in a QASM file and generate a QuantumCircuit object. Args: path (str): Path to the file for a QASM program Return: QuantumCircuit: The QuantumCircuit object for the input QASM See also: :func:`.qasm2.load`: the complete interface to the OpenQASM 2 importer. """ # pylint: disable=cyclic-import from qiskit import qasm2 return qasm2.load( path, include_path=qasm2.LEGACY_INCLUDE_PATH, custom_instructions=qasm2.LEGACY_CUSTOM_INSTRUCTIONS, custom_classical=qasm2.LEGACY_CUSTOM_CLASSICAL, strict=False, ) @staticmethod def from_qasm_str(qasm_str: str) -> "QuantumCircuit": """Take in a QASM string and generate a QuantumCircuit object. Args: qasm_str (str): A QASM program string Return: QuantumCircuit: The QuantumCircuit object for the input QASM See also: :func:`.qasm2.loads`: the complete interface to the OpenQASM 2 importer. """ # pylint: disable=cyclic-import from qiskit import qasm2 return qasm2.loads( qasm_str, include_path=qasm2.LEGACY_INCLUDE_PATH, custom_instructions=qasm2.LEGACY_CUSTOM_INSTRUCTIONS, custom_classical=qasm2.LEGACY_CUSTOM_CLASSICAL, strict=False, ) @property def global_phase(self) -> ParameterValueType: """Return the global phase of the circuit in radians.""" return self._global_phase @global_phase.setter def global_phase(self, angle: ParameterValueType): """Set the phase of the circuit. Args: angle (float, ParameterExpression): radians """ if isinstance(angle, ParameterExpression) and angle.parameters: self._global_phase = angle else: # Set the phase to the [0, 2π) interval angle = float(angle) if not angle: self._global_phase = 0 else: self._global_phase = angle % (2 * np.pi) @property def parameters(self) -> ParameterView: """The parameters defined in the circuit. This attribute returns the :class:`.Parameter` objects in the circuit sorted alphabetically. Note that parameters instantiated with a :class:`.ParameterVector` are still sorted numerically. Examples: The snippet below shows that insertion order of parameters does not matter. .. code-block:: python >>> from qiskit.circuit import QuantumCircuit, Parameter >>> a, b, elephant = Parameter("a"), Parameter("b"), Parameter("elephant") >>> circuit = QuantumCircuit(1) >>> circuit.rx(b, 0) >>> circuit.rz(elephant, 0) >>> circuit.ry(a, 0) >>> circuit.parameters # sorted alphabetically! ParameterView([Parameter(a), Parameter(b), Parameter(elephant)]) Bear in mind that alphabetical sorting might be unintuitive when it comes to numbers. The literal "10" comes before "2" in strict alphabetical sorting. .. code-block:: python >>> from qiskit.circuit import QuantumCircuit, Parameter >>> angles = [Parameter("angle_1"), Parameter("angle_2"), Parameter("angle_10")] >>> circuit = QuantumCircuit(1) >>> circuit.u(*angles, 0) >>> circuit.draw() ┌─────────────────────────────┐ q: ┤ U(angle_1,angle_2,angle_10) ├ └─────────────────────────────┘ >>> circuit.parameters ParameterView([Parameter(angle_1), Parameter(angle_10), Parameter(angle_2)]) To respect numerical sorting, a :class:`.ParameterVector` can be used. .. code-block:: python >>> from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector >>> x = ParameterVector("x", 12) >>> circuit = QuantumCircuit(1) >>> for x_i in x: ... circuit.rx(x_i, 0) >>> circuit.parameters ParameterView([ ParameterVectorElement(x[0]), ParameterVectorElement(x[1]), ParameterVectorElement(x[2]), ParameterVectorElement(x[3]), ..., ParameterVectorElement(x[11]) ]) Returns: The sorted :class:`.Parameter` objects in the circuit. """ # parameters from gates if self._parameters is None: self._parameters = sort_parameters(self._unsorted_parameters()) # return as parameter view, which implements the set and list interface return ParameterView(self._parameters) @property def num_parameters(self) -> int: """The number of parameter objects in the circuit.""" return len(self._unsorted_parameters()) def _unsorted_parameters(self) -> set[Parameter]: """Efficiently get all parameters in the circuit, without any sorting overhead.""" parameters = set(self._parameter_table) if isinstance(self.global_phase, ParameterExpression): parameters.update(self.global_phase.parameters) return parameters @overload def assign_parameters( self, parameters: Union[Mapping[Parameter, ParameterValueType], Sequence[ParameterValueType]], inplace: Literal[False] = ..., *, flat_input: bool = ..., strict: bool = ..., ) -> "QuantumCircuit": ... @overload def assign_parameters( self, parameters: Union[Mapping[Parameter, ParameterValueType], Sequence[ParameterValueType]], inplace: Literal[True] = ..., *, flat_input: bool = ..., strict: bool = ..., ) -> None: ... def assign_parameters( # pylint: disable=missing-raises-doc self, parameters: Union[Mapping[Parameter, ParameterValueType], Sequence[ParameterValueType]], inplace: bool = False, *, flat_input: bool = False, strict: bool = True, ) -> Optional["QuantumCircuit"]: """Assign parameters to new parameters or values. If ``parameters`` is passed as a dictionary, the keys must be :class:`.Parameter` instances in the current circuit. The values of the dictionary can either be numeric values or new parameter objects. If ``parameters`` is passed as a list or array, the elements are assigned to the current parameters in the order of :attr:`parameters` which is sorted alphabetically (while respecting the ordering in :class:`.ParameterVector` objects). The values can be assigned to the current circuit object or to a copy of it. Args: parameters: Either a dictionary or iterable specifying the new parameter values. inplace: If False, a copy of the circuit with the bound parameters is returned. If True the circuit instance itself is modified. flat_input: If ``True`` and ``parameters`` is a mapping type, it is assumed to be exactly a mapping of ``{parameter: value}``. By default (``False``), the mapping may also contain :class:`.ParameterVector` keys that point to a corresponding sequence of values, and these will be unrolled during the mapping. strict: If ``False``, any parameters given in the mapping that are not used in the circuit will be ignored. If ``True`` (the default), an error will be raised indicating a logic error. Raises: CircuitError: If parameters is a dict and contains parameters not present in the circuit. ValueError: If parameters is a list/array and the length mismatches the number of free parameters in the circuit. Returns: A copy of the circuit with bound parameters if ``inplace`` is False, otherwise None. Examples: Create a parameterized circuit and assign the parameters in-place. .. plot:: :include-source: from qiskit.circuit import QuantumCircuit, Parameter circuit = QuantumCircuit(2) params = [Parameter('A'), Parameter('B'), Parameter('C')] circuit.ry(params[0], 0) circuit.crx(params[1], 0, 1) circuit.draw('mpl') circuit.assign_parameters({params[0]: params[2]}, inplace=True) circuit.draw('mpl') Bind the values out-of-place by list and get a copy of the original circuit. .. plot:: :include-source: from qiskit.circuit import QuantumCircuit, ParameterVector circuit = QuantumCircuit(2) params = ParameterVector('P', 2) circuit.ry(params[0], 0) circuit.crx(params[1], 0, 1) bound_circuit = circuit.assign_parameters([1, 2]) bound_circuit.draw('mpl') circuit.draw('mpl') """ if inplace: target = self else: target = self.copy() target._increment_instances() target._name_update() # Normalise the inputs into simple abstract interfaces, so we've dispatched the "iteration" # logic in one place at the start of the function. This lets us do things like calculate # and cache expensive properties for (e.g.) the sequence format only if they're used; for # many large, close-to-hardware circuits, we won't need the extra handling for # `global_phase` or recursive definition binding. # # During normalisation, be sure to reference 'parameters' and related things from 'self' not # 'target' so we can take advantage of any caching we might be doing. if isinstance(parameters, dict): raw_mapping = parameters if flat_input else self._unroll_param_dict(parameters) our_parameters = self._unsorted_parameters() if strict and (extras := raw_mapping.keys() - our_parameters): raise CircuitError( f"Cannot bind parameters ({', '.join(str(x) for x in extras)}) not present in" " the circuit." ) parameter_binds = _ParameterBindsDict(raw_mapping, our_parameters) else: our_parameters = self.parameters if len(parameters) != len(our_parameters): raise ValueError( "Mismatching number of values and parameters. For partial binding " "please pass a dictionary of {parameter: value} pairs." ) parameter_binds = _ParameterBindsSequence(our_parameters, parameters) # Clear out the parameter table for the relevant entries, since we'll be binding those. # Any new references to parameters are reinserted as part of the bind. target._parameters = None # This is deliberately eager, because we want the side effect of clearing the table. all_references = [ (parameter, value, target._parameter_table.pop(parameter, ())) for parameter, value in parameter_binds.items() ] seen_operations = {} # The meat of the actual binding for regular operations. for to_bind, bound_value, references in all_references: update_parameters = ( tuple(bound_value.parameters) if isinstance(bound_value, ParameterExpression) else () ) for operation, index in references: seen_operations[id(operation)] = operation assignee = operation.params[index] if isinstance(assignee, ParameterExpression): new_parameter = assignee.assign(to_bind, bound_value) for parameter in update_parameters: if parameter not in target._parameter_table: target._parameter_table[parameter] = ParameterReferences(()) target._parameter_table[parameter].add((operation, index)) if not new_parameter.parameters: if new_parameter.is_real(): new_parameter = ( int(new_parameter) if new_parameter._symbol_expr.is_integer else float(new_parameter) ) else: new_parameter = complex(new_parameter) new_parameter = operation.validate_parameter(new_parameter) elif isinstance(assignee, QuantumCircuit): new_parameter = assignee.assign_parameters( {to_bind: bound_value}, inplace=False, flat_input=True ) else: raise RuntimeError( # pragma: no cover f"Saw an unknown type during symbolic binding: {assignee}." " This may indicate an internal logic error in symbol tracking." ) operation.params[index] = new_parameter # After we've been through everything at the top level, make a single visit to each # operation we've seen, rebinding its definition if necessary. for operation in seen_operations.values(): if ( definition := getattr(operation, "_definition", None) ) is not None and definition.num_parameters: definition.assign_parameters( parameter_binds.mapping, inplace=True, flat_input=True, strict=False ) if isinstance(target.global_phase, ParameterExpression): new_phase = target.global_phase for parameter in new_phase.parameters & parameter_binds.mapping.keys(): new_phase = new_phase.assign(parameter, parameter_binds.mapping[parameter]) target.global_phase = new_phase # Finally, assign the parameters inside any of the calibrations. We don't track these in # the `ParameterTable`, so we manually reconstruct things. def map_calibration(qubits, parameters, schedule): modified = False new_parameters = list(parameters) for i, parameter in enumerate(new_parameters): if not isinstance(parameter, ParameterExpression): continue if not (contained := parameter.parameters & parameter_binds.mapping.keys()): continue for to_bind in contained: parameter = parameter.assign(to_bind, parameter_binds.mapping[to_bind]) if not parameter.parameters: parameter = ( int(parameter) if parameter._symbol_expr.is_integer else float(parameter) ) new_parameters[i] = parameter modified = True if modified: schedule.assign_parameters(parameter_binds.mapping) return (qubits, tuple(new_parameters)), schedule target._calibrations = defaultdict( dict, ( ( gate, dict( map_calibration(qubits, parameters, schedule) for (qubits, parameters), schedule in calibrations.items() ), ) for gate, calibrations in target._calibrations.items() ), ) return None if inplace else target @staticmethod def _unroll_param_dict( parameter_binds: Mapping[Parameter, ParameterValueType] ) -> Mapping[Parameter, ParameterValueType]: out = {} for parameter, value in parameter_binds.items(): if isinstance(parameter, ParameterVector): if len(parameter) != len(value): raise CircuitError( f"Parameter vector '{parameter.name}' has length {len(parameter)}," f" but was assigned to {len(value)} values." ) out.update(zip(parameter, value)) else: out[parameter] = value return out def bind_parameters( self, values: Union[Mapping[Parameter, float], Sequence[float]] ) -> "QuantumCircuit": """Assign numeric parameters to values yielding a new circuit. If the values are given as list or array they are bound to the circuit in the order of :attr:`parameters` (see the docstring for more details). To assign new Parameter objects or bind the values in-place, without yielding a new circuit, use the :meth:`assign_parameters` method. Args: values: ``{parameter: value, ...}`` or ``[value1, value2, ...]`` Raises: CircuitError: If values is a dict and contains parameters not present in the circuit. TypeError: If values contains a ParameterExpression. Returns: Copy of self with assignment substitution. """ if isinstance(values, dict): if any(isinstance(value, ParameterExpression) for value in values.values()): raise TypeError( "Found ParameterExpression in values; use assign_parameters() instead." ) return self.assign_parameters(values) else: if any(isinstance(value, ParameterExpression) for value in values): raise TypeError( "Found ParameterExpression in values; use assign_parameters() instead." ) return self.assign_parameters(values) def barrier(self, *qargs: QubitSpecifier, label=None) -> InstructionSet: """Apply :class:`~.library.Barrier`. If ``qargs`` is empty, applies to all qubits in the circuit. Args: qargs (QubitSpecifier): Specification for one or more qubit arguments. label (str): The string label of the barrier. Returns: qiskit.circuit.InstructionSet: handle to the added instructions. """ from .barrier import Barrier qubits: list[QubitSpecifier] = [] if not qargs: # None qubits.extend(self.qubits) for qarg in qargs: if isinstance(qarg, QuantumRegister): qubits.extend([qarg[j] for j in range(qarg.size)]) elif isinstance(qarg, list): qubits.extend(qarg) elif isinstance(qarg, range): qubits.extend(list(qarg)) elif isinstance(qarg, slice): qubits.extend(self.qubits[qarg]) else: qubits.append(qarg) return self.append(Barrier(len(qubits), label=label), qubits, []) def delay( self, duration: ParameterValueType, qarg: QubitSpecifier | None = None, unit: str = "dt", ) -> InstructionSet: """Apply :class:`~.circuit.Delay`. If qarg is ``None``, applies to all qubits. When applying to multiple qubits, delays with the same duration will be created. Args: duration (int or float or ParameterExpression): duration of the delay. qarg (Object): qubit argument to apply this delay. unit (str): unit of the duration. Supported units: ``'s'``, ``'ms'``, ``'us'``, ``'ns'``, ``'ps'``, and ``'dt'``. Default is ``'dt'``, i.e. integer time unit depending on the target backend. Returns: qiskit.circuit.InstructionSet: handle to the added instructions. Raises: CircuitError: if arguments have bad format. """ qubits: list[QubitSpecifier] = [] if qarg is None: # -> apply delays to all qubits for q in self.qubits: qubits.append(q) else: if isinstance(qarg, QuantumRegister): qubits.extend([qarg[j] for j in range(qarg.size)]) elif isinstance(qarg, list): qubits.extend(qarg) elif isinstance(qarg, (range, tuple)): qubits.extend(list(qarg)) elif isinstance(qarg, slice): qubits.extend(self.qubits[qarg]) else: qubits.append(qarg) instructions = InstructionSet(resource_requester=self._resolve_classical_resource) for q in qubits: inst: tuple[ Instruction, Sequence[QubitSpecifier] | None, Sequence[ClbitSpecifier] | None ] = (Delay(duration, unit), [q], []) self.append(*inst) instructions.add(*inst) return instructions def h(self, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.HGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.h import HGate return self.append(HGate(), [qubit], []) def ch( self, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CHGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.h import CHGate return self.append( CHGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [] ) def i(self, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.IGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.i import IGate return self.append(IGate(), [qubit], []) def id(self, qubit: QubitSpecifier) -> InstructionSet: # pylint: disable=invalid-name """Apply :class:`~qiskit.circuit.library.IGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. See Also: QuantumCircuit.i: the same function. """ return self.i(qubit) def ms(self, theta: ParameterValueType, qubits: Sequence[QubitSpecifier]) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.MSGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The angle of the rotation. qubits: The qubits to apply the gate to. Returns: A handle to the instructions created. """ # pylint: disable=cyclic-import from .library.generalized_gates.gms import MSGate return self.append(MSGate(len(qubits), theta), qubits) def p(self, theta: ParameterValueType, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.PhaseGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: THe angle of the rotation. qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.p import PhaseGate return self.append(PhaseGate(theta), [qubit], []) def cp( self, theta: ParameterValueType, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CPhaseGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The angle of the rotation. control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.p import CPhaseGate return self.append( CPhaseGate(theta, label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [] ) def mcp( self, lam: ParameterValueType, control_qubits: Sequence[QubitSpecifier], target_qubit: QubitSpecifier, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.MCPhaseGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: lam: The angle of the rotation. control_qubits: The qubits used as the controls. target_qubit: The qubit(s) targeted by the gate. Returns: A handle to the instructions created. """ from .library.standard_gates.p import MCPhaseGate num_ctrl_qubits = len(control_qubits) return self.append( MCPhaseGate(lam, num_ctrl_qubits), control_qubits[:] + [target_qubit], [] ) def r( self, theta: ParameterValueType, phi: ParameterValueType, qubit: QubitSpecifier ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The angle of the rotation. phi: The angle of the axis of rotation in the x-y plane. qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.r import RGate return self.append(RGate(theta, phi), [qubit], []) def rv( self, vx: ParameterValueType, vy: ParameterValueType, vz: ParameterValueType, qubit: QubitSpecifier, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RVGate`. For the full matrix form of this gate, see the underlying gate documentation. Rotation around an arbitrary rotation axis :math:`v`, where :math:`|v|` is the angle of rotation in radians. Args: vx: x-component of the rotation axis. vy: y-component of the rotation axis. vz: z-component of the rotation axis. qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.generalized_gates.rv import RVGate return self.append(RVGate(vx, vy, vz), [qubit], []) def rccx( self, control_qubit1: QubitSpecifier, control_qubit2: QubitSpecifier, target_qubit: QubitSpecifier, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RCCXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit1: The qubit(s) used as the first control. control_qubit2: The qubit(s) used as the second control. target_qubit: The qubit(s) targeted by the gate. Returns: A handle to the instructions created. """ from .library.standard_gates.x import RCCXGate return self.append(RCCXGate(), [control_qubit1, control_qubit2, target_qubit], []) def rcccx( self, control_qubit1: QubitSpecifier, control_qubit2: QubitSpecifier, control_qubit3: QubitSpecifier, target_qubit: QubitSpecifier, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RC3XGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit1: The qubit(s) used as the first control. control_qubit2: The qubit(s) used as the second control. control_qubit3: The qubit(s) used as the third control. target_qubit: The qubit(s) targeted by the gate. Returns: A handle to the instructions created. """ from .library.standard_gates.x import RC3XGate return self.append( RC3XGate(), [control_qubit1, control_qubit2, control_qubit3, target_qubit], [] ) def rx( self, theta: ParameterValueType, qubit: QubitSpecifier, label: str | None = None ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The rotation angle of the gate. qubit: The qubit(s) to apply the gate to. label: The string label of the gate in the circuit. Returns: A handle to the instructions created. """ from .library.standard_gates.rx import RXGate return self.append(RXGate(theta, label=label), [qubit], []) def crx( self, theta: ParameterValueType, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CRXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The angle of the rotation. control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.rx import CRXGate return self.append( CRXGate(theta, label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [] ) def rxx( self, theta: ParameterValueType, qubit1: QubitSpecifier, qubit2: QubitSpecifier ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RXXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The angle of the rotation. qubit1: The qubit(s) to apply the gate to. qubit2: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.rxx import RXXGate return self.append(RXXGate(theta), [qubit1, qubit2], []) def ry( self, theta: ParameterValueType, qubit: QubitSpecifier, label: str | None = None ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RYGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The rotation angle of the gate. qubit: The qubit(s) to apply the gate to. label: The string label of the gate in the circuit. Returns: A handle to the instructions created. """ from .library.standard_gates.ry import RYGate return self.append(RYGate(theta, label=label), [qubit], []) def cry( self, theta: ParameterValueType, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CRYGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The angle of the rotation. control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.ry import CRYGate return self.append( CRYGate(theta, label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [] ) def ryy( self, theta: ParameterValueType, qubit1: QubitSpecifier, qubit2: QubitSpecifier ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RYYGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The rotation angle of the gate. qubit1: The qubit(s) to apply the gate to. qubit2: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.ryy import RYYGate return self.append(RYYGate(theta), [qubit1, qubit2], []) def rz(self, phi: ParameterValueType, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RZGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: phi: The rotation angle of the gate. qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.rz import RZGate return self.append(RZGate(phi), [qubit], []) def crz( self, theta: ParameterValueType, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CRZGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The angle of the rotation. control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.rz import CRZGate return self.append( CRZGate(theta, label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [] ) def rzx( self, theta: ParameterValueType, qubit1: QubitSpecifier, qubit2: QubitSpecifier ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RZXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The rotation angle of the gate. qubit1: The qubit(s) to apply the gate to. qubit2: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.rzx import RZXGate return self.append(RZXGate(theta), [qubit1, qubit2], []) def rzz( self, theta: ParameterValueType, qubit1: QubitSpecifier, qubit2: QubitSpecifier ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RZZGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The rotation angle of the gate. qubit1: The qubit(s) to apply the gate to. qubit2: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.rzz import RZZGate return self.append(RZZGate(theta), [qubit1, qubit2], []) def ecr(self, qubit1: QubitSpecifier, qubit2: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.ECRGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit1, qubit2: The qubits to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.ecr import ECRGate return self.append(ECRGate(), [qubit1, qubit2], []) def s(self, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.SGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.s import SGate return self.append(SGate(), [qubit], []) def sdg(self, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.SdgGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.s import SdgGate return self.append(SdgGate(), [qubit], []) def cs( self, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CSGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.s import CSGate return self.append( CSGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [], ) def csdg( self, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CSdgGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.s import CSdgGate return self.append( CSdgGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [], ) def swap(self, qubit1: QubitSpecifier, qubit2: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.SwapGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit1, qubit2: The qubits to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.swap import SwapGate return self.append(SwapGate(), [qubit1, qubit2], []) def iswap(self, qubit1: QubitSpecifier, qubit2: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.iSwapGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit1, qubit2: The qubits to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.iswap import iSwapGate return self.append(iSwapGate(), [qubit1, qubit2], []) def cswap( self, control_qubit: QubitSpecifier, target_qubit1: QubitSpecifier, target_qubit2: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CSwapGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the control. target_qubit1: The qubit(s) targeted by the gate. target_qubit2: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. ``'1'``). Defaults to controlling on the ``'1'`` state. Returns: A handle to the instructions created. """ from .library.standard_gates.swap import CSwapGate return self.append( CSwapGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit1, target_qubit2], [], ) def fredkin( self, control_qubit: QubitSpecifier, target_qubit1: QubitSpecifier, target_qubit2: QubitSpecifier, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CSwapGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the control. target_qubit1: The qubit(s) targeted by the gate. target_qubit2: The qubit(s) targeted by the gate. Returns: A handle to the instructions created. See Also: QuantumCircuit.cswap: the same function with a different name. """ return self.cswap(control_qubit, target_qubit1, target_qubit2) def sx(self, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.SXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.sx import SXGate return self.append(SXGate(), [qubit], []) def sxdg(self, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.SXdgGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.sx import SXdgGate return self.append(SXdgGate(), [qubit], []) def csx( self, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CSXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.sx import CSXGate return self.append( CSXGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [], ) def t(self, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.TGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.t import TGate return self.append(TGate(), [qubit], []) def tdg(self, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.TdgGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.t import TdgGate return self.append(TdgGate(), [qubit], []) def u( self, theta: ParameterValueType, phi: ParameterValueType, lam: ParameterValueType, qubit: QubitSpecifier, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.UGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The :math:`\theta` rotation angle of the gate. phi: The :math:`\phi` rotation angle of the gate. lam: The :math:`\lambda` rotation angle of the gate. qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.u import UGate return self.append(UGate(theta, phi, lam), [qubit], []) def cu( self, theta: ParameterValueType, phi: ParameterValueType, lam: ParameterValueType, gamma: ParameterValueType, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.CUGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The :math:`\theta` rotation angle of the gate. phi: The :math:`\phi` rotation angle of the gate. lam: The :math:`\lambda` rotation angle of the gate. gamma: The global phase applied of the U gate, if applied. control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.u import CUGate return self.append( CUGate(theta, phi, lam, gamma, label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [], ) def x(self, qubit: QubitSpecifier, label: str | None = None) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.XGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. label: The string label of the gate in the circuit. Returns: A handle to the instructions created. """ from .library.standard_gates.x import XGate return self.append(XGate(label=label), [qubit], []) def cx( self, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.CXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.x import CXGate return self.append( CXGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [] ) def cnot( self, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.CXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. See Also: QuantumCircuit.cx: the same function with a different name. """ return self.cx(control_qubit, target_qubit, label, ctrl_state) def dcx(self, qubit1: QubitSpecifier, qubit2: QubitSpecifier) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.DCXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit1: The qubit(s) to apply the gate to. qubit2: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.dcx import DCXGate return self.append(DCXGate(), [qubit1, qubit2], []) def ccx( self, control_qubit1: QubitSpecifier, control_qubit2: QubitSpecifier, target_qubit: QubitSpecifier, ctrl_state: str | int | None = None, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.CCXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit1: The qubit(s) used as the first control. control_qubit2: The qubit(s) used as the second control. target_qubit: The qubit(s) targeted by the gate. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.x import CCXGate return self.append( CCXGate(ctrl_state=ctrl_state), [control_qubit1, control_qubit2, target_qubit], [], ) def toffoli( self, control_qubit1: QubitSpecifier, control_qubit2: QubitSpecifier, target_qubit: QubitSpecifier, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.CCXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit1: The qubit(s) used as the first control. control_qubit2: The qubit(s) used as the second control. target_qubit: The qubit(s) targeted by the gate. Returns: A handle to the instructions created. See Also: QuantumCircuit.ccx: the same gate with a different name. """ return self.ccx(control_qubit1, control_qubit2, target_qubit) def mcx( self, control_qubits: Sequence[QubitSpecifier], target_qubit: QubitSpecifier, ancilla_qubits: QubitSpecifier | Sequence[QubitSpecifier] | None = None, mode: str = "noancilla", ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.MCXGate`. The multi-cX gate can be implemented using different techniques, which use different numbers of ancilla qubits and have varying circuit depth. These modes are: - ``'noancilla'``: Requires 0 ancilla qubits. - ``'recursion'``: Requires 1 ancilla qubit if more than 4 controls are used, otherwise 0. - ``'v-chain'``: Requires 2 less ancillas than the number of control qubits. - ``'v-chain-dirty'``: Same as for the clean ancillas (but the circuit will be longer). For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubits: The qubits used as the controls. target_qubit: The qubit(s) targeted by the gate. ancilla_qubits: The qubits used as the ancillae, if the mode requires them. mode: The choice of mode, explained further above. Returns: A handle to the instructions created. Raises: ValueError: if the given mode is not known, or if too few ancilla qubits are passed. AttributeError: if no ancilla qubits are passed, but some are needed. """ from .library.standard_gates.x import MCXGrayCode, MCXRecursive, MCXVChain num_ctrl_qubits = len(control_qubits) available_implementations = { "noancilla": MCXGrayCode(num_ctrl_qubits), "recursion": MCXRecursive(num_ctrl_qubits), "v-chain": MCXVChain(num_ctrl_qubits, False), "v-chain-dirty": MCXVChain(num_ctrl_qubits, dirty_ancillas=True), # outdated, previous names "advanced": MCXRecursive(num_ctrl_qubits), "basic": MCXVChain(num_ctrl_qubits, dirty_ancillas=False), "basic-dirty-ancilla": MCXVChain(num_ctrl_qubits, dirty_ancillas=True), } # check ancilla input if ancilla_qubits: _ = self.qbit_argument_conversion(ancilla_qubits) try: gate = available_implementations[mode] except KeyError as ex: all_modes = list(available_implementations.keys()) raise ValueError( f"Unsupported mode ({mode}) selected, choose one of {all_modes}" ) from ex if hasattr(gate, "num_ancilla_qubits") and gate.num_ancilla_qubits > 0: required = gate.num_ancilla_qubits if ancilla_qubits is None: raise AttributeError(f"No ancillas provided, but {required} are needed!") # convert ancilla qubits to a list if they were passed as int or qubit if not hasattr(ancilla_qubits, "__len__"): ancilla_qubits = [ancilla_qubits] if len(ancilla_qubits) < required: actually = len(ancilla_qubits) raise ValueError(f"At least {required} ancillas required, but {actually} given.") # size down if too many ancillas were provided ancilla_qubits = ancilla_qubits[:required] else: ancilla_qubits = [] return self.append(gate, control_qubits[:] + [target_qubit] + ancilla_qubits[:], []) def mct( self, control_qubits: Sequence[QubitSpecifier], target_qubit: QubitSpecifier, ancilla_qubits: QubitSpecifier | Sequence[QubitSpecifier] | None = None, mode: str = "noancilla", ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.MCXGate`. The multi-cX gate can be implemented using different techniques, which use different numbers of ancilla qubits and have varying circuit depth. These modes are: - ``'noancilla'``: Requires 0 ancilla qubits. - ``'recursion'``: Requires 1 ancilla qubit if more than 4 controls are used, otherwise 0. - ``'v-chain'``: Requires 2 less ancillas than the number of control qubits. - ``'v-chain-dirty'``: Same as for the clean ancillas (but the circuit will be longer). For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubits: The qubits used as the controls. target_qubit: The qubit(s) targeted by the gate. ancilla_qubits: The qubits used as the ancillae, if the mode requires them. mode: The choice of mode, explained further above. Returns: A handle to the instructions created. Raises: ValueError: if the given mode is not known, or if too few ancilla qubits are passed. AttributeError: if no ancilla qubits are passed, but some are needed. See Also: QuantumCircuit.mcx: the same gate with a different name. """ return self.mcx(control_qubits, target_qubit, ancilla_qubits, mode) def y(self, qubit: QubitSpecifier) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.YGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.y import YGate return self.append(YGate(), [qubit], []) def cy( self, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.CYGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the controls. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.y import CYGate return self.append( CYGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [] ) def z(self, qubit: QubitSpecifier) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.ZGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.z import ZGate return self.append(ZGate(), [qubit], []) def cz( self, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.CZGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the controls. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.z import CZGate return self.append( CZGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [] ) def ccz( self, control_qubit1: QubitSpecifier, control_qubit2: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.CCZGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit1: The qubit(s) used as the first control. control_qubit2: The qubit(s) used as the second control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '10'). Defaults to controlling on the '11' state. Returns: A handle to the instructions created. """ from .library.standard_gates.z import CCZGate return self.append( CCZGate(label=label, ctrl_state=ctrl_state), [control_qubit1, control_qubit2, target_qubit], [], ) def pauli( self, pauli_string: str, qubits: Sequence[QubitSpecifier], ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.PauliGate`. Args: pauli_string: A string representing the Pauli operator to apply, e.g. 'XX'. qubits: The qubits to apply this gate to. Returns: A handle to the instructions created. """ from qiskit.circuit.library.generalized_gates.pauli import PauliGate return self.append(PauliGate(pauli_string), qubits, []) def _push_scope( self, qubits: Iterable[Qubit] = (), clbits: Iterable[Clbit] = (), registers: Iterable[Register] = (), allow_jumps: bool = True, forbidden_message: Optional[str] = None, ): """Add a scope for collecting instructions into this circuit. This should only be done by the control-flow context managers, which will handle cleaning up after themselves at the end as well. Args: qubits: Any qubits that this scope should automatically use. clbits: Any clbits that this scope should automatically use. allow_jumps: Whether this scope allows jumps to be used within it. forbidden_message: If given, all attempts to add instructions to this scope will raise a :exc:`.CircuitError` with this message. """ # pylint: disable=cyclic-import from qiskit.circuit.controlflow.builder import ControlFlowBuilderBlock # Chain resource requests so things like registers added to inner scopes via conditions are # requested in the outer scope as well. if self._control_flow_scopes: resource_requester = self._control_flow_scopes[-1].request_classical_resource else: resource_requester = self._resolve_classical_resource self._control_flow_scopes.append( ControlFlowBuilderBlock( qubits, clbits, resource_requester=resource_requester, registers=registers, allow_jumps=allow_jumps, forbidden_message=forbidden_message, ) ) def _pop_scope(self) -> "qiskit.circuit.controlflow.builder.ControlFlowBuilderBlock": """Finish a scope used in the control-flow builder interface, and return it to the caller. This should only be done by the control-flow context managers, since they naturally synchronise the creation and deletion of stack elements.""" return self._control_flow_scopes.pop() def _peek_previous_instruction_in_scope(self) -> CircuitInstruction: """Return the instruction 3-tuple of the most recent instruction in the current scope, even if that scope is currently under construction. This function is only intended for use by the control-flow ``if``-statement builders, which may need to modify a previous instruction.""" if self._control_flow_scopes: return self._control_flow_scopes[-1].peek() if not self._data: raise CircuitError("This circuit contains no instructions.") return self._data[-1] def _pop_previous_instruction_in_scope(self) -> CircuitInstruction: """Return the instruction 3-tuple of the most recent instruction in the current scope, even if that scope is currently under construction, and remove it from that scope. This function is only intended for use by the control-flow ``if``-statement builders, which may need to replace a previous instruction with another. """ if self._control_flow_scopes: return self._control_flow_scopes[-1].pop() if not self._data: raise CircuitError("This circuit contains no instructions.") instruction = self._data.pop() if isinstance(instruction.operation, Instruction): self._update_parameter_table_on_instruction_removal(instruction) return instruction def _update_parameter_table_on_instruction_removal(self, instruction: CircuitInstruction): """Update the :obj:`.ParameterTable` of this circuit given that an instance of the given ``instruction`` has just been removed from the circuit. .. note:: This does not account for the possibility for the same instruction instance being added more than once to the circuit. At the time of writing (2021-11-17, main commit 271a82f) there is a defensive ``deepcopy`` of parameterised instructions inside :meth:`.QuantumCircuit.append`, so this should be safe. Trying to account for it would involve adding a potentially quadratic-scaling loop to check each entry in ``data``. """ atomic_parameters: list[tuple[Parameter, int]] = [] for index, parameter in enumerate(instruction.operation.params): if isinstance(parameter, (ParameterExpression, QuantumCircuit)): atomic_parameters.extend((p, index) for p in parameter.parameters) for atomic_parameter, index in atomic_parameters: new_entries = self._parameter_table[atomic_parameter].copy() new_entries.discard((instruction.operation, index)) if not new_entries: del self._parameter_table[atomic_parameter] # Invalidate cache. self._parameters = None else: self._parameter_table[atomic_parameter] = new_entries @typing.overload def while_loop( self, condition: tuple[ClassicalRegister | Clbit, int] | expr.Expr, body: None, qubits: None, clbits: None, *, label: str | None, ) -> "qiskit.circuit.controlflow.while_loop.WhileLoopContext": ... @typing.overload def while_loop( self, condition: tuple[ClassicalRegister | Clbit, int] | expr.Expr, body: "QuantumCircuit", qubits: Sequence[QubitSpecifier], clbits: Sequence[ClbitSpecifier], *, label: str | None, ) -> InstructionSet: ... def while_loop(self, condition, body=None, qubits=None, clbits=None, *, label=None): """Create a ``while`` loop on this circuit. There are two forms for calling this function. If called with all its arguments (with the possible exception of ``label``), it will create a :obj:`~qiskit.circuit.controlflow.WhileLoopOp` with the given ``body``. If ``body`` (and ``qubits`` and ``clbits``) are *not* passed, then this acts as a context manager, which will automatically build a :obj:`~qiskit.circuit.controlflow.WhileLoopOp` when the scope finishes. In this form, you do not need to keep track of the qubits or clbits you are using, because the scope will handle it for you. Example usage:: from qiskit.circuit import QuantumCircuit, Clbit, Qubit bits = [Qubit(), Qubit(), Clbit()] qc = QuantumCircuit(bits) with qc.while_loop((bits[2], 0)): qc.h(0) qc.cx(0, 1) qc.measure(0, 0) Args: condition (Tuple[Union[ClassicalRegister, Clbit], int]): An equality condition to be checked prior to executing ``body``. The left-hand side of the condition must be a :obj:`~ClassicalRegister` or a :obj:`~Clbit`, and the right-hand side must be an integer or boolean. body (Optional[QuantumCircuit]): The loop body to be repeatedly executed. Omit this to use the context-manager mode. qubits (Optional[Sequence[Qubit]]): The circuit qubits over which the loop body should be run. Omit this to use the context-manager mode. clbits (Optional[Sequence[Clbit]]): The circuit clbits over which the loop body should be run. Omit this to use the context-manager mode. label (Optional[str]): The string label of the instruction in the circuit. Returns: InstructionSet or WhileLoopContext: If used in context-manager mode, then this should be used as a ``with`` resource, which will infer the block content and operands on exit. If the full form is used, then this returns a handle to the instructions created. Raises: CircuitError: if an incorrect calling convention is used. """ # pylint: disable=cyclic-import from qiskit.circuit.controlflow.while_loop import WhileLoopOp, WhileLoopContext if isinstance(condition, expr.Expr): condition = self._validate_expr(condition) else: condition = (self._resolve_classical_resource(condition[0]), condition[1]) if body is None: if qubits is not None or clbits is not None: raise CircuitError( "When using 'while_loop' as a context manager," " you cannot pass qubits or clbits." ) return WhileLoopContext(self, condition, label=label) elif qubits is None or clbits is None: raise CircuitError( "When using 'while_loop' with a body, you must pass qubits and clbits." ) return self.append(WhileLoopOp(condition, body, label), qubits, clbits) @typing.overload def for_loop( self, indexset: Iterable[int], loop_parameter: Parameter | None, body: None, qubits: None, clbits: None, *, label: str | None, ) -> "qiskit.circuit.controlflow.for_loop.ForLoopContext": ... @typing.overload def for_loop( self, indexset: Iterable[int], loop_parameter: Union[Parameter, None], body: "QuantumCircuit", qubits: Sequence[QubitSpecifier], clbits: Sequence[ClbitSpecifier], *, label: str | None, ) -> InstructionSet: ... def for_loop( self, indexset, loop_parameter=None, body=None, qubits=None, clbits=None, *, label=None ): """Create a ``for`` loop on this circuit. There are two forms for calling this function. If called with all its arguments (with the possible exception of ``label``), it will create a :class:`~qiskit.circuit.ForLoopOp` with the given ``body``. If ``body`` (and ``qubits`` and ``clbits``) are *not* passed, then this acts as a context manager, which, when entered, provides a loop variable (unless one is given, in which case it will be reused) and will automatically build a :class:`~qiskit.circuit.ForLoopOp` when the scope finishes. In this form, you do not need to keep track of the qubits or clbits you are using, because the scope will handle it for you. For example:: from qiskit import QuantumCircuit qc = QuantumCircuit(2, 1) with qc.for_loop(range(5)) as i: qc.h(0) qc.cx(0, 1) qc.measure(0, 0) qc.break_loop().c_if(0, True) Args: indexset (Iterable[int]): A collection of integers to loop over. Always necessary. loop_parameter (Optional[Parameter]): The parameter used within ``body`` to which the values from ``indexset`` will be assigned. In the context-manager form, if this argument is not supplied, then a loop parameter will be allocated for you and returned as the value of the ``with`` statement. This will only be bound into the circuit if it is used within the body. If this argument is ``None`` in the manual form of this method, ``body`` will be repeated once for each of the items in ``indexset`` but their values will be ignored. body (Optional[QuantumCircuit]): The loop body to be repeatedly executed. Omit this to use the context-manager mode. qubits (Optional[Sequence[QubitSpecifier]]): The circuit qubits over which the loop body should be run. Omit this to use the context-manager mode. clbits (Optional[Sequence[ClbitSpecifier]]): The circuit clbits over which the loop body should be run. Omit this to use the context-manager mode. label (Optional[str]): The string label of the instruction in the circuit. Returns: InstructionSet or ForLoopContext: depending on the call signature, either a context manager for creating the for loop (it will automatically be added to the circuit at the end of the block), or an :obj:`~InstructionSet` handle to the appended loop operation. Raises: CircuitError: if an incorrect calling convention is used. """ # pylint: disable=cyclic-import from qiskit.circuit.controlflow.for_loop import ForLoopOp, ForLoopContext if body is None: if qubits is not None or clbits is not None: raise CircuitError( "When using 'for_loop' as a context manager, you cannot pass qubits or clbits." ) return ForLoopContext(self, indexset, loop_parameter, label=label) elif qubits is None or clbits is None: raise CircuitError( "When using 'for_loop' with a body, you must pass qubits and clbits." ) return self.append(ForLoopOp(indexset, loop_parameter, body, label), qubits, clbits) @typing.overload def if_test( self, condition: tuple[ClassicalRegister | Clbit, int], true_body: None, qubits: None, clbits: None, *, label: str | None, ) -> "qiskit.circuit.controlflow.if_else.IfContext": ... @typing.overload def if_test( self, condition: tuple[ClassicalRegister | Clbit, int], true_body: "QuantumCircuit", qubits: Sequence[QubitSpecifier], clbits: Sequence[ClbitSpecifier], *, label: str | None = None, ) -> InstructionSet: ... def if_test( self, condition, true_body=None, qubits=None, clbits=None, *, label=None, ): """Create an ``if`` statement on this circuit. There are two forms for calling this function. If called with all its arguments (with the possible exception of ``label``), it will create a :obj:`~qiskit.circuit.IfElseOp` with the given ``true_body``, and there will be no branch for the ``false`` condition (see also the :meth:`.if_else` method). However, if ``true_body`` (and ``qubits`` and ``clbits``) are *not* passed, then this acts as a context manager, which can be used to build ``if`` statements. The return value of the ``with`` statement is a chainable context manager, which can be used to create subsequent ``else`` blocks. In this form, you do not need to keep track of the qubits or clbits you are using, because the scope will handle it for you. For example:: from qiskit.circuit import QuantumCircuit, Qubit, Clbit bits = [Qubit(), Qubit(), Qubit(), Clbit(), Clbit()] qc = QuantumCircuit(bits) qc.h(0) qc.cx(0, 1) qc.measure(0, 0) qc.h(0) qc.cx(0, 1) qc.measure(0, 1) with qc.if_test((bits[3], 0)) as else_: qc.x(2) with else_: qc.h(2) qc.z(2) Args: condition (Tuple[Union[ClassicalRegister, Clbit], int]): A condition to be evaluated at circuit runtime which, if true, will trigger the evaluation of ``true_body``. Can be specified as either a tuple of a ``ClassicalRegister`` to be tested for equality with a given ``int``, or as a tuple of a ``Clbit`` to be compared to either a ``bool`` or an ``int``. true_body (Optional[QuantumCircuit]): The circuit body to be run if ``condition`` is true. qubits (Optional[Sequence[QubitSpecifier]]): The circuit qubits over which the if/else should be run. clbits (Optional[Sequence[ClbitSpecifier]]): The circuit clbits over which the if/else should be run. label (Optional[str]): The string label of the instruction in the circuit. Returns: InstructionSet or IfContext: depending on the call signature, either a context manager for creating the ``if`` block (it will automatically be added to the circuit at the end of the block), or an :obj:`~InstructionSet` handle to the appended conditional operation. Raises: CircuitError: If the provided condition references Clbits outside the enclosing circuit. CircuitError: if an incorrect calling convention is used. Returns: A handle to the instruction created. """ # pylint: disable=cyclic-import from qiskit.circuit.controlflow.if_else import IfElseOp, IfContext if isinstance(condition, expr.Expr): condition = self._validate_expr(condition) else: condition = (self._resolve_classical_resource(condition[0]), condition[1]) if true_body is None: if qubits is not None or clbits is not None: raise CircuitError( "When using 'if_test' as a context manager, you cannot pass qubits or clbits." ) # We can only allow jumps if we're in a loop block, but the default path (no scopes) # also allows adding jumps to support the more verbose internal mode. in_loop = bool(self._control_flow_scopes and self._control_flow_scopes[-1].allow_jumps) return IfContext(self, condition, in_loop=in_loop, label=label) elif qubits is None or clbits is None: raise CircuitError("When using 'if_test' with a body, you must pass qubits and clbits.") return self.append(IfElseOp(condition, true_body, None, label), qubits, clbits) def if_else( self, condition: tuple[ClassicalRegister, int] | tuple[Clbit, int] | tuple[Clbit, bool], true_body: "QuantumCircuit", false_body: "QuantumCircuit", qubits: Sequence[QubitSpecifier], clbits: Sequence[ClbitSpecifier], label: str | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.IfElseOp`. .. note:: This method does not have an associated context-manager form, because it is already handled by the :meth:`.if_test` method. You can use the ``else`` part of that with something such as:: from qiskit.circuit import QuantumCircuit, Qubit, Clbit bits = [Qubit(), Qubit(), Clbit()] qc = QuantumCircuit(bits) qc.h(0) qc.cx(0, 1) qc.measure(0, 0) with qc.if_test((bits[2], 0)) as else_: qc.h(0) with else_: qc.x(0) Args: condition: A condition to be evaluated at circuit runtime which, if true, will trigger the evaluation of ``true_body``. Can be specified as either a tuple of a ``ClassicalRegister`` to be tested for equality with a given ``int``, or as a tuple of a ``Clbit`` to be compared to either a ``bool`` or an ``int``. true_body: The circuit body to be run if ``condition`` is true. false_body: The circuit to be run if ``condition`` is false. qubits: The circuit qubits over which the if/else should be run. clbits: The circuit clbits over which the if/else should be run. label: The string label of the instruction in the circuit. Raises: CircuitError: If the provided condition references Clbits outside the enclosing circuit. Returns: A handle to the instruction created. """ # pylint: disable=cyclic-import from qiskit.circuit.controlflow.if_else import IfElseOp if isinstance(condition, expr.Expr): condition = self._validate_expr(condition) else: condition = (self._resolve_classical_resource(condition[0]), condition[1]) return self.append(IfElseOp(condition, true_body, false_body, label), qubits, clbits) @typing.overload def switch( self, target: Union[ClbitSpecifier, ClassicalRegister], cases: None, qubits: None, clbits: None, *, label: Optional[str], ) -> "qiskit.circuit.controlflow.switch_case.SwitchContext": ... @typing.overload def switch( self, target: Union[ClbitSpecifier, ClassicalRegister], cases: Iterable[Tuple[typing.Any, QuantumCircuit]], qubits: Sequence[QubitSpecifier], clbits: Sequence[ClbitSpecifier], *, label: Optional[str], ) -> InstructionSet: ... def switch(self, target, cases=None, qubits=None, clbits=None, *, label=None): """Create a ``switch``/``case`` structure on this circuit. There are two forms for calling this function. If called with all its arguments (with the possible exception of ``label``), it will create a :class:`.SwitchCaseOp` with the given case structure. If ``cases`` (and ``qubits`` and ``clbits``) are *not* passed, then this acts as a context manager, which will automatically build a :class:`.SwitchCaseOp` when the scope finishes. In this form, you do not need to keep track of the qubits or clbits you are using, because the scope will handle it for you. Example usage:: from qiskit.circuit import QuantumCircuit, ClassicalRegister, QuantumRegister qreg = QuantumRegister(3) creg = ClassicalRegister(3) qc = QuantumCircuit(qreg, creg) qc.h([0, 1, 2]) qc.measure([0, 1, 2], [0, 1, 2]) with qc.switch(creg) as case: with case(0): qc.x(0) with case(1, 2): qc.z(1) with case(case.DEFAULT): qc.cx(0, 1) Args: target (Union[ClassicalRegister, Clbit]): The classical value to switch one. This must be integer-like. cases (Iterable[Tuple[typing.Any, QuantumCircuit]]): A sequence of case specifiers. Each tuple defines one case body (the second item). The first item of the tuple can be either a single integer value, the special value :data:`.CASE_DEFAULT`, or a tuple of several integer values. Each of the integer values will be tried in turn; control will then pass to the body corresponding to the first match. :data:`.CASE_DEFAULT` matches all possible values. Omit in context-manager form. qubits (Sequence[Qubit]): The circuit qubits over which all case bodies execute. Omit in context-manager form. clbits (Sequence[Clbit]): The circuit clbits over which all case bodies execute. Omit in context-manager form. label (Optional[str]): The string label of the instruction in the circuit. Returns: InstructionSet or SwitchCaseContext: If used in context-manager mode, then this should be used as a ``with`` resource, which will return an object that can be repeatedly entered to produce cases for the switch statement. If the full form is used, then this returns a handle to the instructions created. Raises: CircuitError: if an incorrect calling convention is used. """ # pylint: disable=cyclic-import from qiskit.circuit.controlflow.switch_case import SwitchCaseOp, SwitchContext if isinstance(target, expr.Expr): target = self._validate_expr(target) else: target = self._resolve_classical_resource(target) if cases is None: if qubits is not None or clbits is not None: raise CircuitError( "When using 'switch' as a context manager, you cannot pass qubits or clbits." ) in_loop = bool(self._control_flow_scopes and self._control_flow_scopes[-1].allow_jumps) return SwitchContext(self, target, in_loop=in_loop, label=label) if qubits is None or clbits is None: raise CircuitError("When using 'switch' with cases, you must pass qubits and clbits.") return self.append(SwitchCaseOp(target, cases, label=label), qubits, clbits) def break_loop(self) -> InstructionSet: """Apply :class:`~qiskit.circuit.BreakLoopOp`. .. warning:: If you are using the context-manager "builder" forms of :meth:`.if_test`, :meth:`.for_loop` or :meth:`.while_loop`, you can only call this method if you are within a loop context, because otherwise the "resource width" of the operation cannot be determined. This would quickly lead to invalid circuits, and so if you are trying to construct a reusable loop body (without the context managers), you must also use the non-context-manager form of :meth:`.if_test` and :meth:`.if_else`. Take care that the :obj:`.BreakLoopOp` instruction must span all the resources of its containing loop, not just the immediate scope. Returns: A handle to the instruction created. Raises: CircuitError: if this method was called within a builder context, but not contained within a loop. """ # pylint: disable=cyclic-import from qiskit.circuit.controlflow.break_loop import BreakLoopOp, BreakLoopPlaceholder if self._control_flow_scopes: operation = BreakLoopPlaceholder() resources = operation.placeholder_resources() return self.append(operation, resources.qubits, resources.clbits) return self.append(BreakLoopOp(self.num_qubits, self.num_clbits), self.qubits, self.clbits) def continue_loop(self) -> InstructionSet: """Apply :class:`~qiskit.circuit.ContinueLoopOp`. .. warning:: If you are using the context-manager "builder" forms of :meth:`.if_test`, :meth:`.for_loop` or :meth:`.while_loop`, you can only call this method if you are within a loop context, because otherwise the "resource width" of the operation cannot be determined. This would quickly lead to invalid circuits, and so if you are trying to construct a reusable loop body (without the context managers), you must also use the non-context-manager form of :meth:`.if_test` and :meth:`.if_else`. Take care that the :class:`~qiskit.circuit.ContinueLoopOp` instruction must span all the resources of its containing loop, not just the immediate scope. Returns: A handle to the instruction created. Raises: CircuitError: if this method was called within a builder context, but not contained within a loop. """ # pylint: disable=cyclic-import from qiskit.circuit.controlflow.continue_loop import ContinueLoopOp, ContinueLoopPlaceholder if self._control_flow_scopes: operation = ContinueLoopPlaceholder() resources = operation.placeholder_resources() return self.append(operation, resources.qubits, resources.clbits) return self.append( ContinueLoopOp(self.num_qubits, self.num_clbits), self.qubits, self.clbits ) def add_calibration( self, gate: Union[Gate, str], qubits: Sequence[int], # Schedule has the type `qiskit.pulse.Schedule`, but `qiskit.pulse` cannot be imported # while this module is, and so Sphinx will not accept a forward reference to it. Sphinx # needs the types available at runtime, whereas mypy will accept it, because it handles the # type checking by static analysis. schedule, params: Sequence[ParameterValueType] | None = None, ) -> None: """Register a low-level, custom pulse definition for the given gate. Args: gate (Union[Gate, str]): Gate information. qubits (Union[int, Tuple[int]]): List of qubits to be measured. schedule (Schedule): Schedule information. params (Optional[List[Union[float, Parameter]]]): A list of parameters. Raises: Exception: if the gate is of type string and params is None. """ def _format(operand): try: # Using float/complex value as a dict key is not good idea. # This makes the mapping quite sensitive to the rounding error. # However, the mechanism is already tied to the execution model (i.e. pulse gate) # and we cannot easily update this rule. # The same logic exists in DAGCircuit.add_calibration. evaluated = complex(operand) if np.isreal(evaluated): evaluated = float(evaluated.real) if evaluated.is_integer(): evaluated = int(evaluated) return evaluated except TypeError: # Unassigned parameter return operand if isinstance(gate, Gate): params = gate.params gate = gate.name if params is not None: params = tuple(map(_format, params)) else: params = () self._calibrations[gate][(tuple(qubits), params)] = schedule # Functions only for scheduled circuits def qubit_duration(self, *qubits: Union[Qubit, int]) -> float: """Return the duration between the start and stop time of the first and last instructions, excluding delays, over the supplied qubits. Its time unit is ``self.unit``. Args: *qubits: Qubits within ``self`` to include. Returns: Return the duration between the first start and last stop time of non-delay instructions """ return self.qubit_stop_time(*qubits) - self.qubit_start_time(*qubits) def qubit_start_time(self, *qubits: Union[Qubit, int]) -> float: """Return the start time of the first instruction, excluding delays, over the supplied qubits. Its time unit is ``self.unit``. Return 0 if there are no instructions over qubits Args: *qubits: Qubits within ``self`` to include. Integers are allowed for qubits, indicating indices of ``self.qubits``. Returns: Return the start time of the first instruction, excluding delays, over the qubits Raises: CircuitError: if ``self`` is a not-yet scheduled circuit. """ if self.duration is None: # circuit has only delays, this is kind of scheduled for instruction in self._data: if not isinstance(instruction.operation, Delay): raise CircuitError( "qubit_start_time undefined. Circuit must be scheduled first." ) return 0 qubits = [self.qubits[q] if isinstance(q, int) else q for q in qubits] starts = {q: 0 for q in qubits} dones = {q: False for q in qubits} for instruction in self._data: for q in qubits: if q in instruction.qubits: if isinstance(instruction.operation, Delay): if not dones[q]: starts[q] += instruction.operation.duration else: dones[q] = True if len(qubits) == len([done for done in dones.values() if done]): # all done return min(start for start in starts.values()) return 0 # If there are no instructions over bits def qubit_stop_time(self, *qubits: Union[Qubit, int]) -> float: """Return the stop time of the last instruction, excluding delays, over the supplied qubits. Its time unit is ``self.unit``. Return 0 if there are no instructions over qubits Args: *qubits: Qubits within ``self`` to include. Integers are allowed for qubits, indicating indices of ``self.qubits``. Returns: Return the stop time of the last instruction, excluding delays, over the qubits Raises: CircuitError: if ``self`` is a not-yet scheduled circuit. """ if self.duration is None: # circuit has only delays, this is kind of scheduled for instruction in self._data: if not isinstance(instruction.operation, Delay): raise CircuitError( "qubit_stop_time undefined. Circuit must be scheduled first." ) return 0 qubits = [self.qubits[q] if isinstance(q, int) else q for q in qubits] stops = {q: self.duration for q in qubits} dones = {q: False for q in qubits} for instruction in reversed(self._data): for q in qubits: if q in instruction.qubits: if isinstance(instruction.operation, Delay): if not dones[q]: stops[q] -= instruction.operation.duration else: dones[q] = True if len(qubits) == len([done for done in dones.values() if done]): # all done return max(stop for stop in stops.values()) return 0 # If there are no instructions over bits class _ParameterBindsDict: __slots__ = ("mapping", "allowed_keys") def __init__(self, mapping, allowed_keys): self.mapping = mapping self.allowed_keys = allowed_keys def items(self): """Iterator through all the keys in the mapping that we care about. Wrapping the main mapping allows us to avoid reconstructing a new 'dict', but just use the given 'mapping' without any copy / reconstruction.""" for parameter, value in self.mapping.items(): if parameter in self.allowed_keys: yield parameter, value class _ParameterBindsSequence: __slots__ = ("parameters", "values", "mapping_cache") def __init__(self, parameters, values): self.parameters = parameters self.values = values self.mapping_cache = None def items(self): """Iterator through all the keys in the mapping that we care about.""" return zip(self.parameters, self.values) @property def mapping(self): """Cached version of a mapping. This is only generated on demand.""" if self.mapping_cache is None: self.mapping_cache = dict(zip(self.parameters, self.values)) return self.mapping_cache # Used by the OQ2 exporter. Just needs to have enough parameters to support the largest standard # (non-controlled) gate in our standard library. We have to use the same `Parameter` instances each # time so the equality comparisons will work. _QASM2_FIXED_PARAMETERS = [Parameter("param0"), Parameter("param1"), Parameter("param2")] def _qasm2_custom_operation_statement( instruction, existing_gate_names, gates_to_define, bit_labels ): operation = _qasm2_define_custom_operation( instruction.operation, existing_gate_names, gates_to_define ) # Insert qasm representation of the original instruction if instruction.clbits: bits = itertools.chain(instruction.qubits, instruction.clbits) else: bits = instruction.qubits bits_qasm = ",".join(bit_labels[j] for j in bits) instruction_qasm = f"{_instruction_qasm2(operation)} {bits_qasm};" return instruction_qasm def _qasm2_define_custom_operation(operation, existing_gate_names, gates_to_define): """Extract a custom definition from the given operation, and append any necessary additional subcomponents' definitions to the ``gates_to_define`` ordered dictionary. Returns a potentially new :class:`.Instruction`, which should be used for the :meth:`~.Instruction.qasm` call (it may have been renamed).""" # pylint: disable=cyclic-import from qiskit.circuit import library as lib from qiskit.qasm2 import QASM2ExportError if operation.name in existing_gate_names: return operation # Check instructions names or label are valid escaped = _qasm_escape_name(operation.name, "gate_") if escaped != operation.name: operation = operation.copy(name=escaped) # These are built-in gates that are known to be safe to construct by passing the correct number # of `Parameter` instances positionally, and have no other information. We can't guarantee that # if they've been subclassed, though. This is a total hack; ideally we'd be able to inspect the # "calling" signatures of Qiskit `Gate` objects to know whether they're safe to re-parameterise. known_good_parameterized = { lib.PhaseGate, lib.RGate, lib.RXGate, lib.RXXGate, lib.RYGate, lib.RYYGate, lib.RZGate, lib.RZXGate, lib.RZZGate, lib.XXMinusYYGate, lib.XXPlusYYGate, lib.UGate, lib.U1Gate, lib.U2Gate, lib.U3Gate, } # In known-good situations we want to use a manually parametrised object as the source of the # definition, but still continue to return the given object as the call-site object. if type(operation) in known_good_parameterized: parameterized_operation = type(operation)(*_QASM2_FIXED_PARAMETERS[: len(operation.params)]) elif hasattr(operation, "_qasm2_decomposition"): new_op = operation._qasm2_decomposition() parameterized_operation = operation = new_op.copy( name=_qasm_escape_name(new_op.name, "gate_") ) else: parameterized_operation = operation # If there's an _equal_ operation in the existing circuits to be defined, then our job is done. previous_definition_source, _ = gates_to_define.get(operation.name, (None, None)) if parameterized_operation == previous_definition_source: return operation # Otherwise, if there's a naming clash, we need a unique name. if operation.name in gates_to_define: operation = _rename_operation(operation) new_name = operation.name if parameterized_operation.params: parameters_qasm = ( "(" + ",".join(f"param{i}" for i in range(len(parameterized_operation.params))) + ")" ) else: parameters_qasm = "" if operation.num_qubits == 0: raise QASM2ExportError( f"OpenQASM 2 cannot represent '{operation.name}, which acts on zero qubits." ) if operation.num_clbits != 0: raise QASM2ExportError( f"OpenQASM 2 cannot represent '{operation.name}', which acts on {operation.num_clbits}" " classical bits." ) qubits_qasm = ",".join(f"q{i}" for i in range(parameterized_operation.num_qubits)) parameterized_definition = getattr(parameterized_operation, "definition", None) if parameterized_definition is None: gates_to_define[new_name] = ( parameterized_operation, f"opaque {new_name}{parameters_qasm} {qubits_qasm};", ) else: qubit_labels = {bit: f"q{i}" for i, bit in enumerate(parameterized_definition.qubits)} body_qasm = " ".join( _qasm2_custom_operation_statement( instruction, existing_gate_names, gates_to_define, qubit_labels ) for instruction in parameterized_definition.data ) # if an inner operation has the same name as the actual operation, it needs to be renamed if operation.name in gates_to_define: operation = _rename_operation(operation) new_name = operation.name definition_qasm = f"gate {new_name}{parameters_qasm} {qubits_qasm} {{ {body_qasm} }}" gates_to_define[new_name] = (parameterized_operation, definition_qasm) return operation def _rename_operation(operation): """Returns the operation with a new name following this pattern: {operation name}_{operation id}""" new_name = f"{operation.name}_{id(operation)}" updated_operation = operation.copy(name=new_name) return updated_operation def _qasm_escape_name(name: str, prefix: str) -> str: """Returns a valid OpenQASM identifier, using `prefix` as a prefix if necessary. `prefix` must itself be a valid identifier.""" # Replace all non-ASCII-word characters (letters, digits, underscore) with the underscore. escaped_name = re.sub(r"\W", "_", name, flags=re.ASCII) if ( not escaped_name or escaped_name[0] not in string.ascii_lowercase or escaped_name in QASM2_RESERVED ): escaped_name = prefix + escaped_name return escaped_name def _instruction_qasm2(operation): """Return an OpenQASM 2 string for the instruction.""" from qiskit.qasm2 import QASM2ExportError # pylint: disable=cyclic-import if operation.name == "c3sx": qasm2_call = "c3sqrtx" else: qasm2_call = operation.name if operation.params: qasm2_call = "{}({})".format( qasm2_call, ",".join([pi_check(i, output="qasm", eps=1e-12) for i in operation.params]), ) if operation.condition is not None: if not isinstance(operation.condition[0], ClassicalRegister): raise QASM2ExportError( "OpenQASM 2 can only condition on registers, but got '{operation.condition[0]}'" ) qasm2_call = ( "if(%s==%d) " % (operation.condition[0].name, operation.condition[1]) + qasm2_call ) return qasm2_call def _make_unique(name: str, already_defined: collections.abc.Set[str]) -> str: """Generate a name by suffixing the given stem that is unique within the defined set.""" if name not in already_defined: return name used = {in_use[len(name) :] for in_use in already_defined if in_use.startswith(name)} characters = (string.digits + string.ascii_letters) if name else string.ascii_letters for parts in itertools.chain.from_iterable( itertools.product(characters, repeat=n) for n in itertools.count(1) ): suffix = "".join(parts) if suffix not in used: return name + suffix # This isn't actually reachable because the above loop is infinite. return name def _bit_argument_conversion(specifier, bit_sequence, bit_set, type_) -> list[Bit]: """Get the list of bits referred to by the specifier ``specifier``. Valid types for ``specifier`` are integers, bits of the correct type (as given in ``type_``), or iterables of one of those two scalar types. Integers are interpreted as indices into the sequence ``bit_sequence``. All allowed bits must be in ``bit_set`` (which should implement fast lookup), which is assumed to contain the same bits as ``bit_sequence``. Returns: List[Bit]: a list of the specified bits from ``bits``. Raises: CircuitError: if an incorrect type or index is encountered, if the same bit is specified more than once, or if the specifier is to a bit not in the ``bit_set``. """ # The duplication between this function and `_bit_argument_conversion_scalar` is so that fast # paths return as quickly as possible, and all valid specifiers will resolve without needing to # try/catch exceptions (which is too slow for inner-loop code). if isinstance(specifier, type_): if specifier in bit_set: return [specifier] raise CircuitError(f"Bit '{specifier}' is not in the circuit.") if isinstance(specifier, (int, np.integer)): try: return [bit_sequence[specifier]] except IndexError as ex: raise CircuitError( f"Index {specifier} out of range for size {len(bit_sequence)}." ) from ex # Slices can't raise IndexError - they just return an empty list. if isinstance(specifier, slice): return bit_sequence[specifier] try: return [ _bit_argument_conversion_scalar(index, bit_sequence, bit_set, type_) for index in specifier ] except TypeError as ex: message = ( f"Incorrect bit type: expected '{type_.__name__}' but got '{type(specifier).__name__}'" if isinstance(specifier, Bit) else f"Invalid bit index: '{specifier}' of type '{type(specifier)}'" ) raise CircuitError(message) from ex def _bit_argument_conversion_scalar(specifier, bit_sequence, bit_set, type_): if isinstance(specifier, type_): if specifier in bit_set: return specifier raise CircuitError(f"Bit '{specifier}' is not in the circuit.") if isinstance(specifier, (int, np.integer)): try: return bit_sequence[specifier] except IndexError as ex: raise CircuitError( f"Index {specifier} out of range for size {len(bit_sequence)}." ) from ex message = ( f"Incorrect bit type: expected '{type_.__name__}' but got '{type(specifier).__name__}'" if isinstance(specifier, Bit) else f"Invalid bit index: '{specifier}' of type '{type(specifier)}'" ) raise CircuitError(message)
https://github.com/Q-MAB/Qiskit-FashionMNIST-Case
Q-MAB
##################################################################################################### #This code is part of the Medium story 'Hybrid Quantum-Classical Neural Network for classification #of images in FashionMNIST dataset' case study. Parts of the code may have been imported from Qiskit #textbook and from the exercises of the Qiskit global summer school on Quantum Machine Learning. The #case study was a challenge to put insights from the Qiskit summer school into practice and explore #the hybrid quantum-classical neural network architecture. #A story on the case study can be found here: medium.com/QMAB ##################################################################################################### import numpy as np import torch from torchvision.transforms import ToTensor from torch import cat, no_grad, manual_seed from torchvision import datasets, transforms import torch.optim as optim from torch.nn import (Module, Conv2d, Linear, Dropout2d, NLLLoss, MaxPool2d, Flatten, Sequential, ReLU) from torch.autograd import Function import torch.nn as nn import torch.nn.functional as F from torch.utils.data import Dataset, DataLoader from torch import Tensor from torch.optim import LBFGS from torchviz import make_dot import torchvision from torchvision.io import read_image from torch.autograd import Variable import qiskit from qiskit import transpile, assemble from qiskit.visualization import * from qiskit import Aer, QuantumCircuit from qiskit.utils import QuantumInstance from qiskit.opflow import AerPauliExpectation from qiskit.circuit import Parameter from qiskit.circuit.library import RealAmplitudes, ZZFeatureMap from qiskit_machine_learning.neural_networks import CircuitQNN, TwoLayerQNN from qiskit_machine_learning.connectors import TorchConnector import matplotlib.pyplot as plt import os import pandas as pd # Declare Quantum instance qi = QuantumInstance(Aer.get_backend('aer_simulator_statevector')) ### Training and test data downloaded from FashionMNIST and transformed into tensors ### training_data = datasets.FashionMNIST( root="data", train=True, download=True, transform=ToTensor() ) test_data = datasets.FashionMNIST( root="data", train=False, download=True, transform=ToTensor() ) ### Inspecting the images in the training data set with their labels ### labels_map = { 0: "T-Shirt", 1: "Trouser", 2: "Pullover", 3: "Dress", 4: "Coat", 5: "Sandal", 6: "Shirt", 7: "Sneaker", 8: "Bag", 9: "Ankle Boot", } figure = plt.figure(figsize=(8, 8)) cols, rows = 3, 3 for i in range(1, cols * rows + 1): sample_idx = torch.randint(len(training_data), size=(1,)).item() img, label = training_data[sample_idx] figure.add_subplot(rows, cols, i) plt.title(labels_map[label]) plt.axis("off") plt.imshow(img.squeeze(), cmap="gray") plt.show() ### Load training data into Torch DataLoader ### X_train = training_data n_samples = 500 batch_size = 64 # Filter out labels (originally 0-9), leaving only labels 0 and 1 idx = np.append(np.where(X_train.targets == 0)[0][:n_samples], np.where(X_train.targets == 1)[0][:n_samples]) X_train.data = X_train.data[idx] X_train.targets = X_train.targets[idx] # A torch dataloader is defined with filtered data train_loader = DataLoader(X_train, batch_size=64, shuffle=True) # Load test data into Torch DataLoader X_test = test_data # Filter out labels (originally 0-9), leaving only labels 0 and 1 idx = np.append(np.where(X_test.targets == 0)[0][:n_samples], np.where(X_test.targets == 1)[0][:n_samples]) X_test.data = X_test.data[idx] X_test.targets = X_test.targets[idx] # Define torch dataloader with filtered data test_loader = DataLoader(X_test, batch_size=64, shuffle=True) ### Two layer QNN constructed ### feature_map = ZZFeatureMap(feature_dimension=2, entanglement='linear') ansatz = RealAmplitudes(2, reps=1, entanglement='linear') qnn2 = TwoLayerQNN(2, feature_map, ansatz, input_gradients=True, exp_val=AerPauliExpectation(), quantum_instance=qi) print(qnn2.operator) ### Torch NN module from Qiskit ### class Net(Module): def __init__(self): super().__init__() self.conv1 = Conv2d(1, 2, kernel_size=5) self.conv2 = Conv2d(2, 16, kernel_size=5) self.dropout = Dropout2d() self.fc1 = Linear(256, 64) self.fc2 = Linear(64, 2) # 2-dimensional input to QNN self.qnn = TorchConnector(qnn2) # Apply torch connector, weights chosen self.fc3 = Linear(1, 1) # uniformly at random from interval [-1,1]. # 1-dimensional output from QNN def forward(self, x): x = F.relu(self.conv1(x)) x = F.max_pool2d(x, 2) x = F.relu(self.conv2(x)) x = F.max_pool2d(x, 2) x = self.dropout(x) x = x.view(x.shape[0], -1) x = F.relu(self.fc1(x)) x = self.fc2(x) x = self.qnn(x) # apply QNN x = self.fc3(x) return torch.cat((x, 1 - x), -1) ### Model trained and the loss computed ### model = Net() optimizer = optim.Adam(model.parameters(), lr=0.001) loss_func = nn.NLLLoss() epochs = 20 loss_list = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_list.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format( 100. * (epoch + 1) / epochs, loss_list[-1])) ### Loss convergence plotted ### plt.plot(loss_list) plt.title('Hybrid NN Training Convergence') plt.xlabel('Training Iterations') plt.ylabel('Neg. Log Likelihood Loss') plt.show() ### Model evaluated ### model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), (correct / len(test_loader) / batch_size) * 100)) ### Predicted images displayed. Either T-shirt or Trouser ### n_samples_show = 5 count = 0 fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(15, 5)) model.eval() with no_grad(): for batch_idx, (data, target) in enumerate(test_loader): if count == n_samples_show: break output = model(data[0:1]) if len(output.shape) == 1: output = output.reshape(1, *output.shape) pred = output.argmax(dim=1, keepdim=True) axes[count].imshow(data[0].numpy().squeeze(), cmap='gray') axes[count].set_xticks([]) axes[count].set_yticks([]) if pred.item() == 0: axes[count].set_title('Predicted item: T-Shirt') elif pred.item() == 1: axes[count].set_title('Predicted item: Trouser') count += 1
https://github.com/qiskit-community/prototype-quantum-kernel-training
qiskit-community
# pylint: disable=import-error, wrong-import-position, pointless-statement import os import sys import numpy as np from qiskit import QuantumCircuit from qiskit.circuit import ParameterVector from qiskit_machine_learning.kernels import TrainableFidelityQuantumKernel NUM_QUBITS = 3 fm = QuantumCircuit(NUM_QUBITS) input_params = ip = ParameterVector("x", NUM_QUBITS) training_params = tp = ParameterVector("θ", NUM_QUBITS) for i in range(NUM_QUBITS): fm.h(i) fm.ry(tp[i], i) for i in range(NUM_QUBITS): fm.crx(ip[i], (i) % NUM_QUBITS, (i + 1) % NUM_QUBITS) # Define a Quantum Kernel using our trainable feature map qk = TrainableFidelityQuantumKernel( feature_map=fm, training_parameters=training_params[:NUM_QUBITS] ) print("input_params:", input_params) print("training_params:", training_params) qk.feature_map.draw() # Bind parameters to numeric values param_binds = {tp[0]: np.pi / 2, tp[1]: np.pi / 3, tp[2]: np.pi / 4} qk.assign_training_parameters(param_binds) qk.parameter_values # Create incomplete training param bindings param_binds = {tp[0]: np.pi / 6, tp[1]: np.pi / 5} qk.assign_training_parameters(param_binds) qk.parameter_values # Create incomplete user param bindings param_binds = {tp[0]: tp[0], tp[1]: tp[0] + tp[2], tp[2]: tp[2]} qk.assign_training_parameters(param_binds) qk.parameter_values qk = TrainableFidelityQuantumKernel(feature_map=fm, training_parameters=training_params) qk.feature_map.draw() param_values = [np.pi / 7, tp[1], np.pi / 9] qk.assign_training_parameters(param_values) qk.parameter_values param_values = [np.pi / 7, np.pi / 6, np.pi / 9] qk.assign_training_parameters(param_values) qk.parameter_values param_values = [tp[0], tp[1], tp[2]] qk.assign_training_parameters(param_values) qk.parameter_values #import qiskit.tools.jupyter # #%qiskit_version_table #%qiskit_copyright
https://github.com/qiskit-community/prototype-quantum-kernel-training
qiskit-community
# pylint: disable=import-error, wrong-import-position, too-few-public-methods, no-self-use, function-redefined from functools import partial from typing import Sequence import os import sys import numpy as np import matplotlib.pyplot as plt # Import Qiskit packages from qiskit.circuit.library import ZZFeatureMap from qiskit_machine_learning.kernels import TrainableFidelityQuantumKernel from qiskit_machine_learning.utils.loss_functions import KernelLoss feature_map = ZZFeatureMap(3) user_params = [feature_map.parameters[1]] qkernel = TrainableFidelityQuantumKernel( feature_map=feature_map, training_parameters=user_params, ) X_train = [[0.6, 0.2], [0.5, 0.3], [0.3, 0.7], [0.1, 0.5]] y_train = np.array([0, 0, 1, 1]) class CustomKernelLoss(KernelLoss): """Example Kernel Loss class""" def __init__(self, **kwargs): self.kwargs = kwargs # Evaluate the Loss of a trainable quantum kernel # at a particular setting of user_param_values on # a particular dataset. def evaluate( self, parameter_values: Sequence[float], quantum_kernel: TrainableFidelityQuantumKernel, data: np.ndarray, labels: np.ndarray, ): # Bind the user parameter values quantum_kernel.assign_training_parameters(parameter_values) kernel_matrix = quantum_kernel.evaluate(data) return labels.T @ kernel_matrix @ labels # Wrap our evaluate method so to produce a callable # which maps user_param_values to loss scores. def get_variational_callable( self, quantum_kernel: TrainableFidelityQuantumKernel, data: np.ndarray, labels: np.ndarray, ): return partial( self.evaluate, quantum_kernel=quantum_kernel, data=data, labels=labels ) kernel_loss = CustomKernelLoss().get_variational_callable(qkernel, X_train, y_train) print(kernel_loss([0.75])) NUM_GRID_POINTS = 100 loss_values = [kernel_loss([val]) for val in np.linspace(0, 2 * np.pi, NUM_GRID_POINTS)] plt.rcParams["font.size"] = 15 plt.figure(figsize=(8, 4)) plt.plot(np.linspace(0, 2 * np.pi, NUM_GRID_POINTS), loss_values) plt.xlabel("θ") plt.ylabel("Kernel Loss") plt.show() def kernel_loss_full(training_param_values, kernel, data, labels): kernel.assign_training_parameters(training_param_values) kernel_matrix = kernel.evaluate(data) return labels.T @ kernel_matrix @ labels kernel_loss = partial(kernel_loss_full, kernel=qkernel, data=X_train, labels=y_train) print(kernel_loss([0.75])) #import qiskit.tools.jupyter # #%qiskit_version_table #%qiskit_copyright
https://github.com/qiskit-community/prototype-quantum-kernel-training
qiskit-community
from typing import List, Callable, Union from qiskit import QuantumCircuit from qiskit.circuit import ParameterVector # To visualize circuit creation process from qiskit.visualization import circuit_drawer # For a dataset with 12 features; and 2 features per qubit FEATURE_DIMENSION = 12 NUM_QUBITS = int(FEATURE_DIMENSION / 2) # Qiskit feature maps should generally be QuantumCircuits or extensions of QuantumCircuit feature_map = QuantumCircuit(NUM_QUBITS) user_params = ParameterVector("θ", NUM_QUBITS) # Create circuit layer with trainable parameters for i in range(NUM_QUBITS): feature_map.ry(user_params[i], feature_map.qubits[i]) print(circuit_drawer(feature_map)) # Linear entanglement entanglement = [[i, i + 1] for i in range(NUM_QUBITS - 1)] for source, target in entanglement: feature_map.cz(feature_map.qubits[source], feature_map.qubits[target]) feature_map.barrier() print(circuit_drawer(feature_map)) input_params = ParameterVector("x", FEATURE_DIMENSION) for i in range(NUM_QUBITS): feature_map.rz(input_params[2 * i + 1], feature_map.qubits[i]) feature_map.rx(input_params[2 * i], feature_map.qubits[i]) print(circuit_drawer(feature_map)) class ExampleFeatureMap(QuantumCircuit): """The Example Feature Map circuit""" def __init__( self, feature_dimension: int, entanglement: Union[str, List[List[int]], Callable[[int], List[int]]] = None, name: str = "ExampleFeatureMap", ) -> None: """Create a new Example Feature Map circuit. Args: feature_dimension: The number of features entanglement: Entanglement scheme to be used in second layer name: Name of QuantumCircuit object Raises: ValueError: ExampleFeatureMap requires an even number of input features """ if (feature_dimension % 2) != 0: raise ValueError( """ Example feature map requires an even number of input features. """ ) self.feature_dimension = feature_dimension self.entanglement = entanglement self.training_parameters = None # Call the QuantumCircuit initialization num_qubits = feature_dimension / 2 super().__init__( num_qubits, name=name, ) # Build the feature map circuit self._generate_feature_map() def _generate_feature_map(self): # If no entanglement scheme specified, use linear entanglement if self.entanglement is None: self.entanglement = [[i, i + 1] for i in range(self.num_qubits - 1)] # Vector of data parameters input_params = ParameterVector("x", self.feature_dimension) training_params = ParameterVector("θ", self.num_qubits) # Create an initial rotation layer of trainable parameters for i in range(self.num_qubits): self.ry(training_params[i], self.qubits[i]) self.training_parameters = training_params # Create the entanglement layer for source, target in self.entanglement: self.cz(self.qubits[source], self.qubits[target]) self.barrier() # Create a circuit representation of the data group for i in range(self.num_qubits): self.rz(input_params[2 * i + 1], self.qubits[i]) self.rx(input_params[2 * i], self.qubits[i]) feature_map = ExampleFeatureMap(feature_dimension=10) circuit_drawer(feature_map) #import qiskit.tools.jupyter # #%qiskit_version_table #%qiskit_copyright
https://github.com/qiskit-community/prototype-quantum-kernel-training
qiskit-community
# pylint: disable=protected-access from qiskit.circuit.library import ZZFeatureMap from qiskit.circuit import ParameterVector # Define a (non-parameterized) feature map from the Qiskit circuit library fm = ZZFeatureMap(2) input_params = fm.parameters fm.draw() # split params into two disjoint sets input_params = fm.parameters[::2] training_params = fm.parameters[1::2] print("input_params:", input_params) print("training_params:", training_params) # define new parameter vectors for the input and user parameters new_input_params = ParameterVector("x", len(input_params)) new_training_params = ParameterVector("θ", len(training_params)) # resassign the origin feature map parameters param_reassignments = {} for i, p in enumerate(input_params): param_reassignments[p] = new_input_params[i] for i, p in enumerate(training_params): param_reassignments[p] = new_training_params[i] fm.assign_parameters(param_reassignments, inplace=True) input_params = new_input_params training_params = new_training_params print("input_params:", input_params) print("training_params:", training_params) fm.draw() # Define two circuits circ1 = ZZFeatureMap(2) circ2 = ZZFeatureMap(2) input_params = circ1.parameters training_params = ParameterVector("θ", 2) # Reassign new parameters to circ2 so there are no name collisions circ2.assign_parameters(training_params, inplace=True) # Compose to build a parameterized feature map fm = circ2.compose(circ1) print("input_params:", list(input_params)) print("training_params:", training_params) fm.draw() #import qiskit.tools.jupyter # #%qiskit_version_table #%qiskit_copyright
https://github.com/qiskit-community/prototype-quantum-kernel-training
qiskit-community
# pylint: disable=import-error, wrong-import-position # Python imports import os import sys # External imports from pylab import cm from sklearn import metrics import numpy as np import matplotlib.pyplot as plt %matplotlib inline # Qiskit imports from qiskit.visualization import circuit_drawer from qiskit_algorithms.optimizers import SPSA from qiskit_machine_learning.kernels import TrainableFidelityQuantumKernel from qiskit_machine_learning.kernels.algorithms import QuantumKernelTrainer from qiskit_machine_learning.algorithms import QSVC # Put this repository on the Python path and import qkt pkgs module_path = os.path.abspath(os.path.join("../..")) sys.path.append(module_path) from qkt.feature_maps import CovariantFeatureMap from qkt.utils import train_test_split, QKTCallback # Load the dataset and split into train and test sets DATA_FILEPATH = "../../data/dataset_graph7.csv" X_train, y_train, X_test, y_test = train_test_split(DATA_FILEPATH) num_features = np.shape(X_train)[1] entangler_map = [[0, 2], [3, 4], [2, 5], [1, 4], [2, 3], [4, 6]] # Note that [[0,1],[2,3],[4,5],[6,7],[8,9],[1,2],[3,4],[5,6],[7,8]] # is a suitable input for the 10-qubit dataset fm = CovariantFeatureMap( feature_dimension=num_features, entanglement=entangler_map, single_training_parameter=True, ) circuit_drawer(fm) print(fm.training_parameters) # Instantiate quantum kernel quant_kernel = TrainableFidelityQuantumKernel( feature_map=fm, training_parameters=fm.training_parameters ) # Set up the optimizer cb_qkt = QKTCallback() spsa_opt = SPSA( maxiter=5, callback=cb_qkt.callback, learning_rate=0.1, perturbation=0.1 ) # Instantiate a quantum kernel trainer. qkt = QuantumKernelTrainer( quantum_kernel=quant_kernel, loss="svc_loss", optimizer=spsa_opt, initial_point=[0.1] * len(fm.training_parameters), ) # Train the kernel using QKT directly qka_results = qkt.fit(X_train, y_train) optimized_kernel = qka_results.quantum_kernel # Use QSVC for classification qsvc = QSVC(quantum_kernel=optimized_kernel) # Fit the QSVC qsvc.fit(X_train, y_train) # Predict the labels labels_test = qsvc.predict(X_test) # Evaluate the test accuracy accuracy_test = metrics.balanced_accuracy_score(y_true=y_test, y_pred=labels_test) print(f"accuracy test: {accuracy_test}") plot_data = cb_qkt.get_callback_data() # callback data K = optimized_kernel.evaluate( X_train ) # kernel matrix evaluated on the training samples plt.rcParams["font.size"] = 20 fig, ax = plt.subplots(1, 2, figsize=(14, 5)) ax[0].plot( [i + 1 for i in range(len(plot_data[0]))], np.array(plot_data[2]), c="k", marker="o" ) ax[0].set_xlabel("Iterations") ax[0].set_ylabel("Loss") ax[1].imshow(K, cmap=cm.get_cmap("bwr", 20)) ax[1].axis("off") fig.tight_layout() plt.show() #import qiskit.tools.jupyter # #%qiskit_version_table #%qiskit_copyright
https://github.com/qiskit-community/prototype-quantum-kernel-training
qiskit-community
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Create a new Covariant Feature Map circuit.""" import copy from typing import Callable, Optional, Union, List, Dict, Any import numpy as np from qiskit import QuantumCircuit from qiskit.circuit import ParameterVector class CovariantFeatureMap(QuantumCircuit): """The Covariant Feature Map circuit. On 3 qubits and a linear entanglement, the circuit is represented by: .. parsed-literal:: ┌──────────────┐ ░ ┌─────────────────┐┌─────────────────┐ q_0: ┤ Ry(θ_par[0]) ├─■─────░─┤ Rz(-2*x_par[1]) ├┤ Rx(-2*x_par[0]) ├ ├──────────────┤ │ ░ ├─────────────────┤├─────────────────┤ q_1: ┤ Ry(θ_par[1]) ├─■──■──░─┤ Rz(-2*x_par[3]) ├┤ Rx(-2*x_par[2]) ├ ├──────────────┤ │ ░ ├─────────────────┤├─────────────────┤ q_2: ┤ Ry(θ_par[2]) ├────■──░─┤ Rz(-2*x_par[5]) ├┤ Rx(-2*x_par[4]) ├ └──────────────┘ ░ └─────────────────┘└─────────────────┘ where θ_par is a vector of trainable feature map parameters and x_par is a vector of data-bound feature map parameters. """ def __init__( self, feature_dimension: int, entanglement: Union[str, List[List[int]], Callable[[int], List[int]]] = None, single_training_parameter: bool = False, name: str = "CovariantFeatureMap", ) -> None: """Create a new Covariant Feature Map circuit. Args: feature_dimension: The number of features insert_barriers: If True, barriers are inserted around the entanglement layer """ if (feature_dimension % 2) != 0: raise ValueError( """ Covariant feature map requires an even number of input features. """ ) self.feature_dimension = feature_dimension self.entanglement = entanglement self.single_training_parameter = single_training_parameter self.training_parameters = None self.input_parameters = None num_qubits = feature_dimension / 2 super().__init__( num_qubits, name=name, ) self._generate_feature_map() @property def settings(self) -> Dict[str, Any]: training_parameters_list = [param for param in self.training_parameters] input_parameters_list = [param for param in self.input_parameters] return { "feature_dimension": self.feature_dimension, "entanglement": self.entanglement, "single_training_parameter": self.single_training_parameter, "training_parameters": training_parameters_list, "input_parameters": input_parameters_list, } def _generate_feature_map(self): # If no entanglement scheme specified, use linear entanglement if self.entanglement is None: self.entanglement = [[i, i + 1] for i in range(self.num_qubits - 1)] # Vector of data parameters input_params = ParameterVector("x_par", self.feature_dimension) # Use a single parameter to rotate each qubit if sharing is desired if self.single_training_parameter: training_params = ParameterVector("\u03B8_par", 1) # Create an initial rotation layer using a single Parameter for i in range(self.num_qubits): self.ry(training_params[0], self.qubits[i]) # Train each qubit's initial rotation individually else: training_params = ParameterVector("\u03B8_par", self.num_qubits) # Create an initial rotation layer of trainable parameters for i in range(self.num_qubits): self.ry(training_params[i], self.qubits[i]) self.training_parameters = training_params self.input_parameters = input_params # Create the entanglement layer for source, target in self.entanglement: self.cz(self.qubits[source], self.qubits[target]) self.barrier() # Create a circuit representation of the data group for i in range(self.num_qubits): self.rz(-2 * input_params[2 * i + 1], self.qubits[i]) self.rx(-2 * input_params[2 * i], self.qubits[i])
https://github.com/Qottmann/Quantum-anomaly-detection
Qottmann
import time import itertools import numpy as np import qiskit from qiskit import * from qiskit.quantum_info import Statevector from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B, SPSA from qiskit.opflow.state_fns import StateFn, CircuitStateFn from qiskit.providers.aer import StatevectorSimulator, AerSimulator from qiskit.opflow import CircuitSampler from qiskit.ignis.mitigation.measurement import CompleteMeasFitter # you will need to pip install qiskit-ignis from qiskit.ignis.mitigation.measurement import complete_meas_cal import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator from matplotlib.colors import BoundaryNorm cmap = plt.get_cmap("plasma") #'viridis' from modules.utils import * from qae import * import datetime print(qiskit.__version__, np.__version__) IBMQ.load_account() # this then automatically loads your saved account provider = IBMQ.get_provider(hub='ibm-q-research') device = provider.backend.ibmq_jakarta # 6 bogota ; 4 rome ### Real device execution: backend_device = device ### Simulation with noise profile from real device backend_sim = qiskit.providers.aer.AerSimulator.from_backend(device) ### Simulation without noise #backend = qiskit.providers.aer.AerSimulator() ### Preliminaries L = 5 num_trash = 2 anti = -1 # 1 for ferromagnetic Ising model, -1 for antiferromagnet run_VQE = True # whether or not you want to compute the VQE values; or load them execute = True real_device = True # want to execute on real device # dataset to be loaded (optimal VQE parameters) # if execute_VQE is True this will overwrite the file filename = f'data/jakarta_execute' # Give a _unique_ name to this notebook execution, the results will be stored in the appropriate files with that name name = "jakarta_execute" # uncomment in case you want to toy around with the ansatz circuit rotation_blocks = "ry" entanglement_blocks = "cz" # cx entanglement = "sca" #"sca" reps = 1 ansatz_config = dict(rotation_blocks = rotation_blocks, entanglement_blocks = entanglement_blocks, reps = reps, entanglement = entanglement) ansatz = qiskit.circuit.library.TwoLocal(L, **ansatz_config) ansatz.draw("mpl") tansatz = qiskit.transpile(ansatz, backend_sim) tansatz.draw("mpl") coupling_map = device.configuration().coupling_map noise_model = qiskit.providers.aer.noise.NoiseModel.from_backend(device) basis_gates = noise_model.basis_gates qi_device = qiskit.utils.QuantumInstance(backend=backend_device, # , seed_simulator=seed, seed_transpiler=seed shots = 1000, coupling_map=coupling_map, #noise_model=noise_model, # comment out on real device execution measurement_error_mitigation_cls= CompleteMeasFitter, cals_matrix_refresh_period=30 #How often to refresh the calibration matrix in measurement mitigation. in minutes ) qi_sim = qiskit.utils.QuantumInstance(backend=backend_sim, # , seed_simulator=seed, seed_transpiler=seed shots = 1000, coupling_map=coupling_map, noise_model=noise_model, # comment out on real device execution measurement_error_mitigation_cls= CompleteMeasFitter, cals_matrix_refresh_period=30 #How often to refresh the calibration matrix in measurement mitigation. in minutes ) if not real_device: backend_device = backend_sim qi_device = qi_sim if run_VQE: maxiter = [200,200,200,200,200, 200,200,200,150,150, 150,150,100,100,100, 60,30,30,30,30 ] maxiter = maxiter[::2] maxiter = [150] + [50] * 9 logspace_size = len(maxiter) gx_vals = np.logspace(-2,2,logspace_size) #gz_vals = [0.] # np.logspace(-2,2,logspace_size) counts = [] values = [] params = [] def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) params.append(parameters) opt_params = [] gx_list = [] gz_list = [] countss, valuess, paramss = [], [], [] Qmag_sim, QZ_sim, Qen_sim= [],[], [] Smag, Sen = [], [] #maxiter = [200,200,200,200, 150, 60, 60, 60, 60, 60] for j,gx in enumerate(gx_vals): gz = 0 t0 = datetime.datetime.now() counts = [] values = [] params = [] optimizer = SPSA(maxiter=maxiter[j], blocking=True) # ,learning_rate=0.05, perturbation=0.05,; setting that speeds things up sometimes vqe = qiskit.algorithms.VQE(ansatz=ansatz, initial_point = opt_params[j-1] if j != 0 else None, optimizer=optimizer, callback=store_intermediate_result, # comment out on real device quantum_instance=qi_sim ) H = QHIsing(L,anti,np.float32(gx),np.float32(gz)) result = vqe.compute_minimum_eigenvalue(H, aux_operators = [QNKron(L,Z,I,i) for i in range(L)]) #ED with Qiskit VQE Qen_sim.append(result.eigenvalue) QZ_sim.append(result.aux_operator_eigenvalues[:,0]) # real-space resolved Z expectation value Qmag_sim.append(np.mean(anti**np.arange(L) * result.aux_operator_eigenvalues[:,0])) countss.append(counts) valuess.append(values) paramss.append(params) # uncomment if you want to recompute ED results (typically provided with guess parameters) ED_state, ED_E, ham = ising_groundstate(L, anti, np.float32(gx), np.float32(gz)) Sen.append(ED_E) Smag.append(ED_state.T.conj()@Mag(L,anti)@ED_state) print(f"ED energy: {Sen[j]} ;; VQE energy: {Qen_sim[j]} ;; diff {Qen_sim[j] - Sen[j]}") print(f"ED mag: {Smag[j]} ;; VQE mag: {Qmag_sim[j]} ;; diff {Qmag_sim[j] - Smag[j]}") gx_list.append(gx) gz_list.append(gz) opt_params.append(sort_params(result.optimal_parameters)) print(f"{j+1} / {len(gx_vals)}, gx = {gx:.2f}, gz = {gz:.2f}, time : {(datetime.datetime.now() - t0)}") fig, axs = plt.subplots(ncols=2,figsize=(6,3)) axs[0].plot(countss[j],valuess[j]) axs[1].plot(result.aux_operator_eigenvalues[:,0]) plt.show() np.savez(filename, gx_list=gx_list, gz_list=gz_list, opt_params=opt_params, Qmag_sim=Qmag_sim, Qen_sim=Qen_sim, QZ_sim = QZ_sim, Sen=Sen, Smag=Smag, ansatz_config=ansatz_config, paramss = paramss, valuess = valuess, countss = countss ) temp = np.load(filename + ".npz",allow_pickle=True) gx_list = temp["gx_list"] gz = 0 gz_list = [0] Qmag_sim = temp["Qmag_sim"] QZ_sim = temp["QZ_sim"] Qen_sim = temp["Qen_sim"] Sen = temp["Sen"] Smag = temp["Smag"] opt_params = temp["opt_params"] paramss = temp["paramss"]; valuess = temp["valuess"]; countss = temp["countss"] # This just recomputes the magnetization with the parameters provided by guess_params if execute: QZ_executed=np.zeros((len(opt_params),L), dtype="complex") Qmag_executed=np.zeros((len(opt_params),), dtype="complex") for j in range(len(opt_params)): t0 = datetime.datetime.now() gx = gx_list[j] #H = QHIsing(L, anti, np.float32(gx), np.float32(gz)) # build Hamiltonian Op state = ansatz.assign_parameters(opt_params[j]) for i in range(L): meas_outcome = ~StateFn(QNKron(L,Z,I,i)) @ StateFn(state) QZ_executed[j,i] = CircuitSampler(qi_device).convert(meas_outcome).eval() #https://quantumcomputing.stackexchange.com/questions/12080/evaluating-expectation-values-of-operators-in-qiskit Qmag_executed[j] = np.mean(anti**np.arange(L) * QZ_executed[j]) #e_outcome = ~StateFn(H) @ StateFn(state) #Qen_executed[j] = CircuitSampler(qi).convert(e_outcome).eval() print(f"{j+1} / {len(opt_params)}, QZ: {Qmag_executed[j]}, gx = {gx:.2f}, gz = {gz:.2f}, time : {(datetime.datetime.now() - t0)}") fig, ax = plt.subplots(ncols=1,figsize=(4,3)) ax.plot(QZ_sim[j].real) ax.plot(QZ_executed[j].real,"x--") ax.set_title("S exec = {:.3f}, S sim = {:.3f}".format(Qmag_executed[j].real, Qmag_sim[j].real)) plt.show() np.savez(filename + f"_executed_-real-device-{real_device}", gx_list=gx_list, gz_list=gz_list, opt_params=opt_params, Qmag_sim=Qmag_sim, Qen_sim=Qen_sim, QZ_sim = QZ_sim, Sen=Sen, Smag=Smag, Qmag_device= Qmag_executed, QZ_device = QZ_executed, ansatz_config=ansatz_config, paramss = paramss, valuess = valuess, countss = countss ) fig, axs = plt.subplots(ncols=2, figsize=(10,5)) ax = axs[0] ax.plot(gx_list, np.abs(Smag),"x--", label="ED") ax.plot(gx_list, np.abs(Qmag_sim),"x--", label="VQE sim") ax.plot(gx_list, np.abs(Qmag_executed),"x--", label="VQE ibmq_rome") ax.set_xscale("log") ax.legend() ax = axs[1] ax.plot(gx_list, Smag,"x--", label="ED") ax.plot(gx_list, Qmag_sim,"x--", label="VQE sim") ax.plot(gx_list, Qmag_executed,"x--", label="VQE ibmq_rome") ax.set_xscale("log") ax.legend() ############################################################################## ### II - Anomaly Detection ################################################## ############################################################################## trash_qubits_idxs = [1,3] # Using our QAEAnsatz class (described in qae.py) circ = QAEAnsatz(num_qubits = L, num_trash_qubits= num_trash, trash_qubits_idxs = trash_qubits_idxs, measure_trash=True) circ.draw("mpl") # an example with assigned parameters circ = circ.assign_parameters(np.arange(L*2+2)) circ.draw("mpl") def prepare_circuit(thetas, L=6, num_trash=2, init_state=None, measurement=True, vqe=True): QAE_circ = QAEAnsatz(num_qubits = L, num_trash_qubits= num_trash, trash_qubits_idxs = trash_qubits_idxs, measure_trash=measurement).assign_parameters(thetas) if vqe: VQE_circ = ansatz.assign_parameters(init_state) fullcirc = VQE_circ + QAE_circ else: fullcirc = QAE_circ.initialize(init_state, qreg) return fullcirc # example of the full circuit with random parameters assigned fullcirc = prepare_circuit(np.random.rand(L*2+2),L,num_trash, vqe=True, init_state=opt_params[0]) fullcirc.draw("mpl") backend = backend_device def calibrate_circuit(L, nums_trash=trash_qubits_idxs,shots=1000): # outputs a CompleteMeasFitter object for alter use num_trash = len(nums_trash) qreg = QuantumRegister(L, 'q') # obtain calibration matrix qubit_list = [i for i in nums_trash] # only need to calibrate the trash qubits circlabel = f'mcal_{datetime.datetime.now()}' meas_calibs, state_labels = complete_meas_cal(qubit_list=qubit_list, qr=qreg, circlabel=circlabel) cal_job = backend.run(meas_calibs, shots=shots) #, noise_model=noise_model) cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel=circlabel) print(circlabel, meas_fitter.cal_matrix) return meas_fitter def run_circuit(thetas, L, num_trash, init_state, vqe=True, shots=100, meas_fitter = None): circ = prepare_circuit(thetas, L, num_trash, init_state, vqe=vqe) tcirc = qiskit.transpile(circ, backend) # Execute the circuit job_sim = backend.run(tcirc, shots=shots) # , seed_simulator=123, seed_transpiler=234 fix seed to make it reproducible result = job_sim.result() # Results without mitigation counts = result.get_counts() if meas_fitter != None: # Get the filter object meas_filter = meas_fitter.filter # Results with mitigation mitigated_results = meas_filter.apply(result) counts = mitigated_results.get_counts(0) return counts phis = opt_params # the parameters for the VQE initialization def cost_function_single(thetas, L, num_trash, p, shots=1000, vqe=True, param_encoding=False, x=0, meas_fitter=None): """ Optimizes circuit """ if vqe: init_state = phis[p] else: J, gx, gz = p init_state, _ = ising_groundstate(L, J, gx, gz) if param_encoding: thetas = feature_encoding(thetas, x) out = run_circuit(thetas, L, num_trash, init_state, vqe=vqe, shots=shots, meas_fitter=meas_fitter) cost = out.get('11', 0)*2 + out.get('01', 0) + out.get('10', 0) return cost/shots def cost_function(thetas, L, num_trash, ising_params, shots=1000, vqe=True, param_encoding=False, x=0, meas_fitter=None): """ Optimizes circuit """ cost = 0. n_samples = len(ising_params) for i, p in enumerate(ising_params): if param_encoding: cost += cost_function_single(thetas, L, num_trash, p, shots, vqe, param_encoding, x[i], meas_fitter=meas_fitter) else: cost += cost_function_single(thetas, L, num_trash, p, shots, vqe, param_encoding, meas_fitter=meas_fitter) return cost/n_samples def optimize(ising_params, L=6, num_trash=2, thetas=None, shots=1000, max_iter=400, vqe=True, param_encoding=False, x=0, pick_optimizer = None, meas_fitter=None, callback=True): if thetas is None: n_params = (2*L+2)*2 if param_encoding else (2*L+2) thetas = np.random.uniform(0, 2*np.pi, n_params) # initial parameters without feature encoding print("Initial cost: {:.3f}".format(cost_function(thetas, L, num_trash, ising_params, shots, vqe, param_encoding, x))) counts, values, accepted = [], [], [] def store_intermediate_result(eval_count, parameters, mean, std, ac): # counts.append(eval_count) values.append(mean) accepted.append(ac) # Initialize optimizer if pick_optimizer == "cobyla": optimizer = COBYLA(maxiter=max_iter, tol=0.0001) if pick_optimizer == "adam" or pick_optimizer == "ADAM": optimizer = qiskit.algorithms.optimizers.ADAM(maxiter=max_iter) # optimizer = L_BFGS_B(maxfun=300, maxiter=max_iter)#, factr=10, iprint=- 1, epsilon=1e-08) if pick_optimizer == "spsa" or pick_optimizer == None: optimizer = SPSA(maxiter=max_iter, blocking=True, callback=store_intermediate_result if callback else None, learning_rate=0.1, perturbation=0.1 ) # recommended from qiskit (first iteraction takes quite long) # to reduce time figure out optimal learning rate and perturbation in advance start_time = time.time() ret = optimizer.optimize( num_vars=len(thetas), objective_function=(lambda thetas: cost_function(thetas, L, num_trash, ising_params, shots, vqe, param_encoding, x, meas_fitter=meas_fitter)), initial_point=thetas ) print("Time: {:.5f} sec".format(time.time()-start_time)) print(ret) return ret[0], values, accepted backend = backend_sim #calibration meas_fitter = calibrate_circuit(L, nums_trash=trash_qubits_idxs) # Training phys_params = [0] thetas_opt, loss, accepted = optimize(phys_params, max_iter=90, L=5, meas_fitter=meas_fitter) #, pick_optimizer="adam") plt.plot(loss) np.savez(filename + "run1_thetas_opt_sim", thetas_opt=thetas_opt, loss=loss, accepted=accepted) # Inference; note that on the real device each inference points takes about ~30 seconds cost = np.zeros((len(gx_vals))) thetas_opt = np.load(filename + "run1_thetas_opt_sim.npz",allow_pickle=True)["thetas_opt"] shots = 1000 for i,p in enumerate(list(gx_list)): t0 = datetime.datetime.now() cost[i] = cost_function_single(thetas_opt, L, num_trash, i, shots=shots, meas_fitter=meas_fitter) # np.random.uniform(0, 2*np.pi, 2*L+2) random parameters to check if training "does" something - result was: with random paremters just get noise, so yes, it "does" something print(f"{i} / {len(gx_list)} - execution time {datetime.datetime.now()-t0}") np.savez(filename + "run1_sim",cost=cost, thetas_opt=thetas_opt, loss=loss, accepted = accepted) # Training phys_params = [0] thetas_opt, loss, accepted = optimize(phys_params, max_iter=90, L=5, meas_fitter=meas_fitter) #, pick_optimizer="adam") plt.plot(loss) np.savez(filename + "run1_thetas_opt_sim2", thetas_opt=thetas_opt, loss=loss, accepted=accepted) # Inference; note that on the real device each inference points takes about ~30 seconds cost = np.zeros((len(gx_vals))) thetas_opt = np.load(filename + "run1_thetas_opt_sim2.npz",allow_pickle=True)["thetas_opt"] shots = 1000 for i,p in enumerate(list(gx_list)): t0 = datetime.datetime.now() cost[i] = cost_function_single(thetas_opt, L, num_trash, i, shots=shots, meas_fitter=meas_fitter) # np.random.uniform(0, 2*np.pi, 2*L+2) random parameters to check if training "does" something - result was: with random paremters just get noise, so yes, it "does" something print(f"{i} / {len(gx_list)} - execution time {datetime.datetime.now()-t0}") np.savez(filename + "run1_sim2",cost=cost, thetas_opt=thetas_opt, loss=loss, accepted = accepted) fig, axs = plt.subplots(ncols=2, figsize=(10,5)) temp0 = np.load(filename + "run1_sim2.npz",allow_pickle=True) cost = temp0["cost"] ; ax = axs[0] ax.plot(gx_list, cost,"X--", label="cost") ax.plot(gx_list, np.abs(Qmag_sim),"x--", label="VQE res") ax.plot(gx_list, np.abs(Qmag_executed),"x--", label="VQE resample") ax.set_xscale("log") ax.legend() ax = axs[1] ax.plot(gx_list, cost,"X--", label="cost") ax.plot(gx_list, Qmag_sim,"x--", label="VQE res") ax.plot(gx_list, Qmag_executed,"x--", label="VQE resample") ax.set_xscale("log") ax.legend() # Training phys_params = [-1] thetas_opt, loss, accepted = optimize(phys_params, max_iter=40, L=5, meas_fitter=meas_fitter) #, pick_optimizer="adam") plt.plot(loss) np.savez(filename + "run2_thetas_opt_sim2", thetas_opt=thetas_opt, loss=loss, accepted=accepted) # Inference; note that on the real device each inference points takes about ~30 seconds cost = np.zeros((len(gx_vals))) thetas_opt = np.load(filename + "run2_thetas_opt_sim2.npz",allow_pickle=True)["thetas_opt"] shots = 1000 for i,p in enumerate(list(gx_list)): t0 = datetime.datetime.now() cost[i] = cost_function_single(thetas_opt, L, num_trash, i, shots=shots, meas_fitter=meas_fitter) # np.random.uniform(0, 2*np.pi, 2*L+2) random parameters to check if training "does" something - result was: with random paremters just get noise, so yes, it "does" something print(f"{i} / {len(gx_list)} - execution time {datetime.datetime.now()-t0}") np.savez(filename + "run2_sim2",cost=cost, thetas_opt=thetas_opt, loss=loss, accepted = accepted) fig, axs = plt.subplots(ncols=2, figsize=(10,5)) temp0 = np.load(filename + "run2_sim2.npz",allow_pickle=True) cost = temp0["cost"] ; ax = axs[0] ax.plot(gx_list, cost,"X--", label="cost") ax.plot(gx_list, np.abs(Qmag_sim),"x--", label="VQE res") ax.plot(gx_list, np.abs(Qmag_executed),"x--", label="VQE resample") ax.set_xscale("log") ax.legend() ax = axs[1] ax.plot(gx_list, cost,"X--", label="cost") ax.plot(gx_list, Qmag_sim,"x--", label="VQE res") ax.plot(gx_list, Qmag_executed,"x--", label="VQE resample") ax.set_xscale("log") ax.legend() backend = backend_device meas_fitter = calibrate_circuit(L, nums_trash=trash_qubits_idxs) # Training phys_params = [0] thetas_guess = np.load(filename + "run1_thetas_opt_sim.npz",allow_pickle=True)["thetas_opt"] thetas_opt, loss, accepted = optimize(phys_params, thetas= thetas_guess, callback=False, max_iter=15, L=5, meas_fitter=meas_fitter) #, pick_optimizer="adam") plt.plot(loss) np.savez(filename + "run1_thetas_opt_device", thetas_opt=thetas_opt, loss=loss, accepted=accepted) # Inference; note that on the real device each inference points takes about ~30 seconds cost = np.zeros((len(gx_vals))) thetas_opt = np.load(filename + "run1_thetas_opt_device.npz",allow_pickle=True)["thetas_opt"] shots = 1000 for i,p in enumerate(list(gx_list)): t0 = datetime.datetime.now() cost[i] = cost_function_single(thetas_opt, L, num_trash, i, shots=shots, meas_fitter=meas_fitter) # np.random.uniform(0, 2*np.pi, 2*L+2) random parameters to check if training "does" something - result was: with random paremters just get noise, so yes, it "does" something print(f"{i} / {len(gx_list)} - execution time {datetime.datetime.now()-t0}") np.savez(filename + "run1_device",cost=cost, thetas_opt=thetas_opt, loss=loss, accepted = accepted) fig, axs = plt.subplots(ncols=2, figsize=(10,5)) cost_device = np.load(filename + "run1_device.npz",allow_pickle=True)["cost"] cost_sim = np.load(filename + "run1_sim.npz",allow_pickle=True)["cost"] ax = axs[0] ax.plot(gx_list, cost_sim,"X--", label="cost sim.") ax.plot(gx_list, cost_device,"X--", label="cost ibmq_jakarta") ax.plot(gx_list, np.abs(Qmag_sim),"x--", label="$\hat{S}$ sim") ax.plot(gx_list, np.abs(Qmag_executed),"x--", label="$\hat{S}$ ibmq_jakarta") ax.set_xscale("log") ax.legend() ax = axs[1] ax.plot(gx_list, cost_sim,"X--", label="cost sim.") ax.plot(gx_list, cost_device,"X--", label="cost ibmq_jakarta") ax.plot(gx_list, Qmag_sim,"x--", label="$\hat{S}$ sim") ax.plot(gx_list, Qmag_executed,"x--", label="$\hat{S}$ ibmq_jakarta") ax.set_xscale("log") ax.legend() # Training phys_params = [0] thetas_guess = np.load(filename + "run1_thetas_opt_sim2.npz",allow_pickle=True)["thetas_opt"] thetas_opt, loss, accepted = optimize(phys_params, thetas= thetas_guess, callback=False, max_iter=25, L=5, meas_fitter=meas_fitter) #, pick_optimizer="adam") plt.plot(loss) np.savez(filename + "run1_thetas_opt_device2", thetas_opt=thetas_opt, loss=loss, accepted=accepted) # Inference; note that on the real device each inference points takes about ~30 seconds cost = np.zeros((len(gx_vals))) thetas_opt = np.load(filename + "run1_thetas_opt_device2.npz",allow_pickle=True)["thetas_opt"] shots = 1000 for i,p in enumerate(list(gx_list)): t0 = datetime.datetime.now() cost[i] = cost_function_single(thetas_opt, L, num_trash, i, shots=shots, meas_fitter=meas_fitter) # np.random.uniform(0, 2*np.pi, 2*L+2) random parameters to check if training "does" something - result was: with random paremters just get noise, so yes, it "does" something print(f"{i} / {len(gx_list)} - execution time {datetime.datetime.now()-t0}") np.savez(filename + "run1_device2",cost=cost, thetas_opt=thetas_opt, loss=loss, accepted = accepted) filename fig, axs = plt.subplots(ncols=2, figsize=(10,5)) cost_device = np.load(filename + "run1_device2.npz",allow_pickle=True)["cost"] cost_sim = np.load(filename + "run1_sim2.npz",allow_pickle=True)["cost"] ax = axs[0] ax.plot(gx_list, cost_sim,"X--", label="cost sim.") ax.plot(gx_list, cost_device,"X--", label="cost ibmq_jakarta") ax.plot(gx_list, np.abs(Qmag_sim),"x--", label="$\hat{S}$ sim") ax.plot(gx_list, np.abs(Qmag_executed),"x--", label="$\hat{S}$ ibmq_jakarta") ax.set_xscale("log") ax.legend() ax = axs[1] ax.plot(gx_list, cost_sim,"X--", label="cost sim.") ax.plot(gx_list, cost_device,"X--", label="cost ibmq_jakarta") ax.plot(gx_list, Qmag_sim,"x--", label="$\hat{S}$ sim") ax.plot(gx_list, Qmag_executed,"x--", label="$\hat{S}$ ibmq_jakarta") ax.set_xscale("log") ax.legend() meas_fitter = calibrate_circuit(L, nums_trash=trash_qubits_idxs) # Inference; note that on the real device each inference points takes about ~30 seconds cost = np.zeros((len(gx_vals))) thetas_opt = np.load(filename + "run2_thetas_opt_sim.npz",allow_pickle=True)["thetas_opt"] shots = 1000 for i,p in enumerate(list(gx_list)): t0 = datetime.datetime.now() cost[i] = cost_function_single(thetas_opt, L, num_trash, i, shots=shots, meas_fitter=meas_fitter) # np.random.uniform(0, 2*np.pi, 2*L+2) random parameters to check if training "does" something - result was: with random paremters just get noise, so yes, it "does" something print(f"{i} / {len(gx_list)} - execution time {datetime.datetime.now()-t0}") filename np.savez(filename + "run2_device",cost=cost, thetas_opt=thetas_opt, loss=loss, accepted = accepted) fig, axs = plt.subplots(ncols=2, figsize=(10,5)) cost_device = np.load(filename + "run2_device.npz",allow_pickle=True)["cost"] cost_sim = np.load(filename + "run2_sim.npz",allow_pickle=True)["cost"] ax = axs[0] ax.plot(gx_list, cost_sim,"X--", label="cost sim.") ax.plot(gx_list, cost_device,"X--", label="cost ibmq_jakarta") ax.plot(gx_list, np.abs(Qmag_sim),"x--", label="$\hat{S}$ sim") ax.plot(gx_list, np.abs(Qmag_executed),"x--", label="$\hat{S}$ ibmq_jakarta") ax.set_xscale("log") ax.legend() ax = axs[1] ax.plot(gx_list, cost_sim,"X--", label="cost sim.") ax.plot(gx_list, cost_device,"X--", label="cost ibmq_jakarta") ax.plot(gx_list, Qmag_sim,"x--", label="$\hat{S}$ sim") ax.plot(gx_list, Qmag_executed,"x--", label="$\hat{S}$ ibmq_jakarta") ax.set_xscale("log") ax.legend() meas_fitter = calibrate_circuit(L, nums_trash=trash_qubits_idxs) # Training phys_params = [-1] thetas_guess = np.load(filename + "run2_thetas_opt_sim.npz",allow_pickle=True)["thetas_opt"] thetas_opt, loss, accepted = optimize(phys_params, thetas= thetas_guess, callback=False, max_iter=25, L=5, meas_fitter=meas_fitter) #, pick_optimizer="adam") plt.plot(loss) np.savez(filename + "run2_thetas_opt_device_overnight", thetas_opt=thetas_opt, loss=loss, accepted=accepted) # Inference; note that on the real device each inference points takes about ~30 seconds cost = np.zeros((len(gx_vals))) thetas_opt = np.load(filename + "run2_thetas_opt_device_overnight.npz",allow_pickle=True)["thetas_opt"] shots = 1000 for i,p in enumerate(list(gx_list)): t0 = datetime.datetime.now() cost[i] = cost_function_single(thetas_opt, L, num_trash, i, shots=shots, meas_fitter=meas_fitter) # np.random.uniform(0, 2*np.pi, 2*L+2) random parameters to check if training "does" something - result was: with random paremters just get noise, so yes, it "does" something print(f"{i} / {len(gx_list)} - execution time {datetime.datetime.now()-t0}") np.savez(filename + "run2_device_overnight",cost=cost, thetas_opt=thetas_opt, loss=loss, accepted = accepted) fig, axs = plt.subplots(ncols=2, figsize=(10,5)) cost_device = np.load(filename + "run2_device_overnight.npz",allow_pickle=True)["cost"] cost_sim = np.load(filename + "run2_sim2.npz",allow_pickle=True)["cost"] ax = axs[0] ax.plot(gx_list, cost_sim,"X--", label="cost sim.") ax.plot(gx_list, cost_device,"X--", label="cost ibmq_jakarta") ax.plot(gx_list, np.abs(Qmag_sim),"x--", label="$\hat{S}$ sim") ax.plot(gx_list, np.abs(Qmag_executed),"x--", label="$\hat{S}$ ibmq_jakarta") ax.set_xscale("log") ax.legend() ax = axs[1] ax.plot(gx_list, cost_sim,"X--", label="cost sim.") ax.plot(gx_list, cost_device,"X--", label="cost ibmq_jakarta") ax.plot(gx_list, Qmag_sim,"x--", label="$\hat{S}$ sim") ax.plot(gx_list, Qmag_executed,"x--", label="$\hat{S}$ ibmq_jakarta") ax.set_xscale("log") ax.legend()
https://github.com/Qottmann/Quantum-anomaly-detection
Qottmann
%%capture %pip install qiskit %pip install qiskit_ibm_provider %pip install qiskit-aer # Importing standard Qiskit libraries from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, QuantumCircuit, transpile, Aer from qiskit_ibm_provider import IBMProvider from qiskit.tools.jupyter import * from qiskit.visualization import * from qiskit.circuit.library import C3XGate # Importing matplotlib import matplotlib.pyplot as plt # Importing Numpy, Cmath and math import numpy as np import os, math, cmath from numpy import pi # Other imports from IPython.display import display, Math, Latex # Specify the path to your env file env_file_path = 'config.env' # Load environment variables from the file os.environ.update(line.strip().split('=', 1) for line in open(env_file_path) if '=' in line and not line.startswith('#')) # Load IBM Provider API KEY IBMP_API_KEY = os.environ.get('IBMP_API_KEY') # Loading your IBM Quantum account(s) IBMProvider.save_account(IBMP_API_KEY, overwrite=True) # Run the quantum circuit on a statevector simulator backend backend = Aer.get_backend('statevector_simulator') qc_b1 = QuantumCircuit(2, 2) qc_b1.h(0) qc_b1.cx(0, 1) qc_b1.draw(output='mpl', style="iqp") sv = backend.run(qc_b1).result().get_statevector() sv.draw(output='latex', prefix = "|\Phi^+\\rangle = ") qc_b2 = QuantumCircuit(2, 2) qc_b2.x(0) qc_b2.h(0) qc_b2.cx(0, 1) qc_b2.draw(output='mpl', style="iqp") sv = backend.run(qc_b2).result().get_statevector() sv.draw(output='latex', prefix = "|\Phi^-\\rangle = ") qc_b2 = QuantumCircuit(2, 2) qc_b2.h(0) qc_b2.cx(0, 1) qc_b2.z(0) qc_b2.draw(output='mpl', style="iqp") sv = backend.run(qc_b2).result().get_statevector() sv.draw(output='latex', prefix = "|\Phi^-\\rangle = ") qc_b3 = QuantumCircuit(2, 2) qc_b3.x(1) qc_b3.h(0) qc_b3.cx(0, 1) qc_b3.draw(output='mpl', style="iqp") sv = backend.run(qc_b3).result().get_statevector() sv.draw(output='latex', prefix = "|\Psi^+\\rangle = ") qc_b3 = QuantumCircuit(2, 2) qc_b3.h(0) qc_b3.cx(0, 1) qc_b3.x(0) qc_b3.draw(output='mpl', style="iqp") sv = backend.run(qc_b3).result().get_statevector() sv.draw(output='latex', prefix = "|\Psi^+\\rangle = ") qc_b4 = QuantumCircuit(2, 2) qc_b4.x(0) qc_b4.h(0) qc_b4.x(1) qc_b4.cx(0, 1) qc_b4.draw(output='mpl', style="iqp") sv = backend.run(qc_b4).result().get_statevector() sv.draw(output='latex', prefix = "|\Psi^-\\rangle = ") qc_b4 = QuantumCircuit(2, 2) qc_b4.h(0) qc_b4.cx(0, 1) qc_b4.x(0) qc_b4.z(1) qc_b4.draw(output='mpl', style="iqp") sv = backend.run(qc_b4).result().get_statevector() sv.draw(output='latex', prefix = "|\Psi^-\\rangle = ") def sv_latex_from_qc(qc, backend): sv = backend.run(qc).result().get_statevector() return sv.draw(output='latex') qc_ej2 = QuantumCircuit(4, 4) qc_ej2.x(0) sv_latex_from_qc(qc_ej2, backend) qc_ej2 = QuantumCircuit(4, 4) qc_ej2.x(1) sv_latex_from_qc(qc_ej2, backend) qc_ej2 = QuantumCircuit(4, 4) qc_ej2.x(0) qc_ej2.x(1) sv_latex_from_qc(qc_ej2, backend) qc_ej2 = QuantumCircuit(4, 4) qc_ej2.x(2) sv_latex_from_qc(qc_ej2, backend) qc_ej2 = QuantumCircuit(4, 4) qc_ej2.x(0) qc_ej2.x(2) sv_latex_from_qc(qc_ej2, backend) qc_ej2 = QuantumCircuit(4, 4) qc_ej2.x(0) qc_ej2.x(2) sv_latex_from_qc(qc_ej2, backend) qc_ej2 = QuantumCircuit(4, 4) qc_ej2.x(0) qc_ej2.x(1) qc_ej2.x(2) sv_latex_from_qc(qc_ej2, backend) qc_ej2 = QuantumCircuit(4, 4) qc_ej2.x(3) sv_latex_from_qc(qc_ej2, backend) def circuit_adder (num): if num<1 or num>8: raise ValueError("Out of range") ## El enunciado limita el sumador a los valores entre 1 y 8. Quitar esta restricción sería directo. # Definición del circuito base que vamos a construir qreg_q = QuantumRegister(4, 'q') creg_c = ClassicalRegister(1, 'c') circuit = QuantumCircuit(qreg_q, creg_c) qbit_position = 0 for element in reversed(np.binary_repr(num)): if (element=='1'): circuit.barrier() match qbit_position: case 0: # +1 circuit.append(C3XGate(), [qreg_q[0], qreg_q[1], qreg_q[2], qreg_q[3]]) circuit.ccx(qreg_q[0], qreg_q[1], qreg_q[2]) circuit.cx(qreg_q[0], qreg_q[1]) circuit.x(qreg_q[0]) case 1: # +2 circuit.ccx(qreg_q[1], qreg_q[2], qreg_q[3]) circuit.cx(qreg_q[1], qreg_q[2]) circuit.x(qreg_q[1]) case 2: # +4 circuit.cx(qreg_q[2], qreg_q[3]) circuit.x(qreg_q[2]) case 3: # +8 circuit.x(qreg_q[3]) qbit_position+=1 return circuit add_3 = circuit_adder(3) add_3.draw(output='mpl', style="iqp") qc_test_2 = QuantumCircuit(4, 4) qc_test_2.x(1) qc_test_2_plus_3 = qc_test_2.compose(add_3) qc_test_2_plus_3.draw(output='mpl', style="iqp") sv_latex_from_qc(qc_test_2_plus_3, backend) qc_test_7 = QuantumCircuit(4, 4) qc_test_7.x(0) qc_test_7.x(1) qc_test_7.x(2) qc_test_7_plus_8 = qc_test_7.compose(circuit_adder(8)) sv_latex_from_qc(qc_test_7_plus_8, backend) #qc_test_7_plus_8.draw() theta = 6.544985 phi = 2.338741 lmbda = 0 alice_1 = 0 alice_2 = 1 bob_1 = 2 qr_alice = QuantumRegister(2, 'Alice') qr_bob = QuantumRegister(1, 'Bob') cr = ClassicalRegister(3, 'c') qc_ej3 = QuantumCircuit(qr_alice, qr_bob, cr) qc_ej3.barrier(label='1') qc_ej3.u(theta, phi, lmbda, alice_1); qc_ej3.barrier(label='2') qc_ej3.h(alice_2) qc_ej3.cx(alice_2, bob_1); qc_ej3.barrier(label='3') qc_ej3.cx(alice_1, alice_2) qc_ej3.h(alice_1); qc_ej3.barrier(label='4') qc_ej3.measure([alice_1, alice_2], [alice_1, alice_2]); qc_ej3.barrier(label='5') qc_ej3.x(bob_1).c_if(alice_2, 1) qc_ej3.z(bob_1).c_if(alice_1, 1) qc_ej3.measure(bob_1, bob_1); qc_ej3.draw(output='mpl', style="iqp") result = backend.run(qc_ej3, shots=1024).result() counts = result.get_counts() plot_histogram(counts) sv_0 = np.array([1, 0]) sv_1 = np.array([0, 1]) def find_symbolic_representation(value, symbolic_constants={1/np.sqrt(2): '1/√2'}, tolerance=1e-10): """ Check if the given numerical value corresponds to a symbolic constant within a specified tolerance. Parameters: - value (float): The numerical value to check. - symbolic_constants (dict): A dictionary mapping numerical values to their symbolic representations. Defaults to {1/np.sqrt(2): '1/√2'}. - tolerance (float): Tolerance for comparing values with symbolic constants. Defaults to 1e-10. Returns: str or float: If a match is found, returns the symbolic representation as a string (prefixed with '-' if the value is negative); otherwise, returns the original value. """ for constant, symbol in symbolic_constants.items(): if np.isclose(abs(value), constant, atol=tolerance): return symbol if value >= 0 else '-' + symbol return value def array_to_dirac_notation(array, tolerance=1e-10): """ Convert a complex-valued array representing a quantum state in superposition to Dirac notation. Parameters: - array (numpy.ndarray): The complex-valued array representing the quantum state in superposition. - tolerance (float): Tolerance for considering amplitudes as negligible. Returns: str: The Dirac notation representation of the quantum state. """ # Ensure the statevector is normalized array = array / np.linalg.norm(array) # Get the number of qubits num_qubits = int(np.log2(len(array))) # Find indices where amplitude is not negligible non_zero_indices = np.where(np.abs(array) > tolerance)[0] # Generate Dirac notation terms terms = [ (find_symbolic_representation(array[i]), format(i, f"0{num_qubits}b")) for i in non_zero_indices ] # Format Dirac notation dirac_notation = " + ".join([f"{amplitude}|{binary_rep}⟩" for amplitude, binary_rep in terms]) return dirac_notation def array_to_matrix_representation(array): """ Convert a one-dimensional array to a column matrix representation. Parameters: - array (numpy.ndarray): The one-dimensional array to be converted. Returns: numpy.ndarray: The column matrix representation of the input array. """ # Replace symbolic constants with their representations matrix_representation = np.array([find_symbolic_representation(value) or value for value in array]) # Return the column matrix representation return matrix_representation.reshape((len(matrix_representation), 1)) def array_to_dirac_and_matrix_latex(array): """ Generate LaTeX code for displaying both the matrix representation and Dirac notation of a quantum state. Parameters: - array (numpy.ndarray): The complex-valued array representing the quantum state. Returns: Latex: A Latex object containing LaTeX code for displaying both representations. """ matrix_representation = array_to_matrix_representation(array) latex = "Matrix representation\n\\begin{bmatrix}\n" + \ "\\\\\n".join(map(str, matrix_representation.flatten())) + \ "\n\\end{bmatrix}\n" latex += f'Dirac Notation:\n{array_to_dirac_notation(array)}' return Latex(latex) sv_b1 = np.kron(sv_0, sv_0) array_to_dirac_and_matrix_latex(sv_b1) sv_b1 = (np.kron(sv_0, sv_0) + np.kron(sv_0, sv_1)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b1) sv_b1 = (np.kron(sv_0, sv_0) + np.kron(sv_1, sv_1)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b1) sv_b2 = np.kron(sv_0, sv_0) array_to_dirac_and_matrix_latex(sv_b2) sv_b2 = (np.kron(sv_0, sv_0) + np.kron(sv_0, sv_1)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b2) sv_b2 = (np.kron(sv_0, sv_0) + np.kron(sv_1, sv_1)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b2) sv_b2 = (np.kron(sv_0, sv_0) - np.kron(sv_1, sv_1)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b2) sv_b3 = np.kron(sv_0, sv_0) array_to_dirac_and_matrix_latex(sv_b3) sv_b3 = np.kron(sv_0, sv_1) array_to_dirac_and_matrix_latex(sv_b3) sv_b3 = (np.kron(sv_0, sv_0) - np.kron(sv_0, sv_1)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b3) sv_b3 = (np.kron(sv_0, sv_1) - np.kron(sv_1, sv_0)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b3) sv_b3 = (np.kron(sv_0, sv_1) + np.kron(sv_1, sv_0)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b3) sv_b4 = np.kron(sv_0, sv_0) array_to_dirac_and_matrix_latex(sv_b4) sv_b4 = np.kron(sv_0, sv_1) array_to_dirac_and_matrix_latex(sv_b4) sv_b4 = (np.kron(sv_0, sv_0) - np.kron(sv_0, sv_1)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b4) sv_b4 = (np.kron(sv_0, sv_1) - np.kron(sv_1, sv_0)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b4)
https://github.com/Qottmann/Quantum-anomaly-detection
Qottmann
import sys from matplotlib import pyplot as plt import numpy as np import matplotlib.gridspec as gridspec plt.rc('text', usetex=True) plt.rc('font', family='serif') path = "data/BH_phase-diagrams-and-loss/data_rike/" x = np.load(path + "x.npy") y = np.load(path + "y.npy") es = np.load(path + "es2.npy") dd = np.load(path + "dd2.npy") cost0 = np.load(path + "cost_bh_L12_trash2_d48_v5_seed17.npy") cost1 = np.load(path + "cost_bh_L12_trash4_d25_v47_seed16.npy") cost2 = np.load(path + "cost_bh_L12_trash6_d10_v10_seed22.npy") vs = np.logspace(-2,2,50) ds = np.linspace(-0.95,0.95,50) fig,aa = plt.subplots(figsize=(16,4),sharey="row",dpi=220) fs_labels = 17 fs_ticks = 16 ax00 = plt.subplot2grid(shape=(8,25), loc=(0, 0), rowspan=4, colspan=4, xticklabels=[]) ax10 = plt.subplot2grid(shape=(8,25), loc=(4, 0), rowspan=4, colspan=4, xticklabels=[]) ax01 = plt.subplot2grid(shape=(8,25), loc=(1, 7), rowspan=6, colspan=6, xticklabels=[]) ax02 = plt.subplot2grid(shape=(8,25), loc=(1, 13), rowspan=6, colspan=6, xticklabels=[], yticklabels=[]) ax03 = plt.subplot2grid(shape=(8,25), loc=(1, 19), rowspan=6, colspan=6, xticklabels=[], yticklabels=[]) cmap = plt.get_cmap("plasma") #'viridis' cbar_labelsize = 10 cbar = np.zeros((2,2), dtype="object") axs=np.array([[ax00,ax10],[ax01,ax02]]) print(axs[0,0]) for ax in axs.flatten(): ax.tick_params(labelsize=fs_ticks) ax = axs[0,0] axs[0,0].set_title("DMRG", fontsize=14) im = ax.pcolormesh(x,y,dd.T, cmap=cmap, shading="auto",rasterized=True) #,rasterized=True necessary for pdf export #im.ax.tick_params(labelsize=cbar_labelsize) ax.set_xscale("log") cbar[0,0] = fig.colorbar(im, ax=ax) cbar[0,0].ax.tick_params(labelsize=fs_ticks) cbar[0,0].ax.set_ylabel("$O_{CDW}$",fontsize=fs_labels) axs[0,0].set_ylabel(r"$\delta J$",fontsize=fs_labels) ax.set_xticks([], minor=True) ax.set_xticks([], minor=False) ax = axs[0,1] im = ax.pcolormesh(x,y,es.T, cmap=cmap, shading="auto",rasterized=True) ax.set_xscale("log") cbar[0,1] = fig.colorbar(im, ax=ax) cbar[0,1].ax.tick_params(labelsize=fs_ticks) cbar[0,1].ax.set_ylabel("$D_{ES}$",fontsize=fs_labels) axs[0,1].set_xlabel(r"$V/J$",fontsize=fs_labels) axs[0,1].set_ylabel(r"$\delta J$",fontsize=fs_labels) ax = axs[1,0] im = ax.pcolormesh(x,y,cost2.T,vmin=0, cmap=cmap, shading="auto",rasterized=True) ax.set_xscale("log") cbar[1,0] = fig.colorbar(im, ax=ax) cbar[1,0].ax.tick_params(labelsize=fs_ticks) ax.plot(vs[10],ds[10],"X", color="magenta",markersize=15, alpha=0.8) axs[1,0].set_xlabel(r"$V/J$",fontsize=fs_labels) axs[1,0].set_ylabel(r"$\delta J$",fontsize=fs_labels) ax = axs[1,1] im = ax.pcolormesh(x,y,cost1.T,vmin=0, cmap=cmap, shading="auto",rasterized=True) ax.set_xscale("log") cbar[1,1] = fig.colorbar(im, ax=ax) cbar[1,1].ax.tick_params(labelsize=fs_ticks) cbar[1,1].ax.set_title("cost", fontsize=fs_labels) ax.plot(vs[47],ds[25],"X", color="magenta",markersize=15, alpha=0.8) axs[1,1].set_xlabel(r"$V/J$",fontsize=fs_labels) ax.set_yticks([]) ax = ax03 ax.tick_params(labelsize=fs_ticks) im = ax.pcolormesh(x,y,cost0.T,vmin=0, cmap=cmap, shading="auto",rasterized=True) ax.set_xscale("log") cbar[1,1] = fig.colorbar(im, ax=ax) cbar[1,1].ax.tick_params(labelsize=fs_ticks) cbar[1,1].ax.set_title("cost", fontsize=fs_labels) ax.plot(vs[5],ds[48],"X", color="magenta",markersize=15, alpha=0.8) ax03.set_xlabel(r"$V/J$",fontsize=fs_labels) ax.set_yticks([]) plt.tight_layout() # has to happen after tight_layout() axs[0,0].text(-0.21,0.89,"(a)", fontweight="bold", size=fs_labels, transform = axs[0,0].transAxes) axs[1,0].text(0.5,1.07,"(c)", fontweight="bold", size=fs_labels, transform = axs[1,0].transAxes) axs[0,1].text(-0.21,0.88,"(b)", fontweight="bold", size=fs_labels, transform = axs[0,1].transAxes) axs[1,1].text(0.5,1.07,"(d)", fontweight="bold", size=fs_labels, transform = axs[1,1].transAxes) ax03.text(0.5,1.07,"(e)", fontweight="bold", size=fs_labels, transform = ax03.transAxes) axs[1,0].text(0.33,0.15,"MI", fontweight="bold", size=fs_labels, transform = axs[1,0].transAxes, color="white") axs[1,0].text(0.23,0.8,"TMI", fontweight="bold", size=fs_labels, transform = axs[1,0].transAxes) axs[1,0].text(0.7,0.5,"CDW", fontweight="bold", size=fs_labels, transform = axs[1,0].transAxes) cbar[1,0].ax.set_title("cost", fontsize=fs_labels) plt.savefig("plots/BH_paper.pdf", bbox_inches='tight') cost = np.load("data/ibmq_antiferro-2D_load-AD_10x10_noisy-rome-simu_thetas-loss-cost_run1.npy",allow_pickle=True) qmag = np.load("data/noisy_rome_simu_VQE_maxiter-500_Ising_L5_anti_-1_10x10.npz", allow_pickle=True)["Qmag"].reshape(10,10) x,y = np.logspace(-2,2,10), np.logspace(-2,2,10) x,y = np.meshgrid(x,y) fig,axs = plt.subplots(ncols=2, nrows=1,figsize=(8,3),sharex=True, sharey=True, dpi=220) cmap1 = plt.get_cmap("viridis") cmap2 = plt.get_cmap("plasma") cbar_labelsize = 18 cbar = np.zeros((2), dtype="object") ax0 = axs[0] im = ax0.pcolormesh(x, y, qmag, cmap=cmap1, shading="auto", rasterized=True) #,rasterized=True necessary for pdf export cbar[0] = fig.colorbar(im, ax=ax0) cbar[0].ax.tick_params(labelsize=cbar_labelsize) cbar[0].ax.set_ylabel("$\hat{S}$",fontsize=20) ax1 = axs[1] im = ax1.pcolormesh(x, y, cost,vmin=0, cmap=cmap2, shading="auto",rasterized=True) cbar[1] = fig.colorbar(im, ax=ax1) cbar[1].ax.tick_params(labelsize=cbar_labelsize) cbar[1].ax.set_ylabel("cost",fontsize=20) #ax.plot(vs[47],ds[25],"x", color="magenta") ax1.plot(1e-2,1e-2,"X", color="magenta",markersize=15, alpha=0.7, clip_on=False) ax0.set_yscale("log") ax0.set_yscale("log") ax1.set_xscale("log") ax0.set_xscale("log") ax0.tick_params(labelsize=18) ax1.tick_params(labelsize=18) ax1.set_xlabel(r"$g_x$",fontsize=20) ax0.set_ylabel(r"$g_z$",fontsize=20) ax0.set_xlabel(r"$g_x$",fontsize=20) #ax1.set_yticks([], minor=True) #ax1.set_yticks([], minor=False) plt.tight_layout() # has to happen after tight_layout() axs[0].text(-0.35,0.9,"(a)", fontweight="bold", size=18, transform = axs[0].transAxes) axs[1].text(-0.2, 0.9,"(b)", fontweight="bold", size=18, transform = axs[1].transAxes) plt.savefig("plots/antiferro2D_paper.pdf", bbox_inches='tight') anti = -1 L = 5 num_trash = 2 name = "ibmq_antiferro-1D-load_bogota-optimize-20points" # 01.06.2021 experiment filename = "data/noisy_VQE_maxiter-500_Ising_L5_anti_-1_20" #"data/noisy_VQE_maxiter-100_Ising_L5_anti_-1_20_recycle" print("filename: ", filename, "notebook name: ", name) # where to get the simulated thetas values from? needs to contain a thetas_mitigated array filename_simulated_thetas = 'data/ibmq_antiferro-1D-load_bogota-optimize_thetas-loss-cost_run2.npz' # this is noisy simulation data L = 5 num_trash = 2 anti = -1 VQE_params = np.load(filename + ".npz", allow_pickle=True) pick = np.arange(0,len(VQE_params['gx_list'])) gx_list = VQE_params['gx_list'][pick] gz_list = VQE_params['gz_list'][pick] opt_params = VQE_params['opt_params'][pick] Qmags = VQE_params["Qmag"][pick] Qen = VQE_params["Qen"][pick] Sen = VQE_params["Sen"][pick] Smags = VQE_params["Smag"][pick] temp = np.load("data/" + name + "executed_mags-Es.npz",allow_pickle=True) Qmags_executed = temp["Qmags"] gx_vals = np.unique(gx_list) gz_vals = np.unique(gz_list) fig, axs = plt.subplots(nrows=2,figsize=(5,5),sharex=True,gridspec_kw={'height_ratios': [2, 2]},dpi=220) ax = axs[0] cost = np.load("data/" + "ibmq_antiferro-1D-load_simu" + "_thetas-loss-cost_run1.npz", allow_pickle=True)["cost_mitigated"] ax.plot(gx_list, cost,".:")#, label="loss noisy sim.") cost = np.load("data/" + name + "_thetas-loss-cost_run1.npz", allow_pickle=True)["cost_mitigated"] ax.plot(gx_list, cost,".:")#, label="loss ibmq_bogota") ax.plot(gx_list, Qmags,"x--", label="$\hat{S}$ noisy sim.") ax.plot(gx_list, Qmags_executed,"x--", label="$\hat{S}$ ibmq$\_$bogota") ax.set_xscale("log") ax.plot(gx_list[0],cost[0], "X",markersize=20,alpha=0.4,color="magenta") ax = axs[1] cost = np.load("data/" + "ibmq_antiferro-1D-load_simu" + "_thetas-loss-cost_run2.npz", allow_pickle=True)["cost_mitigated"] ax.plot(gx_list, cost,"x--", label="cost noisy sim.") cost = np.load("data/" + name + "_thetas-loss-cost_run2.npz", allow_pickle=True)["cost_mitigated"] ax.plot(gx_list, cost,".:", label="cost ibmq$\_$bogota") ax.plot(gx_list, abs(Qmags),"x--", label="$\mid \hat{S} \mid$ noisy sim.") ax.plot(gx_list, abs(Qmags_executed),".:", label="$\mid \hat{S} \mid$ ibmq$\_$bogota") ax.set_xscale("log") ax.plot(gx_list[-1],cost[-1],"X",markersize=20,alpha=0.4,color="magenta") for ax in axs: ax.legend() ax.tick_params(labelsize=14) axs[-1].set_xlabel("$g_x$", fontsize=18) plt.tight_layout() axs[0].text(-0.11,0.9,"(a)", fontweight="bold", size=18, transform = axs[0].transAxes) axs[1].text(-0.11,0.9,"(b)", fontweight="bold", size=18, transform = axs[1].transAxes) plt.savefig("plots/" + name + "_mainplot.png", bbox_inches='tight') plt.savefig("plots/" + name + "_mainplot.pdf", bbox_inches='tight')
https://github.com/Qottmann/Quantum-anomaly-detection
Qottmann
"""A quantum auto-encoder (QAE).""" from typing import Union, Optional, List, Tuple, Callable, Any import numpy as np from qiskit import * from qiskit.circuit.quantumcircuit import QuantumCircuit from qiskit.circuit.library import TwoLocal from qiskit.circuit.library.standard_gates import RYGate, CZGate from qiskit.circuit.gate import Gate from qiskit.algorithms.optimizers import Optimizer, SPSA from qiskit.utils import algorithm_globals from qiskit.providers import BaseBackend, Backend class QAEAnsatz(TwoLocal): def __init__( self, num_qubits: int, num_trash_qubits: int, trash_qubits_idxs: Union[np.ndarray, List] = [1, 2], # TODO measure_trash: bool = False, rotation_blocks: Gate = RYGate, entanglement_blocks: Gate = CZGate, parameter_prefix: str = 'θ', insert_barriers: bool = False, initial_state: Optional[Any] = None, ) -> None: """Create a new QAE circuit. Args: num_qubits: The number of qubits of the QAE circuit. num_trash_qubits: The number of trash qubits that should be measured in the end. trash_qubits_idxs: The explicit indices of the trash qubits, i.e., where the trash qubits should be placed. measure_trash: If True, the trash qubits will be measured at the end. If False, no measurement takes place. rotation_blocks: The blocks used in the rotation layers. If multiple are passed, these will be applied one after another (like new sub-layers). entanglement_blocks: The blocks used in the entanglement layers. If multiple are passed, these will be applied one after another. parameter_prefix: The prefix used if default parameters are generated. insert_barriers: If True, barriers are inserted in between each layer. If False, no barriers are inserted. initial_state: A `QuantumCircuit` object which can be used to describe an initial state prepended to the NLocal circuit. """ assert num_trash_qubits < num_qubits self.num_trash_qubits = num_trash_qubits self.trash_qubits_idxs = trash_qubits_idxs self.measure_trash = measure_trash entanglement = [QAEAnsatz._generate_entangler_map( num_qubits, num_trash_qubits, i, trash_qubits_idxs) for i in range(num_trash_qubits)] super().__init__(num_qubits=num_qubits, rotation_blocks=rotation_blocks, entanglement_blocks=entanglement_blocks, entanglement=entanglement, reps=num_trash_qubits, skip_final_rotation_layer=True, parameter_prefix=parameter_prefix, insert_barriers=insert_barriers, initial_state=initial_state) self.add_register(ClassicalRegister(self.num_trash_qubits)) @staticmethod def _generate_entangler_map(num_qubits: int, num_trash_qubits: int, i_permut: int = 1, trash_qubits_idxs: Union[np.ndarray, List] = [1, 2]) -> List[Tuple[int, int]]: """Generates entanglement map for QAE circuit Entangling gates are only added between trash and non-trash-qubits. Args: num_qubits: The number of qubits of the QAE circuit. num_trash_qubits: The number of trash qubits that should be measured in the end. i_permut: Permutation index; increases for every layer of the circuit trash_qubits_idxs: The explicit indices of the trash qubits, i.e., where the trash qubits should be placed. Returns: entanglement map: List of pairs of qubit indices that should be entangled """ result = [] nums_compressed = list(range(num_qubits)) for trashqubit in trash_qubits_idxs: nums_compressed.remove(trashqubit) if trash_qubits_idxs == None: nums_compressed = list(range(num_qubits))[:num_qubits-num_trash_qubits] trash_qubits_idxs = list(range(num_qubits))[-num_trash_qubits:] # combine all trash qubits with themselves for i,trash_q in enumerate(trash_qubits_idxs[:-1]): result.append((trash_qubits_idxs[i+1], trash_qubits_idxs[i])) # combine each of the trash qubits with every n-th # repeat the list of trash indices cyclicly repeated = list(trash_qubits_idxs) * (num_qubits-num_trash_qubits) for i in range(num_qubits-num_trash_qubits): result.append((repeated[i_permut + i], nums_compressed[i])) return result def _build(self) -> None: """Build the circuit.""" if self._data: return _ = self._check_configuration() self._data = [] if self.num_qubits == 0: return # use the initial state circuit if it is not None if self._initial_state: circuit = self._initial_state.construct_circuit('circuit', register=self.qregs[0]) self.compose(circuit, inplace=True) param_iter = iter(self.ordered_parameters) # build the prepended layers self._build_additional_layers('prepended') # main loop to build the entanglement and rotation layers for i in range(self.reps): # insert barrier if specified and there is a preceding layer if self._insert_barriers and (i > 0 or len(self._prepended_blocks) > 0): self.barrier() # build the rotation layer self._build_rotation_layer(param_iter, i) # barrier in between rotation and entanglement layer if self._insert_barriers and len(self._rotation_blocks) > 0: self.barrier() # build the entanglement layer self._build_entanglement_layer(param_iter, i) # add the final rotation layer if self.insert_barriers and self.reps > 0: self.barrier() for j, block in enumerate(self.rotation_blocks): # create a new layer layer = QuantumCircuit(*self.qregs) block_indices = [[i] for i in self.trash_qubits_idxs] # apply the operations in the layer for indices in block_indices: parameterized_block = self._parameterize_block(block, param_iter, i, j, indices) layer.compose(parameterized_block, indices, inplace=True) # add the layer to the circuit self.compose(layer, inplace=True) # add the appended layers self._build_additional_layers('appended') # measure trash qubits if set if self.measure_trash: for i, j in enumerate(self.trash_qubits_idxs): self.measure(self.qregs[0][j], self.cregs[0][i]) @property def num_parameters_settable(self) -> int: """The number of total parameters that can be set to distinct values. Returns: The number of parameters originally available in the circuit. """ return super().num_parameters_settable + self.num_trash_qubits def hamming_distance(out) -> int: """Computes the Hamming distance of a measurement outcome to the all zero state. For example: A single measurement outcome 101 would have a Hamming distance of 2. Args: out: The measurement outcomes; a dictionary containing all possible measurement strings as keys and their occurences as values. Returns: Hamming distance """ return sum(key.count('1') * value for key, value in out.items()) class QAE: def __init__( self, num_qubits: int, num_trash_qubits: int, ansatz: Optional[QuantumCircuit] = None, initial_params: Optional[Union[np.ndarray, List]] = None, optimizer: Optional[Optimizer] = None, shots: int = 1000, num_epochs: int = 100, save_training_curve: Optional[bool] = False, seed: int = 123, backend: Union[BaseBackend, Backend] = Aer.get_backend('qasm_simulator') ) -> None: """Quantum auto-encoder. Args: num_qubits: The number of qubits of the QAE circuit. num_trash_qubits: The number of trash qubits that should be measured in the end. ansatz: A parameterized quantum circuit ansatz to be optimized. initial_params: The initial list of parameters for the circuit ansatz optimizer: The optimizer used for training (default is SPSA) shots: The number of measurement shots when training and evaluating the QAE. num_epochs: The number of training iterations/epochs. save_training_curve: If True, the cost after each optimizer step is computed and stored. seed: Random number seed. backend: The backend on which the QAE is performed. """ algorithm_globals.random_seed = seed np.random.seed(seed) self.costs = [] if save_training_curve: callback = self._store_intermediate_result else: callback = None if optimizer: self.optimizer = optimizer else: self.optimizer = SPSA(num_epochs, callback=callback) self.backend = backend if ansatz: self.ansatz = ansatz else: self.ansatz = QAEAnsatz(num_qubits, num_trash_qubits, measure_trash=True) if initial_params: self.initial_params = initial_params else: self.initial_params = np.random.uniform(0, 2*np.pi, self.ansatz.num_parameters_settable) self.shots = shots self.save_training_curve = save_training_curve def run(self, input_state: Optional[Any] = None, params: Optional[Union[np.ndarray, List]] = None): """Execute ansatz circuit and measure trash qubits Args: input_state: If provided, circuit is initialized accordingly params: If provided, list of optimization parameters for circuit Returns: measurement outcomes """ if params is None: params = self.initial_params if input_state is not None: if type(input_state) == QuantumCircuit: circ = input_state elif type(input_state) == list or type(input_state) == np.ndarray: circ = QuantumCircuit(self.ansatz.num_qubits, self.ansatz.num_trash_qubits) circ.initialize(input_state) else: raise TypeError("input_state has to be an array or a QuantumCircuit.") circ = circ.compose(self.ansatz) else: circ = self.ansatz circ = circ.assign_parameters(params) job_sim = execute(circ, self.backend, shots=self.shots) return job_sim.result().get_counts(circ) def cost(self, input_state: Optional[Any] = None, params: Optional[Union[np.ndarray, List]] = None) -> float: """ Cost function Average Hamming distance of measurement outcomes to zero state. Args: input_state: If provided, circuit is initialized accordingly params: If provided, list of optimization parameters for circuit Returns: Cost """ out = self.run(input_state, params) cost = hamming_distance(out) return cost/self.shots def _store_intermediate_result(self, eval_count, parameters, mean, std, ac): """Callback function to save intermediate costs during training.""" self.costs.append(mean) def train(self, input_state: Optional[Any] = None): """ Trains the QAE using optimizer (default SPSA) Args: input_state: If provided, circuit is initialized accordingly Returns: Result of optimization: optimized parameters, cost, iterations Training curve: Cost function evaluated after each iteration """ result = self.optimizer.optimize( num_vars=len(self.initial_params), objective_function=lambda params: self.cost(input_state, params), initial_point=self.initial_params ) self.initial_params = result[0] return result, self.costs def reset(self): """Resets parameters to random values""" self.costs = [] self.initial_params = np.random.uniform(0, 2*np.pi, self.ansatz.num_parameters_settable) if __name__ == '__main__': num_qubits = 5 num_trash_qubits = 2 qae = QAE(num_qubits, num_trash_qubits, save_training_curve=True) # for demonstration purposes QAE is trained on a random state input_state = np.random.uniform(size=2**num_qubits) input_state /= np.linalg.norm(input_state) result, cost = qae.train(input_state)
https://github.com/Qottmann/Quantum-anomaly-detection
Qottmann
import time import itertools import numpy as np import qiskit from qiskit import * from qiskit.quantum_info import Statevector from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B, SPSA from qiskit.opflow.state_fns import StateFn, CircuitStateFn from qiskit.providers.aer import StatevectorSimulator, AerSimulator from qiskit.opflow import CircuitSampler from qiskit.ignis.mitigation.measurement import CompleteMeasFitter # you will need to pip install qiskit-ignis from qiskit.ignis.mitigation.measurement import complete_meas_cal import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator from matplotlib.colors import BoundaryNorm cmap = plt.get_cmap("plasma") #'viridis' from modules.utils import * from qae import * import datetime import tenpy from tenpy.networks.mps import MPS from tenpy.models.hubbard import BoseHubbardChain from tenpy.models.tf_ising import TFIChain from tenpy.algorithms import dmrg from tenpy.linalg import np_conserved def DMRG_EBH(L, V, t_list, chi_max=30, bc_MPS='infinite'): model_params = dict(n_max=1, filling=0.5, bc_MPS=bc_MPS, t=t_list, L=L, V=V, mu=0, conserve='N') M = BoseHubbardChain(model_params) vector=[] for i in range(M.lat.N_sites): if i%2: vector.append(1) else: vector.append(0) psi = MPS.from_product_state(M.lat.mps_sites(), vector, bc=M.lat.bc_MPS) dmrg_params = { 'mixer': True, 'trunc_params': { 'chi_max': chi_max, }, 'max_E_err': 1.e-16, #'verbose': 0 } info = dmrg.run(psi, M, dmrg_params) return info['E'], psi def DMRG_Ising(L, J, g, chi_max=30, bc_MPS='finite'): model_params = dict(bc_MPS=bc_MPS, bc_x="open", L=L, J=J, g=g, conserve="best") M = TFIChain(model_params) product_state = ["up"] * M.lat.N_sites psi = MPS.from_product_state(M.lat.mps_sites(), product_state, bc=M.lat.bc_MPS) dmrg_params = { 'mixer': True, 'trunc_params': { 'chi_max': chi_max, }, 'max_E_err': 1e-16, #'verbose': 0 } info = dmrg.run(psi, M, dmrg_params) return info['E'], psi ### Preliminaries qiskit_chi = 100 L = 8 num_trash = int(np.log(L)/np.log(2)) anti = 1 # 1 for ferromagnetic Ising model, -1 for antiferromagnet g = 0.05 J=anti filename = "data/QAEAnsatz_scaling_MPS_script" backend = qiskit.providers.aer.AerSimulator(method="matrix_product_state", precision="single", matrix_product_state_max_bond_dimension = qiskit_chi, matrix_product_state_truncation_threshold = 1e-10, #mps_sample_measure_algorithm = "mps_apply_measure", #alt: "mps_probabilities" ) from qiskit.utils import algorithm_globals algorithm_globals.random_seed = 333 def qiskit_state(psi0): # G is only the local tensor (not multiplied by any singular values) - see https://tenpy.readthedocs.io/en/latest/reference/tenpy.networks.mps.html A_list = [psi0.get_B(i, form="G").to_ndarray().transpose([1,0,2]) for i in range(L)] for i,A in enumerate(A_list): A_list[i] = (A[0], A[1]) S_list = [psi0.get_SR(i) for i in range(L-1)] # skip trivial last bond; hast to be of size L-1 return (A_list, S_list) def prepare_circuit(thetas, L=6, num_trash=2, init_state=None, measurement=True,vqe=False): # QAE ansatz QAE_circ = QAEAnsatz(num_qubits = L, num_trash_qubits= num_trash, trash_qubits_idxs = list(range(L//2-1,L//2-1+num_trash)), measure_trash=measurement).assign_parameters(thetas) # initialize state vector initcirc = QuantumCircuit(QuantumRegister(L,"q"),ClassicalRegister(num_trash, 'c')) if init_state != None: initcirc.set_matrix_product_state(qiskit_state(init_state)) # compose circuits fullcirc = initcirc.compose(QAE_circ) return fullcirc ### Execute circuit count = 0 def run_circuit(thetas, L, num_trash, init_state, vqe=False, shots=100, meas_fitter = None): #global count #count += 1 #print(count, "thetas: ", thetas) #print(L, num_trash) circ = prepare_circuit(thetas, L, num_trash, init_state, vqe=vqe) #circ.draw("mpl") #tcirc = qiskit.transpile(circ, backend) # Execute the circuit job_sim = backend.run(circ, shots=shots, seed_simulator=333, seed_transpiler=444) #fix seed to make it reproducible result = job_sim.result() # Results without mitigation counts = result.get_counts() if meas_fitter != None: # Get the filter object meas_filter = meas_fitter.filter # Results with mitigation mitigated_results = meas_filter.apply(result) counts = mitigated_results.get_counts(0) return counts def count_ones(string): return np.sum([int(_) for _ in string]) ### Optimize circuit def cost_function_single(thetas, L, num_trash, init_state, shots=1000, vqe=True, param_encoding=False, x=0, meas_fitter=None): """ Optimizes circuit """ if param_encoding: thetas = feature_encoding(thetas, x) out = run_circuit(thetas, L, num_trash, init_state, vqe=vqe, shots=shots, meas_fitter=meas_fitter) cost = np.sum([out[_]*count_ones(_) for _ in out if _ != "0" * num_trash]) # all measurement results except "000" return cost/shots def cost_function(thetas, L, num_trash, init_states, shots=1000, vqe=True, param_encoding=False, x=0, meas_fitter=None): """ Optimizes circuit """ cost = 0. for init_state in init_states: cost += cost_function_single(thetas, L, num_trash, init_state, shots, vqe, param_encoding, meas_fitter=meas_fitter) return cost/len(init_states) def optimize(init_states, L=6, num_trash=2, thetas=None, shots=1000, max_iter=400, vqe=True, param_encoding=False, x=0, pick_optimizer = None, meas_fitter=None): if thetas is None: n_params = (num_trash*L+num_trasg)*2 if param_encoding else (num_trash*L+num_trash) thetas = np.random.uniform(0, 2*np.pi, n_params) # initial parameters without feature encoding #print("Initial cost: {:.3f}".format(cost_function(thetas, L, num_trash, init_states, shots, vqe, param_encoding, x))) counts, values, accepted = [], [], [] def store_intermediate_result(eval_count, parameters, mean, std, ac): # counts.append(eval_count) values.append(mean) accepted.append(ac) # Initialize optimizer if pick_optimizer == "cobyla": optimizer = COBYLA(maxiter=max_iter, tol=0.0001) if pick_optimizer == "adam" or pick_optimizer == "ADAM": optimizer = qiskit.algorithms.optimizers.ADAM(maxiter=max_iter) # optimizer = L_BFGS_B(maxfun=300, maxiter=max_iter)#, factr=10, iprint=- 1, epsilon=1e-08) if pick_optimizer == "spsa" or pick_optimizer == None: optimizer = SPSA(maxiter=max_iter, #blocking=True, callback=store_intermediate_result, #learning_rate=0.3, #perturbation=0.1 ) # recommended from qiskit (first iteraction takes quite long) # to reduce time figure out optimal learning rate and perturbation in advance start_time = time.time() ret = optimizer.optimize( num_vars=len(thetas), objective_function=(lambda thetas: cost_function(thetas, L, num_trash, init_states, shots, vqe, param_encoding, x, meas_fitter=meas_fitter)), initial_point=thetas ) print("Time: {:.5f} sec".format(time.time()-start_time)) print(ret) return ret[0], values, accepted Ls = [12,12,12,12] # [3,4,8,10,12,14,16,20, 32, 32, 32] max_iter = [400] * len(Ls) num_trashs = np.log(Ls)/np.log(2) num_trashs = np.array(num_trashs, dtype="int") losses = [None] * len(Ls); accepted = [None] * len(Ls); thetas_opt= [None] * len(Ls) times = [None] * len(Ls) for j,L in enumerate(Ls): L = Ls[j] num_trash = num_trashs[j] # BH V = 1 deltat=-1 chi = 100 g=0.05 # ordered phase to make things a bit more interesting print(f"bond dimension {chi}, max_iter {max_iter[j]}, L {L}, num_trash {num_trash}") t_list = np.ones(L-1) for i in range(len(t_list)): t_list[i] -= deltat*(-1)**i #E0, psi0 = DMRG_EBH(L, V, t_list, chi_max=chi, bc_MPS='finite') E0, psi0 = DMRG_Ising(L, J, g, chi_max=chi, bc_MPS='finite') SZ = psi0.expectation_value("Sigmaz") print(f"Psi magnetization: {SZ}") # note that in tenpy Sz and Sx roles are reversed, i.e. in tenpy its -SxSx - g Sz t0 = time.time() thetas_opt[j], losses[j], accepted[j] = optimize([psi0], max_iter=max_iter[j], L=L, num_trash=num_trash, meas_fitter=None) #, pick_optimizer="adam") times[j] = time.time() - t0 loss_final = cost_function_single(thetas_opt[j], L, num_trash, psi0, shots=1000) print(f"opt loss = {loss_final}, min loss = {np.min(losses[j])}, computation time = {times[j]} sec") print(f"losses vs steps: ", losses[j]) # to save computation time, dont save intermediate results and just compute the loss in the end np.savez(filename + "_results", thetas_opt=thetas_opt, losses=losses, accepted=accepted,Ls=Ls, max_iter=max_iter, times=times)
https://github.com/Qottmann/Quantum-anomaly-detection
Qottmann
import time import itertools import numpy as np import qiskit from qiskit import * from qiskit.quantum_info import Statevector from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B, SPSA from qiskit.opflow.state_fns import StateFn, CircuitStateFn from qiskit.providers.aer import StatevectorSimulator, AerSimulator from qiskit.opflow import CircuitSampler from qiskit.ignis.mitigation.measurement import CompleteMeasFitter # you will need to pip install qiskit-ignis from qiskit.ignis.mitigation.measurement import complete_meas_cal import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator from matplotlib.colors import BoundaryNorm cmap = plt.get_cmap("plasma") #'viridis' from modules.utils import * from qae import * import datetime print(qiskit.__version__, np.__version__) #plt.rc('text', usetex=True) plt.rc('font', family='serif',size=16) #plt.rc('font', family='serif') temp = np.load("data/QAEAnsatz_scaling_losses.npz", allow_pickle=True) losses0 = temp["losses"] Ls = temp["Ls"] # It took 51 hrs to obtain these results. # However, you can confirm the validity by just executing the circuit once for the optimized parameters (as demonstrated down below) temp2 = np.load("data/QAEAnsatz_scaling_MPS_script_L-32_tracked-losses_results.npz",allow_pickle=True) losses32 = temp2["losses"] Ls = list(Ls) Ls += [32] Ls fig, ax = plt.subplots(figsize=(6,5)) for i in range(4): ax.plot(np.array(losses0[i]),label=f"L = {Ls[i]}") ax.plot(losses32[1],label=f"L = {Ls[-1]}") ax.legend() left, bottom, width, height = [0.4,0.61, 0.25, 0.325] ax2 = fig.add_axes([left, bottom, width, height]) for i in range(4): ax2.plot(np.array(losses0[i]),label=f"L = {Ls[i]}") ax2.plot(losses32[1],label=f"L = {Ls[-1]}") ax2.set_yscale("log") #ax.set_xlim(0,405) #ax.set_yscale("log") ax.set_ylabel("cost", fontsize=16) ax.set_xlabel("iteration", fontsize=16) plt.tight_layout() plt.savefig("plots/QAEAnsatz_Ising-scaling.pdf") plt.savefig("plots/QAEAnsatz_Ising-scaling.png") #IBMQ.load_account() # this then automatically loads your saved account #provider = IBMQ.get_provider(hub='ibm-q-research') #device = provider.backend.ibmq_rome # 6 bogota ; 4 rome ### Real device execution: #backend = device ### Simulation with noise profile from real device #backend = qiskit.providers.aer.AerSimulator.from_backend(device) ### Simulation without noise backend = qiskit.providers.aer.AerSimulator() #backend = StatevectorSimulator() ### Preliminaries L = 5 num_trash = 2 anti = 1 # 1 for ferromagnetic Ising model, -1 for antiferromagnet filename = "data/QAEAnsatz_scaling" gz = 0 gx = 0.3 ED_state, ED_E, ham = ising_groundstate(L, anti, np.float32(gx), np.float32(gz)) Sen = ED_E Smag = ED_state.T.conj()@Mag(L,anti)@ED_state def prepare_circuit(thetas, L=6, num_trash=2, init_state=None, measurement=True,vqe=False): # QAE ansatz QAE_circ = QAEAnsatz(num_qubits = L, num_trash_qubits= num_trash, trash_qubits_idxs = list(range(num_trash)), measure_trash=measurement).assign_parameters(thetas) # initialize state vector initcirc = QuantumCircuit(QuantumRegister(L,"q"),ClassicalRegister(num_trash, 'c')) initcirc.initialize(init_state, initcirc.qubits) # compose circuits fullcirc = initcirc.compose(QAE_circ) return fullcirc circ = prepare_circuit(thetas = np.random.rand(2*L+2), L = L, init_state = ED_state) circ.draw("mpl") ### Execute circuit count = 0 def run_circuit(thetas, L, num_trash, init_state, vqe=False, shots=100, meas_fitter = None): #global count #count += 1 #print(count, "thetas: ", thetas) circ = prepare_circuit(thetas, L, num_trash, init_state, vqe=vqe) tcirc = qiskit.transpile(circ, backend) # Execute the circuit job_sim = backend.run(tcirc, shots=shots,seed_simulator=333, seed_transpiler=444) # , seed_simulator=123, seed_transpiler=234 fix seed to make it reproducible result = job_sim.result() # Results without mitigation counts = result.get_counts() if meas_fitter != None: # Get the filter object meas_filter = meas_fitter.filter # Results with mitigation mitigated_results = meas_filter.apply(result) counts = mitigated_results.get_counts(0) return counts res = run_circuit(thetas = np.random.rand(num_trash*L+num_trash), L = L, num_trash = num_trash, init_state = ED_state, shots=1000) res def count_ones(string): return np.sum([int(_) for _ in string]) count_ones("01010111") [_ for _ in res] [_ for _ in res if _ != "0" * num_trash] np.sum([res[_]*count_ones(_) for _ in res if _ != "0" * num_trash]) # all measurement results except "000" ### Optimize circuit def cost_function_single(thetas, L, num_trash, init_state, shots=1000, vqe=True, param_encoding=False, x=0, meas_fitter=None): """ Optimizes circuit """ if param_encoding: thetas = feature_encoding(thetas, x) out = run_circuit(thetas, L, num_trash, init_state, vqe=vqe, shots=shots, meas_fitter=meas_fitter) cost = np.sum([out[_]*count_ones(_) for _ in out if _ != "0" * num_trash]) # all measurement results except "000" return cost/shots def cost_function(thetas, L, num_trash, init_states, shots=1000, vqe=True, param_encoding=False, x=0, meas_fitter=None): """ Optimizes circuit """ cost = 0. for init_state in init_states: cost += cost_function_single(thetas, L, num_trash, init_state, shots, vqe, param_encoding, meas_fitter=meas_fitter) return cost/len(init_states) def optimize(init_states, L=6, num_trash=2, thetas=None, shots=1000, max_iter=400, vqe=True, param_encoding=False, x=0, pick_optimizer = None, meas_fitter=None): if thetas is None: n_params = (num_trash*L+num_trasg)*2 if param_encoding else (num_trash*L+num_trash) thetas = np.random.uniform(0, 2*np.pi, n_params) # initial parameters without feature encoding #print("Initial cost: {:.3f}".format(cost_function(thetas, L, num_trash, init_states, shots, vqe, param_encoding, x))) counts, values, accepted = [], [], [] def store_intermediate_result(eval_count, parameters, mean, std, ac): # counts.append(eval_count) values.append(mean) accepted.append(ac) # Initialize optimizer if pick_optimizer == "cobyla": optimizer = COBYLA(maxiter=max_iter, tol=0.0001) if pick_optimizer == "adam" or pick_optimizer == "ADAM": optimizer = qiskit.algorithms.optimizers.ADAM(maxiter=max_iter) # optimizer = L_BFGS_B(maxfun=300, maxiter=max_iter)#, factr=10, iprint=- 1, epsilon=1e-08) if pick_optimizer == "spsa" or pick_optimizer == None: optimizer = SPSA(maxiter=max_iter, #blocking=True, callback=store_intermediate_result, #learning_rate=0.3, #perturbation=0.1 ) # recommended from qiskit (first iteraction takes quite long) # to reduce time figure out optimal learning rate and perturbation in advance start_time = time.time() ret = optimizer.optimize( num_vars=len(thetas), objective_function=(lambda thetas: cost_function(thetas, L, num_trash, init_states, shots, vqe, param_encoding, x, meas_fitter=meas_fitter)), initial_point=thetas ) print("Time: {:.5f} sec".format(time.time()-start_time)) print(ret) return ret[0], values, accepted thetas_opt_mitigated, losses, accepted = optimize([ED_state], max_iter=120, L=5, meas_fitter=None) #, pick_optimizer="adam") plt.plot(losses) Ls = [3,4,8,16] #note that L=16 may take up few hours, it is faster with MPS further below max_iter = [400] * len(Ls) num_trashs = np.log(Ls)/np.log(2) num_trashs = np.array(num_trashs, dtype="int") gz = 0 gx = 0.3 losses = [None] * len(Ls); accepted = [None] * len(Ls); thetas_opt= [None] * len(Ls) # may have to re-run some sizes when it gets stuck in local minima for j,(L,num_trash) in enumerate(zip(Ls,num_trashs)): print(L,num_trash) ED_state, ED_E, ham = ising_groundstate(L, anti, np.float32(gx), np.float32(gz)) thetas_opt[j], losses[j], accepted[j] = optimize([ED_state], max_iter=max_iter[j], L=L, num_trash=num_trash, meas_fitter=None) #, pick_optimizer="adam") plt.plot(losses[j]) plt.show() np.savez(filename + "_losses", losses=losses, thetas_opt = thetas_opt, Ls=Ls, max_iter=max_iter, num_trashs=num_trashs) temp = np.load(filename + "_losses.npz", allow_pickle=True) losses0 = temp["losses"] fig, ax = plt.subplots(figsize=(6,5)) for i in range(4): ax.plot(np.array(losses0[i]) + 1e-4,label=f"L = {Ls[i]}") ax.legend() ax.set_xlim(0,400) ax.set_yscale("log") ax.set_yticks([1,1e-1,1e-2,1e-3,1e-4]) ax.set_yticklabels(["$10^{}$".format(i) for i in range(4)] + ["0.0"]) ax.set_ylabel("cost", fontsize=16) ax.set_xlabel("iterations", fontsize=16) min_losses = [np.min(l) for l in losses0] min_losses fig, ax = plt.subplots(figsize=(6,5)) ax.plot(Ls, min_losses,"x--") #ax.set_yscale("log") #ax.set_xscale("log") def DMRG_Ising(L, J, g, chi_max=30, bc_MPS='finite'): print("finite DMRG, transverse field Ising model") print("L={L:d}, g={g:.2f}".format(L=L, g=g)) model_params = dict(L=L, J=J, g=g, bc_MPS=bc_MPS, conserve=None) M = TFIChain(model_params) product_state = ["up"] * M.lat.N_sites psi = MPS.from_product_state(M.lat.mps_sites(), product_state, bc=M.lat.bc_MPS) dmrg_params = { 'mixer': None, # setting this to True helps to escape local minima 'max_E_err': 1.e-10, 'trunc_params': { 'chi_max': chi_max, 'svd_min': 1.e-10 }, 'combine': True } info = dmrg.run(psi, M, dmrg_params) # the main work... E = info['E'] print("E = {E:.13f}".format(E=E)) print("final bond dimensions: ", psi.chi) mag_x = np.sum(psi.expectation_value("Sigmax")) mag_z = np.sum(psi.expectation_value("Sigmaz")) print("magnetization in X = {mag_x:.5f}".format(mag_x=mag_x)) print("magnetization in Z = {mag_z:.5f}".format(mag_z=mag_z)) #if L < 20: # compare to exact result # from tfi_exact import finite_gs_energy # E_exact = finite_gs_energy(L, 1., g) # print("Exact diagonalization: E = {E:.13f}".format(E=E_exact)) # print("relative error: ", abs((E - E_exact) / E_exact)) return E, psi #, M ### Preliminaries qiskit_chi = 100 L = 8 num_trash = int(np.log(L)/np.log(2)) anti = 1 # 1 for ferromagnetic Ising model, -1 for antiferromagnet g = 0.05 J=anti filename = "data/QAEAnsatz_scaling_MPS_script_L-32_tracked-losses" backend = qiskit.providers.aer.AerSimulator(method="matrix_product_state", precision="single", matrix_product_state_max_bond_dimension = qiskit_chi, matrix_product_state_truncation_threshold = 1e-10, #mps_sample_measure_algorithm = "mps_apply_measure", #alt: "mps_probabilities" ) from qiskit.utils import algorithm_globals algorithm_globals.random_seed = 333 def qiskit_state(psi0): # G is only the local tensor (not multiplied by any singular values) - see https://tenpy.readthedocs.io/en/latest/reference/tenpy.networks.mps.html A_list = [psi0.get_B(i, form="G").to_ndarray().transpose([1,0,2]) for i in range(L)] for i,A in enumerate(A_list): A_list[i] = (A[0], A[1]) S_list = [psi0.get_SR(i) for i in range(L-1)] # skip trivial last bond; hast to be of size L-1 return (A_list, S_list) def prepare_circuit(thetas, L=6, num_trash=2, init_state=None, measurement=True,vqe=False): # QAE ansatz QAE_circ = QAEAnsatz(num_qubits = L, num_trash_qubits= num_trash, trash_qubits_idxs = list(range(L//2-1,L//2-1+num_trash)), measure_trash=measurement).assign_parameters(thetas) # initialize state vector initcirc = QuantumCircuit(QuantumRegister(L,"q"),ClassicalRegister(num_trash, 'c')) if init_state != None: initcirc.set_matrix_product_state(qiskit_state(init_state)) # compose circuits fullcirc = initcirc.compose(QAE_circ) return fullcirc ### Execute circuit count = 0 def run_circuit(thetas, L, num_trash, init_state, vqe=False, shots=100, meas_fitter = None): #global count #count += 1 #print(count, "thetas: ", thetas) #print(L, num_trash) circ = prepare_circuit(thetas, L, num_trash, init_state, vqe=vqe) #circ.draw("mpl") #tcirc = qiskit.transpile(circ, backend) # Execute the circuit job_sim = backend.run(circ, shots=shots, seed_simulator=333, seed_transpiler=444) #fix seed to make it reproducible result = job_sim.result() # Results without mitigation counts = result.get_counts() if meas_fitter != None: # Get the filter object meas_filter = meas_fitter.filter # Results with mitigation mitigated_results = meas_filter.apply(result) counts = mitigated_results.get_counts(0) return counts def count_ones(string): return np.sum([int(_) for _ in string]) ### Optimize circuit def cost_function_single(thetas, L, num_trash, init_state, shots=1000, vqe=True, param_encoding=False, x=0, meas_fitter=None): """ Optimizes circuit """ if param_encoding: thetas = feature_encoding(thetas, x) out = run_circuit(thetas, L, num_trash, init_state, vqe=vqe, shots=shots, meas_fitter=meas_fitter) cost = np.sum([out[_]*count_ones(_) for _ in out if _ != "0" * num_trash]) # all measurement results except "000" return cost/shots def cost_function(thetas, L, num_trash, init_states, shots=1000, vqe=True, param_encoding=False, x=0, meas_fitter=None): """ Optimizes circuit """ cost = 0. for init_state in init_states: cost += cost_function_single(thetas, L, num_trash, init_state, shots, vqe, param_encoding, meas_fitter=meas_fitter) return cost/len(init_states) def optimize(init_states, L=6, num_trash=2, thetas=None, shots=1000, max_iter=400, vqe=True, param_encoding=False, x=0, pick_optimizer = None, meas_fitter=None): if thetas is None: n_params = (num_trash*L+num_trasg)*2 if param_encoding else (num_trash*L+num_trash) thetas = np.random.uniform(0, 2*np.pi, n_params) # initial parameters without feature encoding #print("Initial cost: {:.3f}".format(cost_function(thetas, L, num_trash, init_states, shots, vqe, param_encoding, x))) counts, values, accepted = [], [], [] def store_intermediate_result(eval_count, parameters, mean, std, ac): # counts.append(eval_count) values.append(mean) accepted.append(ac) # Initialize optimizer if pick_optimizer == "cobyla": optimizer = COBYLA(maxiter=max_iter, tol=0.0001) if pick_optimizer == "adam" or pick_optimizer == "ADAM": optimizer = qiskit.algorithms.optimizers.ADAM(maxiter=max_iter) # optimizer = L_BFGS_B(maxfun=300, maxiter=max_iter)#, factr=10, iprint=- 1, epsilon=1e-08) if pick_optimizer == "spsa" or pick_optimizer == None: optimizer = SPSA(maxiter=max_iter, #blocking=True, callback=store_intermediate_result, #learning_rate=0.3, #perturbation=0.1 ) # recommended from qiskit (first iteraction takes quite long) # to reduce time figure out optimal learning rate and perturbation in advance start_time = time.time() ret = optimizer.optimize( num_vars=len(thetas), objective_function=(lambda thetas: cost_function(thetas, L, num_trash, init_states, shots, vqe, param_encoding, x, meas_fitter=meas_fitter)), initial_point=thetas ) print("Time: {:.5f} sec".format(time.time()-start_time)) print(ret) return ret[0], values, accepted temp2 = np.load("data/QAEAnsatz_scaling/QAEAnsatz_scaling_MPS_script_L-32_results.npz",allow_pickle=True) # 500 iterations, gx = 0.3, chi=100 (but resulting bond dimension of state much smaller) psi0 = temp2["psi0"].item() thetas_opt = temp2["thetas_opt"][0] L = psi0.L loss_final = cost_function_single(thetas_opt, L, int(np.log(L)/np.log(2)), psi0, shots=1000) print(f"Result for L = {L}: loss_opt = {loss_final} with optimal parameters {thetas_opt}") temp2 = np.load("data/QAEAnsatz_scaling_MPS_script_L-32_tracked-losses_results.npz",allow_pickle=True) # 500 iterations, gx = 0.3, chi=100 (but resulting bond dimension of state much smaller) psi0 = temp2["psis"][1] thetas_opt = temp2["thetas_opt"][1] L = psi0.L loss_final = cost_function_single(thetas_opt, L, int(np.log(L)/np.log(2)), psi0, shots=1000) print(f"Result for L = {L}: loss_opt = {loss_final} with optimal parameters {thetas_opt}")
https://github.com/Qottmann/Quantum-anomaly-detection
Qottmann
import sys sys.path.insert(1, '..') # sets the import path to the parent folder import time import datetime import numpy as np from matplotlib import pyplot as plt import qiskit from qiskit import * from qiskit.opflow import X,Z,I from qiskit.opflow.state_fns import StateFn, CircuitStateFn from qiskit.providers.aer import StatevectorSimulator, AerSimulator from qiskit.algorithms import VQE from qiskit.algorithms.optimizers import COBYLA, SLSQP, SPSA from qiskit.opflow import CircuitSampler from qiskit.ignis.mitigation.measurement import CompleteMeasFitter # you will need to pip install qiskit-ignis from qiskit.ignis.mitigation.measurement import complete_meas_cal from scipy import sparse import scipy.sparse.linalg.eigen.arpack as arp from modules.utils import * anti = -1 L = 5 num_trash = 2 name = "ibmq_antiferro-1D-load_bogota-no-optimize" # remove test at the end when running on a real device filename = "data/noisy_VQE_maxiter-500_Ising_L5_anti_-1_20" #"data/noisy_VQE_maxiter-100_Ising_L5_anti_-1_20_recycle" print("filename: ", filename, "notebook name: ", name) # where to get the simulated thetas values from? needs to contain a thetas_mitigated array filename_simulated_thetas = 'data/ibmq_antiferro-1D-load_simu_thetas-loss-cost_run2.npz' load = False recompute = False # whether or not to recompute Magnetization, makes sense on device IBMQ.load_account() # this then automatically loads your saved account provider = IBMQ.get_provider(hub='ibm-q-research') device = provider.backend.ibmq_bogota print(device) backend = device #backend = qiskit.providers.aer.AerSimulator.from_backend(device) coupling_map = device.configuration().coupling_map noise_model = qiskit.providers.aer.noise.NoiseModel.from_backend(device) basis_gates = noise_model.basis_gates #aqua_globals.random_seed = seed qi = qiskit.utils.QuantumInstance(backend=backend, # , seed_simulator=seed, seed_transpiler=seed coupling_map=coupling_map, # noise_model=noise_model, measurement_error_mitigation_cls= CompleteMeasFitter, cals_matrix_refresh_period=30 #How often to refresh the calibration matrix in measurement mitigation. in minutes ) basis_gates # Very important, at the moment poorly coded so it needs to come back to this instance all the time ansatz = qiskit.circuit.library.TwoLocal(L,rotation_blocks="ry", entanglement_blocks='cz', entanglement="sca", reps=1) ansatz.draw("mpl") ansatz = qiskit.transpile(ansatz, backend) ansatz.draw("mpl") L = 5 num_trash = 2 anti = -1 VQE_params = np.load(filename + ".npz", allow_pickle=True) pick = np.arange(0,len(VQE_params['gx_list']),3) gx_list = VQE_params['gx_list'][pick] gz_list = VQE_params['gz_list'][pick] opt_params = VQE_params['opt_params'][pick] Qmags = VQE_params["Qmag"][pick] Qen = VQE_params["Qen"][pick] Sen = VQE_params["Sen"][pick] Smags = VQE_params["Smag"][pick] gx_vals = np.unique(gx_list) gz_vals = np.unique(gz_list) if load: temp = np.load("data/" + name + "executed_mags-Es.npz",allow_pickle=True) Qmags = temp["Qmags"] Qen = temp["Qen"] Sen = temp["Sen"] Smags = temp["Smags"] verbose=1 if recompute: mag = QMag(L,anti) #magnetization operator (Qiskit) Smag = Mag(L,anti) #magnetization operator (numpy) Qen_executed=np.zeros(len(opt_params), dtype="complex") Qmags_executed=np.zeros(len(opt_params), dtype="complex") for j in range(len(opt_params)): t0 = datetime.datetime.now() gx = gx_list[j] gz = gz_list[j] H = QHIsing(L, anti, np.float32(gx), np.float32(gz)) # build Hamiltonian Op state = ansatz.assign_parameters(opt_params[j]) meas_outcome = ~StateFn(mag) @ StateFn(state) Qmags_executed[j] = CircuitSampler(qi).convert(meas_outcome).eval() #https://quantumcomputing.stackexchange.com/questions/12080/evaluating-expectation-values-of-operators-in-qiskit #e_outcome = ~StateFn(H) @ StateFn(state) #Qen_executed[j] = CircuitSampler(qi).convert(e_outcome).eval() init_state, E, ham = ising_groundstate(L, anti, np.float64(gx), np.float64(gz)) Sen[j] = E Smags[j] = init_state.T.conj()@Smag@init_state #Magnetization with Numpy results print(f"{j+1} / {len(opt_params)}, gx = {gx:.2f}, gz = {gz:.2f}, time : {(datetime.datetime.now() - t0)}") np.savez("data/" + name + "executed_mags-Es.npz",Qmags=Qmags_executed, Qen=Qen_executed, Sen=Sen, Smags=Smags) # for large parameter space takes quite a while because of the exact diagonalization fig, axs = plt.subplots(ncols=2, figsize=(10,5)) ax = axs[0] ax.plot(gx_list, Qmags,"x--", label="noisy VQE simu") ax.plot(gx_list, Smags,"x--", label="ED") ax.set_xscale("log") if recompute: ax.plot(gx_list, Qmags_executed,"x--", label="IBMQ") ax.legend() ############################################################################## ### II - Training ########################################################### ############################################################################## # linear entangler (as in scales linearly with trash qubits) def get_entangler_map(L, num_trash, i_permut=1, nums_trash=[1,2]): result = [] nums_compressed = list(range(L)) for trashqubit in nums_trash: nums_compressed.remove(trashqubit) if nums_trash == None: #old way nums_compressed = list(range(L))[:L-num_trash] nums_trash = list(range(L))[-num_trash:] #print(nums, nums_compressed, nums_trash) # combine all trash qubits with themselves for trash_q in nums_trash[:-1]: result.append((trash_q+1,trash_q)) # combine each of the trash qubits with every n-th repeated = list(nums_trash) * (L-num_trash) # repeat the list of trash indices cyclicly for i in range(L-num_trash): result.append((repeated[i_permut + i], nums_compressed[i])) return result def QAE_Ansatz(thetas, L, num_trash, insert_barriers=False, parametrized_gate = "ry", entangling_gate = "cz", nums_trash = [1,2]): entanglement = [get_entangler_map(L,num_trash,i_permut) for i_permut in range(num_trash)] if nums_trash == None: nums_trash = list(range(L))[-num_trash:] circ = qiskit.circuit.library.TwoLocal(L, parametrized_gate, entangling_gate, entanglement, reps=num_trash, insert_barriers=insert_barriers, skip_final_rotation_layer=True ).assign_parameters(thetas[:-num_trash]) if insert_barriers: circ.barrier() for i in nums_trash: circ.ry(thetas[i], i) #circ.ry(circuit.Parameter(f'θ{i}'), L-i-1) return circ def prepare_circuit(thetas, L=6, num_trash=2, init_state=None, measurement=True, vqe=True): qreg = QuantumRegister(L, 'q') creg = ClassicalRegister(num_trash, 'c') circ = QuantumCircuit(qreg, creg) circ += QAE_Ansatz(thetas, L, num_trash, insert_barriers=False)#.assign_parameters(thetas) # difference to bind? if measurement: for i in range(num_trash): circ.measure(qreg[L-i-1], creg[i]) if init_state is not None: if vqe: circ = ansatz.assign_parameters(init_state) + circ # needs to have ansatz defined somewhere in the script else: circ.initialize(init_state, qreg) return circ def feature_encoding(thetas, x): """ thetas: parameters to be optimized, x: Ising model parameter (eg. field) """ new_thetas = [] thetas = thetas.reshape((-1,2)) for theta in thetas: new_thetas.append(theta[0] * x + theta[1]) return new_thetas def calibrate_circuit(L, num_trash,shots=1000): qreg = QuantumRegister(L, 'q') # obtain calibration matrix qubit_list = [L-i-1 for i in range(num_trash)] # only need to calibrate the trash qubits circlabel = f'mcal_{datetime.datetime.now()}' meas_calibs, state_labels = complete_meas_cal(qubit_list=qubit_list, qr=qreg, circlabel=circlabel) cal_job = backend.run(meas_calibs, shots=shots) #, noise_model=noise_model cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel=circlabel) print(circlabel, meas_fitter.cal_matrix) return meas_fitter def run_circuit(thetas, L, num_trash, init_state, vqe=True, shots=100, meas_fitter = None): circ = prepare_circuit(thetas, L, num_trash, init_state, vqe=vqe) tcirc = qiskit.transpile(circ, backend) # Execute the circuit job_sim = backend.run(tcirc, shots=shots) # , seed_simulator=123, seed_transpiler=234 fix seed to make it reproducible result = job_sim.result() # Results without mitigation counts = result.get_counts() if meas_fitter != None: # Get the filter object meas_filter = meas_fitter.filter # Results with mitigation mitigated_results = meas_filter.apply(result) counts = mitigated_results.get_counts(0) return counts meas_fitter = calibrate_circuit(L, num_trash) phis = opt_params # translate to Rikes naming gxs = gx_list gzs = gz_list def cost_function_single(thetas, L, num_trash, p, shots=1000, vqe=True, param_encoding=False, x=0, meas_fitter=None): """ Optimizes circuit """ if vqe: init_state = phis[p] else: J, gx, gz = p init_state, _ = ising_groundstate(L, J, gx, gz) if param_encoding: thetas = feature_encoding(thetas, x) out = run_circuit(thetas, L, num_trash, init_state, vqe=vqe, shots=shots, meas_fitter=meas_fitter) cost = out.get('11', 0)*2 + out.get('01', 0) + out.get('10', 0) return cost/shots def cost_function(thetas, L, num_trash, ising_params, shots=1000, vqe=True, param_encoding=False, x=0, meas_fitter=None): """ Optimizes circuit """ cost = 0. n_samples = len(ising_params) for i, p in enumerate(ising_params): if param_encoding: cost += cost_function_single(thetas, L, num_trash, p, shots, vqe, param_encoding, x[i], meas_fitter=meas_fitter) else: cost += cost_function_single(thetas, L, num_trash, p, shots, vqe, param_encoding, meas_fitter=meas_fitter) return cost/n_samples def optimize(ising_params, L=6, num_trash=2, thetas=None, shots=1000, max_iter=400, vqe=True, param_encoding=False, x=0, pick_optimizer = None, meas_fitter=None): if thetas is None: n_params = (2*L+2)*2 if param_encoding else (2*L+2) thetas = np.random.uniform(0, 2*np.pi, n_params) # initial parameters without feature encoding print("Initial cost: {:.3f}".format(cost_function(thetas, L, num_trash, ising_params, shots, vqe, param_encoding, x))) counts, values, accepted = [], [], [] def store_intermediate_result(eval_count, parameters, mean, std, ac): # counts.append(eval_count) values.append(mean) accepted.append(ac) # Initialize optimizer if pick_optimizer == "cobyla": optimizer = COBYLA(maxiter=max_iter, tol=0.0001) if pick_optimizer == "adam" or pick_optimizer == "ADAM": optimizer = qiskit.algorithms.optimizers.ADAM(maxiter=max_iter) # optimizer = L_BFGS_B(maxfun=300, maxiter=max_iter)#, factr=10, iprint=- 1, epsilon=1e-08) if pick_optimizer == "spsa" or pick_optimizer == None: optimizer = SPSA(maxiter=max_iter, #blocking=True, callback=store_intermediate_result, learning_rate=0.3, perturbation=0.1 ) # recommended from qiskit (first iteraction takes quite long) # to reduce time figure out optimal learning rate and perturbation in advance start_time = time.time() ret = optimizer.optimize( num_vars=len(thetas), objective_function=(lambda thetas: cost_function(thetas, L, num_trash, ising_params, shots, vqe, param_encoding, x, meas_fitter=meas_fitter)), initial_point=thetas ) print("Time: {:.5f} sec".format(time.time()-start_time)) print(ret) return ret[0], values, accepted def run_inference(thetas, shots=1000, L=5, meas_fitter=None): points = 50 J = -1.0 x,y = np.meshgrid(gx_vals, gz_vals) cost = np.zeros((len(gx_vals) * len(gz_vals))) Smags = np.zeros((len(gx_vals) * len(gz_vals))) shots = 1000 for i,p in enumerate(list(zip(gxs, gzs))): t0 = datetime.datetime.now() cost[i] = cost_function_single(thetas, L, num_trash, i, shots=shots, meas_fitter=meas_fitter) if not i%verbose: print(f"{i+1} / {len(opt_params)}, gx = {gx:.2f}, gz = {gz:.2f}, time : {verbose*(datetime.datetime.now() - t0)}") cost = cost.reshape((len(gx_vals), len(gz_vals))) return cost phys_params = [-1] thetas_opt_raw = np.load(filename_simulated_thetas, allow_pickle=True)["thetas_mitigated"] # Inference cost_raw = np.zeros((len(gx_vals))) shots = 1000 for i,p in enumerate(list(zip(gxs, gzs))): t0 = datetime.datetime.now() cost_raw[i] = cost_function_single(thetas_opt_raw, L, num_trash, i, shots=shots, meas_fitter=None) # np.random.uniform(0, 2*np.pi, 2*L+2) random parameters to check if training "does" something - result was: with random paremters just get noise, so yes, it "does" something if not i%verbose: print(f"{i+1} / {len(opt_params)}, gx = {p[0]:.2f}, gz = {p[1]:.2f}, time : {verbose*(datetime.datetime.now() - t0)}") thetas_opt_raw = thetas_opt_mitigated.copy() cost_raw = cost_mitigated.copy() thetas_opt_mitigated = np.load(filename_simulated_thetas, allow_pickle=True)["thetas_mitigated"] # Inference cost_mitigated = np.zeros((len(gx_vals))) shots = 1000 for i,p in enumerate(list(zip(gxs, gzs))): t0 = datetime.datetime.now() cost_mitigated[i] = cost_function_single(thetas_opt_mitigated, L, num_trash, i, shots=shots, meas_fitter=meas_fitter) # np.random.uniform(0, 2*np.pi, 2*L+2) random parameters to check if training "does" something - result was: with random paremters just get noise, so yes, it "does" something if not i%verbose: print(f"{i+1} / {len(opt_params)}, gx = {p[0]:.2f}, gz = {p[1]:.2f}, time : {verbose*(datetime.datetime.now() - t0)}") np.savez("data/" + name + "_thetas-loss-cost_run2", cost_mitigated=cost_mitigated, thetas_mitigated=thetas_opt_mitigated, cost_raw=cost_raw, thetas_raw=thetas_opt_raw, ) fig, axs = plt.subplots(ncols=2,figsize=(12,5)) ax = axs[0] ax.set_title("Raw results") cost = np.load("data/" + name + "_thetas-loss-cost_run2.npz", allow_pickle=True)["cost_raw"] ax.plot(gx_list, cost,".:", label="raw output") ax.plot(gx_list, Qmags,"x--", color="tab:orange", label="Qmag") ax.set_xscale("log") for p in phys_params: ax.plot(gx_list[p],cost[p],"o",alpha=0.3,color="magenta") ax = axs[1] ax.set_title("Mitigated results") cost = np.load("data/" + name + "_thetas-loss-cost_run2.npz", allow_pickle=True)["cost_mitigated"] ax.plot(gx_list, cost,".:", label="raw output") ax.plot(gx_list, Qmags,"x--", color="tab:orange", label="Qmag") ax.set_xscale("log") for p in phys_params: ax.plot(gx_list[p],cost[p],"o",alpha=0.3,color="magenta") fig, ax = plt.subplots(ncols=1,figsize=(6,5)) ax.set_title("Mitigated results") cost = np.load("data/" + name + "_thetas-loss-cost_run2.npz", allow_pickle=True)["cost_raw"] ax.plot(gx_list, cost,".:", label="raw output") ax.plot(gx_list, abs(Qmags),"x--", color="tab:orange", label="Qmag") ax.set_xscale("log") for p in phys_params: ax.plot(gx_list[p],cost[p],"o",alpha=0.3,color="magenta")
https://github.com/Qottmann/Quantum-anomaly-detection
Qottmann
import time import datetime import numpy as np from matplotlib import pyplot as plt import qiskit from qiskit import * from qiskit.opflow import X,Z,I from qiskit.opflow.state_fns import StateFn, CircuitStateFn from qiskit.providers.aer import StatevectorSimulator, AerSimulator from qiskit.algorithms import VQE from qiskit.algorithms.optimizers import COBYLA, SLSQP, SPSA from qiskit.opflow import CircuitSampler from qiskit.ignis.mitigation.measurement import CompleteMeasFitter # you will need to pip install qiskit-ignis from qiskit.ignis.mitigation.measurement import complete_meas_cal from scipy import sparse import scipy.sparse.linalg.eigen.arpack as arp from modules.utils import * anti = -1 L = 5 num_trash = 2 name = "ibmq_antiferro-1D-load_bogota-optimize-20points" # remove test at the end when running on a real device filename = "data/noisy_VQE_maxiter-500_Ising_L5_anti_-1_20" #"data/noisy_VQE_maxiter-100_Ising_L5_anti_-1_20_recycle" print("filename: ", filename, "notebook name: ", name) # where to get the simulated thetas values from? needs to contain a thetas_mitigated array filename_simulated_thetas = 'data/ibmq_antiferro-1D-load_bogota-optimize_thetas-loss-cost_run2.npz' load = False recompute = True # whether or not to recompute Magnetization, makes sense on device IBMQ.load_account() # this then automatically loads your saved account provider = IBMQ.get_provider(hub='ibm-q-research') device = provider.backend.ibmq_bogota print(device) backend = device #backend = qiskit.providers.aer.AerSimulator.from_backend(device) coupling_map = device.configuration().coupling_map noise_model = qiskit.providers.aer.noise.NoiseModel.from_backend(device) basis_gates = noise_model.basis_gates #aqua_globals.random_seed = seed qi = qiskit.utils.QuantumInstance(backend=backend, # , seed_simulator=seed, seed_transpiler=seed coupling_map=coupling_map, #, noise_model=noise_model, measurement_error_mitigation_cls= CompleteMeasFitter, cals_matrix_refresh_period=30 #How often to refresh the calibration matrix in measurement mitigation. in minutes ) # Very important, at the moment poorly coded so it needs to come back to this instance all the time ansatz = qiskit.circuit.library.TwoLocal(L,rotation_blocks="ry", entanglement_blocks='cz', entanglement="sca", reps=1) ansatz.draw("mpl") ansatz = qiskit.transpile(ansatz, backend) ansatz.draw("mpl") L = 5 num_trash = 2 anti = -1 VQE_params = np.load(filename + ".npz", allow_pickle=True) pick = np.arange(0,len(VQE_params['gx_list'])) gx_list = VQE_params['gx_list'][pick] gz_list = VQE_params['gz_list'][pick] opt_params = VQE_params['opt_params'][pick] Qmags = VQE_params["Qmag"][pick] Qen = VQE_params["Qen"][pick] Sen = VQE_params["Sen"][pick] Smags = VQE_params["Smag"][pick] gx_vals = np.unique(gx_list) gz_vals = np.unique(gz_list) if load: temp = np.load("data/" + name + "executed_mags-Es.npz",allow_pickle=True) Qmags = temp["Qmags"] Qen = temp["Qen"] Sen = temp["Sen"] Smags = temp["Smags"] verbose=1 if recompute: mag = QMag(L,anti) #magnetization operator (Qiskit) Smag = Mag(L,anti) #magnetization operator (numpy) Qen_executed=np.zeros(len(opt_params), dtype="complex") Qmags_executed=np.zeros(len(opt_params), dtype="complex") for j in range(len(opt_params)): t0 = datetime.datetime.now() gx = gx_list[j] gz = gz_list[j] H = QHIsing(L, anti, np.float32(gx), np.float32(gz)) # build Hamiltonian Op state = ansatz.assign_parameters(opt_params[j]) meas_outcome = ~StateFn(mag) @ StateFn(state) Qmags_executed[j] = CircuitSampler(qi).convert(meas_outcome).eval() #https://quantumcomputing.stackexchange.com/questions/12080/evaluating-expectation-values-of-operators-in-qiskit #e_outcome = ~StateFn(H) @ StateFn(state) #Qen_executed[j] = CircuitSampler(qi).convert(e_outcome).eval() #init_state, E, ham = ising_groundstate(L, anti, np.float64(gx), np.float64(gz)) #Sen[j] = E #Smags[j] = init_state.T.conj()@Smag@init_state #Magnetization with Numpy results print(f"{j+1} / {len(opt_params)}, gx = {gx:.2f}, gz = {gz:.2f}, time : {(datetime.datetime.now() - t0)}") np.savez("data/" + name + "executed_mags-Es.npz",Qmags=Qmags_executed, Qen=Qen_executed, Sen=Sen, Smags=Smags) # for large parameter space takes quite a while because of the exact diagonalization fig, axs = plt.subplots(ncols=2, figsize=(10,5)) ax = axs[0] ax.plot(gx_list, Qmags,"x--", label="noisy VQE simu") ax.plot(gx_list, Smags,"x--", label="ED") ax.set_xscale("log") if recompute or load: ax.plot(gx_list, Qmags_executed,"x--", label="IBMQ") ax.legend() ############################################################################## ### II - Training ########################################################### ############################################################################## # linear entangler (as in scales linearly with trash qubits) def get_entangler_map(L, num_trash, i_permut=1, nums_trash=[1,2]): result = [] nums_compressed = list(range(L)) for trashqubit in nums_trash: nums_compressed.remove(trashqubit) if nums_trash == None: #old way nums_compressed = list(range(L))[:L-num_trash] nums_trash = list(range(L))[-num_trash:] #print(nums, nums_compressed, nums_trash) # combine all trash qubits with themselves for trash_q in nums_trash[:-1]: result.append((trash_q+1,trash_q)) # combine each of the trash qubits with every n-th repeated = list(nums_trash) * (L-num_trash) # repeat the list of trash indices cyclicly for i in range(L-num_trash): result.append((repeated[i_permut + i], nums_compressed[i])) return result def QAE_Ansatz(thetas, L, num_trash, insert_barriers=False, parametrized_gate = "ry", entangling_gate = "cz", nums_trash = [1,2]): entanglement = [get_entangler_map(L,num_trash,i_permut) for i_permut in range(num_trash)] if nums_trash == None: nums_trash = list(range(L))[-num_trash:] circ = qiskit.circuit.library.TwoLocal(L, parametrized_gate, entangling_gate, entanglement, reps=num_trash, insert_barriers=insert_barriers, skip_final_rotation_layer=True ).assign_parameters(thetas[:-num_trash]) if insert_barriers: circ.barrier() for i in nums_trash: circ.ry(thetas[i], i) #circ.ry(circuit.Parameter(f'θ{i}'), L-i-1) return circ def prepare_circuit(thetas, L=6, num_trash=2, init_state=None, measurement=True, vqe=True): qreg = QuantumRegister(L, 'q') creg = ClassicalRegister(num_trash, 'c') circ = QuantumCircuit(qreg, creg) circ += QAE_Ansatz(thetas, L, num_trash, insert_barriers=False)#.assign_parameters(thetas) # difference to bind? if measurement: for i in range(num_trash): circ.measure(qreg[L-i-1], creg[i]) if init_state is not None: if vqe: circ = ansatz.assign_parameters(init_state) + circ # needs to have ansatz defined somewhere in the script else: circ.initialize(init_state, qreg) return circ def feature_encoding(thetas, x): """ thetas: parameters to be optimized, x: Ising model parameter (eg. field) """ new_thetas = [] thetas = thetas.reshape((-1,2)) for theta in thetas: new_thetas.append(theta[0] * x + theta[1]) return new_thetas def calibrate_circuit(L, num_trash,shots=1000): qreg = QuantumRegister(L, 'q') # obtain calibration matrix qubit_list = [L-i-1 for i in range(num_trash)] # only need to calibrate the trash qubits circlabel = f'mcal_{datetime.datetime.now()}' meas_calibs, state_labels = complete_meas_cal(qubit_list=qubit_list, qr=qreg, circlabel=circlabel) cal_job = backend.run(meas_calibs, shots=shots) #, noise_model=noise_model) cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel=circlabel) print(circlabel, meas_fitter.cal_matrix) return meas_fitter def run_circuit(thetas, L, num_trash, init_state, vqe=True, shots=100, meas_fitter = None): circ = prepare_circuit(thetas, L, num_trash, init_state, vqe=vqe) tcirc = qiskit.transpile(circ, backend) # Execute the circuit job_sim = backend.run(tcirc, shots=shots) # , seed_simulator=123, seed_transpiler=234 fix seed to make it reproducible result = job_sim.result() # Results without mitigation counts = result.get_counts() if meas_fitter != None: # Get the filter object meas_filter = meas_fitter.filter # Results with mitigation mitigated_results = meas_filter.apply(result) counts = mitigated_results.get_counts(0) return counts meas_fitter = calibrate_circuit(L, num_trash) phis = opt_params # translate to Rikes naming gxs = gx_list gzs = gz_list def cost_function_single(thetas, L, num_trash, p, shots=1000, vqe=True, param_encoding=False, x=0, meas_fitter=None): """ Optimizes circuit """ if vqe: init_state = phis[p] else: J, gx, gz = p init_state, _ = ising_groundstate(L, J, gx, gz) if param_encoding: thetas = feature_encoding(thetas, x) out = run_circuit(thetas, L, num_trash, init_state, vqe=vqe, shots=shots, meas_fitter=meas_fitter) cost = out.get('11', 0)*2 + out.get('01', 0) + out.get('10', 0) return cost/shots def cost_function(thetas, L, num_trash, ising_params, shots=1000, vqe=True, param_encoding=False, x=0, meas_fitter=None): """ Optimizes circuit """ cost = 0. n_samples = len(ising_params) for i, p in enumerate(ising_params): if param_encoding: cost += cost_function_single(thetas, L, num_trash, p, shots, vqe, param_encoding, x[i], meas_fitter=meas_fitter) else: cost += cost_function_single(thetas, L, num_trash, p, shots, vqe, param_encoding, meas_fitter=meas_fitter) return cost/n_samples def optimize(ising_params, L=6, num_trash=2, thetas=None, shots=1000, max_iter=400, vqe=True, param_encoding=False, x=0, pick_optimizer = None, meas_fitter=None): if thetas is None: n_params = (2*L+2)*2 if param_encoding else (2*L+2) thetas = np.random.uniform(0, 2*np.pi, n_params) # initial parameters without feature encoding print("Initial cost: {:.3f}".format(cost_function(thetas, L, num_trash, ising_params, shots, vqe, param_encoding, x))) counts, values, accepted = [], [], [] def store_intermediate_result(eval_count, parameters, mean, std, ac): # counts.append(eval_count) values.append(mean) accepted.append(ac) # Initialize optimizer if pick_optimizer == "cobyla": optimizer = COBYLA(maxiter=max_iter, tol=0.0001) if pick_optimizer == "adam" or pick_optimizer == "ADAM": optimizer = qiskit.algorithms.optimizers.ADAM(maxiter=max_iter) # optimizer = L_BFGS_B(maxfun=300, maxiter=max_iter)#, factr=10, iprint=- 1, epsilon=1e-08) if pick_optimizer == "spsa" or pick_optimizer == None: optimizer = SPSA(maxiter=max_iter, #blocking=True, #callback=store_intermediate_result, learning_rate=0.3, perturbation=0.1 ) # recommended from qiskit (first iteraction takes quite long) # to reduce time figure out optimal learning rate and perturbation in advance start_time = time.time() ret = optimizer.optimize( num_vars=len(thetas), objective_function=(lambda thetas: cost_function(thetas, L, num_trash, ising_params, shots, vqe, param_encoding, x, meas_fitter=meas_fitter)), initial_point=thetas ) print("Time: {:.5f} sec".format(time.time()-start_time)) print(ret) return ret[0], values, accepted def run_inference(thetas, shots=1000, L=5, meas_fitter=None): points = 50 J = -1.0 x,y = np.meshgrid(gx_vals, gz_vals) cost = np.zeros((len(gx_vals) * len(gz_vals))) Smags = np.zeros((len(gx_vals) * len(gz_vals))) shots = 1000 for i,p in enumerate(list(zip(gxs, gzs))): t0 = datetime.datetime.now() cost[i] = cost_function_single(thetas, L, num_trash, i, shots=shots, meas_fitter=meas_fitter) if not i%verbose: print(f"{i+1} / {len(opt_params)}, gx = {gx:.2f}, gz = {gz:.2f}, time : {verbose*(datetime.datetime.now() - t0)}") cost = cost.reshape((len(gx_vals), len(gz_vals))) return cost phys_params = [0] filename_simulated_thetas = 'data/ibmq_antiferro-1D-load_simu_thetas-loss-cost_run2.npz' #this was actually a mistake, should have been the run1 but seemed to have worked anyways thetas_guess = np.load(filename_simulated_thetas, allow_pickle=True)["thetas_mitigated"] # Training to = datetime.datetime.now() thetas_opt_mitigated, loss, accepted = optimize(phys_params, thetas = thetas_guess, max_iter=30, L=5,meas_fitter=meas_fitter) #, pick_optimizer="adam") plt.plot(loss) print(datetime.datetime.now() - t0) # Inference cost_mitigated = np.zeros((len(gx_vals))) shots = 1000 for i,p in enumerate(list(zip(gxs, gzs))): t0 = datetime.datetime.now() cost_mitigated[i] = cost_function_single(thetas_opt_mitigated, L, num_trash, i, shots=shots, meas_fitter=meas_fitter) # np.random.uniform(0, 2*np.pi, 2*L+2) random parameters to check if training "does" something - result was: with random paremters just get noise, so yes, it "does" something if not i%verbose: print(f"{i+1} / {len(opt_params)}, gx = {p[0]:.2f}, gz = {p[1]:.2f}, time : {verbose*(datetime.datetime.now() - t0)}") np.savez("data/" + name + "_thetas-loss-cost_run1", cost_mitigated=cost_mitigated, thetas_mitigated=thetas_opt_mitigated, ) fig, ax = plt.subplots(ncols=1,figsize=(6,5)) ax.set_title("Mitigated results") cost = np.load("data/" + name + "_thetas-loss-cost_run1.npz", allow_pickle=True)["cost_mitigated"] ax.plot(gx_list, cost,".:", label="raw output") ax.plot(gx_list, Qmags,"x--", label="$\\langle \\sigma_z \\rangle$ noisy sim") ax.plot(gx_list, Qmags_executed,"x--", label="$\\langle \\sigma_z \\rangle$ ibmq_bogota") ax.set_xscale("log") for p in phys_params: ax.plot(gx_list[p],cost[p],"o",alpha=0.3,color="magenta") ax.legend() np.savez("data/" + name + "_thetas-loss-cost_run2", cost_mitigated=cost_mitigated, thetas_mitigated=thetas_opt_mitigated, ) filename_simulated_thetas = 'data/ibmq_antiferro-1D-load_bogota-optimize_thetas-loss-cost_run2.npz' fig, ax = plt.subplots(ncols=1,figsize=(6,5)) ax.set_title("Mitigated results") cost = np.load("data/" + name + "_thetas-loss-cost_run2.npz", allow_pickle=True)["cost_mitigated"] ax.plot(gx_list, cost,".:", label="raw output") ax.plot(gx_list, Qmags,"x--", color="tab:orange", label="Qmag") ax.set_xscale("log") for p in phys_params: ax.plot(gx_list[p],cost[p],"o",alpha=0.3,color="magenta")
https://github.com/Qottmann/Quantum-anomaly-detection
Qottmann
import sys sys.path.insert(1, '..') # sets the path to the parent folder, where the notebook was originally executed import time import datetime import numpy as np from matplotlib import pyplot as plt import qiskit from qiskit import * from qiskit.opflow import X,Z,I from qiskit.opflow.state_fns import StateFn, CircuitStateFn from qiskit.providers.aer import StatevectorSimulator, AerSimulator from qiskit.algorithms import VQE from qiskit.algorithms.optimizers import COBYLA, SLSQP, SPSA from qiskit.opflow import CircuitSampler from qiskit.ignis.mitigation.measurement import CompleteMeasFitter # you will need to pip install qiskit-ignis from qiskit.ignis.mitigation.measurement import complete_meas_cal from scipy import sparse import scipy.sparse.linalg.eigen.arpack as arp from modules.utils import * anti = -1 L = 5 num_trash = 2 name = "ibmq_antiferro-1D-load_bogota-optimize" # remove test at the end when running on a real device filename = "data/noisy_VQE_maxiter-500_Ising_L5_anti_-1_20" #"data/noisy_VQE_maxiter-100_Ising_L5_anti_-1_20_recycle" print("filename: ", filename, "notebook name: ", name) # where to get the simulated thetas values from? needs to contain a thetas_mitigated array filename_simulated_thetas = 'data/ibmq_antiferro-1D-load_simu_thetas-loss-cost_run2.npz' load = False recompute = False # whether or not to recompute Magnetization, makes sense on device IBMQ.load_account() # this then automatically loads your saved account provider = IBMQ.get_provider(hub='ibm-q-research') device = provider.backend.ibmq_bogota print(device) backend = device #backend = qiskit.providers.aer.AerSimulator.from_backend(device) coupling_map = device.configuration().coupling_map noise_model = qiskit.providers.aer.noise.NoiseModel.from_backend(device) basis_gates = noise_model.basis_gates #aqua_globals.random_seed = seed qi = qiskit.utils.QuantumInstance(backend=backend, # , seed_simulator=seed, seed_transpiler=seed coupling_map=coupling_map, #, noise_model=noise_model, measurement_error_mitigation_cls= CompleteMeasFitter, cals_matrix_refresh_period=30 #How often to refresh the calibration matrix in measurement mitigation. in minutes ) # Very important, at the moment poorly coded so it needs to come back to this instance all the time ansatz = qiskit.circuit.library.TwoLocal(L,rotation_blocks="ry", entanglement_blocks='cz', entanglement="sca", reps=1) ansatz.draw("mpl") ansatz = qiskit.transpile(ansatz, backend) ansatz.draw("mpl") L = 5 num_trash = 2 anti = -1 VQE_params = np.load(filename + ".npz", allow_pickle=True) pick = np.arange(0,len(VQE_params['gx_list']),3) gx_list = VQE_params['gx_list'][pick] gz_list = VQE_params['gz_list'][pick] opt_params = VQE_params['opt_params'][pick] Qmags = VQE_params["Qmag"][pick] Qen = VQE_params["Qen"][pick] Sen = VQE_params["Sen"][pick] Smags = VQE_params["Smag"][pick] gx_vals = np.unique(gx_list) gz_vals = np.unique(gz_list) if load: temp = np.load("data/" + name + "executed_mags-Es.npz",allow_pickle=True) Qmags = temp["Qmags"] Qen = temp["Qen"] Sen = temp["Sen"] Smags = temp["Smags"] verbose=1 if recompute: mag = QMag(L,anti) #magnetization operator (Qiskit) Smag = Mag(L,anti) #magnetization operator (numpy) Qen_executed=np.zeros(len(opt_params), dtype="complex") Qmags_executed=np.zeros(len(opt_params), dtype="complex") for j in range(len(opt_params)): t0 = datetime.datetime.now() gx = gx_list[j] gz = gz_list[j] H = QHIsing(L, anti, np.float32(gx), np.float32(gz)) # build Hamiltonian Op state = ansatz.assign_parameters(opt_params[j]) meas_outcome = ~StateFn(mag) @ StateFn(state) Qmags_executed[j] = CircuitSampler(qi).convert(meas_outcome).eval() #https://quantumcomputing.stackexchange.com/questions/12080/evaluating-expectation-values-of-operators-in-qiskit #e_outcome = ~StateFn(H) @ StateFn(state) #Qen_executed[j] = CircuitSampler(qi).convert(e_outcome).eval() init_state, E, ham = ising_groundstate(L, anti, np.float64(gx), np.float64(gz)) Sen[j] = E Smags[j] = init_state.T.conj()@Smag@init_state #Magnetization with Numpy results print(f"{j+1} / {len(opt_params)}, gx = {gx:.2f}, gz = {gz:.2f}, time : {(datetime.datetime.now() - t0)}") np.savez("data/" + name + "executed_mags-Es.npz",Qmags=Qmags_executed, Qen=Qen_executed, Sen=Sen, Smags=Smags) # for large parameter space takes quite a while because of the exact diagonalization fig, axs = plt.subplots(ncols=2, figsize=(10,5)) ax = axs[0] ax.plot(gx_list, Qmags,"x--", label="noisy VQE simu") ax.plot(gx_list, Smags,"x--", label="ED") ax.set_xscale("log") if recompute: ax.plot(gx_list, Qmags_executed,"x--", label="IBMQ") ax.legend() ############################################################################## ### II - Training ########################################################### ############################################################################## # linear entangler (as in scales linearly with trash qubits) def get_entangler_map(L, num_trash, i_permut=1, nums_trash=[1,2]): result = [] nums_compressed = list(range(L)) for trashqubit in nums_trash: nums_compressed.remove(trashqubit) if nums_trash == None: #old way nums_compressed = list(range(L))[:L-num_trash] nums_trash = list(range(L))[-num_trash:] #print(nums, nums_compressed, nums_trash) # combine all trash qubits with themselves for trash_q in nums_trash[:-1]: result.append((trash_q+1,trash_q)) # combine each of the trash qubits with every n-th repeated = list(nums_trash) * (L-num_trash) # repeat the list of trash indices cyclicly for i in range(L-num_trash): result.append((repeated[i_permut + i], nums_compressed[i])) return result def QAE_Ansatz(thetas, L, num_trash, insert_barriers=False, parametrized_gate = "ry", entangling_gate = "cz", nums_trash = [1,2]): entanglement = [get_entangler_map(L,num_trash,i_permut) for i_permut in range(num_trash)] if nums_trash == None: nums_trash = list(range(L))[-num_trash:] circ = qiskit.circuit.library.TwoLocal(L, parametrized_gate, entangling_gate, entanglement, reps=num_trash, insert_barriers=insert_barriers, skip_final_rotation_layer=True ).assign_parameters(thetas[:-num_trash]) if insert_barriers: circ.barrier() for i in nums_trash: circ.ry(thetas[i], i) #circ.ry(circuit.Parameter(f'θ{i}'), L-i-1) return circ def prepare_circuit(thetas, L=6, num_trash=2, init_state=None, measurement=True, vqe=True): qreg = QuantumRegister(L, 'q') creg = ClassicalRegister(num_trash, 'c') circ = QuantumCircuit(qreg, creg) circ += QAE_Ansatz(thetas, L, num_trash, insert_barriers=False)#.assign_parameters(thetas) # difference to bind? if measurement: for i in range(num_trash): circ.measure(qreg[L-i-1], creg[i]) if init_state is not None: if vqe: circ = ansatz.assign_parameters(init_state) + circ # needs to have ansatz defined somewhere in the script else: circ.initialize(init_state, qreg) return circ def feature_encoding(thetas, x): """ thetas: parameters to be optimized, x: Ising model parameter (eg. field) """ new_thetas = [] thetas = thetas.reshape((-1,2)) for theta in thetas: new_thetas.append(theta[0] * x + theta[1]) return new_thetas def calibrate_circuit(L, num_trash,shots=1000): qreg = QuantumRegister(L, 'q') # obtain calibration matrix qubit_list = [L-i-1 for i in range(num_trash)] # only need to calibrate the trash qubits circlabel = f'mcal_{datetime.datetime.now()}' meas_calibs, state_labels = complete_meas_cal(qubit_list=qubit_list, qr=qreg, circlabel=circlabel) cal_job = backend.run(meas_calibs, shots=shots) #, noise_model=noise_model) cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel=circlabel) print(circlabel, meas_fitter.cal_matrix) return meas_fitter def run_circuit(thetas, L, num_trash, init_state, vqe=True, shots=100, meas_fitter = None): circ = prepare_circuit(thetas, L, num_trash, init_state, vqe=vqe) tcirc = qiskit.transpile(circ, backend) # Execute the circuit job_sim = backend.run(tcirc, shots=shots) # , seed_simulator=123, seed_transpiler=234 fix seed to make it reproducible result = job_sim.result() # Results without mitigation counts = result.get_counts() if meas_fitter != None: # Get the filter object meas_filter = meas_fitter.filter # Results with mitigation mitigated_results = meas_filter.apply(result) counts = mitigated_results.get_counts(0) return counts meas_fitter = calibrate_circuit(L, num_trash) phis = opt_params # translate to Rikes naming gxs = gx_list gzs = gz_list def cost_function_single(thetas, L, num_trash, p, shots=1000, vqe=True, param_encoding=False, x=0, meas_fitter=None): """ Optimizes circuit """ if vqe: init_state = phis[p] else: J, gx, gz = p init_state, _ = ising_groundstate(L, J, gx, gz) if param_encoding: thetas = feature_encoding(thetas, x) out = run_circuit(thetas, L, num_trash, init_state, vqe=vqe, shots=shots, meas_fitter=meas_fitter) cost = out.get('11', 0)*2 + out.get('01', 0) + out.get('10', 0) return cost/shots def cost_function(thetas, L, num_trash, ising_params, shots=1000, vqe=True, param_encoding=False, x=0, meas_fitter=None): """ Optimizes circuit """ cost = 0. n_samples = len(ising_params) for i, p in enumerate(ising_params): if param_encoding: cost += cost_function_single(thetas, L, num_trash, p, shots, vqe, param_encoding, x[i], meas_fitter=meas_fitter) else: cost += cost_function_single(thetas, L, num_trash, p, shots, vqe, param_encoding, meas_fitter=meas_fitter) return cost/n_samples def optimize(ising_params, L=6, num_trash=2, thetas=None, shots=1000, max_iter=400, vqe=True, param_encoding=False, x=0, pick_optimizer = None, meas_fitter=None): if thetas is None: n_params = (2*L+2)*2 if param_encoding else (2*L+2) thetas = np.random.uniform(0, 2*np.pi, n_params) # initial parameters without feature encoding print("Initial cost: {:.3f}".format(cost_function(thetas, L, num_trash, ising_params, shots, vqe, param_encoding, x))) counts, values, accepted = [], [], [] def store_intermediate_result(eval_count, parameters, mean, std, ac): # counts.append(eval_count) values.append(mean) accepted.append(ac) # Initialize optimizer if pick_optimizer == "cobyla": optimizer = COBYLA(maxiter=max_iter, tol=0.0001) if pick_optimizer == "adam" or pick_optimizer == "ADAM": optimizer = qiskit.algorithms.optimizers.ADAM(maxiter=max_iter) # optimizer = L_BFGS_B(maxfun=300, maxiter=max_iter)#, factr=10, iprint=- 1, epsilon=1e-08) if pick_optimizer == "spsa" or pick_optimizer == None: optimizer = SPSA(maxiter=max_iter, #blocking=True, callback=store_intermediate_result, learning_rate=0.3, perturbation=0.1 ) # recommended from qiskit (first iteraction takes quite long) # to reduce time figure out optimal learning rate and perturbation in advance start_time = time.time() ret = optimizer.optimize( num_vars=len(thetas), objective_function=(lambda thetas: cost_function(thetas, L, num_trash, ising_params, shots, vqe, param_encoding, x, meas_fitter=meas_fitter)), initial_point=thetas ) print("Time: {:.5f} sec".format(time.time()-start_time)) print(ret) return ret[0], values, accepted def run_inference(thetas, shots=1000, L=5, meas_fitter=None): points = 50 J = -1.0 x,y = np.meshgrid(gx_vals, gz_vals) cost = np.zeros((len(gx_vals) * len(gz_vals))) Smags = np.zeros((len(gx_vals) * len(gz_vals))) shots = 1000 for i,p in enumerate(list(zip(gxs, gzs))): t0 = datetime.datetime.now() cost[i] = cost_function_single(thetas, L, num_trash, i, shots=shots, meas_fitter=meas_fitter) if not i%verbose: print(f"{i+1} / {len(opt_params)}, gx = {gx:.2f}, gz = {gz:.2f}, time : {verbose*(datetime.datetime.now() - t0)}") cost = cost.reshape((len(gx_vals), len(gz_vals))) return cost phys_params = [-1] thetas_guess = np.load(filename_simulated_thetas, allow_pickle=True)["thetas_mitigated"] # Training thetas_opt_mitigated, loss, accepted = optimize(phys_params, thetas = thetas_guess, max_iter=30, L=5,meas_fitter=meas_fitter) #, pick_optimizer="adam") plt.plot(loss) # Inference cost_mitigated = np.zeros((len(gx_vals))) shots = 1000 for i,p in enumerate(list(zip(gxs, gzs))): t0 = datetime.datetime.now() cost_mitigated[i] = cost_function_single(thetas_opt_mitigated, L, num_trash, i, shots=shots, meas_fitter=meas_fitter) # np.random.uniform(0, 2*np.pi, 2*L+2) random parameters to check if training "does" something - result was: with random paremters just get noise, so yes, it "does" something if not i%verbose: print(f"{i+1} / {len(opt_params)}, gx = {p[0]:.2f}, gz = {p[1]:.2f}, time : {verbose*(datetime.datetime.now() - t0)}") "data/" + name + "_thetas-loss-cost_run2" np.savez("data/" + name + "_thetas-loss-cost_run2", cost_mitigated=cost_mitigated, thetas_mitigated=thetas_opt_mitigated, ) fig, ax = plt.subplots(ncols=1,figsize=(6,5)) ax.set_title("Mitigated results") cost = np.load("data/" + name + "_thetas-loss-cost_run2.npz", allow_pickle=True)["cost_mitigated"] ax.plot(gx_list, cost,".:", label="raw output") ax.plot(gx_list, abs(Qmags),"x--", color="tab:orange", label="Qmag") ax.set_xscale("log") for p in phys_params: ax.plot(gx_list[p],cost[p],"o",alpha=0.3,color="magenta")
https://github.com/Qottmann/Quantum-anomaly-detection
Qottmann
import time import datetime import numpy as np from matplotlib import pyplot as plt import qiskit from qiskit import * from qiskit.opflow import X,Z,I from qiskit.opflow.state_fns import StateFn, CircuitStateFn from qiskit.providers.aer import StatevectorSimulator, AerSimulator from qiskit.algorithms import VQE from qiskit.algorithms.optimizers import COBYLA, SLSQP, SPSA from qiskit.opflow import CircuitSampler from qiskit.ignis.mitigation.measurement import CompleteMeasFitter # you will need to pip install qiskit-ignis from qiskit.ignis.mitigation.measurement import complete_meas_cal from scipy import sparse import scipy.sparse.linalg.eigen.arpack as arp from modules.utils import * anti = -1 L = 5 num_trash = 2 name = "ibmq_antiferro-1D-load_bogota-test" filename = "data/noisy_VQE_maxiter-500_Ising_L5_anti_-1_20" #"data/noisy_VQE_maxiter-100_Ising_L5_anti_-1_20_recycle" filename_simualted_thetas = 'data/ibmq_antiferro-1D-load_simu_thetas-loss-cost_run2.npz' # where to get the simulated thetas values from? print("filename: ", filename, "notebook name: ", name) load = False recompute = False # whether or not to recompute Magnetization, makes sense on device IBMQ.load_account() # this then automatically loads your saved account provider = IBMQ.get_provider(hub='ibm-q-research') device = provider.backend.ibmq_bogota print(device) #backend = device backend = qiskit.providers.aer.AerSimulator.from_backend(device) coupling_map = device.configuration().coupling_map noise_model = qiskit.providers.aer.noise.NoiseModel.from_backend(device) basis_gates = noise_model.basis_gates #aqua_globals.random_seed = seed qi = qiskit.utils.QuantumInstance(backend=backend, # , seed_simulator=seed, seed_transpiler=seed coupling_map=coupling_map, noise_model=noise_model, measurement_error_mitigation_cls= CompleteMeasFitter, cals_matrix_refresh_period=30 #How often to refresh the calibration matrix in measurement mitigation. in minutes ) backend._cached_basis_gates # Very important, at the moment poorly coded so it needs to come back to this instance all the time ansatz = qiskit.circuit.library.TwoLocal(L,rotation_blocks="ry", entanglement_blocks='cz', entanglement="sca", reps=1) ansatz.draw("mpl") ansatz = qiskit.transpile(ansatz, backend) ansatz.draw("mpl") L = 5 num_trash = 2 anti = -1 VQE_params = np.load(filename + ".npz", allow_pickle=True) gx_list = VQE_params['gx_list'] gz_list = VQE_params['gz_list'] opt_params = VQE_params['opt_params'] Qmags = VQE_params["Qmag"] Qen = VQE_params["Qen"] Sen = VQE_params["Sen"] Smags = VQE_params["Smag"] gx_vals = np.unique(gx_list) gz_vals = np.unique(gz_list) if load: temp = np.load("data/" + name + "executed_mags-Es.npz",allow_pickle=True) Qmags = temp["Qmags"] Qen = temp["Qen"] Sen = temp["Sen"] Smags = temp["Smags"] verbose=1 if recompute: mag = QMag(L,anti) #magnetization operator (Qiskit) Smag = Mag(L,anti) #magnetization operator (numpy) Qen_executed=np.zeros(len(opt_params), dtype="complex") Qmags_executed=np.zeros(len(opt_params), dtype="complex") for j in range(len(opt_params)): t0 = datetime.datetime.now() gx = gx_list[j] gz = gz_list[j] H = QHIsing(L, anti, np.float32(gx), np.float32(gz)) # build Hamiltonian Op state = ansatz.assign_parameters(opt_params[j]) meas_outcome = ~StateFn(mag) @ StateFn(state) Qmags_executed[j] = CircuitSampler(qi).convert(meas_outcome).eval() #https://quantumcomputing.stackexchange.com/questions/12080/evaluating-expectation-values-of-operators-in-qiskit #e_outcome = ~StateFn(H) @ StateFn(state) #Qen_executed[j] = CircuitSampler(qi).convert(e_outcome).eval() init_state, E, ham = ising_groundstate(L, anti, np.float64(gx), np.float64(gz)) Sen[j] = E Smags[j] = init_state.T.conj()@Smag@init_state #Magnetization with Numpy results print(f"{j+1} / {len(opt_params)}, gx = {gx:.2f}, gz = {gz:.2f}, time : {(datetime.datetime.now() - t0)}") np.savez("data/" + name + "executed_mags-Es.npz",Qmags=Qmags_executed, Qen=Qen_executed, Sen=Sen, Smags=Smags) # for large parameter space takes quite a while because of the exact diagonalization fig, axs = plt.subplots(ncols=2, figsize=(10,5)) ax = axs[0] ax.plot(gx_list, Qmags,"x--", label="noisy VQE simu") ax.plot(gx_list, Smags,"x--", label="ED") ax.set_xscale("log") if recompute: ax.plot(gx_list, Qmags_executed,"x--", label="IBMQ") ax.legend() ############################################################################## ### II - Training ########################################################### ############################################################################## # linear entangler (as in scales linearly with trash qubits) def get_entangler_map(L, num_trash, i_permut=1, nums_trash=[1,2]): result = [] nums_compressed = list(range(L)) for trashqubit in nums_trash: nums_compressed.remove(trashqubit) if nums_trash == None: #old way nums_compressed = list(range(L))[:L-num_trash] nums_trash = list(range(L))[-num_trash:] #print(nums, nums_compressed, nums_trash) # combine all trash qubits with themselves for trash_q in nums_trash[:-1]: result.append((trash_q+1,trash_q)) # combine each of the trash qubits with every n-th repeated = list(nums_trash) * (L-num_trash) # repeat the list of trash indices cyclicly for i in range(L-num_trash): result.append((repeated[i_permut + i], nums_compressed[i])) return result def QAE_Ansatz(thetas, L, num_trash, insert_barriers=False, parametrized_gate = "ry", entangling_gate = "cz", nums_trash = [1,2]): entanglement = [get_entangler_map(L,num_trash,i_permut) for i_permut in range(num_trash)] if nums_trash == None: nums_trash = list(range(L))[-num_trash:] circ = qiskit.circuit.library.TwoLocal(L, parametrized_gate, entangling_gate, entanglement, reps=num_trash, insert_barriers=insert_barriers, skip_final_rotation_layer=True ).assign_parameters(thetas[:-num_trash]) if insert_barriers: circ.barrier() for i in nums_trash: circ.ry(thetas[i], i) #circ.ry(circuit.Parameter(f'θ{i}'), L-i-1) return circ def prepare_circuit(thetas, L=6, num_trash=2, init_state=None, measurement=True, vqe=True): qreg = QuantumRegister(L, 'q') creg = ClassicalRegister(num_trash, 'c') circ = QuantumCircuit(qreg, creg) circ += QAE_Ansatz(thetas, L, num_trash, insert_barriers=False)#.assign_parameters(thetas) # difference to bind? if measurement: for i in range(num_trash): circ.measure(qreg[L-i-1], creg[i]) if init_state is not None: if vqe: circ = ansatz.assign_parameters(init_state) + circ # needs to have ansatz defined somewhere in the script else: circ.initialize(init_state, qreg) return circ def feature_encoding(thetas, x): """ thetas: parameters to be optimized, x: Ising model parameter (eg. field) """ new_thetas = [] thetas = thetas.reshape((-1,2)) for theta in thetas: new_thetas.append(theta[0] * x + theta[1]) return new_thetas def calibrate_circuit(L, num_trash,shots=1000): qreg = QuantumRegister(L, 'q') # obtain calibration matrix qubit_list = [L-i-1 for i in range(num_trash)] # only need to calibrate the trash qubits circlabel = f'mcal_{datetime.datetime.now()}' meas_calibs, state_labels = complete_meas_cal(qubit_list=qubit_list, qr=qreg, circlabel=circlabel) cal_job = backend.run(meas_calibs, shots=shots, noise_model=noise_model) cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel=circlabel) print(circlabel, meas_fitter.cal_matrix) return meas_fitter def run_circuit(thetas, L, num_trash, init_state, vqe=True, shots=100, meas_fitter = None): circ = prepare_circuit(thetas, L, num_trash, init_state, vqe=vqe) tcirc = qiskit.transpile(circ, backend) # Execute the circuit job_sim = backend.run(tcirc, shots=shots) # , seed_simulator=123, seed_transpiler=234 fix seed to make it reproducible result = job_sim.result() # Results without mitigation counts = result.get_counts() if meas_fitter != None: # Get the filter object meas_filter = meas_fitter.filter # Results with mitigation mitigated_results = meas_filter.apply(result) counts = mitigated_results.get_counts(0) return counts meas_fitter = calibrate_circuit(L, num_trash) phis = opt_params # translate to Rikes naming gxs = gx_list gzs = gz_list def cost_function_single(thetas, L, num_trash, p, shots=1000, vqe=True, param_encoding=False, x=0, meas_fitter=None): """ Optimizes circuit """ if vqe: init_state = phis[p] else: J, gx, gz = p init_state, _ = ising_groundstate(L, J, gx, gz) if param_encoding: thetas = feature_encoding(thetas, x) out = run_circuit(thetas, L, num_trash, init_state, vqe=vqe, shots=shots, meas_fitter=meas_fitter) cost = out.get('11', 0)*2 + out.get('01', 0) + out.get('10', 0) return cost/shots def cost_function(thetas, L, num_trash, ising_params, shots=1000, vqe=True, param_encoding=False, x=0, meas_fitter=None): """ Optimizes circuit """ cost = 0. n_samples = len(ising_params) for i, p in enumerate(ising_params): if param_encoding: cost += cost_function_single(thetas, L, num_trash, p, shots, vqe, param_encoding, x[i], meas_fitter=meas_fitter) else: cost += cost_function_single(thetas, L, num_trash, p, shots, vqe, param_encoding, meas_fitter=meas_fitter) return cost/n_samples def optimize(ising_params, L=6, num_trash=2, thetas=None, shots=1000, max_iter=400, vqe=True, param_encoding=False, x=0, pick_optimizer = None, meas_fitter=None): if thetas is None: n_params = (2*L+2)*2 if param_encoding else (2*L+2) thetas = np.random.uniform(0, 2*np.pi, n_params) # initial parameters without feature encoding print("Initial cost: {:.3f}".format(cost_function(thetas, L, num_trash, ising_params, shots, vqe, param_encoding, x))) counts, values, accepted = [], [], [] def store_intermediate_result(eval_count, parameters, mean, std, ac): # counts.append(eval_count) values.append(mean) accepted.append(ac) # Initialize optimizer if pick_optimizer == "cobyla": optimizer = COBYLA(maxiter=max_iter, tol=0.0001) if pick_optimizer == "adam" or pick_optimizer == "ADAM": optimizer = qiskit.algorithms.optimizers.ADAM(maxiter=max_iter) # optimizer = L_BFGS_B(maxfun=300, maxiter=max_iter)#, factr=10, iprint=- 1, epsilon=1e-08) if pick_optimizer == "spsa" or pick_optimizer == None: optimizer = SPSA(maxiter=max_iter, #blocking=True, callback=store_intermediate_result, learning_rate=0.3, perturbation=0.1 ) # recommended from qiskit (first iteraction takes quite long) # to reduce time figure out optimal learning rate and perturbation in advance start_time = time.time() ret = optimizer.optimize( num_vars=len(thetas), objective_function=(lambda thetas: cost_function(thetas, L, num_trash, ising_params, shots, vqe, param_encoding, x, meas_fitter=meas_fitter)), initial_point=thetas ) print("Time: {:.5f} sec".format(time.time()-start_time)) print(ret) return ret[0], values, accepted def run_inference(thetas, shots=1000, L=5, meas_fitter=None): points = 50 J = -1.0 x,y = np.meshgrid(gx_vals, gz_vals) cost = np.zeros((len(gx_vals) * len(gz_vals))) Smags = np.zeros((len(gx_vals) * len(gz_vals))) shots = 1000 for i,p in enumerate(list(zip(gxs, gzs))): t0 = datetime.datetime.now() cost[i] = cost_function_single(thetas, L, num_trash, i, shots=shots, meas_fitter=meas_fitter) if not i%verbose: print(f"{i+1} / {len(opt_params)}, gx = {gx:.2f}, gz = {gz:.2f}, time : {verbose*(datetime.datetime.now() - t0)}") cost = cost.reshape((len(gx_vals), len(gz_vals))) return cost thetas_guess = np.load(filename_simualted_thetas, allow_pickle=True)["thetas_mitigated"] # Training phys_params = [-1] thetas_opt_mitigated, loss, accepted = optimize(phys_params, thetas = thetas_guess, max_iter=30, L=5,meas_fitter=meas_fitter) #, pick_optimizer="adam") plt.plot(loss) # Inference cost_mitigated = np.zeros((len(gx_vals))) shots = 1000 for i,p in enumerate(list(zip(gxs, gzs))): t0 = datetime.datetime.now() cost_mitigated[i] = cost_function_single(thetas_opt_mitigated, L, num_trash, i, shots=shots, meas_fitter=meas_fitter) # np.random.uniform(0, 2*np.pi, 2*L+2) random parameters to check if training "does" something - result was: with random paremters just get noise, so yes, it "does" something if not i%verbose: print(f"{i+1} / {len(opt_params)}, gx = {p[0]:.2f}, gz = {p[1]:.2f}, time : {verbose*(datetime.datetime.now() - t0)}") np.savez("data/" + name + "_thetas-loss-cost_run2", cost_mitigated=cost_mitigated, thetas_mitigated=thetas_opt_mitigated, ) fig, ax = plt.subplots(ncols=1,figsize=(6,5)) ax.set_title("Mitigated results") cost = np.load("data/" + name + "_thetas-loss-cost_run2.npz", allow_pickle=True)["cost_mitigated"] ax.plot(gx_list, cost,".:", label="raw output") ax.plot(gx_list, Qmags,"x--", color="tab:orange", label="Qmag") ax.set_xscale("log") for p in phys_params: ax.plot(gx_list[p],cost[p],"o",alpha=0.3,color="magenta")
https://github.com/Qottmann/Quantum-anomaly-detection
Qottmann
import sys sys.path.insert(1, '..') # sets the path to the parent folder, where the notebook was originally executed import time import datetime import numpy as np from matplotlib import pyplot as plt import qiskit from qiskit import * from qiskit.opflow import X,Z,I from qiskit.opflow.state_fns import StateFn, CircuitStateFn from qiskit.providers.aer import StatevectorSimulator, AerSimulator from qiskit.algorithms import VQE from qiskit.algorithms.optimizers import COBYLA, SLSQP, SPSA from qiskit.opflow import CircuitSampler from qiskit.ignis.mitigation.measurement import CompleteMeasFitter # you will need to pip install qiskit-ignis from qiskit.ignis.mitigation.measurement import complete_meas_cal from scipy import sparse import scipy.sparse.linalg.eigen.arpack as arp from modules.utils import * anti = -1 L = 5 num_trash = 2 name = "ibmq_antiferro-1D-load_bogota-optimize" # remove test at the end when running on a real device filename = "data/noisy_VQE_maxiter-500_Ising_L5_anti_-1_20" #"data/noisy_VQE_maxiter-100_Ising_L5_anti_-1_20_recycle" print("filename: ", filename, "notebook name: ", name) # where to get the simulated thetas values from? needs to contain a thetas_mitigated array filename_simulated_thetas = 'data/ibmq_antiferro-1D-load_simu_thetas-loss-cost_run2.npz' load = False recompute = True # whether or not to recompute Magnetization, makes sense on device IBMQ.load_account() # this then automatically loads your saved account provider = IBMQ.get_provider(hub='ibm-q-research') device = provider.backend.ibmq_rome print(device) backend = device #backend = qiskit.providers.aer.AerSimulator.from_backend(device) coupling_map = device.configuration().coupling_map noise_model = qiskit.providers.aer.noise.NoiseModel.from_backend(device) basis_gates = noise_model.basis_gates #aqua_globals.random_seed = seed qi = qiskit.utils.QuantumInstance(backend=backend, # , seed_simulator=seed, seed_transpiler=seed coupling_map=coupling_map, #, noise_model=noise_model, measurement_error_mitigation_cls= CompleteMeasFitter, cals_matrix_refresh_period=30 #How often to refresh the calibration matrix in measurement mitigation. in minutes ) # Very important, at the moment poorly coded so it needs to come back to this instance all the time ansatz = qiskit.circuit.library.TwoLocal(L,rotation_blocks="ry", entanglement_blocks='cz', entanglement="sca", reps=1) #ansatz.draw("mpl") ansatz = qiskit.transpile(ansatz, backend) #ansatz.draw("mpl") L = 5 num_trash = 2 anti = -1 VQE_params = np.load(filename + ".npz", allow_pickle=True) pick = np.arange(0,len(VQE_params['gx_list']),3) gx_list = VQE_params['gx_list'][pick] gz_list = VQE_params['gz_list'][pick] opt_params = VQE_params['opt_params'][pick] Qmags = VQE_params["Qmag"][pick] Qen = VQE_params["Qen"][pick] Sen = VQE_params["Sen"][pick] Smags = VQE_params["Smag"][pick] gx_vals = np.unique(gx_list) gz_vals = np.unique(gz_list) if load: temp = np.load("data/" + name + "executed_mags-Es.npz",allow_pickle=True) Qmags = temp["Qmags"] Qen = temp["Qen"] Sen = temp["Sen"] Smags = temp["Smags"] verbose=1 if recompute: mag = QMag(L,anti) #magnetization operator (Qiskit) Smag = Mag(L,anti) #magnetization operator (numpy) Qen_executed=np.zeros(len(opt_params), dtype="complex") Qmags_executed=np.zeros(len(opt_params), dtype="complex") for j in range(len(opt_params)): t0 = datetime.datetime.now() gx = gx_list[j] gz = gz_list[j] H = QHIsing(L, anti, np.float32(gx), np.float32(gz)) # build Hamiltonian Op state = ansatz.assign_parameters(opt_params[j]) meas_outcome = ~StateFn(mag) @ StateFn(state) Qmags_executed[j] = CircuitSampler(qi).convert(meas_outcome).eval() #https://quantumcomputing.stackexchange.com/questions/12080/evaluating-expectation-values-of-operators-in-qiskit #e_outcome = ~StateFn(H) @ StateFn(state) #Qen_executed[j] = CircuitSampler(qi).convert(e_outcome).eval() init_state, E, ham = ising_groundstate(L, anti, np.float64(gx), np.float64(gz)) Sen[j] = E Smags[j] = init_state.T.conj()@Smag@init_state #Magnetization with Numpy results print(f"{j+1} / {len(opt_params)}, gx = {gx:.2f}, gz = {gz:.2f}, time : {(datetime.datetime.now() - t0)}") np.savez("data/" + name + "executed_mags-Es.npz",Qmags=Qmags_executed, Qen=Qen_executed, Sen=Sen, Smags=Smags) # for large parameter space takes quite a while because of the exact diagonalization temp = np.load("data/ibmq_antiferro-1D-load_bogota-optimize-20pointsexecuted_mags-Es.npz",allow_pickle=True) Qmags_executed_bogota = temp["Qmags"] fig, ax = plt.subplots(ncols=1, figsize=(6,5)) ax.plot(gx_list, Qmags,"x--", label="noisy rome simu") ax.plot(gx_list, Smags,"x--", label="ED") ax.plot(gx_list, Qmags_executed_bogota[::3],"x--", label="ibmq_bogota") if recompute: ax.plot(gx_list, Qmags_executed,"x--", label="ibmq_rome") ax.legend() ax.set_xscale("log") plt.tight_layout() plt.savefig("plots/temp_compare-bogota-rome_vqe-vals-from-noisy-rome-simulation.png") ############################################################################## ### II - Training ########################################################### ############################################################################## # linear entangler (as in scales linearly with trash qubits) def get_entangler_map(L, num_trash, i_permut=1, nums_trash=[1,2]): result = [] nums_compressed = list(range(L)) for trashqubit in nums_trash: nums_compressed.remove(trashqubit) if nums_trash == None: #old way nums_compressed = list(range(L))[:L-num_trash] nums_trash = list(range(L))[-num_trash:] #print(nums, nums_compressed, nums_trash) # combine all trash qubits with themselves for trash_q in nums_trash[:-1]: result.append((trash_q+1,trash_q)) # combine each of the trash qubits with every n-th repeated = list(nums_trash) * (L-num_trash) # repeat the list of trash indices cyclicly for i in range(L-num_trash): result.append((repeated[i_permut + i], nums_compressed[i])) return result def QAE_Ansatz(thetas, L, num_trash, insert_barriers=False, parametrized_gate = "ry", entangling_gate = "cz", nums_trash = [1,2]): entanglement = [get_entangler_map(L,num_trash,i_permut) for i_permut in range(num_trash)] if nums_trash == None: nums_trash = list(range(L))[-num_trash:] circ = qiskit.circuit.library.TwoLocal(L, parametrized_gate, entangling_gate, entanglement, reps=num_trash, insert_barriers=insert_barriers, skip_final_rotation_layer=True ).assign_parameters(thetas[:-num_trash]) if insert_barriers: circ.barrier() for i in nums_trash: circ.ry(thetas[i], i) #circ.ry(circuit.Parameter(f'θ{i}'), L-i-1) return circ def prepare_circuit(thetas, L=6, num_trash=2, init_state=None, measurement=True, vqe=True): qreg = QuantumRegister(L, 'q') creg = ClassicalRegister(num_trash, 'c') circ = QuantumCircuit(qreg, creg) circ += QAE_Ansatz(thetas, L, num_trash, insert_barriers=False)#.assign_parameters(thetas) # difference to bind? if measurement: for i in range(num_trash): circ.measure(qreg[L-i-1], creg[i]) if init_state is not None: if vqe: circ = ansatz.assign_parameters(init_state) + circ # needs to have ansatz defined somewhere in the script else: circ.initialize(init_state, qreg) return circ def feature_encoding(thetas, x): """ thetas: parameters to be optimized, x: Ising model parameter (eg. field) """ new_thetas = [] thetas = thetas.reshape((-1,2)) for theta in thetas: new_thetas.append(theta[0] * x + theta[1]) return new_thetas def calibrate_circuit(L, num_trash,shots=1000): qreg = QuantumRegister(L, 'q') # obtain calibration matrix qubit_list = [L-i-1 for i in range(num_trash)] # only need to calibrate the trash qubits circlabel = f'mcal_{datetime.datetime.now()}' meas_calibs, state_labels = complete_meas_cal(qubit_list=qubit_list, qr=qreg, circlabel=circlabel) cal_job = backend.run(meas_calibs, shots=shots) #, noise_model=noise_model) cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel=circlabel) print(circlabel, meas_fitter.cal_matrix) return meas_fitter def run_circuit(thetas, L, num_trash, init_state, vqe=True, shots=100, meas_fitter = None): circ = prepare_circuit(thetas, L, num_trash, init_state, vqe=vqe) tcirc = qiskit.transpile(circ, backend) # Execute the circuit job_sim = backend.run(tcirc, shots=shots) # , seed_simulator=123, seed_transpiler=234 fix seed to make it reproducible result = job_sim.result() # Results without mitigation counts = result.get_counts() if meas_fitter != None: # Get the filter object meas_filter = meas_fitter.filter # Results with mitigation mitigated_results = meas_filter.apply(result) counts = mitigated_results.get_counts(0) return counts meas_fitter = calibrate_circuit(L, num_trash) phis = opt_params # translate to Rikes naming gxs = gx_list gzs = gz_list def cost_function_single(thetas, L, num_trash, p, shots=1000, vqe=True, param_encoding=False, x=0, meas_fitter=None): """ Optimizes circuit """ if vqe: init_state = phis[p] else: J, gx, gz = p init_state, _ = ising_groundstate(L, J, gx, gz) if param_encoding: thetas = feature_encoding(thetas, x) out = run_circuit(thetas, L, num_trash, init_state, vqe=vqe, shots=shots, meas_fitter=meas_fitter) cost = out.get('11', 0)*2 + out.get('01', 0) + out.get('10', 0) return cost/shots def cost_function(thetas, L, num_trash, ising_params, shots=1000, vqe=True, param_encoding=False, x=0, meas_fitter=None): """ Optimizes circuit """ cost = 0. n_samples = len(ising_params) for i, p in enumerate(ising_params): if param_encoding: cost += cost_function_single(thetas, L, num_trash, p, shots, vqe, param_encoding, x[i], meas_fitter=meas_fitter) else: cost += cost_function_single(thetas, L, num_trash, p, shots, vqe, param_encoding, meas_fitter=meas_fitter) return cost/n_samples def optimize(ising_params, L=6, num_trash=2, thetas=None, shots=1000, max_iter=400, vqe=True, param_encoding=False, x=0, pick_optimizer = None, meas_fitter=None): if thetas is None: n_params = (2*L+2)*2 if param_encoding else (2*L+2) thetas = np.random.uniform(0, 2*np.pi, n_params) # initial parameters without feature encoding print("Initial cost: {:.3f}".format(cost_function(thetas, L, num_trash, ising_params, shots, vqe, param_encoding, x))) counts, values, accepted = [], [], [] def store_intermediate_result(eval_count, parameters, mean, std, ac): # counts.append(eval_count) values.append(mean) accepted.append(ac) # Initialize optimizer if pick_optimizer == "cobyla": optimizer = COBYLA(maxiter=max_iter, tol=0.0001) if pick_optimizer == "adam" or pick_optimizer == "ADAM": optimizer = qiskit.algorithms.optimizers.ADAM(maxiter=max_iter) # optimizer = L_BFGS_B(maxfun=300, maxiter=max_iter)#, factr=10, iprint=- 1, epsilon=1e-08) if pick_optimizer == "spsa" or pick_optimizer == None: optimizer = SPSA(maxiter=max_iter, #blocking=True, callback=store_intermediate_result, learning_rate=0.3, perturbation=0.1 ) # recommended from qiskit (first iteraction takes quite long) # to reduce time figure out optimal learning rate and perturbation in advance start_time = time.time() ret = optimizer.optimize( num_vars=len(thetas), objective_function=(lambda thetas: cost_function(thetas, L, num_trash, ising_params, shots, vqe, param_encoding, x, meas_fitter=meas_fitter)), initial_point=thetas ) print("Time: {:.5f} sec".format(time.time()-start_time)) print(ret) return ret[0], values, accepted def run_inference(thetas, shots=1000, L=5, meas_fitter=None): points = 50 J = -1.0 x,y = np.meshgrid(gx_vals, gz_vals) cost = np.zeros((len(gx_vals) * len(gz_vals))) Smags = np.zeros((len(gx_vals) * len(gz_vals))) shots = 1000 for i,p in enumerate(list(zip(gxs, gzs))): t0 = datetime.datetime.now() cost[i] = cost_function_single(thetas, L, num_trash, i, shots=shots, meas_fitter=meas_fitter) if not i%verbose: print(f"{i+1} / {len(opt_params)}, gx = {gx:.2f}, gz = {gz:.2f}, time : {verbose*(datetime.datetime.now() - t0)}") cost = cost.reshape((len(gx_vals), len(gz_vals))) return cost phys_params = [-1] thetas_guess = np.load(filename_simulated_thetas, allow_pickle=True)["thetas_mitigated"] # Training thetas_opt_mitigated, loss, accepted = optimize(phys_params, thetas = thetas_guess, max_iter=30, L=5,meas_fitter=meas_fitter) #, pick_optimizer="adam") plt.plot(loss) # Inference cost_mitigated = np.zeros((len(gx_vals))) shots = 1000 for i,p in enumerate(list(zip(gxs, gzs))): t0 = datetime.datetime.now() cost_mitigated[i] = cost_function_single(thetas_opt_mitigated, L, num_trash, i, shots=shots, meas_fitter=meas_fitter) # np.random.uniform(0, 2*np.pi, 2*L+2) random parameters to check if training "does" something - result was: with random paremters just get noise, so yes, it "does" something if not i%verbose: print(f"{i+1} / {len(opt_params)}, gx = {p[0]:.2f}, gz = {p[1]:.2f}, time : {verbose*(datetime.datetime.now() - t0)}") "data/" + name + "_thetas-loss-cost_run2" np.savez("data/" + name + "_thetas-loss-cost_run2", cost_mitigated=cost_mitigated, thetas_mitigated=thetas_opt_mitigated, ) fig, ax = plt.subplots(ncols=1,figsize=(6,5)) ax.set_title("Mitigated results") cost = np.load("data/" + name + "_thetas-loss-cost_run2.npz", allow_pickle=True)["cost_mitigated"] ax.plot(gx_list, cost,".:", label="raw output") ax.plot(gx_list, abs(Qmags),"x--", color="tab:orange", label="Qmag") ax.set_xscale("log") for p in phys_params: ax.plot(gx_list[p],cost[p],"o",alpha=0.3,color="magenta")
https://github.com/Qottmann/Quantum-anomaly-detection
Qottmann
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Utils for using with Qiskit unit tests.""" import logging import os import unittest from enum import Enum from qiskit import __path__ as qiskit_path class Path(Enum): """Helper with paths commonly used during the tests.""" # Main SDK path: qiskit/ SDK = qiskit_path[0] # test.python path: qiskit/test/python/ TEST = os.path.normpath(os.path.join(SDK, '..', 'test', 'python')) # Examples path: examples/ EXAMPLES = os.path.normpath(os.path.join(SDK, '..', 'examples')) # Schemas path: qiskit/schemas SCHEMAS = os.path.normpath(os.path.join(SDK, 'schemas')) # VCR cassettes path: qiskit/test/cassettes/ CASSETTES = os.path.normpath(os.path.join(TEST, '..', 'cassettes')) # Sample QASMs path: qiskit/test/python/qasm QASMS = os.path.normpath(os.path.join(TEST, 'qasm')) def setup_test_logging(logger, log_level, filename): """Set logging to file and stdout for a logger. Args: logger (Logger): logger object to be updated. log_level (str): logging level. filename (str): name of the output file. """ # Set up formatter. log_fmt = ('{}.%(funcName)s:%(levelname)s:%(asctime)s:' ' %(message)s'.format(logger.name)) formatter = logging.Formatter(log_fmt) # Set up the file handler. file_handler = logging.FileHandler(filename) file_handler.setFormatter(formatter) logger.addHandler(file_handler) # Set the logging level from the environment variable, defaulting # to INFO if it is not a valid level. level = logging._nameToLevel.get(log_level, logging.INFO) logger.setLevel(level) class _AssertNoLogsContext(unittest.case._AssertLogsContext): """A context manager used to implement TestCase.assertNoLogs().""" # pylint: disable=inconsistent-return-statements def __exit__(self, exc_type, exc_value, tb): """ This is a modified version of TestCase._AssertLogsContext.__exit__(...) """ self.logger.handlers = self.old_handlers self.logger.propagate = self.old_propagate self.logger.setLevel(self.old_level) if exc_type is not None: # let unexpected exceptions pass through return False if self.watcher.records: msg = 'logs of level {} or higher triggered on {}:\n'.format( logging.getLevelName(self.level), self.logger.name) for record in self.watcher.records: msg += 'logger %s %s:%i: %s\n' % (record.name, record.pathname, record.lineno, record.getMessage()) self._raiseFailure(msg)
https://github.com/Qottmann/Quantum-anomaly-detection
Qottmann
import time import datetime import numpy as np from matplotlib import pyplot as plt import qiskit from qiskit import * from qiskit.opflow import X,Z,I from qiskit.opflow.state_fns import StateFn, CircuitStateFn from qiskit.providers.aer import StatevectorSimulator, AerSimulator from qiskit.algorithms import VQE from qiskit.algorithms.optimizers import COBYLA, SLSQP, SPSA from scipy import sparse import scipy.sparse.linalg.eigen.arpack as arp from modules.utils import * gz = 0 anti = 1 gx = 1e-1 L = 5 num_trash = 2 name = f"qsim_params_VQE_Ising_L{L:.0f}_anti_{anti:.0f}_single-jobs" filename = 'data/' + name print(filename) # more in-depth noise models https://qiskit.org/documentation/tutorials/simulators/2_device_noise_simulation.html #backend = qiskit.Aer.get_backend('qasm_simulator') # apparently outdated (legacy) IBMQ.load_account() # this then automatically loads your saved account provider = IBMQ.get_provider(hub='ibm-q-research') from qiskit.providers.ibmq import least_busy small_devices = provider.backends(filters=lambda x: x.configuration().n_qubits == 5 and not x.configuration().simulator) least_busy(small_devices) #provider.backends(simulator=False, operational=True) backend = least_busy(small_devices) backend backend.status().pending_jobs backend_sim = qiskit.providers.aer.AerSimulator.from_backend(backend) ansatz = qiskit.circuit.library.EfficientSU2(L, reps=3) ansatz = qiskit.transpile(ansatz, backend) #optimizer = SLSQP(maxiter=1000) #optimizer = COBYLA(maxiter=1000) optimizer = SPSA(maxiter=1000) vqe = VQE(ansatz, optimizer, quantum_instance=backend) from qiskit.tools.monitor import job_monitor # Number of shots to run the program (experiment); # maximum is 8192 shots. shots = 1024 # Maximum number of credits to spend on executions. max_credits = 3 job_exp = execute(qc, backend, shots=shots, max_credits=max_credits) job_monitor(job_exp) t0 = datetime.datetime.now() H = QHIsing(L,anti,np.float32(gx),np.float32(gz)) result = vqe.compute_minimum_eigenvalue(H, aux_operators=[QMag(L,anti)]) #ED with Qiskit VQE print(f"elapsed time {datetime.datetime.now()-t0}") # ED ED_state, E, ham = ising_groundstate(L, anti, np.float32(gx), np.float32(gz)) print(f"ED energy: {E} ;; VQE energy: {result.eigenvalue}") print(f"ED mag: {ED_state.T.conj()@Mag(L,anti)@ED_state} ;; VQE mag: {result.aux_operator_eigenvalues}") phis = [sort_params(result.optimal_parameters)] # needs to be called phis for later vqe2 = VQE(qiskit.circuit.library.EfficientSU2(L, reps=3), optimizer, quantum_instance=StatevectorSimulator()) t0 = datetime.datetime.now() result2 = vqe2.compute_minimum_eigenvalue(H, aux_operators=[QMag(L,anti)]) #ED with Qiskit VQE print(f"elapsed time {datetime.datetime.now()-t0}") phis = [] phis.append(sort_params(result2.optimal_parameters)) state = init_vqe(phis[-1], L=L) state = qiskit.transpile(state, backend) meas_outcome = ~StateFn(QMag(L,anti)) @ StateFn(state) Qmag2 = meas_outcome.eval() e_outcome = ~StateFn(H) @ StateFn(state) Qen2 = e_outcome.eval() print(f"ED energy: {E} ;; VQE energy: {result.eigenvalue} ;; VQE energy from simulated: {result2.eigenvalue} ;; VQE simualted but real execution: {Qen2}") print(f"ED mag: {ED_state.T.conj()@Mag(L,anti)@ED_state} ;; VQE mag: {result.aux_operator_eigenvalues} ;; VQE magfrom simulated: {result2.aux_operator_eigenvalues} ;; VQE simualted but real execution: {Qmag2}") ############################################################################## ### II - Training ########################################################### ############################################################################## thetas = np.random.uniform(0, 2*np.pi, 2*L+2) # initial parameters without feature encoding # thetas = np.random.uniform(0, 2*np.pi, (2*L+2, 2)) # initial parameters with feature encoding # linear entangler (as in scales linearly with trash qubits) def get_entangler_map(L, num_trash, i_permut=1): result = [] nums = list(range(L)) # here was the problem, it doesnt like when list elements are taken from numpy nums_compressed = nums.copy()[:L-num_trash] nums_trash = nums.copy()[-num_trash:] #print(nums, nums_compressed, nums_trash) # combine all trash qubits with themselves for trash_q in nums_trash[:-1]: result.append((trash_q+1,trash_q)) # combine each of the trash qubits with every n-th repeated = list(nums_trash) * (L-num_trash) # repeat the list of trash indices cyclicly for i in range(L-num_trash): result.append((repeated[i_permut + i], nums_compressed[i])) return result def QAE_Ansatz(thetas, L, num_trash, insert_barriers=False, parametrized_gate = "ry", entangling_gate = "cz"): entanglement = [get_entangler_map(L,num_trash,i_permut) for i_permut in range(num_trash)] circ = qiskit.circuit.library.TwoLocal(L, parametrized_gate, entangling_gate, entanglement, reps=num_trash, insert_barriers=insert_barriers, skip_final_rotation_layer=True ).assign_parameters(thetas[:-num_trash]) if insert_barriers: circ.barrier() for i in range(num_trash): circ.ry(thetas[L-i-1], L-i-1) #circ.ry(circuit.Parameter(f'θ{i}'), L-i-1) return circ def prepare_circuit(thetas, L=6, num_trash=2, init_state=None, measurement=True, vqe=True): qreg = QuantumRegister(L, 'q') creg = ClassicalRegister(num_trash, 'c') circ = QuantumCircuit(qreg, creg) circ += QAE_Ansatz(thetas, L, num_trash, insert_barriers=True)#.assign_parameters(thetas) # difference to bind? if measurement: for i in range(num_trash): circ.measure(qreg[L-i-1], creg[i]) if init_state is not None: if vqe: circ = init_vqe(init_state,L=L) + circ else: circ.initialize(init_state, qreg) return circ def run_circuit(thetas, L, num_trash, init_state, vqe=True, shots=1000, backend=backend): circ = prepare_circuit(thetas, L, num_trash, init_state, vqe=vqe) circ = qiskit.transpile(circ, backend) # Execute the circuit on the qasm simulator. job_sim = execute(circ, backend, shots=shots, seed_simulator=123, seed_transpiler=234) # fix seed to make it reproducible return job_sim phi = phis[0] circ = prepare_circuit(thetas, L, num_trash, phi) circ = qiskit.transpile(circ, backend) # Execute the circuit on the qasm simulator. job = execute(circ, backend, shots=shots) # fix seed to make it reproducible from qiskit.tools.monitor import job_monitor job_monitor(job) jobID = job.job_id() print('JOB ID: {}'.format(jobID)) #job_get=backend.retrieve_job(jobID) job_get=backend.retrieve_job(jobID) job_get job_get.result().get_counts() counts def cost_function_single(thetas, L, num_trash, p, shots=1000, vqe=True, param_encoding=False, x=0): """ Optimizes circuit """ if vqe: init_state = phis[p] else: J, gx, gz = p init_state, _ = ising_groundstate(L, J, gx, gz) if param_encoding: thetas = feature_encoding(thetas, x) out = run_circuit(thetas, L, num_trash, init_state, vqe=vqe, shots=shots).result().get_counts() cost = out.get('11', 0)*2 + out.get('01', 0) + out.get('10', 0) return cost/shots def cost_function(thetas, L, num_trash, ising_params, shots=1000, vqe=True, param_encoding=False, x=0): """ Optimizes circuit """ cost = 0. n_samples = len(ising_params) for i, p in enumerate(ising_params): if param_encoding: cost += cost_function_single(thetas, L, num_trash, p, shots, vqe, param_encoding, x[i]) else: cost += cost_function_single(thetas, L, num_trash, p, shots, vqe, param_encoding) return cost/n_samples def optimize(ising_params, L=6, num_trash=2, thetas=None, shots=1000, max_iter=400, vqe=True, param_encoding=False, x=0, pick_optimizer = None): if thetas is None: n_params = (2*L+2)*2 if param_encoding else (2*L+2) thetas = np.random.uniform(0, 2*np.pi, n_params) # initial parameters without feature encoding print("Initial cost: {:.3f}".format(cost_function(thetas, L, num_trash, ising_params, shots, vqe, param_encoding, x))) counts, values, accepted = [], [], [] def store_intermediate_result(eval_count, parameters, mean, std, ac): # counts.append(eval_count) values.append(mean) accepted.append(ac) # Initialize optimizer if pick_optimizer == "cobyla": optimizer = COBYLA(maxiter=max_iter, tol=0.0001) if pick_optimizer == "adam" or pick_optimizer == "ADAM": optimizer = qiskit.algorithms.optimizers.ADAM(maxiter=max_iter) # optimizer = L_BFGS_B(maxfun=300, maxiter=max_iter)#, factr=10, iprint=- 1, epsilon=1e-08) if pick_optimizer == "spsa" or pick_optimizer == None: optimizer = SPSA(maxiter=max_iter, #blocking=True, callback=store_intermediate_result, #learning_rate=1e-1, #perturbation=0.4 ) # recommended from qiskit (first iteraction takes quite long) # to reduce time figure out optimal learning rate and perturbation in advance start_time = time.time() ret = optimizer.optimize( num_vars=len(thetas), objective_function=(lambda thetas: cost_function(thetas, L, num_trash, ising_params, shots, vqe, param_encoding, x)), initial_point=thetas ) print("Time: {:.5f} sec".format(time.time()-start_time)) print(ret) return ret[0], values, accepted def run_inference(thetas, shots=1000, L=5): cost = np.zeros((len(gx_vals))) shots = 1000 for i,p in enumerate(list(zip(gxs, gzs))): cost[i] = cost_function_single(thetas, L, num_trash, i, shots=shots) return cost # from the original vqe calculated state thetas, loss, accepted = optimize([0], max_iter=100, L=5) #, pick_optimizer="adam") plt.plot(loss) # using the VQE parameters from simulation thetas, loss, accepted = optimize([1], max_iter=100, L=5) #, pick_optimizer="adam") plt.plot(loss)
https://github.com/Qottmann/Quantum-anomaly-detection
Qottmann
import time import datetime import numpy as np from matplotlib import pyplot as plt import qiskit from qiskit import * from qiskit.opflow import X,Z,I from qiskit.opflow.state_fns import StateFn, CircuitStateFn from qiskit.providers.aer import StatevectorSimulator, AerSimulator from qiskit.algorithms import VQE from qiskit.algorithms.optimizers import COBYLA, SLSQP, SPSA from scipy import sparse import scipy.sparse.linalg.eigen.arpack as arp from modules.utils import * gz = 0 anti = 1 gx = 1e-1 L = 5 num_trash = 2 name = f"qsim_params_VQE_Ising_L{L:.0f}_anti_{anti:.0f}_single-jobs" filename = 'data/' + name print(filename) gx_vals = np.logspace(-2,2,logspace_size) # more in-depth noise models https://qiskit.org/documentation/tutorials/simulators/2_device_noise_simulation.html #backend = qiskit.Aer.get_backend('qasm_simulator') # apparently outdated (legacy) IBMQ.load_account() # this then automatically loads your saved account provider = IBMQ.get_provider(hub='ibm-q-research') real_backend = provider.backends(simulator=False, operational=True)[6] backend = qiskit.providers.aer.AerSimulator.from_backend(real_backend) backend_sim = backend ansatz = qiskit.circuit.library.EfficientSU2(L, reps=3) ansatz = qiskit.transpile(ansatz, backend) #optimizer = SLSQP(maxiter=1000) #optimizer = COBYLA(maxiter=1000) optimizer = SPSA(maxiter=1000) vqe = VQE(ansatz, optimizer, quantum_instance=backend) t0 = datetime.datetime.now() H = QHIsing(L,anti,np.float32(gx),np.float32(gz)) result = vqe.compute_minimum_eigenvalue(H, aux_operators=[QMag(L,anti)]) #ED with Qiskit VQE print(f"elapsed time {datetime.datetime.now()-t0}") # ED ED_state, E, ham = ising_groundstate(L, anti, np.float32(gx), np.float32(gz)) print(f"ED energy: {E} ;; VQE energy: {result.eigenvalue}") print(f"ED mag: {ED_state.T.conj()@Mag(L,anti)@ED_state} ;; VQE mag: {result.aux_operator_eigenvalues}") phis = [sort_params(result.optimal_parameters)] # needs to be called phis for later vqe2 = VQE(qiskit.circuit.library.EfficientSU2(L, reps=3), optimizer, quantum_instance=StatevectorSimulator()) t0 = datetime.datetime.now() result2 = vqe2.compute_minimum_eigenvalue(H, aux_operators=[QMag(L,anti)]) #ED with Qiskit VQE print(f"elapsed time {datetime.datetime.now()-t0}") phis.append(sort_params(result2.optimal_parameters)) state = init_vqe(phis[-1], L=L) state state = init_vqe(phis[-1], L=L) state = qiskit.transpile(state, backend) meas_outcome = ~StateFn(QMag(L,anti)) @ StateFn(state) Qmag2 = meas_outcome.eval() e_outcome = ~StateFn(H) @ StateFn(state) Qen2 = e_outcome.eval() print(f"ED energy: {E} ;; VQE energy: {result.eigenvalue} ;; VQE energy from simulated: {result2.eigenvalue} ;; VQE simualted but real execution: {Qen2}") print(f"ED mag: {ED_state.T.conj()@Mag(L,anti)@ED_state} ;; VQE mag: {result.aux_operator_eigenvalues} ;; VQE magfrom simulated: {result2.aux_operator_eigenvalues} ;; VQE simualted but real execution: {Qmag2}") ############################################################################## ### II - Training ########################################################### ############################################################################## thetas = np.random.uniform(0, 2*np.pi, 2*L+2) # initial parameters without feature encoding # thetas = np.random.uniform(0, 2*np.pi, (2*L+2, 2)) # initial parameters with feature encoding # linear entangler (as in scales linearly with trash qubits) def get_entangler_map(L, num_trash, i_permut=1): result = [] nums = list(range(L)) # here was the problem, it doesnt like when list elements are taken from numpy nums_compressed = nums.copy()[:L-num_trash] nums_trash = nums.copy()[-num_trash:] #print(nums, nums_compressed, nums_trash) # combine all trash qubits with themselves for trash_q in nums_trash[:-1]: result.append((trash_q+1,trash_q)) # combine each of the trash qubits with every n-th repeated = list(nums_trash) * (L-num_trash) # repeat the list of trash indices cyclicly for i in range(L-num_trash): result.append((repeated[i_permut + i], nums_compressed[i])) return result def QAE_Ansatz(thetas, L, num_trash, insert_barriers=False, parametrized_gate = "ry", entangling_gate = "cz"): entanglement = [get_entangler_map(L,num_trash,i_permut) for i_permut in range(num_trash)] circ = qiskit.circuit.library.TwoLocal(L, parametrized_gate, entangling_gate, entanglement, reps=num_trash, insert_barriers=insert_barriers, skip_final_rotation_layer=True ).assign_parameters(thetas[:-num_trash]) if insert_barriers: circ.barrier() for i in range(num_trash): circ.ry(thetas[L-i-1], L-i-1) #circ.ry(circuit.Parameter(f'θ{i}'), L-i-1) return circ def prepare_circuit(thetas, L=6, num_trash=2, init_state=None, measurement=True, vqe=True): qreg = QuantumRegister(L, 'q') creg = ClassicalRegister(num_trash, 'c') circ = QuantumCircuit(qreg, creg) circ += QAE_Ansatz(thetas, L, num_trash, insert_barriers=True)#.assign_parameters(thetas) # difference to bind? if measurement: for i in range(num_trash): circ.measure(qreg[L-i-1], creg[i]) if init_state is not None: if vqe: circ = init_vqe(init_state,L=L) + circ else: circ.initialize(init_state, qreg) return circ def run_circuit(thetas, L, num_trash, init_state, vqe=True, shots=1000, backend=backend): circ = prepare_circuit(thetas, L, num_trash, init_state, vqe=vqe) circ = qiskit.transpile(circ, backend) # Execute the circuit on the qasm simulator. job_sim = execute(circ, backend_sim, shots=shots, seed_simulator=123, seed_transpiler=234) # fix seed to make it reproducible return job_sim phi = phis[0] job = run_circuit(thetas, L, num_trash, phi) counts = job.result().get_counts() counts def cost_function_single(thetas, L, num_trash, p, shots=1000, vqe=True, param_encoding=False, x=0): """ Optimizes circuit """ if vqe: init_state = phis[p] else: J, gx, gz = p init_state, _ = ising_groundstate(L, J, gx, gz) if param_encoding: thetas = feature_encoding(thetas, x) out = run_circuit(thetas, L, num_trash, init_state, vqe=vqe, shots=shots).result().get_counts() cost = out.get('11', 0)*2 + out.get('01', 0) + out.get('10', 0) return cost/shots def cost_function(thetas, L, num_trash, ising_params, shots=1000, vqe=True, param_encoding=False, x=0): """ Optimizes circuit """ cost = 0. n_samples = len(ising_params) for i, p in enumerate(ising_params): if param_encoding: cost += cost_function_single(thetas, L, num_trash, p, shots, vqe, param_encoding, x[i]) else: cost += cost_function_single(thetas, L, num_trash, p, shots, vqe, param_encoding) return cost/n_samples def optimize(ising_params, L=6, num_trash=2, thetas=None, shots=1000, max_iter=400, vqe=True, param_encoding=False, x=0, pick_optimizer = None): if thetas is None: n_params = (2*L+2)*2 if param_encoding else (2*L+2) thetas = np.random.uniform(0, 2*np.pi, n_params) # initial parameters without feature encoding print("Initial cost: {:.3f}".format(cost_function(thetas, L, num_trash, ising_params, shots, vqe, param_encoding, x))) counts, values, accepted = [], [], [] def store_intermediate_result(eval_count, parameters, mean, std, ac): # counts.append(eval_count) values.append(mean) accepted.append(ac) # Initialize optimizer if pick_optimizer == "cobyla": optimizer = COBYLA(maxiter=max_iter, tol=0.0001) if pick_optimizer == "adam" or pick_optimizer == "ADAM": optimizer = qiskit.algorithms.optimizers.ADAM(maxiter=max_iter) # optimizer = L_BFGS_B(maxfun=300, maxiter=max_iter)#, factr=10, iprint=- 1, epsilon=1e-08) if pick_optimizer == "spsa" or pick_optimizer == None: optimizer = SPSA(maxiter=max_iter, #blocking=True, callback=store_intermediate_result, #learning_rate=1e-1, #perturbation=0.4 ) # recommended from qiskit (first iteraction takes quite long) # to reduce time figure out optimal learning rate and perturbation in advance start_time = time.time() ret = optimizer.optimize( num_vars=len(thetas), objective_function=(lambda thetas: cost_function(thetas, L, num_trash, ising_params, shots, vqe, param_encoding, x)), initial_point=thetas ) print("Time: {:.5f} sec".format(time.time()-start_time)) print(ret) return ret[0], values, accepted def run_inference(thetas, shots=1000, L=5): cost = np.zeros((len(gx_vals))) shots = 1000 for i,p in enumerate(list(zip(gxs, gzs))): cost[i] = cost_function_single(thetas, L, num_trash, i, shots=shots) return cost # from the original vqe calculated state thetas, loss, accepted = optimize([0], max_iter=100, L=5) #, pick_optimizer="adam") plt.plot(loss) # using the VQE parameters from simulation thetas, loss, accepted = optimize([1], max_iter=100, L=5) #, pick_optimizer="adam") plt.plot(loss)
https://github.com/Qottmann/Quantum-anomaly-detection
Qottmann
import time import datetime import numpy as np from matplotlib import pyplot as plt import qiskit from qiskit import * from qiskit.opflow import X,Z,I from qiskit.opflow.state_fns import StateFn, CircuitStateFn from qiskit.providers.aer import StatevectorSimulator, AerSimulator from qiskit.algorithms import VQE from qiskit.algorithms.optimizers import COBYLA, SLSQP, SPSA from qiskit.opflow import CircuitSampler from qiskit.ignis.mitigation.measurement import CompleteMeasFitter # you will need to pip install qiskit-ignis from scipy import sparse import scipy.sparse.linalg.eigen.arpack as arp from modules.utils import * IBMQ.load_account() # this then automatically loads your saved account provider = IBMQ.get_provider(hub='ibm-q-research') device = provider.backend.ibmq_rome print(device) #backend = device backend = qiskit.providers.aer.AerSimulator.from_backend(device) coupling_map = device.configuration().coupling_map noise_model = qiskit.providers.aer.noise.NoiseModel.from_backend(device) basis_gates = noise_model.basis_gates #aqua_globals.random_seed = seed qi = qiskit.utils.QuantumInstance(backend=backend, # , seed_simulator=seed, seed_transpiler=seed coupling_map=coupling_map, noise_model=noise_model, measurement_error_mitigation_cls= CompleteMeasFitter, cals_matrix_refresh_period=30 #How often to refresh the calibration matrix in measurement mitigation. in minutes ) # linear entangler (as in scales linearly with trash qubits) def get_entangler_map(L, num_trash, i_permut=1): result = [] nums = list(range(L)) # here was the problem, it doesnt like when list elements are taken from numpy nums_compressed = nums.copy()[:L-num_trash] nums_trash = nums.copy()[-num_trash:] #print(nums, nums_compressed, nums_trash) # combine all trash qubits with themselves for trash_q in nums_trash[:-1]: result.append((trash_q+1,trash_q)) # combine each of the trash qubits with every n-th repeated = list(nums_trash) * (L-num_trash) # repeat the list of trash indices cyclicly for i in range(L-num_trash): result.append((repeated[i_permut + i], nums_compressed[i])) return result def QAE_Ansatz(thetas, L, num_trash, insert_barriers=False, parametrized_gate = "ry", entangling_gate = "cz"): entanglement = [get_entangler_map(L,num_trash,i_permut) for i_permut in range(num_trash)] circ = qiskit.circuit.library.TwoLocal(L, parametrized_gate, entangling_gate, entanglement, reps=num_trash, insert_barriers=insert_barriers, skip_final_rotation_layer=True ).assign_parameters(thetas[:-num_trash]) if insert_barriers: circ.barrier() for i in range(num_trash): circ.ry(thetas[L-i-1], L-i-1) #circ.ry(circuit.Parameter(f'θ{i}'), L-i-1) return circ def prepare_circuit(thetas, L=6, num_trash=2, init_state=None, measurement=True, vqe=True): qreg = QuantumRegister(L, 'q') creg = ClassicalRegister(num_trash, 'c') circ = QuantumCircuit(qreg, creg) circ += QAE_Ansatz(thetas, L, num_trash, insert_barriers=True)#.assign_parameters(thetas) # difference to bind? if measurement: for i in range(num_trash): circ.measure(qreg[L-i-1], creg[i]) if init_state is not None: if vqe: circ = init_vqe(init_state,L=L) + circ else: circ.initialize(init_state, qreg) return circ, qreg def feature_encoding(thetas, x): """ thetas: parameters to be optimized, x: Ising model parameter (eg. field) """ new_thetas = [] thetas = thetas.reshape((-1,2)) for theta in thetas: new_thetas.append(theta[0] * x + theta[1]) return new_thetas backend_sim = backend def run_circuit(thetas, L, num_trash, init_state, vqe=True, shots=100): circ, qreg = prepare_circuit(thetas, L, num_trash, init_state, vqe=vqe) # Execute the circuit on the qasm simulator. job_sim = execute(circ, backend_sim, shots=shots, seed_simulator=123, seed_transpiler=234) # fix seed to make it reproducible # Grab the results from the job. result_sim = job_sim.result() counts = result_sim.get_counts(circ) # print(counts) # mems = result_sim.get_memory(circ) # print(mems) return counts L = 5 num_trash = 2 phi = np.random.rand(40) thetas = np.random.uniform(0, 2*np.pi, 2*L+2) run_circuit(thetas, L, num_trash, phi)['11'] from qiskit.ignis.mitigation.measurement import complete_meas_cal circ, qreg = prepare_circuit(thetas, L, num_trash, phi) qubit_list = [L-i-1 for i in range(num_trash)] # only need to calibrate the trash qubits meas_calibs, state_labels = complete_meas_cal(qubit_list=qubit_list, qr=qreg, circlabel='mcal') job = qiskit.execute(meas_calibs, backend=backend, shots=1000, noise_model=noise_model) cal_results = job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') print(meas_fitter.cal_matrix) meas_fitter.plot_calibration() job_sim = execute(circ, backend, shots=1000) # fix seed to make it reproducible result = job_sim.result() # Results without mitigation raw_counts = result.get_counts() # Get the filter object meas_filter = meas_fitter.filter # Results with mitigation mitigated_results = meas_filter.apply(result) mitigated_counts = mitigated_results.get_counts(0) from qiskit.tools.visualization import * plot_histogram([raw_counts, mitigated_counts], legend=['raw', 'mitigated'])
https://github.com/Qottmann/Quantum-anomaly-detection
Qottmann
import time import itertools import numpy as np from scipy.optimize import minimize, basinhopping from qiskit import * from qiskit.quantum_info import Statevector from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B, SPSA from qiskit.opflow.state_fns import StateFn, CircuitStateFn from qiskit.providers.aer import StatevectorSimulator, AerSimulator import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator from matplotlib.colors import BoundaryNorm from modules.utils import * %matplotlib inline cmap = plt.get_cmap("plasma") #'viridis' import qiskit #%matplotlib inline print(qiskit.__version__) ### Preliminaries L = 5 num_trash = 3 logspace_size=50 name = f'VQE_Ising_L5_anti_-1_50x50' # _1e-3 # name of the data produced by this notebook filename = "data/params_" + name # name of the data file that is used L = 5 anti = -1. VQE_params = np.load(filename + ".npz", allow_pickle=True) gx_list = VQE_params['gx_list'] gz_list = VQE_params['gz_list'] opt_params = VQE_params['opt_params'] gx_vals = np.unique(gx_list) gz_vals = np.unique(gz_list) mag = QMag(L,anti) #magnetization operator (Qiskit) Smag = Mag(L,anti) #magnetization operator (numpy) # the ~ is the adjoint, but also it turns the is_measurement attribute to True ~StateFn(mag) # state is technically a circuit, that prepares the ground state via VQE circuit #state.draw() # uncomment to see, but is very long Qen=np.zeros(len(opt_params)); Sen=np.zeros(len(opt_params)) #energies Qmags=np.zeros(len(opt_params)); Smags=np.zeros(len(opt_params)) #magnetizations load = True if load: temp = np.load(filename + "_mags-Es.npz",allow_pickle=True) Qmags = temp["Qmags"] Qen = temp["Qen"] Sen = temp["Sen"] Smags = temp["Smags"] if not load: for j in range(len(opt_params)): gx = gx_list[j] gz = gz_list[j] H = QHIsing(L, anti, np.float32(gx), np.float32(gz)) # build Hamiltonian Op state = init_vqe(opt_params[j], L=L) StateFn(state) meas_outcome = ~StateFn(mag) @ StateFn(state) Qmags[j] = meas_outcome.eval() e_outcome = ~StateFn(H) @ StateFn(state) Qen[j] = e_outcome.eval() init_state, E, ham = ising_groundstate(L, anti, np.float(gx), np.float(gz)) Sen[j] = E Smags[j] = init_state.T.conj()@Smag@init_state #Magnetization with Numpy results np.savez(filename + "_mags-Es",Qmags=Qmags, Qen=Qen, Sen=Sen, Smags=Smags) # for large parameter space takes quite a while because of the exact diagonalization fig,ax = plt.subplots(figsize=(8,5)) cmap = plt.get_cmap("plasma") #'viridis' im = ax.pcolormesh(gz_vals, gx_vals, abs(Smags).reshape(len(gz_vals),len(gx_vals)), cmap=cmap) cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) plt.xscale("log") plt.yscale("log") ax.set_title("Magnetization ED L %.0f anti %.0f" %(L, anti),fontsize=20) ax.set_xlabel(r"$g_z$",fontsize=24) ax.set_ylabel(r"$g_x$",fontsize=24) ax.tick_params(labelsize=20) fig,ax = plt.subplots(figsize=(8,5)) cmap = plt.get_cmap("plasma") #'viridis' im = ax.pcolormesh(gz_vals, gx_vals, abs(Qmags).reshape(len(gz_vals),len(gx_vals)), cmap=cmap) cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) plt.xscale("log") plt.yscale("log") ax.set_title("Magnetization VQE L %.0f anti %.0f" %(L, anti),fontsize=20) ax.set_xlabel(r"$g_z$",fontsize=24) ax.set_ylabel(r"$g_x$",fontsize=24) ax.tick_params(labelsize=20) fig,ax = plt.subplots(figsize=(8,5)) cmap = plt.get_cmap("plasma") #'viridis' im = ax.pcolormesh(gz_vals, gx_vals, Sen.reshape(len(gz_vals),len(gx_vals)) - Qen.reshape(len(gz_vals),len(gx_vals)), cmap=cmap) cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) plt.xscale("log") plt.yscale("log") ax.set_title("Difference in energy L %.0f anti %.0f" %(L, anti),fontsize=20) ax.set_xlabel(r"$g_z$",fontsize=24) ax.set_ylabel(r"$g_x$",fontsize=24) ax.tick_params(labelsize=20) ############################################################################## ### II - Training ########################################################### ############################################################################## # Use Aer's qasm_simulator backend_sim = Aer.get_backend('qasm_simulator') thetas = np.random.uniform(0, 2*np.pi, num_trash*L+num_trash) # initial parameters without feature encoding # thetas = np.random.uniform(0, 2*np.pi, (2*L+2, 2)) # initial parameters with feature encoding # linear entangler (as in scales linearly with trash qubits) def get_entangler_map(L, num_trash, i_permut=1): result = [] nums = list(range(L)) # here was the problem, it doesnt like when list elements are taken from numpy nums_compressed = nums.copy()[:L-num_trash] nums_trash = nums.copy()[-num_trash:] #print(nums, nums_compressed, nums_trash) # combine all trash qubits with themselves for trash_q in nums_trash[:-1]: result.append((trash_q+1,trash_q)) # combine each of the trash qubits with every n-th repeated = list(nums_trash) * (L-num_trash) # repeat the list of trash indices cyclicly for i in range(L-num_trash): result.append((repeated[i_permut + i], nums_compressed[i])) return result def QAE_Ansatz(thetas, L, num_trash, insert_barriers=False, parametrized_gate = "ry", entangling_gate = "cz"): entanglement = [get_entangler_map(L,num_trash,i_permut) for i_permut in range(num_trash)] circ = qiskit.circuit.library.TwoLocal(L, parametrized_gate, entangling_gate, entanglement, reps=num_trash, insert_barriers=insert_barriers, skip_final_rotation_layer=True ).assign_parameters(thetas[:-num_trash]) if insert_barriers: circ.barrier() for i in range(num_trash): circ.ry(thetas[L-i-1], L-i-1) #circ.ry(circuit.Parameter(f'θ{i}'), L-i-1) return circ def prepare_circuit(thetas, L=5, num_trash=3, init_state=None, measurement=True, vqe=True): qreg = QuantumRegister(L, 'q') creg = ClassicalRegister(num_trash, 'c') circ = QuantumCircuit(qreg, creg) circ += QAE_Ansatz(thetas, L, num_trash, insert_barriers=True)#.assign_parameters(thetas) # difference to bind? if measurement: for i in range(num_trash): circ.measure(qreg[L-i-1], creg[i]) if init_state is not None: if vqe: circ = init_vqe(init_state,L=L) + circ else: circ.initialize(init_state, qreg) return circ def feature_encoding(thetas, x): """ thetas: parameters to be optimized, x: Ising model parameter (eg. field) """ new_thetas = [] thetas = thetas.reshape((-1,2)) for theta in thetas: new_thetas.append(theta[0] * x + theta[1]) return new_thetas thetas.shape idx = 30 num_trash = 3 J, gx, gz = -1., gx_list[idx], gz_list[idx] # Ising parameters for which ground state should be compressed phi = opt_params[idx] # train on smallest lambda ;; this may grammatically be confusing, init_state = dictionary with unsorted parameters def run_circuit(thetas, L, num_trash, init_state, vqe=True, shots=100): circ = prepare_circuit(thetas, L, num_trash, init_state, vqe=vqe) # Execute the circuit on the qasm simulator. job_sim = execute(circ, backend_sim, shots=shots, seed_simulator=123, seed_transpiler=234) # fix seed to make it reproducible # Grab the results from the job. result_sim = job_sim.result() counts = result_sim.get_counts(circ) # print(counts) # mems = result_sim.get_memory(circ) # print(mems) return counts run_circuit(thetas, L, num_trash, phi)['11'] # translate to Rikes naming phis = opt_params gxs = gx_list gzs = gz_list def cost_function_single(thetas, L, num_trash, p, shots=1000, vqe=True, param_encoding=False, x=0): """ Optimizes circuit """ if vqe: init_state = phis[p] else: J, gx, gz = p init_state, _ = ising_groundstate(L, J, gx, gz) if param_encoding: thetas = feature_encoding(thetas, x) out = run_circuit(thetas, L, num_trash, init_state, vqe=vqe, shots=shots) cost = out.get('11', 0)*2 + out.get('01', 0) + out.get('10', 0) return cost/shots def cost_function(thetas, L, num_trash, ising_params, shots=1000, vqe=True, param_encoding=False, x=0): """ Optimizes circuit """ cost = 0. n_samples = len(ising_params) for i, p in enumerate(ising_params): if param_encoding: cost += cost_function_single(thetas, L, num_trash, p, shots, vqe, param_encoding, x[i]) else: cost += cost_function_single(thetas, L, num_trash, p, shots, vqe, param_encoding) return cost/n_samples def optimize(ising_params, L=6, num_trash=3, thetas=None, shots=1000, max_iter=400, vqe=True, param_encoding=False, x=0, pick_optimizer = None): if thetas is None: n_params = (2*L+2)*2 if param_encoding else (num_trash*L+num_trash) thetas = np.random.uniform(0, 2*np.pi, n_params) # initial parameters without feature encoding print(f"initial thetas: {thetas}") print("Initial cost: {:.3f}".format(cost_function(thetas, L, num_trash, ising_params, shots, vqe, param_encoding, x))) counts, values, accepted = [], [], [] def store_intermediate_result(eval_count, parameters, mean, std, ac): # counts.append(eval_count) values.append(mean) accepted.append(ac) # Initialize optimizer if pick_optimizer == "cobyla": optimizer = COBYLA(maxiter=max_iter, tol=0.0001) if pick_optimizer == "adam" or pick_optimizer == "ADAM": optimizer = qiskit.algorithms.optimizers.ADAM(maxiter=max_iter) # optimizer = L_BFGS_B(maxfun=300, maxiter=max_iter)#, factr=10, iprint=- 1, epsilon=1e-08) if pick_optimizer == "spsa" or pick_optimizer == None: optimizer = SPSA(maxiter=max_iter, #blocking=True, callback=store_intermediate_result, #learning_rate=1e-1, #perturbation=0.4 ) # recommended from qiskit (first iteraction takes quite long) # to reduce time figure out optimal learning rate and perturbation in advance start_time = time.time() ret = optimizer.optimize( num_vars=len(thetas), objective_function=(lambda thetas: cost_function(thetas, L, num_trash, ising_params, shots, vqe, param_encoding, x)), initial_point=thetas ) print("Time: {:.5f} sec".format(time.time()-start_time)) print(ret) return ret[0], values, accepted x,y = np.meshgrid(gx_vals, gz_vals) def run_inference(thetas, shots=1000, L=5): points = 50 J = -1.0 x,y = np.meshgrid(gx_vals, gz_vals) cost = np.zeros((len(gx_vals) * len(gz_vals))) Smags = np.zeros((len(gx_vals) * len(gz_vals))) shots = 1000 for i,p in enumerate(list(zip(gxs, gzs))): cost[i] = cost_function_single(thetas, L, num_trash, i, shots=shots) cost = cost.reshape((len(gx_vals), len(gz_vals))) return cost cmap = plt.get_cmap("plasma") def plot_result(cost): fig,axs = plt.subplots(ncols=2,figsize=(15,5)) nbins=100 ax = axs[0] im = ax.pcolormesh(x, y, cost, cmap=cmap, shading="auto") cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) ax.set_xscale("log") ax.set_yscale("log") ax.set_title(f"Loss",fontsize=20) ax.set_xlabel(r"$g_z$",fontsize=24) ax.set_ylabel(r"$g_x$",fontsize=24) ax.tick_params(labelsize=20) for p in params: gz = gz_list[p] gx = gx_list[p] ax.plot(gz,gx,"o",label="training",color="cyan") ax = axs[1] im = ax.pcolormesh(gz_vals, gx_vals, abs(Qmags).reshape(len(gz_vals),len(gx_vals)), cmap=cmap, shading="auto") cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) ax.set_xscale("log") ax.set_yscale("log") ax.set_title("Magnetization VQE L %.0f anti %.0f" %(L, anti),fontsize=20) ax.set_xlabel(r"$g_z$",fontsize=24) ax.set_ylabel(r"$g_x$",fontsize=24) ax.tick_params(labelsize=20) #reset random seed np.random.seed(123) from qiskit.utils import algorithm_globals algorithm_globals.random_seed = 123 np.intersect1d( np.intersect1d(np.where(gx_list > 5e-2),np.where(1e-1 > gx_list)), np.intersect1d(np.where(gz_list > 5e-2),np.where(1e-1 > gz_list)) ) paramss =[ [0], # train on bottom left point [0], ] for i,params in enumerate(paramss): print(f"{i+1} / {len(paramss)} - params (gz, gx) in {[(gzs[p], gxs[p]) for p in params]}") thetass = [None] * len(paramss) losss = [None] * len(paramss) costs = [None] * len(paramss) thetas.shape run_circuit(thetas, L=5, num_trash=3, init_state = phis[0]) optimize(paramss[0], num_trash=3,L=5,max_iter=100) for i,params in enumerate(paramss): print(f"{i+1} / {len(paramss)} - params (gz, gx) in {[(gzs[p], gxs[p]) for p in params]}") thetas, loss, accepted = optimize(params, num_trash=3, max_iter=100, L=5) #, pick_optimizer="adam") thetass[i], losss[i] = thetas, loss plt.plot(loss) cost = run_inference(thetas) costs[i] = cost filename2 = "data/" + name + "_thetas-loss-cost_vary-training-states_num_trash-3" np.savez(filename2, losss = losss, costs = costs, thetass = thetass) for i,params in enumerate(paramss): print(f"{i+1} / {len(paramss)} - params (gz, gx) in {[(gzs[p], gxs[p]) for p in params]}") plot_result(np.load(filename2 + ".npz",allow_pickle=True)["costs"][i]) plt.show()
https://github.com/Qottmann/Quantum-anomaly-detection
Qottmann
import time import itertools import numpy as np from scipy.optimize import minimize, basinhopping from qiskit import * from qiskit.quantum_info import Statevector from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B, SPSA from qiskit.opflow.state_fns import StateFn, CircuitStateFn from qiskit.providers.aer import StatevectorSimulator, AerSimulator import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator from matplotlib.colors import BoundaryNorm from modules.utils import * %matplotlib inline cmap = plt.get_cmap("plasma") #'viridis' import qiskit #%matplotlib inline print(qiskit.__version__) ### Preliminaries L = 5 num_trash = 2 logspace_size=50 name = f'VQE_Ising_L5_anti_-1_50x50_1e-3' # _1e-3 # name of the data produced by this notebook filename = "data/params_" + name # name of the data file that is used L = 5 anti = -1. VQE_params = np.load(filename + ".npz", allow_pickle=True) gx_list = VQE_params['gx_list'] gz_list = VQE_params['gz_list'] opt_params = VQE_params['opt_params'] gx_vals = np.unique(gx_list) gz_vals = np.unique(gz_list) mag = QMag(L,anti) #magnetization operator (Qiskit) Smag = Mag(L,anti) #magnetization operator (numpy) # the ~ is the adjoint, but also it turns the is_measurement attribute to True ~StateFn(mag) # state is technically a circuit, that prepares the ground state via VQE circuit #state.draw() # uncomment to see, but is very long Qen=np.zeros(len(opt_params)); Sen=np.zeros(len(opt_params)) #energies Qmags=np.zeros(len(opt_params)); Smags=np.zeros(len(opt_params)) #magnetizations load = True if load: temp = np.load(filename + "_mags-Es.npz",allow_pickle=True) Qmags = temp["Qmags"] Qen = temp["Qen"] Sen = temp["Sen"] Smags = temp["Smags"] if not load: for j in range(len(opt_params)): gx = gx_list[j] gz = gz_list[j] H = QHIsing(L, anti, np.float32(gx), np.float32(gz)) # build Hamiltonian Op state = init_vqe(opt_params[j], L=L) StateFn(state) meas_outcome = ~StateFn(mag) @ StateFn(state) Qmags[j] = meas_outcome.eval() e_outcome = ~StateFn(H) @ StateFn(state) Qen[j] = e_outcome.eval() init_state, E, ham = ising_groundstate(L, anti, np.float(gx), np.float(gz)) Sen[j] = E Smags[j] = init_state.T.conj()@Smag@init_state #Magnetization with Numpy results np.savez(filename + "_mags-Es",Qmags=Qmags, Qen=Qen, Sen=Sen, Smags=Smags) # for large parameter space takes quite a while because of the exact diagonalization fig,ax = plt.subplots(figsize=(8,5)) cmap = plt.get_cmap("plasma") #'viridis' im = ax.pcolormesh(gz_vals, gx_vals, abs(Smags).reshape(len(gz_vals),len(gx_vals)), cmap=cmap) cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) plt.xscale("log") plt.yscale("log") ax.set_title("Magnetization ED L %.0f anti %.0f" %(L, anti),fontsize=20) ax.set_xlabel(r"$g_z$",fontsize=24) ax.set_ylabel(r"$g_x$",fontsize=24) ax.tick_params(labelsize=20) fig,ax = plt.subplots(figsize=(8,5)) cmap = plt.get_cmap("plasma") #'viridis' im = ax.pcolormesh(gz_vals, gx_vals, abs(Qmags).reshape(len(gz_vals),len(gx_vals)), cmap=cmap) cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) plt.xscale("log") plt.yscale("log") ax.set_title("Magnetization VQE L %.0f anti %.0f" %(L, anti),fontsize=20) ax.set_xlabel(r"$g_z$",fontsize=24) ax.set_ylabel(r"$g_x$",fontsize=24) ax.tick_params(labelsize=20) fig,ax = plt.subplots(figsize=(8,5)) cmap = plt.get_cmap("plasma") #'viridis' im = ax.pcolormesh(gz_vals, gx_vals, Sen.reshape(len(gz_vals),len(gx_vals)) - Qen.reshape(len(gz_vals),len(gx_vals)), cmap=cmap) cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) plt.xscale("log") plt.yscale("log") ax.set_title("Difference in energy L %.0f anti %.0f" %(L, anti),fontsize=20) ax.set_xlabel(r"$g_z$",fontsize=24) ax.set_ylabel(r"$g_x$",fontsize=24) ax.tick_params(labelsize=20) ############################################################################## ### II - Training ########################################################### ############################################################################## # Use Aer's qasm_simulator backend_sim = Aer.get_backend('qasm_simulator') thetas = np.random.uniform(0, 2*np.pi, 2*L+2) # initial parameters without feature encoding # thetas = np.random.uniform(0, 2*np.pi, (2*L+2, 2)) # initial parameters with feature encoding # linear entangler (as in scales linearly with trash qubits) def get_entangler_map(L, num_trash, i_permut=1): result = [] nums = list(range(L)) # here was the problem, it doesnt like when list elements are taken from numpy nums_compressed = nums.copy()[:L-num_trash] nums_trash = nums.copy()[-num_trash:] #print(nums, nums_compressed, nums_trash) # combine all trash qubits with themselves for trash_q in nums_trash[:-1]: result.append((trash_q+1,trash_q)) # combine each of the trash qubits with every n-th repeated = list(nums_trash) * (L-num_trash) # repeat the list of trash indices cyclicly for i in range(L-num_trash): result.append((repeated[i_permut + i], nums_compressed[i])) return result def QAE_Ansatz(thetas, L, num_trash, insert_barriers=False, parametrized_gate = "ry", entangling_gate = "cz"): entanglement = [get_entangler_map(L,num_trash,i_permut) for i_permut in range(num_trash)] circ = qiskit.circuit.library.TwoLocal(L, parametrized_gate, entangling_gate, entanglement, reps=num_trash, insert_barriers=insert_barriers, skip_final_rotation_layer=True ).assign_parameters(thetas[:-num_trash]) if insert_barriers: circ.barrier() for i in range(num_trash): circ.ry(thetas[L-i-1], L-i-1) #circ.ry(circuit.Parameter(f'θ{i}'), L-i-1) return circ def prepare_circuit(thetas, L=6, num_trash=2, init_state=None, measurement=True, vqe=True): qreg = QuantumRegister(L, 'q') creg = ClassicalRegister(num_trash, 'c') circ = QuantumCircuit(qreg, creg) circ += QAE_Ansatz(thetas, L, num_trash, insert_barriers=True)#.assign_parameters(thetas) # difference to bind? if measurement: for i in range(num_trash): circ.measure(qreg[L-i-1], creg[i]) if init_state is not None: if vqe: circ = init_vqe(init_state,L=L) + circ else: circ.initialize(init_state, qreg) return circ def feature_encoding(thetas, x): """ thetas: parameters to be optimized, x: Ising model parameter (eg. field) """ new_thetas = [] thetas = thetas.reshape((-1,2)) for theta in thetas: new_thetas.append(theta[0] * x + theta[1]) return new_thetas idx = 30 num_trash = 2 J, gx, gz = -1., gx_list[idx], gz_list[idx] # Ising parameters for which ground state should be compressed phi = opt_params[idx] # train on smallest lambda ;; this may grammatically be confusing, init_state = dictionary with unsorted parameters def run_circuit(thetas, L, num_trash, init_state, vqe=True, shots=100): circ = prepare_circuit(thetas, L, num_trash, init_state, vqe=vqe) # Execute the circuit on the qasm simulator. job_sim = execute(circ, backend_sim, shots=shots, seed_simulator=123, seed_transpiler=234) # fix seed to make it reproducible # Grab the results from the job. result_sim = job_sim.result() counts = result_sim.get_counts(circ) # print(counts) # mems = result_sim.get_memory(circ) # print(mems) return counts run_circuit(thetas, L, num_trash, phi)['11'] # translate to Rikes naming phis = opt_params gxs = gx_list gzs = gz_list def cost_function_single(thetas, L, num_trash, p, shots=1000, vqe=True, param_encoding=False, x=0): """ Optimizes circuit """ if vqe: init_state = phis[p] else: J, gx, gz = p init_state, _ = ising_groundstate(L, J, gx, gz) if param_encoding: thetas = feature_encoding(thetas, x) out = run_circuit(thetas, L, num_trash, init_state, vqe=vqe, shots=shots) cost = out.get('11', 0)*2 + out.get('01', 0) + out.get('10', 0) return cost/shots def cost_function(thetas, L, num_trash, ising_params, shots=1000, vqe=True, param_encoding=False, x=0): """ Optimizes circuit """ cost = 0. n_samples = len(ising_params) for i, p in enumerate(ising_params): if param_encoding: cost += cost_function_single(thetas, L, num_trash, p, shots, vqe, param_encoding, x[i]) else: cost += cost_function_single(thetas, L, num_trash, p, shots, vqe, param_encoding) return cost/n_samples def optimize(ising_params, L=6, num_trash=2, thetas=None, shots=1000, max_iter=400, vqe=True, param_encoding=False, x=0, pick_optimizer = None): if thetas is None: n_params = (2*L+2)*2 if param_encoding else (2*L+2) thetas = np.random.uniform(0, 2*np.pi, n_params) # initial parameters without feature encoding print("Initial cost: {:.3f}".format(cost_function(thetas, L, num_trash, ising_params, shots, vqe, param_encoding, x))) counts, values, accepted = [], [], [] def store_intermediate_result(eval_count, parameters, mean, std, ac): # counts.append(eval_count) values.append(mean) accepted.append(ac) # Initialize optimizer if pick_optimizer == "cobyla": optimizer = COBYLA(maxiter=max_iter, tol=0.0001) if pick_optimizer == "adam" or pick_optimizer == "ADAM": optimizer = qiskit.algorithms.optimizers.ADAM(maxiter=max_iter) # optimizer = L_BFGS_B(maxfun=300, maxiter=max_iter)#, factr=10, iprint=- 1, epsilon=1e-08) if pick_optimizer == "spsa" or pick_optimizer == None: optimizer = SPSA(maxiter=max_iter, #blocking=True, callback=store_intermediate_result, #learning_rate=1e-1, #perturbation=0.4 ) # recommended from qiskit (first iteraction takes quite long) # to reduce time figure out optimal learning rate and perturbation in advance start_time = time.time() ret = optimizer.optimize( num_vars=len(thetas), objective_function=(lambda thetas: cost_function(thetas, L, num_trash, ising_params, shots, vqe, param_encoding, x)), initial_point=thetas ) print("Time: {:.5f} sec".format(time.time()-start_time)) print(ret) return ret[0], values, accepted x,y = np.meshgrid(gx_vals, gz_vals) def run_inference(thetas, shots=1000, L=5): points = 50 J = -1.0 x,y = np.meshgrid(gx_vals, gz_vals) cost = np.zeros((len(gx_vals) * len(gz_vals))) Smags = np.zeros((len(gx_vals) * len(gz_vals))) shots = 1000 for i,p in enumerate(list(zip(gxs, gzs))): cost[i] = cost_function_single(thetas, L, num_trash, i, shots=shots) cost = cost.reshape((len(gx_vals), len(gz_vals))) return cost cmap = plt.get_cmap("plasma") def plot_result(cost): fig,axs = plt.subplots(ncols=2,figsize=(15,5)) nbins=100 ax = axs[0] im = ax.pcolormesh(x, y, cost, cmap=cmap, shading="auto") cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) ax.set_xscale("log") ax.set_yscale("log") ax.set_title(f"Loss",fontsize=20) ax.set_xlabel(r"$g_z$",fontsize=24) ax.set_ylabel(r"$g_x$",fontsize=24) ax.tick_params(labelsize=20) for p in params: gz = gz_list[p] gx = gx_list[p] ax.plot(gz,gx,"o",label="training",color="cyan") ax = axs[1] im = ax.pcolormesh(gz_vals, gx_vals, Qmags.reshape(len(gz_vals),len(gx_vals)), cmap=cmap, shading="auto") cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) ax.set_xscale("log") ax.set_yscale("log") ax.set_title("Magnetization VQE L %.0f anti %.0f" %(L, anti),fontsize=20) ax.set_xlabel(r"$g_z$",fontsize=24) ax.set_ylabel(r"$g_x$",fontsize=24) ax.tick_params(labelsize=20) #reset random seed #np.random.seed(123) #from qiskit.utils import algorithm_globals #algorithm_globals.random_seed = 123 np.intersect1d( np.intersect1d(np.where(gx_list > 5e-2),np.where(1e-1 > gx_list)), np.intersect1d(np.where(gz_list > 5e-2),np.where(1e-1 > gz_list)) ) paramss =[ [0], # train on bottom left point ] for i,params in enumerate(paramss): print(f"{i} / {len(paramss)} - params (gz, gx) in {[(gzs[p], gxs[p]) for p in params]}") thetass = [None] * len(paramss) losss = [None] * len(paramss) costs = [None] * len(paramss) for i,params in enumerate(paramss): print(f"{i+1} / {len(paramss)} - params (gz, gx) in {[(gzs[p], gxs[p]) for p in params]}") thetas, loss, accepted = optimize(params, max_iter=50, L=5) #, pick_optimizer="adam") thetass[i], losss[i] = thetas, loss plt.plot(loss) cost = run_inference(thetas) costs[i] = cost filename2 = "data/" + name + "_thetas-loss-cost_vary-training-states-01" np.savez(filename2, losss = losss, costs = costs, thetass = thetass) for i,params in enumerate(paramss): print(f"{i+1} / {len(paramss)} - params (gz, gx) in {[(gzs[p], gxs[p]) for p in params]}") plot_result(np.load(filename2 + ".npz",allow_pickle=True)["costs"][i]) plt.show() for i,params in enumerate(paramss): print(f"{i+1} / {len(paramss)} - params (gz, gx) in {[(gzs[p], gxs[p]) for p in params]}") thetas, loss, accepted = optimize(params, max_iter=50, L=5) #, pick_optimizer="adam") thetass[i], losss[i] = thetas, loss plt.plot(loss) cost = run_inference(thetas) costs[i] = cost filename2 = "data/" + name + "_thetas-loss-cost_vary-training-states-02" np.savez(filename2, losss = losss, costs = costs, thetass = thetass) for i,params in enumerate(paramss): print(f"{i+1} / {len(paramss)} - params (gz, gx) in {[(gzs[p], gxs[p]) for p in params]}") plot_result(np.load(filename2 + ".npz",allow_pickle=True)["costs"][i]) plt.show()
https://github.com/Qottmann/Quantum-anomaly-detection
Qottmann
import time import itertools import numpy as np from scipy.optimize import minimize, basinhopping from qiskit import * from qiskit.quantum_info import Statevector from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B, SPSA from qiskit.opflow.state_fns import StateFn, CircuitStateFn from qiskit.providers.aer import StatevectorSimulator, AerSimulator import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator from matplotlib.colors import BoundaryNorm from modules.utils import * %matplotlib inline cmap = plt.get_cmap("plasma") #'viridis' import qiskit #%matplotlib inline print(qiskit.__version__) ### Preliminaries L = 5 num_trash = 2 logspace_size=50 name = f'VQE_Ising_L5_anti_-1_50x50' # _1e-3 # name of the data produced by this notebook filename = "data/params_" + name # name of the data file that is used L = 5 anti = -1. VQE_params = np.load(filename + ".npz", allow_pickle=True) gx_list = VQE_params['gx_list'] gz_list = VQE_params['gz_list'] opt_params = VQE_params['opt_params'] gx_vals = np.unique(gx_list) gz_vals = np.unique(gz_list) mag = QMag(L,anti) #magnetization operator (Qiskit) Smag = Mag(L,anti) #magnetization operator (numpy) # the ~ is the adjoint, but also it turns the is_measurement attribute to True ~StateFn(mag) # state is technically a circuit, that prepares the ground state via VQE circuit #state.draw() # uncomment to see, but is very long Qen=np.zeros(len(opt_params)); Sen=np.zeros(len(opt_params)) #energies Qmags=np.zeros(len(opt_params)); Smags=np.zeros(len(opt_params)) #magnetizations load = True if load: temp = np.load(filename + "_mags-Es.npz",allow_pickle=True) Qmags = temp["Qmags"] Qen = temp["Qen"] Sen = temp["Sen"] Smags = temp["Smags"] if not load: for j in range(len(opt_params)): gx = gx_list[j] gz = gz_list[j] H = QHIsing(L, anti, np.float32(gx), np.float32(gz)) # build Hamiltonian Op state = init_vqe(opt_params[j], L=L) StateFn(state) meas_outcome = ~StateFn(mag) @ StateFn(state) Qmags[j] = meas_outcome.eval() e_outcome = ~StateFn(H) @ StateFn(state) Qen[j] = e_outcome.eval() init_state, E, ham = ising_groundstate(L, anti, np.float(gx), np.float(gz)) Sen[j] = E Smags[j] = init_state.T.conj()@Smag@init_state #Magnetization with Numpy results np.savez(filename + "_mags-Es",Qmags=Qmags, Qen=Qen, Sen=Sen, Smags=Smags) # for large parameter space takes quite a while because of the exact diagonalization fig,ax = plt.subplots(figsize=(8,5)) cmap = plt.get_cmap("plasma") #'viridis' im = ax.pcolormesh(gz_vals, gx_vals, abs(Smags).reshape(len(gz_vals),len(gx_vals)), cmap=cmap) cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) plt.xscale("log") plt.yscale("log") ax.set_title("Magnetization ED L %.0f anti %.0f" %(L, anti),fontsize=20) ax.set_xlabel(r"$g_z$",fontsize=24) ax.set_ylabel(r"$g_x$",fontsize=24) ax.tick_params(labelsize=20) fig,ax = plt.subplots(figsize=(8,5)) cmap = plt.get_cmap("plasma") #'viridis' im = ax.pcolormesh(gz_vals, gx_vals, abs(Qmags).reshape(len(gz_vals),len(gx_vals)), cmap=cmap) cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) plt.xscale("log") plt.yscale("log") ax.set_title("Magnetization VQE L %.0f anti %.0f" %(L, anti),fontsize=20) ax.set_xlabel(r"$g_z$",fontsize=24) ax.set_ylabel(r"$g_x$",fontsize=24) ax.tick_params(labelsize=20) fig,ax = plt.subplots(figsize=(8,5)) cmap = plt.get_cmap("plasma") #'viridis' im = ax.pcolormesh(gz_vals, gx_vals, Sen.reshape(len(gz_vals),len(gx_vals)) - Qen.reshape(len(gz_vals),len(gx_vals)), cmap=cmap) cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) plt.xscale("log") plt.yscale("log") ax.set_title("Difference in energy L %.0f anti %.0f" %(L, anti),fontsize=20) ax.set_xlabel(r"$g_z$",fontsize=24) ax.set_ylabel(r"$g_x$",fontsize=24) ax.tick_params(labelsize=20) ############################################################################## ### II - Training ########################################################### ############################################################################## # Use Aer's qasm_simulator backend_sim = Aer.get_backend('qasm_simulator') thetas = np.random.uniform(0, 2*np.pi, 2*L+2) # initial parameters without feature encoding # thetas = np.random.uniform(0, 2*np.pi, (2*L+2, 2)) # initial parameters with feature encoding # linear entangler (as in scales linearly with trash qubits) def get_entangler_map(L, num_trash, i_permut=1): result = [] nums = list(range(L)) # here was the problem, it doesnt like when list elements are taken from numpy nums_compressed = nums.copy()[:L-num_trash] nums_trash = nums.copy()[-num_trash:] #print(nums, nums_compressed, nums_trash) # combine all trash qubits with themselves for trash_q in nums_trash[:-1]: result.append((trash_q+1,trash_q)) # combine each of the trash qubits with every n-th repeated = list(nums_trash) * (L-num_trash) # repeat the list of trash indices cyclicly for i in range(L-num_trash): result.append((repeated[i_permut + i], nums_compressed[i])) return result def QAE_Ansatz(thetas, L, num_trash, insert_barriers=False, parametrized_gate = "ry", entangling_gate = "cz"): entanglement = [get_entangler_map(L,num_trash,i_permut) for i_permut in range(num_trash)] circ = qiskit.circuit.library.TwoLocal(L, parametrized_gate, entangling_gate, entanglement, reps=num_trash, insert_barriers=insert_barriers, skip_final_rotation_layer=True ).assign_parameters(thetas[:-num_trash]) if insert_barriers: circ.barrier() for i in range(num_trash): circ.ry(thetas[L-i-1], L-i-1) #circ.ry(circuit.Parameter(f'θ{i}'), L-i-1) return circ def prepare_circuit(thetas, L=6, num_trash=2, init_state=None, measurement=True, vqe=True): qreg = QuantumRegister(L, 'q') creg = ClassicalRegister(num_trash, 'c') circ = QuantumCircuit(qreg, creg) circ += QAE_Ansatz(thetas, L, num_trash, insert_barriers=True)#.assign_parameters(thetas) # difference to bind? if measurement: for i in range(num_trash): circ.measure(qreg[L-i-1], creg[i]) if init_state is not None: if vqe: circ = init_vqe(init_state,L=L) + circ else: circ.initialize(init_state, qreg) return circ def feature_encoding(thetas, x): """ thetas: parameters to be optimized, x: Ising model parameter (eg. field) """ new_thetas = [] thetas = thetas.reshape((-1,2)) for theta in thetas: new_thetas.append(theta[0] * x + theta[1]) return new_thetas idx = 30 num_trash = 2 J, gx, gz = -1., gx_list[idx], gz_list[idx] # Ising parameters for which ground state should be compressed phi = opt_params[idx] # train on smallest lambda ;; this may grammatically be confusing, init_state = dictionary with unsorted parameters def run_circuit(thetas, L, num_trash, init_state, vqe=True, shots=100): circ = prepare_circuit(thetas, L, num_trash, init_state, vqe=vqe) # Execute the circuit on the qasm simulator. job_sim = execute(circ, backend_sim, shots=shots, seed_simulator=123, seed_transpiler=234) # fix seed to make it reproducible # Grab the results from the job. result_sim = job_sim.result() counts = result_sim.get_counts(circ) # print(counts) # mems = result_sim.get_memory(circ) # print(mems) return counts run_circuit(thetas, L, num_trash, phi)['11'] # translate to Rikes naming phis = opt_params gxs = gx_list gzs = gz_list def cost_function_single(thetas, L, num_trash, p, shots=1000, vqe=True, param_encoding=False, x=0): """ Optimizes circuit """ if vqe: init_state = phis[p] else: J, gx, gz = p init_state, _ = ising_groundstate(L, J, gx, gz) if param_encoding: thetas = feature_encoding(thetas, x) out = run_circuit(thetas, L, num_trash, init_state, vqe=vqe, shots=shots) cost = out.get('11', 0)*2 + out.get('01', 0) + out.get('10', 0) return cost/shots def cost_function(thetas, L, num_trash, ising_params, shots=1000, vqe=True, param_encoding=False, x=0): """ Optimizes circuit """ cost = 0. n_samples = len(ising_params) for i, p in enumerate(ising_params): if param_encoding: cost += cost_function_single(thetas, L, num_trash, p, shots, vqe, param_encoding, x[i]) else: cost += cost_function_single(thetas, L, num_trash, p, shots, vqe, param_encoding) return cost/n_samples def optimize(ising_params, L=6, num_trash=2, thetas=None, shots=1000, max_iter=400, vqe=True, param_encoding=False, x=0, pick_optimizer = None): if thetas is None: n_params = (2*L+2)*2 if param_encoding else (2*L+2) thetas = np.random.uniform(0, 2*np.pi, n_params) # initial parameters without feature encoding print("Initial cost: {:.3f}".format(cost_function(thetas, L, num_trash, ising_params, shots, vqe, param_encoding, x))) counts, values, accepted = [], [], [] def store_intermediate_result(eval_count, parameters, mean, std, ac): # counts.append(eval_count) values.append(mean) accepted.append(ac) # Initialize optimizer if pick_optimizer == "cobyla": optimizer = COBYLA(maxiter=max_iter, tol=0.0001) if pick_optimizer == "adam" or pick_optimizer == "ADAM": optimizer = qiskit.algorithms.optimizers.ADAM(maxiter=max_iter) # optimizer = L_BFGS_B(maxfun=300, maxiter=max_iter)#, factr=10, iprint=- 1, epsilon=1e-08) if pick_optimizer == "spsa" or pick_optimizer == None: optimizer = SPSA(maxiter=max_iter, #blocking=True, callback=store_intermediate_result, #learning_rate=1e-1, #perturbation=0.4 ) # recommended from qiskit (first iteraction takes quite long) # to reduce time figure out optimal learning rate and perturbation in advance start_time = time.time() ret = optimizer.optimize( num_vars=len(thetas), objective_function=(lambda thetas: cost_function(thetas, L, num_trash, ising_params, shots, vqe, param_encoding, x)), initial_point=thetas ) print("Time: {:.5f} sec".format(time.time()-start_time)) print(ret) return ret[0], values, accepted x,y = np.meshgrid(gx_vals, gz_vals) def run_inference(thetas, shots=1000, L=5): points = 50 J = -1.0 x,y = np.meshgrid(gx_vals, gz_vals) cost = np.zeros((len(gx_vals) * len(gz_vals))) Smags = np.zeros((len(gx_vals) * len(gz_vals))) shots = 1000 for i,p in enumerate(list(zip(gxs, gzs))): cost[i] = cost_function_single(thetas, L, num_trash, i, shots=shots) cost = cost.reshape((len(gx_vals), len(gz_vals))) return cost cmap = plt.get_cmap("plasma") def plot_result(cost): fig,axs = plt.subplots(ncols=2,figsize=(15,5)) nbins=100 ax = axs[0] im = ax.pcolormesh(x, y, cost, cmap=cmap, shading="auto") cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) ax.set_xscale("log") ax.set_yscale("log") ax.set_title(f"Loss",fontsize=20) ax.set_xlabel(r"$g_z$",fontsize=24) ax.set_ylabel(r"$g_x$",fontsize=24) ax.tick_params(labelsize=20) for p in params: gz = gz_list[p] gx = gx_list[p] ax.plot(gz,gx,"o",label="training",color="cyan") ax = axs[1] im = ax.pcolormesh(gz_vals, gx_vals, abs(Qmags).reshape(len(gz_vals),len(gx_vals)), cmap=cmap, shading="auto") cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) ax.set_xscale("log") ax.set_yscale("log") ax.set_title("Magnetization VQE L %.0f anti %.0f" %(L, anti),fontsize=20) ax.set_xlabel(r"$g_z$",fontsize=24) ax.set_ylabel(r"$g_x$",fontsize=24) ax.tick_params(labelsize=20) #reset random seed np.random.seed(123) from qiskit.utils import algorithm_globals algorithm_globals.random_seed = 123 np.intersect1d( np.intersect1d(np.where(gx_list > 5e-2),np.where(1e-1 > gx_list)), np.intersect1d(np.where(gz_list > 5e-2),np.where(1e-1 > gz_list)) ) paramss =[ [459], # train on bottom left point [460], [509], [560] ] for i,params in enumerate(paramss): print(f"{i} / {len(paramss)} - params (gz, gx) in {[(gzs[p], gxs[p]) for p in params]}") thetass = [None] * len(paramss) losss = [None] * len(paramss) costs = [None] * len(paramss) for i,params in enumerate(paramss): print(f"{i+1} / {len(paramss)} - params (gz, gx) in {[(gzs[p], gxs[p]) for p in params]}") thetas, loss, accepted = optimize(params, max_iter=100, L=5) #, pick_optimizer="adam") thetass[i], losss[i] = thetas, loss plt.plot(loss) cost = run_inference(thetas) costs[i] = cost filename2 = "data/" + name + "_thetas-loss-cost_vary-training-states" np.savez(filename2, losss = losss, costs = costs, thetass = thetass) for i,params in enumerate(paramss): print(f"{i+1} / {len(paramss)} - params (gz, gx) in {[(gzs[p], gxs[p]) for p in params]}") plot_result(np.load(filename2 + ".npz",allow_pickle=True)["costs"][i]) plt.show() for i,params in enumerate(paramss): print(f"{i+1} / {len(paramss)} - params (gz, gx) in {[(gzs[p], gxs[p]) for p in params]}") thetas, loss, accepted = optimize(params, max_iter=100, L=5, pick_optimizer="cobyla") #, pick_optimizer="adam") thetass[i], losss[i] = thetas, loss cost = run_inference(thetas) costs[i] = cost filename2 = "data/" + name + "_thetas-loss-cost_vary-training-states_cobyla" np.savez(filename2, losss = losss, costs = costs, thetass = thetass) for i,params in enumerate(paramss): print(f"{i+1} / {len(paramss)} - params (gz, gx) in {[(gzs[p], gxs[p]) for p in params]}") plot_result(np.load(filename2 + ".npz",allow_pickle=True)["costs"][i]) plt.show()
https://github.com/Qottmann/Quantum-anomaly-detection
Qottmann
import sys sys.path.insert(1, '..') # sets the import path to the parent folder import time import itertools import numpy as np import qiskit from qiskit import * from qiskit.quantum_info import Statevector from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B, SPSA from qiskit.opflow.state_fns import StateFn, CircuitStateFn from qiskit.providers.aer import StatevectorSimulator, AerSimulator from qiskit.opflow import CircuitSampler from qiskit.ignis.mitigation.measurement import CompleteMeasFitter # you will need to pip install qiskit-ignis from qiskit.ignis.mitigation.measurement import complete_meas_cal import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator from matplotlib.colors import BoundaryNorm cmap = plt.get_cmap("plasma") #'viridis' from modules.utils import * from qae import * import datetime from tenpy.networks.mps import MPS from tenpy.models.hubbard import BoseHubbardChain from tenpy.algorithms import dmrg from tenpy.linalg import np_conserved def DMRG_EBH(L, V, t_list, chi_max=30, bc_MPS='infinite'): model_params = dict(n_max=1, filling=0.5, bc_MPS=bc_MPS, t=t_list, L=L, V=V, mu=0, conserve='N') M = BoseHubbardChain(model_params) vector=[] for i in range(M.lat.N_sites): if i%2: vector.append(1) else: vector.append(0) psi = MPS.from_product_state(M.lat.mps_sites(), vector, bc=M.lat.bc_MPS) dmrg_params = { 'mixer': True, 'trunc_params': { 'chi_max': chi_max, }, 'max_E_err': 1.e-16, #'verbose': 0 } info = dmrg.run(psi, M, dmrg_params) return info['E'], psi print(qiskit.__version__, np.__version__) #IBMQ.load_account() # this then automatically loads your saved account #provider = IBMQ.get_provider(hub='ibm-q-research') #device = provider.backend.ibmq_rome # 6 bogota ; 4 rome ### Real device execution: #backend = device ### Simulation with noise profile from real device #backend = qiskit.providers.aer.AerSimulator.from_backend(device) ### Simulation without noise backend = qiskit.providers.aer.AerSimulator(method="matrix_product_state") #backend = StatevectorSimulator() ### Preliminaries L = 10 num_trash = 2 anti = 1 # 1 for ferromagnetic Ising model, -1 for antiferromagnet filename = "data/QAEAnsatz_scaling_MPS" V = 1 deltat=1 chi = 2**3 print("bond dimension : ", chi) t_list = np.ones(L-1) for i in range(len(t_list)): t_list[i] -= deltat*(-1)**i E0, psi0 = DMRG_EBH(L, V, t_list, chi_max=chi, bc_MPS='finite') thetas = np.random.rand(num_trash*(L+1)) QAE_circ = QAEAnsatz(num_qubits = L, num_trash_qubits= num_trash, trash_qubits_idxs = list(range(num_trash)), measure_trash=False).assign_parameters(thetas) QAE_circ.save_matrix_product_state(label="my_mps") result = backend.run(QAE_circ).result() #result.data(0)["my_mps"] [(_[0].shape, _[1].shape) for _ in result.data(0)["my_mps"][0]] [_.shape for _ in result.data(0)["my_mps"][1]] # G is only the local tensor (not multiplied by any singular values) - see https://tenpy.readthedocs.io/en/latest/reference/tenpy.networks.mps.html A_list = [psi0.get_B(i, form="G").to_ndarray().transpose([1,0,2]) for i in range(L)] for i,A in enumerate(A_list): A_list[i] = (A[0], A[1]) [(_[0].shape, _[1].shape) for _ in A_list] S_list = [psi0.get_SR(i) for i in range(L-1)] # skip trivial last bond; hast to be of size L-1 state = (A_list, S_list) initcirc = QuantumCircuit(QuantumRegister(L,"q")) #,ClassicalRegister(num_trash, 'c') initcirc.set_matrix_product_state(state) initcirc.draw() plt.plot(psi0.expectation_value("N")) i=0 qi = qiskit.utils.QuantumInstance(backend=backend, # , seed_simulator=seed, seed_transpiler=seed shots = 1000, #coupling_map=coupling_map, #noise_model=noise_model, # comment out on real device execution #measurement_error_mitigation_cls= CompleteMeasFitter, #cals_matrix_refresh_period=30 #How often to refresh the calibration matrix in measurement mitigation. in minutes ) QZ = np.zeros(L) for i in range(L): meas_outcome = ~StateFn(QNKron(L,Z,I,i)) @ StateFn(initcirc) QZ[i] = CircuitSampler(qi).convert(meas_outcome).eval() plt.plot(QZ)
https://github.com/Qottmann/Quantum-anomaly-detection
Qottmann
from qiskit import IBMQ # token is obtained from IBMQ expierence website, just set up an account at https://quantum-computing.ibm.com/ and once run # IBMQ.enable_account(token) # IBMQ.save_account(token) IBMQ.load_account() # this then automatically loads your saved account IBMQ.providers() # list of providers, in our case just the standard open one since we dont have any special access (yet!) provider = IBMQ.get_provider(hub='ibm-q-research') provider.backends(simulator=False, operational=True) provider.backends(filters=lambda x: x.configuration().n_qubits >= 10 and not x.configuration().simulator and x.status().operational==True) from qiskit.providers.ibmq import least_busy small_devices = provider.backends(filters=lambda x: x.configuration().n_qubits == 5 and not x.configuration().simulator) least_busy(small_devices) backend = least_busy(small_devices) #backend = provider.backends(simulator=False, operational=True)[7] backend status = backend.status() print("pending jobs: ", status.pending_jobs) print("maximum jobs to submit: ", backend.job_limit().maximum_jobs) print("operational: ", status.operational) ran_job = None for ran_job in backend.jobs(limit=5): print(str(ran_job.job_id()) + " " + str(ran_job.status())) import qiskit qr = qiskit.QuantumRegister(3) cr = qiskit.ClassicalRegister(3) circuit = qiskit.QuantumCircuit(qr, cr) circuit.x(qr[0]) circuit.x(qr[1]) circuit.ccx(qr[0], qr[1], qr[2]) circuit.cx(qr[0], qr[1]) circuit.measure(qr, cr) mapped_circuit = qiskit.compiler.transpile(circuit, backend=backend) #qobj = qiskit.compiler.assemble(mapped_circuit, backend=backend, shots=1024) # apparently deprecated and or unnecessary job = backend.run(mapped_circuit) print(status.pending_jobs) job.status() job.job_id() retrieved_job = backend.retrieve_job(job.job_id()) # once job is done this should yield result #result = retrieved_job.result() #counts = result.get_counts() #print(counts) from qiskit.providers.ibmq.managed import IBMQJobManager sim_backend = provider.get_backend('ibmq_qasm_simulator') circs = qiskit.compiler.transpile([circuit]*20, backend=sim_backend) # Submit them all to the backend job_manager = IBMQJobManager() job_set = job_manager.run(circs, backend=sim_backend, name='foo') print(job_set.report())
https://github.com/Qottmann/Quantum-anomaly-detection
Qottmann
import numpy as np from scipy.optimize import minimize import qiskit from qiskit import Aer, QuantumCircuit from qiskit.utils import QuantumInstance from matplotlib import pyplot as plt from qiskit_machine_learning.neural_networks import CircuitQNN # linear entangler (as in scales linearly with trash qubits) def get_entangler_map(L, num_trash, i_permut=1): result = [] nums = list(range(L)) # here was the problem, it doesnt like when list elements are taken from numpy nums_compressed = nums.copy()[:L-num_trash] nums_trash = nums.copy()[-num_trash:] #print(nums, nums_compressed, nums_trash) # combine all trash qubits with themselves for trash_q in nums_trash[:-1]: result.append((trash_q+1,trash_q)) # combine each of the trash qubits with every n-th repeated = list(nums_trash) * (L-num_trash) # repeat the list of trash indices cyclicly for i in range(L-num_trash): result.append((repeated[i_permut + i], nums_compressed[i])) return result def QAE_Ansatz(L,num_trash, insert_barriers=False, parametrized_gate = "ry", entangling_gate = "cz"): entanglement = [get_entangler_map(L,num_trash,i_permut) for i_permut in range(num_trash)] return qiskit.circuit.library.TwoLocal(L, parametrized_gate, entangling_gate, entanglement, reps=num_trash, insert_barriers=insert_barriers, ) QAE_Ansatz(6,2,insert_barriers=True).draw("mpl") QAE_Ansatz(5,2,insert_barriers=True).draw("mpl") QAE_Ansatz(7,2,insert_barriers=True).draw("mpl") QAE_Ansatz(6,3,insert_barriers=True).draw("mpl") # more complicated and as far as i can tell exponential def get_entangler_map_exp(L, num_trash, i_permut=0): result = [] nums = list(range(L)) nums_compressed = nums.copy()[:L-num_trash] nums_trash = nums.copy()[-num_trash:] #print(nums, nums_compressed, nums_trash) # combine all trash qubits with themselves for trash_q in nums_trash[:-1]: result.append((trash_q+1,trash_q)) # combine each of the trash qubits with every n-th permutations = list(itertools.permutations(nums_trash)) for _,trash_q in enumerate(permutations[i_permut]): for comp_q in nums_compressed[_%num_trash::num_trash]: # combine each trash_q with even or odd site result.append((trash_q, comp_q)) return result # Use Qiskit layer generator thingy because now it has everything it needs to get a gradient! # Note that it has redundant Ry rotations at the end on the compression qubits, didnt find a clever way how to get rid of them, but this shouldnt change too much # variational ansatz sub-circuit ansatz = QAE_Ansatz(6,2) # measurement circuit qreg = qiskit.QuantumRegister(L, 'q') creg = qiskit.ClassicalRegister(2, 'c') measurement_circ = qiskit.QuantumCircuit(qreg, creg) measurement_circ.measure(qreg[4], creg[0]) measurement_circ.measure(qreg[5], creg[1]) circ2 = ansatz + measurement_circ circ2.decompose() #print(circ2) #measurement_circ.draw("mpl") circ2.draw("mpl") qi_qasm = QuantumInstance(Aer.get_backend('qasm_simulator'), shots=10) qi_sv = QuantumInstance(Aer.get_backend('statevector_simulator')) qnn4 = CircuitQNN(circ2, [], circ2.parameters, sparse=False, quantum_instance=qi_qasm) input4 = np.random.rand(qnn4.num_inputs) weights4 = np.random.rand(qnn4.num_weights) qnn4.forward(input4, weights4) qnn4.backward(input4, weights4) from qiskit.algorithms.variational_algorithm import VariationalAlgorithm VariationalAlgorithm(ansatz = circ2, optimizer = None) qiskit.__version__ import qiskit import numpy as np L = 6 def create_map(L): return [(i,i+1) for i in np.arange(L-1)] map1 = create_map(L) print(map1) map_by_hand1 = [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)] print(map_by_hand1) map1 == map_by_hand1 ansatz = qiskit.circuit.library.TwoLocal(L,"ry","cz",[map_by_hand1],reps=2, insert_barriers=True) ansatz.draw("mpl") ansatz = qiskit.circuit.library.TwoLocal(L,"ry","cz",[map1],reps=2, insert_barriers=True) ansatz.draw("mpl") map1 = get_entangler_map(6,2) map2 = get_entangler_map(6,2,1) print(map1) print(map2) ansatz = qiskit.circuit.library.TwoLocal(L,"ry","cz",[map1,map2],reps=2, insert_barriers=True) ansatz.draw("mpl") ansatz = qiskit.circuit.library.TwoLocal(L,"ry","cz",[map_by_hand],reps=2, insert_barriers=True) ansatz.draw("mpl")
https://github.com/Qottmann/Quantum-anomaly-detection
Qottmann
import time import numpy as np import qiskit from qiskit.opflow import X,Z,I from qiskit.opflow.state_fns import StateFn, CircuitStateFn from modules.utils import * import matplotlib.pyplot as plt from scipy import sparse import scipy.sparse.linalg.eigen.arpack as arp %matplotlib inline # first need a gate that is the exponential of ZZ, which shouldnt be too difficult since it can be done analytically L = 2 qreg = qiskit.QuantumRegister(L, 'q') creg = qiskit.ClassicalRegister(2, 'c') circ = qiskit.QuantumCircuit(qreg, creg) circ.rz() tau = qiskit.circuit.Parameter("tau") diaglist = [tau, -tau, -tau, tau] diaglist dt = 0.05 diaglist = [np.exp(dt), np.exp(-dt), np.exp(-dt), np.exp(dt)] qiskit.circuit.library.Diagonal(diaglist) import numpy as np from qiskit.opflow import I, X, Y, Z, H, CX, Zero, ListOp, PauliExpectation, PauliTrotterEvolution, CircuitSampler, MatrixEvolution, Suzuki from qiskit.circuit import Parameter from qiskit import BasicAer L=5 anti = -1 gx = 1e-2 gz = 1e-2 two_qubit_H2 = QHIsing(L,anti,np.float32(gx),np.float32(gz)) two_qubit_H2 = 1 * (X^X^X^Z^X + Z^Z^Z^Z^X) two_qubit_H2 evo_time = Parameter('θ') evolution_op = (evo_time * two_qubit_H2).exp_i() h2_measurement = StateFn(two_qubit_H2).adjoint() #print(h2_measurement) evo_and_meas = h2_measurement @ evolution_op @ Zero #print(evo_and_meas) trotterized_op = PauliTrotterEvolution(trotter_mode=Suzuki(order=2, reps=1)).convert(evo_and_meas) bound = trotterized_op.bind_parameters({evo_time: .5}) diagonalized_meas_op = PauliExpectation().convert(trotterized_op) evo_time_points = [1,2,3,4] h2_trotter_expectations = diagonalized_meas_op.bind_parameters({evo_time: evo_time_points}) h2_trotter_expectations.eval() # Ops H = QHIsing(L,anti,np.float32(gx),np.float32(gz)) H_meas = StateFn(H).adjoint() mag = QMag(L,anti) qiskit.opflow.One^5 qiskit.opflow.VectorStateFn(qiskit.opflow.One^5) asd = H_meas @ qiskit.opflow.One^5 asd.eval() evo_time = qiskit.circuit.Parameter('θ') # note that we will have to bind it laterevo_time = Parameter('θ') evolution_op = (evo_time * H).exp_i() #* 1j # expH = suzi.convert(H) evo_and_meas = H_meas @ evolution_op trotterized_op = qiskit.opflow.evolutions.PauliTrotterEvolution(trotter_mode=qiskit.opflow.evolutions.Suzuki(order=2, reps=1)).convert(evo_and_meas) bound = trotterized_op.bind_parameters({evo_time: .5}) bound.eval() diagonalized_meas_op = qiskit.opflow.PauliExpectation().convert(trotterized_op) h2_trotter_expectations = diagonalized_meas_op.bind_parameters({evo_time: 1}) h2_trotter_expectations.eval() H.__class__, evolution_op.__class__ def imaginary_time_evolution(tau, L, gx, gz, anti=-1): H = QHIsing(L,anti,np.float32(gx),np.float32(gz)) evo_time = qiskit.circuit.Parameter('tau') # note that we will have to bind it later evolution_op = (tau * 1j * H).exp_i() trotterized_op = qiskit.opflow.evolutions.PauliTrotterEvolution(trotter_mode=qiskit.opflow.evolutions.Suzuki(order=2, reps=1)).convert(H_meas @ evolution_op) return trotterized_op trott_op = imaginary_time_evolution(tau=1, L=5, gx=1e-2, gz=1e-2, anti=-1) trott_op.bind_param({evo_}) bound = trott_op.bind_parameters({evo_time: 1}) bound.to_circuit().draw() mag_res = ~StateFn(mag) @ StateFn(trott_op) mag_res.eval() bound.eval() bound = trotterized_op.bind_parameters({evo_time: tau}) # this is a dummy circuit for the sake of checking how I can combine the evolved state with a circuit later circ = qiskit.circuit.library.TwoLocal(5,"rx","cz", reps=1,entanglement="linear") circ.draw() circ_fn = CircuitStateFn(circ) print(circ_fn) evolved_processed = evolution_op @ circ_fn # first the imaginary time evolution, then the dummy processing print(evolved_processed ) trotterized_op = qiskit.opflow.evolutions.PauliTrotterEvolution(trotter_mode=qiskit.opflow.evolutions.Suzuki(order=2, reps=1)).convert(evolved_processed) print(trotterized_op) bound = trotterized_op.bind_parameters({evo_time: .5j}) bound.to_circuit().draw() # ED result Smag = Mag(L,anti) init_state, E, ham = ising_groundstate(L, anti, np.float(gx), np.float(gz)) Sen = E Smags = init_state.T.conj()@Smag@init_state #Magnetization with Numpy results
https://github.com/Qottmann/Quantum-anomaly-detection
Qottmann
import time import numpy as np import qiskit from qiskit.opflow import X,Z,I from qiskit.opflow.state_fns import StateFn, CircuitStateFn import matplotlib.pyplot as plt from scipy import sparse import scipy.sparse.linalg.eigen.arpack as arp %matplotlib inline # copypaste niccolo's code def QNKron(N,op1,op2,pos): ''' Tensor product operator (Qiskit Pauli operators) returns tensor product of op1,op2 on sites pos,pos+1 and identity on remaining sites N:number of sites op1,op2: Pauli operators on neighboring sites pos: site to insert op1 ''' temp=np.array([I]*(N)) temp[pos]=op1 if pos!=(N-1): temp[pos+1]=op2 mat=1 for j in range(N): mat=mat^temp[j] return mat def QHIsing(N,lam,p): ''' Quantum Ising Hamiltonian (1D) with transverse field (Qiskit Pauli operators) N:number of sites lam: transverse field) ''' H=-QNKron(N,Z,Z,0)-lam*QNKron(N,X,I,0)-p*QNKron(N,Z,I,0) for i in range(1,N-1): H=H-QNKron(N,Z,Z,i)-lam*QNKron(N,X,I,i)-p*QNKron(N,Z,I,i) H=H-lam*QNKron(N,X,I,N-1)-p*QNKron(N,Z,I,N-1) return H def NKron(N,op1,op2,pos): ''' Tensor product operator returns tensor product of op1,op2 on sites pos,pos+1 and identity on remaining sites N:number of sites op1,op2: Pauli operators on neighboring sites pos: site to insert op1 ''' ide=np.eye(2) temp=np.array([ide]*(N),dtype=np.complex128) temp[pos,:,:]=op1 # if pos!=(N-1): temp[(pos+1)%N,:,:]=op2 mat=1 for j in range(N): mat=np.kron(mat,temp[j]) return mat def Mag(N): #magnetization operator (numpy array) sz=np.array([[1,0],[0,-1]]) M=np.zeros((2**N,2**N)) for i in range(N): M=M+NKron(N,sz,np.eye(2),i) return M/N def QMag(N): #magnetization operator (Qiskit operator) M=QNKron(N,Z,I,0) for i in range(1,N): M=M+QNKron(N,Z,I,i) return M/N def ising_groundstate(L, J, g, p): """For comparison: obtain ground state energy from exact diagonalization. Exponentially expensive in L, only works for small enough `L` <~ 20. """ if L >= 20: warnings.warn("Large L: Exact diagonalization might take a long time!") # get single site operaors sx = sparse.csr_matrix(np.array([[0., 1.], [1., 0.]])) sz = sparse.csr_matrix(np.array([[1., 0.], [0., -1.]])) id = sparse.csr_matrix(np.eye(2)) sx_list = [] # sx_list[i] = kron([id, id, ..., id, sx, id, .... id]) sz_list = [] for i_site in range(L): x_ops = [id] * L z_ops = [id] * L x_ops[i_site] = sx z_ops[i_site] = sz X = x_ops[0] Z = z_ops[0] for j in range(1, L): X = sparse.kron(X, x_ops[j], 'csr') Z = sparse.kron(Z, z_ops[j], 'csr') sx_list.append(X) sz_list.append(Z) H_zz = sparse.csr_matrix((2**L, 2**L)) H_x = sparse.csr_matrix((2**L, 2**L)) for i in range(L - 1): H_zz = H_zz + J*sz_list[i] * sz_list[(i + 1) % L] for i in range(L): H_x = H_x + g*sx_list[i] +p*sz_list[i] H = - H_zz - H_x E, V = arp.eigsh(H, k=1, which='SA', return_eigenvectors=True, ncv=20) return V[:,0], E[0], H def sort_vals(vals): """ vals is (unsorted) dictionary of parameters from VQE ansatz circuit, this returns sorted values as list """ indices = np.array([_.index for _ in vals]) # unordered list of indices from the ParameterVectorElement(Theta(INDEX)) vals_sorted = np.array([vals[_] for _ in vals]) # unordered list of values (but same ordering as indices) return vals_sorted[np.argsort(indices)] def init_vqe(vals): return qiskit.circuit.library.EfficientSU2(L, reps=3).assign_parameters(sort_vals(vals)) L = 6 VQE_vals = np.load(f'params_VQE_ising_N{L}.npy', allow_pickle=True).item() lambdas = np.array([_ for _ in VQE_vals]) # list of lambda values (the items in the dictionary) # note that Rike calls them gs mag = QMag(L) #magnetization operator (Qiskit) Smag=Mag(L) #magnetization operator (numpy) # the ~ is the adjoint, but also it turns the is_measurement attribute to True ~StateFn(mag) # state is technically a circuit, that prepares the ground state via VQE circuit #state.draw() # uncomment to see, but is very long Qen=np.zeros(len(lambdas)); Sen=np.zeros(len(lambdas)) #energies Qmags=np.zeros(len(lambdas)); Smags=np.zeros(len(lambdas)) #magnetizations for j,lambda0 in enumerate(lambdas): print(lambda0) H = QHIsing(L,np.float32(lambda0),1e-4) # build Hamiltonian Op state = init_vqe(VQE_vals[lambda0]) StateFn(state) meas_outcome = ~StateFn(mag) @ StateFn(state) Qmags[j]=meas_outcome.eval() e_outcome = ~StateFn(H) @ StateFn(state) Qen[j]=e_outcome.eval() init_state, E, ham = ising_groundstate(L, 1., np.float(lambda0),1e-4) Sen[j]=E Smags[j]=init_state.T.conj()@Smag@init_state #Magnetization with Numpy results lambdas = np.array([_ for _ in VQE_vals],dtype=np.float) # list of lambda values (the items in the dictionary) plt.figure(1,dpi=220) plt.scatter(lambdas,Sen) plt.scatter(lambdas,Qen) plt.xscale("log") plt.ylabel("GS energy") plt.xlabel("Mag. field") plt.legend(["Sparse","Qiskit"]) plt.grid() print(Sen,Qen) plt.figure(2,dpi=220) plt.scatter(lambdas,Smags) plt.scatter(lambdas,Qmags) plt.xscale('log') plt.ylabel("Magnetization") plt.xlabel("Mag. field") plt.legend(["Sparse","Qiskit"]) plt.grid() print(Smags,Qmags)
https://github.com/Qottmann/Quantum-anomaly-detection
Qottmann
import time import numpy as np import qiskit from qiskit.opflow import X,Z,I from qiskit.opflow.state_fns import StateFn, CircuitStateFn import matplotlib.pyplot as plt from scipy import sparse import scipy.sparse.linalg.eigen.arpack as arp %matplotlib inline # copypaste niccolo's code def QNKron(N,op1,op2,pos): ''' Tensor product operator (Qiskit Pauli operators) returns tensor product of op1,op2 on sites pos,pos+1 and identity on remaining sites N:number of sites op1,op2: Pauli operators on neighboring sites pos: site to insert op1 ''' temp=np.array([I]*(N)) temp[pos]=op1 if pos!=(N-1): temp[pos+1]=op2 mat=1 for j in range(N): mat=mat^temp[j] return mat def QHIsing(N,lam,p): ''' Quantum Ising Hamiltonian (1D) with transverse field (Qiskit Pauli operators) N:number of sites lam: transverse field) ''' H=-QNKron(N,Z,Z,0)-lam*QNKron(N,X,I,0)-p*QNKron(N,Z,I,0) for i in range(1,N-1): H=H-QNKron(N,Z,Z,i)-lam*QNKron(N,X,I,i)-p*QNKron(N,Z,I,i) H=H-lam*QNKron(N,X,I,N-1)-p*QNKron(N,Z,I,N-1) return H def NKron(N,op1,op2,pos): ''' Tensor product operator returns tensor product of op1,op2 on sites pos,pos+1 and identity on remaining sites N:number of sites op1,op2: Pauli operators on neighboring sites pos: site to insert op1 ''' ide=np.eye(2) temp=np.array([ide]*(N),dtype=np.complex128) temp[pos,:,:]=op1 # if pos!=(N-1): temp[(pos+1)%N,:,:]=op2 mat=1 for j in range(N): mat=np.kron(mat,temp[j]) return mat def Mag(N): #magnetization operator (numpy array) sz=np.array([[1,0],[0,-1]]) M=np.zeros((2**N,2**N)) for i in range(N): M=M+NKron(N,sz,np.eye(2),i) return M/N def QMag(N): #magnetization operator (Qiskit operator) M=QNKron(N,Z,I,0) for i in range(1,N): M=M+QNKron(N,Z,I,i) return M/N def ising_groundstate(L, J, g, p): """For comparison: obtain ground state energy from exact diagonalization. Exponentially expensive in L, only works for small enough `L` <~ 20. """ if L >= 20: warnings.warn("Large L: Exact diagonalization might take a long time!") # get single site operaors sx = sparse.csr_matrix(np.array([[0., 1.], [1., 0.]])) sz = sparse.csr_matrix(np.array([[1., 0.], [0., -1.]])) id = sparse.csr_matrix(np.eye(2)) sx_list = [] # sx_list[i] = kron([id, id, ..., id, sx, id, .... id]) sz_list = [] for i_site in range(L): x_ops = [id] * L z_ops = [id] * L x_ops[i_site] = sx z_ops[i_site] = sz X = x_ops[0] Z = z_ops[0] for j in range(1, L): X = sparse.kron(X, x_ops[j], 'csr') Z = sparse.kron(Z, z_ops[j], 'csr') sx_list.append(X) sz_list.append(Z) H_zz = sparse.csr_matrix((2**L, 2**L)) H_x = sparse.csr_matrix((2**L, 2**L)) for i in range(L - 1): H_zz = H_zz + J*sz_list[i] * sz_list[(i + 1) % L] for i in range(L): H_x = H_x + g*sx_list[i] +p*sz_list[i] H = - H_zz - H_x E, V = arp.eigsh(H, k=1, which='SA', return_eigenvectors=True, ncv=20) return V[:,0], E[0], H def sort_vals(vals): """ vals is (unsorted) dictionary of parameters from VQE ansatz circuit, this returns sorted values as list """ indices = np.array([_.index for _ in vals]) # unordered list of indices from the ParameterVectorElement(Theta(INDEX)) vals_sorted = np.array([vals[_] for _ in vals]) # unordered list of values (but same ordering as indices) return vals_sorted[np.argsort(indices)] def init_vqe(vals): return qiskit.circuit.library.EfficientSU2(L, reps=3).assign_parameters(sort_vals(vals)) L = 6 VQE_vals = np.load(f'params_VQE_ising_N{L}.npy', allow_pickle=True).item() lambdas = np.array([_ for _ in VQE_vals]) # list of lambda values (the items in the dictionary) # note that Rike calls them gs mag = QMag(L) #magnetization operator (Qiskit) Smag=Mag(L) #magnetization operator (numpy) # the ~ is the adjoint, but also it turns the is_measurement attribute to True ~StateFn(mag) # state is technically a circuit, that prepares the ground state via VQE circuit #state.draw() # uncomment to see, but is very long Qen=np.zeros(len(lambdas)); Sen=np.zeros(len(lambdas)) #energies Qmags=np.zeros(len(lambdas)); Smags=np.zeros(len(lambdas)) #magnetizations for j,lambda0 in enumerate(lambdas): print(lambda0) H = QHIsing(L,np.float32(lambda0),1e-4) # build Hamiltonian Op state = init_vqe(VQE_vals[lambda0]) StateFn(state) meas_outcome = ~StateFn(mag) @ StateFn(state) Qmags[j]=meas_outcome.eval() e_outcome = ~StateFn(H) @ StateFn(state) Qen[j]=e_outcome.eval() init_state, E, ham = ising_groundstate(L, 1., np.float(lambda0),1e-4) Sen[j]=E Smags[j]=init_state.T.conj()@Smag@init_state #Magnetization with Numpy results lambdas = np.array([_ for _ in VQE_vals],dtype=np.float) # list of lambda values (the items in the dictionary) plt.figure(1,dpi=220) plt.plot(lambdas,Sen,".--") plt.plot(lambdas,Qen) plt.xscale("log") plt.ylabel("GS energy") plt.xlabel("Mag. field") plt.legend(["Sparse","Qiskit"]) plt.grid() print(Sen,Qen) plt.figure(2,dpi=220) plt.scatter(lambdas,Smags) plt.scatter(lambdas,Qmags) plt.xscale('log') plt.ylabel("Magnetization") plt.xlabel("Mag. field") plt.legend(["Sparse","Qiskit"]) plt.grid() print(Smags,Qmags)
https://github.com/Qottmann/Quantum-anomaly-detection
Qottmann
# -*- coding: utf-8 -*- """ Created on Mon May 31 22:57:39 2021 @author: nbaldelli """ import time import itertools import numpy as np from scipy.optimize import minimize, basinhopping from qiskit import * from qiskit.quantum_info import Statevector from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B, SPSA, SLSQP from qiskit.algorithms import VQE from qiskit.opflow.state_fns import StateFn, CircuitStateFn from qiskit.opflow import CircuitSampler from qiskit.providers.aer import StatevectorSimulator, AerSimulator from qiskit.providers.aer.noise import NoiseModel from qiskit.utils import QuantumInstance from qiskit.ignis.mitigation.measurement import CompleteMeasFitter,complete_meas_cal from modules.utils import * import qiskit from qiskit import IBMQ #%% IBMQ.load_account() # Load account from disk IBMQ.providers() # List all available providers provider = IBMQ.get_provider(hub='ibm-q') print(provider.backends) real_backend = provider.backends(simulator=False, operational=True)[6] L=5 mag = QMag(L,-1) #magnetization operator (Qiskit) ~StateFn(mag) gx_vals = np.logspace(-2,2,10)[::-1] opt_params_noiseless=[] opt_params_noisy=[] Qmags=np.zeros(len(gx_vals)) load=False ############################################################################## #NOISY SIMULATION backend = qiskit.providers.aer.AerSimulator.from_backend(real_backend) coupling_map = backend.configuration().coupling_map noise_model = NoiseModel.from_backend(backend) optimizer = SPSA(maxiter=1000) reps=1 ansatz = qiskit.circuit.library.EfficientSU2(L, reps=reps) # ansatz = qiskit.circuit.library.TwoLocal(L,rotation_blocks="ry", entanglement_blocks=entanglement_blocks, entanglement=entanglement, reps=reps) ansatz.draw("mpl") q_instance = QuantumInstance(backend, coupling_map=coupling_map, noise_model=noise_model, measurement_error_mitigation_cls=CompleteMeasFitter, cals_matrix_refresh_period=30 ) gz=1e-3 filename = f'data/params_VQE_Ising_L{L:.0f}_anti_N_reps{reps}_gz{gz}.npz' ##%% if load==False: for i,gx in enumerate(gx_vals): print('gx: %.2f' %(gx)) if i != 0: vqe = VQE(ansatz=ansatz, initial_point = opt_params_noisy[-1], optimizer=optimizer, quantum_instance=q_instance) else: vqe = VQE(ansatz=ansatz, optimizer=optimizer, quantum_instance=q_instance) H = QHIsing(L,-1,np.float32(gx),np.float32(gz)) result = vqe.compute_minimum_eigenvalue(H) #ED with Qiskit VQE opt_params_noisy.append(sort_params(result.optimal_parameters)) np.savez(filename, opt_params=opt_params_noisy)
https://github.com/Qottmann/Quantum-anomaly-detection
Qottmann
from matplotlib import pyplot as plt import numpy as np import matplotlib.gridspec as gridspec path = "data/BH_phase-diagrams-and-loss/data_rike/" x = np.load(path + "x.npy") y = np.load(path + "y.npy") es = np.load(path + "es.npy") dd = np.load(path + "dd.npy") cost0 = np.load(path + "cost_bh_L12_trash2_d48_v5_seed17.npy") cost1 = np.load(path + "cost_bh_L12_trash4_d25_v47_seed16.npy") cost2 = np.load(path + "cost_bh_L12_trash6_d10_v10_seed22.npy") vs = np.logspace(-2,2,50) ds = np.linspace(-0.95,0.95,50) cbar = np.zeros((2,2), dtype="object") fig,axs = plt.subplots(ncols=2, nrows=2,figsize=(10,6),sharex=True, sharey=True) cmap = plt.get_cmap("plasma") #'viridis' cbar_labelsize = 14 cbar = np.zeros((2,2), dtype="object") ax = axs[0,0] im = ax.pcolormesh(x,y,dd.T, cmap=cmap, shading="auto",rasterized=True) #,rasterized=True necessary for pdf export ax.set_xscale("log") cbar[0,0] = fig.colorbar(im, ax=ax) cbar[0,0].ax.tick_params(labelsize=cbar_labelsize) ax = axs[0,1] im = ax.pcolormesh(x,y,es.T, cmap=cmap, shading="auto",rasterized=True) ax.set_xscale("log") cbar[0,1] = fig.colorbar(im, ax=ax) cbar[0,1].ax.tick_params(labelsize=cbar_labelsize) ax = axs[1,0] im = ax.pcolormesh(x,y,cost2.T,vmin=0, cmap=cmap, shading="auto",rasterized=True) ax.set_xscale("log") cbar[1,0] = fig.colorbar(im, ax=ax) cbar[1,0].ax.tick_params(labelsize=cbar_labelsize) ax.plot(vs[10],ds[10],"x", color="magenta") ax = axs[1,1] im = ax.pcolormesh(x,y,cost1.T,vmin=0, cmap=cmap, shading="auto",rasterized=True) ax.set_xscale("log") cbar[1,1] = fig.colorbar(im, ax=ax) cbar[1,1].ax.tick_params(labelsize=cbar_labelsize) ax.plot(vs[47],ds[25],"x", color="magenta") for ax in axs.flatten(): ax.tick_params(labelsize=14) axs[1,0].set_xlabel(r"$V$",fontsize=18) axs[1,1].set_xlabel(r"$V$",fontsize=18) axs[0,0].set_ylabel(r"$\delta t$",fontsize=18) axs[1,0].set_ylabel(r"$\delta t$",fontsize=18) plt.tight_layout() # has to happen after tight_layout() axs[0,0].text(-0.25,0.9,"a", fontweight="bold", size=18, transform = axs[0,0].transAxes) axs[1,0].text(-0.25,0.9,"c", fontweight="bold", size=18, transform = axs[1,0].transAxes) axs[0,1].text(-0.1,0.9,"b", fontweight="bold", size=18, transform = axs[0,1].transAxes) axs[1,1].text(-0.1,0.9,"d", fontweight="bold", size=18, transform = axs[1,1].transAxes) cbar[0,0].ax.set_title("$\\langle n_i n_j \\rangle$") axs[0,0].set_title("density-density correlations", fontsize=14) cbar[0,1].ax.set_title("$\Delta \\lambda$") axs[0,1].set_title("Entanglement spectrum degeneracy", fontsize=14) cbar[1,0].ax.set_title("cost") cbar[1,1].ax.set_title("cost") plt.savefig("plots/BH_replot.pdf", bbox_inches='tight') fig,aa = plt.subplots(figsize=(15,5.7),sharey="row",dpi=220) ax00 = plt.subplot2grid(shape=(2,5), loc=(0, 0), rowspan=1, colspan=1, xticklabels=[]) ax10 = plt.subplot2grid(shape=(2,5), loc=(1, 0), rowspan=1, colspan=1, xticklabels=[]) ax01 = plt.subplot2grid(shape=(2,5), loc=(0, 1), rowspan=2, colspan=2, xticklabels=[], yticklabels=[]) ax02 = plt.subplot2grid(shape=(2,5), loc=(0, 3), rowspan=2, colspan=2, xticklabels=[], yticklabels=[]) cmap = plt.get_cmap("plasma") #'viridis' cbar_labelsize = 10 cbar = np.zeros((2,2), dtype="object") axs=np.array([[ax00,ax10],[ax01,ax02]]) print(axs[0,0]) ax = axs[0,0] im = ax.pcolormesh(x,y,dd.T, cmap=cmap, shading="auto",rasterized=True) #,rasterized=True necessary for pdf export #im.ax.tick_params(labelsize=cbar_labelsize) ax.set_xscale("log") cbar[0,0] = fig.colorbar(im, ax=ax) cbar[0,0].ax.tick_params(labelsize=cbar_labelsize) ax = axs[0,1] im = ax.pcolormesh(x,y,es.T, cmap=cmap, shading="auto",rasterized=True) ax.set_xscale("log") cbar[0,1] = fig.colorbar(im, ax=ax) cbar[0,1].ax.tick_params(labelsize=cbar_labelsize) ax = axs[1,0] im = ax.pcolormesh(x,y,cost2.T,vmin=0, cmap=cmap, shading="auto",rasterized=True) ax.set_xscale("log") cbar[1,0] = fig.colorbar(im, ax=ax) cbar[1,0].ax.tick_params(labelsize=cbar_labelsize) ax.plot(vs[10],ds[10],"X", color="magenta",markersize=15) ax = axs[1,1] im = ax.pcolormesh(x,y,cost1.T,vmin=0, cmap=cmap, shading="auto",rasterized=True) ax.set_xscale("log") cbar[1,1] = fig.colorbar(im, ax=ax) cbar[1,1].ax.tick_params(labelsize=cbar_labelsize) ax.plot(vs[47],ds[25],"X", color="magenta",markersize=15) for ax in axs.flatten(): ax.tick_params(labelsize=10) axs[1,0].set_xlabel(r"$V$",fontsize=12) axs[0,1].set_ylabel(r"$\delta J$",fontsize=12) axs[1,1].set_xlabel(r"$V$",fontsize=12) axs[0,0].set_ylabel(r"$\delta J$",fontsize=12) axs[1,0].set_ylabel(r"$\delta J$",fontsize=12) #plt.tight_layout() # has to happen after tight_layout() axs[0,0].text(0.01,0.89,"a", fontweight="bold", size=18, transform = axs[0,0].transAxes, color="white") axs[1,0].text(0.02,0.95,"c", fontweight="bold", size=18, transform = axs[1,0].transAxes) axs[0,1].text(0.01,0.88,"b", fontweight="bold", size=18, transform = axs[0,1].transAxes) axs[1,1].text(0.02,0.94,"d", fontweight="bold", size=18, transform = axs[1,1].transAxes) axs[1,0].text(0.23,0.05,"MI", fontweight="bold", size=18, transform = axs[1,0].transAxes, color="white") axs[1,0].text(0.23,0.8,"TMI", fontweight="bold", size=18, transform = axs[1,0].transAxes) axs[1,0].text(0.77,0.5,"CDW", fontweight="bold", size=18, transform = axs[1,0].transAxes) #cbar[0,0].ax.set_title("$\\langle n_i n_j \\rangle$") cbar[0,0].ax.set_title("$O_{CDW}$") axs[0,0].set_title("DMRG", fontsize=14) cbar[0,1].ax.set_title("ES") #axs[0,1].set_title("Entanglement spectrum degeneracy", fontsize=14) cbar[1,0].ax.set_title("cost") cbar[1,1].ax.set_title("cost") plt.savefig("plots/BH_replot2.pdf", bbox_inches='tight') fig, ax = plt.subplots(figsize=(6,4)) im = ax.pcolormesh(x,y,cost2.T,vmin=0, cmap=cmap, shading="auto",rasterized=True) ax.set_xscale("log") cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=cbar_labelsize) ax.set_title("Anomaly Syndrome", fontsize=14) cbar.ax.set_title("cost") ax.plot(vs[10],ds[10],"x", markersize=15, color="magenta") ax.text(vs[10],ds[10]-0.25,"Training example", color="magenta") ax.tick_params(labelsize=14) #ax.set_xlabel(r"$V$",fontsize=18) #ax.set_ylabel(r"$\delta t$",fontsize=18) plt.tight_layout() plt.savefig("plots/BH_ex_for_presentation.png", dpi=500, bbox_inches='tight')
https://github.com/Qottmann/Quantum-anomaly-detection
Qottmann
import sys sys.path.insert(1, '..') # sets the import path to the parent folder import time import datetime import numpy as np from matplotlib import pyplot as plt anti = -1 L = 5 num_trash = 2 name = "jakarta_execute" filename = '../data/jakarta_execute' # load data from simulation and experiment temp = np.load(filename + "_executed_-real-device-True.npz",allow_pickle=True) gx_list = temp["gx_list"] gz = 0 gz_list = [0] Qmag_sim = temp["Qmag_sim"] QZ_sim = temp["QZ_sim"] Qmag_device = temp["Qmag_device"] QZ_device = temp["QZ_device"] Qen_sim = temp["Qen_sim"] Sen = temp["Sen"] Smag = temp["Smag"] opt_params = temp["opt_params"] paramss = temp["paramss"]; valuess = temp["valuess"]; countss = temp["countss"] run1 = np.load(filename + "run1_device2.npz",allow_pickle=True) # alt: run1_device2 sim1 = np.load(filename + "run1_sim2.npz",allow_pickle=True) run2 = np.load(filename + "run2_device.npz",allow_pickle=True) # alt: _overnight sim2 = np.load(filename + "run2_sim.npz",allow_pickle=True) fig, axs = plt.subplots(nrows=2,figsize=(6,6),sharex=True,gridspec_kw={'height_ratios': [2, 2]}) ax = axs[0] cost_sim = sim1["cost"] ax.plot(gx_list, cost_sim,".:", label="cost noisy sim.") cost_device = run1["cost"] ax.plot(gx_list, cost_device,".:", label="cost ibmq_jakarta") ax.plot(gx_list, np.abs(Qmag_sim),"x--", label="$|\hat{S}|$ noisy sim.") ax.plot(gx_list, np.abs(Qmag_device),"x--", label="$|\hat{S}|$ ibmq_jakarta") ax.set_xscale("log") ax.plot(gx_list[0],cost_device[0], "X",markersize=20,alpha=0.4,color="magenta") ax = axs[1] cost_sim = sim2["cost"] ax.plot(gx_list, cost_sim,".:", label="cost noisy sim.") cost_device = run2["cost"] ax.plot(gx_list, cost_device,".:", label="cost ibmq_jakarta") ax.plot(gx_list, np.abs(Qmag_sim),"x--", label="$|\hat{S}|$ noisy sim.") ax.plot(gx_list, np.abs(Qmag_device),"x--", label="$|\hat{S}|$ ibmq_jakarta") ax.set_xscale("log") ax.plot(gx_list[-1],cost_device[-1],"X",markersize=16,alpha=0.4,color="magenta", label= "Training point") for ax in axs: ax.tick_params(labelsize=14) axs[1].legend() #ncol=5 axs[-1].set_xlabel("$g_x$", fontsize=14) plt.tight_layout() axs[0].text(0.01,0.9,"a", fontweight="bold", size=18, transform = axs[0].transAxes) axs[1].text(0.01,0.9,"b", fontweight="bold", size=18, transform = axs[1].transAxes) plt.savefig("../plots/" + name + "_mainplot.png", bbox_inches='tight') plt.savefig("../plots/" + name + "_mainplot.pdf", bbox_inches='tight') run1 = np.load(filename + "run1_device.npz",allow_pickle=True) # alt: run1_device2 sim1 = np.load(filename + "run1_sim.npz",allow_pickle=True) run2 = np.load(filename + "run2_device_overnight.npz",allow_pickle=True) # alt: run2_device_ sim2 = np.load(filename + "run2_sim.npz",allow_pickle=True) fig, axs = plt.subplots(nrows=2,figsize=(6,6),sharex=True,gridspec_kw={'height_ratios': [2, 2]}) ax = axs[0] cost_sim = sim1["cost"] ax.plot(gx_list, cost_sim,".:", label="cost noisy sim.") cost_device = run1["cost"] ax.plot(gx_list, cost_device,".:", label="cost ibmq_jakarta") ax.plot(gx_list, np.abs(Qmag_sim),"x--", label="$|\hat{S}|$ noisy sim.") ax.plot(gx_list, np.abs(Qmag_device),"x--", label="$|\hat{S}|$ ibmq_jakarta") ax.set_xscale("log") ax.plot(gx_list[0],cost_device[0], "X",markersize=20,alpha=0.4,color="magenta") ax = axs[1] cost_sim = sim2["cost"] ax.plot(gx_list, cost_sim,".:", label="cost noisy sim.") cost_device = run2["cost"] ax.plot(gx_list, cost_device,".:", label="cost ibmq_jakarta") ax.plot(gx_list, np.abs(Qmag_sim),"x--", label="$|\hat{S}|$ noisy sim.") ax.plot(gx_list, np.abs(Qmag_device),"x--", label="$|\hat{S}|$ ibmq_jakarta") ax.set_xscale("log") ax.plot(gx_list[-1],cost_device[-1],"X",markersize=20,alpha=0.4,color="magenta", label= "Training point") for ax in axs: ax.tick_params(labelsize=14) axs[1].legend() #ncol=5 axs[-1].set_xlabel("$g_x$", fontsize=14) plt.tight_layout() axs[0].text(0.01,0.9,"a", fontweight="bold", size=18, transform = axs[0].transAxes) axs[1].text(0.01,0.9,"b", fontweight="bold", size=18, transform = axs[1].transAxes) plt.savefig("../plots/" + name + "_mainplot_alt.png", bbox_inches='tight') plt.savefig("../plots/" + name + "_mainplot_alt.pdf", bbox_inches='tight')
https://github.com/Qottmann/Quantum-anomaly-detection
Qottmann
import time import datetime import numpy as np from matplotlib import pyplot as plt import qiskit from qiskit import * from qiskit.opflow import X,Z,I from qiskit.opflow.state_fns import StateFn, CircuitStateFn from qiskit.providers.aer import StatevectorSimulator, AerSimulator from qiskit.algorithms import VQE from qiskit.algorithms.optimizers import COBYLA, SLSQP, SPSA from qiskit.opflow import CircuitSampler from qiskit.ignis.mitigation.measurement import CompleteMeasFitter # you will need to pip install qiskit-ignis from qiskit.ignis.mitigation.measurement import complete_meas_cal from scipy import sparse import scipy.sparse.linalg.eigen.arpack as arp from modules.utils import * anti = -1 L = 5 num_trash = 2 name = "ibmq_antiferro-1D-load_bogota-optimize-20points" # 01.06.2021 experiment filename = "data/noisy_VQE_maxiter-500_Ising_L5_anti_-1_20" #"data/noisy_VQE_maxiter-100_Ising_L5_anti_-1_20_recycle" print("filename: ", filename, "notebook name: ", name) # where to get the simulated thetas values from? needs to contain a thetas_mitigated array filename_simulated_thetas = 'data/ibmq_antiferro-1D-load_bogota-optimize_thetas-loss-cost_run2.npz' load = True recompute = False # whether or not to recompute Magnetization, makes sense on device # this is noisy simulation data L = 5 num_trash = 2 anti = -1 VQE_params = np.load(filename + ".npz", allow_pickle=True) pick = np.arange(0,len(VQE_params['gx_list'])) gx_list = VQE_params['gx_list'][pick] gz_list = VQE_params['gz_list'][pick] opt_params = VQE_params['opt_params'][pick] Qmags = VQE_params["Qmag"][pick] Qen = VQE_params["Qen"][pick] Sen = VQE_params["Sen"][pick] Smags = VQE_params["Smag"][pick] gx_vals = np.unique(gx_list) gz_vals = np.unique(gz_list) # these are the results from using precalculated VQE values from noisy simulation on the real device (ibmq_bogota) if load: temp = np.load("data/" + name + "executed_mags-Es.npz",allow_pickle=True) Qmags_executed = temp["Qmags"] # these are values actually obtained with VQE on ibmq_rome VQE_params = np.load("data/rome_VQE_maxiter-30_Ising_L5_anti_-1_20_recycle.npz", allow_pickle=True) print(VQE_params.files) pick = np.arange(0,len(VQE_params['gx_list'])) gx_list2 = VQE_params['gx_list'][pick] gz_list2 = VQE_params['gz_list'][pick] opt_params2 = VQE_params['opt_params'][pick] Qmags2 = VQE_params["Qmag"][pick] Qen2 = VQE_params["Qen"][pick] Sen2 = VQE_params["Sen"][pick] Smags2 = VQE_params["Smag"][pick] gx_vals2 = np.unique(gx_list2) gz_vals2 = np.unique(gz_list2) fig, axs = plt.subplots(ncols=2,figsize=(14,4)) ax=axs[0] ax.plot(gx_list, Qmags_executed,"x--", label="simulated VQE on ibmq_bogota") ax.plot(gx_list2, Qmags2,".:", label = "full mag on ibmq_rome") ax.set_xscale("log") ax.legend() ax=axs[1] ax.plot(gx_list, abs(Qmags_executed),"x--", label="simulated VQE on ibmq_bogota") ax.plot(gx_list2, abs(Qmags2),".:", label = "full mag on ibmq_rome") ax.set_xscale("log") ax.legend() fig, axs = plt.subplots(ncols=2, figsize=(10,5)) ax = axs[0] ax.plot(gx_list, Smags,"x--", label="ED") ax.plot(gx_list, Qmags,"x--", label="VQE simu w/ noise") ax.set_xscale("log") if recompute or load: ax.plot(gx_list, Qmags_executed,"x--", label="IBMQ") ax.legend() ax.set_title("$M$") ax = axs[1] ax.plot(gx_list, Smags,"x--", label="ED") ax.plot(gx_list, abs(Qmags),"x--", label="VQE simu w/ noise") ax.set_xscale("log") if recompute or load: ax.plot(gx_list, abs(Qmags_executed),"x--", label="ibmq_bogota") ax.legend() ax.set_title("$\\mid M \\mid$") ############################################################################## ### II - Training ########################################################### ############################################################################## cal_matrix = np.array([[0.982, 0.036, 0.032, 0.003], [0.011, 0.959, 0., 0.036], [0.007, 0.001, 0.962, 0.023], [0., 0.004, 0.006, 0.938]]) # this was the one from the experiment from qiskit.tools.visualization import * temp = np.load("data/" + 'ibmq_antiferro-1D-load_simu' + "raw-vs-mitigated-counts.npz",allow_pickle=True) plot_histogram([temp["raw_counts"].item(), temp["mitigated_counts"].item()], legend=['raw', 'mitigated']) counts0 = temp["raw_counts"].item() counts1 = temp["mitigated_counts"].item() sortkeys = list(sorted([_ for _ in counts0])) fig, ax = plt.subplots(figsize=(5,3)) plt.grid() sortkeys = list(sorted([_ for _ in counts0])) vals = np.array([counts0[_] for _ in sortkeys]) vals = vals/np.sum(vals) ax.bar(sortkeys,vals, width=-0.3, align="edge", label="raw") sortkeys = list(sorted([_ for _ in counts1])) vals = np.array([counts1[_] for _ in sortkeys]) vals = vals/np.sum(vals) ax.bar(sortkeys,vals, width=0.3, align="edge", label="mitigated") ax.legend() plt.tick_params(labelsize=14) ax.set_ylabel("counts/shots", fontsize=20) plt.tight_layout() plt.savefig("plots/counts_mitigated-vs-raw.png") plt.savefig("plots/counts_mitigated-vs-raw.pdf") phis = opt_params # translate to Rikes naming gxs = gx_list gzs = gz_list phys_params= [0] fig, ax = plt.subplots(ncols=1,figsize=(6,5)) ax.set_title("Mitigated results") cost = np.load("data/" + "ibmq_antiferro-1D-load_simu" + "_thetas-loss-cost_run1.npz", allow_pickle=True)["cost_mitigated"] ax.plot(gx_list, cost,".:", label="loss noisy sim.") cost = np.load("data/" + name + "_thetas-loss-cost_run1.npz", allow_pickle=True)["cost_mitigated"] ax.plot(gx_list, cost,".:", label="loss ibmq_bogota") ax.plot(gx_list, Qmags,"x--", label="$\\langle \\sigma_z \\rangle$ noisy sim.") ax.plot(gx_list, Qmags_executed,"x--", label="$\\langle \\sigma_z \\rangle$ ibmq_bogota") ax.set_xscale("log") for p in phys_params: ax.plot(gx_list[p],cost[p],"o",alpha=0.3,color="magenta") ax.legend() phys_params = [-1] fig, ax = plt.subplots(ncols=1,figsize=(6,5)) ax.set_title("Mitigated results") cost = np.load("data/" + "ibmq_antiferro-1D-load_simu" + "_thetas-loss-cost_run2.npz", allow_pickle=True)["cost_mitigated"] ax.plot(gx_list, cost,"x--", label="loss noisy sim.") cost = np.load("data/" + name + "_thetas-loss-cost_run2.npz", allow_pickle=True)["cost_mitigated"] ax.plot(gx_list, cost,".:", label="loss ibmq_bogota") ax.plot(gx_list, abs(Qmags),"x--", label="$\\mid M \\mid$ noisy sim.") ax.plot(gx_list, abs(Qmags_executed),".:", label="$\\mid M \\mid$ ibmq_bogota") ax.set_xscale("log") for p in phys_params: ax.plot(gx_list[p],cost[p],"o",alpha=0.3,color="magenta") ax.legend() name fig, axs = plt.subplots(nrows=2,figsize=(6,6),sharex=True,gridspec_kw={'height_ratios': [2, 2]}) ax = axs[0] cost = np.load("data/" + "ibmq_antiferro-1D-load_simu" + "_thetas-loss-cost_run1.npz", allow_pickle=True)["cost_mitigated"] ax.plot(gx_list, cost,".:")#, label="loss noisy sim.") cost = np.load("data/" + name + "_thetas-loss-cost_run1.npz", allow_pickle=True)["cost_mitigated"] ax.plot(gx_list, cost,".:")#, label="loss ibmq_bogota") ax.plot(gx_list, Qmags,"x--", label="$\hat{S}$ noisy sim.") ax.plot(gx_list, Qmags_executed,"x--", label="$\hat{S}$ ibmq_bogota") ax.set_xscale("log") ax.plot(gx_list[0],cost[0], "X",markersize=20,alpha=0.4,color="magenta") ax = axs[1] cost = np.load("data/" + "ibmq_antiferro-1D-load_simu" + "_thetas-loss-cost_run2.npz", allow_pickle=True)["cost_mitigated"] ax.plot(gx_list, cost,"x--", label="cost noisy sim.") cost = np.load("data/" + name + "_thetas-loss-cost_run2.npz", allow_pickle=True)["cost_mitigated"] ax.plot(gx_list, cost,".:", label="cost ibmq_bogota") ax.plot(gx_list, abs(Qmags),"x--", label="$\\mid \hat{S} \\mid$ noisy sim.") ax.plot(gx_list, abs(Qmags_executed),".:", label="$\\mid \hat{S} \\mid$ ibmq_bogota") ax.set_xscale("log") ax.plot(gx_list[-1],cost[-1],"X",markersize=20,alpha=0.4,color="magenta") for ax in axs: ax.legend() ax.tick_params(labelsize=14) axs[-1].set_xlabel("$g_x$", fontsize=14) plt.tight_layout() axs[0].text(0.01,0.9,"a", fontweight="bold", size=18, transform = axs[0].transAxes) axs[1].text(0.01,0.9,"b", fontweight="bold", size=18, transform = axs[1].transAxes) plt.savefig("plots/" + name + "_mainplot.png", bbox_inches='tight') plt.savefig("plots/" + name + "_mainplot.pdf", bbox_inches='tight') fig, ax = plt.subplots(ncols=1,figsize=(6,5)) ax.set_title("Mitigated results") cost = np.load("data/" + "ibmq_antiferro-1D-load_simu" + "_thetas-loss-cost_run2.npz", allow_pickle=True)["cost_mitigated"] ax.plot(gx_list, cost,"x--", label="loss noisy sim.") cost = np.load("data/" + name + "_thetas-loss-cost_run2.npz", allow_pickle=True)["cost_mitigated"] ax.plot(gx_list, cost,".:", label="loss ibmq_bogota") ax.plot(gx_list, abs(Qmags),"x--", label="order parameter") #ax.plot(gx_list, abs(Qmags_executed),".:", label="$\\mid M \\mid$ ibmq_bogota") ax.set_xscale("log") ax.plot(gx_list[-1],cost[-1], "X",markersize=20,alpha=0.4,color="magenta") ax.legend(fontsize=16) ax.tick_params(labelsize=14) ax.set_xlabel("$g_x$", fontsize=14) plt.savefig("plots/IBMQ_presentation.png", dpi=400, bbox_inches='tight') cost = np.load("data/ibmq_antiferro-2D_load-AD_10x10_noisy-rome-simu_thetas-loss-cost_run1.npy",allow_pickle=True) qmag = np.load("data/noisy_rome_simu_VQE_maxiter-500_Ising_L5_anti_-1_10x10.npz", allow_pickle=True)["Qmag"].reshape(10,10) x,y = np.logspace(-2,2,10), np.logspace(-2,2,10) x,y = np.meshgrid(x,y) fig,axs = plt.subplots(ncols=1, nrows=2,figsize=(5,5),sharex=True, sharey=True, squeeze=False) cmap = plt.get_cmap("plasma") #'viridis' cbar_labelsize = 14 cbar = np.zeros((2,2), dtype="object") ax = axs[0,0] im = ax.pcolormesh(x,y,qmag, cmap=cmap, shading="auto",rasterized=True) #,rasterized=True necessary for pdf export cbar[0,0] = fig.colorbar(im, ax=ax) cbar[0,0].ax.tick_params(labelsize=cbar_labelsize) ax = axs[1,0] im = ax.pcolormesh(x,y,cost,vmin=0, cmap=cmap, shading="auto",rasterized=True) cbar[1,0] = fig.colorbar(im, ax=ax) cbar[1,0].ax.tick_params(labelsize=cbar_labelsize) #ax.plot(vs[47],ds[25],"x", color="magenta") axs[1,0].plot(1e-2,1e-2,"x", markersize=12, color="magenta") for ax in axs.flatten(): ax.set_xscale("log") ax.set_yscale("log") ax.tick_params(labelsize=14) axs[1,0].set_xlabel(r"$g_x$",fontsize=18) axs[0,0].set_ylabel(r"$g_z$",fontsize=18) axs[1,0].set_ylabel(r"$g_z$",fontsize=18) plt.tight_layout() # has to happen after tight_layout() axs[0,0].text(-0.25,0.9,"a", fontweight="bold", size=18, transform = axs[0,0].transAxes) axs[1,0].text(-0.25,0.9,"b", fontweight="bold", size=18, transform = axs[1,0].transAxes) axs[0,0].text(0.05,0.9,"Staggered Magnetization", size=14, transform = axs[0,0].transAxes) axs[1,0].text(0.05,0.9,"cost", size=14, transform = axs[1,0].transAxes) plt.savefig("plots/antiferro2D.pdf", bbox_inches='tight') fig,axs = plt.subplots(ncols=2,figsize=(9,4),sharex=True, sharey=True) cmap = plt.get_cmap("plasma") #'viridis' cbar_labelsize = 14 cbar = np.zeros((2), dtype="object") ax = axs[0] im = ax.pcolormesh(x,y,qmag, cmap=cmap, shading="auto",rasterized=True) #,rasterized=True necessary for pdf export cbar[0] = fig.colorbar(im, ax=ax) cbar[0].ax.tick_params(labelsize=cbar_labelsize) ax = axs[1] im = ax.pcolormesh(x,y,cost,vmin=0, cmap=cmap, shading="auto",rasterized=True) cbar[1] = fig.colorbar(im, ax=ax) cbar[1].ax.tick_params(labelsize=cbar_labelsize) #ax.plot(vs[47],ds[25],"x", color="magenta") axs[1].plot(1e-2,1e-2,"x", markersize=12, color="magenta") for ax in axs: ax.set_xscale("log") ax.set_yscale("log") ax.tick_params(labelsize=14) axs[1].set_xlabel(r"$g_x$",fontsize=18) axs[0].set_xlabel(r"$g_x$",fontsize=18) axs[0].set_ylabel(r"$g_z$",fontsize=18) plt.tight_layout() # has to happen after tight_layout() #axs[0].text(0.05,0.9,"a Staggered Magnetization", fontweight="bold", size=18, transform = axs[0].transAxes) #axs[1].text(0.05,0.9,"b cost", fontweight="bold", size=18, transform = axs[1].transAxes) axs[0].set_title("order parameter", fontsize=14) axs[1].set_title("cost", fontsize=14) plt.savefig("plots/antiferro2D_bigger.pdf", bbox_inches='tight') plt.savefig("plots/antiferro2D_bigger.png", bbox_inches='tight')
https://github.com/Qottmann/Quantum-anomaly-detection
Qottmann
import sys sys.path.insert(1, '..') # sets the import path to the parent folder import time import numpy as np #import qiskit #from qiskit.opflow import X,Z,I #from qiskit.opflow.state_fns import StateFn, CircuitStateFn #from qiskit.providers.aer import StatevectorSimulator, AerSimulator #from qiskit.algorithms import VQE #from qiskit.algorithms.optimizers import COBYLA, SLSQP, SPSA import matplotlib.pyplot as plt from scipy import sparse import scipy.sparse.linalg.eigen.arpack as arp #from modules.utils import * from tenpy.networks.mps import MPS from tenpy.models.hubbard import BoseHubbardChain from tenpy.algorithms import dmrg from tenpy.linalg import np_conserved %matplotlib inline def DMRG_EBH(L, V, t_list, chi_max=30, bc_MPS='infinite'): model_params = dict(n_max=1, filling=0.5, bc_MPS=bc_MPS, t=t_list, L=L, V=V, mu=0, conserve='N', verbose=0) M = BoseHubbardChain(model_params) vector=[] for i in range(M.lat.N_sites): if i%2: vector.append(1) else: vector.append(0) psi = MPS.from_product_state(M.lat.mps_sites(), vector, bc=M.lat.bc_MPS) dmrg_params = { 'mixer': True, 'trunc_params': { 'chi_max': chi_max, }, 'max_E_err': 1.e-16, 'verbose': 0 } info = dmrg.run(psi, M, dmrg_params) return info['E'], psi chi = 50 V_list = np.linspace(2,8,10) deltat_list = np.linspace(-1,1,10) L = 4 mu = 0 deltat = 0.5 site = 0 psi_array = [] for deltat in deltat_list: print('deltat', deltat) t_list = np.ones(L) for i in range(len(t_list)): t_list[i] -= deltat*(-1)**i psi_0 = [] for V in V_list: print('V', V) E0, psi0 = DMRG_EBH(L, V, t_list, chi_max=chi) psi_0 = np.append(psi_0, psi0) psi_array.append(psi_0) np.save('data/BH_MPS.npy', psi_array) psi_array = np.load('data/BH_MPS.npy', allow_pickle=True) ES_array = [] parity_array = [] dd_array = [] V_list = np.linspace(2,8,10) deltat_list = np.linspace(-1,1,10) for j,deltat in enumerate(deltat_list): ES_list = [] parity_list = [] dd_list = [] psi_list = psi_array[j] for i,V in enumerate(V_list): psi = psi_list[i] ES = np.exp(-np.array(psi.entanglement_spectrum()[2])) dES = -np.sum(ES[::2])+np.sum(ES[1::2]) ES_list.append(dES) dd = psi.expectation_value('dN')[2] dd_list.append(dd) dd_array.append(dd_list) ES_array.append(ES_list) V_list = np.linspace(2,8,10) deltat_list = np.linspace(-1,1,10) fig,ax = plt.subplots(figsize=(8,5)) cmap = plt.get_cmap("plasma") #'viridis' im = ax.pcolormesh(V_list, deltat_list, np.abs(dd_array), cmap=cmap) cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) ax.set_title("density-density correlation",fontsize=20) ax.set_xlabel(r"$V$",fontsize=24) ax.set_ylabel(r"$\delta t$",fontsize=24) ax.tick_params(labelsize=20) fig,ax = plt.subplots(figsize=(8,5)) cmap = plt.get_cmap("plasma") #'viridis' im = ax.pcolormesh(V_list, deltat_list, np.abs(ES_array), cmap=cmap) cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) ax.set_title("Degeneracy entanglement spectrum",fontsize=20) ax.set_xlabel(r"$V$",fontsize=24) ax.set_ylabel(r"$\delta t$",fontsize=24) ax.tick_params(labelsize=20) chi = 50 V_list = np.logspace(-2,2,10) delta_listp= (1-np.logspace(-2,0,5))[::-1] delta_listn = np.logspace(-2,0,5)-1 deltat_list = np.append(delta_listn, delta_listp) #deltat_list = np.linspace(-0.95,0.95,10) L = 10 mu = 0 site = 0 psi_array = [] for deltat in deltat_list: print('deltat', deltat) t_list = np.ones(L-1) for i in range(len(t_list)): t_list[i] -= deltat*(-1)**i psi_0 = [] for V in V_list: print('V', V) E0, psi0 = DMRG_EBH(L, V, t_list, chi_max=chi, bc_MPS='finite') psi_0 = np.append(psi_0, psi0) psi_array.append(psi_0) np.save('data/BH_MPS_L%.0f_logV_logDeltat.npy' %L, psi_array) wf_array = [] V_array = [] deltat_array = [] for i, deltat in enumerate(deltat_list): for j, V in enumerate(V_list): psi = psi_array[i][j] wf = psi.get_theta(0,L).to_ndarray().reshape(-1) wf_array.append(wf) V_array.append(V) deltat_array.append(deltat) np.savez(f'data/wf_BH_L%.0f_logV_logDeltat.npz' %(L), deltat_array=deltat_array, V_array=V_array, wf_array = wf_array) L = 12 psi_array = np.load('../data/BH_MPS_L%.0f_logV_50x50.npy' %L, allow_pickle=True) V_list = np.logspace(-2,2,50) deltat_list = np.linspace(-0.95,0.95,50) ES_array = [] parity_array = [] dd_array = [] for j,deltat in enumerate(deltat_list): ES_list = [] parity_list = [] dd_list = [] psi_list = psi_array[j] for i,V in enumerate(V_list): psi = psi_list[i] ES = np.exp(-np.array(psi.entanglement_spectrum()[int(L/2)+1])) dES = -np.sum(ES[::2])+np.sum(ES[1::2]) ES_list.append(abs(dES)) dd = 0 for i,dd_el in enumerate(psi.expectation_value('dN')[:int(L/2)]): dd += (-1)**i*dd_el dd_list.append(dd/(L-6)) dd_array.append(dd_list) ES_array.append(ES_list) fig,ax = plt.subplots(figsize=(8,5)) cmap = plt.get_cmap("plasma") #'viridis' im = ax.pcolormesh(V_list, deltat_list, dd_array, cmap=cmap) cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) ax.set_title("density-density correlation",fontsize=20) ax.set_xlabel(r"$V$",fontsize=24) ax.set_ylabel(r"$\delta t$",fontsize=24) ax.tick_params(labelsize=20) plt.xscale("log") fig,ax = plt.subplots(figsize=(8,5)) cmap = plt.get_cmap("plasma") #'viridis' im = ax.pcolormesh(V_list, deltat_list, ES_array, cmap=cmap) cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) ax.set_title("Degeneracy entanglement spectrum",fontsize=20) ax.set_xlabel(r"$V$",fontsize=24) ax.set_ylabel(r"$\delta t$",fontsize=24) ax.tick_params(labelsize=20) plt.xscale("log") path = "../data/BH_phase-diagrams-and-loss/data_rike/" np.save(path + "es2.npy", ES_array) np.save(path + "dd2.npy", dd_array) L = 12 psi_array = np.load('data/BH_MPS_L%.0f_logV_50x50.npy' %L, allow_pickle=True) V_list = np.logspace(-2,2,50) deltat_list = np.linspace(-0.95,0.95,50) psi = psi_array[0][0] plt.figure() plt.ylim(-1,1) plt.plot(psi.expectation_value('dN'), 'o-') plt.title('V = %.2f, deltat= %.2f' %(V_list[0], deltat_list[0])) psi = psi_array[49][0] plt.figure() plt.ylim(-1,1) plt.plot(psi.expectation_value('dN'), 'o-') plt.title('V = %.2f, deltat= %.2f' %(V_list[0], deltat_list[9])) psi = psi_array[25][49] plt.figure() plt.ylim(-1,1) plt.plot(psi.expectation_value('dN'), 'o-') plt.title('V = %.2f, deltat= %.2f' %(V_list[9], deltat_list[5])) L = 11 psi_array = np.load('data/BH_MPS_L%.0f_logV_25x25.npy' %L, allow_pickle=True) V_list = np.logspace(-2,2,25) deltat_list = np.linspace(-0.95,0.95,25) ES_array = [] parity_array = [] dd_array = [] for j,deltat in enumerate(deltat_list): ES_list = [] parity_list = [] dd_list = [] psi_list = psi_array[j] for i,V in enumerate(V_list): psi = psi_list[i] ES = np.exp(-np.array(psi.entanglement_spectrum()[int(L/2)])) dES = -np.sum(ES[::2])+np.sum(ES[1::2]) ES_list.append(dES) dd = 0 for dd_el in psi.expectation_value('dN')[3:L-3]: dd += (-1)**i*dd_el #dd = np.sum(abs(psi.expectation_value('dN')[3:L-3])) dd_list.append(dd) dd_array.append(dd_list) ES_array.append(ES_list) fig,ax = plt.subplots(figsize=(8,5)) cmap = plt.get_cmap("plasma") #'viridis' im = ax.pcolormesh(V_list, deltat_list, np.abs(dd_array), cmap=cmap) cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) ax.set_title("density-density correlation",fontsize=20) ax.set_xlabel(r"$V$",fontsize=24) ax.set_ylabel(r"$\delta t$",fontsize=24) ax.tick_params(labelsize=20) plt.xscale("log") fig,ax = plt.subplots(figsize=(8,5)) cmap = plt.get_cmap("plasma") #'viridis' im = ax.pcolormesh(V_list, deltat_list, np.abs(ES_array), cmap=cmap) cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) ax.set_title("Degeneracy entanglement spectrum",fontsize=20) ax.set_xlabel(r"$V$",fontsize=24) ax.set_ylabel(r"$\delta t$",fontsize=24) ax.tick_params(labelsize=20) plt.xscale("log") L = 11 psi_array = np.load('data/BH_MPS_L%.0f_logV_25x25.npy' %L, allow_pickle=True) V_list = np.logspace(-2,2,25) deltat_list = np.linspace(-0.95,0.95,25) psi = psi_array[0][0] plt.figure() plt.ylim(-1,1) plt.plot(psi.expectation_value('dN'), 'o-') plt.title('V = %.2f, deltat= %.2f' %(V_list[0], deltat_list[0])) psi = psi_array[24][0] plt.figure() plt.ylim(-1,1) plt.plot(psi.expectation_value('dN'), 'o-') plt.title('V = %.2f, deltat= %.2f' %(V_list[0], deltat_list[9])) psi = psi_array[15][24] plt.figure() plt.ylim(-1,1) plt.plot(psi.expectation_value('dN'), 'o-') plt.title('V = %.2f, deltat= %.2f' %(V_list[9], deltat_list[5]))
https://github.com/Qottmann/Quantum-anomaly-detection
Qottmann
import time import numpy as np import qiskit from qiskit.opflow import X,Z,I from qiskit.opflow.state_fns import StateFn, CircuitStateFn from qiskit.providers.aer import StatevectorSimulator, AerSimulator from qiskit.algorithms import VQE from qiskit.algorithms.optimizers import COBYLA, SLSQP, SPSA import matplotlib.pyplot as plt from scipy import sparse import scipy.sparse.linalg.eigen.arpack as arp from modules.utils import * from tenpy.networks.mps import MPS from tenpy.models.hubbard import BoseHubbardChain from tenpy.algorithms import dmrg from tenpy.linalg import np_conserved def DMRG_EBH(L, V, t_list, chi_max=30, bc_MPS='infinite'): model_params = dict(n_max=1, filling=0.5, bc_MPS=bc_MPS, t=t_list, L=L, V=V, mu=0, conserve='N', verbose=0) M = BoseHubbardChain(model_params) vector=[] for i in range(M.lat.N_sites): if i%2: vector.append(1) else: vector.append(0) psi = MPS.from_product_state(M.lat.mps_sites(), vector, bc=M.lat.bc_MPS) dmrg_params = { 'mixer': True, 'trunc_params': { 'chi_max': chi_max, }, 'max_E_err': 1.e-16, 'verbose': 0 } info = dmrg.run(psi, M, dmrg_params) return info['E'], psi chi = 50 V_list = np.logspace(-2,2,50) deltat_list = np.linspace(-0.95,0.95,50) L = 12 mu = 0 site = 0 psi_array = [] for deltat in deltat_list: print('deltat', deltat) t_list = np.ones(L-1) for i in range(len(t_list)): t_list[i] -= deltat*(-1)**i psi_0 = [] for V in V_list: print('V', V) E0, psi0 = DMRG_EBH(L, V, t_list, chi_max=chi, bc_MPS='finite') psi_0 = np.append(psi_0, psi0) psi_array.append(psi_0) np.save('data/BH_MPS_L%.0f_logV_50x50.npy' %L, psi_array) wf_array = [] V_array = [] deltat_array = [] for i, deltat in enumerate(deltat_list): for j, V in enumerate(V_list): psi = psi_array[i][j] wf = psi.get_theta(0,L).to_ndarray().reshape(-1) wf_array.append(wf) V_array.append(V) deltat_array.append(deltat) np.savez(f'data/wf_BH_L%.0f_logV_50x50.npz' %(L), deltat_array=deltat_array, V_array=V_array, wf_array = wf_array)
https://github.com/Qottmann/Quantum-anomaly-detection
Qottmann
import time import itertools import numpy as np from scipy.optimize import minimize, basinhopping from qiskit import * from qiskit.quantum_info import Statevector from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B, SPSA from qiskit.opflow.state_fns import StateFn, CircuitStateFn from qiskit.providers.aer import StatevectorSimulator, AerSimulator import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator from matplotlib.colors import BoundaryNorm from modules.utils import * %matplotlib inline cmap = plt.get_cmap("plasma") #'viridis' import qiskit #%matplotlib inline print(qiskit.__version__) #reset random seed np.random.seed(123) from qiskit.utils import algorithm_globals algorithm_globals.random_seed = 123 ### Preliminaries L = 5 num_trash = 2 logspace_size=50 name = f'VQE_Ising_L5_anti_-1_50x50' # _1e-3 # name of the data produced by this notebook filename = "data/params_" + name # name of the data file that is used L = 5 anti = -1. VQE_params = np.load(filename + ".npz", allow_pickle=True) gx_list = VQE_params['gx_list'] gz_list = VQE_params['gz_list'] opt_params = VQE_params['opt_params'] gx_vals = np.unique(gx_list) gz_vals = np.unique(gz_list) mag = QMag(L,anti) #magnetization operator (Qiskit) Smag = Mag(L,anti) #magnetization operator (numpy) # the ~ is the adjoint, but also it turns the is_measurement attribute to True ~StateFn(mag) # state is technically a circuit, that prepares the ground state via VQE circuit #state.draw() # uncomment to see, but is very long Qen=np.zeros(len(opt_params)); Sen=np.zeros(len(opt_params)) #energies Qmags=np.zeros(len(opt_params)); Smags=np.zeros(len(opt_params)) #magnetizations load = True if load: temp = np.load(filename + "_mags-Es.npz",allow_pickle=True) Qmags = temp["Qmags"] Qen = temp["Qen"] Sen = temp["Sen"] Smags = temp["Smags"] if not load: for j in range(len(opt_params)): gx = gx_list[j] gz = gz_list[j] H = QHIsing(L, anti, np.float32(gx), np.float32(gz)) # build Hamiltonian Op state = init_vqe(opt_params[j], L=L) meas_outcome = ~StateFn(mag) @ StateFn(state) Qmags[j] = meas_outcome.eval() e_outcome = ~StateFn(H) @ StateFn(state) Qen[j] = e_outcome.eval() init_state, E, ham = ising_groundstate(L, anti, np.float(gx), np.float(gz)) Sen[j] = E Smags[j] = init_state.T.conj()@Smag@init_state #Magnetization with Numpy results np.savez(filename + "_mags-Es",Qmags=Qmags, Qen=Qen, Sen=Sen, Smags=Smags) # for large parameter space takes quite a while because of the exact diagonalization fig,ax = plt.subplots(figsize=(8,5)) cmap = plt.get_cmap("plasma") #'viridis' im = ax.pcolormesh(gz_vals, gx_vals, abs(Smags).reshape(len(gz_vals),len(gx_vals)), cmap=cmap) cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) plt.xscale("log") plt.yscale("log") ax.set_title("Magnetization ED L %.0f anti %.0f" %(L, anti),fontsize=20) ax.set_xlabel(r"$g_z$",fontsize=24) ax.set_ylabel(r"$g_x$",fontsize=24) ax.tick_params(labelsize=20) fig,ax = plt.subplots(figsize=(8,5)) cmap = plt.get_cmap("plasma") #'viridis' im = ax.pcolormesh(gz_vals, gx_vals, abs(Qmags).reshape(len(gz_vals),len(gx_vals)), cmap=cmap) cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) plt.xscale("log") plt.yscale("log") ax.set_title("Magnetization VQE L %.0f anti %.0f" %(L, anti),fontsize=20) ax.set_xlabel(r"$g_z$",fontsize=24) ax.set_ylabel(r"$g_x$",fontsize=24) ax.tick_params(labelsize=20) fig,ax = plt.subplots(figsize=(8,5)) cmap = plt.get_cmap("plasma") #'viridis' im = ax.pcolormesh(gz_vals, gx_vals, Sen.reshape(len(gz_vals),len(gx_vals)) - Qen.reshape(len(gz_vals),len(gx_vals)), cmap=cmap) cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) plt.xscale("log") plt.yscale("log") ax.set_title("Difference in energy L %.0f anti %.0f" %(L, anti),fontsize=20) ax.set_xlabel(r"$g_z$",fontsize=24) ax.set_ylabel(r"$g_x$",fontsize=24) ax.tick_params(labelsize=20) ############################################################################## ### II - Training ########################################################### ############################################################################## # Use Aer's qasm_simulator backend_sim = Aer.get_backend('qasm_simulator') thetas = np.random.uniform(0, 2*np.pi, 2*L+2) # initial parameters without feature encoding # thetas = np.random.uniform(0, 2*np.pi, (2*L+2, 2)) # initial parameters with feature encoding # linear entangler (as in scales linearly with trash qubits) def get_entangler_map(L, num_trash, i_permut=1): result = [] nums = list(range(L)) # here was the problem, it doesnt like when list elements are taken from numpy nums_compressed = nums.copy()[:L-num_trash] nums_trash = nums.copy()[-num_trash:] #print(nums, nums_compressed, nums_trash) # combine all trash qubits with themselves for trash_q in nums_trash[:-1]: result.append((trash_q+1,trash_q)) # combine each of the trash qubits with every n-th repeated = list(nums_trash) * (L-num_trash) # repeat the list of trash indices cyclicly for i in range(L-num_trash): result.append((repeated[i_permut + i], nums_compressed[i])) return result def QAE_Ansatz(thetas, L, num_trash, insert_barriers=False, parametrized_gate = "ry", entangling_gate = "cz"): entanglement = [get_entangler_map(L,num_trash,i_permut) for i_permut in range(num_trash)] circ = qiskit.circuit.library.TwoLocal(L, parametrized_gate, entangling_gate, entanglement, reps=num_trash, insert_barriers=insert_barriers, skip_final_rotation_layer=True ).assign_parameters(thetas[:-num_trash]) if insert_barriers: circ.barrier() for i in range(num_trash): circ.ry(thetas[L-i-1], L-i-1) #circ.ry(circuit.Parameter(f'θ{i}'), L-i-1) return circ def prepare_circuit(thetas, L=6, num_trash=2, init_state=None, measurement=True, vqe=True): qreg = QuantumRegister(L, 'q') creg = ClassicalRegister(num_trash, 'c') circ = QuantumCircuit(qreg, creg) circ += QAE_Ansatz(thetas, L, num_trash, insert_barriers=True)#.assign_parameters(thetas) # difference to bind? if measurement: for i in range(num_trash): circ.measure(qreg[L-i-1], creg[i]) if init_state is not None: if vqe: circ = init_vqe(init_state,L=L) + circ else: circ.initialize(init_state, qreg) return circ def feature_encoding(thetas, x): """ thetas: parameters to be optimized, x: Ising model parameter (eg. field) """ new_thetas = [] thetas = thetas.reshape((-1,2)) for theta in thetas: new_thetas.append(theta[0] * x + theta[1]) return new_thetas idx = 30 num_trash = 2 J, gx, gz = -1., gx_list[idx], gz_list[idx] # Ising parameters for which ground state should be compressed phi = opt_params[idx] # train on smallest lambda ;; this may grammatically be confusing, init_state = dictionary with unsorted parameters def run_circuit(thetas, L, num_trash, init_state, vqe=True, shots=100): circ = prepare_circuit(thetas, L, num_trash, init_state, vqe=vqe) # Execute the circuit on the qasm simulator. job_sim = execute(circ, backend_sim, shots=shots, seed_simulator=123, seed_transpiler=234) # fix seed to make it reproducible # Grab the results from the job. result_sim = job_sim.result() counts = result_sim.get_counts(circ) # print(counts) # mems = result_sim.get_memory(circ) # print(mems) return counts run_circuit(thetas, L, num_trash, phi)['11'] # translate to Rikes naming phis = opt_params gxs = gx_list gzs = gz_list def cost_function_single(thetas, L, num_trash, p, shots=1000, vqe=True, param_encoding=False, x=0): """ Optimizes circuit """ if vqe: init_state = phis[p] else: J, gx, gz = p init_state, _ = ising_groundstate(L, J, gx, gz) if param_encoding: thetas = feature_encoding(thetas, x) out = run_circuit(thetas, L, num_trash, init_state, vqe=vqe, shots=shots) cost = out.get('11', 0)*2 + out.get('01', 0) + out.get('10', 0) return cost/shots def cost_function(thetas, L, num_trash, ising_params, shots=1000, vqe=True, param_encoding=False, x=0): """ Optimizes circuit """ cost = 0. n_samples = len(ising_params) for i, p in enumerate(ising_params): if param_encoding: cost += cost_function_single(thetas, L, num_trash, p, shots, vqe, param_encoding, x[i]) else: cost += cost_function_single(thetas, L, num_trash, p, shots, vqe, param_encoding) return cost/n_samples def optimize(ising_params, L=6, num_trash=2, thetas=None, shots=1000, max_iter=400, vqe=True, param_encoding=False, x=0, pick_optimizer = None): if thetas is None: n_params = (2*L+2)*2 if param_encoding else (2*L+2) thetas = np.random.uniform(0, 2*np.pi, n_params) # initial parameters without feature encoding print("Initial cost: {:.3f}".format(cost_function(thetas, L, num_trash, ising_params, shots, vqe, param_encoding, x))) counts, values, accepted = [], [], [] def store_intermediate_result(eval_count, parameters, mean, std, ac): # counts.append(eval_count) values.append(mean) accepted.append(ac) # Initialize optimizer if pick_optimizer == "cobyla": optimizer = COBYLA(maxiter=max_iter, tol=0.0001) if pick_optimizer == "adam" or pick_optimizer == "ADAM": optimizer = qiskit.algorithms.optimizers.ADAM(maxiter=max_iter) # optimizer = L_BFGS_B(maxfun=300, maxiter=max_iter)#, factr=10, iprint=- 1, epsilon=1e-08) if pick_optimizer == "spsa" or pick_optimizer == None: optimizer = SPSA(maxiter=max_iter, #blocking=True, callback=store_intermediate_result, #learning_rate=1e-1, #perturbation=0.4 ) # recommended from qiskit (first iteraction takes quite long) # to reduce time figure out optimal learning rate and perturbation in advance start_time = time.time() ret = optimizer.optimize( num_vars=len(thetas), objective_function=(lambda thetas: cost_function(thetas, L, num_trash, ising_params, shots, vqe, param_encoding, x)), initial_point=thetas ) print("Time: {:.5f} sec".format(time.time()-start_time)) print(ret) return ret[0], values, accepted x,y = np.meshgrid(gx_vals, gz_vals) def run_inference(thetas, shots=1000, L=5): points = 50 J = -1.0 x,y = np.meshgrid(gx_vals, gz_vals) cost = np.zeros((len(gx_vals) * len(gz_vals))) Smags = np.zeros((len(gx_vals) * len(gz_vals))) shots = 1000 for i,p in enumerate(list(zip(gxs, gzs))): cost[i] = cost_function_single(thetas, L, num_trash, i, shots=shots) cost = cost.reshape((len(gx_vals), len(gz_vals))) return cost cmap = plt.get_cmap("plasma") def plot_result(cost): fig,axs = plt.subplots(ncols=2,figsize=(15,5)) nbins=100 ax = axs[0] im = ax.pcolormesh(x, y, cost, cmap=cmap, shading="auto") cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) ax.set_xscale("log") ax.set_yscale("log") ax.set_title(f"Loss",fontsize=20) ax.set_xlabel(r"$g_z$",fontsize=24) ax.set_ylabel(r"$g_x$",fontsize=24) ax.tick_params(labelsize=20) for p in params: gz = gz_list[p] gx = gx_list[p] ax.plot(gz,gx,"o",label="training",color="cyan") ax = axs[1] im = ax.pcolormesh(gz_vals, gx_vals, abs(Qmags).reshape(len(gz_vals),len(gx_vals)), cmap=cmap, shading="auto") cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) ax.set_xscale("log") ax.set_yscale("log") ax.set_title("Magnetization VQE L %.0f anti %.0f" %(L, anti),fontsize=20) ax.set_xlabel(r"$g_z$",fontsize=24) ax.set_ylabel(r"$g_x$",fontsize=24) ax.tick_params(labelsize=20) paramss =[ [0], # train on bottom left point np.intersect1d(np.where(gx_list > 99),np.where(gz_list == 1e-2)), # top left np.intersect1d(np.where(gz_list > 99),np.where(gx_list == 1e-2)), # bottom right [2450, 49] # both paramagnetic phases ] for i,params in enumerate(paramss): print(f"{i} / {len(paramss)} - params (gz, gx) in {[(gzs[p], gxs[p]) for p in params]}") thetass = [None] * len(paramss) losss = [None] * len(paramss) costs = [None] * len(paramss) for i,params in enumerate(paramss): print(f"{i+1} / {len(paramss)} - params (gz, gx) in {[(gzs[p], gxs[p]) for p in params]}") thetas, loss, accepted = optimize(params, max_iter=100, L=5) #, pick_optimizer="adam") thetass[i], losss[i] = thetas, loss plt.plot(loss) cost = run_inference(thetas) costs[i] = cost np.savez("data/" + name + "_thetas-loss-cost", losss = losss, costs = costs, thetass = thetass) for i,params in enumerate(paramss): print(f"{i+1} / {len(paramss)} - params (gz, gx) in {[(gzs[p], gxs[p]) for p in params]}") plot_result(np.load("data/" + name + "_thetas-loss-cost.npz",allow_pickle=True)["costs"][i]) plt.show() fig, axs = plt.subplots(ncols=2,figsize=(10,5)) ax = axs[0] ax.imshow(np.load("data/" + name + "_thetas-loss-cost.npz",allow_pickle=True)["costs"][0]) ax = axs[1] ax.imshow(np.load("data/" + name + "_thetas-loss-cost2.npz",allow_pickle=True)["costs"][0]) algorithm_globals.random_seed = 321 for i,params in enumerate(paramss): print(f"{i+1} / {len(paramss)} - params (gz, gx) in {[(gzs[p], gxs[p]) for p in params]}") thetas, loss, accepted = optimize(params, max_iter=100, L=5) #, pick_optimizer="adam") thetass[i], losss[i] = thetas, loss plt.plot(loss) cost = run_inference(thetas) costs[i] = cost np.savez("data/" + name + "_thetas-loss-cost2", losss = losss, costs = costs, thetass = thetass) for i,params in enumerate(paramss): print(f"{i+1} / {len(paramss)} - params (gz, gx) in {[(gzs[p], gxs[p]) for p in params]}") plot_result(np.load("data/" + name + "_thetas-loss-cost2.npz",allow_pickle=True)["costs"][i]) plt.show() for i,params in enumerate(paramss): print(f"{i+1} / {len(paramss)} - params (gz, gx) in {[(gzs[p], gxs[p]) for p in params]}") thetas, loss, accepted = optimize(params, max_iter=100, L=5, pick_optimizer="cobyla") thetass[i], losss[i] = thetas, loss plt.plot(loss) cost = run_inference(thetas) costs[i] = cost np.savez("data/" + name + "_thetas-loss-cost_cobyla", losss = losss, costs = costs, thetass = thetass) for i,params in enumerate(paramss): print(f"{i+1} / {len(paramss)} - params (gz, gx) in {[(gzs[p], gxs[p]) for p in params]}") plot_result(np.load("data/" + name + "_thetas-loss-cost_cobyla.npz",allow_pickle=True)["costs"][i]) plt.show()
https://github.com/Qottmann/Quantum-anomaly-detection
Qottmann
import time import itertools import numpy as np from scipy.optimize import minimize, basinhopping from qiskit import * from qiskit.quantum_info import Statevector from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B, SPSA import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator from matplotlib.colors import BoundaryNorm from modules.utils import Mag %matplotlib inline cmap = plt.get_cmap("plasma") #'viridis' plt.rc('font', family='serif')#, serif='Times') plt.rc('text', usetex=True) plt.rc('xtick', labelsize=14) plt.rc('ytick', labelsize=14) plt.rc('axes', labelsize=16) plt.rc('legend', fontsize=14) plt.rc('legend', handlelength=2) plt.rc('axes', titlesize=20) # from: https://tenpy.readthedocs.io/en/latest/toycodes/tfi_exact.html import numpy as np import scipy.sparse as sparse import scipy.sparse.linalg.eigen.arpack as arp import warnings import scipy.integrate def ising_groundstate(L, J, gx, gz=0): # gx is transverse field, gz the longitudinal """For comparison: obtain ground state energy from exact diagonalization. Exponentially expensive in L, only works for small enough `L` <~ 20. """ if L >= 20: warnings.warn("Large L: Exact diagonalization might take a long time!") # get single site operaors sx = sparse.csr_matrix(np.array([[0., 1.], [1., 0.]])) sz = sparse.csr_matrix(np.array([[1., 0.], [0., -1.]])) id = sparse.csr_matrix(np.eye(2)) sx_list = [] # sx_list[i] = kron([id, id, ..., id, sx, id, .... id]) sz_list = [] for i_site in range(L): x_ops = [id] * L z_ops = [id] * L x_ops[i_site] = sx z_ops[i_site] = sz X = x_ops[0] Z = z_ops[0] for j in range(1, L): X = sparse.kron(X, x_ops[j], 'csr') Z = sparse.kron(Z, z_ops[j], 'csr') sx_list.append(X) sz_list.append(Z) H_zz = sparse.csr_matrix((2**L, 2**L)) H_z = sparse.csr_matrix((2**L, 2**L)) H_x = sparse.csr_matrix((2**L, 2**L)) for i in range(L - 1): H_zz = H_zz + sz_list[i] * sz_list[(i + 1) % L] for i in range(L): H_z = H_z + sz_list[i] H_x = H_x + sx_list[i] H = -J * H_zz - gx * H_x - gz * H_z E, V = arp.eigsh(H, k=1, which='SA', return_eigenvectors=True, ncv=20) return V[:,0], E[0] init_state, E = ising_groundstate(6, 1., 1., 1.) def sort_vals(vals): """ vals is (unsorted) dictionary of parameters from VQE ansatz circuit, this returns sorted values as list """ indices = np.array([_.index for _ in vals]) # unordered list of indices from the ParameterVectorElement(Theta(INDEX)) vals_sorted = np.array([vals[_] for _ in vals]) # unordered list of values (but same ordering as indices) return vals_sorted[np.argsort(indices)] def init_vqe(vals, L): #return qiskit.circuit.library.EfficientSU2(L, reps=3).assign_parameters(sort_vals(vals)) return qiskit.circuit.library.EfficientSU2(L, reps=3).assign_parameters(vals) L = 5 anti = -1 #filename = f'data/params_VQE_Ising_L{L}_anti_{anti}.npz' # name of the data file that is used filename = f'data/params_VQE_Ising_L{L}_anti_{anti}_50x50.npz' VQE_vals = np.load(filename, allow_pickle=True) gxs = VQE_vals['gx_list'] gzs = VQE_vals['gz_list'] phis = VQE_vals['opt_params'] N = int(np.sqrt(gxs.size)) gxs = np.logspace(-2, 2, N)#gxs.reshape(N,N) gzs = np.logspace(-2, 2, N)#gzs.reshape(N,N) phis = phis.reshape(N,N,-1) #(gx, gz) # Use Aer's qasm_simulator backend_sim = Aer.get_backend('qasm_simulator') L = 5 # system size num_trash = 2 thetas = np.random.uniform(0, 2*np.pi, num_trash*L+num_trash) # initial parameters without feature encoding # thetas = np.random.uniform(0, 2*np.pi, (2*L+2, 2)) # initial parameters with feature encoding def prepare_circuit(init_state=None, measurement=True): qreg = QuantumRegister(L, 'q') creg = ClassicalRegister(2, 'c') circ = QuantumCircuit(qreg, creg) entangler_map1 = [(5, 4), (5, 3), (5, 1), (4, 2), (4, 0)] entangler_map2 = [(5, 4), (5, 2), (4, 3), (5, 0), (4, 1)] circ += circuit.library.TwoLocal(L, 'ry', 'cz', entanglement = [entangler_map1, entangler_map2], reps=2, insert_barriers=True, skip_final_rotation_layer=True) circ.ry(circuit.Parameter('θ1'), 4) circ.ry(circuit.Parameter('θ2'), 5) if measurement: circ.measure(qreg[4], creg[0]) circ.measure(qreg[5], creg[1]) if init_state is not None: circ = init_vqe(init_state) + circ return circ # same circuit as above (more explicit) def prepare_circuit2(thetas, init_state=None, measurement=True): qreg = QuantumRegister(L, 'q') creg = ClassicalRegister(2, 'c') circ = QuantumCircuit(qreg, creg) #if init_state is not None: circ.initialize(init_state, qreg) for i,t in enumerate(thetas[:L]): circ.ry(t, i) circ.cz(5,4) circ.cz(5,3) circ.cz(5,1) circ.cz(4,2) circ.cz(4,0) for i,t in enumerate(thetas[L:2*L]): circ.ry(t, i) circ.cz(5,4) circ.cz(5,2) circ.cz(4,3) circ.cz(5,0) circ.cz(4,1) circ.ry(thetas[2*L], 4) circ.ry(thetas[2*L+1], 5) if measurement: circ.measure(qreg[4], creg[0]) circ.measure(qreg[5], creg[1]) if init_state is not None: circ = init_vqe(init_state) + circ return circ # linear entangler (as in scales linearly with trash qubits) def get_entangler_map(L, num_trash, i_permut=1): result = [] nums = list(range(L)) # here was the problem, it doesnt like when list elements are taken from numpy nums_compressed = nums.copy()[:L-num_trash] nums_trash = nums.copy()[-num_trash:] #print(nums, nums_compressed, nums_trash) # combine all trash qubits with themselves for trash_q in nums_trash[:-1]: result.append((trash_q+1,trash_q)) # combine each of the trash qubits with every n-th repeated = list(nums_trash) * (L-num_trash) # repeat the list of trash indices cyclicly for i in range(L-num_trash): result.append((repeated[i_permut + i], nums_compressed[i])) return result def QAE_Ansatz(thetas, L, num_trash, insert_barriers=False, parametrized_gate = "ry", entangling_gate = "cz"): entanglement = [get_entangler_map(L,num_trash,i_permut) for i_permut in range(num_trash)] circ = qiskit.circuit.library.TwoLocal(L, parametrized_gate, entangling_gate, entanglement, reps=num_trash, insert_barriers=insert_barriers, skip_final_rotation_layer=True ).assign_parameters(thetas[:-num_trash]) if insert_barriers: circ.barrier() for i in range(num_trash): circ.ry(thetas[L-i-1], L-i-1) #circ.ry(circuit.Parameter(f'θ{i}'), L-i-1) return circ def prepare_circuit3(thetas, L=6, num_trash=2, init_state=None, measurement=True, vqe=True): qreg = QuantumRegister(L, 'q') creg = ClassicalRegister(num_trash)#?, 'c') circ = QuantumCircuit(qreg, creg) print(circ.cregs) if init_state is not None: if not vqe: circ.initialize(init_state, qreg) circ += QAE_Ansatz(thetas, L, num_trash, insert_barriers=True)#.assign_parameters(thetas) # difference to bind? if measurement: for i in range(num_trash): circ.measure(qreg[L-i-1], creg[i]) if init_state is not None: if vqe: circ = init_vqe(init_state, L) + circ #else: # circ.initialize(init_state, qreg) return circ def feature_encoding(thetas, x): """ thetas: parameters to be optimized, x: Ising model parameter (eg. field) """ new_thetas = [] thetas = thetas.reshape((-1,2)) for theta in thetas: new_thetas.append(theta[0] * x + theta[1]) return new_thetas idx = 30 J, gx, gz = -1., gxs[idx], gzs[idx] phi = phis[idx, idx] def run_circuit(thetas, L, num_trash, init_state, vqe=True, shots=100): circ = prepare_circuit3(thetas, L, num_trash, init_state, vqe=vqe) # Execute the circuit on the qasm simulator. job_sim = execute(circ, backend_sim, shots=shots)#, memory=True) # Grab the results from the job. result_sim = job_sim.result() counts = result_sim.get_counts(circ) # print(counts) # mems = result_sim.get_memory(circ) # print(mems) return counts run_circuit(thetas, L, num_trash, phi) #reset random seed np.random.seed(123) def hamming_distance(out): return sum(key.count('1') * value for key, value in out.items()) def cost_function_single(thetas, L, num_trash, p, shots=1000, vqe=True, param_encoding=False, x=0, model="bh"): """ Optimizes circuit """ if vqe: init_state = phis[p] else: if model=="ising": J, gx, gz = p init_state, _ = ising_groundstate(L, J, gx, gz) elif model=="bh": init_state = p#init_states[p] if param_encoding: thetas = feature_encoding(thetas, x) out = run_circuit(thetas, L, num_trash, init_state, vqe=vqe, shots=shots) cost = hamming_distance(out) return cost/shots def cost_function(thetas, L, num_trash, ising_params, shots=1000, vqe=True, param_encoding=False, x=0): """ Optimizes circuit """ cost = 0. n_samples = len(ising_params) for i, p in enumerate(ising_params): if param_encoding: cost += cost_function_single(thetas, L, num_trash, p, shots, vqe, param_encoding, x[i]) else: cost += cost_function_single(thetas, L, num_trash, p, shots, vqe, param_encoding) return cost/n_samples def optimize(ising_params, L=6, num_trash=2, thetas=None, shots=1000, max_iter=500, lr=None, perturbation=None, vqe=True, param_encoding=False, x=0): if thetas is None: n_params = (num_trash*L+num_trash)*2 if param_encoding else (num_trash*L+num_trash) thetas = np.random.uniform(0, 2*np.pi, n_params) # initial parameters without feature encoding print("Initial cost: {:.3f}".format(cost_function(thetas, L, num_trash, ising_params, shots, vqe, param_encoding, x))) counts, values, accepted = [], [], [] def store_intermediate_result(eval_count, parameters, mean, std, ac): # counts.append(eval_count) values.append(mean) accepted.append(ac) # Initialize optimizer # optimizer = COBYLA(maxiter=max_iter, tol=0.0001) # optimizer = L_BFGS_B(maxfun=300, maxiter=max_iter)#, factr=10, iprint=- 1, epsilon=1e-08) optimizer = SPSA(maxiter=max_iter, #blocking=True, # callback=store_intermediate_result, learning_rate=lr, perturbation=perturbation ) # recommended from qiskit (first iteraction takes quite long) # to reduce time figure out optimal learning rate and perturbation in advance start_time = time.time() ret = optimizer.optimize( num_vars=len(thetas), objective_function=(lambda thetas: cost_function(thetas, L, num_trash, ising_params, shots, vqe, param_encoding, x)), initial_point=thetas ) print("Time: {:.5f} sec".format(time.time()-start_time)) print(ret) return ret[0], values, accepted thetas, loss, accepted = optimize(params, L, 2, max_iter=itera) fig = plt.figure(figsize=(12,4)) plt.subplot(1, 2, 1) plt.plot(losses[2,1,:], "x--") #2,2 1,2 plt.yscale("log") plt.xlabel("step") plt.ylabel("Loss"); for i,lr in enumerate(lrs): for j,p in enumerate(perturbations): fig = plt.figure(figsize=(12,4)) plt.subplot(1, 2, 1) plt.plot(losses[i,j,:], "x--") plt.yscale("log") plt.xlabel("step") plt.ylabel("Loss"); for i,lr in enumerate(lrs): for j,p in enumerate(perturbations): fig = plt.figure(figsize=(12,4)) plt.subplot(1, 2, 1) plt.plot(losses[i,j,:], "x--") plt.yscale("log") plt.xlabel("step") plt.ylabel("Loss"); params = [(13,13)] num_trash = 2 print(gxs[params[0][0]], gzs[params[0][1]]) thetas, loss, accepted = optimize(params, L, 2, max_iter=40) thetas_normal_phase_2 = thetas len(loss) params = [(13,13)] num_trash = 2 print(gxs[params[0][0]], gzs[params[0][1]]) thetas, loss, accepted = optimize(params, L, 2, max_iter=40) thetas_normal_phase_2 = thetas params = [(18,38)] thetas_test, loss, accepted = optimize(params, L, max_iter=40) params = [(13,13)] thetas_test, loss, accepted = optimize(params, 5, 2, max_iter=40, vqe=False) L = 5 anti = -1 # filename = f'data/params_VQE_Ising_L{L}_anti_{anti}.npz' # name of the data file that is used filename = f'data/params_VQE_Ising_L{L}_anti_{anti}_50x50.npz' VQE_vals = np.load(filename, allow_pickle=True) gxs = VQE_vals['gx_list'] gzs = VQE_vals['gz_list'] phis = VQE_vals['opt_params'] N = int(np.sqrt(gxs.size)) gxs = np.logspace(-2, 2, N)#gxs.reshape(N,N) gzs = np.logspace(-2, 2, N)#gzs.reshape(N,N) phis = phis.reshape(N,N,-1) #(gx, gz) params = [(16,37),(37,16)] num_trash = 2 print(gxs[params[0][0]], gzs[params[0][1]]) thetas, loss, accepted = optimize(params, L, num_trash) thetas_normal_phase_2 = thetas seeds = np.arange(20) + 10 for seed in seeds: cost = np.load(f'data_rike/cost_bh_L12_trash2_d48_v5_seed{seed}.npy', allow_pickle=True) # 7, 10 params = [[48,5]] # cost = np.load(f'data_rike/cost_bh_L12_trash2_d2_v5_seed{seed}.npy', allow_pickle=True) # -2 # cost = np.load(f'data_rike/cost_bh_L12_trash4_d2_v5_seed{seed}.npy', allow_pickle=True) # params = [[2,5]] # cost = np.load(f'data_rike/cost_bh_L12_trash2_d10_v10_seed{seed}.npy', allow_pickle=True) # 3, 6 # cost = np.load(f'data_rike/cost_bh_L12_trash4_d10_v10_seed{seed}.npy', allow_pickle=True) # params = [[10,10]] fig,axs = plt.subplots(figsize=(8,5),squeeze=False) nbins=100 ax = axs[0,0] levels = MaxNLocator(nbins=nbins).tick_values(cost.min(),cost.max()) norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True) im = ax.pcolormesh(y, x, cost.T, cmap=cmap, norm=norm) cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) plt.xscale("log") # plt.yscale("log") ax.set_title("Loss",fontsize=20) ax.set_xlabel(r"$V$",fontsize=24) ax.set_ylabel(r"$\delta t$",fontsize=24) ax.tick_params(labelsize=20) for p in params: d = deltas[p[0]] V = Vs[p[1]] ax.plot(V,d,"o",label="training",color="cyan") plt.show() fig = plt.figure(figsize=(12,4)) plt.subplot(1, 2, 1) plt.plot(loss, "x--") plt.yscale("log") plt.xlabel("step") plt.ylabel("Loss"); points = 50 J = -1.0 x,y = np.meshgrid(gxs,gzs) cost = np.zeros((points,points)) #Smags = np.zeros((points,points)) shots = 1000 for i,gx in enumerate(gxs): for j,gz in enumerate(gzs): cost[i,j] = cost_function_single(thetas, L, num_trash, (i,j), shots=shots) #init_state, _ = ising_groundstate(5, J, gx, gz) #Smags[i,j] = np.real(init_state.T.conj()@Mag(5,-1)@init_state) fig,axs = plt.subplots(figsize=(8,5),squeeze=False) nbins=100 ax = axs[0,0] levels = MaxNLocator(nbins=nbins).tick_values(cost.min(),cost.max()) norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True) im = ax.pcolormesh(x, y, cost, cmap=cmap, norm=norm) cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) plt.xscale("log") plt.yscale("log") ax.set_title("Loss",fontsize=20) ax.set_xlabel(r"$g_z$",fontsize=24) ax.set_ylabel(r"$g_x$",fontsize=24) ax.tick_params(labelsize=20) fig,axs = plt.subplots(figsize=(8,5),squeeze=False) nbins=100 ax = axs[0,0] levels = MaxNLocator(nbins=nbins).tick_values(Smags.min(),Smags.max()) norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True) im = ax.pcolormesh(x, y, Smags, cmap=cmap, norm=norm) cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) plt.xscale("log") plt.yscale("log") ax.set_title("Staggered magnetization",fontsize=20) ax.set_xlabel(r"$g_z$",fontsize=24) ax.set_ylabel(r"$g_x$",fontsize=24) ax.tick_params(labelsize=20) fig,axs = plt.subplots(figsize=(8,5),squeeze=False) nbins=100 ax = axs[0,0] levels = MaxNLocator(nbins=nbins).tick_values(cost.min(),cost.max()) norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True) im = ax.pcolormesh(x, y, cost, cmap=cmap, norm=norm) cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) plt.xscale("log") plt.yscale("log") ax.set_title("Loss",fontsize=20) ax.set_xlabel(r"$g_z$",fontsize=24) ax.set_ylabel(r"$g_x$",fontsize=24) ax.tick_params(labelsize=20) fig,axs = plt.subplots(figsize=(8,5),squeeze=False) nbins=100 ax = axs[0,0] levels = MaxNLocator(nbins=nbins).tick_values(Smags.min(),Smags.max()) norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True) im = ax.pcolormesh(x, y, Smags, cmap=cmap, norm=norm) cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) plt.xscale("log") plt.yscale("log") ax.set_title("Staggered magnetization",fontsize=20) ax.set_xlabel(r"$g_z$",fontsize=24) ax.set_ylabel(r"$g_x$",fontsize=24) ax.tick_params(labelsize=20) J = -1 gz = gzs[0] cost1, Smags1, Smags12 = [], [], [] shots = 10000 Ll = 5 for i,gx in enumerate(gxs): cost1.append(cost_function_single(thetas, L, num_trash, (i, 0), shots=shots)) init_state, _ = ising_groundstate(Ll, J, gx, gz) Smags1.append(np.real(init_state.T.conj()@Mag(Ll,-1)@init_state)) #init_state, _ = ising_groundstate(Ll+2, J, gx, gz) #Smags12.append(np.real(init_state.T.conj()@Mag(Ll+2,-1)@init_state)) gx = gxs[0] cost2, Smags2, Smags22 = [], [], [] for i,gz in enumerate(gzs): cost2.append(cost_function_single(thetas, L, num_trash, (0, i), shots=shots)) init_state, _ = ising_groundstate(Ll, J, gx, gz) Smags2.append(np.real(init_state.T.conj()@Mag(Ll,-1)@init_state)) #init_state, _ = ising_groundstate(Ll+2, J, gx, gz) #Smags22.append(np.real(init_state.T.conj()@Mag(Ll+2,-1)@init_state)) fig = plt.figure(figsize=(12,4)) ax1 = plt.subplot(121) ax2 = ax1.twinx() ax3 = plt.subplot(122) ax4 = ax3.twinx() ax1.set_xlabel(r"$g_z$") ax1.set_ylabel("Cost") ax1.plot(gzs, cost1, "x--") ax2.plot(gzs, Smags1, "g-.") #ax2.plot(gzs, Smags12, "r--") ax2.set_ylabel("Staggered mag.") ax2.set_xscale("log") ax3.set_xlabel(r"$g_x$") ax3.set_ylabel("Cost") ax3.plot(gzs, cost2, "x--") ax4.plot(gzs, Smags2, "g-.") #ax4.plot(gzs, Smags22, "r--") ax4.set_xscale("log") ax4.set_ylabel("Staggered mag.") fig.tight_layout() params = [(13,13)] num_trash = 4 print(gxs[params[0][0]], gzs[params[0][1]]) thetas, loss, accepted = optimize(params, L, num_trash) thetas_ordered_phase_4 = thetas fig = plt.figure(figsize=(12,4)) plt.subplot(1, 2, 1) plt.plot(loss, "x--") plt.yscale("log") plt.xlabel("step") plt.ylabel("Loss"); thetas = thetas_ordered_phase_2 num_trash = 2 points = 50 J = -1.0 x,y = np.meshgrid(gxs,gzs) cost = np.zeros((points,points)) #Smags = np.zeros((points,points)) shots = 1000 for i,gx in enumerate(gxs): for j,gz in enumerate(gzs): cost[i,j] = cost_function_single(thetas, L, num_trash, (i,j), shots=shots) #init_state, _ = ising_groundstate(5, J, gx, gz) #Smags[i,j] = np.real(init_state.T.conj()@Mag(5,-1)@init_state) fig,axs = plt.subplots(figsize=(8,5),squeeze=False) nbins=100 ax = axs[0,0] levels = MaxNLocator(nbins=nbins).tick_values(cost.min(),cost.max()) norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True) im = ax.pcolormesh(x, y, cost, cmap=cmap, norm=norm) cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) plt.xscale("log") plt.yscale("log") ax.set_title("Loss",fontsize=20) ax.set_xlabel(r"$g_z$",fontsize=24) ax.set_ylabel(r"$g_x$",fontsize=24) ax.tick_params(labelsize=20) fig,axs = plt.subplots(figsize=(8,5),squeeze=False) nbins=100 ax = axs[0,0] levels = MaxNLocator(nbins=nbins).tick_values(Smags.min(),Smags.max()) norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True) im = ax.pcolormesh(x, y, Smags, cmap=cmap, norm=norm) cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) plt.xscale("log") plt.yscale("log") ax.set_title("Staggered magnetization",fontsize=20) ax.set_xlabel(r"$g_z$",fontsize=24) ax.set_ylabel(r"$g_x$",fontsize=24) ax.tick_params(labelsize=20) # 3 trash qubits fig,axs = plt.subplots(figsize=(8,5),squeeze=False) nbins=100 ax = axs[0,0] levels = MaxNLocator(nbins=nbins).tick_values(cost.min(),cost.max()) norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True) im = ax.pcolormesh(x, y, cost, cmap=cmap, norm=norm) cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) plt.xscale("log") plt.yscale("log") ax.set_title("Loss",fontsize=20) ax.set_xlabel(r"$g_z$",fontsize=24) ax.set_ylabel(r"$g_x$",fontsize=24) ax.tick_params(labelsize=20) fig,axs = plt.subplots(figsize=(8,5),squeeze=False) nbins=100 ax = axs[0,0] levels = MaxNLocator(nbins=nbins).tick_values(Smags.min(),Smags.max()) norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True) im = ax.pcolormesh(x, y, Smags, cmap=cmap, norm=norm) cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) plt.xscale("log") plt.yscale("log") ax.set_title("Staggered magnetization",fontsize=20) ax.set_xlabel(r"$g_z$",fontsize=24) ax.set_ylabel(r"$g_x$",fontsize=24) ax.tick_params(labelsize=20) # 2 trash qubits fig,axs = plt.subplots(figsize=(8,5),squeeze=False) cost_shift = np.abs(1-cost) nbins=100 ax = axs[0,0] levels = MaxNLocator(nbins=nbins).tick_values(cost_shift.min(),cost_shift.max()) norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True) im = ax.pcolormesh(x, y, cost_shift, cmap=cmap, norm=norm) cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) plt.xscale("log") plt.yscale("log") ax.set_title("Loss",fontsize=20) ax.set_xlabel(r"$g_z$",fontsize=24) ax.set_ylabel(r"$g_x$",fontsize=24) ax.tick_params(labelsize=20) fig,axs = plt.subplots(figsize=(8,5),squeeze=False) nbins=100 ax = axs[0,0] levels = MaxNLocator(nbins=nbins).tick_values(Smags.min(),Smags.max()) norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True) im = ax.pcolormesh(x, y, Smags, cmap=cmap, norm=norm) cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) plt.xscale("log") plt.yscale("log") ax.set_title("Staggered magnetization",fontsize=20) ax.set_xlabel(r"$g_z$",fontsize=24) ax.set_ylabel(r"$g_x$",fontsize=24) ax.tick_params(labelsize=20) # 2 trash qubits cmap = plt.get_cmap("plasma") def plot_result(cost, params): fig,axs = plt.subplots(figsize=(8,5),squeeze=False) nbins=100 ax = axs[0,0] im = ax.pcolormesh(x, y, cost.T, cmap=cmap, shading="auto") cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) ax.set_yscale("log") # plt.xscale("log") ax.set_title("Loss",fontsize=20) ax.set_ylabel(r"$V$",fontsize=24) ax.set_xlabel(r"$\delta t$",fontsize=24) ax.tick_params(labelsize=20) for p in params: d = deltas[p[0]] V = Vs[p[1]] ax.plot(d,V,"o",label="training",color="cyan") L = 12 N = 50 #filename = f'data/wf_BH_L{L}.npz' #filename = '../wf_BH_L20.npz' #filename = 'data/wf_BH_L10_logV.npz' filename = 'data/wf_BH_L12_logV_50x50.npz' VQE_vals = np.load(filename, allow_pickle=True) deltas = VQE_vals['deltat_array'] Vs = VQE_vals['V_array'] init_states = VQE_vals['wf_array'] # Vs = np.linspace(2,8,10) # Vs = np.linspace(0,1,10) Vs = np.logspace(-2,2,N) # deltas = np.linspace(-1,1,10) # deltas = np.linspace(-2,2,10) deltas = np.linspace(-0.95,0.95,N) init_states = init_states.reshape(N,N,-1) #(delta, V) dd_vals = np.load('data/BH_dd_L12.npz', allow_pickle=True) # deltas = dd_vals['deltat_array'] dd = dd_vals['dd_array'].reshape(N,N) # init_states = VQE_vals['wf_array'] es_vals = np.load('data/BH_ES_L12.npz', allow_pickle=True) es = es_vals['ES_array'].reshape(N,N) print(deltas[48], Vs[1]) num_trash = 2 thetas, loss, accepted = optimize([init_states[-2,1]], L, num_trash, max_iter=1500, vqe=False) thetas_bh12_10_2 = thetas fig = plt.figure(figsize=(12,4)) plt.subplot(1, 2, 1) plt.plot(loss, "x--") #plt.yscale("log") plt.xlabel("step") plt.ylabel("Loss"); thetas = thetas_bh__1_2 points = 50 x,y = np.meshgrid(deltas,Vs) # cost = np.zeros((points,points)) # Smags = np.zeros((points,points)) # shots = 1000 # for i,d in enumerate(deltas): # print(i) # for j,v in enumerate(Vs): # cost[i,j] = cost_function_single(thetas, L, num_trash, init_states[i,j], shots=shots, vqe=False) #cost_bh12_10_2 = cost np.save(f'data_rike/cost_bh_L{L}_trash{num_trash}_d5_v50.npy', cost_bh12__1_2) dd.shape np.save('../data_rike/es.npy', es) x,y = np.meshgrid(deltas,Vs) np.save('../data_rike/x.npy', y) x params = [[-2,1]] cost = dd fig,axs = plt.subplots(figsize=(8,5),squeeze=False) nbins=100 ax = axs[0,0] levels = MaxNLocator(nbins=nbins).tick_values(cost.min(),cost.max()) norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True) im = ax.pcolormesh(y, x, cost.T, cmap=cmap, norm=norm) cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) plt.xscale("log") # plt.yscale("log") ax.set_title("Loss",fontsize=20) ax.set_xlabel(r"$V$",fontsize=24) ax.set_ylabel(r"$\delta t$",fontsize=24) ax.tick_params(labelsize=20) for p in params: d = deltas[p[0]] V = Vs[p[1]] ax.plot(V,d,"o",label="training",color="cyan") #2 trash qubit params = [[0,0]] fig,axs = plt.subplots(figsize=(8,5),squeeze=False) nbins=100 ax = axs[0,0] levels = MaxNLocator(nbins=nbins).tick_values(cost.min(),cost.max()) norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True) im = ax.pcolormesh(y, x, cost.T, cmap=cmap, norm=norm) cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) plt.xscale("log") # plt.yscale("log") ax.set_title("Loss",fontsize=20) ax.set_xlabel(r"$V$",fontsize=24) ax.set_ylabel(r"$\delta t$",fontsize=24) ax.tick_params(labelsize=20) for p in params: d = deltas[p[0]] V = Vs[p[1]] ax.plot(V,d,"o",label="training",color="cyan") #2 trash qubit params = [[5,-1]] fig,axs = plt.subplots(figsize=(8,5),squeeze=False) nbins=100 ax = axs[0,0] levels = MaxNLocator(nbins=nbins).tick_values(cost.min(),cost.max()) norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True) im = ax.pcolormesh(y, x, cost.T, cmap=cmap, norm=norm) cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) plt.xscale("log") # plt.yscale("log") ax.set_title("Loss",fontsize=20) ax.set_xlabel(r"$V$",fontsize=24) ax.set_ylabel(r"$\delta t$",fontsize=24) ax.tick_params(labelsize=20) for p in params: d = deltas[p[0]] V = Vs[p[1]] ax.plot(V,d,"o",label="training",color="cyan") #2 trash qubit params = [[0,0]] fig,axs = plt.subplots(figsize=(8,5),squeeze=False) nbins=100 ax = axs[0,0] levels = MaxNLocator(nbins=nbins).tick_values(cost.min(),cost.max()) norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True) im = ax.pcolormesh(y, x, cost.T, cmap=cmap, norm=norm) cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) plt.xscale("log") # plt.yscale("log") ax.set_title("Loss",fontsize=20) ax.set_xlabel(r"$V$",fontsize=24) ax.set_ylabel(r"$\delta t$",fontsize=24) ax.tick_params(labelsize=20) for p in params: d = deltas[p[0]] V = Vs[p[1]] ax.plot(V,d,"o",label="training",color="cyan") #2 trash qubit params = [[-1,0]] fig,axs = plt.subplots(figsize=(8,5),squeeze=False) nbins=100 ax = axs[0,0] levels = MaxNLocator(nbins=nbins).tick_values(cost.min(),cost.max()) norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True) im = ax.pcolormesh(y, x, cost.T, cmap=cmap, norm=norm) cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) plt.xscale("log") # plt.yscale("log") ax.set_title("Loss",fontsize=20) ax.set_xlabel(r"$V$",fontsize=24) ax.set_ylabel(r"$\delta t$",fontsize=24) ax.tick_params(labelsize=20) for p in params: d = deltas[p[0]] V = Vs[p[1]] ax.plot(V,d,"o",label="training",color="cyan") #2 trash qubit params = [[5,-1]] fig,axs = plt.subplots(figsize=(8,5),squeeze=False) nbins=100 ax = axs[0,0] levels = MaxNLocator(nbins=nbins).tick_values(cost.min(),cost.max()) norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True) im = ax.pcolormesh(y, x, cost.T, cmap=cmap, norm=norm) cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) plt.xscale("log") # plt.yscale("log") ax.set_title("Loss",fontsize=20) ax.set_xlabel(r"$V$",fontsize=24) ax.set_ylabel(r"$\delta t$",fontsize=24) ax.tick_params(labelsize=20) for p in params: d = deltas[p[0]] V = Vs[p[1]] ax.plot(V,d,"o",label="training",color="cyan") #2 trash qubit cost = np.load('data_rike/cost_bh_L12_trash2_d48_v5_seed10.npy', allow_pickle=True) # cost = np.load('data_rike/cost_bh_L12_trash6_d25_v47_seed29.npy', allow_pickle=True) params = [[25,47]] cost = es fig,axs = plt.subplots(figsize=(8,5),squeeze=False) nbins=100 ax = axs[0,0] levels = MaxNLocator(nbins=nbins).tick_values(cost.min(),cost.max()) norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True) im = ax.pcolormesh(y, x, cost.T, cmap=cmap, norm=norm) cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) plt.xscale("log") # plt.yscale("log") # ax.set_title("Density-density correlation",fontsize=22) # ax.set_title("Loss",fontsize=22) ax.set_title("Degeneracy entanglement spectrum",fontsize=22) ax.set_xlabel(r"$V$",fontsize=24) ax.set_ylabel(r"$\delta t$",fontsize=24) ax.tick_params(labelsize=20) # for p in params: # d = deltas[p[0]] # V = Vs[p[1]] # ax.plot(V,d,"o",label="training",color="cyan") fig.tight_layout() # plt.savefig('plots_rike/cost_bh_L12_trash6_d25_v47_seed29.png', dpi=300) plt.savefig('plots_rike/es_bh_L12.pdf', dpi=300) seeds = np.arange(20) + 10 for seed in seeds: # cost = np.load(f'data_rike/cost_bh_L12_trash2_d48_v5_seed{seed}.npy', allow_pickle=True) # 7, 10 # cost = np.load(f'data_rike/cost_bh_L12_trash4_d48_v5_seed{seed}.npy', allow_pickle=True) # 3 # cost = np.load(f'data_rike/cost_bh_L12_trash6_d48_v5_seed{seed}.npy', allow_pickle=True) # 0 # params = [[48,5]] # cost = np.load(f'data_rike/cost_bh_L12_trash2_d2_v5_seed{seed}.npy', allow_pickle=True) # -2 # cost = np.load(f'data_rike/cost_bh_L12_trash4_d2_v5_seed{seed}.npy', allow_pickle=True) # 0 # cost = np.load(f'data_rike/cost_bh_L12_trash6_d2_v5_seed{seed}.npy', allow_pickle=True) # 2, 10 # params = [[2,5]] # cost = np.load(f'data_rike/cost_bh_L12_trash2_d10_v10_seed{seed}.npy', allow_pickle=True) # 3, 6 # cost = np.load(f'data_rike/cost_bh_L12_trash4_d10_v10_seed{seed}.npy', allow_pickle=True) # -8 # cost = np.load(f'data_rike/cost_bh_L12_trash6_d10_v10_seed{seed}.npy', allow_pickle=True) # 6, 12 # params = [[10,10]] # cost = np.load(f'data_rike/cost_bh_L12_trash2_d25_v47_seed{seed}.npy', allow_pickle=True) # 1 # cost = np.load(f'data_rike/cost_bh_L12_trash4_d25_v47_seed{seed}.npy', allow_pickle=True) # 6 cost = np.load(f'data_rike/cost_bh_L12_trash6_d25_v47_seed{seed}.npy', allow_pickle=True) # 1, 12, 19 params = [[25,47]] fig,axs = plt.subplots(figsize=(8,5),squeeze=False) nbins=100 ax = axs[0,0] levels = MaxNLocator(nbins=nbins).tick_values(cost.min(),cost.max()) norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True) im = ax.pcolormesh(y, x, cost.T, cmap=cmap, norm=norm) cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) plt.xscale("log") # plt.yscale("log") ax.set_title("Loss",fontsize=20) ax.set_xlabel(r"$V$",fontsize=24) ax.set_ylabel(r"$\delta t$",fontsize=24) ax.tick_params(labelsize=20) for p in params: d = deltas[p[0]] V = Vs[p[1]] ax.plot(V,d,"o",label="training",color="cyan") seeds = np.arange(20) + 10 for seed in seeds: cost = np.load(f'data_rike/cost_bh_L12_trash2_d48_v5_seed{seed}.npy', allow_pickle=True) # 7, 10 params = [[48,5]] # cost = np.load(f'data_rike/cost_bh_L12_trash2_d2_v5_seed{seed}.npy', allow_pickle=True) # -2 # cost = np.load(f'data_rike/cost_bh_L12_trash4_d2_v5_seed{seed}.npy', allow_pickle=True) # params = [[2,5]] # cost = np.load(f'data_rike/cost_bh_L12_trash2_d10_v10_seed{seed}.npy', allow_pickle=True) # 3, 6 # cost = np.load(f'data_rike/cost_bh_L12_trash4_d10_v10_seed{seed}.npy', allow_pickle=True) # params = [[10,10]] fig,axs = plt.subplots(figsize=(8,5),squeeze=False) nbins=100 ax = axs[0,0] levels = MaxNLocator(nbins=nbins).tick_values(cost.min(),cost.max()) norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True) im = ax.pcolormesh(y, x, cost.T, cmap=cmap, norm=norm) cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) plt.xscale("log") # plt.yscale("log") ax.set_title("Loss",fontsize=20) ax.set_xlabel(r"$V$",fontsize=24) ax.set_ylabel(r"$\delta t$",fontsize=24) ax.tick_params(labelsize=20) for p in params: d = deltas[p[0]] V = Vs[p[1]] ax.plot(V,d,"o",label="training",color="cyan") plt.show() seeds = np.arange(20) + 10 for seed in seeds: # loss = np.load(f'data_rike/cost_bh_L12_trash2_d48_v5_seed{seed}.npy', allow_pickle=True) # params = [[48,5]] # loss = np.load(f'data_rike/cost_bh_L12_trash2_d2_v5_seed{seed}.npy', allow_pickle=True) # loss = np.load(f'data_rike/cost_bh_L12_trash4_d2_v5_seed{seed}.npy', allow_pickle=True) # params = [[2,5]] # loss = np.load(f'data_rike/loss_bh_L12_trash2_d10_v10_seed{seed}.npy', allow_pickle=True) # loss = np.load(f'data_rike/loss_bh_L12_trash4_d10_v10_seed{seed}.npy', allow_pickle=True) loss = np.load(f'data_rike/loss_bh_L12_trash2_d25_v47_seed{seed}.npy', allow_pickle=True) # loss = np.load(f'data_rike/loss_bh_L12_trash4_d25_v47_seed{seed}.npy', allow_pickle=True) fig = plt.figure(figsize=(12,4)) plt.subplot(1, 2, 1) plt.plot(loss, "x--") plt.yscale("log") plt.xlabel("step") plt.ylabel("Loss")
https://github.com/Qottmann/Quantum-anomaly-detection
Qottmann
import time import itertools import random import numpy as np from scipy.optimize import minimize, basinhopping from qiskit import * from qiskit.quantum_info import Statevector from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B, SPSA import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator from matplotlib.colors import BoundaryNorm from modules.utils import Mag %matplotlib inline cmap = plt.get_cmap("plasma") #'viridis' # from: https://tenpy.readthedocs.io/en/latest/toycodes/tfi_exact.html import numpy as np import scipy.sparse as sparse import scipy.sparse.linalg.eigen.arpack as arp import warnings import scipy.integrate def ising_groundstate(L, J, gx, gz=0): # gx is transverse field, gz the longitudinal """For comparison: obtain ground state energy from exact diagonalization. Exponentially expensive in L, only works for small enough `L` <~ 20. """ if L >= 20: warnings.warn("Large L: Exact diagonalization might take a long time!") # get single site operaors sx = sparse.csr_matrix(np.array([[0., 1.], [1., 0.]])) sz = sparse.csr_matrix(np.array([[1., 0.], [0., -1.]])) id = sparse.csr_matrix(np.eye(2)) sx_list = [] # sx_list[i] = kron([id, id, ..., id, sx, id, .... id]) sz_list = [] for i_site in range(L): x_ops = [id] * L z_ops = [id] * L x_ops[i_site] = sx z_ops[i_site] = sz X = x_ops[0] Z = z_ops[0] for j in range(1, L): X = sparse.kron(X, x_ops[j], 'csr') Z = sparse.kron(Z, z_ops[j], 'csr') sx_list.append(X) sz_list.append(Z) H_zz = sparse.csr_matrix((2**L, 2**L)) H_z = sparse.csr_matrix((2**L, 2**L)) H_x = sparse.csr_matrix((2**L, 2**L)) for i in range(L - 1): H_zz = H_zz + sz_list[i] * sz_list[(i + 1) % L] for i in range(L): H_z = H_z + sz_list[i] H_x = H_x + sx_list[i] H = -J * H_zz - gx * H_x - gz * H_z E, V = arp.eigsh(H, k=1, which='SA', return_eigenvectors=True, ncv=20) return V[:,0], E[0] init_state, E = ising_groundstate(6, 1., 1., 1.) # Use Aer's qasm_simulator backend_sim = Aer.get_backend('qasm_simulator') L = 6 # system size thetas = np.random.uniform(0, 2*np.pi, 2*L+2) # initial parameters without feature encoding # thetas = np.random.uniform(0, 2*np.pi, (2*L+2, 2)) # initial parameters with feature encoding def prepare_circuit(init_state=None, measurement=True): qreg = QuantumRegister(L, 'q') creg = ClassicalRegister(2, 'c') circ = QuantumCircuit(qreg, creg) entangler_map1 = [(5, 4), (5, 3), (5, 1), (4, 2), (4, 0)] entangler_map2 = [(5, 4), (5, 2), (4, 3), (5, 0), (4, 1)] circ += circuit.library.TwoLocal(L, 'ry', 'cz', entanglement = [entangler_map1, entangler_map2], reps=2, insert_barriers=True, skip_final_rotation_layer=True) circ.ry(circuit.Parameter('θ1'), 4) circ.ry(circuit.Parameter('θ2'), 5) if measurement: circ.measure(qreg[4], creg[0]) circ.measure(qreg[5], creg[1]) if init_state is not None: circ.initialize(init_state, qreg) return circ # same circuit as above (more explicit) def prepare_circuit2(thetas, init_state=None, measurement=True): qreg = QuantumRegister(L, 'q') creg = ClassicalRegister(2, 'c') circ = QuantumCircuit(qreg, creg) if init_state is not None: circ.initialize(init_state, qreg) for i,t in enumerate(thetas[2:(L+2)]): # for i,t in enumerate(thetas[0:L]): circ.ry(t, i) circ.cz(5,4) circ.cz(5,3) circ.cz(5,1) circ.cz(4,2) circ.cz(4,0) circ.barrier() for i,t in enumerate(thetas[(L+2):]): # for i,t in enumerate(thetas[L:2*L]): circ.ry(t, i) circ.cz(5,4) circ.cz(5,2) circ.cz(4,3) circ.cz(5,0) circ.cz(4,1) circ.barrier() # circ.ry(thetas[2*L], 4) # circ.ry(thetas[2*L+1], 5) circ.ry(thetas[0], 4) circ.ry(thetas[1], 5) circ.barrier() if measurement: circ.measure(qreg[4], creg[0]) circ.measure(qreg[5], creg[1]) return circ def feature_encoding(thetas, x): """ thetas: parameters to be optimized, x: Ising model parameter (eg. field) """ new_thetas = [] thetas = thetas.reshape((-1,2)) for theta in thetas: new_thetas.append(theta[0] * x + theta[1]) return new_thetas circ = prepare_circuit() circ.draw('mpl') # trash qubits are at the bottom circ = prepare_circuit2(thetas) # circ = prepare_circuit(feature_encoding(thetas, .6)) circ.draw('mpl') # identical to above np.random.seed(123) def run_circuit(thetas, init_state, shots=100000): circ = prepare_circuit2(thetas, init_state) # Execute the circuit on the qasm simulator. job_sim = execute(circ, backend_sim, shots=shots)#, seed_simulator=123, seed_transpiler=234)#, memory=True) # Grab the results from the job result_sim = job_sim.result() counts = result_sim.get_counts(circ) # print(counts) # mems = result_sim.get_memory(circ) # print(mems) return counts # run_circuit(thetas, init_state)['11'] init_state, E = ising_groundstate(6, 1., 1.6) run_circuit(thetas, init_state) def encoder_evolv(thetas, J, gx, gz, param_encoding=False, x=0): """ full quantum state evolution with encoder part of circuit """ if param_encoding: thetas = feature_encoding(thetas, x) circ = prepare_circuit2(thetas, measurement=False) init_state, _ = ising_groundstate(L, J, g, gx) state = Statevector(init_state) state = state.evolve(circ) traced_state = qiskit.quantum_info.partial_trace(state,range(0,4)) return traced_state def encoder_decoder_evolv(thetas, J, gx, gz, param_encoding=False, x=0): """ full quantum state evolution with encoder & decoder part of circuit """ if param_encoding: thetas = feature_encoding(thetas, x) circ = prepare_circuit2(thetas, measurement=False) circ_dagger = circ.inverse() # encoder part init_state, _ = ising_groundstate(L, J, gx, gz) state = Statevector(init_state) state = state.evolve(circ) traced_state = qiskit.quantum_info.partial_trace(state,[4,5]) # decoder part ancilla = np.zeros(4) ancilla[0] = 1 ancilla = qiskit.quantum_info.DensityMatrix(ancilla) new_state = traced_state.expand(ancilla) final_state = new_state.evolve(circ_dagger) fid = qiskit.quantum_info.state_fidelity(Statevector(init_state), final_state) return final_state, init_state, fid # old version init_state, E = ising_groundstate(6, 1., 0.0) circ.initialize(init_state, range(L)) # new_thetas = feature_encoding(thetas, g) # comment out when running w/o feature encoding new_thetas = thetas t_qc = transpile(circ, backend=backend_sim, seed_transpiler=234) qobj = compiler.assemble(t_qc.bind_parameters(new_thetas), backend=backend_sim, seed_simulator=123, shots=100000) result = backend_sim.run(qobj).result() out = result.get_counts() out #reset random seed np.random.seed(123) random.seed(123) def cost_function_single(thetas, J, gx, gz, shots=1000, param_encoding=False, x=0): """ Optimizes circuit """ init_state, _ = ising_groundstate(L, J, gx, gz) if param_encoding: thetas = feature_encoding(thetas, x) out = run_circuit(thetas, init_state, shots=shots) cost = out.get('11', 0)*2 + out.get('01', 0) + out.get('10', 0) return cost/shots def cost_function(thetas, ising_params, shots=1000, param_encoding=False, x=0): """ Optimizes circuit """ cost = 0. n_samples = len(ising_params) for i, p in enumerate(ising_params): J, gx, gz = p if param_encoding: cost += cost_function_single(thetas, J, gx, gz, shots, param_encoding, x[i]) else: cost += cost_function_single(thetas, J, gx, gz, shots, param_encoding) return cost/n_samples def optimize(ising_params, thetas=None, shots=1000, max_iter=400, param_encoding=False, x=0): np.random.seed(123) if thetas is None: n_params = (2*L+2)*2 if param_encoding else (2*L+2) thetas = np.random.uniform(0, 2*np.pi, n_params) # initial parameters without feature encoding print("Initial cost: {:.3f}".format(cost_function(thetas, ising_params, shots, param_encoding, x))) print(thetas) counts, values, accepted = [], [], [] def store_intermediate_result(eval_count, parameters, mean, std, ac): # counts.append(eval_count) values.append(mean) accepted.append(ac) # Initialize optimizer # optimizer = COBYLA(maxiter=max_iter, tol=0.0001) # optimizer = L_BFGS_B(maxfun=300, maxiter=max_iter)#, factr=10, iprint=- 1, epsilon=1e-08) optimizer = SPSA(maxiter=max_iter, #blocking=True, callback=store_intermediate_result, #learning_rate=1e-1, #perturbation=0.4 ) # recommended from qiskit (first iteraction takes quite long) # to reduce time figure out optimal learning rate and perturbation in advance start_time = time.time() ret = optimizer.optimize( num_vars=len(thetas), objective_function=(lambda thetas: cost_function(thetas, ising_params, shots, param_encoding, x)), initial_point=thetas ) print("Time: {:.5f} sec".format(time.time()-start_time)) print(ret) return ret[0], values, accepted params = [(-1.0, 0.1, 0.1)] thetas, loss, accepted = optimize(params, max_iter=40) params = [(-1.0, 0.1, 0.1)] thetas, loss, accepted = optimize(params, max_iter=40) fig = plt.figure(figsize=(12,4)) plt.subplot(1, 2, 1) plt.plot(loss, "x--") # plt.yscale("log") plt.xlabel("step") plt.ylabel("Loss") plt.subplot(1, 2, 2) plt.plot(accepted, "x--") plt.xlabel("step") plt.ylabel("Accepted"); Js = [-1]*2 gxs = [0.1,10] gzs = [10,0.1] params = list(zip(Js, gxs, gzs)) thetas, loss, accepted = optimize(params) thetas_normal_phase = thetas thetas = thetas_normal_phase fig = plt.figure(figsize=(12,4)) plt.subplot(1, 2, 1) plt.plot(loss, "x--") plt.yscale("log") plt.xlabel("step") plt.ylabel("Loss"); points = 50 J = -1.0 gxs = np.logspace(-2, 2, points) gzs = np.logspace(-2, 2, points) x,y = np.meshgrid(gxs,gzs) cost = np.zeros((points,points)) Smags = np.zeros((points,points)) shots = 1000 for i,gx in enumerate(gxs): for j,gz in enumerate(gzs): cost[i,j] = cost_function_single(thetas, J, gx, gz, shots=shots) init_state, _ = ising_groundstate(5, J, gx, gz) Smags[i,j] = init_state.T.conj()@Mag(5,-1)@init_state fig,axs = plt.subplots(figsize=(8,5),squeeze=False) nbins=100 ax = axs[0,0] levels = MaxNLocator(nbins=nbins).tick_values(cost.min(),cost.max()) norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True) im = ax.pcolormesh(x, y, cost, cmap=cmap, norm=norm) cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) plt.xscale("log") plt.yscale("log") ax.set_title("Loss",fontsize=20) ax.set_xlabel(r"$g_z$",fontsize=24) ax.set_ylabel(r"$g_x$",fontsize=24) ax.tick_params(labelsize=20) fig,axs = plt.subplots(figsize=(8,5),squeeze=False) nbins=100 ax = axs[0,0] levels = MaxNLocator(nbins=nbins).tick_values(Smags.min(),Smags.max()) norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True) im = ax.pcolormesh(x, y, Smags, cmap=cmap, norm=norm) cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) plt.xscale("log") plt.yscale("log") ax.set_title("Staggered magnetization",fontsize=20) ax.set_xlabel(r"$g_z$",fontsize=24) ax.set_ylabel(r"$g_x$",fontsize=24) ax.tick_params(labelsize=20) J = -1 gxs = np.logspace(-2, 2, 50) gz = .01 cost1, Smags1, Smags12 = [], [], [] shots = 10000 Ll = 5 for gx in gxs: cost1.append(cost_function_single(thetas, J, gx, gz, shots=shots)) init_state, _ = ising_groundstate(Ll, J, gx, gz) Smags1.append(np.real(init_state.T.conj()@Mag(Ll,-1)@init_state)) init_state, _ = ising_groundstate(Ll+2, J, gx, gz) Smags12.append(np.real(init_state.T.conj()@Mag(Ll+2,-1)@init_state)) gzs = np.logspace(-2, 2, 50) gx = .01 cost2, Smags2, Smags22 = [], [], [] for gz in gzs: cost2.append(cost_function_single(thetas, J, gx, gz, shots=shots)) init_state, _ = ising_groundstate(Ll, J, gx, gz) Smags2.append(np.real(init_state.T.conj()@Mag(Ll,-1)@init_state)) init_state, _ = ising_groundstate(Ll+2, J, gx, gz) Smags22.append(np.real(init_state.T.conj()@Mag(Ll+2,-1)@init_state)) fig = plt.figure(figsize=(12,4)) ax1 = plt.subplot(121) ax2 = ax1.twinx() ax3 = plt.subplot(122) ax4 = ax3.twinx() ax1.set_xlabel(r"$g_z$") ax1.set_ylabel("Cost") ax1.plot(gzs, cost1, "x--") ax2.plot(gzs, Smags1, "g-.") ax2.plot(gzs, Smags12, "r--") ax2.set_ylabel("Staggered mag.") ax2.set_xscale("log") ax3.set_xlabel(r"$g_x$") ax3.set_ylabel("Cost") ax3.plot(gzs, cost2, "x--") ax4.plot(gzs, Smags2, "g-.") ax4.plot(gzs, Smags22, "r--") ax4.set_xscale("log") ax4.set_ylabel("Staggered mag.") fig.tight_layout() fig = plt.figure(figsize=(15,4)) plt.subplot(1, 3, 1) J, g, gx = -1., .1, 10. traced_state = encoder_evolv(thetas, J, gx, gz) plt.imshow(np.real(traced_state.data), cmap='RdBu', vmin=-1.0, vmax=1.0, interpolation='none') plt.colorbar() plt.axis('off'); plt.subplot(1, 3, 2) J, g, gx = -1., 10., .1 traced_state = encoder_evolv(thetas, J, gx, gz) plt.imshow(np.real(traced_state.data), cmap='RdBu', vmin=-1.0, vmax=1.0, interpolation='none') plt.colorbar() plt.axis('off'); plt.subplot(1, 3, 3) J, g, gx = -1., .1, .1 traced_state = encoder_evolv(thetas, J, gx, gz) plt.imshow(np.real(traced_state.data), cmap='RdBu', vmin=-1.0, vmax=1.0, interpolation='none') plt.colorbar() plt.axis('off'); # upper left corner corresponds to |00><00|, the first two images are the ones for which circuit was optimized points = 50 J = 1.0 gxs = np.logspace(-2, 2, points) gzs = np.logspace(-2, 2, points) x,y = np.meshgrid(gxs,gzs) cost = np.zeros((points,points)) shots = 1000 for i,gx in enumerate(gxs): for j,gz in enumerate(gzs): cost[i,j] = cost_function_single(thetas, J, gx, gz, shots=shots) fig,axs = plt.subplots(figsize=(8,5),squeeze=False) nbins=100 ax = axs[0,0] levels = MaxNLocator(nbins=nbins).tick_values(cost.min(),cost.max()) norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True) im = ax.pcolormesh(x, y, cost, cmap=cmap, norm=norm) cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) plt.xscale("log") plt.yscale("log") ax.set_title("Loss",fontsize=20) ax.set_xlabel(r"$g_z$",fontsize=24) ax.set_ylabel(r"$g_x$",fontsize=24) ax.tick_params(labelsize=20) np.random.seed(123) thetas_random = np.random.uniform(0, 2*np.pi, 2*L+2) # initial parameters without feature encoding points = 50 J = -1.0 gxs = np.logspace(-2, 2, points) gzs = np.logspace(-2, 2, points) x,y = np.meshgrid(gxs,gzs) cost = np.zeros((points,points)) shots = 1000 for i,gx in enumerate(gxs): for j,gz in enumerate(gzs): cost[i,j] = cost_function_single(thetas_random, J, gx, gz, shots=shots) fig,axs = plt.subplots(figsize=(8,5),squeeze=False) nbins=100 ax = axs[0,0] levels = MaxNLocator(nbins=nbins).tick_values(cost.min(),cost.max()) norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True) im = ax.pcolormesh(x, y, cost, cmap=cmap, norm=norm) cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) plt.xscale("log") plt.yscale("log") ax.set_title("Loss",fontsize=20) ax.set_xlabel(r"$g_z$",fontsize=24) ax.set_ylabel(r"$g_x$",fontsize=24) ax.tick_params(labelsize=20) params = [(-1.0, 0.1, 0.1)] thetas, loss, accepted = optimize(params) thetas_ordered_phase = thetas thetas = thetas_ordered_phase fig = plt.figure(figsize=(12,4)) plt.subplot(1, 2, 1) plt.plot(loss, "x--") plt.yscale("log") plt.xlabel("step") plt.ylabel("Loss"); points = 50 J = -1.0 gxs = np.logspace(-2, 2, points) gzs = np.logspace(-2, 2, points) x,y = np.meshgrid(gxs,gzs) cost = np.zeros((points,points)) Smags = np.zeros((points,points)) shots = 1000 for i,gx in enumerate(gxs): for j,gz in enumerate(gzs): cost[i,j] = cost_function_single(thetas, J, gx, gz, shots=shots) init_state, _ = ising_groundstate(5, J, gx, gz) Smags[i,j] = init_state.T.conj()@Mag(5,-1)@init_state fig,axs = plt.subplots(figsize=(8,5),squeeze=False) nbins=100 ax = axs[0,0] levels = MaxNLocator(nbins=nbins).tick_values(cost.min(),cost.max()) norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True) im = ax.pcolormesh(x, y, cost, cmap=cmap, norm=norm) cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) plt.xscale("log") plt.yscale("log") ax.set_title("Loss",fontsize=20) ax.set_xlabel(r"$g_z$",fontsize=24) ax.set_ylabel(r"$g_x$",fontsize=24) ax.tick_params(labelsize=20) fig,axs = plt.subplots(figsize=(8,5),squeeze=False) nbins=100 ax = axs[0,0] levels = MaxNLocator(nbins=nbins).tick_values(Smags.min(),Smags.max()) norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True) im = ax.pcolormesh(x, y, Smags, cmap=cmap, norm=norm) cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) plt.xscale("log") plt.yscale("log") ax.set_title("Staggered magnetization",fontsize=20) ax.set_xlabel(r"$g_z$",fontsize=24) ax.set_ylabel(r"$g_x$",fontsize=24) ax.tick_params(labelsize=20) J = -1 gxs = np.logspace(-2, 2, 50) gz = .01 cost1, Smags1, Smags12 = [], [], [] shots = 10000 Ll = 5 for gx in gxs: cost1.append(cost_function_single(thetas, J, gx, gz, shots=shots)) init_state, _ = ising_groundstate(Ll, J, gx, gz) Smags1.append(np.real(init_state.T.conj()@Mag(Ll,-1)@init_state)) init_state, _ = ising_groundstate(Ll+2, J, gx, gz) Smags12.append(np.real(init_state.T.conj()@Mag(Ll+2,-1)@init_state)) gzs = np.logspace(-2, 2, 50) gx = .01 cost2, Smags2, Smags22 = [], [], [] for gz in gzs: cost2.append(cost_function_single(thetas, J, gx, gz, shots=shots)) init_state, _ = ising_groundstate(Ll, J, gx, gz) Smags2.append(np.real(init_state.T.conj()@Mag(Ll,-1)@init_state)) init_state, _ = ising_groundstate(Ll+2, J, gx, gz) Smags22.append(np.real(init_state.T.conj()@Mag(Ll+2,-1)@init_state)) Js = np.linspace(-10, 10, 50) gx = 0.1 gz = 0.1 cost3, Smags3, Smags32 = [], [], [] for J in Js: cost3.append(cost_function_single(thetas, J, gx, gz, shots=shots)) init_state, _ = ising_groundstate(Ll, J, gx, gz) Smags3.append(np.real(init_state.T.conj()@Mag(Ll,-1)@init_state)) init_state, _ = ising_groundstate(Ll+2, J, gx, gz) Smags32.append(np.real(init_state.T.conj()@Mag(Ll+2,-1)@init_state)) fig = plt.figure(figsize=(18,4)) ax1 = plt.subplot(131) ax2 = ax1.twinx() ax3 = plt.subplot(132) ax4 = ax3.twinx() ax5 = plt.subplot(133) ax6 = ax5.twinx() ax1.set_xlabel(r"$g_z$") ax1.set_ylabel("Cost") ax1.plot(gzs, cost1, "x--") ax2.plot(gzs, Smags1, "g-.") ax2.plot(gzs, Smags12, "r--") ax2.set_ylabel("Staggered mag.") ax2.set_xscale("log") ax3.set_xlabel(r"$g_x$") ax3.set_ylabel("Cost") ax3.plot(gzs, cost2, "x--") ax4.plot(gzs, Smags2, "g-.") ax4.plot(gzs, Smags22, "r--") ax4.set_xscale("log") ax4.set_ylabel("Staggered mag.") ax5.set_xlabel(r"$J$") ax5.set_ylabel("Cost") ax5.plot(Js, cost3, "x--") ax6.plot(Js, Smags3, "g-.") ax6.plot(Js, Smags32, "r--") ax6.set_ylabel("Staggered mag.") fig.tight_layout(); fig = plt.figure(figsize=(15,4)) plt.subplot(1, 3, 1) J, g, gx = -1., .1, .1 traced_state = encoder_evolv(thetas, J, gx, gz) plt.imshow(np.real(traced_state.data), cmap='RdBu', vmin=-1.0, vmax=1.0, interpolation='none') plt.colorbar() plt.axis('off'); plt.subplot(1, 3, 2) J, g, gx = -1., 2., 2. traced_state = encoder_evolv(thetas, J, gx, gz) plt.imshow(np.real(traced_state.data), cmap='RdBu', vmin=-1.0, vmax=1.0, interpolation='none') plt.colorbar() plt.axis('off'); plt.subplot(1, 3, 3) J, g, gx = 1., .1, .1 traced_state = encoder_evolv(thetas, J, gx, gz) plt.imshow(np.real(traced_state.data), cmap='RdBu', vmin=-1.0, vmax=1.0, interpolation='none') plt.colorbar() plt.axis('off'); # upper left corner corresponds to |00><00|, the first image is the one for which circuit was optimized J, gx, gz = -1., .1, .1 gzs = np.logspace(-2, 2, 50) fid1 = [] for gz in gzs: fid1.append(encoder_decoder_evolv(thetas, J, gx, gz)[2]) J, gx, gz = -1., .1, .1 gxs = np.logspace(-2, 2, 50) fid2 = [] for gx in gxs: fid2.append(encoder_decoder_evolv(thetas, J, gx, gz)[2]) J, gx, gz = -1., .1, .1 Js = np.linspace(-10, 10, 50) fid3 = [] for J in Js: fid3.append(encoder_decoder_evolv(thetas, J, gx, gz)[2]) fig = plt.figure(figsize=(18,4)) ax1 = plt.subplot(131) ax2 = ax1.twinx() ax3 = plt.subplot(132) ax4 = ax3.twinx() ax5 = plt.subplot(133) ax6 = ax5.twinx() ax1.set_xlabel(r"$g_z$") ax1.set_ylabel("Fidelity") ax1.plot(gzs, fid1, "x--") ax2.plot(gzs, Smags2, "g-.") ax2.plot(gzs, Smags22, "r--") ax2.set_ylabel("Staggered mag.") ax2.set_xscale("log") ax3.set_xlabel(r"$g_x$") ax3.set_ylabel("Fidelity") ax3.plot(gzs, fid2, "x--") ax4.plot(gzs, Smags1, "g-.") ax4.plot(gzs, Smags12, "r--") ax4.set_xscale("log") ax4.set_ylabel("Staggered mag.") ax5.set_xlabel(r"$J$") ax5.set_ylabel("Fidelity") ax5.plot(Js, fid3, "x--") ax6.plot(Js, Smags3, "g-.") ax6.plot(Js, Smags32, "r--") ax6.set_ylabel("Staggered mag.") fig.tight_layout(); fig = plt.figure(figsize=(18,4)) plt.subplot(1, 3, 1) plt.plot(gzs, fid1, "x--") plt.xscale("log") plt.xlabel(r"$g_z$") plt.ylabel("Fidelity"); plt.subplot(1, 3, 2) plt.plot(gxs, fid2, "x--") plt.xscale("log") plt.xlabel(r"$g_x$") plt.ylabel("Fidelity"); plt.subplot(1, 3, 3) plt.plot(gxs, fid3, "x--") plt.xscale("log") plt.xlabel(r"$g_x$") plt.ylabel("Fidelity"); # with feature encoding Js = [1.0] gxs = np.linspace(0.1, 0.6, 10) gzs = [0.01] a = [Js, gxs, gzs] params = list(itertools.product(*a)) thetas, loss, accepted = optimize(params, max_iter=1000, param_encoding=True, x=gxs) thetas2 = thetas # without feature encoding Js = [1.0] gxs = np.linspace(0.1, 0.6, 10) gzs = [0.01] a = [Js, gxs, gzs] params = list(itertools.product(*a)) thetas, loss2, accepted = optimize(params, max_iter=200, param_encoding=False) thetas3 = thetas fig = plt.figure(figsize=(12,4)) plt.subplot(1, 2, 1) plt.plot(loss, "x--") plt.plot(loss2, "o-.") plt.yscale("log") plt.xlabel("step") plt.ylabel("Loss") J = 1. gxs = np.linspace(0.01, 1.2, 50) gz = .01 cost1, cost2 = [], [] shots = 10000 param_encoding=False for gx in gxs: cost1.append(cost_function_single(thetas2, J, gx, gz, shots=shots, param_encoding=True, x=gx)) cost2.append(cost_function_single(thetas3, J, gx, gz, shots=shots, param_encoding=False, x=gx)) fig = plt.figure(figsize=(18,4)) plt.subplot(1, 3, 1) plt.plot(gxs, cost1, "x--") plt.plot(gxs, cost2, "o-.") # plt.xscale("log") plt.vlines(0.6, 0, 1.2, colors="tab:gray", linestyles='dotted') plt.vlines(0.1, 0, 1.2, colors="tab:gray", linestyles='dotted') plt.xlabel(r"$g_x$") plt.ylabel("Cost") fig = plt.figure(figsize=(10,10)) plt.subplot(2, 2, 1) J, g, gx = 1., .6, .01 traced_state = encoder_evolv(thetas2, J, gx, gz, param_encoding=True, x=gx) plt.imshow(np.real(traced_state.data), cmap='RdBu', vmin=-1.0, vmax=1.0, interpolation='none') plt.colorbar() plt.axis('off'); plt.subplot(2, 2, 2) J, g, gx = 1., .6, .01 traced_state = encoder_evolv(thetas3, J, gx, gz) plt.imshow(np.real(traced_state.data), cmap='RdBu', vmin=-1.0, vmax=1.0, interpolation='none') plt.colorbar() plt.axis('off'); plt.subplot(2, 2, 3) J, g, gx = 1., .75, .01 traced_state = encoder_evolv(thetas2, J, gx, gz, param_encoding=True, x=gx) plt.imshow(np.real(traced_state.data), cmap='RdBu', vmin=-1.0, vmax=1.0, interpolation='none') plt.colorbar() plt.axis('off'); plt.subplot(2, 2, 4) J, g, gx = 1., .75, .01 traced_state = encoder_evolv(thetas3, J, gx, gz) plt.imshow(np.real(traced_state.data), cmap='RdBu', vmin=-1.0, vmax=1.0, interpolation='none') plt.colorbar() plt.axis('off'); # same as Fig. 5
https://github.com/suvoooo/Qubits-Qiskit
suvoooo
!pip3 install qiskit import qiskit as q !pip3 install pylatexenc import math import numpy as np statevec_sim = q.Aer.get_backend("statevector_simulator") def statevec_exec(circ): statevec = q.execute(circ, backend=statevec_sim).result().get_statevector() return statevec # qr = q.QuantumRegister(2, name="q") # cr = q.ClassicalRegister(2, name="cr") def build_circ(num_qbits, num_cbits): qr = q.QuantumRegister(num_qbits) cr = q.ClassicalRegister(num_cbits) final_circ = q.QuantumCircuit(qr, cr) return final_circ, qr, cr # simple_circuit, qr, cr = build_circ(2) # simple_circuit.draw() def h_gates(qcirc, a, b): # 2 inputs and h gates in parallel qcirc.h(a) qcirc.h(b) #### start of by applying a rotation around y axis simple_circuit, qr, cr = build_circ(2, 2) simple_circuit.ry(np.pi/6, qr[0]) simple_circuit.ry(np.pi/6, qr[1]) simple_circuit_statevec = statevec_exec(simple_circuit) simple_circuit.measure([0,1], [0,1]) simple_circuit.draw() q.visualization.plot_bloch_multivector(simple_circuit_statevec) qasm_sim = q.Aer.get_backend('qasm_simulator') orig_counts = q.execute(simple_circuit, backend=qasm_sim, shots=1024).result().get_counts() q.visualization.plot_histogram([orig_counts], legend=['output: org qs']) hadamard_front, qr1, cr1 = build_circ(2, 2) hadamard_front.draw() h_gates(hadamard_front, qr1[0], qr1[1]) hadamard_front.ry(math.pi/6, qr1[0]) hadamard_front.ry(math.pi/6, qr1[1]) hadamard_front_statevec = statevec_exec(hadamard_front) hadamard_front.measure([0,1], [0,1]) hadamard_front.draw() q.visualization.plot_bloch_multivector(hadamard_front_statevec) #qasm_sim = q.Aer.get_backend('qasm_simulator') hfront_counts = q.execute(hadamard_front, backend=qasm_sim, shots=1024).result().get_counts() q.visualization.plot_histogram([hfront_counts], legend=['output: hfront qs']) hadamard_front_back, qr2, cr2 = build_circ(2, 2) h_gates(hadamard_front_back, qr2[0], qr2[1]) hadamard_front_back.ry(math.pi/6, [qr2[0]]) hadamard_front_back.ry(math.pi/6, [qr2[1]]) h_gates(hadamard_front_back, qr2[0], qr2[1]) #hadamard_front.barrier() hadamard_front_back_statevec = statevec_exec(hadamard_front_back) hadamard_front_back.measure([0,1], [0,1]) hadamard_front_back.draw() q.visualization.plot_bloch_multivector(hadamard_front_back_statevec) hfront_back_counts = q.execute(hadamard_front_back, backend=qasm_sim, shots=1024).result().get_counts() q.visualization.plot_histogram([hfront_back_counts], legend=['output: hfront-back qs']) num_input = 3 balanced_circuit = q.QuantumCircuit(num_input+1) # num_input + one more where qubit is initialized to |1> ### we can create the balanced oracle by applying CNOT gate to every input and/or by wrapping the second CNOT gate with X gates x_str = "010" # this is for iterating over the string and add X gate when there's 1. for n in range(len(x_str)): if x_str[n]=="1": balanced_circuit.x(n) balanced_circuit.draw() ### add control not for all the inputs balanced_circuit.barrier() for i in range(num_input): balanced_circuit.cx(i, num_input) balanced_circuit.barrier() balanced_circuit.draw() ### add another x gate for n in range(len(x_str)): if x_str[n]=="1": balanced_circuit.x(n) balanced_circuit.draw() init_circuit, qr, cr = build_circ(num_input+1, num_input) ### all the input qubits are initialized to 0, while the target qubit is initialized to 1. for n in range(num_input): init_circuit.h(n) init_circuit.x(qr[num_input]) # state is now initialized to |1> init_circuit.h(qr[num_input]) init_circuit.draw() complete_circuit = init_circuit.compose(balanced_circuit) complete_circuit.draw() ## now we add h gates again to the input qubits for n in range(num_input): complete_circuit.h(n) complete_circuit.barrier() # Now we measure the input qubits for n in range(num_input): complete_circuit.measure(n, n) complete_circuit.draw() from google.colab import drive drive.mount('/content/drive') path = '/content/drive/My Drive/' style = {'backgroundcolor': 'lavender', 'dpi':200, 'subfontsize':10} complete_circuit.draw(output='mpl',scale=0.8, style=style, filename=path+'DJ_Circ_balanced.png') qasm_sim = q.Aer.get_backend('qasm_simulator') balanced_counts = q.execute(complete_circuit, backend=qasm_sim, shots=1024).result().get_counts() q.visualization.plot_histogram([balanced_counts], legend=['output: balanced']) ### let's use IBM Quantum Computer to simulate this, from qiskit import IBMQ IBMQ.save_account('find your token') IBMQ.load_account() provider = IBMQ.get_provider('ibm-q') qcomp = provider.get_backend('ibmq_athens') # check which computer has 0 jobs on queue job = q.execute(complete_circuit, backend=qcomp) q_result = job.result() q.visualization.plot_histogram(q_result.get_counts(complete_circuit))
https://github.com/suvoooo/Qubits-Qiskit
suvoooo
# !pip3 install qiskit import qiskit as q import matplotlib.pyplot as plt from qiskit import IBMQ qr = q.QuantumRegister(2) cr = q.ClassicalRegister(2) circuit = q.QuantumCircuit(qr, cr) circuit.draw() circuit.h(qr[0]) # apply hadamard gate on first qubit. circuit.h(qr[1]) # apply hadamard gate on second qubit. # apply cnot gate. display(circuit.draw()) #### see the state-vector statevec = q.Aer.get_backend('statevector_simulator') final_state = q.execute(circuit, statevec).result().get_statevector() q.visualization.plot_bloch_multivector(final_state) circuit.measure(qr, cr) circuit.draw(scale=2) #### simulate result on a local computer simulator = q.Aer.get_backend(name='qasm_simulator') results = q.execute(circuit, backend=simulator, ).result() q.visualization.plot_histogram(results.get_counts(circuit)) ### try a different circuit where we apply X gate before applying H gate. qr1 = q.QuantumRegister(3) cr1 = q.ClassicalRegister(3) circuit1 = q.QuantumCircuit(qr1, cr1) # circuit1.draw() circuit1.h(qr1[0]) # apply the H gate on q0 circuit1.h(qr1[1]) # apply H gate on q_1 circuit1.h(qr1[2]) # add H gate on q_2 ### draw the circuit circuit1.draw() #### plt the state vector statevec1 = q.Aer.get_backend('statevector_simulator') final_state1 = q.execute(circuit1, statevec1).result().get_statevector() q.visualization.plot_bloch_multivector(final_state1) # the state doesn't not change after application of the CNOT gate #### unchanged state as expected circuit1.measure(qr1, cr1) circuit1.draw(scale=2) circuit1.measure(qr1, cr1) ### simulate result on local computer simulator1 = q.Aer.get_backend('qasm_simulator') results1 = q.execute(circuit1, backend=simulator1, ).result() q.visualization.plot_histogram(results1.get_counts(circuit1)) # Now we will use IBM Quantum Computer to see the result IBMQ.save_account('your token') IBMQ.load_account() provider = IBMQ.get_provider('ibm-q') qcomp = provider.get_backend('ibmq_valencia') # check which computer has 0 jobs on queue job = q.execute(circuit1, backend=qcomp) q_result = job.result() q.visualization.plot_histogram(q_result.get_counts(circuit1))
https://github.com/suvoooo/Qubits-Qiskit
suvoooo
# # install and import qiskit # !pip3 install qiskit import qiskit as q import matplotlib.pyplot as plt from qiskit import IBMQ IBMQ.save_account('putyourtoken') IBMQ.load_account() qr = q.QuantumRegister(2) cr = q.ClassicalRegister(2) circuit = q.QuantumCircuit(qr, cr) circuit.draw() # apply the Hadamard gate on 0th qubit circuit.h(qr[0]) circuit.draw(output='mpl') # now we apply the cnot gate # as explained before the control qubit should be in superposition state circuit.cx(qr[0], qr[1]) circuit.draw(output='mpl') circuit.measure(qr, cr) # measure quantum bit into classical bit circuit.draw(output='mpl') # let's simulate the results on a local computer simulator = q.Aer.get_backend('qasm_simulator') # qasm : quantum assembly lang. results = q.execute(circuit, backend=simulator).result() # execute the circuit based on the simulator as backend q.visualization.plot_histogram(results.get_counts(circuit)) provider = IBMQ.get_provider('ibm-q') qcomp = provider.get_backend('ibmq_london') # check which computer has 0 jobs on queue job = q.execute(circuit, backend=qcomp) q_result = job.result() q.visualization.plot_histogram(q_result.get_counts(circuit))
https://github.com/suvoooo/Qubits-Qiskit
suvoooo
!pip3 install qiskit import qiskit as q print ("check version: ", q.__qiskit_version__) from qiskit import IBMQ import matplotlib.pyplot as plt IBMQ.save_account('find your own number') IBMQ.load_account() circuit = q.QuantumCircuit(2, 2) # creates a new circuit with 2 classical and 2 quantum bits # apply a simple not gate circuit.x(1) # as both the bits are at 0, 0 this will flip the second bit to 1. # the number generally always represents the index, i.e. 1-- second index circuit.draw() # after flipping the second bit to 1 now we apply the controlled not gate circuit.cx(1, 0) # conrolled qubit is the 2nd one and the target qubit is the 1st one # QuantumCircuit.cx(control_qubit, target_qubit, *, label=None, ctrl_state=None, ctl=None, tgt=None) # here's the description [https://qiskit.org/documentation/stubs/qiskit.circuit.QuantumCircuit.cx.html]. # since the controlled bit is 1 so it will flip the target qubit which was initially sitting at 0, to 1. # rather than values think of this 0, 1 inside circuit.cx() as indices of the qubits. # so at this stage we will have 1, 1 as output. circuit.draw() circuit.measure([0, 1], [0, 1]) # measure: quantum bit into classical bit, # again think of the 0, 1 as indices, first list is the quantum register consisting of 2 qubits # second list is the classical register consisting of 2 classical bits. # think of this as value for qubit 0 is what will be returned for classical bit 0 and so on. circuit.draw(output='mpl') # let's simulate this before sending it to a quantum computer # idea is we simulate the quantum computer computation in local computer using Aer framework simulator = q.Aer.get_backend('qasm_simulator') # qasm : quantum assembly lang. results = q.execute(circuit, backend=simulator).result() # execute the circuit based on the simulator as backend q.visualization.plot_histogram(results.get_counts(circuit)) # Now we will use IBM Quantum Computer to see the result provider = IBMQ.get_provider('ibm-q') qcomp = provider.get_backend('ibmq_burlington') # check which computer has 0 jobs on queue job = q.execute(circuit, backend=qcomp) q_result = job.result() q.visualization.plot_histogram(q_result.get_counts(circuit))
https://github.com/suvoooo/Qubits-Qiskit
suvoooo
# !pip3 install qiskit import numpy as np import qiskit as q ### build a circuit for 3 qubits qr = q.QuantumRegister(3) circ = q.QuantumCircuit(qr) ### add the first H gate (in qiskit east significant bit has the lowest index) circ.h(qr[2]) ### add the controlled phase gate circ.cp(np.pi/2, qr[1], qr[2]) # based on qubit 1 apply 2pi/2**(k-1) rotation to qubit 2 ### add the next cp gate circ.cp(np.pi/4, qr[0], qr[2]) # based on qubit 0 apply 2pi/2**(k-1) rotation to qubit 2 ### repeat the process for qubit 1 circ.h(qr[1]) circ.cp(np.pi/2, qr[0], qr[1]) ### add the final h gate circ.h(qr[0]) ### finally swap the bits 0 th, and 2nd qubit circ.swap(qr[0], qr[2]) circ.draw() from google.colab import drive drive.mount('/content/drive') # !pip install pylatexenc path='/content/drive/My Drive/Colab Notebooks/' style = {'backgroundcolor': 'lavender', 'dpi':200, 'subfontsize':10} circ.draw('mpl', scale=0.8, style=style, filename=path+'qfouriert_3bits.png') qr = q.QuantumRegister(3) circ1 = q.QuantumCircuit(qr) ### encode the state 110 at first circ1.x(qr[2]) circ1.x(qr[1]) ### repeat what's done before ### add the first H gate (in qiskit east significant bit has the lowest index) circ1.h(qr[2]) ### add the controlled phase gate circ1.cp(np.pi/2, qr[1], qr[2]) # based on qubit 1 apply 2pi/2**(k-1) rotation to qubit 2 ### add the next cp gate circ1.cp(np.pi/4, qr[0], qr[2]) # based on qubit 0 apply 2pi/2**(k-1) rotation to qubit 2 ### repeat the process for qubit 1 circ1.h(qr[1]) circ1.cp(np.pi/2, qr[0], qr[1]) ### add the final h gate circ1.h(qr[0]) ### finally swap the bits 0 th, and 2nd qubit circ1.swap(qr[0], qr[2]) circ1.draw() circ1.save_statevector() qasm_sim = q.Aer.get_backend('qasm_simulator') statevector = qasm_sim.run(circ1).result().get_statevector() q.visualization.plot_bloch_multivector(statevector) qr = q.QuantumRegister(3) circ2 = q.QuantumCircuit(qr) ### encode the state 101 at first circ2.x(qr[2]) circ2.x(qr[0]) ### repeat what's done before ### add the first H gate (in qiskit east significant bit has the lowest index) circ2.h(qr[2]) ### add the controlled phase gate circ2.cp(np.pi/2, qr[1], qr[2]) # based on qubit 1 apply 2pi/2**(k-1) rotation to qubit 2 ### add the next cp gate circ2.cp(np.pi/4, qr[0], qr[2]) # based on qubit 0 apply 2pi/2**(k-1) rotation to qubit 2 ### repeat the process for qubit 1 circ2.h(qr[1]) circ2.cp(np.pi/2, qr[0], qr[1]) ### add the final h gate circ2.h(qr[0]) ### finally swap the bits 0 th, and 2nd qubit circ2.swap(qr[0], qr[2]) circ2.draw() circ2.save_statevector() qasm_sim = q.Aer.get_backend('qasm_simulator') statevector2 = qasm_sim.run(circ2).result().get_statevector() q.visualization.plot_bloch_multivector(statevector2)
https://github.com/suvoooo/Qubits-Qiskit
suvoooo
!pip3 install qiskit # !pip install pylatexenc import qiskit as q import matplotlib.pyplot as plt qr = q.QuantumRegister(2) cr = q.ClassicalRegister(2) circuit = q.QuantumCircuit(qr, cr) circuit.draw() circuit.h(qr[0]) # apply hadamard gate on first qubit. circuit.h(qr[1]) # apply hadamard gate on second qubit. # apply cnot gate. circuit.cx(qr[0], qr[1]) # in qiskit cnot-- first bit is set as control bit and second as target bit. display(circuit.draw()) #### see the state-vector statevec = q.Aer.get_backend('statevector_simulator') final_state = q.execute(circuit, statevec).result().get_statevector() q.visualization.plot_bloch_multivector(final_state) # the state doesn't not change after application of the CNOT gate circuit.measure(qr, cr) circuit.draw(scale=2) #### simulate result on a local computer simulator = q.Aer.get_backend(name='qasm_simulator') results = q.execute(circuit, backend=simulator, ).result() q.visualization.plot_histogram(results.get_counts(circuit)) ### try a different circuit where we apply X gate before applying H gate. qr1 = q.QuantumRegister(2) cr1 = q.ClassicalRegister(2) circuit1 = q.QuantumCircuit(qr1, cr1) # circuit1.draw() circuit1.h(qr1[0]) # apply the H gate on q0 circuit1.x(qr1[1]) # apply Not gate on q_1 circuit1.h(qr1[1]) # add H gate on q_1 circuit1.cx(qr1[0], qr1[1]) # apply cx gate with control bit at 0th index ### draw the circuit circuit1.draw() #### plt the state vector statevec1 = q.Aer.get_backend('statevector_simulator') final_state1 = q.execute(circuit1, statevec1).result().get_statevector() q.visualization.plot_bloch_multivector(final_state1) # the state doesn't not change after application of the CNOT gate #### unchanged state as expected circuit1.measure(qr1, cr1) ### simulate result on local computer simulator1 = q.Aer.get_backend('qasm_simulator') results1 = q.execute(circuit1, backend=simulator1, ).result() q.visualization.plot_histogram(results1.get_counts(circuit1)) ### try a different circuit where we apply X gate before applying H gate. ### but we do this for first qubit. qr2 = q.QuantumRegister(2) cr2 = q.ClassicalRegister(2) circuit2 = q.QuantumCircuit(qr2, cr2) # circuit2.draw() circuit2.x(qr2[0]) circuit2.h(qr2[0]) circuit2.h(qr2[1]) circuit2.cx(qr2[0], qr2[1]) circuit2.draw() #### plt the state vector statevec2 = q.Aer.get_backend('statevector_simulator') final_state2 = q.execute(circuit2, statevec2).result().get_statevector() q.visualization.plot_bloch_multivector(final_state2) circuit2.measure(qr2, cr2) ### simulate result on local computer simulator2 = q.Aer.get_backend('qasm_simulator') results2 = q.execute(circuit2, backend=simulator1, ).result() q.visualization.plot_histogram(results2.get_counts(circuit2)) qr3 = q.QuantumRegister(2) cr3 = q.ClassicalRegister(2) circuit3 = q.QuantumCircuit(qr3, cr3) # circuit3.draw() circuit3.h(qr3[0]) circuit3.h(qr3[1]) ## apply hadamard gates to both qubits. circuit3.cx(qr3[0], qr3[1]) ## till this is first circuit. Now we add one more H gate. circuit3.h(qr3[0]) circuit3.draw(scale=2) ### plot the state vector statevec3 = q.Aer.get_backend('statevector_simulator') final_state3 = q.execute(circuit3, statevec3).result().get_statevector() q.visualization.plot_bloch_multivector(final_state3) # let's simulate this on local computer circuit3.measure(qr3, cr3) ### simulate result on local computer simulator3 = q.Aer.get_backend('qasm_simulator') results3 = q.execute(circuit3, backend=simulator3, ).result() q.visualization.plot_histogram(results3.get_counts(circuit3)) qr4 = q.QuantumRegister(2) cr4 = q.ClassicalRegister(2) circuit4 = q.QuantumCircuit(qr4, cr4) circuit4.h(qr4[0]) circuit4.h(qr4[1]) ## apply hadamard gates to both qubits. circuit4.cx(qr4[0], qr4[1]) ## till this is first circuit. Now we add one more H gate. circuit4.h(qr4[1]) # but now apply the H gate to the second qubit. circuit4.draw(scale=2) ### plot the state vector statevec4 = q.Aer.get_backend('statevector_simulator') final_state4 = q.execute(circuit4, statevec4).result().get_statevector() q.visualization.plot_bloch_multivector(final_state4) # let's simulate this on local computer circuit4.measure(qr4, cr4) ### simulate result on local computer simulator4 = q.Aer.get_backend('qasm_simulator') results4 = q.execute(circuit4, backend=simulator4, ).result() q.visualization.plot_histogram(results4.get_counts(circuit4)) ### !!! great !!! as expected
https://github.com/suvoooo/Qubits-Qiskit
suvoooo
# !pip3 install qiskit # !pip3 install pylatexenc import qiskit as q import numpy as np import matplotlib.pyplot as plt qr = q.QuantumRegister(3, name="q") crz, crx = q.ClassicalRegister(1, name="crz"), q.ClassicalRegister(1, name="crx") teleport_circuit = q.QuantumCircuit(qr, crz, crx) teleport_circuit.draw() def epr_pair(qc, a, b): ''' qc is the quantum circuit a, b are two different qubits ''' qc.h(a) qc.cx(a, b) epr_pair(teleport_circuit, qr[1], qr[2]) # we leave 0th qubit (this will be used later as Alice's qubit the she wants to teleport) teleport_circuit.draw() # assume alice owns q_1 and bob owns q_2 # now we are ready to take the transformations that Alice applies # the qubit she wants to teleport is control bit and the epr member bit is the target bit def alice_steps(qc, psi, a): qc.cx(psi, a) qc.h(psi) teleport_circuit.barrier() # barrier ensures the epr pair creation part isn't hampered/optimized by whatever happens next alice_steps(teleport_circuit, qr[0], qr[1]) teleport_circuit.draw() # after this alice applies the measurement def alice_measure(qc, a, b): qc.barrier() qc.measure(a, 0) # measures the first qubit and put it into first classical register # measure goes as # Measure quantum bit into classical bit (tuples). # Args: # qubit (QuantumRegister|list|tuple): quantum register # cbit (ClassicalRegister|list|tuple): classical register qc.measure(b, 1) alice_measure(teleport_circuit, 0, 1) # 0th qubit is the one she wants to send and 1st qubit is one of the EPR pairs teleport_circuit.draw() def bob_transform(qc, bob_bit, crz, crx): qc.x(bob_bit).c_if(crx, 1) #c_if Add classical condition on register classical and value val c_if(self, classical, val) qc.z(bob_bit).c_if(crz, 1) # apply x and z gate only when if any of then are in the state '1' teleport_circuit.barrier() bob_transform(teleport_circuit, qr[2], crz, crx) teleport_circuit.draw() from qiskit.quantum_info import random_statevector psi = random_statevector(2, seed=10) print ('check the qubit Alice wants to teleport: ', psi, type(psi), type(psi.data)) q.visualization.plot_bloch_multivector(psi) from qiskit.extensions import Initialize init_qubit = Initialize(psi.data) init_qubit.label = "init" inverse_init_qubit = init_qubit.gates_to_uncompute() #initialization start from zero to psi, we reverse this initialization so it takes us back to zero qc_new_teleport = q.QuantumCircuit(qr, crz, crx) qc_new_teleport.append(init_qubit, [qr[0]]) qc_new_teleport.barrier() epr_pair(qc_new_teleport, qr[1], qr[2]) qc_new_teleport.barrier() alice_steps(qc_new_teleport, qr[0], qr[1]) alice_measure(qc_new_teleport, qr[0], qr[1]) bob_transform(qc_new_teleport, qr[2], crz, crx) qc_new_teleport.draw() from google.colab import drive drive.mount('/content/drive') path = '/content/drive/My Drive/' style = {'backgroundcolor': 'lavender', 'dpi':200, 'subfontsize':10} qc_new_teleport.draw(output='mpl',scale=0.8, style=style, filename=path+'teleport_1.png') statevec_sim = q.Aer.get_backend('statevector_simulator') qobj = q.assemble(qc_new_teleport) out_vector = statevec_sim.run(qobj).result().get_statevector() q.visualization.plot_bloch_multivector(out_vector,) qc_teleport_check = q.QuantumCircuit(qr, crz, crx) qc_teleport_check.append(init_qubit, [qr[0]]) qc_teleport_check.barrier() epr_pair(qc_teleport_check, qr[1], qr[2]) qc_teleport_check.barrier() alice_steps(qc_teleport_check, qr[0], qr[1]) alice_measure(qc_teleport_check, qr[0], qr[1]) bob_transform(qc_teleport_check, qr[2], crz, crx) qc_teleport_check.append(inverse_init_qubit, [qr[2]]) style = {'backgroundcolor': 'lavender'} qc_teleport_check.draw(output='mpl',scale=0.8, style=style) cr_result = q.ClassicalRegister(1) # we need another register to measure if we get 0 or not qc_teleport_check.add_register(cr_result) qc_teleport_check.measure(qr[2], 2) # measure the last qubit and put it into the last classical register qc_teleport_check.draw(output='mpl', scale=0.8, style={'backgroundcolor': 'lavender', 'subfontsize':12}) simulator = q.Aer.get_backend(name='qasm_simulator') results = q.execute(qc_teleport_check, backend=simulator,).result() q.visualization.plot_histogram(results.get_counts(qc_teleport_check))
https://github.com/suvoooo/Qubits-Qiskit
suvoooo
# !pip install qiskit import math import matplotlib.pyplot as plt import numpy as np import qiskit as q from qiskit.visualization import plot_bloch_vector, plot_state_city from google.colab import drive drive.mount('/content/drive') path = '/content/drive/My Drive/Colab Notebooks/Quantum_Compute/' coords = [1, math.pi/2, math.pi] plot_bloch_vector(coords, coord_type='spherical', figsize=(6, 6), ) ## check density matrix from state vector initial_state1 = [0.j + 1./np.sqrt(2), 0, 0, 1/np.sqrt(2) + 0.j] initial_state2 = [0.j + 1./2., 0, 0, 0.j + np.sqrt(3)/2.] m1 = q.quantum_info.Statevector(initial_state1) print ('check the first statevector: ', m1) m2 = q.quantum_info.Statevector(initial_state2) print ('check the first statevector: ', m2) rho_1 = q.quantum_info.DensityMatrix(m1, dims=4) print ('check the density matrix corresponding to 1st statevector: ', '\n', rho_1) rho_2 = q.quantum_info.DensityMatrix(m2, dims=4) print ('check the density matrix corresponding to 2nd statevector: ', '\n', rho_2) rho_1.draw('latex', prefix='\\rho_{1} = ') plot_state_city(rho_1.data, title=r'Density Matrix for StateVector: $\frac{1}{\sqrt{2}}\left(|0\rangle + |1\rangle\right)$', color=['magenta', 'purple'], alpha=0.7, figsize=(11, 7), ) rho_2.draw('latex', prefix='\\rho_{2} = ') plot_state_city(rho_2.data, title=r'Density Matrix for StateVector: $\left(\frac{1}{2}|0\rangle + \frac{\sqrt{3}}{2}|1\rangle\right)$', color=['magenta', 'purple'], alpha=0.7, figsize=(11, 7), ) rho_H_matrix = np.array([[9/20, 0, 0, np.sqrt(3)/20 + 8/20], [0, 0, 0, 0], [0, 0, 0, 0], [np.sqrt(3)/20 + 8/20, 0, 0, 11/20]]) rho_H = q.quantum_info.DensityMatrix(rho_H_matrix) rho_H.draw('latex', prefix='\\rho_{mix} = ') final_density_matrix = 0.8*rho_1 + 0.2*rho_2 check_rho_H = q.quantum_info.DensityMatrix(final_density_matrix) check_rho_H.draw('latex', prefix='\\rho_{mix} = ') ### check the first property rho_H_matrix_square = np.matmul(rho_H_matrix, rho_H_matrix) rho_H_square = q.quantum_info.DensityMatrix(rho_H_matrix_square) rho_H_matrix_square_Trace = np.trace(rho_H_matrix_square) print ('Trace of the square of the density matrix: ', rho_H_matrix_square_Trace) rho_H_square.draw('latex', prefix='\\rho_{mix}^2 = ') ### check the second property rho_H_matrix_eigenvals = np.linalg.eigvals(rho_H_matrix) print ('check the eigenvalues of the density matrix', rho_H_matrix_eigenvals[0], rho_H_matrix_eigenvals[1]) print ('check sum of the eigenvalues of the density matrix: ', np.sum(rho_H_matrix_eigenvals)) plot_state_city(check_rho_H.data, title=r'Density Matrix for Mixed State: $0.8\times\frac{1}{\sqrt{2}}\left(|0\rangle + |1\rangle\right) + 0.2\times \left(\frac{1}{2}|0\rangle + \frac{\sqrt{3}}{2}|1\rangle\right)$', color=['crimson', 'purple'], alpha=0.4, figsize=(11, 7), ) reduced_density_matrix = np.array([[9/20, np.sqrt(3)/20 + 8/20], [np.sqrt(3)/20 + 8/20, 11/20]]) red_rho_H = q.quantum_info.DensityMatrix(reduced_density_matrix) red_rho_H.draw('latex', prefix='\\rho_{mix} = ') from qiskit.visualization import plot_bloch_multivector plot_bloch_multivector(state=red_rho_H.data, figsize=(6, 6), )
https://github.com/suvoooo/Qubits-Qiskit
suvoooo
# !pip3 install qiskit import qiskit as q import matplotlib.pyplot as plt import numpy as np def build_circ(num_qbits, num_cbits): qr = q.QuantumRegister(num_qbits) cr = q.ClassicalRegister(num_cbits) final_circ = q.QuantumCircuit(qr, cr) return final_circ, qr, cr def h_gates(qcirc, a, b): # 2 inputs and h gates in parallel qcirc.h(a) qcirc.h(b) hadamard_front, qr, cr = build_circ(2, 2) h_gates(hadamard_front, qr[0], qr[1]) hadamard_front.draw() ### define the oracle for state 00 hadamard_front.x(qr[0]) hadamard_front.x(qr[1]) hadamard_front.cz(qr[0], qr[1]) hadamard_front.x(qr[0]) hadamard_front.x(qr[1]) hadamard_front.draw() ### We apply the steps below to create the reflection about the original superposition state ### 1. Apply H to each qubit in the register. ### 2. A conditional phase shift of −1 to every computational basis state except |0⟩. ### This can be represented by the unitary operation −O_0, as O_0 represents the conditional phase shift to |0⟩ only. ### 3. Apply H to each qubit in the register. ### reflection about state |0> can be thought of as circuit below ### apply z gate to both qubits, then add a cz gate def reflection_psi(qcirc, a, b): h_gates(qcirc, a, b) qcirc.z(a) qcirc.z(b) qcirc.cz(a, b) h_gates(qcirc, a, b) reflection_psi_circ, qr_rf, cr_rf = build_circ(2, 2) reflection_psi(reflection_psi_circ, qr_rf[0], qr_rf[1]) reflection_psi_circ.draw() # !pip3 install pylatexenc complete_circuit = hadamard_front.compose(reflection_psi_circ) for n in range(2): complete_circuit.measure(n, n) complete_circuit.draw('mpl', filename=path+'Grover_Algo_00.png', scale=1.1) statevec_sim = q.Aer.get_backend("statevector_simulator") def statevec_exec(circ): statevec = q.execute(circ, backend=statevec_sim).result().get_statevector() return statevec complete_circuit_statevec = statevec_exec(complete_circuit) q.visualization.plot_bloch_multivector(complete_circuit_statevec) qasm_sim = q.Aer.get_backend('qasm_simulator') counts = q.execute(complete_circuit, backend=qasm_sim, shots=1024).result().get_counts() q.visualization.plot_histogram([counts], legend=['output']) from qiskit import IBMQ IBMQ.save_account('find your token') IBMQ.load_account() provider = IBMQ.get_provider('ibm-q') qcomp = provider.get_backend('ibmq_manila') # check which computer has 0 jobs on queue job = q.execute(complete_circuit, backend=qcomp) q_result = job.result() q.visualization.plot_histogram(q_result.get_counts(complete_circuit)) check_circ = q.QuantumCircuit(2) # check_circ.iswap(0, 1) check_circ.rz(np.pi/2, 0) check_circ.rz(np.pi/2, 1) check_circ.cz(0, 1) check_circ.rz(np.pi/2, 0) check_circ.rz(np.pi/2, 1) qasm_sim = q.Aer.get_backend('unitary_simulator') # we need to make a copy of the circuit with the 'save_statevector' # instruction to run on the Aer simulator job = q.execute(check_circ, qasm_sim) result = job.result() print(result.get_unitary(check_circ, decimals=2)) from google.colab import drive drive.mount('/content/drive') path = '/content/drive/My Drive/' ### let's use the oracke above to check whether we get 00 state as solution or not hadamard_front_check, qr_check, cr_check = build_circ(2, 2) h_gates(hadamard_front_check, qr_check[0], qr_check[1]) #### oracle with rz and cz gate hadamard_front_check.rz(np.pi/2, qr_check[0]) hadamard_front_check.rz(np.pi/2, qr_check[1]) hadamard_front_check.cz(qr_check[0], qr_check[1]) hadamard_front_check.rz(np.pi/2, qr_check[0]) hadamard_front_check.rz(np.pi/2, qr_check[1]) #### reflection_psi_circ_check, qr_rf_check, cr_rf_check = build_circ(2, 2) reflection_psi(reflection_psi_circ_check, qr_rf_check[0], qr_rf_check[1]) complete_circuit_check = hadamard_front_check.compose(reflection_psi_circ_check) for n in range(2): complete_circuit_check.measure(n, n) style = {'backgroundcolor': 'lavender', 'dpi':200, 'subfontsize':10} complete_circuit_check.draw('mpl', scale=0.8, style=style, filename=path+'Grover_Algo_RZ_00.png') qasm_sim = q.Aer.get_backend('qasm_simulator') counts = q.execute(complete_circuit_check, backend=qasm_sim, shots=1024).result().get_counts() q.visualization.plot_histogram([counts], legend=['output']) provider = IBMQ.get_provider('ibm-q') qcomp = provider.get_backend('ibmq_manila') # check which computer has 0 jobs on queue job = q.execute(complete_circuit_check, backend=qcomp) q_result = job.result() q.visualization.plot_histogram(q_result.get_counts(complete_circuit_check))
https://github.com/suvoooo/Qubits-Qiskit
suvoooo
### calculate the probability for theta = 1 degree import math import cmath def probs_unitary(ang): ang = math.radians(ang) # 1 degree y = complex(0, ang) #i1 y0 = 0.5*(1 + cmath.exp(y)) #print ('probability for getting 0: ', abs(y0)**2) y1 = 0.5*(1 - cmath.exp(y)) #print ('probability for getting 1: ', abs(y1)**2) return abs(y0)**2, abs(y1)**2 prob0, prob1 = probs_unitary(1) print (r'probability for getting 0 and 1 for $\theta=1$: ', prob0, prob1) prob0_10, prob1_10 = probs_unitary(10) print (r'probability for getting 0 and 1 for $\theta=10$: ', prob0_10, prob1_10) from google.colab import drive drive.mount('/content/drive/') !pip install qiskit import qiskit as q import matplotlib import matplotlib.pyplot as plt import numpy as np # from mpl_toolkits.mplot3d import proj3d print (q.__version__) print(matplotlib.__version__) style = {'backgroundcolor': 'lavender', 'dpi':200, 'subfontsize':10} PEcircuit = q.QuantumCircuit(3, 2) PEcircuit.x(2) # this is the eigen state of S gate; in figures above this $\psi$ PEcircuit.draw() # start by applying the H gates for qubit in range(2): PEcircuit.h(qubit) PEcircuit.draw() repetitions = 1 for counting_qubit in range(2): for i in range(repetitions): PEcircuit.cp(np.pi/2, counting_qubit, 2); # This is CU # QuantumCircuit.cp(theta, control_qubit, target_qubit, label=None, ctrl_state=None) # importantly to apply controlled phase rotation we need to know the rotation angle beforehand repetitions *= 2 # 2^{n-1} factor PEcircuit.draw() !pip install pylatexenc style = {'backgroundcolor': 'lavender', 'dpi':200, 'subfontsize':10} PEcircuit.draw(output='mpl', scale=0.8, style=style, filename='/content/drive/My Drive/Colab Notebooks/Quantum_Compute/FourierTransform/2bits_QPE_QiskitEx.png') def qft_dagger(qc, n): """n-qubit inverse qft first n qubits will be transformed check the qft circuit implementation first """ for qubit in range(n//2): qc.swap(qubit, n-qubit-1) for j in range(n): for m in range(j): qc.cp(-math.pi/float(2**(j-m)), m, j) qc.h(j) PEcircuit.barrier() # Apply inverse QFT qft_dagger(PEcircuit, 2) # Measure PEcircuit.barrier() for n in range(2): PEcircuit.measure(n,n) # PEcircuit.draw(output='mpl', style=style, filename='/content/drive/My Drive/Colab Notebooks/Quantum_Compute/FourierTransform/2bits_QPE_QiskitEx_Full.png') aer_sim = q.Aer.get_backend('aer_simulator') shots = 2048 t_PEcircuit = q.transpile(PEcircuit, aer_sim) qobj = q.assemble(t_PEcircuit, shots=shots) results = aer_sim.run(qobj).result() answer = results.get_counts() q.visualization.plot_histogram(answer) PEcircuit_1 = q.QuantumCircuit(4, 3) PEcircuit_1.x(3) # this is the eigen state of S gate; in figures above this $\psi$ for qubit in range(3): PEcircuit_1.h(qubit) repetitions = 1 for counting_qubit in range(3): for i in range(repetitions): PEcircuit_1.cp(np.pi/2, counting_qubit, 3) # This is CU # QuantumCircuit.cp(theta, control_qubit, target_qubit, label=None, ctrl_state=None) # importantly to apply controlled phase rotation we need to know the rotation angle beforehand repetitions *= 2 # 2^{n-1} factor PEcircuit_1.draw() PEcircuit_1.barrier() # Apply inverse QFT qft_dagger(PEcircuit_1, 3) # Measure PEcircuit_1.barrier() for n in range(3): PEcircuit_1.measure(n, n) PEcircuit_1.draw(output='mpl', style=style, filename='/content/drive/My Drive/Colab Notebooks/Quantum_Compute/FourierTransform/3bits_QPE_QiskitEx.png') aer_sim = q.Aer.get_backend('aer_simulator') shots = 2048 t_PEcircuit_1 = q.transpile(PEcircuit_1, aer_sim) qobj = q.assemble(t_PEcircuit_1, shots=shots) results_1 = aer_sim.run(qobj).result() answer_1 = results_1.get_counts() q.visualization.plot_histogram(answer_1) PEcircuit_1.num_qubits-1 def qpe_circ(nq, angle): """ generic qpe circuit nq: number of qubits angle: theta as defined in description """ qc = q.QuantumCircuit(nq+1, nq) # num qubits + eigen state, for measuring we need num qubits = classical bits for measure. qc.x(nq) # apply the not gate to create state 1, i.e. eigen state at the last qubit for qubit in range(nq): qc.h(qubit) repetitions = 1 for counting_qubit in range(qc.num_qubits - 1): #qc.num_qubits - 1 = nq for i in range(repetitions): qc.cp(np.pi *2 * angle, counting_qubit, qc.num_qubits-1); # This is CU # QuantumCircuit.cp(theta, control_qubit, target_qubit, label=None, ctrl_state=None) # importantly to apply controlled phase rotation we need to know the rotation angle beforehand repetitions *= 2 # 2^{n-1} factor qc.barrier() qft_dagger(qc, qc.num_qubits-1) qc.barrier() for n1 in range(qc.num_qubits -1): qc.measure(n1, n1) return qc circuit_1 = qpe_circ(3, 1/5) circuit_1.draw(output='mpl', style=style, filename='/content/drive/My Drive/Colab Notebooks/Quantum_Compute/FourierTransform/3bits_QPE_QiskitEx_NonInt_Theta.png') aer_sim = q.Aer.get_backend('aer_simulator') shots = 2048 t_circuit_1 = q.transpile(circuit_1, aer_sim) qobj = q.assemble(t_circuit_1, shots=shots) results_c1 = aer_sim.run(qobj).result() answer_c1 = results_c1.get_counts() q.visualization.plot_histogram(answer_c1) circuit_2 = qpe_circ(5, 1/5) circuit_2.draw(output='mpl', style=style, filename='/content/drive/My Drive/Colab Notebooks/Quantum_Compute/FourierTransform/5bits_QPE_QiskitEx_NonInt_Theta.png') aer_sim = q.Aer.get_backend('aer_simulator') shots = 2048 t_circuit_2 = q.transpile(circuit_2, aer_sim) qobj = q.assemble(t_circuit_2, shots=shots) results_c2 = aer_sim.run(qobj).result() answer_c2 = results_c2.get_counts() fig, ax = plt.subplots(figsize=(14, 6)) q.visualization.plot_histogram(answer_c2, figsize=(14, 6), color='violet', title=r'QPE Measurement Result with 5 Qubits: $\theta = 1/5$', ax=ax) fig.savefig('/content/drive/My Drive/Colab Notebooks/Quantum_Compute/FourierTransform/5bits_QPE_QiskitEx_NonInt_Theta_Histogram.png', dpi=250) for k, v in answer_c2.items(): print(k, v)
https://github.com/suvoooo/Qubits-Qiskit
suvoooo
# !pip3 install qiskit import numpy as np import qiskit as q ### build a circuit for 3 qubits qr = q.QuantumRegister(3) circ = q.QuantumCircuit(qr) ### add the first H gate (in qiskit east significant bit has the lowest index) circ.h(qr[2]) ### add the controlled phase gate circ.cp(np.pi/2, qr[1], qr[2]) # based on qubit 1 apply 2pi/2**(k-1) rotation to qubit 2 ### add the next cp gate circ.cp(np.pi/4, qr[0], qr[2]) # based on qubit 0 apply 2pi/2**(k-1) rotation to qubit 2 ### repeat the process for qubit 1 circ.h(qr[1]) circ.cp(np.pi/2, qr[0], qr[1]) ### add the final h gate circ.h(qr[0]) ### finally swap the bits 0 th, and 2nd qubit circ.swap(qr[0], qr[2]) circ.draw() from google.colab import drive drive.mount('/content/drive') # !pip install pylatexenc path='/content/drive/My Drive/Colab Notebooks/' style = {'backgroundcolor': 'lavender', 'dpi':200, 'subfontsize':10} circ.draw('mpl', scale=0.8, style=style, filename=path+'qfouriert_3bits.png') qr = q.QuantumRegister(3) circ1 = q.QuantumCircuit(qr) ### encode the state 110 at first circ1.x(qr[2]) circ1.x(qr[1]) ### repeat what's done before ### add the first H gate (in qiskit east significant bit has the lowest index) circ1.h(qr[2]) ### add the controlled phase gate circ1.cp(np.pi/2, qr[1], qr[2]) # based on qubit 1 apply 2pi/2**(k-1) rotation to qubit 2 ### add the next cp gate circ1.cp(np.pi/4, qr[0], qr[2]) # based on qubit 0 apply 2pi/2**(k-1) rotation to qubit 2 ### repeat the process for qubit 1 circ1.h(qr[1]) circ1.cp(np.pi/2, qr[0], qr[1]) ### add the final h gate circ1.h(qr[0]) ### finally swap the bits 0 th, and 2nd qubit circ1.swap(qr[0], qr[2]) circ1.draw() circ1.save_statevector() qasm_sim = q.Aer.get_backend('qasm_simulator') statevector = qasm_sim.run(circ1).result().get_statevector() q.visualization.plot_bloch_multivector(statevector) qr = q.QuantumRegister(3) circ2 = q.QuantumCircuit(qr) ### encode the state 101 at first circ2.x(qr[2]) circ2.x(qr[0]) ### repeat what's done before ### add the first H gate (in qiskit east significant bit has the lowest index) circ2.h(qr[2]) ### add the controlled phase gate circ2.cp(np.pi/2, qr[1], qr[2]) # based on qubit 1 apply 2pi/2**(k-1) rotation to qubit 2 ### add the next cp gate circ2.cp(np.pi/4, qr[0], qr[2]) # based on qubit 0 apply 2pi/2**(k-1) rotation to qubit 2 ### repeat the process for qubit 1 circ2.h(qr[1]) circ2.cp(np.pi/2, qr[0], qr[1]) ### add the final h gate circ2.h(qr[0]) ### finally swap the bits 0 th, and 2nd qubit circ2.swap(qr[0], qr[2]) circ2.draw() circ2.save_statevector() qasm_sim = q.Aer.get_backend('qasm_simulator') statevector2 = qasm_sim.run(circ2).result().get_statevector() q.visualization.plot_bloch_multivector(statevector2)
https://github.com/suvoooo/Qubits-Qiskit
suvoooo
path_to_file = '/content/drive/My Drive/Colab Notebooks/Quantum_Compute/' from google.colab import drive drive.mount('/content/drive/') ###### can we visualize the period import math import matplotlib.pyplot as plt N = 21 #15 a_1 = 5 #13 # starting co-prime a_2 = 11 x = list(range(N)) K_1 = [a_1**r % N for r in x] K_2 = [a_2**r % N for r in x] # K_3 = [a_3**r % N for r in x] period = x[K_2[1:].index(1) + 1] print ('period of the function: ', x[K_1[1:].index(1) + 1]) # (index of the 1 after the first 1) + 1 print ('period of the function: ', x[K_2[1:].index(1) + 1]) fig=plt.figure(figsize=(15, 5)) fig.add_subplot(121) plt.plot(x, K_1, label='a = %d'%(a_1)) plt.xlabel('x', fontsize=14) plt.ylabel(r'$a^x\, (\mathrm{mod}\, N)$', fontsize=14) plt.legend(fontsize=12) fig.add_subplot(122) plt.plot(x, K_2, linestyle='--', color='purple', alpha=0.6, label='a = %d'%(a_2)) plt.axvline(x=period, lw=0.8, ls='--', color='magenta', alpha=0.6, label='Period=%d'%(period)) plt.axvline(x=2*period, lw=0.8, ls='--', color='magenta', alpha=0.6) plt.xlabel('x', fontsize=14) # plt.legend(fontsize=12) # fig.add_subplot(133) # plt.plot(x, K_3, linestyle=':', color='lime', alpha=0.6, label='a = 8') # plt.xlabel('x', fontsize=12) plt.legend(fontsize=12) plt.savefig(path_to_file +'/Period_Mod_N.png', dpi=250) plt.show() # print ('period of the function: ', x[K_3[1:].index(1) + 1]) import numpy as np for y in range(15): exp = np.exp(-1j*2*np.pi*(3*y/16)) + np.exp(-1j*2*np.pi*(7*y/16)) + np.exp(-1j*2*np.pi*(11*y/16)) + np.exp(-1j*2*np.pi*(15*y/16)) if abs(exp) < 1e-10: exp = 0 print(exp, y, abs(exp)) # !pip install qiskit import qiskit as q import numpy as np import matplotlib.pyplot as plt def c_amod15(a, power): """Controlled multiplication by a mod 15""" if a not in [2,4,7,8,11,13]: raise ValueError("'a' must be 2,4,7,8,11 or 13") U = q.QuantumCircuit(4) for iteration in range(power): if a in [2,13]: U.swap(0,1) U.swap(1,2) U.swap(2,3) if a in [7,8]: U.swap(2,3) U.swap(1,2) U.swap(0,1) if a in [4, 11]: U.swap(1,3) U.swap(0,2) if a in [7,11,13]: for i in range(4): U.x(i) U = U.to_gate() U.name = "%i^%i mod 15" % (a, power) c_U = U.control() return c_U def qft_dagger(n): """n-qubit QFTdagger the first n qubits in circ""" qc = q.QuantumCircuit(n) # Don't forget the Swaps! for qubit in range(n//2): qc.swap(qubit, n-qubit-1) for j in range(n): for m in range(j): qc.cp(-np.pi/float(2**(j-m)), m, j) qc.h(j) qc.name = "QFT†" return qc n_count = 8 a = 7 # Create QuantumCircuit with n_count counting qubits # plus 4 qubits for U to act on qc = q.QuantumCircuit(n_count + 4, n_count) # # Initialize counting qubits # # in state |+> for i in range(n_count): qc.h(i) # # And auxiliary register in state |1> qc.x(3+n_count) # # Do controlled-U operations for k in range(n_count): qc.append(c_amod15(a, 2**k), [k] + [i+n_count for i in range(4)]) # # Do inverse-QFT qc.append(qft_dagger(n_count), range(n_count)) # # Measure circuit qc.measure(range(n_count), range(n_count)) qc.draw() # -1 means 'do not fold'
https://github.com/QuSTaR/kaleidoscope
QuSTaR
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/QuSTaR/kaleidoscope
QuSTaR
# -*- coding: utf-8 -*- # This code is part of Kaleidoscope. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # The Hamming distance and internal plot histogram data are part of # Qiskit. The latter will be modified at some point. """Interactive histogram from experiment counts""" import functools from collections import Counter, OrderedDict import numpy as np import plotly.graph_objects as go from kaleidoscope.errors import KaleidoscopeError from kaleidoscope.colors import COLORS1, COLORS2, COLORS3, COLORS4, COLORS5, COLORS14 from kaleidoscope.colors.utils import find_text_color from .plotly_wrapper import PlotlyWidget, PlotlyFigure def hamming_distance(str1, str2): """Calculate the Hamming distance between two bit strings Args: str1 (str): First string. str2 (str): Second string. Returns: int: Distance between strings. Raises: ValueError: Strings not same length """ if len(str1) != len(str2): raise ValueError('Strings not same length.') return sum(s1 != s2 for s1, s2 in zip(str1, str2)) VALID_SORTS = ['asc', 'desc', 'hamming'] DIST_MEAS = {'hamming': hamming_distance} def probability_distribution(data, figsize=(None, None), colors=None, scale='linear', number_to_keep=None, sort='asc', target_string=None, legend=None, bar_labels=True, state_labels_kind='bits', state_labels=None, title=None, plot_background_color='#e5e0df', background_color='#ffffff', as_widget=False): """Interactive histogram plot of probability distributions. Parameters: data (list or dict): This is either a list of dictionaries or a single dict containing the values to represent (ex {'001': 130}) figsize (tuple): Figure size in pixels. colors (list or str): String or list of strings for histogram bar colors. scale (str): Probability scale 'linear' (default) or 'log'. number_to_keep (int): The number of terms to plot and rest is made into a single bar called 'rest'. sort (string): Could be 'asc', 'desc', or 'hamming'. target_string (str): Target string if 'sort' is a distance measure. legend(list): A list of strings to use for labels of the data. The number of entries must match the length of data (if data is a list or 1 if it's a dict) bar_labels (bool): Label each bar in histogram with probability value. state_labels_kind (str): 'bits' (default) or 'ints'. state_labels (list): A list of custom state labels. title (str): A string to use for the plot title. plot_background_color (str): Set the background color behind histogram bars. background_color (str): Set the background color for axes. as_widget (bool): Return figure as an ipywidget. Returns: PlotlyFigure or PlotlyWidget: A figure for the rendered histogram. Raises: ValueError: When legend is provided and the length doesn't match the input data. ImportError: When failed to load plotly. KaleidoscopeError: When state labels is not correct length. Example: .. jupyter-execute:: from qiskit import * import kaleidoscope.qiskit from kaleidoscope.qiskit.services import Simulators from kaleidoscope.interactive import probability_distribution sim = Simulators.aer_vigo_simulator qc = QuantumCircuit(3, 3) >> sim qc.h(1) qc.cx(1,0) qc.cx(1,2) qc.measure(range(3), range(3)) counts = qc.transpile().sample().result_when_done() probability_distribution(counts) """ if sort not in VALID_SORTS: raise ValueError("Value of sort option, %s, isn't a " "valid choice. Must be 'asc', " "'desc', or 'hamming'") if sort in DIST_MEAS and target_string is None: err_msg = 'Must define target_string when using distance measure.' raise ValueError(err_msg) if isinstance(data, dict): data = [data] if legend and len(legend) != len(data): raise ValueError("Length of legendL (%s) doesn't match " "number of input executions: %s" % (len(legend), len(data))) text_color = find_text_color(background_color) labels = list(sorted( functools.reduce(lambda x, y: x.union(y.keys()), data, set()))) if number_to_keep is not None: labels.append('rest') if sort in DIST_MEAS: dist = [] for item in labels: dist.append(DIST_MEAS[sort](item, target_string)) labels = [list(x) for x in zip(*sorted(zip(dist, labels), key=lambda pair: pair[0]))][1] # Set bar colors if colors is None: if len(data) == 1: colors = COLORS1 elif len(data) == 2: colors = COLORS2 elif len(data) == 3: colors = COLORS3 elif len(data) == 4: colors = COLORS4 elif len(data) == 5: colors = COLORS5 else: colors = COLORS14 elif isinstance(colors, str): colors = [colors] width = 1/(len(data)+1) # the width of the bars labels_dict, all_pvalues, _ = _plot_histogram_data(data, labels, number_to_keep) fig = go.Figure() for item, _ in enumerate(data): xvals = [] yvals = [] for idx, val in enumerate(all_pvalues[item]): xvals.append(idx+item*width) yvals.append(val) labels = list(labels_dict.keys()) if state_labels_kind == 'ints': labels = [int(label, 2) for label in labels] if state_labels: if len(state_labels) != len(labels): raise KaleidoscopeError('Number of input state labels does not match data.') labels = state_labels hover_template = "<b>{x}</b><br>P = {y}" hover_text = [hover_template.format(x=labels[kk], y=np.round(yvals[kk], 3)) for kk in range(len(yvals))] fig.add_trace(go.Bar(x=xvals, y=yvals, width=width, hoverinfo="text", hovertext=hover_text, marker_color=colors[item % len(colors)], name=legend[item] if legend else '', text=np.round(yvals, 3) if bar_labels else None, textposition='auto' )) xaxes_labels = list(labels_dict.keys()) if state_labels_kind == 'ints': xaxes_labels = [int(label, 2) for label in xaxes_labels] if state_labels: if len(state_labels) != len(xaxes_labels): raise KaleidoscopeError('Number of input state labels does not match data.') xaxes_labels = state_labels fig.update_xaxes(title='Basis state', titlefont_size=16, tickvals=list(range(len(labels_dict.keys()))), ticktext=xaxes_labels, tickfont_size=14, showline=True, linewidth=1, linecolor=text_color if text_color == 'white' else None, ) fig.update_yaxes(title='Probability', titlefont_size=16, tickfont_size=14, showline=True, linewidth=1, linecolor=text_color if text_color == 'white' else None, ) if scale == 'log': lower = np.min([min(item.values())/sum(item.values()) for item in data]) lower = int(np.floor(np.log10(lower))) fig.update_yaxes(type="log", range=[lower, 0]) fig.update_layout(yaxis=dict(tickmode='array', tickvals=[10**k for k in range(lower, 1)], ticktext=["10<sup>{}</sup>".format(k) for k in range(lower, 1)] )) fig.update_layout(xaxis_tickangle=-70, showlegend=(legend is not None), width=figsize[0], height=figsize[1], plot_bgcolor=plot_background_color, paper_bgcolor=background_color, title=dict(text=title, x=0.5), title_font_size=18, font=dict(color=text_color), ) if as_widget: return PlotlyWidget(fig) return PlotlyFigure(fig) def _plot_histogram_data(data, labels, number_to_keep): """Generate the data needed for plotting counts. Parameters: data (list or dict): This is either a list of dictionaries or a single dict containing the values to represent (ex {'001': 130}) labels (list): The list of bitstring labels for the plot. number_to_keep (int): The number of terms to plot and rest is made into a single bar called 'rest'. Returns: tuple: tuple containing: (dict): The labels actually used in the plotting. (list): List of ndarrays for the bars in each experiment. (list): Indices for the locations of the bars for each experiment. """ labels_dict = OrderedDict() all_pvalues = [] all_inds = [] for execution in data: if number_to_keep is not None: data_temp = dict(Counter(execution).most_common(number_to_keep)) data_temp["rest"] = sum(execution.values()) - sum(data_temp.values()) execution = data_temp values = [] for key in labels: if key not in execution: if number_to_keep is None: labels_dict[key] = 1 values.append(0) else: values.append(-1) else: labels_dict[key] = 1 values.append(execution[key]) values = np.array(values, dtype=float) where_idx = np.where(values >= 0)[0] pvalues = values[where_idx] / sum(values[where_idx]) all_pvalues.append(pvalues) numelem = len(values[where_idx]) ind = np.arange(numelem) # the x locations for the groups all_inds.append(ind) return labels_dict, all_pvalues, all_inds
https://github.com/QuSTaR/kaleidoscope
QuSTaR
#!/usr/bin/env python # # Copyright 2019 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import pygame from qiskit import BasicAer, execute from qiskit.tools.visualization import plot_state_qsphere from utils import load_image class QSphere(pygame.sprite.Sprite): """Displays a qsphere""" def __init__(self, circuit): pygame.sprite.Sprite.__init__(self) self.image = None self.rect = None self.set_circuit(circuit) # def update(self): # # Nothing yet # a = 1 def set_circuit(self, circuit): backend_sv_sim = BasicAer.get_backend('statevector_simulator') job_sim = execute(circuit, backend_sv_sim) result_sim = job_sim.result() quantum_state = result_sim.get_statevector(circuit, decimals=3) qsphere = plot_state_qsphere(quantum_state) qsphere.savefig("utils/data/bell_qsphere.png") self.image, self.rect = load_image('bell_qsphere.png', -1) self.rect.inflate_ip(-100, -100) self.image.convert()
https://github.com/QuSTaR/kaleidoscope
QuSTaR
# -*- coding: utf-8 -*- # This code is part of Kaleidoscope. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Interactive Bloch discs""" import math import numpy as np import plotly.graph_objects as go from plotly.subplots import make_subplots import matplotlib.pyplot as plt import matplotlib.colors from kaleidoscope.utils import pi_check from kaleidoscope.interactive.plotly_wrapper import PlotlyFigure, PlotlyWidget from kaleidoscope.interactive.bloch.utils import bloch_components from kaleidoscope.colors.utils import hex_to_rgb from kaleidoscope.colors import BJY from kaleidoscope.colors.cmap import cmap_to_plotly NORM = plt.Normalize(-1, 1) def bloch_sunburst(vec, colormap): """Create a Bloch disc using a Plotly sunburst. Parameters: vec (ndarray): A vector of Bloch components. colormap (Colormap): A matplotlib colormap. Returns: go.Figure: A Plotly figure instance, Raises: ValueError: Input vector is not normalized. """ eps = 1e-6 vec = np.asarray(vec) vec_norm = np.linalg.norm(vec) if vec_norm > 1.0 + eps: raise ValueError('Input vector has length {} greater than 1.0'.format(vec_norm)) for idx, val in enumerate(vec): if abs(val) < 1e-15: vec[idx] = 0 th = math.atan2(vec[1], vec[0]) if th < 0: th = 2*np.pi+th z_hex = matplotlib.colors.rgb2hex(colormap(NORM(vec[2]))) z_color = "rgba({},{},{},{})".format(*hex_to_rgb(z_hex), 0.95*vec_norm+0.05) ring_color = "rgba({},{},{},{})".format(*hex_to_rgb('#000000'), 0.95*vec_norm+0.05) wedge_str = "\u2329X\u232A= {x}<br>" wedge_str += "\u2329Y\u232A= {y}<br>" wedge_str += "\u2329Z\u232A= {z}<br>" wedge_str += " \u03B8 = {th}<br>" wedge_str += "|\u03C8| = {pur}" th_str = pi_check(th, ndigits=3) th_str = th_str.replace('pi', '\u03C0') hover_text = [wedge_str.format(x=round(vec[0], 3), y=round(vec[1], 3), z=round(vec[2], 3), th=th_str, pur=np.round(vec_norm, 3))] + [None] bloch = go.Sunburst(labels=[" ", " "], parents=["", " "], values=[2*np.pi-th, th], hoverinfo="text", hovertext=hover_text, marker=dict(colors=[z_color, ring_color])) return bloch def bloch_disc(rho, figsize=None, title=None, colormap=None, as_widget=False): """Plot a Bloch disc for a single qubit. Parameters: rho (list or ndarray or Statevector or DensityMatrix): Input statevector, density matrix, or Bloch components. figsize (tuple): Figure size in pixels, default=(200,275). title (str): Plot title. colormap (Colormap): A matplotlib colormap. as_widget (bool): Return plot as a widget. Returns: PlotlyFigure: A Plotly figure instance PlotlyWidget : A Plotly widget if `as_widget=True`. Example: .. jupyter-execute:: import numpy as np from qiskit import * from qiskit.quantum_info import Statevector from kaleidoscope.interactive import bloch_disc qc = QuantumCircuit(1) qc.ry(np.pi*np.random.random(), 0) qc.rz(np.pi*np.random.random(), 0) state = Statevector.from_instruction(qc) bloch_disc(state) """ # A hack so I do not have to import the actual instances from Qiskit. if rho.__class__.__name__ in ['Statevector', 'DensityMatrix'] \ and 'qiskit' in rho.__class__.__module__: rho = rho.data if len(rho) != 3: rho = np.asarray(rho, dtype=complex) comp = bloch_components(rho) else: comp = [rho] if title: title = [title] + ["\u2329Z\u232A"] else: title = [""] + ["\u2329Z\u232A"] if colormap is None: colormap = BJY if figsize is None: figsize = (200, 275) fig = make_subplots(rows=1, cols=2, specs=[[{'type': 'domain'}]+[{'type': 'xy'}]], subplot_titles=title, column_widths=[0.93]+[0.07]) fig.add_trace(bloch_sunburst(comp[0], colormap), row=1, col=1) zval = comp[0][2] zrange = [k*np.ones(1) for k in np.linspace(-1, 1, 100)] idx = (np.abs(np.linspace(-1, 1, 100) - zval)).argmin() tickvals = np.array([0, 49, 99, idx]) idx_sort = np.argsort(tickvals) tickvals = tickvals[idx_sort] ticktext = [-1, 0, 1, "\u25C0"+str(np.round(zval, 3))] if zval <= -0.95: ticktext[0] = '' elif abs(zval) <= 0.05: ticktext[1] = '' elif zval >= 0.95: ticktext[2] = '' ticktext = [ticktext[kk] for kk in idx_sort] PLOTLY_CMAP = cmap_to_plotly(colormap) fig.append_trace(go.Heatmap(z=zrange, colorscale=PLOTLY_CMAP, showscale=False, hoverinfo='none', ), row=1, col=2 ) fig.update_yaxes(row=1, col=2, tickvals=tickvals, ticktext=ticktext) fig.update_yaxes(row=1, col=2, side="right") fig.update_xaxes(row=1, col=2, visible=False) fig.update_layout(margin=dict(t=30, l=10, r=0, b=0), height=figsize[0], width=figsize[1], hoverlabel=dict(font_size=16, font_family="courier,monospace", align='left' ) ) for ann in fig['layout']['annotations']: ann['font'] = dict(size=14) if as_widget: return PlotlyWidget(fig) return PlotlyFigure(fig) def bloch_multi_disc(rho, figsize=None, titles=True, colormap=None, as_widget=False): """Plot Bloch discs for a multi-qubit state. Parameters: rho (list or ndarray or Statevector or DensityMatrix): Input statevector, density matrix. figsize (tuple): Figure size in pixels, default=(125*num_qubits, 150). titles (bool): Display titles. colormap (Colormap): A matplotlib colormap. as_widget (bool): Return plot as a widget. Returns: PlotlyFigure: A Plotly figure instance PlotlyWidget : A Plotly widget if `as_widget=True`. Example: .. jupyter-execute:: import numpy as np from qiskit import * from qiskit.quantum_info import Statevector from kaleidoscope.interactive import bloch_multi_disc N = 4 qc = QuantumCircuit(N) qc.h(range(N)) for kk in range(N): qc.ry(2*np.pi*np.random.random(), kk) for kk in range(N-1): qc.cx(kk,kk+1) for kk in range(N): qc.rz(2*np.pi*np.random.random(), kk) state = Statevector.from_instruction(qc) bloch_multi_disc(state) """ # A hack so I do not have to import the actual instances from Qiskit. if rho.__class__.__name__ in ['Statevector', 'DensityMatrix'] \ and 'qiskit' in rho.__class__.__module__: rho = rho.data rho = np.asarray(rho, dtype=complex) comp = bloch_components(rho) num = int(np.log2(rho.shape[0])) nrows = 1 ncols = num if figsize is None: figsize = (ncols*125, 150) if titles: titles = ["Qubit {}".format(k) for k in range(num)] + ["\u2329Z\u232A"] else: titles = ["" for k in range(num)] + ["\u2329Z\u232A"] if colormap is None: colormap = BJY fig = make_subplots(rows=nrows, cols=ncols+1, specs=[[{'type': 'domain'}]*ncols+[{'type': 'xy'}]], subplot_titles=titles, column_widths=[0.95/num]*num+[0.05]) for jj in range(num): fig.add_trace(bloch_sunburst(comp[jj], colormap), row=1, col=jj+1) zrange = [k*np.ones(1) for k in np.linspace(-1, 1, 100)] PLOTLY_CMAP = cmap_to_plotly(colormap) fig.append_trace(go.Heatmap(z=zrange, colorscale=PLOTLY_CMAP, showscale=False, hoverinfo='none', ), row=1, col=num+1) fig.update_yaxes(row=1, col=num+1, tickvals=[0, 49, 99], ticktext=[-1, 0, 1]) fig.update_yaxes(row=1, col=num+1, side="right") fig.update_xaxes(row=1, col=num+1, visible=False) fig.update_layout(margin=dict(t=50, l=0, r=15, b=30), width=figsize[0], height=figsize[1], hoverlabel=dict(font_size=14, font_family="monospace", align='left' ) ) # Makes the subplot titles smaller than the 16pt default for ann in fig['layout']['annotations']: ann['font'] = dict(size=16) if as_widget: return PlotlyWidget(fig) return PlotlyFigure(fig)
https://github.com/QuSTaR/kaleidoscope
QuSTaR
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=invalid-name """Interactive error map for IBM Quantum Experience devices.""" import math from typing import Tuple, Union import numpy as np from plotly.subplots import make_subplots import plotly.graph_objects as go import matplotlib as mpl from qiskit.providers.ibmq.ibmqbackend import IBMQBackend from .plotly_wrapper import PlotlyWidget, PlotlyFigure from ..device_layouts import DEVICE_LAYOUTS from ..colormaps import (HELIX_LIGHT, HELIX_LIGHT_CMAP, HELIX_DARK, HELIX_DARK_CMAP) from ..exceptions import VisualizationValueError, VisualizationTypeError def iplot_error_map( backend: IBMQBackend, figsize: Tuple[int] = (800, 500), show_title: bool = True, remove_badcal_edges: bool = True, background_color: str = 'white', as_widget: bool = False ) -> Union[PlotlyFigure, PlotlyWidget]: """Plot the error map of a device. Args: backend: Plot the error map for this backend. figsize: Figure size in pixels. show_title: Whether to show figure title. remove_badcal_edges: Whether to remove bad CX gate calibration data. background_color: Background color, either 'white' or 'black'. as_widget: ``True`` if the figure is to be returned as a ``PlotlyWidget``. Otherwise the figure is to be returned as a ``PlotlyFigure``. Returns: The error map figure. Raises: VisualizationValueError: If an invalid input is received. VisualizationTypeError: If the specified `backend` is a simulator. Example: .. jupyter-execute:: :hide-code: :hide-output: from qiskit.test.ibmq_mock import mock_get_backend mock_get_backend('FakeVigo') .. jupyter-execute:: from qiskit import IBMQ from qiskit.providers.ibmq.visualization import iplot_error_map IBMQ.load_account() provider = IBMQ.get_provider(group='open', project='main') backend = provider.get_backend('ibmq_vigo') iplot_error_map(backend, as_widget=True) """ meas_text_color = '#000000' if background_color == 'white': color_map = HELIX_LIGHT_CMAP text_color = '#000000' plotly_cmap = HELIX_LIGHT elif background_color == 'black': color_map = HELIX_DARK_CMAP text_color = '#FFFFFF' plotly_cmap = HELIX_DARK else: raise VisualizationValueError( '"{}" is not a valid background_color selection.'.format(background_color)) if backend.configuration().simulator: raise VisualizationTypeError('Requires a device backend, not a simulator.') config = backend.configuration() n_qubits = config.n_qubits cmap = config.coupling_map if n_qubits in DEVICE_LAYOUTS.keys(): grid_data = DEVICE_LAYOUTS[n_qubits] else: fig = go.Figure() fig.update_layout(showlegend=False, plot_bgcolor=background_color, paper_bgcolor=background_color, width=figsize[0], height=figsize[1], margin=dict(t=60, l=0, r=0, b=0) ) out = PlotlyWidget(fig) return out props = backend.properties().to_dict() t1s = [] t2s = [] for qubit_props in props['qubits']: count = 0 for item in qubit_props: if item['name'] == 'T1': t1s.append(item['value']) count += 1 elif item['name'] == 'T2': t2s.append(item['value']) count += 1 if count == 2: break # U2 error rates single_gate_errors = [0]*n_qubits for gate in props['gates']: if gate['gate'] == 'u2': _qubit = gate['qubits'][0] single_gate_errors[_qubit] = gate['parameters'][0]['value'] # Convert to percent single_gate_errors = 100 * np.asarray(single_gate_errors) avg_1q_err = np.mean(single_gate_errors) max_1q_err = max(single_gate_errors) single_norm = mpl.colors.Normalize( vmin=min(single_gate_errors), vmax=max_1q_err) q_colors = [mpl.colors.rgb2hex(color_map(single_norm(err))) for err in single_gate_errors] line_colors = [] cx_idx = [] if n_qubits > 1 and cmap: cx_errors = [] for cmap_qubits in cmap: for gate in props['gates']: if gate['qubits'] == cmap_qubits: cx_errors.append(gate['parameters'][0]['value']) break else: continue # Convert to percent cx_errors = 100 * np.asarray(cx_errors) # remove bad cx edges if remove_badcal_edges: cx_idx = np.where(cx_errors != 100.0)[0] else: cx_idx = np.arange(len(cx_errors)) avg_cx_err = np.mean(cx_errors[cx_idx]) for err in cx_errors: if err != 100.0 or not remove_badcal_edges: cx_norm = mpl.colors.Normalize( vmin=min(cx_errors[cx_idx]), vmax=max(cx_errors[cx_idx])) line_colors.append(mpl.colors.rgb2hex(color_map(cx_norm(err)))) else: line_colors.append("#ff0000") # Measurement errors read_err = [] for qubit in range(n_qubits): for item in props['qubits'][qubit]: if item['name'] == 'readout_error': read_err.append(item['value']) read_err = 100 * np.asarray(read_err) avg_read_err = np.mean(read_err) max_read_err = np.max(read_err) if n_qubits < 10: num_left = n_qubits num_right = 0 else: num_left = math.ceil(n_qubits / 2) num_right = n_qubits - num_left x_max = max([d[1] for d in grid_data]) y_max = max([d[0] for d in grid_data]) max_dim = max(x_max, y_max) qubit_size = 32 font_size = 14 offset = 0 if cmap: if y_max / max_dim < 0.33: qubit_size = 24 font_size = 10 offset = 1 if n_qubits > 5: right_meas_title = "Readout Error (%)" else: right_meas_title = None if cmap and cx_idx.size > 0: cx_title = "CNOT Error Rate [Avg. {}%]".format(np.round(avg_cx_err, 3)) else: cx_title = None fig = make_subplots(rows=2, cols=11, row_heights=[0.95, 0.05], vertical_spacing=0.15, specs=[[{"colspan": 2}, None, {"colspan": 6}, None, None, None, None, None, {"colspan": 2}, None, None], [{"colspan": 4}, None, None, None, None, None, {"colspan": 4}, None, None, None, None]], subplot_titles=("Readout Error (%)", None, right_meas_title, "Hadamard Error Rate [Avg. {}%]".format( np.round(avg_1q_err, 3)), cx_title) ) # Add lines for couplings if cmap and n_qubits > 1 and cx_idx.size > 0: for ind, edge in enumerate(cmap): is_symmetric = False if edge[::-1] in cmap: is_symmetric = True y_start = grid_data[edge[0]][0] + offset x_start = grid_data[edge[0]][1] y_end = grid_data[edge[1]][0] + offset x_end = grid_data[edge[1]][1] if is_symmetric: if y_start == y_end: x_end = (x_end - x_start) / 2 + x_start x_mid = x_end y_mid = y_start elif x_start == x_end: y_end = (y_end - y_start) / 2 + y_start x_mid = x_start y_mid = y_end else: x_end = (x_end - x_start) / 2 + x_start y_end = (y_end - y_start) / 2 + y_start x_mid = x_end y_mid = y_end else: if y_start == y_end: x_mid = (x_end - x_start) / 2 + x_start y_mid = y_end elif x_start == x_end: x_mid = x_end y_mid = (y_end - y_start) / 2 + y_start else: x_mid = (x_end - x_start) / 2 + x_start y_mid = (y_end - y_start) / 2 + y_start fig.add_trace( go.Scatter(x=[x_start, x_mid, x_end], y=[-y_start, -y_mid, -y_end], mode="lines", line=dict(width=6, color=line_colors[ind]), hoverinfo='text', hovertext='CX<sub>err</sub>{B}_{A} = {err} %'.format( A=edge[0], B=edge[1], err=np.round(cx_errors[ind], 3)) ), row=1, col=3) # Add the qubits themselves qubit_text = [] qubit_str = "<b>Qubit {}</b><br>H<sub>err</sub> = {} %" qubit_str += "<br>T1 = {} \u03BCs<br>T2 = {} \u03BCs" for kk in range(n_qubits): qubit_text.append(qubit_str.format(kk, np.round(single_gate_errors[kk], 3), np.round(t1s[kk], 2), np.round(t2s[kk], 2))) if n_qubits > 20: qubit_size = 23 font_size = 11 if n_qubits > 50: qubit_size = 20 font_size = 9 qtext_color = [] for ii in range(n_qubits): if background_color == 'black': if single_gate_errors[ii] > 0.8*max_1q_err: qtext_color.append('black') else: qtext_color.append('white') else: qtext_color.append('white') fig.add_trace(go.Scatter( x=[d[1] for d in grid_data], y=[-d[0]-offset for d in grid_data], mode="markers+text", marker=go.scatter.Marker(size=qubit_size, color=q_colors, opacity=1), text=[str(ii) for ii in range(n_qubits)], textposition="middle center", textfont=dict(size=font_size, color=qtext_color), hoverinfo="text", hovertext=qubit_text), row=1, col=3) fig.update_xaxes(row=1, col=3, visible=False) _range = None if offset: _range = [-3.5, 0.5] fig.update_yaxes(row=1, col=3, visible=False, range=_range) # H error rate colorbar min_1q_err = min(single_gate_errors) max_1q_err = max(single_gate_errors) if n_qubits > 1: fig.add_trace(go.Heatmap(z=[np.linspace(min_1q_err, max_1q_err, 100), np.linspace(min_1q_err, max_1q_err, 100)], colorscale=plotly_cmap, showscale=False, hoverinfo='none'), row=2, col=1) fig.update_yaxes(row=2, col=1, visible=False) fig.update_xaxes(row=2, col=1, tickvals=[0, 49, 99], ticktext=[np.round(min_1q_err, 3), np.round((max_1q_err-min_1q_err)/2+min_1q_err, 3), np.round(max_1q_err, 3)]) # CX error rate colorbar if cmap and n_qubits > 1 and cx_idx.size > 0: min_cx_err = min(cx_errors) max_cx_err = max(cx_errors) if min_cx_err == max_cx_err: min_cx_err = 0 # Force more than 1 color. fig.add_trace(go.Heatmap(z=[np.linspace(min_cx_err, max_cx_err, 100), np.linspace(min_cx_err, max_cx_err, 100)], colorscale=plotly_cmap, showscale=False, hoverinfo='none'), row=2, col=7) fig.update_yaxes(row=2, col=7, visible=False) min_cx_idx_err = min(cx_errors[cx_idx]) max_cx_idx_err = max(cx_errors[cx_idx]) fig.update_xaxes(row=2, col=7, tickvals=[0, 49, 99], ticktext=[np.round(min_cx_idx_err, 3), np.round((max_cx_idx_err-min_cx_idx_err)/2+min_cx_idx_err, 3), np.round(max_cx_idx_err, 3)]) hover_text = "<b>Qubit {}</b><br>M<sub>err</sub> = {} %" # Add the left side meas errors for kk in range(num_left-1, -1, -1): fig.add_trace(go.Bar(x=[read_err[kk]], y=[kk], orientation='h', marker=dict(color='#eedccb'), hoverinfo="text", hoverlabel=dict(font=dict(color=meas_text_color)), hovertext=[hover_text.format(kk, np.round(read_err[kk], 3) )] ), row=1, col=1) fig.add_trace(go.Scatter(x=[avg_read_err, avg_read_err], y=[-0.25, num_left-1+0.25], mode='lines', hoverinfo='none', line=dict(color=text_color, width=2, dash='dot')), row=1, col=1) fig.update_yaxes(row=1, col=1, tickvals=list(range(num_left)), autorange="reversed") fig.update_xaxes(row=1, col=1, range=[0, 1.1*max_read_err], tickvals=[0, np.round(avg_read_err, 2), np.round(max_read_err, 2)], showline=True, linewidth=1, linecolor=text_color, tickcolor=text_color, ticks="outside", showgrid=False, zeroline=False) # Add the right side meas errors, if any if num_right: for kk in range(n_qubits-1, num_left-1, -1): fig.add_trace(go.Bar(x=[-read_err[kk]], y=[kk], orientation='h', marker=dict(color='#eedccb'), hoverinfo="text", hoverlabel=dict(font=dict(color=meas_text_color)), hovertext=[hover_text.format(kk, np.round(read_err[kk], 3))] ), row=1, col=9) fig.add_trace(go.Scatter(x=[-avg_read_err, -avg_read_err], y=[num_left-0.25, n_qubits-1+0.25], mode='lines', hoverinfo='none', line=dict(color=text_color, width=2, dash='dot') ), row=1, col=9) fig.update_yaxes(row=1, col=9, tickvals=list(range(n_qubits-1, num_left-1, -1)), side='right', autorange="reversed", ) fig.update_xaxes(row=1, col=9, range=[-1.1*max_read_err, 0], tickvals=[0, -np.round(avg_read_err, 2), -np.round(max_read_err, 2)], ticktext=[0, np.round(avg_read_err, 2), np.round(max_read_err, 2)], showline=True, linewidth=1, linecolor=text_color, tickcolor=text_color, ticks="outside", showgrid=False, zeroline=False) # Makes the subplot titles smaller than the 16pt default for ann in fig['layout']['annotations']: ann['font'] = dict(size=13) title_text = "{} Error Map".format(backend.name()) if show_title else '' fig.update_layout(showlegend=False, plot_bgcolor=background_color, paper_bgcolor=background_color, width=figsize[0], height=figsize[1], title=dict(text=title_text, x=0.452), title_font_size=20, font=dict(color=text_color), margin=dict(t=60, l=0, r=40, b=0) ) if as_widget: return PlotlyWidget(fig) return PlotlyFigure(fig)
https://github.com/QuSTaR/kaleidoscope
QuSTaR
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """A module for visualizing device coupling maps.""" import math from typing import List import numpy as np from qiskit.exceptions import MissingOptionalLibraryError, QiskitError from qiskit.providers.backend import BackendV2 from qiskit.tools.visualization import HAS_MATPLOTLIB, VisualizationError from qiskit.visualization.utils import matplotlib_close_if_inline def plot_gate_map( backend, figsize=None, plot_directed=False, label_qubits=True, qubit_size=None, line_width=4, font_size=None, qubit_color=None, qubit_labels=None, line_color=None, font_color="w", ax=None, filename=None, qubit_coordinates=None, ): """Plots the gate map of a device. Args: backend (BaseBackend): The backend instance that will be used to plot the device gate map. figsize (tuple): Output figure size (wxh) in inches. plot_directed (bool): Plot directed coupling map. label_qubits (bool): Label the qubits. qubit_size (float): Size of qubit marker. line_width (float): Width of lines. font_size (int): Font size of qubit labels. qubit_color (list): A list of colors for the qubits qubit_labels (list): A list of qubit labels line_color (list): A list of colors for each line from coupling_map. font_color (str): The font color for the qubit labels. ax (Axes): A Matplotlib axes instance. filename (str): file path to save image to. Returns: Figure: A Matplotlib figure instance. Raises: QiskitError: if tried to pass a simulator, or if the backend is None, but one of num_qubits, mpl_data, or cmap is None. MissingOptionalLibraryError: if matplotlib not installed. Example: .. jupyter-execute:: :hide-code: :hide-output: from qiskit.test.ibmq_mock import mock_get_backend mock_get_backend('FakeVigo') .. jupyter-execute:: from qiskit import QuantumCircuit, execute, IBMQ from qiskit.visualization import plot_gate_map %matplotlib inline provider = IBMQ.load_account() accountProvider = IBMQ.get_provider(hub='ibm-q') backend = accountProvider.get_backend('ibmq_vigo') plot_gate_map(backend) """ if not HAS_MATPLOTLIB: raise MissingOptionalLibraryError( libname="Matplotlib", name="plot_gate_map", pip_install="pip install matplotlib", ) if isinstance(backend, BackendV2): pass elif backend.configuration().simulator: raise QiskitError("Requires a device backend, not simulator.") qubit_coordinates_map = {} qubit_coordinates_map[1] = [[0, 0]] qubit_coordinates_map[5] = [[1, 0], [0, 1], [1, 1], [1, 2], [2, 1]] qubit_coordinates_map[7] = [[0, 0], [0, 1], [0, 2], [1, 1], [2, 0], [2, 1], [2, 2]] qubit_coordinates_map[20] = [ [0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [1, 0], [1, 1], [1, 2], [1, 3], [1, 4], [2, 0], [2, 1], [2, 2], [2, 3], [2, 4], [3, 0], [3, 1], [3, 2], [3, 3], [3, 4], ] qubit_coordinates_map[15] = [ [0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [0, 5], [0, 6], [1, 7], [1, 6], [1, 5], [1, 4], [1, 3], [1, 2], [1, 1], [1, 0], ] qubit_coordinates_map[16] = [ [1, 0], [1, 1], [2, 1], [3, 1], [1, 2], [3, 2], [0, 3], [1, 3], [3, 3], [4, 3], [1, 4], [3, 4], [1, 5], [2, 5], [3, 5], [1, 6], ] qubit_coordinates_map[27] = [ [1, 0], [1, 1], [2, 1], [3, 1], [1, 2], [3, 2], [0, 3], [1, 3], [3, 3], [4, 3], [1, 4], [3, 4], [1, 5], [2, 5], [3, 5], [1, 6], [3, 6], [0, 7], [1, 7], [3, 7], [4, 7], [1, 8], [3, 8], [1, 9], [2, 9], [3, 9], [3, 10], ] qubit_coordinates_map[28] = [ [0, 2], [0, 3], [0, 4], [0, 5], [0, 6], [1, 2], [1, 6], [2, 0], [2, 1], [2, 2], [2, 3], [2, 4], [2, 5], [2, 6], [2, 7], [2, 8], [3, 0], [3, 4], [3, 8], [4, 0], [4, 1], [4, 2], [4, 3], [4, 4], [4, 5], [4, 6], [4, 7], [4, 8], ] qubit_coordinates_map[53] = [ [0, 2], [0, 3], [0, 4], [0, 5], [0, 6], [1, 2], [1, 6], [2, 0], [2, 1], [2, 2], [2, 3], [2, 4], [2, 5], [2, 6], [2, 7], [2, 8], [3, 0], [3, 4], [3, 8], [4, 0], [4, 1], [4, 2], [4, 3], [4, 4], [4, 5], [4, 6], [4, 7], [4, 8], [5, 2], [5, 6], [6, 0], [6, 1], [6, 2], [6, 3], [6, 4], [6, 5], [6, 6], [6, 7], [6, 8], [7, 0], [7, 4], [7, 8], [8, 0], [8, 1], [8, 2], [8, 3], [8, 4], [8, 5], [8, 6], [8, 7], [8, 8], [9, 2], [9, 6], ] qubit_coordinates_map[65] = [ [0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [0, 5], [0, 6], [0, 7], [0, 8], [0, 9], [1, 0], [1, 4], [1, 8], [2, 0], [2, 1], [2, 2], [2, 3], [2, 4], [2, 5], [2, 6], [2, 7], [2, 8], [2, 9], [2, 10], [3, 2], [3, 6], [3, 10], [4, 0], [4, 1], [4, 2], [4, 3], [4, 4], [4, 5], [4, 6], [4, 7], [4, 8], [4, 9], [4, 10], [5, 0], [5, 4], [5, 8], [6, 0], [6, 1], [6, 2], [6, 3], [6, 4], [6, 5], [6, 6], [6, 7], [6, 8], [6, 9], [6, 10], [7, 2], [7, 6], [7, 10], [8, 1], [8, 2], [8, 3], [8, 4], [8, 5], [8, 6], [8, 7], [8, 8], [8, 9], [8, 10], ] if isinstance(backend, BackendV2): num_qubits = backend.num_qubits coupling_map = backend.plot_coupling_map else: config = backend.configuration() num_qubits = config.n_qubits coupling_map = config.coupling_map # don't reference dictionary if provided as a parameter if qubit_coordinates is None: qubit_coordinates = qubit_coordinates_map.get(num_qubits) # try to adjust num_qubits to match the next highest hardcoded grid size if qubit_coordinates is None: if any([num_qubits < key for key in qubit_coordinates_map.keys()]): num_qubits_roundup = max(qubit_coordinates_map.keys()) for key in qubit_coordinates_map.keys(): if key < num_qubits_roundup and key > num_qubits: num_qubits_roundup = key qubit_coordinates = qubit_coordinates_map.get(num_qubits_roundup) return plot_coupling_map( num_qubits, qubit_coordinates, coupling_map, figsize, plot_directed, label_qubits, qubit_size, line_width, font_size, qubit_color, qubit_labels, line_color, font_color, ax, filename, ) def plot_coupling_map( num_qubits: int, qubit_coordinates: List[List[int]], coupling_map: List[List[int]], figsize=None, plot_directed=False, label_qubits=True, qubit_size=None, line_width=4, font_size=None, qubit_color=None, qubit_labels=None, line_color=None, font_color="w", ax=None, filename=None, ): """Plots an arbitrary coupling map of qubits (embedded in a plane). Args: num_qubits (int): The number of qubits defined and plotted. qubit_coordinates (List[List[int]]): A list of two-element lists, with entries of each nested list being the planar coordinates in a 0-based square grid where each qubit is located. coupling_map (List[List[int]]): A list of two-element lists, with entries of each nested list being the qubit numbers of the bonds to be plotted. figsize (tuple): Output figure size (wxh) in inches. plot_directed (bool): Plot directed coupling map. label_qubits (bool): Label the qubits. qubit_size (float): Size of qubit marker. line_width (float): Width of lines. font_size (int): Font size of qubit labels. qubit_color (list): A list of colors for the qubits qubit_labels (list): A list of qubit labels line_color (list): A list of colors for each line from coupling_map. font_color (str): The font color for the qubit labels. ax (Axes): A Matplotlib axes instance. filename (str): file path to save image to. Returns: Figure: A Matplotlib figure instance. Raises: MissingOptionalLibraryError: if matplotlib not installed. QiskitError: If length of qubit labels does not match number of qubits. Example: .. jupyter-execute:: from qiskit.visualization import plot_coupling_map %matplotlib inline num_qubits = 8 coupling_map = [[0, 1], [1, 2], [2, 3], [3, 5], [4, 5], [5, 6], [2, 4], [6, 7]] qubit_coordinates = [[0, 1], [1, 1], [1, 0], [1, 2], [2, 0], [2, 2], [2, 1], [3, 1]] plot_coupling_map(num_qubits, coupling_map, qubit_coordinates) """ if not HAS_MATPLOTLIB: raise MissingOptionalLibraryError( libname="Matplotlib", name="plot_coupling_map", pip_install="pip install matplotlib", ) import matplotlib.patches as mpatches import matplotlib.pyplot as plt input_axes = False if ax: input_axes = True if font_size is None: font_size = 12 if qubit_size is None: qubit_size = 24 if num_qubits > 20: qubit_size = 28 font_size = 10 if qubit_labels is None: qubit_labels = list(range(num_qubits)) else: if len(qubit_labels) != num_qubits: raise QiskitError("Length of qubit labels does not equal number of qubits.") if qubit_coordinates is not None: grid_data = qubit_coordinates else: if not input_axes: fig, ax = plt.subplots(figsize=(5, 5)) ax.axis("off") if filename: fig.savefig(filename) return fig x_max = max(d[1] for d in grid_data) y_max = max(d[0] for d in grid_data) max_dim = max(x_max, y_max) if figsize is None: if num_qubits == 1 or (x_max / max_dim > 0.33 and y_max / max_dim > 0.33): figsize = (5, 5) else: figsize = (9, 3) if ax is None: fig, ax = plt.subplots(figsize=figsize) ax.axis("off") # set coloring if qubit_color is None: qubit_color = ["#648fff"] * num_qubits if line_color is None: line_color = ["#648fff"] * len(coupling_map) if coupling_map else [] # Add lines for couplings if num_qubits != 1: for ind, edge in enumerate(coupling_map): is_symmetric = False if edge[::-1] in coupling_map: is_symmetric = True y_start = grid_data[edge[0]][0] x_start = grid_data[edge[0]][1] y_end = grid_data[edge[1]][0] x_end = grid_data[edge[1]][1] if is_symmetric: if y_start == y_end: x_end = (x_end - x_start) / 2 + x_start elif x_start == x_end: y_end = (y_end - y_start) / 2 + y_start else: x_end = (x_end - x_start) / 2 + x_start y_end = (y_end - y_start) / 2 + y_start ax.add_artist( plt.Line2D( [x_start, x_end], [-y_start, -y_end], color=line_color[ind], linewidth=line_width, zorder=0, ) ) if plot_directed: dx = x_end - x_start dy = y_end - y_start if is_symmetric: x_arrow = x_start + dx * 0.95 y_arrow = -y_start - dy * 0.95 dx_arrow = dx * 0.01 dy_arrow = -dy * 0.01 head_width = 0.15 else: x_arrow = x_start + dx * 0.5 y_arrow = -y_start - dy * 0.5 dx_arrow = dx * 0.2 dy_arrow = -dy * 0.2 head_width = 0.2 ax.add_patch( mpatches.FancyArrow( x_arrow, y_arrow, dx_arrow, dy_arrow, head_width=head_width, length_includes_head=True, edgecolor=None, linewidth=0, facecolor=line_color[ind], zorder=1, ) ) # Add circles for qubits for var, idx in enumerate(grid_data): # add check if num_qubits had been rounded up if var >= num_qubits: break _idx = [idx[1], -idx[0]] ax.add_artist( mpatches.Ellipse( _idx, qubit_size / 48, qubit_size / 48, # This is here so that the changes color=qubit_color[var], zorder=1, ) ) # to how qubits are plotted does if label_qubits: # not affect qubit size kwarg. ax.text( *_idx, s=qubit_labels[var], horizontalalignment="center", verticalalignment="center", color=font_color, size=font_size, weight="bold", ) ax.set_xlim([-1, x_max + 1]) ax.set_ylim([-(y_max + 1), 1]) ax.set_aspect("equal") if not input_axes: matplotlib_close_if_inline(fig) if filename: fig.savefig(filename) return fig return None def plot_circuit_layout(circuit, backend, view="virtual", qubit_coordinates=None): """Plot the layout of a circuit transpiled for a given target backend. Args: circuit (QuantumCircuit): Input quantum circuit. backend (BaseBackend): Target backend. view (str): Layout view: either 'virtual' or 'physical'. Returns: Figure: A matplotlib figure showing layout. Raises: QiskitError: Invalid view type given. VisualizationError: Circuit has no layout attribute. Example: .. jupyter-execute:: :hide-code: :hide-output: from qiskit.test.ibmq_mock import mock_get_backend mock_get_backend('FakeVigo') .. jupyter-execute:: import numpy as np from qiskit import QuantumCircuit, IBMQ, transpile from qiskit.visualization import plot_histogram, plot_gate_map, plot_circuit_layout from qiskit.tools.monitor import job_monitor import matplotlib.pyplot as plt %matplotlib inline IBMQ.load_account() ghz = QuantumCircuit(3, 3) ghz.h(0) for idx in range(1,3): ghz.cx(0,idx) ghz.measure(range(3), range(3)) provider = IBMQ.get_provider(hub='ibm-q') backend = provider.get_backend('ibmq_vigo') new_circ_lv3 = transpile(ghz, backend=backend, optimization_level=3) plot_circuit_layout(new_circ_lv3, backend) """ if circuit._layout is None: raise QiskitError("Circuit has no layout. Perhaps it has not been transpiled.") if isinstance(backend, BackendV2): num_qubits = backend.num_qubits else: num_qubits = backend.configuration().n_qubits qubits = [] qubit_labels = [None] * num_qubits bit_locations = { bit: {"register": register, "index": index} for register in circuit._layout.get_registers() for index, bit in enumerate(register) } for index, qubit in enumerate(circuit._layout.get_virtual_bits()): if qubit not in bit_locations: bit_locations[qubit] = {"register": None, "index": index} if view == "virtual": for key, val in circuit._layout.get_virtual_bits().items(): bit_register = bit_locations[key]["register"] if bit_register is None or bit_register.name != "ancilla": qubits.append(val) qubit_labels[val] = bit_locations[key]["index"] elif view == "physical": for key, val in circuit._layout.get_physical_bits().items(): bit_register = bit_locations[val]["register"] if bit_register is None or bit_register.name != "ancilla": qubits.append(key) qubit_labels[key] = key else: raise VisualizationError("Layout view must be 'virtual' or 'physical'.") qcolors = ["#648fff"] * num_qubits for k in qubits: qcolors[k] = "k" if isinstance(backend, BackendV2): cmap = backend.plot_coupling_map else: cmap = backend.configuration().coupling_map lcolors = ["#648fff"] * len(cmap) for idx, edge in enumerate(cmap): if edge[0] in qubits and edge[1] in qubits: lcolors[idx] = "k" fig = plot_gate_map( backend, qubit_color=qcolors, qubit_labels=qubit_labels, line_color=lcolors, qubit_coordinates=qubit_coordinates, ) return fig def plot_error_map(backend, figsize=(12, 9), show_title=True): """Plots the error map of a given backend. Args: backend (IBMQBackend): Given backend. figsize (tuple): Figure size in inches. show_title (bool): Show the title or not. Returns: Figure: A matplotlib figure showing error map. Raises: VisualizationError: Input is not IBMQ backend. VisualizationError: The backend does not provide gate errors for the 'sx' gate. MissingOptionalLibraryError: If seaborn is not installed Example: .. jupyter-execute:: :hide-code: :hide-output: from qiskit.test.ibmq_mock import mock_get_backend mock_get_backend('FakeVigo') .. jupyter-execute:: from qiskit import QuantumCircuit, execute, IBMQ from qiskit.visualization import plot_error_map %matplotlib inline IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') backend = provider.get_backend('ibmq_vigo') plot_error_map(backend) """ try: import seaborn as sns except ImportError as ex: raise MissingOptionalLibraryError( libname="seaborn", name="plot_error_map", pip_install="pip install seaborn", ) from ex if not HAS_MATPLOTLIB: raise MissingOptionalLibraryError( libname="Matplotlib", name="plot_error_map", pip_install="pip install matplotlib", ) import matplotlib import matplotlib.pyplot as plt from matplotlib import gridspec, ticker color_map = sns.cubehelix_palette(reverse=True, as_cmap=True) props = backend.properties().to_dict() config = backend.configuration().to_dict() num_qubits = config["n_qubits"] # sx error rates single_gate_errors = [0] * num_qubits for gate in props["gates"]: if gate["gate"] == "sx": _qubit = gate["qubits"][0] for param in gate["parameters"]: if param["name"] == "gate_error": single_gate_errors[_qubit] = param["value"] break else: raise VisualizationError( f"Backend '{backend}' did not supply an error for the 'sx' gate." ) # Convert to percent single_gate_errors = 100 * np.asarray(single_gate_errors) avg_1q_err = np.mean(single_gate_errors) single_norm = matplotlib.colors.Normalize( vmin=min(single_gate_errors), vmax=max(single_gate_errors) ) q_colors = [color_map(single_norm(err)) for err in single_gate_errors] cmap = config["coupling_map"] directed = False line_colors = [] if cmap: directed = False if num_qubits < 20: for edge in cmap: if [edge[1], edge[0]] not in cmap: directed = True break cx_errors = [] for line in cmap: for item in props["gates"]: if item["qubits"] == line: cx_errors.append(item["parameters"][0]["value"]) break else: continue # Convert to percent cx_errors = 100 * np.asarray(cx_errors) avg_cx_err = np.mean(cx_errors) cx_norm = matplotlib.colors.Normalize(vmin=min(cx_errors), vmax=max(cx_errors)) line_colors = [color_map(cx_norm(err)) for err in cx_errors] # Measurement errors read_err = [] for qubit in range(num_qubits): for item in props["qubits"][qubit]: if item["name"] == "readout_error": read_err.append(item["value"]) read_err = 100 * np.asarray(read_err) avg_read_err = np.mean(read_err) max_read_err = np.max(read_err) fig = plt.figure(figsize=figsize) gridspec.GridSpec(nrows=2, ncols=3) grid_spec = gridspec.GridSpec( 12, 12, height_ratios=[1] * 11 + [0.5], width_ratios=[2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2], ) left_ax = plt.subplot(grid_spec[2:10, :1]) main_ax = plt.subplot(grid_spec[:11, 1:11]) right_ax = plt.subplot(grid_spec[2:10, 11:]) bleft_ax = plt.subplot(grid_spec[-1, :5]) if cmap: bright_ax = plt.subplot(grid_spec[-1, 7:]) qubit_size = 28 if num_qubits <= 5: qubit_size = 20 plot_gate_map( backend, qubit_color=q_colors, line_color=line_colors, qubit_size=qubit_size, line_width=5, plot_directed=directed, ax=main_ax, ) main_ax.axis("off") main_ax.set_aspect(1) if cmap: single_cb = matplotlib.colorbar.ColorbarBase( bleft_ax, cmap=color_map, norm=single_norm, orientation="horizontal" ) tick_locator = ticker.MaxNLocator(nbins=5) single_cb.locator = tick_locator single_cb.update_ticks() single_cb.update_ticks() bleft_ax.set_title(f"H error rate (%) [Avg. = {round(avg_1q_err, 3)}]") if cmap is None: bleft_ax.axis("off") bleft_ax.set_title(f"H error rate (%) = {round(avg_1q_err, 3)}") if cmap: cx_cb = matplotlib.colorbar.ColorbarBase( bright_ax, cmap=color_map, norm=cx_norm, orientation="horizontal" ) tick_locator = ticker.MaxNLocator(nbins=5) cx_cb.locator = tick_locator cx_cb.update_ticks() bright_ax.set_title(f"CNOT error rate (%) [Avg. = {round(avg_cx_err, 3)}]") if num_qubits < 10: num_left = num_qubits num_right = 0 else: num_left = math.ceil(num_qubits / 2) num_right = num_qubits - num_left left_ax.barh(range(num_left), read_err[:num_left], align="center", color="#DDBBBA") left_ax.axvline(avg_read_err, linestyle="--", color="#212121") left_ax.set_yticks(range(num_left)) left_ax.set_xticks([0, round(avg_read_err, 2), round(max_read_err, 2)]) left_ax.set_yticklabels([str(kk) for kk in range(num_left)], fontsize=12) left_ax.invert_yaxis() left_ax.set_title("Readout Error (%)", fontsize=12) for spine in left_ax.spines.values(): spine.set_visible(False) if num_right: right_ax.barh( range(num_left, num_qubits), read_err[num_left:], align="center", color="#DDBBBA", ) right_ax.axvline(avg_read_err, linestyle="--", color="#212121") right_ax.set_yticks(range(num_left, num_qubits)) right_ax.set_xticks([0, round(avg_read_err, 2), round(max_read_err, 2)]) right_ax.set_yticklabels( [str(kk) for kk in range(num_left, num_qubits)], fontsize=12 ) right_ax.invert_yaxis() right_ax.invert_xaxis() right_ax.yaxis.set_label_position("right") right_ax.yaxis.tick_right() right_ax.set_title("Readout Error (%)", fontsize=12) else: right_ax.axis("off") for spine in right_ax.spines.values(): spine.set_visible(False) if show_title: fig.suptitle(f"{backend.name()} Error Map", fontsize=24, y=0.9) matplotlib_close_if_inline(fig) return fig
https://github.com/QuSTaR/kaleidoscope
QuSTaR
# -*- coding: utf-8 -*- # This file is part of Kaleidoscope. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=invalid-unary-operand-type, consider-using-generator """CNOT error density plot""" import numpy as np from scipy.stats import gaussian_kde import matplotlib as mpl import matplotlib.pyplot as plt from qiskit.providers.models.backendproperties import BackendProperties from kaleidoscope.colors import COLORS1, COLORS2, COLORS3, COLORS4, COLORS5, COLORS14 from kaleidoscope.errors import KaleidoscopeError from kaleidoscope.qiskit.backends.pseudobackend import properties_to_pseudobackend def cnot_error_density(backends, figsize=None, colors=None, offset=None, scale='log', covariance_factor=0.1, xlim=None, text_xval=None, xticks=None): """Plot CNOT error distribution for one or more IBMQ backends. Parameters: backends (list or IBMQBackend or BackendProperties): A single or ist of IBMQBackend instances or properties. figsize (tuple): Optional figure size in inches. colors (list): A list of Matplotlib compatible colors to plot with. offset (float): Positive offset for spacing out the backends. scale (str): 'linear' or 'log' scaling of x-axis. covariance_factor (float): Sets the width of the gaussian for each point. xlim (list or tuple): Optional lower and upper limits of cnot error values. text_xval (float): Optional xaxis value at which to start the backend text. xticks (list): Optional list of xaxis ticks to plot. Returns: Figure: A matplotlib Figure instance. Raises: KaleidoscopeError: A backend with < 2 qubits was passed. KaleidoscopeError: Number of colors did not match number of backends. Example: .. jupyter-execute:: from qiskit import * from kaleidoscope.qiskit.backends import cnot_error_density provider = IBMQ.load_account() backends = [] backends.append(provider.backends.ibmq_vigo) backends.append(provider.backends.ibmq_ourense) backends.append(provider.backends.ibmq_valencia) backends.append(provider.backends.ibmq_santiago) cnot_error_density(backends) """ if not isinstance(backends, list): backends = [backends] for idx, back in enumerate(backends): if isinstance(back, BackendProperties): backends[idx] = properties_to_pseudobackend(back) for back in backends: if back.configuration().n_qubits < 2: raise KaleidoscopeError('Number of backend qubits must be > 1') if scale not in ['linear', 'log']: raise KaleidoscopeError("scale must be 'linear' or 'log'.") # Attempt to autosize if figsize=None if figsize is None: if len(backends) > 1: fig = plt.figure(figsize=(12, len(backends)*1.5)) else: fig = plt.figure(figsize=(12, 2)) else: fig = plt.figure(figsize=figsize) text_color = 'k' if offset is None: offset = 100 if len(backends) > 3 else 200 offset = -offset if colors is None: if len(backends) == 1: colors = COLORS1 elif len(backends) == 2: colors = COLORS2 elif len(backends) == 3: colors = COLORS3 elif len(backends) == 4: colors = COLORS4 elif len(backends) == 5: colors = COLORS5 else: colors = [COLORS14[kk % 14] for kk in range(len(backends))] else: if len(colors) != len(backends): raise KaleidoscopeError('Number of colors does not match number of backends.') cx_errors = [] for idx, back in enumerate(backends): back_props = back.properties().to_dict() cx_errs = [] meas_errs = [] for gate in back_props['gates']: if len(gate['qubits']) == 2: # Ignore cx gates with values of 1.0 if gate['parameters'][0]['value'] != 1.0: cx_errs.append(gate['parameters'][0]['value']) for qubit in back_props['qubits']: for item in qubit: if item['name'] == 'readout_error': meas_errs.append(item['value']) cx_errors.append(100*np.asarray(cx_errs)) max_cx_err = max([cerr.max() for cerr in cx_errors]) min_cx_err = min([cerr.min() for cerr in cx_errors]) if xlim is None: if scale == 'linear': xlim = [0, 1.5*max_cx_err] else: xlim = [10**np.floor(np.log10(min_cx_err)), 10**np.ceil(np.log10(max_cx_err))] if text_xval is None: if scale == 'linear': text_xval = 0.8*xlim[1] else: text_xval = 0.6*xlim[1] for idx, back in enumerate(backends): cx_density = gaussian_kde(cx_errors[idx]) xs = np.linspace(xlim[0], xlim[1], 2500) cx_density.covariance_factor = lambda: covariance_factor cx_density._compute_covariance() if scale == 'linear': plt.plot(xs, 100*cx_density(xs)+offset*idx, zorder=idx, color=colors[idx]) else: plt.semilogx(xs, 100*cx_density(xs)+offset*idx, zorder=idx, color=colors[idx]) plt.fill_between(xs, offset*idx, 100*cx_density(xs)+offset*idx, zorder=idx, color=colors[idx]) qv_val = back.configuration().quantum_volume if qv_val: qv = "(QV"+str(qv_val)+")" else: qv = '' bname = back.name().split('_')[-1].title()+" {}".format(qv) plt.text(text_xval, offset*idx+0.2*(-offset), bname, fontsize=20, color=colors[idx]) fig.axes[0].get_yaxis().set_visible(False) # get rid of the frame for spine in plt.gca().spines.values(): spine.set_visible(False) if xticks is None: if scale == 'linear': xticks = np.round(np.linspace(xlim[0], xlim[1], 4), 2) else: xticks = np.asarray(xticks) if xticks is not None: plt.xticks(np.floor(xticks), labels=np.floor(xticks), color=text_color) plt.xticks(fontsize=18) plt.xlim(xlim) plt.tick_params(axis='x', colors=text_color) plt.xlabel('Gate Error', fontsize=18, color=text_color) plt.title('CNOT Error Distributions', fontsize=18, color=text_color) fig.tight_layout() if mpl.get_backend() in ["module://ipykernel.pylab.backend_inline", "module://matplotlib_inline.backend_inline", "nbAgg"]: plt.close(fig) return fig
https://github.com/QuSTaR/kaleidoscope
QuSTaR
# -*- coding: utf-8 -*- # This code is part of Kaleidoscope. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for Bloch routines""" import pytest from qiskit import QuantumCircuit from qiskit. quantum_info import DensityMatrix, partial_trace from kaleidoscope import qsphere from kaleidoscope.errors import KaleidoscopeError def test_qsphere_bad_dm_input(): """Tests the qsphere raises when passed impure dm""" qc = QuantumCircuit(3) qc.h(0) qc.cx(0, 1) qc.cx(1, 2) dm = DensityMatrix.from_instruction(qc) pdm = partial_trace(dm, [0, 1]) with pytest.raises(KaleidoscopeError): assert qsphere(pdm)
https://github.com/QuSTaR/kaleidoscope
QuSTaR
# -*- coding: utf-8 -*- # This code is part of Kaleidoscope. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=unused-import """Tests for Bloch routines""" from qiskit import IBMQ, QuantumCircuit import kaleidoscope.qiskit PROVIDER = IBMQ.load_account() backend = PROVIDER.backends.ibmq_vigo def test_target_backend_attach(): """Tests attaching target backend""" qc = QuantumCircuit(5, 5) >> backend qc.h(0) qc.cx(0, range(1, 5)) qc.measure(range(5), range(5)) assert qc.target_backend == backend def test_target_backend_transpile(): """Tests target backend attached to transpiled circuit""" qc = QuantumCircuit(5, 5) >> backend qc.h(0) qc.cx(0, range(1, 5)) qc.measure(range(5), range(5)) new_qc = qc.transpile() assert new_qc.target_backend == backend
https://github.com/kdk/qiskit-timeline-debugger
kdk
#initialization import matplotlib.pyplot as plt import numpy as np # importing Qiskit from qiskit import IBMQ, Aer, assemble, transpile from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit.providers.ibmq import least_busy # import basic plot tools from qiskit.visualization import plot_histogram n = 2 grover_circuit = QuantumCircuit(n) def initialize_s(qc, qubits): """Apply a H-gate to 'qubits' in qc""" for q in qubits: qc.h(q) return qc def diffuser(nqubits): qc = QuantumCircuit(nqubits) # Apply transformation |s> -> |00..0> (H-gates) for qubit in range(nqubits): qc.h(qubit) # Apply transformation |00..0> -> |11..1> (X-gates) for qubit in range(nqubits): qc.x(qubit) # Do multi-controlled-Z gate qc.h(nqubits-1) qc.mct(list(range(nqubits-1)), nqubits-1) # multi-controlled-toffoli qc.h(nqubits-1) # Apply transformation |11..1> -> |00..0> for qubit in range(nqubits): qc.x(qubit) # Apply transformation |00..0> -> |s> for qubit in range(nqubits): qc.h(qubit) # We will return the diffuser as a gate U_s = qc.to_gate() U_s.name = "U$_s$" return U_s grover_circuit = initialize_s(grover_circuit, [0,1]) grover_circuit.draw(output="mpl") grover_circuit.cz(0,1) # Oracle grover_circuit.draw(output="mpl") # Diffusion operator (U_s) grover_circuit.append(diffuser(n),[0,1]) grover_circuit.draw(output="mpl") sim = Aer.get_backend('aer_simulator') # we need to make a copy of the circuit with the 'save_statevector' # instruction to run on the Aer simulator grover_circuit_sim = grover_circuit.copy() grover_circuit_sim.save_statevector() qobj = assemble(grover_circuit_sim) result = sim.run(qobj).result() statevec = result.get_statevector() from qiskit_textbook.tools import vector2latex vector2latex(statevec, pretext="|\\psi\\rangle =") grover_circuit.measure_all() aer_sim = Aer.get_backend('aer_simulator') qobj = assemble(grover_circuit) result = aer_sim.run(qobj).result() counts = result.get_counts() plot_histogram(counts) nqubits = 4 qc = QuantumCircuit(nqubits) # Apply transformation |s> -> |00..0> (H-gates) for qubit in range(nqubits): qc.h(qubit) # Apply transformation |00..0> -> |11..1> (X-gates) for qubit in range(nqubits): qc.x(qubit) qc.barrier() # Do multi-controlled-Z gate qc.h(nqubits-1) qc.mct(list(range(nqubits-1)), nqubits-1) # multi-controlled-toffoli qc.h(nqubits-1) qc.barrier() # Apply transformation |11..1> -> |00..0> for qubit in range(nqubits): qc.x(qubit) # Apply transformation |00..0> -> |s> for qubit in range(nqubits): qc.h(qubit) qc.draw(output="mpl") from qiskit.circuit import classical_function, Int1 # define a classical function f(x): this returns 1 for the solutions of the problem # in this case, the solutions are 1010 and 1100 @classical_function def f(x1: Int1, x2: Int1, x3: Int1, x4: Int1) -> Int1: return (x1 and not x2 and x3 and not x4) or (x1 and x2 and not x3 and not x4) nqubits = 4 Uf = f.synth() # turn it into a circuit oracle = QuantumCircuit(nqubits+1) oracle.compose(Uf, inplace=True) oracle.draw(output="mpl") # We will return the diffuser as a gate #U_f = oracle.to_gate() # U_f.name = "U$_f$" # return U_f
https://github.com/kdk/qiskit-timeline-debugger
kdk
from qiskit import QuantumCircuit, transpile, __qiskit_version__ from qiskit.providers import BaseBackend from qiskit.providers.backend import Backend from qiskit.transpiler.basepasses import AnalysisPass, TransformationPass from typing import Optional, Union import logging import warnings from IPython.display import display from qiskit_trebugger.model import TranspilerLoggingHandler from qiskit_trebugger.model import TranspilerDataCollector from qiskit_trebugger.model import TranspilationSequence from qiskit_trebugger.views.widget.timeline_view import TimelineView from .debugger_error import DebuggerError class Debugger: @classmethod def debug( cls, circuit: QuantumCircuit, backend: Optional[Union[Backend, BaseBackend]] = None, optimization_level: Optional[int] = None, **kwargs ): if not isinstance(circuit, QuantumCircuit): raise DebuggerError( "Debugger currently supports single QuantumCircuit only!" ) # Create the view: view = TimelineView() def on_step_callback(step): view.add_step(step) # Prepare the model: transpilation_sequence = TranspilationSequence(on_step_callback) warnings.simplefilter("ignore") transpilation_sequence.general_info = { "Backend": backend.name(), "optimization_level": optimization_level, "Qiskit version": __qiskit_version__["qiskit"], "Terra version": __qiskit_version__["qiskit-terra"], } transpilation_sequence.original_circuit = circuit warnings.simplefilter("default") Debugger._register_logging_handler(transpilation_sequence) transpiler_callback = Debugger._get_data_collector(transpilation_sequence) # Pass the model to the view: view.transpilation_sequence = transpilation_sequence view.update_params(**kwargs) display(view) transpile( circuit, backend, optimization_level=optimization_level, callback=transpiler_callback, **kwargs ) view.update_summary() view.add_class("done") @classmethod def _register_logging_handler(cls, transpilation_sequence): # TODO: Do not depend on loggerDict all_loggers = logging.Logger.manager.loggerDict passes_loggers = { key: value for (key, value) in all_loggers.items() if key.startswith("qiskit.transpiler.passes.") } loggers_map = {} for _pass in AnalysisPass.__subclasses__(): if _pass.__module__ in passes_loggers.keys(): loggers_map[_pass.__module__] = _pass.__name__ for _pass in TransformationPass.__subclasses__(): if _pass.__module__ in passes_loggers.keys(): loggers_map[_pass.__module__] = _pass.__name__ handler = TranspilerLoggingHandler( transpilation_sequence=transpilation_sequence, loggers_map=loggers_map ) logger = logging.getLogger("qiskit.transpiler.passes") logger.setLevel(logging.DEBUG) logger.addHandler(handler) @classmethod def _get_data_collector(cls, transpilation_sequence): return TranspilerDataCollector(transpilation_sequence).transpiler_callback
https://github.com/kdk/qiskit-timeline-debugger
kdk
from qiskit import QuantumCircuit from qiskit.converters import dag_to_circuit, circuit_to_dag from numpy import zeros, uint16 # make the global DP array LCS_DP = zeros((2000, 2000), dtype=uint16) class CircuitComparator: @staticmethod def get_moments(dag): moments = [l["graph"] for l in list(dag.layers())] return moments @staticmethod def make_LCS(moments1, moments2) -> None: # moments1 : list of lists # m2 : list of lists # clear for the base cases of dp for i in range(2000): LCS_DP[i][0], LCS_DP[0][i] = 0, 0 n, m = len(moments1), len(moments2) for i in range(1, n + 1): for j in range(1, m + 1): # if the layers are isomorphic then okay if moments1[i - 1] == moments2[j - 1]: LCS_DP[i][j] = 1 + LCS_DP[i - 1][j - 1] else: LCS_DP[i][j] = max(LCS_DP[i - 1][j], LCS_DP[i][j - 1]) @staticmethod def compare(prev_circ, curr_circ) -> QuantumCircuit: if prev_circ is None: return (False, curr_circ) # update by reference as there is no qasm now prev_dag = circuit_to_dag(prev_circ) curr_dag = circuit_to_dag(curr_circ) moments1 = CircuitComparator.get_moments(prev_dag) moments2 = CircuitComparator.get_moments(curr_dag) CircuitComparator.make_LCS(moments1, moments2) (n, m) = (len(moments1), len(moments2)) id_set = set() i = n j = m while i > 0 and j > 0: if moments1[i - 1] == moments2[j - 1]: # just want diff for second one id_set.add(j - 1) i -= 1 j -= 1 else: if LCS_DP[i - 1][j] > LCS_DP[i][j - 1]: # means the graph came from the # first circuit , go up i -= 1 else: # if equal or small, go left j -= 1 # if the whole circuit has not changed fully_changed = len(id_set) == 0 if not fully_changed: for id2, l in enumerate(list(curr_dag.layers())): if id2 not in id_set: # this is not an LCS node -> highlight it for node in l["graph"].front_layer(): node.name = node.name + " " return (fully_changed, dag_to_circuit(curr_dag))
https://github.com/kdk/qiskit-timeline-debugger
kdk
from qiskit import QuantumCircuit from qiskit.test.mock import FakeCasablanca from qiskit_trebugger import Debugger import warnings warnings.simplefilter('ignore') debugger = Debugger() backend = FakeCasablanca() circuit = QuantumCircuit(2) circuit.h(0) circuit.cx(0,1) circuit.measure_all() # replace transpile call debugger.debug(circuit, backend = backend, initial_layout = [0,1])
https://github.com/matheusmtta/Quantum-Computing
matheusmtta
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit import IBMQ, BasicAer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.quantum_info import Statevector from qiskit.visualization import plot_state_qsphere from qiskit.visualization import plot_histogram from qiskit.tools.monitor import job_monitor from qiskit.tools.visualization import plot_histogram from IPython.display import display, Math, Latex #define a 1 qubit state |0> sv = Statevector.from_label('0') print('State_0 |x> = ', sv.data) #build a circuit with the H gate mycircuit = QuantumCircuit(1) mycircuit.h(0) #apply the circuit into |x> sv = sv.evolve(mycircuit) print('State_1 H|x> = ', sv.data) mycircuit.draw('mpl') ''' OUR FUNCTION F IS DEFINED AS n = 2 f(0, 0) = 0 f(0, 1) = 1 f(1, 0) = 1 f(1, 1) = 1 ''' #input size n = 2 #initialize qubits and measurement bits input_qubits = QuantumRegister(n+1) output_bits = ClassicalRegister(n) #create circuit my_circuit = QuantumCircuit(input_qubits, output_bits) #apply X on the last qubit my_circuit.x(n) #apply Hadamard on all qubits my_circuit.h(range(n+1)) my_circuit.barrier() #Apply Uf, these CNOT gates will mark the desired |x_i> my_circuit.cx(0, 1) my_circuit.cx(1, 2) my_circuit.cx(0, 1) my_circuit.barrier() #apply Hadamard on all qubits my_circuit.h(range(n+1)) my_circuit.measure(range(n), range(n)) #Backend classical simulation backend = BasicAer.get_backend('qasm_simulator') atp = 1024 res = execute(my_circuit, backend=backend, shots=atp).result() ans = res.get_counts() my_circuit.draw(output='mpl') #Quantum Backend #SOON# plot_histogram(ans) from qiskit import IBMQ IBMQ.load_account() provider = IBMQ.get_provider(group='open', project='main') backend = provider.get_backend('ibmq_vigo') job = execute(my_circuit, backend=backend) result = job.result().get_counts() plot_histogram(result)
https://github.com/matheusmtta/Quantum-Computing
matheusmtta
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, Aer, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * from qiskit.providers.aer import QasmSimulator # Loading your IBM Quantum account(s) provider = IBMQ.load_account() from qiskit.circuit.library.standard_gates import XGate, HGate from operator import * n = 3 N = 8 #2**n index_colour_table = {} colour_hash_map = {} index_colour_table = {'000':"yellow", '001':"red", '010':"blue", '011':"red", '100':"green", '101':"blue", '110':"orange", '111':"red"} colour_hash_map = {"yellow":'100', "red":'011', "blue":'000', "green":'001', "orange":'010'} def database_oracle(index_colour_table, colour_hash_map): circ_database = QuantumCircuit(n + n) for i in range(N): circ_data = QuantumCircuit(n) idx = bin(i)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion colour = index_colour_table[idx] colour_hash = colour_hash_map[colour][::-1] for j in range(n): if colour_hash[j] == '1': circ_data.x(j) # qiskit maps the rightmost bit as the 0th qubit -> qn, ..., q0 # we therefore reverse the index string -> q0, ..., qn data_gate = circ_data.to_gate(label=colour).control(num_ctrl_qubits=n, ctrl_state=idx, label="index-"+colour) circ_database.append(data_gate, list(range(n+n))) return circ_database # drawing the database oracle circuit print("Database Encoding") database_oracle(index_colour_table, colour_hash_map).draw() circ_data = QuantumCircuit(n) m = 4 idx = bin(m)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion colour = index_colour_table[idx] colour_hash = colour_hash_map[colour][::-1] for j in range(n): if colour_hash[j] == '1': circ_data.x(j) print("Internal colour encoding for the colour green (as an example)"); circ_data.draw() def oracle_grover(database, data_entry): circ_grover = QuantumCircuit(n + n + 1) circ_grover.append(database, list(range(n+n))) target_reflection_gate = XGate().control(num_ctrl_qubits=n, ctrl_state=colour_hash_map[data_entry], label="Reflection of " + "\"" + data_entry + "\" Target") # control() missing 1 required positional argument: 'self' .... if only 'XGate' used instead of 'XGate()' # The “missing 1 required positional argument: 'self'” error is raised when you do not instantiate an object of a class before calling a class method. This error is also raised when you incorrectly instantiate a class. circ_grover.append(target_reflection_gate, list(range(n, n+n+1))) circ_grover.append(database, list(range(n+n))) return circ_grover print("Grover Oracle (target example: orange)") oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), "orange").decompose().draw() def mcz_gate(num_qubits): num_controls = num_qubits - 1 mcz_gate = QuantumCircuit(num_qubits) target_mcz = QuantumCircuit(1) target_mcz.z(0) target_mcz = target_mcz.to_gate(label="Z_Gate").control(num_ctrl_qubits=num_controls, ctrl_state=None, label="MCZ") mcz_gate.append(target_mcz, list(range(num_qubits))) return mcz_gate.reverse_bits() print("Multi-controlled Z (MCZ) Gate") mcz_gate(n).decompose().draw() def diffusion_operator(num_qubits): circ_diffusion = QuantumCircuit(num_qubits) qubits_list = list(range(num_qubits)) # Layer of H^n gates circ_diffusion.h(qubits_list) # Layer of X^n gates circ_diffusion.x(qubits_list) # Layer of Multi-controlled Z (MCZ) Gate circ_diffusion = circ_diffusion.compose(mcz_gate(num_qubits), qubits_list) # Layer of X^n gates circ_diffusion.x(qubits_list) # Layer of H^n gates circ_diffusion.h(qubits_list) return circ_diffusion print("Diffusion Circuit") diffusion_operator(n).draw() # Putting it all together ... !!! item = "green" print("Searching for the index of the colour", item) circuit = QuantumCircuit(n + n + 1, n) circuit.x(n + n) circuit.barrier() circuit.h(list(range(n))) circuit.h(n+n) circuit.barrier() unitary_oracle = oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), item).to_gate(label="Oracle Operator") unitary_diffuser = diffusion_operator(n).to_gate(label="Diffusion Operator") M = countOf(index_colour_table.values(), item) Q = int(np.pi * np.sqrt(N/M) / 4) for i in range(Q): circuit.append(unitary_oracle, list(range(n + n + 1))) circuit.append(unitary_diffuser, list(range(n))) circuit.barrier() circuit.measure(list(range(n)), list(range(n))) circuit.draw() backend_sim = Aer.get_backend('qasm_simulator') job_sim = backend_sim.run(transpile(circuit, backend_sim), shots=1024) result_sim = job_sim.result() counts = result_sim.get_counts(circuit) if M==1: print("Index of the colour", item, "is the index with most probable outcome") else: print("Indices of the colour", item, "are the indices the most probable outcomes") from qiskit.visualization import plot_histogram plot_histogram(counts)
https://github.com/matheusmtta/Quantum-Computing
matheusmtta
import numpy as np from numpy import pi # importing Qiskit from qiskit import QuantumCircuit, transpile, assemble, Aer from qiskit.visualization import plot_histogram, plot_bloch_multivector qc = QuantumCircuit(3) qc.h(2) qc.cp(pi/2, 1, 2) qc.cp(pi/4, 0, 2) qc.h(1) qc.cp(pi/2, 0, 1) qc.h(0) qc.swap(0, 2) qc.draw() def qft_rotations(circuit, n): if n == 0: return circuit n -= 1 circuit.h(n) for qubit in range(n): circuit.cp(pi/2**(n-qubit), qubit, n) 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_rotations(circuit, n) swap_registers(circuit, n) return circuit qc = QuantumCircuit(4) qft(qc,4) qc.draw() # Create the circuit qc = QuantumCircuit(3) # Encode the state 5 (101 in binary) qc.x(0) qc.x(2) qc.draw() sim = Aer.get_backend("aer_simulator") qc_init = qc.copy() qc_init.save_statevector() statevector = sim.run(qc_init).result().get_statevector() plot_bloch_multivector(statevector) qft(qc, 3) qc.draw() qc.save_statevector() statevector = sim.run(qc).result().get_statevector() plot_bloch_multivector(statevector)
https://github.com/matheusmtta/Quantum-Computing
matheusmtta
#initialization import matplotlib.pyplot as plt import numpy as np import math # importing Qiskit from qiskit import IBMQ, Aer, transpile, assemble from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister # import basic plot tools from qiskit.visualization import plot_histogram qpe = QuantumCircuit(4, 3) qpe.x(3) #Apply Hadamard gate for qubit in range(3): qpe.h(qubit) qpe.draw() repetitions = 1 for counting_qubit in range(3): for i in range(repetitions): qpe.cp(math.pi/4, counting_qubit, 3); # This is CU # we use 2*pi*(1/theta) repetitions *= 2 qpe.draw() def qft_dagger(qc, n): """n-qubit QFTdagger the first n qubits in circ""" # Don't forget the Swaps! for qubit in range(n//2): qc.swap(qubit, n-qubit-1) for j in range(n): for m in range(j): qc.cp(-math.pi/float(2**(j-m)), m, j) qc.h(j) qpe.barrier() # Apply inverse QFT qft_dagger(qpe, 3) # Measure qpe.barrier() for n in range(3): qpe.measure(n,n) qpe.draw() aer_sim = Aer.get_backend('aer_simulator') shots = 2048 t_qpe = transpile(qpe, aer_sim) qobj = assemble(t_qpe, shots=shots) results = aer_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer) # Create and set up circuit qpe2 = QuantumCircuit(4, 3) # Apply H-Gates to counting qubits: for qubit in range(3): qpe2.h(qubit) # Prepare our eigenstate |psi>: qpe2.x(3) # Do the controlled-U operations: angle = 2*math.pi/3 repetitions = 1 for counting_qubit in range(3): for i in range(repetitions): qpe2.cp(angle, counting_qubit, 3); repetitions *= 2 # Do the inverse QFT: qft_dagger(qpe2, 3) # Measure of course! for n in range(3): qpe2.measure(n,n) qpe2.draw() # Let's see the results! aer_sim = Aer.get_backend('aer_simulator') shots = 4096 t_qpe2 = transpile(qpe2, aer_sim) qobj = assemble(t_qpe2, shots=shots) results = aer_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer) # Create and set up circuit qpe3 = QuantumCircuit(6, 5) # Apply H-Gates to counting qubits: for qubit in range(5): qpe3.h(qubit) # Prepare our eigenstate |psi>: qpe3.x(5) # Do the controlled-U operations: angle = 2*math.pi/3 repetitions = 1 for counting_qubit in range(5): for i in range(repetitions): qpe3.cp(angle, counting_qubit, 5); repetitions *= 2 # Do the inverse QFT: qft_dagger(qpe3, 5) # Measure of course! qpe3.barrier() for n in range(5): qpe3.measure(n,n) qpe3.draw() # Let's see the results! aer_sim = Aer.get_backend('aer_simulator') shots = 4096 t_qpe3 = transpile(qpe3, aer_sim) qobj = assemble(t_qpe3, shots=shots) results = aer_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer)
https://github.com/matheusmtta/Quantum-Computing
matheusmtta
from qiskit import QuantumCircuit, Aer, execute, IBMQ from qiskit.utils import QuantumInstance import numpy as np from qiskit.algorithms import Shor IBMQ.enable_account('ENTER API TOKEN HERE') # Enter your API token here provider = IBMQ.get_provider(hub='ibm-q') backend = Aer.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend, shots=1000) my_shor = Shor(quantum_instance) result_dict = my_shor.factor(15) print(result_dict)
https://github.com/matheusmtta/Quantum-Computing
matheusmtta
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit import * from qiskit.tools.visualization import plot_histogram from IPython.display import display, Math, Latex from qiskit.visualization import plot_state_qsphere def BuildBell(x, y): U = QuantumCircuit(2) U.h(0) U.cx(0, 1) if x == 1: U.cz(0, 1) if y == 1: U.x(1) U = U.to_gate() U.name = 'Build Bell' #ctl_U = U.control() make it a controlled gate return U backend = BasicAer.get_backend('statevector_simulator') n = 2 #bell state 00 [x, y] = [0, 0] b00 = QuantumCircuit(n, n) b00.append(BuildBell(x, y), range(n)) #bell state 01 [x, y] = [0, 1] b01 = QuantumCircuit(n, n) b01.append(BuildBell(x, y), range(n)) #bell state 10 [x, y] = [1, 0] b10 = QuantumCircuit(n, n) b10.append(BuildBell(x, y), range(n)) #bell state 11 [x, y] = [1, 1] b11 = QuantumCircuit(n, n) b11.append(BuildBell(x, y), range(n)) bqs00 = execute(b00, backend).result() bqs01 = execute(b01, backend).result() bqs10 = execute(b10, backend).result() bqs11 = execute(b11, backend).result() #GENERAL CIRCUIT b_00 bxy = QuantumCircuit(n, n) bxy.h(0) bxy.cx(0, 1) bxy.measure(range(n), range(n)) backend = BasicAer.get_backend('qasm_simulator') atp = 1024 res = execute(bxy, backend=backend, shots=atp).result() ans = res.get_counts() bxy.draw('mpl') plot_histogram(ans) plot_state_qsphere(bqs00.get_statevector(b00)) #bell state 00 qsphere plot_state_qsphere(bqs01.get_statevector(b01)) #bell state 01 qsphere plot_state_qsphere(bqs10.get_statevector(b10)) #bell state 10 qsphere plot_state_qsphere(bqs11.get_statevector(b11)) #bell state 11 qsphere
https://github.com/matheusmtta/Quantum-Computing
matheusmtta
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit import * from qiskit.tools.visualization import plot_histogram from IPython.display import display, Math, Latex def BuildGHZ(n): U = QuantumCircuit(n) U.h(0) for i in range(1, n): U.cx(0, i) U = U.to_gate() U.name = 'Build GHZ' #ctl_U = U.control() make it a controlled gate return U n = 5 mc = QuantumCircuit(n, n) U = BuildGHZ(n) mc.append(U, range(n)) mc.measure(range(n), range(n)) backend = BasicAer.get_backend('qasm_simulator') atp = 1024 res = execute(mc, backend=backend, shots=atp).result() ans = res.get_counts() mc.draw('mpl') plot_histogram(ans)
https://github.com/matheusmtta/Quantum-Computing
matheusmtta
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit import * from qiskit.tools.visualization import plot_histogram from IPython.display import display, Math, Latex def Decrement(n): U = QuantumCircuit(n) control = [x for x in range(n-1)] for k in range(n-1): U.x(control) U.mcx(control, control[-1]+1) U.x(control) control.pop() U.x(0) U = U.to_gate() U.name = 'Decrement' #ctl_U = U.control() make it a controlled gate return U n = 3 mc = QuantumCircuit(n, n) U = Decrement(n) mc.append(U, range(n)) mc.measure(range(n), range(n)) backend = BasicAer.get_backend('qasm_simulator') atp = 1024 res = execute(mc, backend=backend, shots=atp).result() ans = res.get_counts() mc.draw('mpl') plot_histogram(ans)
https://github.com/matheusmtta/Quantum-Computing
matheusmtta
from qiskit import BasicAer, execute from qiskit.circuit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.circuit.library.standard_gates import PhaseGate from qiskit.circuit.library.basis_change import QFT import math from src.util.util import run_qc q = QuantumRegister(3) b = QuantumRegister(1) c = ClassicalRegister(3) qc = QuantumCircuit(q, b, c) qc.x(q[0]) qc.draw(output='mpl') def increment(circuit, register, apply_QFT=True): q = register num = len(q) qc = circuit if apply_QFT == True: qc.barrier() qc = qc.compose(QFT(num_qubits=num, approximation_degree=0, do_swaps=True, \ inverse=False, insert_barriers=True, name='qft')) qc.barrier() for i, qubit in enumerate(q): qc.rz(math.pi/2**(num-1-i), qubit) if apply_QFT == True: qc.barrier() qc = qc.compose(QFT(num_qubits=num, approximation_degree=0, do_swaps=True, \ inverse=True, insert_barriers=True, name='iqft')) qc.barrier() return qc test = increment(qc, q) test.draw(output='mpl') def control_increment(circuit, qregister, cregister, apply_QFT=True): q = qregister c = cregister numq = len(q) numc = len(c) qc = circuit if apply_QFT == True: qc.barrier() qc = qc.compose(QFT(num_qubits=numq, approximation_degree=0, do_swaps=True, \ inverse=False, insert_barriers=True, name='qft')) qc.barrier() for i, qubit in enumerate(q): ncp = PhaseGate(math.pi/2**(numq-i-1)).control(numc) qc.append(ncp, [*c, qubit]) if apply_QFT == True: qc.barrier() qc = qc.compose(QFT(num_qubits=numq, approximation_degree=0, do_swaps=True, \ inverse=True, insert_barriers=True, name='iqft')) qc.barrier() return qc test2 = control_increment(qc, q, b) test2.draw(output='mpl') ## Test increment without control test = increment(qc, q) test.measure(q[:], c[:]) run_qc(qc) test.draw(output='mpl') # Test control increment q = QuantumRegister(3) b = QuantumRegister(1) c = ClassicalRegister(3) qc = QuantumCircuit(q, b, c) qc.x(q[0]) qc = control_increment(qc, q, b) # Flipping control qubit to 1 qc.x(b[0]) qc = control_increment(qc, q, b) # Flipping control qubit to 1 qc.x(b[0]) qc = control_increment(qc, q, b) # Should equal 010 qc.measure(q[:], c[:]) run_qc(qc) qc.draw(output="mpl")
https://github.com/matheusmtta/Quantum-Computing
matheusmtta
import numpy as np from numpy import pi # importing Qiskit from qiskit import QuantumCircuit, transpile, assemble, Aer from qiskit.visualization import plot_histogram, plot_bloch_multivector qc = QuantumCircuit(3) qc.h(2) qc.cp(pi/2, 1, 2) qc.cp(pi/4, 0, 2) qc.h(1) qc.cp(pi/2, 0, 1) qc.h(0) qc.swap(0, 2) qc.draw() def qft_rotations(circuit, n): if n == 0: return circuit n -= 1 circuit.h(n) for qubit in range(n): circuit.cp(pi/2**(n-qubit), qubit, n) 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_rotations(circuit, n) swap_registers(circuit, n) return circuit qc = QuantumCircuit(4) qft(qc,4) qc.draw() # Create the circuit qc = QuantumCircuit(3) # Encode the state 5 (101 in binary) qc.x(0) qc.x(2) qc.draw() sim = Aer.get_backend("aer_simulator") qc_init = qc.copy() qc_init.save_statevector() statevector = sim.run(qc_init).result().get_statevector() plot_bloch_multivector(statevector) qft(qc, 3) qc.draw() qc.save_statevector() statevector = sim.run(qc).result().get_statevector() plot_bloch_multivector(statevector)
https://github.com/matheusmtta/Quantum-Computing
matheusmtta
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit import * from qiskit.tools.visualization import plot_histogram from IPython.display import display, Math, Latex from qiskit.visualization import plot_state_qsphere def BuildBell(x, y): U = QuantumCircuit(2) U.h(0) U.cx(0, 1) if x == 1: U.cz(0, 1) if y == 1: U.x(1) U = U.to_gate() U.name = 'Build Bell' #ctl_U = U.control() make it a controlled gate return U backend = BasicAer.get_backend('statevector_simulator') n = 2 #bell state 00 [x, y] = [0, 0] b00 = QuantumCircuit(n, n) b00.append(BuildBell(x, y), range(n)) #bell state 01 [x, y] = [0, 1] b01 = QuantumCircuit(n, n) b01.append(BuildBell(x, y), range(n)) #bell state 10 [x, y] = [1, 0] b10 = QuantumCircuit(n, n) b10.append(BuildBell(x, y), range(n)) #bell state 11 [x, y] = [1, 1] b11 = QuantumCircuit(n, n) b11.append(BuildBell(x, y), range(n)) bqs00 = execute(b00, backend).result() bqs01 = execute(b01, backend).result() bqs10 = execute(b10, backend).result() bqs11 = execute(b11, backend).result() #GENERAL CIRCUIT b_00 bxy = QuantumCircuit(n, n) bxy.h(0) bxy.cx(0, 1) bxy.measure(range(n), range(n)) backend = BasicAer.get_backend('qasm_simulator') atp = 1024 res = execute(bxy, backend=backend, shots=atp).result() ans = res.get_counts() bxy.draw('mpl') plot_histogram(ans) plot_state_qsphere(bqs00.get_statevector(b00)) #bell state 00 qsphere plot_state_qsphere(bqs01.get_statevector(b01)) #bell state 01 qsphere plot_state_qsphere(bqs10.get_statevector(b10)) #bell state 10 qsphere plot_state_qsphere(bqs11.get_statevector(b11)) #bell state 11 qsphere
https://github.com/matheusmtta/Quantum-Computing
matheusmtta
open Microsoft.Quantum.Intrinsic; open Microsoft.Quantum.Canon; open Microsoft.Quantum.Math; open Microsoft.Quantum.Diagnostics; open Microsoft.Quantum.Measurement; open Microsoft.Quantum.Convert; open Microsoft.Quantum.Preparation; open Microsoft.Quantum.Arithmetic; //If all entries of x are One, the Oracle returns |y> = |1> operation andOracle (x : Qubit[], y : Qubit) : Unit { body { (Controlled X)(x, y); } adjoint auto; } //If all entries of x are Zero, the Oracle returns |y> = |0> operation orOracle (x : Qubit[], y : Qubit) : Unit { body { ApplyToEachA(X, x); Controlled X (x, y); X(y); ApplyToEachA(X, x); } adjoint auto; } //Given two qubits, XOR gate if 01 or 10 |y> = |1> operation xorOracle2 (x : Qubit[], y : Qubit) : Unit { X(y); Controlled X(x, y); X(x[0]); X(x[1]); Controlled X(x, y); X(x[0]); X(x[1]); } //Puts a state |000...0> into the GHZ state |000..0> + |111..1>/sqrt2 operation buildGHZ (qs : Qubit[]) : Unit{ body { H(qs[0]); for (i in 1..Length(qs)-1){ CNOT(qs[0], qs[i]); } } adjoint auto; } //Puts a state |000...0> into the GHZ state |100..0> + |010..0> + ... |000..1>/sqrtN operation buildW (qs : Qubit[]) : Unit is Adj + Ctl { body { let N = Length(qs); Ry(2.0*ArcSin(Sqrt(1.0/(IntAsDouble(N)))), qs[0]); if (N > 1){ ((ControlledOnInt)(0, buildW))([qs[0]], qs[1...]); } } adjoint auto; } operation isAllZeros (qs : Qubit[]) : Int { return MeasureInteger(LittleEndian(qs)) == 0 ? 0 | 1; } //Generate Bell State 0 : |00>, 1 : |01>, 2 : |10>, 3 |11> operation buildBell (qs : Qubit[], index : Int) : Unit { H(qs[0]); CNOT(qs[0], qs[1]); if (index%2 == 1){ Z(qs[1]); } if (index/2 == 1){ X(qs[0]); } } //Distinguish Bell State 0 : |00>, 1 : |01>, 2 : |10>, 3 : |11> operation distinguishBell (qs : Qubit[]) : Int { CNOT(qs[0], qs[1]); H(qs[0]); let m1 = M(qs[0]) == One ? 1 | 0; let m2 = M(qs[1]) == One ? 1 | 0; return 2*m2 + m1; } //Create a copy of a the given state operation stateCopy (qs : Qubit[], copy : Qubit[]) : Unit { for (i in 0..Length(qs)-1){ CNOT(qs[i], copy[i]); } } //takes a integer array of 0/1s and creates an equivalent qubit string operation arrToQbit (bits : Int[], qs : Qubit[]) : Unit { for (i in 0..Length(qs)-1){ if (bits[i] == 1){ X(qs[i]); } } } //Teleport 2 qubits + message operation Teleport (qAlice : Qubit, qBob : Qubit, qMessage : Qubit) : Unit { H(qAlice); CNOT(qAlice, qBob); CNOT(qMessage, qAlice); H(qMessage); (Controlled Z)([qMessage], qBob); (Controlled X)([qAlice], qBob); } //Superdensecoding protocol operation SuperdenseCodingProtocol (b1 : Bool, b2 : Bool) : (Bool, Bool) { using ((qAlice, qBob) = (Qubit(), Qubit())){ H(qAlice); CNOT(qAlice, qBob); //MCMAHON BOOK P236 if (b1){ Z(qAlice); } if (b2){ X(qAlice); } CNOT(qAlice, qBob); H(qAlice); //Measure the qubit at Z basis, and reset it return ((MResetZ(qAlice) == One, MResetZ(qBob) == One)); } } //Destruct state //Given a superposition state and a integer representing //the state to be destroied we build a uniform superposition //with the remaining ones. operation Destruct(qs : Qubit[], state : Int) : Unit { using (a = Qubit()) { repeat { (ControlledOnInt(state, X)) (qs, a); let r = MResetZ(a); } until (r == Zero) fixup { ResetAll(qs); } } } //Increment, sum two qubits operation Increment(register : LittleEndian) : Unit is Adj + Ctl { using (q = Qubit[Length(register!)]){ X(q[0]); RippleCarryAdderNoCarryTTK(LittleEndian(q), register); X(q[0]); } } //Decrement, operation Decrement(register : LittleEndian) : Unit is Adj + Ctl { using (q = Qubit[Length(register!)]){ ApplyToEachCA(X, q); RippleCarryAdderNoCarryTTK(LittleEndian(q), register); ApplyToEachCA(X, q); } } //QUANTUM FOURIER TRANSFORM operation Reverse(x : Qubit[]) : Unit is Adj+Ctl { let N = Length(x); for (i in 0 .. N/2-1) { SWAP(x[i], x[N-1-i]); } } operation myQFT(x : Qubit[]) : Unit is Adj+Ctl { let n = Length(x); for (i in n-1..-1..0) { H(x[i]); for (j in i-1..-1..0) { let theta = (2.0*PI())/(IntAsDouble(1 <<< i-j+1)); Controlled R1([x[j]], (theta, x[i])); } } Reverse (x); }
https://github.com/matheusmtta/Quantum-Computing
matheusmtta
import numpy as np from numpy import linalg as LA from scipy.linalg import expm, sinm, cosm import matplotlib.pyplot as plt import pandas as pd import seaborn as sns import math from scipy import stats %matplotlib inline from IPython.display import Image, display, Math, Latex sns.set(color_codes=True) #number of vertices n = 4 #Define adjacency matrix A_Cn A = np.zeros((n, n)) for i in range(n): j1 = (i - 1)%n j2 = (i + 1)%n A[i][j1] = 1 A[i][j2] = 1 #Define our initial state Psi_a psi_a = np.zeros(n) psi_a[3] = 1 #Define the time t >= 0 t = math.pi/2 #Exponentiate or hamiltonian U_t = expm(1j*t*A) U_mt = expm(1j*(-t)*A) #Compute Psi_t psi_t = U_t @ psi_a #Compute the probabilities prob_t = abs(psi_t)**2 M_t = U_t*U_mt M_t = np.around(M_t, decimals = 3) M_t x = M_t[:, 0].real plt.bar(range(len(x)), x, tick_label=[0, 1, 2, 3]) plt.xlabel('Vertices') plt.ylabel('Probability')
https://github.com/matheusmtta/Quantum-Computing
matheusmtta
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit import * from qiskit.providers.ibmq import least_busy from qiskit.tools.visualization import plot_histogram from IPython.display import display, Math, Latex def Increment(size): U = QuantumCircuit(size) control = [x for x in range(size-1)] for k in range(size-1): U.mcx(control, control[-1]+1) control.pop() U.x(0) U = U.to_gate() U.name = '--->' ctl_U = U.control() return ctl_U def Decrement(size): U = QuantumCircuit(size) control = [x for x in range(size-1)] for k in range(size-1): U.x(control) U.mcx(control, control[-1]+1) U.x(control) control.pop() U.x(0) U = U.to_gate() U.name = '<---' ctl_U = U.control() return ctl_U n = 2 steps = 2 graph = QuantumRegister(n+1) mes = ClassicalRegister(n) mcq = QuantumCircuit(graph, mes) #define U(t) for i in range(steps): mcq.h(n) mcq.append(Increment(n), [n]+list(range(0, n))) mcq.x(n) mcq.append(Decrement(n), [n]+list(range(0, n))) mcq.x(n) mcq.measure(range(n), range(n)) #mcq = transpile(mcq, basis_gates=['cx','u3'],optimization_level=3) mcq.draw('mpl') backend = BasicAer.get_backend('qasm_simulator') atp = 1024 res = execute(mcq, backend=backend, shots=atp).result() ans = res.get_counts() plot_histogram(ans) IBMQ.load_account() provider = IBMQ.get_provider(group='open', project='main') backend = provider.get_backend('ibmq_16_melbourne') job = execute(mcq, backend=backend) ans_quantum = job.result().get_counts() legend = ['QASM','ibmq_16_melbourne'] plot_histogram([ans,ans_quantum], legend=legend)
https://github.com/matheusmtta/Quantum-Computing
matheusmtta
import numpy as np from scipy.linalg import expm, sinm, cosm import matplotlib.pyplot as plt import pandas as pd import seaborn as sns import math from scipy import stats %matplotlib inline from IPython.display import Image, display, Math, Latex sns.set(color_codes=True)
https://github.com/matteoacrossi/oqs-jupyterbook
matteoacrossi
############################# # Pauli channel on IBMQX2 # ############################# from qiskit import QuantumRegister, QuantumCircuit # Quantum register q = QuantumRegister(5, name="q") # Quantum circuit pauli = QuantumCircuit(q) # Pauli channel acting on q_2 ## Qubit identification system = 2 a_0 = 3 a_1 = 4 ## Define rotation angles theta_1 = 0.0 theta_2 = 0.0 theta_3 = 0.0 ## Construct circuit pauli.ry(theta_1, q[a_0]) pauli.cx(q[a_0], q[a_1]) pauli.ry(theta_2, q[a_0]) pauli.ry(theta_3, q[a_1]) pauli.cx(q[a_0], q[system]) pauli.cy(q[a_1], q[system]) # Draw circuit pauli.draw(output='mpl') #################################### # Depolarizing channel on IBMQX2 # #################################### # Quantum register q = QuantumRegister(5, name="q") # Quantum circuit depolarizing = QuantumCircuit(q) # Depolarizing channel acting on q_2 ## Qubit identification system = 2 a_0 = 1 a_1 = 3 a_2 = 4 ## Define rotation angles theta = 0.0 ## Construct circuit depolarizing.ry(theta, q[a_0]) depolarizing.ry(theta, q[a_1]) depolarizing.ry(theta, q[a_2]) depolarizing.cx(q[a_0], q[system]) depolarizing.cy(q[a_1], q[system]) depolarizing.cz(q[a_2], q[system]) # Draw circuit depolarizing.draw(output='mpl') ####################### # ZZ pump on IBMQX2 # ####################### # Quantum register q = QuantumRegister(5, name='q') # Quantum circuit zz = QuantumCircuit(q) # ZZ pump acting on system qubits ## Qubit identification system = [2, 1] a_zz = 0 ## Define pump efficiency ## and corresponding rotation p = 0.5 theta = 2 * np.arcsin(np.sqrt(p)) ## Construct circuit ### Map information to ancilla zz.cx(q[system[0]], q[system[1]]) zz.x(q[a_zz]) zz.cx(q[system[1]], q[a_zz]) ### Conditional rotation zz.cu3(theta, 0.0, 0.0, q[a_zz], q[system[1]]) ### Inverse mapping zz.cx(q[system[1]], q[a_zz]) zz.cx(q[system[0]], q[system[1]]) # Draw circuit zz.draw(output='mpl') ####################### # XX pump on IBMQX2 # ####################### # Quantum register q = QuantumRegister(5, name='q') # Quantum circuit xx = QuantumCircuit(q) # XX pump acting on system qubits ## Qubit identification system = [2, 1] a_xx = 4 ## Define pump efficiency ## and corresponding rotation p = 0.5 theta = 2 * np.arcsin(np.sqrt(p)) ## Construct circuit ### Map information to ancilla xx.cx(q[system[0]], q[system[1]]) xx.h(q[system[0]]) xx.x(q[a_xx]) xx.cx(q[system[0]], q[a_xx]) ### Conditional rotation xx.cu3(theta, 0.0, 0.0, q[a_xx], q[system[0]]) ### Inverse mapping xx.cx(q[system[0]], q[a_xx]) xx.h(q[system[0]]) xx.cx(q[system[0]], q[system[1]]) # Draw circuit xx.draw(output='mpl') ########################### # ZZ-XX pumps on IBMQX2 # ########################### # Quantum register q = QuantumRegister(5, name='q') # Quantum circuit zz_xx = QuantumCircuit(q) # ZZ and XX pumps acting on system qubits ## Qubit identification system = [2, 1] a_zz = 0 a_xx = 4 ## Define pump efficiency ## and corresponding rotation p = 0.5 theta = 2 * np.arcsin(np.sqrt(p)) ## Construct circuit ## ZZ pump ### Map information to ancilla zz_xx.cx(q[system[0]], q[system[1]]) zz_xx.x(q[a_zz]) zz_xx.cx(q[system[1]], q[a_zz]) ### Conditional rotation zz_xx.cu3(theta, 0.0, 0.0, q[a_zz], q[system[1]]) ### Inverse mapping zz_xx.cx(q[system[1]], q[a_zz]) #zz_xx.cx(q[system[0]], q[system[1]]) ## XX pump ### Map information to ancilla #zz_xx.cx(q[system[0]], q[system[1]]) zz_xx.h(q[system[0]]) zz_xx.x(q[a_xx]) zz_xx.cx(q[system[0]], q[a_xx]) ### Conditional rotation zz_xx.cu3(theta, 0.0, 0.0, q[a_xx], q[system[0]]) ### Inverse mapping zz_xx.cx(q[system[0]], q[a_xx]) zz_xx.h(q[system[0]]) zz_xx.cx(q[system[0]], q[system[1]]) # Draw circuit zz_xx.draw(output='mpl')
https://github.com/matteoacrossi/oqs-jupyterbook
matteoacrossi
from IPython.display import IFrame IFrame(src='./gen_plots/jaynescummings.html', width=900, height=350) ########################################### # Amplitude damping channel on IBMQ_VIGO # ########################################### from qiskit import QuantumRegister, QuantumCircuit # Quantum register q = QuantumRegister(5, name='q') # Quantum circuit ad = QuantumCircuit(q) # Amplitude damping channel acting on system qubit ## Qubit identification system = 1 environment = 2 # Define rotation angle theta = 0.0 # Construct circuit ad.x(q[system]) ad.cu3(theta, 0.0, 0.0, q[system], q[environment]) ad.cx(q[environment], q[system]) # Draw circuit ad.draw(output='mpl')
https://github.com/matteoacrossi/oqs-jupyterbook
matteoacrossi
from IPython.display import IFrame IFrame(src='./gen_plots/channel_cap.html', width=450, height=500) from IPython.display import IFrame IFrame(src='./gen_plots/nonmark_witness.html', width=700, height=350) ####################################### # Amplitude damping channel # # with non-M. witness on IBMQ_VIGO # ####################################### from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit # Quantum and classical register q = QuantumRegister(5, name='q') c = ClassicalRegister(2, name='c') # Quantum circuit ad = QuantumCircuit(q, c) # Amplitude damping channel acting on system qubit # with non-Markovianity witness ## Qubit identification system = 1 environment = 2 ancilla = 3 # Define rotation angle theta = 0.0 # Construct circuit ## Bell state between system and ancilla ad.h(q[system]) ad.cx(q[system], q[ancilla]) ## Channel acting on system qubit ad.cu3(theta, 0.0, 0.0, q[system], q[environment]) ad.cx(q[environment], q[system]) ## Local measurement for the witness ### Choose observable observable = 'YY' ### Change to the corresponding basis if observable == 'XX': ad.h(q[system]) ad.h(q[ancilla]) elif observable == 'YY': ad.sdg(q[system]) ad.h(q[system]) ad.sdg(q[ancilla]) ad.h(q[ancilla]) ### Measure ad.measure(q[system], c[0]) ad.measure(q[ancilla], c[1]) # Draw circuit ad.draw(output='mpl')