repo
stringclasses
900 values
file
stringclasses
754 values
content
stringlengths
4
215k
https://github.com/mett29/Shor-s-Algorithm
mett29
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/Cortexelus/qubit-audio-synthesis
Cortexelus
import numpy as np pi = np.pi import matplotlib.pyplot as plt import librosa %matplotlib inline # Importing standard Qiskit libraries and configuring account from qiskit import QuantumCircuit, execute, Aer, IBMQ, ClassicalRegister, QuantumRegister from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * from qiskit.quantum_info import Pauli, state_fidelity, basis_state, process_fidelity from qiskit.providers.aer import StatevectorSimulator import soundfile as sf # Loading your IBM Q account(s) provider = IBMQ.load_account() # Construct quantum circuit sr = 44100 # sample rate of audio f = 90 # frequency n = int(np.ceil(sr/f)) # number of samples in wavetable print(n) qclist = [] for i in range(n): # for evey sample qc = QuantumCircuit(1,1) # phase clock qc.h(0) qc.ry(i/n * 2*pi,0) # begin "creative" section.. # make an arbitrary quantum circuit here qc.rz(3.6 * i/n * 9*pi,0) qc.rx(7 * i/n * 0.9*pi,0) qc.s(0) # ..end "creative" section # the output is the amplitude of the statevector # todo: collapse to classical register when running on real computer qclist.append(qc) # Select the StatevectorSimulator from the Aer provider simulator = Aer.get_backend('statevector_simulator') # Execute and get counts result = execute(qclist, simulator).result() # convert statevector results into a list of magnitudes wavetable = [] for i in range(n): sv = result.get_statevector(qclist[i]) mag = np.power(np.abs(sv),2) assert mag[0]+mag[1]-1 < 1e-9 wavetable.append(mag[0]) plt.plot(wavetable) ## add noise to the waveform ## by simulating multiple shots ## you could also achieve this by collapsing the output qubit statevector to a classical register ## which you need to do if you're running it on a real quantum computer shots = 10 wavetable_r = [] for i in range(len(wavetable)): mag = wavetable[i] r = np.random.binomial(shots,mag,1)/shots wavetable_r.append(r) plt.plot(wavetable_r) # repeat the waveform to fill an audio file # use the clean one # w = wavetable # use the noisy one w = wavetable_r ylen = 5 # the output wave file is __ seconds long ysamps = ylen * sr # the length of the output wave file in samples yreps = int(np.ceil(ysamps / len(w))) # how many repeats of the waveform w = np.tile(np.squeeze(np.array(w)), yreps) print(yreps, w.shape) w = w[:ysamps] # trim #print(w.shape) plt.plot(w) plt.show() # normalize w -= 0.5 w /= np.max(np.abs(w)) print(w.shape) # write to wave sf.write('quantum_test.wav', w, 44100, 'PCM_24')
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
%matplotlib inline from qiskit import * from qiskit.visualization import * from qiskit.tools.monitor import * # Let's create a circuit to put a state in superposition and measure it circ = QuantumCircuit(1,1) # We use one qubit and also one classical bit for the measure result circ.h(0) #We apply the H gate circ.measure(range(1),range(1)) # We measure circ.draw(output='mpl') #We draw the circuit print(circ.qasm()) # Executing on the local simulator backend_sim = Aer.get_backend('qasm_simulator') # We choose the backend job_sim = execute(circ, backend_sim, shots=1024) # We execute the circuit, selecting the number of repetitions or 'shots' result_sim = job_sim.result() # We collect the results counts = result_sim.get_counts(circ) # We obtain the frequency of each result and we show them print(counts) plot_histogram(counts) # Execution to the get the statevector circ2 = QuantumCircuit(1,1) circ2.h(0) backend = Aer.get_backend('statevector_simulator') # We change the backend job = execute(circ2, backend) # We execute the circuit with the new simulator. Now, we do not need repetitions result = job.result() # We collect the results and access the stavector outputstate = result.get_statevector(circ2) print(outputstate) backend = Aer.get_backend('unitary_simulator') # We change the backend again job = execute(circ2, backend) # We execute the circuit result = job.result() # We collect the results and obtain the matrix unitary = result.get_unitary() print(unitary) # Connecting to the real quantum computers provider = IBMQ.load_account() # We load our account provider.backends() # We retrieve the backends to check their status for b in provider.backends(): print(b.status().to_dict()) # Executing on the IBM Q Experience simulator backend_sim = provider.get_backend('ibmq_qasm_simulator') # We choose the backend job_sim = execute(circ, backend_sim, shots=1024) # We execute the circuit, selecting the number of repetitions or 'shots' result_sim = job_sim.result() # We collect the results counts = result_sim.get_counts(circ) # We obtain the frequency of each result and we show them print(counts) plot_histogram(counts) # Executing on the quantum computer backend = provider.get_backend('ibmq_armonk') job_exp = execute(circ, backend=backend) job_monitor(job_exp) result_exp = job_exp.result() counts_exp = result_exp.get_counts(circ) plot_histogram([counts_exp,counts], legend=['Device', 'Simulator'])
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
%matplotlib inline from qiskit import * from qiskit.visualization import * from qiskit.tools.monitor import * circ_random = QuantumCircuit(1,1) # We need qubit and one classical bit circ_random.h(0) #We apply the H gate circ_random.measure(range(1),range(1)) # Measure circ_random.draw(output='mpl') n = 100 # Number of bits that we are going to use # Alice generates n random bits (some of these bits will form the key) backend = Aer.get_backend('qasm_simulator') job = execute(circ_random, backend, shots=n, memory = True) # We set the 'memory' parameter to true to be able to access the string of results bits_alice = [int(q) for q in job.result().get_memory()] print(bits_alice) # Alice randomly chooses the bases in which she is going to measure job = execute(circ_random, backend, shots=n, memory = True) basis_alice = [int(q) for q in job.result().get_memory()] print(basis_alice) # Bob also chooses at random the bases in which he will measure job = execute(circ_random, backend, shots=n, memory = True) basis_bob = [int(q) for q in job.result().get_memory()] print(basis_bob) # Now, Alice codes each bit of her initial string as a qubit and sends it to Bob, who measures in his basis bits_bob = [] for i in range(n): circ_send = QuantumCircuit(1,1) if bits_alice[i]: # Alice has to send '1' circ_send.x(0) if basis_alice[i]: # Alice codes in basis |+>, |-> circ_send.h(0) # Alice sends the qubit to Bob and he measures if basis_bob[i]: # Bob has to measure in basis |+>, |-> circ_send.h(0) circ_send.measure(0,0) job = execute(circ_send, backend, shots = 1, memory = True) bits_bob.append(int(job.result().get_memory()[0])) print(bits_bob) # Bob tells Alice the basis he used for his measurements # Alice confirms which of the basis are correct key = [] for i in range(n): if basis_alice[i] == basis_bob[i]: key.append(bits_bob[i]) print("Key length", len(key)) print(key)
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
%matplotlib inline from qiskit import * from qiskit.visualization import * from qiskit.tools.monitor import * circ_bell = QuantumCircuit(2,2) # We need two qubits and two classical bits (for the measurements) circ_bell.h(0) # We apply the H gate on the first qubit circ_bell.cx(0,1) # We apply the CNOT gate with control on the first qubit and target on the second circ_bell.measure(range(2),range(2)) # Measurement circ_bell.draw(output='mpl') backend = Aer.get_backend('qasm_simulator') job = execute(circ_bell, backend, shots=1000) counts = job.result().get_counts() print(counts) circ_bell2 = QuantumCircuit(2) circ_bell2.h(0) circ_bell2.cx(0,1) backend = Aer.get_backend('statevector_simulator') job = execute(circ_bell2, backend) state = job.result().get_statevector() for i in range(4): s = format(i,"b") # Convert to binary s = (2-len(s))*"0"+s # Prepend zeroes if needed print("Amplitude of",s,"=",state[i]) print() for i in range(4): s = format(i,"b") # Convert to binary s = (2-len(s))*"0"+s # Prepend zeroes if needed print("Probability of",s,"=",abs(state[i])**2) provider = IBMQ.load_account() backend_overview() backend_monitor(provider.get_backend("ibmq_ourense")) from qiskit.providers.ibmq import least_busy # We execute on the least busy device (among the actual quantum computers) backend = least_busy(provider.backends(operational = True, simulator=False, status_msg='active', filters=lambda x: x.configuration().n_qubits > 1)) print("We are executing on...",backend) print("It has",backend.status().pending_jobs,"pending jobs") job_exp = execute(circ_bell, backend=backend) job_monitor(job_exp) result_exp = job_exp.result() counts_exp = result_exp.get_counts(circ_bell) plot_histogram([counts_exp,counts], legend=['Device', 'Simulator'])
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
#%matplotlib inline from qiskit import * from qiskit.tools.monitor import * from qiskit.providers.ibmq import least_busy import numpy as np #Function to create the circuits for the CHSH game def CHSH_circuit(x,y,a0=0,a1=np.pi/2,b0=np.pi/4,b1=-np.pi/4): #x: bit received by Alice #y: bit received by Bob #a0: measure angle used by Alice when she receives 0 #a1: measure angle used by Alice when she receives 1 #b0: measure angle used by Bob when he receives 0 #b1: measure angle used by Bob when he receives 1 circ = QuantumCircuit(2,2) # First, we create a Bell pair circ.h(0) circ.cx(0,1) # Now, we apply rotations for Alice and Bob depending on the bits they have received if(x==0): circ.ry(a0,0) else: circ.ry(a1,0) if(y==0): circ.ry(b0,1) else: circ.ry(b1,1) # We measure circ.measure(range(2),range(2)) # Medimos return circ def winning_probability(backend, shots = 8192, a0=0,a1=np.pi/2,b0=np.pi/4,b1=-np.pi/4): total = 0 circuits = [CHSH_circuit(0,0,a0,a1,b0,b1), CHSH_circuit(0,1,a0,a1,b0,b1), CHSH_circuit(1,0,a0,a1,b0,b1), CHSH_circuit(1,1,a0,a1,b0,b1)] # We 'pack' four different circuits for execution job = execute(circuits, backend=backend, shots = shots) # For the first three circuits, the winning condition is that Alice's and Bob's outputs are equal for qc in circuits[0:3]: counts = job.result().get_counts(qc) if('00' in counts): total += counts['00'] if('11' in counts): total += counts['11'] # For the fourth circuit, Alice's and Bob's outputs must be different for them to win counts = job.result().get_counts(circuits[3]) if('01' in counts): total += counts['01'] if('10' in counts): total += counts['10'] return total/(4*shots) # Backend definition backend = Aer.get_backend('qasm_simulator') # Execution print(winning_probability(backend)) # Load the account provider = IBMQ.load_account() # We execute on the least busy device (among the actual quantum computers) backend = least_busy(provider.backends(operational = True, simulator=False, status_msg='active', filters=lambda x: x.configuration().n_qubits > 1)) print("We are executing on...",backend) print(winning_probability(backend))
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
%matplotlib inline from qiskit import * from qiskit.visualization import * from qiskit.tools.monitor import * import random, time # We will create a random qubit by directly assigning random amplitudes a1 = random.random()*2 -1 #Uniform number in [-1,1] a2 = random.random()*2 -1 b1 = random.random()*2 -1 b2 = random.random()*2 -1 # We need to normalize norm = (a1**2 + a2**2 + b1**2 + b2**2)**0.5 c1 = complex(a1/norm,a2/norm) #Amplitude for |0> c2 = complex(b1/norm,b2/norm) #Amplitude for |1> psi = QuantumRegister(1, name = 'psi') # The qubit to teleport bell = QuantumRegister(2, name = 'bell') # The shared entangled pair c = ClassicalRegister(2, name = 'c') # Two classical bits for the measures teleport = QuantumCircuit(psi,bell,c) # We create the circuit with the two quantum registers and the classical bits teleport.initialize([c1,c2],psi) # We set the amplitudes for Alice's quibt teleport.barrier() print("Alice's qubit is:") print(c1,"|0> + ", c2,"|1>") # Now we create the Bell pair teleport.h(bell[0]) teleport.cx(bell[0],bell[1]) teleport.barrier() # We apply CNOT to |psi> and Alice's part of the entangled pair # We also apply the H gate # Then, Alice measure her qubits and send the results to Bob teleport.cx(psi,bell[0]) teleport.h(psi) teleport.measure([psi[0],bell[0]],c) teleport.barrier() # Bob applies his gates depending on the values received from Alice teleport.cx(bell[0],bell[1]) teleport.cz(psi,bell[1]) teleport.draw(output='mpl') # We run the circuit and access the amplitudes to check that Bob got the qubit backend = Aer.get_backend('statevector_simulator') job = execute(teleport, backend) outputstate = job.result().get_statevector() print(outputstate) # We start by creating the Bell pair that Alice and Bob share bell = QuantumRegister(2, name = 'bell') # We need two qubits c = ClassicalRegister(2) # And two bits for the measurements dense = QuantumCircuit(bell,c) dense.h(bell[0]) dense.cx(bell[0],bell[1]) dense.barrier() # We randomly choose which bits to send b1 = random.randint(0,1) b2 = random.randint(0,1) print("Alice wants to send ",b1,b2) # And we apply the gates accordingly if(b2==1): dense.x(bell[0]) if(b1==1): dense.z(bell[0]) dense.barrier() dense.draw(output='mpl') # Alice sends her qubit to Bob, who applies his gates and measures dense.cx(bell[0],bell[1]) dense.h(bell[0]) dense.barrier() dense.measure(bell,c) dense.draw(output='mpl') # Let us run the circuit backend = Aer.get_backend('qasm_simulator') job = execute(dense, backend, shots = 1, memory = True) result = job.result().get_memory() print("Bob has received ",int(result[0][1]),int(result[0][0]))
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
%matplotlib inline from qiskit import * from qiskit.visualization import * from qiskit.tools.monitor import * n = 4 # Number of qubits that we are going to use in the oracle q = QuantumRegister(n, 'q') # The oracle qubits out = QuantumRegister(1, 'out') # Qubit for the oracle output c = ClassicalRegister(n, 'c') # Classical bits needed for the result of the measurement circ_init = QuantumCircuit(q,out,c) # Initial part of the circuit for i in range(n): circ_init.h(q[i]) # We apply H to all the oracle qubits circ_init.x(out) # We apply X and H to the output qubit circ_init.h(out) circ_init.barrier() # Visual barrier to separate the parts of the circuit circ_init.draw(output='mpl') circ_end = QuantumCircuit(q,out,c) circ_end.barrier() # Visual barrier to separate the parts of the circuit for i in range(n): circ_end.h(q[i]) # We apply H to all the oracle qubits circ_end.measure(q,c) circ_end.draw(output='mpl') # Oracle for a boolean function that always returns 1 const = QuantumCircuit(q,out,c) const.cx(q[0],out) const.x(q[0]) const.cx(q[0],out) const.x(q[0]) const.draw(output='mpl') # Oracle for a boolean function that returns 1 for half of the inputs bal = QuantumCircuit(q,out,c) bal.cx(q[0],out) bal.draw(output='mpl') circ_const = circ_init + const + circ_end circ_const.draw(output='mpl') backend = Aer.get_backend('qasm_simulator') job = execute(circ_const, backend, shots=10) counts = job.result().get_counts() print(counts) circ_bal = circ_init + bal + circ_end circ_bal.draw(output='mpl') job = execute(circ_bal, backend, shots=10) counts = job.result().get_counts() print(counts) from qiskit.providers.ibmq import least_busy provider = IBMQ.load_account() # We choose the least busy device backend = least_busy(provider.backends(operational = True, simulator=False, status_msg='active', filters=lambda x: x.configuration().n_qubits >= n+1)) print("We are using...",backend) print("It has",backend.status().pending_jobs,"pending jobs") # We send both circuits at a time circuits = [circ_const,circ_bal] job_exp = execute(circuits, backend=backend) job_monitor(job_exp) result_exp = job_exp.result() counts_const = result_exp.get_counts(circ_const) print("Results for the circuit with the constant function") print(counts_const) print() counts_equi = result_exp.get_counts(circ_bal) print("Results for the circuit with the balanced function") print(counts_equi)
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
%matplotlib inline from qiskit import * from qiskit.visualization import * from qiskit.tools.monitor import * import numpy as np def init_grover(q): circ = QuantumCircuit(q) n = len(q) circ.x(n-1) # The qubit that receives the oracle output must be set to |1> for i in range(n): circ.h(q[i]) circ.barrier() return circ def difussion(q): circ = QuantumCircuit(q) # Diffusion operator n = len(q) for i in range(n-1): circ.h(q[i]) for i in range(n-1): circ.x(q[i]) # To implement a multicontrolled Z we use a multicontrolled Z rotation mcz = QuantumCircuit(q, name = 'cZ') if(n>2): mcz.mcrz(np.pi,q[0:n-2],q[n-2]) else: mcz.z(q[0]) # If there is only input qubit for the oracle, we don't have controls circ.append(mcz.to_instruction(),q) for i in range(n-1): circ.x(q[i]) for i in range(n-1): circ.h(q[i]) circ.barrier() return circ def ones(q): # We will use a multicontrolled X gate circ = QuantumCircuit(q) n = len(q) circ.mcx(q[0:n-1],q[n-1]) return circ def grover(n, oracle, it = 10, measurement = True): q = QuantumRegister(n, name = 'q') # We create the quantum register if(measurement): c = ClassicalRegister(n-1,name='c') # We are only going to measure the qubits that are the input to the oracle circ = QuantumCircuit(q,c) # We create the circuit else: circ = QuantumCircuit(q) # Circuit without measurements circ += init_grover(q) # We add the initial part for _ in range(it): # We add it repetitions of the oracle plus the diffusion operator circ += oracle(q) circ += difussion(q) if(measurement): # Measurements circ.measure(q[0:n-1],c) return circ n = 3 circ_grover = grover(n,ones,1) circ_grover.draw(output = 'mpl') backend = Aer.get_backend('qasm_simulator') job = execute(circ_grover, backend) counts = job.result().get_counts() print(counts) import matplotlib.pyplot as plt n = 5 max_it = 20 shots = 1000 backend = Aer.get_backend('qasm_simulator') target=(n-1)*'1' # The marked element as a string, to retrieve its probability prob = [0.0 for _ in range(max_it+1)] for it in range(max_it+1): circ_grover2 = grover(n,ones,it) job = execute(circ_grover2, backend, shots = shots) counts = job.result().get_counts() if target in counts.keys(): prob[it]=counts[target]/shots else: prob[it] = 0 # Element not found iter = range(max_it+1) plt.xlabel('Iterations') plt.ylabel('Probability') plt.plot(iter,prob) plt.show()
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
%matplotlib inline from qiskit import * from qiskit.visualization import * from qiskit.tools.monitor import * from qiskit.aqua import * from qiskit.aqua.components.oracles import * from qiskit.aqua.algorithms import * oracle = TruthTableOracle("0101") oracle.construct_circuit().draw(output='mpl') dj = DeutschJozsa(oracle) dj.construct_circuit(measurement=True).draw(output='mpl') backend = Aer.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend) result = dj.run(quantum_instance) print(result) oracle2 = TruthTableOracle('00000000') dj2 = DeutschJozsa(oracle2) result = dj2.run(quantum_instance) print("The function is",result['result']) backend = Aer.get_backend('qasm_simulator') oracle3 = TruthTableOracle('0001') g = Grover(oracle3, iterations=1) result = g.run(quantum_instance) print(result) expression = '(x | y) & (~y | z) & (~x | ~z | w) & (~x | y | z | ~w)' oracle4 = LogicalExpressionOracle(expression) g2 = Grover(oracle4, iterations = 3) result = g2.run(quantum_instance) print(result) backend = Aer.get_backend('qasm_simulator') expression2 = '(x & y & z & w) | (~x & ~y & ~z & ~w)' #expression2 = '(x & y) | (~x & ~y)' oracle5 = LogicalExpressionOracle(expression2, optimization = True) g3 = Grover(oracle5, incremental = True) result = g3.run(quantum_instance) print(result)
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
%matplotlib inline from qiskit import * from qiskit.visualization import * from qiskit.tools.monitor import * from qiskit.aqua import * from qiskit.aqua.algorithms import * shor = Shor(N=15, a = 2) backend = Aer.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend) result = shor.run(quantum_instance) print(result) from math import gcd N=15 print("N=",N) for a in range(2,N): print() print("***** a=",a) print() f = gcd(N,a) if f==1: shor = Shor(N,a) result = shor.run(quantum_instance) print(result["factors"]) else: print("A factor of",N,"is",f)
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
import numpy as np from qiskit import Aer, IBMQ from qiskit.aqua import aqua_globals, QuantumInstance from qiskit.aqua.algorithms import QAOA from qiskit.aqua.components.optimizers import * from qiskit.quantum_info import Pauli from qiskit.aqua.operators import WeightedPauliOperator from qiskit.providers.aer.noise import NoiseModel provider = IBMQ.load_account() def get_operator(J,h,n): pauli_list = [] for (i,j) in J: # For each coefficient in J (couplings) we add a term J[i,j]Z_iZj x_p = np.zeros(n, dtype=np.bool) z_p = np.zeros(n, dtype=np.bool) z_p[n-1-i] = True z_p[n-1-j] = True pauli_list.append([J[(i,j)],Pauli(z_p, x_p)]) for i in h: # For each coefficient in h we add a term h[i]Z_i x_p = np.zeros(n, dtype=np.bool) z_p = np.zeros(n, dtype=np.bool) z_p[n-1-i] = True pauli_list.append([h[i],Pauli(z_p, x_p)]) return WeightedPauliOperator(paulis=pauli_list) # Edges of the graph J1 = {(0,1):1, (1,2):1, (2,3):1, (3,4):1, (4,0):1} h1 = {} n = 5 # Hamiltonian q_op =get_operator(J1,h1,n) print(q_op) q_op.print_details() rep = 10 backend = Aer.get_backend('statevector_simulator') quantum_instance = QuantumInstance(backend) p = 1 val = 0 for i in range(rep): print("----- ITERATION ",i, " ------") optimizer = COBYLA() qaoa = QAOA(q_op, optimizer, p=p) result = qaoa.run(quantum_instance) print("Optimal value", result['optimal_value']) val+=result['optimal_value'] print("----- AVERAGE -----") print("Average value",val/rep) p = 2 val = 0 for i in range(rep): print("----- ITERATION ",i, " ------") optimizer = COBYLA() qaoa = QAOA(q_op, optimizer, p=p) result = qaoa.run(quantum_instance) print("Optimal value", result['optimal_value']) val+=result['optimal_value'] print("----- AVERAGE -----") print("Average value",val/rep) rep = 10 backendIBM = provider.get_backend('ibmq_ourense') noise_model = NoiseModel.from_backend(backendIBM) coupling_map = backendIBM.configuration().coupling_map basis_gates = noise_model.basis_gates backend = Aer.get_backend("qasm_simulator") shots = 8192 optimization_level = 3 p = 1 quantum_instance = QuantumInstance(backend, shots = shots, optimization_level = optimization_level, noise_model = noise_model, basis_gates = basis_gates, coupling_map = coupling_map) p = 1 val = 0 for i in range(rep): print("----- ITERATION ",i, " ------") optimizer = COBYLA() qaoa = QAOA(q_op, optimizer, p=p) result = qaoa.run(quantum_instance) print("Optimal value", result['optimal_value']) val+=result['optimal_value'] print("----- AVERAGE -----") print("Average value",val/rep)
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
from qiskit.chemistry.drivers import PySCFDriver, UnitsType, Molecule from qiskit.chemistry.transformations import FermionicTransformation, FermionicQubitMappingType molecule = Molecule(geometry=[['H', [0., 0., 0.]], ['H', [0., 0., 0.735]]], charge=0, multiplicity=1) driver = PySCFDriver(molecule = molecule, unit=UnitsType.ANGSTROM, basis='sto3g') transformation = FermionicTransformation(qubit_mapping=FermionicQubitMappingType.JORDAN_WIGNER) from qiskit import Aer from qiskit.aqua import QuantumInstance from qiskit.chemistry.algorithms.ground_state_solvers.minimum_eigensolver_factories import VQEUCCSDFactory vqe_solver = VQEUCCSDFactory(QuantumInstance(Aer.get_backend('statevector_simulator'))) from qiskit.chemistry.algorithms.ground_state_solvers import GroundStateEigensolver calc = GroundStateEigensolver(transformation, vqe_solver) res = calc.solve(driver) print(res) from qiskit.aqua.algorithms import NumPyMinimumEigensolver numpy_solver = NumPyMinimumEigensolver() calc = GroundStateEigensolver(transformation, numpy_solver) res = calc.solve(driver) print(res) import numpy as np distances = np.linspace(0.25, 3.0, 30) exact_energies = [] vqe_energies = [] for dist in distances: molecule = Molecule(geometry=[['H', [0., 0., 0.]], ['H', [0., 0., dist]]], charge=0, multiplicity=1) driver = PySCFDriver(molecule = molecule, unit=UnitsType.ANGSTROM, basis='sto3g') # Exact solver calc = GroundStateEigensolver(transformation, numpy_solver) res = calc.solve(driver) exact_energies.append(res.total_energies) # VQE calc = GroundStateEigensolver(transformation, vqe_solver) res = calc.solve(driver) vqe_energies.append(res.total_energies) import matplotlib.pyplot as plt plt.plot(exact_energies, label = 'Exact solver') plt.plot(vqe_energies, label = 'VQE') plt.title('Dissociation profile') plt.xlabel('Interatomic distance') plt.legend() plt.ylabel('Energy');
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
import matplotlib.pyplot as plt import numpy as np from qiskit import Aer from qiskit.ml.datasets import breast_cancer from qiskit.circuit.library import ZZFeatureMap from qiskit.aqua import QuantumInstance from qiskit.aqua.algorithms import QSVM np.random.seed(2020) n = 30 # Training examples for class 0 mean = [0, 1] cov = [[0.1, 0], [0, 0.1]] A = (np.random.multivariate_normal(mean, cov, n)) x_A, y_A = A.T plt.plot(x_A, y_A, 'ro'); # Training examples for class 1 mean = [1, 0] cov = [[0.1, 0], [0, 0.1]] B = (np.random.multivariate_normal(mean, cov, n)) x_B, y_B = B.T plt.plot(x_B, y_B, 'bo'); feature_map = ZZFeatureMap(feature_dimension=2, reps=2, entanglement='linear') feature_map.draw() training_input = np.append(A,B,axis =0) training_labels = np.array([0]*n+[1]*n) # Training labels are 0 and 1 backend = Aer.get_backend('statevector_simulator') quantum_instance = QuantumInstance(backend) qsvm = QSVM(feature_map, quantum_instance = quantum_instance) qsvm.train(training_input,training_labels) n = 10 # Test examples for class 0 mean = [0, 1] cov = [[0.1, 0], [0, 0.1]] C = (np.random.multivariate_normal(mean, cov, n)) x_C, y_C = C.T plt.plot(x_C, y_C, 'ro'); # Test examples for class 1 mean = [1, 0] cov = [[0.05, 0], [0, 0.05]] D = (np.random.multivariate_normal(mean, cov, n)) x_D, y_D = D.T plt.plot(x_D, y_D, 'bo'); print("Prediction for examples in test class 0",qsvm.predict(C)) print("Prediction for examples in test class 1",qsvm.predict(D)) test_input = np.append(C,D,axis =0) test_labels = np.array([0]*n+[1]*n) print("Accuracy",qsvm.test(test_input,test_labels)) sample_Total, training_input, test_input, class_labels = breast_cancer( training_size=100, test_size=10, n=2, plot_data=True ) feature_map = ZZFeatureMap(feature_dimension=2, reps=1, entanglement='linear') feature_map.draw() qsvm = QSVM(feature_map, training_input, test_input) result = qsvm.run(quantum_instance) print("Accuracy: ", result['testing_accuracy']) feature_map = ZZFeatureMap(feature_dimension=2, reps=2, entanglement='linear') feature_map.draw() qsvm = QSVM(feature_map, training_input, test_input) result = qsvm.run(quantum_instance) print("Accuracy: ", result['testing_accuracy'])
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
import matplotlib.pyplot as plt import numpy as np from qiskit import Aer from qiskit.ml.datasets import breast_cancer from qiskit.circuit.library import ZZFeatureMap from qiskit.circuit.library.n_local.two_local import TwoLocal from qiskit.aqua import QuantumInstance from qiskit.aqua.algorithms import VQC from qiskit.aqua.components.optimizers import COBYLA feature_map = ZZFeatureMap(feature_dimension=2, reps=1, entanglement='linear') feature_map.draw(output="mpl") var_form = TwoLocal(num_qubits=2, rotation_blocks = 'ry', entanglement_blocks = 'cx', entanglement = 'linear', reps = 1) var_form.draw(output="mpl") sample_Total, training_input, test_input, class_labels = breast_cancer( training_size=100, test_size=10, n=2, plot_data=True ) backend = Aer.get_backend('statevector_simulator') quantum_instance = QuantumInstance(backend) optimizer = COBYLA() vqc = VQC(optimizer = optimizer, feature_map = feature_map, var_form = var_form, training_dataset = training_input, test_dataset = test_input) result = vqc.run(quantum_instance) print(result) feature_map = ZZFeatureMap(feature_dimension=2, reps=2, entanglement='linear') feature_map.draw(output="mpl") var_form = TwoLocal(num_qubits=2, rotation_blocks = 'ry', entanglement_blocks = 'cx', entanglement = 'linear', reps = 2) var_form.draw(output="mpl") vqc = VQC(optimizer = optimizer, feature_map = feature_map, var_form = var_form, training_dataset = training_input, test_dataset = test_input) result = vqc.run(quantum_instance) print(result)
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
%matplotlib inline import numpy as np import matplotlib.pyplot as plt from qiskit import Aer from qiskit.aqua import QuantumInstance from qiskit.aqua.algorithms import QGAN np.random.seed(2020) N = 1000 real_data = np.random.binomial(3,0.5,N) plt.hist(real_data, bins = 4); n = 2 num_qubits = [n] num_epochs = 100 batch_size = 100 bounds = [0,3] qgan = QGAN(data = real_data, num_qubits = num_qubits, batch_size = batch_size, num_epochs = num_epochs, bounds = bounds, seed = 2020) quantum_instance = QuantumInstance(backend=Aer.get_backend('statevector_simulator')) result = qgan.run(quantum_instance) samples_g, prob_g = qgan.generator.get_output(qgan.quantum_instance, shots=10000) plt.hist(range(4), weights = prob_g, bins = 4); plt.title("Loss function evolution") plt.plot(range(num_epochs), qgan.g_loss, label='Generator') plt.plot(range(num_epochs), qgan.d_loss, label='Discriminator') plt.legend() plt.show() plt.title('Relative entropy evolution') plt.plot(qgan.rel_entr) plt.show() import qiskit qiskit.__qiskit_version__
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
%matplotlib inline import numpy as np import matplotlib.pyplot as plt from qiskit import Aer from qiskit.aqua import QuantumInstance from qiskit.aqua.algorithms import QGAN np.random.seed(2020) N = 1000 real_data = np.random.binomial(3,0.5,N) plt.hist(real_data, bins = 4); n = 2 num_qubits = [n] num_epochs = 100 batch_size = 100 bounds = [0,3] qgan = QGAN(data = real_data, num_qubits = num_qubits, batch_size = batch_size, num_epochs = num_epochs, bounds = bounds, seed = 2020) quantum_instance = QuantumInstance(backend=Aer.get_backend('statevector_simulator')) result = qgan.run(quantum_instance) samples_g, prob_g = qgan.generator.get_output(qgan.quantum_instance, shots=10000) plt.hist(range(4), weights = prob_g, bins = 4); plt.title("Loss function evolution") plt.plot(range(num_epochs), qgan.g_loss, label='Generator') plt.plot(range(num_epochs), qgan.d_loss, label='Discriminator') plt.legend() plt.show() plt.title('Relative entropy evolution') plt.plot(qgan.rel_entr) plt.show() import qiskit qiskit.__qiskit_version__
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
# Importing standard Qiskit libraries from qiskit import QuantumCircuit, execute, Aer, IBMQ # Loading your IBM Q account(s) provider = IBMQ.load_account() n = 1000 circ = QuantumCircuit(n,n) circ.h(0) for i in range(1,n): circ.cx(0,i) circ.measure(range(n),range(n)) backend = Aer.get_backend("qasm_simulator") job = execute(circ,backend) print(job.result().get_counts())
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
%matplotlib inline import matplotlib.pyplot as plt from qiskit import QuantumCircuit, execute, Aer from qiskit.circuit.random import random_circuit n_circs = 10000 n_qubits = 4 n_layers = 30 freq = [] backend_m = Aer.get_backend("qasm_simulator") backend_s = Aer.get_backend("statevector_simulator") for _ in range(n_circs): #Generate a random circuit circ = random_circuit(n_qubits, n_layers, measure = False) #Sample one string from its output meas = QuantumCircuit(n_qubits,n_qubits) meas.measure(range(n_qubits),range(n_qubits)) circ_m = circ + meas job = execute(circ_m,backend = backend_m, shots = 1, memory = True) string = job.result().get_memory()[0] #Compute the exact probability of the string job = execute(circ, backend = backend_s) state = job.result().get_statevector() freq.append(abs(state[int(string,2)])**2) import numpy as np xs = np.linspace(0.0, 1.0, 100) dim = 2**n_qubits ys = xs*(dim**2)*np.exp(-dim*xs) plt.hist(freq, bins = 100, density = True) plt.plot(xs, ys, label='Theoretical') plt.show()
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
#Adding Two Numbers x=2+5 print(x) #Subtracting Two Numbers y=8-5 print(y) #Multiplying Two Numbers a=3*5 print(a) #Dividing Two Numbers b=8/4 print(b) #Calculate the Remainder r=4%3 print(r) #Exponent of a Number e=5**3 print(e) c1=1j*1j print(c1) #Initialize two complex numbers z=4+8j w=5-5j import numpy as np print("Real part of z is:", np.real(z)) print("Imaginary part of w is:", np.imag(w)) #Add two complex numbers add=z+w print(add) #Subtract two complex numbers sub=z-w print(sub) #complex conjugate of w print(w) print("Complex conjugate of w is:", np.conj(w)) #Calculating absolute values for z and w print(z) print("Norm/Absolute value of z is:", np.abs(z)) print(w) print("Norm/Absolute value of w is:", np.abs(w)) #Initialize a row vector row_vector=np.array([1, 2+2j, 3]) print(row_vector) #Initialize a column vector column_vector=np.array([[1],[2+2j],[3j]]) print(column_vector) # Define the 4x1 matrix version of a column vector A=np.array([[1],[4-5j],[5],[-3]]) # Define B as a 1x4 matrix B=np.array([1, 5, -4j, -1j]) # Compute <B|A> np.dot(B,A) M=np.array([[2-1j, -3], [-5j, 2]]) #Note how the brackets are placed! print(M) M=np.matrix([[2-1j, 3],[-5j, 2]]) print(M) #To calculate hermitian matrix simple follow: <your matrix>.H hermitian = M.H print(hermitian) #Use the np.kron method np.kron(M,M)
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
#Uncomment the below line #!pip install qiskit #!pip install qiskit[visualization] import numpy as np import qiskit qiskit.__qiskit_version__ #Import everything from qiskit from qiskit import * from qiskit.visualization import plot_bloch_vector plot_bloch_vector([0,0,1],title = 'spinup') plot_bloch_vector([1,0,0]) ket_zero = np.array([[1],[0]]) ket_one = np.array([[0],[1]]) np.kron(ket_one,ket_zero)
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
from qiskit import * from qiskit.visualization import plot_bloch_multivector # Let's do an X-gate on a |0> qubit qc=QuantumCircuit(1) qc.x(0) qc.draw('mpl')#mpl stands for the matplotlib argument # Let's see the result backend = Aer.get_backend('statevector_simulator') out = execute(qc, backend).result().get_statevector() print(out) # Do Y-gate on qubit 0 qc.y(0) # Do Z-gate on qubit 0 qc.z(0) qc.draw('mpl') #create circuit with three qubit qc = QuantumCircuit(3) # Apply H-gate to each qubit: for qubit in range(3): qc.h(qubit) # See the circuit: qc.draw('mpl') qc.i(0) qc.draw('mpl')
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
import numpy as np from qiskit import * qc = QuantumCircuit(3) # Apply H-gate to each qubit: for qubit in range(3): qc.h(qubit) # See the circuit: qc.draw('mpl') # Let's see the result backend = Aer.get_backend('statevector_simulator') out = execute(qc,backend).result().get_statevector() print(out) qc = QuantumCircuit(2) qc.h(0) qc.x(1) qc.draw('mpl') #create circuit with two qubit qc = QuantumCircuit(2) # Apply CNOT qc.cx(0,1) # See the circuit: qc.draw('mpl') #create two qubit circuit qc = QuantumCircuit(2) # Apply H-gate to the first: qc.h(0) qc.draw('mpl') # Let's see the result: backend = Aer.get_backend('statevector_simulator') final_state = execute(qc,backend).result().get_statevector() print(final_state) # Apply a CNOT: qc.cx(0,1) qc.draw('mpl') # Let's see the result: final_state = execute(qc,backend).result().get_statevector() print(final_state)
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
import numpy as np from qiskit import * %matplotlib inline from qiskit.tools.visualization import plot_histogram s = 101011 from qiskit import * qc = QuantumCircuit(6+1,6) qc.h([0,1,2,3,4,5]) qc.draw('mpl') qc.x(6) qc.h(6) qc.barrier() qc.draw('mpl') qc.cx(5, 6) qc.cx(3, 6) qc.cx(1, 6) qc.cx(0, 6) qc.barrier() qc.draw('mpl') qc.h([0,1,2,3,4,5]) qc.draw('mpl') qc.measure([0,1,2,3,4,5], [0,1,2,3,4,5]) qc.draw('mpl') simulator = Aer.get_backend('qasm_simulator') result = execute(qc, backend = simulator, shots = 1).result() counts =result.get_counts() print(counts)
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit import * from qiskit.tools.visualization import plot_histogram from IPython.display import display, Math, Latex from qiskit.visualization import plot_state_qsphere def BuildBell(x, y): U = QuantumCircuit(2) U.h(0) U.cx(0, 1) if x == 1: U.cz(0, 1) if y == 1: U.x(1) U = U.to_gate() U.name = 'Build Bell' #ctl_U = U.control() make it a controlled gate return U backend = BasicAer.get_backend('statevector_simulator') n = 2 #bell state 00 [x, y] = [0, 0] b00 = QuantumCircuit(n, n) b00.append(BuildBell(x, y), range(n)) #bell state 01 [x, y] = [0, 1] b01 = QuantumCircuit(n, n) b01.append(BuildBell(x, y), range(n)) #bell state 10 [x, y] = [1, 0] b10 = QuantumCircuit(n, n) b10.append(BuildBell(x, y), range(n)) #bell state 11 [x, y] = [1, 1] b11 = QuantumCircuit(n, n) b11.append(BuildBell(x, y), range(n)) bqs00 = execute(b00, backend).result() bqs01 = execute(b01, backend).result() bqs10 = execute(b10, backend).result() bqs11 = execute(b11, backend).result() #GENERAL CIRCUIT b_00 bxy = QuantumCircuit(n, n) bxy.h(0) bxy.cx(0, 1) bxy.measure(range(n), range(n)) backend = BasicAer.get_backend('qasm_simulator') atp = 1024 res = execute(bxy, backend=backend, shots=atp).result() ans = res.get_counts() bxy.draw('mpl') plot_histogram(ans) plot_state_qsphere(bqs00.get_statevector(b00)) #bell state 00 qsphere plot_state_qsphere(bqs01.get_statevector(b01)) #bell state 01 qsphere plot_state_qsphere(bqs10.get_statevector(b10)) #bell state 10 qsphere plot_state_qsphere(bqs11.get_statevector(b11)) #bell state 11 qsphere
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit import * from qiskit.tools.visualization import plot_histogram from IPython.display import display, Math, Latex def BuildGHZ(n): U = QuantumCircuit(n) U.h(0) for i in range(1, n): U.cx(0, i) U = U.to_gate() U.name = 'Build GHZ' #ctl_U = U.control() make it a controlled gate return U n = 5 mc = QuantumCircuit(n, n) U = BuildGHZ(n) mc.append(U, range(n)) mc.measure(range(n), range(n)) backend = BasicAer.get_backend('qasm_simulator') atp = 1024 res = execute(mc, backend=backend, shots=atp).result() ans = res.get_counts() mc.draw('mpl') plot_histogram(ans)
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
import numpy as np from numpy import linalg as LA from scipy.linalg import expm, sinm, cosm import matplotlib.pyplot as plt import pandas as pd import seaborn as sns import math from scipy import stats %matplotlib inline from IPython.display import Image, display, Math, Latex sns.set(color_codes=True) #number of vertices n = 4 #Define adjacency matrix A_Cn A = np.zeros((n, n)) for i in range(n): j1 = (i - 1)%n j2 = (i + 1)%n A[i][j1] = 1 A[i][j2] = 1 #Define our initial state Psi_a psi_a = np.zeros(n) psi_a[3] = 1 #Define the time t >= 0 t = math.pi/2 #Exponentiate or hamiltonian U_t = expm(1j*t*A) U_mt = expm(1j*(-t)*A) #Compute Psi_t psi_t = U_t @ psi_a #Compute the probabilities prob_t = abs(psi_t)**2 M_t = U_t*U_mt M_t = np.around(M_t, decimals = 3) M_t x = M_t[:, 0].real plt.bar(range(len(x)), x, tick_label=[0, 1, 2, 3]) plt.xlabel('Vertices') plt.ylabel('Probability')
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit import * from qiskit.tools.visualization import plot_histogram from IPython.display import display, Math, Latex def Decrement(n): U = QuantumCircuit(n) control = [x for x in range(n-1)] for k in range(n-1): U.x(control) U.mcx(control, control[-1]+1) U.x(control) control.pop() U.x(0) U = U.to_gate() U.name = 'Decrement' #ctl_U = U.control() make it a controlled gate return U n = 3 mc = QuantumCircuit(n, n) U = Decrement(n) mc.append(U, range(n)) mc.measure(range(n), range(n)) backend = BasicAer.get_backend('qasm_simulator') atp = 1024 res = execute(mc, backend=backend, shots=atp).result() ans = res.get_counts() mc.draw('mpl') plot_histogram(ans)
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit import IBMQ, BasicAer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.quantum_info import Statevector from qiskit.visualization import plot_state_qsphere from qiskit.visualization import plot_histogram from qiskit.tools.monitor import job_monitor from qiskit.tools.visualization import plot_histogram from IPython.display import display, Math, Latex #define a 1 qubit state |0> sv = Statevector.from_label('0') print('State_0 |x> = ', sv.data) #build a circuit with the H gate mycircuit = QuantumCircuit(1) mycircuit.h(0) #apply the circuit into |x> sv = sv.evolve(mycircuit) print('State_1 H|x> = ', sv.data) mycircuit.draw('mpl') ''' OUR FUNCTION F IS DEFINED AS n = 2 f(0, 0) = 0 f(0, 1) = 1 f(1, 0) = 1 f(1, 1) = 1 ''' #input size n = 2 #initialize qubits and measurement bits input_qubits = QuantumRegister(n+1) output_bits = ClassicalRegister(n) #create circuit my_circuit = QuantumCircuit(input_qubits, output_bits) #apply X on the last qubit my_circuit.x(n) #apply Hadamard on all qubits my_circuit.h(range(n+1)) my_circuit.barrier() #Apply Uf, these CNOT gates will mark the desired |x_i> my_circuit.cx(0, 1) my_circuit.cx(1, 2) my_circuit.cx(0, 1) my_circuit.barrier() #apply Hadamard on all qubits my_circuit.h(range(n+1)) my_circuit.measure(range(n), range(n)) #Backend classical simulation backend = BasicAer.get_backend('qasm_simulator') atp = 1024 res = execute(my_circuit, backend=backend, shots=atp).result() ans = res.get_counts() my_circuit.draw(output='mpl') #Quantum Backend #SOON# plot_histogram(ans) from qiskit import IBMQ IBMQ.load_account() provider = IBMQ.get_provider(group='open', project='main') backend = provider.get_backend('ibmq_vigo') job = execute(my_circuit, backend=backend) result = job.result().get_counts() plot_histogram(result)
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit import * from qiskit.providers.ibmq import least_busy from qiskit.tools.visualization import plot_histogram from IPython.display import display, Math, Latex def Increment(size): U = QuantumCircuit(size) control = [x for x in range(size-1)] for k in range(size-1): U.mcx(control, control[-1]+1) control.pop() U.x(0) U = U.to_gate() U.name = '--->' ctl_U = U.control() return ctl_U def Decrement(size): U = QuantumCircuit(size) control = [x for x in range(size-1)] for k in range(size-1): U.x(control) U.mcx(control, control[-1]+1) U.x(control) control.pop() U.x(0) U = U.to_gate() U.name = '<---' ctl_U = U.control() return ctl_U n = 2 steps = 2 graph = QuantumRegister(n+1) mes = ClassicalRegister(n) mcq = QuantumCircuit(graph, mes) #define U(t) for i in range(steps): mcq.h(n) mcq.append(Increment(n), [n]+list(range(0, n))) mcq.x(n) mcq.append(Decrement(n), [n]+list(range(0, n))) mcq.x(n) mcq.measure(range(n), range(n)) #mcq = transpile(mcq, basis_gates=['cx','u3'],optimization_level=3) mcq.draw('mpl') backend = BasicAer.get_backend('qasm_simulator') atp = 1024 res = execute(mcq, backend=backend, shots=atp).result() ans = res.get_counts() plot_histogram(ans) IBMQ.load_account() provider = IBMQ.get_provider(group='open', project='main') backend = provider.get_backend('ibmq_16_melbourne') job = execute(mcq, backend=backend) ans_quantum = job.result().get_counts() legend = ['QASM','ibmq_16_melbourne'] plot_histogram([ans,ans_quantum], legend=legend)
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, Aer, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * from qiskit.providers.aer import QasmSimulator # Loading your IBM Quantum account(s) provider = IBMQ.load_account() from qiskit.circuit.library.standard_gates import XGate, HGate from operator import * n = 3 N = 8 #2**n index_colour_table = {} colour_hash_map = {} index_colour_table = {'000':"yellow", '001':"red", '010':"blue", '011':"red", '100':"green", '101':"blue", '110':"orange", '111':"red"} colour_hash_map = {"yellow":'100', "red":'011', "blue":'000', "green":'001', "orange":'010'} def database_oracle(index_colour_table, colour_hash_map): circ_database = QuantumCircuit(n + n) for i in range(N): circ_data = QuantumCircuit(n) idx = bin(i)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion colour = index_colour_table[idx] colour_hash = colour_hash_map[colour][::-1] for j in range(n): if colour_hash[j] == '1': circ_data.x(j) # qiskit maps the rightmost bit as the 0th qubit -> qn, ..., q0 # we therefore reverse the index string -> q0, ..., qn data_gate = circ_data.to_gate(label=colour).control(num_ctrl_qubits=n, ctrl_state=idx, label="index-"+colour) circ_database.append(data_gate, list(range(n+n))) return circ_database # drawing the database oracle circuit print("Database Encoding") database_oracle(index_colour_table, colour_hash_map).draw() circ_data = QuantumCircuit(n) m = 4 idx = bin(m)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion colour = index_colour_table[idx] colour_hash = colour_hash_map[colour][::-1] for j in range(n): if colour_hash[j] == '1': circ_data.x(j) print("Internal colour encoding for the colour green (as an example)"); circ_data.draw() def oracle_grover(database, data_entry): circ_grover = QuantumCircuit(n + n + 1) circ_grover.append(database, list(range(n+n))) target_reflection_gate = XGate().control(num_ctrl_qubits=n, ctrl_state=colour_hash_map[data_entry], label="Reflection of " + "\"" + data_entry + "\" Target") # control() missing 1 required positional argument: 'self' .... if only 'XGate' used instead of 'XGate()' # The “missing 1 required positional argument: 'self'” error is raised when you do not instantiate an object of a class before calling a class method. This error is also raised when you incorrectly instantiate a class. circ_grover.append(target_reflection_gate, list(range(n, n+n+1))) circ_grover.append(database, list(range(n+n))) return circ_grover print("Grover Oracle (target example: orange)") oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), "orange").decompose().draw() def mcz_gate(num_qubits): num_controls = num_qubits - 1 mcz_gate = QuantumCircuit(num_qubits) target_mcz = QuantumCircuit(1) target_mcz.z(0) target_mcz = target_mcz.to_gate(label="Z_Gate").control(num_ctrl_qubits=num_controls, ctrl_state=None, label="MCZ") mcz_gate.append(target_mcz, list(range(num_qubits))) return mcz_gate.reverse_bits() print("Multi-controlled Z (MCZ) Gate") mcz_gate(n).decompose().draw() def diffusion_operator(num_qubits): circ_diffusion = QuantumCircuit(num_qubits) qubits_list = list(range(num_qubits)) # Layer of H^n gates circ_diffusion.h(qubits_list) # Layer of X^n gates circ_diffusion.x(qubits_list) # Layer of Multi-controlled Z (MCZ) Gate circ_diffusion = circ_diffusion.compose(mcz_gate(num_qubits), qubits_list) # Layer of X^n gates circ_diffusion.x(qubits_list) # Layer of H^n gates circ_diffusion.h(qubits_list) return circ_diffusion print("Diffusion Circuit") diffusion_operator(n).draw() # Putting it all together ... !!! item = "green" print("Searching for the index of the colour", item) circuit = QuantumCircuit(n + n + 1, n) circuit.x(n + n) circuit.barrier() circuit.h(list(range(n))) circuit.h(n+n) circuit.barrier() unitary_oracle = oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), item).to_gate(label="Oracle Operator") unitary_diffuser = diffusion_operator(n).to_gate(label="Diffusion Operator") M = countOf(index_colour_table.values(), item) Q = int(np.pi * np.sqrt(N/M) / 4) for i in range(Q): circuit.append(unitary_oracle, list(range(n + n + 1))) circuit.append(unitary_diffuser, list(range(n))) circuit.barrier() circuit.measure(list(range(n)), list(range(n))) circuit.draw() backend_sim = Aer.get_backend('qasm_simulator') job_sim = backend_sim.run(transpile(circuit, backend_sim), shots=1024) result_sim = job_sim.result() counts = result_sim.get_counts(circuit) if M==1: print("Index of the colour", item, "is the index with most probable outcome") else: print("Indices of the colour", item, "are the indices the most probable outcomes") from qiskit.visualization import plot_histogram plot_histogram(counts)
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
from qiskit import BasicAer, execute from qiskit.circuit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.circuit.library.standard_gates import PhaseGate from qiskit.circuit.library.basis_change import QFT import math from src.util.util import run_qc q = QuantumRegister(3) b = QuantumRegister(1) c = ClassicalRegister(3) qc = QuantumCircuit(q, b, c) qc.x(q[0]) qc.draw(output='mpl') def increment(circuit, register, apply_QFT=True): q = register num = len(q) qc = circuit if apply_QFT == True: qc.barrier() qc = qc.compose(QFT(num_qubits=num, approximation_degree=0, do_swaps=True, \ inverse=False, insert_barriers=True, name='qft')) qc.barrier() for i, qubit in enumerate(q): qc.rz(math.pi/2**(num-1-i), qubit) if apply_QFT == True: qc.barrier() qc = qc.compose(QFT(num_qubits=num, approximation_degree=0, do_swaps=True, \ inverse=True, insert_barriers=True, name='iqft')) qc.barrier() return qc test = increment(qc, q) test.draw(output='mpl') def control_increment(circuit, qregister, cregister, apply_QFT=True): q = qregister c = cregister numq = len(q) numc = len(c) qc = circuit if apply_QFT == True: qc.barrier() qc = qc.compose(QFT(num_qubits=numq, approximation_degree=0, do_swaps=True, \ inverse=False, insert_barriers=True, name='qft')) qc.barrier() for i, qubit in enumerate(q): ncp = PhaseGate(math.pi/2**(numq-i-1)).control(numc) qc.append(ncp, [*c, qubit]) if apply_QFT == True: qc.barrier() qc = qc.compose(QFT(num_qubits=numq, approximation_degree=0, do_swaps=True, \ inverse=True, insert_barriers=True, name='iqft')) qc.barrier() return qc test2 = control_increment(qc, q, b) test2.draw(output='mpl') ## Test increment without control test = increment(qc, q) test.measure(q[:], c[:]) run_qc(qc) test.draw(output='mpl') # Test control increment q = QuantumRegister(3) b = QuantumRegister(1) c = ClassicalRegister(3) qc = QuantumCircuit(q, b, c) qc.x(q[0]) qc = control_increment(qc, q, b) # Flipping control qubit to 1 qc.x(b[0]) qc = control_increment(qc, q, b) # Flipping control qubit to 1 qc.x(b[0]) qc = control_increment(qc, q, b) # Should equal 010 qc.measure(q[:], c[:]) run_qc(qc) qc.draw(output="mpl")
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
import matplotlib.pyplot as plt %matplotlib inline import numpy as np import math from qiskit.visualization import plot_state_qsphere from qiskit import * from qiskit.tools.visualization import plot_histogram from IPython.display import display, Math, Latex def reflect(U, n): for i in range(int(n/2)): U.swap(i, n-i-1) def myQFT(n): U = QuantumCircuit(n) for x_k in range(n): U.h(x_k) for x_j in range(x_k+1, n): angle = math.pi/2**(x_j-x_k) U.cu1(angle, x_j, x_k) reflect(U, n) U = U.to_gate() U.name = 'Quantum Fourier Tranform' #ctl_U = U.control() make it a controlled gate return U n = 5 mc = QuantumCircuit(n, n) #state |x> = |10101> mc.x(0) mc.x(2) mc.x(4) #Computational basis state qsphere backend = BasicAer.get_backend('statevector_simulator') job0 = execute(mc, backend).result() U = myQFT(n) mc.append(U, range(n)) #Fourier basis state qsphere job1 = execute(mc, backend).result() mc.measure(range(n), range(n)) backend = BasicAer.get_backend('qasm_simulator') atp = 1024 res = execute(mc, backend=backend, shots=atp).result() ans = res.get_counts() mc.draw('mpl') plot_histogram(ans) plot_state_qsphere(job0.get_statevector(mc)) plot_state_qsphere(job1.get_statevector(mc))
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit import * from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.quantum_info import Statevector from qiskit.circuit.library import QFT from qiskit.visualization import plot_state_qsphere from qiskit.quantum_info import Operator from qiskit.tools.visualization import plot_histogram from IPython.display import display, Math, Latex import math def reflect(mcq, n): for i in range(int(n/2)): mcq.swap(i, n-i-1) def myQFT(mcq, n): for x_k in range(n): mcq.h(x_k) for x_j in range(x_k+1, n): angle = math.pi/2**(x_j-x_k) mcq.cu1(angle, x_j, x_k) n = 4 qbt1 = QuantumRegister(n) cbt1 = ClassicalRegister(n) mcq1 = QuantumCircuit(qbt1, cbt1) myQFT(mcq1, n) mcq1.barrier() reflect(mcq1, n) mcq1.barrier() mcq1.measure(range(n), range(n)) backend = BasicAer.get_backend('qasm_simulator') atp = 1024 res = execute(mcq1, backend=backend, shots=atp).result() ans1 = res.get_counts() mcq1.draw('mpl') qbt2 = QuantumRegister(n) cbt2 = ClassicalRegister(n) mcq2 = QuantumCircuit(qbt2, cbt2) mcq2.append(QFT(n, do_swaps=True), qbt2) #mcq2.h(range(n)) mcq2.measure(range(n), range(n)) backend = BasicAer.get_backend('qasm_simulator') atp = 1024 res = execute(mcq2, backend=backend, shots=atp).result() ans2 = res.get_counts() mcq2.draw('mpl') legend = ['myQFT','qiskitQFT'] plot_histogram([ans1,ans2], legend=legend)
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
import numpy as np from scipy.linalg import expm, sinm, cosm import matplotlib.pyplot as plt import pandas as pd import seaborn as sns import math from scipy import stats %matplotlib inline from IPython.display import Image, display, Math, Latex sns.set(color_codes=True)
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
# A jupyter notebook is composed by one or more cells. # There are two main cells: Code and Markdown. # A code cell is used to write and execute your codes. # A markdown cell is used to write text descriptions, notes, formulas or include graphics and images. # On a markdown cell, you can format your content by using Markdown, HTML, or LaTeX codes. # During our tutorial, you are expected to write only python codes. # Interested readers may also use markdown cells, but it is not necesary to complete our tutorial. # # We explain basic usage of cells in Jupyter notebooks here # # This is the first cell in this notebook. # You can write Python code here, # and then EXECUTE/RUN it by # 1) pressing CTRL+ENTER or SHIFT+ENTER # 2) clicking "Run" on the menu # here are few lines of python code print("hello world") str="*" for i in range(10): print(str) str+="*" # after executing this cell, the outcomes will immedeately appear after this cell # you can change the range above and re-run this cell # This is the second cell in this notebook. # # By using menu item "Insert", you can add a new cell before or after the active cell. # When a cell is selected, you may delete it by using menu item "Edit". # # As you may notice, there are other editing options under "Edit", # for example, copy/cut-paste cells and split-merge cells. # %%writefile first.py print("hello world") str="*" for i in range(5): print(str) str+="*" %run first.py # %load first.py print("hello world") str="*" for i in range(5): print(str) str+="*"
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
number = 5 # integer real = -3.4 # float name = 'Asja' # string surname = "Sarkana" # string boolean1 = True # Boolean boolean2 = False # Boolean a = 13 b = 5 print("a =",a) print("b =",b) print() # basics operators print("a + b =",a+b) print("a - b =",a-b) print("a * b =",a*b) print("a / b =",a/b) a = 13 b = 5 print("a =",a) print("b =",b) print() print("integer division:") print("a//b =",a//b) print("modulus operator:") print("a mod b =",a % b) b = 5 print("b =",b) print() print("b*b =",b**2) print("b*b*b =",b**3) print("sqrt(b)=",b**0.5) # list mylist = [10,8,6,4,2] print(mylist) # tuple mytuple=(1,4,5,'Asja') print(mytuple) # dictionary mydictionary = { 'name' : "Asja", 'surname':'Sarkane', 'age': 23 } print(mydictionary) print(mydictionary['surname']) # list of the other objects or variables list_of_other_objects =[ mylist, mytuple, 3, "Asja", mydictionary ] print(list_of_other_objects) # length of a string print(len("Asja Sarkane")) # size of a list print(len([1,2,3,4])) # size of a dictionary mydictionary = { 'name' : "Asja", 'surname':'Sarkane', 'age': 23} print(len(mydictionary)) i = 10 while i>0: # while condition(s): print(i) i = i - 1 for i in range(10): # i is in [0,1,...,9] print(i) for i in range(-5,6): # i is in [-5,-4,...,0,...,4,5] print(i) for i in range(0,23,4): # i is in [0,4,8,12,16,20] print(i) for i in [3,8,-5,11]: print(i) for i in "Sarkane": print(i) # dictionary mydictionary = { 'name' : "Asja", 'surname':'Sarkane', 'age': 23, } for key in mydictionary: print("key is",key,"and its value is",mydictionary[key]) for a in range(4,7): # if condition(s) if a<5: print(a,"is less than 5") # elif conditions(s) elif a==5: print(a,"is equal to 5") # else else: print(a,"is greater than 5") # Logical operator "and" i = -3 j = 4 if i<0 and j > 0: print(i,"is negative AND",j,"is positive") # Logical operator "or" i = -2 j = 2 if i==2 or j == 2: print("i OR j is 2: (",i,",",j,")") # Logical operator "not" i = 3 if not (i==2): print(i,"is NOT equal to 2") # Operator "equal to" i = -1 if i == -1: print(i,"is EQUAL TO -1") # Operator "not equal to" i = 4 if i != 3: print(i,"is NOT EQUAL TO 3") # Operator "not equal to" i = 2 if i <= 5: print(i,"is LESS THAN OR EQUAL TO 5") # Operator "not equal to" i = 5 if i >= 1: print(i,"is GREATER THAN OR EQUAL TO 3") A =[ [1,2,3], [-2,-4,-6], [3,6,9] ] # print all print(A) print() # print each list in a new line for list in A: print(list) list1 = [1,2,3] list2 = [4,5,6] #concatenation of two lists list3 = list1 + list2 print(list3) list4 = list2 + list1 print(list4) list = [0,1,2] list.append(3) print(list) list = list + [4] print(list) def summation_of_integers(n): summation = 0 for integer in range(n+1): summation = summation + integer return summation print(summation_of_integers(10)) print(summation_of_integers(20)) from random import randrange print(randrange(10),"is picked randomly between 0 and 9") print(randrange(-9,10),"is picked randomly between -9 and 9") print(randrange(0,20,3),"is picked randomly from the list [0,3,6,9,12,15,18]")
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
from matplotlib.pyplot import plot, figure, arrow, Circle, gca, text, bar figure(figsize=(6,6), dpi=60) #The higher dpi value makes the figure bigger. plot(1,5,'bo') arrow(0.5,0.5,0.1,0.1,head_width=0.04,head_length=0.08,color="blue") arrow(0,0,1.1,0,head_width=0.04,head_length=0.08) arrow(0,0,-1.1,0,head_width=0.04,head_length=0.08) arrow(0,0,0,-1.1,head_width=0.04,head_length=0.08) arrow(0,0,0,1.1,head_width=0.04,head_length=0.08) gca().add_patch( Circle((0.5,0.5),0.2,color='black',fill=False) ) %run qlatvia.py import matplotlib def draw_axes(): # dummy points for zooming out points = [ [1.3,0], [0,1.3], [-1.3,0], [0,-1.3] ] # coordinates for the axes arrows = [ [1.1,0], [0,1.1], [-1.1,0], [0,-1.1] ] # drawing dummy points for p in points: matplotlib.pyplot.plot(p[0],p[1]+0.2) # drawing the axes for a in arrows: matplotlib.pyplot.arrow(0,0,a[0],a[1],head_width=0.04, head_length=0.08) draw_axes() import matplotlib def draw_unit_circle(): unit_circle= matplotlib.pyplot.Circle((0.2,0.2),0.2,color='black',fill=False) matplotlib.pyplot.gca().add_patch(unit_circle) draw_unit_circle() import matplotlib def draw_quantum_state(x,y): # shorten the line length to 0.92 # line_length + head_length should be 1 x1 = 0.92 * x y1 = 0.92 * y matplotlib.pyplot.arrow(0,0,x1,y1,head_width=0.04,head_length=0.08,color="blue") x2 = 1.15 * x y2 = 1.15 * y matplotlib.pyplot.text(x2,y2,arrow) draw_quantum_state(1,1) import matplotlib def draw_qubit(): # draw a figure matplotlib.pyplot.figure(figsize=(6,6), dpi=60) # draw the origin matplotlib.pyplot.plot(0,0,'ro') # a point in red color # drawing the axes by using one of our predefined functions draw_axes() # drawing the unit circle by using one of our predefined functions draw_unit_circle() # drawing |0> matplotlib.pyplot.plot(1,0,"o") matplotlib.pyplot.text(1.05,0.05,"|0>") # drawing |1> matplotlib.pyplot.plot(0,1,"o") matplotlib.pyplot.text(0.05,1.05,"|1>") # drawing -|0> matplotlib.pyplot.plot(-1,0,"o") matplotlib.pyplot.text(-1.2,-0.1,"-|0>") # drawing -|1> matplotlib.pyplot.plot(0,-1,"o") matplotlib.pyplot.text(-0.2,-1.1,"-|1>") draw_qubit()
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
# This is a comment # A comment is used for explanations/descriptions/etc. # Comments do not affect the programs # let's define an integer variable named a a = 5 # let's print its value print(a) # let's define three integer variables named a, b, and c a = 2 b = 4 c = a + b # summation of a and b # let's print their values together print(a,b,c) # a single space will automatically appear in between # let's print their values in reverse order print(c,b,a) # let's print their summation and multiplication print(a+b+c,a*b*c) # let's define variables with string/text values hw = "hello world" # we can use double quotes hqw = 'hello quantum world' # we can use single quotes # let's print them print(hw) print(hqw) # let's print them together by inserting another string in between print(hw,"and",hqw) # let's concatenate a few strings d = "Hello " + 'World' + " but " + 'Quantum ' + "World" # let's print the result print(d) # let's print numeric and string values together print("a =",a,", b =",b,", a+b =",a+b) # let's subtract two numbers d = a-b print(a,b,d) # let's divide two numbers d = a/b print(a,b,d) # let's divide integers over integers # the result is always an integer (with possible integer remainder) d = 33 // 6 print(d) # reminder/mod operator r = 33 % 6 # 33 mod 6 = 3 # or when 33 is divided by 6 over integers, the reminder is 3 # 33 = 5 * 6 + 3 # let's print the result print(r) # Booleen variables t = True f = False # let's print their values print(t,f) # print their negations print(not t) print("the negation of",t,"is",not t) print(not f) print("the negation of",f,"is",not f) # define a float variable d = -3.4444 # let's print its value and its square print(d, d * d) e = (23*13) - (11 * 15) print(e) # we can use more than one variable # left is the variable for the left part of the expression # we start with the multiplication inside the parentheses left = 34*11 # we continue with the substruction inside the parentheses # we reuse the variable named left left = 123 - left # we reuse left again for the multiplication with -3 left = -3 * left # right is the variable for the right part of the expression # we use the same idea here right = 23 * 15 right = 5 + right right = 4 * right # at the end, we use left for the result left = left + right # let's print the result print(left) # # your solution is here # n1,n2,n3 = 3,-4,6 print(n1,n2,n3) r1 = (2 * n1 + 3 * n2)*2 - 5 *n3 print(r1) # # your solution is here # n1,n2,n3 = 3,-4,6 up = (n1-n2) * (n2-n3) down = (n3-n1) * (n3+1) result = up/down print (result) # # your solution is here # N = "Arya" S = "Shah" print("hello from the quantum world to",N,S)
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
# let's print all numbers between 0 and 9 for i in range(10): print(i) # range(n) represents the list of all numbers from 0 to n-1 # i is the variable to take the values in the range(n) iteratively: 0, 1, ..., 9 in our example # let's write the same code in two lines for i in range(10): # do not forget to use colon print(i) # the second line is indented # this means that the command in the second line will be executed inside the for-loop # any other code executed inside the for-loop must be intented in the same way #my_code_inside_for-loop_2 will come here #my_code_inside_for-loop_3 will come here #my_code_inside_for-loop_4 will come here # now I am out of the scope of for-loop #my_code_outside_for-loop_1 will come here #my_code_outside_for-loop_2 will come here # let's calculate the summation 1+2+...+10 by using a for-loop # we use variable total for the total summation total = 0 for i in range(11): # do not forget to use colon total = total + i # total is increased by i in each iteration # alternatively, the same assignment can shortly be written as total += i similarly to languages C, C++, Java, etc. # now I am out of the scope of for-loop # let's print the latest value of total print(total) # let's calculate the summation 10+12+14+...+44 # we create a list having all numbers in the summation # for this purpose, this time we will use three parameters in range total = 0 for j in range(10,45,2): # the range is defined between 10 and 44, and the value of j will be increased by 2 after each iteration total += j # let's use the shortened version of total = total + j print(total) # let's calculate the summation 1+2+4+8+16+...+256 # remark that 256 = 2*2*...*2 (8 times) total = 0 current_number = 1 # this value will be multiplied by 2 after each iteration for k in range(9): total = total + current_number # current_number is 1 at the beginning, and its value will be doubled after each iteration current_number = 2 * current_number # let's double the value of the current_number for the next iteration # short version of the same assignment: current_number *= 2 as in the languages C, C++, Java, etc. # now I am out of the scope of for-loop # let's print the latest value of total print(total) # instead of a range, we can directly use a list for i in [1,10,100,1000,10000]: print(i) # instead of [...], we can also use (...) # but this time it is a tuple, not a list (keep in your mind that the values in a tuple cannot be changed) for i in (1,10,100,1000,10000): print(i) # let's create a range between 10 and 91 that contains the multiples of 7 for j in range(14,92,7): # 14 is the first multiple of 7 greater than or equal to 10 # 91 should be in the range, and so we write 92 print(j) # let's create a range between 11 and 22 for i in range(11,23): print(i) # we can also use variables in range n = 5 for j in range(n,2*n): print(j) # we will print all numbers in {n,n+1,n+2,...,2n-1} # we can use a list of strings for name in ("Asja","Balvis","Fyodor"): print("Hello",name,":-)") # any range can be converted to a list L1 = list(range(10)) print(L1) L2 = list(range(55,200,11)) print(L2) # # your solution is here # total1 = 0 total2 = 0 for i in range(3,52,3): total1 = total1 + i total2 += i # shorter form print("The summation is",total1) print("The summation is",total2) # # your solution is here # T = 0 current_number = 1 for i in range(9): T = T + current_number print("3 to",i,"is",current_number) current_number = 3 * current_number print("summation is",T) # Python has also exponent operator: ** # we can also directly use it T = 0 for i in range(9): print("3 to",i,"is",3**i) T = T + 3 ** i print("summation is",T) # let's calculate the summation 1+2+4+8+...+256 by using a while-loop total = 0 i = 1 #while condition(s): # your_code1 # your_code2 # your_code3 while i < 257: # this loop iterates as long as i is less than 257 total = total + i i = i * 2 # i is doubled in each iteration, and so soon it will be greater than 256 print(total) # remember that we calculated this summation as 511 before L = [0,1,2,3,4,5,11] # this is a list containing 7 integer values i = 0 while i in L: # this loop will be iterated as long as i is in L print(i) i = i + 1 # the value of i iteratively increased, and so soon it will hit a value not in the list L # the loop is terminated after i is set to 6, because 6 is not in L # let's use negation in the condition of while-loop L = [10] # this list has a single element i = 0 while i not in L: # this loop will be iterated as long as i is not equal to 10 print(i) i = i+1 # the value of i will hit 10 after ten iterations # let's rewrite the same loop by using a direct inequality i = 0 while i != 10: # "!=" is used for "not equal to" operator print(i) i=i+1 # let's rewrite the same loop by using negation of equality i = 0 while not (i == 10): # "==" is used for "equal to" operator print(i) i=i+1 # while-loop seems having more fun :-) # but we should be more careful when writing the condition(s)! # summation and n is zero at the beginning S = 0 n = 0 while S < 1000: # this loop will stop after S exceeds 999 (S = 1000 or S > 1000) n = n +1 S = S + n # let's print n and S print("n =",n," S =",S) # three examples for the operator "less than or equal to" #print (4 <= 5) #print (5 <= 5) #print (6 <= 5) # you may comment out the above three lines and see the results by running this cell # # your solution is here # T = 0 n = 2 # this value iteratively will be first halved and then added to the summation T how_many_terms = 0 while T<=1.99: n = n/2 # half the value of n print("n = ",n) T = T + n # update the value of T how_many_terms = how_many_terms + 1 print("T = ",T) print("how many terms in the summation:",how_many_terms) # our result says that there should be 8 terms in our summation # let's calculate the summations of the first seven and eight terms, and verify our results T7 = 0 n = 2 # this value iteratively will be first halved and then added to the summation for i in range(7): n = n/2 print("n =",n) T7 = T7 + n print("the summation of the first seven terms is",T7) T8 = 0 n = 2 # this value iteratively will be first halved and then added to the summation for i in range(8): n = n/2 print("n =",n) T8 = T8 + n print("the summation of the first eight terms is",T8) print("(the summation of the first seven terms is",T7,")") # this is the code for including function randrange into our program from random import randrange # randrange(n) picks a number from the list [0,1,2,...,n-1] randomly #r = randrange(100) #print(r) # # your solution is here # from random import randrange r = 0 attempt = 0 while r != 3: # the loop iterates as long as r is not equal to 3 r = randrange(10) # randomly pick a number attempt = attempt + 1 # increase the number of attempts by 1 print (attempt,"->",r) # print the number of attempt and the randomly picked number print("total number of attempt(s) is",attempt) # here is a schematic example for double nested loops #for i in range(10): # your_code1 # your_code2 # while j != 7: # your_code_3 # your_code_4 # # your solution is here # # be aware of single and double indentions number_of_execution = 2000 # change this with 200, 2000, 20000, 200000 and reexecute this cell total_attempts = 0 from random import randrange for i in range(number_of_execution): # the outer loop iterates number_of_execution times r = 0 attempt = 0 while r != 3: # the while-loop iterates as long as r is not equal to 3 r = randrange(10) # randomly pick a number attempt = attempt + 1 # increase the number of attempts by 1 # I am out of scope of while-loop total_attempts = total_attempts + attempt # update the total number of attempts # I am out of scope of for-loop print(number_of_execution,"->",total_attempts/number_of_execution) # let's use triple nested loops for number_of_execution in [20,200,2000,20000,200000]: # we will use the same code by indenting all lines by one more level total_attempts = 0 for i in range(number_of_execution): # the middle loop iterates number_of_execution times r = 0 attempt = 0 while r != 3: # the while-loop iterates as long as r is not equal to 3 r = randrange(10) # randomly pick a number attempt = attempt + 1 # increase the number of attempts by 1 # I am out of scope of while-loop total_attempts = total_attempts + attempt # update the total number of attempts # I am out of scope of for-loop print(number_of_execution,"->",total_attempts/number_of_execution) # you can include 2 million to the list, but you should WAIT for a while to see the result # can your computer compete with exponential growth? # if you think "yes", please try 20 million, 200 million, and so on
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
# let's randomly pick a number between 0 and 9, and print its value if it is greater than 5 from random import randrange r = randrange(10) if r > 5: print(r) # when the condition (r > 5) is valid/true, the code (print(r)) will be executed # you may need to execute your code more than once to see an outcome # repeat the same task four times, and also print the value of iteration variable (i) for i in range(4): r = randrange(10) # this code belongs to for-loop, and so it is indented if r > 5: # this code also belongs to for-loop, and so it is indented as well print("i =",i,"r =",r) # this code belongs to if-statement, and so it is indented with respect to if-statement # if you are unlucky (with probabability less than 13/100), you may not see any outcome after a single run # do the same task 100 times, and find the percentage of successful iterations (attempts) # an iteration (attempt) is successful if the randomly picked number is greater than 5 # the expected percentage is 40, because, out of 10 numbers, there are 4 numbers greater than 5 # but the experimental results differ success = 0 for i in range(100): r = randrange(10) if r > 5: success = success + 1 print(success,"%") # each experiment most probably will give different percentage value # let's randomly pick a number between 0 and 9, and print whether it is less than 6 or not # we use two conditionals here r = randrange(10) print("the picked number is ",r) if r < 6: print("it is less than 6") if r >= 6: print("it is greater than or equal to 6") # let's write the same algorithm by using if-else structure r = randrange(10) print("the picked number is ",r) if r < 6: print("it is less than 6") else: # if the above condition (r<6) is False print("it is greater than or equal to 6") # # your solution is here # from random import randrange r = randrange(10,51) if r % 2 ==0: print(r,"is even") else: print(r,"is odd") # # when there are many related conditionals, we can use if-elif-else structure # # let's randomly pick an even number between 1 and 99 # then determine whether it is less than 25, between 25 and 50, between 51 and 75, or greater than 75. r = randrange(2,100,2) # randonmly pick a number in range {2,4,6,...,98}, which satisfies our condition # let's print this range to verify our claim print(list(range(2,100,2))) print() # print an empty line print("the picked number is",r) if r < 25: print("it is less than 25") elif r<=50: # if the above condition is False and the condition here is True print("it is between 25 and 50") elif r<=75: # if both conditions above are False and the condition here is True print("it is between 51 and 75") else: # if none of the above conditions is True print("it is greater than 75") # # your solution is here # from random import randrange for N in [100,1000,10000,100000]: first_half=second_half=0 for i in range(N): r = randrange(100) if r<50: first_half = first_half + 1 else: second_half=second_half + 1 print(N,"->",first_half/N,second_half/N) # let's determine whether a randomly picked number between -10 and 100 is prime or not. # this is a good example for using more than one conditional in different parts of the program # this is also an example for "break" command, which terminates any loop immediately r = randrange(-10,101) # pick a number between -10 and 100 print(r) # print is value if r < 2: print("it is NOT a prime number") # this is by definition elif r == 2: print("it is a PRIME number") # we already know this else: prime=True # we assume that r is prime, and try to falsify this assumption by looking for a divisor in the following loop for i in range(2,r): # check all integers between 2 and r-1 if r % i ==0: # if i divides r without any reminder (or reminder is zero), then r is not a prime number print("it is NOT a prime number") prime=False # our assumption is falsifed break # TERMINATE the iteration immediately # we are out of if-scope # we are out of for-loop-scope if prime == True: # if our assumption is still True (if it was not falsified inside for-loop) print("it is a PRIME number") # this is an example to write a function # our function will return a Boolean value True or False def prime(number): # our function takes one parameter (has one argument) if number < 2: return False # once return command is executed, we exit the function if number == 2: return True # because of return command, we can use "if" instead of "elif" if number % 2 == 0: return False # any even number greater than 2 is not prime, because it is divisible by 2 for i in range(3,number,2): # we can skip even integers if number % i == 0: return False # once we find a divisor of the number, we return False and exit the function return True # the number has passed all checks until now # by using "return" command appropriately, the programs can be shortened # remark that this might not be a good choice everytime for readibility of codes # let's test our program by printing all prime numbers between -10 and 30 for i in range(-10,30): # we pass i to the function prime if prime(i): # the function prime(i) returns True or False print(i) # this code will be executed if i is prime, i.e., prime(i) returns True
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
# here is a list holding all even numbers between 10 and 20 L = [10, 12, 14, 16, 18, 20] # let's print the list print(L) # let's print each element by using its index but in reverse order print(L[5],L[4],L[3],L[2],L[1],L[0]) # let's print the length (size) of list print(len(L)) # let's print each element and its index in the list # we use a for-loop, and the number of iteration is determined by the length of the list # everthing is automatical :-) L = [10, 12, 14, 16, 18, 20] for i in range(len(L)): print(L[i],"is the element in our list with the index",i) # let's replace each number in the above list with its double value # L = [10, 12, 14, 16, 18, 20] # let's print the list before doubling operation print("the list before doubling operation is",L) for i in range(len(L)): current_element=L[i] # get the value of the i-th element L[i] = 2 * current_element # update the value of the i-th element # let's shorten the code as #L[i] = 2 * L[i] # or #L[i] *= 2 # let's print the list after doubling operation print("the list after doubling operation is",L) # after each execution of this cell, the latest values will be doubled # so the values in the list will be exponentially increased # let's define two lists L1 = [1,2,3,4] L2 = [-5,-6,-7,-8] # two lists can be concatenated # the result is a new list print("the concatenation of L1 and L2 is",L1+L2) # the order of terms is important print("the concatenation of L2 and L1 is",L2+L1) # this is a different list than L1+L2 # we can add a new element to a list, which increases its length/size by 1 L = [10, 12, 14, 16, 18, 20] print(L,"the current length is",len(L)) # we add two values by showing two different methods # L.append(value) directly adds the value as a new element to the list L.append(-4) # we can also use concatenation operator + L = L + [-8] # here [-8] is a list having a single element print(L,"the new length is",len(L)) # a list can be multiplied with an integer L = [1,2] # we can consider the multiplication of L by an integer as a repeated summation (concatenation) of L by itself # L * 1 is the list itself # L * 2 is L + L (the concatenation of L with itself) # L * 3 is L + L + L (the concatenation of L with itself twice) # L * m is L + ... + L (the concatenation of L with itself m-1 times) # L * 0 is the empty list # L * i is the same as i * L # let's print the different cases for i in range(6): print(i,"* L is",i*L) # this operation can be useful when initializing a list with the same value(s) # let's create a list of prime numbers less than 100 # here is a function that determines whether a given number is prime or not def prime(number): if number < 2: return False if number == 2: return True if number % 2 == 0: return False for i in range(3,number,2): if number % i == 0: return False return True # end of a function # let's start with an empty list L=[] # what can the length of this list be? print("my initial length is",len(L)) for i in range(2,100): if prime(i): L.append(i) # alternative methods: #L = L + [i] #L += [i] # print the final list print(L) print("my final length is",len(L)) # let's define the list with S(0) L = [0] # let's iteratively define n and S # initial values n = 0 S = 0 # the number of iterations N = 20 while n <= N: # we iterate all values from 1 to 20 n = n + 1 S = S + n L.append(S) # print the final list print(L) # # your solution is here # the first and second elements are 1 and 1 F = [1,1] for i in range(2,30): F.append(F[i-1] + F[i-2]) # print the final list print(F) # the following list stores certain information about Asja # name, surname, age, profession, height, weight, partner(s) if any, kid(s) if any, the creation date of list ASJA = ['Asja','Sarkane',34,'musician',180,65.5,[],['Eleni','Fyodor'],"October 24, 2018"] print(ASJA) # Remark that an element of a list can be another list as well. # # your solution is here # # define an empty list N = [] for i in range(11): N.append([ i , i*i , i*i*i , i*i + i*i*i ]) # a list having four elements is added to the list N # Alternatively: #N.append([i , i**2 , i**3 , i**2 + i**3]) # ** is the exponent operator #N = N + [ [i , i*i , i*i*i , i*i + i*i*i] ] # Why using double brackets? #N = N + [ [i , i**2 , i**3 , i**2 + i**3] ] # Why using double brackets? # In the last two alternative solutions, you may try with a single bracket, # and then see why double brackets are needed for the exact answer. # print the final list print(N) # let's print the list N element by element for i in range(len(N)): print(N[i]) # let's print the list N element by element by using an alternative method for el in N: # el will iteratively takes the values of elements in N print(el) # let's define a dictionary pairing a person with her/his age ages = { 'Asja':32, 'Balvis':28, 'Fyodor':43 } # let print all keys for person in ages: print(person) # let's print the values for person in ages: print(ages[person])
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
# import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer # define a quantum register with one qubit q = QuantumRegister(1,"qreg") # define a classical register with one bit # it stores the measurement result of the quantum part c = ClassicalRegister(1,"creg") # define our quantum circuit qc = QuantumCircuit(q,c) # apply h-gate (Hadamard: quantum coin-flipping) to the first qubit qc.h(q[0]) # measure the first qubit, and store the result in the first classical bit qc.measure(q,c) # draw the circuit by using matplotlib qc.draw(output='mpl') # re-run the cell if the figure is not displayed # execute the circuit 10000 times in the local simulator job = execute(qc,Aer.get_backend('qasm_simulator'),shots=10000) counts = job.result().get_counts(qc) print(counts) # print the outcomes print() n_zeros = counts['0'] n_ones = counts['1'] print("State 0 is observed with frequency %",100*n_zeros/(n_zeros+n_ones)) print("State 1 is observed with frequency %",100*n_ones/(n_zeros+n_ones)) # we can show the result by using histogram print() from qiskit.visualization import plot_histogram plot_histogram(counts) # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer # define a quantum register with one qubit q2 = QuantumRegister(1,"qreg2") # define a classical register with one bit # it stores the measurement result of the quantum part c2 = ClassicalRegister(1,"creg2") # define our quantum circuit qc2 = QuantumCircuit(q2,c2) # apply h-gate (Hadamard: quantum coin-flipping) to the first qubit qc2.h(q2[0]) # apply h-gate (Hadamard: quantum coin-flipping) to the first qubit once more qc2.h(q2[0]) # measure the first qubit, and store the result in the first classical bit qc2.measure(q2,c2) # draw the circuit by using matplotlib qc2.draw(output='mpl') # re-run the cell if the figure is not displayed # execute the circuit 10000 times in the local simulator job = execute(qc2,Aer.get_backend('qasm_simulator'),shots=10000) counts2 = job.result().get_counts(qc2) print(counts2) # print the outcomes # # your solution is here # # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer # define a quantum register with one qubit q = QuantumRegister(1,"qreg") # define a classical register with one bit # it stores the measurement result of the quantum part c = ClassicalRegister(1,"creg") # define our quantum circuit qc = QuantumCircuit(q,c) # apply x-gate to the first qubit qc.x(q[0]) # apply h-gate (Hadamard: quantum coin-flipping) to the first qubit qc.h(q[0]) # measure the first qubit, and store the result in the first classical bit qc.measure(q,c) # draw the circuit by using matplotlib qc.draw(output='mpl') # re-run the cell if the figure is not displayed # execute the circuit and read the results job = execute(qc,Aer.get_backend('qasm_simulator'),shots=10000) counts = job.result().get_counts(qc) print(counts) # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer # define a quantum register with one qubit q2 = QuantumRegister(1,"qreg2") # define a classical register with one bit # it stores the measurement result of the quantum part c2 = ClassicalRegister(1,"creg2") # define our quantum circuit qc2 = QuantumCircuit(q2,c2) # apply x-gate to the first qubit qc2.x(q2[0]) # apply h-gate (Hadamard: quantum coin-flipping) to the first qubit twice qc2.h(q2[0]) qc2.h(q2[0]) # measure the first qubit, and store the result in the first classical bit qc2.measure(q2,c2) # draw the circuit by using matplotlib qc2.draw(output='mpl') # re-run the cell if the figure is not displayed # execute the circuit and read the results job = execute(qc2,Aer.get_backend('qasm_simulator'),shots=10000) counts2 = job.result().get_counts(qc2) print(counts2)
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
# the given matrix M = [ [0.05, 0, 0.70, 0.60], [0.45, 0.50, 0.20, 0.25], [0.20, 0.35, 0.10, 0], [0.30, 0.15, 0, 0.15] ] # # you may enumarate the columns and rows by the strings '00', '01', '10', and '11' # int('011',2) returns the decimal value of the binary string '011' # # # your solution is here # # the given matrix M = [ [0.05, 0, 0.70, 0.60], [0.45, 0.50, 0.20, 0.25], [0.20, 0.35, 0.10, 0], [0.30, 0.15, 0, 0.15] ] print("Matrix M is") for row in M: print(row) print() # the target matrix is K # we create it and filled with zeros K = [] for i in range(8): K.append([]) for j in range(8): K[i].append(0) # for each transition in M, we create four transitions in K, two of which are always zeros for col in ['00','01','10','11']: for row in ['00','01','10','11']: prob = M[int(col,2)][int(row,2)] # second bit is 0 newcol = col[0]+'0'+col[1] newrow = row[0]+'0'+row[1] K[int(newcol,2)][int(newrow,2)] = prob # second bit is 1 newcol = col[0]+'1'+col[1] newrow = row[0]+'1'+row[1] K[int(newcol,2)][int(newrow,2)] = prob print("Matrix K is") for row in K: print(row)
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
from random import randrange # # you may use method 'randrange' for this task # randrange(n) returns a value from {0,1,...,n-1} randomly # # # your solution is here # from random import randrange for experiment in [100,1000,10000,100000]: heads = tails = 0 for i in range(experiment): if randrange(2) == 0: heads = heads + 1 else: tails = tails + 1 print("experiment:",experiment) print("heads =",heads," tails = ",tails) print("the ratio of #heads/#tails is",(round(heads/tails,4))) print() # empty line # # you may use method 'randrange' for this task # randrange(n) returns a value from {0,1,...,n-1} randomly # # # your solution is here # from random import randrange # let's pick a random number between {0,1,...,99} # it is expected to be less than 60 with probability 0.6 # and greater than or equal to 60 with probability 0.4 for experiment in [100,1000,10000,100000]: heads = tails = 0 for i in range(experiment): if randrange(100) <60: heads = heads + 1 # with probability 0.6 else: tails = tails + 1 # with probability 0.4 print("experiment:",experiment) print("heads =",heads," tails = ",tails) print("the ratio of #heads/#tails is",(round(heads/tails,4))) print() # empty line def biased_coin(N,B): from random import randrange random_number = randrange(N) if random_number < B: return "Heads" else: return "Tails" def biased_coin(N,B): from random import randrange random_number = randrange(N) if random_number < B: return "Heads" else: return "Tails" from random import randrange N = 101 B = randrange(100) total_tosses = 500 the_number_of_heads = 0 for i in range(total_tosses): if biased_coin(N,B) == "Heads": the_number_of_heads = the_number_of_heads + 1 my_guess = the_number_of_heads/total_tosses real_bias = B/N error = abs(my_guess-real_bias)/real_bias*100 print("my guess is",my_guess) print("real bias is",real_bias) print("error (%) is",error)
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
# # OUR SOLUTION # # initial condition: # Asja will start with one euro, # and so, we assume that the probability of having head is 1 at the beginning. prob_head = 1 prob_tail = 0 # # first coin-flip # # the new probability of head is calculated by using the first row of table new_prob_head = prob_head * 0.6 + prob_tail * 0.3 # the new probability of tail is calculated by using the second row of the table new_prob_tail = prob_head * 0.4 + prob_tail * 0.7 # update the probabilities for the second round prob_head = new_prob_head prob_tail = new_prob_tail # # second coin-flip # # we do the same calculations new_prob_head = prob_head * 0.6 + prob_tail * 0.3 new_prob_tail = prob_head * 0.4 + prob_tail * 0.7 prob_head = new_prob_head prob_tail = new_prob_tail # # third coin-flip # # we do the same calculations new_prob_head = prob_head * 0.6 + prob_tail * 0.3 new_prob_tail = prob_head * 0.4 + prob_tail * 0.7 prob_head = new_prob_head prob_tail = new_prob_tail # print prob_head and prob_tail print("the probability of getting head after 3 coin tosses is",prob_head) print("the probability of getting tail after 3 coin tosses is",prob_tail) # # your solution is here # # # We copy and paste the previous code # # initial condition: # Asja will start with one euro, # and so, we assume that the probability of having head is 1 at the beginning. prob_head = 1 prob_tail = 0 number_of_iterations = 10 for i in range(number_of_iterations): # the new probability of head is calculated by using the first row of table new_prob_head = prob_head * 0.6 + prob_tail * 0.3 # the new probability of tail is calculated by using the second row of table new_prob_tail = prob_head * 0.4 + prob_tail * 0.7 # update the probabilities prob_head = new_prob_head prob_tail = new_prob_tail # print prob_head and prob_tail print("the probability of getting head after",number_of_iterations,"coin tosses is",prob_head) print("the probability of getting tail after",number_of_iterations,"coin tosses is",prob_tail) # # your solution is here # # define iterations as a list iterations = [20,30,50] for iteration in iterations: # initial probabilites prob_head = 1 prob_tail = 0 print("the number of iterations is",iteration) for i in range(iteration): # the new probability of head is calculated by using the first row of table new_prob_head = prob_head * 0.6 + prob_tail * 0.3 # the new probability of tail is calculated by using the second row of table new_prob_tail = prob_head * 0.4 + prob_tail * 0.7 # update the probabilities prob_head = new_prob_head prob_tail = new_prob_tail # print prob_head and prob_tail print("the probability of getting head after",iteration,"coin tosses is",prob_head) print("the probability of getting tail after",iteration,"coin tosses is",prob_tail) print() # # your solution is here # # define iterations as a list iterations = [20,30,50] # define initial probability pairs as a double list initial_probabilities =[ [1/2,1/2], [0,1] ] for initial_probability_pair in initial_probabilities: print("probability of head is",initial_probability_pair[0]) print("probability of tail is",initial_probability_pair[1]) print() for iteration in iterations: # initial probabilites [prob_head,prob_tail] = initial_probability_pair print("the number of iterations is",iteration) for i in range(iteration): # the new probability of head is calculated by using the first row of table new_prob_head = prob_head * 0.6 + prob_tail * 0.3 # the new probability of tail is calculated by using the second row of table new_prob_tail = prob_head * 0.4 + prob_tail * 0.7 # update the probabilities prob_head = new_prob_head prob_tail = new_prob_tail # print prob_head and prob_tail print("the probability of getting head after",iteration,"coin tosses is",prob_head) print("the probability of getting tail after",iteration,"coin tosses is",prob_tail) print() print() # # your solution is here # # # your solution is here # # # your solution is here # # # your solution is here #
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
# # your code is here # # all portions are stored in a list all_portions = [7,5,4,2,6,1]; # calculate the total portions total_portion = 0 for i in range(6): total_portion = total_portion + all_portions[i] print("total is",total_portion) # find the weight of one portion one_portion = 1/total_portion print("the weight of one portion is",one_portion) print() # print an empty line # now we can calculate the probabilities of getting 1,2,3,4,5, or 6 for i in range(6): print("the probability of getting",(i+1),"is",(one_portion*all_portions[i])) # # your solution is here # # we randomly create a probabilistic state # # we should be careful about two things: # 1. a probability value must be between 0 and 1 # 2. the total probability must be 1 # # we use a list of size 4 # initial values are zeros my_state = [0,0,0,0] normalization_factor = 0 # this will be the summation of four values # we pick for random values between 0 and 100 from random import randrange while normalization_factor==0: # the normalization factor cannot be zero for i in range(4): my_state[i] = randrange(101) # pick a random value between 0 and (101-1) normalization_factor += my_state[i] print("the random values before the normalization",my_state) # normalize each value for i in range(4): my_state[i] = my_state[i]/normalization_factor print("the random values after the normalization",my_state) # find their summation sum = 0 for i in range(4): sum += my_state[i] print("the summation is",sum) # # your solution is here #
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
# # your solution is here # # let's start with a zero matrix A = [ [0,0,0], [0,0,0], [0,0,0] ] # we will randomly pick the entries and then make normalization for each column # it will be easier to iteratively construct the columns # you may notice that each column is a probabilistic state from random import randrange normalization_factor = [0,0,0] # the normalization factor of each column may be different for j in range(3): # each column is iteratively constructed normalization_factor[j] = 0 while normalization_factor[j]==0: # the normalization factor cannot be zero for i in range(3): A[i][j] = randrange(101) # pick a random value between 0 and 100 normalization_factor[j] += A[i][j] # let's print matrix A before the normalization # the entries are between 0 and 100 print("matrix A before normalization:") for i in range(3): print(A[i]) # let's normalize each column for j in range(3): for i in range(3): A[i][j] /= normalization_factor[j] # shorter form of A[i][j] = A[i][j] / normalization_factor[j] # let's print matrix A after the normalization print() # print an empty line print("matrix A after normalization:") for i in range(3): print(A[i]) print() print("the column summations must be 1") sum = [0,0,0] for j in range(3): for i in range(3): sum[j] += A[i][j] print(sum) # operator B B = [ [0.4,0.6,0], [0.2,0.1,0.7], [0.4,0.3,0.3] ] # the current state v = [0.1,0.3,0.6] # # your solution is here # # operator B B = [ [0.4,0.6,0], [0.2,0.1,0.7], [0.4,0.3,0.3] ] # the current state v = [0.1,0.3,0.6] newstate = [] index = 0 for row in B: newstate.append(0) for i in range(len(row)): newstate[index] = newstate[index] + row[i] * v[i] index = index + 1 print(newstate) # %%writefile linear_evolve.py def linear_evolve(operator,state): newstate=[] for i in range(len(operator)): # for each row # we calculate the corresponding entry of the new state newstate.append(0) # we set this value to 0 for the initialization for j in range(len(state)): # for each element in state newstate[i] = newstate[i] + operator[i][j] * state[j] # summation of pairwise multiplications return newstate # return the new probabilistic state # test the function # operator for the test B = [ [0.4,0.6,0], [0.2,0.1,0.7], [0.4,0.3,0.3] ] # state for test v = [0.1,0.3,0.6] newstate = linear_evolve(B,v) print(newstate) for step in [5,10,20,40]: new_state = [0.1,0.3,0.6] # initial state for i in range(step): new_state = linear_evolve(B,new_state) print(new_state) # change the initial state for step in [5,10,20,40]: new_state = [1,0,0] # initial state for i in range(step): new_state = linear_evolve(B,new_state) print(new_state)
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
# the initial state initial = [0.5, 0, 0.5, 0] # probabilistic operator for symbol a A = [ [0.5, 0, 0, 0], [0.25, 1, 0, 0], [0, 0, 1, 0], [0.25, 0, 0, 1] ] # probabilistic operator for symbol b B = [ [1, 0, 0, 0], [0, 1, 0.25, 0], [0, 0, 0.5, 0], [0, 0, 0.25, 1] ] # # your solution is here # # for random number generation from random import randrange # we will use evolve function def evolve(Op,state): newstate=[] for i in range(len(Op)): # for each row newstate.append(0) for j in range(len(state)): # for each element in state newstate[i] = newstate[i] + Op[i][j] * state[j] # summation of pairwise multiplications return newstate # return the new probabilistic state # the initial state state = [0.5, 0, 0.5, 0] # probabilistic operator for symbol a A = [ [0.5, 0, 0, 0], [0.25, 1, 0, 0], [0, 0, 1, 0], [0.25, 0, 0, 1] ] # probabilistic operator for symbol b B = [ [1, 0, 0, 0], [0, 1, 0.25, 0], [0, 0, 0.5, 0], [0, 0, 0.25, 1] ] # # your solution is here # length = 40 total = 50 # total = 1000 # we will also test our code for 1000 strings # we will check 5 cases # let's use a list cases = [0,0,0,0,0] for i in range(total): # total number of strings Na = 0 Nb = 0 string = "" state = [0.5, 0, 0.5, 0] for j in range(length): # generate random string if randrange(2) == 0: Na = Na + 1 # new symbol is a string = string + "a" state = evolve(A,state) # update the probabilistic state by A else: Nb = Nb + 1 # new symbol is b string = string + "b" state = evolve(B,state) # update the probabilistic state by B # now we have the final state p0 = state[0] + state[1] # the probabilities of being in 00 and 01 p1 = state[2] + state[3] # the probabilities of being in 10 and 11 print() # print an empty line print("(Na-Nb) is",Na-Nb,"and","(p0-p1) is",p0-p1) # let's check possible different cases # start with the case in which both are nonzero # then their multiplication is nonzero # let's check the sign of their multiplication if (Na-Nb) * (p0-p1) < 0: print("they have opposite sign") cases[0] = cases[0] + 1 elif (Na-Nb) * (p0-p1) > 0: print("they have the same sign") cases[1] = cases[1] + 1 # one of them should be zero elif (Na-Nb) == 0: if (p0-p1) == 0: print("both are zero") cases[2] = cases[2] + 1 else: print("(Na-Nb) is zero, but (p0-p1) is nonzero") cases[3] = cases[3] + 1 elif (p0-p1) == 0: print("(Na-Nb) is nonzero, while (p0-p1) is zero") cases[4] = cases[4] + 1 # check the case(s) that are observed and the case(s) that are not observed print() # print an empty line print(cases)
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
# # A quantum circuit is composed by quantum and classical bits in Qiskit. # # here are the objects that we use to create a quantum circuit in qiskit from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit # we use a quantum register to keep our quantum bits. q = QuantumRegister(1,"qreg") # in this example we will use a single quantum bit # the second parameter is optional # To retrieve an information from a quantum bit, it must be measured. (More details will appear.) # The measurement result is stored classically. # Therefore, we also use a classical regiser with classical bit(s) c = ClassicalRegister(1,"creg") # in this example we will use a single classical bit # the second parameter is optional # now we can define our quantum circuit # it is composed by a quantum and a classical registers qc = QuantumCircuit(q,c) # we apply operators on quantum bits # operators are called as gates # we apply NOT operator represented as "x" in qiskit # operator is a part of the circuit, and we should specify the quantum bit as its parameter qc.x(q[0]) # (quantum) bits are enumerated starting from 0 # NOT operator or x-gate is applied to the first qubit of the quantum register # measurement is defined by associating a quantum bit to a classical bit qc.measure(q[0],c[0]) # after the measurement, the observed value of the quantum bit is stored in the classical bit # we run our codes until now, and then draw our circuit print("The design of the circuit is done.") # in Qiskit, the circuit object has a method called "draw" # the default drawing method uses ASCII art # let's draw our circuit now qc.draw() # re-execute this cell if you DO NOT see the circuit diagram # we can draw the same circuit by using matplotlib qc.draw(output='mpl') # we use the method "execute" and the object "Aer" from qiskit library from qiskit import execute, Aer # we create a job object for execution of the circuit # there are three parameters # 1. mycircuit # 2. backend on which it will be executed: we will use local simulator # 3. how many times it will be executed, by default it is 1024 job = execute(qc,Aer.get_backend('qasm_simulator'),shots=1024) # we can get the result of the outcome as follows counts = job.result().get_counts(qc) print(counts) # counts is a dictionary # we can show the result by using histogram as follows from qiskit.visualization import plot_histogram plot_histogram(counts) #print qasm code of our program print(qc.qasm()) # # A quantum circuit with four quantum and classical bits # # import all objects and methods at once from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer # define quantum and classical registers and then quantum circuit q2 = QuantumRegister(4,"qreg") c2 = ClassicalRegister(4,"creg") qc2 = QuantumCircuit(q2,c2) # apply x-gate to the first quantum bit twice qc2.x(q2[0]) qc2.x(q2[0]) # apply x-gate to the fourth quantum bit once qc2.x(q2[3]) # apply x-gate to the third quantum bit three times qc2.x(q2[2]) qc2.x(q2[2]) qc2.x(q2[2]) # apply x-gate to the second quantum bit four times qc2.x(q2[1]) qc2.x(q2[1]) qc2.x(q2[1]) qc2.x(q2[1]) # define a barrier (for a better visualization) qc2.barrier() # if the sizes of quantum and classical registers are the same, we can define measurements with a single line of code qc2.measure(q2,c2) # then quantum bits and classical bits are associated with respect to their indices # run the codes until now, and then draw our circuit print("The design of the circuit is done.") qc2.draw(output='mpl') # re-execute this cell if the circuit diagram does not appear # by seting parameter "reverse_bits" to "True", the order of quantum bits are reversed when drawing qc2.draw(output='mpl',reverse_bits=True) # re-execute this cell if the circuit diagram does not appear job = execute(qc2,Aer.get_backend('qasm_simulator'),shots=100) counts = job.result().get_counts(qc2) print(counts) from random import randrange n = 20 r=randrange(n) # pick a number from the list {0,1,...,n-1} print(r) # test this method by using a loop for i in range(10): print(randrange(n)) # # your solution is here # # we import all necessary methods and objects from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from random import randrange # we use 8 qubits and 8 classical bits q = QuantumRegister(8) c = ClassicalRegister(8) qc = QuantumCircuit(q,c) # we store the index of each qubit to which x-gate is applied picked_qubits=[] for i in range(8): if randrange(2) == 0: # Assume that 0 is Head and 1 is Tail qc.x(q[i]) # apply x-gate print("x-gate is applied to the qubit with index",i) picked_qubits.append(i) # i is picked # define a barrier qc.barrier() # measurement qc.measure(q,c) # draw the circuit #mycircuit.draw(reverse_bits=True) qc.draw(output='mpl',reverse_bits=True) # execute the circuit and read the results job = execute(qc,Aer.get_backend('qasm_simulator'),shots=128) counts = job.result().get_counts(qc) print(counts)
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
def biased_coin(N,B): from random import randrange random_number = randrange(N) if random_number < B: return "Heads" else: return "Tails" from random import randrange N = 1001 B = randrange(1000) total_tosses = 1000 the_number_of_heads = 0 for i in range(total_tosses): if biased_coin(N,B) == "Heads": the_number_of_heads = the_number_of_heads + 1 my_guess = the_number_of_heads/total_tosses real_bias = B/N error = abs(my_guess-real_bias)/real_bias*100 print("my guess is",my_guess) print("real bias is",real_bias) print("error (%) is",error) from random import randrange # let's pick a random number between {0,1,...,99} # it is expected to be less than 60 with probability 0.6 # and greater than or equal to 60 with probability 0.4 for experiment in [100,1000,10000,100000]: heads = tails = 0 for i in range(experiment): if randrange(100) <40: heads = heads + 1 # with probability 0.6 else: tails = tails + 1 # with probability 0.4 print("experiment:",experiment) print("heads =",heads," tails = ",tails) print("the ratio of #heads/#tails is",(round(heads/tails,4))) print() # empty line from qiskit import * q2 = QuantumRegister(2,"qreg") c2 = ClassicalRegister(2,"creg") qc2 = QuantumCircuit(q2,c2) ## Your code here qc2.x(q2[1]) qc2.measure(q2,c2) job = execute(qc2,Aer.get_backend('qasm_simulator'),shots=100) counts = job.result().get_counts(qc2) print(counts) # counts is a dictionary q = QuantumRegister(1) c = ClassicalRegister(1) qc = QuantumCircuit(q,c) #Your code here qc.x(0) qc.measure(q[0],c[0]) job = execute(qc,Aer.get_backend('qasm_simulator'),shots=1024) counts = job.result().get_counts(qc) print(counts) # counts is a dictionary q3 = QuantumRegister(4,"qreg") c3 = ClassicalRegister(4,"creg") qc3 = QuantumCircuit(q3,c3) #Your code here qc3.x(1) qc3.measure(q3,c3) job = execute(qc3,Aer.get_backend('qasm_simulator'),shots=1024) counts = job.result().get_counts(qc3) print(counts) # counts is a dictionary
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
# # your solution is here #
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
# # your code is here # (you may find the values by hand (in mind) as well) # # vector |v> print("vector |v>") values = [-0.1, -0.3, 0.4, 0.5] total = 0 # summation of squares for i in range(len(values)): total += values[i]**2; # add the square of each value print("total is ",total) print("the missing part is",1-total) print("so, the value of 'a' can be",(1-total)**0.5,"or",-(1-total)**0.5) # square root of the missing part print() print("vector |u>") values = [1/(2**0.5), -1/(3**0.5)] total = 0 # summation of squares for i in range(len(values)): total += values[i]**2; # add the square of each value print("total is ",total) print("the missing part is",1-total) # the missing part is 1/b, square of 1/sqrt(b) # thus, b is 1/missing_part print("so, the value of 'b' should be",1/(1-total)) # # you may define your first function in a separate cell # # randomly creating a 2-dimensional quantum state from random import randrange def random_quantum_state(): first_entry = randrange(-100,101) second_entry = randrange(-100,101) length_square = first_entry**2+second_entry**2 while length_square == 0: first_entry = randrange(-100,101) second_entry = randrange(-100,101) length_square = first_entry**2+second_entry**2 first_entry = first_entry / length_square**0.5 second_entry = second_entry / length_square**0.5 return [first_entry,second_entry] # # your code is here # # testing whether a given quantum state is valid def is_quantum_state(quantum_state): length_square = 0 for i in range(len(quantum_state)): length_square += quantum_state[i]**2 print("summation of entry squares is",length_square) # there might be precision problem # the length may be very close to 1 but not exactly 1 # so we use the following trick if (length_square - 1)**2 < 0.00000001: return True return False # else # defining a function for Hadamard multiplication def hadamard(quantum_state): result_quantum_state = [0,0] # define with zero entries result_quantum_state[0] = (1/(2**0.5)) * quantum_state[0] + (1/(2**0.5)) * quantum_state[1] result_quantum_state[1] = (1/(2**0.5)) * quantum_state[0] - (1/(2**0.5)) * quantum_state[1] return result_quantum_state # we are ready for i in range(10): picked_quantum_state=random_quantum_state() print(picked_quantum_state,"this is randomly picked quantum state") print("Is it valid?",is_quantum_state(picked_quantum_state)) new_quantum_state = hadamard(picked_quantum_state) print(new_quantum_state,"this is new quantum state") print("Is it valid?",is_quantum_state(new_quantum_state)) print() # print an empty line
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
# import the drawing methods from matplotlib.pyplot import plot, figure, show # draw a figure figure(figsize=(6,6), dpi=80) # include our predefined functions %run qlatvia.py # draw the axes draw_axes() # draw the origin plot(0,0,'ro') # a point in red color # draw these quantum states as points (in blue, green, yellow, and cyan colors) plot(1,0,'bo') plot(0,1,'go') plot(-1,0,'yo') plot(0,-1,'co') show() # import the drawing methods from matplotlib.pyplot import figure, arrow, show # draw a figure figure(figsize=(6,6), dpi=80) # include our predefined functions %run qlatvia.py # draw the axes draw_axes() # draw the quantum states as vectors (in red, blue, green, and yellow colors) arrow(0,0,0.92,0,head_width=0.04, head_length=0.08, color="r") arrow(0,0,0,0.92,head_width=0.04, head_length=0.08, color="b") arrow(0,0,-0.92,0,head_width=0.04, head_length=0.08, color="g") arrow(0,0,0,-0.92,head_width=0.04, head_length=0.08, color="y") show() # import the drawing methods from matplotlib.pyplot import plot, figure # draw a figure figure(figsize=(6,6), dpi=60) # draw the origin plot(0,0,'ro') from random import randrange colors = ['ro','bo','go','yo','co','mo','ko'] # # your solution is here # # randomly creating a 2-dimensional quantum state from random import randrange def random_quantum_state(): first_entry = randrange(-100,101) second_entry = randrange(-100,101) length_square = first_entry**2+second_entry**2 while length_square == 0: first_entry = randrange(-100,101) second_entry = randrange(-100,101) length_square = first_entry**2+second_entry**2 first_entry = first_entry / length_square**0.5 second_entry = second_entry / length_square**0.5 return [first_entry,second_entry] # import the drawing methods from matplotlib.pyplot import plot, figure, show # draw a figure figure(figsize=(6,6), dpi=60) # draw the origin plot(0,0,'ro') from random import randrange colors = ['ro','bo','go','yo','co','mo','ko'] for i in range(500): # create a random quantum state quantum_state = random_quantum_state(); # draw a blue point for the random quantum state x = quantum_state[0]; y = quantum_state[1]; plot(x,y,colors[randrange(len(colors))]) show() # import the drawing methods from matplotlib.pyplot import plot, figure, arrow # draw a figure figure(figsize=(6,6), dpi=60) # include our predefined functions %run qlatvia.py # draw the axes draw_axes() # draw the origin plot(0,0,'ro') from random import randrange colors = ['r','b','g','y','b','c','m'] # # your solution is here # # randomly creating a 2-dimensional quantum state from random import randrange def random_quantum_state(): first_entry = randrange(-100,101) second_entry = randrange(-100,101) length_square = first_entry**2+second_entry**2 while length_square == 0: first_entry = randrange(-100,101) second_entry = randrange(-100,101) length_square = first_entry**2+second_entry**2 first_entry = first_entry / length_square**0.5 second_entry = second_entry / length_square**0.5 return [first_entry,second_entry] # import the drawing methods from matplotlib.pyplot import plot, figure, arrow, show %run qlatvia.py # draw a figure figure(figsize=(6,6), dpi=60) draw_axes(); # draw the origin plot(0,0,'ro') from random import randrange colors = ['r','b','g','y','b','c','m'] for i in range(500): # create a random quantum state quantum_state = random_quantum_state(); # draw a blue vector for the random quantum state x = quantum_state[0]; y = quantum_state[1]; # shorten the line length to 0.92 # line_length + head_length (0.08) should be 1 x = 0.92 * x y = 0.92 * y arrow(0,0,x,y,head_width=0.04,head_length=0.08,color=colors[randrange(len(colors))]) show() # import the drawing methods from matplotlib.pyplot import figure figure(figsize=(6,6), dpi=80) # size of the figure # include our predefined functions %run qlatvia.py # draw axes draw_axes() # draw the unit circle draw_unit_circle() %run qlatvia.py draw_qubit() draw_quantum_state(3/5,4/5,"|v>") %run qlatvia.py draw_qubit() draw_quantum_state(3/5,4/5,"|v>") from matplotlib.pyplot import arrow, text, gca # the projection on |0>-axis arrow(0,0,3/5,0,color="blue",linewidth=1.5) arrow(0,4/5,3/5,0,color="blue",linestyle='dotted') text(0.1,-0.1,"cos(a)=3/5") # the projection on |1>-axis arrow(0,0,0,4/5,color="blue",linewidth=1.5) arrow(3/5,0,0,4/5,color="blue",linestyle='dotted') text(-0.1,0.55,"sin(a)=4/5",rotation="90") # drawing the angle with |0>-axis from matplotlib.patches import Arc gca().add_patch( Arc((0,0),0.4,0.4,angle=0,theta1=0,theta2=53) ) text(0.08,0.05,'.',fontsize=30) text(0.21,0.09,'a') # set the angle from random import randrange myangle = randrange(361) ################################################ from matplotlib.pyplot import figure,gca from matplotlib.patches import Arc from math import sin,cos,pi # draw a figure figure(figsize=(6,6), dpi=60) %run qlatvia.py draw_axes() print("the selected angle is",myangle,"degrees") ratio_of_arc = ((1000*myangle/360)//1)/1000 print("it is",ratio_of_arc,"of a full circle") print("its length is",ratio_of_arc,"x 2\u03C0","=",ratio_of_arc*2*pi) myangle_in_radian = 2*pi*(myangle/360) print("its radian value is",myangle_in_radian) gca().add_patch( Arc((0,0),0.2,0.2,angle=0,theta1=0,theta2=myangle,color="red",linewidth=2) ) gca().add_patch( Arc((0,0),2,2,angle=0,theta1=0,theta2=myangle,color="brown",linewidth=2) ) x = cos(myangle_in_radian) y = sin(myangle_in_radian) draw_quantum_state(x,y,"|v>") # the projection on |0>-axis arrow(0,0,x,0,color="blue",linewidth=1) arrow(0,y,x,0,color="blue",linestyle='dashed') # the projection on |1>-axis arrow(0,0,0,y,color="blue",linewidth=1) arrow(x,0,0,y,color="blue",linestyle='dashed') print() print("the amplitude of state |0> is",x) print("the amplitude of state |1> is",y) print() print("the probability of observing state |0> is",x*x) print("the probability of observing state |1> is",y*y) print("the total probability is",round(x*x+y*y,6)) # %%writefile FILENAME.py # your function is here from math import cos, sin, pi from random import randrange def random_quantum_state2(): angle_degree = randrange(360) angle_radian = 2*pi*angle_degree/360 return [cos(angle_radian),sin(angle_radian)] # include our predefined functions %run qlatvia.py # draw the axes draw_qubit() for i in range(6): [x,y]=random_quantum_state2() draw_quantum_state(x,y,"|v"+str(i)+">") # include our predefined functions %run qlatvia.py # draw the axes draw_qubit() for i in range(100): [x,y]=random_quantum_state2() draw_quantum_state(x,y,"")
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
# import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer # define a quantum register with a single qubit q = QuantumRegister(1,"q") # define a classical register with a single bit c = ClassicalRegister(1,"c") # define a quantum circuit qc = QuantumCircuit(q,c) # apply the first Hadamard qc.h(q[0]) # the first measurement qc.measure(q,c) # apply the second Hadamard if the measurement outcome is 0 qc.h(q[0]).c_if(c,0) # the second measurement qc.measure(q[0],c) # draw the circuit qc.draw(output="mpl") job = execute(qc,Aer.get_backend('qasm_simulator'),shots=1000) counts = job.result().get_counts(qc) print(counts) # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer # # your code is here # # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer # define a quantum register with a single qubit q = QuantumRegister(1) # define a classical register with a single bit c = ClassicalRegister(1,"c") # define a quantum circuit qc = QuantumCircuit(q,c) # start in state |1> qc.x(q[0]) # apply the first Hadamard qc.h(q[0]) # the first measurement qc.measure(q,c) # apply the second Hadamard if the measurement outcome is 1 qc.h(q[0]).c_if(c,1) # the second measurement qc.measure(q[0],c) # draw the circuit qc.draw(output="mpl") # execute the circuit 1000 times in the local simulator job = execute(qc,Aer.get_backend('qasm_simulator'),shots=1000) counts = job.result().get_counts(qc) print(counts) # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer # # your code is here # # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer # define a quantum register with a single qubit q = QuantumRegister(1) # define a classical register with a single bit c = ClassicalRegister(1,"c") # define a quantum circuit qc = QuantumCircuit(q,c) for i in range(3): qc.h(q[0]).c_if(c,0) qc.measure(q,c) # draw the circuit qc.draw(output="mpl") # execute the circuit 1000 times in the local simulator job = execute(qc,Aer.get_backend('qasm_simulator'),shots=1000) counts = job.result().get_counts(qc) print(counts) # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer # import randrange for random choices from random import randrange # # your code is here # # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer # import randrange for random choices from random import randrange # define a quantum register with a single qubit q = QuantumRegister(1) # define a classical register with a single bit c = ClassicalRegister(1,"c") # define a quantum circuit qc = QuantumCircuit(q,c) shot = 10000 observe = [0,0] qc.h(q[0]) qc.measure(q,c) observe = [shot/2,shot/2] for i in range(4): x = randrange(2) if x==0: observe[0] = observe[0] / 2 observe[1] = observe[1] + observe[0] else: observe[1] = observe[1] / 2 observe[0] = observe[0] + observe[1] qc.h(q[0]).c_if(c,x) qc.measure(q,c) # draw the circuit qc.draw(output="mpl") print('0:',round(observe[0]),'1:',round(observe[1])) # execute the circuit 10000 times in the local simulator job = execute(qc,Aer.get_backend('qasm_simulator'),shots=shot) counts = job.result().get_counts(qc) print(counts)
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
%run qlatvia.py draw_qubit() sqrttwo=2**0.5 draw_quantum_state(1,0,"") draw_quantum_state(1/sqrttwo,1/sqrttwo,"|+>") # drawing the angle with |0>-axis from matplotlib.pyplot import gca, text from matplotlib.patches import Arc gca().add_patch( Arc((0,0),0.4,0.4,angle=0,theta1=0,theta2=45) ) text(0.08,0.05,'.',fontsize=30) text(0.21,0.09,'\u03C0/4') %run qlatvia.py draw_qubit() sqrttwo=2**0.5 draw_quantum_state(0,1,"") draw_quantum_state(1/sqrttwo,-1/sqrttwo,"|->") # drawing the angle with |0>-axis from matplotlib.pyplot import gca, text from matplotlib.patches import Arc gca().add_patch( Arc((0,0),0.4,0.4,angle=0,theta1=-45,theta2=90) ) text(0.08,0.05,'.',fontsize=30) text(0.21,0.09,'3\u03C0/4') from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.visualization import plot_histogram from math import pi # we define a quantum circuit with one qubit and one bit q = QuantumRegister(1) # quantum register with a single qubit c = ClassicalRegister(1) # classical register with a single bit qc = QuantumCircuit(q,c) # quantum circuit with quantum and classical registers # angle of rotation in radian rotation_angle = 2*pi/3 # rotate the qubit with rotation_angle qc.ry(2*rotation_angle,q[0]) # measure the qubit qc.measure(q,c) # draw the circuit qc.draw(output='mpl') # execute the program 1000 times job = execute(qc,Aer.get_backend('qasm_simulator'),shots=1000) # print the results counts = job.result().get_counts(qc) print(counts) # draw the histogram plot_histogram(counts) from math import sin,cos # the quantum state quantum_state = [ cos(rotation_angle) , sin (rotation_angle) ] print("The quantum state is",round(quantum_state[0],4),"|0> +",round(quantum_state[1],4),"|1>") the_expected_number_of_zeros = 1000*cos(rotation_angle)**2 the_expected_number_of_ones = 1000*sin(rotation_angle)**2 # expected results print("The expected value of observing '0' is",round(the_expected_number_of_zeros,4)) print("The expected value of observing '1' is",round(the_expected_number_of_ones,4)) # draw the quantum state %run qlatvia.py draw_qubit() draw_quantum_state(quantum_state[0],quantum_state[1],"|v>") # # your code is here # from random import randrange from math import sin,cos, pi # randomly pick an angle random_angle = randrange(360) print("random angle is",random_angle) # pick angle in radian rotation_angle = random_angle/360*2*pi # the quantum state quantum_state = [ cos(rotation_angle) , sin (rotation_angle) ] the_expected_number_of_zeros = 1000*cos(rotation_angle)**2 the_expected_number_of_ones = 1000*sin(rotation_angle)**2 # expected results print("The expected value of observing '0' is",round(the_expected_number_of_zeros,4)) print("The expected value of observing '1' is",round(the_expected_number_of_ones,4)) # draw the quantum state %run qlatvia.py draw_qubit() draw_quantum_state(quantum_state[0],quantum_state[1],"|v>") from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.visualization import plot_histogram # we define a quantum circuit with one qubit and one bit q = QuantumRegister(1) # quantum register with a single qubit c = ClassicalRegister(1) # classical register with a single bit qc = QuantumCircuit(q,c) # quantum circuit with quantum and classical registers # rotate the qubit with rotation_angle qc.ry(2*rotation_angle,q[0]) # measure the qubit qc.measure(q,c) # draw the circuit qc.draw(output='mpl') # execute the program 1000 times job = execute(qc,Aer.get_backend('qasm_simulator'),shots=1000) # print the results counts = job.result().get_counts(qc) print(counts) the_observed_number_of_ones = 0 if '1' in counts: the_observed_number_of_ones= counts['1'] # draw the histogram plot_histogram(counts) difference = abs(the_expected_number_of_ones - the_observed_number_of_ones) print("The expected number of ones is",the_expected_number_of_ones) print("The observed number of ones is",the_observed_number_of_ones) print("The difference is",difference) print("The difference in percentage is",difference/100,"%")
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
%run qlatvia.py draw_qubit() sqrttwo=2**0.5 draw_quantum_state(1,0,"") draw_quantum_state(1/sqrttwo,1/sqrttwo,"|+>") # drawing the angle with |0>-axis from matplotlib.pyplot import gca, text from matplotlib.patches import Arc gca().add_patch( Arc((0,0),0.4,0.4,angle=0,theta1=0,theta2=45) ) text(0.08,0.05,'.',fontsize=30) text(0.21,0.09,'\u03C0/4') %run qlatvia.py draw_qubit() [x,y]=[1,0] draw_quantum_state(x,y,"v0") sqrttwo = 2**0.5 oversqrttwo = 1/sqrttwo R = [ [oversqrttwo, -1*oversqrttwo], [oversqrttwo,oversqrttwo] ] # # your code is here # # %run qlatvia.py draw_qubit() [x,y]=[1,0] draw_quantum_state(x,y,"v0") sqrttwo = 2**0.5 oversqrttwo = 1/sqrttwo R = [ [oversqrttwo, -1*oversqrttwo], [oversqrttwo,oversqrttwo] ] # function for rotation R def rotate(px,py): newx = R[0][0]*px + R[0][1]*py newy = R[1][0]*px + R[1][1]*py return [newx,newy] # apply rotation R 7 times for i in range(1,8): [x,y] = rotate(x,y) draw_quantum_state(x,y,"|v"+str(i)+">") %run qlatvia.py draw_qubit() [x,y]=[1,0] draw_quantum_state(x,y,"v0") # # your code is here # # %run qlatvia.py draw_qubit() [x,y]=[1,0] draw_quantum_state(x,y,"v0") from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi # we define a quantum circuit with one qubit and one bit q = QuantumRegister(1) # quantum register with a single qubit c = ClassicalRegister(1) # classical register with a single bit qc = QuantumCircuit(q,c) # quantum circuit with quantum and classical registers rotation_angle = pi/4 for i in range(1,9): # rotate the qubit with angle pi/4 qc.ry(2*rotation_angle,q[0]) # read the current quantum state job = execute(qc,Aer.get_backend('statevector_simulator'),optimization_level=0) current_quantum_state=job.result().get_statevector(qc) # print the current quantum state x_value = current_quantum_state[0].real # get the amplitude of |0> y_value = current_quantum_state[1].real # get the amplitude of |1> print("iteration",i,": the quantum state is (",round(x_value,3),") |0>","+(",round(y_value,3),") |1>") # draw the current quantum state draw_quantum_state(x_value,y_value,"|v"+str(i)+">") # # your code is here # %run qlatvia.py draw_qubit() from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi # we define a quantum circuit with one qubit and one bit q = QuantumRegister(1) # quantum register with a single qubit c = ClassicalRegister(1) # classical register with a single bit qc = QuantumCircuit(q,c) # quantum circuit with quantum and classical registers rotation_angle = pi/6 for i in range(1,13): # rotate the qubit with angle pi/4 qc.ry(2*rotation_angle,q[0]) # read the current quantum state job = execute(qc,Aer.get_backend('statevector_simulator'),optimization_level=0) current_quantum_state=job.result().get_statevector(qc) # print the current quantum state x_value = current_quantum_state[0].real # get the amplitude of |0> y_value = current_quantum_state[1].real # get the amplitude of |1> print("iteration",i,": the quantum state is (",round(x_value,3),") |0>","+(",round(y_value,3),") |1>") # draw the current quantum state draw_quantum_state(x_value,y_value,"|v"+str(i)+">") %run qlatvia.py draw_qubit() from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi # we define a quantum circuit with one qubit and one bit q = QuantumRegister(1) # quantum register with a single qubit c = ClassicalRegister(1) # classical register with a single bit qc = QuantumCircuit(q,c) # quantum circuit with quantum and classical registers rotation_angle = 3*pi/8 for i in range(1,17): # rotate the qubit with angle pi/4 qc.ry(2*rotation_angle,q[0]) # read the current quantum state job = execute(qc,Aer.get_backend('statevector_simulator'),optimization_level=0) current_quantum_state=job.result().get_statevector(qc) # print the current quantum state x_value = current_quantum_state[0].real # get the amplitude of |0> y_value = current_quantum_state[1].real # get the amplitude of |1> print("iteration",i,": the quantum state is (",round(x_value,3),") |0>","+(",round(y_value,3),") |1>") # draw the current quantum state draw_quantum_state(x_value,y_value,"|v"+str(i)+">") %run qlatvia.py draw_qubit() from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi # we define a quantum circuit with one qubit and one bit q = QuantumRegister(1) # quantum register with a single qubit c = ClassicalRegister(1) # classical register with a single bit qc = QuantumCircuit(q,c) # quantum circuit with quantum and classical registers rotation_angle = 2**(0.5) for i in range(1,21): # rotate the qubit with angle pi/4 qc.ry(2*rotation_angle,q[0]) # read the current quantum state job = execute(qc,Aer.get_backend('statevector_simulator'),optimization_level=0) current_quantum_state=job.result().get_statevector(qc) # print the current quantum state x_value = current_quantum_state[0].real # get the amplitude of |0> y_value = current_quantum_state[1].real # get the amplitude of |1> print("iteration",i,": the quantum state is (",round(x_value,3),") |0>","+(",round(y_value,3),") |1>") # draw the current quantum state draw_quantum_state(x_value,y_value,"|v"+str(i)+">") # # your code is here # from random import randrange from math import pi from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer # implement the experiment 10 times for i in range(10): # pick a random angle random_angle = randrange(3600)/10 # specify the angles rotation_angle1 = random_angle/360*2*pi rotation_angle2 = rotation_angle1 + pi/2 # # first qubit # q1 = QuantumRegister(1) c1 = ClassicalRegister(1) qc1 = QuantumCircuit(q1,c1) # rotate the qubit qc1.ry(2 * rotation_angle1,q1[0]) # read the quantum state job = execute(qc1,Aer.get_backend('statevector_simulator'),optimization_level=0) current_quantum_state1=job.result().get_statevector(qc1) [x1,y1]=[current_quantum_state1[0].real,current_quantum_state1[1].real] # # second qubit # q2 = QuantumRegister(1) c2 = ClassicalRegister(1) qc2 = QuantumCircuit(q2,c2) # rotate the qubit qc2.ry(2 * rotation_angle2,q2[0]) # read the quantum state job = execute(qc2,Aer.get_backend('statevector_simulator'),optimization_level=0) current_quantum_state2=job.result().get_statevector(qc2) [x2,y2]=[current_quantum_state2[0].real,current_quantum_state2[1].real] # # dot product # print(i,"- the result of dot product is ",round(x1*x2+y1*y2,5)) print("random angle is",random_angle) print("x1 , y1 =",round(x1,5),round(y1,5)) print("x2 , y2 =",round(x2,5),round(y2,5)) print() from random import randrange from math import pi from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer random_angle = randrange(3600)/10 rotation_angle1 = random_angle/360*2*pi rotation_angle2 = rotation_angle1 - pi/2 # we define a quantum circuit with one qubit and one bit q = QuantumRegister(1) # quantum register with a single qubit c = ClassicalRegister(1) # classical register with a single bit qc = QuantumCircuit(q,c) # quantum circuit with quantum and classical registers if randrange(2)==0: qc.ry(2 * rotation_angle1,q[0]) picked_angle = "theta1" else: qc.ry(2 * rotation_angle2,q[0]) picked_angle = "theta2" # # your code is here # your_guess = "" qc.ry(-2 * rotation_angle1,q[0]) # the new state will be either |0> or -|1> qc.measure(q,c) job = execute(qc,Aer.get_backend('qasm_simulator'),shots=100) counts = job.result().get_counts(qc) print(counts) if '0' in counts: your_guess = "theta1" else: your_guess = "theta2" ###################### print("your guess is",your_guess) print("picked_angle is",picked_angle)
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
%run qlatvia.py draw_qubit() draw_quantum_state(3/5,4/5,"u") draw_quantum_state(3/5,-4/5,"u'") # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer # import randrange for random choices from random import randrange # # your code is here # # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer # import randrange for random choices from random import randrange number_of_qubit = 5 # define a quantum register with 5 qubits q = QuantumRegister(number_of_qubit) # define a classical register with 5 bits c = ClassicalRegister(number_of_qubit) # define our quantum circuit qc = QuantumCircuit(q,c) # apply h-gate to all qubits for i in range(number_of_qubit): qc.h(q[i]) # apply z-gate to randomly picked qubits for i in range(number_of_qubit): if randrange(2) == 0: # the qubit with index i is picked to apply z-gate qc.z(q[i]) # apply h-gate to all qubits for i in range(number_of_qubit): qc.h(q[i]) qc.barrier() # measure all qubits qc.measure(q,c) # draw the circuit qc.draw(output='mpl') # execute the circuit 1000 times in the local simulator job = execute(qc,Aer.get_backend('qasm_simulator'),shots=1000) counts = job.result().get_counts(qc) print(counts) %run qlatvia.py draw_qubit() sqrttwo=2**0.5 draw_quantum_state(1,0,"") draw_quantum_state(1/sqrttwo,1/sqrttwo,"|+>") %run qlatvia.py draw_qubit() sqrttwo=2**0.5 draw_quantum_state(0,1,"") draw_quantum_state(1/sqrttwo,-1/sqrttwo,"|->") %run qlatvia.py draw_qubit() sqrttwo=2**0.5 draw_quantum_state(1,0,"") draw_quantum_state(1/sqrttwo,1/sqrttwo,"|+>") draw_quantum_state(0,1,"") draw_quantum_state(1/sqrttwo,-1/sqrttwo,"|->") # line of reflection for Hadamard from matplotlib.pyplot import arrow arrow(-1.109,-0.459,2.218,0.918,linestyle='dotted',color='red') # drawing the angle with |0>-axis from matplotlib.pyplot import gca, text from matplotlib.patches import Arc gca().add_patch( Arc((0,0),0.4,0.4,angle=0,theta1=0,theta2=22.5) ) text(0.09,0.015,'.',fontsize=30) text(0.25,0.03,'\u03C0/8') gca().add_patch( Arc((0,0),0.4,0.4,angle=0,theta1=22.5,theta2=45) ) text(0.075,0.065,'.',fontsize=30) text(0.21,0.16,'\u03C0/8') %run qlatvia.py draw_qubit() # line of reflection for Hadamard from matplotlib.pyplot import arrow arrow(-1.109,-0.459,2.218,0.918,linestyle='dotted',color='red') # # your code is here # # randomly create a 2-dimensional quantum state from math import cos, sin, pi from random import randrange def random_quantum_state2(): angle_degree = randrange(360) angle_radian = 2*pi*angle_degree/360 return [cos(angle_radian),sin(angle_radian)] %run qlatvia.py draw_qubit() # line of reflection for Hadamard from matplotlib.pyplot import arrow arrow(-1.109,-0.459,2.218,0.918,linestyle='dotted',color='red') [x1,y1] = random_quantum_state2() print(x1,y1) sqrttwo=2**0.5 oversqrttwo = 1/sqrttwo [x2,y2] = [ oversqrttwo*x1 + oversqrttwo*y1 , oversqrttwo*x1 - oversqrttwo*y1 ] print(x2,y2) draw_quantum_state(x1,y1,"main") draw_quantum_state(x2,y2,"ref") %run qlatvia.py draw_qubit() # the line y=x from matplotlib.pyplot import arrow arrow(-1,-1,2,2,linestyle='dotted',color='red') # # your code is here # # draw_quantum_state(x,y,"name") # randomly create a 2-dimensional quantum state from math import cos, sin, pi from random import randrange def random_quantum_state2(): angle_degree = randrange(360) angle_radian = 2*pi*angle_degree/360 return [cos(angle_radian),sin(angle_radian)] %run qlatvia.py draw_qubit() # the line y=x from matplotlib.pyplot import arrow arrow(-1,-1,2,2,linestyle='dotted',color='red') [x1,y1] = random_quantum_state2() [x2,y2] = [y1,x1] draw_quantum_state(x1,y1,"main") draw_quantum_state(x2,y2,"ref") %run qlatvia.py draw_qubit() # # your code is here # # line of reflection # from matplotlib.pyplot import arrow # arrow(x,y,dx,dy,linestyle='dotted',color='red') # # # draw_quantum_state(x,y,"name")
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
from qiskit import * q = QuantumRegister(2,"q") c = ClassicalRegister(2,"c") qc = QuantumCircuit(q,c) qc.x(q[0]) qc.measure(q[0],c[0]) qc.h(q[1]).c_if(c,0) qc.measure(q,c) print(qc) job = execute(qc,Aer.get_backend('qasm_simulator'),shots=1024) counts = job.result().get_counts(qc) print(counts) # counts is a dictionary q2 = QuantumRegister(2,"qreg") c2 = ClassicalRegister(2,"creg") qc2 = QuantumCircuit(q2,c2) qc2.x(q2[1]) qc2.z(q2[1]) qc2.measure(q2,c2) job = execute(qc2,Aer.get_backend('qasm_simulator'),shots=100) counts = job.result().get_counts(qc2) print(counts) # counts is a dictionary from math import pi q = QuantumRegister(1) # quantum register with a single qubit c = ClassicalRegister(1) # classical register with a single bit qc = QuantumCircuit(q,c) # quantum circuit with quantum and classical registers # rotate the qubit with rotation_angle qc.ry(2*(pi/3),q[0]) # measure the qubit qc.measure(q,c) job = execute(qc,Aer.get_backend('qasm_simulator'),shots=1000) counts = job.result().get_counts(qc) print(counts) # counts is a dictionary q2 = QuantumRegister(1,"qreg") c2 = ClassicalRegister(1,"creg") qc2 = QuantumCircuit(q2,c2) #Your code here1 qc2.x(q2[0]) #Your code here2 qc2.h(q2[0]) qc2.measure(q2,c2) job = execute(qc2,Aer.get_backend('qasm_simulator'),shots=100) counts = job.result().get_counts(qc2) print(counts) # counts is a dictionary
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
# class unknown_qubit # available_qubit = 1000 -> you get at most 1000 qubit copies # get_qubits(number_of_qubits) -> you get the specified number of qubits for your experiment # measure_qubits() -> your qubits are measured and the result is returned as a dictionary variable # -> after measurement, these qubits are destroyed # rotate_qubits(angle) -> your qubits are rotated with the specified angle in radian # compare_my_guess(my_angle) -> your guess in radian is compared with the real angle from random import randrange from math import pi from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer class unknown_qubit: def __init__(self): self.__theta = randrange(18000)/18000*pi self.__available_qubits = 1000 self.__active_qubits = 0 print(self.__available_qubits,"qubits are created") def get_qubits(self,number_of_qubits=None): if number_of_qubits is None or isinstance(number_of_qubits,int) is False or number_of_qubits < 1: print() print("ERROR: the method 'get_qubits' takes the number of qubit(s) as a positive integer, i.e., get_qubits(100)") elif number_of_qubits <= self.__available_qubits: self.__qc = QuantumCircuit(1,1) self.__qc.ry(2 * self.__theta,0) self.__active_qubits = number_of_qubits self.__available_qubits = self.__available_qubits - self.__active_qubits print() print("You have",number_of_qubits,"active qubits that are set to (cos(theta),sin(theta))") self.available_qubits() else: print() print("WARNING: you requested",number_of_qubits,"qubits, but there is not enough available qubits!") self.available_qubits() def measure_qubits(self): if self.__active_qubits > 0: self.__qc.measure(0,0) job = execute(self.__qc,Aer.get_backend('qasm_simulator'),shots=self.__active_qubits) counts = job.result().get_counts(self.__qc) print() print("your",self.__active_qubits,"qubits are measured") print("counts = ",counts) self.__active_qubits = 0 return counts else: print() print("WARNING: there is no active qubits -- you might first execute 'get_qubits()' method") self.available_qubits() def rotate_qubits(self,angle=None): if angle is None or (isinstance(angle,float) is False and isinstance(angle,int) is False): print() print("ERROR: the method 'rotate_qubits' takes a real-valued angle in radian as its parameter, i.e., rotate_qubits(1.2121)") elif self.__active_qubits > 0: self.__qc.ry(2 * angle,0) print() print("your active qubits are rotated by angle",angle,"in radian") else: print() print("WARNING: there is no active qubits -- you might first execute 'get_qubits()' method") self.available_qubits() def compare_my_guess(self,my_angle): if my_angle is None or (isinstance(my_angle,float) is False and isinstance(my_angle,int) is False): print("ERROR: the method 'compare_my_guess' takes a real-valued angle in radian as your guessed angle, i.e., compare_my_guess(1.2121)") else: self.__available_qubits = 0 diff = abs(my_angle-self.__theta) print() print(self.__theta,"is the original",) print(my_angle,"is your guess") print("the angle difference between the original theta and your guess is",diff/pi*180,"degree") print("-->the number of available qubits is (set to) zero, and so you cannot make any further experiment") def available_qubits(self): print("--> the number of available unused qubit(s) is",self.__available_qubits) from math import pi, cos, sin, acos, asin # an angle theta is randomly picked and it is fixed througout the experiment my_experiment = unknown_qubit() # # my_experiment.get_qubits(number_of_qubits) # my_experiment.rotate_qubits(angle) # my_experiment.measure_qubits() # my_experiment.compare_my_guess(my_angle) # # # your solution is here # # class unknown_qubit # available_qubit = 1000 -> you get at most 1000 qubit copies # get_qubits(number_of_qubits) -> you get the specified number of qubits for your experiment # measure_qubits() -> your qubits are measured and the result is returned as a dictionary variable # -> after measurement, these qubits are destroyed # rotate_qubits(angle) -> your qubits are rotated with the specified angle in radian # compare_my_guess(my_angle) -> your guess in radian is compared with the real angle from random import randrange from math import pi from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer class unknown_qubit: def __init__(self): self.__theta = randrange(18000)/18000*pi self.__available_qubits = 1000 self.__active_qubits = 0 print(self.__available_qubits,"qubits are created") def get_qubits(self,number_of_qubits=None): if number_of_qubits is None or isinstance(number_of_qubits,int) is False or number_of_qubits < 1: print() print("ERROR: the method 'get_qubits' takes the number of qubit(s) as a positive integer, i.e., get_qubits(100)") elif number_of_qubits <= self.__available_qubits: self.__qc = QuantumCircuit(1,1) self.__qc.ry(2 * self.__theta,0) self.__active_qubits = number_of_qubits self.__available_qubits = self.__available_qubits - self.__active_qubits print() print("You have",number_of_qubits,"active qubits that are set to (cos(theta),sin(theta))") self.available_qubits() else: print() print("WARNING: you requested",number_of_qubits,"qubits, but there is not enough available qubits!") self.available_qubits() def measure_qubits(self): if self.__active_qubits > 0: self.__qc.measure(0,0) job = execute(self.__qc,Aer.get_backend('qasm_simulator'),shots=self.__active_qubits) counts = job.result().get_counts(self.__qc) print() print("your",self.__active_qubits,"qubits are measured") print("counts = ",counts) self.__active_qubits = 0 return counts else: print() print("WARNING: there is no active qubits -- you might first execute 'get_qubits()' method") self.available_qubits() def rotate_qubits(self,angle=None): if angle is None or (isinstance(angle,float) is False and isinstance(angle,int) is False): print() print("ERROR: the method 'rotate_qubits' takes a real-valued angle in radian as its parameter, i.e., rotate_qubits(1.2121)") elif self.__active_qubits > 0: self.__qc.ry(2 * angle,0) print() print("your active qubits are rotated by angle",angle,"in radian") else: print() print("WARNING: there is no active qubits -- you might first execute 'get_qubits()' method") self.available_qubits() def compare_my_guess(self,my_angle): if my_angle is None or (isinstance(my_angle,float) is False and isinstance(my_angle,int) is False): print("ERROR: the method 'compare_my_guess' takes a real-valued angle in radian as your guessed angle, i.e., compare_my_guess(1.2121)") else: self.__available_qubits = 0 diff = abs(my_angle-self.__theta) print() print(self.__theta,"is the original",) print(my_angle,"is your guess") print("the angle difference between the original theta and your guess is",diff/pi*180,"degree") print("-->the number of available qubits is (set to) zero, and so you cannot make any further experiment") def available_qubits(self): print("--> the number of available unused qubit(s) is",self.__available_qubits) from math import pi, cos, sin, acos, asin my_experiment = unknown_qubit() # we use 900 copies to determine our two candidates my_experiment.get_qubits(900) counts = my_experiment.measure_qubits() number_of_observed_zeros = 0 if '0' in counts: number_of_observed_zeros = counts['0'] probability_of_observing_zeros = number_of_observed_zeros/900 cos_theta = probability_of_observing_zeros ** 0.5 theta = acos(cos_theta) theta_first_candidate = theta theta_second_candidate = pi-theta print("the first candidate is",theta_first_candidate,"in radian and",theta_first_candidate*180/pi,"in degree") print("the second candidate is",theta_second_candidate,"in radian and",theta_second_candidate*180/pi,"in degree") my_experiment.get_qubits(100) my_experiment.rotate_qubits(-1 * theta_first_candidate) counts = my_experiment.measure_qubits() number_of_observed_zeros = 0 if '0' in counts: number_of_observed_zeros = counts['0'] if number_of_observed_zeros == 100: my_guess = theta_first_candidate else: my_guess = theta_second_candidate my_experiment.compare_my_guess(my_guess) for i in range(10): print("Experiment",(i+1)) print("___________") print() my_experiment = unknown_qubit() my_experiment.get_qubits(900) counts = my_experiment.measure_qubits() number_of_observed_zeros = 0 if '0' in counts: number_of_observed_zeros = counts['0'] probability_of_observing_zeros = number_of_observed_zeros/900 cos_theta = probability_of_observing_zeros ** 0.5 theta = acos(cos_theta) theta_first_candidate = theta theta_second_candidate = pi-theta my_experiment.get_qubits(100) my_experiment.rotate_qubits(-1 * theta_first_candidate) counts = my_experiment.measure_qubits() number_of_observed_zeros = 0 if '0' in counts: number_of_observed_zeros = counts['0'] if number_of_observed_zeros == 100: my_guess = theta_first_candidate else: my_guess = theta_second_candidate my_experiment.compare_my_guess(my_guess) print() print() print() # # your solution #
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
from qiskit import QuantumCircuit # remark the coincise representation of a quantum circuit qc = QuantumCircuit(2) qc.h(0) qc.h(1) qc.draw(output='mpl',reverse_bits=True) from qiskit import execute, Aer job = execute(qc, Aer.get_backend('unitary_simulator'),shots=1,optimization_level=0) current_unitary = job.result().get_unitary(qc, decimals=3) for row in current_unitary: column = "" for entry in row: column = column + str(entry.real) + " " print(column) from qiskit import QuantumCircuit qc = QuantumCircuit(2) qc.h(1) qc.draw(output='mpl',reverse_bits=True) from qiskit import execute, Aer # # your code is here # from qiskit import QuantumCircuit qc = QuantumCircuit(2) qc.h(1) display(qc.draw(output='mpl',reverse_bits=True)) from qiskit import execute, Aer job = execute(qc, Aer.get_backend('unitary_simulator'),shots=1,optimization_level=0) current_unitary = job.result().get_unitary(qc, decimals=3) for row in current_unitary: column = "" for entry in row: column = column + str(round(entry.real,3)) + " " print(column) pairs = ['00','01','10','11'] for pair in pairs: from qiskit import QuantumCircuit, execute, Aer qc = QuantumCircuit(2,2) # initialize the pair # we follow the reading order in Qiskit # q1-tensor-q0 if pair[1] == '1': qc.x(0) if pair[0] =='1': qc.x(1) qc.cx(1,0) qc.measure(0,0) qc.measure(1,1) display(qc.draw(output='mpl',reverse_bits=True)) job = execute(qc,Aer.get_backend('qasm_simulator'),shots=1024) counts = job.result().get_counts(qc) print(pair,"--CNOT->",counts) # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer # import randrange for random choices from random import randrange # # your code is here # # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer # import randrange for random choices from random import randrange n = 5 m = 4 states_of_qubits = [] # we trace the state of each qubit also by ourselves q = QuantumRegister(n,"q") # quantum register with n qubits c = ClassicalRegister(n,"c") # classical register with n bits qc = QuantumCircuit(q,c) # quantum circuit with quantum and classical registers # set each qubit to |1> for i in range(n): qc.x(q[i]) # apply x-gate (NOT operator) states_of_qubits.append(1) # the state of each qubit is set to 1 # randomly pick m pairs of qubits for i in range(m): controller_qubit = randrange(n) target_qubit = randrange(n) # controller and target qubits should be different while controller_qubit == target_qubit: # if they are the same, we pick the target_qubit again target_qubit = randrange(n) # print our picked qubits print("the indices of the controller and target qubits are",controller_qubit,target_qubit) # apply cx-gate (CNOT operator) qc.cx(q[controller_qubit],q[target_qubit]) # we also trace the results if states_of_qubits[controller_qubit] == 1: # if the value of the controller qubit is 1, states_of_qubits[target_qubit] = 1 - states_of_qubits[target_qubit] # then flips the value of the target qubit # remark that 1-x gives the negation of x # measure the quantum register qc.barrier() qc.measure(q,c) # draw the circuit in reading order display(qc.draw(output='mpl',reverse_bits=True)) # execute the circuit 100 times in the local simulator job = execute(qc,Aer.get_backend('qasm_simulator'),shots=100) counts = job.result().get_counts(qc) print("the measurument result is",counts) our_result="" for state in states_of_qubits: our_result = str(state) + our_result print("our result is",our_result) # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer # # your code is here # # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer all_inputs=['00','01','10','11'] for input in all_inputs: q = QuantumRegister(2,"q") # quantum register with 2 qubits c = ClassicalRegister(2,"c") # classical register with 2 bits qc = QuantumCircuit(q,c) # quantum circuit with quantum and classical registers # initialize the inputs w.r.t the reading order of Qiskit if input[0]=='1': qc.x(q[1]) # set the state of the up qubit to |1> if input[1]=='1': qc.x(q[0]) # set the state of the down qubit to |1> # apply h-gate to both qubits qc.h(q[0]) qc.h(q[1]) # apply cx(up-qubit,down-qubit) qc.cx(q[1],q[0]) # apply h-gate to both qubits qc.h(q[0]) qc.h(q[1]) # measure both qubits qc.barrier() qc.measure(q,c) # draw the circuit w.r.t the reading order of Qiskit display(qc.draw(output='mpl',reverse_bits=True)) # execute the circuit 100 times in the local simulator job = execute(qc,Aer.get_backend('qasm_simulator'),shots=100) counts = job.result().get_counts(qc) print(input,"is mapped to",counts) # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer # # your code is here # # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer all_inputs=['00','01','10','11'] for input in all_inputs: q = QuantumRegister(2,"q") # quantum register with 2 qubits c = ClassicalRegister(2,"c") # classical register with 2 bits qc = QuantumCircuit(q,c) # quantum circuit with quantum and classical registers #initialize the inputs w.r.t the reading order of Qiskit if input[0]=='1': qc.x(q[1]) # set the state of the up qubit to |1> if input[1]=='1': qc.x(q[0]) # set the state of the down qubit to |1> # apply cx(up-qubit,down-qubit) qc.cx(q[1],q[0]) # apply cx(down-qubit,up-qubit) qc.cx(q[0],q[1]) # apply cx(up-qubit,down-qubit) qc.cx(q[1],q[0]) # measure both qubits qc.barrier() qc.measure(q,c) # draw the circuit w.r.t the reading order of Qiskit display(qc.draw(output='mpl',reverse_bits=True)) # execute the circuit 100 times in the local simulator job = execute(qc,Aer.get_backend('qasm_simulator'),shots=100) counts = job.result().get_counts(qc) print(input,"is mapped to",counts)
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
# import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer # # your code is here # # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer q = QuantumRegister(2,"q") # quantum register with 2 qubits c = ClassicalRegister(2,"c") # classical register with 2 bits qc = QuantumCircuit(q,c) # quantum circuit with quantum and classical registers # the up qubit is in |0> # set the down qubit to |1> qc.x(q[0]) # apply x-gate (NOT operator) qc.barrier() # apply Hadamard to both qubits. qc.h(q[0]) qc.h(q[1]) # apply CNOT operator, where the controller qubit is the up qubit and the target qubit is the down qubit. qc.cx(1,0) # apply Hadamard to both qubits. qc.h(q[0]) qc.h(q[1]) # measure both qubits qc.measure(q,c) # draw the circuit in Qiskit reading order display(qc.draw(output='mpl',reverse_bits=True)) # execute the circuit 100 times in the local simulator job = execute(qc,Aer.get_backend('qasm_simulator'),shots=100) counts = job.result().get_counts(qc) print(counts) # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer # # your code is here # # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer # Create a circuit with 7 qubits. q = QuantumRegister(7,"q") # quantum register with 7 qubits c = ClassicalRegister(7) # classical register with 7 bits qc = QuantumCircuit(q,c) # quantum circuit with quantum and classical registers # the top six qubits are already in |0> # set the bottom qubit to |1> qc.x(0) # apply x-gate (NOT operator) # define a barrier qc.barrier() # apply Hadamard to all qubits. for i in range(7): qc.h(q[i]) # define a barrier qc.barrier() # apply CNOT operator (q[1],q[0]) # apply CNOT operator (q[4],q[0]) # apply CNOT operator (q[5],q[0]) qc.cx(q[1],q[0]) qc.cx(q[4],q[0]) qc.cx(q[5],q[0]) # define a barrier qc.barrier() # apply Hadamard to all qubits. for i in range(7): qc.h(q[i]) # define a barrier qc.barrier() # measure all qubits qc.measure(q,c) # draw the circuit in Qiskit reading order display(qc.draw(output='mpl',reverse_bits=True)) # execute the circuit 100 times in the local simulator job = execute(qc,Aer.get_backend('qasm_simulator'),shots=100) counts = job.result().get_counts(qc) print(counts)
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer q = QuantumRegister(2, "q") c = ClassicalRegister(2, "c") qc = QuantumCircuit(q,c) qc.x(q[1]) qc.cx(q[1],q[0]) # Returning control qubit to the initial state qc.x(q[1]) job = execute(qc,Aer.get_backend('unitary_simulator'), shots = 1) U=job.result().get_unitary(qc,decimals=3) print("CNOT(0) = ") for row in U: s = "" for value in row: s = s + str(round(value.real,2)) + " " print(s) qc.draw(output="mpl", reverse_bits=True) # # your solution is here # from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer q = QuantumRegister(3,"q") c = ClassicalRegister(3,"c") qc = QuantumCircuit(q,c) qc.x(q[2]) qc.x(q[1]) qc.ccx(q[2],q[1],q[0]) qc.x(q[2]) qc.x(q[1]) job = execute(qc,Aer.get_backend('unitary_simulator'), shots = 1) U=job.result().get_unitary(qc,decimals=3) print("CCNOT(00) = ") for row in U: s = "" for value in row: s = s + str(round(value.real,2)) + " " print(s) qc.draw(output="mpl",reverse_bits=True) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer q = QuantumRegister(3,"q") c = ClassicalRegister(3,"c") qc = QuantumCircuit(q,c) qc.x(q[2]) qc.ccx(q[2],q[1],q[0]) qc.x(q[2]) job = execute(qc,Aer.get_backend('unitary_simulator'), shots = 1) U=job.result().get_unitary(qc,decimals=3) print("CCNOT(01) = ") for row in U: s = "" for value in row: s = s + str(round(value.real,2)) + " " print(s) qc.draw(output="mpl",reverse_bits=True) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer q = QuantumRegister(3,"q") c = ClassicalRegister(3,"c") qc = QuantumCircuit(q,c) qc.x(q[1]) qc.ccx(q[2],q[1],q[0]) qc.x(q[1]) job = execute(qc,Aer.get_backend('unitary_simulator'), shots = 1) U=job.result().get_unitary(qc,decimals=3) print("CCNOT(10) = ") for row in U: s = "" for value in row: s = s + str(round(value.real,2)) + " " print(s) qc.draw(output="mpl",reverse_bits=True) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer qaux = QuantumRegister(1,"qaux") q = QuantumRegister(4,"q") c = ClassicalRegister(4,"c") qc = QuantumCircuit(q,qaux,c) # step 1: set qaux to |1> if both q3 and q2 are in |1> qc.ccx(q[3],q[2],qaux[0]) # step 2: apply NOT gate to q0 if both qaux and q1 are in |1> qc.ccx(qaux[0],q[1],q[0]) # step 3: set qaux to |0> if both q3 and q2 are in |1> by reversing the affect of step 1 qc.ccx(q[3],q[2],qaux[0]) qc.draw(output="mpl",reverse_bits=True) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer all_inputs=[] for q3 in ['0','1']: for q2 in ['0','1']: for q1 in ['0','1']: for q0 in ['0','1']: all_inputs.append(q3+q2+q1+q0) # print(all_inputs) print("input --> output") for the_input in all_inputs: # create the circuit qaux = QuantumRegister(1,"qaux") q = QuantumRegister(4,"q") c = ClassicalRegister(4,"c") qc = QuantumCircuit(q,qaux,c) # set the initial value of the circuit w.r.t. the input if the_input[0] =='1': qc.x(q[3]) if the_input[1] =='1': qc.x(q[2]) if the_input[2] =='1': qc.x(q[1]) if the_input[3] =='1': qc.x(q[0]) # implement the CCNOT gates qc.ccx(q[3],q[2],qaux[0]) qc.ccx(qaux[0],q[1],q[0]) qc.ccx(q[3],q[2],qaux[0]) # measure the main quantum register qc.measure(q,c) # execute the circuit job = execute(qc,Aer.get_backend('qasm_simulator'),shots=1) counts = job.result().get_counts(qc) for key in counts: the_output = key printed_str = the_input[0:3]+" "+the_input[3]+" --> "+the_output[0:3]+" "+the_output[3] if (the_input!=the_output): printed_str = printed_str + " the output is different than the input" print(printed_str) # # your solution is here # from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer qaux = QuantumRegister(2,"qaux") q = QuantumRegister(5,"q") c = ClassicalRegister(5,"c") qc = QuantumCircuit(q,qaux,c) qc.ccx(q[4],q[3],qaux[1]) qc.ccx(q[2],q[1],qaux[0]) qc.ccx(qaux[1],qaux[0],q[0]) qc.ccx(q[4],q[3],qaux[1]) qc.ccx(q[2],q[1],qaux[0]) qc.draw(output="mpl",reverse_bits=True) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer all_inputs=[] for q4 in ['0','1']: for q3 in ['0','1']: for q2 in ['0','1']: for q1 in ['0','1']: for q0 in ['0','1']: all_inputs.append(q4+q3+q2+q1+q0) #print(all_inputs) print("input --> output") for the_input in all_inputs: # create the circuit qaux = QuantumRegister(2,"qaux") q = QuantumRegister(5,"q") c = ClassicalRegister(5,"c") qc = QuantumCircuit(q,qaux,c) # set the initial value of the circuit w.r.t. the input if the_input[0] =='1': qc.x(q[4]) if the_input[1] =='1': qc.x(q[3]) if the_input[2] =='1': qc.x(q[2]) if the_input[3] =='1': qc.x(q[1]) if the_input[4] =='1': qc.x(q[0]) # implement the CCNOT gates qc.ccx(q[4],q[3],qaux[1]) qc.ccx(q[2],q[1],qaux[0]) qc.ccx(qaux[1],qaux[0],q[0]) qc.ccx(q[4],q[3],qaux[1]) qc.ccx(q[2],q[1],qaux[0]) # measure the main quantum register qc.measure(q,c) # execute the circuit job = execute(qc,Aer.get_backend('qasm_simulator'),shots=1) counts = job.result().get_counts(qc) for key in counts: the_output = key printed_str = the_input[0:4]+" "+the_input[4]+" --> "+the_output[0:4]+" "+the_output[4] if (the_input!=the_output): printed_str = printed_str + " the output is different than the input" print(printed_str) # # your solution is here # from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer qaux = QuantumRegister(2,"qaux") q = QuantumRegister(5,"q") c = ClassicalRegister(5,"c") qc = QuantumCircuit(q,qaux,c) qc.x(q[3]) qc.x(q[1]) qc.ccx(q[4],q[3],qaux[1]) qc.ccx(q[2],q[1],qaux[0]) qc.ccx(qaux[1],qaux[0],q[0]) qc.ccx(q[4],q[3],qaux[1]) qc.ccx(q[2],q[1],qaux[0]) qc.x(q[3]) qc.x(q[1]) qc.draw(output="mpl",reverse_bits=True) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer all_inputs=[] for q4 in ['0','1']: for q3 in ['0','1']: for q2 in ['0','1']: for q1 in ['0','1']: for q0 in ['0','1']: all_inputs.append(q4+q3+q2+q1+q0) #print(all_inputs) print("input --> output") for the_input in all_inputs: # create the circuit qaux = QuantumRegister(2,"qaux") q = QuantumRegister(5,"q") c = ClassicalRegister(5,"c") qc = QuantumCircuit(q,qaux,c) # set the initial value of the circuit w.r.t. the input if the_input[0] =='1': qc.x(q[4]) if the_input[1] =='1': qc.x(q[3]) if the_input[2] =='1': qc.x(q[2]) if the_input[3] =='1': qc.x(q[1]) if the_input[4] =='1': qc.x(q[0]) # implement the CCNOT gates qc.x(q[3]) qc.x(q[1]) qc.ccx(q[4],q[3],qaux[1]) qc.ccx(q[2],q[1],qaux[0]) qc.ccx(qaux[1],qaux[0],q[0]) qc.ccx(q[4],q[3],qaux[1]) qc.ccx(q[2],q[1],qaux[0]) qc.x(q[3]) qc.x(q[1]) # measure the main quantum register qc.measure(q,c) # execute the circuit job = execute(qc,Aer.get_backend('qasm_simulator'),shots=1) counts = job.result().get_counts(qc) for key in counts: the_output = key printed_str = the_input[0:4]+" "+the_input[4]+" --> "+the_output[0:4]+" "+the_output[4] if (the_input!=the_output): printed_str = printed_str + " the output is different than the input" print(printed_str) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer all_inputs=[] for q4 in ['0','1']: for q3 in ['0','1']: for q2 in ['0','1']: for q1 in ['0','1']: for q0 in ['0','1']: all_inputs.append(q4+q3+q2+q1+q0) #print(all_inputs) def c4not(control_state='1111'): # # drawing the circuit # print("Control state is",control_state) print("Drawing the circuit:") qaux = QuantumRegister(2,"qaux") q = QuantumRegister(5,"q") c = ClassicalRegister(5,"c") qc = QuantumCircuit(q,qaux,c) for b in range(4): if control_state[b] == '0': qc.x(q[4-b]) qc.ccx(q[4],q[3],qaux[1]) qc.ccx(q[2],q[1],qaux[0]) qc.ccx(qaux[1],qaux[0],q[0]) qc.ccx(q[4],q[3],qaux[1]) qc.ccx(q[2],q[1],qaux[0]) for b in range(4): if control_state[b] == '0': qc.x(q[4-b]) display(qc.draw(output="mpl",reverse_bits=True)) # # executing the operator on all possible inputs # print("Control state is",control_state) print("input --> output") for the_input in all_inputs: # create the circuit qaux = QuantumRegister(2,"qaux") q = QuantumRegister(5,"q") c = ClassicalRegister(5,"c") qc = QuantumCircuit(q,qaux,c) # set the initial value of the circuit w.r.t. the input if the_input[0] =='1': qc.x(q[4]) if the_input[1] =='1': qc.x(q[3]) if the_input[2] =='1': qc.x(q[2]) if the_input[3] =='1': qc.x(q[1]) if the_input[4] =='1': qc.x(q[0]) # implement the CCNOT gates for b in range(4): if control_state[b] == '0': qc.x(q[4-b]) qc.ccx(q[4],q[3],qaux[1]) qc.ccx(q[2],q[1],qaux[0]) qc.ccx(qaux[1],qaux[0],q[0]) qc.ccx(q[4],q[3],qaux[1]) qc.ccx(q[2],q[1],qaux[0]) for b in range(4): if control_state[b] == '0': qc.x(q[4-b]) # measure the main quantum register qc.measure(q,c) # execute the circuit job = execute(qc,Aer.get_backend('qasm_simulator'),shots=1) counts = job.result().get_counts(qc) for key in counts: the_output = key printed_str = the_input[0:4]+" "+the_input[4]+" --> "+the_output[0:4]+" "+the_output[4] if (the_input!=the_output): printed_str = printed_str + " the output is different than the input" print(printed_str) # try different values #c4not() #c4not('1001') c4not('0011') #c4not('1101') #c4not('0000')
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
from qiskit import * q2=QuantumRegister(3,"qreg") c2=ClassicalRegister(3,"creg") qc2=QuantumCircuit(q2,c2) qc2.x(q2[1]) qc2.barrier() qc2.x(q2[2]) qc2.ccx(q2[2],q2[1],q2[0]) qc2.x(q2[2]) qc2.barrier() qc2.measure(q2,c2) job=execute(qc2,Aer.get_backend('qasm_simulator'),shots=100) counts=job.result().get_counts(qc2) print(counts) qc2.draw('mpl') q2 = QuantumRegister(2,"qreg") c2 = ClassicalRegister(2,"creg") qc2 = QuantumCircuit(q2,c2) qc2.h(q2[0]) qc2.cx(q2[0],q2[1]) #Your code here qc2.x(q2[0]) qc2.measure(q2,c2) job = execute(qc2,Aer.get_backend('qasm_simulator'),shots=1000) counts = job.result().get_counts(qc2) print(counts) # counts is a dictionary qc2.draw('mpl') qc = QuantumCircuit(2) #Your code here qc.h(1) qc.draw('mpl') q3=QuantumRegister(3,"qreg") c3=ClassicalRegister(3,"creg") qc3=QuantumCircuit(q3,c3) qc3.h(q3[0]) qc3.cx(q3[0],q3[1]) qc3.cx(q3[0],q3[2]) qc3.measure(q3,c3) job=execute(qc3,Aer.get_backend('qasm_simulator'),shots=1000) counts=job.result().get_counts(qc3) print(counts) qc3.draw('mpl')
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
# import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer all_pairs = ['00','01','10','11'] # # your code is here # # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer all_pairs = ['00','01','10','11'] for pair in all_pairs: # create a quantum curcuit with two qubits: Asja's and Balvis' qubits. # both are initially set to |0>. q = QuantumRegister(2,"q") # quantum register with 2 qubits c = ClassicalRegister(2,"c") # classical register with 2 bits qc = QuantumCircuit(q,c) # quantum circuit with quantum and classical registers # apply h-gate (Hadamard) to the Asja's qubit qc.h(q[1]) # apply cx-gate as CNOT(Asja's-qubit,Balvis'-qubit) qc.cx(q[1],q[0]) # they are separated from each other now # if a is 1, then apply z-gate to Asja's qubit if pair[0]=='1': qc.z(q[1]) # if b is 1, then apply x-gate (NOT) to Asja's qubit if pair[1]=='1': qc.x(q[1]) # Asja sends her qubit to Balvis qc.barrier() # apply cx-gate as CNOT(Asja's-qubit,Balvis'-qubit) qc.cx(q[1],q[0]) # apply h-gate (Hadamard) to the Asja's qubit qc.h(q[1]) # measure both qubits qc.barrier() qc.measure(q,c) # draw the circuit in Qiskit's reading order display(qc.draw(output='mpl',reverse_bits=True)) # compare the results with pair (a,b) job = execute(qc,Aer.get_backend('qasm_simulator'),shots=100) counts = job.result().get_counts(qc) print(pair,"-->",counts) # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer all_pairs = ['00','01','10','11'] # # your code is here # # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer all_pairs = ['00','01','10','11'] for pair in all_pairs: # create a quantum curcuit with two qubits: Asja's and Balvis' qubits. # both are initially set to |0>. q = QuantumRegister(2,"q") # quantum register with 2 qubits c = ClassicalRegister(2,"c") # classical register with 2 bits qc = QuantumCircuit(q,c) # quantum circuit with quantum and classical registers # apply h-gate (Hadamard) to the Asja's qubit qc.h(q[1]) # apply cx-gate as CNOT(Asja's-qubit,Balvis'-qubit) qc.cx(q[1],q[0]) # they are separated from each other now # if a is 1, then apply z-gate to Balvis' qubit if pair[0]=='1': qc.z(q[0]) # if b is 1, then apply x-gate (NOT) to Balvis' qubit if pair[1]=='1': qc.x(q[0]) # Balvis sends his qubit to Asja qc.barrier() # apply cx-gate as CNOT(Asja's-qubit,Balvis'-qubit) qc.cx(q[1],q[0]) # apply h-gate (Hadamard) to the Asja's qubit qc.h(q[1]) # measure both qubits qc.barrier() qc.measure(q,c) # draw the circuit in Qiskit's reading order display(qc.draw(output='mpl',reverse_bits=True)) # compare the results with pair (a,b) job = execute(qc,Aer.get_backend('qasm_simulator'),shots=100) counts = job.result().get_counts(qc) print(pair,"-->",counts)
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
# # your code is here # from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi, cos, sin from random import randrange # quantum circuit with three qubits and three bits q = QuantumRegister(3,"q") c = ClassicalRegister(3,"c") qc = QuantumCircuit(q,c) # rotate the first qubit by random angle r = randrange(100) theta = 2*pi*(r/100) # radians print("the picked angle is",r*3.6,"degrees and",theta,"radians") a = cos(theta) b = sin(theta) print("a=",round(a,3),"b=",round(b,3)) print("a*a=",round(a**2,3),"b*b=",round(b**2,3)) qc.ry(2*theta,q[2]) # creating an entanglement between q[1] and q[0] qc.h(q[1]) qc.cx(q[1],q[0]) # CNOT operator by Asja on her qubits where q[2] is the control qubit qc.cx(q[2],q[1]) # Hadamard operator by Asja on q[2] qc.h(q[2]) # the measurement done by Asja qc.measure(q[2],c[2]) qc.measure(q[1],c[1]) # draw thw circuit display(qc.draw(output='mpl',reverse_bits=True)) # read the state vector job = execute(qc,Aer.get_backend('statevector_simulator'),optimization_level=0,shots=1) current_quantum_state=job.result().get_statevector(qc) print("the state vector is") for i in range(len(current_quantum_state)): print(current_quantum_state[i].real) print() classical_outcomes = ['00','01','10','11'] for i in range(4): if (current_quantum_state[2*i].real != 0) or (current_quantum_state[2*i+1].real != 0): print("the classical outcome is",classical_outcomes[i]) classical_outcome = classical_outcomes[i] balvis_state = [ current_quantum_state[2*i].real,current_quantum_state[2*i+1].real ] print() readable_quantum_state = "|"+classical_outcome+">" readable_quantum_state += "("+str(round(balvis_state[0],3))+"|0>+"+str(round(balvis_state[1],3))+"|1>)" print("the new quantum state is",readable_quantum_state) all_states = ['000','001','010','011','100','101','110','111'] balvis_state_str = "|"+classical_outcome+">(" for i in range(len(current_quantum_state)): if abs(current_quantum_state[i].real-a)<0.000001: balvis_state_str += "+a|"+ all_states[i][2]+">" elif abs(current_quantum_state[i].real+a)<0.000001: balvis_state_str += "-a|"+ all_states[i][2]+">" elif abs(current_quantum_state[i].real-b)<0.000001: balvis_state_str += "+b|"+ all_states[i][2]+">" elif abs(current_quantum_state[i].real+b)<0.000001: balvis_state_str += "-b|"+ all_states[i][2]+">" balvis_state_str += ")" print("the new quantum state is",balvis_state_str) # # your code is here # from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi, cos, sin from random import randrange # quantum circuit with three qubits and two bits q = QuantumRegister(3,"q") c1 = ClassicalRegister(1,"c1") c2 = ClassicalRegister(1,"c2") qc = QuantumCircuit(q,c1,c2) # rotate the first qubit by random angle r = randrange(100) theta = 2*pi*(r/100) # radians print("the picked angle is",r*3.6,"degrees and",theta,"radians") a = cos(theta) b = sin(theta) print("a=",round(a,4),"b=",round(b,4)) qc.ry(2*theta,q[2]) # creating an entanglement between q[1] and q[0] qc.h(q[1]) qc.cx(q[1],q[0]) # CNOT operator by Asja on her qubits where q[2] is the control qubit qc.cx(q[2],q[1]) # Hadamard operator by Asja on q[2] qc.h(q[2]) qc.barrier() # the measurement done by Asja qc.measure(q[2],c2) qc.measure(q[1],c1) qc.barrier() # post-processing done by Balvis qc.x(q[0]).c_if(c1,1) qc.z(q[0]).c_if(c2,1) # draw the circuit display(qc.draw(output='mpl',reverse_bits=True)) # read the state vector job = execute(qc,Aer.get_backend('statevector_simulator'),optimization_level=0,shots=1) current_quantum_state=job.result().get_statevector(qc) print("the state vector is") for i in range(len(current_quantum_state)): print(round(current_quantum_state[i].real,4)) print() classical_outcomes = ['00','01','10','11'] for i in range(4): if (current_quantum_state[2*i].real != 0) or (current_quantum_state[2*i+1].real != 0): print("the classical outcome is",classical_outcomes[i])
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi # the angle of rotation theta = pi/16 # we read streams of length 8, 16, 24, 32, 40, 48, 56, 64 for i in [8, 16, 24, 32, 40, 48, 56, 64]: # quantum circuit with one qubit and one bit qreg = QuantumRegister(1) creg = ClassicalRegister(1) mycircuit = QuantumCircuit(qreg,creg) # the stream of length i for j in range(i): mycircuit.ry(2*theta,qreg[0]) # apply one rotation for each symbol # we measure after reading the whole stream mycircuit.measure(qreg[0],creg[0]) # execute the circuit 100 times job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=100) counts = job.result().get_counts(mycircuit) d = i /8 if d % 2 == 0: print(i,"is even multiple of 8") else: print(i,"is odd multiple of 8") print("stream of lenght",i,"->",counts) print() from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi from random import randrange # the angle of rotation r = randrange(1,11) print("the picked angle is",r,"times of 2pi/11") print() theta = r*2*pi/11 # we read streams of length from 1 to 11 for i in range(1,12): # quantum circuit with one qubit and one bit qreg = QuantumRegister(1) creg = ClassicalRegister(1) mycircuit = QuantumCircuit(qreg,creg) # the stream of length i for j in range(i): mycircuit.ry(2*theta,qreg[0]) # apply one rotation for each symbol # we measure after reading the whole stream mycircuit.measure(qreg[0],creg[0]) # execute the circuit 1000 times job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=1000) counts = job.result().get_counts(mycircuit) print("stream of lenght",i,"->",counts) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi from random import randrange # for each stream of length from 1 to 10 for i in range(1,11): # we try each angle of the form k*2*pi/11 for k=1,...,10 # we try to find the best k for which we observe 1 the most number_of_one_state = 0 best_k = 1 all_outcomes_for_i = "length "+str(i)+"-> " for k in range(1,11): theta = k*2*pi/11 # quantum circuit with one qubit and one bit qreg = QuantumRegister(1) creg = ClassicalRegister(1) mycircuit = QuantumCircuit(qreg,creg) # the stream of length i for j in range(i): mycircuit.ry(2*theta,qreg[0]) # apply one rotation for each symbol # we measure after reading the whole stream mycircuit.measure(qreg[0],creg[0]) # execute the circuit 10000 times job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=10000) counts = job.result().get_counts(mycircuit) all_outcomes_for_i = all_outcomes_for_i + str(k)+ ":" + str(counts['1']) + " " if int(counts['1']) > number_of_one_state: number_of_one_state = counts['1'] best_k = k print(all_outcomes_for_i) print("for length",i,", the best k is",best_k) print() from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi from random import randrange # the angles of rotations theta1 = 3*2*pi/31 theta2 = 7*2*pi/31 theta3 = 11*2*pi/31 # we read streams of length from 1 to 30 for i in range(1,31): # quantum circuit with three qubits and three bits qreg = QuantumRegister(3) creg = ClassicalRegister(3) mycircuit = QuantumCircuit(qreg,creg) # the stream of length i for j in range(i): # apply rotations for each symbol mycircuit.ry(2*theta1,qreg[0]) mycircuit.ry(2*theta2,qreg[1]) mycircuit.ry(2*theta3,qreg[2]) # we measure after reading the whole stream mycircuit.measure(qreg,creg) # execute the circuit N times N = 1000 job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=N) counts = job.result().get_counts(mycircuit) print(counts) if '000' in counts.keys(): c = counts['000'] else: c = 0 print('000 is observed',c,'times out of',N) percentange = round(c/N*100,1) print("the ratio of 000 is ",percentange,"%") print() from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi from random import randrange # randomly picked angles of rotations k1 = randrange(1,31) theta1 = k1*2*pi/31 k2 = randrange(1,31) theta2 = k2*2*pi/31 k3 = randrange(1,31) theta3 = k3*2*pi/31 print("k1 =",k1,"k2 =",k2,"k3 =",k3) print() max_percentange = 0 # we read streams of length from 1 to 30 for i in range(1,31): k1 = randrange(1,31) theta1 = k1*2*pi/31 k2 = randrange(1,31) theta2 = k2*2*pi/31 k3 = randrange(1,31) theta3 = k3*2*pi/31 # quantum circuit with three qubits and three bits qreg = QuantumRegister(3) creg = ClassicalRegister(3) mycircuit = QuantumCircuit(qreg,creg) # the stream of length i for j in range(i): # apply rotations for each symbol mycircuit.ry(2*theta1,qreg[0]) mycircuit.ry(2*theta2,qreg[1]) mycircuit.ry(2*theta3,qreg[2]) # we measure after reading the whole stream mycircuit.measure(qreg,creg) # execute the circuit N times N = 1000 job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=N) counts = job.result().get_counts(mycircuit) # print(counts) if '000' in counts.keys(): c = counts['000'] else: c = 0 # print('000 is observed',c,'times out of',N) percentange = round(c/N*100,1) if max_percentange < percentange: max_percentange = percentange # print("the ration of 000 is ",percentange,"%") # print() print("max percentage is",max_percentange) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi from random import randrange number_of_qubits = 4 #number_of_qubits = 5 # randomly picked angles of rotations theta = [] for i in range(number_of_qubits): k = randrange(1,31) print("k",str(i),"=",k) theta += [k*2*pi/31] # print(theta) # we count the number of zeros zeros = '' for i in range(number_of_qubits): zeros = zeros + '0' print("zeros = ",zeros) print() max_percentange = 0 # we read streams of length from 1 to 30 for i in range(1,31): # quantum circuit with qubits and bits qreg = QuantumRegister(number_of_qubits) creg = ClassicalRegister(number_of_qubits) mycircuit = QuantumCircuit(qreg,creg) # the stream of length i for j in range(i): # apply rotations for each symbol for k in range(number_of_qubits): mycircuit.ry(2*theta[k],qreg[k]) # we measure after reading the whole stream mycircuit.measure(qreg,creg) # execute the circuit N times N = 1000 job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=N) counts = job.result().get_counts(mycircuit) # print(counts) if zeros in counts.keys(): c = counts[zeros] else: c = 0 # print('000 is observed',c,'times out of',N) percentange = round(c/N*100,1) if max_percentange < percentange: max_percentange = percentange # print("the ration of 000 is ",percentange,"%") # print() print("max percentage is",max_percentange)
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer q = QuantumRegister(2, "q") c = ClassicalRegister(2, "c") qc = QuantumCircuit(q,c) qc.x(q[1]) qc.cx(q[1],q[0]) # Returning control qubit to the initial state qc.x(q[1]) job = execute(qc,Aer.get_backend('unitary_simulator'), shots = 1) U=job.result().get_unitary(qc,decimals=3) print("CNOT(0) = ") for row in U: s = "" for value in row: s = s + str(round(value.real,2)) + " " print(s) qc.draw(output="mpl", reverse_bits=True) # # your solution is here # from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer q = QuantumRegister(3,"q") c = ClassicalRegister(3,"c") qc = QuantumCircuit(q,c) qc.x(q[2]) qc.x(q[1]) qc.ccx(q[2],q[1],q[0]) qc.x(q[2]) qc.x(q[1]) job = execute(qc,Aer.get_backend('unitary_simulator'), shots = 1) U=job.result().get_unitary(qc,decimals=3) print("CCNOT(00) = ") for row in U: s = "" for value in row: s = s + str(round(value.real,2)) + " " print(s) qc.draw(output="mpl",reverse_bits=True) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer q = QuantumRegister(3,"q") c = ClassicalRegister(3,"c") qc = QuantumCircuit(q,c) qc.x(q[2]) qc.ccx(q[2],q[1],q[0]) qc.x(q[2]) job = execute(qc,Aer.get_backend('unitary_simulator'), shots = 1) U=job.result().get_unitary(qc,decimals=3) print("CCNOT(01) = ") for row in U: s = "" for value in row: s = s + str(round(value.real,2)) + " " print(s) qc.draw(output="mpl",reverse_bits=True) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer q = QuantumRegister(3,"q") c = ClassicalRegister(3,"c") qc = QuantumCircuit(q,c) qc.x(q[1]) qc.ccx(q[2],q[1],q[0]) qc.x(q[1]) job = execute(qc,Aer.get_backend('unitary_simulator'), shots = 1) U=job.result().get_unitary(qc,decimals=3) print("CCNOT(10) = ") for row in U: s = "" for value in row: s = s + str(round(value.real,2)) + " " print(s) qc.draw(output="mpl",reverse_bits=True) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer qaux = QuantumRegister(1,"qaux") q = QuantumRegister(4,"q") c = ClassicalRegister(4,"c") qc = QuantumCircuit(q,qaux,c) # step 1: set qaux to |1> if both q3 and q2 are in |1> qc.ccx(q[3],q[2],qaux[0]) # step 2: apply NOT gate to q0 if both qaux and q1 are in |1> qc.ccx(qaux[0],q[1],q[0]) # step 3: set qaux to |0> if both q3 and q2 are in |1> by reversing the affect of step 1 qc.ccx(q[3],q[2],qaux[0]) qc.draw(output="mpl",reverse_bits=True) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer all_inputs=[] for q3 in ['0','1']: for q2 in ['0','1']: for q1 in ['0','1']: for q0 in ['0','1']: all_inputs.append(q3+q2+q1+q0) # print(all_inputs) print("input --> output") for the_input in all_inputs: # create the circuit qaux = QuantumRegister(1,"qaux") q = QuantumRegister(4,"q") c = ClassicalRegister(4,"c") qc = QuantumCircuit(q,qaux,c) # set the initial value of the circuit w.r.t. the input if the_input[0] =='1': qc.x(q[3]) if the_input[1] =='1': qc.x(q[2]) if the_input[2] =='1': qc.x(q[1]) if the_input[3] =='1': qc.x(q[0]) # implement the CCNOT gates qc.ccx(q[3],q[2],qaux[0]) qc.ccx(qaux[0],q[1],q[0]) qc.ccx(q[3],q[2],qaux[0]) # measure the main quantum register qc.measure(q,c) # execute the circuit job = execute(qc,Aer.get_backend('qasm_simulator'),shots=1) counts = job.result().get_counts(qc) for key in counts: the_output = key printed_str = the_input[0:3]+" "+the_input[3]+" --> "+the_output[0:3]+" "+the_output[3] if (the_input!=the_output): printed_str = printed_str + " the output is different than the input" print(printed_str) # # your solution is here # from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer qaux = QuantumRegister(2,"qaux") q = QuantumRegister(5,"q") c = ClassicalRegister(5,"c") qc = QuantumCircuit(q,qaux,c) qc.ccx(q[4],q[3],qaux[1]) qc.ccx(q[2],q[1],qaux[0]) qc.ccx(qaux[1],qaux[0],q[0]) qc.ccx(q[4],q[3],qaux[1]) qc.ccx(q[2],q[1],qaux[0]) qc.draw(output="mpl",reverse_bits=True) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer all_inputs=[] for q4 in ['0','1']: for q3 in ['0','1']: for q2 in ['0','1']: for q1 in ['0','1']: for q0 in ['0','1']: all_inputs.append(q4+q3+q2+q1+q0) #print(all_inputs) print("input --> output") for the_input in all_inputs: # create the circuit qaux = QuantumRegister(2,"qaux") q = QuantumRegister(5,"q") c = ClassicalRegister(5,"c") qc = QuantumCircuit(q,qaux,c) # set the initial value of the circuit w.r.t. the input if the_input[0] =='1': qc.x(q[4]) if the_input[1] =='1': qc.x(q[3]) if the_input[2] =='1': qc.x(q[2]) if the_input[3] =='1': qc.x(q[1]) if the_input[4] =='1': qc.x(q[0]) # implement the CCNOT gates qc.ccx(q[4],q[3],qaux[1]) qc.ccx(q[2],q[1],qaux[0]) qc.ccx(qaux[1],qaux[0],q[0]) qc.ccx(q[4],q[3],qaux[1]) qc.ccx(q[2],q[1],qaux[0]) # measure the main quantum register qc.measure(q,c) # execute the circuit job = execute(qc,Aer.get_backend('qasm_simulator'),shots=1) counts = job.result().get_counts(qc) for key in counts: the_output = key printed_str = the_input[0:4]+" "+the_input[4]+" --> "+the_output[0:4]+" "+the_output[4] if (the_input!=the_output): printed_str = printed_str + " the output is different than the input" print(printed_str) # # your solution is here # from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer qaux = QuantumRegister(2,"qaux") q = QuantumRegister(5,"q") c = ClassicalRegister(5,"c") qc = QuantumCircuit(q,qaux,c) qc.x(q[3]) qc.x(q[1]) qc.ccx(q[4],q[3],qaux[1]) qc.ccx(q[2],q[1],qaux[0]) qc.ccx(qaux[1],qaux[0],q[0]) qc.ccx(q[4],q[3],qaux[1]) qc.ccx(q[2],q[1],qaux[0]) qc.x(q[3]) qc.x(q[1]) qc.draw(output="mpl",reverse_bits=True) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer all_inputs=[] for q4 in ['0','1']: for q3 in ['0','1']: for q2 in ['0','1']: for q1 in ['0','1']: for q0 in ['0','1']: all_inputs.append(q4+q3+q2+q1+q0) #print(all_inputs) print("input --> output") for the_input in all_inputs: # create the circuit qaux = QuantumRegister(2,"qaux") q = QuantumRegister(5,"q") c = ClassicalRegister(5,"c") qc = QuantumCircuit(q,qaux,c) # set the initial value of the circuit w.r.t. the input if the_input[0] =='1': qc.x(q[4]) if the_input[1] =='1': qc.x(q[3]) if the_input[2] =='1': qc.x(q[2]) if the_input[3] =='1': qc.x(q[1]) if the_input[4] =='1': qc.x(q[0]) # implement the CCNOT gates qc.x(q[3]) qc.x(q[1]) qc.ccx(q[4],q[3],qaux[1]) qc.ccx(q[2],q[1],qaux[0]) qc.ccx(qaux[1],qaux[0],q[0]) qc.ccx(q[4],q[3],qaux[1]) qc.ccx(q[2],q[1],qaux[0]) qc.x(q[3]) qc.x(q[1]) # measure the main quantum register qc.measure(q,c) # execute the circuit job = execute(qc,Aer.get_backend('qasm_simulator'),shots=1) counts = job.result().get_counts(qc) for key in counts: the_output = key printed_str = the_input[0:4]+" "+the_input[4]+" --> "+the_output[0:4]+" "+the_output[4] if (the_input!=the_output): printed_str = printed_str + " the output is different than the input" print(printed_str) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer all_inputs=[] for q4 in ['0','1']: for q3 in ['0','1']: for q2 in ['0','1']: for q1 in ['0','1']: for q0 in ['0','1']: all_inputs.append(q4+q3+q2+q1+q0) #print(all_inputs) def c4not(control_state='1111'): # # drawing the circuit # print("Control state is",control_state) print("Drawing the circuit:") qaux = QuantumRegister(2,"qaux") q = QuantumRegister(5,"q") c = ClassicalRegister(5,"c") qc = QuantumCircuit(q,qaux,c) for b in range(4): if control_state[b] == '0': qc.x(q[4-b]) qc.ccx(q[4],q[3],qaux[1]) qc.ccx(q[2],q[1],qaux[0]) qc.ccx(qaux[1],qaux[0],q[0]) qc.ccx(q[4],q[3],qaux[1]) qc.ccx(q[2],q[1],qaux[0]) for b in range(4): if control_state[b] == '0': qc.x(q[4-b]) display(qc.draw(output="mpl",reverse_bits=True)) # # executing the operator on all possible inputs # print("Control state is",control_state) print("input --> output") for the_input in all_inputs: # create the circuit qaux = QuantumRegister(2,"qaux") q = QuantumRegister(5,"q") c = ClassicalRegister(5,"c") qc = QuantumCircuit(q,qaux,c) # set the initial value of the circuit w.r.t. the input if the_input[0] =='1': qc.x(q[4]) if the_input[1] =='1': qc.x(q[3]) if the_input[2] =='1': qc.x(q[2]) if the_input[3] =='1': qc.x(q[1]) if the_input[4] =='1': qc.x(q[0]) # implement the CCNOT gates for b in range(4): if control_state[b] == '0': qc.x(q[4-b]) qc.ccx(q[4],q[3],qaux[1]) qc.ccx(q[2],q[1],qaux[0]) qc.ccx(qaux[1],qaux[0],q[0]) qc.ccx(q[4],q[3],qaux[1]) qc.ccx(q[2],q[1],qaux[0]) for b in range(4): if control_state[b] == '0': qc.x(q[4-b]) # measure the main quantum register qc.measure(q,c) # execute the circuit job = execute(qc,Aer.get_backend('qasm_simulator'),shots=1) counts = job.result().get_counts(qc) for key in counts: the_output = key printed_str = the_input[0:4]+" "+the_input[4]+" --> "+the_output[0:4]+" "+the_output[4] if (the_input!=the_output): printed_str = printed_str + " the output is different than the input" print(printed_str) # try different values #c4not() #c4not('1001') c4not('0011') #c4not('1101') #c4not('0000')
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi # the angles of rotations theta1 = pi/4 theta2 = pi/6 # the circuit with two qubits qreg = QuantumRegister(2) creg = ClassicalRegister(2) mycircuit = QuantumCircuit(qreg,creg) # when the second qubit is in |0>, the first qubit is rotated by theta1 mycircuit.x(qreg[1]) mycircuit.cu3(2*theta1,0,0,qreg[1],qreg[0]) mycircuit.x(qreg[1]) # when the second qubit is in |1>, the first qubit is rotated by theta2 mycircuit.cu3(2*theta2,0,0,qreg[1],qreg[0]) # we read the unitary matrix job = execute(mycircuit,Aer.get_backend('unitary_simulator'),optimization_level=0) u=job.result().get_unitary(mycircuit,decimals=3) # we print the unitary matrix in nice format for i in range(len(u)): s="" for j in range(len(u)): val = str(u[i][j].real) while(len(val)<8): val = " "+val s = s + val print(s) from math import pi, sin, cos theta1 = pi/4 theta2 = pi/6 print(round(cos(theta1),3),-round(sin(theta1),3),0,0) print(round(sin(theta1),3),-round(cos(theta1),3),0,0) print(0,0,round(cos(theta2),3),-round(sin(theta2),3)) print(0,0,round(sin(theta2),3),-round(cos(theta2),3)) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi, sin, cos # the angle of rotation theta1 = pi/23 theta2 = 2*pi/23 theta3 = 4*pi/23 precision = 3 print("a1 = theta3 => sin(a1) = ",round(sin(theta3),precision)) print("a2 = theta2+theta3 => sin(a2) = ",round(sin(theta2+theta3),precision)) print("a3 = theta1 => sin(a3) = ",round(sin(theta1),precision)) print("a4 = theta1+theta2 => sin(a4) = ",round(sin(theta1+theta2),precision)) print() qreg = QuantumRegister(3) creg = ClassicalRegister(3) circuit = QuantumCircuit(qreg,creg) # controlled rotation when the third qubit is |1> circuit.cu3(2*theta1,0,0,qreg[2],qreg[0]) # controlled rotation when the second qubit is |1> circuit.cu3(2*theta2,0,0,qreg[1],qreg[0]) # controlled rotation when the third qubit is |0> circuit.x(qreg[2]) circuit.cu3(2*theta3,0,0,qreg[2],qreg[0]) circuit.x(qreg[2]) # read the corresponding unitary matrix job = execute(circuit,Aer.get_backend('unitary_simulator'),optimization_level=0) unitary_matrix=job.result().get_unitary(circuit,decimals=precision) for i in range(len(unitary_matrix)): s="" for j in range(len(unitary_matrix)): val = str(unitary_matrix[i][j].real) while(len(val)<precision+4): val = " "+val s = s + val print(s) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi, sin, cos from random import randrange # the angle of rotation k1 = randrange(1,31) theta1 = k1*2*pi/31 k2 = randrange(1,31) theta2 = k2*2*pi/31 k3 = randrange(1,31) theta3 = k3*2*pi/31 max_percentange = 0 # for each stream of length from 1 to 31 for i in range(1,32): # initialize the circuit qreg = QuantumRegister(3) creg = ClassicalRegister(3) circuit = QuantumCircuit(qreg,creg) # Hadamard operators before reading the stream for m in range(3): circuit.h(qreg[m]) # read the stream of length i print("stream of length",i,"is being read") for j in range(i): # controlled rotation when the third qubit is |1> circuit.cu3(2*theta1,0,0,qreg[2],qreg[0]) # controlled rotation when the second qubit is |1> circuit.cu3(2*theta2,0,0,qreg[1],qreg[0]) # controlled rotation when the third qubit is |0> circuit.x(qreg[2]) circuit.cu3(2*theta3,0,0,qreg[2],qreg[0]) circuit.x(qreg[2]) # Hadamard operators after reading the stream for m in range(3): circuit.h(qreg[m]) # we measure after reading the whole stream circuit.measure(qreg,creg) # execute the circuit N times N = 1000 job = execute(circuit,Aer.get_backend('qasm_simulator'),shots=N) counts = job.result().get_counts(circuit) print(counts) if '000' in counts.keys(): c = counts['000'] else: c = 0 print('000 is observed',c,'times out of',N) percentange = round(c/N*100,1) if max_percentange < percentange and i != 31: max_percentange = percentange print("the ration of 000 is ",percentange,"%") print() print("maximum percentage of observing unwanted '000' is",max_percentange) # # your solution is here # from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi # initialize the circuit qreg = QuantumRegister(4) circuit = QuantumCircuit(qreg) # we use the fourth qubit as the auxiliary # apply a rotation to the first qubit when the third and second qubits are in states |0> and |1> # change the state of the third qubit to |1> circuit.x(qreg[2]) # if both the third and second qubits are in states |1>, the state of auxiliary qubit is changed to |1> circuit.ccx(qreg[2],qreg[1],qreg[3]) # the rotation is applied to the first qubit if the state of auxiliary qubit is |1> circuit.cu3(2*pi/6,0,0,qreg[3],qreg[0]) # reverse the effects circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.x(qreg[2]) circuit.draw() from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi,sin # the angles of rotations theta1 = pi/10 theta2 = 2*pi/10 theta3 = 3*pi/10 theta4 = 4*pi/10 # for verification, print sin(theta)'s print("sin(theta1) = ",round(sin(theta1),3)) print("sin(theta2) = ",round(sin(theta2),3)) print("sin(theta3) = ",round(sin(theta3),3)) print("sin(theta4) = ",round(sin(theta4),3)) print() qreg = QuantumRegister(4) circuit = QuantumCircuit(qreg) # the third qubit is in |0> # the second qubit is in |0> circuit.x(qreg[2]) circuit.x(qreg[1]) circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.cu3(2*theta1,0,0,qreg[3],qreg[0]) # reverse the effects circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.x(qreg[1]) circuit.x(qreg[2]) # the third qubit is in |0> # the second qubit is in |1> circuit.x(qreg[2]) circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.cu3(2*theta2,0,0,qreg[3],qreg[0]) # reverse the effects circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.x(qreg[2]) # the third qubit is in |1> # the second qubit is in |0> circuit.x(qreg[1]) circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.cu3(2*theta3,0,0,qreg[3],qreg[0]) # reverse the effects circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.x(qreg[1]) # the third qubit is in |1> # the second qubit is in |1> circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.cu3(2*theta4,0,0,qreg[3],qreg[0]) # reverse the effects circuit.ccx(qreg[2],qreg[1],qreg[3]) # read the corresponding unitary matrix job = execute(circuit,Aer.get_backend('unitary_simulator'),optimization_level=0) unitary_matrix=job.result().get_unitary(circuit,decimals=3) for i in range(len(unitary_matrix)): s="" for j in range(len(unitary_matrix)): val = str(unitary_matrix[i][j].real) while(len(val)<7): val = " "+val s = s + val print(s) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi,sin from random import randrange # the angle of rotation k1 = randrange(1,61) theta1 = k1*2*pi/61 k2 = randrange(1,61) theta2 = k2*2*pi/61 k3 = randrange(1,61) theta3 = k3*2*pi/61 k4 = randrange(1,61) theta4 = k4*2*pi/61 max_percentange = 0 # for each stream of length of 1, 11, 21, 31, 41, 51, and 61 for i in [1,11,21,31,41,51,61]: #for i in range(1,62): # initialize the circuit qreg = QuantumRegister(4) creg = ClassicalRegister(4) circuit = QuantumCircuit(qreg,creg) # Hadamard operators before reading the stream for m in range(3): circuit.h(qreg[m]) # read the stream of length i print("stream of length",i,"is being read") for j in range(i): # the third qubit is in |0> # the second qubit is in |0> circuit.x(qreg[2]) circuit.x(qreg[1]) circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.cu3(2*theta1,0,0,qreg[3],qreg[0]) # reverse the effects circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.x(qreg[1]) circuit.x(qreg[2]) # the third qubit is in |0> # the second qubit is in |1> circuit.x(qreg[2]) circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.cu3(2*theta2,0,0,qreg[3],qreg[0]) # reverse the effects circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.x(qreg[2]) # the third qubit is in |1> # the second qubit is in |0> circuit.x(qreg[1]) circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.cu3(2*theta3,0,0,qreg[3],qreg[0]) # reverse the effects circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.x(qreg[1]) # the third qubit is in |1> # the second qubit is in |1> circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.cu3(2*theta4,0,0,qreg[3],qreg[0]) # reverse the effects circuit.ccx(qreg[2],qreg[1],qreg[3]) # Hadamard operators after reading the stream for m in range(3): circuit.h(qreg[m]) # we measure after reading the whole stream circuit.measure(qreg,creg) # execute the circuit N times N = 1000 job = execute(circuit,Aer.get_backend('qasm_simulator'),shots=N) counts = job.result().get_counts(circuit) print(counts) if '0000' in counts.keys(): c = counts['0000'] else: c = 0 print('0000 is observed',c,'times out of',N) percentange = round(c/N*100,1) if max_percentange < percentange and i != 61: max_percentange = percentange print("the ration of 0000 is ",percentange,"%") print() print("maximum percentage of observing unwanted '0000' is",max_percentange) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi qreg11 = QuantumRegister(4) creg11 = ClassicalRegister(4) theta = pi/4 # define our quantum circuit mycircuit11 = QuantumCircuit(qreg11,creg11) def ccc_ry(angle,q1,q2,q3,q4): mycircuit11.cu3(angle/2,0,0,q3,q4) mycircuit11.ccx(q1,q2,q4) mycircuit11.cu3(-angle/2,0,0,q3,q4) mycircuit11.ccx(q1,q2,q4) ccc_ry(2*theta,qreg11[3],qreg11[2],qreg11[1],qreg11[0]) mycircuit11.draw(output='mpl') from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi qreg12 = QuantumRegister(4) creg12 = ClassicalRegister(4) theta1 = pi/16 theta2 = 2*pi/16 theta3 = 3*pi/16 theta4 = 4*pi/16 theta5 = 5*pi/16 theta6 = 6*pi/16 theta7 = 7*pi/16 theta8 = 8*pi/16 # define our quantum circuit mycircuit12 = QuantumCircuit(qreg12,creg12) def ccc_ry(angle,q1,q2,q3,q4): mycircuit12.cu3(angle/2,0,0,q3,q4) mycircuit12.ccx(q1,q2,q4) mycircuit12.cu3(-angle/2,0,0,q3,q4) mycircuit12.ccx(q1,q2,q4) mycircuit12.x(qreg12[3]) mycircuit12.x(qreg12[2]) mycircuit12.x(qreg12[1]) ccc_ry(2*theta1,qreg12[3],qreg12[2],qreg12[1],qreg12[0]) mycircuit12.x(qreg12[1]) mycircuit12.x(qreg12[2]) mycircuit12.x(qreg12[3]) mycircuit12.x(qreg12[3]) mycircuit12.x(qreg12[2]) #mycircuit12.x(qreg12[1]) ccc_ry(2*theta2,qreg12[3],qreg12[2],qreg12[1],qreg12[0]) #mycircuit12.x(qreg12[1]) mycircuit12.x(qreg12[2]) mycircuit12.x(qreg12[3]) mycircuit12.x(qreg12[3]) #mycircuit12.x(qreg12[2]) mycircuit12.x(qreg12[1]) ccc_ry(2*theta3,qreg12[3],qreg12[2],qreg12[1],qreg12[0]) mycircuit12.x(qreg12[1]) #mycircuit12.x(qreg12[2]) mycircuit12.x(qreg12[3]) mycircuit12.x(qreg12[3]) #mycircuit12.x(qreg12[2]) #mycircuit12.x(qreg12[1]) ccc_ry(2*theta4,qreg12[3],qreg12[2],qreg12[1],qreg12[0]) #mycircuit12.x(qreg12[1]) #mycircuit12.x(qreg12[2]) mycircuit12.x(qreg12[3]) #mycircuit12.x(qreg12[3]) mycircuit12.x(qreg12[2]) mycircuit12.x(qreg12[1]) ccc_ry(2*theta5,qreg12[3],qreg12[2],qreg12[1],qreg12[0]) mycircuit12.x(qreg12[1]) mycircuit12.x(qreg12[2]) #mycircuit12.x(qreg12[3]) #mycircuit12.x(qreg12[3]) mycircuit12.x(qreg12[2]) #mycircuit12.x(qreg12[1]) ccc_ry(2*theta6,qreg12[3],qreg12[2],qreg12[1],qreg12[0]) #mycircuit12.x(qreg12[1]) mycircuit12.x(qreg12[2]) #mycircuit12.x(qreg12[3]) #mycircuit12.x(qreg12[3]) #mycircuit12.x(qreg12[2]) mycircuit12.x(qreg12[1]) ccc_ry(2*theta7,qreg12[3],qreg12[2],qreg12[1],qreg12[0]) mycircuit12.x(qreg12[1]) #mycircuit12.x(qreg12[2]) #mycircuit12.x(qreg12[3]) #mycircuit12.x(qreg12[3]) #mycircuit12.x(qreg12[2]) #mycircuit12.x(qreg12[1]) ccc_ry(2*theta8,qreg12[3],qreg12[2],qreg12[1],qreg12[0]) #mycircuit12.x(qreg12[1]) #mycircuit12.x(qreg12[2]) #mycircuit12.x(qreg12[3]) job = execute(mycircuit12,Aer.get_backend('unitary_simulator'),optimization_level=0) u=job.result().get_unitary(mycircuit12,decimals=3) for i in range(len(u)): s="" for j in range(len(u)): val = str(u[i][j].real) while(len(val)<7): val = " "+val s = s + val print(s)
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
from matplotlib.pyplot import bar labels = [] elements = [] for i in range(8): labels = labels + [i+1] elements = elements + [1] # visualize the values of elements in the list bar(labels,elements) # # 1st step - query # # change the sign of the marked element, i.e., multiply it by -1 # visualize the values of elements in the list bar(labels,elements) # # 1st step - inversion # # calculate the mean of all values # then reflect each element over the mean, e.g.: # if the mean is 0, then the reflection of 3 is -3 # if the mean is 1, then the reflection of 3 is -1 # if the mean is -1, then the reflection of 3 is -5 # visualize the values of elements in the list bar(labels,elements) # # 2nd step - query # # visualize the values of elements in the list bar(labels,elements) # # 2nd step - inversion # # visualize the values of elements in the list bar(labels,elements) # # your code is here # from matplotlib.pyplot import bar labels = [] elements = [] for i in range(8): labels = labels + [i+1] elements = elements + [1] # visualize the values of elements in the list bar(labels,elements) # visualize the values of elements in the list bar(labels,elements) # # 1st step - query # # flip the sign of the marked element elements[3] = -1 * elements[3] # visualize the values of elements in the list bar(labels,elements) # # 1st step - inversion # # summation of all values sum = 0 for i in range(len(elements)): sum += elements[i] # mean of all values mean = sum / len(elements) # reflection over the mean for i in range(len(elements)): value = elements[i] new_value = mean - (elements[i]-mean) elements[i] = new_value # visualize the values of elements in the list bar(labels,elements) # # 2nd step - query # # flip the sign of the marked element elements[3] = -1 * elements[3] # visualize the values of elements in the list bar(labels,elements) # # 2nd step - inversion # # summation of all values sum = 0 for i in range(len(elements)): sum += elements[i] # mean of all values mean = sum / len(elements) # reflection over mean for i in range(len(elements)): value = elements[i] new_value = mean - (elements[i]-mean) elements[i] = new_value # visualize the values of elements in the list bar(labels,elements) for i in range(3): # flip the sign of the marked element elements[3] = -1 * elements[3] # summation of all values sum = 0 for i in range(len(elements)): sum += elements[i] # mean of all values mean = sum / len(elements) # reflection over mean for i in range(len(elements)): value = elements[i] new_value = mean - (elements[i]-mean) elements[i] = new_value # visualize the values of elements in the list bar(labels,elements) def query(elements=[1],marked_elements=[0]): for i in marked_elements: elements[i] = -1 * elements[i] return elements def inversion (elements=[1]): # summation of all values summation = 0 for i in range(len(elements)): summation += elements[i] # mean of all values mean = summation / len(elements) # reflection over mean for i in range(len(elements)): value = elements[i] new_value = mean - (elements[i]-mean) elements[i] = new_value return elements from matplotlib.pyplot import bar # define the list of size 8 on which each element has value of 1 elements = [] for i in range(8): elements = elements + [1] # index of the marked element marked_elements = [3] # define the list of iterations iterations = [] # the list storing the values of the 4th element after each step L = [] # the first values iterations.append(0) L.append(elements[marked_elements[0]]) for step in range(20): # store the iteration iterations.append(step+1) # flip the sign of the marked element elements = query(elements,marked_elements) elements = inversion(elements) # store the new value of the 4th element L.append(elements[marked_elements[0]]) # visualize the values of the 4th elements after each iteration bar(iterations,L) print(iterations) print(L) def query(elements=[1],marked_elements=[0]): for i in marked_elements: elements[i] = -1 * elements[i] return elements def inversion (elements=[1]): # summation of all values summation = 0 for i in range(len(elements)): summation += elements[i] # mean of all values mean = summation / len(elements) # reflection over mean for i in range(len(elements)): value = elements[i] new_value = mean - (elements[i]-mean) elements[i] = new_value return elements from matplotlib.pyplot import bar # define the list of size 8 on which each element has value of 1 elements = [] for i in range(16): elements = elements + [1] # index of the marked element marked_elements = [10] # define the list of iterations iterations = [] # the list storing the values of the marked element after each step L = [] # the first values iterations.append(0) L.append(elements[marked_elements[0]]) for step in range(20): # store the iteration iterations.append(step+1) # flip the sign of the marked element elements = query(elements,marked_elements) elements = inversion(elements) # store the new value of the 4th element L.append(elements[marked_elements[0]]) # visualize the values of the marked elements after each iteration bar(iterations,L) print(iterations) print(L) def query(elements=[1],marked_elements=[0]): for i in marked_elements: elements[i] = -1 * elements[i] return elements def inversion (elements=[1]): # summation of all values summation = 0 for i in range(len(elements)): summation += elements[i] # mean of all values mean = summation / len(elements) # reflection over mean for i in range(len(elements)): value = elements[i] new_value = mean - (elements[i]-mean) elements[i] = new_value return elements from matplotlib.pyplot import bar # define the list of size 8 on which each element has value of 1 elements = [] for i in range(16): elements = elements + [1] # index of the marked element marked_elements = [4,7,9] # define the list of iterations iterations = [] # the list storing the values of the first element after each step L = [] # the first values iterations.append(0) L.append(elements[marked_elements[0]]) for step in range(20): # store the iteration iterations.append(step+1) # flip the sign of the marked element elements = query(elements,marked_elements) elements = inversion(elements) # store the new value of the first marked element L.append(elements[marked_elements[0]]) # visualizing the values of the first marked elements after each iteration bar(iterations,L) print(iterations) print(L) def query(elements=[1],marked_elements=[0]): for i in marked_elements: elements[i] = -1 * elements[i] return elements def inversion (elements=[1]): # summation of all values summation = 0 for i in range(len(elements)): summation += elements[i] # mean of all values mean = summation / len(elements) # reflection over mean for i in range(len(elements)): value = elements[i] new_value = mean - (elements[i]-mean) elements[i] = new_value return elements def length_of_list (elements=[1]): summation = 0 for el in elements: summation = summation + el**2 return round(summation**0.5,3) # define the list of size 8 on which each element has value of 1 elements = [] for i in range(16): elements = elements + [1] # index of the marked element marked_elements = [0,1,2,3] print("the initial length",length_of_list(elements)) for step in range(20): # store the iteration iterations.append(step+1) # flip the sign of the marked element elements = query(elements,marked_elements) print("step",step,"the length after query is ",length_of_list(elements)) elements = inversion(elements) print("step",step,"the length after inversion is ",length_of_list(elements)) def query(elements=[1],marked_elements=[0]): for i in marked_elements: elements[i] = -1 * elements[i] return elements def inversion (elements=[1]): # summation of all values summation = 0 for i in range(len(elements)): summation += elements[i] # mean of all values mean = summation / len(elements) # reflection over mean for i in range(len(elements)): value = elements[i] new_value = mean - (elements[i]-mean) elements[i] = new_value return elements def length_of_list (elements=[1]): summation = 0 for el in elements: summation = summation + el**2 return round(summation**0.5,3) # define the list of size 10 on which each element has value of 1 elements = [] for i in range(10): elements = elements + [1] # index of the marked element marked_elements = [9] print("the initial length",length_of_list(elements)) for step in range(20): # store the iteration iterations.append(step+1) # flip the sign of the marked element elements = query(elements,marked_elements) print("step",step,"the length after query is ",length_of_list(elements)) elements = inversion(elements) print("step",step,"the length after inversion is ",length_of_list(elements)) def query(elements=[1],marked_elements=[0]): for i in marked_elements: elements[i] = -1 * elements[i] return elements def inversion (elements=[1]): # summation of all values summation = 0 for i in range(len(elements)): summation += elements[i] # mean of all values mean = summation / len(elements) # reflection over mean for i in range(len(elements)): value = elements[i] new_value = mean - (elements[i]-mean) elements[i] = new_value return elements def length_of_list (elements=[1]): summation = 0 for el in elements: summation = summation + el**2 return round(summation**0.5,3) # print the elements of a given list with a given precision def print_list(L,precision): output = "" for i in range(len(L)): output = output + str(round(L[i],precision))+" " print(output) # define the list of size 8 on which each element has value of 1 elements = [] for i in range(8): elements = elements + [1/(8**0.5)] # index of the marked element marked_elements = [1] print("step 0") print("the list of elements is") print_list(elements,3) print("the initial length",length_of_list(elements)) for step in range(20): # store the iteration iterations.append(step+1) # flip the sign of the marked element elements = query(elements,marked_elements) elements = inversion(elements) print() print("after step",step+1) print("the list of elements is") print_list(elements,3) print("the length after iteration is ",length_of_list(elements)) def query(elements=[1],marked_elements=[0]): for i in marked_elements: elements[i] = -1 * elements[i] return elements def inversion (elements=[1]): # summation of all values summation = 0 for i in range(len(elements)): summation += elements[i] # mean of all values mean = summation / len(elements) # reflection over mean for i in range(len(elements)): value = elements[i] new_value = mean - (elements[i]-mean) elements[i] = new_value return elements def length_of_list (elements=[1]): summation = 0 for el in elements: summation = summation + el**2 return round(summation**0.5,3) # print the elements of a given list with a given precision def print_list(L,precision): output = "" for i in range(len(L)): output = output + str(round(L[i],precision))+" " print(output) # define the list of size 8 on which each element has value of 1 elements = [] for i in range(16): elements = elements + [1/(16**0.5)] # index of the marked element marked_elements = range(12) print("step 0") print("the list of elements is") print_list(elements,3) print("the initial length",length_of_list(elements)) for step in range(20): # store the iteration iterations.append(step+1) # flip the sign of the marked element elements = query(elements,marked_elements) elements = inversion(elements) print() print("after step",step+1) print("the list of elements is") print_list(elements,3) print("the length after iteration is ",length_of_list(elements))
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
%run qlatvia.py draw_qubit_grover() draw_quantum_state((5/8)**0.5,(3/8)**0.5,"|u>") def query(elements=[1],marked_elements=[0]): for i in marked_elements: elements[i] = -1 * elements[i] return elements def inversion (elements=[1]): # summation of all values summation = 0 for i in range(len(elements)): summation += elements[i] # mean of all values mean = summation / len(elements) # reflection over mean for i in range(len(elements)): value = elements[i] new_value = mean - (elements[i]-mean) elements[i] = new_value return elements from math import asin, pi # initial values iteration = 5 N = 16 marked_elements = [0] k = len(marked_elements) elements = [] states_on_unit_circle= [] # initial quantum state for i in range(N): elements.append(1/N**0.5) x = elements[N-1] * ((N-k)**0.5) y = elements[0] * (k**0.5) states_on_unit_circle.append([x,y,"0"]) # Execute Grover's search algorithm for $iteration steps for step in range(iteration): # query elements = query(elements,marked_elements) x = elements[N-1] * ((N-k)**0.5) y = elements[0] * (k**0.5) states_on_unit_circle.append([x,y,str(step)+"''"]) # inversion elements = inversion(elements) x = elements[N-1] * ((N-k)**0.5) y = elements[0] * (k**0.5) states_on_unit_circle.append([x,y,str(step+1)]) # draw all states %run qlatvia.py draw_qubit_grover() for state in states_on_unit_circle: draw_quantum_state(state[0],state[1],state[2]) # print the angles print("angles in degree") for state in states_on_unit_circle: print(asin(state[1])/pi*180) def query(elements=[1],marked_elements=[0]): for i in marked_elements: elements[i] = -1 * elements[i] return elements def inversion (elements=[1]): # summation of all values summation = 0 for i in range(len(elements)): summation += elements[i] # mean of all values mean = summation / len(elements) # reflection over mean for i in range(len(elements)): value = elements[i] new_value = mean - (elements[i]-mean) elements[i] = new_value return elements from math import asin, pi # initial values iteration = 10 N = 128 # try each case one by one marked_elements = [0] #marked_elements = [0,1] #marked_elements = [0,1,2,3] #marked_elements = [0,1,2,3,4,5,6,7] k = len(marked_elements) elements = [] states_on_unit_circle= [] # initial quantum state for i in range(N): elements.append(1/N**0.5) x = elements[N-1] * ((N-k)**0.5) y = elements[0] * (k**0.5) states_on_unit_circle.append([x,y,"0"]) # Execute Grover's search algorithm for $iteration steps for step in range(iteration): # query elements = query(elements,marked_elements) x = elements[N-1] * ((N-k)**0.5) y = elements[0] * (k**0.5) states_on_unit_circle.append([x,y,str(step)+"''"]) # inversion elements = inversion(elements) x = elements[N-1] * ((N-k)**0.5) y = elements[0] * (k**0.5) states_on_unit_circle.append([x,y,str(step+1)]) # draw all states %run qlatvia.py draw_qubit_grover() for state in states_on_unit_circle: draw_quantum_state(state[0],state[1],state[2]) # print the angles print("angles in degree") for state in states_on_unit_circle: print(asin(state[1])/pi*180) def query(elements=[1],marked_elements=[0]): for i in marked_elements: elements[i] = -1 * elements[i] return elements def inversion (elements=[1]): # summation of all values summation = 0 for i in range(len(elements)): summation += elements[i] # mean of all values mean = summation / len(elements) # reflection over mean for i in range(len(elements)): value = elements[i] new_value = mean - (elements[i]-mean) elements[i] = new_value return elements from math import asin, pi # initial values iteration = 20 #iteration = 10 N = 256 # try each case one by one marked_elements = [0] #marked_elements = [0,1] #marked_elements = [0,1,2,3] #marked_elements = [0,1,2,3,4,5,6,7] k = len(marked_elements) elements = [] states_on_unit_circle= [] # initial quantum state for i in range(N): elements.append(1/N**0.5) x = elements[N-1] * ((N-k)**0.5) y = elements[0] * (k**0.5) states_on_unit_circle.append([x,y,"0"]) # Execute Grover's search algorithm for $iteration steps for step in range(iteration): # query elements = query(elements,marked_elements) x = elements[N-1] * ((N-k)**0.5) y = elements[0] * (k**0.5) states_on_unit_circle.append([x,y,str(step)+"''"]) # inversion elements = inversion(elements) x = elements[N-1] * ((N-k)**0.5) y = elements[0] * (k**0.5) states_on_unit_circle.append([x,y,str(step+1)]) # draw all states %run qlatvia.py draw_qubit_grover() for state in states_on_unit_circle: draw_quantum_state(state[0],state[1],state[2]) # print the angles print("angles in degree") for state in states_on_unit_circle: print(asin(state[1])/pi*180)
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
%run ../include/quantum.py from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer qreg = QuantumRegister(3) #No need to define classical register as we are not measuring mycircuit = QuantumCircuit(qreg) #set ancilla mycircuit.x(qreg[2]) mycircuit.h(qreg[2]) Uf(mycircuit,qreg) #set ancilla back mycircuit.h(qreg[2]) mycircuit.x(qreg[2]) job = execute(mycircuit,Aer.get_backend('unitary_simulator')) u=job.result().get_unitary(mycircuit,decimals=3) #We are interested in the top-left 4x4 part for i in range(4): s="" for j in range(4): val = str(u[i][j].real) while(len(val)<5): val = " "+val s = s + val print(s) mycircuit.draw(output='mpl') def inversion(circuit,quantum_reg): #step 1 circuit.h(quantum_reg[1]) circuit.h(quantum_reg[0]) #step 2 circuit.x(quantum_reg[1]) circuit.x(quantum_reg[0]) #step 3 circuit.ccx(quantum_reg[1],quantum_reg[0],quantum_reg[2]) #step 4 circuit.x(quantum_reg[1]) circuit.x(quantum_reg[0]) #step 5 circuit.x(quantum_reg[2]) #step 6 circuit.h(quantum_reg[1]) circuit.h(quantum_reg[0]) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer qreg1 = QuantumRegister(3) mycircuit1 = QuantumCircuit(qreg1) #set ancilla qubit mycircuit1.x(qreg1[2]) mycircuit1.h(qreg1[2]) inversion(mycircuit1,qreg1) #set ancilla qubit back mycircuit1.h(qreg1[2]) mycircuit1.x(qreg1[2]) job = execute(mycircuit1,Aer.get_backend('unitary_simulator')) u=job.result().get_unitary(mycircuit1,decimals=3) for i in range(4): s="" for j in range(4): val = str(u[i][j].real) while(len(val)<5): val = " "+val s = s + val print(s) mycircuit1.draw(output='mpl') %run ..\include\quantum.py from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer qreg = QuantumRegister(3) creg = ClassicalRegister(2) mycircuit = QuantumCircuit(qreg,creg) #Grover #initial step - equal superposition for i in range(2): mycircuit.h(qreg[i]) #set ancilla mycircuit.x(qreg[2]) mycircuit.h(qreg[2]) mycircuit.barrier() #change the number of iterations iterations=1 #Grover's iterations. for i in range(iterations): #query Uf(mycircuit,qreg) mycircuit.barrier() #inversion inversion(mycircuit,qreg) mycircuit.barrier() #set ancilla back mycircuit.h(qreg[2]) mycircuit.x(qreg[2]) mycircuit.measure(qreg[0],creg[0]) mycircuit.measure(qreg[1],creg[1]) job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=10000) counts = job.result().get_counts(mycircuit) # print the outcome for outcome in counts: print(outcome,"is observed",counts[outcome],"times") mycircuit.draw(output='mpl') def big_inversion(circuit,quantum_reg): for i in range(3): circuit.h(quantum_reg[i]) circuit.x(quantum_reg[i]) circuit.ccx(quantum_reg[1],quantum_reg[0],quantum_reg[4]) circuit.ccx(quantum_reg[2],quantum_reg[4],quantum_reg[3]) circuit.ccx(quantum_reg[1],quantum_reg[0],quantum_reg[4]) for i in range(3): circuit.x(quantum_reg[i]) circuit.h(quantum_reg[i]) circuit.x(quantum_reg[3]) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer big_qreg2 = QuantumRegister(5) big_mycircuit2 = QuantumCircuit(big_qreg2) #set ancilla big_mycircuit2.x(big_qreg2[3]) big_mycircuit2.h(big_qreg2[3]) big_inversion(big_mycircuit2,big_qreg2) #set ancilla back big_mycircuit2.h(big_qreg2[3]) big_mycircuit2.x(big_qreg2[3]) job = execute(big_mycircuit2,Aer.get_backend('unitary_simulator')) u=job.result().get_unitary(big_mycircuit2,decimals=3) for i in range(8): s="" for j in range(8): val = str(u[i][j].real) while(len(val)<6): val = " "+val s = s + val print(s) %run ..\include\quantum.py def big_inversion(circuit,quantum_reg): for i in range(3): circuit.h(quantum_reg[i]) circuit.x(quantum_reg[i]) circuit.ccx(quantum_reg[1],quantum_reg[0],quantum_reg[4]) circuit.ccx(quantum_reg[2],quantum_reg[4],quantum_reg[3]) circuit.ccx(quantum_reg[1],quantum_reg[0],quantum_reg[4]) for i in range(3): circuit.x(quantum_reg[i]) circuit.h(quantum_reg[i]) circuit.x(quantum_reg[3]) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer qreg8 = QuantumRegister(5) creg8 = ClassicalRegister(3) mycircuit8 = QuantumCircuit(qreg8,creg8) #set ancilla mycircuit8.x(qreg8[3]) mycircuit8.h(qreg8[3]) #Grover for i in range(3): mycircuit8.h(qreg8[i]) mycircuit8.barrier() #Try 1,2,6,12 8iterations of Grover for i in range(2): Uf_8(mycircuit8,qreg8) mycircuit8.barrier() big_inversion(mycircuit8,qreg8) mycircuit8.barrier() #set ancilla back mycircuit8.h(qreg8[3]) mycircuit8.x(qreg8[3]) for i in range(3): mycircuit8.measure(qreg8[i],creg8[i]) job = execute(mycircuit8,Aer.get_backend('qasm_simulator'),shots=10000) counts8 = job.result().get_counts(mycircuit8) # print the reverse of the outcome for outcome in counts8: print(outcome,"is observed",counts8[outcome],"times") mycircuit8.draw(output='mpl') %run ../include/quantum.py from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer qreg12 = QuantumRegister(19) creg12 = ClassicalRegister(10) mycircuit12 = QuantumCircuit(qreg12,creg12) for i in range(10): mycircuit12.h(qreg12[i]) mycircuit12.x(qreg12[10]) mycircuit12.h(qreg12[10]) #number of iterations - change this value iteration_count = 1 for i in range(iteration_count): giant_oracle2(mycircuit12,qreg12) giant_diffusion(mycircuit12,qreg12) mycircuit12.h(qreg12[10]) mycircuit12.x(qreg12[10]) for i in range(10): mycircuit12.measure(qreg12[i],creg12[i]) job = execute(mycircuit12,Aer.get_backend('qasm_simulator'),shots=100000) counts12 = job.result().get_counts(mycircuit12) # print the reverse of the outcome for outcome in counts12: print(outcome,"is observed",counts12[outcome],"times") def oracle_11(circuit,qreg): circuit1.ccx(qreg[0],qreg[1],qreg[2]) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer qreg1 = QuantumRegister(3) circuit1 = QuantumCircuit(qreg1) # prepare ancilla qubit circuit1.x(qreg1[2]) circuit1.h(qreg1[2]) #call the oracle oracle_11(circuit1,qreg1) # put ancilla qubit back into state |0> circuit1.h(qreg1[2]) circuit1.x(qreg1[2]) job = execute(circuit1,Aer.get_backend('unitary_simulator')) u=job.result().get_unitary(circuit1,decimals=3) for i in range(4): s="" for j in range(4): val = str(u[i][j].real) while(len(val)<5): val = " "+val s = s + val print(s) circuit1.draw(output='mpl') def oracle_01(circuit,qreg): circuit.x(qreg[1]) circuit.ccx(qreg[0],qreg[1],qreg[2]) circuit.x(qreg[1]) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer qreg1 = QuantumRegister(3) circuit1 = QuantumCircuit(qreg1) # prepare ancilla qubit circuit1.x(qreg1[2]) circuit1.h(qreg1[2]) #call the oracle oracle_01(circuit1,qreg1) # put ancilla qubit back into state |0> circuit1.h(qreg1[2]) circuit1.x(qreg1[2]) job = execute(circuit1,Aer.get_backend('unitary_simulator')) u=job.result().get_unitary(circuit1,decimals=3) for i in range(4): s="" for j in range(4): val = str(u[i][j].real) while(len(val)<5): val = " "+val s = s + val print(s) circuit1.draw(output='mpl') def oracle_00(circuit,qreg): circuit.x(qreg[0]) circuit.x(qreg[1]) circuit.ccx(qreg[0],qreg[1],qreg[2]) circuit.x(qreg[0]) circuit.x(qreg[1]) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer qreg = QuantumRegister(3) creg = ClassicalRegister(2) mycircuit = QuantumCircuit(qreg,creg) #Grover #initial step - equal superposition for i in range(2): mycircuit.h(qreg[i]) #set ancilla mycircuit.x(qreg[2]) mycircuit.h(qreg[2]) mycircuit.barrier() #change the number of iterations iterations=1 #Grover's iterations. for i in range(iterations): #query oracle_00(mycircuit,qreg) mycircuit.barrier() #inversion inversion(mycircuit,qreg) mycircuit.barrier() #set ancilla back mycircuit.h(qreg[2]) mycircuit.x(qreg[2]) mycircuit.measure(qreg[0],creg[0]) mycircuit.measure(qreg[1],creg[1]) job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=10000) counts = job.result().get_counts(mycircuit) # print the reverse of the outcome for outcome in counts: reverse_outcome = '' for i in outcome: reverse_outcome = i + reverse_outcome print(reverse_outcome,"is observed",counts[outcome],"times") mycircuit.draw(output='mpl') def oracle_001_111(circuit,qreg): #Your code here # #
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
# consider the following list with 4 elements L = [1,-2,0,5] print(L) # 3 * v v = [1,-2,0,5] print("v is",v) # we use the same list for the result for i in range(len(v)): v[i] = 3 * v[i] print("3v is",v) # -0.6 * u # reinitialize the list v v = [1,-2,0,5] for i in range(len(v)): v[i] = -0.6 * v[i] print("0.6v is",v) u = [-3,-2,0,-1,4] v = [-1,-1,2,-3,5] result=[] for i in range(len(u)): result.append(u[i]+v[i]) print("u+v is",result) # print the result vector similarly to a column vector print() # print an empty line print("the elements of u+v are") for j in range(len(result)): print(result[j]) from random import randrange # # your solution is here # from random import randrange dimension = 7 # create u and v as empty lists u = [] v = [] for i in range(dimension): u.append(randrange(-10,11)) # add a randomly picked number to the list u v.append(randrange(-10,11)) # add a randomly picked number to the list v # print both lists print("u is",u) print("v is",v) #r=randrange(-10,11) # randomly pick a number from the list {-10,-9,...,-1,0,1,...,9,10} # # your solution is here # # please execute the cell for Task 1 to define u and v # create a result list # the first method result=[] # fill it with zeros for i in range(dimension): result.append(0) print("by using the first method, the result vector is initialized to",result) # the second method # alternative and shorter solution for creating a list with zeros result = [0] * 7 print("by using the second method, the result vector is initialized to",result) # calculate 3u-2v for i in range(dimension): result[i] = 3 * u[i] - 2 * v[i] # print all lists print("u is",u) print("v is",v) print("3u-2v is",result) v = [-1,-3,5,3,1,2] length_square=0 for i in range(len(v)): print(v[i],":square ->",v[i]**2) # print each entry and its square value length_square = length_square + v[i]**2 # sum up the square of each entry length = length_square ** 0.5 # take the square root of the summation of the squares of all entries print("the summation is",length_square) print("then the length is",length) # for square root, we can also use built-in function math.sqrt print() # print an empty line from math import sqrt print("the square root of",length_square,"is",sqrt(length_square)) # # your solution is here # u = [1,-2,-4,2] fouru=[4,-8,-16,8] len_u = 0 len_fouru = 0 for i in range(len(u)): len_u = len_u + u[i]**2 # adding square of each value len_fouru = len_fouru + fouru[i]**2 # adding square of each value len_u = len_u ** 0.5 # taking square root of the summation len_fouru = len_fouru ** 0.5 # taking square root of the summation # print the lengths print("length of u is",len_u) print("4 * length of u is",4 * len_u) print("length of 4u is",len_fouru) # # your solution is here # from random import randrange u = [1,-2,-4,2] print("u is",u) r = randrange(9) # r is a number in {0,...,8} r = r + 1 # r is a number in {1,...,9} r = r/10 # r is a number in {1/10,...,9/10} print() print("r is",r) newu=[] for i in range(len(u)): newu.append(-1*r*u[i]) print() print("-ru is",newu) print() length = 0 for i in range(len(newu)): length = length + newu[i]**2 # adding square of each number print(newu[i],"->[square]->",newu[i]**2) print() print("the summation of squares is",length) length = length**0.5 # taking square root print("the length of",newu,"is",length)
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
# let's define both vectors u = [-3,-2,0,-1,4] v = [-1,-1,2,-3,5] uv = 0; # summation is initially zero for i in range(len(u)): # iteratively access every pair with the same indices print("pairwise multiplication of the entries with index",i,"is",u[i]*v[i]) uv = uv + u[i]*v[i] # i-th entries are multiplied and then added to summation print() # print an empty line print("The dot product of",u,'and',v,'is',uv) # # your solution is here # # let's define the vectors v=[-3,4,-5,6] u=[4,3,6,5] vu = 0 for i in range(len(v)): vu = vu + v[i]*u[i] print(v,u,vu) # # your solution is here # u = [-3,-4] uu = u[0]*u[0] + u[1]*u[1] print(u,u,uu) # let's find the dot product of v and u v = [-4,0] u = [0,-5] result = 0; for i in range(2): result = result + v[i]*u[i] print("the dot product of u and v is",result) # we can use the same code v = [-4,3] u = [-3,-4] result = 0; for i in range(2): result = result + v[i]*u[i] print("the dot product of u and v is",result) # you may consider to write a function in Python for dot product # # your solution is here # u = [-3,-4] neg_u=[3,4] v=[-4,3] neg_v=[4,-3] # let's define a function for inner product def dot(v_one,v_two): summation = 0 for i in range(len(v_one)): summation = summation + v_one[i]*v_two[i] # adding up pairwise multiplications return summation # return the inner product print("the dot product of u and -v (",u," and ",neg_v,") is",dot(u,neg_v)) print("the dot product of -u and v (",neg_u," and ",v,") is",dot(neg_u,v)) print("the dot product of -u and -v (",neg_u," and ",neg_v,") is",dot(neg_u,neg_v)) # # your solution is here # # let's define a function for inner product def dot(v_one,v_two): summation = 0 for i in range(len(v_one)): summation = summation + v_one[i]*v_two[i] # adding up pairwise multiplications return summation # return the inner product v = [-1,2,-3,4] v_neg_two=[2,-4,6,-8] u=[-2,-1,5,2] u_three=[-6,-3,15,6] print("the dot product of v and u is",dot(v,u)) print("the dot product of -2v and 3u is",dot(v_neg_two,u_three))
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
# we may break lines when defining our list M = [ [8 , 0 , -1 , 0 , 2], [-2 , -3 , 1 , 1 , 4], [0 , 0 , 1 , -7 , 1], [1 , 4 , -2 , 5 , 9] ] # let's print matrix M print(M) # let's print M in matrix form, row by row for i in range(4): # there are 4 rows print(M[i]) M = [ [8 , 0 , -1 , 0 , 2], [-2 , -3 , 1 , 1 , 4], [0 , 0 , 1 , -7 , 1], [1 , 4 , -2 , 5 , 9] ] # print the element of M in the 1st row and the 1st column. print(M[0][0]) # print the element of M in the 3rd row and the 4th column. print(M[2][3]) # print the element of M in the 4th row and the 5th column. print(M[3][4]) # we use double nested for-loops N =[] # the result matrix for i in range(4): # for each row N.append([]) # create an empty sub-list for each row in the result matrix for j in range(5): # in row (i+1), we do the following for each column N[i].append(M[i][j]*-2) # we add new elements into the i-th sub-list # print M and N, and see the results print("I am M:") for i in range(4): print(M[i]) print() print("I am N:") for i in range(4): print(N[i]) # create an empty list for the result matrix K=[] for i in range(len(M)): # len(M) return the number of rows in M K.append([]) # we create a new row for K for j in range(len(M[0])): # len(M[0]) returns the number of columns in M K[i].append(M[i][j]+N[i][j]) # we add new elements into the i-th sublist/rows # print each matrix in a single line print("M=",M) print("N=",N) print("K=",K) from random import randrange # # your solution is here # from random import randrange A = [] B = [] for i in range(3): A.append([]) B.append([]) for j in range(4): A[i].append(randrange(-5,6)) B[i].append(randrange(-5,6)) print("A is",A) print("B is",B) C = [] for i in range(3): C.append([]) for j in range(4): C[i].append( 3*A[i][j]-2*B[i][j]) print("C is 3A - 2B") print("C is",C) M = [ [-2,3,0,4], [-1,1,5,9] ] N =[ [1,2,3], [4,5,6], [7,8,9] ] # # your solution is here # M = [ [-2,3,0,4], [-1,1,5,9] ] N =[ [1,2,3], [4,5,6], [7,8,9] ] # create the transpose of M as a zero matrix # its dimension is (4x2) MT = [] for i in range(4): MT.append([]) for j in range(2): MT[i].append(0) # create the transpose of N as a zero matrix # its dimension is (3x3) NT = [] for i in range(3): NT.append([]) for j in range(3): NT[i].append(0) # calculate the MT for i in range(2): for j in range(4): MT[j][i]=M[i][j] # check the indices print("M is") for i in range(len(M)): print(M[i]) print() print("Transpose of M is") for i in range(len(MT)): print(MT[i]) print() # calculate the NT for i in range(3): for j in range(3): NT[j][i]=N[i][j] # check the indices print("N is") for i in range(len(N)): print(N[i]) print() print("Transpose of N is") for i in range(len(NT)): print(NT[i]) # matrix M M = [ [-1,0,1], [-2,-3,4], [1,5,6] ] # vector v v = [1,-3,2] # the result vector u u = [] # for each row, we do an inner product for i in range(3): # inner product for one row is initiated inner_result = 0 # this variable keeps the summation of the pairwise multiplications for j in range(3): # the elements in the i-th row inner_result = inner_result + M[i][j] * v[j] # inner product for one row is completed u.append(inner_result) print("M is") for i in range(len(M)): print(M[i]) print() print("v=",v) print() print("u=",u) # # your solution is here # N = [ [-1,1,2], [0,-2,-3], [3,2,5], [0,2,-2] ] u = [2,-1,3] uprime =[] print("N is") for i in range(len(N)): print(N[i]) print() print("u is",u) for i in range(len(N)): # the number of rows of N S = 0 # summation of pairwise multiplications for j in range(len(u)): # the dimension of u S = S + N[i][j] * u[j] uprime.append(S) print() print("u' is",uprime) # matrix M M = [ [-1,0,1], [-2,-1,2], [1,2,-2] ] # matrix N N = [ [0,2,1], [3,-1,-2], [-1,1,0] ] # matrix K K = [] # # your solution is here # # matrix M M = [ [-1,0,1], [-2,-1,2], [1,2,-2] ] # matrix N N = [ [0,2,1], [3,-1,-2], [-1,1,0] ] # matrix K K = [] for i in range(3): K.append([]) for j in range(3): # here we calculate K[i][j] # inner product of i-th row of M with j-th row of N S = 0 for k in range(3): S = S + M[i][k] * N[k][j] K[i].append(S) print("M is") for i in range(len(M)): print(M[i]) print() print("N is") for i in range(len(N)): print(N[i]) print() print("K is") for i in range(len(K)): print(K[i]) # # your solution is here # from random import randrange A = [] B = [] AB = [] BA = [] DIFF = [] # create A, B, AB, BA, DIFF together for i in range(2): A.append([]) B.append([]) AB.append([]) BA.append([]) DIFF.append([]) for j in range(2): A[i].append(randrange(-10,10)) # the elements of A are random B[i].append(randrange(-10,10)) # the elements of B are random AB[i].append(0) # the elements of AB are initially set to zeros BA[i].append(0) # the elements of BA are initially set to zeros DIFF[i].append(0) # the elements of DIFF are initially set to zeros print("A =",A) print("B =",B) print() # print a line print("AB, BA, and DIFF are initially zero matrices") print("AB =",AB) print("BA =",BA) print("DIFF =",BA) # let's find AB for i in range(2): for j in range(2): # remark that AB[i][j] is already 0, and so we can directly add all pairwise multiplications for k in range(2): AB[i][j] = AB[i][j] + A[i][k] * B[k][j] # each multiplication is added print() # print a line print("AB =",AB) # let's find BA for i in range(2): for j in range(2): # remark that BA[i][j] is already 0, and so we can directly add all pairwise multiplications for k in range(2): BA[i][j] = BA[i][j] + B[i][k] * A[k][j] # each multiplication is added print("BA =",BA) # let's calculate DIFF = AB- BA for i in range(2): for j in range(2): DIFF[i][j] = AB[i][j] - BA[i][j] print() # print a line print("DIFF = AB - BA =",DIFF)
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
# vector v v = [1,2,-3] # vector u u=[-2,3] vu = [] for i in range(len(v)): # each element of v will be replaced for j in range(len(u)): # the vector u will come here after multiplying with the entry there vu.append( v[i] * u[j] ) print("v=",v) print("u=",u) print("vu=",vu) # # your solution is here # u = [-2,-1,0,1] v = [1,2,3] uv = [] vu = [] for i in range(len(u)): # one element of u is picked for j in range(len(v)): # now we iteratively select every element of v uv.append(u[i]*v[j]) # this one element of u is iteratively multiplied with every element of v print("u-tensor-v is",uv) for i in range(len(v)): # one element of v is picked for j in range(len(u)): # now we iteratively select every element of u vu.append(v[i]*u[j]) # this one element of v is iteratively multiplied with every element of u print("v-tensor-u is",vu) # matrix M M = [ [-1,0,1], [-2,-1,2], [1,2,-2] ] # matrix N N = [ [0,2,1], [3,-1,-2], [-1,1,0] ] # MN will be a (9x9)-dimensional matrix # prepare it as a zero matrix # this helps us to easily fill it MN=[] for i in range(9): MN.append([]) for j in range(9): MN[i].append(0) for i in range(3): # row of M for j in range(3): # column of M for k in range(3): # row of N for l in range(3): # column of N MN[i*3+k][3*j+l] = M[i][j] * N[k][l] print("M-tensor-N is") for i in range(9): print(MN[i]) # matrices M and N were defined above # matrix NM will be prepared as a (9x9)-dimensional zero matrix NM=[] for i in range(9): NM.append([]) for j in range(9): NM[i].append(0) for i in range(3): # row of N for j in range(3): # column of N for k in range(3): # row of M for l in range(3): # column of M NM[i*3+k][3*j+l] = N[i][j] * M[k][l] print("N-tensor-M is") for i in range(9): print(NM[i]) # # your solution is here # A = [ [-1,0,1], [-2,-1,2] ] B = [ [0,2], [3,-1], [-1,1] ] print("A =") for i in range(len(A)): print(A[i]) print() # print a line print("B =") for i in range(len(B)): print(B[i]) # let's define A-tensor-B as a (6x6)-dimensional zero matrix AB = [] for i in range(6): AB.append([]) for j in range(6): AB[i].append(0) # let's find A-tensor-B for i in range(2): for j in range(3): # for each A(i,j) we execute the following codes a = A[i][j] # we access each element of B for m in range(3): for n in range(2): b = B[m][n] # now we put (a*b) in the appropriate index of AB AB[3*i+m][2*j+n] = a * b print() # print a line print("A-tensor-B =") print() # print a line for i in range(6): print(AB[i]) # # your solution is here # A = [ [-1,0,1], [-2,-1,2] ] B = [ [0,2], [3,-1], [-1,1] ] print() # print a line print("B =") for i in range(len(B)): print(B[i]) print("A =") for i in range(len(A)): print(A[i]) # let's define B-tensor-A as a (6x6)-dimensional zero matrix BA = [] for i in range(6): BA.append([]) for j in range(6): BA[i].append(0) # let's find B-tensor-A for i in range(3): for j in range(2): # for each B(i,j) we execute the following codes b = B[i][j] # we access each element of A for m in range(2): for n in range(3): a = A[m][n] # now we put (a*b) in the appropriate index of AB BA[2*i+m][3*j+n] = b * a print() # print a line print("B-tensor-A =") print() # print a line for i in range(6): print(BA[i])
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
import qiskit versions = qiskit.__qiskit_version__ print("The version of Qiskit is",versions['qiskit']) print() print("The version of each component:") for key in versions: print(key,"->",versions[key]) !pip install qiskit[visualization] --user #!pip install -U qiskit --user #!pip uninstall qiskit # import the objects from qiskit from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from random import randrange # create a quantum circuit and its register objects qreg = QuantumRegister(2) # quantum register with two quantum bits creg = ClassicalRegister(2) # classical register with two classical bit circuit = QuantumCircuit(qreg,creg) # quantum circuit composed by a quantum register and a classical register # apply a Hadamard gate to the first qubit circuit.h(qreg[0]) # set the second qubit to state |1> circuit.x(qreg[1]) # apply CNOT(first_qubit,second_qubit) circuit.cx(qreg[0],qreg[1]) # measure the both qubits circuit.measure(qreg,creg) print("The execution of the cell was completed, and the circuit was created :)") # draw circuit circuit.draw(output='mpl') # the output will be a "matplotlib.Figure" object ## execute the circuit 1024 times job = execute(circuit,Aer.get_backend('qasm_simulator'),shots=1024) # get the result counts = job.result().get_counts(circuit) print(counts)
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
# I am a comment in python print("Hello From Quantum World :-)") # please run this cell # import the objects from qiskit from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from random import randrange # create a quantum circuit and its register objects qreg = QuantumRegister(2) # my quantum register creg = ClassicalRegister(2) # my classical register circuit = QuantumCircuit(qreg,creg) # my quantum circuit # apply a Hadamard gate to the first qubit circuit.h(qreg[0]) # set the second qubit to |1> circuit.x(qreg[1]) # apply CNOT(first_qubit,second_qubit) circuit.cx(qreg[0],qreg[1]) # measure the both qubits circuit.measure(qreg,creg) print("The execution of the cell was completed, and the circuit was created :)") ## execute the circuit 100 times job = execute(circuit,Aer.get_backend('qasm_simulator'),shots=1024) # get the result counts = job.result().get_counts(circuit) print(counts) # draw circuit circuit.draw(output='mpl') # the output will be a "matplotlib.Figure" object
https://github.com/NTU-ALComLab/SliQSim-Qiskit-Interface
NTU-ALComLab
# -*- coding: utf-8 -*- # Copyright 2018, IBM. # # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. """ Exception for errors raised by SliQSim simulator. """ from qiskit import QiskitError class SliQSimError(QiskitError): """Class for errors raised by the SliQSim simulator.""" def __init__(self, *message): """Set the error message.""" super().__init__(*message) self.message = ' '.join(message) def __str__(self): """Return the message.""" return repr(self.message)
https://github.com/NTU-ALComLab/SliQSim-Qiskit-Interface
NTU-ALComLab
# Import tools from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute from qiskit_sliqsim_provider import SliQSimProvider # Initiate SliQSim Provider provider = SliQSimProvider() # Construct a quantum circuit: 2-qubit bell-state qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) qc.h(qr[0]) qc.cx(qr[0], qr[1]) qc.measure(qr, cr) # Read a circuit from a .qasm file # qc = QuantumCircuit.from_qasm_file("../SliQSim/examples/bell_state.qasm") # Get the backend of sampling simulation backend = provider.get_backend('sampling') # Get the backend of statevector simulation # backend = provider.get_backend('all_amplitude') # Execute simulation job = execute(qc, backend=backend, shots=1024, optimization_level=0) # Obtain and print the results result = job.result() print(result.get_counts(qc)) # print(result.get_statevector(qc))
https://github.com/Naphann/Solving-TSP-Grover
Naphann
import qiskit from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import Aer import numpy as np from math import floor, ceil %matplotlib inline def max_number(arr_size): return (2 ** arr_size)-1 def check_min_circuit(a, threshold): max = max_number(a) foo = max - threshold binary = format(foo, 'b')[::-1] print(binary) extra = a - len(binary) for i in range(extra): binary = "0" + binary print(binary) for i in range(a): if int(binary[i])==1: qc1.x(_q[i]) _q = QuantumRegister(5) qc1 = QuantumCircuit(_q) check_min_circuit(5, 20) qc1.draw()
https://github.com/Naphann/Solving-TSP-Grover
Naphann
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import IBMQ, Aer, execute from qiskit.tools.visualization import plot_histogram ## distance_black_box distances = { "32": 3, "31": 2, "30": 4, "21": 7, "20": 6, "10": 5, } def dist_single(): qr = QuantumRegister(2) qr_target = QuantumRegister(5) qc = QuantumCircuit(qr, qr_target, name='dist_single') for edge in distances: if edge[0] == '3': node = format(int(edge[1]), '02b')[::-1] d_bin = format(distances[edge], '02b')[::-1] for idx in range(len(node)): if node[idx] == '0': qc.x(qr[idx]) for idx in range(len(d_bin)): if d_bin[idx] == '1': qc.ccx(qr[0], qr[1], qr_target[idx]) for idx in range(len(node)): if node[idx] == '0': qc.x(qr[idx]) return qc def dist(): qr1 = QuantumRegister(2) qr2 = QuantumRegister(2) qr_target = QuantumRegister(5) qr_anc = QuantumRegister(2) qc = QuantumCircuit(qr1, qr2, qr_target, qr_anc, name='dist') for edge in distances: if edge[0] != '3': # convert to binaries node1 = format(int(edge[0]), '02b')[::-1] node2 = format(int(edge[1]), '02b')[::-1] d_bin = format(distances[edge], '02b')[::-1] for idx in range(len(node1)): # assume node1 and node2 have the same length if node1[idx] == '0': qc.x(qr1[idx]) for idx in range(len(node2)): if node2[idx] == '0': qc.x(qr2[idx]) for idx in range(len(d_bin)): if d_bin[idx] == '1': qc.mct(qr1[:]+qr2[:], qr_target[idx], qr_anc) for idx in range(len(node2)): # invert back if node2[idx] == '0': qc.x(qr2[idx]) for idx in range(len(node1)): if node1[idx] == '0': qc.x(qr1[idx]) return qc qr1 = QuantumRegister(2) # node reg. qr2 = QuantumRegister(2) # node reg. qr_target = QuantumRegister(5) # distance reg. qr_anc = QuantumRegister(2) c = ClassicalRegister(5) qc = QuantumCircuit(qr1, qr2, qr_target, qr_anc, c) qc.x(qr1[0]) # qc.x(qr2[0]) qc.append(dist(), qr1[:] + qr2[:] + qr_target[:] + qr_anc[:]) qc.measure(qr_target, c) # qc.draw(output='mpl') backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend, shots=1024) counts = job.result().get_counts() plot_histogram(counts) format(1, '02b')
https://github.com/Naphann/Solving-TSP-Grover
Naphann
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import IBMQ, Aer, execute from qiskit.tools.visualization import plot_histogram ## oracle_initialize_part def OR(qubit_1, qubit_2, k): # enter qubit numbers here """ function does the equivalent of a classical OR between qubit numbers a and b and stores the result in qubit number k """ # qc.barrier(q) qc.x(q[qubit_1]) qc.x(q[qubit_2]) # qc.barrier(q) qc.ccx(q[qubit_1], q[qubit_2], q[k]) qc.x(q[k]) # qc.barrier(q) qc.x(q[qubit_1]) qc.x(q[qubit_2]) # qc.barrier(q) def are_not_equal(a_0, b_0, k): # enter node numbers here. For example, a is node 0, b is node 1 and c is node 2 """ function outputs 1 if nodes a and b are not the same. Node numbering starts from 0 as in the problem statement. k is the qubit number where the output is XOR-ed. qubit numbering also starts from 0 """ # qc.barrier(q) qc.cx(q[2*a_0], q[2*b_0]) qc.cx(q[(2*a_0) + 1], q[(2*b_0) + 1]) OR(2*b_0, (2*b_0)+1, k) qc.cx(q[2*a_0], q[2*b_0]) qc.cx(q[(2*a_0) + 1], q[(2*b_0) + 1]) # qc.barrier(q) def is_not_3(a, k): qc.ccx(q[2*a], q[(2*a)+1], q[k]) qc.x(q[k]) def initialize_oracle_part(n): t = 4 # qc.barrier(q) are_not_equal(0, 1, 6) # node a and b are not equal are_not_equal(0, 2, 7) are_not_equal(1, 2, 8) is_not_3(0, 11) is_not_3(1, 12) is_not_3(2, 13) # qc.barrier(q) qc.mct([q[6], q[7], q[8], q[11], q[12], q[13]], q[10],[q[9], q[14], q[15], q[16]]) # answer is stored in 10. please keep 9 a clean qubit, it's used as ancilla here # qc.barrier(q) is_not_3(0, 11) is_not_3(1, 12) is_not_3(2, 13) are_not_equal(0, 1, 6) # node a and b are not equal are_not_equal(0, 2, 7) are_not_equal(1, 2, 8) ## distance_black_box distances = { "32": 3, "31": 2, "30": 4, "21": 7, "20": 6, "10": 5, } def dist_single(): qr = QuantumRegister(2) qr_target = QuantumRegister(5) qc = QuantumCircuit(qr, qr_target, name='dist_single') for edge in distances: if edge[0] == '3': node = format(int(edge[1]), '02b') d_bin = format(distances[edge], '02b') for idx in range(len(node)): if node[idx] == '0': qc.x(qr[idx]) for idx in range(len(d_bin)): if d_bin[idx] == '1': qc.ccx(qr[0], qr[1], qr_target[idx]) for idx in range(len(node)): if node[idx] == '0': qc.x(qr[idx]) return qc def dist(): qr1 = QuantumRegister(2) qr2 = QuantumRegister(2) qr_target = QuantumRegister(5) qr_anc = QuantumRegister(2) qc = QuantumCircuit(qr1, qr2, qr_target, qr_anc, name='dist') for edge in distances: if edge[0] != '3': # convert to binaries node1 = format(int(edge[0]), '02b') node2 = format(int(edge[1]), '02b') d_bin = format(distances[edge], '02b') for idx in range(len(node1)): # assume node1 and node2 have the same length if node1[idx] == '0': qc.x(qr1[idx]) for idx in range(len(node2)): if node2[idx] == '0': qc.x(qr2[idx]) for idx in range(len(d_bin)): if d_bin[idx] == '1': qc.mct(qr1[:]+qr2[:], qr_target[idx], qr_anc) for idx in range(len(node2)): # invert back if node2[idx] == '0': qc.x(qr2[idx]) for idx in range(len(node1)): if node1[idx] == '0': qc.x(qr1[idx]) return qc ## multi_adder_1 def maj(a, b, k): qc.cx(q[k], q[b]) qc.cx(q[k], q[a]) qc.ccx(q[a], q[b], q[k]) def unmaj(a, b, k): qc.ccx(q[a], q[b], q[k]) qc.cx(q[k], q[a]) qc.cx(q[a], q[b]) def multiple_adder(a, b, c_0, z): arr_size = len(a) maj(c_0, b[0], a[0]) for i in range(arr_size-1): maj(a[i], b[i+1], a[i+1]) qc.cx(q[a[arr_size-1]], q[z]) for i in reversed(range(arr_size-1)): unmaj(a[i], b[i+1], a[i+1]) unmaj(c_0, b[0], a[0]) ## diffusion def diffusion(): qc.h(q[0:6]) qc.x(q[0:6]) qc.h(q[5]) qc.barrier() qc.mct(q[0:5], q[5], q[7:10]) qc.barrier() qc.h(q[5]) qc.x(q[0:6]) qc.h(q[0:6]) qubit_num = 25 # max is 32 if you're using the simulator # Ancilla indices inputs = [0, 1, 2, 3, 4, 5] init_ancillae = [6, 7, 8, 9] valid = [10] temp_dist = [11, 12, 13, 14, 15] total_dist = [16, 17, 18, 19, 20] gate_ancillae = [21, 22, 23] check_dist = [11, 12, 13, 14, 15] # initialize 13 here carry_check = [24] inputs = inputs[0] init_ancillae = init_ancillae[0] valid = valid[0] temp_dist = temp_dist[0] total_dist = total_dist[0] gate_ancillae = gate_ancillae[0] check_dist = check_dist[0] carry_check = carry_check[0] q = QuantumRegister(qubit_num) c = ClassicalRegister(6) qc = QuantumCircuit(q, c) qc.h(q[0:6]) qc.x(q[carry_check]) for i in range(loop): # forward oracle initialize_oracle_part(4) qc.append(dist_single(), q[inputs:inputs+2] + q[temp_dist:temp_dist+5]) multiple_adder([11, 12, 13, 14], [16, 17, 18, 19], init_ancillae, 20) qc.append(dist_single().inverse(), q[inputs:inputs+2] + q[temp_dist:temp_dist+5]) qc.append(dist(), q[inputs:inputs+4] + q[temp_dist:temp_dist+5] + q[gate_ancillae:gate_ancillae+2]) multiple_adder([11, 12, 13, 14], [16, 17, 18, 19], init_ancillae, 20) qc.append(dist().inverse(), q[inputs:inputs+4] + q[temp_dist:temp_dist+5] + q[gate_ancillae:gate_ancillae+2]) qc.append(dist(), q[inputs+2:inputs+6] + q[temp_dist:temp_dist+5] + q[gate_ancillae:gate_ancillae+2]) multiple_adder([11, 12, 13, 14], [16, 17, 18, 19], init_ancillae, 20) qc.append(dist().inverse(), q[inputs+2:inputs+6] + q[temp_dist:temp_dist+5] + q[gate_ancillae:gate_ancillae+2]) qc.x(q[check_dist:check_dist+3]) # init 15 multiple_adder([11, 12, 13, 14, 15], [16, 17, 18, 19, 20], init_ancillae, carry_check) # carry_check # qc.barrier() qc.cz(q[valid], q[carry_check]) # qc.barrier() # inverse oracle multiple_adder([11, 12, 13, 14, 15], [16, 17, 18, 19, 20], init_ancillae, carry_check) qc.x(q[check_dist:check_dist+3]) # init 15 qc.append(dist().inverse(), q[inputs+2:inputs+6] + q[temp_dist:temp_dist+5] + q[gate_ancillae:gate_ancillae+2]) multiple_adder([11, 12, 13, 14], [16, 17, 18, 19], init_ancillae, 20) qc.append(dist(), q[inputs+2:inputs+6] + q[temp_dist:temp_dist+5] + q[gate_ancillae:gate_ancillae+2]) qc.append(dist().inverse(), q[inputs:inputs+4] + q[temp_dist:temp_dist+5] + q[gate_ancillae:gate_ancillae+2]) multiple_adder([11, 12, 13, 14], [16, 17, 18, 19], init_ancillae, 20) qc.append(dist(), q[inputs:inputs+4] + q[temp_dist:temp_dist+5] + q[gate_ancillae:gate_ancillae+2]) qc.append(dist_single().inverse(), q[inputs:inputs+2] + q[temp_dist:temp_dist+5]) multiple_adder([11, 12, 13, 14], [16, 17, 18, 19], init_ancillae, 20) qc.append(dist_single(), q[inputs:inputs+2] + q[temp_dist:temp_dist+5]) initialize_oracle_part(4) diffusion() qc.measure(q[:6], c) # qc.draw() from qiskit.transpiler import PassManager from qiskit.transpiler.passes import Unroller pass_ = Unroller(['u3', 'cx']) pm = PassManager(pass_) new_circuit = pm.run(qc) print(new_circuit.count_ops()) backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend, shots=1024) counts = job.result().get_counts() print(sorted(counts.items(), key=lambda x:x[1], reverse=True)[0:20]) plot_histogram(counts)
https://github.com/Naphann/Solving-TSP-Grover
Naphann
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import IBMQ, Aer, execute from qiskit.tools.visualization import plot_histogram ## oracle_initialize_part def OR(qubit_1, qubit_2, k): # enter qubit numbers here """ function does the equivalent of a classical OR between qubit numbers a and b and stores the result in qubit number k """ # qc.barrier(q) qc.x(q[qubit_1]) qc.x(q[qubit_2]) # qc.barrier(q) qc.ccx(q[qubit_1], q[qubit_2], q[k]) qc.x(q[k]) # qc.barrier(q) qc.x(q[qubit_1]) qc.x(q[qubit_2]) # qc.barrier(q) def are_not_equal(a_0, b_0, k): # enter node numbers here. For example, a is node 0, b is node 1 and c is node 2 """ function outputs 1 if nodes a and b are not the same. Node numbering starts from 0 as in the problem statement. k is the qubit number where the output is XOR-ed. qubit numbering also starts from 0 """ # qc.barrier(q) qc.cx(q[2*a_0], q[2*b_0]) qc.cx(q[(2*a_0) + 1], q[(2*b_0) + 1]) OR(2*b_0, (2*b_0)+1, k) qc.cx(q[2*a_0], q[2*b_0]) qc.cx(q[(2*a_0) + 1], q[(2*b_0) + 1]) # qc.barrier(q) def is_not_3(a, k): qc.ccx(q[2*a], q[(2*a)+1], q[k]) qc.x(q[k]) def initialize_oracle_part(n): t = 4 # qc.barrier(q) are_not_equal(0, 1, 6) # node a and b are not equal are_not_equal(0, 2, 7) are_not_equal(1, 2, 8) is_not_3(0, 11) is_not_3(1, 12) is_not_3(2, 13) # qc.barrier(q) qc.mct([q[6], q[7], q[8], q[11], q[12], q[13]], q[10],[q[9], q[14], q[15], q[16]]) # answer is stored in 10. please keep 9 a clean qubit, it's used as ancilla here # qc.barrier(q) is_not_3(0, 11) is_not_3(1, 12) is_not_3(2, 13) are_not_equal(0, 1, 6) # node a and b are not equal are_not_equal(0, 2, 7) are_not_equal(1, 2, 8) ## distance_black_box distances = { "32": 3, "31": 2, "30": 4, "21": 7, "20": 6, "10": 5, } def dist_single(): qr = QuantumRegister(2) qr_target = QuantumRegister(5) qc = QuantumCircuit(qr, qr_target, name='dist_single') for edge in distances: if edge[0] == '3': node = format(int(edge[1]), '02b') d_bin = format(distances[edge], '02b') for idx in range(len(node)): if node[idx] == '0': qc.x(qr[idx]) for idx in range(len(d_bin)): if d_bin[idx] == '1': qc.ccx(qr[0], qr[1], qr_target[idx]) for idx in range(len(node)): if node[idx] == '0': qc.x(qr[idx]) return qc def dist(): qr1 = QuantumRegister(2) qr2 = QuantumRegister(2) qr_target = QuantumRegister(5) qr_anc = QuantumRegister(2) qc = QuantumCircuit(qr1, qr2, qr_target, qr_anc, name='dist') for edge in distances: if edge[0] != '3': # convert to binaries node1 = format(int(edge[0]), '02b') node2 = format(int(edge[1]), '02b') d_bin = format(distances[edge], '02b') for idx in range(len(node1)): # assume node1 and node2 have the same length if node1[idx] == '0': qc.x(qr1[idx]) for idx in range(len(node2)): if node2[idx] == '0': qc.x(qr2[idx]) for idx in range(len(d_bin)): if d_bin[idx] == '1': qc.mct(qr1[:]+qr2[:], qr_target[idx], qr_anc) for idx in range(len(node2)): # invert back if node2[idx] == '0': qc.x(qr2[idx]) for idx in range(len(node1)): if node1[idx] == '0': qc.x(qr1[idx]) return qc ## multi_adder_1 def maj(a, b, k): qc.cx(q[k], q[b]) qc.cx(q[k], q[a]) qc.ccx(q[a], q[b], q[k]) def unmaj(a, b, k): qc.ccx(q[a], q[b], q[k]) qc.cx(q[k], q[a]) qc.cx(q[a], q[b]) def multiple_adder(a, b, c_0, z): arr_size = len(a) maj(c_0, b[0], a[0]) for i in range(arr_size-1): maj(a[i], b[i+1], a[i+1]) qc.cx(q[a[arr_size-1]], q[z]) for i in reversed(range(arr_size-1)): unmaj(a[i], b[i+1], a[i+1]) unmaj(c_0, b[0], a[0]) ## diffusion def diffusion(): qc.h(q[0:6]) qc.x(q[0:6]) qc.h(q[5]) qc.barrier() qc.mct(q[0:5], q[5], q[7:10]) qc.barrier() qc.h(q[5]) qc.x(q[0:6]) qc.h(q[0:6]) qubit_num = 25 # max is 32 if you're using the simulator # Ancilla indices inputs = [0, 1, 2, 3, 4, 5] init_ancillae = [6, 7, 8, 9] valid = [10] temp_dist = [11, 12, 13, 14, 15] total_dist = [16, 17, 18, 19, 20] gate_ancillae = [21, 22, 23] check_dist = [11, 12, 13, 14, 15] # initialize 13 here carry_check = [24] inputs = inputs[0] init_ancillae = init_ancillae[0] valid = valid[0] temp_dist = temp_dist[0] total_dist = total_dist[0] gate_ancillae = gate_ancillae[0] check_dist = check_dist[0] carry_check = carry_check[0] q = QuantumRegister(qubit_num) c = ClassicalRegister(6) qc = QuantumCircuit(q, c) qc.h(q[0:6]) qc.x(q[carry_check]) # forward oracle initialize_oracle_part(4) qc.append(dist_single(), q[inputs:inputs+2] + q[temp_dist:temp_dist+5]) multiple_adder([11, 12, 13, 14], [16, 17, 18, 19], init_ancillae, 20) qc.append(dist_single().inverse(), q[inputs:inputs+2] + q[temp_dist:temp_dist+5]) qc.append(dist(), q[inputs:inputs+4] + q[temp_dist:temp_dist+5] + q[gate_ancillae:gate_ancillae+2]) multiple_adder([11, 12, 13, 14], [16, 17, 18, 19], init_ancillae, 20) qc.append(dist().inverse(), q[inputs:inputs+4] + q[temp_dist:temp_dist+5] + q[gate_ancillae:gate_ancillae+2]) qc.append(dist(), q[inputs+2:inputs+6] + q[temp_dist:temp_dist+5] + q[gate_ancillae:gate_ancillae+2]) multiple_adder([11, 12, 13, 14], [16, 17, 18, 19], init_ancillae, 20) qc.append(dist().inverse(), q[inputs+2:inputs+6] + q[temp_dist:temp_dist+5] + q[gate_ancillae:gate_ancillae+2]) qc.x(q[check_dist:check_dist+3]) # init 15 multiple_adder([11, 12, 13, 14, 15], [16, 17, 18, 19, 20], init_ancillae, carry_check) # carry_check # qc.barrier() qc.cz(q[valid], q[carry_check]) # qc.barrier() # inverse oracle multiple_adder([11, 12, 13, 14, 15], [16, 17, 18, 19, 20], init_ancillae, carry_check) qc.x(q[check_dist:check_dist+3]) # init 15 qc.append(dist().inverse(), q[inputs+2:inputs+6] + q[temp_dist:temp_dist+5] + q[gate_ancillae:gate_ancillae+2]) multiple_adder([11, 12, 13, 14], [16, 17, 18, 19], init_ancillae, 20) qc.append(dist(), q[inputs+2:inputs+6] + q[temp_dist:temp_dist+5] + q[gate_ancillae:gate_ancillae+2]) qc.append(dist().inverse(), q[inputs:inputs+4] + q[temp_dist:temp_dist+5] + q[gate_ancillae:gate_ancillae+2]) multiple_adder([11, 12, 13, 14], [16, 17, 18, 19], init_ancillae, 20) qc.append(dist(), q[inputs:inputs+4] + q[temp_dist:temp_dist+5] + q[gate_ancillae:gate_ancillae+2]) qc.append(dist_single().inverse(), q[inputs:inputs+2] + q[temp_dist:temp_dist+5]) multiple_adder([11, 12, 13, 14], [16, 17, 18, 19], init_ancillae, 20) qc.append(dist_single(), q[inputs:inputs+2] + q[temp_dist:temp_dist+5]) initialize_oracle_part(4) diffusion() qc.measure(q[:6], c) # qc.draw() from qiskit.transpiler import PassManager from qiskit.transpiler.passes import Unroller pass_ = Unroller(['u3', 'cx']) pm = PassManager(pass_) new_circuit = pm.run(qc) print(new_circuit.count_ops()) backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend, shots=1024) counts = job.result().get_counts() print(sorted(counts.items(), key=lambda x:x[1], reverse=True)[0:20]) plot_histogram(counts)
https://github.com/Naphann/Solving-TSP-Grover
Naphann
import qiskit from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import Aer import numpy as np from math import floor, ceil %matplotlib inline import gate_extensions for n in range(5, 7): print('{}-bit controls'.format(n)) for inp in range(2**n): qr = QuantumRegister(n, 'qr') anc = QuantumRegister(max(ceil((n-2)/2), 1), 'anc') target = QuantumRegister(1) cr = ClassicalRegister(1, 'cr') qc = QuantumCircuit(qr, anc, target, cr) for i in range(n): if (inp & (1<<i)) > 0: qc.x(qr[i]) qc.mct(qr, target, anc, mode='clean-ancilla') qc.barrier() qc.measure(target, cr[0]) backend = Aer.get_backend('qasm_simulator') job = qiskit.execute(qc, backend, shots=10) result = job.result() counts = result.get_counts() # print(inp) if '1' in counts: print('{} got 1'.format(inp))
https://github.com/Naphann/Solving-TSP-Grover
Naphann
import qiskit from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import Aer import numpy as np from math import floor, ceil %matplotlib inline def RTL(qc, a, b, c): ## fig 3 dashed qc.rccx(a, b, c) def RTL_inv(qc, a, b, c): RTL(qc, a, b, c) def RTS(qc, a, b, c): ## fig 3 gates 2-6 qc.h(c) qc.t(c) qc.cx(b, c) qc.tdg(c) qc.cx(a, c) def RTS_inv(qc, a, b, c): qc.cx(a, c) qc.t(c) qc.cx(b, c) qc.tdg(c) qc.h(c) def SRTS(qc, a, b, c): ## circuit 3 dashed qc.h(c) qc.cx(c, b) qc.tdg(b) qc.cx(a, b) qc.t(b) qc.cx(c, b) qc.tdg(b) qc.cx(a, b) qc.t(b) def SRTS_inv(qc, a, b, c): qc.tdg(b) qc.cx(a, b) qc.t(b) qc.cx(c, b) qc.tdg(b) qc.cx(a, b) qc.t(b) qc.cx(c, b) qc.h(c) def RT4L(qc, a, b, c, d): ## fig 4 qc.rcccx(a, b, c, d) def RT4L_inv(qc, a, b, c, d): qc.h(d) qc.t(d) qc.cx(c, d) qc.tdg(d) qc.h(d) qc.t(d) qc.cx(b, d) qc.tdg(d) qc.cx(a, d) qc.t(d) qc.cx(b, d) qc.tdg(d) qc.cx(a, d) qc.h(d) qc.t(d) qc.cx(c, d) qc.tdg(d) qc.h(d) def RT4S(qc, a, b, c, d): ## fig 4 dashed qc.h(d) qc.t(d) qc.cx(c, d) qc.tdg(d) qc.h(d) qc.cx(a, d) qc.t(d) qc.cx(b, d) qc.tdg(d) qc.cx(a, d) def RT4S_inv(qc, a, b, c, d): qc.cx(a, d) qc.t(d) qc.cx(b, d) qc.tdg(d) qc.cx(a, d) qc.h(d) qc.t(d) qc.cx(c, d) qc.tdg(d) qc.h(d) def apply_mct_clean(self, controls, target, ancilla_register): if len(controls) < 3: raise ValueError("there's something wrong") n = len(controls) ancilla = ancilla_register[:ceil((n-2)/2)] if n == 3: # TODO: Check for ancilla length self.rccx(controls[0], controls[1], ancilla[0]) self.ccx(controls[2], ancilla[0], target) self.rccx(controls[0], controls[1], ancilla[0]) return if n == 4: # TODO: Check for ancilla length self.rcccx(controls[0], controls[1], controls[2], ancilla[0]) self.ccx(controls[3], ancilla[0], target) self.rcccx(controls[0], controls[1], controls[2], ancilla[0]) return ## when controls >= 5 if n % 2 == 0: self.rcccx(controls[0], controls[1], controls[2], ancilla[0]) self.barrier() anc_idx = 1 for i in range(3, n-1, 2): # print('i = /{}'.format(i)) self.rcccx(controls[i], controls[i+1], ancilla[anc_idx-1], ancilla[anc_idx]) self.barrier() anc_idx += 1 if (n-3)%2 == 1: self.ccx(controls[-1], ancilla[-1], target) self.barrier() else: self.rccx(controls[-2], ancilla[-2], ancilla[-1]) self.barrier() self.ccx(controls[-1], ancilla[-1], target) self.barrier() self.rccx(controls[-2], ancilla[-2], ancilla[-1]) self.barrier() for i in reversed(range(3, n-1, 2)): anc_idx -= 1 self.rcccx(controls[i], controls[i+1], ancilla[anc_idx-1], ancilla[anc_idx]) self.barrier() self.rcccx(controls[0], controls[1], controls[2], ancilla[0]) else: self.rcccx(controls[0], controls[1], controls[2], ancilla[0]) self.barrier() anc_idx = 1 for i in range(3, n-3, 2): # print('i = /{}'.format(i)) self.rcccx(controls[i], controls[i+1], ancilla[anc_idx-1], ancilla[anc_idx]) self.barrier() anc_idx += 1 if (n-3)%2 == 1: self.ccx(controls[-1], ancilla[-1], target) self.barrier() else: self.rccx(controls[-2], ancilla[-2], ancilla[-1]) self.barrier() self.ccx(controls[-1], ancilla[-1], target) self.barrier() self.rccx(controls[-2], ancilla[-2], ancilla[-1]) self.barrier() for i in reversed(range(3, n-3, 2)): anc_idx -= 1 self.rcccx(controls[i], controls[i+1], ancilla[anc_idx-1], ancilla[anc_idx]) self.barrier() self.rcccx(controls[0], controls[1], controls[2], ancilla[0]) qr = QuantumRegister(5, 'qr') anc = QuantumRegister(2, 'anc') target = QuantumRegister(1, 'target') qc = QuantumCircuit(qr, anc, target) apply_mct_clean(qc, qr, target, anc) # backend = Aer.get_backend('unitary_simulator') # job = qiskit.execute(qc, backend) # result = job.result() # print(result.get_unitary(qc, decimals=3)) # qc.draw(output='mpl') def apply_mct_dirty(self, controls, target, ancilla): # TODO: check controls to be list of bits or register if len(controls) == 1: self.cx(controls[0], target) return if len(controls) == 2: self.ccx(controls[0], controls[1], target) return if len(controls) == 3: SRTS(self, controls[2], ancilla[0], target) RTL(self, controls[0], controls[1], ancilla[0]) SRTS_inv(self, controls[2], ancilla[0], target) RTL_inv(self, controls[0], controls[1], ancilla[0]) return n = len(controls) anc = ancilla[:ceil((n-2)/2)] SRTS(self, controls[-1], anc[-1], target) qc.barrier() if (n-4)%2 == 0: a_idx = 1 for i in reversed(range(floor((n-4)/2))): RT4S(self, anc[a_idx - 1 + i], controls[2*i+3], controls[2*i+4], anc[a_idx + i]) qc.barrier() else: a_idx = 2 for i in reversed(range(floor((n-4)/2))): RT4S(self, anc[a_idx - 1 + i], controls[2*i+4], controls[2*i+5], anc[a_idx + i]) qc.barrier() RTS(self, anc[0], controls[3], anc[1]) qc.barrier() RT4L(self, controls[0], controls[1], controls[2], anc[0]) qc.barrier() if (n-4)%2 == 0: a_idx = 1 for i in (range(floor((n-4)/2))): RT4S_inv(self, anc[a_idx - 1 + i], controls[2*i+3], controls[2*i+4], anc[a_idx + i]) qc.barrier() else: a_idx = 2 RTS_inv(self, anc[0], controls[3], anc[1]) qc.barrier() for i in (range(floor((n-4)/2))): RT4S_inv(self, anc[a_idx - 1 + i], controls[2*i+4], controls[2*i+5], anc[a_idx + i]) qc.barrier() SRTS_inv(self, controls[-1], anc[-1], target) qc.barrier() ## SAME AS ABOVE if (n-4)%2 == 0: a_idx = 1 for i in reversed(range(floor((n-4)/2))): RT4S(self, anc[a_idx - 1 + i], controls[2*i+3], controls[2*i+4], anc[a_idx + i]) qc.barrier() else: a_idx = 2 for i in reversed(range(floor((n-4)/2))): RT4S(self, anc[a_idx - 1 + i], controls[2*i+4], controls[2*i+5], anc[a_idx + i]) qc.barrier() RTS(self, anc[0], controls[3], anc[1]) qc.barrier() RT4L_inv(self, controls[0], controls[1], controls[2], anc[0]) qc.barrier() if (n-4)%2 == 0: a_idx = 1 for i in (range(floor((n-4)/2))): RT4S_inv(self, anc[a_idx - 1 + i], controls[2*i+3], controls[2*i+4], anc[a_idx + i]) qc.barrier() else: a_idx = 2 RTS_inv(self, anc[0], controls[3], anc[1]) qc.barrier() for i in (range(floor((n-4)/2))): RT4S_inv(self, anc[a_idx - 1 + i], controls[2*i+4], controls[2*i+5], anc[a_idx + i]) qc.barrier() qr = QuantumRegister(3, 'qr') anc = QuantumRegister(3, 'anc') target = QuantumRegister(1, 'target') qc = QuantumCircuit(qr, anc, target) apply_mct_dirty(qc, qr, target, anc) # backend = Aer.get_backend('unitary_simulator') # job = qiskit.execute(qc, backend) # result = job.result() # print(result.get_unitary(qc, decimals=3)) # qc.draw(output='mpl') for n in range(5, 10): print('{}-bit controls'.format(n)) for inp in range(2**n): qr = QuantumRegister(n, 'qr') anc = QuantumRegister(max(ceil((n-2)/2), 1), 'anc') target = QuantumRegister(1) cr = ClassicalRegister(1, 'cr') qc = QuantumCircuit(qr, anc, target, cr) for i in range(n): if (inp & (1<<i)) > 0: qc.x(qr[i]) # apply_mct_dirty(qc, qr, target, anc) apply_mct_clean(qc, qr, target, anc) qc.barrier() qc.measure(target, cr[0]) backend = Aer.get_backend('qasm_simulator') job = qiskit.execute(qc, backend, shots=10) result = job.result() counts = result.get_counts() # print(inp) if '1' in counts: print('{} got 1'.format(inp)) def apply_mct(circuit, controls, target, anc, mode='clean-ancilla'): if len(controls) == 1: circuit.cx(controls[0], target) else if mode == 'clean-ancilla':
https://github.com/Naphann/Solving-TSP-Grover
Naphann
#initialization import matplotlib.pyplot as plt %matplotlib inline import numpy as np # importing Qiskit from qiskit import IBMQ, BasicAer, Aer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute # import basic plot tools from qiskit.tools.visualization import plot_histogram provider = IBMQ.load_account() def maj(a, b, k): qc.cx(q[k], q[b]) qc.cx(q[k], q[a]) qc.ccx(q[a], q[b], q[k]) def unmaj(a, b, k): qc.ccx(q[a], q[b], q[k]) qc.cx(q[k], q[a]) qc.cx(q[a], q[b]) def multiple_adder(a, b, c_0, z): arr_size = len(a) maj(c_0, b[0], a[0]) for i in range(arr_size-1): maj(a[i], b[i+1], a[i+1]) qc.cx(q[a[arr_size-1]], q[z]) for i in reversed(range(arr_size-1)): unmaj(a[i], b[i+1], a[i+1]) unmaj(c_0, b[0], a[0]) qubit_num = 20 # max is 32 if you're using the simulator q = QuantumRegister(qubit_num) c = ClassicalRegister(10) qc = QuantumCircuit(q, c) qc.x(q[0:2]) qc.x(q[6]) qc.barrier(q) # initialize_oracle_part(4) multiple_adder([0,1,2,3], [4,5,6,7], 8, 9) for i in range(10): qc.measure(q[i], c[i]) r = execute(qc, Aer.get_backend('qasm_simulator')).result() rc = r.get_counts() print(rc) plot_histogram(rc) qc.draw()
https://github.com/Naphann/Solving-TSP-Grover
Naphann
#initialization import matplotlib.pyplot as plt %matplotlib inline import numpy as np # importing Qiskit from qiskit import IBMQ, BasicAer, Aer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute # import basic plot tools from qiskit.tools.visualization import plot_histogram provider = IBMQ.load_account() #functions # def OR(a, b, k): # # enter qubit numbers here # """ function does the equivalent of a classical OR between nodes a and b and stores the result in k """ # qc.barrier(q) # qc.cx(q[a], q[k]) # qc.barrier(q) # qc.x(q[a]) # qc.barrier(q) # qc.ccx(q[a], q[b], q[k]) # qc.barrier(q) # qc.x(q[a]) # qc.barrier(q) def OR(qubit_1, qubit_2, k): # enter qubit numbers here """ function does the equivalent of a classical OR between qubit numbers a and b and stores the result in qubit number k """ qc.barrier(q) qc.x(q[qubit_1]) qc.x(q[qubit_2]) qc.barrier(q) qc.ccx(q[qubit_1], q[qubit_2], q[k]) qc.x(q[k]) qc.barrier(q) qc.x(q[qubit_1]) qc.x(q[qubit_2]) qc.barrier(q) def are_not_equal(a_0, b_0, k): # enter node numbers here. For example, a is node 0, b is node 1 and c is node 2 """ function outputs 1 if nodes a and b are not the same. Node numbering starts from 0 as in the problem statement. k is the qubit number where the output is XOR-ed. qubit numbering also starts from 0 """ qc.barrier(q) qc.cx(q[2*a_0], q[2*b_0]) qc.cx(q[(2*a_0) + 1], q[(2*b_0) + 1]) OR(2*b_0, (2*b_0)+1, k) qc.cx(q[2*a_0], q[2*b_0]) qc.cx(q[(2*a_0) + 1], q[(2*b_0) + 1]) qc.barrier(q) # number of nodes def initialize_oracle_part(): qc.h(q[0:6]) qc.barrier(q) are_not_equal(0, 1, 6) # node a and b are not equal are_not_equal(0, 2, 7) are_not_equal(1, 2, 8) qc.barrier(q) qc.mct([q[6], q[7], q[8]], q[10],[q[9]]) # answer is stored in 10. please keep 9 a clean qubit, it's used as ancilla here qc.barrier(q) are_not_equal(0, 1, 6) # node a and b are not equal are_not_equal(0, 2, 7) are_not_equal(1, 2, 8) def diffusion(): qc.h(q[0:6]) qc.x(q[0:6]) qc.h(q[5]) qc.barrier() qc.mct([q[0], q[1], q[2], q[3], q[4]], q[5], [q[11], q[12], q[13]]) qc.barrier() qc.h(q[5]) qc.x(q[0:6]) qc.h(q[0:6]) def grover(iter): for i in range(iter): initialize_oracle_part() diffusion() qubit_num = 20 # max is 32 if you're using the simulator q = QuantumRegister(qubit_num) c = ClassicalRegister(14) qc = QuantumCircuit(q, c) qc.x(q[10]) qc.h(q[10]) grover(2) qc.measure(q[0:6], c[0:6]) qc.draw() # running and getting results backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend, shots=1000) # backend = provider.get_backend('ibmq_qasm_simulator') # job = execute(qc, backend=backend, shots=8000, seed_simulator=12345, backend_options={"fusion_enable":True}) result = job.result() count = result.get_counts() print(count) #sort count count_sorted = sorted(count.items(), key=lambda x:x[1], reverse=True) # collect answers with Top 9 probability ans_list = count_sorted[0:9] print(ans_list)
https://github.com/Naphann/Solving-TSP-Grover
Naphann
#initialization import matplotlib.pyplot as plt %matplotlib inline import numpy as np # importing Qiskit from qiskit import IBMQ, BasicAer, Aer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute # import basic plot tools from qiskit.tools.visualization import plot_histogram provider = IBMQ.load_account() #functions # def OR(a, b, k): # # enter qubit numbers here # """ function does the equivalent of a classical OR between nodes a and b and stores the result in k """ # qc.barrier(q) # qc.cx(q[a], q[k]) # qc.barrier(q) # qc.x(q[a]) # qc.barrier(q) # qc.ccx(q[a], q[b], q[k]) # qc.barrier(q) # qc.x(q[a]) # qc.barrier(q) def OR(qubit_1, qubit_2, k): # enter qubit numbers here """ function does the equivalent of a classical OR between qubit numbers a and b and stores the result in qubit number k """ qc.barrier(q) qc.x(q[qubit_1]) qc.x(q[qubit_2]) qc.barrier(q) qc.ccx(q[qubit_1], q[qubit_2], q[k]) qc.x(q[k]) qc.barrier(q) qc.x(q[qubit_1]) qc.x(q[qubit_2]) qc.barrier(q) def are_not_equal(a_0, b_0, k): # enter node numbers here. For example, a is node 0, b is node 1 and c is node 2 """ function outputs 1 if nodes a and b are not the same. Node numbering starts from 0 as in the problem statement. k is the qubit number where the output is XOR-ed. qubit numbering also starts from 0 """ qc.barrier(q) qc.cx(q[2*a_0], q[2*b_0]) qc.cx(q[(2*a_0) + 1], q[(2*b_0) + 1]) OR(2*b_0, (2*b_0)+1, k) qc.cx(q[2*a_0], q[2*b_0]) qc.cx(q[(2*a_0) + 1], q[(2*b_0) + 1]) qc.barrier(q) # number of nodes n = 4 def initialize_oracle_part(n): t = 2*(n-1) qc.h(q[0:t]) qc.barrier(q) are_not_equal(0, 1, 6) # node a and b are not equal are_not_equal(0, 2, 7) are_not_equal(1, 2, 8) qc.barrier(q) qc.mct([q[6], q[7], q[8]], q[10],[q[9]]) # answer is stored in 10. please keep 9 a clean qubit, it's used as ancilla here qc.barrier(q) are_not_equal(0, 1, 6) # node a and b are not equal are_not_equal(0, 2, 7) are_not_equal(1, 2, 8) qubit_num = 20 # max is 32 if you're using the simulator q = QuantumRegister(qubit_num) c = ClassicalRegister(14) qc = QuantumCircuit(q, c) initialize_oracle_part(4) qc.draw(output='mpl')
https://github.com/Naphann/Solving-TSP-Grover
Naphann
import qiskit from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import Aer from qiskit.circuit import Qubit import numpy as np from math import floor, ceil def RTL(qc, a, b, c): ## fig 3 dashed qc.rccx(a, b, c) def RTL_inv(qc, a, b, c): RTL(qc, a, b, c) def RTS(qc, a, b, c): ## fig 3 gates 2-6 qc.h(c) qc.t(c) qc.cx(b, c) qc.tdg(c) qc.cx(a, c) def RTS_inv(qc, a, b, c): qc.cx(a, c) qc.t(c) qc.cx(b, c) qc.tdg(c) qc.h(c) def SRTS(qc, a, b, c): ## circuit 3 dashed qc.h(c) qc.cx(c, b) qc.tdg(b) qc.cx(a, b) qc.t(b) qc.cx(c, b) qc.tdg(b) qc.cx(a, b) qc.t(b) def SRTS_inv(qc, a, b, c): qc.tdg(b) qc.cx(a, b) qc.t(b) qc.cx(c, b) qc.tdg(b) qc.cx(a, b) qc.t(b) qc.cx(c, b) qc.h(c) def RT4L(qc, a, b, c, d): ## fig 4 qc.rcccx(a, b, c, d) def RT4L_inv(qc, a, b, c, d): qc.h(d) qc.t(d) qc.cx(c, d) qc.tdg(d) qc.h(d) qc.t(d) qc.cx(b, d) qc.tdg(d) qc.cx(a, d) qc.t(d) qc.cx(b, d) qc.tdg(d) qc.cx(a, d) qc.h(d) qc.t(d) qc.cx(c, d) qc.tdg(d) qc.h(d) def RT4S(qc, a, b, c, d): ## fig 4 dashed qc.h(d) qc.t(d) qc.cx(c, d) qc.tdg(d) qc.h(d) qc.cx(a, d) qc.t(d) qc.cx(b, d) qc.tdg(d) qc.cx(a, d) def RT4S_inv(qc, a, b, c, d): qc.cx(a, d) qc.t(d) qc.cx(b, d) qc.tdg(d) qc.cx(a, d) qc.h(d) qc.t(d) qc.cx(c, d) qc.tdg(d) qc.h(d) def apply_mct_clean(self, controls, target, ancilla_register): if len(controls) < 3: raise ValueError("there's something wrong") n = len(controls) ancilla = ancilla_register[:ceil((n-2)/2)] if n == 3: # TODO: Check for ancilla length self.rccx(controls[0], controls[1], ancilla[0]) self.ccx(controls[2], ancilla[0], target) self.rccx(controls[0], controls[1], ancilla[0]) return if n == 4: # TODO: Check for ancilla length self.rcccx(controls[0], controls[1], controls[2], ancilla[0]) self.ccx(controls[3], ancilla[0], target) self.rcccx(controls[0], controls[1], controls[2], ancilla[0]) return ## when controls >= 5 if n % 2 == 0: self.rcccx(controls[0], controls[1], controls[2], ancilla[0]) self.barrier() anc_idx = 1 for i in range(3, n-1, 2): # print('i = /{}'.format(i)) self.rcccx(controls[i], controls[i+1], ancilla[anc_idx-1], ancilla[anc_idx]) self.barrier() anc_idx += 1 if (n-3)%2 == 1: self.ccx(controls[-1], ancilla[-1], target) self.barrier() else: self.rccx(controls[-2], ancilla[-2], ancilla[-1]) self.barrier() self.ccx(controls[-1], ancilla[-1], target) self.barrier() self.rccx(controls[-2], ancilla[-2], ancilla[-1]) self.barrier() for i in reversed(range(3, n-1, 2)): anc_idx -= 1 self.rcccx(controls[i], controls[i+1], ancilla[anc_idx-1], ancilla[anc_idx]) self.barrier() self.rcccx(controls[0], controls[1], controls[2], ancilla[0]) else: self.rcccx(controls[0], controls[1], controls[2], ancilla[0]) self.barrier() anc_idx = 1 for i in range(3, n-3, 2): # print('i = /{}'.format(i)) self.rcccx(controls[i], controls[i+1], ancilla[anc_idx-1], ancilla[anc_idx]) self.barrier() anc_idx += 1 if (n-3)%2 == 1: self.ccx(controls[-1], ancilla[-1], target) self.barrier() else: self.rccx(controls[-2], ancilla[-2], ancilla[-1]) self.barrier() self.ccx(controls[-1], ancilla[-1], target) self.barrier() self.rccx(controls[-2], ancilla[-2], ancilla[-1]) self.barrier() for i in reversed(range(3, n-3, 2)): anc_idx -= 1 self.rcccx(controls[i], controls[i+1], ancilla[anc_idx-1], ancilla[anc_idx]) self.barrier() self.rcccx(controls[0], controls[1], controls[2], ancilla[0]) def apply_mct_dirty(self, controls, target, ancilla): # TODO: check controls to be list of bits or register if len(controls) == 1: self.cx(controls[0], target) return if len(controls) == 2: self.ccx(controls[0], controls[1], target) return if len(controls) == 3: SRTS(self, controls[2], ancilla[0], target) RTL(self, controls[0], controls[1], ancilla[0]) SRTS_inv(self, controls[2], ancilla[0], target) RTL_inv(self, controls[0], controls[1], ancilla[0]) return n = len(controls) anc = ancilla[:ceil((n-2)/2)] SRTS(self, controls[-1], anc[-1], target) self.barrier() if (n-4)%2 == 0: a_idx = 1 for i in reversed(range(floor((n-4)/2))): RT4S(self, anc[a_idx - 1 + i], controls[2*i+3], controls[2*i+4], anc[a_idx + i]) self.barrier() else: a_idx = 2 for i in reversed(range(floor((n-4)/2))): RT4S(self, anc[a_idx - 1 + i], controls[2*i+4], controls[2*i+5], anc[a_idx + i]) self.barrier() RTS(self, anc[0], controls[3], anc[1]) self.barrier() RT4L(self, controls[0], controls[1], controls[2], anc[0]) self.barrier() if (n-4)%2 == 0: a_idx = 1 for i in (range(floor((n-4)/2))): RT4S_inv(self, anc[a_idx - 1 + i], controls[2*i+3], controls[2*i+4], anc[a_idx + i]) self.barrier() else: a_idx = 2 RTS_inv(self, anc[0], controls[3], anc[1]) self.barrier() for i in (range(floor((n-4)/2))): RT4S_inv(self, anc[a_idx - 1 + i], controls[2*i+4], controls[2*i+5], anc[a_idx + i]) self.barrier() SRTS_inv(self, controls[-1], anc[-1], target) self.barrier() ## SAME AS ABOVE if (n-4)%2 == 0: a_idx = 1 for i in reversed(range(floor((n-4)/2))): RT4S(self, anc[a_idx - 1 + i], controls[2*i+3], controls[2*i+4], anc[a_idx + i]) self.barrier() else: a_idx = 2 for i in reversed(range(floor((n-4)/2))): RT4S(self, anc[a_idx - 1 + i], controls[2*i+4], controls[2*i+5], anc[a_idx + i]) self.barrier() RTS(self, anc[0], controls[3], anc[1]) self.barrier() RT4L_inv(self, controls[0], controls[1], controls[2], anc[0]) self.barrier() if (n-4)%2 == 0: a_idx = 1 for i in (range(floor((n-4)/2))): RT4S_inv(self, anc[a_idx - 1 + i], controls[2*i+3], controls[2*i+4], anc[a_idx + i]) self.barrier() else: a_idx = 2 RTS_inv(self, anc[0], controls[3], anc[1]) self.barrier() for i in (range(floor((n-4)/2))): RT4S_inv(self, anc[a_idx - 1 + i], controls[2*i+4], controls[2*i+5], anc[a_idx + i]) self.barrier() def apply_mct(circuit, controls, target, anc, mode='clean-ancilla'): if len(controls) == 1: circuit.cx(controls[0], target) elif len(controls) == 2: circuit.ccx(controls[0], controls[1], target) else: if mode == 'clean-ancilla': apply_mct_clean(circuit, controls, target, anc) if mode == 'dirty-ancilla': apply_mct_dirty(circuit, controls, target, anc) def _mct(self, controls, target, ancilla, mode): if controls is None or len(controls) < 0: raise ValueError('you should pass controls as list or registers') if target is None or (not isinstance(target, Qubit) and len(target) != 1): raise ValueError('target length is not 1') if ancilla is None or len(ancilla) < ceil((len(controls)-2)/2): raise ValueError('for {} controls, need at least {} ancilla'.format(len(controls), ceil((len(controls)-2)/2))) if mode is None or (mode != 'dirty-ancilla' and mode != 'clean-ancilla'): raise ValueError('unknown mode') apply_mct(self, controls, target, ancilla, mode) QuantumCircuit.mct = _mct
https://github.com/samuraigab/Quantum-Basic-Algorithms
samuraigab
from qiskit import QuantumCircuit from qiskit.visualization import plot_histogram qc=QuantumCircuit(4,2) ## for adder we need four quantum register and 2 classical register qc.barrier() # use cnots to write the XOR of the inputs on qubit 2 qc.cx(0,2) qc.cx(1,2) qc.ccx(0,1,3) qc.barrier() # extract outputs qc.measure(2,0) # extract XOR value qc.measure(3,1) qc.draw() from qiskit import Aer sim = Aer.get_backend('aer_simulator') from qiskit import assemble qobj = assemble(qc) counts = sim.run(qobj).result().get_counts() plot_histogram(counts) from qiskit import QuantumCircuit qc1=QuantumCircuit(4,2) ## for adder we need four quantum register and 2 classical register qc1.x(1) qc1.barrier() # use cnots to write the XOR of the inputs on qubit 2 qc1.cx(0,2) qc1.cx(1,2) qc1.ccx(0,1,3) qc1.barrier() # extract outputs qc1.measure(2,0) # extract XOR value qc1.measure(3,1) qc1.draw() from qiskit import Aer sim = Aer.get_backend('aer_simulator') from qiskit import assemble qobj = assemble(qc1) counts = sim.run(qobj).result().get_counts() plot_histogram(counts) from qiskit import QuantumCircuit qc2=QuantumCircuit(4,2) ## for adder we need four quantum register and 2 classical register qc2.x(0) qc2.barrier() # use cnots to write the XOR of the inputs on qubit 2 qc2.cx(0,2) qc2.cx(1,2) qc2.ccx(0,1,3) qc2.barrier() # extract outputs qc2.measure(2,0) # extract XOR value qc2.measure(3,1) qc2.draw() from qiskit import Aer sim = Aer.get_backend('aer_simulator') from qiskit import assemble qobj = assemble(qc2) counts = sim.run(qobj).result().get_counts() plot_histogram(counts) from qiskit import QuantumCircuit qc3=QuantumCircuit(4,2) ## for adder we need four quantum register and 2 classical register qc3.x(0) qc3.x(1) qc3.barrier() # use cnots to write the XOR of the inputs on qubit 2 qc3.cx(0,2) qc3.cx(1,2) qc3.ccx(0,1,3) qc3.barrier() # extract outputs qc3.measure(2,0) # extract XOR value qc3.measure(3,1) qc3.draw() from qiskit import Aer sim = Aer.get_backend('aer_simulator') from qiskit import assemble qobj = assemble(qc3) counts = sim.run(qobj).result().get_counts() plot_histogram(counts)
https://github.com/samuraigab/Quantum-Basic-Algorithms
samuraigab
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, Aer, IBMQ,execute from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * # Loading your IBM Quantum account(s) provider = IBMQ.load_account() # Criando um circuito de n qubits n = 4 qc = QuantumCircuit(n) #Desenhando o circuito qc.draw() backend = Aer.get_backend('statevector_simulator') results = execute(qc, backend).result().get_statevector() plot_bloch_multivector(qc) import matplotlib.pyplot as plt from IPython.display import display, Latex n = 1 qc = QuantumCircuit(n) print('Com probabilidade máxima (igual 1) o qubit se econtra no estado 0.') backend = Aer.get_backend('statevector_simulator') results = execute(qc,backend).result().get_counts() display(plot_histogram(results, figsize = (2,2))) state = execute(qc,backend).result().get_statevector() plot_bloch_multivector(state) # Colocando em superposição qc = QuantumCircuit(n) qc.h(0) display(qc.draw()) state = execute(qc,backend).result().get_statevector() plot_bloch_multivector(state) # print('--- O resultado abaixo mostra que temos um qubit em superposição.') # print("--- Apesar termos 50% de chance de medir o estado 0 ou 1, só conseguimos extrair um bit \ # de informação do sistema. O número de bits (clássicos) de informação extraídos \ # do sistema será, no máximo, igual ao número qubits") # print("--- O nosso resultado será 0 ou 1") qc = QuantumCircuit(n,1) qc.h(0) qc.measure(0,0) backend = Aer.get_backend('qasm_simulator') results = execute(qc,backend, shots=10000).result().get_counts() plot_histogram(results, figsize=(2,2)) n = 4 qc = QuantumCircuit(n) qc.id(0) # nao faz nada no qubit 0 qc.x(1) # flipa o qubit 1 --- 0->1 qc.h(2) # coloca o qubit 2 em superposição: |0> = |0> + |1> qc.x(3) # flipa o qubit 3 --- |0> -> |1> qc.h(3) # coloca o qubit 3 em superposção: |1> = |0> - |1> qc.draw() print("--------- Mostra a posição de cada um dos qubits na esfera de Bloch ---------") backend = Aer.get_backend('statevector_simulator') results = execute(qc,backend).result().get_statevector() plot_bloch_multivector(results) n = 1 qc = QuantumCircuit(n,1) qc.h(0) qc.measure(0,0) display(qc.draw()) # |0> ---> H ----->|0> + |1> print('----------O resultado da medida de um qubit em superposição.---------\n') shots = 10000 backend = Aer.get_backend('qasm_simulator') results = execute(qc,backend, shots=shots).result().get_counts() display(plot_histogram(results,figsize = (3,3))) state0 = results['0'] state1 = results['1'] print(f'Ao rodar {shots} vezes experimento, o resultado 0 apareceu {state0} \ vezes e resultado 1 ocorreu {state1} vezes') print("\n\n------ Visualização da medida do experimento rodando quatro vezes ------\n") for i in range(4): results = execute(qc,backend, shots = 1).result().get_counts() display(plot_histogram(results, figsize=(2,2))) # Run the code in this cell to see the widget from qiskit_textbook.widgets import gate_demo gate_demo(gates='pauli+h+rz') n = 2 qc = QuantumCircuit(n) qc.h(0) qc.h(1) # qc.measure(range(n), range(n)) display(qc.draw()) #|0> -> H -> |0> + |1> #|00> -> H|0>*Id|0> = (|0> + |1>)(|0>) = (|00> + |10>) Estado nao emaranhado backend = Aer.get_backend('statevector_simulator') results = execute(qc,backend).result().get_counts() plot_histogram(results, figsize = (3,3)) n = 2 qc = QuantumCircuit(n) qc.h(0) qc.cx(0,1) # qc.measure(0,0) # qc.measure(1,1) qc.draw() backend = Aer.get_backend('statevector_simulator') results = execute(qc,backend).result().get_counts() plot_histogram(results, figsize = (3,3)) #|0> -> H -> |0> + |1> #|00> -> H|0>*Id|0> = (|0> + |1>)(|0>) = (|00> + |10>) aplicar CNOT (|00> + |11>) - Estado Emaranhado
https://github.com/samuraigab/Quantum-Basic-Algorithms
samuraigab
import numpy as np # Importing standard Qiskit libraries from qiskit import * from qiskit import QuantumCircuit, transpile, Aer, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * from qiskit_textbook.tools import array_to_latex # Loading your IBM Quantum account(s) provider = IBMQ.load_account() n = 2 qc = QuantumCircuit(n) qc.h(0) qc.h(1) display(qc.draw()) ''' Executando o circuito acima em um simulador quântico. O resultado irá mostrar a probabilidade de obter um dos 4 estados possivíveis: 00, 01, 10 e 11 Lembrando que o que conseguimos estrair de informação são os bits clássicos. ''' backend = Aer.get_backend('statevector_simulator') results = execute(qc,backend).result().get_counts() state = execute(qc,backend).result().get_statevector() #Gerando o histograma dos resultatos display(plot_histogram(results, figsize = (3,3))) #Mostrando vetor de estado array_to_latex(state, pretext="\\vert \psi\\rangle = ") n = 2 # número de qubits c = 2 # número de bits (clássicos) #iniciando o circuito com n qubit e c bits qc = QuantumCircuit(n, c) qc.h(0) qc.h(1) #medindo os qubits q0 e q1 e guarando o valor em c0 e c1 (respectivamente) qc.measure(range(n), range(c)) display(qc.draw()) shots = 100 #quantidade de vezes que realizamos o experimento plots = 1 #numero de plots backend = Aer.get_backend('qasm_simulator') for i in range(plots): results = execute(qc,backend, shots = shots).result().get_counts() #Gerando o histograma dos resultatos display(plot_histogram(results, figsize = (3,3))) print(f"O resultado 00 apareceu {results['00']}") print(f"O resultado 01 apareceu {results['01']}") print(f"O resultado 10 apareceu {results['10']}") print(f"O resultado 11 apareceu {results['11']}") n = 2 # número de qubits c = 2 # número de bits (clássicos) #iniciando o circuito com n qubit e c bits qc = QuantumCircuit(n) qc.h(0) qc.cx(0,1) qc.draw() backend = Aer.get_backend('statevector_simulator') results = execute(qc,backend).result().get_counts() display(plot_histogram(results, figsize = (3,3))) state = execute(qc,backend).result().get_statevector() array_to_latex(state, pretext="\\vert \psi \\rangle = ") n = 2 # número de qubits c = 2 # número de bits (clássicos) #iniciando o circuito com n qubit e c bits qc = QuantumCircuit(n) # qc.h(0) # qc.z(0) qc.x(0) qc.h(0) qc.cx(0,1) qc.draw() backend = Aer.get_backend('statevector_simulator') results = execute(qc,backend).result().get_counts() display(plot_histogram(results, figsize = (3,3))) state = execute(qc,backend).result().get_statevector() array_to_latex(state, pretext="\\vert \psi \\rangle = ") n = 2 # número de qubits c = 2 # número de bits (clássicos) #iniciando o circuito com n qubit e c bits qc = QuantumCircuit(n) qc.h(0) #00 + 10 qc.x(1) #01 + 11 (0 + 1)* 1 qc.cx(0,1) #01 +10 (?) qc.draw() backend = Aer.get_backend('statevector_simulator') results = execute(qc,backend).result().get_counts() display(plot_histogram(results, figsize = (3,3))) state = execute(qc,backend).result().get_statevector() array_to_latex(state, pretext="\\vert \psi \\rangle = ") n = 2 # número de qubits c = 2 # número de bits (clássicos) #iniciando o circuito com n qubit e c bits qc = QuantumCircuit(n) qc.x(0) qc.h(0) qc.x(1) qc.cx(0,1) display(qc.draw()) backend = Aer.get_backend('statevector_simulator') results = execute(qc,backend).result().get_counts() display(plot_histogram(results, figsize = (3,3))) state = execute(qc,backend).result().get_statevector() array_to_latex(state, pretext="\\vert \psi \\rangle = ")
https://github.com/samuraigab/Quantum-Basic-Algorithms
samuraigab
import numpy as np from numpy import pi # importing Qiskit from qiskit import QuantumCircuit, transpile, assemble, Aer from qiskit.visualization import plot_histogram, plot_bloch_multivector qc = QuantumCircuit(3) qc.h(2) qc.cp(pi/2, 1, 2) qc.cp(pi/4, 0, 2) qc.h(1) qc.cp(pi/2, 0, 1) qc.h(0) qc.swap(0, 2) qc.draw() def qft_rotations(circuit, n): if n == 0: return circuit n -= 1 circuit.h(n) for qubit in range(n): circuit.cp(pi/2**(n-qubit), qubit, n) qft_rotations(circuit, n) def swap_registers(circuit, n): for qubit in range(n//2): circuit.swap(qubit, n-qubit-1) return circuit def qft(circuit, n): qft_rotations(circuit, n) swap_registers(circuit, n) return circuit qc = QuantumCircuit(4) qft(qc,4) qc.draw() # Create the circuit qc = QuantumCircuit(3) # Encode the state 5 (101 in binary) qc.x(0) qc.x(2) qc.draw() sim = Aer.get_backend("aer_simulator") qc_init = qc.copy() qc_init.save_statevector() statevector = sim.run(qc_init).result().get_statevector() plot_bloch_multivector(statevector) qft(qc, 3) qc.draw() qc.save_statevector() statevector = sim.run(qc).result().get_statevector() plot_bloch_multivector(statevector)
https://github.com/samuraigab/Quantum-Basic-Algorithms
samuraigab
import matplotlib as mpl import numpy as np import matplotlib.pyplot as plt from qiskit import QuantumCircuit, Aer, transpile, assemble from qiskit.visualization import plot_histogram, plot_bloch_multivector qc = QuantumCircuit(1,1) # Alice prepares qubit in state |+> qc.h(0) qc.barrier() # Alice now sends the qubit to Bob # who measures it in the X-basis qc.h(0) qc.measure(0,0) # Draw and simulate circuit display(qc.draw()) aer_sim = Aer.get_backend('aer_simulator') job = aer_sim.run(assemble(qc)) plot_histogram(job.result().get_counts()) qc = QuantumCircuit(1,1) # Alice prepares qubit in state |+> qc.h(0) # Alice now sends the qubit to Bob # but Eve intercepts and tries to read it qc.measure(0, 0) qc.barrier() # Eve then passes this on to Bob # who measures it in the X-basis qc.h(0) qc.measure(0,0) # Draw and simulate circuit display(qc.draw()) aer_sim = Aer.get_backend('aer_simulator') job = aer_sim.run(assemble(qc)) plot_histogram(job.result().get_counts()) n = 100 ## Step 1 # Alice generates bits. alice_bits = np.random.randint(0,2,n) ## Step 2 # Create an array to tell us which qubits # are encoded in which bases alice_bases = np.random.randint(0,2,n) # Function to compare the bits & bases generated by alice, and then 'encode' the message. Basically determines the state of the qubit/photon to send. def encode_message(bits, bases): message = [] for i in range(n): qc = QuantumCircuit(1,1) if bases[i] == 0: # Prepare qubit in Z-basis if bits[i] == 0: pass else: qc.x(0) else: # Prepare qubit in X-basis if bits[i] == 0: qc.h(0) else: qc.x(0) qc.h(0) qc.barrier() message.append(qc) return message # Alice computes the encoded message using the function defined above. message = encode_message(alice_bits, alice_bases) ## Step 3 # Decide which basis to measure in: bob_bases = np.random.randint(0,2,n) # Function to decode the message sent by alice by comparing qubit/photon states with Bob's generated bases. def measure_message(message, bases): backend = Aer.get_backend('aer_simulator') measurements = [] for q in range(n): if bases[q] == 0: # measuring in Z-basis message[q].measure(0,0) if bases[q] == 1: # measuring in X-basis message[q].h(0) message[q].measure(0,0) aer_sim = Aer.get_backend('aer_simulator') qobj = assemble(message[q], shots=1, memory=True) result = aer_sim.run(qobj).result() measured_bit = int(result.get_memory()[0]) measurements.append(measured_bit) return measurements # Decode the message according to his bases bob_results = measure_message(message, bob_bases) ## Step 4 # Function to perform sifting i.e. disregard the bits for which Bob's & A;ice's bases didnot match. def remove_garbage(a_bases, b_bases, bits): good_bits = [] for q in range(n): if a_bases[q] == b_bases[q]: # If both used the same basis, add # this to the list of 'good' bits good_bits.append(bits[q]) return good_bits # Performing sifting for Alice's and Bob's bits. alice_key = remove_garbage(alice_bases, bob_bases, alice_bits) bob_key = remove_garbage(alice_bases, bob_bases, bob_results) print("Alice's key after sifting (without interception)", alice_key) print("Bob's key after sifting (without interception) ", bob_key) # # Step 5 # # Function for parameter estimation i.e. determining the error rate by comparing subsets taen from both Alice's key & Bob's key. # def sample_bits(bits, selection): # sample = [] # for i in selection: # # use np.mod to make sure the # # bit we sample is always in # # the list range # i = np.mod(i, len(bits)) # # pop(i) removes the element of the # # list at index 'i' # sample.append(bits.pop(i)) # return sample # # Performing parameter estimation & disregarding the bits used for comparison from Alice's & Bob's key. # sample_size = 15 # bit_selection = np.random.randint(0,n,size=sample_size) # bob_sample = sample_bits(bob_key, bit_selection) # alice_sample = sample_bits(alice_key, bit_selection) num = 0 for i in range(0,len(bob_key)): if alice_key[i] == bob_key[i]: num = num + 1 matching_bits = (num/len(bob_key))*100 print(matching_bits,"% of the bits match.") ## Step 1 alice_bits = np.random.randint(2, size=n) ## Step 2 alice_bases = np.random.randint(2, size=n) message = encode_message(alice_bits, alice_bases) ## Interception!! eve_bases = np.random.randint(2, size=n) intercepted_message = measure_message(message, eve_bases) ## Step 3 bob_bases = np.random.randint(2, size=n) bob_results = measure_message(message, bob_bases) ## Step 4 bob_key = remove_garbage(alice_bases, bob_bases, bob_results) alice_key = remove_garbage(alice_bases, bob_bases, alice_bits) print("Alice's key after sifting (with interception)", alice_key) print("Bob's key after sifting (with interception) ", bob_key) # ## Step 5 # sample_size = 15 # bit_selection = np.random.randint(n, size=sample_size) # bob_sample = sample_bits(bob_key, bit_selection) # alice_sample = sample_bits(alice_key, bit_selection) num = 0 for i in range(0,len(bob_key)): if alice_key[i] == bob_key[i]: num = num + 1 matching_bits = (num/len(bob_key))*100 print(matching_bits,"% of the bits match.") plt.rcParams['axes.linewidth'] = 2 mpl.rcParams['font.family'] = ['Georgia'] plt.figure(figsize=(10.5,6)) ax=plt.axes() ax.set_title('') ax.set_xlabel('$n$ (Number of bits drawn from the sifted keys for determining error rate)',fontsize = 18,labelpad=10) ax.set_ylabel(r'$P(Eve\ detected)$',fontsize = 18,labelpad=10) ax.xaxis.set_tick_params(which='major', size=8, width=2, direction='in', top='on') ax.yaxis.set_tick_params(which='major', size=8, width=2, direction='in', top='on') ax.tick_params(axis='x', labelsize=20) ax.tick_params(axis='y', labelsize=20) ax. xaxis. label. set_size(20) ax. yaxis. label. set_size(20) n = 30 x = np.arange(n+1) y = 1 - 0.75**x ax.plot(x,y,color = plt.cm.rainbow(np.linspace(0, 1, 5))[0], marker = "s", markerfacecolor='r')
https://github.com/samuraigab/Quantum-Basic-Algorithms
samuraigab
''' Quantum Phase Estimation Por Samuraí Brito Data:02072021 ''' import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, Aer, IBMQ, execute from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * # Loading your IBM Quantum account(s) # provider = IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-research', group='inter-inst-phys-1', project='main') from qiskit.circuit.library import QFT n = 4 qft = QFT(num_qubits = n, name = 'QFT') qft.draw('mpl') #Creating 101 state qft_circ = QuantumCircuit(n,n) qft_circ.x(0) qft_circ.x(2) qft_circ.draw() sim_backend = Aer.get_backend('statevector_simulator') state = execute(qft_circ, sim_backend).result().get_statevector() # #get results # results = job.result() # state = results.get_statevector() plot_bloch_multivector(state) #appending QFT subroutine qft_circ.append(qft,range(n)) qft_circ.save_statevector() qft_circ.draw() #Run in a simulator sim_backend = Aer.get_backend('statevector_simulator') state = execute(qft_circ, sim_backend).result().get_statevector() plot_bloch_multivector(state) iqft = QFT(n, inverse=True, name = 'iQFT') iqft.draw() #apply inverse QFT qft_circ.append(iqft, range(n)) qft_circ.measure(range(n), range(n)) qft_circ.draw() sim_backend = Aer.get_backend('statevector_simulator') state = execute(qft_circ, sim_backend, shots = 10000000).result().get_statevector() plot_bloch_multivector(state) sim_backend = Aer.get_backend('qasm_simulator') state = execute(qft_circ, sim_backend).result().get_counts() plot_histogram(state) def qft(qc,n): for i in range(n): qc.h(n-i-1) # qc.barrier() # display(qc.draw('mpl')) for j in range(n-i-1): qc.cp(np.pi/(2**(n-i-j-1)), n-i-1,j) qc.barrier() for qubit in range(n//2): qc.swap(qubit, n-qubit-1) return qc # display(qc.draw('mpl')) n = 4 qc = QuantumCircuit(n) qc = qft(qc,n) qc.draw('mpl') qc = QuantumCircuit(n) def inverse_qft(qc, n): """Does the inverse QFT on the first n qubits in circuit""" # First we create a QFT circuit of the correct size: qft_circ = qft(QuantumCircuit(n), n) # Then we take the inverse of this circuit invqft_circ = qft_circ.inverse() # And add it to the first n qubits in our existing circuit qc.append(invqft_circ, qc.qubits[:n]) return qc n = 4 qc = QuantumCircuit(n) qc = inverse_qft(qc,n).decompose() qc.draw('mpl') import numpy as np from qiskit.extensions import * from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * import numpy as np import random from scipy.linalg import expm from qiskit.circuit.add_control import add_control n = 10 Id = np.eye(2) theta = 0.15 U = expm(2*1j*np.pi*theta*Id) u = UnitaryGate(U,label='U') u = add_control(operation=u, num_ctrl_qubits=1,ctrl_state=1, label = 'U') print('Expected phase:', theta) def qpe(n, u): qc = QuantumCircuit(n + 1,n) for i in range(n): qc.h(i) qc.x(n) for i in range(n): for j in range(2**i): qc.append(u, [i, n]) qc.draw() #------------------- QFT dag ---------------------- qft_circ = qft(QuantumCircuit(n), n) invqft_circ = qft_circ.inverse() qc.append(invqft_circ, qc.qubits[:n]) qc.measure(range(n),range(n)) return qc qc = qpe(n,u) display(qc.draw('mpl')) shots = 10000 backend = Aer.get_backend('qasm_simulator') result = execute(qc,backend, shots=shots).result().get_counts() states = sorted([[result[i]/shots, i] for i in result], reverse=True) res = [int(i[1],2) for i in states] if len(res) > 1 and states[1][0] > 0.1: print('The phase is between:', res[0]/2**n, res[1]/2**n) else: print('The phase is:', res[0]/2**n) print('Integer number:', res[:2]) plot_histogram(result, figsize = (22,6)) # for i in range(n): # qc.cp()
https://github.com/samuraigab/Quantum-Basic-Algorithms
samuraigab
# !pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org Ipython # pip install -U notebook-as-pdf from IPython.display import display, Latex from IPython.display import Image from qiskit import * from qiskit.visualization import * from qiskit.quantum_info import Statevector import numpy as np import warnings # warnings.filterwarnings("ignore", category=DepriciationWarning) warnings.filterwarnings("ignore", category=UserWarning) qc = QuantumCircuit(3) qc.ry (np.pi/4, 0) # optional, we want to transfer state 1 in this example save = Statevector.from_instruction(qc) qc.draw('mpl') simulator = Aer.get_backend('statevector_simulator') result = execute(qc, backend= simulator, shots = 100000).result().get_statevector() print(f'Amplitudes alpha e beta são: [{np.round(np.cos(np.pi/8)**2,5)} {np.round(np.sin(np.pi/8)**2,5)}]') plot_bloch_multivector(result) alice = QuantumRegister(2, 'a') bob = QuantumRegister(1,'b') cr_alice = ClassicalRegister(2, 'ca') cr_bob = ClassicalRegister(1,'cb') qc = QuantumCircuit(alice,bob,cr_alice, cr_bob) qc.ry(np.pi/4, alice[0]) # optional, we want to transfer state 1 in this example qc.barrier() qc.draw('mpl') qc.h(alice[1]) qc.cx(alice[1],bob[0]) qc.barrier() qc.draw('mpl') qc.cx(alice[0],alice[1]) qc.h(alice[0]) qc.barrier() qc.draw('mpl') qc.measure(alice, cr_alice) qc.barrier() qc.draw('mpl') qc.cx(alice[1], bob[0]) qc.cz(alice[0], bob[0]) # qc.measure(bob, cr_bob) qc.draw('mpl') simulator = Aer.get_backend('statevector_simulator') result = execute(qc, backend= simulator, shots = 10000).result().get_statevector() # plot_histogram(result) states = [format(i,'0'+str(n)+'b')[::-1] for i in range(2**n)] print(states) res = [round(i.real, 5) for i in result] array_to_latex(result) n = 3 states = [format(i,'0'+str(n)+'b')[::-1] for i in range(2**n)] medida = [(j,i) for i,j in zip(res,states) if i > 0] print(f'\n\nAlice mediu {medida[0][0][:2]} o estado que está com Bob é [{medida[0][1]} {medida[1][1]}]\n\n') alice = QuantumRegister(2, 'a') bob = QuantumRegister(1,'b') cr_alice = ClassicalRegister(2, 'ca') cr_bob = ClassicalRegister(1,'cb') qc = QuantumCircuit(alice,bob,cr_alice, cr_bob) qc.ry(np.pi/4, alice[0]) # optional, we want to transfer state 1 in this example qc.barrier() save1 = Statevector.from_instruction(qc) qc.h(alice[1]) qc.cx(alice[1],bob[0]) qc.barrier() qc.cx(alice[0],alice[1]) qc.h(alice[0]) qc.barrier() # qc.measure(alice, cr_alice) qc.barrier() qc.cx(alice[1], bob[0]) qc.cz(alice[0], bob[0]) save2 = Statevector.from_instruction(qc) qc.measure(bob, cr_bob) qc.draw('mpl') plot_bloch_multivector(save1) plot_bloch_multivector(save2) alice = QuantumRegister(2, 'a') bob = QuantumRegister(1,'b') cr_alice = ClassicalRegister(2, 'ca') cr_bob = ClassicalRegister(1,'cb') qc = QuantumCircuit(alice,bob,cr_alice, cr_bob) qc.ry(np.pi/4, alice[0]) # optional, we want to transfer state 1 in this example qc.barrier() qc.h(alice[1]) qc.cx(alice[1],bob[0]) qc.barrier() qc.cx(alice[0],alice[1]) qc.h(alice[0]) qc.barrier() qc.measure(alice, cr_alice) qc.barrier() qc.cx(alice[1], bob[0]) qc.cz(alice[0], bob[0]) qc.measure(bob, cr_bob) qc.draw('mpl') simulator = Aer.get_backend('qasm_simulator') shots = 100000 result = execute(qc, backend=simulator, shots=shots).result().get_counts() from qiskit.visualization import plot_histogram plot_histogram(result) prob0 = 0 prob1 = 0 for i in result.keys(): if i[0] == '0': prob0+= result[i] if i[0] == '1': prob1+= result[i] print(prob0/shots,prob1/shots) print(np.round(np.cos(np.pi/8)**2,5), np.round(np.sin(np.pi/8)**2,5)) np.cos(np.pi/8)**2 simulator = Aer.get_backend('statevector_simulator') result = execute(qc, backend= simulator, shots = 10000).result().get_statevector() # plot_histogram(result) array_to_latex(result, prefix= '\\vert \psi \\rangle = ')
https://github.com/weiT1993/qiskit_helper_functions
weiT1993
""" Teague Tomesh - 2/10/2020 Implementation of an n-bit ripple-carry adder. Based on the specification given in Cuccaro, Draper, Kutin, Moulton. (https://arxiv.org/abs/quant-ph/0410184v1) """ from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister class RCAdder: """ An n-bit ripple-carry adder can be generated using an instance of the RCAdder class by calling the gen_circuit() method. This adder circuit uses 1 ancilla qubit to add together two values a = a_(n-1)...a_0 and b = b_(n-1)...a_0 and store their sum s = s_n...s_0 in the registers which initially held the b value. The adder circuit uses 2 + binary_len(a) + binary_len(b) qubits. The initial carry value is stored in the qubit at index = 0. The binary value of a_i is stored in the qubit at index = 2*i + 2 The binary value of b_i is stored in the qubit at index = 2*i + 1 The high bit, s_n, is stored in the last qubit at index = num_qubits - 1 Attributes ---------- nbits : int size, in bits, of the numbers the adder can handle nq : int number of qubits needed to construct the adder circuit a, b : int optional parameters to specify the numbers the adder should add. Will throw an exception if the length of the bitstring representations of a or b are greater than nbits. use_toffoli : bool Should the toffoli gate be used in the generated circuit or should it first be decomposed barriers : bool should barriers be included in the generated circuit regname : str optional string to name the quantum and classical registers. This allows for the easy concatenation of multiple QuantumCircuits. qr : QuantumRegister Qiskit QuantumRegister holding all of the quantum bits circ : QuantumCircuit Qiskit QuantumCircuit that represents the uccsd circuit """ def __init__( self, nbits=None, a=0, b=0, use_toffoli=False, barriers=False, measure=False, regname=None, ): # number of bits the adder can handle if nbits is None: raise Exception("Number of bits must be specified") else: self.nbits = nbits # given nbits, compute the number of qubits the adder will need # number of qubits = 1 ancilla for the initial carry value # + 2*nbits to hold both a and b # + 1 more qubit to hold the high bit, s_n self.nq = 1 + 2 * nbits + 1 # set flags for circuit generation if len("{0:b}".format(a)) > nbits or len("{0:b}".format(b)) > nbits: raise Exception( "Binary representations of a and b must be less than or equal to nbits" ) self.a = a self.b = b self.use_toffoli = use_toffoli self.barriers = barriers self.measure = measure # create a QuantumCircuit object if regname is None: self.qr = QuantumRegister(self.nq) else: self.qr = QuantumRegister(self.nq, name=regname) self.circ = QuantumCircuit(self.qr) # add ClassicalRegister if measure is True if self.measure: self.cr = ClassicalRegister(self.nq) self.circ.add_register(self.cr) def _initialize_value(self, indices, value): """ Initialize the qubits at indices to the given value Parameters ---------- indices : List[int] List of qubit indices value : int The desired initial value """ binstr = "{0:b}".format(value) for index, val in enumerate(reversed(binstr)): if val == "1": self.circ.x(indices[index]) def _toffoli(self, x, y, z): """ Implement the toffoli gate using 1 and 2 qubit gates """ self.circ.h(z) self.circ.cx(y, z) self.circ.tdg(z) self.circ.cx(x, z) self.circ.t(z) self.circ.cx(y, z) self.circ.t(y) self.circ.tdg(z) self.circ.cx(x, z) self.circ.cx(x, y) self.circ.t(z) self.circ.h(z) self.circ.t(x) self.circ.tdg(y) self.circ.cx(x, y) def _MAJ(self, x, y, z): """ Implement the MAJ (Majority) gate described in Cuccaro, Draper, Kutin, Moulton. """ self.circ.cx(z, y) self.circ.cx(z, x) if self.use_toffoli: self.circ.ccx(x, y, z) else: # use a decomposed version of toffoli self._toffoli(x, y, z) def _UMA(self, x, y, z): """ Implement the UMA (UnMajority and Add) gate described in Cuccaro, Draper, Kutin, Moulton. """ self.circ.x(y) self.circ.cx(x, y) if self.use_toffoli: self.circ.ccx(x, y, z) else: # use a decomposed version of toffoli self._toffoli(x, y, z) self.circ.x(y) self.circ.cx(z, x) self.circ.cx(z, y) def gen_circuit(self): """ Create a circuit implementing the ripple-carry adder Returns ------- QuantumCircuit QuantumCircuit object of size self.nq """ high_bit_index = self.nq - 1 # initialize the a and b registers a_indices = [2 * i + 2 for i in range(self.nbits)] b_indices = [2 * i + 1 for i in range(self.nbits)] for index_list, value in zip([a_indices, b_indices], [self.a, self.b]): self._initialize_value(index_list, value) # compute the carry bits, c_i, in order using the MAJ ladder for a_i in a_indices: self._MAJ(a_i - 2, a_i - 1, a_i) # write the final carry bit value to the high bit register self.circ.cx(a_indices[-1], high_bit_index) # erase the carry bits in reverse order using the UMA ladder for a_i in reversed(a_indices): self._UMA(a_i - 2, a_i - 1, a_i) if self.measure: # measure the circuit self.circ.measure_all() return self.circ if __name__ == "__main__": adder = RCAdder(nbits=6, a=0, b=0, use_toffoli=True, measure=True) circ = adder.gen_circuit() print(circ)
https://github.com/weiT1993/qiskit_helper_functions
weiT1993
from qiskit import QuantumCircuit from QCLG_lvl3.oracles.secret_number_oracle import SecretNUmberOracle class BernsteinVazirani: @classmethod def bernstein_vazirani(cls, random_binary, eval_mode: bool) -> QuantumCircuit: # Construct secret number oracle secret_number_oracle = SecretNUmberOracle.create_secret_number_oracle(random_binary=random_binary, eval_mode=eval_mode) num_of_qubits = secret_number_oracle.num_qubits # Construct circuit according to the length of the number dj_circuit = QuantumCircuit(num_of_qubits, num_of_qubits - 1) dj_circuit_before_oracle = QuantumCircuit(num_of_qubits, num_of_qubits - 1) # Apply H-gates for qubit in range(num_of_qubits - 1): dj_circuit_before_oracle.h(qubit) # Put output qubit in state |-> dj_circuit_before_oracle.x(num_of_qubits - 1) dj_circuit_before_oracle.h(num_of_qubits - 1) dj_circuit += dj_circuit_before_oracle # Add oracle dj_circuit += secret_number_oracle dj_circuit_after_oracle = QuantumCircuit(num_of_qubits, num_of_qubits - 1) # Repeat H-gates for qubit in range(num_of_qubits - 1): dj_circuit_after_oracle.h(qubit) dj_circuit_after_oracle.barrier() # Measure for i in range(num_of_qubits - 1): dj_circuit_after_oracle.measure(i, i) dj_circuit += dj_circuit_after_oracle if not eval_mode: print("Circuit before the oracle\n") print(QuantumCircuit.draw(dj_circuit_before_oracle)) print("Circuit after the oracle\n") print(QuantumCircuit.draw(dj_circuit_after_oracle)) print(dj_circuit) return dj_circuit
https://github.com/weiT1993/qiskit_helper_functions
weiT1993
from qiskit import QuantumCircuit, QuantumRegister import sys import math import numpy as np class Dynamics: """ Class to implement the simulation of quantum dynamics as described in Section 4.7 of Nielsen & Chuang (Quantum computation and quantum information (10th anniv. version), 2010.) A circuit implementing the quantum simulation can be generated for a given problem Hamiltonian parameterized by calling the gen_circuit() method. Attributes ---------- H : ?? The given Hamiltonian whose dynamics we want to simulate barriers : bool should barriers be included in the generated circuit measure : bool should a ClassicalRegister and measurements be added to the circuit regname : str optional string to name the quantum and classical registers. This allows for the easy concatenation of multiple QuantumCircuits. qr : QuantumRegister Qiskit QuantumRegister holding all of the quantum bits circ : QuantumCircuit Qiskit QuantumCircuit that represents the uccsd circuit """ def __init__(self, H, barriers=False, measure=False, regname=None): # Hamiltonian self.H = H # set flags for circuit generation self.barriers = barriers self.nq = self.get_num_qubits() # create a QuantumCircuit object if regname is None: self.qr = QuantumRegister(self.nq) else: self.qr = QuantumRegister(self.nq, name=regname) self.circ = QuantumCircuit(self.qr) # Create and add an ancilla register to the circuit self.ancQ = QuantumRegister(1, "ancQ") self.circ.add_register(self.ancQ) def get_num_qubits(self): """ Given the problem Hamiltonian, return the appropriate number of qubits needed to simulate its dynamics. This number does not include the single ancilla qubit that is added to the circuit. """ numq = 0 for term in self.H: if len(term) > numq: numq = len(term) return numq def compute_to_Z_basis(self, pauli_str): """ Take the given pauli_str of the form ABCD and apply operations to the circuit which will take it from the ABCD basis to the ZZZZ basis Parameters ---------- pauli_str : str string of the form 'p1p2p3...pN' where pK is a Pauli matrix """ for i, pauli in enumerate(pauli_str): if pauli == "X": self.circ.h(self.qr[i]) elif pauli == "Y": self.circ.h(self.qr[i]) self.circ.s(self.qr[i]) def uncompute_to_Z_basis(self, pauli_str): """ Take the given pauli_str of the form ABCD and apply operations to the circuit which will take it from the ZZZZ basis to the ABCD basis Parameters ---------- pauli_str : str string of the form 'p1p2p3...pN' where pK is a Pauli matrix """ for i, pauli in enumerate(pauli_str): if pauli == "X": self.circ.h(self.qr[i]) elif pauli == "Y": self.circ.sdg(self.qr[i]) self.circ.h(self.qr[i]) def apply_phase_shift(self, delta_t): """ Simulate the evolution of exp(-i(dt)Z) """ # apply CNOT ladder -> compute parity for i in range(self.nq): self.circ.cx(self.qr[i], self.ancQ[0]) # apply phase shift to the ancilla # rz applies the unitary: exp(-i*theta*Z/2) self.circ.rz(2 * delta_t, self.ancQ[0]) # apply CNOT ladder -> uncompute parity for i in range(self.nq - 1, -1, -1): self.circ.cx(self.qr[i], self.ancQ[0]) def gen_circuit(self): """ Create a circuit implementing the quantum dynamics simulation Returns ------- QuantumCircuit QuantumCircuit object of size nq with no ClassicalRegister and no measurements """ # generate a naive version of a simulation circuit for term in self.H: self.compute_to_Z_basis(term) if self.barriers: self.circ.barrier() self.apply_phase_shift(1) if self.barriers: self.circ.barrier() self.uncompute_to_Z_basis(term) if self.barriers: self.circ.barrier() # generate a commutation aware version of a simulation circuit # simulate all commuting terms simulataneously by using 1 ancilla per # term that will encode the phase shift based on the parity of the term. return self.circ