repo
stringclasses
900 values
file
stringclasses
754 values
content
stringlengths
4
215k
https://github.com/arthurfaria/Qiskit_certificate_prep
arthurfaria
# General tools import numpy as np import matplotlib.pyplot as plt import math # Importing standard Qiskit libraries from qiskit import execute,QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, transpile, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * # Loading your IBM Quantum account(s) provider = IBMQ.load_account() QuantumCircuit(4, 4) qc = QuantumCircuit(1) qc.ry(3 * math.pi/4, 0) # draw the circuit qc.draw() # et's plot the histogram and see the probability :) qc.measure_all() qasm_sim = Aer.get_backend('qasm_simulator') #this time we call the qasm simulator result = execute(qc, qasm_sim).result() # NOTICE: we can skip some steps by doing .result() directly, we could go further! counts = result.get_counts() #this time, we are not getting the state, but the counts! plot_histogram(counts) #a new plotting method! this works for counts obviously! inp_reg = QuantumRegister(2, name='inp') ancilla = QuantumRegister(1, name='anc') qc = QuantumCircuit(inp_reg, ancilla) # Insert code here qc.h(inp_reg[0:2]) qc.x(ancilla[0]) qc.draw() bell = QuantumCircuit(2) bell.h(0) bell.x(1) bell.cx(0, 1) bell.draw() qc = QuantumCircuit(1,1) # Insert code fragment here qc.ry(math.pi / 2,0) simulator = Aer.get_backend('statevector_simulator') job = execute(qc, simulator) result = job.result() outputstate = result.get_statevector(qc) plot_bloch_multivector(outputstate) from qiskit import QuantumCircuit, Aer, execute from math import sqrt qc = QuantumCircuit(2) # Insert fragment here v = [1/sqrt(2), 0, 0, 1/sqrt(2)] qc.initialize(v,[0,1]) simulator = Aer.get_backend('statevector_simulator') result = execute(qc, simulator).result() statevector = result.get_statevector() print(statevector) qc = QuantumCircuit(3,3) qc.barrier() # B. qc.barrier([0,1,2]) qc.draw() qc = QuantumCircuit(1,1) qc.h(0) qc.s(0) qc.h(0) qc.measure(0,0) qc.draw() qc = QuantumCircuit(2, 2) qc.h(0) qc.barrier(0) qc.cx(0,1) qc.barrier([0,1]) qc.draw() qc.depth() # Use Aer's qasm_simulator qasm_sim = Aer.get_backend('qasm_simulator') #use a coupling map that connects three qubits linearly couple_map = [[0, 1], [1, 2]] # Execute the circuit on the qasm simulator. # We've set the number of repeats of the circuit # to be 1024, which is the default. job = execute(qc, backend=qasm_sim, shots=1024, coupling_map=couple_map) from qiskit import QuantumCircuit, execute, BasicAer backend = BasicAer.get_backend('qasm_simulator') qc = QuantumCircuit(3) # insert code here execute(qc, backend, shots=1024, coupling_map=[[0,1], [1,2]]) qc = QuantumCircuit(2, 2) qc.x(0) qc.measure([0,1], [0,1]) simulator = Aer.get_backend('qasm_simulator') result = execute(qc, simulator, shots=1000).result() counts = result.get_counts(qc) print(counts)
https://github.com/arthurfaria/Qiskit_certificate_prep
arthurfaria
from qiskit import QuantumCircuit, BasicAer, execute, IBMQ from qiskit.visualization import plot_histogram ghz = QuantumCircuit(3,3) ghz.h(0) ghz.cx(0,1) ghz.cx(1,2) #ghz.barrier(0,2) ghz.measure([0,1,2],[0,1,2]) # also possible to measure only one qubit with the desired classical bit. #For example, qubit 2 with classical bit 1: qc.measure(1,0) ghz.draw('mpl') backend = BasicAer.get_backend('qasm_simulator') result = execute(ghz, backend).result() #shots=1024 is by default defined counts = result.get_counts() plot_histogram(counts) leg = ['counts'] plot_histogram(counts, legend=leg, sort='asc',color='green') # for more counts, we have job2 = execute(ghz, backend, shots=1024) result2 = job2.result() counts2 = result2.get_counts() job3 = execute(ghz, backend, shots=1024) result3 = job3.result() counts3 = result3.get_counts() #brazilian flag :D leg = ['counts-1','counts-2', 'counts-3'] plot_histogram([counts,counts2,counts3], legend=leg, sort='asc', figsize = (8,7), color=['gold','green','blue']) plot_histogram([counts,counts2,counts3], legend=leg, sort='asc') qc_spec = QuantumCircuit(3) qc_spec.measure_all() backend = BasicAer.get_backend('qasm_simulator') #specify some linear connection couple_map = [[0,1],[1,2]] qc_spec.draw('mpl') job = execute(qc_spec,backend, shots= 1024, coupling_map = couple_map) results = job.result() counts = result.get_counts() print(counts) import qiskit.tools.jupyter from qiskit.tools import job_monitor provider = IBMQ.load_account() %qiskit_backend_overview backend_real = provider.get_backend('ibmq_belem') job = execute(ghz, backend_real) job_monitor(job) result = job.result() counts = result.get_counts() plot_histogram(counts)
https://github.com/arthurfaria/Qiskit_certificate_prep
arthurfaria
import numpy as np from qiskit import QuantumCircuit, assemble, Aer, execute, BasicAer from qiskit.visualization import * from qiskit.quantum_info import Statevector, random_statevector from qiskit.tools.jupyter import * from qiskit.extensions import Initialize bell_0 = QuantumCircuit(2,2) bell_0.h(0) bell_0.cx(0,1) bell_0.draw('latex') #we define the basis sv = Statevector.from_label("00") #we evolve this initial state through our circuit sv_bell_0 = sv.evolve(bell_0) sv_bell_0.draw('latex') bell_1 = QuantumCircuit(2,2) bell_1.h(0) bell_1.cx(0,1) bell_1.z(1) #mpl = matplotlib #latex_source also possible, but really hard to see what is going on bell_1.draw('mpl') sv_bell_1 = sv.evolve(bell_1) sv_bell_1.draw('latex_source') bell_2 = QuantumCircuit(2,2) bell_2.h(0) bell_2.x(1) bell_2.cx(0,1) bell_2.draw('text') sv_bell_2 = sv.evolve(bell_2) sv_bell_2.draw('text') #text by default bell_3 = QuantumCircuit(2,2) bell_3.h(0) bell_3.x(1) bell_3.cx(0,1) bell_3.z(1) bell_3.draw() #text by default sv_bell_3 = sv.evolve(bell_3) sv_bell_3.draw() ghz = QuantumCircuit(3) ghz.h(0) ghz.cx(0,1) ghz.cx(1,2) ghz.draw('mpl') ### drawing the statevector sv_ghz= Statevector.from_label("000") state_ghz = sv_ghz.evolve(ghz) state_ghz.draw('latex') plot_state_qsphere(bell_1) plot_state_hinton(bell_1) plot_state_paulivec(bell_3) plot_state_city(bell_2) plot_bloch_multivector(bell_2) # It is not a separable state!! ex_sep_state = QuantumCircuit(2) ex_sep_state.h(0) ex_sep_state.h(1) ex_sv = Statevector.from_label("00") ex_state = ex_sv.evolve(ex_sep_state) plot_bloch_multivector(ex_state) plot_bloch_vector([0.7,0.5,1]) #here for [x,y,z]; x=Tr[Xρ] and similar for y and z ###Part1: circuit part qc = QuantumCircuit(3) qc.h(0) qc.cx(0,1) qc.cx(1,2) #it saves the current simulator quantum state as a statevector. qc.save_statevector() ###Parts 2 and 3 using Aer_simulator qobj = assemble(qc) backend1 = Aer.get_backend('aer_simulator') ###Parts 4 and 5 result = backend1.run(qobj).result() sv_qc0 = result.get_statevector() sv_qc0.draw('latex') sv_qc0.draw('qsphere') ######## PART2: statevetor_simulator ###Part1: circuit part qc1 = QuantumCircuit(3) qc1.h(0) qc1.cx(0,1) qc1.cx(1,2) ### backend part backend2 = BasicAer.get_backend('statevector_simulator') ### result part # by default shots = 1024 job = execute(qc1, backend2, shots=1024) result = job.result() #finally, we get the statevector from the result sv_qc1 = result.get_statevector(qc1) sv_qc1.draw('qsphere') plot_state_city(sv_qc1) N = 1/np.sqrt(3) desired_state = [N,np.sqrt(1-N**2)] #adding it to a circuit qc_custom0 = QuantumCircuit(1) qc_custom0.initialize(desired_state,0) #as simple as this! qc_custom0.draw('mpl') meas = QuantumCircuit(1,1) meas.measure(0,0) #we add, through the composite function, the measurement to the custom state qc_custom = meas.compose(qc_custom0, front=True) qc_custom.draw('mpl') #To get histograms, we use qasm_simulator. #We will see this in the notebook qasm_simulator_and_visualization.ipynb backend_qasm = BasicAer.get_backend('qasm_simulator') job0 = execute(qc_custom, backend_qasm, shots=1000) counts = job0.result().get_counts() plot_histogram(counts) # random_statevector of dimension 2 psi = random_statevector(2) #Initialize qubits in a specific state. init_gate = Initialize(psi) # defining a name to the state. By default is |psi\rangle init_gate.label = "initial state" qc_random = QuantumCircuit(1) # random state for the first qibit qc_random.append(init_gate, [0]) qc_random.draw('mpl') qc_random.measure_all() qc_random.draw('mpl') job1 = execute(qc_random, backend_qasm, shots=1000) counts1 = job1.result().get_counts() plot_histogram(counts1) decomp = qc_custom0.decompose() decomp.draw('mpl')
https://github.com/arthurfaria/Qiskit_certificate_prep
arthurfaria
import numpy as np from qiskit import QuantumCircuit, BasicAer, execute, Aer from qiskit.quantum_info import Operator, DensityMatrix, Pauli from qiskit.extensions import YGate from qiskit.visualization import plot_histogram Cnot = Operator([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]) Cnot #returns Numpy array Cnot.data #total input and output dimension in_dim, out_dim = Cnot.dim in_dim, out_dim ghz = QuantumCircuit(3) ghz.h(0) ghz.cx([0,0],[1,2]) ghz.draw('mpl') U_ghz = Operator(ghz) np.around(U_ghz.data,3) #np.around specifies how many decimals is desired in the oputput #Aer has also a unitary_simulator backend. back_uni = Aer.get_backend('unitary_simulator') job = execute(ghz, back_uni) result = job.result() #getting the unitary with 3 decimals U_qc = result.get_unitary(decimals=3) U_qc op1 = [[1+0.j, 0.5+0.j], [0.5+0.j, 1+0.j]] op2 = [[0.5+0.j, 1+0.j], [0.5+0.j, 1+0.j]] matrix = DensityMatrix(op1) #doing the tensor product between op1 and op2 matrix.tensor(op2) # Pauli('Y') generates the Pauli Y-matrix object # On the other hand, Operator generates the operator of Pauli('Y') Operator( Pauli('Y')) == Operator(YGate()) Operator(YGate()) == np.exp(1j * 0.4) * Operator(YGate()) ZZ = Operator(Pauli('ZZ')) ZZ # Add to a circuit qc = QuantumCircuit(2, 2) qc.append(ZZ, [0, 1]) qc.measure([0,1], [0,1]) qc.draw('mpl') backend = BasicAer.get_backend('qasm_simulator') result = backend.run(qc).result() counts = result.get_counts() plot_histogram(counts) decomp = qc.decompose() decomp.draw('mpl') op1 = Operator(Pauli('Y')) op2 = Operator(Pauli('Z')) op1.compose(op2, front=True) op1 = Operator(Pauli('X')) op2 = Operator(Pauli('Y')) op1.tensor(op2)
https://github.com/asierarranz/QiskitUnityAsset
asierarranz
#!/usr/bin/env python3 from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit, Aer, execute def run_qasm(qasm, backend_to_run="qasm_simulator"): qc = QuantumCircuit.from_qasm_str(qasm) backend = Aer.get_backend(backend_to_run) job_sim = execute(qc, backend) sim_result = job_sim.result() return sim_result.get_counts(qc)
https://github.com/kaelynj/Qiskit-HubbardModel
kaelynj
%matplotlib inline import sys sys.path.append('./src') # Importing standard Qiskit libraries and configuring account #from qiskit import QuantumCircuit, execute, Aer, IBMQ #from qiskit.compiler import transpile, assemble #from qiskit.tools.jupyter import * #from qiskit.visualization import * import matplotlib.pyplot as plt import matplotlib.colors as mcolors import numpy as np import ClassicalHubbardEvolutionChain as chc import random as rand import scipy.linalg as la def get_bin(x, n=0): """ Get the binary representation of x. Parameters: x (int), n (int, number of digits)""" binry = format(x, 'b').zfill(n) sup = list( reversed( binry[0:int(len(binry)/2)] ) ) sdn = list( reversed( binry[int(len(binry)/2):len(binry)] ) ) return format(x, 'b').zfill(n) #============ Run Classical Evolution ============== #Define our basis states #States for 3 electrons with net spin up ''' states = [ [[1,1,0],[1,0,0]], [[1,1,0],[0,1,0]], [[1,1,0], [0,0,1]], [[1,0,1],[1,0,0]], [[1,0,1],[0,1,0]], [[1,0,1], [0,0,1]], [[0,1,1],[1,0,0]], [[0,1,1],[0,1,0]], [[0,1,1], [0,0,1]] ] ''' #States for 2 electrons in singlet state states = [ [[1,0,0],[1,0,0]], [[1,0,0],[0,1,0]], [[1,0,0],[0,0,1]], [[0,1,0],[1,0,0]], [[0,1,0],[0,1,0]], [[0,1,0],[0,0,1]], [[0,0,1],[1,0,0]], [[0,0,1],[0,1,0]], [[0,0,1],[0,0,1]] ] #''' #States for a single electron #states = [ [[1,0,0],[0,0,0]], [[0,1,0],[0,0,0]], [[0,0,1],[0,0,0]] ] #Possible initial wavefunctions #wfk = [0., 0., 0., 0., 1., 0., 0., 0., 0.] #Half-filling initial state wfk = [0., 0., 0., 0., 1.0, 0., 0., 0., 0.] #2 electron initial state #wfk = [0., 1., 0.] #1 electron initial state #System parameters t = 1.0 U = 2. classical_time_step = 0.01 classical_total_time = 500*0.01 times = np.arange(0., classical_total_time, classical_time_step) evolution, engs = chc.sys_evolve(states, wfk, t, U, classical_total_time, classical_time_step) #print(evolution) probs = [np.sum(x) for x in evolution] #print(probs) #print(np.sum(evolution[0])) print(engs) states_list = [] nsite = 3 for state in range(0, 2**(2*nsite)): state_bin = get_bin(state, 2*nsite) state_list = [[],[]] for mode in range(0,nsite): state_list[0].append(int(state_bin[mode])) state_list[1].append(int(state_bin[mode+nsite])) #print(state_list) states_list.append(state_list) #print(states_list[18]) #evolution2, engs2 = chc.sys_evolve(states_list, wfk_full, t, U, classical_total_time, classical_time_step) #System parameters t = 1.0 U = 2. classical_time_step = 0.01 classical_total_time = 500*0.01 times = np.arange(0., classical_total_time, classical_time_step) #Create full Hamiltonian wfk_full = np.zeros(len(states_list)) #wfk_full[18] = 1. #010010 wfk_full[21] = 1. #010101 #wfk_full[2] = 1. #000010 #evolution2, engs2 = chc.sys_evolve(states_list, wfk_full, t, U, classical_total_time, classical_time_step) def repel(l,state): if state[0][l]==1 and state[1][l]==1: return state else: return [] #Check if two states are different by a single hop def hop(psii, psij, hopping): #Check spin down hopp = 0 if psii[0]==psij[0]: #Create array of indices with nonzero values ''' indi = np.nonzero(psii[1])[0] indj = np.nonzero(psij[1])[0] if len(indi) != len(indj): return hopp print('ind_i: ',indi,' ind_j: ',indj) for i in range(len(indi)): if abs(indi[i]-indj[i])==1: hopp = -hopping print('Hopping Found: ',psii,' with: ',psij) return hopp ''' hops = [] for site in range(len(psii[0])): if psii[1][site] != psij[1][site]: hops.append(site) if len(hops)==2 and np.sum(psii[1]) == np.sum(psij[1]): if hops[1]-hops[0]==1: hopp = -hopping return hopp #Check spin up if psii[1]==psij[1]: ''' indi = np.nonzero(psii[0])[0] indj = np.nonzero(psij[0])[0] if len(indi) != len(indj): return hopp print('ind_i: ',indi,' ind_j: ',indj) for i in range(len(indi)): if abs(indi[i]-indj[i])==1: hopp = -hopping print('Hopping Found: ',psii,' with: ',psij) return hopp ''' hops = [] for site in range(len(psii[1])): if psii[0][site] != psij[0][site]: hops.append(site) if len(hops)==2 and np.sum(psii[0])==np.sum(psij[0]): if hops[1]-hops[0]==1: hopp = -hopping return hopp return hopp def get_hamiltonian(states, t, U): H = np.zeros((len(states),len(states)) ) #Construct Hamiltonian matrix for i in range(len(states)): psi_i = states[i] for j in range(i, len(states)): psi_j = states[j] if j==i: for l in range(0,len(states[0][0])): if psi_i == repel(l,psi_j): H[i,j] = U break else: #print('psi_i: ',psi_i,' psi_j: ',psi_j) H[i,j] = hop(psi_i, psi_j, t) H[j,i] = H[i,j] return H hamil = get_hamiltonian(states_list, t, U) print(hamil) print(states_list) print() print("Target state: ", states_list[21]) mapping = get_mapping(states_list) print('Second mapping set') print(mapping[1]) print(wfk_full) mapped_wfk = np.zeros(6) for i in range(len(mapping)): if 21 in mapping[i]: print("True for mapping set: ",i) def get_mapping(states): num_sites = len(states[0][0]) mode_list = [] for i in range(0,2*num_sites): index_list = [] for state_index in range(0,len(states)): state = states[state_index] #Check spin-up modes if i < num_sites: if state[0][i]==1: index_list.append(state_index) #Check spin-down modes else: if state[1][i-num_sites]==1: index_list.append(state_index) if index_list: mode_list.append(index_list) return mode_list def wfk_energy(wfk, hamil): eng = np.dot(np.conj(wfk), np.dot(hamil, wfk)) return eng def get_variance(wfk, h): h_squared = np.matmul(h, h) eng_squared = np.vdot(wfk, np.dot(h_squared, wfk)) squared_eng = np.vdot(wfk, np.dot(h, wfk)) var = np.sqrt(eng_squared - squared_eng) return var def sys_evolve(states, init_wfk, hopping, repulsion, total_time, dt): hamiltonian = get_hamiltonian(states, hopping, repulsion) t_operator = la.expm(-1j*hamiltonian*dt) mapping = get_mapping(states) print(mapping) #Initalize system tsteps = int(total_time/dt) evolve = np.zeros([tsteps, len(init_wfk)]) mode_evolve = np.zeros([tsteps, len(mapping)]) wfk = init_wfk energies = np.zeros(tsteps) #Store first time step in mode_evolve evolve[0] = np.multiply(np.conj(wfk), wfk) for i in range(0, len(mapping)): wfk_sum = 0. norm = 0. print("Mapping: ", mapping[i]) for j in mapping[i]: print(evolve[0][j]) wfk_sum += evolve[0][j] mode_evolve[0][i] = wfk_sum energies[0] = wfk_energy(wfk, hamiltonian) norm = np.sum(mode_evolve[0]) mode_evolve[0][:] = mode_evolve[0][:] / norm #print('wfk_sum: ',wfk_sum,' norm: ',norm) #print('Variance: ',get_variance(wfk, hamiltonian) ) #Now do time evolution print(mode_evolve[0]) times = np.arange(0., total_time, dt) for t in range(1, tsteps): wfk = np.dot(t_operator, wfk) evolve[t] = np.multiply(np.conj(wfk), wfk) #print(evolve[t]) energies[t] = wfk_energy(wfk, hamiltonian) for i in range(0, len(mapping)): norm = 0. wfk_sum = 0. for j in mapping[i]: wfk_sum += evolve[t][j] mode_evolve[t][i] = wfk_sum norm = np.sum(mode_evolve[t]) mode_evolve[t][:] = mode_evolve[t][:] / norm #Return time evolution return mode_evolve, energies evolution2, engs2 = sys_evolve(states_list, wfk_full, t, U, classical_total_time, classical_time_step) print(evolution2) #print(engs2) colors = list(mcolors.TABLEAU_COLORS.keys()) fig2, ax2 = plt.subplots(figsize=(20,10)) for i in range(3): #Create string label strup = "Site "+str(i+1)+r'$\uparrow$' strdwn = "Site "+str(i+1)+r'$\downarrow$' ax2.plot(times, evolution2[:,i], linestyle='-', color=str(colors[i]), linewidth=2, label=strup) ax2.plot(times, evolution2[:,i+3], linestyle='--', color=str(colors[i]), linewidth=2, label=strdwn) plt.legend() #print(evolution[10]) #H = np.array([[0., -t, 0.],[-t, 0., -t],[0., -t, 0.]]) #print(np.dot(np.conj(evolution[10]), np.dot(H, evolution[10]))) print(engs[0]) plt.plot(times, engs) plt.xlabel('Time') plt.ylabel('Energy') #Save data import json fname = './data/classical_010101.json' data = {'times': list(times)} for i in range(3): key1 = 'site_'+str(i)+'_up' key2 = 'site_'+str(i)+'_down' data[key1] = list(evolution2[:,i]) data[key2] = list(evolution2[:,i+3]) with open(fname, 'w') as fp: json.dump(data, fp, indent=4) #Create plots of the processed data fig2, ax2 = plt.subplots(figsize=(20,10)) colors = list(mcolors.TABLEAU_COLORS.keys()) cos = np.cos(np.sqrt(2)*times)**2 sit1 = "Site "+str(1)+r'$\uparrow$' sit2 = "Site "+str(2)+r'$\uparrow$' sit3 = "Site "+str(3)+r'$\uparrow$' #ax2.plot(times, evolution[:,0], marker='.', color='k', linewidth=2, label=sit1) #ax2.plot(times, evolution[:,1], marker='.', color=str(colors[0]), linewidth=2, label=sit2) #ax2.plot(times, evolution[:,2], marker='.', color=str(colors[1]), linewidth=1.5, label=sit3) #ax2.plot(times, cos, label='cosdat') #ax2.plot(times, np.zeros(len(times))) for i in range(3): #Create string label strup = "Site "+str(i+1)+r'$\uparrow$' strdwn = "Site "+str(i+1)+r'$\downarrow$' ax2.plot(times, evolution[:,i], linestyle='-', color=str(colors[i]), linewidth=2, label=strup) ax2.plot(times, evolution[:,i+3], linestyle='--', color=str(colors[i]), linewidth=2, label=strdwn) #ax2.set_ylim(0, 1.) ax2.set_xlim(0, classical_total_time) #ax2.set_xlim(0, 1.) ax2.set_xticks(np.arange(0,classical_total_time, 0.2)) #ax2.set_yticks(np.arange(0,1.1, 0.05)) ax2.tick_params(labelsize=16) ax2.set_title('Time Evolution of 3 Site One Dimensional Chain', fontsize=22) ax2.set_xlabel('Time', fontsize=24) ax2.set_ylabel('Probability', fontsize=24) ax2.legend(fontsize=20) #Try by constructing the matrix and finding the eigenvalues N = 3 Nup = 2 Ndwn = N - Nup t = 1. U = 2. #Check if two states are different by a single hop def hop(psii, psij): #Check spin down hopp = 0 if psii[0]==psij[0]: #Create array of indices with nonzero values indi = np.nonzero(psii[1])[0] indj = np.nonzero(psij[1])[0] for i in range(len(indi)): if abs(indi[i]-indj[i])==1: hopp = -t return hopp #Check spin up if psii[1]==psij[1]: indi = np.nonzero(psii[0])[0] indj = np.nonzero(psij[0])[0] for i in range(len(indi)): if abs(indi[i]-indj[i])==1: hopp = -t return hopp return hopp #On-site terms def repel(l,state): if state[0][l]==1 and state[1][l]==1: return state else: return [] #States for 3 electrons with net spin up states = [ [[1,1,0],[1,0,0]], [[1,1,0],[0,1,0]], [[1,1,0], [0,0,1]], [[1,0,1],[1,0,0]], [[1,0,1],[0,1,0]], [[1,0,1], [0,0,1]], [[0,1,1],[1,0,0]], [[0,1,1],[0,1,0]], [[0,1,1], [0,0,1]] ] #States for 2 electrons in singlet state #states = [ [[1,0,0],[1,0,0]], [[1,0,0],[0,1,0]], [[1,0,0],[0,0,1]], # [[0,1,0],[1,0,0]], [[0,1,0],[0,1,0]], [[0,1,0],[0,0,1]], # [[0,0,1],[1,0,0]], [[0,0,1],[0,1,0]], [[0,0,1],[0,0,1]] ] #States for a single electron states = [ [[1,0,0],[0,0,0]], [[0,1,0],[0,0,0]], [[0,0,1],[0,0,0]] ] H = np.zeros((len(states),len(states)) ) #Construct Hamiltonian matrix for i in range(len(states)): psi_i = states[i] for j in range(len(states)): psi_j = states[j] if j==i: for l in range(0,N): if psi_i == repel(l,psi_j): H[i,j] = U break else: H[i,j] = hop(psi_i, psi_j) print(H) results = la.eig(H) print() for i in range(len(results[0])): print('Eigenvalue: ',results[0][i]) print('Eigenvector: \n',results[1][i]) print('Norm: ', np.linalg.norm(results[1][i])) print('Density Matrix: ') print(np.outer(results[1][i],results[1][i])) print() dens_ops = [] eigs = [] for vec in results[1]: dens_ops.append(np.outer(results[1][i],results[1][i])) eigs.append(results[0][i]) print(dens_ops) dt = 0.01 tsteps = 450 times = np.arange(0., tsteps*dt, dt) t_op = la.expm(-1j*H*dt) #print(np.subtract(np.identity(len(H)), dt*H*1j)) #print(t_op) wfk = [0., 0., 0., 0., 1., 0., 0., 0., 0.] wfk = [0., 0., 0., 0., 1.0, 0., 0., 0., 0.] #2 electron initial state evolve = np.zeros([tsteps, len(wfk)]) mode_evolve = np.zeros([tsteps, 6]) evolve[0] = wfk #Figure out how to generalize this later #'''[[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8]] mode_evolve[0][0] = (evolve[0][0]+evolve[0][1]+evolve[0][2]) /2. mode_evolve[0][1] = (evolve[0][3]+evolve[0][4]+evolve[0][5]) /2. mode_evolve[0][2] = (evolve[0][6]+evolve[0][7]+evolve[0][8]) /2. mode_evolve[0][3] = (evolve[0][0]+evolve[0][3]+evolve[0][6]) /2. mode_evolve[0][4] = (evolve[0][1]+evolve[0][4]+evolve[0][7]) /2. mode_evolve[0][5] = (evolve[0][2]+evolve[0][5]+evolve[0][8]) /2. ''' mode_evolve[0][0] = (evolve[0][0]+evolve[0][1]+evolve[0][2]+evolve[0][3]+evolve[0][4]+evolve[0][5]) /3. mode_evolve[0][1] = (evolve[0][0]+evolve[0][1]+evolve[0][2]+evolve[0][6]+evolve[0][7]+evolve[0][8]) /3. mode_evolve[0][2] = (evolve[0][3]+evolve[0][4]+evolve[0][5]+evolve[0][6]+evolve[0][7]+evolve[0][8]) /3. mode_evolve[0][3] = (evolve[0][0]+evolve[0][3]+evolve[0][6]) /3. mode_evolve[0][4] = (evolve[0][1]+evolve[0][4]+evolve[0][7]) /3. mode_evolve[0][5] = (evolve[0][2]+evolve[0][5]+evolve[0][8]) /3. ''' print(mode_evolve[0]) #Define density matrices for t in range(1, tsteps): #t_op = la.expm(-1j*H*t) wfk = np.dot(t_op, wfk) evolve[t] = np.multiply(np.conj(wfk), wfk) norm = np.sum(evolve[t]) #print(evolve[t]) #Store data in modes rather than basis defined in 'states' variable #''' #Procedure for two electrons mode_evolve[t][0] = (evolve[t][0]+evolve[t][1]+evolve[t][2]) / (2) mode_evolve[t][1] = (evolve[t][3]+evolve[t][4]+evolve[t][5]) / (2) mode_evolve[t][2] = (evolve[t][6]+evolve[t][7]+evolve[t][8]) / (2) mode_evolve[t][3] = (evolve[t][0]+evolve[t][3]+evolve[t][6]) / (2) mode_evolve[t][4] = (evolve[t][1]+evolve[t][4]+evolve[t][7]) / (2) mode_evolve[t][5] = (evolve[t][2]+evolve[t][5]+evolve[t][8]) / (2) ''' mode_evolve[t][0] = (evolve[t][0]+evolve[t][1]+evolve[t][2]+evolve[t][3]+evolve[t][4]+evolve[t][5]) /3. mode_evolve[t][1] = (evolve[t][0]+evolve[t][1]+evolve[t][2]+evolve[t][6]+evolve[t][7]+evolve[t][8]) /3. mode_evolve[t][2] = (evolve[t][3]+evolve[t][4]+evolve[t][5]+evolve[t][6]+evolve[t][7]+evolve[t][8]) /3. mode_evolve[t][3] = (evolve[t][0]+evolve[t][3]+evolve[t][6]) /3. mode_evolve[t][4] = (evolve[t][1]+evolve[t][4]+evolve[t][7]) /3. mode_evolve[t][5] = (evolve[t][2]+evolve[t][5]+evolve[t][8]) /3. print(mode_evolve[t]) ''' #print(np.linalg.norm(evolve[t])) #print(len(evolve[:,0]) ) #print(len(times)) #print(evolve[:,0]) #print(min(evolve[:,0])) #Create plots of the processed data fig2, ax2 = plt.subplots(figsize=(20,10)) colors = list(mcolors.TABLEAU_COLORS.keys()) cos = np.cos(np.sqrt(2)*times)**2 sit1 = "Site "+str(1)+r'$\uparrow$' sit2 = "Site "+str(2)+r'$\uparrow$' sit3 = "Site "+str(3)+r'$\uparrow$' #ax2.plot(times, evolve[:,0], marker='.', color='k', linewidth=2, label=sit1) #ax2.plot(times, evolve[:,1], marker='.', color=str(colors[0]), linewidth=2, label=sit2) #ax2.plot(times, evolve[:,2], marker='.', color=str(colors[1]), linewidth=1.5, label=sit3) #ax2.plot(times, cos, label='cosdat') #ax2.plot(times, np.zeros(len(times))) for i in range(3): #Create string label strup = "Site "+str(i+1)+r'$\uparrow$' strdwn = "Site "+str(i+1)+r'$\downarrow$' ax2.plot(times, mode_evolve[:,i], linestyle='-', color=str(colors[i]), linewidth=2, label=strup) ax2.plot(times, mode_evolve[:,i+3], linestyle='--', color=str(colors[i]), linewidth=2, label=strdwn) #ax2.set_ylim(0, 1.) ax2.set_xlim(0, tsteps*dt+dt/2.) #ax2.set_xlim(0, 1.) ax2.set_xticks(np.arange(0,tsteps*dt+dt, 0.2)) #ax2.set_yticks(np.arange(0,1.1, 0.05)) ax2.tick_params(labelsize=16) ax2.set_title('Time Evolution of 3 Site One Dimensional Chain', fontsize=22) ax2.set_xlabel('Time', fontsize=24) ax2.set_ylabel('Probability', fontsize=24) ax2.legend(fontsize=20) dt = 0.1 tsteps = 50 times = np.arange(0., tsteps*dt, dt) t_op = la.expm(-1j*H*dt) #print(np.subtract(np.identity(len(H)), dt*H*1j)) #print(t_op) #wfk = [0., 1., 0., 0., .0, 0., 0., 0., 0.] #Half-filling initial state wfk0 = [0., 0., 0., 0., 1.0, 0., 0., 0., 0.] #2 electron initial state #wfk0 = [0., 1., 0.] #1 electron initial state evolve = np.zeros([tsteps, len(wfk0)]) mode_evolve = np.zeros([tsteps, 6]) evolve[0] = wfk0 #Figure out how to generalize this later #''' mode_evolve[0][0] = (evolve[0][0]+evolve[0][1]+evolve[0][2]) /2. mode_evolve[0][1] = (evolve[0][3]+evolve[0][4]+evolve[0][5]) /2. mode_evolve[0][2] = (evolve[0][6]+evolve[0][7]+evolve[0][8]) /2. mode_evolve[0][3] = (evolve[0][0]+evolve[0][3]+evolve[0][6]) /2. mode_evolve[0][4] = (evolve[0][1]+evolve[0][4]+evolve[0][7]) /2. mode_evolve[0][5] = (evolve[0][2]+evolve[0][5]+evolve[0][8]) /2. ''' mode_evolve[0][0] = (evolve[0][0]+evolve[0][1]+evolve[0][2]+evolve[0][3]+evolve[0][4]+evolve[0][5]) /3. mode_evolve[0][1] = (evolve[0][0]+evolve[0][1]+evolve[0][2]+evolve[0][6]+evolve[0][7]+evolve[0][8]) /3. mode_evolve[0][2] = (evolve[0][3]+evolve[0][4]+evolve[0][5]+evolve[0][6]+evolve[0][7]+evolve[0][8]) /3. mode_evolve[0][3] = (evolve[0][0]+evolve[0][3]+evolve[0][6]) /3. mode_evolve[0][4] = (evolve[0][1]+evolve[0][4]+evolve[0][7]) /3. mode_evolve[0][5] = (evolve[0][2]+evolve[0][5]+evolve[0][8]) /3. #''' #Define density matrices for t in range(1, tsteps): t_op = la.expm(-1j*H*t*dt) wfk = np.dot(t_op, wfk0) evolve[t] = np.multiply(np.conj(wfk), wfk) norm = np.sum(evolve[t]) print(evolve[t]) #Store data in modes rather than basis defined in 'states' variable #''' #Procedure for two electrons mode_evolve[t][0] = (evolve[t][0]+evolve[t][1]+evolve[t][2]) / (2) mode_evolve[t][1] = (evolve[t][3]+evolve[t][4]+evolve[t][5]) / (2) mode_evolve[t][2] = (evolve[t][6]+evolve[t][7]+evolve[t][8]) / (2) mode_evolve[t][3] = (evolve[t][0]+evolve[t][3]+evolve[t][6]) / (2) mode_evolve[t][4] = (evolve[t][1]+evolve[t][4]+evolve[t][7]) / (2) mode_evolve[t][5] = (evolve[t][2]+evolve[t][5]+evolve[t][8]) / (2) #Procedure for half-filling ''' mode_evolve[t][0] = (evolve[t][0]+evolve[t][1]+evolve[t][2]+evolve[t][3]+evolve[t][4]+evolve[t][5]) /3. mode_evolve[t][1] = (evolve[t][0]+evolve[t][1]+evolve[t][2]+evolve[t][6]+evolve[t][7]+evolve[t][8]) /3. mode_evolve[t][2] = (evolve[t][3]+evolve[t][4]+evolve[t][5]+evolve[t][6]+evolve[t][7]+evolve[t][8]) /3. mode_evolve[t][3] = (evolve[t][0]+evolve[t][3]+evolve[t][6]) /3. mode_evolve[t][4] = (evolve[t][1]+evolve[t][4]+evolve[t][7]) /3. mode_evolve[t][5] = (evolve[t][2]+evolve[t][5]+evolve[t][8]) /3. #''' #print(mode_evolve[t]) #print(np.linalg.norm(evolve[t])) #print(len(evolve[:,0]) ) #print(len(times)) #print(evolve[:,0]) #print(min(evolve[:,0])) #Create plots of the processed data fig2, ax2 = plt.subplots(figsize=(20,10)) colors = list(mcolors.TABLEAU_COLORS.keys()) cos = np.cos(np.sqrt(2)*times)**2 sit1 = "Site "+str(1)+r'$\uparrow$' sit2 = "Site "+str(2)+r'$\uparrow$' sit3 = "Site "+str(3)+r'$\uparrow$' #ax2.plot(times, evolve[:,0], marker='.', color='k', linewidth=2, label=sit1) #ax2.plot(times, evolve[:,1], marker='.', color=str(colors[0]), linewidth=2, label=sit2) #ax2.plot(times, evolve[:,2], marker='.', color=str(colors[1]), linewidth=1.5, label=sit3) #ax2.plot(times, cos, label='cosdat') #ax2.plot(times, np.zeros(len(times))) for i in range(3): #Create string label strup = "Site "+str(i+1)+r'$\uparrow$' strdwn = "Site "+str(i+1)+r'$\downarrow$' ax2.plot(times, mode_evolve[:,i], linestyle='-', color=str(colors[i]), linewidth=2, label=strup) ax2.plot(times, mode_evolve[:,i+3], linestyle='--', color=str(colors[i]), linewidth=2, label=strdwn) #ax2.set_ylim(0, 1.) ax2.set_xlim(0, tsteps*dt+dt/2.) #ax2.set_xlim(0, 1.) ax2.set_xticks(np.arange(0,tsteps*dt+dt, 0.2)) #ax2.set_yticks(np.arange(0,1.1, 0.05)) ax2.tick_params(labelsize=16) ax2.set_title('Time Evolution of 3 Site One Dimensional Chain', fontsize=22) ax2.set_xlabel('Time', fontsize=24) ax2.set_ylabel('Probability', fontsize=24) ax2.legend(fontsize=20) #Calculate total energy for 1D Hubbard model of N sites #Number of sites in chain N = 10 Ne = 10 #Filling factor nu = Ne/N #Hamiltonian parameters t = 2.0 #Hopping U = 4.0 #On-site repulsion state = np.zeros(2*N) #Add in space to populate array randomly, but do it by hand for now #Populate Psi n = 0 while n < Ne: site = rand.randint(0,N-1) spin = rand.randint(0,1) if state[site+spin*N]==0: state[site+spin*N] = 1 n+=1 print(state) #Loop over state and gather energy E = 0 ############# ADD UP ENERGY FROM STATE ############# #Add hoppings at edges if state[0]==1: if state[1]==0: E+=t/2. if state[N-1]==0: #Periodic boundary E+=t/2. if state[N]==1: if state[N+1]==0: E+=t/2. if state[-1]==0: E+=t/2. print('Ends of energy are: ',E) for i in range(1,N-1): print('i is: ',i) #Check spin up sites if site is occupied and if electron can hop if state[i]==1: if state[i+1]==0: E+=t/2. if state[i-1]==0: E+=t/2. #Check spin down sites if site is occupied and if electron can hop j = i+N if state[j]==1: if state[j+1]==0: E+=t/2. if state[j-1]==0: E+=t/2. #Check Hubbard repulsion terms for i in range(0,N): if state[i]==1 and state[i+N]==1: E+=U/4. print('Energy is: ',E) print('State is: ',state) #Try by constructing the matrix and finding the eigenvalues N = 3 Nup = 2 Ndwn = N - Nup t = 1.0 U = 2.5 #To generalize, try using permutations function but for now hard code this #Store a list of 2d list of all the states where the 2d list stores the spin-up occupation #and the spin down occupation states = [ [1,1,0,1,0,0], [1,1,0,0,1,0], [1,1,0,0,0,1], [1,0,1,1,0,0], [1,0,1,0,1,0], [1,0,1,0,0,1], [0,1,1,1,0,0], [0,1,1,0,1,0], [0,1,1,0,0,1] ] print(len(states)) H = np.zeros((len(states),len(states)) ) print(H[0,4]) print(states[0]) for i in range(len(states)): psi_i = states[i] for j in range(len(states)): psi_j = states[j] #Check over sites #Check rest of state for hopping or double occupation for l in range(1,N-1): #Check edges if psi_i[l]==1 and (psi_j[l+1]==1 and psi_i[l+1]==0) or (psi_j[l-1]==1 and psi_i[l-1]==0): H[i,j] = -t/2. break if psi_i[l+N]==1 and (psi_j[l+1+N]==1 and psi_i[l+1+N]==0) or (psi_j[l-1+N]==1 and psi_i[l-1+N]==0): H[i,j] = -t/2. break if psi_i==psi_j: for l in range(N): if psi_i[l]==1 and psi_j[l+N]==1: H[i,j] = U/4. break print(H) tst = [[0,1],[2,3]] print(tst[1][1]) psi_i = [[1,1,0],[1,0,0]] psi_j = [[1,1,0],[0,1,0]] print(psi_j[0]) print(psi_j[1], ' 1st: ',psi_j[1][0], ' 2nd: ',psi_j[1][1], ' 3rd: ',psi_j[1][2]) for l in range(N): print('l: ',l) if psi_j[1][l]==0 and psi_j[1][l-1]==1: psi_j[1][l]=1 psi_j[1][l-1]=0 print('1st') print(psi_j) break if psi_j[1][l-1]==0 and psi_j[1][l]==1: psi_j[1][l-1]=1 psi_j[1][l]=0 print('2nd') print(psi_j) break if psi_j[1][l]==0 and psi_j[1][l+1]==1: psi_j[1][l]=1 psi_j[1][l+1]=0 print('3rd: l=',l,' l+1=',l+1) print(psi_j) break if psi_j[1][l+1]==0 and psi_j[1][l]==1: psi_j[1][l+1]=1 psi_j[1][l]=0 print('4th') print(psi_j) break def hoptst(l,m,spin,state): #Spin is either 0 or 1 which corresponds to which array w/n state we're examining if (state[spin][l]==0 and state[spin][m]==1): state[spin][l]=1 state[spin][m]=0 return state elif (state[spin][m]==0 and state[spin][l]==1): state[spin][m]=1 state[spin][l]=0 return state else: return [] #Try using hoptst: print(hoptst(0,1,1,psi_j)) ### Function to permutate a given list # Python function to print permutations of a given list def permutation(lst): # If lst is empty then there are no permutations if len(lst) == 0: return [] # If there is only one element in lst then, only # one permuatation is possible if len(lst) == 1: return [lst] # Find the permutations for lst if there are # more than 1 characters l = [] # empty list that will store current permutation # Iterate the input(lst) and calculate the permutation for i in range(len(lst)): m = lst[i] # Extract lst[i] or m from the list. remLst is # remaining list remLst = lst[:i] + lst[i+1:] # Generating all permutations where m is first # element for p in permutation(remLst): l.append([m] + p) return l # Driver program to test above function data = list('1000') for p in permutation(data): print(p) import itertools items = [1,0,0] perms = itertools.permutations tst = 15.2 tst = np.full(3, tst) print(tst) H = np.array([[1, 1], [1, -1]]) H_2 = np.tensordot(H,H, 0) print(H_2) print('==============================') M = np.array([[0,1,1,0],[1,1,0,0],[1,0,1,0],[0,0,0,1]]) print(M) print(np.dot(np.conj(M.T),M))
https://github.com/kaelynj/Qiskit-HubbardModel
kaelynj
%matplotlib inline import sys sys.path.append('./src') # Importing standard Qiskit libraries and configuring account #from qiskit import QuantumCircuit, execute, Aer, IBMQ #from qiskit.compiler import transpile, assemble #from qiskit.tools.jupyter import * #from qiskit.visualization import * import matplotlib.pyplot as plt import matplotlib.colors as mcolors import numpy as np import ClassicalHubbardEvolutionChain as chc import FullClassicalHubbardEvolutionChain as fhc import random as rand import scipy.linalg as la numsites = 3 states_list = fhc.get_states(numsites) hamil = fhc.get_hamiltonian(states_list, 1.0, 2.0) print(hamil) eigval, eigvec = la.eig(hamil) #Attempt to get trotter error def XX(theta): theta2 = theta / 2 cos = np.cos(theta2) isin = 1j * np.sin(theta2) return np.array([[cos, 0, 0, -isin], [0, cos, -isin, 0], [0, -isin, cos, 0], [-isin, 0, 0, cos]]) def YY(theta): cos = np.cos(theta / 2) isin = 1j * np.sin(theta / 2) return np.array([[cos, 0, 0, isin], [0, cos, -isin, 0], [0, -isin, cos, 0], [isin, 0, 0, cos]]) def ZZ(theta): itheta2 = 1j * float(theta) / 2 return np.array( [ [np.exp(-itheta2), 0, 0, 0], [0, np.exp(itheta2), 0, 0], [0, 0, np.exp(itheta2), 0], [0, 0, 0, np.exp(-itheta2)], ]) def Z(theta): itheta2 = 1j * float(theta)/2 return np.array([np.exp(-itheta2), 0], [0, np.exp(itehta2)]) t = 6.0 trotter_steps = np.arange(2,50,2) U_over_t = 2.0 I = np.array([[1., 0.], [0., 1.]]) X = np.array([[0., 1.], [1., 0.]]) Y = np.array([[0., -1.j], [1.j, 0.]]) Z = np.array([[1., 0.],[0., -1.]]) for N in trotter_steps: delta = t/N H0_trot = np.tensordot(I, np.tensordot(ZZ(delta), I, axes=0), axes=0) H1_trot = np.tensordot(XX(delta), np.tensordot(I, I, axes=0), axes=0) H2_trot = np.tensordot(YY(delta), np.tensordot(I, I, axes=0), axes=0) H3_trot = np.tensordot(I, np.tensordot(I, XX(delta), axes=0), axes=0) H4_trot = np.tensordot(I, np.tensordot(I, YY(delta), axes=0), axes=0) H_trot = np.matmul(H3_trot, H4_trot) H_trot = np.matmul(H2_trot, H_trot) H_trot = np.matmul(H1_trot, H_trot) H_trot = np.matmul(H0_trot, H_trot) for step in range(N): H_trot = np.matmul(H_trot, H_trot) H0 = np.tensordot(I, np.tensordot(Z, np.tensordot(Z, I, axes=0), axes=0), axes=0) H1 = np.tensordot(X, np.tensordot(X, np.tensordot(I, I, axes=0), axes=0), axes=0) H2 = np.tensordot(Y, np.tensordot(Y, np.tensordot(I, I, axes=0), axes=0), axes=0) H3 = np.tensordot(I, np.tensordot(I, np.tensordot(X, X, axes=0), axes=0), axes=0) H4 = np.tensordot(I, np.tensordot(I, np.tensordot(Y, Y, axes=0), axes=0), axes=0) H = H0 + H1 + H2 + H3 + H4 true_unitary = np.expm(-1j*H*t) diff = np.linalg.norm(true_unitary - H_trot) print("Trotter Steps: ", N, " Error: ",diff) print(eigval) #System parameters numsites = 3 t = 1.0 U = 2. classical_time_step = 0.01 classical_total_time = 500*0.01 times = np.arange(0., classical_total_time, classical_time_step) states_list = fhc.get_states(numsites) #Create full Hamiltonian wfk_full = np.zeros(len(states_list)) #wfk_full[18] = 1. #010010 wfk_full[21] = 1. #010101 #wfk_full[2] = 1. #000010 evolution2, engs2, wfks = fhc.sys_evolve(states_list, wfk_full, t, U, classical_total_time, classical_time_step) print(wfks[10]) print(evolution2) #print(engs2) colors = list(mcolors.TABLEAU_COLORS.keys()) fig2, ax2 = plt.subplots(figsize=(20,10)) for i in range(3): #Create string label strup = "Site "+str(i+1)+r'$\uparrow$' strdwn = "Site "+str(i+1)+r'$\downarrow$' ax2.plot(times, evolution2[:,i], linestyle='-', color=str(colors[i]), linewidth=2, label=strup) ax2.plot(times, evolution2[:,i+3], linestyle='--', color=str(colors[i]), linewidth=2, label=strdwn) plt.legend() def get_bin(x, n=0): """ Get the binary representation of x. Parameters: x (int), n (int, number of digits)""" binry = format(x, 'b').zfill(n) sup = list( reversed( binry[0:int(len(binry)/2)] ) ) sdn = list( reversed( binry[int(len(binry)/2):len(binry)] ) ) return format(x, 'b').zfill(n) #==== Create all Possible States for given system size ===# states_list = [] nsite = 3 for state in range(0, 2**(2*nsite)): state_bin = get_bin(state, 2*nsite) state_list = [[],[]] for mode in range(0,nsite): state_list[0].append(int(state_bin[mode])) state_list[1].append(int(state_bin[mode+nsite])) #print(state_list) states_list.append(state_list) def repel(l,state): if state[0][l]==1 and state[1][l]==1: return state else: return [] #Check if two states are different by a single hop def hop(psii, psij, hopping): #Check spin down hopp = 0 if psii[0]==psij[0]: #Create array of indices with nonzero values hops = [] for site in range(len(psii[0])): if psii[1][site] != psij[1][site]: hops.append(site) if len(hops)==2 and np.sum(psii[1]) == np.sum(psij[1]): if hops[1]-hops[0]==1: hopp = -hopping return hopp #Check spin up if psii[1]==psij[1]: hops = [] for site in range(len(psii[1])): if psii[0][site] != psij[0][site]: hops.append(site) if len(hops)==2 and np.sum(psii[0])==np.sum(psij[0]): if hops[1]-hops[0]==1: hopp = -hopping return hopp return hopp def get_hamiltonian(states, t, U): H = np.zeros((len(states),len(states)) ) #Construct Hamiltonian matrix for i in range(len(states)): psi_i = states[i] for j in range(i, len(states)): psi_j = states[j] if j==i: for l in range(0,len(states[0][0])): if psi_i == repel(l,psi_j): H[i,j] = U break else: #print('psi_i: ',psi_i,' psi_j: ',psi_j) H[i,j] = hop(psi_i, psi_j, t) H[j,i] = H[i,j] return H def get_mapping(states): num_sites = len(states[0][0]) mode_list = [] for i in range(0,2*num_sites): index_list = [] for state_index in range(0,len(states)): state = states[state_index] #Check spin-up modes if i < num_sites: if state[0][i]==1: index_list.append(state_index) #Check spin-down modes else: if state[1][i-num_sites]==1: index_list.append(state_index) if index_list: mode_list.append(index_list) return mode_list def wfk_energy(wfk, hamil): eng = np.dot(np.conj(wfk), np.dot(hamil, wfk)) return eng def get_variance(wfk, h): h_squared = np.matmul(h, h) eng_squared = np.vdot(wfk, np.dot(h_squared, wfk)) squared_eng = np.vdot(wfk, np.dot(h, wfk)) var = np.sqrt(eng_squared - squared_eng) return var def sys_evolve(states, init_wfk, hopping, repulsion, total_time, dt): hamiltonian = get_hamiltonian(states, hopping, repulsion) t_operator = la.expm(-1j*hamiltonian*dt) wavefunctions = [] mapping = get_mapping(states) #print(mapping) #Initalize system tsteps = int(total_time/dt) evolve = np.zeros([tsteps, len(init_wfk)]) mode_evolve = np.zeros([tsteps, len(mapping)]) wfk = init_wfk wavefunctions.append(np.ndarray.tolist(wfk)) energies = np.zeros(tsteps) #Store first time step in mode_evolve evolve[0] = np.multiply(np.conj(wfk), wfk) for i in range(0, len(mapping)): wfk_sum = 0. norm = 0. for j in mapping[i]: wfk_sum += evolve[0][j] norm += evolve[0][j] if norm == 0.: norm = 1. mode_evolve[0][i] = wfk_sum #/ norm #print('wfk_sum: ',wfk_sum,' norm: ',norm) energies[0] = wfk_energy(wfk, hamiltonian) #print('Variance: ',get_variance(wfk, hamiltonian) ) #Now do time evolution print(mode_evolve[0]) times = np.arange(0., total_time, dt) for t in range(1, tsteps): wfk = np.dot(t_operator, wfk) evolve[t] = np.multiply(np.conj(wfk), wfk) wavefunctions.append(np.ndarray.tolist(wfk)) #print(evolve[t]) energies[t] = wfk_energy(wfk, hamiltonian ) for i in range(0, len(mapping)): norm = 0. wfk_sum = 0. for j in mapping[i]: wfk_sum += evolve[t][j] norm += evolve[t][j] #print('wfk_sum: ',wfk_sum,' norm: ',norm) if norm == 0.: norm = 1. mode_evolve[t][i] = wfk_sum #/ norm #print(mode_evolve[t]) #Return time evolution return mode_evolve, energies, wavefunctions #System parameters t = 1.0 U = 2. classical_time_step = 0.01 classical_total_time = 500*0.01 times = np.arange(0., classical_total_time, classical_time_step) #Create full Hamiltonian wfk_full = np.zeros(len(states_list)) #wfk_full[18] = 1. #010010 wfk_full[21] = 1. #010101 #wfk_full[2] = 1. #000010 evolution2, engs2, wfks = sys_evolve(states_list, wfk_full, t, U, classical_total_time, classical_time_step) print(wfks[10]) print(evolution2) #print(engs2) colors = list(mcolors.TABLEAU_COLORS.keys()) fig2, ax2 = plt.subplots(figsize=(20,10)) for i in range(3): #Create string label strup = "Site "+str(i+1)+r'$\uparrow$' strdwn = "Site "+str(i+1)+r'$\downarrow$' ax2.plot(times, evolution2[:,i], linestyle='-', color=str(colors[i]), linewidth=2, label=strup) ax2.plot(times, evolution2[:,i+3], linestyle='--', color=str(colors[i]), linewidth=2, label=strdwn) plt.legend()
https://github.com/kaelynj/Qiskit-HubbardModel
kaelynj
%matplotlib inline # Importing standard Qiskit libraries and configuring account from qiskit import QuantumCircuit, execute, Aer, IBMQ, BasicAer, QuantumRegister, ClassicalRegister from qiskit.compiler import transpile, assemble from qiskit.quantum_info import Operator from qiskit.tools.monitor import job_monitor from qiskit.tools.jupyter import * from qiskit.visualization import * import random as rand import scipy.linalg as la provider = IBMQ.load_account() import matplotlib.pyplot as plt import matplotlib.colors as mcolors import numpy as np from matplotlib import rcParams rcParams['text.usetex'] = True def reverse_list(s): temp_list = list(s) temp_list.reverse() return ''.join(temp_list) #Useful tool for converting an integer to a binary bit string def get_bin(x, n=0): """ Get the binary representation of x. Parameters: x (int), n (int, number of digits)""" binry = format(x, 'b').zfill(n) sup = list( reversed( binry[0:int(len(binry)/2)] ) ) sdn = list( reversed( binry[int(len(binry)/2):len(binry)] ) ) return format(x, 'b').zfill(n) #return ''.join(sup)+''.join(sdn) '''The task here is now to define a function which will either update a given circuit with a time-step or return a single gate which contains all the necessary components of a time-step''' #==========Needed Functions=============# #Function to apply a full set of time evolution gates to a given circuit def qc_evolve(qc, numsite, time, hop, U, trotter_steps): #Compute angles for the onsite and hopping gates # based on the model parameters t, U, and dt theta = hop*time/(2*trotter_slices) phi = U*time/(trotter_slices) numq = 2*numsite y_hop = Operator([[np.cos(theta), 0, 0, -1j*np.sin(theta)], [0, np.cos(theta), 1j*np.sin(theta), 0], [0, 1j*np.sin(theta), np.cos(theta), 0], [-1j*np.sin(theta), 0, 0, np.cos(theta)]]) x_hop = Operator([[np.cos(theta), 0, 0, 1j*np.sin(theta)], [0, np.cos(theta), 1j*np.sin(theta), 0], [0, 1j*np.sin(theta), np.cos(theta), 0], [1j*np.sin(theta), 0, 0, np.cos(theta)]]) z_onsite = Operator([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, np.exp(1j*phi)]]) #Loop over each time step needed and apply onsite and hopping gates for trot in range(trotter_steps): #Onsite Terms for i in range(0, numsite): qc.unitary(z_onsite, [i,i+numsite], label="Z_Onsite") #Add barrier to separate onsite from hopping terms qc.barrier() #Hopping terms for i in range(0,numsite-1): #Spin-up chain qc.unitary(y_hop, [i,i+1], label="YHop") qc.unitary(x_hop, [i,i+1], label="Xhop") #Spin-down chain qc.unitary(y_hop, [i+numsite, i+1+numsite], label="Xhop") qc.unitary(x_hop, [i+numsite, i+1+numsite], label="Xhop") #Add barrier after finishing the time step qc.barrier() #Measure the circuit for i in range(numq): qc.measure(i, i) #Function to run the circuit and store the counts for an evolution with # num_steps number of time steps. def sys_evolve(nsites, excitations, total_time, dt, hop, U, trotter_steps): #Check for correct data types if not isinstance(nsites, int): raise TypeError("Number of sites should be int") if np.isscalar(excitations): raise TypeError("Initial state should be list or numpy array") if not np.isscalar(total_time): raise TypeError("Evolution time should be scalar") if not np.isscalar(dt): raise TypeError("Time step should be scalar") if not np.isscalar(hop): raise TypeError("Hopping term should be scalar") if not np.isscalar(U): raise TypeError("Repulsion term should be scalar") if not isinstance(trotter_steps, int): raise TypeError("Number of trotter slices should be int") numq = 2*nsites num_steps = int(total_time/dt) print('Num Steps: ',num_steps) print('Total Time: ', total_time) data = np.zeros((2**numq, num_steps)) for t_step in range(0, num_steps): #Create circuit with t_step number of steps q = QuantumRegister(numq) c = ClassicalRegister(numq) qcirc = QuantumCircuit(q,c) #=========USE THIS REGION TO SET YOUR INITIAL STATE============== #Initialize circuit by setting the occupation to # a spin up and down electron in the middle site #qcirc.x(int(nsites/2)) #qcirc.x(nsites+int(nsites/2)) for flip in excitations: qcirc.x(flip) #if nsites==3: #Half-filling #qcirc.x(1) # qcirc.x(4) # qcirc.x(0) # qcirc.x(2) #1 electron # qcirc.x(1) #=============================================================== qcirc.barrier() #Append circuit with Trotter steps needed qc_evolve(qcirc, nsites, t_step*dt, hop, U, trotter_steps) #Choose provider and backend provider = IBMQ.get_provider() #backend = Aer.get_backend('statevector_simulator') backend = Aer.get_backend('qasm_simulator') #backend = provider.get_backend('ibmq_qasm_simulator') #backend = provider.get_backend('ibmqx4') #backend = provider.get_backend('ibmqx2') #backend = provider.get_backend('ibmq_16_melbourne') shots = 8192 max_credits = 10 #Max number of credits to spend on execution job_exp = execute(qcirc, backend=backend, shots=shots, max_credits=max_credits) job_monitor(job_exp) result = job_exp.result() counts = result.get_counts(qcirc) print(result.get_counts(qcirc)) print("Job: ",t_step+1, " of ", num_steps," complete.") #Store results in data array and normalize them for i in range(2**numq): if counts.get(get_bin(i,numq)) is None: dat = 0 else: dat = counts.get(get_bin(i,numq)) data[i,t_step] = dat/shots return data #==========Set Parameters of the System=============# dt = 0.25 #Delta t T = 4.5 time_steps = int(T/dt) t = 1.0 #Hopping parameter U = 2. #On-Site repulsion #time_steps = 10 nsites = 3 trotter_slices = 5 initial_state = np.array([1,4]) #Run simulation run_results = sys_evolve(nsites, initial_state, T, dt, t, U, trotter_slices) #print(True if np.isscalar(initial_state) else False) #Process and plot data '''The procedure here is, for each fermionic mode, add the probability of every state containing that mode (at a given time step), and renormalize the data based on the total occupation of each mode. Afterwards, plot the data as a function of time step for each mode.''' proc_data = np.zeros((2*nsites, time_steps)) timesq = np.arange(0.,time_steps*dt, dt) #Sum over time steps for t in range(time_steps): #Sum over all possible states of computer for i in range(2**(2*nsites)): #num = get_bin(i, 2*nsite) num = ''.join( list( reversed(get_bin(i,2*nsites)) ) ) #For each state, check which mode(s) it contains and add them for mode in range(len(num)): if num[mode]=='1': proc_data[mode,t] += run_results[i,t] #Renormalize these sums so that the total occupation of the modes is 1 norm = 0.0 for mode in range(len(num)): norm += proc_data[mode,t] proc_data[:,t] = proc_data[:,t] / norm ''' At this point, proc_data is a 2d array containing the occupation of each mode, for every time step ''' #Create plots of the processed data fig2, ax2 = plt.subplots(figsize=(20,10)) colors = list(mcolors.TABLEAU_COLORS.keys()) for i in range(nsites): #Create string label strup = "Site "+str(i+1)+r'$\uparrow$' strdwn = "Site "+str(i+1)+r'$\downarrow$' ax2.plot(timesq, proc_data[i,:], marker="^", color=str(colors[i]), label=strup) ax2.plot(timesq, proc_data[i+nsites,:], marker="v", color=str(colors[i]), label=strdwn) #ax2.set_ylim(0, 0.55) ax2.set_xlim(0, time_steps*dt+dt/2.) #ax2.set_xticks(np.arange(0,time_steps*dt+dt, 0.2)) #ax2.set_yticks(np.arange(0,0.55, 0.05)) ax2.tick_params(labelsize=16) ax2.set_title('Time Evolution of 3 Site One Dimensional Chain', fontsize=22) ax2.set_xlabel('Time', fontsize=24) ax2.set_ylabel('Probability', fontsize=24) ax2.legend(fontsize=20) #Plot the raw data as a colormap xticks = np.arange(2**(nsite*2)) xlabels=[] print("Time Steps: ",time_steps, " Step Size: ",dt) for i in range(2**(nsite*2)): xlabels.append(get_bin(i,6)) fig, ax = plt.subplots(figsize=(10,20)) c = ax.pcolor(run_results, cmap='binary') ax.set_title('Time Evolution of 3 Site One Dimensional Chain', fontsize=22) plt.yticks(xticks, xlabels, size=18) ax.set_xlabel('Time Step', fontsize=22) ax.set_ylabel('State', fontsize=26) plt.show() #Try by constructing the matrix and finding the eigenvalues N = 3 Nup = 2 Ndwn = N - Nup t = 1.0 U = 2. #Check if two states are different by a single hop def hop(psii, psij): #Check spin down hopp = 0 if psii[0]==psij[0]: #Create array of indices with nonzero values indi = np.nonzero(psii[1])[0] indj = np.nonzero(psij[1])[0] for i in range(len(indi)): if abs(indi[i]-indj[i])==1: hopp = -t return hopp #Check spin up if psii[1]==psij[1]: indi = np.nonzero(psii[0])[0] indj = np.nonzero(psij[0])[0] for i in range(len(indi)): if abs(indi[i]-indj[i])==1: hopp = -t return hopp return hopp #On-site terms def repel(l,state): if state[0][l]==1 and state[1][l]==1: return state else: return [] #States for 3 electrons with net spin up ''' states = [ [[1,1,0],[1,0,0]], [[1,1,0],[0,1,0]], [[1,1,0], [0,0,1]], [[1,0,1],[1,0,0]], [[1,0,1],[0,1,0]], [[1,0,1], [0,0,1]], [[0,1,1],[1,0,0]], [[0,1,1],[0,1,0]], [[0,1,1], [0,0,1]] ] #States for 2 electrons in singlet state ''' states = [ [[1,0,0],[1,0,0]], [[1,0,0],[0,1,0]], [[1,0,0],[0,0,1]], [[0,1,0],[1,0,0]], [[0,1,0],[0,1,0]], [[0,1,0],[0,0,1]], [[0,0,1],[1,0,0]], [[0,0,1],[0,1,0]], [[0,0,1],[0,0,1]] ] #''' #States for a single electron #states = [ [[1,0,0],[0,0,0]], [[0,1,0],[0,0,0]], [[0,0,1],[0,0,0]] ] #''' H = np.zeros((len(states),len(states)) ) #Construct Hamiltonian matrix for i in range(len(states)): psi_i = states[i] for j in range(len(states)): psi_j = states[j] if j==i: for l in range(0,N): if psi_i == repel(l,psi_j): H[i,j] = U break else: H[i,j] = hop(psi_i, psi_j) print(H) results = la.eig(H) print() for i in range(len(results[0])): print('Eigenvalue: ',results[0][i]) print('Eigenvector: \n',results[1][i]) print() dens_ops = [] eigs = [] for vec in results[1]: dens_ops.append(np.outer(results[1][i],results[1][i])) eigs.append(results[0][i]) print(dens_ops) dt = 0.1 tsteps = 50 times = np.arange(0., tsteps*dt, dt) t_op = la.expm(-1j*H*dt) #print(np.subtract(np.identity(len(H)), dt*H*1j)) #print(t_op) #wfk = [0., 0., 0., 0., 1., 0., 0., 0., 0.] #Half-filling initial state wfk = [0., 0., 0., 0., 1.0, 0., 0., 0., 0.] #2 electron initial state #wfk = [0., 1., 0.] #1 electron initial state evolve = np.zeros([tsteps, len(wfk)]) mode_evolve = np.zeros([tsteps, 6]) evolve[0] = wfk #Figure out how to generalize this later #''' mode_evolve[0][0] = (evolve[0][0]+evolve[0][1]+evolve[0][2]) /2. mode_evolve[0][1] = (evolve[0][3]+evolve[0][4]+evolve[0][5]) /2. mode_evolve[0][2] = (evolve[0][6]+evolve[0][7]+evolve[0][8]) /2. mode_evolve[0][3] = (evolve[0][0]+evolve[0][3]+evolve[0][6]) /2. mode_evolve[0][4] = (evolve[0][1]+evolve[0][4]+evolve[0][7]) /2. mode_evolve[0][5] = (evolve[0][2]+evolve[0][5]+evolve[0][8]) /2. ''' mode_evolve[0][0] = (evolve[0][0]+evolve[0][1]+evolve[0][2]+evolve[0][3]+evolve[0][4]+evolve[0][5]) /3. mode_evolve[0][1] = (evolve[0][0]+evolve[0][1]+evolve[0][2]+evolve[0][6]+evolve[0][7]+evolve[0][8]) /3. mode_evolve[0][2] = (evolve[0][3]+evolve[0][4]+evolve[0][5]+evolve[0][6]+evolve[0][7]+evolve[0][8]) /3. mode_evolve[0][3] = (evolve[0][0]+evolve[0][3]+evolve[0][6]) /3. mode_evolve[0][4] = (evolve[0][1]+evolve[0][4]+evolve[0][7]) /3. mode_evolve[0][5] = (evolve[0][2]+evolve[0][5]+evolve[0][8]) /3. #''' print(mode_evolve[0]) #Define density matrices for t in range(1, tsteps): #t_op = la.expm(-1j*H*t) wfk = np.dot(t_op, wfk) evolve[t] = np.multiply(np.conj(wfk), wfk) norm = np.sum(evolve[t]) #print(evolve[t]) #Store data in modes rather than basis defined in 'states' variable #Procedure for two electrons mode_evolve[t][0] = (evolve[t][0]+evolve[t][1]+evolve[t][2]) / (2) mode_evolve[t][1] = (evolve[t][3]+evolve[t][4]+evolve[t][5]) / (2) mode_evolve[t][2] = (evolve[t][6]+evolve[t][7]+evolve[t][8]) / (2) mode_evolve[t][3] = (evolve[t][0]+evolve[t][3]+evolve[t][6]) / (2) mode_evolve[t][4] = (evolve[t][1]+evolve[t][4]+evolve[t][7]) / (2) mode_evolve[t][5] = (evolve[t][2]+evolve[t][5]+evolve[t][8]) / (2) ''' #Procedure for half-filling mode_evolve[t][0] = (evolve[t][0]+evolve[t][1]+evolve[t][2]+evolve[t][3]+evolve[t][4]+evolve[t][5]) /3. mode_evolve[t][1] = (evolve[t][0]+evolve[t][1]+evolve[t][2]+evolve[t][6]+evolve[t][7]+evolve[t][8]) /3. mode_evolve[t][2] = (evolve[t][3]+evolve[t][4]+evolve[t][5]+evolve[t][6]+evolve[t][7]+evolve[t][8]) /3. mode_evolve[t][3] = (evolve[t][0]+evolve[t][3]+evolve[t][6]) /3. mode_evolve[t][4] = (evolve[t][1]+evolve[t][4]+evolve[t][7]) /3. mode_evolve[t][5] = (evolve[t][2]+evolve[t][5]+evolve[t][8]) /3. #''' print(mode_evolve[t]) #print(np.linalg.norm(evolve[t])) #print(len(evolve[:,0]) ) #print(len(times)) #print(evolve[:,0]) #print(min(evolve[:,0])) #Create plots of the processed data fig2, ax2 = plt.subplots(figsize=(20,10)) colors = list(mcolors.TABLEAU_COLORS.keys()) sit1 = "Exact Site "+str(1)+r'$\uparrow$' sit2 = "Exact Site "+str(2)+r'$\uparrow$' sit3 = "Exact Site "+str(3)+r'$\uparrow$' #ax2.plot(times, evolve[:,0], linestyle='--', color=colors[0], linewidth=2.5, label=sit1) #ax2.plot(times, evolve[:,1], linestyle='--', color=str(colors[1]), linewidth=2.5, label=sit2) #ax2.plot(times, evolve[:,2], linestyle='--', color=str(colors[2]), linewidth=2., label=sit3) #ax2.plot(times, np.zeros(len(times))) for i in range(nsites): #Create string label strupq = "Quantum Site "+str(i+1)+r'$\uparrow$' strdwnq = "Quantum Site "+str(i+1)+r'$\downarrow$' strup = "Numerical Site "+str(i+1)+r'$\uparrow$' strdwn = "Numerical Site "+str(i+1)+r'$\downarrow$' ax2.scatter(timesq, proc_data[i,:], marker="*", color=str(colors[i]), label=strupq) #ax2.scatter(timesq, proc_data[i+nsite,:], marker="v", color=str(colors[i]), label=strdwnq) ax2.plot(times, mode_evolve[:,i], linestyle='-', color=str(colors[i]), linewidth=2, label=strup) ax2.plot(times, mode_evolve[:,i+3], linestyle='--', color=str(colors[i]), linewidth=2, label=strdwn) #ax2.plot(times, evolve[:,i], linestyle='-', color=str(colors[i]), linewidth=2, label=strup) #ax2.plot(times, evolve[:,i+3], linestyle='--', color=str(colors[i]), linewidth=2, label=strdwn) ax2.set_ylim(0, .51) ax2.set_xlim(0, tsteps*dt+dt/2.) #ax2.set_xticks(np.arange(0,tsteps*dt+dt, 2*dt)) #ax2.set_yticks(np.arange(0,0.5, 0.05)) ax2.tick_params(labelsize=16) ax2.set_title('Time Evolution of 2 Electrons in 3 Site Chain', fontsize=22) ax2.set_xlabel('Time', fontsize=24) ax2.set_ylabel('Probability', fontsize=24) #ax2.legend(fontsize=20)
https://github.com/kaelynj/Qiskit-HubbardModel
kaelynj
%matplotlib inline # Importing standard Qiskit libraries and configuring account from qiskit import QuantumCircuit, execute, Aer, IBMQ, BasicAer, QuantumRegister, ClassicalRegister from qiskit.compiler import transpile, assemble from qiskit.quantum_info import Operator from qiskit.tools.monitor import job_monitor from qiskit.tools.jupyter import * from qiskit.visualization import * import random as rand import scipy.linalg as la provider = IBMQ.load_account() import matplotlib.pyplot as plt import matplotlib.colors as mcolors import numpy as np from matplotlib import rcParams rcParams['text.usetex'] = True def reverse_list(s): temp_list = list(s) temp_list.reverse() return ''.join(temp_list) #Useful tool for converting an integer to a binary bit string def get_bin(x, n=0): """ Get the binary representation of x. Parameters: x (int), n (int, number of digits)""" binry = format(x, 'b').zfill(n) sup = list( reversed( binry[0:int(len(binry)/2)] ) ) sdn = list( reversed( binry[int(len(binry)/2):len(binry)] ) ) return format(x, 'b').zfill(n) #return ''.join(sup)+''.join(sdn) '''The task here is now to define a function which will either update a given circuit with a time-step or return a single gate which contains all the necessary components of a time-step''' #==========Set Parameters of the System=============# dt = 0.2 #Delta t t = 1.0 #Hopping parameter U = 2. #On-Site repulsion time_steps = 30 nsite = 3 trotter_slices = 5 #==========Needed Functions=============# #Function to apply a full set of time evolution gates to a given circuit def qc_evolve(qc, numsite, dt, t, U, num_steps): #Compute angles for the onsite and hopping gates # based on the model parameters t, U, and dt theta = t*dt/(2*trotter_slices) phi = U*dt/(trotter_slices) numq = 2*numsite y_hop = Operator([[np.cos(theta), 0, 0, -1j*np.sin(theta)], [0, np.cos(theta), 1j*np.sin(theta), 0], [0, 1j*np.sin(theta), np.cos(theta), 0], [-1j*np.sin(theta), 0, 0, np.cos(theta)]]) x_hop = Operator([[np.cos(theta), 0, 0, 1j*np.sin(theta)], [0, np.cos(theta), 1j*np.sin(theta), 0], [0, 1j*np.sin(theta), np.cos(theta), 0], [1j*np.sin(theta), 0, 0, np.cos(theta)]]) z_onsite = Operator([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, np.exp(1j*phi)]]) #Loop over each time step needed and apply onsite and hopping gates for step in range(num_steps): for trot in range(trotter_slices): #Onsite Terms for i in range(0, numsite): qc.unitary(z_onsite, [i,i+numsite], label="Z_Onsite") #Add barrier to separate onsite from hopping terms qc.barrier() #Hopping terms for i in range(0,numsite-1): #Spin-up chain qc.unitary(y_hop, [i,i+1], label="YHop") qc.unitary(x_hop, [i,i+1], label="Xhop") #Spin-down chain qc.unitary(y_hop, [i+numsite, i+1+numsite], label="Xhop") qc.unitary(x_hop, [i+numsite, i+1+numsite], label="Xhop") #Add barrier after finishing the time step qc.barrier() #Measure the circuit for i in range(numq): qc.measure(i, i) #Function to run the circuit and store the counts for an evolution with # num_steps number of time steps. def sys_evolve(nsites, dt, t, U, num_steps): numq = 2*nsites data = np.zeros((2**numq, num_steps)) for t_step in range(0, num_steps): #Create circuit with t_step number of steps q = QuantumRegister(numq) c = ClassicalRegister(numq) qcirc = QuantumCircuit(q,c) #Initialize circuit by setting the occupation to # a spin up and down electron in the middle site #=========I TURNED THIS OFF FOR A SPECIFIC CASE============== #qcirc.x(int(nsites/2)) #qcirc.x(nsites+int(nsites/2)) # if nsites==3: #Half-filling # qcirc.x(1) # qcirc.x(4) # qcirc.x(0) #1 electron qcirc.x(1) #=======USE THE REGION ABOVE TO SET YOUR INITIAL STATE======= qcirc.barrier() #Append circuit with Trotter steps needed qc_evolve(qcirc, nsites, dt, t, U, t_step) #Choose provider and backend provider = IBMQ.get_provider() #backend = Aer.get_backend('statevector_simulator') backend = Aer.get_backend('qasm_simulator') #backend = provider.get_backend('ibmq_qasm_simulator') #backend = provider.get_backend('ibmqx4') #backend = provider.get_backend('ibmqx2') #backend = provider.get_backend('ibmq_16_melbourne') shots = 8192 max_credits = 10 #Max number of credits to spend on execution job_exp = execute(qcirc, backend=backend, shots=shots, max_credits=max_credits) job_monitor(job_exp) result = job_exp.result() counts = result.get_counts(qcirc) print(result.get_counts(qcirc)) print("Job: ",t_step+1, " of ", time_steps," complete.") #Store results in data array and normalize them for i in range(2**numq): if counts.get(get_bin(i,numq)) is None: dat = 0 else: dat = counts.get(get_bin(i,numq)) data[i,t_step] = dat/shots return data #Run simulation run_results = sys_evolve(nsite, dt, t, U, time_steps) #Process and plot data '''The procedure here is, for each fermionic mode, add the probability of every state containing that mode (at a given time step), and renormalize the data based on the total occupation of each mode. Afterwards, plot the data as a function of time step for each mode.''' proc_data = np.zeros((2*nsite, time_steps)) timesq = np.arange(0.,time_steps*dt, dt) #Sum over time steps for t in range(time_steps): #Sum over all possible states of computer for i in range(2**(2*nsite)): #num = get_bin(i, 2*nsite) num = ''.join( list( reversed(get_bin(i,2*nsite)) ) ) #For each state, check which mode(s) it contains and add them for mode in range(len(num)): if num[mode]=='1': proc_data[mode,t] += run_results[i,t] #Renormalize these sums so that the total occupation of the modes is 1 norm = 0.0 for mode in range(len(num)): norm += proc_data[mode,t] proc_data[:,t] = proc_data[:,t] / norm ''' At this point, proc_data is a 2d array containing the occupation of each mode, for every time step ''' #Create plots of the processed data fig2, ax2 = plt.subplots(figsize=(20,10)) colors = list(mcolors.TABLEAU_COLORS.keys()) for i in range(nsite): #Create string label strup = "Site "+str(i+1)+r'$\uparrow$' strdwn = "Site "+str(i+1)+r'$\downarrow$' ax2.plot(timesq, proc_data[i,:], marker="^", color=str(colors[i]), label=strup) ax2.plot(timesq, proc_data[i+nsite,:], marker="v", color=str(colors[i]), label=strdwn) #ax2.set_ylim(0, 0.55) ax2.set_xlim(0, time_steps*dt+dt/2.) #ax2.set_xticks(np.arange(0,time_steps*dt+dt, 0.2)) #ax2.set_yticks(np.arange(0,0.55, 0.05)) ax2.tick_params(labelsize=16) ax2.set_title('Time Evolution of 3 Site One Dimensional Chain', fontsize=22) ax2.set_xlabel('Time', fontsize=24) ax2.set_ylabel('Probability', fontsize=24) ax2.legend(fontsize=20) #Plot the raw data as a colormap xticks = np.arange(2**(nsite*2)) xlabels=[] print("Time Steps: ",time_steps, " Step Size: ",dt) for i in range(2**(nsite*2)): xlabels.append(get_bin(i,6)) fig, ax = plt.subplots(figsize=(10,20)) c = ax.pcolor(run_results, cmap='binary') ax.set_title('Time Evolution of 3 Site One Dimensional Chain', fontsize=22) plt.yticks(xticks, xlabels, size=18) ax.set_xlabel('Time Step', fontsize=22) ax.set_ylabel('State', fontsize=26) plt.show() #Try by constructing the matrix and finding the eigenvalues N = 3 Nup = 2 Ndwn = N - Nup t = 1.0 U = 2. #Check if two states are different by a single hop def hop(psii, psij): #Check spin down hopp = 0 if psii[0]==psij[0]: #Create array of indices with nonzero values indi = np.nonzero(psii[1])[0] indj = np.nonzero(psij[1])[0] for i in range(len(indi)): if abs(indi[i]-indj[i])==1: hopp = -t return hopp #Check spin up if psii[1]==psij[1]: indi = np.nonzero(psii[0])[0] indj = np.nonzero(psij[0])[0] for i in range(len(indi)): if abs(indi[i]-indj[i])==1: hopp = -t return hopp return hopp #On-site terms def repel(l,state): if state[0][l]==1 and state[1][l]==1: return state else: return [] #States for 3 electrons with net spin up ''' states = [ [[1,1,0],[1,0,0]], [[1,1,0],[0,1,0]], [[1,1,0], [0,0,1]], [[1,0,1],[1,0,0]], [[1,0,1],[0,1,0]], [[1,0,1], [0,0,1]], [[0,1,1],[1,0,0]], [[0,1,1],[0,1,0]], [[0,1,1], [0,0,1]] ] #States for 2 electrons in singlet state ''' states = [ [[1,0,0],[1,0,0]], [[1,0,0],[0,1,0]], [[1,0,0],[0,0,1]], [[0,1,0],[1,0,0]], [[0,1,0],[0,1,0]], [[0,1,0],[0,0,1]], [[0,0,1],[1,0,0]], [[0,0,1],[0,1,0]], [[0,0,1],[0,0,1]] ] #''' #States for a single electron #states = [ [[1,0,0],[0,0,0]], [[0,1,0],[0,0,0]], [[0,0,1],[0,0,0]] ] #''' H = np.zeros((len(states),len(states)) ) #Construct Hamiltonian matrix for i in range(len(states)): psi_i = states[i] for j in range(len(states)): psi_j = states[j] if j==i: for l in range(0,N): if psi_i == repel(l,psi_j): H[i,j] = U break else: H[i,j] = hop(psi_i, psi_j) print(H) results = la.eig(H) print() for i in range(len(results[0])): print('Eigenvalue: ',results[0][i]) print('Eigenvector: \n',results[1][i]) print() dens_ops = [] eigs = [] for vec in results[1]: dens_ops.append(np.outer(results[1][i],results[1][i])) eigs.append(results[0][i]) print(dens_ops) dt = 0.1 tsteps = 50 times = np.arange(0., tsteps*dt, dt) t_op = la.expm(-1j*H*dt) #print(np.subtract(np.identity(len(H)), dt*H*1j)) #print(t_op) wfk = [0., 1., 0., 0., .0, 0., 0., 0., 0.] #Half-filling initial state #wfk = [0., 0., 0., 0., 1.0, 0., 0., 0., 0.] #2 electron initial state #wfk = [0., 1., 0.] #1 electron initial state evolve = np.zeros([tsteps, len(wfk)]) mode_evolve = np.zeros([tsteps, 6]) evolve[0] = wfk #Figure out how to generalize this later #''' mode_evolve[0][0] = (evolve[0][0]+evolve[0][1]+evolve[0][2]) /2. mode_evolve[0][1] = (evolve[0][3]+evolve[0][4]+evolve[0][5]) /2. mode_evolve[0][2] = (evolve[0][6]+evolve[0][7]+evolve[0][8]) /2. mode_evolve[0][3] = (evolve[0][0]+evolve[0][3]+evolve[0][6]) /2. mode_evolve[0][4] = (evolve[0][1]+evolve[0][4]+evolve[0][7]) /2. mode_evolve[0][5] = (evolve[0][2]+evolve[0][5]+evolve[0][8]) /2. ''' mode_evolve[0][0] = (evolve[0][0]+evolve[0][1]+evolve[0][2]+evolve[0][3]+evolve[0][4]+evolve[0][5]) /3. mode_evolve[0][1] = (evolve[0][0]+evolve[0][1]+evolve[0][2]+evolve[0][6]+evolve[0][7]+evolve[0][8]) /3. mode_evolve[0][2] = (evolve[0][3]+evolve[0][4]+evolve[0][5]+evolve[0][6]+evolve[0][7]+evolve[0][8]) /3. mode_evolve[0][3] = (evolve[0][0]+evolve[0][3]+evolve[0][6]) /3. mode_evolve[0][4] = (evolve[0][1]+evolve[0][4]+evolve[0][7]) /3. mode_evolve[0][5] = (evolve[0][2]+evolve[0][5]+evolve[0][8]) /3. ''' print(mode_evolve[0]) #Define density matrices for t in range(1, tsteps): #t_op = la.expm(-1j*H*t) wfk = np.dot(t_op, wfk) evolve[t] = np.multiply(np.conj(wfk), wfk) norm = np.sum(evolve[t]) #print(evolve[t]) #Store data in modes rather than basis defined in 'states' variable #''' #Procedure for two electrons mode_evolve[t][0] = (evolve[t][0]+evolve[t][1]+evolve[t][2]) / (2) mode_evolve[t][1] = (evolve[t][3]+evolve[t][4]+evolve[t][5]) / (2) mode_evolve[t][2] = (evolve[t][6]+evolve[t][7]+evolve[t][8]) / (2) mode_evolve[t][3] = (evolve[t][0]+evolve[t][3]+evolve[t][6]) / (2) mode_evolve[t][4] = (evolve[t][1]+evolve[t][4]+evolve[t][7]) / (2) mode_evolve[t][5] = (evolve[t][2]+evolve[t][5]+evolve[t][8]) / (2) ''' #Procedure for half-filling mode_evolve[t][0] = (evolve[t][0]+evolve[t][1]+evolve[t][2]+evolve[t][3]+evolve[t][4]+evolve[t][5]) /3. mode_evolve[t][1] = (evolve[t][0]+evolve[t][1]+evolve[t][2]+evolve[t][6]+evolve[t][7]+evolve[t][8]) /3. mode_evolve[t][2] = (evolve[t][3]+evolve[t][4]+evolve[t][5]+evolve[t][6]+evolve[t][7]+evolve[t][8]) /3. mode_evolve[t][3] = (evolve[t][0]+evolve[t][3]+evolve[t][6]) /3. mode_evolve[t][4] = (evolve[t][1]+evolve[t][4]+evolve[t][7]) /3. mode_evolve[t][5] = (evolve[t][2]+evolve[t][5]+evolve[t][8]) /3. #''' print(mode_evolve[t]) #print(np.linalg.norm(evolve[t])) #print(len(evolve[:,0]) ) #print(len(times)) #print(evolve[:,0]) #print(min(evolve[:,0])) #Create plots of the processed data fig2, ax2 = plt.subplots(figsize=(20,10)) colors = list(mcolors.TABLEAU_COLORS.keys()) sit1 = "Exact Site "+str(1)+r'$\uparrow$' sit2 = "Exact Site "+str(2)+r'$\uparrow$' sit3 = "Exact Site "+str(3)+r'$\uparrow$' #ax2.plot(times, evolve[:,0], linestyle='--', color=colors[0], linewidth=2.5, label=sit1) #ax2.plot(times, evolve[:,1], linestyle='--', color=str(colors[1]), linewidth=2.5, label=sit2) #ax2.plot(times, evolve[:,2], linestyle='--', color=str(colors[2]), linewidth=2., label=sit3) #ax2.plot(times, np.zeros(len(times))) for i in range(nsite): #Create string label strupq = "Quantum Site "+str(i+1)+r'$\uparrow$' strdwnq = "Quantum Site "+str(i+1)+r'$\downarrow$' strup = "Numerical Site "+str(i+1)+r'$\uparrow$' strdwn = "Numerical Site "+str(i+1)+r'$\downarrow$' #ax2.plot(timesq, proc_data[i,:], marker="*", color=str(colors[i]), markersize=5, label=strupq) #ax2.plot(timesq, proc_data[i+nsite,:], marker="v", color=str(colors[i]), markersize=5, label=strdwnq) ax2.plot(times, mode_evolve[:,i], linestyle='-', color=str(colors[i]), linewidth=2, label=strup) ax2.plot(times, mode_evolve[:,i+3], linestyle='--', color=str(colors[i]), linewidth=2, label=strdwn) #ax2.plot(times, evolve[:,i], linestyle='-', color=str(colors[i]), linewidth=2, label=strup) #ax2.plot(times, evolve[:,i+3], linestyle='--', color=str(colors[i]), linewidth=2, label=strdwn) ax2.set_ylim(0, .5) ax2.set_xlim(0, tsteps*dt+dt/2.) ax2.set_xticks(np.arange(0,tsteps*dt+dt, 2*dt)) ax2.set_yticks(np.arange(0,0.5, 0.05)) ax2.tick_params(labelsize=16) ax2.set_title('Time Evolution of 2 Electrons in 3 Site Chain', fontsize=22) ax2.set_xlabel('Time', fontsize=24) ax2.set_ylabel('Probability', fontsize=24) ax2.legend(fontsize=20)
https://github.com/kaelynj/Qiskit-HubbardModel
kaelynj
#Jupyter notebook to check if imports work correctly %matplotlib inline import sys sys.path.append('./src') import HubbardEvolutionChain as hc import ClassicalHubbardEvolutionChain as chc from qiskit import QuantumCircuit, execute, Aer, IBMQ, BasicAer, QuantumRegister, ClassicalRegister from qiskit.compiler import transpile, assemble from qiskit.quantum_info import Operator from qiskit.tools.monitor import job_monitor from qiskit.tools.jupyter import * import qiskit.visualization as qvis import random as rand import scipy.linalg as la provider = IBMQ.load_account() import matplotlib.pyplot as plt import matplotlib.colors as mcolors import numpy as np from matplotlib import rcParams rcParams['text.usetex'] = True def get_bin(x, n=0): """ Get the binary representation of x. Parameters: x (int), n (int, number of digits)""" binry = format(x, 'b').zfill(n) sup = list( reversed( binry[0:int(len(binry)/2)] ) ) sdn = list( reversed( binry[int(len(binry)/2):len(binry)] ) ) return format(x, 'b').zfill(n) #Energy Measurement Functions #Measure the total repulsion from circuit run def measure_repulsion(U, num_sites, results, shots): repulsion = 0. #Figure out how to include different hoppings later for state in results: for i in range( int( len(state)/2 ) ): if state[i]=='1': if state[i+num_sites]=='1': repulsion += U*results.get(state)/shots return repulsion def measure_hopping(hopping, pairs, circuit, num_qubits): #Add diagonalizing circuit for pair in pairs: circuit.cnot(pair[0],pair[1]) circuit.ch(pair[1],pair[0]) circuit.cnot(pair[0],pair[1]) #circuit.measure(pair[0],pair[0]) #circuit.measure(pair[1],pair[1]) circuit.measure_all() #Run circuit backend = Aer.get_backend('qasm_simulator') shots = 8192 max_credits = 10 #Max number of credits to spend on execution #print("Computing Hopping") hop_exp = execute(circuit, backend=backend, shots=shots, max_credits=max_credits) job_monitor(hop_exp) result = hop_exp.result() counts = result.get_counts(circuit) #print(counts) #Compute energy #print(pairs) for pair in pairs: hop_eng = 0. #print('Pair is: ',pair) for state in counts: #print('State is: ',state,' Index at pair[0]: ',num_qubits-1-pair[0],' Val: ',state[num_qubits-pair[0]]) if state[num_qubits-1-pair[0]]=='1': prob_01 = counts.get(state)/shots #print('Check state is: ',state) for comp_state in counts: #print('Comp State is: ',state,' Index at pair[0]: ',num_qubits-1-pair[1],' Val: ',comp_state[num_qubits-pair[0]]) if comp_state[num_qubits-1-pair[1]]=='1': #print('Comp state is: ',comp_state) hop_eng += -hopping*(prob_01 - counts.get(comp_state)/shots) return hop_eng #nsites, excitations, total_time, dt, hop, U, trotter_steps dt = 0.25 #Delta t total_time = 5. #time_steps = int(T/dt) hop = 1.0 #Hopping parameter #t = [1.0, 2.] U = 2. #On-Site repulsion #time_steps = 10 nsites = 3 trotter_steps = 1000 excitations = np.array([1]) numq = 2*nsites num_steps = int(total_time/dt) print('Num Steps: ',num_steps) print('Total Time: ', total_time) data = np.zeros((2**numq, num_steps)) energies = np.zeros(num_steps) for t_step in range(0, num_steps): #Create circuit with t_step number of steps q = QuantumRegister(numq) c = ClassicalRegister(numq) qcirc = QuantumCircuit(q,c) #=========USE THIS REGION TO SET YOUR INITIAL STATE============== #Loop over each excitation for flip in excitations: qcirc.x(flip) #=============================================================== qcirc.barrier() #Append circuit with Trotter steps needed hc.qc_evolve(qcirc, nsites, t_step*dt, hop, U, trotter_steps) #Measure the circuit for i in range(numq): qcirc.measure(i, i) #Choose provider and backend provider = IBMQ.get_provider() #backend = Aer.get_backend('statevector_simulator') backend = Aer.get_backend('qasm_simulator') #backend = provider.get_backend('ibmq_qasm_simulator') #backend = provider.get_backend('ibmqx4') #backend = provider.get_backend('ibmqx2') #backend = provider.get_backend('ibmq_16_melbourne') shots = 8192 max_credits = 10 #Max number of credits to spend on execution job_exp = execute(qcirc, backend=backend, shots=shots, max_credits=max_credits) #job_monitor(job_exp) result = job_exp.result() counts = result.get_counts(qcirc) print(result.get_counts(qcirc)) print("Job: ",t_step+1, " of ", num_steps," computing energy...") #Store results in data array and normalize them for i in range(2**numq): if counts.get(get_bin(i,numq)) is None: dat = 0 else: dat = counts.get(get_bin(i,numq)) data[i,t_step] = dat/shots #======================================================= #Compute energy of system #Compute repulsion energies repulsion_energy = measure_repulsion(U, nsites, counts, shots) print('Repulsion: ', repulsion_energy) #Compute hopping energies #Get list of hopping pairs even_pairs = [] for i in range(0,nsites-1,2): #up_pair = [i, i+1] #dwn_pair = [i+nsites, i+nsites+1] even_pairs.append([i, i+1]) even_pairs.append([i+nsites, i+nsites+1]) odd_pairs = [] for i in range(1,nsites-1,2): odd_pairs.append([i, i+1]) odd_pairs.append([i+nsites, i+nsites+1]) #Start with even hoppings, initialize circuit and find hopping pairs q = QuantumRegister(numq) c = ClassicalRegister(numq) qcirc = QuantumCircuit(q,c) #Loop over each excitation for flip in excitations: qcirc.x(flip) qcirc.barrier() #Append circuit with Trotter steps needed hc.qc_evolve(qcirc, nsites, t_step*dt, hop, U, trotter_steps) '''for pair in odd_pairs: qcirc.cnot(pair[0],pair[1]) qcirc.ch(pair[1],pair[0]) qcirc.cnot(pair[0],pair[1]) qcirc.measure(pair[0],pair[0]) qcirc.measure(pair[1],pair[1]) #circuit.draw() print(t_step) ''' #break even_hopping = measure_hopping(hop, even_pairs, qcirc, numq) print('Even hopping: ', even_hopping) #=============================================================== #Now do the same for the odd hoppings #Start with even hoppings, initialize circuit and find hopping pairs q = QuantumRegister(numq) c = ClassicalRegister(numq) qcirc = QuantumCircuit(q,c) #Loop over each excitation for flip in excitations: qcirc.x(flip) qcirc.barrier() #Append circuit with Trotter steps needed hc.qc_evolve(qcirc, nsites, t_step*dt, hop, U, trotter_steps) odd_hopping = measure_hopping(hop, odd_pairs, qcirc, numq) print('Odd hopping: ',odd_hopping) total_energy = repulsion_energy + even_hopping + odd_hopping print(total_energy) energies[t_step] = total_energy print("Total Energy is: ", total_energy) print("Job: ",t_step+1, " of ", num_steps," complete") #qcirc.draw() plt.plot(energies) print(np.ptp(energies)) #Trotter Steps=1000 plt.plot(energies) print(np.ptp(energies)) #Trotter Steps=100 plt.plot(energies) print(np.ptp(energies)) #Trotter Steps=50 plt.plot(energies) print(np.ptp(energies)) #Trotter Steps=10 plt.plot(energies) print(np.ptp(energies)) #Trotter Steps=100
https://github.com/kaelynj/Qiskit-HubbardModel
kaelynj
''' Code taken from Warren Alphonso's Website discussing the VQE implementation of the FermiHubbard model https://warrenalphonso.github.io/qc/hubbard#VQE ''' from openfermion.hamiltonians import FermiHubbardModel from openfermion.utils import SpinPairs from openfermion.utils import HubbardSquareLattice from openfermioncirq import SwapNetworkTrotterAnsatz #==== Create 2x2 Hubbard Square Lattice ======== # HubbardSquareLattice parameters x_n = 2 y_n = 2 n_dofs = 1 # 1 degree of freedom for spin periodic = 0 # Don't want tunneling terms to loop back around spinless = 0 # Has spin lattice = HubbardSquareLattice(x_n, y_n, n_dofs=n_dofs, periodic=periodic, spinless=spinless) #====== Create FermiHubbardModel Instance from Defined Lattice ========= tunneling = [('neighbor', (0, 0), 1.)] interaction = [('onsite', (0, 0), 2., SpinPairs.DIFF)] potential = [(0, 1.)] # Must be U/2 for half-filling mag_field = 0. particle_hole_sym = False hubbard = FermiHubbardModel(lattice , tunneling_parameters=tunneling, interaction_parameters=interaction, potential_parameters=potential, magnetic_field=mag_field, particle_hole_symmetry=particle_hole_sym) #print(hubbard.hamiltonian()) #Example Adiabatic Evolution for 2x2 Hamiltonian import numpy as np import scipy.linalg as sp import matplotlib.pyplot as plt H_A = np.array( [[1, 0], [0, -1]] ) H_B = np.array( [[0, 1], [1, 0]] ) H = lambda s: (1-s)*H_A + s*H_B psi_A = np.array([0, 1]) # The ground state of H_A # If n=5, then we do 5 steps: H(0), H(0.25), H(0.5), H(0.75), H(1) n = 50 t = 1 res = psi_A s_vals = [] up_eigs = [] dwn_eigs = [] for i in range(n): s = i / (n-1) s_vals.append(s) res = np.dot(sp.expm(-1j * H(s) * t), res) up_eigs.append(sp.eig(H(s))[0][0]) dwn_eigs.append((sp.eig(H(s))[0][1])) plt.plot(s_vals, up_eigs) plt.plot(s_vals, dwn_eigs) plt.ylabel('Eigenvalues') plt.xlabel('s') import sys sys.path.append('./src') import CustomSwapNetworkTrotterAnsatz #from openfermioncirq import SwapNetworkTrotterAnsatz #from CustomSwapNetworkTrotterAnsatz import * steps = 2 #ansatz = CustomSwapNetworkTrotterAnsatz(hubbard, iterations=steps)
https://github.com/kaelynj/Qiskit-HubbardModel
kaelynj
#Jupyter notebook to check if imports work correctly %matplotlib inline import sys sys.path.append('./src') import HubbardEvolutionChain as hc import ClassicalHubbardEvolutionChain as chc import FullClassicalHubbardEvolutionChain as fhc from qiskit import QuantumCircuit, execute, Aer, IBMQ, BasicAer, QuantumRegister, ClassicalRegister from qiskit.compiler import transpile, assemble from qiskit.quantum_info import Operator from qiskit.tools.monitor import job_monitor from qiskit.tools.jupyter import * import qiskit.visualization as qvis import random as rand import scipy.linalg as la provider = IBMQ.load_account() import matplotlib.pyplot as plt import matplotlib.colors as mcolors import numpy as np from matplotlib import rcParams rcParams['text.usetex'] = True def get_bin(x, n=0): """ Get the binary representation of x. Parameters: x (int), n (int, number of digits)""" binry = format(x, 'b').zfill(n) sup = list( reversed( binry[0:int(len(binry)/2)] ) ) sdn = list( reversed( binry[int(len(binry)/2):len(binry)] ) ) return format(x, 'b').zfill(n) #==========Set Parameters of the System=============# dt = 0.25 #Delta t T = 5. time_steps = int(T/dt) t = 1.0 #Hopping parameter #t = [1.0, 2.] U = 2. #On-Site repulsion #time_steps = 10 nsites = 3 trotter_slices = 10 initial_state = np.array([1, 4]) #Run simulation run_results1 = hc.sys_evolve(nsites, initial_state, T, dt, t, U, 10) run_results2 = hc.sys_evolve(nsites, initial_state, T, dt, t, U, 40) run_results3, eng3 = hc.sys_evolve_eng(nsites, initial_state, T, dt, t, U, 60) run_results4 = hc.sys_evolve(nsites, initial_state, T, dt, t, U, 90) #print(True if np.isscalar(initial_state) else False) ''' #Fidelity measurements #run_results1, engs1 = hc.sys_evolve_eng(nsites, initial_state, T, dt, t, U, 10) run_results2 = hc.sys_evolve_den(nsites, initial_state, T, dt, t, U, 40) #run_results3, engs3 = hc.sys_evolve_eng(nsites, initial_state, T, dt, t, U, 100) #run_results4, engs4 = hc.sys_evolve_eng(nsites, initial_state, T, dt, t, U, 150) #Collect data on how Trotter steps change energy range trotter_range = [10, 20, 30, 40, 50, 60, 70, 80] eng_range = [] #engs = [] #runs = [] for trot_step in trotter_range: run_results3, eng3 = hc.sys_evolve_eng(nsites, initial_state, T, dt, t, U, trot_step) runs.append(run_results3[:,-1]) eng_range.append(np.ptp(eng3)) engs.append(eng3) ''' #sample_run = run_results3[:,-1] #print(sample_run) #print(run_results3[:,-1],' ',len(run_results3[:,-1])) #print(tp_run[-1],' ',len(tp_run[-1])) #Plot the raw data as a colormap #xticks = np.arange(2**(nsites*2)) xlabels=[] print("Time Steps: ",time_steps, " Step Size: ",dt) for i in range(2**(nsites*2)): xlabels.append(hc.get_bin(i,6)) fig, ax = plt.subplots(figsize=(10,20)) c = ax.pcolor(np.transpose(runs), cmap='binary') ax.set_title('Basis State Amplitude', fontsize=22) plt.yticks(np.arange(2**(nsites*2)), xlabels, size=18) plt.xticks(np.arange(0,13), trotter_range, size=18) ax.set_xlabel('No. of Trotter Steps', fontsize=22) ax.set_ylabel('State', fontsize=26) plt.show() #plt.plot(trotter_range, eng_range) #plt.xlabel('No. of Trotter Steps', fontsize=18) #plt.ylabel('Energy Range', fontsize=18) proc_data = np.zeros([2*nsites, len(trotter_range)]) runs_array = np.array(runs) for step in range(0,len(trotter_range)): for i in range(0,2**(2*nsites)): num = ''.join( list( reversed(hc.get_bin(i,2*nsites)) ) ) #print('i: ', i,' step: ',step) for mode in range(len(num)): if num[mode]=='1': proc_data[mode, step] += runs_array[step, i] norm = 0. for mode in range(len(num)): norm += proc_data[mode, step] proc_data[:,step] = proc_data[:,step] / norm print(proc_data[0,:]) #============ Run Classical Evolution ==============# #Define our basis states #States for 3 electrons with net spin up ''' states = [ [[1,1,0],[1,0,0]], [[1,1,0],[0,1,0]], [[1,1,0], [0,0,1]], [[1,0,1],[1,0,0]], [[1,0,1],[0,1,0]], [[1,0,1], [0,0,1]], [[0,1,1],[1,0,0]], [[0,1,1],[0,1,0]], [[0,1,1], [0,0,1]] ] ''' #States for 2 electrons in singlet state states = [ [[1,0,0],[1,0,0]], [[1,0,0],[0,1,0]], [[1,0,0],[0,0,1]], [[0,1,0],[1,0,0]], [[0,1,0],[0,1,0]], [[0,1,0],[0,0,1]], [[0,0,1],[1,0,0]], [[0,0,1],[0,1,0]], [[0,0,1],[0,0,1]] ] #''' #States for a single electron #states = [ [[1,0,0],[0,0,0]], [[0,1,0],[0,0,0]], [[0,0,1],[0,0,0]] ] #Possible initial wavefunctions #wfk = [0., 0., 0., 0., 1., 0., 0., 0., 0.] #Half-filling initial state (101010) wfk = [0., 0., 0., 0., 1.0, 0., 0., 0., 0.] #2 electron initial state (010010) #wfk = [0., 0., 0., 0., 0., 1., 0., 0., 0.] #2 electron initial state (010001) #wfk = [0., -1., 0.] #1 electron initial state #System parameters t = 1.0 U = 2. classical_time_step = 0.01 classical_total_time = 500*0.01 times = np.arange(0., classical_total_time, classical_time_step) states = fhc.get_states(numsites) evolution, engs = chc.sys_evolve(states, wfk, t, U, classical_total_time, classical_time_step) print(evolution[-25]) #System parameters t = 1.0 U = 2. classical_time_step = 0.01 classical_total_time = 500*0.01 times = np.arange(0., classical_total_time, classical_time_step) states = fhc.get_states(nsites) #print(states) #print(states[64]) wfk_full = np.zeros(len(states), dtype=np.complex_) target_state = [[0,1], [0,0]] target_index = 0 for l in range(len(states)): if len(target_state) == sum([1 for i, j in zip(target_state, states[l]) if i == j]): print('Target state found at: ',l) target_index = l wfk_full[18] = 1. #010010 #wfk_full[21] = 1. #010101 #wfk_full[42] = 1. #101010 #wfk_full[2] = 1. #000010 #wfk_full[target_index] = 1. #wfk_full[2] = 0.5 - 0.5*1j #wfk_full[0] = 1/np.sqrt(2) print(wfk_full) evolution, engs, wfks = fhc.sys_evolve(states, wfk_full, t, U, classical_total_time, classical_time_step) #print(wfks[-26]) #print(run_results1[-1]) tst = np.outer(np.conj(wfks[-25]),wfks[-25]) #print(times[-25]) #print(np.shape(tst)) def fidelity(numerical_density, quantum_density): sqrt_quantum = la.sqrtm(quantum_density) fidelity_matrix = np.matmul(sqrt_quantum, np.matmul(numerical_density,sqrt_quantum)) fidelity_matrix = la.sqrtm(fidelity_matrix) trace = np.trace(fidelity_matrix) trace2 = np.conj(trace)*trace #Try tr(rho*sigma)+sqrt(det(rho)*det(sigma)) fidelity = np.trace(np.matmul(numerical_density, quantum_density)) + np.sqrt(np.linalg.det(numerical_density)*np.linalg.det(quantum_density)) return fidelity print("Fidelity") print( fidelity( run_results2[-1], tst) ) print('============================') print('Trace') print('Numerical: ',np.trace(tst)) print('Quantum: ',np.trace(run_results2[-1])) print('============================') print('Square Trace') print('Numerical: ',np.trace(np.matmul(tst, tst))) print('Quantum: ',np.trace(np.matmul(run_results2[-1], run_results2[-1]))) print('============================') fidelities = [] fidelities.append(fidelity(tst, run_results1[-1])) fidelities.append(fidelity(tst, run_results2[-1])) fidelities.append(fidelity(tst, run_results3[-1])) fidelities.append(fidelity(tst, run_results4[-1])) trotters = [10, 40, 100, 150] plt.plot(trotters, fidelities) #Calculate RootMeanSquare rms = np.zeros(len(trotter_range)) for trotter_index in range(len(trotter_range)): sq_diff = 0. for mode in range(2*nsites): sq_diff += (evolution[-25, mode] - proc_data[mode, trotter_index])**2 rms[trotter_index] = np.sqrt(sq_diff / 2*nsites) plt.plot(trotter_range, rms) plt.xlabel('Trotter Steps', fontsize=14) plt.ylabel('RMS',fontsize=14) plt.title('RMS for 1 Electrons 010000', fontsize=14) #Create plots of the processed data fig2, ax2 = plt.subplots(figsize=(20,10)) colors = list(mcolors.TABLEAU_COLORS.keys()) for i in range(nsites): #Create string label strup = "Site "+str(i+1)+r'$\uparrow$' strdwn = "Site "+str(i+1)+r'$\downarrow$' ax2.plot(trotter_range, proc_data[i,:], marker="^", color=str(colors[i]), label=strup) ax2.plot(trotter_range, proc_data[i+nsites,:], marker="v", linestyle='--', color=str(colors[i]), label=strdwn) ax2.plot(trotter_range, np.full(len(trotter_range), evolution[-1, i]), linestyle='-', color=str(colors[i]),label=strup) ax2.plot(trotter_range, np.full(len(trotter_range), evolution[-1, i+nsites]), linestyle='-', color=str(colors[i]),label=strdwn) #ax2.set_ylim(0, 0.55) #ax2.set_xlim(0, time_steps*dt+dt/2.) #ax2.set_xticks(np.arange(0,time_steps*dt+dt, 0.2)) #ax2.set_yticks(np.arange(0,0.55, 0.05)) ax2.tick_params(labelsize=16) ax2.set_title('Probability Convergence for 3 electrons', fontsize=22) ax2.set_xlabel('Number of Trotter Steps', fontsize=24) ax2.set_ylabel('Probability', fontsize=24) ax2.legend(fontsize=20) processed_data3 = hc.process_run(nsites, time_steps, dt, run_results3) tdat = np.arange(0.,T, dt) norm_dat = [np.sum(x) for x in np.transpose(processed_data3)] print(norm_dat) print(eng3) #plt.plot(norm_dat) plt.plot(tdat, eng3, label='80 Steps') plt.plot(times, engs, label='Numerical') plt.xlabel('Time', fontsize=18) plt.ylabel('Energy',fontsize=18) plt.ylim(-1e-5, 1e-5) plt.legend() print(np.ptp(eng3)) ## ============ Run Classical Evolution ============== #Define our basis states #States for 3 electrons with net spin up ''' states = [ [[1,1,0],[1,0,0]], [[1,1,0],[0,1,0]], [[1,1,0], [0,0,1]], [[1,0,1],[1,0,0]], [[1,0,1],[0,1,0]], [[1,0,1], [0,0,1]], [[0,1,1],[1,0,0]], [[0,1,1],[0,1,0]], [[0,1,1], [0,0,1]] ] ''' #States for 2 electrons in singlet state states = [ [[1,0,0],[1,0,0]], [[1,0,0],[0,1,0]], [[1,0,0],[0,0,1]], [[0,1,0],[1,0,0]], [[0,1,0],[0,1,0]], [[0,1,0],[0,0,1]], [[0,0,1],[1,0,0]], [[0,0,1],[0,1,0]], [[0,0,1],[0,0,1]] ] #''' #States for a single electron #states = [ [[1,0,0],[0,0,0]], [[0,1,0],[0,0,0]], [[0,0,1],[0,0,0]] ] #Possible initial wavefunctions #wfk = [0., 0., 0., 0., 1., 0., 0., 0., 0.] #Half-filling initial state wfk = [0., 0., 0., 0., 1.0, 0., 0., 0., 0.] #2 electron initial state #wfk = [0., 1., 0.] #1 electron initial state #System parameters for evolving system numerically t = 1.0 U = 2. classical_time_step = 0.01 classical_total_time = 500*0.01 times = np.arange(0., classical_total_time, classical_time_step) evolution, engs = chc.sys_evolve(states, wfk, t, U, classical_total_time, classical_time_step) #Get norms and energies as a function of time. Round to 10^-12 norms = np.array([np.sum(x) for x in evolution]) norms = np.around(norms, 12) engs = np.around(engs, 12) #Create plots of the processed data fig2, ax2 = plt.subplots(figsize=(20,10)) fig3, ax3 = plt.subplots(1, 2, figsize=(20,10)) colors = list(mcolors.TABLEAU_COLORS.keys()) cos = np.cos(np.sqrt(2)*times)**2 sit1 = "Site "+str(1)+r'$\uparrow$' sit2 = "Site "+str(2)+r'$\uparrow$' sit3 = "Site "+str(3)+r'$\uparrow$' #ax2.plot(times, evolve[:,0], marker='.', color='k', linewidth=2, label=sit1) #ax2.plot(times, evolve[:,1], marker='.', color=str(colors[0]), linewidth=2, label=sit2) #ax2.plot(times, evolve[:,2], marker='.', color=str(colors[1]), linewidth=1.5, label=sit3) #ax2.plot(times, cos, label='cosdat') #ax2.plot(times, np.zeros(len(times))) for i in range(3): #Create string label strup = "Site "+str(i+1)+r'$\uparrow$' strdwn = "Site "+str(i+1)+r'$\downarrow$' ax2.plot(times, evolution[:,i], linestyle='-', color=str(colors[i]), linewidth=2, label=strup) ax2.plot(times, evolution[:,i+3], linestyle='--', color=str(colors[i]), linewidth=2, label=strdwn) #ax2.set_ylim(0, 1.) ax2.set_xlim(0, classical_total_time) #ax2.set_xlim(0, 1.) ax2.set_xticks(np.arange(0,classical_total_time, 0.2)) #ax2.set_yticks(np.arange(0,1.1, 0.05)) ax2.tick_params(labelsize=16) ax2.set_title('Time Evolution of 3 Site One Dimensional Chain', fontsize=22) ax2.set_xlabel('Time', fontsize=24) ax2.set_ylabel('Probability', fontsize=24) ax2.legend(fontsize=20) #Plot energy and normalization ax3[0].plot(times, engs, color='b') ax3[1].plot(times, norms, color='r') ax3[0].set_xlabel('Time', fontsize=24) ax3[0].set_ylabel('Energy [t]', fontsize=24) ax3[1].set_xlabel('Time', fontsize=24) ax3[1].set_ylabel('Normalization', fontsize=24) print(evolution) #processed_data1 = hc.process_run(nsites, time_steps, dt, run_results1) #processed_data2 = hc.process_run(nsites, time_steps, dt, run_results2) processed_data3 = hc.process_run(nsites, time_steps, dt, run_results3) #processed_data4 = hc.process_run(nsites, time_steps, dt, run_results4) timesq = np.arange(0, time_steps*dt, dt) #Create plots of the processed data #fig0, ax0 = plt.subplots(figsize=(20,10)) fig1, ax1 = plt.subplots(figsize=(20,10)) fig2, ax2 = plt.subplots(figsize=(20,10)) fig3, ax3 = plt.subplots(figsize=(20,10)) fig4, ax4 = plt.subplots(figsize=(20,10)) fig5, ax5 = plt.subplots(figsize=(20,10)) colors = list(mcolors.TABLEAU_COLORS.keys()) ''' #Plot energies ax0.plot(timesq, eng1, color=str(colors[0]), label='10 Steps') ax0.plot(timesq, eng2, color=str(colors[1]), label='20 Steps') ax0.plot(timesq, eng3, color=str(colors[2]), label='40 Steps') ax0.plot(timesq, eng4, color=str(colors[3]), label='60 Steps') ax0.legend(fontsize=20) ax0.set_xlabel("Time", fontsize=24) ax0.set_ylabel("Total Energy", fontsize=24) ax0.tick_params(labelsize=16) ''' #Site 1 strup = "10 Steps"+r'$\uparrow$' strdwn = "10 Steps"+r'$\downarrow$' #ax1.plot(timesq, processed_data1[0,:], marker="^", color=str(colors[0]), label=strup) #ax1.plot(timesq, processed_data1[0+nsites,:], linestyle='--', marker="v", color=str(colors[0]), label=strdwn) strup = "40 Steps"+r'$\uparrow$' strdwn = "40 Steps"+r'$\downarrow$' #ax1.plot(timesq, processed_data2[0,:], marker="^", color=str(colors[1]), label=strup) #ax1.plot(timesq, processed_data2[0+nsites,:], linestyle='--', marker="v", color=str(colors[1]), label=strdwn) strup = "60 Steps"+r'$\uparrow$' strdwn = "60 Steps"+r'$\downarrow$' ax1.plot(timesq, processed_data3[0,:], marker="^", color=str(colors[2]), label=strup) ax1.plot(timesq, processed_data3[0+nsites,:],linestyle='--', marker="v", color=str(colors[2]), label=strdwn) strup = "100 Steps"+r'$\uparrow$' strdwn = "100 Steps"+r'$\downarrow$' #ax1.plot(timesq, processed_data3[0,:], marker="^", color=str(colors[3]), label=strup) #ax1.plot(timesq, processed_data3[0+nsites,:], linestyle='--', marker="v", color=str(colors[3]), label=strdwn) strup = "Exact"+r'$\uparrow$' strdwn = "Exact"+r'$\downarrow$' #1e numerical evolution ax1.plot(times, evolution[:,0], linestyle='-', color='k', linewidth=2, label=strup) ax1.plot(times, evolution[:,0+nsites], linestyle='--', color='k', linewidth=2, label=strdwn) #2e+ numerical evolution #ax1.plot(times, mode_evolve[:,0], linestyle='-', color='k', linewidth=2, label=strup) #ax1.plot(times, mode_evolve[:,0+nsites], linestyle='--', color='k', linewidth=2, label=strdwn) #Site 2 strup = "10 Steps"+r'$\uparrow$' strdwn = "10 Steps"+r'$\downarrow$' #ax2.plot(timesq, processed_data1[1,:], marker="^", color=str(colors[0]), label=strup) #ax2.plot(timesq, processed_data1[1+nsites,:], marker="v", linestyle='--',color=str(colors[0]), label=strdwn) strup = "40 Steps"+r'$\uparrow$' strdwn = "40 Steps"+r'$\downarrow$' #ax2.plot(timesq, processed_data2[1,:], marker="^", color=str(colors[1]), label=strup) #ax2.plot(timesq, processed_data2[1+nsites,:], marker="v", linestyle='--',color=str(colors[1]), label=strdwn) strup = "60 Steps"+r'$\uparrow$' strdwn = "60 Steps"+r'$\downarrow$' ax2.plot(timesq, processed_data3[1,:], marker="^", color=str(colors[2]), label=strup) ax2.plot(timesq, processed_data3[1+nsites,:], marker="v", linestyle='--', color=str(colors[2]), label=strdwn) strup = "100 Steps"+r'$\uparrow$' strdwn = "100 Steps"+r'$\downarrow$' #ax2.plot(timesq, processed_data4[1,:], marker="^", color=str(colors[3]), label=strup) #ax2.plot(timesq, processed_data4[1+nsites,:], marker="v", linestyle='--', color=str(colors[3]), label=strdwn) #1e numerical evolution strup = "Exact"+r'$\uparrow$' strdwn = "Exact"+r'$\downarrow$' ax2.plot(times, evolution[:,1], linestyle='-', color='k', linewidth=2, label=strup) ax2.plot(times, evolution[:,1+nsites], linestyle='--', color='k', linewidth=2, label=strdwn) #2e+ numerical evolution #ax2.plot(times, mode_evolve[:,1], linestyle='-', color='k', linewidth=2, label=strup) #ax2.plot(times, mode_evolve[:,1+nsites], linestyle='--', color='k', linewidth=2, label=strdwn) #Site 3 strup = "10 Steps"+r'$\uparrow$' strdwn = "10 Steps"+r'$\downarrow$' #ax3.plot(timesq, processed_data1[2,:], marker="^", color=str(colors[0]), label=strup) #ax3.plot(timesq, processed_data1[2+nsites,:], marker="v", linestyle='--', color=str(colors[0]), label=strdwn) strup = "40 Steps"+r'$\uparrow$' strdwn = "40 Steps"+r'$\downarrow$' #ax3.plot(timesq, processed_data2[2,:], marker="^", color=str(colors[1]), label=strup) #ax3.plot(timesq, processed_data2[2+nsites,:], marker="v", linestyle='--', color=str(colors[1]), label=strdwn) strup = "60 Steps"+r'$\uparrow$' strdwn = "60 Steps"+r'$\downarrow$' ax3.plot(timesq, processed_data3[2,:], marker="^", color=str(colors[2]), label=strup) ax3.plot(timesq, processed_data3[2+nsites,:], marker="v", linestyle='--', color=str(colors[2]), label=strdwn) strup = "100 Steps"+r'$\uparrow$' strdwn = "100 Steps"+r'$\downarrow$' #ax3.plot(timesq, processed_data4[2,:], marker="^", color=str(colors[3]), label=strup) #ax3.plot(timesq, processed_data4[2+nsites,:], marker="v", linestyle='--', color=str(colors[3]), label=strdwn) #1e numerical evolution strup = "Exact"+r'$\uparrow$' strdwn = "Exact"+r'$\downarrow$' ax3.plot(times, evolution[:,2], linestyle='-', color='k', linewidth=2, label=strup) ax3.plot(times, evolution[:,2+nsites], linestyle='--', color='k', linewidth=2, label=strdwn) #2e+ numerical evolution #ax3.plot(times, mode_evolve[:,2], linestyle='-', color='k', linewidth=2, label=strup) #ax3.plot(times, mode_evolve[:,2+nsites], linestyle='--', color='k', linewidth=2, label=strdwn) #Site 4 r''' strup = "10 Steps"+r'$\uparrow$' strdwn = "10 Steps"+r'$\downarrow$' #ax4.plot(timesq, processed_data1[3,:], marker="^", color=str(colors[0]), label=strup) #ax4.plot(timesq, processed_data1[3+nsites,:], marker="v", linestyle='--', color=str(colors[0]), label=strdwn) strup = "40 Steps"+r'$\uparrow$' strdwn = "40 Steps"+r'$\downarrow$' #ax4.plot(timesq, processed_data2[3,:], marker="^", color=str(colors[1]), label=strup) #ax4.plot(timesq, processed_data2[3+nsites,:], marker="v", linestyle='--', color=str(colors[1]), label=strdwn) strup = "150 Steps"+r'$\uparrow$' strdwn = "150 Steps"+r'$\downarrow$' ax4.plot(timesq, processed_data3[3,:], marker="^", color=str(colors[2]), label=strup) ax4.plot(timesq, processed_data3[3+nsites,:], marker="v", linestyle='--', color=str(colors[2]), label=strdwn) strup = "100 Steps"+r'$\uparrow$' strdwn = "100 Steps"+r'$\downarrow$' #ax4.plot(timesq, processed_data4[3,:], marker="^", color=str(colors[3]), label=strup) #ax4.plot(timesq, processed_data4[3+nsites,:], marker="v", linestyle='--', color=str(colors[3]), label=strdwn) #1e numerical evolution strup = "Exact"+r'$\uparrow$' strdwn = "Exact"+r'$\downarrow$' ax4.plot(times, evolution[:,3], linestyle='-', color='k', linewidth=2, label=strup) ax4.plot(times, evolution[:,3+nsites], linestyle='--', color='k', linewidth=2, label=strdwn) #2e+ numerical evolution #ax3.plot(times, mode_evolve[:,2], linestyle='-', color='k', linewidth=2, label=strup) #ax3.plot(times, mode_evolve[:,2+nsites], linestyle='--', color='k', linewidth=2, label=strdwn) #Site 5 strup = "10 Steps"+r'$\uparrow$' strdwn = "10 Steps"+r'$\downarrow$' ax5.plot(timesq, processed_data1[4,:], marker="^", color=str(colors[0]), label=strup) ax5.plot(timesq, processed_data1[4+nsites,:], marker="v", linestyle='--', color=str(colors[0]), label=strdwn) strup = "40 Steps"+r'$\uparrow$' strdwn = "40 Steps"+r'$\downarrow$' #ax5.plot(timesq, processed_data2[4,:], marker="^", color=str(colors[1]), label=strup) #ax5.plot(timesq, processed_data2[4+nsites,:], marker="v", linestyle='--', color=str(colors[1]), label=strdwn) strup = "150 Steps"+r'$\uparrow$' strdwn = "150 Steps"+r'$\downarrow$' ax5.plot(timesq, processed_data3[4,:], marker="^", color=str(colors[2]), label=strup) ax5.plot(timesq, processed_data3[4+nsites,:], marker="v", linestyle='--', color=str(colors[2]), label=strdwn) strup = "100 Steps"+r'$\uparrow$' strdwn = "100 Steps"+r'$\downarrow$' #ax5.plot(timesq, processed_data4[4,:], marker="^", color=str(colors[3]), label=strup) #ax5.plot(timesq, processed_data4[4+nsites,:], marker="v", linestyle='--', color=str(colors[3]), label=strdwn) #1e numerical evolution strup = "Exact"+r'$\uparrow$' strdwn = "Exact"+r'$\downarrow$' ax5.plot(times, evolution[:,4], linestyle='-', color='k', linewidth=2, label=strup) ax5.plot(times, evolution[:,4+nsites], linestyle='--', color='k', linewidth=2, label=strdwn) #2e+ numerical evolution #ax3.plot(times, mode_evolve[:,2], linestyle='-', color='k', linewidth=2, label=strup) #ax3.plot(times, mode_evolve[:,2+nsites], linestyle='--', color='k', linewidth=2, label=strdwn) r''' #ax2.set_ylim(0, 0.55) #ax2.set_xlim(0, time_steps*dt+dt/2.) #ax2.set_xticks(np.arange(0,time_steps*dt+dt, 0.2)) #ax2.set_yticks(np.arange(0,0.55, 0.05)) ax1.tick_params(labelsize=16) ax2.tick_params(labelsize=16) ax3.tick_params(labelsize=16) ax4.tick_params(labelsize=16) ax5.tick_params(labelsize=16) ax1.set_title(r"Time Evolution of Site 1: 1/sqrt(2)*000000 + (0.5-0.5i)*0100000", fontsize=22) ax2.set_title(r"Time Evolution of Site 2: 1/sqrt(2)*000000 + (0.5-0.5i)*0100000", fontsize=22) ax3.set_title(r"Time Evolution of Site 3: 1/sqrt(2)*000000 + (0.5-0.5i)*0100000", fontsize=22) ax4.set_title(r"Time Evolution of Site 4: 1/sqrt(2)*000000 + (0.5-0.5i)*0100000", fontsize=22) ax5.set_title(r"Time Evolution of Site 5: 1/sqrt(2)*000000 + (0.5-0.5i)*0100000", fontsize=22) ax1.set_xlabel('Time', fontsize=24) ax2.set_xlabel('Time', fontsize=24) ax3.set_xlabel('Time', fontsize=24) ax4.set_xlabel('Time', fontsize=24) ax5.set_xlabel('Time', fontsize=24) ax1.set_ylabel('Probability', fontsize=24) ax2.set_ylabel('Probability', fontsize=24) ax3.set_ylabel('Probability', fontsize=24) ax4.set_ylabel('Probability', fontsize=24) ax5.set_ylabel('Probability', fontsize=24) ax1.legend(fontsize=20) ax2.legend(fontsize=20) ax3.legend(fontsize=20) ax4.legend(fontsize=20) ax5.legend(fontsize=20) #==== Cell to Implement Energy Measurement Functions ====# def sys_evolve(nsites, excitations, total_time, dt, hop, U, trotter_steps): #Check for correct data types of input if not isinstance(nsites, int): raise TypeError("Number of sites should be int") if np.isscalar(excitations): raise TypeError("Initial state should be list or numpy array") if not np.isscalar(total_time): raise TypeError("Evolution time should be scalar") if not np.isscalar(dt): raise TypeError("Time step should be scalar") if not isinstance(trotter_steps, int): raise TypeError("Number of trotter slices should be int") numq = 2*nsites num_steps = int(total_time/dt) print('Num Steps: ',num_steps) print('Total Time: ', total_time) data = np.zeros((2**numq, num_steps)) energies = np.zeros(num_steps) for t_step in range(0, num_steps): #Create circuit with t_step number of steps q = QuantumRegister(numq) c = ClassicalRegister(numq) qcirc = QuantumCircuit(q,c) #=========USE THIS REGION TO SET YOUR INITIAL STATE============== #Loop over each excitation for flip in excitations: qcirc.x(flip) #=============================================================== qcirc.barrier() #Append circuit with Trotter steps needed hc.qc_evolve(qcirc, nsites, t_step*dt, hop, U, trotter_steps) #Measure the circuit for i in range(numq): qcirc.measure(i, i) #Choose provider and backend provider = IBMQ.get_provider() #backend = Aer.get_backend('statevector_simulator') backend = Aer.get_backend('qasm_simulator') #backend = provider.get_backend('ibmq_qasm_simulator') #backend = provider.get_backend('ibmqx4') #backend = provider.get_backend('ibmqx2') #backend = provider.get_backend('ibmq_16_melbourne') shots = 8192 max_credits = 10 #Max number of credits to spend on execution job_exp = execute(qcirc, backend=backend, shots=shots, max_credits=max_credits) #job_monitor(job_exp) result = job_exp.result() counts = result.get_counts(qcirc) #print(result.get_counts(qcirc)) print("Job: ",t_step+1, " of ", num_steps," computing energy...") #Store results in data array and normalize them for i in range(2**numq): if counts.get(get_bin(i,numq)) is None: dat = 0 else: dat = counts.get(get_bin(i,numq)) data[i,t_step] = dat/shots #======================================================= #Compute energy of system #Compute repulsion energies repulsion_energy = measure_repulsion(U, nsites, counts, shots) #Compute hopping energies #Get list of hopping pairs even_pairs = [] for i in range(0,nsites-1,2): #up_pair = [i, i+1] #dwn_pair = [i+nsites, i+nsites+1] even_pairs.append([i, i+1]) even_pairs.append([i+nsites, i+nsites+1]) odd_pairs = [] for i in range(1,nsites-1,2): odd_pairs.append([i, i+1]) odd_pairs.append([i+nsites, i+nsites+1]) #Start with even hoppings, initialize circuit and find hopping pairs q = QuantumRegister(numq) c = ClassicalRegister(numq) qcirc = QuantumCircuit(q,c) #Loop over each excitation for flip in excitations: qcirc.x(flip) qcirc.barrier() #Append circuit with Trotter steps needed hc.qc_evolve(qcirc, nsites, t_step*dt, hop, U, trotter_steps) even_hopping = measure_hopping(hop, even_pairs, qcirc, numq) #=============================================================== #Now do the same for the odd hoppings #Start with even hoppings, initialize circuit and find hopping pairs q = QuantumRegister(numq) c = ClassicalRegister(numq) qcirc = QuantumCircuit(q,c) #Loop over each excitation for flip in excitations: qcirc.x(flip) qcirc.barrier() #Append circuit with Trotter steps needed hc.qc_evolve(qcirc, nsites, t_step*dt, hop, U, trotter_steps) odd_hopping = measure_hopping(hop, odd_pairs, qcirc, numq) total_energy = repulsion_energy + even_hopping + odd_hopping energies[t_step] = total_energy print("Total Energy is: ", total_energy) print("Job: ",t_step+1, " of ", num_steps," complete") return data, energies #Measure the total repulsion from circuit run def measure_repulsion(U, num_sites, results, shots): repulsion = 0. #Figure out how to include different hoppings later for state in results: for i in range( int( len(state)/2 ) ): if state[i]=='1': if state[i+num_sites]=='1': repulsion += U*results.get(state)/shots return repulsion def measure_hopping(hopping, pairs, circuit, num_qubits): #Add diagonalizing circuit for pair in pairs: circuit.cnot(pair[0],pair[1]) circuit.ch(pair[1],pair[0]) circuit.cnot(pair[0],pair[1]) #circuit.measure(pair[0],pair[0]) #circuit.measure(pair[1],pair[1]) circuit.measure_all() #Run circuit backend = Aer.get_backend('qasm_simulator') shots = 8192 max_credits = 10 #Max number of credits to spend on execution #print("Computing Hopping") hop_exp = execute(circuit, backend=backend, shots=shots, max_credits=max_credits) job_monitor(hop_exp) result = hop_exp.result() counts = result.get_counts(circuit) #print(counts) #Compute energy #print(pairs) for pair in pairs: hop_eng = 0. #print('Pair is: ',pair) for state in counts: #print('State is: ',state,' Index at pair[0]: ',num_qubits-1-pair[0],' Val: ',state[num_qubits-pair[0]]) if state[num_qubits-1-pair[0]]=='1': prob_01 = counts.get(state)/shots #print('Check state is: ',state) for comp_state in counts: #print('Comp State is: ',state,' Index at pair[0]: ',num_qubits-1-pair[1],' Val: ',comp_state[num_qubits-pair[0]]) if comp_state[num_qubits-1-pair[1]]=='1': #print('Comp state is: ',comp_state) hop_eng += -hopping*(prob_01 - counts.get(comp_state)/shots) return hop_eng #Try by constructing the matrix and finding the eigenvalues N = 3 Nup = 2 Ndwn = N - Nup t = 1.0 U = 2. #Check if two states are different by a single hop def hop(psii, psij): #Check spin down hopp = 0 if psii[0]==psij[0]: #Create array of indices with nonzero values indi = np.nonzero(psii[1])[0] indj = np.nonzero(psij[1])[0] for i in range(len(indi)): if abs(indi[i]-indj[i])==1: hopp = -t return hopp #Check spin up if psii[1]==psij[1]: indi = np.nonzero(psii[0])[0] indj = np.nonzero(psij[0])[0] for i in range(len(indi)): if abs(indi[i]-indj[i])==1: hopp = -t return hopp return hopp #On-site terms def repel(l,state): if state[0][l]==1 and state[1][l]==1: return state else: return [] #States for 3 electrons with net spin up ''' states = [ [[1,1,0],[1,0,0]], [[1,1,0],[0,1,0]], [[1,1,0], [0,0,1]], [[1,0,1],[1,0,0]], [[1,0,1],[0,1,0]], [[1,0,1], [0,0,1]], [[0,1,1],[1,0,0]], [[0,1,1],[0,1,0]], [[0,1,1], [0,0,1]] ] ''' #States for 2 electrons in singlet state states = [ [[1,0,0],[1,0,0]], [[1,0,0],[0,1,0]], [[1,0,0],[0,0,1]], [[0,1,0],[1,0,0]], [[0,1,0],[0,1,0]], [[0,1,0],[0,0,1]], [[0,0,1],[1,0,0]], [[0,0,1],[0,1,0]], [[0,0,1],[0,0,1]] ] #''' #States for a single electron states = [ [[1,0,0],[0,0,0]], [[0,1,0],[0,0,0]], [[0,0,1],[0,0,0]] ] #''' H = np.zeros((len(states),len(states)) ) #Construct Hamiltonian matrix for i in range(len(states)): psi_i = states[i] for j in range(len(states)): psi_j = states[j] if j==i: for l in range(0,len(states[0][0])): if psi_i == repel(l,psi_j): H[i,j] = U break else: H[i,j] = hop(psi_i, psi_j) print(H) results = la.eig(H) print() for i in range(len(results[0])): print('Eigenvalue: ',results[0][i]) print('Eigenvector: \n',results[1][i]) print() dens_ops = [] eigs = [] for vec in results[1]: dens_ops.append(np.outer(results[1][i],results[1][i])) eigs.append(results[0][i]) print(dens_ops) #Loop/function to flip through states mode_list = [] num_sites = 3 print(len(states[0][0])) for i in range(0,2*num_sites): index_list = [] for state_index in range(0,len(states)): state = states[state_index] #print(state[0]) #print(state[1]) #Check spin-up modes if i < num_sites: if state[0][i]==1: index_list.append(state_index) #Check spin-down modes else: if state[1][i-num_sites]==1: index_list.append(state_index) if index_list: mode_list.append(index_list) print(mode_list) wfk0 = 1/np.sqrt(2)*results[1][0] - 1/np.sqrt(2)*results[1][2] print(np.dot(np.conj(wfk0), np.dot(H, wfk0))) dtc = 0.01 tsteps = 500 times = np.arange(0., tsteps*dtc, dtc) t_op = la.expm(-1j*H*dtc) #print(np.subtract(np.identity(len(H)), dt*H*1j)) #print(t_op) #wfk = [0., 0., 0., 0., 1., 0., 0., 0., 0.] #Half-filling initial state #wfk = [0., 0., 0., 0., 1.0, 0., 0., 0., 0.] #2 electron initial state wfk = [0., 1., 0.] #1 electron initial state evolve = np.zeros([tsteps, len(wfk)]) energies = np.zeros(tsteps) mode_evolve = np.zeros([tsteps, 6]) mode_evolve = np.zeros([tsteps, len(mode_list)]) evolve[0] = wfk energies[0] = np.dot(np.conj(wfk), np.dot(H, wfk)) print(energies[0]) excitations = 3. #Loop to find occupation of each mode for i in range(0,len(mode_list)): wfk_sum = 0. for j in mode_list[i]: wfk_sum += evolve[0][j] mode_evolve[0][i] = wfk_sum / excitations print(mode_evolve) print('========================================================') #Figure out how to generalize this later ''' mode_evolve[0][0] = (evolve[0][0]+evolve[0][1]+evolve[0][2]) /2. mode_evolve[0][1] = (evolve[0][3]+evolve[0][4]+evolve[0][5]) /2. mode_evolve[0][2] = (evolve[0][6]+evolve[0][7]+evolve[0][8]) /2. mode_evolve[0][3] = (evolve[0][0]+evolve[0][3]+evolve[0][6]) /2. mode_evolve[0][4] = (evolve[0][1]+evolve[0][4]+evolve[0][7]) /2. mode_evolve[0][5] = (evolve[0][2]+evolve[0][5]+evolve[0][8]) /2. ''' ''' mode_evolve[0][0] = (evolve[0][0]+evolve[0][1]+evolve[0][2]+evolve[0][3]+evolve[0][4]+evolve[0][5]) /3. mode_evolve[0][1] = (evolve[0][0]+evolve[0][1]+evolve[0][2]+evolve[0][6]+evolve[0][7]+evolve[0][8]) /3. mode_evolve[0][2] = (evolve[0][3]+evolve[0][4]+evolve[0][5]+evolve[0][6]+evolve[0][7]+evolve[0][8]) /3. mode_evolve[0][3] = (evolve[0][0]+evolve[0][3]+evolve[0][6]) /3. mode_evolve[0][4] = (evolve[0][1]+evolve[0][4]+evolve[0][7]) /3. mode_evolve[0][5] = (evolve[0][2]+evolve[0][5]+evolve[0][8]) /3. #''' #print(mode_evolve[0]) #Define density matrices print(mode_evolve) print() print() for t in range(1, tsteps): #t_op = la.expm(-1j*H*t*dtc) wfk = np.dot(t_op, wfk) evolve[t] = np.multiply(np.conj(wfk), wfk) energies[t] = np.dot(np.conj(wfk), np.dot(H, wfk)) norm = np.sum(evolve[t]) #print(evolve[t]) #Store data in modes rather than basis defined in 'states' variable ''' #Procedure for two electrons mode_evolve[t][0] = (evolve[t][0]+evolve[t][1]+evolve[t][2]) / (2) mode_evolve[t][1] = (evolve[t][3]+evolve[t][4]+evolve[t][5]) / (2) mode_evolve[t][2] = (evolve[t][6]+evolve[t][7]+evolve[t][8]) / (2) mode_evolve[t][3] = (evolve[t][0]+evolve[t][3]+evolve[t][6]) / (2) mode_evolve[t][4] = (evolve[t][1]+evolve[t][4]+evolve[t][7]) / (2) mode_evolve[t][5] = (evolve[t][2]+evolve[t][5]+evolve[t][8]) / (2) #Procedure for half-filling mode_evolve[t][0] = (evolve[t][0]+evolve[t][1]+evolve[t][2]+evolve[t][3]+evolve[t][4]+evolve[t][5]) /3. mode_evolve[t][1] = (evolve[t][0]+evolve[t][1]+evolve[t][2]+evolve[t][6]+evolve[t][7]+evolve[t][8]) /3. mode_evolve[t][2] = (evolve[t][3]+evolve[t][4]+evolve[t][5]+evolve[t][6]+evolve[t][7]+evolve[t][8]) /3. mode_evolve[t][3] = (evolve[t][0]+evolve[t][3]+evolve[t][6]) /3. mode_evolve[t][4] = (evolve[t][1]+evolve[t][4]+evolve[t][7]) /3. mode_evolve[t][5] = (evolve[t][2]+evolve[t][5]+evolve[t][8]) /3. #''' #print(mode_evolve[t]) #print(np.linalg.norm(evolve[t])) #print(len(evolve[:,0]) ) #print(len(times)) #print(evolve[:,0]) #print(min(evolve[:,0])) print(energies) timesq = np.arange(0, time_steps*dt, dt) for i in range(nsites): #Create string label strup = "Site "+str(i+1)+r'$\uparrow$' strdwn = "Site "+str(i+1)+r'$\downarrow$' ax2.plot(timesq, processed_data[i,:], marker="^", color=str(colors[i]), label=strup) ax2.plot(timesq, processed_data[i+nsites,:], marker="v", color=str(colors[i]), label=strdwn) #ax2.set_ylim(0, 0.55) ax2.set_xlim(0, time_steps*dt+dt/2.) #ax2.set_xticks(np.arange(0,time_steps*dt+dt, 0.2)) #ax2.set_yticks(np.arange(0,0.55, 0.05)) ax2.tick_params(labelsize=16) ax2.set_title('Time Evolution of 3 Site One Dimensional Chain', fontsize=22) ax2.set_xlabel('Time', fontsize=24) ax2.set_ylabel('Probability', fontsize=24) ax2.legend(fontsize=20) #Process and plot data '''The procedure here is, for each fermionic mode, add the probability of every state containing that mode (at a given time step), and renormalize the data based on the total occupation of each mode. Afterwards, plot the data as a function of time step for each mode.''' def process_run(num_sites, time_steps, results): proc_data = np.zeros((2*num_sites, time_steps)) timesq = np.arange(0.,time_steps*dt, dt) #Sum over time steps for t in range(time_steps): #Sum over all possible states of computer for i in range(2**(2*num_sites)): #num = get_bin(i, 2*nsite) num = ''.join( list( reversed(hc.get_bin(i,2*nsites)) ) ) #For each state, check which mode(s) it contains and add them for mode in range(len(num)): if num[mode]=='1': proc_data[mode,t] += results[i,t] #Renormalize these sums so that the total occupation of the modes is 1 norm = 0.0 for mode in range(len(num)): norm += proc_data[mode,t] proc_data[:,t] = proc_data[:,t] / norm return proc_data ''' At this point, proc_data is a 2d array containing the occupation of each mode, for every time step ''' processed_data = process_run(nsites, time_steps, run_results) #Create plots of the processed data fig2, ax2 = plt.subplots(figsize=(20,10)) colors = list(mcolors.TABLEAU_COLORS.keys()) for i in range(nsites): #Create string label strup = "Site "+str(i+1)+r'$\uparrow$' strdwn = "Site "+str(i+1)+r'$\downarrow$' ax2.plot(timesq, processed_data[i,:], marker="^", color=str(colors[i]), label=strup) ax2.plot(timesq, processed_data[i+nsites,:], marker="v", color=str(colors[i]), label=strdwn) #ax2.set_ylim(0, 0.55) ax2.set_xlim(0, time_steps*dt+dt/2.) #ax2.set_xticks(np.arange(0,time_steps*dt+dt, 0.2)) #ax2.set_yticks(np.arange(0,0.55, 0.05)) ax2.tick_params(labelsize=16) ax2.set_title('Time Evolution of 3 Site One Dimensional Chain', fontsize=22) ax2.set_xlabel('Time', fontsize=24) ax2.set_ylabel('Probability', fontsize=24) ax2.legend(fontsize=20)
https://github.com/kaelynj/Qiskit-HubbardModel
kaelynj
%%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/kaelynj/Qiskit-HubbardModel
kaelynj
%matplotlib inline # Importing standard Qiskit libraries and configuring account from qiskit import QuantumCircuit, execute, Aer, IBMQ, BasicAer, QuantumRegister, ClassicalRegister from qiskit.compiler import transpile, assemble from qiskit.quantum_info import Operator from qiskit.tools.monitor import job_monitor from qiskit.tools.jupyter import * from qiskit.visualization import * import matplotlib.pyplot as plt import matplotlib.colors as mcolors import numpy as np from matplotlib import rcParams rcParams['text.usetex'] = True #Useful tool for converting an integer to a binary bit string def get_bin(x, n=0): """ Get the binary representation of x. Parameters: x (int), n (int, number of digits)""" return format(x, 'b').zfill(n)
https://github.com/kaelynj/Qiskit-HubbardModel
kaelynj
%matplotlib inline import sys sys.path.append('./src') # Importing standard Qiskit libraries and configuring account #from qiskit import QuantumCircuit, execute, Aer, IBMQ #from qiskit.compiler import transpile, assemble #from qiskit.tools.jupyter import * #from qiskit.visualization import * import matplotlib.pyplot as plt import matplotlib.colors as mcolors import numpy as np import ClassicalHubbardEvolutionChain as chc import random as rand import scipy.linalg as la def get_bin(x, n=0): """ Get the binary representation of x. Parameters: x (int), n (int, number of digits)""" binry = format(x, 'b').zfill(n) sup = list( reversed( binry[0:int(len(binry)/2)] ) ) sdn = list( reversed( binry[int(len(binry)/2):len(binry)] ) ) return format(x, 'b').zfill(n) #============ Run Classical Evolution ============== #Define our basis states #States for 3 electrons with net spin up ''' states = [ [[1,1,0],[1,0,0]], [[1,1,0],[0,1,0]], [[1,1,0], [0,0,1]], [[1,0,1],[1,0,0]], [[1,0,1],[0,1,0]], [[1,0,1], [0,0,1]], [[0,1,1],[1,0,0]], [[0,1,1],[0,1,0]], [[0,1,1], [0,0,1]] ] ''' #States for 2 electrons in singlet state states = [ [[1,0,0],[1,0,0]], [[1,0,0],[0,1,0]], [[1,0,0],[0,0,1]], [[0,1,0],[1,0,0]], [[0,1,0],[0,1,0]], [[0,1,0],[0,0,1]], [[0,0,1],[1,0,0]], [[0,0,1],[0,1,0]], [[0,0,1],[0,0,1]] ] #''' #States for a single electron #states = [ [[1,0,0],[0,0,0]], [[0,1,0],[0,0,0]], [[0,0,1],[0,0,0]] ] #Possible initial wavefunctions #wfk = [0., 0., 0., 0., 1., 0., 0., 0., 0.] #Half-filling initial state wfk = [0., 0., 0., 0., 1.0, 0., 0., 0., 0.] #2 electron initial state #wfk = [0., 1., 0.] #1 electron initial state #System parameters t = 1.0 U = 2. classical_time_step = 0.01 classical_total_time = 500*0.01 times = np.arange(0., classical_total_time, classical_time_step) evolution, engs = chc.sys_evolve(states, wfk, t, U, classical_total_time, classical_time_step) #print(evolution) probs = [np.sum(x) for x in evolution] #print(probs) #print(np.sum(evolution[0])) print(engs) states_list = [] nsite = 3 for state in range(0, 2**(2*nsite)): state_bin = get_bin(state, 2*nsite) state_list = [[],[]] for mode in range(0,nsite): state_list[0].append(int(state_bin[mode])) state_list[1].append(int(state_bin[mode+nsite])) #print(state_list) states_list.append(state_list) #print(states_list[18]) #evolution2, engs2 = chc.sys_evolve(states_list, wfk_full, t, U, classical_total_time, classical_time_step) #System parameters t = 1.0 U = 2. classical_time_step = 0.01 classical_total_time = 500*0.01 times = np.arange(0., classical_total_time, classical_time_step) #Create full Hamiltonian wfk_full = np.zeros(len(states_list)) #wfk_full[18] = 1. #010010 wfk_full[21] = 1. #010101 #wfk_full[2] = 1. #000010 #evolution2, engs2 = chc.sys_evolve(states_list, wfk_full, t, U, classical_total_time, classical_time_step) def repel(l,state): if state[0][l]==1 and state[1][l]==1: return state else: return [] #Check if two states are different by a single hop def hop(psii, psij, hopping): #Check spin down hopp = 0 if psii[0]==psij[0]: #Create array of indices with nonzero values ''' indi = np.nonzero(psii[1])[0] indj = np.nonzero(psij[1])[0] if len(indi) != len(indj): return hopp print('ind_i: ',indi,' ind_j: ',indj) for i in range(len(indi)): if abs(indi[i]-indj[i])==1: hopp = -hopping print('Hopping Found: ',psii,' with: ',psij) return hopp ''' hops = [] for site in range(len(psii[0])): if psii[1][site] != psij[1][site]: hops.append(site) if len(hops)==2 and np.sum(psii[1]) == np.sum(psij[1]): if hops[1]-hops[0]==1: hopp = -hopping return hopp #Check spin up if psii[1]==psij[1]: ''' indi = np.nonzero(psii[0])[0] indj = np.nonzero(psij[0])[0] if len(indi) != len(indj): return hopp print('ind_i: ',indi,' ind_j: ',indj) for i in range(len(indi)): if abs(indi[i]-indj[i])==1: hopp = -hopping print('Hopping Found: ',psii,' with: ',psij) return hopp ''' hops = [] for site in range(len(psii[1])): if psii[0][site] != psij[0][site]: hops.append(site) if len(hops)==2 and np.sum(psii[0])==np.sum(psij[0]): if hops[1]-hops[0]==1: hopp = -hopping return hopp return hopp def get_hamiltonian(states, t, U): H = np.zeros((len(states),len(states)) ) #Construct Hamiltonian matrix for i in range(len(states)): psi_i = states[i] for j in range(i, len(states)): psi_j = states[j] if j==i: for l in range(0,len(states[0][0])): if psi_i == repel(l,psi_j): H[i,j] = U break else: #print('psi_i: ',psi_i,' psi_j: ',psi_j) H[i,j] = hop(psi_i, psi_j, t) H[j,i] = H[i,j] return H hamil = get_hamiltonian(states_list, t, U) print(hamil) print(states_list) print() print("Target state: ", states_list[21]) mapping = get_mapping(states_list) print('Second mapping set') print(mapping[1]) print(wfk_full) mapped_wfk = np.zeros(6) for i in range(len(mapping)): if 21 in mapping[i]: print("True for mapping set: ",i) def get_mapping(states): num_sites = len(states[0][0]) mode_list = [] for i in range(0,2*num_sites): index_list = [] for state_index in range(0,len(states)): state = states[state_index] #Check spin-up modes if i < num_sites: if state[0][i]==1: index_list.append(state_index) #Check spin-down modes else: if state[1][i-num_sites]==1: index_list.append(state_index) if index_list: mode_list.append(index_list) return mode_list def wfk_energy(wfk, hamil): eng = np.dot(np.conj(wfk), np.dot(hamil, wfk)) return eng def get_variance(wfk, h): h_squared = np.matmul(h, h) eng_squared = np.vdot(wfk, np.dot(h_squared, wfk)) squared_eng = np.vdot(wfk, np.dot(h, wfk)) var = np.sqrt(eng_squared - squared_eng) return var def sys_evolve(states, init_wfk, hopping, repulsion, total_time, dt): hamiltonian = get_hamiltonian(states, hopping, repulsion) t_operator = la.expm(-1j*hamiltonian*dt) mapping = get_mapping(states) print(mapping) #Initalize system tsteps = int(total_time/dt) evolve = np.zeros([tsteps, len(init_wfk)]) mode_evolve = np.zeros([tsteps, len(mapping)]) wfk = init_wfk energies = np.zeros(tsteps) #Store first time step in mode_evolve evolve[0] = np.multiply(np.conj(wfk), wfk) for i in range(0, len(mapping)): wfk_sum = 0. norm = 0. print("Mapping: ", mapping[i]) for j in mapping[i]: print(evolve[0][j]) wfk_sum += evolve[0][j] mode_evolve[0][i] = wfk_sum energies[0] = wfk_energy(wfk, hamiltonian) norm = np.sum(mode_evolve[0]) mode_evolve[0][:] = mode_evolve[0][:] / norm #print('wfk_sum: ',wfk_sum,' norm: ',norm) #print('Variance: ',get_variance(wfk, hamiltonian) ) #Now do time evolution print(mode_evolve[0]) times = np.arange(0., total_time, dt) for t in range(1, tsteps): wfk = np.dot(t_operator, wfk) evolve[t] = np.multiply(np.conj(wfk), wfk) #print(evolve[t]) energies[t] = wfk_energy(wfk, hamiltonian) for i in range(0, len(mapping)): norm = 0. wfk_sum = 0. for j in mapping[i]: wfk_sum += evolve[t][j] mode_evolve[t][i] = wfk_sum norm = np.sum(mode_evolve[t]) mode_evolve[t][:] = mode_evolve[t][:] / norm #Return time evolution return mode_evolve, energies evolution2, engs2 = sys_evolve(states_list, wfk_full, t, U, classical_total_time, classical_time_step) print(evolution2) #print(engs2) colors = list(mcolors.TABLEAU_COLORS.keys()) fig2, ax2 = plt.subplots(figsize=(20,10)) for i in range(3): #Create string label strup = "Site "+str(i+1)+r'$\uparrow$' strdwn = "Site "+str(i+1)+r'$\downarrow$' ax2.plot(times, evolution2[:,i], linestyle='-', color=str(colors[i]), linewidth=2, label=strup) ax2.plot(times, evolution2[:,i+3], linestyle='--', color=str(colors[i]), linewidth=2, label=strdwn) plt.legend() #print(evolution[10]) #H = np.array([[0., -t, 0.],[-t, 0., -t],[0., -t, 0.]]) #print(np.dot(np.conj(evolution[10]), np.dot(H, evolution[10]))) print(engs[0]) plt.plot(times, engs) plt.xlabel('Time') plt.ylabel('Energy') #Save data import json fname = './data/classical_010101.json' data = {'times': list(times)} for i in range(3): key1 = 'site_up'+str(i) key2 = 'site_dwn'+str(i) data[key1] = list(evolution2[:,i]) data[key2] = list(evolution2[:,i+3]) with open(fname, 'w') as fp: json.dump(data, fp, indent=4) #Create plots of the processed data fig2, ax2 = plt.subplots(figsize=(20,10)) colors = list(mcolors.TABLEAU_COLORS.keys()) cos = np.cos(np.sqrt(2)*times)**2 sit1 = "Site "+str(1)+r'$\uparrow$' sit2 = "Site "+str(2)+r'$\uparrow$' sit3 = "Site "+str(3)+r'$\uparrow$' #ax2.plot(times, evolution[:,0], marker='.', color='k', linewidth=2, label=sit1) #ax2.plot(times, evolution[:,1], marker='.', color=str(colors[0]), linewidth=2, label=sit2) #ax2.plot(times, evolution[:,2], marker='.', color=str(colors[1]), linewidth=1.5, label=sit3) #ax2.plot(times, cos, label='cosdat') #ax2.plot(times, np.zeros(len(times))) for i in range(3): #Create string label strup = "Site "+str(i+1)+r'$\uparrow$' strdwn = "Site "+str(i+1)+r'$\downarrow$' ax2.plot(times, evolution[:,i], linestyle='-', color=str(colors[i]), linewidth=2, label=strup) ax2.plot(times, evolution[:,i+3], linestyle='--', color=str(colors[i]), linewidth=2, label=strdwn) #ax2.set_ylim(0, 1.) ax2.set_xlim(0, classical_total_time) #ax2.set_xlim(0, 1.) ax2.set_xticks(np.arange(0,classical_total_time, 0.2)) #ax2.set_yticks(np.arange(0,1.1, 0.05)) ax2.tick_params(labelsize=16) ax2.set_title('Time Evolution of 3 Site One Dimensional Chain', fontsize=22) ax2.set_xlabel('Time', fontsize=24) ax2.set_ylabel('Probability', fontsize=24) ax2.legend(fontsize=20) #Try by constructing the matrix and finding the eigenvalues N = 3 Nup = 2 Ndwn = N - Nup t = 1. U = 2. #Check if two states are different by a single hop def hop(psii, psij): #Check spin down hopp = 0 if psii[0]==psij[0]: #Create array of indices with nonzero values indi = np.nonzero(psii[1])[0] indj = np.nonzero(psij[1])[0] for i in range(len(indi)): if abs(indi[i]-indj[i])==1: hopp = -t return hopp #Check spin up if psii[1]==psij[1]: indi = np.nonzero(psii[0])[0] indj = np.nonzero(psij[0])[0] for i in range(len(indi)): if abs(indi[i]-indj[i])==1: hopp = -t return hopp return hopp #On-site terms def repel(l,state): if state[0][l]==1 and state[1][l]==1: return state else: return [] #States for 3 electrons with net spin up states = [ [[1,1,0],[1,0,0]], [[1,1,0],[0,1,0]], [[1,1,0], [0,0,1]], [[1,0,1],[1,0,0]], [[1,0,1],[0,1,0]], [[1,0,1], [0,0,1]], [[0,1,1],[1,0,0]], [[0,1,1],[0,1,0]], [[0,1,1], [0,0,1]] ] #States for 2 electrons in singlet state #states = [ [[1,0,0],[1,0,0]], [[1,0,0],[0,1,0]], [[1,0,0],[0,0,1]], # [[0,1,0],[1,0,0]], [[0,1,0],[0,1,0]], [[0,1,0],[0,0,1]], # [[0,0,1],[1,0,0]], [[0,0,1],[0,1,0]], [[0,0,1],[0,0,1]] ] #States for a single electron states = [ [[1,0,0],[0,0,0]], [[0,1,0],[0,0,0]], [[0,0,1],[0,0,0]] ] H = np.zeros((len(states),len(states)) ) #Construct Hamiltonian matrix for i in range(len(states)): psi_i = states[i] for j in range(len(states)): psi_j = states[j] if j==i: for l in range(0,N): if psi_i == repel(l,psi_j): H[i,j] = U break else: H[i,j] = hop(psi_i, psi_j) print(H) results = la.eig(H) print() for i in range(len(results[0])): print('Eigenvalue: ',results[0][i]) print('Eigenvector: \n',results[1][i]) print('Norm: ', np.linalg.norm(results[1][i])) print('Density Matrix: ') print(np.outer(results[1][i],results[1][i])) print() dens_ops = [] eigs = [] for vec in results[1]: dens_ops.append(np.outer(results[1][i],results[1][i])) eigs.append(results[0][i]) print(dens_ops) dt = 0.01 tsteps = 450 times = np.arange(0., tsteps*dt, dt) t_op = la.expm(-1j*H*dt) #print(np.subtract(np.identity(len(H)), dt*H*1j)) #print(t_op) wfk = [0., 0., 0., 0., 1., 0., 0., 0., 0.] wfk = [0., 0., 0., 0., 1.0, 0., 0., 0., 0.] #2 electron initial state evolve = np.zeros([tsteps, len(wfk)]) mode_evolve = np.zeros([tsteps, 6]) evolve[0] = wfk #Figure out how to generalize this later #'''[[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8]] mode_evolve[0][0] = (evolve[0][0]+evolve[0][1]+evolve[0][2]) /2. mode_evolve[0][1] = (evolve[0][3]+evolve[0][4]+evolve[0][5]) /2. mode_evolve[0][2] = (evolve[0][6]+evolve[0][7]+evolve[0][8]) /2. mode_evolve[0][3] = (evolve[0][0]+evolve[0][3]+evolve[0][6]) /2. mode_evolve[0][4] = (evolve[0][1]+evolve[0][4]+evolve[0][7]) /2. mode_evolve[0][5] = (evolve[0][2]+evolve[0][5]+evolve[0][8]) /2. ''' mode_evolve[0][0] = (evolve[0][0]+evolve[0][1]+evolve[0][2]+evolve[0][3]+evolve[0][4]+evolve[0][5]) /3. mode_evolve[0][1] = (evolve[0][0]+evolve[0][1]+evolve[0][2]+evolve[0][6]+evolve[0][7]+evolve[0][8]) /3. mode_evolve[0][2] = (evolve[0][3]+evolve[0][4]+evolve[0][5]+evolve[0][6]+evolve[0][7]+evolve[0][8]) /3. mode_evolve[0][3] = (evolve[0][0]+evolve[0][3]+evolve[0][6]) /3. mode_evolve[0][4] = (evolve[0][1]+evolve[0][4]+evolve[0][7]) /3. mode_evolve[0][5] = (evolve[0][2]+evolve[0][5]+evolve[0][8]) /3. ''' print(mode_evolve[0]) #Define density matrices for t in range(1, tsteps): #t_op = la.expm(-1j*H*t) wfk = np.dot(t_op, wfk) evolve[t] = np.multiply(np.conj(wfk), wfk) norm = np.sum(evolve[t]) #print(evolve[t]) #Store data in modes rather than basis defined in 'states' variable #''' #Procedure for two electrons mode_evolve[t][0] = (evolve[t][0]+evolve[t][1]+evolve[t][2]) / (2) mode_evolve[t][1] = (evolve[t][3]+evolve[t][4]+evolve[t][5]) / (2) mode_evolve[t][2] = (evolve[t][6]+evolve[t][7]+evolve[t][8]) / (2) mode_evolve[t][3] = (evolve[t][0]+evolve[t][3]+evolve[t][6]) / (2) mode_evolve[t][4] = (evolve[t][1]+evolve[t][4]+evolve[t][7]) / (2) mode_evolve[t][5] = (evolve[t][2]+evolve[t][5]+evolve[t][8]) / (2) ''' mode_evolve[t][0] = (evolve[t][0]+evolve[t][1]+evolve[t][2]+evolve[t][3]+evolve[t][4]+evolve[t][5]) /3. mode_evolve[t][1] = (evolve[t][0]+evolve[t][1]+evolve[t][2]+evolve[t][6]+evolve[t][7]+evolve[t][8]) /3. mode_evolve[t][2] = (evolve[t][3]+evolve[t][4]+evolve[t][5]+evolve[t][6]+evolve[t][7]+evolve[t][8]) /3. mode_evolve[t][3] = (evolve[t][0]+evolve[t][3]+evolve[t][6]) /3. mode_evolve[t][4] = (evolve[t][1]+evolve[t][4]+evolve[t][7]) /3. mode_evolve[t][5] = (evolve[t][2]+evolve[t][5]+evolve[t][8]) /3. print(mode_evolve[t]) ''' #print(np.linalg.norm(evolve[t])) #print(len(evolve[:,0]) ) #print(len(times)) #print(evolve[:,0]) #print(min(evolve[:,0])) #Create plots of the processed data fig2, ax2 = plt.subplots(figsize=(20,10)) colors = list(mcolors.TABLEAU_COLORS.keys()) cos = np.cos(np.sqrt(2)*times)**2 sit1 = "Site "+str(1)+r'$\uparrow$' sit2 = "Site "+str(2)+r'$\uparrow$' sit3 = "Site "+str(3)+r'$\uparrow$' #ax2.plot(times, evolve[:,0], marker='.', color='k', linewidth=2, label=sit1) #ax2.plot(times, evolve[:,1], marker='.', color=str(colors[0]), linewidth=2, label=sit2) #ax2.plot(times, evolve[:,2], marker='.', color=str(colors[1]), linewidth=1.5, label=sit3) #ax2.plot(times, cos, label='cosdat') #ax2.plot(times, np.zeros(len(times))) for i in range(3): #Create string label strup = "Site "+str(i+1)+r'$\uparrow$' strdwn = "Site "+str(i+1)+r'$\downarrow$' ax2.plot(times, mode_evolve[:,i], linestyle='-', color=str(colors[i]), linewidth=2, label=strup) ax2.plot(times, mode_evolve[:,i+3], linestyle='--', color=str(colors[i]), linewidth=2, label=strdwn) #ax2.set_ylim(0, 1.) ax2.set_xlim(0, tsteps*dt+dt/2.) #ax2.set_xlim(0, 1.) ax2.set_xticks(np.arange(0,tsteps*dt+dt, 0.2)) #ax2.set_yticks(np.arange(0,1.1, 0.05)) ax2.tick_params(labelsize=16) ax2.set_title('Time Evolution of 3 Site One Dimensional Chain', fontsize=22) ax2.set_xlabel('Time', fontsize=24) ax2.set_ylabel('Probability', fontsize=24) ax2.legend(fontsize=20) dt = 0.1 tsteps = 50 times = np.arange(0., tsteps*dt, dt) t_op = la.expm(-1j*H*dt) #print(np.subtract(np.identity(len(H)), dt*H*1j)) #print(t_op) #wfk = [0., 1., 0., 0., .0, 0., 0., 0., 0.] #Half-filling initial state wfk0 = [0., 0., 0., 0., 1.0, 0., 0., 0., 0.] #2 electron initial state #wfk0 = [0., 1., 0.] #1 electron initial state evolve = np.zeros([tsteps, len(wfk0)]) mode_evolve = np.zeros([tsteps, 6]) evolve[0] = wfk0 #Figure out how to generalize this later #''' mode_evolve[0][0] = (evolve[0][0]+evolve[0][1]+evolve[0][2]) /2. mode_evolve[0][1] = (evolve[0][3]+evolve[0][4]+evolve[0][5]) /2. mode_evolve[0][2] = (evolve[0][6]+evolve[0][7]+evolve[0][8]) /2. mode_evolve[0][3] = (evolve[0][0]+evolve[0][3]+evolve[0][6]) /2. mode_evolve[0][4] = (evolve[0][1]+evolve[0][4]+evolve[0][7]) /2. mode_evolve[0][5] = (evolve[0][2]+evolve[0][5]+evolve[0][8]) /2. ''' mode_evolve[0][0] = (evolve[0][0]+evolve[0][1]+evolve[0][2]+evolve[0][3]+evolve[0][4]+evolve[0][5]) /3. mode_evolve[0][1] = (evolve[0][0]+evolve[0][1]+evolve[0][2]+evolve[0][6]+evolve[0][7]+evolve[0][8]) /3. mode_evolve[0][2] = (evolve[0][3]+evolve[0][4]+evolve[0][5]+evolve[0][6]+evolve[0][7]+evolve[0][8]) /3. mode_evolve[0][3] = (evolve[0][0]+evolve[0][3]+evolve[0][6]) /3. mode_evolve[0][4] = (evolve[0][1]+evolve[0][4]+evolve[0][7]) /3. mode_evolve[0][5] = (evolve[0][2]+evolve[0][5]+evolve[0][8]) /3. #''' #Define density matrices for t in range(1, tsteps): t_op = la.expm(-1j*H*t*dt) wfk = np.dot(t_op, wfk0) evolve[t] = np.multiply(np.conj(wfk), wfk) norm = np.sum(evolve[t]) print(evolve[t]) #Store data in modes rather than basis defined in 'states' variable #''' #Procedure for two electrons mode_evolve[t][0] = (evolve[t][0]+evolve[t][1]+evolve[t][2]) / (2) mode_evolve[t][1] = (evolve[t][3]+evolve[t][4]+evolve[t][5]) / (2) mode_evolve[t][2] = (evolve[t][6]+evolve[t][7]+evolve[t][8]) / (2) mode_evolve[t][3] = (evolve[t][0]+evolve[t][3]+evolve[t][6]) / (2) mode_evolve[t][4] = (evolve[t][1]+evolve[t][4]+evolve[t][7]) / (2) mode_evolve[t][5] = (evolve[t][2]+evolve[t][5]+evolve[t][8]) / (2) #Procedure for half-filling ''' mode_evolve[t][0] = (evolve[t][0]+evolve[t][1]+evolve[t][2]+evolve[t][3]+evolve[t][4]+evolve[t][5]) /3. mode_evolve[t][1] = (evolve[t][0]+evolve[t][1]+evolve[t][2]+evolve[t][6]+evolve[t][7]+evolve[t][8]) /3. mode_evolve[t][2] = (evolve[t][3]+evolve[t][4]+evolve[t][5]+evolve[t][6]+evolve[t][7]+evolve[t][8]) /3. mode_evolve[t][3] = (evolve[t][0]+evolve[t][3]+evolve[t][6]) /3. mode_evolve[t][4] = (evolve[t][1]+evolve[t][4]+evolve[t][7]) /3. mode_evolve[t][5] = (evolve[t][2]+evolve[t][5]+evolve[t][8]) /3. #''' #print(mode_evolve[t]) #print(np.linalg.norm(evolve[t])) #print(len(evolve[:,0]) ) #print(len(times)) #print(evolve[:,0]) #print(min(evolve[:,0])) #Create plots of the processed data fig2, ax2 = plt.subplots(figsize=(20,10)) colors = list(mcolors.TABLEAU_COLORS.keys()) cos = np.cos(np.sqrt(2)*times)**2 sit1 = "Site "+str(1)+r'$\uparrow$' sit2 = "Site "+str(2)+r'$\uparrow$' sit3 = "Site "+str(3)+r'$\uparrow$' #ax2.plot(times, evolve[:,0], marker='.', color='k', linewidth=2, label=sit1) #ax2.plot(times, evolve[:,1], marker='.', color=str(colors[0]), linewidth=2, label=sit2) #ax2.plot(times, evolve[:,2], marker='.', color=str(colors[1]), linewidth=1.5, label=sit3) #ax2.plot(times, cos, label='cosdat') #ax2.plot(times, np.zeros(len(times))) for i in range(3): #Create string label strup = "Site "+str(i+1)+r'$\uparrow$' strdwn = "Site "+str(i+1)+r'$\downarrow$' ax2.plot(times, mode_evolve[:,i], linestyle='-', color=str(colors[i]), linewidth=2, label=strup) ax2.plot(times, mode_evolve[:,i+3], linestyle='--', color=str(colors[i]), linewidth=2, label=strdwn) #ax2.set_ylim(0, 1.) ax2.set_xlim(0, tsteps*dt+dt/2.) #ax2.set_xlim(0, 1.) ax2.set_xticks(np.arange(0,tsteps*dt+dt, 0.2)) #ax2.set_yticks(np.arange(0,1.1, 0.05)) ax2.tick_params(labelsize=16) ax2.set_title('Time Evolution of 3 Site One Dimensional Chain', fontsize=22) ax2.set_xlabel('Time', fontsize=24) ax2.set_ylabel('Probability', fontsize=24) ax2.legend(fontsize=20) #Calculate total energy for 1D Hubbard model of N sites #Number of sites in chain N = 10 Ne = 10 #Filling factor nu = Ne/N #Hamiltonian parameters t = 2.0 #Hopping U = 4.0 #On-site repulsion state = np.zeros(2*N) #Add in space to populate array randomly, but do it by hand for now #Populate Psi n = 0 while n < Ne: site = rand.randint(0,N-1) spin = rand.randint(0,1) if state[site+spin*N]==0: state[site+spin*N] = 1 n+=1 print(state) #Loop over state and gather energy E = 0 ############# ADD UP ENERGY FROM STATE ############# #Add hoppings at edges if state[0]==1: if state[1]==0: E+=t/2. if state[N-1]==0: #Periodic boundary E+=t/2. if state[N]==1: if state[N+1]==0: E+=t/2. if state[-1]==0: E+=t/2. print('Ends of energy are: ',E) for i in range(1,N-1): print('i is: ',i) #Check spin up sites if site is occupied and if electron can hop if state[i]==1: if state[i+1]==0: E+=t/2. if state[i-1]==0: E+=t/2. #Check spin down sites if site is occupied and if electron can hop j = i+N if state[j]==1: if state[j+1]==0: E+=t/2. if state[j-1]==0: E+=t/2. #Check Hubbard repulsion terms for i in range(0,N): if state[i]==1 and state[i+N]==1: E+=U/4. print('Energy is: ',E) print('State is: ',state) #Try by constructing the matrix and finding the eigenvalues N = 3 Nup = 2 Ndwn = N - Nup t = 1.0 U = 2.5 #To generalize, try using permutations function but for now hard code this #Store a list of 2d list of all the states where the 2d list stores the spin-up occupation #and the spin down occupation states = [ [1,1,0,1,0,0], [1,1,0,0,1,0], [1,1,0,0,0,1], [1,0,1,1,0,0], [1,0,1,0,1,0], [1,0,1,0,0,1], [0,1,1,1,0,0], [0,1,1,0,1,0], [0,1,1,0,0,1] ] print(len(states)) H = np.zeros((len(states),len(states)) ) print(H[0,4]) print(states[0]) for i in range(len(states)): psi_i = states[i] for j in range(len(states)): psi_j = states[j] #Check over sites #Check rest of state for hopping or double occupation for l in range(1,N-1): #Check edges if psi_i[l]==1 and (psi_j[l+1]==1 and psi_i[l+1]==0) or (psi_j[l-1]==1 and psi_i[l-1]==0): H[i,j] = -t/2. break if psi_i[l+N]==1 and (psi_j[l+1+N]==1 and psi_i[l+1+N]==0) or (psi_j[l-1+N]==1 and psi_i[l-1+N]==0): H[i,j] = -t/2. break if psi_i==psi_j: for l in range(N): if psi_i[l]==1 and psi_j[l+N]==1: H[i,j] = U/4. break print(H) tst = [[0,1],[2,3]] print(tst[1][1]) psi_i = [[1,1,0],[1,0,0]] psi_j = [[1,1,0],[0,1,0]] print(psi_j[0]) print(psi_j[1], ' 1st: ',psi_j[1][0], ' 2nd: ',psi_j[1][1], ' 3rd: ',psi_j[1][2]) for l in range(N): print('l: ',l) if psi_j[1][l]==0 and psi_j[1][l-1]==1: psi_j[1][l]=1 psi_j[1][l-1]=0 print('1st') print(psi_j) break if psi_j[1][l-1]==0 and psi_j[1][l]==1: psi_j[1][l-1]=1 psi_j[1][l]=0 print('2nd') print(psi_j) break if psi_j[1][l]==0 and psi_j[1][l+1]==1: psi_j[1][l]=1 psi_j[1][l+1]=0 print('3rd: l=',l,' l+1=',l+1) print(psi_j) break if psi_j[1][l+1]==0 and psi_j[1][l]==1: psi_j[1][l+1]=1 psi_j[1][l]=0 print('4th') print(psi_j) break def hoptst(l,m,spin,state): #Spin is either 0 or 1 which corresponds to which array w/n state we're examining if (state[spin][l]==0 and state[spin][m]==1): state[spin][l]=1 state[spin][m]=0 return state elif (state[spin][m]==0 and state[spin][l]==1): state[spin][m]=1 state[spin][l]=0 return state else: return [] #Try using hoptst: print(hoptst(0,1,1,psi_j)) ### Function to permutate a given list # Python function to print permutations of a given list def permutation(lst): # If lst is empty then there are no permutations if len(lst) == 0: return [] # If there is only one element in lst then, only # one permuatation is possible if len(lst) == 1: return [lst] # Find the permutations for lst if there are # more than 1 characters l = [] # empty list that will store current permutation # Iterate the input(lst) and calculate the permutation for i in range(len(lst)): m = lst[i] # Extract lst[i] or m from the list. remLst is # remaining list remLst = lst[:i] + lst[i+1:] # Generating all permutations where m is first # element for p in permutation(remLst): l.append([m] + p) return l # Driver program to test above function data = list('1000') for p in permutation(data): print(p) import itertools items = [1,0,0] perms = itertools.permutations tst = 15.2 tst = np.full(3, tst) print(tst) H = np.array([[1, 1], [1, -1]]) H_2 = np.tensordot(H,H, 0) print(H_2) print('==============================') M = np.array([[0,1,1,0],[1,1,0,0],[1,0,1,0],[0,0,0,1]]) print(M) print(np.dot(np.conj(M.T),M))
https://github.com/kaelynj/Qiskit-HubbardModel
kaelynj
%matplotlib inline import sys sys.path.append('./src') # Importing standard Qiskit libraries and configuring account #from qiskit import QuantumCircuit, execute, Aer, IBMQ #from qiskit.compiler import transpile, assemble #from qiskit.tools.jupyter import * #from qiskit.visualization import * import matplotlib.pyplot as plt import matplotlib.colors as mcolors import numpy as np import ClassicalHubbardEvolutionChain as chc import FullClassicalHubbardEvolutionChain as fhc import random as rand import scipy.linalg as la #System parameters numsites = 3 t = 1.0 U = 2. classical_time_step = 0.01 classical_total_time = 500*0.01 times = np.arange(0., classical_total_time, classical_time_step) states_list = fhc.get_states(numsites) #Create full Hamiltonian wfk_full = np.zeros(len(states_list)) #wfk_full[18] = 1. #010010 wfk_full[21] = 1. #010101 #wfk_full[2] = 1. #000010 evolution2, engs2, wfks = fhc.sys_evolve(states_list, wfk_full, t, U, classical_total_time, classical_time_step) print(wfks[10]) print(evolution2) #print(engs2) colors = list(mcolors.TABLEAU_COLORS.keys()) fig2, ax2 = plt.subplots(figsize=(20,10)) for i in range(3): #Create string label strup = "Site "+str(i+1)+r'$\uparrow$' strdwn = "Site "+str(i+1)+r'$\downarrow$' ax2.plot(times, evolution2[:,i], linestyle='-', color=str(colors[i]), linewidth=2, label=strup) ax2.plot(times, evolution2[:,i+3], linestyle='--', color=str(colors[i]), linewidth=2, label=strdwn) plt.legend() def get_bin(x, n=0): """ Get the binary representation of x. Parameters: x (int), n (int, number of digits)""" binry = format(x, 'b').zfill(n) sup = list( reversed( binry[0:int(len(binry)/2)] ) ) sdn = list( reversed( binry[int(len(binry)/2):len(binry)] ) ) return format(x, 'b').zfill(n) #==== Create all Possible States for given system size ===# states_list = [] nsite = 3 for state in range(0, 2**(2*nsite)): state_bin = get_bin(state, 2*nsite) state_list = [[],[]] for mode in range(0,nsite): state_list[0].append(int(state_bin[mode])) state_list[1].append(int(state_bin[mode+nsite])) #print(state_list) states_list.append(state_list) def repel(l,state): if state[0][l]==1 and state[1][l]==1: return state else: return [] #Check if two states are different by a single hop def hop(psii, psij, hopping): #Check spin down hopp = 0 if psii[0]==psij[0]: #Create array of indices with nonzero values hops = [] for site in range(len(psii[0])): if psii[1][site] != psij[1][site]: hops.append(site) if len(hops)==2 and np.sum(psii[1]) == np.sum(psij[1]): if hops[1]-hops[0]==1: hopp = -hopping return hopp #Check spin up if psii[1]==psij[1]: hops = [] for site in range(len(psii[1])): if psii[0][site] != psij[0][site]: hops.append(site) if len(hops)==2 and np.sum(psii[0])==np.sum(psij[0]): if hops[1]-hops[0]==1: hopp = -hopping return hopp return hopp def get_hamiltonian(states, t, U): H = np.zeros((len(states),len(states)) ) #Construct Hamiltonian matrix for i in range(len(states)): psi_i = states[i] for j in range(i, len(states)): psi_j = states[j] if j==i: for l in range(0,len(states[0][0])): if psi_i == repel(l,psi_j): H[i,j] = U break else: #print('psi_i: ',psi_i,' psi_j: ',psi_j) H[i,j] = hop(psi_i, psi_j, t) H[j,i] = H[i,j] return H def get_mapping(states): num_sites = len(states[0][0]) mode_list = [] for i in range(0,2*num_sites): index_list = [] for state_index in range(0,len(states)): state = states[state_index] #Check spin-up modes if i < num_sites: if state[0][i]==1: index_list.append(state_index) #Check spin-down modes else: if state[1][i-num_sites]==1: index_list.append(state_index) if index_list: mode_list.append(index_list) return mode_list def wfk_energy(wfk, hamil): eng = np.dot(np.conj(wfk), np.dot(hamil, wfk)) return eng def get_variance(wfk, h): h_squared = np.matmul(h, h) eng_squared = np.vdot(wfk, np.dot(h_squared, wfk)) squared_eng = np.vdot(wfk, np.dot(h, wfk)) var = np.sqrt(eng_squared - squared_eng) return var def sys_evolve(states, init_wfk, hopping, repulsion, total_time, dt): hamiltonian = get_hamiltonian(states, hopping, repulsion) t_operator = la.expm(-1j*hamiltonian*dt) wavefunctions = [] mapping = get_mapping(states) #print(mapping) #Initalize system tsteps = int(total_time/dt) evolve = np.zeros([tsteps, len(init_wfk)]) mode_evolve = np.zeros([tsteps, len(mapping)]) wfk = init_wfk wavefunctions.append(np.ndarray.tolist(wfk)) energies = np.zeros(tsteps) #Store first time step in mode_evolve evolve[0] = np.multiply(np.conj(wfk), wfk) for i in range(0, len(mapping)): wfk_sum = 0. norm = 0. for j in mapping[i]: wfk_sum += evolve[0][j] norm += evolve[0][j] if norm == 0.: norm = 1. mode_evolve[0][i] = wfk_sum #/ norm #print('wfk_sum: ',wfk_sum,' norm: ',norm) energies[0] = wfk_energy(wfk, hamiltonian) #print('Variance: ',get_variance(wfk, hamiltonian) ) #Now do time evolution print(mode_evolve[0]) times = np.arange(0., total_time, dt) for t in range(1, tsteps): wfk = np.dot(t_operator, wfk) evolve[t] = np.multiply(np.conj(wfk), wfk) wavefunctions.append(np.ndarray.tolist(wfk)) #print(evolve[t]) energies[t] = wfk_energy(wfk, hamiltonian ) for i in range(0, len(mapping)): norm = 0. wfk_sum = 0. for j in mapping[i]: wfk_sum += evolve[t][j] norm += evolve[t][j] #print('wfk_sum: ',wfk_sum,' norm: ',norm) if norm == 0.: norm = 1. mode_evolve[t][i] = wfk_sum #/ norm #print(mode_evolve[t]) #Return time evolution return mode_evolve, energies, wavefunctions #System parameters t = 1.0 U = 2. classical_time_step = 0.01 classical_total_time = 500*0.01 times = np.arange(0., classical_total_time, classical_time_step) #Create full Hamiltonian wfk_full = np.zeros(len(states_list)) #wfk_full[18] = 1. #010010 wfk_full[21] = 1. #010101 #wfk_full[2] = 1. #000010 evolution2, engs2, wfks = sys_evolve(states_list, wfk_full, t, U, classical_total_time, classical_time_step) print(wfks[10]) print(evolution2) #print(engs2) colors = list(mcolors.TABLEAU_COLORS.keys()) fig2, ax2 = plt.subplots(figsize=(20,10)) for i in range(3): #Create string label strup = "Site "+str(i+1)+r'$\uparrow$' strdwn = "Site "+str(i+1)+r'$\downarrow$' ax2.plot(times, evolution2[:,i], linestyle='-', color=str(colors[i]), linewidth=2, label=strup) ax2.plot(times, evolution2[:,i+3], linestyle='--', color=str(colors[i]), linewidth=2, label=strdwn) plt.legend()
https://github.com/kaelynj/Qiskit-HubbardModel
kaelynj
%matplotlib inline # Importing standard Qiskit libraries and configuring account from qiskit import QuantumCircuit, execute, Aer, IBMQ, BasicAer, QuantumRegister, ClassicalRegister from qiskit.compiler import transpile, assemble from qiskit.quantum_info import Operator from qiskit.tools.monitor import job_monitor from qiskit.tools.jupyter import * from qiskit.visualization import * import random as rand import scipy.linalg as la provider = IBMQ.load_account() import matplotlib.pyplot as plt import matplotlib.colors as mcolors import numpy as np from matplotlib import rcParams rcParams['text.usetex'] = True def reverse_list(s): temp_list = list(s) temp_list.reverse() return ''.join(temp_list) #Useful tool for converting an integer to a binary bit string def get_bin(x, n=0): """ Get the binary representation of x. Parameters: x (int), n (int, number of digits)""" binry = format(x, 'b').zfill(n) sup = list( reversed( binry[0:int(len(binry)/2)] ) ) sdn = list( reversed( binry[int(len(binry)/2):len(binry)] ) ) return format(x, 'b').zfill(n) #return ''.join(sup)+''.join(sdn) '''The task here is now to define a function which will either update a given circuit with a time-step or return a single gate which contains all the necessary components of a time-step''' #==========Needed Functions=============# #Function to apply a full set of time evolution gates to a given circuit def qc_evolve(qc, numsite, time, hop, U, trotter_steps): #Compute angles for the onsite and hopping gates # based on the model parameters t, U, and dt theta = hop*time/(2*trotter_slices) phi = U*time/(trotter_slices) numq = 2*numsite y_hop = Operator([[np.cos(theta), 0, 0, -1j*np.sin(theta)], [0, np.cos(theta), 1j*np.sin(theta), 0], [0, 1j*np.sin(theta), np.cos(theta), 0], [-1j*np.sin(theta), 0, 0, np.cos(theta)]]) x_hop = Operator([[np.cos(theta), 0, 0, 1j*np.sin(theta)], [0, np.cos(theta), 1j*np.sin(theta), 0], [0, 1j*np.sin(theta), np.cos(theta), 0], [1j*np.sin(theta), 0, 0, np.cos(theta)]]) z_onsite = Operator([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, np.exp(1j*phi)]]) #Loop over each time step needed and apply onsite and hopping gates for trot in range(trotter_steps): #Onsite Terms for i in range(0, numsite): qc.unitary(z_onsite, [i,i+numsite], label="Z_Onsite") #Add barrier to separate onsite from hopping terms qc.barrier() #Hopping terms for i in range(0,numsite-1): #Spin-up chain qc.unitary(y_hop, [i,i+1], label="YHop") qc.unitary(x_hop, [i,i+1], label="Xhop") #Spin-down chain qc.unitary(y_hop, [i+numsite, i+1+numsite], label="Xhop") qc.unitary(x_hop, [i+numsite, i+1+numsite], label="Xhop") #Add barrier after finishing the time step qc.barrier() #Measure the circuit for i in range(numq): qc.measure(i, i) #Function to run the circuit and store the counts for an evolution with # num_steps number of time steps. def sys_evolve(nsites, excitations, total_time, dt, hop, U, trotter_steps): #Check for correct data types if not isinstance(nsites, int): raise TypeError("Number of sites should be int") if np.isscalar(excitations): raise TypeError("Initial state should be list or numpy array") if not np.isscalar(total_time): raise TypeError("Evolution time should be scalar") if not np.isscalar(dt): raise TypeError("Time step should be scalar") if not np.isscalar(hop): raise TypeError("Hopping term should be scalar") if not np.isscalar(U): raise TypeError("Repulsion term should be scalar") if not isinstance(trotter_steps, int): raise TypeError("Number of trotter slices should be int") numq = 2*nsites num_steps = int(total_time/dt) print('Num Steps: ',num_steps) print('Total Time: ', total_time) data = np.zeros((2**numq, num_steps)) for t_step in range(0, num_steps): #Create circuit with t_step number of steps q = QuantumRegister(numq) c = ClassicalRegister(numq) qcirc = QuantumCircuit(q,c) #=========USE THIS REGION TO SET YOUR INITIAL STATE============== #Initialize circuit by setting the occupation to # a spin up and down electron in the middle site #qcirc.x(int(nsites/2)) #qcirc.x(nsites+int(nsites/2)) for flip in excitations: qcirc.x(flip) #if nsites==3: #Half-filling #qcirc.x(1) # qcirc.x(4) # qcirc.x(0) # qcirc.x(2) #1 electron # qcirc.x(1) #=============================================================== qcirc.barrier() #Append circuit with Trotter steps needed qc_evolve(qcirc, nsites, t_step*dt, hop, U, trotter_steps) #Choose provider and backend provider = IBMQ.get_provider() #backend = Aer.get_backend('statevector_simulator') backend = Aer.get_backend('qasm_simulator') #backend = provider.get_backend('ibmq_qasm_simulator') #backend = provider.get_backend('ibmqx4') #backend = provider.get_backend('ibmqx2') #backend = provider.get_backend('ibmq_16_melbourne') shots = 8192 max_credits = 10 #Max number of credits to spend on execution job_exp = execute(qcirc, backend=backend, shots=shots, max_credits=max_credits) job_monitor(job_exp) result = job_exp.result() counts = result.get_counts(qcirc) print(result.get_counts(qcirc)) print("Job: ",t_step+1, " of ", num_steps," complete.") #Store results in data array and normalize them for i in range(2**numq): if counts.get(get_bin(i,numq)) is None: dat = 0 else: dat = counts.get(get_bin(i,numq)) data[i,t_step] = dat/shots return data #==========Set Parameters of the System=============# dt = 0.25 #Delta t T = 4.5 time_steps = int(T/dt) t = 1.0 #Hopping parameter U = 2. #On-Site repulsion #time_steps = 10 nsites = 3 trotter_slices = 5 initial_state = np.array([1,4]) #Run simulation run_results = sys_evolve(nsites, initial_state, T, dt, t, U, trotter_slices) #print(True if np.isscalar(initial_state) else False) #Process and plot data '''The procedure here is, for each fermionic mode, add the probability of every state containing that mode (at a given time step), and renormalize the data based on the total occupation of each mode. Afterwards, plot the data as a function of time step for each mode.''' proc_data = np.zeros((2*nsites, time_steps)) timesq = np.arange(0.,time_steps*dt, dt) #Sum over time steps for t in range(time_steps): #Sum over all possible states of computer for i in range(2**(2*nsites)): #num = get_bin(i, 2*nsite) num = ''.join( list( reversed(get_bin(i,2*nsites)) ) ) #For each state, check which mode(s) it contains and add them for mode in range(len(num)): if num[mode]=='1': proc_data[mode,t] += run_results[i,t] #Renormalize these sums so that the total occupation of the modes is 1 norm = 0.0 for mode in range(len(num)): norm += proc_data[mode,t] proc_data[:,t] = proc_data[:,t] / norm ''' At this point, proc_data is a 2d array containing the occupation of each mode, for every time step ''' #Create plots of the processed data fig2, ax2 = plt.subplots(figsize=(20,10)) colors = list(mcolors.TABLEAU_COLORS.keys()) for i in range(nsites): #Create string label strup = "Site "+str(i+1)+r'$\uparrow$' strdwn = "Site "+str(i+1)+r'$\downarrow$' ax2.plot(timesq, proc_data[i,:], marker="^", color=str(colors[i]), label=strup) ax2.plot(timesq, proc_data[i+nsites,:], marker="v", color=str(colors[i]), label=strdwn) #ax2.set_ylim(0, 0.55) ax2.set_xlim(0, time_steps*dt+dt/2.) #ax2.set_xticks(np.arange(0,time_steps*dt+dt, 0.2)) #ax2.set_yticks(np.arange(0,0.55, 0.05)) ax2.tick_params(labelsize=16) ax2.set_title('Time Evolution of 3 Site One Dimensional Chain', fontsize=22) ax2.set_xlabel('Time', fontsize=24) ax2.set_ylabel('Probability', fontsize=24) ax2.legend(fontsize=20) #Plot the raw data as a colormap xticks = np.arange(2**(nsite*2)) xlabels=[] print("Time Steps: ",time_steps, " Step Size: ",dt) for i in range(2**(nsite*2)): xlabels.append(get_bin(i,6)) fig, ax = plt.subplots(figsize=(10,20)) c = ax.pcolor(run_results, cmap='binary') ax.set_title('Time Evolution of 3 Site One Dimensional Chain', fontsize=22) plt.yticks(xticks, xlabels, size=18) ax.set_xlabel('Time Step', fontsize=22) ax.set_ylabel('State', fontsize=26) plt.show() #Try by constructing the matrix and finding the eigenvalues N = 3 Nup = 2 Ndwn = N - Nup t = 1.0 U = 2. #Check if two states are different by a single hop def hop(psii, psij): #Check spin down hopp = 0 if psii[0]==psij[0]: #Create array of indices with nonzero values indi = np.nonzero(psii[1])[0] indj = np.nonzero(psij[1])[0] for i in range(len(indi)): if abs(indi[i]-indj[i])==1: hopp = -t return hopp #Check spin up if psii[1]==psij[1]: indi = np.nonzero(psii[0])[0] indj = np.nonzero(psij[0])[0] for i in range(len(indi)): if abs(indi[i]-indj[i])==1: hopp = -t return hopp return hopp #On-site terms def repel(l,state): if state[0][l]==1 and state[1][l]==1: return state else: return [] #States for 3 electrons with net spin up ''' states = [ [[1,1,0],[1,0,0]], [[1,1,0],[0,1,0]], [[1,1,0], [0,0,1]], [[1,0,1],[1,0,0]], [[1,0,1],[0,1,0]], [[1,0,1], [0,0,1]], [[0,1,1],[1,0,0]], [[0,1,1],[0,1,0]], [[0,1,1], [0,0,1]] ] #States for 2 electrons in singlet state ''' states = [ [[1,0,0],[1,0,0]], [[1,0,0],[0,1,0]], [[1,0,0],[0,0,1]], [[0,1,0],[1,0,0]], [[0,1,0],[0,1,0]], [[0,1,0],[0,0,1]], [[0,0,1],[1,0,0]], [[0,0,1],[0,1,0]], [[0,0,1],[0,0,1]] ] #''' #States for a single electron #states = [ [[1,0,0],[0,0,0]], [[0,1,0],[0,0,0]], [[0,0,1],[0,0,0]] ] #''' H = np.zeros((len(states),len(states)) ) #Construct Hamiltonian matrix for i in range(len(states)): psi_i = states[i] for j in range(len(states)): psi_j = states[j] if j==i: for l in range(0,N): if psi_i == repel(l,psi_j): H[i,j] = U break else: H[i,j] = hop(psi_i, psi_j) print(H) results = la.eig(H) print() for i in range(len(results[0])): print('Eigenvalue: ',results[0][i]) print('Eigenvector: \n',results[1][i]) print() dens_ops = [] eigs = [] for vec in results[1]: dens_ops.append(np.outer(results[1][i],results[1][i])) eigs.append(results[0][i]) print(dens_ops) dt = 0.1 tsteps = 50 times = np.arange(0., tsteps*dt, dt) t_op = la.expm(-1j*H*dt) #print(np.subtract(np.identity(len(H)), dt*H*1j)) #print(t_op) #wfk = [0., 0., 0., 0., 1., 0., 0., 0., 0.] #Half-filling initial state wfk = [0., 0., 0., 0., 1.0, 0., 0., 0., 0.] #2 electron initial state #wfk = [0., 1., 0.] #1 electron initial state evolve = np.zeros([tsteps, len(wfk)]) mode_evolve = np.zeros([tsteps, 6]) evolve[0] = wfk #Figure out how to generalize this later #''' mode_evolve[0][0] = (evolve[0][0]+evolve[0][1]+evolve[0][2]) /2. mode_evolve[0][1] = (evolve[0][3]+evolve[0][4]+evolve[0][5]) /2. mode_evolve[0][2] = (evolve[0][6]+evolve[0][7]+evolve[0][8]) /2. mode_evolve[0][3] = (evolve[0][0]+evolve[0][3]+evolve[0][6]) /2. mode_evolve[0][4] = (evolve[0][1]+evolve[0][4]+evolve[0][7]) /2. mode_evolve[0][5] = (evolve[0][2]+evolve[0][5]+evolve[0][8]) /2. ''' mode_evolve[0][0] = (evolve[0][0]+evolve[0][1]+evolve[0][2]+evolve[0][3]+evolve[0][4]+evolve[0][5]) /3. mode_evolve[0][1] = (evolve[0][0]+evolve[0][1]+evolve[0][2]+evolve[0][6]+evolve[0][7]+evolve[0][8]) /3. mode_evolve[0][2] = (evolve[0][3]+evolve[0][4]+evolve[0][5]+evolve[0][6]+evolve[0][7]+evolve[0][8]) /3. mode_evolve[0][3] = (evolve[0][0]+evolve[0][3]+evolve[0][6]) /3. mode_evolve[0][4] = (evolve[0][1]+evolve[0][4]+evolve[0][7]) /3. mode_evolve[0][5] = (evolve[0][2]+evolve[0][5]+evolve[0][8]) /3. #''' print(mode_evolve[0]) #Define density matrices for t in range(1, tsteps): #t_op = la.expm(-1j*H*t) wfk = np.dot(t_op, wfk) evolve[t] = np.multiply(np.conj(wfk), wfk) norm = np.sum(evolve[t]) #print(evolve[t]) #Store data in modes rather than basis defined in 'states' variable #Procedure for two electrons mode_evolve[t][0] = (evolve[t][0]+evolve[t][1]+evolve[t][2]) / (2) mode_evolve[t][1] = (evolve[t][3]+evolve[t][4]+evolve[t][5]) / (2) mode_evolve[t][2] = (evolve[t][6]+evolve[t][7]+evolve[t][8]) / (2) mode_evolve[t][3] = (evolve[t][0]+evolve[t][3]+evolve[t][6]) / (2) mode_evolve[t][4] = (evolve[t][1]+evolve[t][4]+evolve[t][7]) / (2) mode_evolve[t][5] = (evolve[t][2]+evolve[t][5]+evolve[t][8]) / (2) ''' #Procedure for half-filling mode_evolve[t][0] = (evolve[t][0]+evolve[t][1]+evolve[t][2]+evolve[t][3]+evolve[t][4]+evolve[t][5]) /3. mode_evolve[t][1] = (evolve[t][0]+evolve[t][1]+evolve[t][2]+evolve[t][6]+evolve[t][7]+evolve[t][8]) /3. mode_evolve[t][2] = (evolve[t][3]+evolve[t][4]+evolve[t][5]+evolve[t][6]+evolve[t][7]+evolve[t][8]) /3. mode_evolve[t][3] = (evolve[t][0]+evolve[t][3]+evolve[t][6]) /3. mode_evolve[t][4] = (evolve[t][1]+evolve[t][4]+evolve[t][7]) /3. mode_evolve[t][5] = (evolve[t][2]+evolve[t][5]+evolve[t][8]) /3. #''' print(mode_evolve[t]) #print(np.linalg.norm(evolve[t])) #print(len(evolve[:,0]) ) #print(len(times)) #print(evolve[:,0]) #print(min(evolve[:,0])) #Create plots of the processed data fig2, ax2 = plt.subplots(figsize=(20,10)) colors = list(mcolors.TABLEAU_COLORS.keys()) sit1 = "Exact Site "+str(1)+r'$\uparrow$' sit2 = "Exact Site "+str(2)+r'$\uparrow$' sit3 = "Exact Site "+str(3)+r'$\uparrow$' #ax2.plot(times, evolve[:,0], linestyle='--', color=colors[0], linewidth=2.5, label=sit1) #ax2.plot(times, evolve[:,1], linestyle='--', color=str(colors[1]), linewidth=2.5, label=sit2) #ax2.plot(times, evolve[:,2], linestyle='--', color=str(colors[2]), linewidth=2., label=sit3) #ax2.plot(times, np.zeros(len(times))) for i in range(nsites): #Create string label strupq = "Quantum Site "+str(i+1)+r'$\uparrow$' strdwnq = "Quantum Site "+str(i+1)+r'$\downarrow$' strup = "Numerical Site "+str(i+1)+r'$\uparrow$' strdwn = "Numerical Site "+str(i+1)+r'$\downarrow$' ax2.scatter(timesq, proc_data[i,:], marker="*", color=str(colors[i]), label=strupq) #ax2.scatter(timesq, proc_data[i+nsite,:], marker="v", color=str(colors[i]), label=strdwnq) ax2.plot(times, mode_evolve[:,i], linestyle='-', color=str(colors[i]), linewidth=2, label=strup) ax2.plot(times, mode_evolve[:,i+3], linestyle='--', color=str(colors[i]), linewidth=2, label=strdwn) #ax2.plot(times, evolve[:,i], linestyle='-', color=str(colors[i]), linewidth=2, label=strup) #ax2.plot(times, evolve[:,i+3], linestyle='--', color=str(colors[i]), linewidth=2, label=strdwn) ax2.set_ylim(0, .51) ax2.set_xlim(0, tsteps*dt+dt/2.) #ax2.set_xticks(np.arange(0,tsteps*dt+dt, 2*dt)) #ax2.set_yticks(np.arange(0,0.5, 0.05)) ax2.tick_params(labelsize=16) ax2.set_title('Time Evolution of 2 Electrons in 3 Site Chain', fontsize=22) ax2.set_xlabel('Time', fontsize=24) ax2.set_ylabel('Probability', fontsize=24) #ax2.legend(fontsize=20)
https://github.com/kaelynj/Qiskit-HubbardModel
kaelynj
%matplotlib inline # Importing standard Qiskit libraries and configuring account from qiskit import QuantumCircuit, execute, Aer, IBMQ, BasicAer, QuantumRegister, ClassicalRegister from qiskit.compiler import transpile, assemble from qiskit.quantum_info import Operator from qiskit.tools.monitor import job_monitor from qiskit.tools.jupyter import * from qiskit.visualization import * import random as rand import scipy.linalg as la provider = IBMQ.load_account() import matplotlib.pyplot as plt import matplotlib.colors as mcolors import numpy as np from matplotlib import rcParams rcParams['text.usetex'] = True def reverse_list(s): temp_list = list(s) temp_list.reverse() return ''.join(temp_list) #Useful tool for converting an integer to a binary bit string def get_bin(x, n=0): """ Get the binary representation of x. Parameters: x (int), n (int, number of digits)""" binry = format(x, 'b').zfill(n) sup = list( reversed( binry[0:int(len(binry)/2)] ) ) sdn = list( reversed( binry[int(len(binry)/2):len(binry)] ) ) return format(x, 'b').zfill(n) #return ''.join(sup)+''.join(sdn) '''The task here is now to define a function which will either update a given circuit with a time-step or return a single gate which contains all the necessary components of a time-step''' #==========Set Parameters of the System=============# dt = 0.2 #Delta t t = 1.0 #Hopping parameter U = 2. #On-Site repulsion time_steps = 30 nsite = 3 trotter_slices = 5 #==========Needed Functions=============# #Function to apply a full set of time evolution gates to a given circuit def qc_evolve(qc, numsite, dt, t, U, num_steps): #Compute angles for the onsite and hopping gates # based on the model parameters t, U, and dt theta = t*dt/(2*trotter_slices) phi = U*dt/(trotter_slices) numq = 2*numsite y_hop = Operator([[np.cos(theta), 0, 0, -1j*np.sin(theta)], [0, np.cos(theta), 1j*np.sin(theta), 0], [0, 1j*np.sin(theta), np.cos(theta), 0], [-1j*np.sin(theta), 0, 0, np.cos(theta)]]) x_hop = Operator([[np.cos(theta), 0, 0, 1j*np.sin(theta)], [0, np.cos(theta), 1j*np.sin(theta), 0], [0, 1j*np.sin(theta), np.cos(theta), 0], [1j*np.sin(theta), 0, 0, np.cos(theta)]]) z_onsite = Operator([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, np.exp(1j*phi)]]) #Loop over each time step needed and apply onsite and hopping gates for step in range(num_steps): for trot in range(trotter_slices): #Onsite Terms for i in range(0, numsite): qc.unitary(z_onsite, [i,i+numsite], label="Z_Onsite") #Add barrier to separate onsite from hopping terms qc.barrier() #Hopping terms for i in range(0,numsite-1): #Spin-up chain qc.unitary(y_hop, [i,i+1], label="YHop") qc.unitary(x_hop, [i,i+1], label="Xhop") #Spin-down chain qc.unitary(y_hop, [i+numsite, i+1+numsite], label="Xhop") qc.unitary(x_hop, [i+numsite, i+1+numsite], label="Xhop") #Add barrier after finishing the time step qc.barrier() #Measure the circuit for i in range(numq): qc.measure(i, i) #Function to run the circuit and store the counts for an evolution with # num_steps number of time steps. def sys_evolve(nsites, dt, t, U, num_steps): numq = 2*nsites data = np.zeros((2**numq, num_steps)) for t_step in range(0, num_steps): #Create circuit with t_step number of steps q = QuantumRegister(numq) c = ClassicalRegister(numq) qcirc = QuantumCircuit(q,c) #Initialize circuit by setting the occupation to # a spin up and down electron in the middle site #=========I TURNED THIS OFF FOR A SPECIFIC CASE============== #qcirc.x(int(nsites/2)) #qcirc.x(nsites+int(nsites/2)) # if nsites==3: #Half-filling # qcirc.x(1) # qcirc.x(4) # qcirc.x(0) #1 electron qcirc.x(1) #=======USE THE REGION ABOVE TO SET YOUR INITIAL STATE======= qcirc.barrier() #Append circuit with Trotter steps needed qc_evolve(qcirc, nsites, dt, t, U, t_step) #Choose provider and backend provider = IBMQ.get_provider() #backend = Aer.get_backend('statevector_simulator') backend = Aer.get_backend('qasm_simulator') #backend = provider.get_backend('ibmq_qasm_simulator') #backend = provider.get_backend('ibmqx4') #backend = provider.get_backend('ibmqx2') #backend = provider.get_backend('ibmq_16_melbourne') shots = 8192 max_credits = 10 #Max number of credits to spend on execution job_exp = execute(qcirc, backend=backend, shots=shots, max_credits=max_credits) job_monitor(job_exp) result = job_exp.result() counts = result.get_counts(qcirc) print(result.get_counts(qcirc)) print("Job: ",t_step+1, " of ", time_steps," complete.") #Store results in data array and normalize them for i in range(2**numq): if counts.get(get_bin(i,numq)) is None: dat = 0 else: dat = counts.get(get_bin(i,numq)) data[i,t_step] = dat/shots return data #Run simulation run_results = sys_evolve(nsite, dt, t, U, time_steps) #Process and plot data '''The procedure here is, for each fermionic mode, add the probability of every state containing that mode (at a given time step), and renormalize the data based on the total occupation of each mode. Afterwards, plot the data as a function of time step for each mode.''' proc_data = np.zeros((2*nsite, time_steps)) timesq = np.arange(0.,time_steps*dt, dt) #Sum over time steps for t in range(time_steps): #Sum over all possible states of computer for i in range(2**(2*nsite)): #num = get_bin(i, 2*nsite) num = ''.join( list( reversed(get_bin(i,2*nsite)) ) ) #For each state, check which mode(s) it contains and add them for mode in range(len(num)): if num[mode]=='1': proc_data[mode,t] += run_results[i,t] #Renormalize these sums so that the total occupation of the modes is 1 norm = 0.0 for mode in range(len(num)): norm += proc_data[mode,t] proc_data[:,t] = proc_data[:,t] / norm ''' At this point, proc_data is a 2d array containing the occupation of each mode, for every time step ''' #Create plots of the processed data fig2, ax2 = plt.subplots(figsize=(20,10)) colors = list(mcolors.TABLEAU_COLORS.keys()) for i in range(nsite): #Create string label strup = "Site "+str(i+1)+r'$\uparrow$' strdwn = "Site "+str(i+1)+r'$\downarrow$' ax2.plot(timesq, proc_data[i,:], marker="^", color=str(colors[i]), label=strup) ax2.plot(timesq, proc_data[i+nsite,:], marker="v", color=str(colors[i]), label=strdwn) #ax2.set_ylim(0, 0.55) ax2.set_xlim(0, time_steps*dt+dt/2.) #ax2.set_xticks(np.arange(0,time_steps*dt+dt, 0.2)) #ax2.set_yticks(np.arange(0,0.55, 0.05)) ax2.tick_params(labelsize=16) ax2.set_title('Time Evolution of 3 Site One Dimensional Chain', fontsize=22) ax2.set_xlabel('Time', fontsize=24) ax2.set_ylabel('Probability', fontsize=24) ax2.legend(fontsize=20) #Plot the raw data as a colormap xticks = np.arange(2**(nsite*2)) xlabels=[] print("Time Steps: ",time_steps, " Step Size: ",dt) for i in range(2**(nsite*2)): xlabels.append(get_bin(i,6)) fig, ax = plt.subplots(figsize=(10,20)) c = ax.pcolor(run_results, cmap='binary') ax.set_title('Time Evolution of 3 Site One Dimensional Chain', fontsize=22) plt.yticks(xticks, xlabels, size=18) ax.set_xlabel('Time Step', fontsize=22) ax.set_ylabel('State', fontsize=26) plt.show() #Try by constructing the matrix and finding the eigenvalues N = 3 Nup = 2 Ndwn = N - Nup t = 1.0 U = 2. #Check if two states are different by a single hop def hop(psii, psij): #Check spin down hopp = 0 if psii[0]==psij[0]: #Create array of indices with nonzero values indi = np.nonzero(psii[1])[0] indj = np.nonzero(psij[1])[0] for i in range(len(indi)): if abs(indi[i]-indj[i])==1: hopp = -t return hopp #Check spin up if psii[1]==psij[1]: indi = np.nonzero(psii[0])[0] indj = np.nonzero(psij[0])[0] for i in range(len(indi)): if abs(indi[i]-indj[i])==1: hopp = -t return hopp return hopp #On-site terms def repel(l,state): if state[0][l]==1 and state[1][l]==1: return state else: return [] #States for 3 electrons with net spin up ''' states = [ [[1,1,0],[1,0,0]], [[1,1,0],[0,1,0]], [[1,1,0], [0,0,1]], [[1,0,1],[1,0,0]], [[1,0,1],[0,1,0]], [[1,0,1], [0,0,1]], [[0,1,1],[1,0,0]], [[0,1,1],[0,1,0]], [[0,1,1], [0,0,1]] ] #States for 2 electrons in singlet state ''' states = [ [[1,0,0],[1,0,0]], [[1,0,0],[0,1,0]], [[1,0,0],[0,0,1]], [[0,1,0],[1,0,0]], [[0,1,0],[0,1,0]], [[0,1,0],[0,0,1]], [[0,0,1],[1,0,0]], [[0,0,1],[0,1,0]], [[0,0,1],[0,0,1]] ] #''' #States for a single electron #states = [ [[1,0,0],[0,0,0]], [[0,1,0],[0,0,0]], [[0,0,1],[0,0,0]] ] #''' H = np.zeros((len(states),len(states)) ) #Construct Hamiltonian matrix for i in range(len(states)): psi_i = states[i] for j in range(len(states)): psi_j = states[j] if j==i: for l in range(0,N): if psi_i == repel(l,psi_j): H[i,j] = U break else: H[i,j] = hop(psi_i, psi_j) print(H) results = la.eig(H) print() for i in range(len(results[0])): print('Eigenvalue: ',results[0][i]) print('Eigenvector: \n',results[1][i]) print() dens_ops = [] eigs = [] for vec in results[1]: dens_ops.append(np.outer(results[1][i],results[1][i])) eigs.append(results[0][i]) print(dens_ops) dt = 0.1 tsteps = 50 times = np.arange(0., tsteps*dt, dt) t_op = la.expm(-1j*H*dt) #print(np.subtract(np.identity(len(H)), dt*H*1j)) #print(t_op) wfk = [0., 1., 0., 0., .0, 0., 0., 0., 0.] #Half-filling initial state #wfk = [0., 0., 0., 0., 1.0, 0., 0., 0., 0.] #2 electron initial state #wfk = [0., 1., 0.] #1 electron initial state evolve = np.zeros([tsteps, len(wfk)]) mode_evolve = np.zeros([tsteps, 6]) evolve[0] = wfk #Figure out how to generalize this later #''' mode_evolve[0][0] = (evolve[0][0]+evolve[0][1]+evolve[0][2]) /2. mode_evolve[0][1] = (evolve[0][3]+evolve[0][4]+evolve[0][5]) /2. mode_evolve[0][2] = (evolve[0][6]+evolve[0][7]+evolve[0][8]) /2. mode_evolve[0][3] = (evolve[0][0]+evolve[0][3]+evolve[0][6]) /2. mode_evolve[0][4] = (evolve[0][1]+evolve[0][4]+evolve[0][7]) /2. mode_evolve[0][5] = (evolve[0][2]+evolve[0][5]+evolve[0][8]) /2. ''' mode_evolve[0][0] = (evolve[0][0]+evolve[0][1]+evolve[0][2]+evolve[0][3]+evolve[0][4]+evolve[0][5]) /3. mode_evolve[0][1] = (evolve[0][0]+evolve[0][1]+evolve[0][2]+evolve[0][6]+evolve[0][7]+evolve[0][8]) /3. mode_evolve[0][2] = (evolve[0][3]+evolve[0][4]+evolve[0][5]+evolve[0][6]+evolve[0][7]+evolve[0][8]) /3. mode_evolve[0][3] = (evolve[0][0]+evolve[0][3]+evolve[0][6]) /3. mode_evolve[0][4] = (evolve[0][1]+evolve[0][4]+evolve[0][7]) /3. mode_evolve[0][5] = (evolve[0][2]+evolve[0][5]+evolve[0][8]) /3. ''' print(mode_evolve[0]) #Define density matrices for t in range(1, tsteps): #t_op = la.expm(-1j*H*t) wfk = np.dot(t_op, wfk) evolve[t] = np.multiply(np.conj(wfk), wfk) norm = np.sum(evolve[t]) #print(evolve[t]) #Store data in modes rather than basis defined in 'states' variable #''' #Procedure for two electrons mode_evolve[t][0] = (evolve[t][0]+evolve[t][1]+evolve[t][2]) / (2) mode_evolve[t][1] = (evolve[t][3]+evolve[t][4]+evolve[t][5]) / (2) mode_evolve[t][2] = (evolve[t][6]+evolve[t][7]+evolve[t][8]) / (2) mode_evolve[t][3] = (evolve[t][0]+evolve[t][3]+evolve[t][6]) / (2) mode_evolve[t][4] = (evolve[t][1]+evolve[t][4]+evolve[t][7]) / (2) mode_evolve[t][5] = (evolve[t][2]+evolve[t][5]+evolve[t][8]) / (2) ''' #Procedure for half-filling mode_evolve[t][0] = (evolve[t][0]+evolve[t][1]+evolve[t][2]+evolve[t][3]+evolve[t][4]+evolve[t][5]) /3. mode_evolve[t][1] = (evolve[t][0]+evolve[t][1]+evolve[t][2]+evolve[t][6]+evolve[t][7]+evolve[t][8]) /3. mode_evolve[t][2] = (evolve[t][3]+evolve[t][4]+evolve[t][5]+evolve[t][6]+evolve[t][7]+evolve[t][8]) /3. mode_evolve[t][3] = (evolve[t][0]+evolve[t][3]+evolve[t][6]) /3. mode_evolve[t][4] = (evolve[t][1]+evolve[t][4]+evolve[t][7]) /3. mode_evolve[t][5] = (evolve[t][2]+evolve[t][5]+evolve[t][8]) /3. #''' print(mode_evolve[t]) #print(np.linalg.norm(evolve[t])) #print(len(evolve[:,0]) ) #print(len(times)) #print(evolve[:,0]) #print(min(evolve[:,0])) #Create plots of the processed data fig2, ax2 = plt.subplots(figsize=(20,10)) colors = list(mcolors.TABLEAU_COLORS.keys()) sit1 = "Exact Site "+str(1)+r'$\uparrow$' sit2 = "Exact Site "+str(2)+r'$\uparrow$' sit3 = "Exact Site "+str(3)+r'$\uparrow$' #ax2.plot(times, evolve[:,0], linestyle='--', color=colors[0], linewidth=2.5, label=sit1) #ax2.plot(times, evolve[:,1], linestyle='--', color=str(colors[1]), linewidth=2.5, label=sit2) #ax2.plot(times, evolve[:,2], linestyle='--', color=str(colors[2]), linewidth=2., label=sit3) #ax2.plot(times, np.zeros(len(times))) for i in range(nsite): #Create string label strupq = "Quantum Site "+str(i+1)+r'$\uparrow$' strdwnq = "Quantum Site "+str(i+1)+r'$\downarrow$' strup = "Numerical Site "+str(i+1)+r'$\uparrow$' strdwn = "Numerical Site "+str(i+1)+r'$\downarrow$' #ax2.plot(timesq, proc_data[i,:], marker="*", color=str(colors[i]), markersize=5, label=strupq) #ax2.plot(timesq, proc_data[i+nsite,:], marker="v", color=str(colors[i]), markersize=5, label=strdwnq) ax2.plot(times, mode_evolve[:,i], linestyle='-', color=str(colors[i]), linewidth=2, label=strup) ax2.plot(times, mode_evolve[:,i+3], linestyle='--', color=str(colors[i]), linewidth=2, label=strdwn) #ax2.plot(times, evolve[:,i], linestyle='-', color=str(colors[i]), linewidth=2, label=strup) #ax2.plot(times, evolve[:,i+3], linestyle='--', color=str(colors[i]), linewidth=2, label=strdwn) ax2.set_ylim(0, .5) ax2.set_xlim(0, tsteps*dt+dt/2.) ax2.set_xticks(np.arange(0,tsteps*dt+dt, 2*dt)) ax2.set_yticks(np.arange(0,0.5, 0.05)) ax2.tick_params(labelsize=16) ax2.set_title('Time Evolution of 2 Electrons in 3 Site Chain', fontsize=22) ax2.set_xlabel('Time', fontsize=24) ax2.set_ylabel('Probability', fontsize=24) ax2.legend(fontsize=20)
https://github.com/kaelynj/Qiskit-HubbardModel
kaelynj
#Jupyter notebook to check if imports work correctly %matplotlib inline import sys sys.path.append('./src') import HubbardEvolutionChain as hc import ClassicalHubbardEvolutionChain as chc from qiskit import QuantumCircuit, execute, Aer, IBMQ, BasicAer, QuantumRegister, ClassicalRegister from qiskit.compiler import transpile, assemble from qiskit.quantum_info import Operator from qiskit.tools.monitor import job_monitor from qiskit.tools.jupyter import * import qiskit.visualization as qvis import random as rand import scipy.linalg as la provider = IBMQ.load_account() import matplotlib.pyplot as plt import matplotlib.colors as mcolors import numpy as np from matplotlib import rcParams rcParams['text.usetex'] = True def get_bin(x, n=0): """ Get the binary representation of x. Parameters: x (int), n (int, number of digits)""" binry = format(x, 'b').zfill(n) sup = list( reversed( binry[0:int(len(binry)/2)] ) ) sdn = list( reversed( binry[int(len(binry)/2):len(binry)] ) ) return format(x, 'b').zfill(n) #Energy Measurement Functions #Measure the total repulsion from circuit run def measure_repulsion(U, num_sites, results, shots): repulsion = 0. #Figure out how to include different hoppings later for state in results: for i in range( int( len(state)/2 ) ): if state[i]=='1': if state[i+num_sites]=='1': repulsion += U*results.get(state)/shots return repulsion def measure_hopping(hopping, pairs, circuit, num_qubits): #Add diagonalizing circuit for pair in pairs: circuit.cnot(pair[0],pair[1]) circuit.ch(pair[1],pair[0]) circuit.cnot(pair[0],pair[1]) #circuit.measure(pair[0],pair[0]) #circuit.measure(pair[1],pair[1]) circuit.measure_all() #Run circuit backend = Aer.get_backend('qasm_simulator') shots = 8192 max_credits = 10 #Max number of credits to spend on execution #print("Computing Hopping") hop_exp = execute(circuit, backend=backend, shots=shots, max_credits=max_credits) job_monitor(hop_exp) result = hop_exp.result() counts = result.get_counts(circuit) #print(counts) #Compute energy #print(pairs) for pair in pairs: hop_eng = 0. #print('Pair is: ',pair) for state in counts: #print('State is: ',state,' Index at pair[0]: ',num_qubits-1-pair[0],' Val: ',state[num_qubits-pair[0]]) if state[num_qubits-1-pair[0]]=='1': prob_01 = counts.get(state)/shots #print('Check state is: ',state) for comp_state in counts: #print('Comp State is: ',state,' Index at pair[0]: ',num_qubits-1-pair[1],' Val: ',comp_state[num_qubits-pair[0]]) if comp_state[num_qubits-1-pair[1]]=='1': #print('Comp state is: ',comp_state) hop_eng += -hopping*(prob_01 - counts.get(comp_state)/shots) return hop_eng #nsites, excitations, total_time, dt, hop, U, trotter_steps dt = 0.25 #Delta t total_time = 5. #time_steps = int(T/dt) hop = 1.0 #Hopping parameter #t = [1.0, 2.] U = 2. #On-Site repulsion #time_steps = 10 nsites = 3 trotter_steps = 1000 excitations = np.array([1]) numq = 2*nsites num_steps = int(total_time/dt) print('Num Steps: ',num_steps) print('Total Time: ', total_time) data = np.zeros((2**numq, num_steps)) energies = np.zeros(num_steps) for t_step in range(0, num_steps): #Create circuit with t_step number of steps q = QuantumRegister(numq) c = ClassicalRegister(numq) qcirc = QuantumCircuit(q,c) #=========USE THIS REGION TO SET YOUR INITIAL STATE============== #Loop over each excitation for flip in excitations: qcirc.x(flip) #=============================================================== qcirc.barrier() #Append circuit with Trotter steps needed hc.qc_evolve(qcirc, nsites, t_step*dt, hop, U, trotter_steps) #Measure the circuit for i in range(numq): qcirc.measure(i, i) #Choose provider and backend provider = IBMQ.get_provider() #backend = Aer.get_backend('statevector_simulator') backend = Aer.get_backend('qasm_simulator') #backend = provider.get_backend('ibmq_qasm_simulator') #backend = provider.get_backend('ibmqx4') #backend = provider.get_backend('ibmqx2') #backend = provider.get_backend('ibmq_16_melbourne') shots = 8192 max_credits = 10 #Max number of credits to spend on execution job_exp = execute(qcirc, backend=backend, shots=shots, max_credits=max_credits) #job_monitor(job_exp) result = job_exp.result() counts = result.get_counts(qcirc) print(result.get_counts(qcirc)) print("Job: ",t_step+1, " of ", num_steps," computing energy...") #Store results in data array and normalize them for i in range(2**numq): if counts.get(get_bin(i,numq)) is None: dat = 0 else: dat = counts.get(get_bin(i,numq)) data[i,t_step] = dat/shots #======================================================= #Compute energy of system #Compute repulsion energies repulsion_energy = measure_repulsion(U, nsites, counts, shots) print('Repulsion: ', repulsion_energy) #Compute hopping energies #Get list of hopping pairs even_pairs = [] for i in range(0,nsites-1,2): #up_pair = [i, i+1] #dwn_pair = [i+nsites, i+nsites+1] even_pairs.append([i, i+1]) even_pairs.append([i+nsites, i+nsites+1]) odd_pairs = [] for i in range(1,nsites-1,2): odd_pairs.append([i, i+1]) odd_pairs.append([i+nsites, i+nsites+1]) #Start with even hoppings, initialize circuit and find hopping pairs q = QuantumRegister(numq) c = ClassicalRegister(numq) qcirc = QuantumCircuit(q,c) #Loop over each excitation for flip in excitations: qcirc.x(flip) qcirc.barrier() #Append circuit with Trotter steps needed hc.qc_evolve(qcirc, nsites, t_step*dt, hop, U, trotter_steps) '''for pair in odd_pairs: qcirc.cnot(pair[0],pair[1]) qcirc.ch(pair[1],pair[0]) qcirc.cnot(pair[0],pair[1]) qcirc.measure(pair[0],pair[0]) qcirc.measure(pair[1],pair[1]) #circuit.draw() print(t_step) ''' #break even_hopping = measure_hopping(hop, even_pairs, qcirc, numq) print('Even hopping: ', even_hopping) #=============================================================== #Now do the same for the odd hoppings #Start with even hoppings, initialize circuit and find hopping pairs q = QuantumRegister(numq) c = ClassicalRegister(numq) qcirc = QuantumCircuit(q,c) #Loop over each excitation for flip in excitations: qcirc.x(flip) qcirc.barrier() #Append circuit with Trotter steps needed hc.qc_evolve(qcirc, nsites, t_step*dt, hop, U, trotter_steps) odd_hopping = measure_hopping(hop, odd_pairs, qcirc, numq) print('Odd hopping: ',odd_hopping) total_energy = repulsion_energy + even_hopping + odd_hopping print(total_energy) energies[t_step] = total_energy print("Total Energy is: ", total_energy) print("Job: ",t_step+1, " of ", num_steps," complete") #qcirc.draw() plt.plot(energies) print(np.ptp(energies)) #Trotter Steps=1000 plt.plot(energies) print(np.ptp(energies)) #Trotter Steps=100 plt.plot(energies) print(np.ptp(energies)) #Trotter Steps=50 plt.plot(energies) print(np.ptp(energies)) #Trotter Steps=10 plt.plot(energies) print(np.ptp(energies)) #Trotter Steps=100
https://github.com/kaelynj/Qiskit-HubbardModel
kaelynj
my_list = [1,3,6,8,2,7,5,7,9,2,16,4] def my_oracle(my_input): winner = 9 response = False if winner == my_input: response = True return response for index, number in enumerate(my_list): if (my_oracle(number) == True): print("Winner winner chicken dinner! at index = %i"%index) print("%i times the Oracle was called"%(index+1)) break from qiskit import * import matplotlib.pyplot as plt import numpy as np # create the oracle quantum circuit oracle = QuantumCircuit(2, name='oracle') oracle.cz(0,1) # apply the Controlled-Z gate or CZ gate oracle.to_gate() # make oracle into its own gate oracle.draw() backend = Aer.get_backend('statevector_simulator') grover_circuit = QuantumCircuit(2,2) # 2 qubits, 2 classical registers grover_circuit.h([0,1]) # apply hadamard gate on both qubits 0 and 1 to prepare superposition state discussed in description.md grover_circuit.append(oracle, [0,1]) # append oracle to be able to query each state at same time grover_circuit.draw() job = execute(grover_circuit, backend) result = job.result() sv = result.get_statevector() np.around(sv, 2) reflection = QuantumCircuit(2, name='reflection') reflection.h([0,1]) # apply hadamard gate on all qubits to bring them back to '00' state from the original 's' state reflection.z([0,1]) # apply Z gate on both qubits reflection.cz(0,1) # controlled-z gate reflection.h([0,1]) # transform back with hadamard on both qubits reflection.to_gate() reflection.draw() backend = Aer.get_backend('qasm_simulator') grover_circuit = QuantumCircuit(2,2) grover_circuit.h([0,1]) grover_circuit.append(oracle, [0,1]) grover_circuit.append(reflection, [0,1]) grover_circuit.measure([0,1], [0,1]) grover_circuit.draw() job = execute(grover_circuit, backend, shots=1) result = job.result() result.get_counts()
https://github.com/kaelynj/Qiskit-HubbardModel
kaelynj
#Jupyter notebook to check if imports work correctly %matplotlib inline import sys sys.path.append('./src') import HubbardEvolutionChain as hc import ClassicalHubbardEvolutionChain as chc import FullClassicalHubbardEvolutionChain as fhc from qiskit import QuantumCircuit, execute, Aer, IBMQ, BasicAer, QuantumRegister, ClassicalRegister from qiskit.compiler import transpile, assemble from qiskit.quantum_info import Operator from qiskit.tools.monitor import job_monitor from qiskit.tools.jupyter import * import qiskit.visualization as qvis import random as rand import scipy.linalg as la provider = IBMQ.load_account() import matplotlib.pyplot as plt import matplotlib.colors as mcolors import numpy as np from matplotlib import rcParams rcParams['text.usetex'] = True def get_bin(x, n=0): """ Get the binary representation of x. Parameters: x (int), n (int, number of digits)""" binry = format(x, 'b').zfill(n) sup = list( reversed( binry[0:int(len(binry)/2)] ) ) sdn = list( reversed( binry[int(len(binry)/2):len(binry)] ) ) return format(x, 'b').zfill(n) #==========Set Parameters of the System=============# dt = 0.25 #Delta t T = 5. time_steps = int(T/dt) t = 1.0 #Hopping parameter #t = [1.0, 2.] U = 2. #On-Site repulsion #time_steps = 10 nsites = 3 trotter_slices = 10 initial_state = np.array([1]) '''#Run simulation run_results1 = hc.sys_evolve(nsites, initial_state, T, dt, t, U, 10) run_results2 = hc.sys_evolve(nsites, initial_state, T, dt, t, U, 40) run_results3, eng3 = hc.sys_evolve_eng(nsites, initial_state, T, dt, t, U, 150) run_results4 = hc.sys_evolve(nsites, initial_state, T, dt, t, U, 100) #print(True if np.isscalar(initial_state) else False) ''' #Fidelity measurements #run_results1, engs1 = hc.sys_evolve_eng(nsites, initial_state, T, dt, t, U, 10) run_results2 = hc.sys_evolve_den(nsites, initial_state, T, dt, t, U, 40) #run_results3, engs3 = hc.sys_evolve_eng(nsites, initial_state, T, dt, t, U, 100) #run_results4, engs4 = hc.sys_evolve_eng(nsites, initial_state, T, dt, t, U, 150) #Collect data on how Trotter steps change energy range trotter_range = [10, 20, 30, 40, 50, 60, 70, 80] eng_range = [] #engs = [] #runs = [] ''' for trot_step in trotter_range: run_results3, eng3 = hc.sys_evolve_eng(nsites, initial_state, T, dt, t, U, trot_step) runs.append(run_results3[:,-1]) eng_range.append(np.ptp(eng3)) engs.append(eng3) ''' #sample_run = run_results3[:,-1] #print(sample_run) #print(run_results3[:,-1],' ',len(run_results3[:,-1])) #print(tp_run[-1],' ',len(tp_run[-1])) #Plot the raw data as a colormap #xticks = np.arange(2**(nsites*2)) xlabels=[] print("Time Steps: ",time_steps, " Step Size: ",dt) for i in range(2**(nsites*2)): xlabels.append(hc.get_bin(i,6)) fig, ax = plt.subplots(figsize=(10,20)) c = ax.pcolor(np.transpose(runs), cmap='binary') ax.set_title('Basis State Amplitude', fontsize=22) plt.yticks(np.arange(2**(nsites*2)), xlabels, size=18) plt.xticks(np.arange(0,13), trotter_range, size=18) ax.set_xlabel('No. of Trotter Steps', fontsize=22) ax.set_ylabel('State', fontsize=26) plt.show() #plt.plot(trotter_range, eng_range) #plt.xlabel('No. of Trotter Steps', fontsize=18) #plt.ylabel('Energy Range', fontsize=18) proc_data = np.zeros([2*nsites, len(trotter_range)]) runs_array = np.array(runs) for step in range(0,len(trotter_range)): for i in range(0,2**(2*nsites)): num = ''.join( list( reversed(hc.get_bin(i,2*nsites)) ) ) #print('i: ', i,' step: ',step) for mode in range(len(num)): if num[mode]=='1': proc_data[mode, step] += runs_array[step, i] norm = 0. for mode in range(len(num)): norm += proc_data[mode, step] proc_data[:,step] = proc_data[:,step] / norm print(proc_data[0,:]) #============ Run Classical Evolution ==============# #Define our basis states #States for 3 electrons with net spin up ''' states = [ [[1,1,0],[1,0,0]], [[1,1,0],[0,1,0]], [[1,1,0], [0,0,1]], [[1,0,1],[1,0,0]], [[1,0,1],[0,1,0]], [[1,0,1], [0,0,1]], [[0,1,1],[1,0,0]], [[0,1,1],[0,1,0]], [[0,1,1], [0,0,1]] ] ''' #States for 2 electrons in singlet state states = [ [[1,0,0],[1,0,0]], [[1,0,0],[0,1,0]], [[1,0,0],[0,0,1]], [[0,1,0],[1,0,0]], [[0,1,0],[0,1,0]], [[0,1,0],[0,0,1]], [[0,0,1],[1,0,0]], [[0,0,1],[0,1,0]], [[0,0,1],[0,0,1]] ] #''' #States for a single electron #states = [ [[1,0,0],[0,0,0]], [[0,1,0],[0,0,0]], [[0,0,1],[0,0,0]] ] #Possible initial wavefunctions #wfk = [0., 0., 0., 0., 1., 0., 0., 0., 0.] #Half-filling initial state (101010) wfk = [0., 0., 0., 0., 1.0, 0., 0., 0., 0.] #2 electron initial state (010010) #wfk = [0., 0., 0., 0., 0., 1., 0., 0., 0.] #2 electron initial state (010001) #wfk = [0., -1., 0.] #1 electron initial state #System parameters t = 1.0 U = 2. classical_time_step = 0.01 classical_total_time = 500*0.01 times = np.arange(0., classical_total_time, classical_time_step) states = fhc.get_states(numsites) evolution, engs = chc.sys_evolve(states, wfk, t, U, classical_total_time, classical_time_step) print(evolution[-25]) #System parameters t = 1.0 U = 2. classical_time_step = 0.01 classical_total_time = 500*0.01 times = np.arange(0., classical_total_time, classical_time_step) states = fhc.get_states(nsites) #print(states) #print(states[64]) wfk_full = np.zeros(len(states), dtype=np.complex_) target_state = [[0,1], [0,0]] target_index = 0 for l in range(len(states)): if len(target_state) == sum([1 for i, j in zip(target_state, states[l]) if i == j]): print('Target state found at: ',l) target_index = l #wfk_full[18] = 1. #010010 #wfk_full[21] = 1. #010101 #wfk_full[42] = 1. #101010 wfk_full[2] = 1. #000010 #wfk_full[target_index] = 1. #wfk_full[2] = 0.5 - 0.5*1j #wfk_full[0] = 1/np.sqrt(2) print(wfk_full) evolution, engs, wfks = fhc.sys_evolve(states, wfk_full, t, U, classical_total_time, classical_time_step) #print(wfks[-26]) #print(run_results1[-1]) tst = np.outer(np.conj(wfks[-25]),wfks[-25]) #print(times[-25]) #print(np.shape(tst)) def fidelity(numerical_density, quantum_density): sqrt_quantum = la.sqrtm(quantum_density) fidelity_matrix = np.matmul(sqrt_quantum, np.matmul(numerical_density,sqrt_quantum)) fidelity_matrix = la.sqrtm(fidelity_matrix) trace = np.trace(fidelity_matrix) trace2 = np.conj(trace)*trace #Try tr(rho*sigma)+sqrt(det(rho)*det(sigma)) fidelity = np.trace(np.matmul(numerical_density, quantum_density)) + np.sqrt(np.linalg.det(numerical_density)*np.linalg.det(quantum_density)) return fidelity print("Fidelity") print( fidelity( run_results2[-1], tst) ) print('============================') print('Trace') print('Numerical: ',np.trace(tst)) print('Quantum: ',np.trace(run_results2[-1])) print('============================') print('Square Trace') print('Numerical: ',np.trace(np.matmul(tst, tst))) print('Quantum: ',np.trace(np.matmul(run_results2[-1], run_results2[-1]))) print('============================') fidelities = [] fidelities.append(fidelity(tst, run_results1[-1])) fidelities.append(fidelity(tst, run_results2[-1])) fidelities.append(fidelity(tst, run_results3[-1])) fidelities.append(fidelity(tst, run_results4[-1])) trotters = [10, 40, 100, 150] plt.plot(trotters, fidelities) #Calculate RootMeanSquare rms = np.zeros(len(trotter_range)) for trotter_index in range(len(trotter_range)): sq_diff = 0. for mode in range(2*nsites): sq_diff += (evolution[-25, mode] - proc_data[mode, trotter_index])**2 rms[trotter_index] = np.sqrt(sq_diff / 2*nsites) plt.plot(trotter_range, rms) plt.xlabel('Trotter Steps', fontsize=14) plt.ylabel('RMS',fontsize=14) plt.title('RMS for 1 Electrons 010000', fontsize=14) #Create plots of the processed data fig2, ax2 = plt.subplots(figsize=(20,10)) colors = list(mcolors.TABLEAU_COLORS.keys()) for i in range(nsites): #Create string label strup = "Site "+str(i+1)+r'$\uparrow$' strdwn = "Site "+str(i+1)+r'$\downarrow$' ax2.plot(trotter_range, proc_data[i,:], marker="^", color=str(colors[i]), label=strup) ax2.plot(trotter_range, proc_data[i+nsites,:], marker="v", linestyle='--', color=str(colors[i]), label=strdwn) ax2.plot(trotter_range, np.full(len(trotter_range), evolution[-1, i]), linestyle='-', color=str(colors[i]),label=strup) ax2.plot(trotter_range, np.full(len(trotter_range), evolution[-1, i+nsites]), linestyle='-', color=str(colors[i]),label=strdwn) #ax2.set_ylim(0, 0.55) #ax2.set_xlim(0, time_steps*dt+dt/2.) #ax2.set_xticks(np.arange(0,time_steps*dt+dt, 0.2)) #ax2.set_yticks(np.arange(0,0.55, 0.05)) ax2.tick_params(labelsize=16) ax2.set_title('Probability Convergence for 3 electrons', fontsize=22) ax2.set_xlabel('Number of Trotter Steps', fontsize=24) ax2.set_ylabel('Probability', fontsize=24) ax2.legend(fontsize=20) processed_data3 = hc.process_run(nsites, time_steps, dt, run_results3) tdat = np.arange(0.,T, dt) norm_dat = [np.sum(x) for x in np.transpose(processed_data3)] print(norm_dat) print(eng3) #plt.plot(norm_dat) plt.plot(tdat, eng3, label='80 Steps') plt.plot(times, engs, label='Numerical') plt.xlabel('Time', fontsize=18) plt.ylabel('Energy',fontsize=18) plt.ylim(-1e-5, 1e-5) plt.legend() print(np.ptp(eng3)) ## ============ Run Classical Evolution ============== #Define our basis states #States for 3 electrons with net spin up ''' states = [ [[1,1,0],[1,0,0]], [[1,1,0],[0,1,0]], [[1,1,0], [0,0,1]], [[1,0,1],[1,0,0]], [[1,0,1],[0,1,0]], [[1,0,1], [0,0,1]], [[0,1,1],[1,0,0]], [[0,1,1],[0,1,0]], [[0,1,1], [0,0,1]] ] ''' #States for 2 electrons in singlet state states = [ [[1,0,0],[1,0,0]], [[1,0,0],[0,1,0]], [[1,0,0],[0,0,1]], [[0,1,0],[1,0,0]], [[0,1,0],[0,1,0]], [[0,1,0],[0,0,1]], [[0,0,1],[1,0,0]], [[0,0,1],[0,1,0]], [[0,0,1],[0,0,1]] ] #''' #States for a single electron #states = [ [[1,0,0],[0,0,0]], [[0,1,0],[0,0,0]], [[0,0,1],[0,0,0]] ] #Possible initial wavefunctions #wfk = [0., 0., 0., 0., 1., 0., 0., 0., 0.] #Half-filling initial state wfk = [0., 0., 0., 0., 1.0, 0., 0., 0., 0.] #2 electron initial state #wfk = [0., 1., 0.] #1 electron initial state #System parameters for evolving system numerically t = 1.0 U = 2. classical_time_step = 0.01 classical_total_time = 500*0.01 times = np.arange(0., classical_total_time, classical_time_step) evolution, engs = chc.sys_evolve(states, wfk, t, U, classical_total_time, classical_time_step) #Get norms and energies as a function of time. Round to 10^-12 norms = np.array([np.sum(x) for x in evolution]) norms = np.around(norms, 12) engs = np.around(engs, 12) #Create plots of the processed data fig2, ax2 = plt.subplots(figsize=(20,10)) fig3, ax3 = plt.subplots(1, 2, figsize=(20,10)) colors = list(mcolors.TABLEAU_COLORS.keys()) cos = np.cos(np.sqrt(2)*times)**2 sit1 = "Site "+str(1)+r'$\uparrow$' sit2 = "Site "+str(2)+r'$\uparrow$' sit3 = "Site "+str(3)+r'$\uparrow$' #ax2.plot(times, evolve[:,0], marker='.', color='k', linewidth=2, label=sit1) #ax2.plot(times, evolve[:,1], marker='.', color=str(colors[0]), linewidth=2, label=sit2) #ax2.plot(times, evolve[:,2], marker='.', color=str(colors[1]), linewidth=1.5, label=sit3) #ax2.plot(times, cos, label='cosdat') #ax2.plot(times, np.zeros(len(times))) for i in range(3): #Create string label strup = "Site "+str(i+1)+r'$\uparrow$' strdwn = "Site "+str(i+1)+r'$\downarrow$' ax2.plot(times, evolution[:,i], linestyle='-', color=str(colors[i]), linewidth=2, label=strup) ax2.plot(times, evolution[:,i+3], linestyle='--', color=str(colors[i]), linewidth=2, label=strdwn) #ax2.set_ylim(0, 1.) ax2.set_xlim(0, classical_total_time) #ax2.set_xlim(0, 1.) ax2.set_xticks(np.arange(0,classical_total_time, 0.2)) #ax2.set_yticks(np.arange(0,1.1, 0.05)) ax2.tick_params(labelsize=16) ax2.set_title('Time Evolution of 3 Site One Dimensional Chain', fontsize=22) ax2.set_xlabel('Time', fontsize=24) ax2.set_ylabel('Probability', fontsize=24) ax2.legend(fontsize=20) #Plot energy and normalization ax3[0].plot(times, engs, color='b') ax3[1].plot(times, norms, color='r') ax3[0].set_xlabel('Time', fontsize=24) ax3[0].set_ylabel('Energy [t]', fontsize=24) ax3[1].set_xlabel('Time', fontsize=24) ax3[1].set_ylabel('Normalization', fontsize=24) print(evolution) #processed_data1 = hc.process_run(nsites, time_steps, dt, run_results1) #processed_data2 = hc.process_run(nsites, time_steps, dt, run_results2) processed_data3 = hc.process_run(nsites, time_steps, dt, run_results3) #processed_data4 = hc.process_run(nsites, time_steps, dt, run_results4) timesq = np.arange(0, time_steps*dt, dt) #Create plots of the processed data #fig0, ax0 = plt.subplots(figsize=(20,10)) fig1, ax1 = plt.subplots(figsize=(20,10)) fig2, ax2 = plt.subplots(figsize=(20,10)) fig3, ax3 = plt.subplots(figsize=(20,10)) fig4, ax4 = plt.subplots(figsize=(20,10)) fig5, ax5 = plt.subplots(figsize=(20,10)) colors = list(mcolors.TABLEAU_COLORS.keys()) ''' #Plot energies ax0.plot(timesq, eng1, color=str(colors[0]), label='10 Steps') ax0.plot(timesq, eng2, color=str(colors[1]), label='20 Steps') ax0.plot(timesq, eng3, color=str(colors[2]), label='40 Steps') ax0.plot(timesq, eng4, color=str(colors[3]), label='60 Steps') ax0.legend(fontsize=20) ax0.set_xlabel("Time", fontsize=24) ax0.set_ylabel("Total Energy", fontsize=24) ax0.tick_params(labelsize=16) ''' #Site 1 strup = "10 Steps"+r'$\uparrow$' strdwn = "10 Steps"+r'$\downarrow$' #ax1.plot(timesq, processed_data1[0,:], marker="^", color=str(colors[0]), label=strup) #ax1.plot(timesq, processed_data1[0+nsites,:], linestyle='--', marker="v", color=str(colors[0]), label=strdwn) strup = "40 Steps"+r'$\uparrow$' strdwn = "40 Steps"+r'$\downarrow$' #ax1.plot(timesq, processed_data2[0,:], marker="^", color=str(colors[1]), label=strup) #ax1.plot(timesq, processed_data2[0+nsites,:], linestyle='--', marker="v", color=str(colors[1]), label=strdwn) strup = "80 Steps"+r'$\uparrow$' strdwn = "80 Steps"+r'$\downarrow$' ax1.plot(timesq, processed_data3[0,:], marker="^", color=str(colors[2]), label=strup) ax1.plot(timesq, processed_data3[0+nsites,:],linestyle='--', marker="v", color=str(colors[2]), label=strdwn) strup = "100 Steps"+r'$\uparrow$' strdwn = "100 Steps"+r'$\downarrow$' #ax1.plot(timesq, processed_data3[0,:], marker="^", color=str(colors[3]), label=strup) #ax1.plot(timesq, processed_data3[0+nsites,:], linestyle='--', marker="v", color=str(colors[3]), label=strdwn) strup = "Exact"+r'$\uparrow$' strdwn = "Exact"+r'$\downarrow$' #1e numerical evolution ax1.plot(times, evolution[:,0], linestyle='-', color='k', linewidth=2, label=strup) ax1.plot(times, evolution[:,0+nsites], linestyle='--', color='k', linewidth=2, label=strdwn) #2e+ numerical evolution #ax1.plot(times, mode_evolve[:,0], linestyle='-', color='k', linewidth=2, label=strup) #ax1.plot(times, mode_evolve[:,0+nsites], linestyle='--', color='k', linewidth=2, label=strdwn) #Site 2 strup = "10 Steps"+r'$\uparrow$' strdwn = "10 Steps"+r'$\downarrow$' #ax2.plot(timesq, processed_data1[1,:], marker="^", color=str(colors[0]), label=strup) #ax2.plot(timesq, processed_data1[1+nsites,:], marker="v", linestyle='--',color=str(colors[0]), label=strdwn) strup = "40 Steps"+r'$\uparrow$' strdwn = "40 Steps"+r'$\downarrow$' #ax2.plot(timesq, processed_data2[1,:], marker="^", color=str(colors[1]), label=strup) #ax2.plot(timesq, processed_data2[1+nsites,:], marker="v", linestyle='--',color=str(colors[1]), label=strdwn) strup = "80 Steps"+r'$\uparrow$' strdwn = "80 Steps"+r'$\downarrow$' ax2.plot(timesq, processed_data3[1,:], marker="^", color=str(colors[2]), label=strup) ax2.plot(timesq, processed_data3[1+nsites,:], marker="v", linestyle='--', color=str(colors[2]), label=strdwn) strup = "100 Steps"+r'$\uparrow$' strdwn = "100 Steps"+r'$\downarrow$' #ax2.plot(timesq, processed_data4[1,:], marker="^", color=str(colors[3]), label=strup) #ax2.plot(timesq, processed_data4[1+nsites,:], marker="v", linestyle='--', color=str(colors[3]), label=strdwn) #1e numerical evolution strup = "Exact"+r'$\uparrow$' strdwn = "Exact"+r'$\downarrow$' ax2.plot(times, evolution[:,1], linestyle='-', color='k', linewidth=2, label=strup) ax2.plot(times, evolution[:,1+nsites], linestyle='--', color='k', linewidth=2, label=strdwn) #2e+ numerical evolution #ax2.plot(times, mode_evolve[:,1], linestyle='-', color='k', linewidth=2, label=strup) #ax2.plot(times, mode_evolve[:,1+nsites], linestyle='--', color='k', linewidth=2, label=strdwn) #Site 3 strup = "10 Steps"+r'$\uparrow$' strdwn = "10 Steps"+r'$\downarrow$' #ax3.plot(timesq, processed_data1[2,:], marker="^", color=str(colors[0]), label=strup) #ax3.plot(timesq, processed_data1[2+nsites,:], marker="v", linestyle='--', color=str(colors[0]), label=strdwn) strup = "40 Steps"+r'$\uparrow$' strdwn = "40 Steps"+r'$\downarrow$' #ax3.plot(timesq, processed_data2[2,:], marker="^", color=str(colors[1]), label=strup) #ax3.plot(timesq, processed_data2[2+nsites,:], marker="v", linestyle='--', color=str(colors[1]), label=strdwn) strup = "80 Steps"+r'$\uparrow$' strdwn = "80 Steps"+r'$\downarrow$' ax3.plot(timesq, processed_data3[2,:], marker="^", color=str(colors[2]), label=strup) ax3.plot(timesq, processed_data3[2+nsites,:], marker="v", linestyle='--', color=str(colors[2]), label=strdwn) strup = "100 Steps"+r'$\uparrow$' strdwn = "100 Steps"+r'$\downarrow$' #ax3.plot(timesq, processed_data4[2,:], marker="^", color=str(colors[3]), label=strup) #ax3.plot(timesq, processed_data4[2+nsites,:], marker="v", linestyle='--', color=str(colors[3]), label=strdwn) #1e numerical evolution strup = "Exact"+r'$\uparrow$' strdwn = "Exact"+r'$\downarrow$' ax3.plot(times, evolution[:,2], linestyle='-', color='k', linewidth=2, label=strup) ax3.plot(times, evolution[:,2+nsites], linestyle='--', color='k', linewidth=2, label=strdwn) #2e+ numerical evolution #ax3.plot(times, mode_evolve[:,2], linestyle='-', color='k', linewidth=2, label=strup) #ax3.plot(times, mode_evolve[:,2+nsites], linestyle='--', color='k', linewidth=2, label=strdwn) #Site 4 r''' strup = "10 Steps"+r'$\uparrow$' strdwn = "10 Steps"+r'$\downarrow$' #ax4.plot(timesq, processed_data1[3,:], marker="^", color=str(colors[0]), label=strup) #ax4.plot(timesq, processed_data1[3+nsites,:], marker="v", linestyle='--', color=str(colors[0]), label=strdwn) strup = "40 Steps"+r'$\uparrow$' strdwn = "40 Steps"+r'$\downarrow$' #ax4.plot(timesq, processed_data2[3,:], marker="^", color=str(colors[1]), label=strup) #ax4.plot(timesq, processed_data2[3+nsites,:], marker="v", linestyle='--', color=str(colors[1]), label=strdwn) strup = "150 Steps"+r'$\uparrow$' strdwn = "150 Steps"+r'$\downarrow$' ax4.plot(timesq, processed_data3[3,:], marker="^", color=str(colors[2]), label=strup) ax4.plot(timesq, processed_data3[3+nsites,:], marker="v", linestyle='--', color=str(colors[2]), label=strdwn) strup = "100 Steps"+r'$\uparrow$' strdwn = "100 Steps"+r'$\downarrow$' #ax4.plot(timesq, processed_data4[3,:], marker="^", color=str(colors[3]), label=strup) #ax4.plot(timesq, processed_data4[3+nsites,:], marker="v", linestyle='--', color=str(colors[3]), label=strdwn) #1e numerical evolution strup = "Exact"+r'$\uparrow$' strdwn = "Exact"+r'$\downarrow$' ax4.plot(times, evolution[:,3], linestyle='-', color='k', linewidth=2, label=strup) ax4.plot(times, evolution[:,3+nsites], linestyle='--', color='k', linewidth=2, label=strdwn) #2e+ numerical evolution #ax3.plot(times, mode_evolve[:,2], linestyle='-', color='k', linewidth=2, label=strup) #ax3.plot(times, mode_evolve[:,2+nsites], linestyle='--', color='k', linewidth=2, label=strdwn) #Site 5 strup = "10 Steps"+r'$\uparrow$' strdwn = "10 Steps"+r'$\downarrow$' ax5.plot(timesq, processed_data1[4,:], marker="^", color=str(colors[0]), label=strup) ax5.plot(timesq, processed_data1[4+nsites,:], marker="v", linestyle='--', color=str(colors[0]), label=strdwn) strup = "40 Steps"+r'$\uparrow$' strdwn = "40 Steps"+r'$\downarrow$' #ax5.plot(timesq, processed_data2[4,:], marker="^", color=str(colors[1]), label=strup) #ax5.plot(timesq, processed_data2[4+nsites,:], marker="v", linestyle='--', color=str(colors[1]), label=strdwn) strup = "150 Steps"+r'$\uparrow$' strdwn = "150 Steps"+r'$\downarrow$' ax5.plot(timesq, processed_data3[4,:], marker="^", color=str(colors[2]), label=strup) ax5.plot(timesq, processed_data3[4+nsites,:], marker="v", linestyle='--', color=str(colors[2]), label=strdwn) strup = "100 Steps"+r'$\uparrow$' strdwn = "100 Steps"+r'$\downarrow$' #ax5.plot(timesq, processed_data4[4,:], marker="^", color=str(colors[3]), label=strup) #ax5.plot(timesq, processed_data4[4+nsites,:], marker="v", linestyle='--', color=str(colors[3]), label=strdwn) #1e numerical evolution strup = "Exact"+r'$\uparrow$' strdwn = "Exact"+r'$\downarrow$' ax5.plot(times, evolution[:,4], linestyle='-', color='k', linewidth=2, label=strup) ax5.plot(times, evolution[:,4+nsites], linestyle='--', color='k', linewidth=2, label=strdwn) #2e+ numerical evolution #ax3.plot(times, mode_evolve[:,2], linestyle='-', color='k', linewidth=2, label=strup) #ax3.plot(times, mode_evolve[:,2+nsites], linestyle='--', color='k', linewidth=2, label=strdwn) r''' #ax2.set_ylim(0, 0.55) #ax2.set_xlim(0, time_steps*dt+dt/2.) #ax2.set_xticks(np.arange(0,time_steps*dt+dt, 0.2)) #ax2.set_yticks(np.arange(0,0.55, 0.05)) ax1.tick_params(labelsize=16) ax2.tick_params(labelsize=16) ax3.tick_params(labelsize=16) ax4.tick_params(labelsize=16) ax5.tick_params(labelsize=16) ax1.set_title(r"Time Evolution of Site 1: 1/sqrt(2)*000000 + (0.5-0.5i)*0100000", fontsize=22) ax2.set_title(r"Time Evolution of Site 2: 1/sqrt(2)*000000 + (0.5-0.5i)*0100000", fontsize=22) ax3.set_title(r"Time Evolution of Site 3: 1/sqrt(2)*000000 + (0.5-0.5i)*0100000", fontsize=22) ax4.set_title(r"Time Evolution of Site 4: 1/sqrt(2)*000000 + (0.5-0.5i)*0100000", fontsize=22) ax5.set_title(r"Time Evolution of Site 5: 1/sqrt(2)*000000 + (0.5-0.5i)*0100000", fontsize=22) ax1.set_xlabel('Time', fontsize=24) ax2.set_xlabel('Time', fontsize=24) ax3.set_xlabel('Time', fontsize=24) ax4.set_xlabel('Time', fontsize=24) ax5.set_xlabel('Time', fontsize=24) ax1.set_ylabel('Probability', fontsize=24) ax2.set_ylabel('Probability', fontsize=24) ax3.set_ylabel('Probability', fontsize=24) ax4.set_ylabel('Probability', fontsize=24) ax5.set_ylabel('Probability', fontsize=24) ax1.legend(fontsize=20) ax2.legend(fontsize=20) ax3.legend(fontsize=20) ax4.legend(fontsize=20) ax5.legend(fontsize=20) #==== Cell to Implement Energy Measurement Functions ====# def sys_evolve(nsites, excitations, total_time, dt, hop, U, trotter_steps): #Check for correct data types of input if not isinstance(nsites, int): raise TypeError("Number of sites should be int") if np.isscalar(excitations): raise TypeError("Initial state should be list or numpy array") if not np.isscalar(total_time): raise TypeError("Evolution time should be scalar") if not np.isscalar(dt): raise TypeError("Time step should be scalar") if not isinstance(trotter_steps, int): raise TypeError("Number of trotter slices should be int") numq = 2*nsites num_steps = int(total_time/dt) print('Num Steps: ',num_steps) print('Total Time: ', total_time) data = np.zeros((2**numq, num_steps)) energies = np.zeros(num_steps) for t_step in range(0, num_steps): #Create circuit with t_step number of steps q = QuantumRegister(numq) c = ClassicalRegister(numq) qcirc = QuantumCircuit(q,c) #=========USE THIS REGION TO SET YOUR INITIAL STATE============== #Loop over each excitation for flip in excitations: qcirc.x(flip) #=============================================================== qcirc.barrier() #Append circuit with Trotter steps needed hc.qc_evolve(qcirc, nsites, t_step*dt, hop, U, trotter_steps) #Measure the circuit for i in range(numq): qcirc.measure(i, i) #Choose provider and backend provider = IBMQ.get_provider() #backend = Aer.get_backend('statevector_simulator') backend = Aer.get_backend('qasm_simulator') #backend = provider.get_backend('ibmq_qasm_simulator') #backend = provider.get_backend('ibmqx4') #backend = provider.get_backend('ibmqx2') #backend = provider.get_backend('ibmq_16_melbourne') shots = 8192 max_credits = 10 #Max number of credits to spend on execution job_exp = execute(qcirc, backend=backend, shots=shots, max_credits=max_credits) #job_monitor(job_exp) result = job_exp.result() counts = result.get_counts(qcirc) #print(result.get_counts(qcirc)) print("Job: ",t_step+1, " of ", num_steps," computing energy...") #Store results in data array and normalize them for i in range(2**numq): if counts.get(get_bin(i,numq)) is None: dat = 0 else: dat = counts.get(get_bin(i,numq)) data[i,t_step] = dat/shots #======================================================= #Compute energy of system #Compute repulsion energies repulsion_energy = measure_repulsion(U, nsites, counts, shots) #Compute hopping energies #Get list of hopping pairs even_pairs = [] for i in range(0,nsites-1,2): #up_pair = [i, i+1] #dwn_pair = [i+nsites, i+nsites+1] even_pairs.append([i, i+1]) even_pairs.append([i+nsites, i+nsites+1]) odd_pairs = [] for i in range(1,nsites-1,2): odd_pairs.append([i, i+1]) odd_pairs.append([i+nsites, i+nsites+1]) #Start with even hoppings, initialize circuit and find hopping pairs q = QuantumRegister(numq) c = ClassicalRegister(numq) qcirc = QuantumCircuit(q,c) #Loop over each excitation for flip in excitations: qcirc.x(flip) qcirc.barrier() #Append circuit with Trotter steps needed hc.qc_evolve(qcirc, nsites, t_step*dt, hop, U, trotter_steps) even_hopping = measure_hopping(hop, even_pairs, qcirc, numq) #=============================================================== #Now do the same for the odd hoppings #Start with even hoppings, initialize circuit and find hopping pairs q = QuantumRegister(numq) c = ClassicalRegister(numq) qcirc = QuantumCircuit(q,c) #Loop over each excitation for flip in excitations: qcirc.x(flip) qcirc.barrier() #Append circuit with Trotter steps needed hc.qc_evolve(qcirc, nsites, t_step*dt, hop, U, trotter_steps) odd_hopping = measure_hopping(hop, odd_pairs, qcirc, numq) total_energy = repulsion_energy + even_hopping + odd_hopping energies[t_step] = total_energy print("Total Energy is: ", total_energy) print("Job: ",t_step+1, " of ", num_steps," complete") return data, energies #Measure the total repulsion from circuit run def measure_repulsion(U, num_sites, results, shots): repulsion = 0. #Figure out how to include different hoppings later for state in results: for i in range( int( len(state)/2 ) ): if state[i]=='1': if state[i+num_sites]=='1': repulsion += U*results.get(state)/shots return repulsion def measure_hopping(hopping, pairs, circuit, num_qubits): #Add diagonalizing circuit for pair in pairs: circuit.cnot(pair[0],pair[1]) circuit.ch(pair[1],pair[0]) circuit.cnot(pair[0],pair[1]) #circuit.measure(pair[0],pair[0]) #circuit.measure(pair[1],pair[1]) circuit.measure_all() #Run circuit backend = Aer.get_backend('qasm_simulator') shots = 8192 max_credits = 10 #Max number of credits to spend on execution #print("Computing Hopping") hop_exp = execute(circuit, backend=backend, shots=shots, max_credits=max_credits) job_monitor(hop_exp) result = hop_exp.result() counts = result.get_counts(circuit) #print(counts) #Compute energy #print(pairs) for pair in pairs: hop_eng = 0. #print('Pair is: ',pair) for state in counts: #print('State is: ',state,' Index at pair[0]: ',num_qubits-1-pair[0],' Val: ',state[num_qubits-pair[0]]) if state[num_qubits-1-pair[0]]=='1': prob_01 = counts.get(state)/shots #print('Check state is: ',state) for comp_state in counts: #print('Comp State is: ',state,' Index at pair[0]: ',num_qubits-1-pair[1],' Val: ',comp_state[num_qubits-pair[0]]) if comp_state[num_qubits-1-pair[1]]=='1': #print('Comp state is: ',comp_state) hop_eng += -hopping*(prob_01 - counts.get(comp_state)/shots) return hop_eng #Try by constructing the matrix and finding the eigenvalues N = 3 Nup = 2 Ndwn = N - Nup t = 1.0 U = 2. #Check if two states are different by a single hop def hop(psii, psij): #Check spin down hopp = 0 if psii[0]==psij[0]: #Create array of indices with nonzero values indi = np.nonzero(psii[1])[0] indj = np.nonzero(psij[1])[0] for i in range(len(indi)): if abs(indi[i]-indj[i])==1: hopp = -t return hopp #Check spin up if psii[1]==psij[1]: indi = np.nonzero(psii[0])[0] indj = np.nonzero(psij[0])[0] for i in range(len(indi)): if abs(indi[i]-indj[i])==1: hopp = -t return hopp return hopp #On-site terms def repel(l,state): if state[0][l]==1 and state[1][l]==1: return state else: return [] #States for 3 electrons with net spin up ''' states = [ [[1,1,0],[1,0,0]], [[1,1,0],[0,1,0]], [[1,1,0], [0,0,1]], [[1,0,1],[1,0,0]], [[1,0,1],[0,1,0]], [[1,0,1], [0,0,1]], [[0,1,1],[1,0,0]], [[0,1,1],[0,1,0]], [[0,1,1], [0,0,1]] ] ''' #States for 2 electrons in singlet state states = [ [[1,0,0],[1,0,0]], [[1,0,0],[0,1,0]], [[1,0,0],[0,0,1]], [[0,1,0],[1,0,0]], [[0,1,0],[0,1,0]], [[0,1,0],[0,0,1]], [[0,0,1],[1,0,0]], [[0,0,1],[0,1,0]], [[0,0,1],[0,0,1]] ] #''' #States for a single electron states = [ [[1,0,0],[0,0,0]], [[0,1,0],[0,0,0]], [[0,0,1],[0,0,0]] ] #''' H = np.zeros((len(states),len(states)) ) #Construct Hamiltonian matrix for i in range(len(states)): psi_i = states[i] for j in range(len(states)): psi_j = states[j] if j==i: for l in range(0,len(states[0][0])): if psi_i == repel(l,psi_j): H[i,j] = U break else: H[i,j] = hop(psi_i, psi_j) print(H) results = la.eig(H) print() for i in range(len(results[0])): print('Eigenvalue: ',results[0][i]) print('Eigenvector: \n',results[1][i]) print() dens_ops = [] eigs = [] for vec in results[1]: dens_ops.append(np.outer(results[1][i],results[1][i])) eigs.append(results[0][i]) print(dens_ops) #Loop/function to flip through states mode_list = [] num_sites = 3 print(len(states[0][0])) for i in range(0,2*num_sites): index_list = [] for state_index in range(0,len(states)): state = states[state_index] #print(state[0]) #print(state[1]) #Check spin-up modes if i < num_sites: if state[0][i]==1: index_list.append(state_index) #Check spin-down modes else: if state[1][i-num_sites]==1: index_list.append(state_index) if index_list: mode_list.append(index_list) print(mode_list) wfk0 = 1/np.sqrt(2)*results[1][0] - 1/np.sqrt(2)*results[1][2] print(np.dot(np.conj(wfk0), np.dot(H, wfk0))) dtc = 0.01 tsteps = 500 times = np.arange(0., tsteps*dtc, dtc) t_op = la.expm(-1j*H*dtc) #print(np.subtract(np.identity(len(H)), dt*H*1j)) #print(t_op) #wfk = [0., 0., 0., 0., 1., 0., 0., 0., 0.] #Half-filling initial state #wfk = [0., 0., 0., 0., 1.0, 0., 0., 0., 0.] #2 electron initial state wfk = [0., 1., 0.] #1 electron initial state evolve = np.zeros([tsteps, len(wfk)]) energies = np.zeros(tsteps) mode_evolve = np.zeros([tsteps, 6]) mode_evolve = np.zeros([tsteps, len(mode_list)]) evolve[0] = wfk energies[0] = np.dot(np.conj(wfk), np.dot(H, wfk)) print(energies[0]) excitations = 3. #Loop to find occupation of each mode for i in range(0,len(mode_list)): wfk_sum = 0. for j in mode_list[i]: wfk_sum += evolve[0][j] mode_evolve[0][i] = wfk_sum / excitations print(mode_evolve) print('========================================================') #Figure out how to generalize this later ''' mode_evolve[0][0] = (evolve[0][0]+evolve[0][1]+evolve[0][2]) /2. mode_evolve[0][1] = (evolve[0][3]+evolve[0][4]+evolve[0][5]) /2. mode_evolve[0][2] = (evolve[0][6]+evolve[0][7]+evolve[0][8]) /2. mode_evolve[0][3] = (evolve[0][0]+evolve[0][3]+evolve[0][6]) /2. mode_evolve[0][4] = (evolve[0][1]+evolve[0][4]+evolve[0][7]) /2. mode_evolve[0][5] = (evolve[0][2]+evolve[0][5]+evolve[0][8]) /2. ''' ''' mode_evolve[0][0] = (evolve[0][0]+evolve[0][1]+evolve[0][2]+evolve[0][3]+evolve[0][4]+evolve[0][5]) /3. mode_evolve[0][1] = (evolve[0][0]+evolve[0][1]+evolve[0][2]+evolve[0][6]+evolve[0][7]+evolve[0][8]) /3. mode_evolve[0][2] = (evolve[0][3]+evolve[0][4]+evolve[0][5]+evolve[0][6]+evolve[0][7]+evolve[0][8]) /3. mode_evolve[0][3] = (evolve[0][0]+evolve[0][3]+evolve[0][6]) /3. mode_evolve[0][4] = (evolve[0][1]+evolve[0][4]+evolve[0][7]) /3. mode_evolve[0][5] = (evolve[0][2]+evolve[0][5]+evolve[0][8]) /3. #''' #print(mode_evolve[0]) #Define density matrices print(mode_evolve) print() print() for t in range(1, tsteps): #t_op = la.expm(-1j*H*t*dtc) wfk = np.dot(t_op, wfk) evolve[t] = np.multiply(np.conj(wfk), wfk) energies[t] = np.dot(np.conj(wfk), np.dot(H, wfk)) norm = np.sum(evolve[t]) #print(evolve[t]) #Store data in modes rather than basis defined in 'states' variable ''' #Procedure for two electrons mode_evolve[t][0] = (evolve[t][0]+evolve[t][1]+evolve[t][2]) / (2) mode_evolve[t][1] = (evolve[t][3]+evolve[t][4]+evolve[t][5]) / (2) mode_evolve[t][2] = (evolve[t][6]+evolve[t][7]+evolve[t][8]) / (2) mode_evolve[t][3] = (evolve[t][0]+evolve[t][3]+evolve[t][6]) / (2) mode_evolve[t][4] = (evolve[t][1]+evolve[t][4]+evolve[t][7]) / (2) mode_evolve[t][5] = (evolve[t][2]+evolve[t][5]+evolve[t][8]) / (2) #Procedure for half-filling mode_evolve[t][0] = (evolve[t][0]+evolve[t][1]+evolve[t][2]+evolve[t][3]+evolve[t][4]+evolve[t][5]) /3. mode_evolve[t][1] = (evolve[t][0]+evolve[t][1]+evolve[t][2]+evolve[t][6]+evolve[t][7]+evolve[t][8]) /3. mode_evolve[t][2] = (evolve[t][3]+evolve[t][4]+evolve[t][5]+evolve[t][6]+evolve[t][7]+evolve[t][8]) /3. mode_evolve[t][3] = (evolve[t][0]+evolve[t][3]+evolve[t][6]) /3. mode_evolve[t][4] = (evolve[t][1]+evolve[t][4]+evolve[t][7]) /3. mode_evolve[t][5] = (evolve[t][2]+evolve[t][5]+evolve[t][8]) /3. #''' #print(mode_evolve[t]) #print(np.linalg.norm(evolve[t])) #print(len(evolve[:,0]) ) #print(len(times)) #print(evolve[:,0]) #print(min(evolve[:,0])) print(energies) timesq = np.arange(0, time_steps*dt, dt) for i in range(nsites): #Create string label strup = "Site "+str(i+1)+r'$\uparrow$' strdwn = "Site "+str(i+1)+r'$\downarrow$' ax2.plot(timesq, processed_data[i,:], marker="^", color=str(colors[i]), label=strup) ax2.plot(timesq, processed_data[i+nsites,:], marker="v", color=str(colors[i]), label=strdwn) #ax2.set_ylim(0, 0.55) ax2.set_xlim(0, time_steps*dt+dt/2.) #ax2.set_xticks(np.arange(0,time_steps*dt+dt, 0.2)) #ax2.set_yticks(np.arange(0,0.55, 0.05)) ax2.tick_params(labelsize=16) ax2.set_title('Time Evolution of 3 Site One Dimensional Chain', fontsize=22) ax2.set_xlabel('Time', fontsize=24) ax2.set_ylabel('Probability', fontsize=24) ax2.legend(fontsize=20) #Process and plot data '''The procedure here is, for each fermionic mode, add the probability of every state containing that mode (at a given time step), and renormalize the data based on the total occupation of each mode. Afterwards, plot the data as a function of time step for each mode.''' def process_run(num_sites, time_steps, results): proc_data = np.zeros((2*num_sites, time_steps)) timesq = np.arange(0.,time_steps*dt, dt) #Sum over time steps for t in range(time_steps): #Sum over all possible states of computer for i in range(2**(2*num_sites)): #num = get_bin(i, 2*nsite) num = ''.join( list( reversed(hc.get_bin(i,2*nsites)) ) ) #For each state, check which mode(s) it contains and add them for mode in range(len(num)): if num[mode]=='1': proc_data[mode,t] += results[i,t] #Renormalize these sums so that the total occupation of the modes is 1 norm = 0.0 for mode in range(len(num)): norm += proc_data[mode,t] proc_data[:,t] = proc_data[:,t] / norm return proc_data ''' At this point, proc_data is a 2d array containing the occupation of each mode, for every time step ''' processed_data = process_run(nsites, time_steps, run_results) #Create plots of the processed data fig2, ax2 = plt.subplots(figsize=(20,10)) colors = list(mcolors.TABLEAU_COLORS.keys()) for i in range(nsites): #Create string label strup = "Site "+str(i+1)+r'$\uparrow$' strdwn = "Site "+str(i+1)+r'$\downarrow$' ax2.plot(timesq, processed_data[i,:], marker="^", color=str(colors[i]), label=strup) ax2.plot(timesq, processed_data[i+nsites,:], marker="v", color=str(colors[i]), label=strdwn) #ax2.set_ylim(0, 0.55) ax2.set_xlim(0, time_steps*dt+dt/2.) #ax2.set_xticks(np.arange(0,time_steps*dt+dt, 0.2)) #ax2.set_yticks(np.arange(0,0.55, 0.05)) ax2.tick_params(labelsize=16) ax2.set_title('Time Evolution of 3 Site One Dimensional Chain', fontsize=22) ax2.set_xlabel('Time', fontsize=24) ax2.set_ylabel('Probability', fontsize=24) ax2.legend(fontsize=20)
https://github.com/kaelynj/Qiskit-HubbardModel
kaelynj
%matplotlib inline # Importing standard Qiskit libraries and configuring account from qiskit import QuantumCircuit, execute, Aer, IBMQ, BasicAer, QuantumRegister, ClassicalRegister from qiskit.compiler import transpile, assemble from qiskit.quantum_info import Operator from qiskit.tools.monitor import job_monitor from qiskit.tools.jupyter import * from qiskit.visualization import * import matplotlib.pyplot as plt import matplotlib.colors as mcolors import numpy as np from matplotlib import rcParams rcParams['text.usetex'] = True #Useful tool for converting an integer to a binary bit string def get_bin(x, n=0): """ Get the binary representation of x. Parameters: x (int), n (int, number of digits)""" return format(x, 'b').zfill(n)
https://github.com/kaelynj/Qiskit-HubbardModel
kaelynj
# Importing standard Qiskit libraries and configuring account from qiskit import QuantumCircuit, execute, Aer, IBMQ, BasicAer, QuantumRegister, ClassicalRegister from qiskit.compiler import transpile, assemble from qiskit.quantum_info import Operator, DensityMatrix import qiskit.quantum_info as qi from qiskit.tools.monitor import job_monitor import random as rand import scipy.linalg as la import numpy as np #Function to convert an integer to a binary bit string using "little Endian" encoding # where the most significant bit is the first bit def get_bin(x, n=0): """ Get the binary representation of x. Parameters: x (int), n (int, number of digits)""" binry = format(x, 'b').zfill(n) sup = list( reversed( binry[0:int(len(binry)/2)] ) ) sdn = list( reversed( binry[int(len(binry)/2):len(binry)] ) ) return format(x, 'b').zfill(n) #return ''.join(sup)+''.join(sdn) #================== qc_evolve ========================== ''' Function to compute the time evolution operator and append the needed gates to a given circuit. Inputs: -qc (qiskit circuit) Circuit object to append time evolution gates -numsite (int) Number of sites in the one-dimensional chain -time (float) Current time of the evolution to build the operator -hop (float, list) Hopping parameter of the chain. Can be either float for constant hopping or array describing the hopping across each site. Length should be numsite-1 -U (float, list) Repulsion parameter of the chain. Can be either float for constant repulsion or array to describe different repulsions for each site -trotter_steps (int) Number of trotter steps used to approximate the time evolution operator Outputs: -None: qc is modified and returned ''' def qc_evolve(qc, numsite, time, dt, hop, U, trotter_steps): #Compute angles for the onsite and hopping gates # based on the model parameters t, U, and dt #theta = hop*time/(2*trotter_steps) #phi = U*time/(trotter_steps) numq = 2*numsite # if np.isscalar(U): # U = np.full(numsite, U) # if np.isscalar(hop): # hop = np.full(numsite, hop) z_onsite = [] x_hop = [] y_hop = [] #MODIFIED TO TRY SMALLER TIME STEPS num_steps = int(time/dt) theta = hop*dt/(2*trotter_steps) phi = U*dt/(trotter_steps) z_onsite.append(Operator([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, np.exp(1j*phi)]])) x_hop.append(Operator([[np.cos(theta), 0, 0, 1j*np.sin(theta)], [0, np.cos(theta), 1j*np.sin(theta), 0], [0, 1j*np.sin(theta), np.cos(theta), 0], [1j*np.sin(theta), 0, 0, np.cos(theta)]])) y_hop.append(Operator([[np.cos(theta), 0, 0, -1j*np.sin(theta)], [0, np.cos(theta), 1j*np.sin(theta), 0], [0, 1j*np.sin(theta), np.cos(theta), 0], [-1j*np.sin(theta), 0, 0, np.cos(theta)]])) #for step in range(num_steps): for trot in range(trotter_steps): #Onsite terms for i in range(0, numsite): qc.unitary(z_onsite[0], [i, i+numsite], label="Z_Onsite") qc.barrier() #Hopping terms for i in range(0,numsite-1): #Spin-up chain qc.unitary(y_hop[0], [i,i+1], label="YHop") qc.unitary(x_hop[0], [i,i+1], label="Xhop") #Spin-down chain qc.unitary(y_hop[0], [i+numsite, i+1+numsite], label="Xhop") qc.unitary(x_hop[0], [i+numsite, i+1+numsite], label="Xhop") qc.barrier() #============================================================= ''' for i in range(0, numsite): phi = U[i]*time/(trotter_steps) z_onsite.append( Operator([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, np.exp(1j*phi)]]) ) if i < numsite-1: theta = hop[i]*time/(2*trotter_steps) x_hop.append( Operator([[np.cos(theta), 0, 0, 1j*np.sin(theta)], [0, np.cos(theta), 1j*np.sin(theta), 0], [0, 1j*np.sin(theta), np.cos(theta), 0], [1j*np.sin(theta), 0, 0, np.cos(theta)]]) ) y_hop.append( Operator([[np.cos(theta), 0, 0, -1j*np.sin(theta)], [0, np.cos(theta), 1j*np.sin(theta), 0], [0, 1j*np.sin(theta), np.cos(theta), 0], [-1j*np.sin(theta), 0, 0, np.cos(theta)]])) #Loop over each time step needed and apply onsite and hopping gates for trot in range(trotter_steps): #Onsite Terms for i in range(0, numsite): qc.unitary(z_onsite[i], [i,i+numsite], label="Z_Onsite") #Add barrier to separate onsite from hopping terms qc.barrier() #Hopping terms for i in range(0,numsite-1): #Spin-up chain qc.unitary(y_hop[i], [i,i+1], label="YHop") qc.unitary(x_hop[i], [i,i+1], label="Xhop") #Spin-down chain qc.unitary(y_hop[i], [i+numsite, i+1+numsite], label="Xhop") qc.unitary(x_hop[i], [i+numsite, i+1+numsite], label="Xhop") #Add barrier after finishing the time step qc.barrier() ''' # circuit_operator = qi.Operator(qc) # return circuit_operator.data #================== sys_evolve ========================== ''' Function to evolve the 1d-chain in time given a set of system parameters and using the qiskit qasm_simulator (will later on add in functionality to set the backend) Inputs: -nsites (int) Number of sites in the chain -excitations (list) List to create initial state of the system. The encoding here is the first half of the qubits are the spin-up electrons for each site and the second half for the spin-down electrons -total_time (float) Total time to evolve the system (units of inverse energy, 1/hop) -dt (float) Time step to evolve the system with -hop (float, list) Hopping parameter of the chain. Can be either float for constant hopping or array describing the hopping across each site. Length should be numsite-1 -U (float, list) Repulsion parameter of the chain. Can be either float for constant repulsion or array to describe different repulsions for each site -trotter_steps (int) Number of trotter steps used to approximate the time evolution operator Outputs: -data (2d array of length [2*nsites, time_steps]) Output data of the quantum simulation. Record the normalized counts for each qubit at each time step ''' def sys_evolve(nsites, excitations, total_time, dt, hop, U, trotter_steps): #Check for correct data types of input if not isinstance(nsites, int): raise TypeError("Number of sites should be int") if np.isscalar(excitations): raise TypeError("Initial state should be list or numpy array") if not np.isscalar(total_time): raise TypeError("Evolution time should be scalar") if not np.isscalar(dt): raise TypeError("Time step should be scalar") if not isinstance(trotter_steps, int): raise TypeError("Number of trotter slices should be int") numq = 2*nsites num_steps = int(total_time/dt) print('Num Steps: ',num_steps) print('Total Time: ', total_time) data = np.zeros((2**numq, num_steps)) for t_step in range(0, num_steps): #Create circuit with t_step number of steps q = QuantumRegister(numq) c = ClassicalRegister(numq) qcirc = QuantumCircuit(q,c) #=========USE THIS REGION TO SET YOUR INITIAL STATE============== #Loop over each excitation for flip in excitations: qcirc.x(flip) # qcirc.z(flip) #=============================================================== qcirc.barrier() #Append circuit with Trotter steps needed qc_evolve(qcirc, nsites, t_step*dt, dt, hop, U, trotter_steps) #Measure the circuit for i in range(numq): qcirc.measure(i, i) #Choose provider and backend #provider = IBMQ.get_provider() #backend = Aer.get_backend('statevector_simulator') backend = Aer.get_backend('qasm_simulator') #backend = provider.get_backend('ibmq_qasm_simulator') #backend = provider.get_backend('ibmqx4') #backend = provider.get_backend('ibmqx2') #backend = provider.get_backend('ibmq_16_melbourne') shots = 8192 max_credits = 10 #Max number of credits to spend on execution job_exp = execute(qcirc, backend=backend, shots=shots, max_credits=max_credits) job_monitor(job_exp) result = job_exp.result() counts = result.get_counts(qcirc) print(result.get_counts(qcirc)) print("Job: ",t_step+1, " of ", num_steps," complete.") #Store results in data array and normalize them for i in range(2**numq): if counts.get(get_bin(i,numq)) is None: dat = 0 else: dat = counts.get(get_bin(i,numq)) data[i,t_step] = dat/shots return data #================== sys_evolve_eng ========================== ''' Function to evolve the 1d-chain in time given a set of system parameters and using the qiskit qasm_simulator and compute the total energy along the way Inputs: -nsites (int) Number of sites in the chain -excitations (list) List to create initial state of the system. The encoding here is the first half of the qubits are the spin-up electrons for each site and the second half for the spin-down electrons -total_time (float) Total time to evolve the system (units of inverse energy, 1/hop) -dt (float) Time step to evolve the system with -hop (float, list) Hopping parameter of the chain. Can be either float for constant hopping or array describing the hopping across each site. Length should be numsite-1 -U (float, list) Repulsion parameter of the chain. Can be either float for constant repulsion or array to describe different repulsions for each site -trotter_steps (int) Number of trotter steps used to approximate the time evolution operator Outputs: -data (2d array of length [2*nsites, time_steps]): Output data of the quantum simulation. Record the normalized counts for each qubit at each time step -energies (array of length [time_steps]) Output data of the total energy of the system at each time step ''' def sys_evolve_eng(nsites, excitations, total_time, dt, hop, U, trotter_steps): #Check for correct data types of input if not isinstance(nsites, int): raise TypeError("Number of sites should be int") if np.isscalar(excitations): raise TypeError("Initial state should be list or numpy array") if not np.isscalar(total_time): raise TypeError("Evolution time should be scalar") if not np.isscalar(dt): raise TypeError("Time step should be scalar") if not isinstance(trotter_steps, int): raise TypeError("Number of trotter slices should be int") numq = 2*nsites num_steps = int(total_time/dt) print('Num Steps: ',num_steps) print('Total Time: ', total_time) data = np.zeros((2**numq, num_steps)) energies = np.zeros(num_steps) for t_step in range(0, num_steps): #Create circuit with t_step number of steps q = QuantumRegister(numq) c = ClassicalRegister(numq) qcirc = QuantumCircuit(q,c) #=========SET YOUR INITIAL STATE============== #Loop over each excitation for flip in excitations: qcirc.x(flip) # qcirc.h(flip) # qcirc.t(flip) #=============================================================== qcirc.barrier() #Append circuit with Trotter steps needed qc_evolve(qcirc, nsites, t_step*dt, dt, hop, U, trotter_steps) #Measure the circuit for i in range(numq): qcirc.measure(i, i) #Choose provider and backend #provider = IBMQ.get_provider() #backend = Aer.get_backend('statevector_simulator') backend = Aer.get_backend('qasm_simulator') #backend = provider.get_backend('ibmq_qasm_simulator') #backend = provider.get_backend('ibmqx4') #backend = provider.get_backend('ibmqx2') #backend = provider.get_backend('ibmq_16_melbourne') shots = 8192 max_credits = 10 #Max number of credits to spend on execution job_exp = execute(qcirc, backend=backend, shots=shots, max_credits=max_credits) #job_monitor(job_exp) result = job_exp.result() counts = result.get_counts(qcirc) #print(result.get_counts(qcirc)) print("Job: ",t_step+1, " of ", num_steps," computing energy...") #Store results in data array and normalize them for i in range(2**numq): if counts.get(get_bin(i,numq)) is None: dat = 0 else: dat = counts.get(get_bin(i,numq)) data[i,t_step] = dat/shots #======================================================= #Compute energy of system #Compute repulsion energies repulsion_energy = measure_repulsion(U, nsites, counts, shots) #Compute hopping energies #Get list of hopping pairs even_pairs = [] for i in range(0,nsites-1,2): #up_pair = [i, i+1] #dwn_pair = [i+nsites, i+nsites+1] even_pairs.append([i, i+1]) even_pairs.append([i+nsites, i+nsites+1]) odd_pairs = [] for i in range(1,nsites-1,2): odd_pairs.append([i, i+1]) odd_pairs.append([i+nsites, i+nsites+1]) #Start with even hoppings, initialize circuit and find hopping pairs q = QuantumRegister(numq) c = ClassicalRegister(numq) qcirc = QuantumCircuit(q,c) #Loop over each excitation for flip in excitations: qcirc.x(flip) qcirc.barrier() #Append circuit with Trotter steps needed qc_evolve(qcirc, nsites, t_step*dt, dt, hop, U, trotter_steps) even_hopping = measure_hopping(hop, even_pairs, qcirc, numq) #=============================================================== #Now do the same for the odd hoppings #Start with even hoppings, initialize circuit and find hopping pairs q = QuantumRegister(numq) c = ClassicalRegister(numq) qcirc = QuantumCircuit(q,c) #Loop over each excitation for flip in excitations: qcirc.x(flip) qcirc.barrier() #Append circuit with Trotter steps needed qc_evolve(qcirc, nsites, t_step*dt, dt, hop, U, trotter_steps) odd_hopping = measure_hopping(hop, odd_pairs, qcirc, numq) total_energy = repulsion_energy + even_hopping + odd_hopping energies[t_step] = total_energy print("Total Energy is: ", total_energy) print("Job: ",t_step+1, " of ", num_steps," complete") return data, energies #================== measure_repulsion ========================= ''' Measure the energy due to the repulsive U term in H Inputs: -U (float): Repulsion energy of system -num_sites (int): Number of sites in chain -results (qiskit counts object): Results from qiskit circuit run -shots (int): Number of shots from circuit run Outputs: -repulsion (float): Measures U*|a|^2|11> for each pair of modes ''' def measure_repulsion(U, num_sites, results, shots): repulsion = 0. for state in results: #Adding in debug print statement #print(state) for i in range( int( len(state)/2 ) ): if state[i]=='1': if state[i+num_sites]=='1': print("Measured State: ",state) repulsion += U*results.get(state)/shots return repulsion #================== measure_hopping ========================= ''' Measure the hopping energy at a given time step for a given set of even/odd pairs. Apply the diagonalizing circuit to each pair and measure the hopping as -t*( |a|^2*|01> - |b|^2*|10> ) Inputs: -hopping (float): Hopping energy -pairs (2d list): List of pairs of qubits to apply diagonalizing circuit -circuit (qiskit circuit): Circuit to append diagonalizing gates to -num_qubits (int): Number of qubits Outputs: -hop_eng (floats): Hopping energy at a given time step ''' def measure_hopping(hopping, pairs, circuit, num_qubits): #Add diagonalizing circuit for pair in pairs: circuit.cnot(pair[0],pair[1]) circuit.ch(pair[1],pair[0]) circuit.cnot(pair[0],pair[1]) circuit.measure_all() #Run circuit backend = Aer.get_backend('qasm_simulator') shots = 8192 max_credits = 10 #Max number of credits to spend on execution hop_exp = execute(circuit, backend=backend, shots=shots, max_credits=max_credits) job_monitor(hop_exp) result = hop_exp.result() counts = result.get_counts(circuit) #Compute energy for pair in pairs: hop_eng = 0. for state in counts: if state[num_qubits-1-pair[0]]=='1': prob_01 = counts.get(state)/shots for comp_state in counts: if comp_state[num_qubits-1-pair[1]]=='1': hop_eng += -hopping*(prob_01 - counts.get(comp_state)/shots) return hop_eng '''The procedure here is, for each fermionic mode, add the probability of every state containing that mode (at a given time step), and renormalize the data based on the total occupation of each mode. Afterwards, plot the data as a function of time step for each mode.''' #================== process_run ========================== ''' Function to process the data output from sys_evolve or sys_evolve_eng. Will map each of the possible basis states to each fermionic mode in order to plot the occupation probability as a function of time. Inputs: -num_sites (int) Number of sites in the chain -time_steps (int) Number of time steps in the evolution -dt (float) Time step size (units of inverse energy) -results (output of sys_evolve) List obtained from the sys_evolve function Outputs: -proc_data (2d array of size [2*num_sites, time_steps]) Processes the data by mapping the outputs of each qubit into occupation of each fermionic mode of the system. Does this by adding and renormalizing each possible state into a given fermionic mode. ''' def process_run(num_sites, time_steps, dt, results): proc_data = np.zeros((2*num_sites, time_steps)) timesq = np.arange(0.,time_steps*dt, dt) #Sum over time steps for t in range(time_steps): #Sum over all possible states of computer for i in range(2**(2*num_sites)): #Grab binary string in "little Endian" encoding by reversing get_bin() num = ''.join( list( reversed(get_bin(i,2*num_sites)) ) ) #For each state, check which mode(s) it contains and add them for mode in range(len(num)): if num[mode]=='1': proc_data[mode,t] += results[i,t] #Renormalize these sums so that the total occupation of the modes is 1 norm = 0.0 for mode in range(len(num)): norm += proc_data[mode,t] proc_data[:,t] = proc_data[:,t] / norm ''' At this point, proc_data is a 2d array containing the occupation of each mode, for every time step ''' return proc_data #================== sys_evolve ========================== ''' Function to evolve the 1d-chain in time given a set of system parameters and using the qiskit qasm_simulator (will later on add in functionality to set the backend) Inputs: -nsites (int) Number of sites in the chain -excitations (list) List to create initial state of the system. The encoding here is the first half of the qubits are the spin-up electrons for each site and the second half for the spin-down electrons -total_time (float) Total time to evolve the system (units of inverse energy, 1/hop) -dt (float) Time step to evolve the system with -hop (float, list) Hopping parameter of the chain. Can be either float for constant hopping or array describing the hopping across each site. Length should be numsite-1 -U (float, list) Repulsion parameter of the chain. Can be either float for constant repulsion or array to describe different repulsions for each site -trotter_steps (int) Number of trotter steps used to approximate the time evolution operator Outputs: -data (2d array of length [2*nsites, time_steps]) Output data of the quantum simulation. Record the normalized counts for each qubit at each time step ''' def sys_evolve_den(nsites, excitations, total_time, dt, hop, U, trotter_steps): #Check for correct data types of input if not isinstance(nsites, int): raise TypeError("Number of sites should be int") if np.isscalar(excitations): raise TypeError("Initial state should be list or numpy array") if not np.isscalar(total_time): raise TypeError("Evolution time should be scalar") if not np.isscalar(dt): raise TypeError("Time step should be scalar") if not isinstance(trotter_steps, int): raise TypeError("Number of trotter slices should be int") numq = 2*nsites num_steps = int(total_time/dt) print('Num Steps: ',num_steps) print('Total Time: ', total_time) data = [] for t_step in range(0, num_steps): #Create circuit with t_step number of steps q = QuantumRegister(numq) c = ClassicalRegister(numq) qcirc = QuantumCircuit(q,c) #=========USE THIS REGION TO SET YOUR INITIAL STATE============== #Loop over each excitation for flip in excitations: qcirc.x(flip) #qcirc.h(flip) # qcirc.z(flip) #=============================================================== qcirc.barrier() #Append circuit with Trotter steps needed qc_evolve(qcirc, nsites, t_step*dt, dt, hop, U, trotter_steps) den_mtrx_obj = DensityMatrix.from_instruction(qcirc) den_mtrx = den_mtrx_obj.to_operator().data state_vector = qi.Statevector.from_instruction(qcirc) #data.append(state_vector.data) data.append(den_mtrx) #Measure the circuit for i in range(numq): qcirc.measure(i, i) ''' #Choose provider and backend provider = IBMQ.get_provider() #backend = Aer.get_backend('statevector_simulator') backend = Aer.get_backend('qasm_simulator') #backend = provider.get_backend('ibmq_qasm_simulator') #backend = provider.get_backend('ibmqx4') #backend = provider.get_backend('ibmqx2') #backend = provider.get_backend('ibmq_16_melbourne') shots = 8192 max_credits = 10 #Max number of credits to spend on execution job_exp = execute(qcirc, backend=backend, shots=shots, max_credits=max_credits) job_monitor(job_exp) result = job_exp.result() counts = result.get_counts(qcirc) print(result.get_counts(qcirc)) print("Job: ",t_step+1, " of ", num_steps," complete.") ''' return data
https://github.com/kaelynj/Qiskit-HubbardModel
kaelynj
# -*- 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/fedimser/quantum_decomp
fedimser
import quantum_decomp as qd from scipy.stats import unitary_group from collections import Counter import time for qubits_count in range(1,10): time_start = time.time() gates = qd.matrix_to_gates(unitary_group.rvs(2 ** qubits_count)) duration = time.time() - time_start total = len(gates) print("%d qubits" % qubits_count) ctr = Counter([gate.type() for gate in gates]) for t, count in ctr.most_common(10): print("%s: %d" % (t, count)) print("%d total, %.02f gates per matrix element." % (total, total/(4**qubits_count))) print("Time: %.03fs" % duration) print("\n")
https://github.com/fedimser/quantum_decomp
fedimser
import math import numpy as np from .src.decompose_2x2 import unitary2x2_to_gates from .src.decompose_4x4 import decompose_4x4_optimal from .src.gate import GateFC, GateSingle from .src.gate2 import Gate2 from .src.two_level_unitary import TwoLevelUnitary from .src.utils import PAULI_X, is_unitary, is_special_unitary, \ is_power_of_two, IDENTITY_2x2, permute_matrix def two_level_decompose(A): """Returns list of two-level unitary matrices, which multiply to A. Matrices are listed in application order, i.e. if answer is [u_1, u_2, u_3], it means A = u_3 u_2 u_1. :param A: matrix to decompose. :return: The decomposition - list of two-level unitary matrices. """ def make_eliminating_matrix(a, b): """Returns unitary matrix U, s.t. [a, b] U = [c, 0]. Makes second element equal to zero. Guarantees np.angle(c)=0. """ assert (np.abs(a) > 1e-9 and np.abs(b) > 1e-9) theta = np.arctan(np.abs(b / a)) lmbda = -np.angle(a) mu = np.pi + np.angle(b) - np.angle(a) - lmbda result = np.array([[np.cos(theta) * np.exp(1j * lmbda), np.sin(theta) * np.exp(1j * mu)], [-np.sin(theta) * np.exp(-1j * mu), np.cos(theta) * np.exp(-1j * lmbda)]]) assert is_special_unitary(result) assert np.allclose(np.angle(result[0, 0] * a + result[1, 0] * b), 0) assert (np.abs(result[0, 1] * a + result[1, 1] * b) < 1e-9) return result assert is_unitary(A) n = A.shape[0] result = [] # Make a copy, because we are going to mutate it. cur_A = np.array(A) for i in range(n - 2): for j in range(n - 1, i, -1): a = cur_A[i, j - 1] b = cur_A[i, j] if abs(cur_A[i, j]) < 1e-9: # Element is already zero, nothing to do. u_2x2 = IDENTITY_2x2 # But if it's last in row, ensure diagonal element will be 1. if j == i + 1: u_2x2 = np.array([[1 / a, 0], [0, a]]) elif abs(cur_A[i, j - 1]) < 1e-9: # Just swap columns. u_2x2 = PAULI_X # But if it's last in row, ensure diagonal element will be 1. if j == i + 1: u_2x2 = np.array([[0, b], [1 / b, 0]]) else: u_2x2 = make_eliminating_matrix(a, b) u_2x2 = TwoLevelUnitary(u_2x2, n, j - 1, j) u_2x2.multiply_right(cur_A) if not u_2x2.is_identity(): result.append(u_2x2.inv()) # After we are done with row, diagonal element is 1. assert np.allclose(cur_A[i, i], 1.0) last_matrix = TwoLevelUnitary(cur_A[n - 2:n, n - 2:n], n, n - 2, n - 1) if not last_matrix.is_identity(): result.append(last_matrix) return result def two_level_decompose_gray(A): """Returns list of two-level matrices, which multiply to A. :param A: matrix to decompose. :return: The decomposition - list of two-level unitary matrices. Guarantees that each matrix acts on single bit. """ N = A.shape[0] assert is_power_of_two(N) assert A.shape == (N, N), "Matrix must be square." assert is_unitary(A) perm = [x ^ (x // 2) for x in range(N)] # Gray code. result = two_level_decompose(permute_matrix(A, perm)) for matrix in result: matrix.apply_permutation(perm) return result def add_flips(flip_mask, gates): """Adds X gates for all qubits specified by qubit_mask.""" qubit_id = 0 while (flip_mask > 0): if (flip_mask % 2) == 1: gates.append(GateSingle(Gate2('X'), qubit_id)) flip_mask //= 2 qubit_id += 1 def matrix_to_gates(A, **kwargs): """Given unitary matrix A, returns sequence of gates which implements action of this matrix on register of qubits. If `optimize=True`, applies optimized algorithm yielding less gates. Will affect output only when A is 4x4 matrix. :param A: 2^N x 2^N unitary matrix. :return: sequence of `Gate`s. """ if 'optimize' in kwargs and kwargs['optimize'] and A.shape[0] == 4: return decompose_4x4_optimal(A) matrices = two_level_decompose_gray(A) gates = [] prev_flip_mask = 0 for matrix in matrices: matrix.order_indices() # Ensures that index2 > index1. qubit_id_mask = matrix.index1 ^ matrix.index2 assert is_power_of_two(qubit_id_mask) qubit_id = int(math.log2(qubit_id_mask)) flip_mask = (matrix.matrix_size - 1) - matrix.index2 add_flips(flip_mask ^ prev_flip_mask, gates) for gate2 in unitary2x2_to_gates(matrix.matrix_2x2): gates.append(GateFC(gate2, qubit_id)) prev_flip_mask = flip_mask add_flips(prev_flip_mask, gates) return gates def matrix_to_qsharp(matrix, **kwargs): """Given unitary matrix A, retuns Q# code which implements action of this matrix on register of qubits called `qs`. :param matrix: 2^N x 2^N unitary matrix to convert to Q# code. :param op_name: name which operation should have. Default name is "ApplyUnitaryMatrix". :return: string - Q# code. """ op_name = 'ApplyUnitaryMatrix' if 'op_name' in kwargs: op_name = kwargs['op_name'] header = ('operation %s (qs : Qubit[]) : Unit {\n' % op_name) footer = '}\n' qubits_count = int(np.log2(matrix.shape[0])) code = '\n'.join([' ' + gate.to_qsharp_command(qubits_count) for gate in matrix_to_gates(matrix, **kwargs)]) return header + code + '\n' + footer def matrix_to_cirq_circuit(A, **kwargs): """Converts unitary matrix to Cirq circuit. :param A: 2^N x 2^N unitary matrix. :return: `cirq.Circuit` implementing this matrix. """ import cirq def gate_to_cirq(gate2): if gate2.name == 'X': return cirq.X elif gate2.name == 'Ry': return cirq.ry(-gate2.arg) elif gate2.name == 'Rz': return cirq.rz(-gate2.arg) elif gate2.name == 'R1': return cirq.ZPowGate(exponent=gate2.arg / np.pi) else: raise RuntimeError("Can't implement: %s" % gate2) gates = matrix_to_gates(A, **kwargs) qubits_count = int(np.log2(A.shape[0])) circuit = cirq.Circuit() qubits = cirq.LineQubit.range(qubits_count)[::-1] for gate in gates: if isinstance(gate, GateFC): controls = [qubits[i] for i in range(qubits_count) if i != gate.qubit_id] target = qubits[gate.qubit_id] arg_gates = controls + [target] cgate = cirq.ControlledGate( gate_to_cirq(gate.gate2), num_controls=qubits_count - 1) circuit.append(cgate.on(*arg_gates)) elif isinstance(gate, GateSingle): circuit.append(gate_to_cirq(gate.gate2).on(qubits[gate.qubit_id])) else: raise RuntimeError('Unknown gate type.') return circuit def matrix_to_qiskit_circuit(A, **kwargs): """Converts unitary matrix to Qiskit circuit. :param A: 2^N x 2^N unitary matrix. :return: `qiskit.QuantumCircuit` implementing this matrix. """ from qiskit import QuantumCircuit from qiskit.circuit.library import XGate, RYGate, RZGate, U1Gate def gate_to_qiskit(gate2): if gate2.name == 'X': return XGate() elif gate2.name == 'Ry': return RYGate(-gate2.arg) elif gate2.name == 'Rz': return RZGate(-gate2.arg) elif gate2.name == 'R1': return U1Gate(gate2.arg) else: raise RuntimeError("Can't implement: %s" % gate2) gates = matrix_to_gates(A, **kwargs) qubits_count = int(np.log2(A.shape[0])) circuit = QuantumCircuit(qubits_count) qubits = circuit.qubits for gate in gates: if isinstance(gate, GateFC): controls = [qubits[i] for i in range(qubits_count) if i != gate.qubit_id] target = qubits[gate.qubit_id] arg_gates = controls + [target] cgate = gate_to_qiskit(gate.gate2) if len(controls): cgate = cgate.control(num_ctrl_qubits=len(controls)) circuit.append(cgate, arg_gates) elif isinstance(gate, GateSingle): circuit.append(gate_to_qiskit(gate.gate2), [qubits[gate.qubit_id]]) else: raise RuntimeError('Unknown gate type.') return circuit
https://github.com/fedimser/quantum_decomp
fedimser
import unittest import warnings import numpy as np from scipy.stats import unitary_group, ortho_group import quantum_decomp as qd from quantum_decomp.src.gate import gates_to_matrix from quantum_decomp.src.test_utils import SWAP, check_decomp, QFT_2, CNOT, \ assert_all_close, random_orthogonal_matrix, random_unitary from quantum_decomp.src.two_level_unitary import TwoLevelUnitary from quantum_decomp.src.utils import is_power_of_two def _check_correct_product(A, matrices): n = A.shape[0] B = np.eye(n) for matrix in matrices: assert matrix.matrix_size == n B = matrix.get_full_matrix() @ B assert np.allclose(A, B) def _check_acting_on_same_bit(matrices): for matrix in matrices: assert is_power_of_two(matrix.index1 ^ matrix.index2) def _check_two_level_decompose(matrix): matrix = np.array(matrix) _check_correct_product(matrix, qd.two_level_decompose(matrix)) def _check_decompose_gray(matrix): matrix = np.array(matrix) result = qd.two_level_decompose_gray(matrix) _check_correct_product(matrix, result) _check_acting_on_same_bit(result) def _check_matrix_to_gates(mx): check_decomp(mx, qd.matrix_to_gates(mx)) if mx.shape[0] == 4: check_decomp(mx, qd.matrix_to_gates(mx, optimize=True)) def test_decompose_2x2(): _check_two_level_decompose([[1, 0], [0, 1]]) _check_two_level_decompose([[0, 1], [1, 0]]) _check_two_level_decompose([[0, 1j], [1j, 0]]) _check_two_level_decompose(np.array([[1, 1], [1, -1]]) / np.sqrt(2)) def test_decompose_3x3(): w = np.exp((2j / 3) * np.pi) A = w * np.array([[1, 1, 1], [1, w, w * w], [1, w * w, w]]) / np.sqrt(3) _check_two_level_decompose(A) # This test checks that two-level decomposition algorithm ensures that # diagonal element is equal to 1 after we are done with a row. def test_diagonal_elements_handled_correctly(): _check_matrix_to_gates(np.array([ [1j, 0, 0, 0], [0, -1j, 0, 0], [0, 0, -1j, 0], [0, 0, 0, 1j], ])) _check_matrix_to_gates(np.array([ [1, 0, 0, 0], [0, 0, 0, 1j], [0, 0, 1, 0], [0, 1j, 0, 0], ])) _check_matrix_to_gates(np.array([ [0, 0, 1j, 0], [0, 1j, 0, 0], [1j, 0, 0, 0], [0, 0, 0, 1], ])) def test_decompose_random(): for matrix_size in range(2, 20): for i in range(4): A = np.array(unitary_group.rvs(matrix_size)) _check_correct_product(A, qd.two_level_decompose(A)) def test_decompose_gray_2x2(): _check_decompose_gray([[1, 0], [0, 1]]) _check_decompose_gray([[0, 1], [1, 0]]) _check_decompose_gray([[0, 1j], [1j, 0]]) _check_decompose_gray(np.array([[1, 1], [1, -1]] / np.sqrt(2))) def test_decompose_gray_4x4(): _check_decompose_gray(np.eye(4).T) w = np.exp((2j / 3) * np.pi) A = w * np.array([[1, 1, 1, 0], [1, w, w * w, 0], [1, w * w, w, 0], [0, 0, 0, np.sqrt(3)]]) / np.sqrt(3) _check_decompose_gray(A) def test_decompose_gray_random(): for matrix_size in [2, 4, 8, 16]: for i in range(4): A = np.array(unitary_group.rvs(matrix_size)) _check_correct_product(A, qd.two_level_decompose(A)) def test_TwoLevelUnitary_inv(): matrix1 = TwoLevelUnitary(unitary_group.rvs(2), 8, 1, 5) matrix2 = matrix1.inv() product = matrix1.get_full_matrix() @ matrix2.get_full_matrix() assert np.allclose(product, np.eye(8)) def test_TwoLevelUnitary_multiply_right(): matrix_2x2 = TwoLevelUnitary(unitary_group.rvs(2), 8, 1, 5) A1 = unitary_group.rvs(8) A2 = np.array(A1) matrix_2x2.multiply_right(A1) assert np.allclose(A1, A2 @ matrix_2x2.get_full_matrix()) def test_matrix_to_gates_SWAP(): _check_matrix_to_gates(SWAP) def test_matrix_to_gates_random_unitary(): np.random.seed(100) for matrix_size in [2, 4, 8, 16]: for _ in range(10): _check_matrix_to_gates(unitary_group.rvs(matrix_size)) def test_matrix_to_gates_random_orthogonal(): np.random.seed(100) for matrix_size in [2, 4, 8]: for _ in range(10): _check_matrix_to_gates((ortho_group.rvs(matrix_size))) def test_matrix_to_gates_identity(): A = np.eye(16) gates = qd.matrix_to_gates(A) assert len(gates) == 0 def test_matrix_to_qsharp_SWAP(): qsharp_code = qd.matrix_to_qsharp(SWAP) expected = "\n".join([ "operation ApplyUnitaryMatrix (qs : Qubit[]) : Unit {", " CNOT(qs[1], qs[0]);", " CNOT(qs[0], qs[1]);", " CNOT(qs[1], qs[0]);", "}", ""]) assert qsharp_code == expected def test_matrix_to_cirq_circuit(): def _check(A): with warnings.catch_warnings(): warnings.simplefilter("ignore") assert_all_close(A, qd.matrix_to_cirq_circuit(A).unitary()) _check(SWAP) _check(CNOT) _check(QFT_2) np.random.seed(100) for matrix_size in [2, 4, 8]: _check(random_orthogonal_matrix(matrix_size)) _check(random_unitary(matrix_size)) def test_matrix_to_qiskit_circuit(): import qiskit.quantum_info as qi def _check(matrix): circuit = qd.matrix_to_qiskit_circuit(matrix) op = qi.Operator(circuit) assert np.allclose(op.data, matrix) _check(SWAP) _check(CNOT) _check(QFT_2) np.random.seed(100) for matrix_size in [2, 4, 8]: _check(random_orthogonal_matrix(matrix_size)) _check(random_unitary(matrix_size)) if __name__ == '__main__': unittest.main()
https://github.com/JackHidary/quantumcomputingbook
JackHidary
"""키스킷 간단한 예제 프로그램.""" # 키스킷 패키지를 가져오세요. import qiskit # 1개 큐비트를 갖는 양자 레지스터를 생성하세요. qreg = qiskit.QuantumRegister(1, name='qreg') # 1개 큐비트와 연결된 고전 레지스터를 생성하세요. creg = qiskit.ClassicalRegister(1, name='creg') # 위의 두 레지스터들로 구성된 양자 회로를 생성하세요. circ = qiskit.QuantumCircuit(qreg, creg) # NOT연산을 추가하세요. circ.x(qreg[0]) # 측정하기를 추가하세요. circ.measure(qreg, creg) # 회로를 출력합니다. print(circ.draw()) # 양자 회로를 실행할 시뮬레이터 백엔드를 가져옵니다. backend = qiskit.BasicAer.get_backend("qasm_simulator") # 회로를 가져온 백엔드 위에서 실행하고 측정결과를 얻습니다. job = qiskit.execute(circ, backend, shots=10) result = job.result() # 측정결과를 출력합니다. print(result.get_counts())
https://github.com/JackHidary/quantumcomputingbook
JackHidary
"""Superdense coding.""" # Imports import qiskit # Create two quantum and classical registers qreg = qiskit.QuantumRegister(2) creg = qiskit.ClassicalRegister(2) circ = qiskit.QuantumCircuit(qreg, creg) # Add a Hadamard gate on qubit 0 to create a superposition circ.h(qreg[0]) # Apply the X operator to qubit 0 circ.x(qreg[0]) # To get the Bell state apply the CNOT operator on qubit 0 and 1 circ.cx(qreg[0], qreg[1]) # Apply the H operator to take qubit 0 out of superposition circ.h(qreg[0]) # Add a Measure gate to obtain the message circ.measure(qreg, creg) # Print out the circuit print("Circuit:") print(circ.draw()) # Run the quantum circuit on a simulator backend backend = qiskit.Aer.get_backend("statevector_simulator") job = qiskit.execute(circ, backend) res = job.result() print(res.get_counts())
https://github.com/JackHidary/quantumcomputingbook
JackHidary
# Do the necessary imports import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import Aer from qiskit.extensions import Initialize from qiskit.quantum_info import random_statevector, Statevector,partial_trace def trace01(out_vector): return Statevector([sum([out_vector[i] for i in range(0,4)]), sum([out_vector[i] for i in range(4,8)])]) def teleportation(): # Create random 1-qubit state psi = random_statevector(2) print(psi) init_gate = Initialize(psi) init_gate.label = "init" ## SETUP qr = QuantumRegister(3, name="q") # Protocol uses 3 qubits crz = ClassicalRegister(1, name="crz") # and 2 classical registers crx = ClassicalRegister(1, name="crx") qc = QuantumCircuit(qr, crz, crx) # Don't modify the code above ## Put your code below # ---------------------------- qc.initialize(psi, qr[0]) qc.h(qr[1]) qc.cx(qr[1],qr[2]) qc.cx(qr[0],qr[1]) qc.h(qr[0]) qc.measure(qr[0],crz[0]) qc.measure(qr[1],crx[0]) qc.x(qr[2]).c_if(crx[0], 1) qc.z(qr[2]).c_if(crz[0], 1) # ---------------------------- # Don't modify the code below sim = Aer.get_backend('aer_simulator') qc.save_statevector() out_vector = sim.run(qc).result().get_statevector() result = trace01(out_vector) return psi, result # (psi,res) = teleportation() # print(psi) # print(res) # if psi == res: # print('1') # else: # print('0')
https://github.com/JackHidary/quantumcomputingbook
JackHidary
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/JackHidary/quantumcomputingbook
JackHidary
"""키스킷 간단한 예제 프로그램.""" # 키스킷 패키지를 가져오세요. import qiskit # 1개 큐비트를 갖는 양자 레지스터를 생성하세요. qreg = qiskit.QuantumRegister(1, name='qreg') # 1개 큐비트와 연결된 고전 레지스터를 생성하세요. creg = qiskit.ClassicalRegister(1, name='creg') # 위의 두 레지스터들로 구성된 양자 회로를 생성하세요. circ = qiskit.QuantumCircuit(qreg, creg) # NOT연산을 추가하세요. circ.x(qreg[0]) # 측정하기를 추가하세요. circ.measure(qreg, creg) # 회로를 출력합니다. print(circ.draw()) # 양자 회로를 실행할 시뮬레이터 백엔드를 가져옵니다. backend = qiskit.BasicAer.get_backend("qasm_simulator") # 회로를 가져온 백엔드 위에서 실행하고 측정결과를 얻습니다. job = qiskit.execute(circ, backend, shots=10) result = job.result() # 측정결과를 출력합니다. print(result.get_counts())
https://github.com/JackHidary/quantumcomputingbook
JackHidary
"""키스킷 초고밀집 부호.""" # 가져오기. import qiskit # 2개 큐비트의 양자 레지스터와 2개 비트의 고전레지스터로 회로 구성하기. qreg = qiskit.QuantumRegister(2) creg = qiskit.ClassicalRegister(2) circ = qiskit.QuantumCircuit(qreg, creg) # 아다마르(Hadamard) 게이트를 0번째 큐비트에 적용하여 중첩상태를 구현합니다. circ.h(qreg[0]) # X 연산자를 0번째 큐비트에 적용합니다. circ.x(qreg[0]) # 벨상태를 얻기 위해 0번째와 1번째 큐비트로 CNOT연산을 가합니다. # (역자주: 첫 번째 인자가 제어비트, 두 번째 인자가 피연산비트입니다.) circ.cx(qreg[0], qreg[1]) # 아다마르 연산자를 0번째 큐비트에 적용하여 중첩을 해제합니다. circ.h(qreg[0]) # 메시지를 얻기위해 측정 게이트를 추가합니다. circ.measure(qreg, creg) # 회로를 출력합니다. print("Circuit:") print(circ.draw()) # 상태벡터 시뮬레이터 백엔드 위에서 회로를 실행하고 결과를 얻습니다. backend = qiskit.Aer.get_backend("statevector_simulator") job = qiskit.execute(circ, backend) res = job.result() print(res.get_counts())
https://github.com/JackHidary/quantumcomputingbook
JackHidary
# Do the necessary imports import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import Aer from qiskit.extensions import Initialize from qiskit.quantum_info import random_statevector, Statevector,partial_trace def trace01(out_vector): return Statevector([sum([out_vector[i] for i in range(0,4)]), sum([out_vector[i] for i in range(4,8)])]) def teleportation(): # Create random 1-qubit state psi = random_statevector(2) print(psi) init_gate = Initialize(psi) init_gate.label = "init" ## SETUP qr = QuantumRegister(3, name="q") # Protocol uses 3 qubits crz = ClassicalRegister(1, name="crz") # and 2 classical registers crx = ClassicalRegister(1, name="crx") qc = QuantumCircuit(qr, crz, crx) # Don't modify the code above ## Put your code below # ---------------------------- qc.initialize(psi, qr[0]) qc.h(qr[1]) qc.cx(qr[1],qr[2]) qc.cx(qr[0],qr[1]) qc.h(qr[0]) qc.measure(qr[0],crz[0]) qc.measure(qr[1],crx[0]) qc.x(qr[2]).c_if(crx[0], 1) qc.z(qr[2]).c_if(crz[0], 1) # ---------------------------- # Don't modify the code below sim = Aer.get_backend('aer_simulator') qc.save_statevector() out_vector = sim.run(qc).result().get_statevector() result = trace01(out_vector) return psi, result # (psi,res) = teleportation() # print(psi) # print(res) # if psi == res: # print('1') # else: # print('0')
https://github.com/JackHidary/quantumcomputingbook
JackHidary
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/JackHidary/quantumcomputingbook
JackHidary
# install latest version !pip install cirq==0.5 --quiet # Alternatively, install directly from HEAD on github: # !pip install git+https://github.com/quantumlib/Cirq.git --quiet import cirq import numpy as np import matplotlib print(cirq.google.Bristlecone) a = cirq.NamedQubit("a") b = cirq.NamedQubit("b") c = cirq.NamedQubit("c") ops = [cirq.H(a), cirq.H(b), cirq.CNOT(b, c), cirq.H(b)] circuit = cirq.Circuit.from_ops(ops) print(circuit) cirq.unitary(cirq.H) for i, moment in enumerate(circuit): print('Moment {}: {}'.format(i, moment)) print(repr(circuit)) def xor_swap(a, b): yield cirq.CNOT(a, b) yield cirq.CNOT(b, a) yield cirq.CNOT(a, b) def left_rotate(qubits): for i in range(len(qubits) - 1): a, b = qubits[i:i+2] yield xor_swap(a, b) line = cirq.LineQubit.range(5) print(cirq.Circuit.from_ops(left_rotate(line))) circuit = cirq.Circuit() circuit.append([cirq.CZ(a, b)]) circuit.append([cirq.H(a), cirq.H(b), cirq.H(c)]) print(circuit) circuit = cirq.Circuit() circuit.append([cirq.CZ(a, b)]) circuit.append([cirq.H(c), cirq.H(b), cirq.H(b), cirq.H(a)], ) print(circuit) #@title a = cirq.NamedQubit('a') b = cirq.NamedQubit('b') c = cirq.NamedQubit('c') circuit = cirq.Circuit() circuit.append([cirq.CZ(a, b), cirq.H(c), cirq.H(a)] ) circuit.append([cirq.H(b), cirq.CZ(b, c), cirq.H(b), cirq.H(a), cirq.H(a)], strategy=cirq.InsertStrategy.NEW_THEN_INLINE) print(circuit) def basic_circuit(measure=True): sqrt_x = cirq.X**0.5 cz = cirq.CZ yield sqrt_x(a), sqrt_x(b) yield cz(a, b) yield sqrt_x(a), sqrt_x(b) if measure: yield cirq.measure(a,b) circuit = cirq.Circuit.from_ops(basic_circuit()) print(circuit) simulator = cirq.Simulator() circuit = cirq.Circuit.from_ops(basic_circuit()) result = simulator.run(circuit) print('Measurement results') print(result) circuit = cirq.Circuit() circuit.append(basic_circuit(measure=False)) result = simulator.simulate(circuit, qubit_order=[a, b]) print('Wavefunction:') print(np.around(result.final_state, 3)) print('Dirac notation:') print(result.dirac_notation()) circuit = cirq.Circuit.from_ops(basic_circuit()) result = simulator.run(circuit, repetitions=1000) print(result.histogram(key='a,b')) print(result.histogram(key='a,b', fold_func=lambda e: 'agree' if e[0] == e[1] else 'disagree')) q0, q1 = cirq.LineQubit.range(2) oracles = { '0': [], '1': [cirq.X(q1)], 'x': [cirq.CNOT(q0, q1)], 'notx': [cirq.CNOT(q0, q1), cirq.X(q1)] } q0, q1 = cirq.LineQubit.range(2) oracles = { '0': [], '1': [cirq.X(q1)], 'x': [cirq.CNOT(q0, q1)], 'notx': [cirq.CNOT(q0, q1), cirq.X(q1)] } def deutsch_algorithm(oracle): yield cirq.X(q1) yield cirq.H(q0), cirq.H(q1) yield oracle yield cirq.H(q0) yield cirq.measure(q0) for key, oracle in oracles.items(): print('Circuit for {}...'.format(key)) print('{}\n'.format(cirq.Circuit.from_ops(deutsch_algorithm(oracle)))) simulator = cirq.Simulator() for key, oracle in oracles.items(): result = simulator.run(cirq.Circuit.from_ops(deutsch_algorithm(oracle)), repetitions=10) print('oracle: {:<4} results: {}'.format(key, result)) q0, q1, q2 = cirq.LineQubit.range(3) constant = ([], [cirq.X(q2)]) balanced = ([cirq.CNOT(q0, q2)], [cirq.CNOT(q1, q2)], [cirq.CNOT(q0, q2), cirq.CNOT(q1, q2)], [cirq.CNOT(q0, q2), cirq.X(q2)], [ cirq.CNOT(q1, q2), cirq.X(q2)], [cirq.CNOT(q0, q2), cirq.CNOT(q1, q2), cirq.X(q2)]) for i, ops in enumerate(constant): print('\nConstant function {}'.format(i)) print(cirq.Circuit.from_ops(ops).to_text_diagram(qubit_order=[q0, q1, q2])) print() for i, ops in enumerate(balanced): print('\nBalanced function {}'.format(i)) print(cirq.Circuit.from_ops(ops).to_text_diagram(qubit_order=[q0, q1, q2])) simulator = cirq.Simulator() def your_circuit(oracle): # your code here yield oracle # and here yield cirq.measure(q0, q1, q2) print('Your result on constant functions') for oracle in constant: result = simulator.run(cirq.Circuit.from_ops(your_circuit(oracle)), repetitions=10) print(result) print('Your result on balanced functions') for oracle in balanced: result = simulator.run(cirq.Circuit.from_ops(your_circuit(oracle)), repetitions=10) print(result) #@title simulator = cirq.Simulator() def your_circuit(oracle): # phase kickback trick yield cirq.X(q2), cirq.H(q2) # equal superposition over input bits yield cirq.H(q0), cirq.H(q1) # query the function yield oracle # interference to get result, put last qubit into |1> yield cirq.H(q0), cirq.H(q1), cirq.H(q2) # a final OR gate to put result in final qubit yield cirq.X(q0), cirq.X(q1), cirq.CCX(q0, q1, q2) yield cirq.measure(q2) print('Your result on constant functions') for oracle in constant: result = simulator.run(cirq.Circuit.from_ops(your_circuit(oracle)), repetitions=10) print(result) print('Your result on balanced functions') for oracle in balanced: result = simulator.run(cirq.Circuit.from_ops(your_circuit(oracle)), repetitions=10) print(result) q0, q1, q2 = cirq.LineQubit.range(3) ops = [ cirq.X(q0), cirq.Y(q1), cirq.Z(q2), cirq.CZ(q0,q1), cirq.CNOT(q1,q2), cirq.H(q0), cirq.T(q1), cirq.S(q2), cirq.CCZ(q0, q1, q2), cirq.SWAP(q0, q1), cirq.CSWAP(q0, q1, q2), cirq.CCX(q0, q1, q2), cirq.ISWAP(q0, q1), cirq.Rx(0.5 * np.pi)(q0), cirq.Ry(.5 * np.pi)(q1), cirq.Rz(0.5 * np.pi)(q2), (cirq.X**0.5)(q0), ] print(cirq.Circuit.from_ops(ops)) print(cirq.unitary(cirq.CNOT)) print(cirq.unitary(cirq.Rx(0.5 * np.pi))) a = cirq.NamedQubit('a') circuit = cirq.Circuit.from_ops([cirq.Rx(np.pi / 50.0)(a) for theta in range(200)]) print('Circuit is a bunch of small rotations about Pauli X axis:') print('{}\n'.format(circuit)) p0 = [] z = [] print('We step through the circuit and plot the z component of the vector ' 'as a function of index of the moment being stepped over.') for i, step in enumerate(simulator.simulate_moment_steps(circuit)): prob = np.abs(step.state_vector()) ** 2 z.append(i) p0.append(prob[0]) matplotlib.pyplot.style.use('seaborn-whitegrid') matplotlib.pyplot.plot(z, p0, 'o') repetitions = 100 a = cirq.NamedQubit('a') circuit = cirq.Circuit.from_ops([cirq.Rx(np.pi / 50.0)(a) for theta in range(200)]) p0 = [] z = [] for i, step in enumerate(simulator.simulate_moment_steps(circuit)): samples = step.sample([a], repetitions=repetitions) prob0 = np.sum(samples, axis=0)[0] / repetitions p0.append(prob0) z.append(i) matplotlib.pyplot.style.use('seaborn-whitegrid') matplotlib.pyplot.plot(z, p0, 'o') class RationalGate(cirq.SingleQubitGate): def _unitary_(self): return np.array([[3 / 5, 4 / 5], [-4 / 5, 3 / 5]]) def __str__(self): return 'ζ' a = cirq.NamedQubit('a') rg = RationalGate() print(cirq.Circuit.from_ops([rg(a)])) print(cirq.unitary(rg)) circuit = cirq.Circuit.from_ops([rg(a)]) simulator = cirq.Simulator() result = simulator.simulate(circuit) print(result.final_state) class CRx(cirq.TwoQubitGate): def __init__(self, theta): self.theta = theta def _unitary_(self): return np.array([ ]) pass # Get this to print nicely in an ASCII circuit, you should also # implement the _circuit_diagram_info_ method from the # SupportsCircuitDiagramInfo protocol. You can return a tuple # of strings from this method. print(np.around(cirq.unitary(CRx(0.25 * np.pi)))) # Also get your class to print a circuit correctly. a = cirq.NamedQubit('a') b = cirq.NamedQubit('b') op = CRx(0.25 * np.pi)(a, b) print(cirq.Circuit.from_ops([op])) class CRx(cirq.TwoQubitGate): def __init__(self, theta): self.theta = theta def _unitary_(self): return np.array([ [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, np.cos(self.theta), -1j * np.sin(self.theta)], [0, 0, -1j * np.sin(self.theta), np.cos(self.theta)] ]) def _circuit_diagram_info_(self, args): return '@', 'Rx({}π)'.format(self.theta / np.pi) print('cirq.unitary on the gate yields:') print(np.around(cirq.unitary(CRx(0.25 * np.pi)))) print() a = cirq.NamedQubit('a') b = cirq.NamedQubit('b') op = CRx(0.25 * np.pi)(a, b) print('Circuit diagram:') print(cirq.Circuit.from_ops([op])) class HXGate(cirq.SingleQubitGate): def _decompose_(self, qubits): return cirq.H(*qubits), cirq.X(*qubits) def __str__(self): return 'HX' HX = HXGate() a = cirq.NamedQubit('a') circuit = cirq.Circuit.from_ops([HX(a)]) print(circuit) print(cirq.Circuit.from_ops(cirq.decompose(circuit))) print(cirq.Circuit.from_ops(cirq.decompose_once(HX(a)))) def my_decompose(op): if isinstance(op, cirq.GateOperation) and isinstance(op.gate, HXGate): return cirq.Z(*op.qubits), cirq.H(*op.qubits) cirq.Circuit.from_ops(cirq.decompose(HX(a), intercepting_decomposer=my_decompose)) def keep_h_and_x(op): return isinstance(op, cirq.GateOperation) and op.gate in [cirq.H, cirq.X] print(cirq.decompose(HX(a), keep=keep_h_and_x)) import sympy as sp a = cirq.NamedQubit('a') b = cirq.NamedQubit('b') simulator = cirq.Simulator() val = sp.Symbol('s') pow_x_gate = cirq.X**val circuit = cirq.Circuit() circuit.append([pow_x_gate(a), pow_x_gate(b)]) print('Circuit with parameterized gates:') print(circuit) print() for y in range(5): result = simulator.simulate(circuit, param_resolver={'s': y / 4.0}) print('s={}: {}'.format(y, np.around(result.final_state, 2))) resolvers = [cirq.ParamResolver({'s': y / 8.0}) for y in range(9)] circuit = cirq.Circuit() circuit.append([pow_x_gate(a), pow_x_gate(b)]) circuit.append([cirq.measure(a), cirq.measure(b)]) results = simulator.run_sweep(program=circuit, params=resolvers, repetitions=10) for i, result in enumerate(results): print('params: {}\n{}'.format(result.params.param_dict, result)) linspace = cirq.Linspace(start=0, stop=1.0, length=11, key='x') for p in linspace: print(p) import matplotlib.pyplot as plt plt.plot([1, 2, 3], [5, 3, 10]) # Insert your code here circuit = cirq.Circuit.from_ops(cirq.depolarize(0.2)(a), cirq.measure(a)) print(circuit) for i, krauss in enumerate(cirq.channel(cirq.depolarize(0.2))): print('{}th krauss operator is {}'.format(i, krauss)) print() for i, krauss in enumerate(cirq.channel(cirq.depolarize(0.2))): pauli_ex = cirq.expand_matrix_in_orthogonal_basis(krauss, cirq.PAULI_BASIS) print('{}th krauss operator is {}'.format(i, pauli_ex)) circuit = cirq.Circuit.from_ops(cirq.depolarize(0.2)(a)) print('Circuit:\n{}\n'.format(circuit)) simulator = cirq.DensityMatrixSimulator() matrix = simulator.simulate(circuit).final_density_matrix print('Final density matrix:\n{}'.format(matrix)) circuit = cirq.Circuit.from_ops(cirq.depolarize(0.2)(a), cirq.measure(a)) simulator = cirq.DensityMatrixSimulator() for _ in range(5): print(simulator.simulate(circuit).final_density_matrix) for p, u in cirq.mixture(cirq.depolarize(0.2)): print('prob={}\nunitary\n{}\n'.format(p, u)) d = cirq.depolarize(0.2) print('does cirq.depolarize(0.2) have _channel_? {}'.format('yes' if getattr(d, '_channel_', None) else 'no')) print('does cirq.depolarize(0.2) have _mixture_? {}'.format('yes' if getattr(d, '_mixture_', None) else 'no')) circuit = cirq.Circuit.from_ops(cirq.depolarize(0.5).on(a), cirq.measure(a)) simulator = cirq.Simulator() result = simulator.run(circuit, repetitions=10) print(result) noise = cirq.ConstantQubitNoiseModel(cirq.depolarize(0.2)) circuit = cirq.Circuit.from_ops(cirq.H(a), cirq.CNOT(a, b), cirq.measure(a, b)) print('Circuit with no noise:\n{}\n'.format(circuit)) system_qubits = sorted(circuit.all_qubits()) noisy_circuit = cirq.Circuit() for moment in circuit: noisy_circuit.append(noise.noisy_moment(moment, system_qubits)) print('Circuit with noise:\n{}'.format(noisy_circuit)) noise = cirq.ConstantQubitNoiseModel(cirq.depolarize(0.2)) circuit = cirq.Circuit.from_ops(cirq.H(a), cirq.CNOT(a, b), cirq.measure(a, b)) simulator = cirq.DensityMatrixSimulator(noise=noise) for i, step in enumerate(simulator.simulate_moment_steps(circuit)): print('After step {} state was\n{}\n'.format(i, step.density_matrix())) print(cirq.google.Bristlecone) brissy = cirq.google.Bristlecone op = cirq.X.on(cirq.GridQubit(5, 5)) print(brissy.duration_of(op)) q55 = cirq.GridQubit(5, 5) q56 = cirq.GridQubit(5, 6) q66 = cirq.GridQubit(6, 6) q67 = cirq.GridQubit(6, 7) ops = [cirq.CZ(q55, q56), cirq.CZ(q66, q67)] circuit = cirq.Circuit.from_ops(ops) print(circuit) print('But when we validate it against the device:') cirq.google.Bristlecone.validate_circuit(circuit) # (this should throw an error) ops = [cirq.CZ(q55, q56), cirq.CZ(q66, q67)] circuit = cirq.Circuit(device=cirq.google.Bristlecone) circuit.append(ops) print(circuit) # your code here class XZOptimizer(cirq.PointOptimizer): """Replaces an X followed by a Z with a Y.""" def optimization_at(self, circuit, index, op): # Is the gate an X gate? if isinstance(op, cirq.GateOperation) and (op.gate == cirq.X): next_op_index = circuit.next_moment_operating_on(op.qubits, index + 1) qubit = op.qubits[0] if next_op_index is not None: next_op = circuit.operation_at(qubit, next_op_index) if isinstance(next_op, cirq.GateOperation) and (next_op.gate == cirq.Z): new_op = cirq.Y.on(qubit) return cirq.PointOptimizationSummary( clear_span = next_op_index - index + 1, clear_qubits=op.qubits, new_operations=[new_op]) opt = XZOptimizer() circuit = cirq.Circuit.from_ops(cirq.X(a), cirq.Z(a), cirq.CZ(a, b), cirq.X(a)) print('Before\n{}\n'. format(circuit)) opt.optimize_circuit(circuit) print('After\n{}'.format(circuit)) # Insert your code here. # Here is a circuit to test this on. circuit = cirq.Circuit.from_ops(cirq.H(a), cirq.H(a), cirq.H(b), cirq.CNOT(a, b), cirq.H(a), cirq.H(b), cirq.CZ(a, b)) # Instantiate your optimizer # And check that it worked. print(my_opt.optimizer_circuit(circuit)) cirq.google.is_native_xmon_op(cirq.X.on(cirq.NamedQubit('a'))) cirq.google.is_native_xmon_op(cirq.CNOT.on(cirq.NamedQubit('a'), cirq.NamedQubit('b'))) converter = cirq.google.ConvertToXmonGates() converted = converter.convert(cirq.CNOT.on(cirq.NamedQubit('a'), cirq.NamedQubit('b'))) print(cirq.Circuit.from_ops(converted)) circuit = cirq.Circuit.from_ops([cirq.CNOT.on(cirq.NamedQubit('a'), cirq.NamedQubit('b'))]) print(cirq.google.optimized_for_xmon(circuit)) cirq.google.gate_to_proto_dict(cirq.X, [cirq.GridQubit(5, 5)]) result = cirq.experiments.rabi_oscillations( sampler=cirq.Simulator(), # In the future, sampler could point at real hardware. qubit=cirq.LineQubit(0) ) result.plot() class InconsistentXGate(cirq.SingleQubitGate): def _decompose_(self, qubits): yield cirq.H(qubits[0]) yield cirq.Z(qubits[0]) yield cirq.H(qubits[0]) def _unitary_(self): return np.array([[0, -1j], [1j, 0]]) # Oops! Y instead of X! cirq.testing.assert_decompose_is_consistent_with_unitary(InconsistentXGate()) a, b, c = cirq.LineQubit.range(3) circuit = cirq.Circuit.from_ops(cirq.H(a), cirq.H(c), cirq.CNOT(a, b), cirq.CCZ(a, b, c)) print(circuit.to_qasm()) from cirq.contrib.quirk.export_to_quirk import circuit_to_quirk_url print(circuit_to_quirk_url(circuit))
https://github.com/JackHidary/quantumcomputingbook
JackHidary
# install release containing NeutralAtomDevice and IonDevice classes !pip install cirq~=0.5.0 import cirq import numpy as np import cirq.ion as ci from cirq import Simulator import itertools import random ### number of qubits qubit_num = 5 ### define your qubits as line qubits for a linear ion trap qubit_list = cirq.LineQubit.range(qubit_num) ### make your ion trap device with desired gate times and qubits us = 1000*cirq.Duration(nanos=1) ion_device = ci.IonDevice(measurement_duration=100*us, twoq_gates_duration=200*us, oneq_gates_duration=10*us, qubits=qubit_list) # Single Qubit Z rotation by Pi/5 radians ion_device.validate_gate(cirq.Rz(np.pi/5)) # Single Qubit X rotation by Pi/7 radians ion_device.validate_gate(cirq.Rx(np.pi/7)) # Molmer-Sorensen gate by Pi/4 ion_device.validate_gate(cirq.MS(np.pi/4)) #Controlled gate with non-integer exponent (rotation angle must be a multiple of pi) ion_device.validate_gate(cirq.TOFFOLI) ### length of your hidden string string_length = qubit_num-1 ### generate all possible strings of length string_length, and randomly choose one as your hidden string all_strings = ["".join(seq) for seq in itertools.product("01", repeat=string_length)] hidden_string = random.choice(all_strings) ### make the circuit for BV with clifford gates circuit = cirq.Circuit() circuit.append([cirq.X(qubit_list[qubit_num-1])]) for i in range(qubit_num): circuit.append([cirq.H(qubit_list[i])]) for i in range(qubit_num-1): if hidden_string[i] == '1': circuit.append([cirq.CNOT(qubit_list[i], qubit_list[qubit_num-1])]) for i in range(qubit_num - 1): circuit.append([cirq.H(qubit_list[i])]) circuit.append([cirq.measure(qubit_list[i])]) print("Doing Bernstein-Vazirani algorithm with hidden string", hidden_string, "\n") print("Clifford Circuit:\n") print(circuit, "\n") ### convert the clifford circuit into circuit with ion trap native gates ion_circuit = ion_device.decompose_circuit(circuit) print(repr(ion_circuit)) print("Iontrap Circuit: \n", ion_circuit, "\n") ### convert the clifford circuit into circuit with ion trap native gates ion_circuit = ion_device.decompose_circuit(circuit) optimized_ion_circuit=cirq.merge_single_qubit_gates_into_phased_x_z(ion_circuit) print("Iontrap Circuit: \n", ion_circuit, "\n") ### run the ion trap circuit simulator = Simulator() clifford_result = simulator.run(circuit) result = simulator.run(ion_circuit) measurement_results = '' for i in range(qubit_num-1): if result.measurements[str(i)][0][0]: measurement_results += '1' else: measurement_results += '0' print("Hidden string is:", hidden_string) print("Measurement results are:", measurement_results) print("Found answer using Bernstein-Vazirani:", hidden_string == measurement_results)
https://github.com/JackHidary/quantumcomputingbook
JackHidary
# install release containing NeutralAtomDevice and IonDevice classes !pip install cirq~=0.5.0 --quiet import cirq import numpy as np from matplotlib import pyplot as plt ms = cirq.Duration(nanos=10**6) us = cirq.Duration(nanos=10**3) neutral_device = cirq.NeutralAtomDevice(measurement_duration = 5*ms, gate_duration = 100*us, control_radius = 2, max_parallel_z = 3, max_parallel_xy = 3, max_parallel_c = 3, qubits = [cirq.GridQubit(row, col) for col in range(3) for row in range(3)]) # Single Qubit Z rotation by Pi/5 radians neutral_device.validate_gate(cirq.Rz(np.pi/5)) # Single Qubit rotation about axis in X-Y plane Pi/3 radians from X axis by angle of Pi/7 neutral_device.validate_gate(cirq.PhasedXPowGate(phase_exponent=np.pi/3,exponent=np.pi/7)) # Controlled gate with integer exponent neutral_device.validate_gate(cirq.CNOT) # Controlled Not gate with two controls neutral_device.validate_gate(cirq.TOFFOLI) #Controlled gate with non-integer exponent (rotation angle must be a multiple of pi) neutral_device.validate_gate(cirq.CZ**1.5) # Hadamard gates rotate about the X-Z axis, which isn't compatable with our single qubit rotations neutral_device.validate_gate(cirq.H) ms = cirq.Duration(nanos=10**6) us = cirq.Duration(nanos=10**3) neutral_device = cirq.NeutralAtomDevice(measurement_duration = 5*ms, gate_duration = 100*us, control_radius = 2, max_parallel_z = 3, max_parallel_xy = 3, max_parallel_c = 3, qubits = [cirq.GridQubit(row, col) for col in range(3) for row in range(3)]) # Moment/Circuit Examples moment_circ = cirq.Circuit(device=neutral_device) qubits = [cirq.GridQubit(row, col) for col in range(3) for row in range(3)] # Three qubits affected by a Z gate in parallel with Three qubits affected # by an XY gate operation_list_one = cirq.Z.on_each(*qubits[:3])+cirq.X.on_each(*qubits[3:6]) valid_moment_one = cirq.Moment(operation_list_one) moment_circ.append(valid_moment_one) # A TOFFOLI gate on three qubits that are close enough to eachother operation_list_two = [cirq.TOFFOLI.on(*qubits[:3])] valid_moment_two = cirq.Moment(operation_list_two) moment_circ.append(valid_moment_two) print(moment_circ) global_circuit = cirq.Circuit(device=neutral_device) global_list_of_operations = cirq.X.on_each(*qubits) global_circuit.append(global_list_of_operations) print(global_circuit) global_moment_circuit = cirq.Circuit(device=neutral_device) global_moment = cirq.Moment(cirq.X.on_each(*qubits)) global_moment_circuit.append(global_moment) print(global_moment_circuit) parallel_gate_op_circuit = cirq.Circuit(device=neutral_device) parallel_gate_op = cirq.ParallelGateOperation(cirq.X,qubits) parallel_gate_op_circuit.append(parallel_gate_op) print(parallel_gate_op_circuit) def oracle(qubits, key_bits): yield (cirq.X(q) for (q, bit) in zip(qubits, key_bits) if not bit) yield cirq.CCZ(*qubits) yield (cirq.X(q) for (q, bit) in zip(qubits, key_bits) if not bit) # Try changing the key to see the relationship between # the placement of the X gates and the key key = (1, 0, 1) qubits = [cirq.GridQubit(0,col) for col in range(3)] oracle_example_circuit = cirq.Circuit().from_ops(oracle(qubits,key)) print(oracle_example_circuit) def diffusion_operator(qubits): yield cirq.H.on_each(*qubits) yield cirq.X.on_each(*qubits) yield cirq.CCZ(*qubits) yield cirq.X.on_each(*qubits) yield cirq.H.on_each(*qubits) qubits = [cirq.GridQubit(0,col) for col in range(3)] diffusion_circuit = cirq.Circuit().from_ops(diffusion_operator(qubits)) print(diffusion_circuit) def initial_hadamards(qubits): yield cirq.H.on_each(*qubits) uncompiled_circuit = cirq.Circuit() key = (1,0,1) qubits = [cirq.GridQubit(0,0),cirq.GridQubit(0,1),cirq.GridQubit(0,2)] uncompiled_circuit.append(initial_hadamards(qubits)) uncompiled_circuit.append(oracle(qubits,key)) uncompiled_circuit.append(diffusion_operator(qubits)) uncompiled_circuit.append(oracle(qubits,key)) uncompiled_circuit.append(diffusion_operator(qubits)) print(uncompiled_circuit) def neutral_atom_initial_step(qubits): yield cirq.ParallelGateOperation(cirq.Y**(1/2), qubits) def neutral_atom_diffusion_operator(qubits): yield cirq.ParallelGateOperation(cirq.Y**(1/2), qubits) yield cirq.CCZ(*qubits) yield cirq.ParallelGateOperation(cirq.Y**(-1/2), qubits) ms = cirq.Duration(nanos=10**6) us = cirq.Duration(nanos=10**3) qubits = [cirq.GridQubit(row, col) for col in range(3) for row in range(1)] three_qubit_device = cirq.NeutralAtomDevice(measurement_duration = 5*ms, gate_duration = us, control_radius = 2, max_parallel_z = 3, max_parallel_xy = 3, max_parallel_c = 3, qubits=qubits) key = (0,1,0) compiled_grover_circuit = cirq.Circuit(device=three_qubit_device) compiled_grover_circuit.append(neutral_atom_initial_step(qubits)) compiled_grover_circuit.append(oracle(qubits,key)) compiled_grover_circuit.append(neutral_atom_diffusion_operator(qubits)) compiled_grover_circuit.append(oracle(qubits,key)) compiled_grover_circuit.append(neutral_atom_diffusion_operator(qubits)) print(compiled_grover_circuit) def grover_circuit_with_n_repetitions(n, key): ms = cirq.Duration(nanos=10**6) us = cirq.Duration(nanos=10**3) qubits = [cirq.GridQubit(row, col) for col in range(3) for row in range(1)] three_qubit_device = cirq.NeutralAtomDevice(measurement_duration = 5*ms, gate_duration = us, control_radius = 2, max_parallel_z = 3, max_parallel_xy = 3, max_parallel_c = 3, qubits=qubits) grover_circuit = cirq.Circuit(device=three_qubit_device) grover_circuit.append(neutral_atom_initial_step(qubits)) for repetition in range(n): grover_circuit.append(oracle(qubits,key)) grover_circuit.append(neutral_atom_diffusion_operator(qubits)) return grover_circuit success_probabilities = [] key = (0,1,1) N = 2**3 #Convert key from binary to a base 10 number diag = sum(2**(2-count) for (count, val) in enumerate(key) if val) num_points = 10 for repetitions in range(num_points): test_circuit = grover_circuit_with_n_repetitions(repetitions, key) sim = cirq.Simulator() result = sim.simulate(test_circuit) rho = result.density_matrix_of(qubits) success_probabilities.append(np.real(rho[diag][diag])) plt.scatter(range(num_points), success_probabilities, label="Simulation") x = np.linspace(0, num_points, 1000) y = np.sin((2*x+1)*np.arcsin(1/np.sqrt(N)))**2 plt.plot(x, y, label="Theoretical Curve") plt.title("Probability of Success Vs. Number of Oracle-Diffusion Operators") plt.ylabel("Probability of Success") plt.xlabel("Number of Times Oracle and Diffusion Operators are Applied") plt.legend(loc='upper right') plt.show()
https://github.com/JackHidary/quantumcomputingbook
JackHidary
# install cirq !pip install cirq==0.5 --quiet import cirq import numpy as np import sympy import matplotlib.pyplot as plt print(cirq.google.Bristlecone) a = cirq.NamedQubit("a") b = cirq.NamedQubit("b") gamma = 0.3 # Put your own value here. circuit = cirq.Circuit.from_ops(cirq.ZZ(a,b)**gamma) print(circuit) cirq.unitary(circuit).round(2) test_matrix = np.array([[np.exp(-1j*np.pi*gamma/2),0, 0, 0], [0, np.exp(1j*np.pi*gamma/2), 0, 0], [0, 0, np.exp(1j*np.pi*gamma/2), 0], [0, 0, 0,np.exp(-1j*np.pi*gamma/2)]]) cirq.testing.assert_allclose_up_to_global_phase(test_matrix, cirq.unitary(circuit), atol=1e-5) a = cirq.NamedQubit("a") gamma = 0.3 # Put your own value here. h = 1.3 # Put your own value here. circuit = cirq.Circuit.from_ops(cirq.Z(a)**(gamma*h)) print(circuit) print(cirq.unitary(circuit).round(2)) test_matrix = np.array([[np.exp(-1j*np.pi*gamma*h/2),0], [0, np.exp(1j*np.pi*gamma*h/2)]]) cirq.testing.assert_allclose_up_to_global_phase(test_matrix, cirq.unitary(circuit), atol=1e-5) n_cols = 3 n_rows = 3 h = 0.5*np.ones((n_rows,n_cols)) # Arranging the qubits in a list-of-lists like this makes them easy to refer to later. qubits = [[cirq.GridQubit(i,j) for j in range(n_cols)] for i in range(n_rows)] def beta_layer(beta): """Generator for U(beta, B) layer (mixing layer) of QAOA""" for row in qubits: for qubit in row: yield cirq.X(qubit)**beta def gamma_layer(gamma, h): """Generator for U(gamma, C) layer of QAOA Args: gamma: Float variational parameter for the circuit h: Array of floats of external magnetic field values """ for i in range(n_rows): for j in range(n_cols): if i < n_rows-1: yield cirq.ZZ(qubits[i][j], qubits[i+1][j])**gamma if j < n_cols-1: yield cirq.ZZ(qubits[i][j], qubits[i][j+1])**gamma yield cirq.Z(qubits[i][j])**(gamma*h[i,j]) qaoa = cirq.Circuit() qaoa.append(cirq.H.on_each(*[q for row in qubits for q in row])) # YOUR CODE HERE print(qaoa) qaoa = cirq.Circuit() gamma = sympy.Symbol('g') beta = sympy.Symbol('b') qaoa.append(cirq.H.on_each(*[q for row in qubits for q in row])) qaoa.append(gamma_layer(gamma,h)) qaoa.append(beta_layer(beta)) print(qaoa) def energy_from_wavefunction(wf, h): """Computes the energy-per-site of the Ising Model directly from the a given wavefunction. Args: wf: Array of size 2**(n_rows*n_cols) specifying the wavefunction. h: Array of shape (n_rows, n_cols) giving the magnetic field values. Returns: energy: Float equal to the expectation value of the energy per site """ n_sites = n_rows*n_cols # Z is an array of shape (n_sites, 2**n_sites). Each row consists of the # 2**n_sites non-zero entries in the operator that is the Pauli-Z matrix on # one of the qubits times the identites on the other qubits. The # (i*n_cols + j)th row corresponds to qubit (i,j). Z = np.array([(-1)**(np.arange(2**n_sites) >> i) for i in range(n_sites-1,-1,-1)]) # Create the operator corresponding to the interaction energy summed over all # nearest-neighbor pairs of qubits ZZ_filter = np.zeros_like(wf, dtype=float) for i in range(n_rows): for j in range(n_cols): if i < n_rows-1: ZZ_filter += Z[i*n_cols + j]*Z[(i+1)*n_cols + j] if j < n_cols-1: ZZ_filter += Z[i*n_cols + j]*Z[i*n_cols + (j+1)] energy_operator = -ZZ_filter - h.reshape(n_sites).dot(Z) # Expectation value of the energy divided by the number of sites return np.sum(np.abs(wf)**2 * energy_operator) / n_sites def energy_from_params(gamma, beta, qaoa, h): sim = cirq.Simulator() params = cirq.ParamResolver({'g':gamma, 'b':beta}) wf = sim.simulate(qaoa, param_resolver = params).final_state return energy_from_wavefunction(wf, h) %%time grid_size = 50 gamma_max = 2 beta_max = 2 energies = np.zeros((grid_size,grid_size)) for i in range(grid_size): for j in range(grid_size): energies[i,j] = energy_from_params(i*gamma_max/grid_size, j*beta_max/grid_size, qaoa, h) plt.ylabel('gamma') plt.xlabel('beta') plt.title('Energy as a Function of Parameters') plt.imshow(energies, extent = (0,beta_max,gamma_max,0)); def gradient_energy(gamma, beta, qaoa, h): """Uses a symmetric difference to calulate the gradient.""" eps = 10**-3 # Try different values of the discretization parameter # Gamma-component of the gradient grad_g = energy_from_params(gamma + eps, beta, qaoa, h) grad_g -= energy_from_params(gamma - eps, beta, qaoa, h) grad_g /= 2*eps # Beta-compoonent of the gradient grad_b = energy_from_params(gamma, beta + eps, qaoa, h) grad_b -= energy_from_params(gamma, beta - eps, qaoa, h) grad_b /= 2*eps return grad_g, grad_b gamma, beta = 0.2, 0.7 # Try different initializations eta = 10**-2 # Try adjusting the learning rate. for i in range(151): grad_g, grad_b = gradient_energy(gamma, beta, qaoa, h) gamma -= eta*grad_g beta -= eta*grad_b if not i%25: print('Step: {} Energy: {}'.format(i, energy_from_params(gamma, beta, qaoa, h))) print('Learned gamma: {} Learned beta: {}'.format(gamma, beta, qaoa, h)) measurement_circuit = qaoa.copy() measurement_circuit.append(cirq.measure(*[qubit for row in qubits for qubit in row],key='m')) measurement_circuit num_reps = 10**3 # Try different numbers of repetitions gamma, beta = 0.2,0.25 # Try different values of the parameters simulator = cirq.Simulator() params = cirq.ParamResolver({'g':gamma, 'b':beta}) result = simulator.run(measurement_circuit, param_resolver = params, repetitions=num_reps) def compute_energy(meas, h): Z_vals = 1-2*meas.reshape(n_rows,n_cols) energy = 0 for i in range(n_rows): for j in range(n_cols): if i < n_rows-1: energy -= Z_vals[i, j]*Z_vals[i+1, j] if j < n_cols-1: energy -= Z_vals[i, j]*Z_vals[i, j+1] energy -= h[i,j]*Z_vals[i,j] return energy/(n_rows*n_cols) hist = result.histogram(key='m') num = 10 probs = [v/result.repetitions for _,v in hist.most_common(num)] configs = [c for c,_ in hist.most_common(num)] plt.title('Probability of {} Most Common Outputs'.format(num)) plt.bar([x for x in range(len(probs))],probs) plt.show() meas = [[int(s) for s in ''.join([str(b) for b in bin(k)[2:]]).zfill(n_rows*n_cols)] for k in configs] costs = [compute_energy(np.array(m), h) for m in meas] plt.title('Energy of {} Most Common Outputs'.format(num)) plt.bar([x for x in range(len(costs))],costs) plt.show() print('Fraction of outputs displayed: {}'.format(np.sum(probs).round(2)))
https://github.com/JackHidary/quantumcomputingbook
JackHidary
!pip install openfermion openfermioncirq pyscf openfermionpyscf import openfermion as of op = of.FermionOperator(((4, 1), (3, 1), (9, 0), (1, 0)), 1+2j) + of.FermionOperator(((3, 1), (1, 0)), -1.7) print(op.terms) op = of.FermionOperator('4^ 3^ 9 1', 1+2j) + of.FermionOperator('3^ 1', -1.7) print(op.terms) print(op) op = of.QubitOperator(((1, 'X'), (2, 'Y'), (3, 'Z'))) op += of.QubitOperator('X3 Z4', 3.0) print(op) op = of.FermionOperator('2^ 15') print(of.jordan_wigner(op)) print() print(of.bravyi_kitaev(op, n_qubits=16)) a2 = of.FermionOperator('2') print(of.jordan_wigner(a2)) print() a2dag = of.FermionOperator('2^') print(of.jordan_wigner(a2dag*a2)) print() a7 = of.FermionOperator('7') a7dag = of.FermionOperator('7^') print(of.jordan_wigner((1+2j)*(a2dag*a7) + (1-2j)*(a7dag*a2))) a2 = of.FermionOperator('2') a2dag = of.FermionOperator('2^') a7 = of.FermionOperator('7') a7dag = of.FermionOperator('7^') print(of.jordan_wigner(a2dag)) print() print(of.jordan_wigner(a2dag*a2)) print() op = (2+3j)*a2dag*a7 op += of.hermitian_conjugated(op) print(of.jordan_wigner(op)) a2_jw = of.jordan_wigner(a2) a2dag_jw = of.jordan_wigner(a2dag) a7_jw = of.jordan_wigner(a7) a7dag_jw = of.jordan_wigner(a7dag) print(a2_jw * a7_jw + a7_jw * a2_jw) print(a2_jw * a7dag_jw + a7dag_jw * a2_jw) print(a2_jw * a2dag_jw + a2dag_jw * a2_jw) import openfermionpyscf as ofpyscf # Set molecule parameters geometry = [('H', (0.0, 0.0, 0.0)), ('H', (0.0, 0.0, 0.8))] basis = 'sto-3g' multiplicity = 1 charge = 0 # Perform electronic structure calculations and # obtain Hamiltonian as an InteractionOperator hamiltonian = ofpyscf.generate_molecular_hamiltonian( geometry, basis, multiplicity, charge) # Convert to a FermionOperator hamiltonian_ferm_op = of.get_fermion_operator(hamiltonian) print(hamiltonian_ferm_op) import scipy.sparse # Map to QubitOperator using the JWT hamiltonian_jw = of.jordan_wigner(hamiltonian_ferm_op) # Convert to Scipy sparse matrix hamiltonian_jw_sparse = of.get_sparse_operator(hamiltonian_jw) # Compute ground energy eigs, _ = scipy.sparse.linalg.eigsh(hamiltonian_jw_sparse, k=1, which='SA') ground_energy = eigs[0] print('Ground_energy: {}'.format(ground_energy)) print('JWT transformed Hamiltonian:') print(hamiltonian_jw) import scipy.sparse # Map to QubitOperator using the JWT hamiltonian_bk = of.bravyi_kitaev(hamiltonian_ferm_op) # Convert to Scipy sparse matrix hamiltonian_bk_sparse = of.get_sparse_operator(hamiltonian_bk) # Compute ground energy eigs, _ = scipy.sparse.linalg.eigsh(hamiltonian_bk_sparse, k=1, which='SA') ground_energy = eigs[0] print('Ground_energy: {}'.format(ground_energy)) print('BK transformed Hamiltonian:') print(hamiltonian_bk) # Map to QubitOperator using the BKT hamiltonian_bk = of.bravyi_kitaev(hamiltonian_ferm_op) # Convert to Scipy sparse matrix hamiltonian_bk_sparse = of.get_sparse_operator(hamiltonian_bk) # Compute ground state energy eigs, _ = scipy.sparse.linalg.eigsh(hamiltonian_bk_sparse, k=1, which='SA') ground_energy = eigs[0] print('Ground_energy: {}'.format(ground_energy)) print('BKT transformed Hamiltonian:') print(hamiltonian_bk) # Create a random initial state n_qubits = of.count_qubits(hamiltonian) initial_state = of.haar_random_vector(2**n_qubits, seed=7) # Set evolution time time = 1.0 # Apply exp(-i H t) to the state exact_state = scipy.sparse.linalg.expm_multiply(-1j*hamiltonian_jw_sparse*time, initial_state) import cirq import openfermioncirq as ofc import numpy as np # Initialize qubits qubits = cirq.LineQubit.range(n_qubits) # Create circuit circuit = cirq.Circuit.from_ops( ofc.simulate_trotter( qubits, hamiltonian, time, n_steps=10, order=0, algorithm=ofc.trotter.LOW_RANK) ) # Apply the circuit to the initial state result = circuit.apply_unitary_effect_to_state(initial_state) # Compute the fidelity with the final state from exact evolution fidelity = abs(np.dot(exact_state, result.conj()))**2 print(fidelity) print(circuit.to_text_diagram(transpose=True)) import cirq import openfermioncirq as ofc ansatz = ofc.LowRankTrotterAnsatz(hamiltonian) cirq.DropNegligible().optimize_circuit(ansatz.circuit) print(ansatz.circuit.to_text_diagram(transpose=True)) import scipy.optimize def energy_from_params(x): param_resolver = ansatz.param_resolver(x) circuit = cirq.resolve_parameters(ansatz.circuit, param_resolver) final_state = circuit.apply_unitary_effect_to_state(0b1100) return of.expectation(hamiltonian_jw_sparse, final_state).real initial_guess = ansatz.default_initial_params() result = scipy.optimize.minimize(energy_from_params, initial_guess) print('Initial energy: {}'.format(energy_from_params(initial_guess))) print('Optimized energy: {}'.format(result.fun)) n_qubits = 5 quad_ham = of.random_quadratic_hamiltonian( n_qubits, conserves_particle_number=True, seed=7) print(of.get_fermion_operator(quad_ham)) _, basis_change_matrix, _ = quad_ham.diagonalizing_bogoliubov_transform() qubits = cirq.LineQubit.range(n_qubits) circuit = cirq.Circuit.from_ops( ofc.bogoliubov_transform( qubits, basis_change_matrix)) print(circuit.to_text_diagram(transpose=True)) orbital_energies, constant = quad_ham.orbital_energies() print(orbital_energies) print(constant) # Apply the circuit with initial state having the first two modes occupied. result = circuit.apply_unitary_effect_to_state(0b11000) # Compute the expectation value of the final state with the Hamiltonian quad_ham_sparse = of.get_sparse_operator(quad_ham) print(of.expectation(quad_ham_sparse, result)) # Print out the ground state energy; it should match print(quad_ham.ground_energy()) from scipy.sparse.linalg import expm_multiply # Create a random initial state initial_state = of.haar_random_vector(2**n_qubits) # Set evolution time time = 1.0 # Apply exp(-i H t) to the state final_state = expm_multiply(-1j*quad_ham_sparse*time, initial_state) # Initialize qubits qubits = cirq.LineQubit.range(n_qubits) # Write code below to create the circuit # You should define the `circuit` variable here # --------------------------------------------- # --------------------------------------------- # Apply the circuit to the initial state result = circuit.apply_unitary_effect_to_state(initial_state) # Compute the fidelity with the correct final state fidelity = abs(np.dot(final_state, result.conj()))**2 # Print fidelity; it should be 1 print(fidelity) # Initialize qubits qubits = cirq.LineQubit.range(n_qubits) # Write code below to create the circuit # You should define the `circuit` variable here # --------------------------------------------- def exponentiate_quad_ham(qubits, quad_ham): _, basis_change_matrix, _ = quad_ham.diagonalizing_bogoliubov_transform() orbital_energies, _ = quad_ham.orbital_energies() yield cirq.inverse( ofc.bogoliubov_transform(qubits, basis_change_matrix)) for i in range(len(qubits)): yield cirq.Rz(rads=-orbital_energies[i]).on(qubits[i]) yield ofc.bogoliubov_transform(qubits, basis_change_matrix) circuit = cirq.Circuit.from_ops(exponentiate_quad_ham(qubits, quad_ham)) # --------------------------------------------- # Apply the circuit to the initial state result = circuit.apply_unitary_effect_to_state(initial_state) # Compute the fidelity with the correct final state fidelity = abs(np.dot(final_state, result.conj()))**2 # Print fidelity; it should be 1 print(fidelity)
https://github.com/JackHidary/quantumcomputingbook
JackHidary
# install cirq !pip install cirq==0.5 --quiet import cirq import numpy as np import random print(cirq.google.Bristlecone) def make_quantum_teleportation_circuit(gate): circuit = cirq.Circuit() msg, alice, bob = cirq.LineQubit.range(3) # Creates Bell state to be shared between Alice and Bob circuit.append([cirq.H(alice), cirq.CNOT(alice, bob)]) # Creates a random state for the Message circuit.append(gate(msg)) # Bell measurement of the Message and Alice's entangled qubit circuit.append([cirq.CNOT(msg, alice), cirq.H(msg)]) circuit.append(cirq.measure(msg, alice)) # Uses the two classical bits from the Bell measurement to recover the # original quantum Message on Bob's entangled qubit circuit.append([cirq.CNOT(alice, bob), cirq.CZ(msg, bob)]) return circuit gate = cirq.SingleQubitMatrixGate(cirq.testing.random_unitary(2)) circuit = make_quantum_teleportation_circuit(gate) print("Circuit:") print(circuit) sim = cirq.Simulator() # Create qubits. q0 = cirq.LineQubit # Produces the message using random unitary message = sim.simulate(cirq.Circuit.from_ops(gate(q0))) print("Bloch Vector of Message After Random Unitary:") # Prints the Bloch vector of the Message after the random gate b0X, b0Y, b0Z = cirq.bloch_vector_from_state_vector( message.final_state, 0) print("x: ", np.around(b0X, 4), "y: ", np.around(b0Y, 4), "z: ", np.around(b0Z, 4)) # Records the final state of the simulation final_results = sim.simulate(circuit) print("Bloch Sphere of Qubit 2 at Final State:") # Prints the Bloch Sphere of Bob's entangled qubit at the final state b2X, b2Y, b2Z = cirq.bloch_vector_from_state_vector( final_results.final_state, 2) print("x: ", np.around(b2X, 4), "y: ", np.around(b2Y, 4), "z: ", np.around(b2Z, 4)) def make_oracle(q0, q1, secret_function): """ Gates implementing the secret function f(x).""" # coverage: ignore if secret_function[0]: yield [cirq.CNOT(q0, q1), cirq.X(q1)] if secret_function[1]: yield cirq.CNOT(q0, q1) def make_deutsch_circuit(q0, q1, oracle): c = cirq.Circuit() # Initialize qubits. c.append([cirq.X(q1), cirq.H(q1), cirq.H(q0)]) # Query oracle. c.append(oracle) # Measure in X basis. c.append([cirq.H(q0), cirq.measure(q0, key='result')]) return c # Choose qubits to use. q0, q1 = cirq.LineQubit.range(2) # Pick a secret 2-bit function and create a circuit to query the oracle. secret_function = [random.randint(0,1) for _ in range(2)] oracle = make_oracle(q0, q1, secret_function) print('Secret function:\nf(x) = <{}>'.format( ', '.join(str(e) for e in secret_function))) # Embed the oracle into a quantum circuit querying it exactly once. circuit = make_deutsch_circuit(q0, q1, oracle) print('Circuit:') print(circuit) # Simulate the circuit. simulator = cirq.Simulator() result = simulator.run(circuit) print('Result of f(0)⊕f(1):') print(result) def make_qft(qubits): """Generator for the QFT on an arbitrary number of qubits. With four qubits the answer is ---H--@-------@--------@--------------------------------------------- | | | ------@^0.5---+--------+---------H--@-------@------------------------ | | | | --------------@^0.25---+------------@^0.5---+---------H--@----------- | | | -----------------------@^0.125--------------@^0.25-------@^0.5---H--- """ # YOUR CODE HERE def make_qft(qubits): """Generator for the QFT on an arbitrary number of qubits. With four qubits the answer is ---H--@-------@--------@--------------------------------------------- | | | ------@^0.5---+--------+---------H--@-------@------------------------ | | | | --------------@^0.25---+------------@^0.5---+---------H--@----------- | | | -----------------------@^0.125--------------@^0.25-------@^0.5---H--- """ qubits = list(qubits) while len(qubits) > 0: q_head = qubits.pop(0) yield cirq.H(q_head) for i, qubit in enumerate(qubits): yield (cirq.CZ**(1/2**(i+1)))(qubit, q_head) num_qubits = 4 qubits = cirq.LineQubit.range(num_qubits) qft = cirq.Circuit.from_ops(make_qft(qubits)) print(qft) class QFT(cirq.Gate): """Gate for the Quantum Fourier Transformation """ def __init__(self, n_qubits): self.n_qubits = n_qubits def num_qubits(self): return self.n_qubits def _decompose_(self, qubits): # YOUR CODE HERE # How should the gate look in ASCII diagrams? def _circuit_diagram_info_(self, args): return tuple('QFT{}'.format(i) for i in range(self.n_qubits)) class QFT(cirq.Gate): """Gate for the Quantum Fourier Transformation """ def __init__(self, n_qubits): self.n_qubits = n_qubits def num_qubits(self): return self.n_qubits def _decompose_(self, qubits): """Implements the QFT on an arbitrary number of qubits. The circuit for num_qubits = 4 is given by ---H--@-------@--------@--------------------------------------------- | | | ------@^0.5---+--------+---------H--@-------@------------------------ | | | | --------------@^0.25---+------------@^0.5---+---------H--@----------- | | | -----------------------@^0.125--------------@^0.25-------@^0.5---H--- """ qubits = list(qubits) while len(qubits) > 0: q_head = qubits.pop(0) yield cirq.H(q_head) for i, qubit in enumerate(qubits): yield (cirq.CZ**(1/2**(i+1)))(qubit, q_head) # How should the gate look in ASCII diagrams? def _circuit_diagram_info_(self, args): return tuple('QFT{}'.format(i) for i in range(self.n_qubits)) num_qubits = 4 qubits = cirq.LineQubit.range(num_qubits) circuit = cirq.Circuit.from_ops(QFT(num_qubits).on(*qubits)) print(circuit) qft_test = cirq.Circuit.from_ops(make_qft(qubits)) print(qft_test) np.testing.assert_allclose(cirq.unitary(qft_test), cirq.unitary(circuit)) class QFT_inv(cirq.Gate): """Gate for the inverse Quantum Fourier Transformation """ # YOUR CODE HERE class QFT_inv(cirq.Gate): """Gate for the inverse Quantum Fourier Transformation """ def __init__(self, n_qubits): self.n_qubits = n_qubits def num_qubits(self): return self.n_qubits def _decompose_(self, qubits): """Implements the inverse QFT on an arbitrary number of qubits. The circuit for num_qubits = 4 is given by ---H--@-------@--------@--------------------------------------------- | | | ------@^-0.5--+--------+---------H--@-------@------------------------ | | | | --------------@^-0.25--+------------@^-0.5--+---------H--@----------- | | | -----------------------@^-0.125-------------@^-0.25------@^-0.5--H--- """ qubits = list(qubits) while len(qubits) > 0: q_head = qubits.pop(0) yield cirq.H(q_head) for i, qubit in enumerate(qubits): yield (cirq.CZ**(-1/2**(i+1)))(qubit, q_head) def _circuit_diagram_info_(self, args): return tuple('QFT{}^-1'.format(i) for i in range(self.n_qubits)) num_qubits = 2 qubits = cirq.LineQubit.range(num_qubits) circuit = cirq.Circuit.from_ops(QFT(num_qubits).on(*qubits), QFT_inv(num_qubits).on(*qubits)) print(circuit) cirq.unitary(circuit).round(2) num_qubits = 2 qubits = cirq.LineQubit.range(num_qubits) circuit = cirq.Circuit.from_ops(QFT(num_qubits).on(*qubits), QFT_inv(num_qubits).on(*qubits[::-1])) # qubit order reversed print(circuit) cirq.unitary(circuit) theta = 0.234 # Try your own n_bits = 3 # Accuracy of the estimate for theta. Try different values. qubits = cirq.LineQubit.range(n_bits) u_bit = cirq.NamedQubit('u') U = cirq.Z**(2*theta) phase_estimator = cirq.Circuit() phase_estimator.append(cirq.H.on_each(*qubits)) for i, bit in enumerate(qubits): phase_estimator.append(cirq.ControlledGate(U).on(bit,u_bit)**(2**(n_bits-1-i))) print(phase_estimator) phase_estimator.append(QFT_inv(n_bits).on(*qubits)) print(phase_estimator) # Add measurements to the end of the circuit phase_estimator.append(cirq.measure(*qubits, key='m')) # Add gate to change initial state to |1> phase_estimator.insert(0,cirq.X(u_bit)) print(phase_estimator) sim = cirq.Simulator() result = sim.run(phase_estimator, repetitions=10) theta_estimates = np.sum(2**np.arange(n_bits)*result.measurements['m'], axis=1)/2**n_bits print(theta_estimates) def phase_estimation(theta, n_bits, n_reps=10): # YOUR CODE HERE return theta_estimates def phase_estimation(theta, n_bits, n_reps=10): qubits = cirq.LineQubit.range(n_bits) u_bit = cirq.NamedQubit('u') U = cirq.Z**(2*theta) # Try out a different gate if you like phase_estimator = cirq.Circuit() phase_estimator.append(cirq.H.on_each(*qubits)) for i, bit in enumerate(qubits): phase_estimator.append(cirq.ControlledGate(U).on(bit,u_bit)**(2**(n_bits-1-i))) phase_estimator.append(QFT_inv(n_bits).on(*qubits)) # Measurement gates phase_estimator.append(cirq.measure(*qubits, key='m')) # Gates to choose initial state for the u_bit. Placing X here chooses the |1> state phase_estimator.insert(0,cirq.X(u_bit)) # Code to simulate measurements sim = cirq.Simulator() result = sim.run(phase_estimator, repetitions=n_reps) # Convert measurements into estimates of theta theta_estimates = np.sum(2**np.arange(n_bits)*result.measurements['m'], axis=1)/2**n_bits return theta_estimates phase_estimation(0.234, 10) def phase_estimation(theta, n_bits, n_reps=10): qubits = cirq.LineQubit.range(n_bits) u_bit = cirq.NamedQubit('u') U = cirq.Z**(2*theta) phase_estimator = cirq.Circuit() phase_estimator.append(cirq.H.on_each(*qubits)) for i, bit in enumerate(qubits): phase_estimator.append(cirq.ControlledGate(U).on(bit,u_bit)**(2**(n_bits-1-i))) # Could have used CZ in this example phase_estimator.append(QFT_inv(n_bits).on(*qubits)) phase_estimator.append(cirq.measure(*qubits, key='m')) # Changed the X gate here to an H phase_estimator.insert(0,cirq.H(u_bit)) sim = cirq.Simulator() result = sim.run(phase_estimator, repetitions=n_reps) theta_estimates = np.sum(2**np.arange(n_bits)*result.measurements['m'], axis=1)/2**n_bits return theta_estimates phase_estimation(0.234,10) def set_io_qubits(qubit_count): """Add the specified number of input and output qubits.""" input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)] output_qubit = cirq.GridQubit(qubit_count, 0) return (input_qubits, output_qubit) def make_oracle(input_qubits, output_qubit, x_bits): """Implement function {f(x) = 1 if x==x', f(x) = 0 if x!= x'}.""" # Make oracle. # for (1, 1) it's just a Toffoli gate # otherwise negate the zero-bits. yield(cirq.X(q) for (q, bit) in zip(input_qubits, x_bits) if not bit) yield(cirq.TOFFOLI(input_qubits[0], input_qubits[1], output_qubit)) yield(cirq.X(q) for (q, bit) in zip(input_qubits, x_bits) if not bit) def make_grover_circuit(input_qubits, output_qubit, oracle): """Find the value recognized by the oracle in sqrt(N) attempts.""" # For 2 input qubits, that means using Grover operator only once. c = cirq.Circuit() # Initialize qubits. c.append([ cirq.X(output_qubit), cirq.H(output_qubit), cirq.H.on_each(*input_qubits), ]) # Query oracle. c.append(oracle) # Construct Grover operator. c.append(cirq.H.on_each(*input_qubits)) c.append(cirq.X.on_each(*input_qubits)) c.append(cirq.H.on(input_qubits[1])) c.append(cirq.CNOT(input_qubits[0], input_qubits[1])) c.append(cirq.H.on(input_qubits[1])) c.append(cirq.X.on_each(*input_qubits)) c.append(cirq.H.on_each(*input_qubits)) # Measure the result. c.append(cirq.measure(*input_qubits, key='result')) return c def bitstring(bits): return ''.join(str(int(b)) for b in bits) qubit_count = 2 circuit_sample_count = 10 #Set up input and output qubits. (input_qubits, output_qubit) = set_io_qubits(qubit_count) #Choose the x' and make an oracle which can recognize it. x_bits = [random.randint(0, 1) for _ in range(qubit_count)] print('Secret bit sequence: {}'.format(x_bits)) # Make oracle (black box) oracle = make_oracle(input_qubits, output_qubit, x_bits) # Embed the oracle into a quantum circuit implementing Grover's algorithm. circuit = make_grover_circuit(input_qubits, output_qubit, oracle) print('Circuit:') print(circuit) # Sample from the circuit a couple times. simulator = cirq.Simulator() result = simulator.run(circuit, repetitions=circuit_sample_count) frequencies = result.histogram(key='result', fold_func=bitstring) print('Sampled results:\n{}'.format(frequencies)) # Check if we actually found the secret value. most_common_bitstring = frequencies.most_common(1)[0][0] print('Most common bitstring: {}'.format(most_common_bitstring)) print('Found a match: {}'.format( most_common_bitstring == bitstring(x_bits)))
https://github.com/ionq-samples/qiskit-getting-started
ionq-samples
# import Aer here, before calling qiskit_ionq_provider from qiskit import Aer from qiskit_ionq import IonQProvider # Call provider and set token value provider = IonQProvider(token='My token') provider.backends() from qiskit import QuantumCircuit # Create a bell state circuit. qc = QuantumCircuit(2, 2) qc.h(0) qc.cx(0, 1) qc.measure([0, 1], [0, 1]) # Show the circuit: qc.draw() from qiskit.providers.jobstatus import JobStatus # Get an IonQ simulator backend to run circuits on: backend = provider.get_backend("ionq_simulator") # Then run the circuit: job = backend.run(qc, shots=1000) # Save job_id job_id_bell = job.job_id() # Fetch the result: result = job.result() from qiskit.visualization import plot_histogram plot_histogram(result.get_counts()) # Next get an IonQ hardware backend to run circuits on: qpu_backend = provider.get_backend("ionq_qpu") # Then run the circuit: qpu_job_bell = qpu_backend.run(qc) # Store job id job_id_bell = qpu_job_bell.job_id() # Check if job is done if qpu_job_bell.status() is JobStatus.DONE: print("Job status is DONE") # Fetch the result: qpu_result_bell = qpu_job_bell.result() else: print("Job status is ", qpu_job_bell.status() ) # If job is finished, plot and validate results: plot_histogram(qpu_result_bell.get_counts()) # Retrieve a previously executed job: old_job = backend.retrieve_job(job_id_bell) # Then render the old job results: old_result = old_job.result() plot_histogram(old_result.get_counts()) n=4 qc_cat = QuantumCircuit(n, n) qc_cat.h(0) for i in range(1,n): qc_cat.cx(0, i) qc_cat.measure(range(n), range(n)) # Show the circuit: qc_cat.draw() # Run the circuit on the simulator and plot the results job_cat = backend.run(qc_cat) # Save job id job_id_cat = job_cat.job_id() # Fetch the result: result_cat = job_cat.result() plot_histogram(result_cat.get_counts()) # Then run the circuit on the hardware: qpu_job_cat = qpu_backend.run(qc_cat) # Save job id qpu_job_id_cat = qpu_job_cat.job_id() # Check if job is done if qpu_job_cat.status() is JobStatus.DONE: print("Job status is DONE") # Fetch the result: qpu_result_cat = qpu_job_cat.result() else: print("Job status is ", qpu_job_cat.status() ) # If job is finished, plot and validate results: plot_histogram(qpu_result_cat.get_counts())
https://github.com/ionq-samples/qiskit-getting-started
ionq-samples
# general imports import math import time import pickle import random import numpy as np import matplotlib.pyplot as plt from scipy.optimize import minimize from datetime import datetime # Noisy optimization package — you could also use scipy's optimization functions, # but this is a little better suited to the noisy output of NISQ devices. %pip install noisyopt import noisyopt # magic invocation for producing visualizations in notebook %matplotlib inline # Qiskit imports from qiskit import Aer from qiskit_ionq import IonQProvider #Call provider and set token value provider = IonQProvider(token='My token') provider.backends() # fix random seed for reproducibility — this allows us to re-run the process and get the same results seed = 42 np.random.seed(seed) random.seed(a=seed) #Generate BAS, only one bar or stripe allowed def generate_target_distribution(rows, columns): #Stripes states=[] for i in range(rows): s=['0']*rows*columns for j in range(columns): s[j+columns*i]='1' states.append(''.join(s)) #Bars for j in range(columns): s=['0']*rows*columns for i in range(rows): s[j+columns*i]='1' states.append(''.join(s)) return states #Parameters for driver def generate_beta(ansatz_type,random_init): if ansatz_type[0]==0: #No driver beta=[] elif ansatz_type[0]==1: #Rz(t1)Rx(t2)Rz(t3), angles different for each qubit beta=( [random.uniform(0.0,2.*math.pi) for i in range(3*n*(layers-1))] if random_init else [0]*3*n*(layers-1) ) elif ansatz_type[0]==2: #Rz(t1)Rx(t2)Rz(t3), angles same for all qubits beta=( [random.uniform(0.0,2.*math.pi) for i in range(3*(layers-1))] if random_init else [0]*3*(layers-1) ) elif ansatz_type[0]==3: #Rz(t1), angles different for each qubit beta=( [random.uniform(0.0,2.*math.pi) for i in range(n*(layers-1))] if random_init else [0]*n*(layers-1) ) else: raise Exception("Undefined driver type") return beta #Parameters for entangler def generate_gamma(ansatz_type,random_init, n, conn): length_gamma=int(n*conn-conn*(conn+1)/2.) if ansatz_type[1]==0: #No entangler gamma=[] elif ansatz_type[1]==1: #XX(t1), angles different for each qubit gamma=( [random.uniform(0.0,2.*math.pi) for i in range(length_gamma*layers)] if random_init else [0]*length_gamma*layers ) elif ansatz_type[1]==2: #XX(t1), angles same for all qubits gamma=( [random.uniform(0.0,2.*math.pi) for i in range(layers)] if random_init else gamma[0]*layers ) else: raise Exception("Undefined entangler type") return gamma from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.circuit import Gate def driver(circ,qr,beta,n,ansatz_type): #qr=QuantumRegister(n) #circ = QuantumCircuit(qr) if ansatz_type==0: pass elif ansatz_type==1: for i_q in range(n): circ.rz(beta[3*i_q], qr[i_q]) circ.rx(beta[3*i_q+1], qr[i_q]) circ.rz(beta[3*i_q+2], qr[i_q]) elif ansatz_type==2: for i_q in range(n): circ.rz(beta[0], qr[i_q]) circ.rx(beta[1], qr[i_q]) circ.rz(beta[2], qr[i_q]) elif ansatz_type==3: for i_q in range(n): circ.rz(beta[i_q], qr[i_q]) return def entangler(circ,qr,gamma,n,conn,ansatz_type): #qr=QuantumRegister(n) #cr=ClassicalRegister(n) #circ = QuantumCircuit(qr) if ansatz_type==0: pass elif ansatz_type==1: i_gamma=0 for i_conn in range(1,conn+1): for i_q in range(0,n-i_conn): circ.cx(qr[i_q],qr[i_q+i_conn]) circ.rx(gamma[i_gamma],qr[i_q]) circ.cx(qr[i_q],qr[i_q+i_conn]) #circ.rxx(gamma[i_gamma], qr[i_q], qr[i_q+i_conn]) i_gamma+=1 elif ansatz_type==2: for i_conn in range(1,conn+1): for i_q in range(0,n-i_conn): circ.cx(qr[i_q],qr[i_q+i_conn]) circ.rx(gamma[0],qr[i_q]) circ.cx(qr[i_q],qr[i_q+i_conn]) #circ.rxx(gamma[0], qr[i_q], qr[i_q+i_conn]) #circ.measure(qr,cr) return #Define circuit ansatz def circuit_ansatz(n,params,conn=1, layers=1, ansatz_type=[1,1]): qr=QuantumRegister(n) cr=ClassicalRegister(n) circ = QuantumCircuit(qr,cr) if ansatz_type[0]==0: length_beta=0 elif ansatz_type[0]==1: length_beta=3*n elif ansatz_type[0]==2: length_beta=3 elif ansatz_type[0]==3: length_beta=n if ansatz_type[1]==0: length_gamma=0 elif ansatz_type[1]==1: length_gamma=int(n*conn-conn*(conn+1)/2.) elif ansatz_type[1]==2: length_gamma=1 for i_layer in range(layers-1): beta=params[(length_beta+length_gamma)*i_layer:(length_beta+length_gamma)*i_layer+length_beta] gamma=params[(length_beta+length_gamma)*i_layer+length_beta:(length_beta+length_gamma)*(i_layer+1)] entangler(circ,qr,gamma,n,conn,ansatz_type[1]) driver(circ,qr,beta,n,ansatz_type[0]) gamma=params[(length_beta+length_gamma)*(layers-1):] entangler(circ,qr,gamma,n,conn,ansatz_type[1]) circ.measure(qr, cr) return circ def cost(counts, shots, target_states,tol=0.0001): cost=0 for state in target_states: if state in counts: cost-=1./len(target_states)*np.log2(max(tol,counts[state]/shots)) else: cost-=1./len(target_states)*np.log2(tol) return cost from qiskit.providers.jobstatus import JobStatus def run_iteration(circ, num_qubits, shots=100): # submit task: define task (asynchronous) task_status='' while task_status != JobStatus.DONE: task = backend.run(circ, shots=shots) #print("Job submitted") # Get ID of submitted task task_id = task.job_id() #print('Task ID :', task_id) while (task_status == JobStatus.INITIALIZING) or (task_status == JobStatus.QUEUED) or (task_status == JobStatus.VALIDATING) or (task_status == JobStatus.RUNNING) or (task_status==''): time.sleep(1) try: task_status=task.status() except: print("Error querying status. Trying again.") pass #print('Task status is', task_status) # get result counts = task.result().get_counts() return counts #Run an iteration of the circuit and calculate its cost def run_circuit_and_calc_cost(params, *args): n, conn, layers, ansatz_type, target_states, shots = args circ=circuit_ansatz(n, params, conn, layers,ansatz_type) counts=run_iteration(circ, n, shots=shots) iter_cost=cost(counts, shots, target_states) cost_history.append(iter_cost) print("Current cost:", iter_cost) return iter_cost backend = provider.get_backend("ionq_simulator") #Set problem parameters r=2 #Number of rows — make sure r*c is less than qubit count c=2 #Number of columns — make sure r*c is less than qubit count n=r*c #Qubits needed conn=2 #Connectivity of the entangler. #Check on qubit count if n>backend.configuration().n_qubits: raise Exception("Too many qubits") #Check on conn if conn>(n-1): raise Exception("Connectivity is too large") target_states=generate_target_distribution(r,c) # Check expected output print('Bitstrings that should be generated by trained circuit are', target_states, 'corresponding to the following BAS patterns:\n') for state in target_states: for i in range(r): print(state[c*i:][:c].replace('0','□ ').replace('1','■ ')) print('') # Choose entangler and driver type layers=1 # Number of layers in each circuit shots=100 # Number of shots per iteration ansatz_type=[1,1] random_init=False # Set to true for random initialization; will be slower to converge # Set up args beta=generate_beta(ansatz_type, random_init) gamma=generate_gamma(ansatz_type, random_init, n, conn) params=beta+gamma base_bounds=(0,2.*math.pi) bnds=((base_bounds , ) * len(params)) #Set up list to track cost history cost_history=[] max_iter=100 # max number of optimizer iterations args=(n, conn, layers, ansatz_type, target_states, shots) opts = {'disp': True, 'maxiter': max_iter, 'maxfev': max_iter, 'return_all': True} #Visualize the circuit circ=circuit_ansatz(n, params, conn,layers,ansatz_type) circ.draw() from qiskit.visualization import plot_histogram #Train Circuit result=noisyopt.minimizeSPSA(run_circuit_and_calc_cost, params, args=args, bounds=bnds, niter=max_iter, disp=False, paired=False) print("Success: ", result.success) print(result.message) print("Final cost function is ", result.fun) print("Min possible cost function is ", np.log2(len(target_states))) print("Number of iterations is ", result.nit) print("Number of function evaluations is ", result.nfev) print("Number of parameters was ", len(params)) print("Approximate cost on hardware: $", 0.01*len(cost_history)*shots) #Plot the evolution of the cost function plt.figure() plt.plot(cost_history) plt.ylabel('Cost') plt.xlabel('Iteration') #Visualize the result result_final=run_iteration(circuit_ansatz(n, result.x, conn,layers,ansatz_type), shots) plot_histogram(result_final) #Train Circuit backend = provider.get_backend("ionq_qpu") result=noisyopt.minimizeSPSA(run_circuit_and_calc_cost, params, args=args, bounds=bnds, niter=max_iter, disp=False, paired=False) print("Success: ", result.success) print(result.message) print("Final cost function is ", result.fun) print("Min possible cost function is ", np.log2(len(target_states))) print("Number of iterations is ", result.nit) print("Number of function evaluations is ", result.nfev) print("Number of parameters was ", len(params)) print("Approximate cost on hardware: $", 0.01*len(cost_history)*shots) #Plot the evolution of the cost function plt.figure() plt.plot(cost_history) plt.ylabel('Cost') plt.xlabel('Iteration') #Visualize the result result_final=run_iteration(circuit_ansatz(n, result.x, conn,layers,ansatz_type), shots) plot_histogram(result_final)
https://github.com/ionq-samples/qiskit-getting-started
ionq-samples
# initialization import numpy as np # importing Qiskit from qiskit import IBMQ, Aer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, transpile # import basic plot tools from qiskit.visualization import plot_histogram # set the length of the n-bit input string. n = 3 # set the length of the n-bit input string. n = 3 const_oracle = QuantumCircuit(n+1) output = np.random.randint(2) if output == 1: const_oracle.x(n) const_oracle.draw() balanced_oracle = QuantumCircuit(n+1) b_str = "101" balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) balanced_oracle.draw() balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Use barrier as divider balanced_oracle.barrier() # Controlled-NOT gates for qubit in range(n): balanced_oracle.cx(qubit, n) balanced_oracle.barrier() balanced_oracle.draw() balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Use barrier as divider balanced_oracle.barrier() # Controlled-NOT gates for qubit in range(n): balanced_oracle.cx(qubit, n) balanced_oracle.barrier() # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Show oracle balanced_oracle.draw() dj_circuit = QuantumCircuit(n+1, n) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) dj_circuit.draw() dj_circuit = QuantumCircuit(n+1, n) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) # Add oracle dj_circuit = dj_circuit.compose(balanced_oracle) dj_circuit.draw() dj_circuit = QuantumCircuit(n+1, n) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) # Add oracle dj_circuit = dj_circuit.compose(balanced_oracle) # Repeat H-gates for qubit in range(n): dj_circuit.h(qubit) dj_circuit.barrier() # Measure for i in range(n): dj_circuit.measure(i, i) # Display circuit dj_circuit.draw() # use local simulator aer_sim = Aer.get_backend('aer_simulator') results = aer_sim.run(dj_circuit).result() answer = results.get_counts() plot_histogram(answer) # ...we have a 0% chance of measuring 000. assert answer.get('000', 0) == 0 def dj_oracle(case, n): # We need to make a QuantumCircuit object to return # This circuit has n+1 qubits: the size of the input, # plus one output qubit oracle_qc = QuantumCircuit(n+1) # First, let's deal with the case in which oracle is balanced if case == "balanced": # First generate a random number that tells us which CNOTs to # wrap in X-gates: b = np.random.randint(1,2**n) # Next, format 'b' as a binary string of length 'n', padded with zeros: b_str = format(b, '0'+str(n)+'b') # Next, we place the first X-gates. Each digit in our binary string # corresponds to a qubit, if the digit is 0, we do nothing, if it's 1 # we apply an X-gate to that qubit: for qubit in range(len(b_str)): if b_str[qubit] == '1': oracle_qc.x(qubit) # Do the controlled-NOT gates for each qubit, using the output qubit # as the target: for qubit in range(n): oracle_qc.cx(qubit, n) # Next, place the final X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': oracle_qc.x(qubit) # Case in which oracle is constant if case == "constant": # First decide what the fixed output of the oracle will be # (either always 0 or always 1) output = np.random.randint(2) if output == 1: oracle_qc.x(n) oracle_gate = oracle_qc.to_gate() oracle_gate.name = "Oracle" # To show when we display the circuit return oracle_gate def dj_algorithm(oracle, n): dj_circuit = QuantumCircuit(n+1, n) # Set up the output qubit: dj_circuit.x(n) dj_circuit.h(n) # And set up the input register: for qubit in range(n): dj_circuit.h(qubit) # Let's append the oracle gate to our circuit: dj_circuit.append(oracle, range(n+1)) # Finally, perform the H-gates again and measure: for qubit in range(n): dj_circuit.h(qubit) for i in range(n): dj_circuit.measure(i, i) return dj_circuit n = 4 oracle_gate = dj_oracle('balanced', n) dj_circuit = dj_algorithm(oracle_gate, n) dj_circuit.draw() transpiled_dj_circuit = transpile(dj_circuit, aer_sim) results = aer_sim.run(transpiled_dj_circuit).result() answer = results.get_counts() plot_histogram(answer) # Load our saved IBMQ accounts and get the least busy backend device with greater than or equal to (n+1) qubits IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (n+1) and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) # Run our circuit on the least busy backend. Monitor the execution of the job in the queue from qiskit.tools.monitor import job_monitor transpiled_dj_circuit = transpile(dj_circuit, backend, optimization_level=3) job = backend.run(transpiled_dj_circuit) job_monitor(job, interval=2) # Get the results of the computation results = job.result() answer = results.get_counts() plot_histogram(answer) # ...the most likely result is 1111. assert max(answer, key=answer.get) == '1111' from qiskit_textbook.problems import dj_problem_oracle oracle = dj_problem_oracle(1) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/ionq-samples/qiskit-getting-started
ionq-samples
#import Aer here, before calling qiskit_ionq_provider from qiskit import Aer from qiskit_ionq import IonQProvider #Call provider and set token value provider = IonQProvider(token='my token') provider.backends() from qiskit import QuantumCircuit, QuantumRegister from math import pi qr = QuantumRegister(6,'q') qc_par = QuantumCircuit(qr) for i in range(3): qc_par.rxx(pi/2,i,i+3) qc_par.draw() qr = QuantumRegister(6,'q') qc_star = QuantumCircuit(qr) for i in range(1,6): qc_star.rxx(pi/2,0,i) qc_star.draw() from qiskit import ClassicalRegister # Add the measurement register circs = [qc_par,qc_star] cr = ClassicalRegister(6,'c') for qc in circs: qc.add_register(cr) qc.measure(range(6),range(6)) from qiskit.providers.jobstatus import JobStatus from qiskit import Aer, execute # Choose the simulator backend backend = provider.get_backend("ionq_simulator") #backend = Aer.get_backend("qasm_simulator") # Run the circuit: def run_jobs(backend,circs,nshots): jobs = [] job_ids = [] qcs = [] for qc in circs: qcs.append(qc) job = backend.run(qc, shots=nshots) #job = execute(qc, backend, shots=nshots, memory=True) jobs.append(job) #job_ids.append(job.job_id()) return jobs jobs = run_jobs(backend,circs,1000) # Calculate output state populations def get_pops(res,nn,n): #print(res) pops = [0 for i in range(2**nn)] for key in res.keys(): pops[int(key,16)] = res[key]/n #pops[int(key,2)] = res[key]/n return pops # Fetch the result def get_jobs(jobs,nshots): results = [] for i in range(len(jobs)): result = jobs[i].result() print(result.data()['counts']) print(get_pops(result.data()['counts'],6,nshots)) results.append(get_pops(result.data()['counts'],6,nshots)) return results results = get_jobs(jobs,1000) def get_ion(res,ion): p1 = 0 for x in range(2**6): if (x&(2**ion)): p1 += res[x] return p1 def get_pair(res,pair): p00 = 0 p01 = 0 p10 = 0 p11 = 0 for x in range(2**6): if (x&(2**pair[0])>0) and (x&(2**pair[1])>0): p11 += res[x] elif (x&(2**pair[0])>0) and (x&(2**pair[1])==0): p01 += res[x] elif (x&(2**pair[1])>0) and (x&(2**pair[0])==0): p10 += res[x] elif (x&(2**pair[0])==0) and (x&(2**pair[1])==0): p00 += res[x] return [p00,p01,p10,p11] prsq = [get_pair(results[0],[i,i+3]) for i in range(3)] prbi = [get_ion(results[1],i) for i in range(6)] print(prbi) print(prsq) import matplotlib.pyplot as plt for i in range(3): plt.bar([x-0.3+0.3*i for x in range(4)],prsq[i],width=0.3,label="Pair "+str(i)+"-"+str(i+3)) plt.ylim([0,1]) plt.xticks(range(4), [bin(x)[2:].zfill(2) for x in range(4)],rotation=30) plt.ylabel("Output probability") plt.xlabel("Output state") plt.legend() plt.bar(range(6),prbi) plt.ylim([0,1]) plt.ylabel("State |1> probability") plt.xlabel("Qubit") # Switch the backend to run circuits on a quantum computer qpu_backend = provider.get_backend("ionq_qpu") jobs = run_jobs(qpu_backend,circs,1000) #Check if jobs are done for i in range(len(jobs)): print(jobs[i].status()) # Fetch the result results = get_jobs(jobs,1000) prsq_m = [get_pair(results[0],[i,i+3]) for i in range(3)] prbi_m = [get_ion(results[1],i) for i in range(6)] for i in range(3): plt.bar([x-0.3+0.3*i for x in range(4)],prsq_m[i],width=0.3,label="Pair "+str(i)+"-"+str(i+3)) plt.ylim([0,1]) plt.xticks(range(4), [bin(x)[2:].zfill(2) for x in range(4)],rotation=30) plt.ylabel("Output probability") plt.xlabel("Output state") plt.legend() plt.bar(range(6),prbi_m) plt.ylim([0,1]) plt.ylabel("State |1> probability") plt.xlabel("Qubit")
https://github.com/ionq-samples/qiskit-getting-started
ionq-samples
# import qiskit from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import Aer, execute from qiskit.circuit.library import QFT from qiskit_ionq import IonQProvider #Call provider and set token value provider = IonQProvider(token='my token') # numpy import numpy as np # plotting from matplotlib import pyplot as plt %matplotlib inline provider.backends() # Quantum Fourier transform of |q>, of length n. def qft(circ, q, n): # Loop through the target qubits. for i in range(n,0,-1): # Apply the H gate to the target. circ.h(q[i-1]) # Loop through the control qubits. for j in range(i-1,0,-1): circ.cp(2*np.pi/2**(i-j+1), q[j-1], q[i-1]) # Inverse Fourier transform of |q>, of length n. def iqft(circ, q, n): # Loop through the target qubits. for i in range(1,n+1): # Loop through the control qubits. for j in range(1,i): # The inverse Fourier transform just uses a negative phase. circ.cp(-2*np.pi/2**(i-j+1), q[j-1], q[i-1]) # Apply the H gate to the target. circ.h(q[i-1]) # define the Add function def Add(circ, a, b, n): # add 1 to n to account for overflow n += 1 # take the QFT qft(circ, b, n) circ.barrier() # Compute the controlled phases # Iterate over targets for i in range(n, 0, -1): # Iterate over controls for j in range(i, 0, -1): # If the qubit a[j-1] exists run cp, if not assume the qubit is 0 and never existed if len(a) - 1 >= j - 1: circ.cp(2*np.pi/2**(i-j+1), a[j-1], b[i-1]) circ.barrier() # take the inverse QFT iqft(circ, b, n) # Registers and circuit. a = QuantumRegister(2) b = QuantumRegister(3) ca = ClassicalRegister(2) cb = ClassicalRegister(3) qc = QuantumCircuit(a, b, ca, cb) # Numbers to add. qc.x(a[1]) # a = 01110 / a = 10 #qc.x(a[2]) #qc.x(a[3]) qc.x(b[0]) # b = 01011 / b = 001 #qc.x(b[1]) #qc.x(b[3]) qc.barrier() # Add the numbers, so |a>|b> to |a>|a+b>. Add(qc, a, b, 2) qc.barrier() # Measure the results. qc.measure(a, ca) qc.measure(b, cb) qc.draw(output="mpl") # simulate the circuit simulator = Aer.get_backend('qasm_simulator') job_sim = execute(qc, simulator) result_sim = job_sim.result() print(result_sim.get_counts(qc)) # run the circuit on a real-device qpu = provider.get_backend("ionq_qpu") qpu_job = qpu.run(qc) from qiskit.providers.jobstatus import JobStatus import time # Check if job is done while qpu_job.status() is not JobStatus.DONE: print("Job status is", qpu_job.status() ) time.sleep(60) # grab a coffee! This can take up to a few minutes. # once we break out of that while loop, we know our job is finished print("Job status is", qpu_job.status() ) print(qpu_job.get_counts()) # these counts are the “true” counts from the actual QPU Run result_exp = qpu_job.result() from qiskit.visualization import plot_histogram plot_histogram(qpu_job.get_counts())
https://github.com/ionq-samples/qiskit-getting-started
ionq-samples
#import Aer here, before calling qiskit_ionq_provider from qiskit import Aer from qiskit_ionq import IonQProvider #Call provider and set token value provider = IonQProvider(token='my token') provider.backends() from qiskit import QuantumCircuit, QuantumRegister from math import pi def get_qc(p): qr = QuantumRegister(11,'q') qc = QuantumCircuit(qr) for i in range(1,12): qc.rx(i*p,i-1) return qc qci = get_qc(pi/3) qci.draw() qca = get_qc(pi/3+pi/18) qcr = get_qc(pi/3-pi/18) from qiskit import ClassicalRegister # Add the measurement register circs = [qci,qca,qcr] cr = ClassicalRegister(11,'c') for qc in circs: qc.add_register(cr) qc.measure(range(11),range(11)) from qiskit.providers.jobstatus import JobStatus from qiskit import Aer, execute # Choose the simulator backend backend = provider.get_backend("ionq_simulator") #backend = Aer.get_backend("qasm_simulator") # Run the circuit: def run_jobs(backend,circs,nshots): jobs = [] job_ids = [] qcs = [] for qc in circs: qcs.append(qc) job = backend.run(qc, shots=nshots) #job = execute(qc, backend, shots=nshots, memory=True) jobs.append(job) #job_ids.append(job.job_id()) return jobs jobs = run_jobs(backend,circs,1000) # Calculate output state populations def get_pops(res,nn,n): #print(res) pops = [0 for i in range(2**nn)] for key in res.keys(): pops[int(key,16)] = res[key]/n #pops[int(key,2)] = res[key]/n return pops # Fetch the result def get_jobs(jobs,nshots): results = [] for i in range(len(jobs)): result = jobs[i].result() #print(result.data()['counts']) #print(get_pops(result.data()['counts'],11,nshots)) results.append(get_pops(result.data()['counts'],11,nshots)) return results results = get_jobs(jobs,1000) def get_ion(res,ion): p1 = 0 for x in range(2**11): if (x&(2**ion)): p1 += res[x] return p1 prbi = [get_ion(results[0],i) for i in range(11)] prba = [get_ion(results[1],i) for i in range(11)] prbr = [get_ion(results[2],i) for i in range(11)] avres = [sum([results[i][j] for i in range(3)])/3 for j in range(2**11)] prbs = [get_ion(avres,i) for i in range(11)] import matplotlib.pyplot as plt plt.plot(range(12),[0]+prbi,label="Ideal") plt.plot(range(12),[0]+prba,label="Over-rotation") plt.plot(range(12),[0]+prbr,label="Under-rotation") plt.plot(range(12),[0]+prbs,label="Average",linewidth=3) plt.ylim([0,1]) plt.ylabel("State |1> probability") plt.xlabel("Qubit (*time*)") plt.legend() # Switch the backend to run circuits on a quantum computer qpu_backend = provider.get_backend("ionq_qpu") jobs = run_jobs(qpu_backend,circs,1000) #Check if jobs are done for i in range(len(jobs)): print(jobs[i].status()) # Fetch the result results = get_jobs(jobs,1000) prbi_m = [get_ion(results[0],i) for i in range(11)] prba_m = [get_ion(results[1],i) for i in range(11)] prbr_m = [get_ion(results[2],i) for i in range(11)] avres = [sum([results[i][j] for i in range(3)])/3 for j in range(2**11)] prbs_m = [get_ion(avres,i) for i in range(11)] plt.plot(range(12),[0]+prbi_m,label="Ideal") plt.plot(range(12),[0]+prba_m,label="Over-rotation") plt.plot(range(12),[0]+prbr_m,label="Under-rotation") plt.plot(range(12),[0]+prbs_m,label="Average",linewidth=3) plt.ylim([0,1]) plt.ylabel("State |1> probability") plt.legend()
https://github.com/ionq-samples/qiskit-getting-started
ionq-samples
#imports from qiskit_ionq import IonQProvider ionq_provider = IonQProvider(token='API-Key-goes-here') import numpy as np from qiskit import QuantumCircuit, execute, Aer from qiskit.tools.visualization import plot_histogram, array_to_latex from qiskit.extensions import UnitaryGate BV=QuantumCircuit(4,3) BV.h(0) BV.h(1) BV.h(2) BV.h(3) BV.z(3) BV.barrier() BV.draw() BV.cx(0,3) BV.barrier() BV.draw() BV.h(0) BV.h(1) BV.h(2) BV.measure(0,0) BV.measure(1,1) BV.measure(2,2) BV.draw() backend = ionq_provider.get_backend("ionq_simulator")#choose your backend job = execute(BV, backend,shot=50000) #get the job object result = job.result() # get result object counts = result.get_counts() #get the counts dictionary fig=plot_histogram(counts) #plot the histogram of the counts ax = fig.axes[0] fig
https://github.com/ionq-samples/qiskit-getting-started
ionq-samples
#imports from qiskit_ionq import IonQProvider ionq_provider = IonQProvider(token='API-key-goes-here') import numpy as np from qiskit import QuantumCircuit, execute, Aer from qiskit.tools.visualization import plot_histogram, array_to_latex from qiskit.extensions import UnitaryGate swap_gate=QuantumCircuit(2) swap_gate.cx(0,1) swap_gate.cx(1,0) swap_gate.cx(0,1) swap_gate.draw() ata = QuantumCircuit(4) ata.h(0) ata.cx(0,3) ata.measure_all() ata.draw() backend = ionq_provider.get_backend("ionq_simulator")#choose your backend job = execute(ata, backend,shots=5000) #get the job object result = job.result() # get result object counts = result.get_counts() #get the counts dictionary fig=plot_histogram(counts) #plot the histogram of the counts ax = fig.axes[0] fig lmt = QuantumCircuit(4) lmt.h(0) lmt.cx(1,3) lmt.cx(3,1) lmt.cx(1,3) lmt.cx(0,1) lmt.cx(1,3) lmt.cx(3,1) lmt.cx(1,3) lmt.measure_all() lmt.draw() backend = ionq_provider.get_backend("ionq_simulator")#choose your backend job = execute(lmt, backend,shots=5000) #get the job object result = job.result() # get result object counts = result.get_counts() #get the counts dictionary fig=plot_histogram(counts) #plot the histogram of the counts ax = fig.axes[0] fig
https://github.com/ionq-samples/qiskit-getting-started
ionq-samples
#import Aer here, before calling qiskit_ionq_provider from qiskit import Aer from qiskit_ionq import IonQProvider #Call provider and set token value provider = IonQProvider(token='my token') provider.backends() from qiskit import * #import qiskit.aqua as aqua #from qiskit.quantum_info import Pauli #from qiskit.aqua.operators.primitive_ops import PauliOp from qiskit.circuit.library import PhaseEstimation from qiskit import QuantumCircuit from qiskit.visualization import plot_histogram %matplotlib inline import pyscf from pyscf import gto, scf, cc from matplotlib import pyplot as plt import numpy as np from qiskit_ionq import IonQProvider provider = IonQProvider("sUkOPlNLf6vamkFMB3SuHR2qYR5cLaMn") from qiskit.providers.jobstatus import JobStatus import time as timer g = {"I": -0.4804, "Z0": 0.3435, "Z1": -0.4347, "Z0Z1": 0.5716, "X0X1": 0.0910, "Y0Y1": 0.0910} """ This function implements the controlled exp(-iHt) Inputs: phase: phase to correct weights: Pauli weights time: Time order_index: Pauli operator index iter_num: iteration trotter_step: trotter steps Output: qc: Quantum circuit """ def buildControlledHam(phase, time, iter_num): # initialize the circuit qc = QuantumCircuit(3, 3) # Hardmard on ancilla qc.h(0) # initialize to |01> qc.x(2) # Z0 qc.crz(g["Z0"] * time * 2 * 2**iter_num, 0, 2) # Y0Y1 qc.rz(np.pi/2, 1) qc.rz(np.pi/2, 2) qc.h(1) qc.h(2) qc.cx(1, 2) qc.crz(g["Y0Y1"] * time * 2 * 2**iter_num, 0, 2) qc.cx(1, 2) qc.h(1) qc.h(2) qc.rz(-np.pi/2, 1) qc.rz(-np.pi/2, 2) # Z1 qc.crz(g["Z1"] * time * 2 * 2**iter_num, 0, 1) # X0X1 qc.h(1) qc.h(2) qc.cx(1, 2) qc.crz(g["X0X1"] * time * 2 * 2**iter_num, 0, 2) qc.cx(1, 2) qc.h(1) qc.h(2) # phase correction qc.rz(phase, 0) # inverse QFT qc.h(0) qc.measure([0, 1, 2],[0, 1, 2]) return qc """ This function implements the controlled exp(-iHt) Inputs: weights: Pauli weights time: Time order_index: Pauli operator index tot_num_iter: number of iterations trotter_step: trotter steps Output: bits: list of measured bits """ def IPEA(time, tot_num_iter, backend_id): # get backend if (backend_id == "qasm_simulator"): backend = Aer.get_backend(backend_id) else: backend = provider.get_backend("ionq_qpu") # bits bits = [] # phase correction phase = 0.0 # loop over iterations for i in range(tot_num_iter-1, -1, -1): # construct the circuit qc = buildControlledHam(phase, time, i) # run the circuit job = execute(qc, backend) if (backend_id == "ionq_qpu"): # Check if job is done while job.status() is not JobStatus.DONE: print("Job status is", job.status() ) timer.sleep(60) # once we break out of that while loop, we know our job is finished print("Job status is", job.status() ) # get result result = job.result() # get current bit this_bit = int(max(result.get_counts(), key=result.get_counts().get)[-1]) bits.append(this_bit) # update phase correction phase /= 2 phase -= (2 * np.pi * this_bit / 4.0) return bits """ This function that computes eigenvalues from bit list Inputs: bits: list of measured bits time: Time Output: eig: eigenvalue """ def eig_from_bits(bits, time): eig = 0. m = len(bits) # loop over all bits for k in range(len(bits)): eig += bits[k] / (2**(m-k)) eig *= -2*np.pi eig /= time return eig """ This function that performs classical post-processing Inputs: eig: eigenvalue weights: Pauli operator weights R: Bond distance Output: energy: total energy """ def post_process(eig, weights, R): # initialize energy energy = eig # Z0Z1 contribution energy -= weights["Z0Z1"] # I contribution energy += weights["I"] # Nuclear Repulsion ( assume R is in Angstrom ) energy += 1.0/ (R * 1.88973) # return energy return energy # backend backend_id = "qasm_simulator" # Bond Length R = 0.75 # time t = 0.74 # number of iteration max_num_iter = 8 # get exact energy # This function initialises a molecule mol = pyscf.M( atom = 'H 0 0 0; H 0 0 0.75', # in Angstrom basis = 'sto-6g', symmetry = False, ) myhf = mol.RHF().run() # create an FCI solver based on the SCF object # cisolver = pyscf.fci.FCI(myhf) print('E(FCI) = %.12f' % cisolver.kernel()[0]) error_list = [] # perform IPEA for i in range(1, max_num_iter + 1): bits = IPEA(t, i, backend_id) # re-construct phase eig = eig_from_bits(bits, t) print(eig, 'eig') # re-construct energy eng = post_process(eig, g, R) print("Total Energy is %.7f for R = %.2f, t = %.3f with %d iterations" % (eng, R, t, i) ) backend_id = "qpu" error_list = [] # perform IPEA for i in range(1, max_num_iter + 1): bits = IPEA(t, i, backend_id) # re-construct phase eig = eig_from_bits(bits, t) # re-construct energy eng = post_process(eig, g, R) print("Total Energy is %.7f for R = %.2f, t = %.3f with %d iterations" % (eng, R, t, i) )
https://github.com/ionq-samples/qiskit-getting-started
ionq-samples
#import Aer here, before calling qiskit_ionq_provider from qiskit import Aer from qiskit_ionq import IonQProvider #Call provider and set token value provider = IonQProvider(token='my token') provider.backends() from qiskit import * #import qiskit.aqua as aqua #from qiskit.quantum_info import Pauli #from qiskit.aqua.operators.primitive_ops import PauliOp from qiskit.circuit.library import PhaseEstimation from qiskit import QuantumCircuit from matplotlib import pyplot as plt import numpy as np from qiskit.chemistry.drivers import PySCFDriver, UnitsType from qiskit.chemistry.drivers import Molecule def buildControlledT(p, m): # initialize the circuit qc = QuantumCircuit(2, 1) # Hardmard on ancilla, now in |+> qc.h(0) # initialize to |1> qc.x(1) # applying T gate to qubit 1 for i in range(2**m): qc.cp(np.pi/4, 0, 1) # phase correction qc.rz(p, 0) # inverse QFT (in other words, just measuring in the x-basis) qc.h(0) qc.measure([0],[0]) return qc def IPEA(k, backend_string): # get backend if backend_string == 'qpu': backend = provider.get_backend('ionq_qpu') elif backend_string == 'qasm': backend = Aer.get_backend('qasm_simulator') # bits bits = [] # phase correction phase = 0.0 # loop over iterations for i in range(k-1, -1, -1): # construct the circuit qc = buildControlledT(phase, i) # run the circuit job = execute(qc, backend) if backend_string == 'qpu': from qiskit.providers.jobstatus import JobStatus import time # Check if job is done while job.status() is not JobStatus.DONE: print("Job status is", job.status() ) time.sleep(60) # grab a coffee! This can take up to a few minutes. # once we break out of that while loop, we know our job is finished print("Job status is", job.status() ) print(job.get_counts()) # these counts are the “true” counts from the actual QPU Run # get result result = job.result() # get current bit this_bit = int(max(result.get_counts(), key=result.get_counts().get)) print(result.get_counts()) bits.append(this_bit) # update phase correction phase /= 2 phase -= (2 * np.pi * this_bit / 4.0) return bits def eig_from_bits(bits): eig = 0. m = len(bits) # loop over all bits for k in range(len(bits)): eig += bits[k] / (2**(m-k)) #eig *= 2*np.pi return eig # perform IPEA backend = 'qasm' bits = IPEA(5, backend) print(bits) # re-construct energy eig = eig_from_bits(bits) print(eig) #perform IPEA with different values of n n_values = [] eig_values = [] for i in range(1, 8): n_values.append(i) # perform IPEA backend = 'qasm' bits = IPEA(i, backend) # re-construct energy eig = eig_from_bits(bits) eig_values.append(eig) n_values, eig_values = np.array(n_values), np.array(eig_values) plt.plot(n_values, eig_values) plt.xlabel('n (bits)', fontsize=15) plt.ylabel(r'$\phi$', fontsize=15) plt.title(r'$\phi$ vs. n', fontsize=15) # perform IPEA backend = 'qpu' bits = IPEA(5, backend) print(bits) # re-construct energy eig = eig_from_bits(bits) print(eig) #perform IPEA with different values of n n_values = [] eig_values = [] for i in range(1, 8): n_values.append(i) # perform IPEA backend = 'qpu' bits = IPEA(i, backend) # re-construct energy eig = eig_from_bits(bits) eig_values.append(eig) n_values, eig_values = np.array(n_values), np.array(eig_values) plt.plot(n_values, eig_values) plt.xlabel('n (bits)', fontsize=15) plt.ylabel(r'$\phi$', fontsize=15) plt.title(r'$\phi$ vs. n', fontsize=15)
https://github.com/ionq-samples/qiskit-getting-started
ionq-samples
#import Aer here, before calling qiskit_ionq_provider from qiskit import Aer from qiskit_ionq import IonQProvider #Call provider and set token value ionq_provider = IonQProvider(token='your token') ionq_provider.backends() import numpy as np from qiskit import execute from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.utils import QuantumInstance from qiskit.algorithms import VQE from qiskit.algorithms.optimizers import COBYLA, ADAM, L_BFGS_B, SLSQP, SPSA from qiskit import Aer from qiskit.circuit import Parameter from qiskit.circuit.parametervector import ParameterVectorElement from qiskit_nature.drivers import PySCFDriver, UnitsType, Molecule from qiskit_nature.circuit.library import HartreeFock from qiskit_nature.problems.second_quantization.electronic import ElectronicStructureProblem from qiskit_nature.mappers.second_quantization import JordanWignerMapper from qiskit_nature.converters.second_quantization import QubitConverter from qiskit.algorithms import NumPyMinimumEigensolver from qiskit_nature.algorithms.ground_state_solvers import GroundStateEigensolver from qiskit_nature.runtime import VQEProgram from matplotlib import pyplot as plt %matplotlib inline class UCCAnsatz(): def __init__(self, params, num_particles, num_spin_orbitals): # number of qubits self.num_of_qubits = num_spin_orbitals # number of parameters self.num_params = len(params) # parameters self.params = [] for index in range(self.num_params): p = Parameter("t"+str(index)) self.params.append(ParameterVectorElement(p, index)) def UCC1(self): qc = QuantumCircuit(4) # basis rotation qc.rx(np.pi / 2, 0) qc.h(1) qc.h(2) qc.h(3) # parameter theta_0 qc.cx(0, 1) qc.cx(1, 2) qc.cx(2, 3) qc.rz(self.params[0], 3) qc.cx(2, 3) qc.cx(1, 2) qc.cx(0, 1) # basis rotation qc.rx(-np.pi / 2, 0) qc.h(1) qc.h(2) qc.h(3) return qc ################## Hamiltonian Definition ####################################### def GetHamiltonians(mol): # construct the driver driver = PySCFDriver(molecule=mol, unit=UnitsType.ANGSTROM, basis='sto6g') # the electronic structure problem problem = ElectronicStructureProblem(driver) # get quantum molecule q_molecule = driver.run() # classical eigenstate np_solver = NumPyMinimumEigensolver() np_groundstate_solver = GroundStateEigensolver(QubitConverter(JordanWignerMapper()), np_solver) np_result = np_groundstate_solver.solve(problem) print(f"Classical results is {np_result.eigenenergies}") # generate the second-quantized operators second_q_ops = problem.second_q_ops() # construct a qubit converter qubit_converter = QubitConverter(JordanWignerMapper()) # qubit Operations qubit_op = qubit_converter.convert(second_q_ops[0]) # return the qubit operations return qubit_op def constructAnsatz(params): # initialize the HF state hf_state = HartreeFock(4, [1, 1], QubitConverter(JordanWignerMapper())) # VQE circuit ansatz = UCCAnsatz(params, 2, 4).UCC1() # add initial state ansatz.compose(hf_state, front=True, inplace=True) # return the circuit return ansatz def constructCircuit(params, mol, backend_id): # Hamiltonian qubit_op = GetHamiltonians(mol) # Optimizer optimizer = COBYLA() # ansatz ansatz = constructAnsatz(params) print(ansatz) # initial parameters init_params = {} for index in range(len(params)): p = Parameter("t"+str(index)) init_params[ParameterVectorElement(p, index)] = 0.0 # backend if (backend_id == "qasm_simulator"): backend = Aer.get_backend("qasm_simulator") elif (backend_id == "ionq_qpu"): backend = ionq_provider.get_backend("ionq_qpu") def job_callback(job_id, job_status, queue_position, job) -> None: ''' Printing logs for debugging. The function is the parameter job_callback of QuantumInstance :param job_id: :param job_status: :param queue_position: :param job: :return: ''' print(f"[API JOB-CALLBACK] Job Id: {job_id}") print(f"[API JOB-CALLBACK] Job status: {job_status}") print(f"[API JOB-CALLBACK] Queue position: {queue_position}") print(f"[API JOB-CALLBACK] Job: {job}") ionq_quantum_instance = QuantumInstance(backend=backend, job_callback=job_callback) counts = [] values = [] stds = [] def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) stds.append(std) # VQE algorithm algorithm = VQE(ansatz, optimizer=optimizer, initial_point = np.array([0.0]), callback=store_intermediate_result, quantum_instance=ionq_quantum_instance) result = algorithm.compute_minimum_eigenvalue(qubit_op) print(result) print("Optimized VQE Energy ", result.eigenvalue.real) print(values) # Execute program with default parameters def run(backend_id="qasm_simulator"): molecule = Molecule(geometry=[['H', [0., 0., 0.]], ['H', [0., 0., 0.75]]], charge=0, multiplicity=1) opt_values = constructCircuit([0.0], molecule, backend_id) run() opt_process = [-1.8308337397334875, -1.6045286426151377, -1.3176850880519417, -1.642972785671419, -1.853378862063689, -1.806712185391583, -1.8281518913000796, -1.853965175510973, -1.8546227409607912, -1.8512623145326073, -1.8499200431393457, -1.8490846844773303, -1.8508890835046492, -1.8474757232657733, -1.8492536553877457, -1.8544537700503756, -1.8461599187778577, -1.8476358718744068, -1.849466737807071] plt.plot(opt_process, linestyle="", marker="o") plt.show() run("ionq_qpu") opt_process_exp = [-1.8112359199652812, -1.4416498480789817, -1.2335035452225904, -1.4989706208229303, -1.6937521890989031, -1.6557546667316045, -1.6898027909394815, -1.740016937435431, -1.7592133266130963, -1.755505060521276, -1.7199835843097526, -1.7476529655074913, -1.7142357090197362, -1.7366022956905651, -1.7307574124517149, -1.7437590702130892, -1.721561556686939] plt.plot(opt_process, linestyle="", marker="o", color="b", label="simulator") plt.plot(opt_process_exp, linestyle="", marker="o", color="r", label="ionq_qpu") plt.legend() plt.show() opt_process_exp = [-1.8112359199652812, -1.4416498480789817, -1.2335035452225904, -1.4989706208229303, -1.6937521890989031, -1.6557546667316045, -1.6898027909394815, -1.740016937435431, -1.7592133266130963, -1.755505060521276, -1.7199835843097526, -1.7476529655074913, -1.7142357090197362, -1.7366022956905651, -1.7307574124517149, -1.7437590702130892, -1.721561556686939] opt_process = [-1.8308337397334875, -1.6045286426151377, -1.3176850880519417, -1.642972785671419, -1.853378862063689, -1.806712185391583, -1.8281518913000796, -1.853965175510973, -1.8546227409607912, -1.8512623145326073, -1.8499200431393457, -1.8490846844773303, -1.8508890835046492, -1.8474757232657733, -1.8492536553877457, -1.8544537700503756, -1.8461599187778577, -1.8476358718744068, -1.849466737807071] plt.plot(opt_process, linestyle="", marker="o", color="b", label="simulator") plt.plot(opt_process_exp, linestyle="", marker="o", color="r", label="ionq_qpu") plt.xlabel("Number of Iteration") plt.ylabel("Energy (Hartree)") plt.legend() plt.show()
https://github.com/ionq-samples/qiskit-getting-started
ionq-samples
#import Aer here, before calling qiskit_ionq_provider from qiskit import Aer from qiskit_ionq import IonQProvider #Call provider and set token value ionq_provider = IonQProvider(token='my token') ionq_provider.backends() import numpy as np from qiskit import execute from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.utils import QuantumInstance from qiskit.algorithms import VQE from qiskit.algorithms.optimizers import COBYLA, ADAM, L_BFGS_B, SLSQP, SPSA from qiskit import Aer from qiskit.circuit import Parameter from qiskit.circuit.parametervector import ParameterVectorElement from qiskit_nature.drivers import PySCFDriver, UnitsType, Molecule from qiskit_nature.circuit.library import HartreeFock from qiskit_nature.problems.second_quantization.electronic import ElectronicStructureProblem from qiskit_nature.mappers.second_quantization import JordanWignerMapper from qiskit_nature.converters.second_quantization import QubitConverter from qiskit.algorithms import NumPyMinimumEigensolver from qiskit_nature.algorithms.ground_state_solvers import GroundStateEigensolver from qiskit_nature.runtime import VQEProgram from matplotlib import pyplot as plt %matplotlib inline class UCCAnsatz(): def __init__(self, params, num_particles, num_spin_orbitals): # number of qubits self.num_of_qubits = num_spin_orbitals # number of parameters self.num_params = len(params) # parameters self.params = [] for index in range(self.num_params): p = Parameter("t"+str(index)) self.params.append(ParameterVectorElement(p, index)) def UCC1(self): qc = QuantumCircuit(4) # basis rotation qc.rx(np.pi / 2, 0) qc.h(1) qc.h(2) qc.h(3) # parameter theta_0 qc.cx(0, 1) qc.cx(1, 2) qc.cx(2, 3) qc.rz(self.params[0], 3) qc.cx(2, 3) qc.cx(1, 2) qc.cx(0, 1) # basis rotation qc.rx(-np.pi / 2, 0) qc.h(1) qc.h(2) qc.h(3) return qc ################## Hamiltonian Definition ####################################### def GetHamiltonians(mol): # construct the driver driver = PySCFDriver(molecule=mol, unit=UnitsType.ANGSTROM, basis='sto6g') # the electronic structure problem problem = ElectronicStructureProblem(driver) # get quantum molecule q_molecule = driver.run() # classical eigenstate np_solver = NumPyMinimumEigensolver() np_groundstate_solver = GroundStateEigensolver(QubitConverter(JordanWignerMapper()), np_solver) np_result = np_groundstate_solver.solve(problem) print(f"Classical results is {np_result.eigenenergies}") # generate the second-quantized operators second_q_ops = problem.second_q_ops() # construct a qubit converter qubit_converter = QubitConverter(JordanWignerMapper()) # qubit Operations qubit_op = qubit_converter.convert(second_q_ops[0]) # return the qubit operations return qubit_op def constructAnsatz(params): # initialize the HF state hf_state = HartreeFock(4, [1, 1], QubitConverter(JordanWignerMapper())) # VQE circuit ansatz = UCCAnsatz(params, 2, 4).UCC1() # add initial state ansatz.compose(hf_state, front=True, inplace=True) # return the circuit return ansatz def runVQE(params, backend_id="qasm_simulator", optimizer_id="COBYLA", noise=None): molecule = Molecule(geometry=[['H', [0., 0., 0.]], ['H', [0., 0., 0.75]]], charge=0, multiplicity=1) # Get Hamiltonian qubit_op = GetHamiltonians(molecule) # Get classical optimizer if (optimizer_id == "COBYLA"): optimizer = COBYLA() elif (optimizer_id == "SPSA"): optimizer = SPSA() elif (optimizer_id == "ADAM"): optimizer = ADAM() # Construct and display ansatz ansatz = constructAnsatz(params) print('Ansatz :', '\n', ansatz) # initial parameters init_params = {} for index in range(len(params)): p = Parameter("t"+str(index)) init_params[ParameterVectorElement(p, index)] = 0.0 # backend if (backend_id == "qasm_simulator"): backend = Aer.get_backend("qasm_simulator") elif (backend_id == "ionq_qpu"): backend = ionq_provider.get_backend("ionq_qpu") def job_callback(job_id, job_status, queue_position, job) -> None: ''' Printing logs for debugging. The function is the parameter job_callback of QuantumInstance :param job_id: :param job_status: :param queue_position: :param job: :return: ''' print(f"[API JOB-CALLBACK] Job Id: {job_id}") print(f"[API JOB-CALLBACK] Job status: {job_status}") print(f"[API JOB-CALLBACK] Queue position: {queue_position}") print(f"[API JOB-CALLBACK] Job: {job}") ionq_quantum_instance = QuantumInstance(backend=backend, job_callback=job_callback, noise_model=noise) counts = [] values = [] stds = [] def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) stds.append(std) # VQE algorithm algorithm = VQE(ansatz, optimizer=optimizer, initial_point = np.array([0.0]), callback=store_intermediate_result, quantum_instance=ionq_quantum_instance) result = algorithm.compute_minimum_eigenvalue(qubit_op) print("Optimized VQE Energy ", result.eigenvalue.real) return values, stds # Execute program with default parameters eng_hist, error_hist = runVQE([0.0]) plt.plot([*range(len(eng_hist))], eng_hist, linestyle="", marker="o") #plt.plot([*range(len(eng_hist))], eng_hist) plt.show() eng_hist_SPSA, error_hist_SPSA = runVQE([0.0],optimizer_id="SPSA") plt.plot([*range(len(eng_hist))], eng_hist, linestyle="", marker="o", label="COBYLA") plt.plot([*range(len(eng_hist_SPSA))], eng_hist_SPSA, linestyle="", marker="*", label="SPSA") plt.legend() plt.show() eng_hist_ADAM, error_hist_ADAM = runVQE([0.0],optimizer_id="ADAM") plt.plot([*range(len(eng_hist))], eng_hist, linestyle="", marker="o", label="COBYLA") plt.plot([*range(len(eng_hist_SPSA))], eng_hist_SPSA, linestyle="", marker="*", label="SPSA") plt.plot([*range(len(eng_hist_ADAM))], eng_hist_ADAM, linestyle="", marker="x", label="ADAM") plt.legend() plt.show() # Noise from qiskit.providers.aer.noise import NoiseModel from qiskit.providers.aer.noise import depolarizing_error # default noise model, can be overridden using set_noise_model noise = NoiseModel() # Add depolarizing error to all single qubit gates with error rate 0.5% one_qb_error = 0.005 noise.add_all_qubit_quantum_error(depolarizing_error(one_qb_error, 1), ['u1', 'u2', 'u3']) # Add depolarizing error to all two qubit gates with error rate 5.0% two_qb_error = 0.05 noise.add_all_qubit_quantum_error(depolarizing_error(two_qb_error, 2), ['cx']) eng_hist, error_hist = runVQE([0.0],optimizer_id="COBYLA", noise=noise) eng_hist_SPSA, error_hist_SPSA = runVQE([0.0],optimizer_id="SPSA", noise=noise) eng_hist_ADAM, error_hist_ADAM = runVQE([0.0],optimizer_id="ADAM", noise=noise) plt.plot([*range(len(eng_hist))], eng_hist, linestyle="", marker="o", label="COBYLA") plt.plot([*range(len(eng_hist_SPSA))], eng_hist_SPSA, linestyle="", marker="*", label="SPSA") plt.plot([*range(len(eng_hist_ADAM))], eng_hist_ADAM, linestyle="", marker="x", label="ADAM") plt.legend() plt.show() # run("ionq_qpu") # opt_process_exp = [-1.8112359199652812, -1.4416498480789817, -1.2335035452225904, -1.4989706208229303, -1.6937521890989031, -1.6557546667316045, -1.6898027909394815, -1.740016937435431, -1.7592133266130963, -1.755505060521276, -1.7199835843097526, -1.7476529655074913, -1.7142357090197362, -1.7366022956905651, -1.7307574124517149, -1.7437590702130892, -1.721561556686939] # plt.plot(opt_process, linestyle="", marker="o", color="b", label="simulator") # plt.plot(opt_process_exp, linestyle="", marker="o", color="r", label="ionq_qpu") # plt.legend() # plt.show() eng_hist, error_hist = runVQE([0.0],optimizer_id="COBYLA", backend_id = "ionq_qpu") eng_hist_SPSA, error_hist_SPSA = runVQE([0.0],optimizer_id="SPSA", backend_id = "ionq_qpu") eng_hist_ADAM, error_hist_ADAM = runVQE([0.0],optimizer_id="ADAM", backend_id = "ionq_qpu") plt.plot([*range(len(eng_hist))], eng_hist, linestyle="", marker="o", label="COBYLA") plt.plot([*range(len(eng_hist_SPSA))], eng_hist_SPSA, linestyle="", marker="*", label="SPSA") plt.plot([*range(len(eng_hist_ADAM))], eng_hist_ADAM, linestyle="", marker="x", label="ADAM") plt.legend() plt.show()
https://github.com/stefan-woerner/qiskit_tutorial
stefan-woerner
print("Hello! I'm a code cell") print('Set up started...') %matplotlib notebook import sys sys.path.append('game_engines') import hello_quantum print('Set up complete!') initialize = [] success_condition = {} allowed_gates = {'0': {'NOT': 3}, '1': {}, 'both': {}} vi = [[1], False, False] qubit_names = {'0':'the only bit', '1':None} puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names) initialize = [] success_condition = {} allowed_gates = {'0': {}, '1': {'NOT': 0}, 'both': {}} vi = [[], False, False] qubit_names = {'0':'the bit on the left', '1':'the bit on the right'} puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names) initialize = [['x', '0']] success_condition = {'IZ': -1.0} allowed_gates = {'0': {'CNOT': 0}, '1': {'CNOT': 0}, 'both': {}} vi = [[], False, False] qubit_names = {'0':'the bit on the left', '1':'the bit on the right'} puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names) initialize = [['x', '0']] success_condition = {'ZI': 1.0, 'IZ': -1.0} allowed_gates = {'0': {'CNOT': 0}, '1': {'CNOT': 0}, 'both': {}} vi = [[], False, False] qubit_names = {'0':'the bit on the left', '1':'the bit on the right'} puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names) initialize = [['h', '0']] success_condition = {'IZ': 0.0} allowed_gates = {'0': {'CNOT': 0}, '1': {'CNOT': 0}, 'both': {}} vi = [[], False, False] qubit_names = {'0':'the bit on the left', '1':'the bit on the right'} puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names) initialize = [['h', '0']] success_condition = {'ZZ': -1.0} allowed_gates = {'0': {'NOT': 0, 'CNOT': 0}, '1': {'NOT': 0, 'CNOT': 0}, 'both': {}} vi = [[], False, True] qubit_names = {'0':'the bit on the left', '1':'the bit on the right'} puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names) initialize = [['h', '1']] success_condition = {'IZ': -1.0} allowed_gates = {'0': {'NOT': 0, 'CNOT': 0}, '1': {'NOT': 0, 'CNOT': 0}, 'both': {}} vi = [[], False, True] qubit_names = {'0':'the bit on the left', '1':'the bit on the right'} puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names) initialize = [ ["x","0"] ] success_condition = {"ZI":1.0} allowed_gates = { "0":{"x":3}, "1":{}, "both":{} } vi = [[1],True,True] qubit_names = {'0':'the only qubit', '1':None} puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names) initialize = [['x', '0']] success_condition = {'ZI': 1.0} allowed_gates = {'0': {'x': 0}, '1': {}, 'both': {}} vi = [[1], True, True] qubit_names = {'0':'the only qubit', '1':None} puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names) initialize = [['x', '1']] success_condition = {'IZ': 1.0} allowed_gates = {'0': {}, '1': {'x': 0}, 'both': {}} vi = [[0], True, True] qubit_names = {'0':None, '1':'the other qubit'} puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names) initialize = [] success_condition = {'ZI': 0.0} allowed_gates = {'0': {'h': 3}, '1': {}, 'both': {}} vi = [[1], True, True] qubit_names = {'0':'qubit 0', '1':'qubit 1'} puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names) initialize = [['h', '1']] success_condition = {'IZ': 1.0} allowed_gates = {'0': {}, '1': {'x': 3, 'h': 0}, 'both': {}} vi = [[0], True, True] qubit_names = {'0':'qubit 0', '1':'qubit 1'} puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names) initialize = [['h', '0'], ['z', '0']] success_condition = {'XI': 1.0} allowed_gates = {'0': {'z': 0, 'h': 0}, '1': {}, 'both': {}} vi = [[1], True, True] qubit_names = {'0':'qubit 0', '1':'qubit 1'} puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names) initialize = [] success_condition = {'ZI': -1.0} allowed_gates = {'0': {'z': 0, 'h': 0}, '1': {}, 'both': {}} vi = [[1], True, True] qubit_names = {'0':'qubit 0', '1':'qubit 1'} puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names) initialize = [['h', '0']] success_condition = {'IX': 1.0} allowed_gates = {'0': {}, '1': {'z': 0, 'h': 0}, 'both': {}} vi = [[0], True, True] qubit_names = {'0':'qubit 0', '1':'qubit 1'} puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names) initialize = [['ry(pi/4)', '1']] success_condition = {'IZ': -0.7071, 'IX': -0.7071} allowed_gates = {'0': {}, '1': {'z': 0, 'h': 0}, 'both': {}} vi = [[0], True, True] qubit_names = {'0':'qubit 0', '1':'qubit 1'} puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names) initialize = [['x', '1']] success_condition = {'ZI': 0.0, 'IZ': 0.0} allowed_gates = {'0': {'x': 0, 'z': 0, 'h': 0}, '1': {'x': 0, 'z': 0, 'h': 0}, 'both': {}} vi = [[], True, False] qubit_names = {'0':'qubit 0', '1':'qubit 1'} puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names) initialize = [['h','0'],['h','1']] success_condition = {'ZZ': -1.0} allowed_gates = {'0': {'x': 0, 'z': 0, 'h': 0}, '1': {'x': 0, 'z': 0, 'h': 0}, 'both': {}} vi = [[], True, True] qubit_names = {'0':'qubit 0', '1':'qubit 1'} puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names) initialize = [['x','0']] success_condition = {'XX': 1.0} allowed_gates = {'0': {'x': 0, 'z': 0, 'h': 0}, '1': {'x': 0, 'z': 0, 'h': 0}, 'both': {}} vi = [[], True, True] qubit_names = {'0':'qubit 0', '1':'qubit 1'} puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names) initialize = [] success_condition = {'XZ': -1.0} allowed_gates = {'0': {'x': 0, 'z': 0, 'h': 0}, '1': {'x': 0, 'z': 0, 'h': 0}, 'both': {}} vi = [[], True, True] qubit_names = {'0':'qubit 0', '1':'qubit 1'} puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names) initialize = [['ry(-pi/4)', '1'], ['ry(-pi/4)','0']] success_condition = {'ZI': -0.7071, 'IZ': -0.7071} allowed_gates = {'0': {'x': 0}, '1': {'x': 0}, 'both': {}} vi = [[], True, True] qubit_names = {'0':'qubit 0', '1':'qubit 1'} puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names) initialize = [['x', '1'], ['x','0']] success_condition = {'XI':1, 'IX':1} allowed_gates = {'0': {'z': 0, 'h': 0}, '1': {'z': 0, 'h': 0}, 'both': {}} vi = [[], True, True] qubit_names = {'0':'qubit 0', '1':'qubit 1'} puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names) initialize = [['x', '0']] success_condition = {'ZI': 1.0, 'IZ': -1.0} allowed_gates = {'0': {'cx': 0}, '1': {'cx': 0}, 'both': {}} vi = [[], True, True] qubit_names = {'0':'qubit 0', '1':'qubit 1'} puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names) initialize = [['h', '0'],['x', '1']] success_condition = {'XI': -1.0, 'IZ': 1.0} allowed_gates = {'0': {'h': 0, 'cz': 0}, '1': {'cx': 0}, 'both': {}} vi = [[], True, True] qubit_names = {'0':'qubit 0', '1':'qubit 1'} puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names) initialize = [['h', '0'],['x', '1'],['h', '1']] success_condition = { } allowed_gates = {'0':{'cz': 2}, '1':{'cz': 2}, 'both': {}} vi = [[], True, True] qubit_names = {'0':'qubit 0', '1':'qubit 1'} puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names) initialize = [['x', '0']] success_condition = {'IZ': -1.0} allowed_gates = {'0': {'h':0}, '1': {'h':0}, 'both': {'cz': 0}} vi = [[], True, True] qubit_names = {'0':'qubit 0', '1':'qubit 1'} puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names) initialize = [['h', '0'],['h', '1']] success_condition = {'XI': -1.0, 'IX': -1.0} allowed_gates = {'0': {}, '1': {'z':0,'cx': 0}, 'both': {}} vi = [[], True, True] qubit_names = {'0':'qubit 0', '1':'qubit 1'} puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names) initialize = [] success_condition = {'IZ': -1.0} allowed_gates = {'0': {'x':0,'h':0,'cx':0}, '1': {'h':0}, 'both': {}} vi = [[], True, True] qubit_names = {'0':'qubit 0', '1':'qubit 1'} puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names) initialize = [['ry(-pi/4)','0'],['ry(-pi/4)','0'],['ry(-pi/4)','0'],['x','0'],['x','1']] success_condition = {'ZI': -1.0,'XI':0,'IZ':0.7071,'IX':-0.7071} allowed_gates = {'0': {'h':0}, '1': {'h':0}, 'both': {'cz': 0}} vi = [[], True, True] qubit_names = {'0':'qubit 0', '1':'qubit 1'} puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names) initialize = [['x','0'],['h','1']] success_condition = {'IX':1,'ZI':-1} allowed_gates = {'0': {'h':0}, '1': {'h':0}, 'both': {'cz':3}} vi = [[], True, True] qubit_names = {'0':'qubit 0', '1':'qubit 1'} puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names,shots=2000) initialize = [['x','1']] success_condition = {'IZ':1.0,'ZI':-1.0} allowed_gates = {'0': {'h':0}, '1': {'h':0}, 'both': {'cz':0}} vi = [[], True, True] qubit_names = {'0':'qubit 0', '1':'qubit 1'} puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names,shots=2000) initialize = [] success_condition = {} allowed_gates = {'0': {'ry(pi/4)': 4}, '1': {}, 'both': {}} vi = [[], True, True] qubit_names = {'0':'qubit 0', '1':'qubit 1'} puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names) initialize = [['x','0']] success_condition = {'XX': 1.0} allowed_gates = {'0': {'x': 0, 'z': 0, 'h': 0}, '1': {'x': 0, 'z': 0, 'h': 0}, 'both': {}} vi = [[], True, True] qubit_names = {'0':'qubit 0', '1':'qubit 1'} puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names, mode='line') initialize = [] success_condition = {'ZI': -1.0} allowed_gates = {'0': {'bloch':1, 'ry(pi/4)': 0}, '1':{}, 'both': {'unbloch':0}} vi = [[], True, True] qubit_names = {'0':'qubit 0', '1':'qubit 1'} puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names, mode='line') initialize = [['h','0'],['h','1']] success_condition = {'ZI': -1.0,'IZ': -1.0} allowed_gates = {'0': {'bloch':0, 'ry(pi/4)': 0, 'ry(-pi/4)': 0}, '1': {'bloch':0, 'ry(pi/4)': 0, 'ry(-pi/4)': 0}, 'both': {'unbloch':0}} vi = [[], True, True] qubit_names = {'0':'qubit 0', '1':'qubit 1'} puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names, mode='line') initialize = [['h','0']] success_condition = {'ZZ': 1.0} allowed_gates = {'0': {}, '1': {'bloch':0, 'ry(pi/4)': 0, 'ry(-pi/4)': 0}, 'both': {'unbloch':0,'cz':0}} vi = [[], True, True] qubit_names = {'0':'qubit 0', '1':'qubit 1'} puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names, mode='line') initialize = [['ry(pi/4)','0'],['ry(pi/4)','1']] success_condition = {'ZI': 1.0,'IZ': 1.0} allowed_gates = {'0': {'bloch':0, 'z':0, 'ry(pi/4)': 1}, '1': {'bloch':0, 'x':0, 'ry(pi/4)': 1}, 'both': {'unbloch':0}} vi = [[], True, True] qubit_names = {'0':'qubit 0', '1':'qubit 1'} puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names, mode='line') initialize = [['x','0'],['h','1']] success_condition = {'IZ': 1.0} allowed_gates = {'0': {}, '1': {'bloch':0, 'cx':0, 'ry(pi/4)': 1, 'ry(-pi/4)': 1}, 'both': {'unbloch':0}} vi = [[], True, True] qubit_names = {'0':'qubit 0', '1':'qubit 1'} puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names, mode='line') initialize = [] success_condition = {'IZ': 1.0,'IX': 1.0} allowed_gates = {'0': {'bloch':0, 'x':0, 'z':0, 'h':0, 'cx':0, 'ry(pi/4)': 0, 'ry(-pi/4)': 0}, '1': {'bloch':0, 'x':0, 'z':0, 'h':0, 'cx':0, 'ry(pi/4)': 0, 'ry(-pi/4)': 0}, 'both': {'cz':0, 'unbloch':0}} vi = [[], True, True] qubit_names = {'0':'qubit 0', '1':'qubit 1'} puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names, mode='line') import random def setup_variables (): ### Replace this section with anything you want ### r = random.random() A = r*(2/3) B = r*(1/3) ### End of section ### return A, B def hash2bit ( variable, hash ): ### Replace this section with anything you want ### if hash=='V': bit = (variable<0.5) elif hash=='H': bit = (variable<0.25) bit = str(int(bit)) ### End of section ### return bit shots = 8192 def calculate_P ( ): P = {} for hashes in ['VV','VH','HV','HH']: # calculate each P[hashes] by sampling over `shots` samples P[hashes] = 0 for shot in range(shots): A, B = setup_variables() a = hash2bit ( A, hashes[0] ) # hash type for variable `A` is the first character of `hashes` b = hash2bit ( B, hashes[1] ) # hash type for variable `B` is the second character of `hashes` P[hashes] += (a!=b) / shots return P P = calculate_P() print(P) def bell_test (P): sum_P = sum(P.values()) for hashes in P: bound = sum_P - P[hashes] print("The upper bound for P['"+hashes+"'] is "+str(bound)) print("The value of P['"+hashes+"'] is "+str(P[hashes])) if P[hashes]<=bound: print("The upper bound is obeyed :)\n") else: if P[hashes]-bound < 0.1: print("This seems to have gone over the upper bound, but only by a little bit :S\nProbably just rounding errors or statistical noise.\n") else: print("!!!!! This has gone well over the upper bound :O !!!!!\n") bell_test(P) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit def initialize_program (): qubit = QuantumRegister(2) A = qubit[0] B = qubit[1] bit = ClassicalRegister(2) a = bit[0] b = bit[1] qc = QuantumCircuit(qubit, bit) return A, B, a, b, qc def hash2bit ( variable, hash, bit, qc ): if hash=='H': qc.h( variable ) qc.measure( variable, bit ) initialize = [] success_condition = {'ZZ':-0.7071,'ZX':-0.7071,'XZ':-0.7071,'XX':-0.7071} allowed_gates = {'0': {'bloch':0, 'x':0, 'z':0, 'h':0, 'cx':0, 'ry(pi/4)': 0, 'ry(-pi/4)': 0}, '1': {'bloch':0, 'x':0, 'z':0, 'h':0, 'cx':0, 'ry(pi/4)': 0, 'ry(-pi/4)': 0}, 'both': {'cz':0, 'unbloch':0}} vi = [[], True, True] qubit_names = {'0':'A', '1':'B'} puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names, mode='line') import numpy as np def setup_variables ( A, B, qc ): for line in puzzle.program: eval(line) shots = 8192 from qiskit import execute def calculate_P ( backend ): P = {} program = {} for hashes in ['VV','VH','HV','HH']: A, B, a, b, program[hashes] = initialize_program () setup_variables( A, B, program[hashes] ) hash2bit ( A, hashes[0], a, program[hashes]) hash2bit ( B, hashes[1], b, program[hashes]) # submit jobs job = execute( list(program.values()), backend, shots=shots ) # get the results for hashes in ['VV','VH','HV','HH']: stats = job.result().get_counts(program[hashes]) P[hashes] = 0 for string in stats.keys(): a = string[-1] b = string[-2] if a!=b: P[hashes] += stats[string] / shots return P device = 'qasm_simulator' from qiskit import Aer, IBMQ try: IBMQ.load_accounts() except: pass try: backend = Aer.get_backend(device) except: backend = IBMQ.get_backend(device) print(backend.status()) P = calculate_P( backend ) print(P) bell_test( P )
https://github.com/stefan-woerner/qiskit_tutorial
stefan-woerner
from svm.datasets import * from qiskit.aqua.input import ClassificationInput from qiskit.aqua import run_algorithm from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import Aer, execute from qiskit.aqua.components.optimizers.cobyla import COBYLA import numpy as np import matplotlib.pyplot as plt %matplotlib inline # size of training data set training_size = 20 # size of test data set test_size = 10 # dimension of data sets n = 2 # construct training and test data # set the following flag to True for the first data set and to False for the second dataset use_adhoc_dataset = True if use_adhoc_dataset: # first (artifical) data set to test the classifier training_input, test_input, class_labels = \ ad_hoc_data(training_size=training_size, test_size=test_size, n=n, gap=0.3, plot_data=True) else: # second data set to test the classifier training_input, test_input, class_labels = \ Wine(training_size=training_size, test_size=test_size, n=n, plot_data=True) def feature_map(x, q): # initialize quantum circuit qc = QuantumCircuit(q) # apply hadamards and U_Phi twice for _ in range(2): # apply the hadamard and Z-rotatiion to all qubits for i in range(x.shape[0]): qc.h(q[i]) qc.rz(2 * x[i], q[i]) # apply the two qubit gate qc.cx(q[0], q[1]) qc.rz(2*(np.pi-x[0])*(np.pi-x[1]), q[1]) qc.cx(q[0], q[1]) # return quantum circuit return qc # initialize quantum register num_qubits = 2 qr = QuantumRegister(num_qubits) # initialize test data (x1, x2) data = np.asarray([1.5, 0.3]) # get quantum circuit qc_feature_map = feature_map(data, qr) # simulate using local statevector simulator backend = Aer.get_backend('statevector_simulator') job_sim = execute(qc_feature_map, backend) sim_results = job_sim.result() print('simulation: ', sim_results) print('statevector: ', np.round(sim_results.get_statevector(), decimals=4)) # draw circuit qc_feature_map.draw(output='mpl', plot_barriers=False) def variational_form(q, params, depth): # initialize quantum circuit qc = QuantumCircuit(q) # first set of rotations param_idx = 0 for qubit in range(2): qc.ry(params[param_idx], q[qubit]) qc.rz(params[param_idx+1], q[qubit]) param_idx += 2 # entangler blocks and succeeding rotations for block in range(depth): qc.cz(q[0], q[1]) for qubit in range(2): qc.ry(params[param_idx], q[qubit]) qc.rz(params[param_idx+1], q[qubit]) param_idx += 2 # return quantum circuit return qc # initialize quantum register num_qubits = 2 qr = QuantumRegister(num_qubits) # set depth, i.e. number of entangler blocks and rotations (after the initial rotation) depth = 2 params = [0.5,-0.3, 0.2, 0.6]*(depth+1) qc_variational_form = variational_form(qr, params, depth) # simulate using local statevector simulator job_sim = execute(qc_variational_form, backend) sim_results = job_sim.result() print('simulation: ', sim_results) print('statevector: ', np.round(sim_results.get_statevector(), decimals=4)) # draw circuit qc_variational_form.draw(output='mpl', plot_barriers=False) def assign_label(bit_string, class_labels): hamming_weight = sum([int(k) for k in list(bit_string)]) is_odd_parity = hamming_weight & 1 if is_odd_parity: return class_labels[1] else: return class_labels[0] # assigns a label assign_label('01', class_labels) def return_probabilities(counts, class_labels): shots = sum(counts.values()) result = {class_labels[0]: 0, class_labels[1]: 0} for key, item in counts.items(): label = assign_label(key, class_labels) result[label] += counts[key]/shots return result return_probabilities({'00' : 10, '01': 10}, class_labels) def classifier_circuit(x, params, depth): q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc_feature_map = feature_map(x, q) qc_variational_form = variational_form(q, params, depth) qc += qc_feature_map qc += qc_variational_form qc.measure(q, c) return qc def classify(x_list, params, class_labels, depth=2, shots=100): qc_list = [] for x in x_list: qc = classifier_circuit(x, params, depth) qc_list += [qc] qasm_backend = Aer.get_backend('qasm_simulator') jobs = execute(qc_list, qasm_backend, shots=shots) probs = [] for qc in qc_list: counts = jobs.result().get_counts(qc) prob = return_probabilities(counts, class_labels) probs += [prob] return probs # draw classifier circuit qc = classifier_circuit(np.asarray([0.5, 0.5]), params, depth) # classify test data point (using random parameters constructed earlier) x = np.asarray([[0.5, 0.5]]) classify(x, params, class_labels, depth) qc.draw(output='mpl', plot_barriers=False) def cost_estimate_sigmoid(probs, expected_label): p = probs.get(expected_label) sig = None if np.isclose(p, 0.0): sig = 1 elif np.isclose(p, 1.0): sig = 0 else: denominator = np.sqrt(2*p*(1-p)) x = np.sqrt(200)*(0.5-p)/denominator sig = 1/(1+np.exp(-x)) return sig x = np.linspace(0, 1, 20) y = [cost_estimate_sigmoid({'A': x_, 'B': 1-x_}, 'A') for x_ in x] plt.plot(x, y) plt.xlabel('Probability of assigning the correct class') plt.ylabel('Cost value') plt.show() def cost_function(training_input, class_labels, params, depth=2, shots=100, print_value=False): # map training input to list of labels and list of samples cost = 0 training_labels = [] training_samples = [] for label, samples in training_input.items(): for sample in samples: training_labels += [label] training_samples += [sample] # classify all samples probs = classify(training_samples, params, class_labels, depth) # evaluate costs for all classified samples for i, prob in enumerate(probs): cost += cost_estimate_sigmoid(prob, training_labels[i]) cost /= len(training_samples) # print resulting objective function if print_value: print('%.4f' % cost) # return objective value return cost cost_function(training_input, class_labels, params, depth) # set depth of variational form depth = 2 # set number of shots to evaluate the classification circuit shots = 100 # setup the optimizer optimizer = COBYLA() # define objective function for training objective_function = lambda params: cost_function(training_input, class_labels, params, depth, shots, print_value=True) # randomly initialize the parameters init_params = 2*np.pi*np.random.rand(num_qubits*(depth+1)*2) # train classifier opt_params, value, _ = optimizer.optimize(len(init_params), objective_function, initial_point=init_params) # print results print() print('opt_params:', opt_params) print('opt_value: ', value) # collect coordinates of test data test_label_0_x = [x[0] for x in test_input[class_labels[0]]] test_label_0_y = [x[1] for x in test_input[class_labels[0]]] test_label_1_x = [x[0] for x in test_input[class_labels[1]]] test_label_1_y = [x[1] for x in test_input[class_labels[1]]] # initialize lists for misclassified datapoints test_label_misclassified_x = [] test_label_misclassified_y = [] # evaluate test data for label, samples in test_input.items(): # classify samples results = classify(samples, opt_params, class_labels, depth, shots=shots) # analyze results for i, result in enumerate(results): # assign label assigned_label = class_labels[np.argmax([p for p in result.values()])] print('----------------------------------------------------') print('Data point: ', samples[i]) print('Label: ', label) print('Assigned: ', assigned_label) print('Probabilities: ', result) if label != assigned_label: print('Classification:', 'INCORRECT') test_label_misclassified_x += [samples[i][0]] test_label_misclassified_y += [samples[i][1]] else: print('Classification:', 'CORRECT') # compute fraction of misclassified samples total = len(test_label_0_x) + len(test_label_1_x) num_misclassified = len(test_label_misclassified_x) print() print(100*(1-num_misclassified/total), "% of the test data was correctly classified!") # plot results plt.figure() plt.scatter(test_label_0_x, test_label_0_y, c='b', label=class_labels[0], linewidths=5) plt.scatter(test_label_1_x, test_label_1_y, c='g', label=class_labels[1], linewidths=5) plt.scatter(test_label_misclassified_x, test_label_misclassified_y, linewidths=20, s=1, facecolors='none', edgecolors='r') plt.legend() plt.show()
https://github.com/quantumjim/qreative
quantumjim
# coding: utf-8 # Aug 2018 version: Copyright © 2018 James Wootton, University of Basel # Later versions: Copyright © 2018 IBM Research from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit, execute, IBMQ from qiskit import Aer from qiskit.providers.aer.noise import NoiseModel from qiskit.providers.aer.noise.errors import pauli_error, depolarizing_error from qiskit.providers.aer import noise from qiskit.transpiler import PassManager import numpy as np import random import matplotlib.pyplot as plt from matplotlib.patches import Circle, Rectangle import copy import networkx as nx import datetime try: from pydub import AudioSegment # pydub can be a bit dodgy and might cause some warnings except: pass try: IBMQ.load_account() except: print("No IBMQ account was found, so you'll only be able to simulate locally.") def get_backend(device): """Returns backend object for device specified by input string.""" try: backend = Aer.get_backend(device) except: print("You are using an IBMQ backend. The results for this are provided in accordance with the IBM Q Experience EULA.\nhttps://quantumexperience.ng.bluemix.net/qx/terms") # Legal stuff! Yay! for provider in IBMQ.providers(): for potential_backend in provider.backends(): if potential_backend.name()==device_name: backend = potential_backend return backend def get_noise(noisy): """Returns a noise model when input is not False or None. A string will be interpreted as the name of a backend, and the noise model of this will be extracted. A float will be interpreted as an error probability for a depolarizing+measurement error model. Anything else (such as True) will give the depolarizing+measurement error model with default error probabilities.""" if noisy: if type(noisy) is str: # get noise information from a real device (via the IBM Q Experience) device = get_backend(noisy) noise_model = noise.device.basic_device_noise_model( device.properties() ) else: # make a simple noise model for a given noise strength if type(noisy) is float: p_meas = noisy p_gate1 = noisy else: # default values p_meas = 0.08 p_gate1 = 0.04 error_meas = pauli_error([('X',p_meas), ('I', 1 - p_meas)]) # bit flip error with prob p_meas error_gate1 = depolarizing_error(p_gate1, 1) # replaces qubit state with nonsense with prob p_gate1 error_gate2 = error_gate1.tensor(error_gate1) # as above, but independently on two qubits noise_model = NoiseModel() noise_model.add_all_qubit_quantum_error(error_meas, "measure") # add bit flip noise to measurement noise_model.add_all_qubit_quantum_error(error_gate1, ["u1", "u2", "u3"]) # add depolarising to single qubit gates noise_model.add_all_qubit_quantum_error(error_gate2, ["cx"]) # add two qubit depolarising to two qubit gates else: noise_model = None return noise_model class ladder: """An integer implemented on a single qubit. Addition and subtraction are implemented via partial NOT gates.""" def __init__(self,d): """Create a new ladder object. This has the attribute `value`, which is an int that can be 0 at minimum and the supplied value `d` at maximum. This value is initialized to 0.""" self.d = d self.qr = QuantumRegister(1) # declare our single qubit self.cr = ClassicalRegister(1) # declare a single bit to hold the result self.qc = QuantumCircuit(self.qr, self.cr) # combine them in an empty quantum circuit def add(self,delta): """Changes value of ladder object by the given amount `delta`. This is initially done by addition, but it changes to subtraction once the maximum value of `d` is reached. It will then change back to addition once 0 is reached, and so on. delta = Amount by which to change the value of the ladder object. Can be int or float.""" self.qc.rx(np.pi*delta/self.d,self.qr[0]) def value(self,device='qasm_simulator',noisy=False,shots=1024): """Returns the current version of the ladder operator as an int. If floats have been added to this value, the sum of all floats added thus far are rounded. device = A string specifying a backend. The noisy behaviour from a real device will result in some randomness in the value given, and can lead to the reported value being less than the true value on average. These effects will be more evident for high `d`. shots = Number of shots used when extracting results from the qubit. A low value will result in randomness in the value given. This should be neglible when the value is a few orders of magnitude greater than `d`. """ temp_qc = copy.deepcopy(self.qc) temp_qc.barrier(self.qr) temp_qc.measure(self.qr,self.cr) try: job = execute(temp_qc,backend=get_backend(device),noise_model=get_noise(noisy),shots=shots) except: job = execute(temp_qc,backend=get_backend(device),shots=shots) if '1' in job.result().get_counts(): p = job.result().get_counts()['1']/shots else: p = 0 delta = round(2*np.arcsin(np.sqrt(p))*self.d/np.pi) return int(delta) class twobit: """An object that can store a single boolean value, but can do so in two incompatible ways. It is implemented on a single qubit using two complementary measurement bases.""" def __init__(self): """Create a twobit object, initialized to give a random boolean value for both measurement types.""" self.qr = QuantumRegister(1) self.cr = ClassicalRegister(1) self.qc = QuantumCircuit(self.qr, self.cr) self.prepare({'Y':None}) def prepare(self,state): """Supplying `state={basis,b}` prepares a twobit with the boolean `b` stored using the measurement type specified by `basis` (which can be 'X', 'Y' or 'Z'). Note that `basis='Y'` (and arbitrary `b`) will result in the twobit giving a random result for both 'X' and 'Z' (and similarly for any one versus the remaining two). """ self.qc = QuantumCircuit(self.qr, self.cr) if 'Y' in state: self.qc.h(self.qr[0]) if state['Y']: self.qc.sdg(self.qr[0]) else: self.qc.s(self.qr[0]) elif 'X' in state: if state['X']: self.qc.x(self.qr[0]) self.qc.h(self.qr[0]) elif 'Z' in state: if state['Z']: self.qc.x(self.qr[0]) def value (self,basis,device='qasm_simulator',noisy=False,shots=1024,mitigate=True): """Extracts the boolean value for the given measurement type. The twobit is also reinitialized to ensure that the same value would if the same call to `measure()` was repeated. basis = 'X' or 'Z', specifying the desired measurement type. device = A string specifying a backend. The noisy behaviour from a real device will result in some randomness in the value given, even if it has been set to a definite value for a given measurement type. This effect can be reduced using `mitigate=True`. shots = Number of shots used when extracting results from the qubit. A value of greater than 1 only has any effect for `mitigate=True`, in which case larger values of `shots` allow for better mitigation. mitigate = Boolean specifying whether mitigation should be applied. If so the values obtained over `shots` samples are considered, and the fraction which output `True` is calculated. If this is more than 90%, measure will return `True`. If less than 10%, it will return `False`, otherwise it returns a random value using the fraction as the probability.""" if basis=='X': self.qc.h(self.qr[0]) elif basis=='Y': self.qc.sdg(self.qr[0]) self.qc.h(self.qr[0]) self.qc.barrier(self.qr) self.qc.measure(self.qr,self.cr) try: job = execute(self.qc, backend=get_backend(device), noise_model=get_noise(noisy), shots=shots) except: job = execute(self.qc, backend=get_backend(device), shots=shots) stats = job.result().get_counts() if '1' in stats: p = stats['1']/shots else: p = 0 if mitigate: # if p is close to 0 or 1, just make it 0 or 1 if p<0.1: p = 0 elif p>0.9: p = 1 measured_value = ( p>random.random() ) self.prepare({basis:measured_value}) return measured_value def X_value (self,device='qasm_simulator',noisy=False,shots=1024,mitigate=True): """Extracts the boolean value via the X basis. For details of kwargs, see `value()`.""" return self.value('X',device=device,noisy=noisy,shots=shots,mitigate=mitigate) def Y_value (self,device='qasm_simulator',noisy=False,shots=1024,mitigate=True): """Extracts the boolean value via the X basis. For details of kwargs, see `value()`.""" return self.value('Y',device=device,noisy=noisy,shots=shots,mitigate=mitigate) def Z_value (self,device='qasm_simulator',noisy=False,shots=1024,mitigate=True): """Extracts the boolean value via the X basis. For details of kwargs, see `value()`.""" return self.value('Z',device=device,noisy=noisy,shots=shots,mitigate=mitigate) def bell_correlation (basis,device='qasm_simulator',noisy=False,shots=1024): """Prepares a rotated Bell state of two qubits. Measurement is done in the specified basis for each qubit. The fraction of results for which the two qubits agree is returned. basis = String specifying measurement bases. 'XX' denotes X measurement on each qubit, 'XZ' denotes X measurement on qubit 0 and Z on qubit 1, vice-versa for 'ZX', and 'ZZ' denotes 'Z' measurement on both. device = A string specifying a backend. The noisy behaviour from a real device will result in the correlations being less strong than in the ideal case. shots = Number of shots used when extracting results from the qubit. For shots=1, the returned value will randomly be 0 (if the results for the two qubits disagree) or 1 (if they agree). For large shots, the returned value will be probability for this random process. """ qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr,cr) qc.h( qr[0] ) qc.cx( qr[0], qr[1] ) qc.ry( np.pi/4, qr[1]) qc.h( qr[1] ) #qc.x( qr[0] ) #qc.z( qr[0] ) for j in range(2): if basis[j]=='X': qc.h(qr[j]) qc.barrier(qr) qc.measure(qr,cr) try: job = execute(qc, backend=get_backend(device), noise_model=get_noise(noisy), shots=shots, memory=True) except: job = execute(qc, backend=get_backend(device), shots=shots, memory=True) stats = job.result().get_counts() P = 0 for string in stats: p = stats[string]/shots if string in ['00','11']: P += p return {'P':P, 'samples':job.result().get_memory() } def bitstring_superposer (strings,bias=0.5,device='qasm_simulator',noisy=False,shots=1024): """Prepares the superposition of the two given n bit strings. The number of qubits used is equal to the length of the string. The superposition is measured, and the process repeated many times. A dictionary with the fraction of shots for which each string occurred is returned. string = List of two binary strings. If the list has more than two elements, all but the first two are ignored. device = A string specifying a backend. The noisy behaviour from a real device will result in strings other than the two supplied occuring with non-zero fraction. shots = Number of times the process is repeated to calculate the fractions. For shots=1, only a single randomnly generated bit string is return (as the key of a dict).""" # make it so that the input is a list of list of strings, even if it was just a list of strings strings_list = [] if type(strings[0])==str: strings_list = [strings] else: strings_list = strings batch = [] for strings in strings_list: # find the length of the longest string, and pad any that are shorter num = 0 for string in strings: num = max(len(string),num) for string in strings: string = '0'*(num-len(string)) + string qr = QuantumRegister(num) cr = ClassicalRegister(num) qc = QuantumCircuit(qr,cr) if len(strings)==2**num: # create equal superposition of all if all are asked for for n in range(num): qc.h(qr[n]) else: # create superposition of just two diff = [] for bit in range(num): if strings[0][bit]==strings[1][bit]: if strings[0][bit]=='1': qc.x(qr[bit]) if strings[0][bit]!=strings[1][bit]: diff.append(bit) if diff: frac = np.arccos(np.sqrt(bias))/(np.pi/2) qc.rx(np.pi*frac,qr[diff[0]]) for bit in diff[1:]: qc.cx(qr[diff[0]],qr[bit]) for bit in diff: if strings[0][bit]=='1': qc.x(qr[bit]) qc.barrier(qr) qc.measure(qr,cr) batch.append(qc) try: job = execute(batch, backend=get_backend(device), noise_model=get_noise(noisy), shots=shots) except: job = execute(batch, backend=get_backend(device), shots=shots) stats_raw_list = [] for j in range(len(strings_list)): stats_raw_list.append( job.result().get_counts(batch[j]) ) stats_list = [] for stats_raw in stats_raw_list: stats = {} for string in stats_raw: stats[string[::-1]] = stats_raw[string]/shots stats_list.append(stats) # if only one instance was given, output dict rather than list with a single dict if len(stats_list)==1: stats_list = stats_list[0] return stats_list def emoticon_superposer (emoticons,bias=0.5,device='qasm_simulator',noisy=False,shots=1024,figsize=(20,20),encoding=7): """Creates superposition of two emoticons. A dictionary is returned, which supplies the relative strength of each pair of ascii characters in the superposition. An image representing the superposition, with each pair of ascii characters appearing with an weight that represents their strength in the superposition, is also created. emoticons = A list of two strings, each of which is composed of two ascii characters, such as [ ";)" , "8)" ]. device = A string specifying a backend. The noisy behaviour from a real device will result in emoticons other than the two supplied occuring with non-zero strength. shots = Number of times the process is repeated to calculate the fractions used as strengths. For shots=1, only a single randomnly generated emoticon is return (as the key of the dict). emcoding = Number of bits used to encode ascii characters.""" # make it so that the input is a list of list of strings, even if it was just a list of strings if type(emoticons[0])==str: emoticons_list = [emoticons] else: emoticons_list = emoticons strings = [] for emoticons in emoticons_list: string = [] for emoticon in emoticons: bin4emoticon = "" for character in emoticon: bin4char = bin(ord(character))[2:] bin4char = (encoding-len(bin4char))*'0'+bin4char bin4emoticon += bin4char string.append(bin4emoticon) strings.append(string) stats = bitstring_superposer(strings,bias=bias,device=device,noisy=noisy,shots=shots) # make a list of dicts from stats if type(stats) is dict: stats_list = [stats] else: stats_list = stats ascii_stats_list = [] for stats in stats_list: fig = plt.figure() ax=fig.add_subplot(111) plt.rc('font', family='monospace') ascii_stats = {} for string in stats: char = chr(int( string[0:encoding] ,2)) # get string of the leftmost bits and convert to an ASCII character char += chr(int( string[encoding:2*encoding] ,2)) # do the same for string of rightmost bits, and add it to the previous character prob = stats[string] # fraction of shots for which this result occurred ascii_stats[char] = prob # create plot with all characters on top of each other with alpha given by how often it turned up in the output try: plt.annotate( char, (0.5,0.5), va="center", ha="center", color = (0,0,0, prob ), size = 300) except: pass ascii_stats_list.append(ascii_stats) plt.axis('off') plt.savefig('outputs/emoticon_'+datetime.datetime.now().strftime("%H:%M:%S %p on %B %d, %Y")+'.png') plt.show() # if only one instance was given, output dict rather than list with a single dict if len(ascii_stats_list)==1: ascii_stats_list = ascii_stats_list[0] return ascii_stats_list def _filename_superposer (all_files,files,bias,device,noisy,shots): """Takes a list of all possible filenames (all_files) as well as a pair to be superposed or list of such pairs (files) and superposes them for a given bias and number of shots on a given device. Output is a dictionary will filenames as keys and the corresponding fractions of shots as target.""" file_num = len(all_files) bit_num = int(np.ceil( np.log2(file_num) )) all_files += [None]*(2**bit_num-file_num) # make it so that the input is a list of list of strings, even if it was just a list of strings if type(files[0])==str: files_list = [files] else: files_list = files strings = [] for files in files_list: string = [] for file in files: bin4pic = "{0:b}".format(all_files.index(file)) bin4pic = '0'*(bit_num-len(bin4pic)) + bin4pic string.append( bin4pic ) strings.append(string) full_stats = bitstring_superposer(strings,bias=bias,device=device,noisy=noisy,shots=shots) # make a list of dicts from stats if type(full_stats) is dict: full_stats_list = [full_stats] else: full_stats_list = full_stats stats_list = [] for full_stats in full_stats_list: Z = 0 for j in range(file_num): string = "{0:b}".format(j) string = '0'*(bit_num-len(string)) + string if string in full_stats: Z += full_stats[string] stats = {} for j in range(file_num): string = "{0:b}".format(j) string = '0'*(bit_num-len(string)) + string if string in full_stats: stats[string] = full_stats[string]/Z stats_list.append(stats) file_stats_list = [] for stats in stats_list: file_stats = {} for string in stats: file_stats[ all_files[int(string,2)] ] = stats[string] file_stats_list.append(file_stats) return file_stats_list def image_superposer (all_images,images,bias=0.5,device='qasm_simulator',noisy=False,shots=1024,figsize=(20,20)): """Creates superposition of two images from a set of images. A dictionary is returned, which supplies the relative strength of each pair of ascii characters in the superposition. An image representing the superposition, with each of the original images appearing with an weight that represents their strength in the superposition, is also created. all_images = List of strings that are filenames for a set of images. The files should be located in 'images/<filename>.png relative to where the code is executed. images = List of strings for image files to be superposed. This can either contain the strings for two files, or for all in all_images. Other options are not currently supported. device = A string specifying a backend. The noisy behaviour from a real device will result in images other than those intended appearing with non-zero strength. shots = Number of times the process is repeated to calculate the fractions used as strengths.""" image_stats_list = _filename_superposer (all_images,images,bias,device,noisy,shots) print(image_stats_list) for image_stats in image_stats_list: # sort from least to most likely and create corresponding lists of the strings and fractions sorted_strings = sorted(image_stats,key=image_stats.get) sorted_fracs = sorted(image_stats.values()) n = len(image_stats) # construct alpha values such that the final image is a weighted average of the images specified by the keys of `image_stats` alpha = [ sorted_fracs[0] ] for j in range(0,n-1): alpha.append( ( alpha[j]/(1-alpha[j]) ) * ( sorted_fracs[j+1] / sorted_fracs[j] ) ) fig, ax = plt.subplots(figsize=figsize) for j in reversed(range(n)): filename = sorted_strings[j] if filename: image = plt.imread( "images/"+filename+".png" ) plt.imshow(image,alpha=alpha[j]) plt.axis('off') plt.savefig('outputs/image_'+datetime.datetime.now().strftime("%H:%M:%S %p on %B %d, %Y")+'.png') plt.show() # if only one instance was given, output dict rather than list with a single dict if len(image_stats_list)==1: image_stats_list = image_stats_list[0] return image_stats_list def audio_superposer (all_audio,audio,bias=0.5,device='qasm_simulator',noisy=False,shots=1024,format='wav'): audio_stats_list = _filename_superposer (all_audio,audio,bias,device,noisy,shots) for audio_stats in audio_stats_list: loudest = max(audio_stats, key=audio_stats.get) mixed = AudioSegment.from_wav('audio/'+loudest+'.'+format) for filename in audio_stats: if filename != loudest: dBFS = np.log10( audio_stats[filename]/audio_stats[loudest] ) file = AudioSegment.from_wav('audio/'+filename+'.'+format) - dBFS mixed = mixed.overlay(file) mixed.export('outputs/audio_'+'_'.join(audio)+'.'+format, format=format) return audio_stats_list class layout: """Processing and display of data in ways that depend on the layout of a quantum device.""" def __init__(self,device): """Given a device, specified by device = A string specifying a device, or a list of two integers to define a grid. the following attributes are determined. num = Number of qubits on the device. pairs = Dictionary detailing the pairs of qubits for which cnot gates can be directly implemented. Each value is a list of two qubits for which this is possible. The corresponding key is a string that is used as the name of the pair. pos = A dictionary of positions for qubits, to be used in plots. """ if device in ['ibmq_5_yorktown', 'ibmq_16_melbourne']: backend = get_backend(device) self.num = backend.configuration().n_qubits coupling = backend.configuration().coupling_map self.pairs = {} char = 65 for pair in coupling: self.pairs[chr(char)] = pair char += 1 if device in ['ibmq_5_yorktown']: self.pos = { 0: [1,1], 1: [1,0], 2: [0.5,0.5], 3: [0,0], 4: [0,1] } elif device=='ibmq_16_melbourne': self.pos = { 0: (0,1), 1: (1,1), 2: (2,1), 3: (3,1), 4: (4,1), 5: (5,1), 6: (6,1), 7: (7,0), 8: (6,0), 9: (5,0), 10: (4,0), 11: (3,0), 12: (2,0), 13: (1,0) } elif type(device) is list: Lx = device[0] Ly = device[1] self.num = Lx*Ly self.pairs = {} char = 65 for x in range(Lx-1): for y in range(Ly): n = x + y*Ly m = n+1 self.pairs[chr(char)] = [n,m] char += 1 for x in range(Lx): for y in range(Ly-1): n = x + y*Ly m = n+Ly self.pairs[chr(char)] = [n,m] char += 1 self.pos = {} for x in range(Lx): for y in range(Ly): n = x + y*Ly self.pos[n] = [x,y] else: print("Error: Device not recognized.\nMake sure it is a list of two integers (to specify a grid) or one of the supported IBM devices ('ibmqx2', 'ibmqx4' and 'ibmqx5').") for pair in self.pairs: self.pos[pair] = [(self.pos[self.pairs[pair][0]][j] + self.pos[self.pairs[pair][1]][j])/2 for j in range(2)] def calculate_probs(self,raw_stats): """Given a counts dictionary as the input `raw_stats`, a dictionary of probabilities is returned. The keys for these are either integers (referring to qubits) or strings (referring to pairs of neighbouring qubits). For the qubit entries, the corresponding value is the probability that the qubit is in state `1`. For the pair entries, the values are the probabilities that the two qubits disagree (so either the outcome `01` or `10`.""" Z = 0 for string in raw_stats: Z += raw_stats[string] stats = {} for string in raw_stats: stats[string] = raw_stats[string]/Z probs = {} for n in self.pos: probs[n] = 0 for string in stats: for n in range(self.num): if string[-n-1]=='1': probs[n] += stats[string] for pair in self.pairs: if string[-self.pairs[pair][0]-1]!=string[-self.pairs[pair][1]-1]: probs[pair] += stats[string] return probs def plot(self,probs={},labels={},colors={},sizes={}): """An image representing the device is created and displayed. When no kwargs are supplied, qubits are labelled according to their numbers. The pairs of qubits for which a cnot is possible are shown by lines connecting the qubitsm, and are labelled with letters. The kwargs should all be supplied in the form of dictionaries for which qubit numbers and pair labels are the keys (i.e., the same keys as for the `pos` attribute). If `probs` is supplied (such as from the output of the `calculate_probs()` method, the labels, colors and sizes of qubits and pairs will be determined by these probabilities. Otherwise, the other kwargs set these properties directly.""" G=nx.Graph() for pair in self.pairs: G.add_edge(self.pairs[pair][0],self.pairs[pair][1]) G.add_edge(self.pairs[pair][0],pair) G.add_edge(self.pairs[pair][1],pair) if probs: label_changes = copy.deepcopy(labels) color_changes = copy.deepcopy(colors) size_changes = copy.deepcopy(sizes) labels = {} colors = {} sizes = {} for node in G: if probs[node]>1: labels[node] = "" colors[node] = 'grey' sizes[node] = 3000 else: labels[node] = "%.0f" % ( 100 * ( probs[node] ) ) colors[node] =( 1-probs[node],0,probs[node] ) if type(node)!=str: if labels[node]=='0': sizes[node] = 3000 else: sizes[node] = 4000 else: if labels[node]=='0': sizes[node] = 800 else: sizes[node] = 1150 for node in label_changes: labels[node] = label_changes[node] for node in color_changes: colors[node] = color_changes[node] for node in size_changes: sizes[node] = size_changes[node] else: if not labels: labels = {} for node in G: labels[node] = node if not colors: colors = {} for node in G: if type(node) is int: colors[node] = (node/self.num,0,1-node/self.num) else: colors[node] = (0,0,0) if not sizes: sizes = {} for node in G: if type(node)!=str: sizes[node] = 3000 else: sizes[node] = 750 # convert to lists, which is required by nx color_list = [] size_list = [] for node in G: color_list.append(colors[node]) size_list.append(sizes[node]) area = [0,0] for coord in self.pos.values(): for j in range(2): area[j] = max(area[j],coord[j]) for j in range(2): area[j] = (area[j] + 1 )*1.1 if area[0]>2*area[1]: ratio = 0.65 else: ratio = 1 plt.figure(2,figsize=(2*area[0],2*ratio*area[1])) nx.draw(G, self.pos, node_color = color_list, node_size = size_list, labels = labels, with_labels = True, font_color ='w', font_size = 18) plt.show() class pauli_grid(): # Allows a quantum circuit to be created, modified and implemented, and visualizes the output in the style of 'Hello Quantum'. def __init__(self,device='qasm_simulator',noisy=False,shots=1024,mode='circle',y_boxes=False): """ device='qasm_simulator' Backend to be used by Qiskit to calculate expectation values (defaults to local simulator). shots=1024 Number of shots used to to calculate expectation values. mode='circle' Either the standard 'Hello Quantum' visualization can be used (with mode='circle') or the alternative line based one (mode='line'). y_boxes=True Whether to display full grid that includes Y expectation values. """ self.backend = get_backend(device) self.noise_model = get_noise(noisy) self.shots = shots self.y_boxes = y_boxes if self.y_boxes: self.box = {'ZI':(-1, 2),'XI':(-3, 4),'IZ':( 1, 2),'IX':( 3, 4),'ZZ':( 0, 3),'ZX':( 2, 5),'XZ':(-2, 5),'XX':( 0, 7), 'YY':(0,5), 'YI':(-2,3), 'IY':(2,3), 'YZ':(-1,4), 'ZY':(1,4), 'YX':(1,6), 'XY':(-1,6) } else: self.box = {'ZI':(-1, 2),'XI':(-2, 3),'IZ':( 1, 2),'IX':( 2, 3),'ZZ':( 0, 3),'ZX':( 1, 4),'XZ':(-1, 4),'XX':( 0, 5)} self.rho = {} for pauli in self.box: self.rho[pauli] = 0.0 for pauli in ['ZI','IZ','ZZ']: self.rho[pauli] = 1.0 self.qr = QuantumRegister(2) self.cr = ClassicalRegister(2) self.qc = QuantumCircuit(self.qr, self.cr) self.mode = mode # colors are background, qubit circles and correlation circles, respectively if self.mode=='line': self.colors = [(1.6/255,72/255,138/255),(132/255,177/255,236/255),(33/255,114/255,216/255)] else: self.colors = [(1.6/255,72/255,138/255),(132/255,177/255,236/255),(33/255,114/255,216/255)] self.fig = plt.figure(figsize=(5,5),facecolor=self.colors[0]) self.ax = self.fig.add_subplot(111) plt.axis('off') self.bottom = self.ax.text(-3,1,"",size=9,va='top',color='w') self.lines = {} for pauli in self.box: w = plt.plot( [self.box[pauli][0],self.box[pauli][0]], [self.box[pauli][1],self.box[pauli][1]], color=(1.0,1.0,1.0), lw=0 ) b = plt.plot( [self.box[pauli][0],self.box[pauli][0]], [self.box[pauli][1],self.box[pauli][1]], color=(0.0,0.0,0.0), lw=0 ) c = {} c['w'] = self.ax.add_patch( Circle(self.box[pauli], 0.0, color=(0,0,0), zorder=10) ) c['b'] = self.ax.add_patch( Circle(self.box[pauli], 0.0, color=(1,1,1), zorder=10) ) self.lines[pauli] = {'w':w,'b':b,'c':c} def get_rho(self): # Runs the circuit specified by self.qc and determines the expectation values for 'ZI', 'IZ', 'ZZ', 'XI', 'IX', 'XX', 'ZX' and 'XZ' (and the ones with Ys too if needed). if self.y_boxes: corr = ['ZZ','ZX','XZ','XX','YY','YX','YZ','XY','ZY'] ps = ['X','Y','Z'] else: corr = ['ZZ','ZX','XZ','XX'] ps = ['X','Z'] results = {} for basis in corr: temp_qc = copy.deepcopy(self.qc) for j in range(2): if basis[j]=='X': temp_qc.h(self.qr[j]) elif basis[j]=='Y': temp_qc.sdg(self.qr[j]) temp_qc.h(self.qr[j]) temp_qc.barrier(self.qr) temp_qc.measure(self.qr,self.cr) try: job = execute(temp_qc, backend=self.backend, noise_model=self.noise_model, shots=self.shots) except: job = execute(temp_qc, backend=self.backend, shots=self.shots) results[basis] = job.result().get_counts() for string in results[basis]: results[basis][string] = results[basis][string]/self.shots prob = {} # prob of expectation value -1 for single qubit observables for j in range(2): for p in ps: pauli = {} for pp in ['I']+ps: pauli[pp] = (j==1)*pp + p + (j==0)*pp prob[pauli['I']] = 0 for ppp in ps: basis = pauli[ppp] for string in results[basis]: if string[(j+1)%2]=='1': prob[pauli['I']] += results[basis][string]/(2+self.y_boxes) # prob of expectation value -1 for two qubit observables for basis in corr: prob[basis] = 0 for string in results[basis]: if string[0]!=string[1]: prob[basis] += results[basis][string] for pauli in prob: self.rho[pauli] = 1-2*prob[pauli] def update_grid(self,rho=None,labels=False,bloch=None,hidden=[],qubit=True,corr=True,message=""): """ rho = None Dictionary of expectation values for 'ZI', 'IZ', 'ZZ', 'XI', 'IX', 'XX', 'ZX' and 'XZ'. If supplied, this will be visualized instead of the results of running self.qc. labels = False Determines whether basis labels are printed in the corresponding boxes. bloch = None If a qubit name is supplied, and if mode='line', Bloch circles are displayed for this qubit hidden = [] Which qubits have their circles hidden (empty list if both shown). qubit = True Whether both circles shown for each qubit (use True for qubit puzzles and False for bit puzzles). corr = True Whether the correlation circles (the four in the middle) are shown. message A string of text that is displayed below the grid. """ def see_if_unhidden(pauli): # For a given Pauli, see whether its circle should be shown. unhidden = True # first: does it act non-trivially on a qubit in `hidden` for j in hidden: unhidden = unhidden and (pauli[j]=='I') # second: does it contain something other than 'I' or 'Z' when only bits are shown if qubit==False: for j in range(2): unhidden = unhidden and (pauli[j] in ['I','Z']) # third: is it a correlation pauli when these are not allowed if corr==False: unhidden = unhidden and ((pauli[0]=='I') or (pauli[1]=='I')) return unhidden def add_line(line,pauli_pos,pauli): """ For mode='line', add in the line. line = the type of line to be drawn (X, Z or the other one) pauli = the box where the line is to be drawn expect = the expectation value that determines its length """ unhidden = see_if_unhidden(pauli) coord = None p = (1-self.rho[pauli])/2 # prob of 1 output # in the following, white lines goes from a to b, and black from b to c if unhidden: if line=='Z': a = ( self.box[pauli_pos][0], self.box[pauli_pos][1]+l/2 ) c = ( self.box[pauli_pos][0], self.box[pauli_pos][1]-l/2 ) b = ( (1-p)*a[0] + p*c[0] , (1-p)*a[1] + p*c[1] ) lw = 8 coord = (b[1] - (a[1]+c[1])/2)*1.2 + (a[1]+c[1])/2 elif line=='X': a = ( self.box[pauli_pos][0]+l/2, self.box[pauli_pos][1] ) c = ( self.box[pauli_pos][0]-l/2, self.box[pauli_pos][1] ) b = ( (1-p)*a[0] + p*c[0] , (1-p)*a[1] + p*c[1] ) lw = 9 coord = (b[0] - (a[0]+c[0])/2)*1.1 + (a[0]+c[0])/2 else: a = ( self.box[pauli_pos][0]+l/(2*np.sqrt(2)), self.box[pauli_pos][1]+l/(2*np.sqrt(2)) ) c = ( self.box[pauli_pos][0]-l/(2*np.sqrt(2)), self.box[pauli_pos][1]-l/(2*np.sqrt(2)) ) b = ( (1-p)*a[0] + p*c[0] , (1-p)*a[1] + p*c[1] ) lw = 9 self.lines[pauli]['w'].pop(0).remove() self.lines[pauli]['b'].pop(0).remove() self.lines[pauli]['w'] = plt.plot( [a[0],b[0]], [a[1],b[1]], color=(1.0,1.0,1.0), lw=lw ) self.lines[pauli]['b'] = plt.plot( [b[0],c[0]], [b[1],c[1]], color=(0.0,0.0,0.0), lw=lw ) return coord l = 0.9 # line length r = 0.6 # circle radius L = 0.98*np.sqrt(2) # box height and width if rho==None: self.get_rho() # draw boxes for pauli in self.box: if 'I' in pauli: color = self.colors[1] else: color = self.colors[2] self.ax.add_patch( Rectangle( (self.box[pauli][0],self.box[pauli][1]-1), L, L, angle=45, color=color) ) # draw circles for pauli in self.box: unhidden = see_if_unhidden(pauli) if unhidden: if self.mode=='line': self.ax.add_patch( Circle(self.box[pauli], r, color=(0.5,0.5,0.5)) ) else: prob = (1-self.rho[pauli])/2 self.ax.add_patch( Circle(self.box[pauli], r, color=(prob,prob,prob)) ) # update bars if required if self.mode=='line': if bloch in ['0','1']: for other in 'IXZ': px = other*(bloch=='1') + 'X' + other*(bloch=='0') pz = other*(bloch=='1') + 'Z' + other*(bloch=='0') z_coord = add_line('Z',pz,pz) x_coord = add_line('X',pz,px) for j in self.lines[pz]['c']: self.lines[pz]['c'][j].center = (x_coord,z_coord) self.lines[pz]['c'][j].radius = (j=='w')*0.05 + (j=='b')*0.04 px = 'I'*(bloch=='0') + 'X' + 'I'*(bloch=='1') pz = 'I'*(bloch=='0') + 'Z' + 'I'*(bloch=='1') add_line('Z',pz,pz) add_line('X',px,px) else: for pauli in self.box: for j in self.lines[pauli]['c']: self.lines[pauli]['c'][j].radius = 0.0 if pauli in ['ZI','IZ','ZZ']: add_line('Z',pauli,pauli) if pauli in ['XI','IX','XX']: add_line('X',pauli,pauli) if pauli in ['XZ','ZX']: add_line('ZX',pauli,pauli) self.bottom.set_text(message) if labels: for pauli in self.box: plt.text(self.box[pauli][0]-0.18,self.box[pauli][1]-0.85, pauli) if self.y_boxes: self.ax.set_xlim([-4,4]) self.ax.set_ylim([0,8]) else: self.ax.set_xlim([-3,3]) self.ax.set_ylim([0,6]) self.fig.canvas.draw() class qrng (): """This object generations `num` strings, each of `precision=8192/num` bits. These are then dispensed one-by-one as random integers, floats, etc, depending on the method called. Once all `num` strings are used, it'll loop back around.""" def __init__( self, precision=None, num = 1280, sim=True, noisy=False, noise_only=False, verbose=True ): if precision: self.precision = precision self.num = int(np.floor( 5*8192/self.precision )) else: self.num = num self.precision = int(np.floor( 5*8192/self.num )) q = QuantumRegister(5) c = ClassicalRegister(5) qc = QuantumCircuit(q,c) if not noise_only: qc.h(q) qc.measure(q,c) if sim: backend = get_backend('qasm_simulator') else: backend = get_backend('ibmq_5_yorktown') if verbose and not sim: print('Sending job to quantum device') try: job = execute(qc,backend,shots=8192,noise_model=get_noise(noisy),memory=True) except: job = execute(qc,backend,shots=8192,memory=True) data = job.result().get_memory() if verbose and not sim: print('Results from device received') full_data = [] for datum in data: full_data += list(datum) self.int_list = [] self.bit_list = [] n = 0 for _ in range(num): bitstring = '' for b in range(self.precision): bitstring += full_data[n] n += 1 self.bit_list.append(bitstring) self.int_list.append( int(bitstring,2) ) self.n = 0 def _iterate(self): self.n = self.n+1 % self.num def rand_int(self): # get a random integer rand_int = self.int_list[self.n] self._iterate() return rand_int def rand(self): # get a random float rand_float = self.int_list[self.n] / 2**self.precision self._iterate() return rand_float class random_grid (): """Creates an Lx by Ly grid of random bit values""" def __init__(self,Lx,Ly,coord_map=None): self.Lx = Lx self.Ly = Ly self.coord_map = coord_map self.qr = QuantumRegister(Lx*Ly) self.cr = ClassicalRegister(Lx*Ly) self.qc = QuantumCircuit(self.qr,self.cr) def address(self,x,y): # returns the index for the qubit associated with grid point (x,y) # if self.coord_map: address = coord_map( (x,y) ) else: address = y*self.Lx + x return address def neighbours(self,coords): # determines a list of coordinates that neighbour the input coords (x,y) = coords neighbours = [] for (xx,yy) in [(x+1,y),(x-1,y),(x,y+1),(x,y-1)]: if (xx>=0) and (xx<=self.Lx-1) and (yy>=0) and (yy<=self.Ly-1): neighbours.append( (xx,yy) ) return neighbours def get_samples(self,device='qasm_simulator',noisy=False,shots=1024): # run the program and get samples def separate_string(string): string = string[::-1] grid = [] for y in range(self.Ly): line = '' for x in range(self.Lx): line += string[self.address(x,y)] grid.append(line) return '\n'.join(grid) temp_qc = copy.deepcopy(self.qc) temp_qc.barrier(self.qr) temp_qc.measure(self.qr,self.cr) # different backends require different executions, and this block somehow works try: job = execute(temp_qc,backend=get_backend(device),noise_model=get_noise(noisy),shots=shots,memory=True) except: try: if device=='ibmq_qasm_simulator': raise backend=get_backend(device) qobj = compile(temp_qc,backend,pass_manager=PassManager()) job = backend.run(qobj) except: job = execute(temp_qc,backend=get_backend(device),shots=shots,memory=True) stats = job.result().get_counts() grid_stats = {} for string in stats: grid_stats[separate_string(string)] = stats[string] try: # real memory data = job.result().get_memory() grid_data = [] for string in data: grid_data.append(separate_string(string)) except: # fake memory from stats grid_data = [] for string in grid_stats: grid_data += [string]*grid_stats[string] return grid_stats, grid_data def NOT (self,coords,frac=1,axis='x'): '''Implement an rx or ry on the qubit for the given coords, according to the given fraction (`frac=1` is a NOT gate) and the given axis ('x' or 'y').''' if axis=='x': self.qc.rx(np.pi*frac,self.qr[self.address(coords[0],coords[1])]) else: self.qc.ry(np.pi*frac,self.qr[self.address(coords[0],coords[1])]) def CNOT (self,ctl,tgt,frac=1,axis='x'): '''Controlled version of the `NOT` above''' if axis=='y': self.qc.sdg(self.qr[self.address(tgt[0],tgt[1])]) self.qc.h(self.qr[self.address(tgt[0],tgt[1])]) self.qc.crz(np.pi*frac,self.qr[self.address(ctl[0],ctl[1])],self.qr[self.address(tgt[0],tgt[1])]) self.qc.h(self.qr[self.address(tgt[0],tgt[1])]) if axis=='y': self.qc.s(self.qr[self.address(tgt[0],tgt[1])]) class random_mountain(): '''Create a random set of (x,y,z) coordinates that look something like a mountain''' def __init__(self,n): # initializes the quantum circuit of n qubits used to generate the n points self.n = n self.qr = QuantumRegister(n) self.cr = ClassicalRegister(n) self.qc = QuantumCircuit(self.qr,self.cr) def get_mountain(self,new_data=True,method='square',device='qasm_simulator',noisy=False,shots=None): # run based on the current circuit performed on self.qc if shots==None: shots = 2**(2*self.n) if new_data: temp_qc = copy.deepcopy(self.qc) temp_qc.measure(self.qr,self.cr) job = execute(temp_qc, backend=get_backend(device),noise_model=get_noise(noisy),shots=shots) stats = job.result().get_counts() self.prob = {} for string in ['0'*(self.n-len(bin(j)[2:])) + bin(j)[2:] for j in range(2**self.n)]: # loop over all n-bit strings try: self.prob[string] = stats[string]/shots except: self.prob[string] = 0 nodes = sorted(self.prob, key=self.prob.get)[::-1] Z = {} for node in nodes: Z[node] = max(self.prob[node],1/shots) if method=='rings': pos = {} for node in nodes: distance = 0 for j in range(self.n): distance += (node[j]!=nodes[0][j])/self.n theta = random.random()*2*np.pi pos[node] = (distance*np.cos(theta),distance*np.sin(theta)) else: Lx = int(2**np.ceil(self.n/2)) Ly = int(2**np.floor(self.n/2)) strings = [ ['' for k in range(Lx)] for j in range(Ly)] for y in range(Ly): for x in range(Lx): for j in range(self.n): if (j%2)==0: xx = np.floor(x/2**(j/2)) strings[y][x] = str( int( ( xx + np.floor(xx/2) )%2 ) ) + strings[y][x] else: yy = np.floor(y/2**((j-1)/2)) strings[y][x] = str( int( ( yy + np.floor(yy/2) )%2 ) ) + strings[y][x] center = strings[int(np.floor(Ly/2))][int(np.floor(Lx/2))] maxstring = nodes[0] diff = '' for j in range(self.n): diff += '0'*(center[j]==maxstring[j]) + '1'*(center[j]!=maxstring[j]) for y in range(Ly): for x in range(Lx): newstring = '' for j in range(self.n): newstring += strings[y][x][j]*(diff[j]=='0') + ('0'*(strings[y][x][j]=='1')+'1'*(strings[y][x][j]=='0'))*(diff[j]=='1') strings[y][x] = newstring pos = {} for y in range(Ly): for x in range(Lx): pos[strings[y][x]] = (x,y) return pos,Z
https://github.com/quantumjim/qreative
quantumjim
import sys sys.path.append('../') import CreativeQiskit result = CreativeQiskit.bell_correlation('ZZ') print(' Probability of agreement =',result['P']) result = CreativeQiskit.bell_correlation('XZ') print(' Probability of agreement =',result['P']) result = CreativeQiskit.bell_correlation('ZX') print(' Probability of agreement =',result['P']) result = CreativeQiskit.bell_correlation('XX') print(' Probability of agreement =',result['P']) result = CreativeQiskit.bell_correlation('XX') print(' Probability of agreement =',result['samples']) for basis in ['ZZ','XZ','ZX','XX']: result = CreativeQiskit.bell_correlation(basis,noisy=True) print(' Probability of agreement for',basis,'=',result['P'])
https://github.com/quantumjim/qreative
quantumjim
import sys sys.path.append('../') import CreativeQiskit A = CreativeQiskit.ladder(3) a = A.value() print(' Initial value =',a) A.add(1) print(' Add 1 ---> value =',A.value()) A.add(2) print(' Add 2 ---> value =',A.value()) for example in range(9): A.add(1) print(' Add 1 ---> value =',A.value()) A = CreativeQiskit.ladder(10) for example in range(20): print(' Add 1 ---> value =',A.value(shots=50)) A.add(1) A = CreativeQiskit.ladder(10) for example in range(20): print(' Add 1 ---> value =',A.value(noisy=True)) A.add(1) ship = [None]*3 ship[0] = CreativeQiskit.ladder(1) ship[1] = CreativeQiskit.ladder(2) ship[2] = CreativeQiskit.ladder(3) destroyed = 0 while destroyed<3: attack = int(input('\n > Choose a ship to attack (0,1 or 2)...\n ')) ship[attack].add(1) destroyed = 0 for j in range(3): if ship[j].value()==ship[j].d: print('\n *Ship',j,'has been destroyed!*') destroyed += 1 print('\n **Mission complete!**')
https://github.com/quantumjim/qreative
quantumjim
import sys sys.path.append('../') import CreativeQiskit from qiskit import IBMQ IBMQ.load_accounts() L = CreativeQiskit.layout('ibmq_16_melbourne') L.num L.pairs L.pos L.plot() colors = {} labels = {} sizes = {} import random for node in L.pos: colors[node] = (random.random(),random.random(),random.random()) labels[node] = random.choice([';',':','8']) + random.choice([')','(','D']) sizes[node] = 1000+2000*(random.random()) L.plot(colors=colors,labels=labels,sizes=sizes) stats = CreativeQiskit.bitstring_superposer(['1100011001111100','0110010101011001']) print(stats) probs = L.calculate_probs(stats) print(probs) L.plot(probs=probs) L.plot(probs=probs,colors={0:(0.5,0.5,0.5)}) from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit, execute, Aer import numpy as np qr = QuantumRegister(16) cr = ClassicalRegister(16) qc = QuantumCircuit(qr, cr) correct_pairs = ['A','P','D','N','H','I'] for pair in correct_pairs: qc.rx(random.random()*np.pi,qr[L.pairs[pair][0]]) qc.cx(qr[L.pairs[pair][0]],qr[L.pairs[pair][1]]) qc.measure(qr,cr) device = 'qasm_simulator' backend = CreativeQiskit.get_backend(device) noisy = True noise_model = CreativeQiskit.get_noise(noisy) try: job = execute(qc,backend,noise_model=noise_model) except: job = execute(qc,backend) stats = job.result().get_counts() probs = L.calculate_probs(stats) pair_labels = {} for node in L.pos: if type(node)==str: pair_labels[node] = node chosen_pairs = [] colors = {} while len(chosen_pairs)<6: L.plot(probs=probs,labels=pair_labels,colors=colors) pair = str.upper(input(" > Type the name of a pair of qubits whose numbers are the same (or very similar)...\n")) chosen_pairs.append( pair ) colors[pair] = (0.5,0.5,0.5) for j in range(2): colors[L.pairs[pair][j]] = (0.5,0.5,0.5) L.plot(probs=probs,labels=pair_labels,colors=colors) if set(chosen_pairs)==set(correct_pairs): print("\n **You got all the correct pairs! :) **\n") else: print("\n **You didn't get all the correct pairs! :( **\n")
https://github.com/quantumjim/qreative
quantumjim
%matplotlib notebook import sys sys.path.append('../') import CreativeQiskit grid = CreativeQiskit.pauli_grid() grid.update_grid() for gate in [['x','1'],['h','0'],['z','0'],['h','1'],['z','1']]: command = 'grid.qc.'+gate[0]+'(grid.qr['+gate[1]+'])' eval(command) grid.update_grid() grid = CreativeQiskit.pauli_grid(mode='line') grid.update_grid() grid = CreativeQiskit.pauli_grid(y_boxes=True) grid.update_grid() grid.qc.h(grid.qr[0]) grid.update_grid() grid = CreativeQiskit.pauli_grid(y_boxes=True) grid.update_grid(labels=True) grid.qc.h(grid.qr[0]) grid.qc.s(grid.qr[0]) grid.update_grid(labels=True) grid = CreativeQiskit.pauli_grid(noisy=True) grid.update_grid()
https://github.com/quantumjim/qreative
quantumjim
import sys sys.path.append('../') import CreativeQiskit rng = CreativeQiskit.qrng() for _ in range(5): print( rng.rand_int() ) for _ in range(5): print( rng.rand() ) rng = CreativeQiskit.qrng(noise_only=True) for _ in range(5): print( rng.rand() ) rng = CreativeQiskit.qrng(noise_only=True,noisy=True) for _ in range(5): print( rng.rand() ) rng = CreativeQiskit.qrng(noise_only=True,noisy=0.2) for _ in range(5): print( rng.rand() )
https://github.com/quantumjim/qreative
quantumjim
import json import requests from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit, IBMQ, execute, compile IBMQ.load_accounts() q = QuantumRegister(5) c = ClassicalRegister(5) qc = QuantumCircuit(q, c) qc.h(q) qc.measure(q,c) device = 'ibmqx4' backend = IBMQ.get_backend(device) qobj = compile(qc,backend,shots=8192,memory=True) qobj_dict = qobj.as_dict() print(qobj_dict) print( json.dumps(qobj_dict) ) data_dict = {'qObject': qobj_dict,'backend': {'name':device}} data = json.dumps(data_dict) print(data) token = 'insert your API token here' url = 'https://quantumexperience.ng.bluemix.net/api' response = requests.post(str(url + "/users/loginWithToken"),data={'apiToken': token}) resp_id = response.json()['id'] job_url = url+'/Jobs?access_token='+resp_id job = requests.post(job_url, data=data,headers={'Content-Type': 'application/json'}) job_id = job.json()['id'] results_url = url+'/Jobs/'+job_id+'?access_token='+resp_id result = requests.get(results_url).json() random_hex = result['qObjectResult']['results'][0]['data']['memory']
https://github.com/quantumjim/qreative
quantumjim
import numpy as np import matplotlib.pyplot as plt import random import sys sys.path.append('../') from CreativeQiskit import random_grid grid = random_grid(4,4) grid_stats,grid_data = grid.get_samples(shots=1,noisy=0.2) print(grid_data) def string2array (string): grid_list = [] for line in string.split('\n'): grid_list.append( [int(char) for char in line] ) return np.array(grid_list) print( string2array( '1000\n0010\n0000\n0000' ) ) def random_map (size=(4,4),cell=(4,4),seeds=1,sweeps=1,axes=['x','y'],frac=1,shots=1,noisy=False): cell_maps = [ [] for _ in range(shots) ] # loop over all cells, and for Y in range(size[1]): cell_lines = [ [] for _ in range(shots) ] for X in range(size[0]): grid = random_grid(cell[0],cell[1]) # place the seeds if seeds>=1: for seed in range(int(seeds)): coords = (random.randrange(cell[0]),random.randrange(cell[1])) grid.NOT( coords ) elif random.random()<seeds: coords = (random.randrange(cell[0]),random.randrange(cell[1])) grid.NOT( coords ) # sweep over qubits in cell and apply cnots to neighbours for sweep in range(sweeps): for y in range(cell[1]): # in each sweep, half the qubits act as controls to the cnots, and half as targets # they then alternate roles from one sweep to the next # the dividing of qubits into two groups is on in 'checkerboard pattern for x in range((y+sweep)%2,cell[0],2): # sweeps for (xx,yy) in [(x+1,y),(x-1,y),(x,y+1),(x,y-1)]: if (xx in range(cell[0]) and (yy in range(cell[1]))): axis = random.choice(axes) grid.CNOT((x,y),(xx,yy),frac=frac,axis=axis) # collect the results _,grid_data = grid.get_samples(shots=shots,noisy=noisy) for sample in range(shots): cell_lines[sample].append( string2array(grid_data[sample]) ) for sample in range(shots): cell_maps[sample].append( cell_lines[sample] ) # create the final grid maps = [] for cell_map in cell_maps: maps.append( np.block(cell_map) ) return maps maps = random_map(size=(7,7),cell=(4,4),seeds=0,sweeps=1,frac=0.5,shots=5,noisy=0.015) for map_sample in maps: plt.imshow(map_sample,cmap='gray') plt.axis('off') plt.show()
https://github.com/quantumjim/qreative
quantumjim
import sys sys.path.append('../') import CreativeQiskit grid = CreativeQiskit.random_grid(5,4) grid.neighbours( (2,2) ) grid_stats,grid_data = grid.get_samples(shots=3) for sample in grid_stats: print(grid_stats[sample],'shots returned the grid state\n') print(sample,'\n') for sample in grid_data: print(sample,'\n') grid.NOT((0,0)) grid.NOT((4,3),frac=0.5) control = (4,3) for target in grid.neighbours( control ): grid.CNOT(control,target) grid_stats,grid_data = grid.get_samples(shots=10) def show_results (grid): for sample in grid_stats: print(grid_stats[sample],'shots returned the grid state\n') print(sample,'\n') show_results(grid) grid.NOT( (0,3) ) grid.CNOT((0,3), (1,3), frac=0.5) grid_stats,grid_data = grid.get_samples(shots=10) show_results(grid) grid = CreativeQiskit.random_grid(2,2) grid.NOT( (0,0), frac=0.5, axis='x' ) grid.NOT( (0,0), frac=0.5, axis='x' ) grid_stats,grid_data = grid.get_samples(shots=10) show_results(grid) grid = CreativeQiskit.random_grid(2,2) grid.NOT( (0,0), frac=0.5, axis='y' ) grid.NOT( (0,0), frac=0.5, axis='y' ) grid_stats,grid_data = grid.get_samples(shots=10) show_results(grid) grid = CreativeQiskit.random_grid(2,2) grid.NOT( (0,0), frac=0.5, axis='x' ) grid.NOT( (0,0), frac=0.5, axis='y' ) grid_stats,grid_data = grid.get_samples(shots=10) show_results(grid) from qiskit import IBMQ IBMQ.load_accounts() grid = CreativeQiskit.random_grid(5,5) grid.NOT( (0,0), frac=0.5, ) for j in range(5): control = (j,j) grid.NOT( control, frac=(1/(j+1)) ) for target in grid.neighbours( control ): grid.CNOT(control,target) grid_stats,grid_data = grid.get_samples(shots=10,device='ibmq_qasm_simulator') show_results(grid)
https://github.com/quantumjim/qreative
quantumjim
import sys sys.path.append('../') import CreativeQiskit n = 2 alps = CreativeQiskit.random_mountain(n) pos,prob = alps.get_mountain() print('coordinates\n',pos) print('\nprobabilities\n',prob) n = 8 alps = CreativeQiskit.random_mountain(n) alps.qc.h(alps.qr[0]) pos,prob = alps.get_mountain() import matplotlib.pyplot as plt import numpy as np from scipy.spatial import Voronoi, voronoi_plot_2d import random def plot_mountain(pos,prob,levels=[0.3,0.8,0.9],log=True,perturb=0.0): [sea,tree,snow] = levels coords = [] Z = [] for node in pos: coords.append( [pos[node][0]+(1-random.random())*perturb,pos[node][1]+(1-random.random())*perturb] ) if log: Z.append(np.log(prob[node])) else: Z.append(prob[node]) vor = Voronoi(coords) minZ = min(Z) maxZ = max(Z) # normalize chosen colormap colors = [] for node in range(len(Z)): z = (Z[node]-minZ)/(maxZ-minZ) if levels: if z<sea: color = (0,0.5,1,1) elif z<tree: color = (1*(z-sea),1*(1-sea),1*(z-sea),1) elif z<snow: color = (0.7,0.7,0.7,1) else: color = (1,1,1,1) else: color = (z,z,z,1) colors.append(color) # plot Voronoi diagram, and fill finite regions with color mapped from speed value voronoi_plot_2d(vor, show_points=True, show_vertices=False, point_size=0, line_width=0.0) for r in range(len(vor.point_region)): region = vor.regions[vor.point_region[r]] if not -1 in region: polygon = [vor.vertices[i] for i in region] plt.fill(*zip(*polygon), color=colors[r]) plt.savefig('outputs/islands.png',dpi=1000) plt.show() pos,prob = alps.get_mountain(noisy=0.3) plot_mountain(pos,prob) from qiskit import IBMQ IBMQ.load_accounts() pos,prob = alps.get_mountain(noisy='ibmq_16_melbourne') plot_mountain(pos,prob) pos,prob = alps.get_mountain(noisy=0.3,method='rings') plot_mountain(pos,prob,levels=[0.35,0.8,0.9]) pos,prob = alps.get_mountain(method='rings',new_data=False) plot_mountain(pos,prob,levels=[0.35,0.8,0.9]) for j in range(n-1): alps.qc.cx(alps.qr[j],alps.qr[j+1]) pos,prob = alps.get_mountain() plot_mountain(pos,prob) pos,prob = alps.get_mountain(noisy=0.3) plot_mountain(pos,prob) plot_mountain(pos,prob,perturb=0.75)
https://github.com/quantumjim/qreative
quantumjim
import sys sys.path.append('../') import CreativeQiskit stats = CreativeQiskit.bitstring_superposer(['0000','0101'],shots=1) print(" Random string from superposition: ",list(stats.keys())[0]) stats = CreativeQiskit.bitstring_superposer(['0000','1111']) print(" Strings and their fractions: ",stats) stats = CreativeQiskit.bitstring_superposer(['0000','1111'],bias=0.8) print(" Strings and their fractions: ",stats) stats = CreativeQiskit.bitstring_superposer(['00','01','10','11'],bias=0.8) print(" Strings and their fractions: ",stats) stats = CreativeQiskit.emoticon_superposer([';)','8)']) print(" Emoticons and their fractions: ",stats) import sys sys.path.append('../') import CreativeQiskit stats = CreativeQiskit.emoticon_superposer([';)','8)'],noisy=True) stats = CreativeQiskit.emoticon_superposer([ [';)','8)'] , [':D','8|'] ]) print(stats) CreativeQiskit.image_superposer(['butterfly','moth','heron'],[['moth','heron'],['moth','butterfly']]) import sys sys.path.append('../') import CreativeQiskit CreativeQiskit.audio_superposer(['8bit_Dungeon_Level','Bit_Quest','8bit_Dungeon_Boss','Bit_Shift'],['8bit_Dungeon_Level','Bit_Quest'],noisy=True)
https://github.com/quantumjim/qreative
quantumjim
import sys sys.path.append('../') import CreativeQiskit b = CreativeQiskit.twobit() b.prepare({'Z':True}) print(" bit value =",b.Z_value() ) b.prepare({'Z':False}) print(" bit value =",b.Z_value() ) b.prepare({'X':True}) print(" bit value =",b.X_value() ) b.prepare({'X':False}) print(" bit value =",b.X_value() ) print(" Here are 10 trials with, each with True encoded in the Z basis. The values read out with X are:\n") for trial in range(1,11): b.prepare({'Z':True}) message = " Try " + str(trial)+": " message += str( b.X_value() ) print( message ) for trial in range(1,11): message = " Try " + str(trial)+": " b.prepare({'Z':True}) for repeat in range(5): message += str( b.X_value() ) + ", " print(message) b = CreativeQiskit.twobit() for trial in range(1,11): message = " Try " + str(trial)+": " b.prepare({'Z':True}) for repeat in range(5): message += str( b.X_value(noisy=0.2,mitigate=False) ) + ", " print(message) b = CreativeQiskit.twobit() for trial in range(1,11): message = " Try " + str(trial)+": " b.prepare({'Z':True}) for repeat in range(5): message += str( b.X_value(noisy=True) ) + ", " print(message) ship = CreativeQiskit.twobit() destroyed = False while not destroyed: basis = input('\n > Choose a torpedo type (Z or X)...\n ') destroyed = ship.value(basis) if destroyed: print('\n *Ship destroyed!*') else: print('\n *Attack failed!*') print('\n **Mission complete!**')
https://github.com/quantumjim/qreative
quantumjim
from qiskit import IBMQ IBMQ.save_account('MY_API_TOKEN') from qiskit import IBMQ IBMQ.load_accounts() from qiskit import IBMQ IBMQ.enable_account('MY_API_TOKEN') IBMQ.backends() import CreativeQiskit result = CreativeQiskit.bell_correlation('ZZ',device='ibmq_16_melbourne') print(' Probability of agreement =',result['P'])
https://github.com/MonitSharma/Learn-Quantum-Computing-with-Qiskit
MonitSharma
from qiskit.circuit import QuantumCircuit from qiskit_aer import AerSimulator from qiskit.visualization import plot_histogram def decimal_to_binary(decimal): binary = "" if decimal == 0: return "0" while decimal > 0: binary = str(decimal % 2) + binary decimal //= 2 return binary # Example usage decimal_number = 42 binary_number = decimal_to_binary(decimal_number) print(f"The binary representation of {decimal_number} is: {binary_number}") def binary_to_decimal(binary): decimal = 0 power = len(binary) - 1 for digit in binary: decimal += int(digit) * (2 ** power) power -= 1 return decimal # Example usage binary_number = "101010" decimal_number = binary_to_decimal(binary_number) print(f"The decimal representation of {binary_number} is: {decimal_number}") qcirc = QuantumCircuit(8) qcirc.measure_all() qcirc.draw() qcirc.draw('mpl') from qiskit.primitives import Sampler, Estimator, BackendEstimator, BackendSampler backend = AerSimulator() # decide the backend on which to run the circuit sampler = BackendSampler(backend) # create a sampler object sampler2 = Sampler() result = sampler.run(qcirc).result() # run the circuit and save the results result print("Counts",result.quasi_dists[0]) plot_histogram(result.quasi_dists[0]) qcirc = QuantumCircuit(1) # only a single qubit quantum circuit qcirc.draw('mpl') # let's visualize the circuit qcirc.initialize([1,0]) qcirc.draw('mpl') qcirc.measure_all() # applying the measurement qcirc.draw('mpl') result = sampler.run(qcirc).result() counts = result.quasi_dists[0] counts plot_histogram(counts) result = sampler.run(qcirc, shots = 2000).result() counts = result.quasi_dists[0] counts plot_histogram(counts) from qiskit import QuantumRegister, ClassicalRegister qr = QuantumRegister(1,'q0') # you can specifically name the qubit q0 cr = ClassicalRegister(1,'c0') qc = QuantumCircuit(qr, cr) # combine the quantum and classical register qc.initialize([1,0],0) qc.measure(0,0) # apply the measurement as operator qc.draw('mpl') result = sampler.run(qc, shots = 2000).result() counts = result.quasi_dists[0] counts plot_histogram(counts)
https://github.com/MonitSharma/Learn-Quantum-Computing-with-Qiskit
MonitSharma
from qiskit import QuantumCircuit from qiskit.circuit import Gate from math import pi qc = QuantumCircuit(2) c = 0 t = 1 # a controlled-Z qc.cz(c,t) qc.draw('mpl') qc = QuantumCircuit(2) # also a controlled-Z qc.h(t) qc.cx(c,t) qc.h(t) qc.draw('mpl') qc = QuantumCircuit(2) # a controlled-Y qc.sdg(t) qc.cx(c,t) qc.s(t) qc.draw('mpl') qc = QuantumCircuit(2) # a controlled-H qc.ry(pi/4,t) qc.cx(c,t) qc.ry(-pi/4,t) qc.draw('mpl') a = 0 b = 1 qc = QuantumCircuit(2) # swaps states of qubits a and b qc.swap(a,b) qc.draw('mpl') qc = QuantumCircuit(2) # swap a 1 from a to b qc.cx(a,b) # copies 1 from a to b qc.cx(b,a) # uses the 1 on b to rotate the state of a to 0 qc.draw('mpl') # swap a q from b to a qc.cx(b,a) # copies 1 from b to a qc.cx(a,b) # uses the 1 on a to rotate the state of b to 0 qc.draw('mpl') qc = QuantumCircuit(2) qc.cx(b,a) qc.cx(a,b) qc.cx(b,a) qc.draw('mpl') qc = QuantumCircuit(2) # swaps states of qubits a and b qc.cx(b,a) qc.cx(a,b) qc.cx(b,a) qc.draw('mpl') qc = QuantumCircuit(2) # swaps states of qubits a and b qc.cx(a,b) qc.cx(b,a) qc.cx(a,b) qc.draw('mpl') qc = QuantumCircuit(2) theta = pi # theta can be anything (pi chosen arbitrarily) qc.ry(theta/2,t) qc.cx(c,t) qc.ry(-theta/2,t) qc.cx(c,t) qc.draw('mpl') A = Gate('A', 1, []) B = Gate('B', 1, []) C = Gate('C', 1, []) alpha = 1 # arbitrarily define alpha to allow drawing of circuit qc = QuantumCircuit(2) qc.append(C, [t]) qc.cz(c,t) qc.append(B, [t]) qc.cz(c,t) qc.append(A, [t]) qc.p(alpha,c) qc.draw('mpl') qc = QuantumCircuit(3) a = 0 b = 1 t = 2 # Toffoli with control qubits a and b and target t qc.ccx(a,b,t) qc.draw('mpl') qc = QuantumCircuit(3) qc.cp(theta,b,t) qc.cx(a,b) qc.cp(-theta,b,t) qc.cx(a,b) qc.cp(theta,a,t) qc.draw('mpl') qc = QuantumCircuit(3) qc.ch(a,t) qc.cz(b,t) qc.ch(a,t) qc.draw('mpl') qc = QuantumCircuit(1) qc.t(0) # T gate on qubit 0 qc.draw('mpl') qc = QuantumCircuit(1) qc.h(0) qc.t(0) qc.h(0) qc.draw('mpl') qc = QuantumCircuit(1) qc.h(0) qc.t(0) qc.h(0) qc.t(0) qc.draw('mpl')
https://github.com/MonitSharma/Learn-Quantum-Computing-with-Qiskit
MonitSharma
# Importing standard Qiskit libraries: from qiskit import * from qiskit.providers.ibmq import least_busy from qiskit.tools.jupyter import * from qiskit.visualization import * %matplotlib inline circuit = QuantumCircuit(7+1,7) circuit.draw("mpl") circuit.h([0,1,2,3,4,5,6]) circuit.x(7) circuit.h(7) circuit.barrier() circuit.draw("mpl") circuit.cx(6,7) circuit.cx(3,7) circuit.cx(2,7) circuit.cx(0,7) circuit.barrier() circuit.draw("mpl") circuit.h([0,1,2,3,4,5,6]) circuit.barrier() circuit.measure([0,1,2,3,4,5,6],[0,1,2,3,4,5,6]) circuit.draw("mpl") simulator = Aer.get_backend('qasm_simulator') result = execute(circuit, backend = simulator, shots = 1).result() counts = result.get_counts() print(counts) plot_histogram(counts) secret_number = input("Input a Binary String of your choice ") ## Not more than 4 bits if you want to run on a real quantum device later on bv_circ = QuantumCircuit(len(secret_number)+1,len(secret_number)) bv_circ.h(range(len(secret_number))) bv_circ.x(len(secret_number)) bv_circ.h(len(secret_number)) bv_circ.barrier() bv_circ.draw("mpl") for digit, query in enumerate(reversed(secret_number)): if query == "1": bv_circ.cx(digit, len(secret_number)) bv_circ.barrier() bv_circ.draw("mpl") bv_circ.h(range(len(secret_number))) bv_circ.barrier() bv_circ.measure(range(len(secret_number)),range(len(secret_number))) bv_circ.draw("mpl") simulator = Aer.get_backend("qasm_simulator") result = execute(bv_circ, backend = simulator, shots = 1).result() counts = result.get_counts() print(counts) plot_histogram(counts) # Enabling our IBMQ accounts to get the least busy backend device with less than or equal to 5 qubits IBMQ.enable_account('IBM Q API Token') provider = IBMQ.get_provider(hub='ibm-q') provider.backends() backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits <= 5 and x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) exp = execute(bv_circ, backend, shots = 1024) result_exp = exp.result() counts_exp = result_exp.get_counts() plot_histogram([counts_exp,counts])
https://github.com/MonitSharma/Learn-Quantum-Computing-with-Qiskit
MonitSharma
from qiskit import QuantumCircuit, QuantumRegister input_bit = QuantumRegister(1, 'input') output_bit = QuantumRegister(1, 'output') garbage_bit = QuantumRegister(1, 'garbage') Uf = QuantumCircuit(input_bit, output_bit, garbage_bit) Uf.cx(input_bit[0], output_bit[0]) Uf.draw('mpl') Vf = QuantumCircuit(input_bit, output_bit, garbage_bit) Vf.cx(input_bit[0], garbage_bit[0]) Vf.cx(input_bit[0], output_bit[0]) Vf.draw('mpl') qc = Uf.compose(Vf.inverse()) qc.draw('mpl') final_output_bit = QuantumRegister(1, 'final-output') copy = QuantumCircuit(output_bit, final_output_bit) copy.cx(output_bit, final_output_bit) copy.draw('mpl') (Vf.inverse().compose(copy).compose(Vf)).draw('mpl')
https://github.com/MonitSharma/Learn-Quantum-Computing-with-Qiskit
MonitSharma
# Run this cell using Shift+Enter (⌘+Enter on Mac). from typing import Tuple import math Complex = Tuple[float, float] Polar = Tuple[float, float] def imaginary_power(n : int) -> int: # If n is divisible by 4 if n % 4 == 0: return 1 else: return 1j ** (n % 4) imaginary_power(4) def complex_add(x : Complex, y : Complex) -> Complex: # You can extract elements from a tuple like this a = x[0] b = x[1] c = y[0] d = y[1] # This creates a new variable and stores the real component into it real = a + c # Replace the ... with code to calculate the imaginary component imaginary = b+d # You can create a tuple like this ans = (real, imaginary) return ans complex_add((1,2),(3,4)) def complex_mult(x, y): # Extract the real and imaginary components of x and y a = x[0] b = x[1] c = y[0] d = y[1] # Calculate the real component of the result real = a * c - b * d # Calculate the imaginary component of the result imaginary = a * d + b * c # Create a new tuple with the calculated real and imaginary components ans = (real, imaginary) return ans result = complex_mult((1, 2), (3, 4)) print(result) # Output: (-5, 10) def conjugate(x): # Extract the real and imaginary components of x real, imaginary = x # Calculate the conjugate by negating the imaginary component conjugate_imaginary = -imaginary # Create a new tuple with the original real component and the conjugate imaginary component conjugate = (real, conjugate_imaginary) return conjugate result = conjugate((3, 4)) print(result) # Output: (3, -4) def complex_div(x, y): # Extract the real and imaginary components of x and y a, b = x c, d = y # Calculate the denominator of the division denominator = c**2 + d**2 # Calculate the real and imaginary components of the result real = (a * c + b * d) / denominator imaginary = (b * c - a * d) / denominator # Create a new tuple with the calculated real and imaginary components result = (real, imaginary) return result result = complex_div((5, 2), (3, 1)) print(result) # Output: (1.6, 0.2) def modulus(x): # Extract the real and imaginary components of x a = x[0] b = x[1] # Calculate the modulus using the Pythagorean theorem modulus_value = (a**2 + b**2)**0.5 return modulus_value result = modulus((3, 4)) print(result) # Output: 5.0 import cmath def complex_exp(x): # Extract the real and imaginary components of x a = x[0] b = x[1] # Calculate the complex exponential using the cmath library result = cmath.exp(complex(a, b)) # Extract the real and imaginary components of the result g = result.real h = result.imag return (g, h) result = complex_exp((1, 1)) print(result) # Output: (1.4686939399158851+2.2873552871788423j) import cmath def complex_exp_real(r, x): # Extract the real and imaginary components of x a = x[0] b = x[1] # Calculate the complex power using the cmath library result = cmath.exp(complex(a, b) * cmath.log(r)) # Extract the real and imaginary components of the result g = result.real h = result.imag return (g, h) result = complex_exp_real(2, (1, 1)) print(result) # Output: (-1.1312043837568135+2.4717266720048188j) import cmath def polar_convert(x): # Extract the real and imaginary components of x a = x[0] b = x[1] # Calculate the modulus and phase using the cmath library modulus = abs(complex(a, b)) phase = cmath.phase(complex(a, b)) return (modulus, phase) result = polar_convert((3, 4)) print(result) # Output: (5.0, 0.9272952180016122) import cmath def cartesian_convert(x): # Extract the modulus and phase from x modulus = x[0] phase = x[1] # Calculate the real and imaginary components using cmath library real = modulus * cmath.cos(phase) imaginary = modulus * cmath.sin(phase) return (real, imaginary) result = cartesian_convert((5.0, 0.9272952180016122)) print(result) # Output: (3.0000000000000004, 3.9999999999999996) import math def polar_mult(x, y): # Extract the modulus and phase from x and y r1, theta1 = x r2, theta2 = y # Calculate the modulus of the product r3 = r1 * r2 # Calculate the phase of the product theta3 = theta1 + theta2 # Normalize theta3 to be between -pi and pi theta3 = math.atan2(math.sin(theta3), math.cos(theta3)) return (r3, theta3) result = polar_mult((2.0, 1.0471975511965979), (3.0, -0.5235987755982988)) print(result) # Output: (6.0, 0.5235987755982988) import cmath def complex_power(x, y): # Extract the real and imaginary components from x and y a, b = x c, d = y # Convert x and y to complex numbers x_complex = complex(a, b) y_complex = complex(c, d) # Calculate the result using the cmath library result = cmath.exp(y_complex * cmath.log(x_complex)) # Extract the real and imaginary components of the result g = result.real h = result.imag return (g, h) result = complex_power((2, 1), (1, 1)) print(result) # Output: (0.6466465358226179, 1.5353981633974483)
https://github.com/MonitSharma/Learn-Quantum-Computing-with-Qiskit
MonitSharma
# initialization import numpy as np # importing Qiskit from qiskit import QuantumCircuit, transpile from qiskit.primitives import Sampler, Estimator # import basic plot tools from qiskit.visualization import plot_histogram # set the length of the n-bit input string. n = 3 # set the length of the n-bit input string. n = 3 const_oracle = QuantumCircuit(n+1) output = np.random.randint(2) if output == 1: const_oracle.x(n) const_oracle.draw('mpl') balanced_oracle = QuantumCircuit(n+1) b_str = "101" balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) balanced_oracle.draw('mpl') balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Use barrier as divider balanced_oracle.barrier() # Controlled-NOT gates for qubit in range(n): balanced_oracle.cx(qubit, n) balanced_oracle.barrier() balanced_oracle.draw('mpl') balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Use barrier as divider balanced_oracle.barrier() # Controlled-NOT gates for qubit in range(n): balanced_oracle.cx(qubit, n) balanced_oracle.barrier() # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Show oracle balanced_oracle.draw('mpl') dj_circuit = QuantumCircuit(n+1, n) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) dj_circuit.draw('mpl') dj_circuit = QuantumCircuit(n+1, n) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) # Add oracle dj_circuit = dj_circuit.compose(balanced_oracle) dj_circuit.draw('mpl') dj_circuit = QuantumCircuit(n+1, n) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) # Add oracle dj_circuit = dj_circuit.compose(balanced_oracle) # Repeat H-gates for qubit in range(n): dj_circuit.h(qubit) dj_circuit.barrier() # Measure for i in range(n): dj_circuit.measure(i, i) # Display circuit dj_circuit.draw('mpl') # use local simulator sampler = Sampler() result = sampler.run(dj_circuit).result() answer = result.quasi_dists[0] plot_histogram(answer) def dj_oracle(case, n): # We need to make a QuantumCircuit object to return # This circuit has n+1 qubits: the size of the input, # plus one output qubit oracle_qc = QuantumCircuit(n+1) # First, let's deal with the case in which oracle is balanced if case == "balanced": # First generate a random number that tells us which CNOTs to # wrap in X-gates: b = np.random.randint(1,2**n) # Next, format 'b' as a binary string of length 'n', padded with zeros: b_str = format(b, '0'+str(n)+'b') # Next, we place the first X-gates. Each digit in our binary string # corresponds to a qubit, if the digit is 0, we do nothing, if it's 1 # we apply an X-gate to that qubit: for qubit in range(len(b_str)): if b_str[qubit] == '1': oracle_qc.x(qubit) # Do the controlled-NOT gates for each qubit, using the output qubit # as the target: for qubit in range(n): oracle_qc.cx(qubit, n) # Next, place the final X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': oracle_qc.x(qubit) # Case in which oracle is constant if case == "constant": # First decide what the fixed output of the oracle will be # (either always 0 or always 1) output = np.random.randint(2) if output == 1: oracle_qc.x(n) oracle_gate = oracle_qc.to_gate() oracle_gate.name = "Oracle" # To show when we display the circuit return oracle_gate def dj_algorithm(oracle, n): dj_circuit = QuantumCircuit(n+1, n) # Set up the output qubit: dj_circuit.x(n) dj_circuit.h(n) # And set up the input register: for qubit in range(n): dj_circuit.h(qubit) # Let's append the oracle gate to our circuit: dj_circuit.append(oracle, range(n+1)) # Finally, perform the H-gates again and measure: for qubit in range(n): dj_circuit.h(qubit) for i in range(n): dj_circuit.measure(i, i) return dj_circuit n = 4 oracle_gate = dj_oracle('balanced', n) dj_circuit = dj_algorithm(oracle_gate, n) dj_circuit.draw('mpl') result = sampler.run(dj_circuit).result() answer = result.quasi_dists[0] plot_histogram(answer) # from qiskit_ibm_runtime import QiskitRuntimeService # # Save an IBM Quantum account and set it as your default account. # QiskitRuntimeService.save_account(channel="ibm_quantum", token="<Enter Your Token Here>", overwrite=True) # # Load saved credentials # service = QiskitRuntimeService() from qiskit_ibm_runtime import QiskitRuntimeService service = QiskitRuntimeService() service.backends() service = QiskitRuntimeService() backend = service.least_busy(operational=True,min_num_qubits=5) print(backend) # Run our circuit on the least busy backend. Monitor the execution of the job in the queue from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager pm = generate_preset_pass_manager(optimization_level=3, backend=backend,seed_transpiler=11) qc = pm.run(dj_circuit) qc.draw('mpl',idle_wires=False) # Get the results of the computation from qiskit.primitives import BackendSampler sampler = BackendSampler(backend) result = sampler.run(qc).result() answer = result.quasi_dists[0] plot_histogram(answer)
https://github.com/MonitSharma/Learn-Quantum-Computing-with-Qiskit
MonitSharma
!pip install qiskit # or #%pip install qiskit !pip install qiskit[visualization] !pip install qiskit[machine-learning] !pip install qiskit[nature] %pip install matplotlib import qiskit qiskit.version.get_version_info() !pip install pylatexenc
https://github.com/MonitSharma/Learn-Quantum-Computing-with-Qiskit
MonitSharma
%pip install qiskit import math, cmath from typing import List Matrix = List[List[complex]] def create_empty_matrix(rows, columns): # Create an empty matrix filled with 0s matrix = [[0] * columns for _ in range(rows)] return matrix def matrix_add(a, b): # Get the size of the matrices rows = len(a) columns = len(a[0]) # Create an empty matrix to store the result c = create_empty_matrix(rows, columns) # Perform element-wise addition of matrices for i in range(rows): for j in range(columns): c[i][j] = a[i][j] + b[i][j] return c A = [[1, 2, 3], [4, 5, 6]] B = [[7, 8, 9], [10, 11, 12]] result = matrix_add(A, B) print(result) # Output: [[8, 10, 12], # [14, 16, 18]] def scalar_mult(x, a): # Get the size of the matrix rows = len(a) columns = len(a[0]) # Create a new matrix to store the result result = create_empty_matrix(rows, columns) # Perform scalar multiplication for i in range(rows): for j in range(columns): # Access element of the matrix element = a[i][j] # Compute the scalar multiplication and store it in the result matrix result[i][j] = x * element return result x = 2 A = [[1, 2, 3], [4, 5, 6]] result = scalar_mult(x, A) print(result) # Output: [[2, 4, 6], # [8, 10, 12]] def matrix_mult(a, b): # Get the dimensions of matrices a and b rows_a = len(a) cols_a = len(a[0]) rows_b = len(b) cols_b = len(b[0]) # Check if the matrices can be multiplied if cols_a != rows_b: raise ValueError("Matrices cannot be multiplied. Invalid dimensions.") # Create a new matrix to store the result result = create_empty_matrix(rows_a, cols_b) # Perform matrix multiplication for i in range(rows_a): for j in range(cols_b): for k in range(cols_a): # Access elements from matrices a and b element_a = a[i][k] element_b = b[k][j] # Compute the product and accumulate it in the result matrix result[i][j] += element_a * element_b return result A = [[1, 2, 3], [4, 5, 6]] B = [[7, 8], [9, 10], [11, 12]] result = matrix_mult(A, B) print(result) # Output: [[58, 64], # [139, 154]] def determinant(a): # Get the dimension of the matrix n = len(a) # Check if the matrix is square if n != len(a[0]): raise ValueError("Matrix must be square.") # Base case: for a 1x1 matrix, return the single element as the determinant if n == 1: return a[0][0] # Recursive case: calculate the determinant using cofactor expansion det = 0 for j in range(n): # Create a submatrix without the first row and the j-th column submatrix = [[a[i][col] for col in range(n) if col != j] for i in range(1, n)] # Calculate the determinant of the submatrix recursively sub_det = determinant(submatrix) # Calculate the cofactor by multiplying the element with (-1)^(1+j) cofactor = (-1) ** (1 + j) * sub_det # Accumulate the cofactors to compute the determinant det += a[0][j] * cofactor return det def matrix_inverse(a): # Get the dimensions of the matrix n = len(a) # Check if the matrix is square if n != len(a[0]): raise ValueError("Matrix must be square.") # Calculate the determinant of the matrix det = determinant(a) # Check if the matrix is invertible (non-zero determinant) if det == 0: raise ValueError("Matrix is not invertible.") # Create an empty matrix to store the inverse inverse = create_empty_matrix(n, n) # Calculate the matrix of minors for i in range(n): for j in range(n): # Create a submatrix without the i-th row and j-th column submatrix = [[a[row][col] for col in range(n) if col != j] for row in range(n) if row != i] # Calculate the determinant of the submatrix minor = determinant(submatrix) # Calculate the cofactor by multiplying the determinant with (-1)^(i+j) cofactor = (-1) ** (i + j) * minor # Calculate the element of the inverse matrix inverse[j][i] = cofactor / det return inverse A = [[1, 3, 3], [4, 5, 6], [7,8,9]] result = matrix_inverse(A) print(result) def transpose(a): # Get the dimensions of the matrix rows = len(a) columns = len(a[0]) # Create an empty matrix to store the transpose transposed = create_empty_matrix(columns, rows) # Fill in the transposed matrix with elements from the original matrix for i in range(rows): for j in range(columns): transposed[j][i] = a[i][j] return transposed A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] A_transposed = transpose(A) print(A_transposed) # Output: [[1, 4, 7], # [2, 5, 8], # [3, 6, 9]] def conjugate(a): # Get the dimensions of the matrix rows = len(a) columns = len(a[0]) # Create an empty matrix to store the conjugate conjugated = create_empty_matrix(rows, columns) # Fill in the conjugated matrix with conjugates of elements from the original matrix for i in range(rows): for j in range(columns): element = a[i][j] conjugated[i][j] = complex(element.real, -element.imag) return conjugated A = [[1+2j, 2+3j], [3+4j, 4+5j]] A_conjugated = conjugate(A) print(A_conjugated) # Output: [[1-2j, 2-3j], # [3-4j, 4-5j]] def adjoint(a): # Get the dimensions of the matrix rows = len(a) columns = len(a[0]) # Create an empty matrix to store the adjoint adjointed = create_empty_matrix(columns, rows) # Fill in the adjointed matrix with conjugates of elements from the original matrix for i in range(rows): for j in range(columns): element = a[i][j] adjointed[j][i] = complex(element.real, -element.imag) return adjointed A = [[1+2j, 2+3j], [3+4j, 4+5j]] A_adjointed = adjoint(A) print(A_adjointed) # Output: [[1-2j, 3-4j], # [2-3j, 4-5j]] def inner_prod(v, w): # Check if the vectors have the same length if len(v) != len(w): raise ValueError("Vectors must have the same length") inner_product = 0 for i in range(len(v)): inner_product += v[i] * w[i].conjugate() return inner_product v = [1+2j, 3+4j, 5+6j] w = [7+8j, 9+10j, 11+12j] result = inner_prod(v, w) print(result) import math def normalize(v): # Calculate the magnitude of the vector magnitude = math.sqrt(sum(abs(element)**2 for element in v)) # Check if the magnitude is zero if magnitude == 0: raise ValueError("Cannot normalize a zero vector") # Divide each element of the vector by the magnitude normalized = [element / magnitude for element in v] return normalized v = [1+2j, 3+4j, 5+6j] normalized_v = normalize(v) print(normalized_v) def outer_prod(v, w): # Get the lengths of the vectors len_v = len(v) len_w = len(w) # Create an empty matrix to store the outer product matrix = [[0] * len_w for _ in range(len_v)] # Calculate the outer product for i in range(len_v): for j in range(len_w): matrix[i][j] = v[i] * w[j] return matrix v = [1+2j, 3+4j, 5+6j] w = [7+8j, 9+10j, 11+12j] result = outer_prod(v, w) print(result) def tensor_prod(A, B): # Get the dimensions of matrices A and B rows_A, cols_A = len(A), len(A[0]) rows_B, cols_B = len(B), len(B[0]) # Calculate the dimensions of the resulting tensor product matrix rows_result = rows_A * rows_B cols_result = cols_A * cols_B # Create an empty matrix to store the tensor product result = [[0] * cols_result for _ in range(rows_result)] # Calculate the tensor product for i in range(rows_A): for j in range(cols_A): for m in range(rows_B): for n in range(cols_B): result[i * rows_B + m][j * cols_B + n] = A[i][j] * B[m][n] return result A = [[1+2j, 3+4j], [5+6j, 7+8j]] B = [[9+10j, 11+12j], [13+14j, 15+16j]] result = tensor_prod(A, B) print(result) import numpy as np def eigenvalue_eigenvector(A): # Convert the matrix A to a numpy array A = np.array(A) # Calculate the eigenvalues and eigenvectors using numpy's eig function eigen_vals, eigen_vecs = np.linalg.eig(A) # Return the eigenvalues and eigenvectors as a tuple return eigen_vals, eigen_vecs A = [[1, 2], [3, 4]] eigen_vals, eigen_vecs = eigenvalue_eigenvector(A) print("Eigenvalues:", eigen_vals) print("Eigenvectors:") for i, vec in enumerate(eigen_vecs.T): print("Eigenvalue:", eigen_vals[i]) print("Eigenvector:", vec)
https://github.com/MonitSharma/Learn-Quantum-Computing-with-Qiskit
MonitSharma
from qiskit import QuantumCircuit from qiskit.primitives import Sampler, Estimator from qiskit.visualization import plot_histogram, plot_bloch_multivector qc = QuantumCircuit(3) # Apply H-gate to each qubit: for i in range(3): qc.h(i) # See the circuit: qc.draw('mpl') # Let's see the result from qiskit.quantum_info import Statevector state = Statevector.from_instruction(qc) plot_bloch_multivector(state) qc.draw('mpl') from qiskit.visualization import array_to_latex array_to_latex(state, prefix="\\text{Statevector} = ") qc = QuantumCircuit(2) qc.h(0) qc.x(1) qc.draw('mpl') # You can similar get a unitary matrix representing the circuit as an operator by passing it to the Operator default constructor from qiskit.quantum_info import Operator operator = Operator(qc) print(operator.data) # In Jupyter Notebooks we can display this nicely using Latex. # If not using Jupyter Notebooks you may need to remove the # array_to_latex function and use print(unitary) instead. from qiskit.visualization import array_to_latex array_to_latex(operator.data, prefix="\\text{Circuit = }\n") qc = QuantumCircuit(2) qc.x(1) qc.draw('mpl') # Simulate the unitary unitary = Operator(qc).data # Display the results: array_to_latex(unitary, prefix="\\text{Circuit = } ") qc = QuantumCircuit(2) # appkt the cnot gate qc.cx(0,1) # the first number represent the control qubit and the second qubit represent the target qubit # draw it qc.draw('mpl') # Simulate the unitary unitary = Operator(qc).data # Display the results: array_to_latex(unitary, prefix="\\text{Circuit = } ") qc = QuantumCircuit(2) # appkt the cnot gate qc.cx(1,0) # the first number represent the control qubit and the second qubit represent the target qubit # draw it qc.draw('mpl') # Simulate the unitary unitary = Operator(qc).data # Display the results: array_to_latex(unitary, prefix="\\text{Circuit = } ") qc = QuantumCircuit(2) # Apply H-gate to the first: qc.h(0) qc.draw('mpl') # Let's see the result: final_state = Statevector.from_instruction(qc) # Print the statevector neatly: array_to_latex(final_state, prefix="\\text{Statevector = }") qc = QuantumCircuit(2) # Apply H-gate to the first: qc.h(0) # Apply a CNOT: qc.cx(0,1) qc.draw('mpl') # Let's get the result:f final_state = Statevector.from_instruction(qc) array_to_latex(final_state, prefix="\\text{Statevector = }") qc.measure_all() qc.draw('mpl') result = sampler.run(qc).result() counts = result.quasi_dists[0] plot_histogram(counts) plot_bloch_multivector(final_state) from qiskit.visualization import plot_state_qsphere plot_state_qsphere(final_state)
https://github.com/MonitSharma/Learn-Quantum-Computing-with-Qiskit
MonitSharma
from qiskit import QuantumCircuit import numpy as np from qiskit import QuantumCircuit, assemble, Aer def deutsch_problem(seed=None): """Returns a circuit that carries out the function from Deutsch's problem. Args: seed (int): If set, then returned circuit will always be the same for the same seed. Returns: QuantumCircuit """ np.random.seed(seed) problem = QuantumCircuit(2) if np.random.randint(2): print("Function is balanced.") problem.cx(0, 1) else: print("Function is constant.") if np.random.randint(2): problem.x(1) return problem def deutsch(problem): """Implements Deutsch's algorithm. Args: function (QuantumCircuit): Deutsch function to solve. Must be a 2-qubit circuit, and either balanced, or constant. Returns: bool: True if the circuit is balanced, otherwise False. """ qc=QuantumCircuit(2,1) qc.x(1) qc.h([0,1]) qc.draw() qc.append(problem.to_gate(label='f'),[0,1]) qc.h(0) qc.measure(0,0) qc = qc.decompose('f') display(qc.draw()) sim = Aer.get_backend('aer_simulator') state = sim.run(qc).result().get_counts() # Execute the circuit and get the count state=list(state.keys())[0] ## fetch the bit from the Dictionary if state=='1': return('balanced') if state=='0': return('constant') problem=deutsch_problem() print(deutsch(problem))
https://github.com/MonitSharma/Learn-Quantum-Computing-with-Qiskit
MonitSharma
from qiskit import QuantumCircuit from qiskit.circuit import Parameter theta = Parameter('theta') qc = QuantumCircuit(3) qc.cx(0,2) qc.cx(0,1) qc.rx(theta,0) qc.cx(0,1) qc.cx(0,2) qc.draw('mpl') qc = QuantumCircuit(3) qc.h(0) qc.h(1) qc.h(2) qc.cx(0,2) qc.cx(0,1) qc.rx(theta,0) qc.cx(0,1) qc.cx(0,2) qc.h(2) qc.h(1) qc.h(0) qc.draw('mpl')
https://github.com/MonitSharma/Learn-Quantum-Computing-with-Qiskit
MonitSharma
%matplotlib inline import numpy as np import matplotlib.pyplot as plt # Importing standard Qiskit libraries and configuring account from qiskit import QuantumCircuit, execute, IBMQ from qiskit.compiler import transpile from qiskit.providers.aer import QasmSimulator, StatevectorSimulator from qiskit.visualization import * from qiskit.quantum_info import * qc1 = QuantumCircuit(1) qc1.x(0) qc1.measure_all() qc1.draw(output='mpl') job1 = execute(qc1, backend=QasmSimulator(), shots=1024) plot_histogram(job1.result().get_counts()) qc2 = QuantumCircuit(2) # State Preparation qc2.x(0) qc2.barrier() # Perform q_0 XOR 0 qc2.cx(0,1) qc2.measure_all() qc2.draw(output='mpl') job2 = execute(qc2.reverse_bits(), backend=QasmSimulator(), shots=1024) plot_histogram(job2.result().get_counts()) qc3 = QuantumCircuit(3) # State Preparation qc3.x(0) qc3.x(1) qc3.barrier() # Perform q_0 XOR 0 qc3.ccx(0,1,2) qc3.measure_all() qc3.draw(output='mpl') job3 = execute(qc3.reverse_bits(), backend=QasmSimulator(), shots=1024) plot_histogram(job3.result().get_counts()) qc4 = QuantumCircuit(3) # State Preparation qc4.h(range(3)) qc4.measure_all() qc4.draw(output='mpl') job4 = execute(qc4.reverse_bits(), backend=QasmSimulator(), shots=8192) plot_histogram(job4.result().get_counts()) from qiskit.providers.aer.noise import NoiseModel from qiskit.test.mock import FakeMelbourne device_backend = FakeMelbourne() coupling_map = device_backend.configuration().coupling_map noise_model = NoiseModel.from_backend(device_backend) basis_gates = noise_model.basis_gates result_noise = execute(qc4, QasmSimulator(), shots=8192, noise_model=noise_model, coupling_map=coupling_map, basis_gates=basis_gates).result() plot_histogram(result_noise.get_counts()) qc3_t = transpile(qc3, basis_gates=basis_gates) qc3_t.draw(output='mpl') # Loading your IBM Q account(s) provider = IBMQ.load_account() provider.backends() ibmq_backend = provider.get_backend('ibmq_16_melbourne') result_device = execute(qc4, backend=ibmq_backend, shots=8192).result() plot_histogram(result_device.get_counts())
https://github.com/MonitSharma/Learn-Quantum-Computing-with-Qiskit
MonitSharma
from qiskit import IBMQ, Aer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, transpile, assemble from qiskit.tools.monitor import job_monitor import matplotlib as mpl # import basic plot tools from qiskit.visualization import plot_histogram, plot_bloch_multivector import numpy as np from numpy import pi qft_circuit = QuantumCircuit(3) qft_circuit.clear() #input state= 5 qft_circuit.x(0) qft_circuit.x(2) qft_circuit.h(0) qft_circuit.cp(pi/2,0,1) qft_circuit.cp(pi/4,0,2) qft_circuit.h(1) qft_circuit.cp(pi/2,1,2) qft_circuit.h(2) #qft_circuit.swap(0,2) qft_circuit.draw('mpl') #output is the bloch sphere representation in the fourier basis sim = Aer.get_backend("aer_simulator") qft_circuit_init = qft_circuit.copy() qft_circuit_init.save_statevector() statevector = sim.run(qft_circuit_init).result().get_statevector() plot_bloch_multivector(statevector) IBMQ.save_account('') IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') backend = least_busy(provider.backends(filters=lambda b: b.configuration().n_qubits >= 2 and not b.configuration().simulator and b.status().operational==True)) print(backend) t_qc = transpile(qft_circuit, backend, optimization_level=3)#transpile=assembling the circuit and everything job = backend.run(t_qc)#backend means device job_monitor(job)
https://github.com/MonitSharma/Learn-Quantum-Computing-with-Qiskit
MonitSharma
#initialization import matplotlib.pyplot as plt import numpy as np import math # importing Qiskit from qiskit import transpile from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister # import basic plot tools and circuits from qiskit.visualization import plot_histogram from qiskit.circuit.library import QFT from qiskit.primitives import Sampler, Estimator qpe = QuantumCircuit(4, 3) qpe.x(3) qpe.draw('mpl') for qubit in range(3): qpe.h(qubit) qpe.draw('mpl') repetitions = 1 for counting_qubit in range(3): for i in range(repetitions): qpe.cp(math.pi/4, counting_qubit, 3); # controlled-T repetitions *= 2 qpe.draw('mpl') qpe.barrier() # Apply inverse QFT qpe = qpe.compose(QFT(3, inverse=True), [0,1,2]) # Measure qpe.barrier() for n in range(3): qpe.measure(n,n) qpe.draw('mpl') sampler = Sampler() result = sampler.run(qpe).result() answer = result.quasi_dists[0] 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: qpe2 = qpe2.compose(QFT(3, inverse=True), [0,1,2]) # Measure of course! for n in range(3): qpe2.measure(n,n) qpe2.draw('mpl') # Let's see the results! result = sampler.run(qpe2).result() answer = result.quasi_dists[0] 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: qpe3 = qpe3.compose(QFT(5, inverse=True), range(5)) # Measure of course! qpe3.barrier() for n in range(5): qpe3.measure(n,n) qpe3.draw('mpl') # Let's see the results! result = sampler.run(qpe3).result() answer = result.quasi_dists[0] plot_histogram(answer) qpe.draw('mpl') from qiskit_ibm_runtime import QiskitRuntimeService service = QiskitRuntimeService() service.backends() # Load our saved IBMQ accounts and get the least busy backend device with less than or equal to nqubits service = QiskitRuntimeService() backend = service.least_busy(operational=True,min_num_qubits=5) print(backend) # Run our circuit on the least busy backend. Monitor the execution of the job in the queue from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager pm = generate_preset_pass_manager(optimization_level=3, backend=backend,seed_transpiler=11) qc = pm.run(qpe) qpe.draw('mpl',idle_wires=False) # get the results from the computation from qiskit.primitives import BackendSampler sampler = BackendSampler(backend) result = sampler.run(qpe).result() answer = result.quasi_dists[0] plot_histogram(answer)
https://github.com/MonitSharma/Learn-Quantum-Computing-with-Qiskit
MonitSharma
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit_aer import AerSimulator from qiskit import * from qiskit.visualization import plot_histogram, plot_bloch_vector from math import sqrt, pi qc = QuantumCircuit(1) # Create a quantum circuit with one qubit qc.draw('mpl') qc.initialize([1,0]) # Define initial_state as |0> qc.draw('mpl') initial_state = [0,1] # this is the |1> state qc.initialize(initial_state,0) # apply the initialisation on the qubit qc.draw('mpl') from qiskit.primitives import Sampler sampler = Sampler() # tell qiskit how to simulate the circuit backend = AerSimulator() # tell qiskit to use the AerSimulator backend.available_devices() backend.available_methods() qc.draw('mpl') from qiskit.quantum_info import Statevector # get the statevcector state = Statevector.from_instruction(qc) print(state) # lets plot the histogram qc.measure_all() # run the simulation result = sampler.run(qc).result() counts = result.quasi_dists[0] plot_histogram(counts) initial_state = [1/sqrt(2), 1j/sqrt(2)] # Define state |q_0> qc = QuantumCircuit(1) qc.initialize(initial_state,0) # apply the initialisation on the qubit qc.draw('mpl') # get the statevcector state = Statevector.from_instruction(qc) print(state) qc.measure_all() # run the simulation result = sampler.run(qc).result() counts = result.quasi_dists[0] plot_histogram(counts) vector = [1,1] qc.initialize(vector,0) qc = QuantumCircuit(1) # making a new quantum circuit initial_state = [0.+1.j/sqrt(2),1/sqrt(2)+0.j] qc.initialize(initial_state,0) qc.draw('mpl') qc = QuantumCircuit(1) initial_state = [0.+1.j/sqrt(2),1/sqrt(2)+0.j] qc.initialize(initial_state, 0) # get the statevcector state = Statevector.from_instruction(qc) print(state) qc.draw('mpl') from qiskit.visualization import plot_bloch_vector plot_bloch_vector([pi/2,0,1]) # let's plot |0> plot_bloch_vector([0,0,1]) # let's plot |0> plot_bloch_vector([1,0,0])
https://github.com/MonitSharma/Learn-Quantum-Computing-with-Qiskit
MonitSharma
# importing Qiskit from qiskit import IBMQ, Aer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, transpile # import basic plot tools from qiskit.visualization import plot_histogram from qiskit_textbook.tools import simon_oracle b = '110' n = len(b) simon_circuit = QuantumCircuit(n*2, n) # Apply Hadamard gates before querying the oracle simon_circuit.h(range(n)) # Apply barrier for visual separation simon_circuit.barrier() simon_circuit = simon_circuit.compose(simon_oracle(b)) # Apply barrier for visual separation simon_circuit.barrier() # Apply Hadamard gates to the input register simon_circuit.h(range(n)) # Measure qubits simon_circuit.measure(range(n), range(n)) simon_circuit.draw("mpl") # use local simulator aer_sim = Aer.get_backend('aer_simulator') results = aer_sim.run(simon_circuit).result() counts = results.get_counts() print(f"Measured output: {counts}") plot_histogram(counts) from qiskit import QuantumCircuit, Aer, transpile, assemble from qiskit.visualization import plot_histogram # Function to create Simon's oracle for a given hidden string 's' def simon_oracle(s): n = len(s) oracle_circuit = QuantumCircuit(n*2, n) # Apply CNOT gates according to the hidden string 's' for qubit in range(n): if s[qubit] == '1': oracle_circuit.cx(qubit, n + qubit) return oracle_circuit # Hidden string 'b' b = '1101' # Number of qubits n = len(b) # Create a quantum circuit simon_circuit = QuantumCircuit(n*2, n) # Apply Hadamard gates to the first n qubits simon_circuit.h(range(n)) # Apply a barrier for visual separation simon_circuit.barrier() # Compose the circuit with the Simon oracle for the given hidden string 'b' simon_circuit = simon_circuit.compose(simon_oracle(b)) # Apply a barrier for visual separation simon_circuit.barrier() # Apply Hadamard gates to the first n qubits simon_circuit.h(range(n)) # Measure the qubits simon_circuit.measure(range(n), range(n)) # Visualize the circuit simon_circuit.draw("mpl") # Transpile the circuit for the simulator simon_circuit = transpile(simon_circuit, Aer.get_backend('qasm_simulator')) # Run the simulation simulator = Aer.get_backend('qasm_simulator') result = simulator.run(simon_circuit).result() # Display the measured output counts = result.get_counts(simon_circuit) print(f"Measured output: {counts}") # Plot the results plot_histogram(counts)
https://github.com/MonitSharma/Learn-Quantum-Computing-with-Qiskit
MonitSharma
from qiskit import QuantumCircuit, assemble, Aer from math import pi, sqrt, exp from qiskit.visualization import plot_bloch_multivector, plot_histogram sim = Aer.get_backend('aer_simulator') qc = QuantumCircuit(1) qc.x(0) qc.draw() qc.save_statevector() qobj = assemble(qc) state = sim.run(qobj).result().get_statevector() plot_bloch_multivector(state) qc = QuantumCircuit(1) qc.y(0) qc.draw() qc.save_statevector() qobj = assemble(qc) state = sim.run(qobj).result().get_statevector() plot_bloch_multivector(state) qc = QuantumCircuit(1) qc.z(0) qc.draw() qc.save_statevector() qobj = assemble(qc) state = sim.run(qobj).result().get_statevector() plot_bloch_multivector(state) qc = QuantumCircuit(1) qc.h(0) qc.draw() qc.save_statevector() qobj = assemble(qc) state = sim.run(qobj).result().get_statevector() plot_bloch_multivector(state) qc = QuantumCircuit(1) qc.p(pi/4, 0) qc.draw() qc = QuantumCircuit(1) qc.s(0) # Apply S-gate to qubit 0 qc.sdg(0) # Apply Sdg-gate to qubit 0 qc.draw() qc = QuantumCircuit(1) qc.t(0) # Apply T-gate to qubit 0 qc.tdg(0) # Apply Tdg-gate to qubit 0 qc.draw() qc = QuantumCircuit(1) qc.u(pi/2, 0, pi, 0) qc.draw() qc.save_statevector() qobj = assemble(qc) state = sim.run(qobj).result().get_statevector() plot_bloch_multivector(state) initial_state =[1/sqrt(2), -1/sqrt(2)] # Define state |q_0> qc = QuantumCircuit(1) # Must redefine qc qc.initialize(initial_state, 0) # Initialize the 0th qubit in the state `initial_state` qc.save_statevector() # Save statevector qobj = assemble(qc) state = sim.run(qobj).result().get_statevector() # Execute the circuit print(state) # Print the result qobj = assemble(qc) results = sim.run(qobj).result().get_counts() plot_histogram(results) initial_state =[1/sqrt(2), 1/sqrt(2)] # Define state |q_0> qc = QuantumCircuit(1) # Must redefine qc qc.initialize(initial_state, 0) # Initialize the 0th qubit in the state `initial_state` qc.save_statevector() # Save statevector qobj = assemble(qc) state = sim.run(qobj).result().get_statevector() # Execute the circuit print(state) # Print the result qobj = assemble(qc) results = sim.run(qobj).result().get_counts() plot_histogram(results) # Create the Y-measurement function: def x_measurement(qc, qubit, cbit): """Measure 'qubit' in the X-basis, and store the result in 'cbit'""" qc.s(qubit) qc.h(qubit) qc.measure(qubit, cbit) return qc initial_state = [1/sqrt(2), -complex(0,1)/sqrt(2)] # Initialize our qubit and measure it qc = QuantumCircuit(1,1) qc.initialize(initial_state, 0) x_measurement(qc, 0, 0) # measure qubit 0 to classical bit 0 qc.draw() qobj = assemble(qc) # Assemble circuit into a Qobj that can be run counts = sim.run(qobj).result().get_counts() # Do the simulation, returning the state vector plot_histogram(counts) # Display the output on measurement of state vector
https://github.com/MonitSharma/Learn-Quantum-Computing-with-Qiskit
MonitSharma
import matplotlib.pyplot as plt import time # Function with constant runtime complexity: O(1) def constant_time(): return 42 # Function with linear runtime complexity: O(n) def linear_time(n): result = 0 for i in range(n): result += i return result # Function with quadratic runtime complexity: O(n^2) def quadratic_time(n): result = 0 for i in range(n): for j in range(n): result += i * j return result # Function with exponential runtime complexity: O(2^n) def exponential_time(n): if n <= 1: return n return exponential_time(n-1) + exponential_time(n-2) # Function to measure the execution time of a function def measure_time(func, *args): start_time = time.time() result = func(*args) end_time = time.time() execution_time = end_time - start_time return execution_time # Input sizes input_sizes = list(range(1, 11)) # Adjust the input sizes as desired # Measure execution times for different complexities constant_times = [measure_time(constant_time) for _ in input_sizes] linear_times = [measure_time(linear_time, n) for n in input_sizes] quadratic_times = [measure_time(quadratic_time, n) for n in input_sizes] exponential_times = [measure_time(exponential_time, n) for n in input_sizes] # Plotting the graph plt.plot(input_sizes, constant_times, label='O(1)') plt.plot(input_sizes, linear_times, label='O(n)') plt.plot(input_sizes, quadratic_times, label='O(n^2)') plt.plot(input_sizes, exponential_times, label='O(2^n)') plt.xlabel('Input Size (n)') plt.ylabel('Execution Time (s)') plt.title('Runtime Complexity Comparison') plt.legend() plt.show() # Python implementation of Karatsuba algorithm for bit string multiplication. # Helper method: given two unequal sized bit strings, converts them to # same length by adding leading 0s in the smaller string. Returns the # the new length def make_equal_length(str1, str2): len1 = len(str1) len2 = len(str2) if len1 < len2: for i in range(len2 - len1): str1 = '0' + str1 return len2 elif len1 > len2: for i in range(len1 - len2): str2 = '0' + str2 return len1 # If len1 >= len2 # The main function that adds two bit sequences and returns the addition def add_bit_strings(first, second): result = "" # To store the sum bits # make the lengths same before adding length = make_equal_length(first, second) carry = 0 # Initialize carry # Add all bits one by one for i in range(length-1, -1, -1): first_bit = int(first[i]) second_bit = int(second[i]) # boolean expression for sum of 3 bits sum = (first_bit ^ second_bit ^ carry) + ord('0') result = chr(sum) + result # boolean expression for 3-bit addition carry = (first_bit & second_bit) | (second_bit & carry) | (first_bit & carry) # if overflow, then add a leading 1 if carry: result = '1' + result return result # A utility function to multiply single bits of strings a and b def multiply_single_bit(a, b): return int(a[0]) * int(b[0]) # The main function that multiplies two bit strings X and Y and returns # result as long integer def multiply(X, Y): # Find the maximum of lengths of x and Y and make length # of smaller string same as that of larger string n = max(len(X), len(Y)) X = X.zfill(n) Y = Y.zfill(n) # Base cases if n == 0: return 0 if n == 1: return int(X[0])*int(Y[0]) fh = n//2 # First half of string sh = n - fh # Second half of string # Find the first half and second half of first string. Xl = X[:fh] Xr = X[fh:] # Find the first half and second half of second string Yl = Y[:fh] Yr = Y[fh:] # Recursively calculate the three products of inputs of size n/2 P1 = multiply(Xl, Yl) P2 = multiply(Xr, Yr) P3 = multiply(str(int(Xl, 2) + int(Xr, 2)), str(int(Yl, 2) + int(Yr, 2))) # Combine the three products to get the final result. return P1*(1<<(2*sh)) + (P3 - P1 - P2)*(1<<sh) + P2 if __name__ == '__main__': print(multiply("1100", "1010")) print(multiply("110", "1010")) print(multiply("11", "1010")) print(multiply("1", "1010")) print(multiply("0", "1010")) print(multiply("111", "111")) print(multiply("11", "11")) # Python 3 program to find a prime factor of composite using # Pollard's Rho algorithm import random import math # Function to calculate (base^exponent)%modulus def modular_pow(base, exponent,modulus): # initialize result result = 1 while (exponent > 0): # if y is odd, multiply base with result if (exponent & 1): result = (result * base) % modulus # exponent = exponent/2 exponent = exponent >> 1 # base = base * base base = (base * base) % modulus return result # method to return prime divisor for n def PollardRho( n): # no prime divisor for 1 if (n == 1): return n # even number means one of the divisors is 2 if (n % 2 == 0): return 2 # we will pick from the range [2, N) x = (random.randint(0, 2) % (n - 2)) y = x # the constant in f(x). # Algorithm can be re-run with a different c # if it throws failure for a composite. c = (random.randint(0, 1) % (n - 1)) # Initialize candidate divisor (or result) d = 1 # until the prime factor isn't obtained. # If n is prime, return n while (d == 1): # Tortoise Move: x(i+1) = f(x(i)) x = (modular_pow(x, 2, n) + c + n)%n # Hare Move: y(i+1) = f(f(y(i))) y = (modular_pow(y, 2, n) + c + n)%n y = (modular_pow(y, 2, n) + c + n)%n # check gcd of |x-y| and n d = math.gcd(abs(x - y), n) # retry if the algorithm fails to find prime factor # with chosen x and c if (d == n): return PollardRho(n) return d # Driver function if __name__ == "__main__": n = 10967535067 print("One of the divisors for", n , "is ",PollardRho(n)) # This code is contributed by chitranayal rsa_250 = 2140324650240744961264423072839333563008614715144755017797754920881418023447140136643345519095804679610992851872470914587687396261921557363047454770520805119056493106687691590019759405693457452230589325976697471681738069364894699871578494975937497937 p = 64135289477071580278790190170577389084825014742943447208116859632024532344630238623598752668347708737661925585694639798853367 q = 33372027594978156556226010605355114227940760344767554666784520987023841729210037080257448673296881877565718986258036932062711 p*q
https://github.com/kuehnste/QiskitTutorial
kuehnste
# Importing standard Qiskit libraries from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.visualization import * from qiskit.quantum_info import state_fidelity # Magic function to render plots in the notebook after the cell executing the plot command %matplotlib inline def run_on_qasm_simulator(quantum_circuit, num_shots): """Takes a circuit, the number of shots and a backend and returns the qasi-probabilities for running the circuit on the qasm_simulator backend.""" qasm_simulator = Aer.get_backend('qasm_simulator') job = execute(quantum_circuit, backend=qasm_simulator, shots=num_shots) result = job.result() counts = result.get_counts(quantum_circuit) counts = {key: value / num_shots for key, value in counts.items()} return counts # Create a quantum circuit with a single qubit qc1 = QuantumCircuit(1) # Add the Hadamard gate qc1.h(0) # Add the final measurement qc1.measure_all() # Visualize the circuit qc1.draw('mpl') # Now we run the circuit various number of shots num_shots = [100, 500, 1000, 10000] res_qc1 = list() for curr_shots in num_shots: res_qc1.append(run_on_qasm_simulator(qc1, curr_shots)) # Visualize the results in form of a histogram plot_histogram(res_qc1, title='Single Hadamard gate', legend=['number of shots ' + str(x) for x in num_shots]) # Create a quantum circuit with two qubits qc2 = QuantumCircuit(2) # Add the gates creating a Bell state qc2.h(0) qc2.cnot(0,1) # Add the final measurement qc2.measure_all() # Visualize the circuit qc2.draw('mpl') # Now we run the circuit various number of shots num_shots = [100, 500, 1000, 10000] res_qc2 = list() for curr_shots in num_shots: res_qc2.append(run_on_qasm_simulator(qc2, curr_shots)) # Visualize the results in form of a histogram plot_histogram(res_qc2, title='Bell state', legend=['number of shots ' + str(x) for x in num_shots]) # We prepare a similar function for running on the state vector simulator def run_on_statevector_simulator(quantum_circuit, decimals=6): """Takes a circuit, and runs it on the state vector simulator backend.""" statevector_simulator = Aer.get_backend('statevector_simulator') job = execute(quantum_circuit, backend=statevector_simulator) result = job.result() statevector = result.get_statevector(quantum_circuit, decimals=decimals) return statevector # Let us first prepare the Phi^- state qc_phi_minus = QuantumCircuit(2) qc_phi_minus.x(0) qc_phi_minus.h(0) qc_phi_minus.cnot(0,1) qc_phi_minus.draw('mpl') # To obtain the statevector, we run on Aer's state vector simulator. Note, that there is no measurement at the end # when running on the state vector simulator, as otherwise the state would collapse onto one of the computational # basis states and we do not get the actual state vector prepared by the circuit phi_minus_state = run_on_statevector_simulator(qc_phi_minus) print('|Phi^-> =', phi_minus_state) #The Psi^+ state qc_psi_plus = QuantumCircuit(2) qc_psi_plus.x(1) qc_psi_plus.h(0) qc_psi_plus.cnot(0,1) qc_psi_plus.draw('mpl') psi_plus_state = run_on_statevector_simulator(qc_psi_plus) print('|Psi^+> =', psi_plus_state) # Let us first prepare the Psi^- state qc_psi_minus = QuantumCircuit(2) qc_psi_minus.x(0) qc_psi_minus.x(1) qc_psi_minus.h(0) qc_psi_minus.cnot(0,1) qc_psi_minus.draw('mpl') psi_minus_state = run_on_statevector_simulator(qc_psi_minus) print('|Psi^-> =', psi_minus_state) # Let us first prepare the Phi^+ state qc_phi_plus = QuantumCircuit(2) qc_phi_plus.h(0) qc_phi_plus.cnot(0,1) qc_phi_plus.draw('mpl') phi_plus_state = run_on_statevector_simulator(qc_phi_plus) print('|Phi^+> =', phi_plus_state) print('|<Phi^+|Phi^->|^2 =', state_fidelity(phi_plus_state, phi_minus_state)) print('|<Phi^+|Psi^+>|^2 =', state_fidelity(phi_plus_state, psi_plus_state)) print('|<Phi^+|Psi^->|^2 =', state_fidelity(phi_plus_state, psi_minus_state)) print('|<Psi^+|Psi^->|^2 =', state_fidelity(psi_plus_state, phi_minus_state)) print('|<Psi^+|Phi^->|^2 =', state_fidelity(psi_plus_state, phi_minus_state)) print('|<Phi^-|Psi^->|^2 =', state_fidelity(phi_minus_state, psi_minus_state))
https://github.com/kuehnste/QiskitTutorial
kuehnste
# Importing standard Qiskit libraries from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.visualization import * from qiskit.quantum_info import state_fidelity # Magic function to render plots in the notebook after the cell executing the plot command %matplotlib inline def run_on_qasm_simulator(quantum_circuit, num_shots): """Takes a circuit, the number of shots and a backend and returns the counts for running the circuit on the qasm_simulator backend.""" qasm_simulator = Aer.get_backend('qasm_simulator') job = execute(quantum_circuit, backend=qasm_simulator, shots=num_shots) result = job.result() counts = result.get_counts(quantum_circuit) return counts # Create a quantum circuit with a single qubit qc = QuantumCircuit(1) # Add the Hadamard gate # Add the final measurement # Visualize the circuit qc.draw('mpl') # Now we run the circuit various number of shots # Visualize the results in form of a histogram # Create a quantum circuit with two qubits # Add the gates creating a Bell state # Add the final measurement # Visualize the circuit # Now we run the circuit various number of shots # Visualize the results in form of a histogram # We prepare a similar function for running on the state vector simulator # This way we can obtain the state vectors and check for orthogonality def run_on_statevector_simulator(quantum_circuit, decimals=6): """Takes a circuit, and runs it on the state vector simulator backend.""" statevector_simulator = Aer.get_backend('statevector_simulator') job = execute(quantum_circuit, backend=statevector_simulator) result = job.result() statevector = result.get_statevector(quantum_circuit, decimals=decimals) return statevector # A quantum circuit for two qubits qc_phi_minus = QuantumCircuit(2) # Now add the gates # Visualize the circuit qc_phi_minus.draw('mpl') # To obtain the statevector, we run on Aer's state vector simulator. Note, that there is no measurement at the end # when running on the state vector simulator, as otherwise the state would collapse onto one of the computational # basis states and we do not get the actual state vector prepared by the circuit phi_minus_state = run_on_statevector_simulator(qc_phi_minus) print('|Phi^-> =', phi_minus_state) #The psi^+ state qc_psi_plus = QuantumCircuit(2) # Now add the gates # Visualize the circuit qc_psi_plus.draw('mpl') psi_plus_state = run_on_statevector_simulator(qc_psi_plus) print('|Psi^+> =', psi_plus_state) # Let us first prepare the psi^- state qc_psi_minus = QuantumCircuit(2) # Now add the gates # Visualize the circuit qc_psi_minus.draw('mpl') psi_minus_state = run_on_statevector_simulator(qc_psi_minus) print('|Psi^-> =', psi_minus_state) # The Phi^+ state qc_phi_plus = QuantumCircuit(2) qc_phi_plus.h(0) qc_phi_plus.cnot(0,1) qc_phi_plus.draw('mpl') phi_plus_state = run_on_statevector_simulator(qc_phi_plus) print('|Phi^+> =', phi_plus_state) # Check all of the six possible combinations print('|<Phi^+|Phi^->|^2 =', state_fidelity(phi_plus_state, phi_minus_state)) # ...
https://github.com/kuehnste/QiskitTutorial
kuehnste
# Importing standard Qiskit libraries from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.visualization import * from qiskit.quantum_info import state_fidelity # Numpy for numeric functions import numpy as np # Magic function to render plots in the notebook after the cell executing the plot command %matplotlib inline def run_on_statevector_simulator(quantum_circuit, decimals=6): """Takes a circuit, and runs it on the state vector simulator backend.""" statevector_simulator = Aer.get_backend('statevector_simulator') job = execute(quantum_circuit, backend=statevector_simulator) result = job.result() statevector = result.get_statevector(quantum_circuit, decimals=decimals) return statevector # Generate a quantum circuit for two qubits qc = QuantumCircuit(2) # Add the gates which generate |psi_0> qc.x(1) qc.h(0) qc.h(1) # Draw the quantum circuit qc.draw(output='mpl') # Run it on the state vector simulator vec = run_on_statevector_simulator(qc) # Visualize the resulting state vector plot_bloch_multivector(vec) # Add a CNOT gate to the circuit qc.cnot(0,1) # Draw the circuit qc.draw(output='mpl') # Run it on the state vector simulator vec = run_on_statevector_simulator(qc) # Visualize the resulting state vector plot_bloch_multivector(vec) # Generate a quantum circuit for two qubits which generates |psi_0> qc2 = QuantumCircuit(2) # Add the gates qc2.x(1) qc2.h(0) qc2.h(1) # Draw the quantum circuit qc2.draw(output='mpl') # Run it on the state vector simulator for various angles of Rx # Number of steps nsteps = 10 for i in range(nsteps): # We add a controlled R_x gate with different angle to our base circuit qc3 = QuantumCircuit(2) qc3.compose(qc2, inplace=True) qc3.crx(i*4*np.pi/nsteps,0,1) # Run the resulting circuit on the state vector simulator vec = run_on_statevector_simulator(qc3) # Visualize the state vector h = plot_bloch_multivector(vec) # Save the image to disk h.savefig(str(i)+'.png')
https://github.com/kuehnste/QiskitTutorial
kuehnste
# Importing standard Qiskit libraries from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.visualization import * from qiskit.quantum_info import state_fidelity # Numpy for numeric functions import numpy as np # Magic function to render plots in the notebook after the cell executing the plot command %matplotlib inline def run_on_statevector_simulator(quantum_circuit, decimals=6): """Takes a circuit, and runs it on the state vector simulator backend.""" statevector_simulator = Aer.get_backend('statevector_simulator') job = execute(quantum_circuit, backend=statevector_simulator) result = job.result() statevector = result.get_statevector(quantum_circuit, decimals=decimals) return statevector # Generate a quantum circuit for two qubits # Add the gates which generate |psi_0> # Draw the quantum circuit # Run it on the state vector simulator # Visualize the resulting state vector # Add a CNOT gate to the circuit # Draw the circuit # Run it on the state vector simulator # Visualize the resulting state vector # Generate a quantum circuit qc2 for two qubits qc2 = QuantumCircuit(2) # Add the gates which generate |psi_0> # Draw the quantum circuit # Run it on the state vector simulator for various angles of Rx # Number of steps nsteps = 10 for i in range(nsteps): # We copy the quantum circuit qc2 into a new circuit qc3 qc3 = QuantumCircuit(2) qc3.compose(qc2, inplace=True) # Add the controllec Rx gates between qubits 0 and 1 for various angles # Hint set: the angle to i*4*np.pi/nsteps # Run the resulting circuit on the state vector simulator vec = run_on_statevector_simulator(qc3) # Visualize the state vector
https://github.com/kuehnste/QiskitTutorial
kuehnste
# Importing standard Qiskit libraries from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.visualization import * from qiskit.quantum_info import state_fidelity # Numpy and Scipy for data evaluation and reference calculations import numpy as np from scipy.linalg import expm # Matplotlib for visualization import matplotlib.pyplot as plt # Magic function to render plots in the notebook after the cell executing the plot command %matplotlib inline # Function for convenience which allows for running the simulator and extracting the results def run_on_qasm_simulator(quantum_circuit, num_shots): """Takes a circuit, the number of shots and a backend and returns the counts for running the circuit on the qasm_simulator backend.""" qasm_simulator = Aer.get_backend('qasm_simulator') job = execute(quantum_circuit, backend=qasm_simulator, shots=num_shots) result = job.result() counts = result.get_counts() return counts def Op(M, n ,N): """Given a single site operator, provide the N-body operator string obtained by tensoring identities""" d = M.shape[0] id_left = np.eye(d**n) id_right = np.eye(d**(N-n-1)) res = np.kron(id_left,np.kron(M,id_right)) return res def IsingHamiltonian(N, h): """The Ising Hamiltonian for N sites with parameter h""" Z = np.array([[1., 0.],[0., -1.]]) X = np.array([[0., 1.],[1., 0.]]) H = np.zeros((2**N, 2**N)) for i in range(N): if i<N-1: H += Op(Z, i, N)@Op(Z, i+1, N) H += h*Op(X, i, N) return H # For reference, we provide a function computing the exact solution for # the magnetization as a function of time def get_magnetization_vs_time(h, delta_t, nsteps): """Compute the exact value of the magnetization""" Z = np.array([[1., 0.],[0., -1.]]) X = np.array([[0., 1.],[1., 0.]]) Id = np.eye(2) # The Ising Hamiltonian for 4 sites with parameter h H = IsingHamiltonian(4, h) # The time evolution operator for an interval \Delta t U = expm(-1.0j*delta_t*H) # The operator for the total magnetization M = Op(Z,0,4) + Op(Z,1,4) + Op(Z,2,4) + Op(Z,3,4) # Numpy array to hold the results magnetization = np.zeros(nsteps) # The initial wave function corresponding to |0010> psi = np.zeros(16) psi[int('0010', 2)] = 1 # Evolve in steps of \Delta t and measure the magnetization for n in range(nsteps): psi = U@psi magnetization[n] = np.real(psi.conj().T@M@psi) return magnetization def provide_initial_state(): # Create a quantum circuit qc for 4 qubits qc = QuantumCircuit(4) # Add the necessary gate(s) to provide the inital state |0010> qc.x(2) return qc def Uzz(delta_t): # Create an empty quantum circuit qc for 4 qubits qc = QuantumCircuit(4) # Add the gates for exp(-i Z_k Z_k+1 \Delta t) for all neighboring qubits for i in range(3): qc.rzz(2.0*delta_t, i, i+1) return qc def Ux(delta_t, h): # Create an empty quantum circuit qc for 4 qubits qc = QuantumCircuit(4) # Add the gates for exp(-i h X_k \Delta t) to all qubits for i in range(4): qc.rx(2.0*delta_t*h, i) return qc def build_time_evolution_circuit(qc_init_state, qc_Uzz, qc_Ux, N): """Given the circuits implementing the initial state and the two parts of the trotterized time-evolution operator build the circuit evolving the wave function N steps """ # Generate an empty quantum circuit qc for 4 qubits qc = QuantumCircuit(4) # Add the inital state qc.compose(qc_init_state, inplace=True) # For each time step add qc_Uzz and qc_Ux for i in range(N): qc.compose(qc_Uzz, inplace=True) qc.compose(qc_Ux, inplace=True) # Add the final measurments qc.measure_all() return qc def get_magnetization(counts): """Given the counts resulting form a measurement, compute the site resolved magnetization""" total_counts = sum(counts.values()) res = np.zeros(4) for qubit in range(4): Z_expectation = 0. for key, value in counts.items(): if key[qubit] == '0': Z_expectation += value else: Z_expectation -= value res[qubit] = Z_expectation/total_counts return res # The parameters for the time evolution h = 1.5 delta_t = 0.05 nsteps = 40 nshots = 1000 # Provide the initial state qc_init_state = provide_initial_state() # The time-evolution operators qc_Uzz = Uzz(delta_t) qc_Ux = Ux(delta_t,h) # Numpy array for expectation values of the magnetization magnetization = np.zeros(nsteps) # Numpy array for qubit configuration configuration = np.zeros((4, nsteps)) # Run the time evolution for n in range(1, nsteps+1): # Build the evolution circuit out of qc_init_state, qc_Uzz and qc_Ux for # n steps qc_evo = build_time_evolution_circuit(qc_init_state, qc_Uzz, qc_Ux, n) # Run the evolution circuit on the qasm_simulator res = run_on_qasm_simulator(qc_evo, nshots) # Compute the ovservables configuration[:,n-1] = get_magnetization(res) magnetization[n-1] = sum(configuration[:,n-1]) # For reference we compute the exact solution magnetization_exact = get_magnetization_vs_time(h, delta_t, nsteps) # Plot the total magnetization as a function of time and compare to # the exact result plt.figure() plt.plot(magnetization_exact, '--', label='exact') plt.plot(magnetization, 'o', label='quantum circuit') plt.xlabel('$t/\Delta t$') plt.ylabel('$<\sum_i Z_i(t)>$') plt.title('Total magnetization') plt.legend() # Plot the site resolved spin configuration as a function of time plt.figure() plt.imshow(configuration, aspect='auto') plt.colorbar() plt.xlabel('$t/\Delta t$') plt.ylabel('$<Z_i(t)>$') plt.title('Spatially resolved spin configuration') # Import the package for working with parameters from qiskit.circuit import Parameter # Define parameters, the arguments define the symbols that are shown if we # draw the circuit dt = Parameter('Δt') h = Parameter('h') def Uzz_parameterized(param_delta_t): # Create an empty quantum circuit qc for 4 qubits qc = QuantumCircuit(4) # Add the gates for exp(-i Z_k Z_k+1 \Delta t) for all neighboring qubits for i in range(3): qc.rzz(2.0*param_delta_t, i, i+1) return qc def Ux_parameterized(param_delta_t, param_h): # Create an empty quantum circuit qc for 4 qubits qc = QuantumCircuit(4) for i in range(4): # Add the exp(-i \Delta t Z_k Z_k+1) gates qc.rx(2.0*param_delta_t*param_h, i) return qc # The parameters for the time evolution (now we can conveniently check # for multiple values of h since we have a parameterized circuit) h_values = [1.0, 1.2 , 1.5] delta_t = 0.05 nsteps = 40 nshots = 1000 # Provide the initial state qc_init_state = provide_initial_state() # The time-evolution operators qc_Uzz = Uzz_parameterized(dt) qc_Ux = Ux_parameterized(dt, h) # Numpy array for expectation values of the magnetization magnetization = np.zeros((len(h_values), nsteps)) # Run the time evolution for n in range(1, nsteps+1): # Build the evolution circuit out of qc_init_state, qc_Uzz and qc_Ux for # n steps qc_evo = build_time_evolution_circuit(qc_init_state, qc_Uzz, qc_Ux, n) # Now we bind the parameter \Delta t qc_evo = qc_evo.bind_parameters({dt: delta_t}) # Now we bind the parameters for h and get a list of circuits, one for each value of h circs = [qc_evo.bind_parameters({h: h_value}) for h_value in h_values] # Run the evolution circuits on the qasm_simulator res = run_on_qasm_simulator(circs, nshots) # Compute the ovservables (now res is a list of counts with one entry for each different value of h) for i in range(len(res)): configuration = get_magnetization(res[i]) magnetization[i, n-1] = sum(configuration) # For reference we compute the exact solutions magnetization_exact = np.zeros((len(h_values), nsteps)) for i in range(len(h_values)): magnetization_exact[i,:] = get_magnetization_vs_time(h_values[i], delta_t, nsteps) # Plot the total magnetization as a function of time and compare to # the exact result plt.figure() for i in range(len(h_values)): hf = plt.plot(magnetization_exact[i,:], '--', label='exact, $h = ' + str(h_values[i]) + '$') plt.plot(magnetization[i,:], 'o', label='quantum circuit, $h = ' + str(h_values[i]) + '$', c=hf[0].get_color()) plt.xlabel('$t/\Delta t$') plt.ylabel('$<\sum_i Z_i(t)>$') plt.title('Total magnetization') plt.legend()
https://github.com/kuehnste/QiskitTutorial
kuehnste
# Importing standard Qiskit libraries from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.visualization import * from qiskit.quantum_info import state_fidelity # Numpy and Scipy for data evaluation and reference calculations import numpy as np from scipy.linalg import expm # Matplotlib for visualization import matplotlib.pyplot as plt # Magic function to render plots in the notebook after the cell executing the plot command %matplotlib inline # Function for convenience which allows for running the simulator and extracting the results def run_on_qasm_simulator(quantum_circuit, num_shots): """Takes a circuit, the number of shots and a backend and returns the counts for running the circuit on the qasm_simulator backend.""" qasm_simulator = Aer.get_backend('qasm_simulator') job = execute(quantum_circuit, backend=qasm_simulator, shots=num_shots) result = job.result() counts = result.get_counts() return counts def Op(M, n ,N): """Given a single site operator, provide the N-body operator string obtained by tensoring identities""" d = M.shape[0] id_left = np.eye(d**n) id_right = np.eye(d**(N-n-1)) res = np.kron(id_left,np.kron(M,id_right)) return res def IsingHamiltonian(N, h): """The Ising Hamiltonian for N sites with parameter h""" Z = np.array([[1., 0.],[0., -1.]]) X = np.array([[0., 1.],[1., 0.]]) H = np.zeros((2**N, 2**N)) for i in range(N): if i<N-1: H += Op(Z, i, N)@Op(Z, i+1, N) H += h*Op(X, i, N) return H # For reference, we provide a function computing the exact solution for # the magnetization as a function of time def get_magnetization_vs_time(h, delta_t, nsteps): """Compute the exact value of the magnetization""" Z = np.array([[1., 0.],[0., -1.]]) X = np.array([[0., 1.],[1., 0.]]) Id = np.eye(2) # The Ising Hamiltonian for 4 sites with parameter h H = IsingHamiltonian(4, h) # The time evolution operator for an interval \Delta t U = expm(-1.0j*delta_t*H) # The operator for the total magnetization M = Op(Z,0,4) + Op(Z,1,4) + Op(Z,2,4) + Op(Z,3,4) # Numpy array to hold the results magnetization = np.zeros(nsteps) # The initial wave function corresponding to |0010> psi = np.zeros(16) psi[int('0010', 2)] = 1 # Evolve in steps of \Delta t and measure the magnetization for n in range(nsteps): psi = U@psi magnetization[n] = np.real(psi.conj().T@M@psi) return magnetization def provide_initial_state(): # Create a quantum circuit qc for 4 qubits qc = QuantumCircuit(4) # Add the necessary gate(s) to provide the inital state |0010> return qc def Uzz(delta_t): # Create an empty quantum circuit qc for 4 qubits qc = QuantumCircuit(4) # Add the gates for exp(-i Z_k Z_k+1 \Delta t) for all neighboring qubits return qc def Ux(delta_t, h): # Create an empty quantum circuit qc for 4 qubits qc = QuantumCircuit(4) # Add the gates for exp(-i h X_k \Delta t) to all qubits return qc def build_time_evolution_circuit(qc_init_state, qc_Uzz, qc_Ux, N): """Given the circuits implementing the initial state and the two parts of the trotterized time-evolution operator build the circuit evolving the wave function N steps """ # Generate an empty quantum circuit qc for 4 qubits qc = QuantumCircuit(4) # Add the inital state qc.compose(qc_init_state, inplace=True) # For each time step add qc_Uzz and qc_Ux for i in range(N): qc.compose(qc_Uzz, inplace=True) qc.compose(qc_Ux, inplace=True) # Add the final measurments qc.measure_all() return qc def get_magnetization(counts): """Given the counts resulting form a measurement, compute the site resolved magnetization""" total_counts = sum(counts.values()) res = np.zeros(4) for qubit in range(4): Z_expectation = 0. for key, value in counts.items(): if key[qubit] == '0': Z_expectation += value else: Z_expectation -= value res[qubit] = Z_expectation/total_counts return res # The parameters for the time evolution h = 1.5 delta_t = 0.05 nsteps = 40 nshots = 1000 # Provide the initial state qc_init_state = provide_initial_state() # The time-evolution operators qc_Uzz = Uzz(delta_t) qc_Ux = Ux(delta_t, h) # Numpy array for expectation values of the magnetization magnetization = np.zeros(nsteps) # Numpy array for qubit configuration configuration = np.zeros((4, nsteps)) # Run the time evolution for n in range(1, nsteps+1): # Build the evolution circuit out of qc_init_state, qc_Uzz and qc_Ux for # n steps qc_evo = build_time_evolution_circuit(qc_init_state, qc_Uzz, qc_Ux, n) # Run the evolution circuit on the qasm_simulator res = run_on_qasm_simulator(qc_evo, nshots) # Compute the ovservables configuration[:,n-1] = get_magnetization(res) magnetization[n-1] = sum(configuration[:,n-1]) # For reference we compute the exact solution magnetization_exact = get_magnetization_vs_time(h, delta_t, nsteps) # Plot the total magnetization as a function of time and compare to # the exact result plt.figure() plt.plot(magnetization_exact, '--', label='exact') plt.plot(magnetization, 'o', label='quantum circuit') plt.xlabel('$t/\Delta t$') plt.ylabel('$<\sum_i Z_i(t)>$') plt.title('Total magnetization') plt.legend() # Plot the site resolved spin configuration as a function of time plt.figure() plt.imshow(configuration, aspect='auto') plt.colorbar() plt.xlabel('$t/\Delta t$') plt.ylabel('$<Z_i(t)>$') plt.title('Spatially resolved spin configuration')
https://github.com/kuehnste/QiskitTutorial
kuehnste
# Importing standard Qiskit libraries from qiskit import QuantumCircuit, execute, Aer from qiskit.visualization import * from qiskit.quantum_info import state_fidelity # Magic function to render plots in the notebook after the cell executing the plot command %matplotlib inline def run_on_qasm_simulator(quantum_circuit, num_shots): """Takes a circuit, the number of shots and a backend and returns the counts for running the circuit on the qasm_simulator backend.""" qasm_simulator = Aer.get_backend('qasm_simulator') job = execute(quantum_circuit, backend=qasm_simulator, shots=num_shots) result = job.result() counts = result.get_counts(quantum_circuit) return counts def oracle_f1(): "Oracle implementing function f1" qc = QuantumCircuit(3) qc.cnot(0,2) qc.cnot(1,2) qc.x(2) qc.cnot(1,2) qc.cnot(0,2) return qc def oracle_f2(): "Oracle implementing function f2" qc = QuantumCircuit(3) qc.cnot(0,2) qc.x(2) qc.cnot(1,2) return qc # We visualize the oracle qc_oracle_f1 = oracle_f1() qc_oracle_f1.draw('mpl') # Create a quantum circuit for 3 qubits and 2 classical registers qc_deutch_josza_oracle1 = QuantumCircuit(3,2) # Add the Hadamard gate qc_deutch_josza_oracle1.h(0) qc_deutch_josza_oracle1.h(1) # Apply the oracle qc_deutch_josza_oracle1.compose(qc_oracle_f1, inplace=True) # Add the z-gate acting on the ancilla qc_deutch_josza_oracle1.z(2) # Apply the oracle again qc_deutch_josza_oracle1.compose(qc_oracle_f1, inplace=True) # Add the Hadamard gate qc_deutch_josza_oracle1.h(0) qc_deutch_josza_oracle1.h(1) # Add measurement to the first two qubits qc_deutch_josza_oracle1.barrier() qc_deutch_josza_oracle1.measure(range(2),range(2)) # Visualize the circuit qc_deutch_josza_oracle1.draw('mpl') # The number of shots we use num_shots = 100 # Now we run the circuit res_qc_deutch_josza_oracle1 = run_on_qasm_simulator(qc_deutch_josza_oracle1, num_shots) # Visualize the results in form of a histogram plot_histogram(res_qc_deutch_josza_oracle1, title='Deutsch-Josza algorithm, oracle 1') # We visualize the oracle qc_oracle_f2 = oracle_f2() qc_oracle_f2.draw('mpl') # Create a quantum circuit for 3 qubits and 2 classical registers qc_deutch_josza_oracle2 = QuantumCircuit(3,2) # Add the Hadamard gate qc_deutch_josza_oracle2.h(0) qc_deutch_josza_oracle2.h(1) # Apply the oracle qc_deutch_josza_oracle2.compose(qc_oracle_f2, inplace=True) # Add the z-gate acting on the ancilla qc_deutch_josza_oracle2.z(2) # Apply the oracle again qc_deutch_josza_oracle2.compose(qc_oracle_f2, inplace=True) # Add the Hadamard gate qc_deutch_josza_oracle2.h(0) qc_deutch_josza_oracle2.h(1) # Add measurement to the first two qubits qc_deutch_josza_oracle2.barrier() qc_deutch_josza_oracle2.measure(range(2),range(2)) # Visualize the circuit qc_deutch_josza_oracle2.draw('mpl') # The number of shots we use num_shots = 100 # Now we run the circuit res_qc_deutch_josza_oracle2 = run_on_qasm_simulator(qc_deutch_josza_oracle2, num_shots) # Visualize the results in form of a histogram plot_histogram(res_qc_deutch_josza_oracle2, title='Deutsch-Josza algorithm, oracle 2') # Generate the circuits that are preparing the basis states qc_00 = QuantumCircuit(3) # 00 qc_01 = QuantumCircuit(3) qc_01.x(1) # 10 qc_10 = QuantumCircuit(3) qc_10.x(0) # 11 qc_11 = QuantumCircuit(3) qc_11.x(0) qc_11.x(1) qcs_basis_states = [qc_00, qc_01, qc_10, qc_11] # The number of shots we are going to use num_shots = 100 # Prepare empty lists for the results of the two oracles res_oracle1 = list() res_oracle2 = list() # We run the oracles on the basis states and record the outcomes for qc_basis_state in qcs_basis_states: # The quantum circuit sending a basis state through oracle 1 and measuring the output qc_oracle1 = QuantumCircuit(3,1) qc_oracle1.compose(qc_basis_state, inplace=True) qc_oracle1.compose(oracle_f1(), inplace=True) qc_oracle1.measure(2,0) # The quantum circuit sending a basis state through oracle 2 and measuring the output qc_oracle2 = QuantumCircuit(3,1) qc_oracle2.compose(qc_basis_state, inplace=True) qc_oracle2.compose(oracle_f2(), inplace=True) qc_oracle2.measure(2,0) # We run the circuits on the qasm simulator res_oracle1.append(run_on_qasm_simulator(qc_oracle1, num_shots)) res_oracle2.append(run_on_qasm_simulator(qc_oracle2, num_shots)) # Visualize the results for oracle 1 plot_histogram(res_oracle1, title='Results oracle 1', legend=['input |00>', 'input |01>', 'input |10>', 'input |11>']) # Visualize the results for oracle 2 plot_histogram(res_oracle2, title='Results oracle 2', legend=['input |00>', 'input |01>', 'input |10>', 'input |11>'])
https://github.com/kuehnste/QiskitTutorial
kuehnste
# Importing standard Qiskit libraries from qiskit import QuantumCircuit, execute, Aer from qiskit.visualization import * from qiskit.quantum_info import state_fidelity # Magic function to render plots in the notebook after the cell executing the plot command %matplotlib inline def run_on_qasm_simulator(quantum_circuit, num_shots): """Takes a circuit, the number of shots and a backend and returns the counts for running the circuit on the qasm_simulator backend.""" qasm_simulator = Aer.get_backend('qasm_simulator') job = execute(quantum_circuit, backend=qasm_simulator, shots=num_shots) result = job.result() counts = result.get_counts(quantum_circuit) return counts def oracle_f1(): "Oracle implementing function f1" qc = QuantumCircuit(3) qc.cnot(0,2) qc.cnot(1,2) qc.x(2) qc.cnot(1,2) qc.cnot(0,2) return qc def oracle_f2(): "Oracle implementing function f2" qc = QuantumCircuit(3) qc.cnot(0,2) qc.x(2) qc.cnot(1,2) return qc # We visualize the oracle # Create a quantum circuit for 3 qubits and 2 classical registers qc_deutch_josza_oracle1 = QuantumCircuit(3,2) # Add the Hadamard gate # Apply the oracle # Add the z-gate acting on the ancilla # Apply the oracle again # Add the Hadamard gate # Add measurement to the first two qubits qc_deutch_josza_oracle1.barrier() qc_deutch_josza_oracle1.measure(range(2),range(2)) # Visualize the circuit # The number of shots we use num_shots = 100 # Now we run the circuit # Visualize the results in form of a histogram # We visualize the oracle # Create a quantum circuit for 3 qubits and 2 classical registers qc_deutch_josza_oracle2 = QuantumCircuit(3,2) # Add the Hadamard gate # Apply the oracle # Add the z-gate acting on the ancilla # Apply the oracle again # Add the Hadamard gate # Add measurement to the first two qubits # Visualize the circuit # The number of shots we use num_shots = 100 # Now we run the circuit # Visualize the results in form of a histogram
https://github.com/kuehnste/QiskitTutorial
kuehnste
# Importing standard Qiskit libraries from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.visualization import * from qiskit.quantum_info import state_fidelity # Magic function to render plots in the notebook after the cell executing the plot command %matplotlib inline qc = QuantumCircuit(3) qc.h(0) qc.cnot(0,1) qc.cnot(1,2) qc.measure_active() qc.draw(output='mpl') # Loading your IBM Q account IBMQ.load_account() provider = IBMQ.get_provider(group='open') # List the existing quantum devices and their number of qubits device_list = provider.backends(simulator=False) for dev in device_list: print(dev.name() + ': ' + str(dev.configuration().n_qubits) + ' qubits') # We choose one device which has enough qubits for our experiment and send the job to the device num_shots_hardware = 1024 hardware_backend = provider.get_backend('ibmq_quito') job = execute(qc, backend=hardware_backend, shots=num_shots_hardware) result = job.result() counts = result.get_counts() plot_histogram(counts, title='Run on hardware') simulator_backend = Aer.get_backend('qasm_simulator') counts_simulator = list() num_shots_simulator = [1024, 8192] for num_shots in num_shots_simulator: job = execute(qc, backend=simulator_backend, shots=num_shots) result_simulator = job.result() counts_simulator.append(result_simulator.get_counts()) # We plot a comparison between the different results plot_histogram([counts] + counts_simulator, title='Hardware vs. simulator', legend=['hardware ' + str(num_shots_hardware) + ' shots', 'simulator ' + str(num_shots_simulator[0]) + ' shots', 'simulator ' + str(num_shots_simulator[1]) + ' shots'])
https://github.com/qiskit-community/prototype-qrao
qiskit-community
%matplotlib inline import numpy as np import networkx as nx from tqdm.notebook import tqdm from docplex.mp.model import Model from qiskit_optimization.translators import from_docplex_mp from qrao.encoding import QuantumRandomAccessEncoding, EncodingCommutationVerifier num_nodes = 6 elist = [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 0), (0, 3), (1, 4), (2, 4)] edges = np.zeros((num_nodes, num_nodes)) for i, j in elist: edges[i, j] = (i + 1) * (j + 2) mod = Model("maxcut") nodes = list(range(num_nodes)) var = [mod.binary_var(name="x" + str(i)) for i in nodes] mod.maximize( mod.sum( edges[i, j] * (1 - (2 * var[i] - 1) * (2 * var[j] - 1)) for i in nodes for j in nodes ) ) graph = nx.from_edgelist(elist) nx.draw(graph) problem = from_docplex_mp(mod) print(problem) encoding = QuantumRandomAccessEncoding(max_vars_per_qubit=3) encoding.encode(problem) print("Encoded Problem:\n=================") print(encoding.qubit_op) # The Hamiltonian without the offset print("Offset = ", encoding.offset) print("Variables encoded on each qubit: ", encoding.q2vars) verifier = EncodingCommutationVerifier(encoding) progress_bar = tqdm(verifier) for str_dvars, obj_val, encoded_obj_val in progress_bar: if not np.isclose(encoded_obj_val, obj_val, atol=1e-4): progress_bar.disp(bar_style="danger") raise Exception( # pylint: disable=broad-exception-raised f"Violation identified: {str_dvars} evaluates to {obj_val} " f"but the encoded problem evaluates to {encoded_obj_val}." ) import qiskit.tools.jupyter # pylint: disable=unused-import,wrong-import-order %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/prototype-qrao
qiskit-community
import numpy as np from qiskit.utils import QuantumInstance from qiskit.algorithms.minimum_eigen_solvers import VQE from qiskit.circuit.library import RealAmplitudes from qiskit.algorithms.optimizers import SPSA from qiskit_aer import Aer from qrao import ( QuantumRandomAccessEncoding, QuantumRandomAccessOptimizer, SemideterministicRounding, ) from qrao.utils import get_random_maxcut_qp # Generate a random QUBO in the form of a QuadraticProgram problem = get_random_maxcut_qp(degree=3, num_nodes=6, seed=3, draw=True) print(problem.export_as_lp_string()) # Create an encoding object with a maximum of 3 variables per qubit, aka a (3,1,p)-QRAC encoding = QuantumRandomAccessEncoding(max_vars_per_qubit=3) # Encode the QUBO problem into an encoded Hamiltonian operator encoding.encode(problem) # This is our encoded operator print(f"Our encoded Hamiltonian is:\n( {encoding.qubit_op} ).\n") print( "We achieve a compression ratio of " f"({encoding.num_vars} binary variables : {encoding.num_qubits} qubits) " f"≈ {encoding.compression_ratio}.\n" ) # Create a QuantumInstance for solving the relaxed Hamiltonian using VQE relaxed_qi = QuantumInstance(backend=Aer.get_backend("aer_simulator"), shots=1024) # Set up the variational quantum eigensolver (ansatz width is determined by the encoding) vqe = VQE( ansatz=RealAmplitudes(encoding.num_qubits), optimizer=SPSA(maxiter=50), quantum_instance=relaxed_qi, ) # Use semideterministic rounding, known as "Pauli rounding" # in https://arxiv.org/pdf/2111.03167v2.pdf # (This is the default if no rounding scheme is specified.) rounding_scheme = SemideterministicRounding() # Construct the optimizer qrao = QuantumRandomAccessOptimizer( encoding=encoding, min_eigen_solver=vqe, rounding_scheme=rounding_scheme ) # Solve the optimization problem results = qrao.solve(problem) qrao_fval = results.fval print(results) # relaxed function value results.relaxed_fval # optimal function value results.fval # optimal value results.x # status results.status print( f"The obtained solution places a partition between nodes {np.where(results.x == 0)[0]} " f"and nodes {np.where(results.x == 1)[0]}." ) results.relaxed_results results.rounding_results.samples # pylint: disable=wrong-import-order from qiskit_optimization.algorithms import CplexOptimizer cplex_optimizer = CplexOptimizer() cplex_results = cplex_optimizer.solve(problem) exact_fval = cplex_results.fval cplex_results approximation_ratio = qrao_fval / exact_fval print("QRAO Approximate Optimal Function Value:", qrao_fval) print("Exact Optimal Function Value:", exact_fval) print(f"Approximation Ratio: {approximation_ratio:.2f}") import qiskit.tools.jupyter # pylint: disable=unused-import,wrong-import-order %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/prototype-qrao
qiskit-community
from qiskit.utils import QuantumInstance from qiskit.algorithms.minimum_eigen_solvers import VQE from qiskit.circuit.library import RealAmplitudes from qiskit.algorithms.optimizers import SPSA from qiskit_aer import Aer from qrao import ( QuantumRandomAccessOptimizer, QuantumRandomAccessEncoding, SemideterministicRounding, MagicRounding, ) from qrao.utils import get_random_maxcut_qp # Generate a random QUBO in the form of a QuadraticProgram problem = get_random_maxcut_qp(degree=3, num_nodes=6, seed=1, draw=True) # Create and encode the problem using the (3,1,p)-QRAC encoding = QuantumRandomAccessEncoding(max_vars_per_qubit=3) encoding.encode(problem) backend = Aer.get_backend("aer_simulator") # Create a QuantumInstance for solving the relaxed Hamiltonian using VQE relaxed_qi = QuantumInstance(backend=backend, shots=500) # Create a QuantumInstance for magic rounding rounding_qi = QuantumInstance(backend=backend, shots=1000) # Set up the variational quantum eigensolver (ansatz width is determined by the encoding) vqe = VQE( ansatz=RealAmplitudes(encoding.num_qubits), optimizer=SPSA(maxiter=50), quantum_instance=relaxed_qi, ) # Use magic rounding rounding_scheme = MagicRounding(rounding_qi) # Construct the optimizer qrao = QuantumRandomAccessOptimizer( encoding=encoding, min_eigen_solver=vqe, rounding_scheme=rounding_scheme ) # Solve the optimization problem results = qrao.solve() print(results) # Calculate number of consolidated samples len(results.samples) # The first solution sample (which is not optimal in this case since the optimal # function value is 14.0) results.samples[0] print(f"The optimal function value is {results.fval} at {results.x}.") # Solve the relaxed problem manually relaxed_results, rounding_context = qrao.solve_relaxed() # Print the MinimumEigensolverResult object, from Terra print(relaxed_results) mr_results = MagicRounding(rounding_qi).round(rounding_context) print( f"Collected {len(mr_results.samples)} samples in {mr_results.time_taken} seconds." ) sdr_results = SemideterministicRounding().round(rounding_context) print(f"Performed semideterministic rounding ({len(sdr_results.samples)} sample).") print(f"Result: {sdr_results.samples[0]}") import qiskit.tools.jupyter # pylint: disable=unused-import,wrong-import-order %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/prototype-qrao
qiskit-community
# This code is part of Qiskit. # # (C) Copyright IBM 2019, 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Quantum Random Access Encoding module. Contains code dealing with QRACs (quantum random access codes) and preparation of such states. .. autosummary:: :toctree: ../stubs/ z_to_31p_qrac_basis_circuit z_to_21p_qrac_basis_circuit qrac_state_prep_1q qrac_state_prep_multiqubit QuantumRandomAccessEncoding """ from typing import Tuple, List, Dict, Optional, Union from collections import defaultdict from functools import reduce from itertools import chain import numpy as np import rustworkx as rx from qiskit import QuantumCircuit from qiskit.opflow import ( I, X, Y, Z, PauliSumOp, PrimitiveOp, CircuitOp, Zero, One, StateFn, CircuitStateFn, ) from qiskit.quantum_info import SparsePauliOp from qiskit_optimization.problems.quadratic_program import QuadraticProgram def _ceildiv(n: int, d: int) -> int: """Perform ceiling division in integer arithmetic >>> _ceildiv(0, 3) 0 >>> _ceildiv(1, 3) 1 >>> _ceildiv(3, 3) 1 >>> _ceildiv(4, 3) 2 """ return (n - 1) // d + 1 def z_to_31p_qrac_basis_circuit(basis: List[int]) -> QuantumCircuit: """Return the basis rotation corresponding to the (3,1,p)-QRAC Args: basis: 0, 1, 2, or 3 for each qubit Returns: The ``QuantumCircuit`` implementing the rotation. """ circ = QuantumCircuit(len(basis)) BETA = np.arccos(1 / np.sqrt(3)) for i, base in enumerate(reversed(basis)): if base == 0: circ.r(-BETA, -np.pi / 4, i) elif base == 1: circ.r(np.pi - BETA, np.pi / 4, i) elif base == 2: circ.r(np.pi + BETA, np.pi / 4, i) elif base == 3: circ.r(BETA, -np.pi / 4, i) else: raise ValueError(f"Unknown base: {base}") return circ def z_to_21p_qrac_basis_circuit(basis: List[int]) -> QuantumCircuit: """Return the basis rotation corresponding to the (2,1,p)-QRAC Args: basis: 0 or 1 for each qubit Returns: The ``QuantumCircuit`` implementing the rotation. """ circ = QuantumCircuit(len(basis)) for i, base in enumerate(reversed(basis)): if base == 0: circ.r(-1 * np.pi / 4, -np.pi / 2, i) elif base == 1: circ.r(-3 * np.pi / 4, -np.pi / 2, i) else: raise ValueError(f"Unknown base: {base}") return circ def qrac_state_prep_1q(*m: int) -> CircuitStateFn: """Prepare a single qubit QRAC state This function accepts 1, 2, or 3 arguments, in which case it generates a 1-QRAC, 2-QRAC, or 3-QRAC, respectively. Args: m: The data to be encoded. Each argument must be 0 or 1. Returns: The circuit state function. """ if len(m) not in (1, 2, 3): raise TypeError( f"qrac_state_prep_1q requires 1, 2, or 3 arguments, not {len(m)}." ) if not all(mi in (0, 1) for mi in m): raise ValueError("Each argument to qrac_state_prep_1q must be 0 or 1.") if len(m) == 3: # Prepare (3,1,p)-qrac # In the following lines, the input bits are XOR'd to match the # conventions used in the paper. # To understand why this transformation happens, # observe that the two states that define each magic basis # correspond to the same bitstrings but with a global bitflip. # Thus the three bits of information we use to construct these states are: # c0,c1 : two bits to pick one of four magic bases # c2: one bit to indicate which magic basis projector we are interested in. c0 = m[0] ^ m[1] ^ m[2] c1 = m[1] ^ m[2] c2 = m[0] ^ m[2] base = [2 * c1 + c2] cob = z_to_31p_qrac_basis_circuit(base) # This is a convention chosen to be consistent with https://arxiv.org/pdf/2111.03167v2.pdf # See SI:4 second paragraph and observe that π+ = |0X0|, π- = |1X1| sf = One if (c0) else Zero # Apply the z_to_magic_basis circuit to either |0> or |1> logical = CircuitOp(cob) @ sf elif len(m) == 2: # Prepare (2,1,p)-qrac # (00,01) or (10,11) c0 = m[0] # (00,11) or (01,10) c1 = m[0] ^ m[1] base = [c1] cob = z_to_21p_qrac_basis_circuit(base) # This is a convention chosen to be consistent with https://arxiv.org/pdf/2111.03167v2.pdf # See SI:4 second paragraph and observe that π+ = |0X0|, π- = |1X1| sf = One if (c0) else Zero # Apply the z_to_magic_basis circuit to either |0> or |1> logical = CircuitOp(cob) @ sf else: assert len(m) == 1 c0 = m[0] sf = One if (c0) else Zero logical = sf return logical.to_circuit_op() def qrac_state_prep_multiqubit( dvars: Union[Dict[int, int], List[int]], q2vars: List[List[int]], max_vars_per_qubit: int, ) -> CircuitStateFn: """ Prepare a multiqubit QRAC state. Args: dvars: state of each decision variable (0 or 1) """ remaining_dvars = set(dvars if isinstance(dvars, dict) else range(len(dvars))) ordered_bits = [] for qi_vars in q2vars: if len(qi_vars) > max_vars_per_qubit: raise ValueError( "Each qubit is expected to be associated with at most " f"`max_vars_per_qubit` ({max_vars_per_qubit}) variables, " f"not {len(qi_vars)} variables." ) if not qi_vars: # This probably actually doesn't cause any issues, but why support # it (and test this edge case) if we don't have to? raise ValueError( "There is a qubit without any decision variables assigned to it." ) qi_bits: List[int] = [] for dv in qi_vars: try: qi_bits.append(dvars[dv]) except (KeyError, IndexError): raise ValueError( f"Decision variable not included in dvars: {dv}" ) from None try: remaining_dvars.remove(dv) except KeyError: raise ValueError( f"Unused decision variable(s) in dvars: {remaining_dvars}" ) from None # Pad with zeros if there are fewer than `max_vars_per_qubit`. # NOTE: This results in everything being encoded as an n-QRAC, # even if there are fewer than n decision variables encoded in the qubit. # In the future, we plan to make the encoding "adaptive" so that the # optimal encoding is used on each qubit, based on the number of # decision variables assigned to that specific qubit. # However, we cannot do this until magic state rounding supports 2-QRACs. while len(qi_bits) < max_vars_per_qubit: qi_bits.append(0) ordered_bits.append(qi_bits) if remaining_dvars: raise ValueError(f"Not all dvars were included in q2vars: {remaining_dvars}") qracs = [qrac_state_prep_1q(*qi_bits) for qi_bits in ordered_bits] logical = reduce(lambda x, y: x ^ y, qracs) return logical def q2vars_from_var2op(var2op: Dict[int, Tuple[int, PrimitiveOp]]) -> List[List[int]]: """Calculate q2vars given var2op""" num_qubits = max(qubit_index for qubit_index, _ in var2op.values()) + 1 q2vars: List[List[int]] = [[] for i in range(num_qubits)] for var, (q, _) in var2op.items(): q2vars[q].append(var) return q2vars class QuantumRandomAccessEncoding: """This class specifies a Quantum Random Access Code that can be used to encode the binary variables of a QUBO (quadratic unconstrained binary optimization problem). Args: max_vars_per_qubit: maximum possible compression ratio. Supported values are 1, 2, or 3. """ # This defines the convention of the Pauli operators (and their ordering) # for each encoding. OPERATORS = ( (Z,), # (1,1,1) QRAC (X, Z), # (2,1,p) QRAC, p ≈ 0.85 (X, Y, Z), # (3,1,p) QRAC, p ≈ 0.79 ) def __init__(self, max_vars_per_qubit: int = 3): if max_vars_per_qubit not in (1, 2, 3): raise ValueError("max_vars_per_qubit must be 1, 2, or 3") self._ops = self.OPERATORS[max_vars_per_qubit - 1] self._qubit_op: Optional[PauliSumOp] = None self._offset: Optional[float] = None self._problem: Optional[QuadraticProgram] = None self._var2op: Dict[int, Tuple[int, PrimitiveOp]] = {} self._q2vars: List[List[int]] = [] self._frozen = False @property def num_qubits(self) -> int: """Number of qubits""" return len(self._q2vars) @property def num_vars(self) -> int: """Number of decision variables""" return len(self._var2op) @property def max_vars_per_qubit(self) -> int: """Maximum number of variables per qubit This is set in the constructor and controls the maximum compression ratio """ return len(self._ops) @property def var2op(self) -> Dict[int, Tuple[int, PrimitiveOp]]: """Maps each decision variable to ``(qubit_index, operator)``""" return self._var2op @property def q2vars(self) -> List[List[int]]: """Each element contains the list of decision variable indice(s) encoded on that qubit""" return self._q2vars @property def compression_ratio(self) -> float: """Compression ratio Number of decision variables divided by number of qubits """ return self.num_vars / self.num_qubits @property def minimum_recovery_probability(self) -> float: """Minimum recovery probability, as set by ``max_vars_per_qubit``""" n = self.max_vars_per_qubit return (1 + 1 / np.sqrt(n)) / 2 @property def qubit_op(self) -> PauliSumOp: """Relaxed Hamiltonian operator""" if self._qubit_op is None: raise AttributeError( "No objective function has been provided from which a " "qubit Hamiltonian can be constructed. Please use the " "encode method if you wish to manually compile " "this field." ) return self._qubit_op @property def offset(self) -> float: """Relaxed Hamiltonian offset""" if self._offset is None: raise AttributeError( "No objective function has been provided from which a " "qubit Hamiltonian can be constructed. Please use the " "encode method if you wish to manually compile " "this field." ) return self._offset @property def problem(self) -> QuadraticProgram: """The ``QuadraticProgram`` used as basis for the encoding""" if self._problem is None: raise AttributeError( "No quadratic program has been associated with this object. " "Please use the encode method if you wish to do so." ) return self._problem def _add_variables(self, variables: List[int]) -> None: self.ensure_thawed() # NOTE: If this is called multiple times, it *always* adds an # additional qubit (see final line), even if aggregating them into a # single call would have resulted in fewer qubits. if self._qubit_op is not None: raise RuntimeError( "_add_variables() cannot be called once terms have been added " "to the operator, as the number of qubits must thereafter " "remain fixed." ) if not variables: return if len(variables) != len(set(variables)): raise ValueError("Added variables must be unique") for v in variables: if v in self._var2op: raise ValueError("Added variables cannot collide with existing ones") # Modify the object now that error checking is complete. n = len(self._ops) old_num_qubits = len(self._q2vars) num_new_qubits = _ceildiv(len(variables), n) # Populate self._var2op and self._q2vars for _ in range(num_new_qubits): self._q2vars.append([]) for i, v in enumerate(variables): qubit, op = divmod(i, n) qubit_index = old_num_qubits + qubit assert v not in self._var2op # was checked above self._var2op[v] = (qubit_index, self._ops[op]) self._q2vars[qubit_index].append(v) def _add_term(self, w: float, *variables: int) -> None: self.ensure_thawed() # Eq. (31) in https://arxiv.org/abs/2111.03167v2 assumes a weight-2 # Pauli operator. To generalize, we replace the `d` in that equation # with `d_prime`, defined as follows: d_prime = np.sqrt(self.max_vars_per_qubit) ** len(variables) op = self.term2op(*variables).mul(w * d_prime) # We perform the following short-circuit *after* calling term2op so at # least we have confirmed that the user provided a valid variables list. if w == 0.0: return if self._qubit_op is None: self._qubit_op = op else: self._qubit_op += op def term2op(self, *variables: int) -> PauliSumOp: """Construct a ``PauliSumOp`` that is a product of encoded decision ``variable``\\(s). The decision variables provided must all be encoded on different qubits. """ ops = [I] * self.num_qubits done = set() for x in variables: pos, op = self._var2op[x] if pos in done: raise RuntimeError(f"Collision of variables: {variables}") ops[pos] = op done.add(pos) pauli_op = reduce(lambda x, y: x ^ y, ops) # Convert from PauliOp to PauliSumOp return PauliSumOp(SparsePauliOp(pauli_op.primitive, coeffs=[pauli_op.coeff])) @staticmethod def _generate_ising_terms( problem: QuadraticProgram, ) -> Tuple[float, np.ndarray, np.ndarray]: num_vars = problem.get_num_vars() # set a sign corresponding to a maximized or minimized problem: # 1 is for minimized problem, -1 is for maximized problem. sense = problem.objective.sense.value # convert a constant part of the objective function into Hamiltonian. offset = problem.objective.constant * sense # convert linear parts of the objective function into Hamiltonian. linear = np.zeros(num_vars) for idx, coef in problem.objective.linear.to_dict().items(): assert isinstance(idx, int) # hint for mypy weight = coef * sense / 2 linear[idx] -= weight offset += weight # convert quadratic parts of the objective function into Hamiltonian. quad = np.zeros((num_vars, num_vars)) for (i, j), coef in problem.objective.quadratic.to_dict().items(): assert isinstance(i, int) # hint for mypy assert isinstance(j, int) # hint for mypy weight = coef * sense / 4 if i == j: linear[i] -= 2 * weight offset += 2 * weight else: quad[i, j] += weight linear[i] -= weight linear[j] -= weight offset += weight return offset, linear, quad @staticmethod def _find_variable_partition(quad: np.ndarray) -> Dict[int, List[int]]: num_nodes = quad.shape[0] assert quad.shape == (num_nodes, num_nodes) graph = rx.PyGraph() # type: ignore graph.add_nodes_from(range(num_nodes)) graph.add_edges_from_no_data(list(zip(*np.where(quad != 0)))) # type: ignore node2color = rx.graph_greedy_color(graph) # type: ignore color2node: Dict[int, List[int]] = defaultdict(list) for node, color in sorted(node2color.items()): color2node[color].append(node) return color2node def encode(self, problem: QuadraticProgram) -> None: """Encode the (n,1,p) QRAC relaxed Hamiltonian of this problem. We associate to each binary decision variable one bit of a (n,1,p) Quantum Random Access Code. This is done in such a way that the given problem's objective function commutes with the encoding. After being called, the object will have the following attributes: qubit_op: The qubit operator encoding the input QuadraticProgram. offset: The constant value in the encoded Hamiltonian. problem: The ``problem`` used for encoding. Inputs: problem: A QuadraticProgram object encoding a QUBO optimization problem Raises: RuntimeError: if the ``problem`` isn't a QUBO or if the current object has been used already """ # Ensure fresh object if self.num_qubits > 0: raise RuntimeError( "Must call encode() on an Encoding that has not been used already" ) # if problem has variables that are not binary, raise an error if problem.get_num_vars() > problem.get_num_binary_vars(): raise RuntimeError( "The type of all variables must be binary. " "You can use `QuadraticProgramToQubo` converter " "to convert integer variables to binary variables. " "If the problem contains continuous variables, `qrao` " "cannot handle it." ) # if constraints exist, raise an error if problem.linear_constraints or problem.quadratic_constraints: raise RuntimeError( "There must be no constraint in the problem. " "You can use `QuadraticProgramToQubo` converter to convert " "constraints to penalty terms of the objective function." ) num_vars = problem.get_num_vars() # Generate the decision variable terms in terms of Ising variables (+1 or -1) offset, linear, quad = self._generate_ising_terms(problem) # Find variable partition (a graph coloring is sufficient) variable_partition = self._find_variable_partition(quad) # The other methods of the current class allow for the variables to # have arbitrary integer indices [i.e., they need not correspond to # range(num_vars)], and the tests corresponding to this file ensure # that this works. However, the current method is a high-level one # that takes a QuadraticProgram, which always has its variables # numbered sequentially. Furthermore, other portions of the QRAO code # base [most notably the assignment of variable_ops in solve_relaxed() # and the corresponding result objects] assume that the variables are # numbered from 0 to (num_vars - 1). So we enforce that assumption # here, both as a way of documenting it and to make sure # _find_variable_partition() returns a sensible result (in case the # user overrides it). assert sorted(chain.from_iterable(variable_partition.values())) == list( range(num_vars) ) # generate a Hamiltonian for _, v in sorted(variable_partition.items()): self._add_variables(sorted(v)) for i in range(num_vars): w = linear[i] if w != 0: self._add_term(w, i) for i in range(num_vars): for j in range(num_vars): w = quad[i, j] if w != 0: self._add_term(w, i, j) self._offset = offset self._problem = problem # This is technically optional and can wait until the optimizer is # constructed, but there's really no reason not to freeze # immediately. self.freeze() def freeze(self): """Freeze the object to prevent further modification. Once an instance of this class is frozen, ``_add_variables`` and ``_add_term`` can no longer be called. This operation is idempotent. There is no way to undo it, as it exists to allow another object to rely on this one not changing its state going forward without having to make a copy as a distinct object. """ if self._frozen is False: self._qubit_op = self._qubit_op.reduce() self._frozen = True @property def frozen(self) -> bool: """``True`` if the object can no longer be modified, ``False`` otherwise.""" return self._frozen def ensure_thawed(self) -> None: """Raise a ``RuntimeError`` if the object is frozen and thus cannot be modified.""" if self._frozen: raise RuntimeError("Cannot modify an encoding that has been frozen") def state_prep(self, dvars: Union[Dict[int, int], List[int]]) -> CircuitStateFn: """Prepare a multiqubit QRAC state.""" return qrac_state_prep_multiqubit(dvars, self.q2vars, self.max_vars_per_qubit) class EncodingCommutationVerifier: """Class for verifying that the relaxation commutes with the objective function See also the "check encoding problem commutation" how-to notebook. """ def __init__(self, encoding: QuantumRandomAccessEncoding): self._encoding = encoding def __len__(self) -> int: return 2**self._encoding.num_vars def __iter__(self): for i in range(len(self)): yield self[i] def __getitem__(self, i: int) -> Tuple[str, float, float]: if i not in range(len(self)): raise IndexError(f"Index out of range: {i}") encoding = self._encoding str_dvars = ("{0:0" + str(encoding.num_vars) + "b}").format(i) dvars = [int(b) for b in str_dvars] encoded_bitstr = encoding.state_prep(dvars) # Offset accounts for the value of the encoded Hamiltonian's # identity coefficient. This term need not be evaluated directly as # Tr[I•rho] is always 1. offset = encoding.offset # Evaluate Un-encoded Problem # ======================== # `sense` accounts for sign flips depending on whether # we are minimizing or maximizing the objective function problem = encoding.problem sense = problem.objective.sense.value obj_val = problem.objective.evaluate(dvars) * sense # Evaluate Encoded Problem # ======================== encoded_problem = encoding.qubit_op # H encoded_obj_val = ( np.real((~StateFn(encoded_problem) @ encoded_bitstr).eval()) + offset ) return (str_dvars, obj_val, encoded_obj_val)
https://github.com/qiskit-community/prototype-qrao
qiskit-community
# This code is part of Qiskit. # # (C) Copyright IBM 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Magic bases rounding""" from typing import List, Dict, Tuple, Optional from collections import defaultdict import numbers import time import warnings import numpy as np from qiskit import QuantumCircuit from qiskit.providers import Backend from qiskit.opflow import PrimitiveOp from qiskit.utils import QuantumInstance from .encoding import z_to_31p_qrac_basis_circuit, z_to_21p_qrac_basis_circuit from .rounding_common import ( RoundingSolutionSample, RoundingScheme, RoundingContext, RoundingResult, ) _invalid_backend_names = [ "aer_simulator_unitary", "aer_simulator_superop", "unitary_simulator", "pulse_simulator", ] def _backend_name(backend: Backend) -> str: """Return the backend name in a way that is agnostic to Backend version""" # See qiskit.utils.backend_utils in qiskit-terra for similar examples if backend.version <= 1: return backend.name() return backend.name def _is_original_statevector_simulator(backend: Backend) -> bool: """Return True if the original statevector simulator""" return _backend_name(backend) == "statevector_simulator" class MagicRoundingResult(RoundingResult): """Result of magic rounding""" def __init__( self, samples: List[RoundingSolutionSample], *, bases=None, basis_shots=None, basis_counts=None, time_taken=None, ): self._bases = bases self._basis_shots = basis_shots self._basis_counts = basis_counts super().__init__(samples, time_taken=time_taken) @property def bases(self): return self._bases @property def basis_shots(self): return self._basis_shots @property def basis_counts(self): return self._basis_counts class MagicRounding(RoundingScheme): """ "Magic rounding" method This method is described in https://arxiv.org/abs/2111.03167v2. """ _DECODING = { 3: ( # Eq. (8) {"0": [0, 0, 0], "1": [1, 1, 1]}, # I mu+ I, I mu- I {"0": [0, 1, 1], "1": [1, 0, 0]}, # X mu+ X, X mu- X {"0": [1, 0, 1], "1": [0, 1, 0]}, # Y mu+ Y, Y mu- Y {"0": [1, 1, 0], "1": [0, 0, 1]}, # Z mu+ Z, Z mu- Z ), 2: ( # Sec. VII {"0": [0, 0], "1": [1, 1]}, # I xi+ I, I xi- I {"0": [0, 1], "1": [1, 0]}, # X xi+ X, X xi- X ), 1: ({"0": [0], "1": [1]},), } # Pauli op string to label index in ops _OP_INDICES = {1: {"Z": 0}, 2: {"X": 0, "Z": 1}, 3: {"X": 0, "Y": 1, "Z": 2}} def __init__( self, quantum_instance: QuantumInstance, *, basis_sampling: str = "uniform", seed: Optional[int] = None, ): """ Args: quantum_instance: Provides the ``Backend`` for quantum execution and the ``shots`` count (i.e., the number of samples to collect from the magic bases). basis_sampling: Method to use for sampling the magic bases. Must be either ``"uniform"`` (default) or ``"weighted"``. ``"uniform"`` samples all magic bases uniformly, and is the method described in https://arxiv.org/abs/2111.03167v2. ``"weighted"`` attempts to choose bases strategically using the Pauli expectation values from the minimum eigensolver. However, the approximation bounds given in https://arxiv.org/abs/2111.03167v2 apply only to ``"uniform"`` sampling. seed: Seed for random number generator, which is used to sample the magic bases. """ if basis_sampling not in ("uniform", "weighted"): raise ValueError( f"'{basis_sampling}' is not an implemented sampling method. " "Please choose either 'uniform' or 'weighted'." ) self.quantum_instance = quantum_instance self.rng = np.random.RandomState(seed) self._basis_sampling = basis_sampling super().__init__() @property def shots(self) -> int: """Shots count as configured by the given ``quantum_instance``.""" return self.quantum_instance.run_config.shots @property def basis_sampling(self): """Basis sampling method (either ``"uniform"`` or ``"weighted"``).""" return self._basis_sampling @property def quantum_instance(self) -> QuantumInstance: """Provides the ``Backend`` and the ``shots`` (samples) count.""" return self._quantum_instance @quantum_instance.setter def quantum_instance(self, quantum_instance: QuantumInstance) -> None: backend_name = _backend_name(quantum_instance.backend) if backend_name in _invalid_backend_names: raise ValueError(f"{backend_name} is not supported.") if _is_original_statevector_simulator(quantum_instance.backend): warnings.warn( 'Use of "statevector_simulator" is discouraged because it effectively ' "brute-forces all possible solutions. We suggest using the newer " '"aer_simulator_statevector" instead.' ) self._quantum_instance = quantum_instance def _unpack_measurement_outcome( self, bits: str, basis: List[int], var2op: Dict[int, Tuple[int, PrimitiveOp]], vars_per_qubit: int, ) -> List[int]: output_bits = [] # iterate in order over decision variables # (assumes variables are numbered consecutively beginning with 0) for var in range(len(var2op)): # pylint: disable=consider-using-enumerate q, op = var2op[var] # get the decoding outcome index for the variable # corresponding to this Pauli op. op_index = self._OP_INDICES[vars_per_qubit][str(op)] # get the bits associated to this magic basis' # measurement outcomes bit_outcomes = self._DECODING[vars_per_qubit][basis[q]] # select which measurement outcome we observed # this gives up to 3 bits of information magic_bits = bit_outcomes[bits[q]] # Assign our variable's value depending on # which pauli our variable was associated to variable_value = magic_bits[op_index] output_bits.append(variable_value) return output_bits @staticmethod def _make_circuits( circ: QuantumCircuit, bases: List[List[int]], measure: bool, vars_per_qubit: int ) -> List[QuantumCircuit]: circuits = [] for basis in bases: if vars_per_qubit == 3: qc = circ.compose( z_to_31p_qrac_basis_circuit(basis).inverse(), inplace=False ) elif vars_per_qubit == 2: qc = circ.compose( z_to_21p_qrac_basis_circuit(basis).inverse(), inplace=False ) elif vars_per_qubit == 1: qc = circ.copy() if measure: qc.measure_all() circuits.append(qc) return circuits def _evaluate_magic_bases(self, circuit, bases, basis_shots, vars_per_qubit): """ Given a circuit you wish to measure, a list of magic bases to measure, and a list of the shots to use for each magic basis configuration. Measure the provided circuit in the magic bases given and return the counts dictionaries associated with each basis measurement. len(bases) == len(basis_shots) == len(basis_counts) """ measure = not _is_original_statevector_simulator(self.quantum_instance.backend) circuits = self._make_circuits(circuit, bases, measure, vars_per_qubit) # Execute each of the rotated circuits and collect the results # Batch the circuits into jobs where each group has the same number of # shots, so that you can wait for the queue as few times as possible if # using hardware. circuit_indices_by_shots: Dict[int, List[int]] = defaultdict(list) assert len(circuits) == len(basis_shots) for i, shots in enumerate(basis_shots): circuit_indices_by_shots[shots].append(i) basis_counts: List[Optional[Dict[str, int]]] = [None] * len(circuits) overall_shots = self.quantum_instance.run_config.shots try: for shots, indices in sorted( circuit_indices_by_shots.items(), reverse=True ): self.quantum_instance.set_config(shots=shots) result = self.quantum_instance.execute([circuits[i] for i in indices]) counts_list = result.get_counts() if not isinstance(counts_list, List): # This is the only case where this should happen, and that # it does at all (namely, when a single-element circuit # list is provided) is a weird API quirk of Qiskit. # https://github.com/Qiskit/qiskit-terra/issues/8103 assert len(indices) == 1 counts_list = [counts_list] assert len(indices) == len(counts_list) for i, counts in zip(indices, counts_list): basis_counts[i] = counts finally: # We've temporarily modified quantum_instance; now we restore it to # its initial state. self.quantum_instance.set_config(shots=overall_shots) assert None not in basis_counts # Process the outcomes and extract expectation of decision vars # The "statevector_simulator", unlike all the others, returns # probabilities instead of integer counts. So if probabilities are # detected, we rescale them. if any( any(not isinstance(x, numbers.Integral) for x in counts.values()) for counts in basis_counts ): basis_counts = [ {key: val * basis_shots[i] for key, val in counts.items()} for i, counts in enumerate(basis_counts) ] return basis_counts def _compute_dv_counts(self, basis_counts, bases, var2op, vars_per_qubit): """ Given a list of bases, basis_shots, and basis_counts, convert each observed bitstrings to its corresponding decision variable configuration. Return the counts of each decision variable configuration. """ dv_counts = {} for i, counts in enumerate(basis_counts): base = bases[i] # For each measurement outcome... for bitstr, count in counts.items(): # For each bit in the observed bitstring... soln = self._unpack_measurement_outcome( bitstr, base, var2op, vars_per_qubit ) soln = "".join([str(int(bit)) for bit in soln]) if soln in dv_counts: dv_counts[soln] += count else: dv_counts[soln] = count return dv_counts def _sample_bases_uniform(self, q2vars, vars_per_qubit): bases = [ self.rng.choice(2 ** (vars_per_qubit - 1), size=len(q2vars)).tolist() for _ in range(self.shots) ] bases, basis_shots = np.unique(bases, axis=0, return_counts=True) return bases, basis_shots def _sample_bases_weighted(self, q2vars, trace_values, vars_per_qubit): """Perform weighted sampling from the expectation values. The goal is to make smarter choices about which bases to measure in using the trace values. """ # First, we make sure all Pauli expectation values have absolute value # at most 1. Otherwise, some of the probabilities computed below might # be negative. tv = np.clip(trace_values, -1, 1) # basis_probs will have num_qubits number of elements. # Each element will be a list of length 4 specifying the # probability of picking the corresponding magic basis on that qubit. basis_probs = [] for dvars in q2vars: if vars_per_qubit == 3: x = 0.5 * (1 - tv[dvars[0]]) y = 0.5 * (1 - tv[dvars[1]]) if (len(dvars) > 1) else 0 z = 0.5 * (1 - tv[dvars[2]]) if (len(dvars) > 2) else 0 # ppp: mu± = .5(I ± 1/sqrt(3)( X + Y + Z)) # pmm: X mu± X = .5(I ± 1/sqrt(3)( X - Y - Z)) # mpm: Y mu± Y = .5(I ± 1/sqrt(3)(-X + Y - Z)) # mmp: Z mu± Z = .5(I ± 1/sqrt(3)(-X - Y + Z)) # fmt: off ppp_mmm = x * y * z + (1-x) * (1-y) * (1-z) pmm_mpp = x * (1-y) * (1-z) + (1-x) * y * z mpm_pmp = (1-x) * y * (1-z) + x * (1-y) * z ppm_mmp = x * y * (1-z) + (1-x) * (1-y) * z # fmt: on basis_probs.append([ppp_mmm, pmm_mpp, mpm_pmp, ppm_mmp]) elif vars_per_qubit == 2: x = 0.5 * (1 - tv[dvars[0]]) z = 0.5 * (1 - tv[dvars[1]]) if (len(dvars) > 1) else 0 # pp: xi± = .5(I ± 1/sqrt(2)( X + Z )) # pm: X xi± X = .5(I ± 1/sqrt(2)( X - Z )) # fmt: off pp_mm = x * z + (1-x) * (1-z) pm_mp = x * (1-z) + (1-x) * z # fmt: on basis_probs.append([pp_mm, pm_mp]) elif vars_per_qubit == 1: basis_probs.append([1.0]) bases = [ [ self.rng.choice(2 ** (vars_per_qubit - 1), p=probs) for probs in basis_probs ] for _ in range(self.shots) ] bases, basis_shots = np.unique(bases, axis=0, return_counts=True) return bases, basis_shots def round(self, ctx: RoundingContext) -> MagicRoundingResult: """Perform magic rounding""" start_time = time.time() trace_values = ctx.trace_values circuit = ctx.circuit if circuit is None: raise NotImplementedError( "Magic rounding requires a circuit to be available. Perhaps try " "semideterministic rounding instead." ) # We've already checked that it is one of these two in the constructor if self.basis_sampling == "uniform": bases, basis_shots = self._sample_bases_uniform( ctx.q2vars, ctx._vars_per_qubit ) elif self.basis_sampling == "weighted": if trace_values is None: raise NotImplementedError( "Magic rounding with weighted sampling requires the trace values " "to be available, but they are not." ) bases, basis_shots = self._sample_bases_weighted( ctx.q2vars, trace_values, ctx._vars_per_qubit ) else: # pragma: no cover raise NotImplementedError( f'No such basis sampling method: "{self.basis_sampling}".' ) assert self.shots == np.sum(basis_shots) # For each of the Magic Bases sampled above, measure # the appropriate number of times (given by basis_shots) # and return the circuit results basis_counts = self._evaluate_magic_bases( circuit, bases, basis_shots, ctx._vars_per_qubit ) # keys will be configurations of decision variables # values will be total number of observations. soln_counts = self._compute_dv_counts( basis_counts, bases, ctx.var2op, ctx._vars_per_qubit ) soln_samples = [ RoundingSolutionSample( x=np.asarray([int(bit) for bit in soln]), probability=count / self.shots, ) for soln, count in soln_counts.items() ] assert np.isclose( sum(soln_counts.values()), self.shots ), f"{sum(soln_counts.values())} != {self.shots}" assert len(bases) == len(basis_shots) == len(basis_counts) stop_time = time.time() return MagicRoundingResult( samples=soln_samples, bases=bases, basis_shots=basis_shots, basis_counts=basis_counts, time_taken=stop_time - start_time, )