repo
stringclasses 900
values | file
stringclasses 754
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/vandnaChaturvedi/Qauntum_algorithms_Qiskit
|
vandnaChaturvedi
|
import numpy as np
import qiskit
from qiskit import QuantumCircuit
import matplotlib.pyplot as plt
from qiskit.circuit import QuantumCircuit, Parameter
import warnings
warnings.filterwarnings('ignore')
theta = Parameter("θ")
phi = Parameter("φ")
lamb = Parameter("λ")
def sampleCircuitA(layer=1, qubits=4):
circuit = QuantumCircuit(qubits)
for i in range(layer):
for i in range(qubits - 1):
circuit.cx(i, i + 1)
circuit.cx(qubits - 1, 0)
for i in range(qubits - 1):
circuit.cx(i, i + 1)
circuit.cx(qubits - 1, 0)
circuit.barrier()
for i in range(qubits):
circuit.u3(theta, phi, lamb, i)
return circuit
circuitA = sampleCircuitA(qubits=4)
circuitA.draw(output='mpl')
def sampleCircuitB1(layer=1, qubits=4):
circuit = QuantumCircuit(qubits)
for i in range(qubits):
circuit.u1(theta, i)
for i in range(layer):
for j in range(qubits - 1):
circuit.cz(j, j + 1)
circuit.cz(qubits - 1, 0)
circuit.barrier()
for j in range(qubits):
circuit.u1(theta, j)
return circuit
def sampleCircuitB2(layer=1, qubits=4):
circuit = QuantumCircuit(qubits)
for i in range(qubits):
circuit.u2(phi, lamb, i)
for i in range(layer):
for j in range(qubits - 1):
circuit.cz(j, j + 1)
circuit.cz(qubits - 1, 0)
circuit.barrier()
for j in range(qubits):
circuit.u2(phi, lamb, j)
return circuit
def sampleCircuitB3(layer=1, qubits=4):
circuit = QuantumCircuit(qubits)
for i in range(qubits):
circuit.u3(theta, phi, lamb, i)
for i in range(layer):
for j in range(qubits - 1):
circuit.cz(j, j + 1)
circuit.cz(qubits - 1, 0)
circuit.barrier()
for j in range(qubits):
circuit.u3(theta, phi, lamb, j)
return circuit
circuitB1 = sampleCircuitB1(qubits=4)
circuitB1.draw(output='mpl')
circuitB2 = sampleCircuitB2(qubits=4)
circuitB2.draw(output='mpl')
circuitB3 = sampleCircuitB3(qubits=4)
circuitB3.draw(output='mpl')
def sampleCircuitC(layer=1, qubits=4):
circuit = QuantumCircuit(qubits)
for i in range(layer):
for j in range(qubits):
circuit.ry(theta, j)
circuit.crx(theta, qubits - 1, 0)
for j in range(qubits - 1, 0, -1):
circuit.crx(theta, j - 1, j)
circuit.barrier()
for j in range(qubits):
circuit.ry(theta, j)
circuit.crx(theta, 3, 2)
circuit.crx(theta, 0, 3)
circuit.crx(theta, 1, 0)
circuit.crx(theta, 2, 1)
return circuit
circuitC = sampleCircuitC(qubits=4)
circuitC.draw(output='mpl')
def sampleCircuitD(layer=1, qubits=4):
circuit = QuantumCircuit(qubits)
for i in range(layer):
for j in range(qubits):
circuit.rx(theta, j)
circuit.rz(theta, j)
for j in range(qubits - 1, -1, -1):
for k in range(qubits - 1, -1, -1):
if j != k:
circuit.crx(theta, j, k)
circuit.barrier()
for j in range(qubits):
circuit.rx(theta, j)
circuit.rz(theta, j)
return circuit
circuitD = sampleCircuitD(qubits=4)
circuitD.draw(output='mpl')
def sampleCircuitE(layer=1, qubits=4):
circuit = QuantumCircuit(qubits)
for i in range(layer):
for j in range(qubits):
circuit.rx(theta, j)
circuit.rz(theta, j)
for j in range(1, qubits, 2):
circuit.crx(theta, j, j - 1)
for j in range(qubits):
circuit.rx(theta, j)
circuit.rz(theta, j)
for j in range(2, qubits, 2):
circuit.crx(theta, j, j - 1)
return circuit
circuitE = sampleCircuitE(qubits=4)
circuitE.draw(output='mpl')
def sampleCircuitF(layer=1, qubits=4):
circuit = QuantumCircuit(qubits)
for i in range(layer):
for j in range(qubits):
circuit.rx(theta, j)
circuit.rz(theta, j)
circuit.crx(theta, qubits - 1, 0)
for j in range(qubits - 1, 0, -1):
circuit.crx(theta, j - 1, j)
return circuit
circuitF = sampleCircuitF(qubits=4)
circuitF.draw(output='mpl')
def sampleEncoding(qubits):
circuit = QuantumCircuit(qubits)
for i in range(qubits):
circuit.h(i)
circuit.ry(theta, i)
return circuit
circuit = sampleEncoding(4)
circuit.draw(output='mpl')
# demo:
circuit = sampleEncoding(5).compose(sampleCircuitB3(layer=2, qubits=5))
circuit.draw(output='mpl')
|
https://github.com/sohamch08/Qiskit-Quantum-Algo
|
sohamch08
|
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, execute
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
# qiskit-ibmq-provider has been deprecated.
# Please see the Migration Guides in https://ibm.biz/provider_migration_guide for more detail.
from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Estimator, Session, Options
# Loading your IBM Quantum account(s)
service = QiskitRuntimeService(channel="ibm_quantum")
backend = Aer.get_backend('qasm_simulator')
# Invoke a primitive. For more details see https://qiskit.org/documentation/partners/qiskit_ibm_runtime/tutorials.html
# result = Sampler("ibmq_qasm_simulator").run(circuits).result()
from qiskit.providers.fake_provider import FakeGuadalupe, FakeKolkata
from qiskit_aer import AerSimulator
from qiskit_aer.noise import NoiseModel
not_gate=QuantumCircuit(1,1) # Create a quantum circuit with 1 qubit and 1 classical bit
not_gate.x(0)
not_gate.measure(0,0)
not_gate.draw(output='mpl')
and_gate=QuantumCircuit(3,1) # Create a quantum circuit with 3 qubits and 1 classical bit
and_gate.ccx(0,1,2)
and_gate.measure(2,0)
and_gate.draw(output='mpl')
or_gate=QuantumCircuit(3,1) # Create a quantum circuit with 3 qubits and 1 classical bit
or_gate.cx(1,2)
or_gate.cx(0,2)
or_gate.ccx(0,1,2)
or_gate.measure(2,0)
or_gate.draw(output='mpl')
xor_gate=QuantumCircuit(3,1) # Create a quantum circuit with 3 qubits and 1 classical bit
xor_gate.cx(0,2)
xor_gate.cx(1,2)
xor_gate.measure(2,0)
xor_gate.draw(output='mpl')
# Write your code here
myxor_gate=QuantumCircuit(3) # Create a quantum circuit with 3 qubits and 1 classical bit
myxor_gate.cx(0,2)
myxor_gate.cx(1,2)
sudokucheck = QuantumCircuit(9)
sudokucheck = sudokucheck.compose(myxor_gate,[0,1,5]) # Check if v_0 = v_1
sudokucheck = sudokucheck.compose(myxor_gate,[2,3,6]) # Check if v_2 = v_3
sudokucheck = sudokucheck.compose(myxor_gate,[0,2,7]) # Check if v_0 = v_2
sudokucheck = sudokucheck.compose(myxor_gate,[1,3,8]) # Check if v_1 = v_3
sudokucheck.mct([5,6,7,8],4) # Take the AND of all the upper results
sudokucheck.draw('mpl')
# Write your code here
oracle = QuantumCircuit(9)
oracle.x(4)
oracle.h(4)
oracle = oracle.compose(sudokucheck, [0,1,2,3,4,5,6,7,8])
oracle.draw('mpl')
# Write your code here
uncompute = QuantumCircuit(9)
uncompute = uncompute.compose(oracle, [0,1,2,3,4,5,6,7,8])
uncompute = uncompute.compose(myxor_gate,[1,3,8])
uncompute = uncompute.compose(myxor_gate,[0,2,7])
uncompute = uncompute.compose(myxor_gate,[2,3,6])
uncompute = uncompute.compose(myxor_gate,[0,1,5])
uncompute.h(4)
uncompute.x(4)
uncompute.draw('mpl')
# Write a code to construct the diffuser operator for the problem
def diffuser_operator(n):
diffuse = QuantumCircuit(n)
controlbit = [] # This will help to list all the control bits for
for i in range(n):
diffuse.h(i) # First layer of hadamard gates
diffuse.x(i) # Layer of X gates
if i>0:
controlbit.append(i)
diffuse.h(0)
diffuse.mcx(control_qubits=controlbit, target_qubit=[0]) # applied C^nX
diffuse.h(0)
for i in range(n):
diffuse.x(i) # The second last layer of X gates
diffuse.h(i) # The last layer of hadamard gates
return diffuse
n = 4
diffuser_circuit = diffuser_operator(4)
diffuser_circuit.draw('mpl')
# Write your code here to put all the pieces together as a single circuit
# pi/4 x sqrt{2^4}=pi/4 which is approximately 3. So we will apply the operator = uncompute + diffuser_operator 3 times
grover_search = QuantumCircuit(9,4)
for i in range(4):
grover_search.h(i)
for i in range(3):
grover_search = grover_search.compose(uncompute, [0,1,2,3,4,5,6,7,8]) # apply the uncompute operator
grover_search = grover_search.compose(diffuser_circuit, [0,1,2,3]) # then apply the diffuser operator
grover_search.measure([0,1,2,3],[0,1,2,3])
grover_search.draw('mpl')
# Write a code to run the final circuit and plot the results to see if there are any satisfying assignments
result = execute(grover_search, backend).result()
counts = result.get_counts(grover_search)
plot_histogram(counts)
# List down the satisfying assignments and verify for yourself if they are correct
# Write your code here
fake_kolkata = FakeKolkata()
fake_guadalupe = FakeGuadalupe()
fake_kolkata_noisemodel = NoiseModel.from_backend(fake_kolkata) # Created a noisemodel from FakeKolkata backend
fake_guadalupe_noisemodel = NoiseModel.from_backend(fake_guadalupe) # Created a noisemodel from FakeGuadalupe backend
# simulate with fakekoklkata backend
simulate_fake_kolkata = AerSimulator(noise_model = fake_kolkata_noisemodel)
fake_kolkata_circ= transpile(grover_search,simulate_fake_kolkata)
fake_kolkata_counts = simulate_fake_kolkata.run(fake_kolkata_circ,shots=1000).result().get_counts()
plot_histogram(fake_kolkata_counts)
# Simulate with fakeguadalupe bakcend
simulate_fake_guadalupe = AerSimulator(noise_model = fake_guadalupe_noisemodel)
fake_guadalupe_circ= transpile(grover_search,simulate_fake_guadalupe)
fake_guadalupe_counts = simulate_fake_guadalupe.run(fake_guadalupe_circ,shots=1000).result().get_counts()
plot_histogram(fake_guadalupe_counts)
# Write your code here
|
https://github.com/sohamch08/Qiskit-Quantum-Algo
|
sohamch08
|
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
import numpy as np
def step_1_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit:
# qr is a quantum register with 2 qubits
# cr is a classical register with 2 bits
qc = QuantumCircuit(qr, cr)
########## your code goes here #######
##1 Initialization
q0, q1 = qr
# apply Hadamard on the auxiliary qubit
qc.h(q0)
# put the system qubit into the |1> state
qc.x(q1)
##2 Apply control-U operator as many times as needed to get the least significant phase bit
# controlled-S is equivalent to CPhase with angle pi / 2
s_angle = np.pi / 2
# we want to apply controlled-S 2^k times
k = 1
# calculate the angle of CPhase corresponding to 2^k applications of controlled-S
cphase_angle = s_angle * 2**k
# apply the controlled phase gate
qc.cp(cphase_angle, q0, q1)
##3 Measure the auxiliary qubit in x-basis into the first classical bit
# apply Hadamard to change to the X basis
qc.h(q0)
# measure the auxiliary qubit into the first classical bit
c0, _ = cr
qc.measure(q0, c0)
return qc
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
qc = QuantumCircuit(qr, cr)
qc = step_1_circuit(qr, cr)
qc.draw("mpl")
# Submit your circuit
from qc_grader.challenges.spring_2023 import grade_ex3a
grade_ex3a(qc)
def step_2_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit:
# qr is a quantum register with 2 qubits
# cr is a classical register with 2 bits
# begin with the circuit from Step 1
qc = step_1_circuit(qr, cr)
########## your code goes here #######
##1 Reset and re-initialize the auxiliary qubit
q0, q1 = qr
# reset the auxiliary qubit
qc.reset(q0)
# apply Hadamard on the auxiiliary qubit
qc.h(q0)
##2 Apply phase correction conditioned on the first classical bit
c0, c1 = cr
with qc.if_test((c0, 1)):
qc.p(-np.pi / 2, q0)
##3 Apply control-U operator as many times as needed to get the next phase bit
# controlled-S is equivalent to CPhase with angle pi / 2
s_angle = np.pi / 2
# we want to apply controlled-S 2^k times
k = 0
# calculate the angle of CPhase corresponding to 2^k applications of controlled-S
cphase_angle = s_angle * 2**k
# apply the controlled phase gate
qc.cp(cphase_angle, q0, q1)
##4 Measure the auxiliary qubit in x-basis into the second classical bit
# apply Hadamard to change to the X basis
qc.h(q0)
# measure the auxiliary qubit into the first classical bit
qc.measure(q0, c1)
return qc
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
qc = QuantumCircuit(qr, cr)
qc = step_2_circuit(qr, cr)
qc.draw("mpl")
# Submit your circuit
from qc_grader.challenges.spring_2023 import grade_ex3b
grade_ex3b(qc)
from qiskit_aer import AerSimulator
sim = AerSimulator()
job = sim.run(qc, shots=1000)
result = job.result()
counts = result.get_counts()
counts
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
import numpy as np
def t_gate_ipe_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit:
# qr is a quantum register with 2 qubits
# cr is a classical register with 3 bits
qc = QuantumCircuit(qr, cr)
########## your code goes here #######
# Initialization
q0, q1 = qr
qc.h(q0)
qc.x(q1)
# Apply control-U operator as many times as needed to get the least significant phase bit
t_angle = np.pi / 4
k = 2
cphase_angle = t_angle * 2**k
qc.cp(cphase_angle, q0, q1)
# Measure the auxiliary qubit in x-basis into the first classical bit
qc.h(q0)
c0, c1, c2 = cr
qc.measure(q0, c0)
# Reset and re-initialize the auxiliary qubit
qc.reset(q0)
qc.h(q0)
# Apply phase correction conditioned on the first classical bit
with qc.if_test((c0, 1)):
qc.p(-np.pi / 2, q0)
# Apply control-U operator as many times as needed to get the next phase bit
k = 1
cphase_angle = t_angle * 2**k
qc.cp(cphase_angle, q0, q1)
# Measure the auxiliary qubit in x-basis into the second classical bit
qc.h(q0)
qc.measure(q0, c1)
# Reset and re-initialize the auxiliary qubit
qc.reset(q0)
qc.h(q0)
# Apply phase correction conditioned on the first and second classical bits
with qc.if_test((c0, 1)):
qc.p(-np.pi / 4, q0)
with qc.if_test((c1, 1)):
qc.p(-np.pi / 2, q0)
# Apply control-U operator as many times as needed to get the next phase bit
k = 0
cphase_angle = t_angle * 2**k
qc.cp(cphase_angle, q0, q1)
# Measure the auxiliary qubit in x-basis into the third classical bit
qc.h(q0)
qc.measure(q0, c2)
return qc
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(3, "c")
qc = QuantumCircuit(qr, cr)
qc = t_gate_ipe_circuit(qr, cr)
qc.draw("mpl")
from qiskit_aer import AerSimulator
sim = AerSimulator()
job = sim.run(qc, shots=1000)
result = job.result()
counts = result.get_counts()
counts
# Submit your circuit
from qc_grader.challenges.spring_2023 import grade_ex3c
grade_ex3c(qc)
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
import numpy as np
def u_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit:
# qr is a quantum register with 2 qubits
# cr is a classical register with 2 bits
qc = QuantumCircuit(qr, cr)
# Initialization
q0, q1 = qr
qc.h(q0)
qc.x(q1)
# Apply control-U operator as many times as needed to get the least significant phase bit
u_angle = 2 * np.pi / 3
k = 1
cphase_angle = u_angle * 2**k
qc.cp(cphase_angle, q0, q1)
# Measure the auxiliary qubit in x-basis into the first classical bit
qc.h(q0)
c0, c1 = cr
qc.measure(q0, c0)
# Reset and re-initialize the auxiliary qubit
qc.reset(q0)
qc.h(q0)
# Apply phase correction conditioned on the first classical bit
with qc.if_test((c0, 1)):
qc.p(-np.pi / 2, q0)
# Apply control-U operator as many times as needed to get the next phase bit
k = 0
cphase_angle = u_angle * 2**k
qc.cp(cphase_angle, q0, q1)
# Measure the auxiliary qubit in x-basis into the second classical bit
qc.h(q0)
qc.measure(q0, c1)
return qc
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
qc = QuantumCircuit(qr, cr)
qc = u_circuit(qr, cr)
qc.draw("mpl")
from qiskit_aer import AerSimulator
sim = AerSimulator()
job = sim.run(qc, shots=1000)
result = job.result()
counts = result.get_counts()
print(counts)
success_probability = counts["01"] / counts.shots()
print(f"Success probability: {success_probability}")
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
import numpy as np
def u_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit:
# qr is a quantum register with 2 qubits
# cr is a classical register with 1 bits
qc = QuantumCircuit(qr, cr)
# Initialization
q0, q1 = qr
qc.h(q0)
qc.x(q1)
# Apply control-U operator as many times as needed to get the least significant phase bit
u_angle = 2 * np.pi / 3
k = 1
cphase_angle = u_angle * 2**k
qc.cp(cphase_angle, q0, q1)
# Measure the auxiliary qubit in x-basis
qc.h(q0)
(c0,) = cr
qc.measure(q0, c0)
return qc
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
qc = QuantumCircuit(qr, cr)
qc = u_circuit(qr, cr)
qc.draw("mpl")
job = sim.run(qc, shots=15)
result = job.result()
counts = result.get_counts()
print(counts)
step1_bit = 1
####### your code goes here #######
print(step1_bit)
# Submit your result
from qc_grader.challenges.spring_2023 import grade_ex3d
grade_ex3d(step1_bit)
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
import numpy as np
def u_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit:
# qr is a quantum register with 2 qubits
# cr is a classical register with 2 bits
qc = QuantumCircuit(qr, cr)
########## your code goes here #######
# Initialization
q0, q1 = qr
if step1_bit:
qc.x(q0)
qc.x(q1)
# Measure the auxiliary qubit
c0, c1 = cr
qc.measure(q0, c0)
# Reset and re-initialize the auxiliary qubit
qc.reset(q0)
qc.h(q0)
# Apply phase correction conditioned on the first classical bit
with qc.if_test((c0, 1)):
qc.p(-np.pi / 2, q0)
# Apply control-U operator as many times as needed to get the next phase bit
u_angle = 2 * np.pi / 3
k = 0
cphase_angle = u_angle * 2**k
qc.cp(cphase_angle, q0, q1)
# Measure the auxiliary qubit in x-basis into the second classical bit
qc.h(q0)
qc.measure(q0, c1)
return qc
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
qc = QuantumCircuit(qr, cr)
qc = u_circuit(qr, cr)
qc.draw("mpl")
# Submit your result
from qc_grader.challenges.spring_2023 import grade_ex3e
grade_ex3e(qc)
from qiskit_aer import AerSimulator
sim = AerSimulator()
job = sim.run(qc, shots=1000)
result = job.result()
counts = result.get_counts()
print(counts)
success_probability = counts["01"] / counts.shots()
print(f"Success probability: {success_probability}")
from qiskit_ibm_provider import IBMProvider
provider = IBMProvider()
hub = "qc-spring-23-1"
group = "group-1"
project = "recIvcxUcc27LvvSh"
backend_name = "ibm_peekskill"
backend = provider.get_backend(backend_name, instance=f"{hub}/{group}/{project}")
from qiskit import transpile
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
qc = QuantumCircuit(qr, cr)
qc = step_2_circuit(qr, cr)
qc_transpiled = transpile(qc, backend)
job = backend.run(qc_transpiled, shots=1000, dynamic=True)
job_id = job.job_id()
print(job_id)
retrieve_job = provider.retrieve_job(job_id)
retrieve_job.status()
from qiskit.tools.visualization import plot_histogram
counts = retrieve_job.result().get_counts()
plot_histogram(counts)
|
https://github.com/sohamch08/Qiskit-Quantum-Algo
|
sohamch08
|
# Import all the necessary libraries numpy, math, random, time
import numpy as np
import math
import random
import time
seed = np.random.seed(0)
"""
Define parameters
n - Problem size in terms of input variables. Change it as per the problem size
theta,delta,m1,m2 - Parameters defined in the algorithm
"""
n = 3
theta = 0.5 # Theta and delta parameters, feel free to change
delta = 0.1
# Expression for m1 and m2
m1 = int((1/theta**2)*math.log2(n/(delta*theta**2)))
m2 = int((1/theta**4)*math.log2(n*m1/(delta*theta**2)))
"""
Values of m1 and m2 are usually restricted to be m1<=100 and m2 ,= 5/(theta**2)
"""
if(m1>=100):
m1 = 100
m2_max = math.ceil(5/(theta**2))
if(m2>=m2_max):
m2 = m2_max
print(m1,m2)
def f_val(x):
f = [1,1,1,-1,1,1,1,-1]
return f[x]
"""
-Function to generate a random binary string of size l bits
"""
def generate_binary_string(l):
bin_string = []
for i in range(l):
bin_string.append(random.randint(0,1))
return bin_string
def bin_to_dec(b):
n = 0
for i in range(len(b)):
n = n + (2**(i))*(b[i])
return n
def exponent(a,b):
if a == 0:
return 1
elif a == 1:
return b
elif a % 2 == 0:
n = exponent(a//2 , b)
return n*n
else:
n = exponent(a//2, b)
return (n*n)*b
def dot(a,b):
length = len(a)
norm = 0
for i in range(length):
norm = norm + a[i]*b[i]
return norm
"""
- SUBROUTINE Approx(alpha,k)
- Returns an estimate of the significance of the fourier coefficient whose prefix is alpha, where length of alpha is k.
"""
def approx(alpha, k):
"""
- Special case: k==n; # for k==n case, there is no list of x_i s
- Generate yij_list. This has two cases, 2**(k)<=m2 and 2**(k)>m2. We chose the length of yij to be min of either.
- Compute A_i by iterating of yij and beta_alpha (Recall that there is only one i in this case)
"""
min1 = min(m1, exponent(n-k,2))
min2 = min(m2, exponent(k,2))
if(k==n):
## Write your code here for the case when k==n
yi = []
for j in range(min2):
yij = generate_binary_string(n)
yi.append(yij)
A_i = 0
for j in range(min2):
# value of sum f(yij) xhi_alpha(yij)
A_i = (f_val(bin_to_dec(yi[j])))*((-1)**(dot(alpha, yi[j]))) + A_i
A_i = A_i/min2 # approximated value of f_alpha(xi)
return [A_i**2, A_i] # keeps track of the expected fourier coefficient when n==k
else:
"""
1. Generate xi_list. This has two cases, 2**(n-k)<=m1 and 2**(n-k)>m1. We chose the length of xi to be min of either.
2. Generate yij_list. This has two cases, 2**(k)<=m2 and 2**(k)>m2. We chose the length of yij to be min of either.
3. Iterate over x_i and y_ij and compute A_i and finally beta_alpha
"""
# Part-1: Write a code to Generate random Xi string
beta_alpha = 0
A = []
for i in range(min1):
xi = generate_binary_string(n-k)
yi = []
# -----------------------------------------------------------------------
# Part -2 : Write a code to Generate random Yi string
for j in range(min2):
yij = generate_binary_string(k)
yi.append(yij)
#------------------------------------------------------------
# Part 3: Iterate over xi and yj and compute Ai and beta_alpha
A_i = 0
for j in range(min2):
# value of sum f(yij xi) xhi_alpha(yij)
A_i = (f_val(bin_to_dec(xi+yi[j])))*((-1)**(dot(alpha, yi[j]))) + A_i
A_i = A_i/min2 # value of f_alpha(xi)
A.append(A_i)
for i in range(min1):
beta_alpha = beta_alpha + (A[i]**2)
beta_alpha = beta_alpha/min1
return [beta_alpha, beta_alpha] # keeps track of the expected fourier coefficient
"""
SUBROUTINE Coef(alpha,k)
Input: alpha value, k - Size of alpha
Output: Set of binary strings corresponding to the monomials with largest fourier coefficients
This function is called recursively call till k==n by extending the prefix with both '0' and '1'
and pruned as needed (refer to the algorithm).
"""
def Coef(alpha,k, list):
# Compute B_alpha for each value of alpha and keep those alpha values for which B_alpha> threshold
# Write your code here
B_alpha_list = approx(alpha, k)
if B_alpha_list[0] >= (theta**2)/2:
if k == n:
list.append([alpha, B_alpha_list[1]])
else:
Coef(alpha+[0], k+1, list)
Coef(alpha+[1], k+1, list)
if __name__ == '__main__':
k=1
alpha = [0]
coephs = []
Coef([], 0, coephs) # starting with 0 then we will recurse on adding new bits
print(coephs)
# Using the alpha values and the corresponding fourier estimates, create the fourier expansion of the majority function
# You can output the expression as a string and print below
def bin_to_coefficient(lst):
strg = ""
flag = True
for i in range(len(lst)):
if lst[i] == 1:
strg = strg + "x_" + str(len(lst)-i)
flag = False
if flag:
strg = strg + '1'
return strg
return strg
to_print = []
for coefficient in coephs:
if coefficient[1] < 0:
to_print.append('(')
to_print.append(str(coefficient[1]))
to_print.append(')')
else:
to_print.append(str(coefficient[1]))
to_print.append('*')
to_print.append(bin_to_coefficient(coefficient[0]))
to_print.append(' + ')
for item in to_print[:-1]:
print(item, end="")
"""
Ex. 5: Generate a random function f
"""
n = 5
N = 2**n
f = []
for i in range(N):
f.append((-1)**np.random.randint(0,2))
#print(f)
#for i in range(len(f)):
# f[i] = (-1)**np.random.randint(0,2)
print(f)
def f_val(a_int):
a = a_int % N
return f[a]
# Generate a random function. One example is shown below
#f = (x32 © x8 © x34 © x13) AND (x33 © x20 © x9 © x1 © x15 © x39) OR (x24 © x10 © x27 © x6 © x34)
# f = f1 and f2 or f3
n = 40
# Hardcode the f1,f2,f3 lists as
f1_list = [32,8,34,13]
f2_list = [33,20,9,1,15,39]
f3_list = [24,10,27,6,34]
f_list = set(f1_list + f2_list + f3_list )
# OR Generate f1_list, f2_list, f3_list randomly as below
f1_l1 = 7
f2_l2 = 5
f3_l3 = 8
f4_l4 = 4
f1_list,f2_list,f3_list,f4_list = [],[],[],[]
f = []
i=0
while(i<f1_l1):
r=random.randint(1,n)
if r not in f1_list:
f1_list.append(r)
i = i+1
else:
pass
# Write similar code for f2_l2, f3_l3, f4_l4
f_list = set(f1_list + f2_list + f3_list + f4_list)
print(f' f1_list data is {f1_list}')
print(f' f2_list data is {f2_list}')
print(f' f3_list data is {f3_list}')
print(f' f4_list data is {f4_list}')
print(f' f_list data is {f_list}')
def count(f_bits):
f_ = f_bits.count(1)
if (f_%2==0):
return 0
else:
return 1
def f_val(a_int):
a = bin(a_int)[2:].zfill(n)
f1_bits = []
f2_bits = []
f3_bits = []
f4_bits = []
for i in f1_list:
f1_bits.append(int(a[n-i]))
for i in f2_list:
f2_bits.append(int(a[n-i]))
for i in f3_list:
f3_bits.append(int(a[n-i]))
for i in f4_list:
f4_bits.append(int(a[n-i]))
#print(f1_bits)
#print(f2_bits)
#print(f3_bits)
#print(f4_bits)
f1 = count(f1_bits)
f2 = count(f2_bits)
f3 = count(f3_bits)
f4 = count(f4_bits)
f = f1 and f2 or f3
return (-1)**f
# Write a code to compute fourier coefficients and final alpha values as explained
# Verify your end result for following 3 points by compairing it with elements present in the original function
# 1. Check for Elements correctly retrieved
# 2. Elements retrieved but not present in the original function
# 3. Elements present in the original function but not retrieved
# Write your code here
# Compare total execution times of both and accuracy of the KM
"""
Ex.3 (4 variables), Ex. Ref. 1 sec. 2.3.1 page no 8
f(x1,x2,x3,x4) = x1 AND x3 (x1 is lsb and x4 is msb, x=x4, y=x3, z=x2, w=x1)
f = [1,1,1,1,1,-1,1,-1,1,1,1,1,1,-1,1,-1]
"""
def f_val(a_int):
a = bin(a_int)[2:].zfill(n)
f = int(a[1]) and int(a[3])
return (-1)**f
"""
Ex. 4 (40 variables), Ref. 1, sec. 3.1 page no 15
f = (x32 © x8 © x34 © x13) AND (x33 © x20 © x9 © x1 © x15 © x39) OR (x24 © x10 © x27 © x6 © x34)
"""
def f_val(a_int):
a = bin(a_int)[2:].zfill(n)
f1 = int(a[40-32])^int(a[40-8])^int(a[40-34])^int(a[40-13])
f2 = int(a[40-33])^int(a[40-20])^int(a[40-9])^int(a[40-39])
f3 = int(a[40-24])^int(a[40-10])^int(a[40-27])^int(a[40-34])
f = f1 and f2 or f3
return (-1)**f
|
https://github.com/benkoehlL/Qiskit_Playground
|
benkoehlL
|
'''
This program stores the API token of IBM Quantum (can be found in the
account settings) for later use in a qiskitrc-file, loads your IBMQ account
and it lists all the versions of your qiskit installation.
'''
import qiskit
from qiskit import IBMQ
IBMQ.save_account('***********')
IBMQ.load_account
print(qiskit.__qiskit_version__)
|
https://github.com/benkoehlL/Qiskit_Playground
|
benkoehlL
|
'''
This program sets up the Half Adder and the Full Adder and creates a .tex file
with the gate geometry. It also evaluates the result with a qasm quantum
simulator
'''
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, \
execute, result, Aer
import os
import shutil
import numpy as np
import lib.adder as adder
import lib.quantum_logic as logic
LaTex_folder_Adder_gates = str(os.getcwd())+'/Latex_quantum_gates/Adder-gates/'
if not os.path.exists(LaTex_folder_Adder_gates):
os.makedirs(LaTex_folder_Adder_gates)
else:
shutil.rmtree(LaTex_folder_Adder_gates)
os.makedirs(LaTex_folder_Adder_gates)
qubit_space = ['0','1']
## Half Adder (my version)
print("Test Half Adder (my version",'\n')
for add0 in qubit_space: # loop over all possible additions
for add1 in qubit_space:
q = QuantumRegister(3, name = 'q')
c = ClassicalRegister(2, name = 'c')
qc = QuantumCircuit(q,c)
for qubit in q:
qc.reset(qubit)
# initialisation
if(add0== '1'):
qc.x(q[0])
if(add1 == '1'):
qc.x(q[1])
adder.Half_Adder(qc, q[0],q[1],q[2])
qc.measure(q[0], c[0])
qc.measure(q[2], c[1])
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend, shots=1000)
results = job.result()
count = results.get_counts()
print('|0', add0, '>', '+', '|0', add1, '>', '\t', count)
## Plot a sketch of the gate
q = QuantumRegister(3, name = 'q')
c = ClassicalRegister(2, name = 'c')
qc = QuantumCircuit(q,c)
qc.reset(q[2])
adder.Half_Adder(qc, q[0],q[1],q[2])
qc.measure(q[1], c[0])
qc.measure(q[2], c[1])
LaTex_code = qc.draw(output='latex_source',
justify=None) # draw the circuit
f_name = 'Half_Adder_gate_Benjamin.tex'
with open(LaTex_folder_Adder_gates+f_name, 'w') as f:
f.write(LaTex_code)
## Half Adder for two qubits (Beyond Classical book version)
print("Test Half Adder Beyond Classical")
for add0 in qubit_space: # loop over all possible additions
for add1 in qubit_space:
q = QuantumRegister(5, name = 'q')
c = ClassicalRegister(2, name = 'c')
qc = QuantumCircuit(q,c)
# initialisation
if(add0 == '1'):
qc.x(q[0])
if(add1 == '1'):
qc.x(q[1])
logic.XOR(qc, q[0],q[1],q[2])
qc.barrier(q)
logic.AND(qc, q[0], q[1], q[3])
qc.barrier(q)
qc.measure(q[2], c[0])
qc.measure(q[3], c[1])
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend, shots=1000)
results = job.result()
count = results.get_counts()
print('|0', add0, '>', '+', '|0', add1, '>', '\t', count)
if(add0=='0' and add1=='1'):
LaTex_code = qc.draw(output='latex_source', justify=None) # draw the circuit
f_name = 'Half_Adder_gate_Beyond_Classical.tex'
with open(LaTex_folder_Adder_gates+f_name, 'w') as f:
f.write(LaTex_code)
## Full Adder for addition of two-qubits |q1>, |q2>, and a carry bit |qd>
# from another calculation using a anxiliary bit |q0> with a carry qubit |cq>
# which is initialised to |0>
# iteration over all possible values for |q1>, |q2>, and |qd>
print('\n',"Full Adder Test (my version)")
for qubit_2 in qubit_space:
for qubit_1 in qubit_space:
for qubit_d in qubit_space:
string_q1 = str(qubit_1)
string_q2 = str(qubit_2)
string_qd = str(qubit_d)
q1 = QuantumRegister(1, name ='q1')
q2 = QuantumRegister(1, name = 'q2')
qd = QuantumRegister(1, name = 'qd')
q0 = QuantumRegister(1, name = 'q0')
c = ClassicalRegister(2, name = 'c')
qc = QuantumCircuit(q1,q2,qd,q0,c)
for qubit in q1:
qc.reset(qubit)
for qubit in q2:
qc.reset(qubit)
for qubit in qd:
qc.reset(qubit)
for qubit in q0:
qc.reset(qubit)
# initialise qubits which should be added
for i, qubit in enumerate(q1):
if(string_q1[i] == '1'):
qc.x(qubit)
print(1,end="")
else:
print(0,end="")
print('\t',end="")
for i, qubit in enumerate(q2):
if(string_q2[i] == '1'):
qc.x(qubit)
print(1,end="")
else:
print(0,end="")
print('\t',end="")
for i, qubit in enumerate(qd):
if(string_qd[i] == '1'):
qc.x(qubit)
print(1,end="")
else:
print(0,end="")
print('\t',end="")
adder.Full_Adder(qc, q1, q2, qd, q0, c[0])
qc.measure(q0, c[1])
# check the results
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend, shots=1000)
results = job.result()
count = results.get_counts()
print('|', qubit_1, '>', '+', '|', qubit_2, '>', '+', '|', qubit_d, '> = ' , '\t', count)
if(qubit_1 == '0' and qubit_2 == '0' and qubit_d == '0'):
LaTex_code = qc.draw(output='latex_source') # draw the circuit
f_name = 'Full_Adder_gate_Benjamin.tex'
with open(LaTex_folder_Adder_gates+f_name, 'w') as f:
f.write(LaTex_code)
## Test for adding two two-qubit numbers |q1> and |q2>
for qubit1_0 in qubit_space:
for qubit1_1 in qubit_space:
for qubit2_0 in qubit_space:
for qubit2_1 in qubit_space:
string_q1 = str(qubit1_1)+str(qubit1_0)
string_q2 = str(qubit2_1)+str(qubit2_0)
q1 = QuantumRegister(2, name ='q1')
q2 = QuantumRegister(2, name = 'q2')
# qubit to store carry over for significiant bit
q0 = QuantumRegister(1, name = 'q0')
c = ClassicalRegister(3, name = 'c')
qc = QuantumCircuit(q1,q2,q0,c)
for qubit in q1:
qc.reset(qubit)
qc.reset(q2)
qc.reset(q0)
# initialise qubits which should be added
for i, qubit in enumerate(q1):
if(string_q1[i] == '1'):
qc.x(qubit)
print(1,end="")
else:
print(0,end="")
print('\t',end="")
for i, qubit in enumerate(q2):
if(string_q2[i] == '1'):
qc.x(qubit)
print(1,end="")
else:
print(0,end="")
print('\t',end="")
adder.Half_Adder(qc,q1[-1],q2[-1],q0)
qc.measure(q2[-1],c[0])
adder.Full_Adder(qc, q1[-2],q2[-2], q0, q2[-1], c[1])
qc.measure(q2[-1], c[2])
# check the results
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend, shots=1000)
results = job.result()
count = results.get_counts()
print('|', qubit1_1, qubit1_0, '>', '+', '|', qubit2_1,
qubit2_0, '> = ' , '\t', count)
if(qubit1_1 == '0' and qubit1_0 == '1'
and qubit2_1 == '0' and qubit2_0 == '0'):
LaTex_code = qc.draw(output='latex_source') # draw the circuit
# export QASM code
qc.qasm(filename="one_plus_one.qasm")
f_name = 'Adder_gate_for_two_two-qubit_numbers.tex'
with open(LaTex_folder_Adder_gates+f_name, 'w') as f:
f.write(LaTex_code)
## Adder for two arbitrary binary numbers
# randomly draw number of bits from the numbers to add
bit_number_q1 = int(np.ceil(10*np.random.rand()))+2
bit_number_q2 = int(np.ceil(10*np.random.rand()))+2
# prepare two random binary numbers
string_q1 = []
string_q2 = []
for i in range(bit_number_q1):
#string_q1.append(1)
string_q1.append(int(np.round(np.random.rand())))
for i in range(bit_number_q2):
string_q2.append(int(np.round(np.random.rand())))
while(len(string_q1)<len(string_q2)):
string_q1 = np.insert(string_q1, 0, 0, axis=0)
while(len(string_q1)>len(string_q2)):
string_q2 = np.insert(string_q2, 0, 1, axis=0)
string_q1 = np.array(string_q1)
string_q2 = np.array(string_q2)
q1 = QuantumRegister(len(string_q1), name = 'q1')
q2 = QuantumRegister(len(string_q2), name = 'q2')
# qubit to store carry over for initial half adder
q0 = QuantumRegister(1, name = 'q0')
c = ClassicalRegister(len(string_q1)+1, name = 'c')
qc = QuantumCircuit(q1,q2,q0,c)
for qubit in q1:
qc.reset(qubit)
for qubit in q2:
qc.reset(qubit)
qc.reset(q0)
# initialise qubits which should be added
for i, qubit in enumerate(q1):
if(string_q1[i] == 1):
qc.x(qubit)
print(1,end="")
else:
print(0,end="")
print('\n',end="")
for i, qubit in enumerate(q2):
if(string_q2[i] == 1):
qc.x(qubit)
print(1,end="")
else:
print(0,end="")
print('\n')
# initial addition of least significant bits and determining carry bit
adder.Half_Adder(qc, q1[-1], q2[-1], q0)
qc.measure(q2[-1], c[0])
# adding of next significant bits
adder.Full_Adder(qc, q1[-2], q2[-2], q0, q2[-1], c[1])
# adding of other digits by full adder cascade
for i in range(2, len(string_q1)):
adder.Full_Adder(qc,
q1[-i-1], # bit to add
q2[-i-1], # bit to add
#(and to measure as next significant bit)
q2[-i+1], # carry from last calculation
q2[-i], # carry for next calculation
c[i])
qc.measure(q2[-len(string_q1)+1], c[len(string_q1)])
# check the results
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend, shots=10)
results = job.result()
count = results.get_counts()
print(count)
LaTex_code = qc.draw(output='latex_source') # draw the circuit
f_name = 'Adder_gate_for_'+str(string_q1)+'_and_'+str(string_q2)+'.tex'
print(f_name)
with open(LaTex_folder_Adder_gates+f_name, 'w') as f:
f.write(LaTex_code)
|
https://github.com/benkoehlL/Qiskit_Playground
|
benkoehlL
|
import numpy as np
from qiskit import *
from qiskit.visualization import plot_histogram
from matplotlib.pyplot import plot, draw, show
def SendState(qc1, qc2, qc1_name):
'''
This function takes the output of circuit qc1
(made up of only H and X gates)
and initialises another circuit qc2 with the same state
'''
qs = qc1.qasm().split(sep=';')[4:-1]
# process the code to get the instructions
for i, instruction in enumerate(qs):
qs[i] = instruction.lstrip()
# parse the instructions and apply to new circuit
for instruction in qs:
instruction_gate = instruction[0]
instruction_qubit_list = []
i = 0
while instruction[i] != '[':
i += 1
i += 1
while instruction[i] != ']':
instruction_qubit_list.append(instruction[i])
i += 1
instruction_qubit = 0
for i, dec in enumerate(reversed(instruction_qubit_list)):
instruction_qubit += int(dec)*10**i
if(instruction_gate == 'x'):
old_qr = int(instruction_qubit)
qc2.x(qr[old_qr])
elif instruction_gate == 'h':
old_qr = int(instruction_qubit)
qc2.h(qr[old_qr])
elif instruction_gate == 'm':
# exclude measuring
pass
else:
raise Exception('Unable to parse instruction')
# declare classical and quantum register
n = 16 # for local backend 'n' can go up to 23,
#after which a memery error is raised
qr = QuantumRegister(n, name='q')
cr = ClassicalRegister(n, name='c')
# create Alice's circuit
alice = QuantumCircuit(qr, cr, name='Alice')
# generate a random number expressible by the available qubits
alice_key = np.random.randint(0,high=2**n)
# cast key to binary representation
alice_key = np.binary_repr(alice_key,n)
# encode key as alice qubits
for i, digit in enumerate(alice_key):
if(digit == '1'):
alice.x(qr[i])
# switch randomly about half qubits to Hadamard basis
alice_table = []
for qubit in qr:
if(np.random.rand()>0.5):
alice.h(qubit)
alice_table.append('H') # indicate the Hadamard-basis
else:
alice_table.append('Z') # indicate the Z-basis
# create Bob's circuit
bob = QuantumCircuit(qr, cr, name='Bob')
SendState(alice,bob, 'Alice')
# Bob does not know which basis to use
bob_table = []
for qubit in qr:
if(np.random.rand()>0.5):
bob.h(qubit)
bob_table.append('H') # indicate the Hadamard-basis
else:
bob_table.append('Z') # indicate the Z-basis
# measure all qubits
for i, qubit in enumerate(qr):
bob.measure(qubit, cr[i])
backend = BasicAer.get_backend('qasm_simulator')
# Bob has only one chance of measuring correctly
result = execute(bob, backend=backend, shots=1).result()
#plot_histogram(result.get_counts(bob))
#draw()
#show(block=True)
# result of the measurement is Bob's key candidate
bob_key = list(result.get_counts(bob))[0]
# key is reversed so that first qubit is the first element of the list
bob_key = bob_key[::-1]
# compare basis and discard qubits not measured in the same basis
keep = []
discard = []
print('\n', "Compare Bob's and Alice's basis (without eavesdropping): ")
for qubit, basis in enumerate(zip(alice_table,bob_table)):
if(basis[0] == basis[1]):
print("Same choice for qubit: {}, basis: {}".format(qubit, basis[0]))
keep.append(qubit)
else:
print("Different choice for qubit: {}, Alice has {}, Bob has {}".format(qubit, basis[0], basis[1]))
discard.append(qubit)
# measure the percentage of qubits to be discarded
acc = 0
for bit in zip(alice_key, bob_key):
if(bit[0]==bit[1]):
acc += 1
print('\n Percentage of qubits to be discarded according to table comparison: ',
len(keep)/n)
print('Measurement convergence by additional chance: ', acc/n)
new_alice_key = [alice_key[qubit] for qubit in keep]
new_bob_key = [bob_key[qubit] for qubit in keep]
acc = 0
for bit in zip(new_alice_key, new_bob_key):
if(bit[0] == bit[1]):
acc += 1
print('Percentage of similarity between the keys: ', acc/len(new_alice_key))
if(acc//len(new_alice_key) == 1):
print('Key exchange has been succesfull')
print("New Alice's key: ", new_alice_key)
print("New Bob's key: ", new_bob_key)
else:
print('Key exchange has been tampered! ---> Check for eavesdropper or try again')
print("New Alice's key is invalid: ", new_alice_key)
print("New Bob's key is invalid: ", new_bob_key)
# let's intrude a eavesdropper Eve (which is initialised to Alice's state)
eve = QuantumCircuit(qr, cr, name='Eve')
SendState(alice, eve, 'Alice')
eve_table = []
for qubit in qr:
if(np.random.rand()>0.5):
eve.h(qubit)
eve_table.append('H')
else:
eve_table.append('Z')
for i, qubit in enumerate(qr):
eve.measure(qubit,cr[i])
# Execute (build and run) the quantum circuit
backend = BasicAer.get_backend('qasm_simulator')
result = execute(eve, backend=backend, shots=1).result()
# Result of the measurement is Eve's key
eve_key = list(result.get_counts(eve))[0]
eve_key = eve_key[::-1]
# Update states to new eigenstates (of wrongly chosen basis)
print('\n', "Compare Eve's and Alice's basis: ")
for i, basis in enumerate(zip(alice_table,eve_table)):
if(basis[0] == basis[1]):
print("Same choice for qubit: {}, basis: {}".format(qubit, basis[0]))
keep.append(i)
else:
print("Different choice for qubit: {}, Alice has {}, Eve has {}".format(qubit, basis[0], basis[1]))
discard.append(i)
if eve_key[i] == alice_key[i]:
eve.h(qr[i])
else:
if (basis[0] == 'H' and basis[1] == 'Z'):
alice.h(qr[i])
eve.x(qr[i])
else:
eve.x(qr[i])
eve.h(qr[i])
# Eve's state is now sent to Bob
SendState(eve, bob, 'Eve')
bob_table = []
for qubit in qr:
if(np.random.rand()>0.5):
bob.h(qubit)
bob_table.append('H')
else:
bob_table.append('Z')
for i, qubit in enumerate(qr):
bob.measure(qubit, cr[i])
result = execute(bob, backend, shots=1).result()
#plot_histogram(result.get_counts(bob))
#draw()
#show(block=True)
bob_key = list(result.get_counts(bob))[0]
bob_key = bob_key[::-1]
# Now Alice and Bob will share their table data and perform checking operations
keep = []
discard = []
print('\n', "Compare Bob's and Alice's basis (with eavesdropping by Eve): ")
for qubit, basis in enumerate(zip(alice_table, bob_table)):
if(basis[0] == basis[1]):
print("Same choice for qubit: {}, basis: {}".format(qubit, basis[0]))
keep.append(qubit)
else:
print("Different choice for qubit: {}, Alice has {}, Bob has {}".format(qubit, basis[0], basis[1]))
discard.append(qubit)
# measure the percentage of qubits to be discarded
acc = 0
for bit in zip(alice_key, bob_key):
if(bit[0]==bit[1]):
acc += 1
print('Percentage of qubits to be discarded according to table comparison: ',
len(keep)/n)
print('Measurement convergence by additional chance: ', acc/n)
new_alice_key = [alice_key[qubit] for qubit in keep]
new_bob_key = [bob_key[qubit] for qubit in keep]
acc = 0
for bit in zip(new_alice_key, new_bob_key):
if(bit[0] == bit[1]):
acc += 1
print('\n Percentage of similarity between the keys: ', acc/len(new_alice_key))
if(acc//len(new_alice_key) == 1):
print('Key exchange has been succesfull')
print("New Alice's key: ", new_alice_key)
print("New Bob's key: ", new_bob_key)
else:
print('Key exchange has been tampered! --->',
'Check for eavesdropper or try again')
print("New Alice's key is invalid: ", new_alice_key)
print("New Bob's key is invalid: ", new_bob_key)
|
https://github.com/benkoehlL/Qiskit_Playground
|
benkoehlL
|
'''
This code creates the gates for all four Bell states
and prints the LaTex code for the circuit
'''
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
import os
import shutil
use_classical_register = True
LaTex_folder_Bell_states = str(os.getcwd())+'/Latex_quantum_gates/Bell_measurement/'
if not os.path.exists(LaTex_folder_Bell_states):
os.makedirs(LaTex_folder_Bell_states)
else:
shutil.rmtree(LaTex_folder_Bell_states)
os.makedirs(LaTex_folder_Bell_states)
qr = QuantumRegister(2) # initialise a two-bit quantum register
cr = ClassicalRegister(2) # initialise a two-bit classical register
if(not use_classical_register):
circuit = QuantumCircuit(qr) # put only quantum registers into circuit
else:
circuit = QuantumCircuit(qr, cr) # put classical and quantum registers into circuit
circuit.cx(qr[0],qr[1]) # at a CNOT gate to the second qubit depending on the state of the first one
circuit.h(qr[0]) # add a Hadamard gate to first qubit
if(use_classical_register):
circuit.measure(qr,cr) # measure the quantum bits
LaTex_code = circuit.draw(output='latex_source', initial_state=True, justify=None) # draw the circuit
f_name = 'Bell_state_measurement.tex'
with open(LaTex_folder_Bell_states+f_name, 'w') as f:
f.write(LaTex_code)
|
https://github.com/benkoehlL/Qiskit_Playground
|
benkoehlL
|
'''
This code creates the gates for all four Bell states
and prints the LaTex code for the circuit
'''
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
import os
import shutil
use_classical_register = False
LaTex_folder_Bell_states = str(os.getcwd())+'/Latex_quantum_gates/Bell_states/'
if not os.path.exists(LaTex_folder_Bell_states):
os.makedirs(LaTex_folder_Bell_states)
else:
shutil.rmtree(LaTex_folder_Bell_states)
os.makedirs(LaTex_folder_Bell_states)
for not0 in [False,True]:
for not1 in [False,True]:
qr = QuantumRegister(2,name='q') # initialise a two-bit quantum register
cr = ClassicalRegister(2, name='c') # initialise a two-bit classical register
if(not use_classical_register):
circuit = QuantumCircuit(qr) # put only quantum registers into circuit
else:
circuit = QuantumCircuit(qr, cr) # put classical and quantum registers into circuit
if(not0):
circuit.x(qr[0])
if(not1):
circuit.x(qr[1])
circuit.h(qr[0]) # add a Hadamard gate to first qubit
circuit.cx(qr[0],qr[1]) # at a CNOT gate to the second qubit depending on the state of the first one
if(use_classical_register):
circuit.measure(qr,cr) # measure the quantum bits
LaTex_code = circuit.draw(output='latex_source', initial_state=True, justify=None) # draw the circuit
f_name = 'Bell_state_creator_beta_'
if(not0):
f_name += '1'
else:
f_name += '0'
if(not1):
f_name += '1'
else:
f_name += '0'
f_name += '.tex'
with open(LaTex_folder_Bell_states+f_name, 'w') as f:
f.write(LaTex_code)
|
https://github.com/benkoehlL/Qiskit_Playground
|
benkoehlL
|
'''
This program performs the Berstein-Vazirani algorithm to guess a secret code
'''
from qiskit import *
from qiskit.visualization import plot_histogram
from matplotlib.pyplot import plot, draw, show
import numpy as np
import os, shutil
LaTex_folder_Berstein_Vazirani = str(os.getcwd())+'/Latex_quantum_gates/Berstein_Vazarani/'
if not os.path.exists(LaTex_folder_Berstein_Vazirani):
os.makedirs(LaTex_folder_Berstein_Vazirani)
else:
shutil.rmtree(LaTex_folder_Berstein_Vazirani)
os.makedirs(LaTex_folder_Berstein_Vazirani)
## guess a secret binary number
s = '110101' #secret number/code
n = len(s)
qc = QuantumCircuit(n+1,n)
qc.x(n)
qc.barrier()
qc.h(range(n+1))
qc.barrier()
# to separate steps
for i, tf in enumerate(reversed(s)):
if(tf == '1'):
qc.cx(i,n)
qc.barrier()
qc.h(range(n+1))
qc.barrier()
qc.measure(range(n), range(n))
# create a LaTex file for the algorithm
LaTex_code = qc.draw(output='latex_source', initial_state=True, justify=None) # draw the circuit
f_name = 'Berstein_Vazirani.tex'
with open(LaTex_folder_Berstein_Vazirani+f_name, 'w') as f:
f.write(LaTex_code)
# simulate the algorithm
simulator = Aer.get_backend('qasm_simulator')
job = execute(qc, simulator, shots=1)
results = job.result()
count = results.get_counts()
plot_histogram(results.get_counts(qc))
print(count)
draw()
show(block=True)
## guess a secret string
string = 'Thank you for the nice book'
bit_string = []
# convert string to bit-string
for c in string:
bits_letter = format(ord(c), 'b')
for bit in bits_letter:
bit_string.append(bit)
n = len(bit_string)
qc = QuantumCircuit(n+1,n)
qc.x(n)
qc.barrier()
qc.h(range(n+1))
qc.barrier()
# to separate steps
for i, tf in enumerate(reversed(bit_string)):
if(tf == '1'):
qc.cx(i,n)
qc.barrier()
qc.h(range(n+1))
qc.barrier()
qc.measure(range(n), range(n))
simulator = Aer.get_backend('qasm_simulator')
job = execute(qc, simulator, shots=1)
results = job.result()
count = results.get_counts()
plot_histogram(results.get_counts(qc))
print(len(bit_string),'\n', count)
draw()
show(block=True)
|
https://github.com/benkoehlL/Qiskit_Playground
|
benkoehlL
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
import numpy as np
import os
from matplotlib.pyplot import draw, show
import shutil
'''
LaTex_folder = str(os.getcwd())+'/Latex_quantum_gates/circuits/'
if not os.path.exists(LaTex_folder):
os.makedirs(LaTex_folder)
## A decomposition of the CU(theta,phi,lambda, alpha)
qr = QuantumRegister(2,name='q')
circuit = QuantumCircuit(qr)
circuit.rz(np.pi/2,qr[1]) # angle (lambda+pi)/2
circuit.cx(qr[0],qr[1])
circuit.rz(-np.pi/2,qr[1]) # angle -(lambda+pi)/2
circuit.ry(np.pi/4,qr[1]) # angle theta/2
circuit.cx(qr[0],qr[1])
circuit.ry(-np.pi/4,qr[1]) # angle -theta/2
circuit.rz(np.pi/8,qr[1]) # angle (phi+pi)/2
circuit.cx(qr[0],qr[1])
circuit.rz(-np.pi/8,qr[1]) # angle -(phi+pi)/2
circuit.cx(qr[0],qr[1])
# global phase gate to target qubit
circuit.x(qr[1])
circuit.u(0,0,np.pi/16,qr[1]) # angle alpha
circuit.x(qr[1])
circuit.u(0,0,np.pi/16,qr[1]) # angle alpha
LaTex_code = circuit.draw(output='latex_source', initial_state=True, justify=None) # draw the circuit
f_name = 'CU_Gate.tex'
with open(LaTex_folder+f_name, 'w') as f:
f.write(LaTex_code)
## The qiskit CU-gate
circuit = QuantumCircuit(qr)
circuit.cu(np.pi/4,np.pi/8,np.pi/2,np.pi/16,qr[0],qr[1])
LaTex_code = circuit.draw(output='latex_source', initial_state=True, justify=None) # draw the circuit
f_name = 'CU_Gate_compact.tex'
with open(LaTex_folder+f_name, 'w') as f:
f.write(LaTex_code)
'''
QASM_folder = str(os.getcwd())+'/OpenQASM_pictures/'
if not os.path.exists(QASM_folder):
os.makedirs(QASM_folder)
n= 5
qr = QuantumRegister(n,name='q')
cr = ClassicalRegister(n,name='c')
circuit = QuantumCircuit(qr, cr)
for q in qr:
circuit.h(q)
for i in range(len(qr)):
circuit.cx(qr[i],qr[(i+1)%len(qr)])
circuit.u(np.pi/8,np.pi/4,0,qr[0])
circuit.rx(np.pi/2,qr[0])
circuit.ccx(qr[0],qr[1],qr[2])
circuit.toffoli(qr[0],qr[1],qr[2])
circuit.measure(qr,cr)
circuit.sdg(qr[0])
qasm = circuit.qasm()
print(qasm)
|
https://github.com/benkoehlL/Qiskit_Playground
|
benkoehlL
|
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.pyplot import plot, draw, show
import os, shutil
from qiskit import BasicAer, IBMQ, QuantumCircuit, ClassicalRegister,\
QuantumRegister, execute
from qiskit.compiler import transpile
from qiskit.transpiler import CouplingMap
from qiskit.tools.monitor import job_monitor
from qiskit.tools.visualization import plot_histogram
LaTex_folder_Deutsch_Josza = str(os.getcwd())+'/Latex_quantum_gates/Deutsch_Josza_algorithm/'
if not os.path.exists(LaTex_folder_Deutsch_Josza):
os.makedirs(LaTex_folder_Deutsch_Josza)
else:
shutil.rmtree(LaTex_folder_Deutsch_Josza)
os.makedirs(LaTex_folder_Deutsch_Josza)
n = 4 # number of qubits in state |0>
# Choose a type of oracle at random.
# With probability one-half it is constant
# and with the same probability it is balanced
oracleType, oracleValue = np.random.randint(2), np.random.randint(2)
if oracleType == 0:
print("Oracle is constant with value = ", oracleValue)
else:
print("Oracle is balanced ")
# this is a hidden parameter for balanced oracles
a = np.random.randint(1,2**n)
# Creating registers
# n qubits for querying the oracle and one qubit forstoring the answer
qr = QuantumRegister(n+1, 'q') #all qubits are initialised to |0>
# for recording the measurement on the first register
cr = ClassicalRegister(n, 'c')
circuitName = "DeutschJosza"
djCircuit = QuantumCircuit(qr, cr)
# Create the superposition of all input queries in the first register
# by applying the Hadamard gate to each qubit.
for qubit in qr[0:-2]:
djCircuit.h(qubit)
# Flip the second register and apply the Hadamard gate
djCircuit.x(qr[n])
djCircuit.h(qr[n])
# Apply the barrier to mark the beginning of the oracle
djCircuit.barrier()
if oracleType == 0:#If the oracleType is "0", the oracle returns oracleValue
#for all inputs
if oracleValue == 1:
djCircuit.x(qr[n])
else:
djCircuit.id(qr[n])
else: #otherwise, it returns the inner product of the input with
#a (non-zero) bitstring
for i, qubit in enumerate(qr[0:-2]):
if(a & (1 << i)):
djCircuit.cx(qubit, qr[n])
# Apply barrier to mark the end of the oracle
djCircuit.barrier()
# Apply Hadamard gates after querying the oracle
for qubit in qr[0:-2]:
djCircuit.h(qubit)
# Measurement
djCircuit.barrier()
for i in range(n):
djCircuit.measure(qr[i], cr[i])
# create a LaTex file for the algorithm
LaTex_code = djCircuit.draw(output='latex_source', initial_state=True, justify=None) # draw the circuit
f_name = 'Deutsch_Josza_algorithm.tex'
with open(LaTex_folder_Deutsch_Josza+f_name, 'w') as f:
f.write(LaTex_code)
## execute on a simulator
backend = BasicAer.get_backend('qasm_simulator')
shots = 1000
job = execute(djCircuit, backend=backend, shots=shots)
results = job.result()
answer = results.get_counts()
plot_histogram(answer)
draw()
show(block=True)
## execute on a real device
provider = IBMQ.load_account()
for backend in IBMQ.providers()[0].backends():
print(backend.name(),)
backend = provider.backend.ibmq_lima
djCompiled = transpile(djCircuit, backend=backend, optimization_level=1)
djCompiled.draw(output='mpl', scale=0.5)
draw()
show(block=True)
print("This step might take some time!!!")
job = execute(djCompiled, backend=backend, shots=shots)
job_monitor(job)
results = job.result()
answer = results.get_counts()
threshold = int(0.01 *shots) # the threshld of plotting significant measurements
# filter the answer for better view of plots
filteredAnswer = {k: v for k,v in answer.items() if v>= threshold}
# number of counts removed
removedCounts = np.sum([ v for k,v in answer.items() if v < threshold])
# the removed counts are assigned to a new index
filteredAnswer['other_bitstrings'] = removedCounts
plot_histogram(filteredAnswer)
draw()
show(block=True)
# Quantum computers have noise so they would not produce discrete outputs
# like simulators - that only demonstrates the superiority
# of quantum over classical
print(filteredAnswer)
|
https://github.com/benkoehlL/Qiskit_Playground
|
benkoehlL
|
import os, shutil
from qiskit import *
from qiskit.visualization import plot_histogram
from qiskit.visualization import circuit_drawer as drawer
import numpy as np
from matplotlib.pyplot import draw, plot, show
N = 1000 # number of circuits with random errors
p = 0.1 # error probability
LaTex_folder_Error_Correction = str(os.getcwd())+'/Latex_quantum_gates/Error_Correction/'
if not os.path.exists(LaTex_folder_Error_Correction):
os.makedirs(LaTex_folder_Error_Correction)
else:
shutil.rmtree(LaTex_folder_Error_Correction)
os.makedirs(LaTex_folder_Error_Correction)
def ERROR_X(circuit, q):
if(np.random.rand()<p):
circuit.x(q)
def ERROR_Y(circuit, q):
if(np.random.rand()<p):
circuit.y(q)
def ERROR_Z(circuit, q):
if(np.random.rand()<p):
circuit.z(q)
def All_Errors(circuit, q):
for qubit in q:
ran = np.random.rand()
if(ran < 1/3):
ERROR_X(circuit, qubit)
elif(ran < 2/3):
ERROR_Y(circuit, qubit)
else:
ERROR_Z(circuit, qubit)
def Shor_error_correction(Circuit_FUNC, qr, qr_Shor):
# This function creates the Shor error correction circuit
# for a error-prone function Circuit_FUNC and its related
# qubit(s) qr (qr_Shor are the ancilla qubits)
# it returns this error corrected circuit
qc_preprocess = QuantumCircuit(qr, qr_Shor)
for i, qubit in enumerate(qr):
qc_preprocess.cx(qubit, qr_Shor[8*i+2])
qc_preprocess.cx(qubit, qr_Shor[8*i+5])
qc_preprocess.h(qubit)
qc_preprocess.h(qr_Shor[8*i+2])
qc_preprocess.h(qr_Shor[8*i+5])
qc_preprocess.cx(qubit, qr_Shor[8*i])
qc_preprocess.cx(qubit, qr_Shor[8*i+1])
qc_preprocess.cx(qr_Shor[8*i+2], qr_Shor[8*i+3])
qc_preprocess.cx(qr_Shor[8*i+2], qr_Shor[8*i+4])
qc_preprocess.cx(qr_Shor[8*i+5], qr_Shor[8*i+6])
qc_preprocess.cx(qr_Shor[8*i+5], qr_Shor[8*i+7])
#qc_preprocess.barrier()
qc_preprocess.barrier()
qc = qc_preprocess
# apply main function (with possible errors) to qr
# and the error ancilla qubits
Circuit_FUNC(qc, qr)
for j in range(8):
Circuit_FUNC(qc, qr_Shor[j:j+8*len(qr):8])
qc.barrier()
qc_postprocess = QuantumCircuit(qr,qr_Shor)
for i, qubit in enumerate(qr):
qc_postprocess.cx(qubit, qr_Shor[8*i])
qc_postprocess.cx(qubit, qr_Shor[8*i+1])
qc_postprocess.cx(qr_Shor[8*i+2], qr_Shor[8*i+3])
qc_postprocess.cx(qr_Shor[8*i+2], qr_Shor[8*i+4])
qc_postprocess.cx(qr_Shor[8*i+5], qr_Shor[8*i+6])
qc_postprocess.cx(qr_Shor[8*i+5], qr_Shor[8*i+7])
qc_postprocess.ccx(qr_Shor[8*i], qr_Shor[8*i+1], qubit)
qc_postprocess.ccx(qr_Shor[8*i+3], qr_Shor[8*i+4], qr_Shor[8*i+2])
qc_postprocess.ccx(qr_Shor[8*i+6], qr_Shor[8*i+7], qr_Shor[8*i+5])
qc_postprocess.h(qubit)
qc_postprocess.h(qr_Shor[8*i+2])
qc_postprocess.h(qr_Shor[8*i+5])
qc_postprocess.cx(qubit, qr_Shor[8*i+2])
qc_postprocess.cx(qubit, qr_Shor[8*i+5])
qc_postprocess.ccx(qr_Shor[8*i+2], qr_Shor[8*i+5], qubit)
#qc_postprocess.barrier()
qc = QuantumCircuit.compose(qc, qc_postprocess)
return qc
## X-Error
print("X error")
for qubit in [0, 1]:
answer_plot = {}
print("|",qubit,'> : ',end='')
for i in range(N):
q = QuantumRegister(1,'q')
q_Shor = QuantumRegister(8*len(q),'q_shor')
c = ClassicalRegister(len(q), 'c')
qc = QuantumCircuit(q,q_Shor, c)
if(qubit):
qc.x(q)
qc_Shor = Shor_error_correction(ERROR_X, q, q_Shor)
qc_Shor.barrier()
qc_Shor = QuantumCircuit.compose(qc, qc_Shor)
qc_Shor.measure(q, c)
# evaluate result
simulator = Aer.get_backend('qasm_simulator')
result = execute(qc_Shor, backend=simulator, shots=100).result()
answer = result.get_counts()
for measureresult in answer.keys():
measureresults_input = measureresult
if measureresults_input in answer_plot:
answer_plot[measureresults_input] += answer[measureresult]
else:
answer_plot[measureresults_input] = answer[measureresult]
# Plot the categorised results
print(answer_plot)
#plt = plot_histogram(answer_plot)
#draw()
#show(block=True)
LaTex_code = qc_Shor.draw(output='latex_source', initial_state=True, justify=None) # draw the circuit
f_name = 'Shor_error_correction_XERROR.tex'
with open(LaTex_folder_Error_Correction+f_name, 'w') as f:
f.write(LaTex_code)
## Y-Error
print("Y error")
for qubit in [0, 1]:
answer_plot = {}
print("|",qubit,'> : ',end='')
for i in range(N):
q = QuantumRegister(1,'q')
q_Shor = QuantumRegister(8*len(q),'q_shor')
c = ClassicalRegister(len(q), 'c')
qc = QuantumCircuit(q,q_Shor, c)
if qubit:
qc.x(q)
qc.h(q) # y error is detected in Hadamard basis
qc_Shor = Shor_error_correction(ERROR_Y, q, q_Shor)
qc_Shor.barrier()
qc_Shor = QuantumCircuit.compose(qc, qc_Shor)
qc_Shor.h(q) # y error is detected in Hadamard basis
qc_Shor.measure(q, c)
# evaluate result
simulator = Aer.get_backend('qasm_simulator')
result = execute(qc_Shor, backend=simulator, shots=100).result()
answer = result.get_counts()
for measureresult in answer.keys():
measureresults_input = measureresult
if measureresults_input in answer_plot:
answer_plot[measureresults_input] += answer[measureresult]
else:
answer_plot[measureresults_input] = answer[measureresult]
# Plot the categorised results
print(answer_plot)
#plt = plot_histogram(answer_plot)
#draw()
#show(block=True)
LaTex_code = qc_Shor.draw(output='latex_source', initial_state=True, justify=None) # draw the circuit
f_name = 'Shor_error_correction_YERROR.tex'
with open(LaTex_folder_Error_Correction+f_name, 'w') as f:
f.write(LaTex_code)
## Z-Error
print("Z error")
for qubit in [0, 1]:
answer_plot = {}
print("|",qubit,'> : ',end='')
for i in range(N):
q = QuantumRegister(1,'q')
q_Shor = QuantumRegister(8*len(q),'q_shor')
c = ClassicalRegister(len(q), 'c')
qc = QuantumCircuit(q,q_Shor, c)
if qubit:
qc.x(q)
qc.h(q) # z error is detected in Hadamard basis
qc_Shor = Shor_error_correction(ERROR_Z, q, q_Shor)
qc_Shor.barrier()
qc_Shor = QuantumCircuit.compose(qc, qc_Shor)
qc_Shor.h(q) # z error is detected in Hadamard basis
qc_Shor.measure(q, c)
# evaluate result
simulator = Aer.get_backend('qasm_simulator')
result = execute(qc_Shor, backend=simulator, shots=100).result()
answer = result.get_counts()
for measureresult in answer.keys():
measureresults_input = measureresult
if measureresults_input in answer_plot:
answer_plot[measureresults_input] += answer[measureresult]
else:
answer_plot[measureresults_input] = answer[measureresult]
# Plot the categorised results
print(answer_plot)
#plt = plot_histogram(answer_plot)
#draw()
#show(block=True)
LaTex_code = qc_Shor.draw(output='latex_source', initial_state=True, justify=None) # draw the circuit
f_name = 'Shor_error_correction_ZERROR.tex'
with open(LaTex_folder_Error_Correction+f_name, 'w') as f:
f.write(LaTex_code)
## All three errors possible before CX-gate
print("CX with all error types")
for qubit1 in [0, 1]:
for qubit2 in [0, 1]:
print("|",qubit1,qubit2,'> : ',end='')
answer_plot = {}
for i in range(N):
q = QuantumRegister(2,'q')
c = ClassicalRegister(len(q), 'c')
q_Shor = QuantumRegister(8*len(q),'q_shor')
qc = QuantumCircuit(q, q_Shor, c)
if(qubit1):
qc.x(q[0])
if(qubit2):
qc.x(q[1])
qc.barrier()
qc_Shor = Shor_error_correction(All_Errors, q, q_Shor)
qc_Shor.barrier()
qc_Shor = QuantumCircuit.compose(qc, qc_Shor)
qc_Shor.cx(q[0],q[1])
for i, qubit in enumerate(reversed(q)):
qc_Shor.measure(qubit, c[i])
# evaluate result
simulator = Aer.get_backend('qasm_simulator')
result = execute(qc_Shor, backend=simulator, shots=10).result()
answer = result.get_counts()
for measureresult in answer.keys():
measureresults_input = measureresult
if measureresults_input in answer_plot:
answer_plot[measureresults_input] += answer[measureresult]
else:
answer_plot[measureresults_input] = answer[measureresult]
# Plot the categorised results
print(answer_plot)
plt = plot_histogram(answer_plot)
draw()
show(block=True)
|
https://github.com/benkoehlL/Qiskit_Playground
|
benkoehlL
|
from qiskit import *
print("GHZ")
c2 = QuantumCircuit(3,3)
c2.h(0)
c2.h(1)
c2.ccz(0,1,2)
c2.x(2)
c2.ccz(0,1,2)
c2.x(2)
c2.h(1)
c2.h(2)
c2.ccz(0,1,2)
c2.h(2)
c2.measure([i for i in range(3)], [i for i in range(3)])
simulator = Aer.get_backend('qasm_simulator')
result = execute(c2, backend=simulator, shots=1000).result()
answer = result.get_counts()
print(answer)
|
https://github.com/benkoehlL/Qiskit_Playground
|
benkoehlL
|
from argparse import ArgumentParser, Namespace, BooleanOptionalAction
from qiskit import QuantumCircuit as qc
from qiskit import QuantumRegister as qr
from qiskit import transpile
from qiskit_aer import AerSimulator
from qiskit.result import Counts
from matplotlib.pyplot import show, subplots, xticks, yticks
from math import pi, sqrt
from heapq import nlargest
class GroversAlgorithm:
def __init__(self,
title: str = "Grover's Algorithm",
n_qubits: int = 5,
search: set[int] = { 11, 9, 0, 3 },
shots: int = 1000,
fontsize: int = 10,
print: bool = False,
combine_states: bool = False) -> None:
"""
_summary_
Args:
title (str, optional): Window title. Defaults to "Grover's Algorithm".
n_qubits (int, optional): Number of qubits. Defaults to 5.
search (set[int], optional): Set of nonnegative integers to search for using Grover's algorithm. Defaults to { 11, 9, 0, 3 }.
shots (int, optional): Amount of times the algorithm is simulated. Defaults to 10000.
fontsize (int, optional): Histogram's font size. Defaults to 10.
print (bool, optional): Whether or not to print quantum circuit(s). Defaults to False.
combine_states (bool, optional): Whether to combine all non-winning states into 1 bar labeled "Others" or not. Defaults to False.
"""
# Parsing command line arguments
self._parser: ArgumentParser = ArgumentParser(description = "Run grover's algorithm via command line", add_help = False)
self._init_parser(title, n_qubits, search, shots, fontsize, print, combine_states)
self._args: Namespace = self._parser.parse_args()
# Set of nonnegative ints to search for
self.search: set[int] = set(self._args.search)
# Set of m N-qubit binary strings representing target state(s) (i.e. self.search in base 2)
self._targets: set[str] = { f"{s:0{self._args.n_qubits}b}" for s in self.search }
# N-qubit quantum register
self._qubits: qr = qr(self._args.n_qubits, "qubit")
def _print_circuit(self, circuit: qc, name: str) -> None:
"""Print quantum circuit.
Args:
circuit (qc): Quantum circuit to print.
name (str): Quantum circuit's name.
"""
print(f"\n{name}:\n{circuit}")
def _oracle(self, targets: set[str]) -> qc:
"""Mark target state(s) with negative phase.
Args:
targets (set[str]): N-qubit binary string(s) representing target state(s).
Returns:
qc: Quantum circuit representation of oracle.
"""
# Create N-qubit quantum circuit for oracle
oracle = qc(self._qubits, name = "Oracle")
for target in targets:
# Reverse target state since Qiskit uses little-endian for qubit ordering
target = target[::-1]
# Flip zero qubits in target
for i in range(self._args.n_qubits):
if target[i] == "0":
# Pauli-X gate
oracle.x(i)
# Simulate (N - 1)-control Z gate
# 1. Hadamard gate
oracle.h(self._args.n_qubits - 1)
# 2. (N - 1)-control Toffoli gate
oracle.mcx(list(range(self._args.n_qubits - 1)), self._args.n_qubits - 1)
# 3. Hadamard gate
oracle.h(self._args.n_qubits - 1)
# Flip back to original state
for i in range(self._args.n_qubits):
if target[i] == "0":
# Pauli-X gate
oracle.x(i)
# Display oracle, if applicable
if self._args.print: self._print_circuit(oracle, "ORACLE")
return oracle
def _diffuser(self) -> qc:
"""Amplify target state(s) amplitude, which decreases the amplitudes of other states
and increases the probability of getting the correct solution (i.e. target state(s)).
Returns:
qc: Quantum circuit representation of diffuser (i.e. Grover's diffusion operator).
"""
# Create N-qubit quantum circuit for diffuser
diffuser = qc(self._qubits, name = "Diffuser")
# Hadamard gate
diffuser.h(self._qubits)
# Oracle with all zero target state
diffuser.append(self._oracle({"0" * self._args.n_qubits}), list(range(self._args.n_qubits)))
# Hadamard gate
diffuser.h(self._qubits)
# Display diffuser, if applicable
if self._args.print: self._print_circuit(diffuser, "DIFFUSER")
return diffuser
def _grover(self) -> qc:
"""Create quantum circuit representation of Grover's algorithm,
which consists of 4 parts: (1) state preparation/initialization,
(2) oracle, (3) diffuser, and (4) measurement of resulting state.
Steps 2-3 are repeated an optimal number of times (i.e. Grover's
iterate) in order to maximize probability of success of Grover's algorithm.
Returns:
qc: Quantum circuit representation of Grover's algorithm.
"""
# Create N-qubit quantum circuit for Grover's algorithm
grover = qc(self._qubits, name = "Grover Circuit")
# Intialize qubits with Hadamard gate (i.e. uniform superposition)
grover.h(self._qubits)
# # Apply barrier to separate steps
grover.barrier()
# Apply oracle and diffuser (i.e. Grover operator) optimal number of times
for _ in range(int((pi / 4) * sqrt((2 ** self._args.n_qubits) / len(self._targets)))):
grover.append(self._oracle(self._targets), list(range(self._args.n_qubits)))
grover.append(self._diffuser(), list(range(self._args.n_qubits)))
# Measure all qubits once finished
grover.measure_all()
# Display grover circuit, if applicable
if self._args.print: self._print_circuit(grover, "GROVER CIRCUIT")
return grover
def _outcome(self, winners: list[str], counts: Counts) -> None:
"""Print top measurement(s) (state(s) with highest frequency)
and target state(s) in binary and decimal form, determine
if top measurement(s) equals target state(s), then print result.
Args:
winners (list[str]): State(s) (N-qubit binary string(s))
with highest probability of being measured.
counts (Counts): Each state and its respective frequency.
"""
print("WINNER(S):")
print(f"Binary = {winners}\nDecimal = {[ int(key, 2) for key in winners ]}\n")
print("TARGET(S):")
print(f"Binary = {self._targets}\nDecimal = {self.search}\n")
if not all(key in self._targets for key in winners): print("Target(s) not found...")
else:
winners_frequency, total = 0, 0
for value, frequency in counts.items():
if value in winners:
winners_frequency += frequency
total += frequency
print(f"Target(s) found with {winners_frequency / total:.2%} accuracy!")
def _show_histogram(self, histogram_data) -> None:
"""Print outcome and display histogram of simulation results.
Args:
data: Each state and its respective frequency.
"""
# State(s) with highest count and their frequencies
winners = { winner : histogram_data.get(winner) for winner in nlargest(len(self._targets), histogram_data, key = histogram_data.get) }
# Print outcome
self._outcome(list(winners.keys()), histogram_data)
# X-axis and y-axis value(s) for winners, respectively
winners_x_axis = [ str(winner) for winner in [*winners] ]
winners_y_axis = [ *winners.values() ]
# All other states (i.e. non-winners) and their frequencies
others = { state : frequency for state, frequency in histogram_data.items() if state not in winners }
# X-axis and y-axis value(s) for all other states, respectively
other_states_x_axis = "Others" if self._args.combine else [*others]
other_states_y_axis = [ sum([*others.values()]) ] if self._args.combine else [ *others.values() ]
# Create histogram for simulation results
figure, axes = subplots(num = "Grover's Algorithm — Results", layout = "constrained")
axes.bar(winners_x_axis, winners_y_axis, color = "green", label = "Target")
axes.bar(other_states_x_axis, other_states_y_axis, color = "red", label = "Non-target")
axes.legend(fontsize = self._args.fontsize)
axes.grid(axis = "y", ls = "dashed")
axes.set_axisbelow(True)
# Set histogram title, x-axis title, and y-axis title respectively
axes.set_title(f"Outcome of {self._args.shots} Simulations", fontsize = int(self._args.fontsize * 1.45))
axes.set_xlabel("States (Qubits)", fontsize = int(self._args.fontsize * 1.3))
axes.set_ylabel("Frequency", fontsize = int(self._args.fontsize * 1.3))
# Set font properties for x-axis and y-axis labels respectively
xticks(fontsize = self._args.fontsize, family = "monospace", rotation = 0 if self._args.combine else 70)
yticks(fontsize = self._args.fontsize, family = "monospace")
# Set properties for annotations displaying frequency above each bar
annotation = axes.annotate("",
xy = (0, 0),
xytext = (5, 5),
xycoords = "data",
textcoords = "offset pixels",
ha = "center",
va = "bottom",
family = "monospace",
weight = "bold",
fontsize = self._args.fontsize,
bbox = dict(facecolor = "white", alpha = 0.4, edgecolor = "None", pad = 0)
)
def _hover(event) -> None:
"""Display frequency above each bar upon hovering over it.
Args:
event: Matplotlib event.
"""
visibility = annotation.get_visible()
if event.inaxes == axes:
for bars in axes.containers:
for bar in bars:
cont, _ = bar.contains(event)
if cont:
x, y = bar.get_x() + bar.get_width() / 2, bar.get_y() + bar.get_height()
annotation.xy = (x, y)
annotation.set_text(y)
annotation.set_visible(True)
figure.canvas.draw_idle()
return
if visibility:
annotation.set_visible(False)
figure.canvas.draw_idle()
# Display histogram
id = figure.canvas.mpl_connect("motion_notify_event", _hover)
show()
figure.canvas.mpl_disconnect(id)
def run(self) -> None:
"""
Run Grover's algorithm simulation.
"""
# Simulate Grover's algorithm locally
backend = AerSimulator(method = "density_matrix")
# Generate optimized grover circuit for simulation
transpiled_circuit = transpile(self._grover(), backend, optimization_level = 2)
# Run Grover's algorithm simulation
job = backend.run(transpiled_circuit, shots = self._args.shots)
# Get simulation results
results = job.result()
# Get each state's histogram data (including frequency) from simulation results
data = results.get_counts()
# Display simulation results
self._show_histogram(data)
def _init_parser(self,
title: str,
n_qubits: int,
search: set[int],
shots: int,
fontsize: int,
print: bool,
combine_states: bool) -> None:
"""
Helper method to initialize command line argument parser.
Args:
title (str): Window title.
n_qubits (int): Number of qubits.
search (set[int]): Set of nonnegative integers to search for using Grover's algorithm.
shots (int): Amount of times the algorithm is simulated.
fontsize (int): Histogram's font size.
print (bool): Whether or not to print quantum circuit(s).
combine_states (bool): Whether to combine all non-winning states into 1 bar labeled "Others" or not.
"""
self._parser.add_argument("-H, --help",
action = "help",
help = "show this help message and exit")
self._parser.add_argument("-T, --title",
type = str,
default = title,
dest = "title",
metavar = "<title>",
help = f"window title (default: \"{title}\")")
self._parser.add_argument("-n, --n-qubits",
type = int,
default = n_qubits,
dest = "n_qubits",
metavar = "<n_qubits>",
help = f"number of qubits (default: {n_qubits})")
self._parser.add_argument("-s, --search",
default = search,
type = int,
nargs = "+",
dest = "search",
metavar = "<search>",
help = f"nonnegative integers to search for with Grover's algorithm (default: {search})")
self._parser.add_argument("-S, --shots",
type = int,
default = shots,
dest = "shots",
metavar = "<shots>",
help = f"amount of times the algorithm is simulated (default: {shots})")
self._parser.add_argument("-f, --font-size",
type = int,
default = fontsize,
dest = "fontsize",
metavar = "<font_size>",
help = f"histogram's font size (default: {fontsize})")
self._parser.add_argument("-p, --print",
action = BooleanOptionalAction,
type = bool,
default = print,
dest = "print",
help = f"whether or not to print quantum circuit(s) (default: {print})")
self._parser.add_argument("-c, --combine",
action = BooleanOptionalAction,
type = bool,
default = combine_states,
dest = "combine",
help = f"whether to combine all non-winning states into 1 bar labeled \"Others\" or not (default: {combine_states})")
if __name__ == "__main__":
GroversAlgorithm().run()
|
https://github.com/benkoehlL/Qiskit_Playground
|
benkoehlL
|
import os
from qiskit import (QuantumCircuit,
QuantumRegister,
ClassicalRegister,
execute,
BasicAer)
from scipy.optimize import minimize
import matplotlib.pyplot as plt
from matplotlib.pyplot import plot, draw, show
import numpy as np
os.environ["QT_QPA_PLATFORM"] = "xcb"
def ansatz_H(theta):
qc = QuantumCircuit(2,2)
qc.x(0)
qc.ry(theta[0],0)
qc.rx(theta[0]+2*np.pi,1)
qc.cx(0,1)
qc.rz(theta[1],0)
qc.cx(0,1)
qc.ry(theta[0]+2*np.pi,0)
qc.rx(theta[0],1)
return qc
def expectation_H(theta):
# See DOI: 10.1103/PhysRevX.6.031007
# Here, we use parameters given for H2 at R=0.75A
g0 = -0.4804
g1 = +0.3435
g2 = -0.4347
g3 = +0.5716
g4 = +0.0910
g5 = +0.0910
energy = g0
qc = ansatz_H(theta)
qc.measure(0,0)
qc.measure(1,1)
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
results = execute(qc, backend=backend, shots=shots).result()
counts = results.get_counts()
for key in counts.keys():
if(key[0]=='0'):
energy += g1*counts[key]/shots
else:
energy += -g1*counts[key]/shots
if(key[1]=='0'):
energy += g2*counts[key]/shots
else:
energy += -g2*counts[key]/shots
if(key[0]==key[1]):
energy += g3*counts[key]/shots
else:
energy += -g3*counts[key]/shots
qc = ansatz_H(theta)
qc.h(0)
qc.h(1)
qc.s(0)
qc.s(1)
qc.measure(0,0)
qc.measure(1,1)
results = execute(qc, backend=backend, shots=shots).result()
counts = results.get_counts()
for key in counts.keys():
if(key[0]==key[1]):
energy += g4*counts[key]/shots
else:
energy += -g4*counts[key]/shots
qc = ansatz_H(theta)
qc.h(0)
qc.h(1)
qc.measure(0,0)
qc.measure(1,1)
results = execute(qc, backend=backend, shots=shots).result()
counts = results.get_counts()
for key in counts.keys():
if(key[0]==key[1]):
energy += g5*counts[key]/shots
else:
energy += -g5*counts[key]/shots
return energy
nuclear_repulsion = 0.7055696146
theta = [4*np.pi*np.random.uniform(), 4*np.pi*np.random.uniform()]
result = minimize(expectation_H,theta, method='Nelder-Mead')
theta = result.x
val = result.fun
print("VQE: ")
print(" [+] theta1: {:+2.8} rad, theta2: {:+2.8} rad".format(theta[0],theta[1]))
print(" [+] energy: {:+2.8} Eh".format(val + nuclear_repulsion))
'''
import numpy as np
from scipy.linalg import block_diag
from scipy.optimize import minimize
np.set_printoptions(precision=4,suppress=True)
# Pauli matrices
I = np.array([[ 1, 0],
[ 0, 1]])
Sx = np.array([[ 0, 1],
[ 1, 0]])
Sy = np.array([[ 0,-1j],
[1j, 0]])
Sz = np.array([[ 1, 0],
[ 0,-1]])
# Hadamard matrix
H = (1/np.sqrt(2))*np.array([[ 1, 1],
[ 1,-1]])
# Phase matrix
S = np.array([[ 1, 0],
[ 0,1j]])
# single qubit basis states |0> and |1>
q0 = np.array([[1],
[0]])
q1 = np.array([[0],
[1]])
# Projection matrices |0><0| and |1><1|
P0 = np.dot(q0,q0.conj().T)
P1 = np.dot(q1,q1.conj().T)
# Rotation matrices as a function of theta, e.g. Rx(theta), etc.
Rx = lambda theta : np.array([[ np.cos(theta/2),-1j*np.sin(theta/2)],
[-1j*np.sin(theta/2), np.cos(theta/2)]])
Ry = lambda theta : np.array([[ np.cos(theta/2), -np.sin(theta/2)],
[ np.sin(theta/2), np.cos(theta/2)]])
Rz = lambda theta : np.array([[np.exp(-1j*theta/2), 0.0],
[ 0.0, np.exp(1j*theta/2)]])
# CNOTij, where i is control qubit and j is target qubit
CNOT10 = np.kron(P0,I) + np.kron(P1,Sx) # control -> q1, target -> q0
CNOT01 = np.kron(I,P0) + np.kron(Sx,P1) # control -> q0, target -> q1
SWAP = block_diag(1,Sx,1)
# See DOI: 10.1103/PhysRevX.6.031007
# Here, we use parameters given for H2 at R=0.75A
g0 = -0.4804
g1 = +0.3435
g2 = -0.4347
g3 = +0.5716
g4 = +0.0910
g5 = +0.0910
nuclear_repulsion = 0.7055696146
Hmol = (g0 * np.kron( I, I) + # g0 * I
g1 * np.kron( I,Sz) + # g1 * Z0
g2 * np.kron(Sz, I) + # g2 * Z1
g3 * np.kron(Sz,Sz) + # g3 * Z0Z1
g4 * np.kron(Sy,Sy) + # g4 * Y0Y1
g5 * np.kron(Sx,Sx)) # g5 * X0X1
electronic_energy = np.linalg.eigvalsh(Hmol)[0] # take the lowest value
print("Classical diagonalization: {:+2.8} Eh".format(electronic_energy + nuclear_repulsion))
print("Exact (from G16): {:+2.8} Eh".format(-1.1457416808))
# initial basis, put in |01> state with Sx operator on q0
psi0 = np.zeros((4,1))
psi0[0] = 1
psi0 = np.dot(np.kron(I,Sx),psi0)
# read right-to-left (bottom-to-top?)
ansatz = lambda theta: (np.dot(np.dot(np.kron(-Ry(np.pi/2),Rx(np.pi/2)),
np.dot(CNOT10,
np.dot(np.kron(I,Rz(theta)),
CNOT10))),
np.kron(Ry(np.pi/2),-Rx(np.pi/2))))
def projective_expected(theta,ansatz,psi0):
# this will depend on the hard-coded Hamiltonian + coefficients
circuit = ansatz(theta[0])
psi = np.dot(circuit,psi0)
# for 2 qubits, assume we can only take Pauli Sz measurements (Sz \otimes I)
# we just apply the right unitary for the desired Pauli measurement
measureZ = lambda U: np.dot(np.conj(U).T,np.dot(np.kron(Sz,I),U))
energy = 0.0
# although the paper indexes the hamiltonian left-to-right (0-to-1)
# qubit-1 is always the top qubit for us, so the tensor pdt changes
# e.g. compare with the "exact Hamiltonian" we explicitly diagonalized
# <I1 I0>
energy += g0 # it is a constant
# <I1 Sz0>
U = SWAP
energy += g1*np.dot(psi.conj().T,np.dot(measureZ(U),psi))
# <Sz1 I0>
U = np.kron(I,I)
energy += g2*np.dot(psi.conj().T,np.dot(measureZ(U),psi))
# <Sz1 Sz0>
U = CNOT01
energy += g3*np.dot(psi.conj().T,np.dot(measureZ(U),psi))
# <Sx1 Sx0>
U = np.dot(CNOT01,np.kron(H,H))
energy += g4*np.dot(psi.conj().T,np.dot(measureZ(U),psi))
# <Sy1 Sy0>
U = np.dot(CNOT01,np.kron(np.dot(H,S.conj().T),np.dot(H,S.conj().T)))
energy += g5*np.dot(psi.conj().T,np.dot(measureZ(U),psi))
return np.real(energy)[0,0]
theta = [0.0]
result = minimize(projective_expected,theta,args=(ansatz,psi0))
theta = result.x[0]
val = result.fun
# check it works...
#assert np.allclose(val + nuclear_repulsion,-1.1456295)
print("VQE: ")
print(" [+] theta: {:+2.8} deg".format(theta))
print(" [+] energy: {:+2.8} Eh".format(val + nuclear_repulsion))
'''
|
https://github.com/benkoehlL/Qiskit_Playground
|
benkoehlL
|
from qiskit import IBMQ
from qiskit import *
#provider = IBMQ.enable_account(<INSERT_IBM_QUANTUM_EXPERIENCE_TOKEN>)
qc = QuantumCircuit(2,2)
qc.h(0)
qc.cx(0,1)
qc.measure(1,0)
backend = IBMQ.get_backend('ibmq_qasm_simulator', hub=None)
job=execute(qc, backend, shots=1000)
result = job.result()
print(result.get_counts())
|
https://github.com/benkoehlL/Qiskit_Playground
|
benkoehlL
|
'''
This program creates a .tex file of several classical logic gates
'''
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
import os
import shutil
logic_folder = os.getcwd()
LaTex_folder_logic_gates = str(os.getcwd())+'/Latex_quantum_gates/logic_gates/'
if not os.path.exists(LaTex_folder_logic_gates):
os.makedirs(LaTex_folder_logic_gates)
else:
shutil.rmtree(LaTex_folder_logic_gates)
os.makedirs(LaTex_folder_logic_gates)
print(LaTex_folder_logic_gates)
## NOT gate
q = QuantumRegister(1, name='q')
c = ClassicalRegister(1, name='c')
qc = QuantumCircuit(q,c)
qc.x(q[0])
qc.measure(q[0],c[0])
LaTex_code = qc.draw(output='latex_source', justify=None) # draw the circuit
f_name = 'NOT_gate.tex'
with open(LaTex_folder_logic_gates+f_name, 'w') as f:
f.write(LaTex_code)
## AND gate
q = QuantumRegister(3, name='q')
qubit_state = '0'
c = ClassicalRegister(1, name='c')
qc = QuantumCircuit(q,c)
qc.reset(q[2])
qc.ccx(q[0], q[1], q[2])
qc.measure(q[2], c[0])
LaTex_code = qc.draw(output='latex_source', justify=None) # draw the circuit
f_name = 'AND_gate.tex'
with open(LaTex_folder_logic_gates+f_name, 'w') as f:
f.write(LaTex_code)
## OR gate
q = QuantumRegister(3, name='q')
c = ClassicalRegister(1, name='c')
qc = QuantumCircuit(q,c)
qc.reset(q[2])
qc.ccx(q[0], q[1], q[2])
qc.cx(q[0],q[2])
qc.cx(q[1],q[2])
qc.measure(q[2],c[0])
LaTex_code = qc.draw(output='latex_source', justify=None) # draw the circuit
f_name = 'OR_gate.tex'
with open(LaTex_folder_logic_gates+f_name, 'w') as f:
f.write(LaTex_code)
## XOR gate
q = QuantumRegister(3, name='q')
c = ClassicalRegister(1, name='c')
qc = QuantumCircuit(q,c)
qc.reset(q[2])
qc.cx(q[0],q[2])
qc.cx(q[1],q[2])
qc.measure(q[2],c[0])
LaTex_code = qc.draw(output='latex_source', justify=None) # draw the circuit
f_name = 'XOR_gate.tex'
with open(LaTex_folder_logic_gates+f_name, 'w') as f:
f.write(LaTex_code)
## NOR gate
q = QuantumRegister(3, name='q')
c = ClassicalRegister(1, name='c')
qc = QuantumCircuit(q,c)
qc.reset(q[2])
qc.ccx(q[0], q[1], q[2])
qc.cx(q[0],q[2])
qc.cx(q[1],q[2])
qc.x(q[2])
qc.measure(q[2],c[0])
LaTex_code = qc.draw(output='latex_source', justify=None) # draw the circuit
f_name = 'NOR_gate.tex'
with open(LaTex_folder_logic_gates+f_name, 'w') as f:
f.write(LaTex_code)
|
https://github.com/benkoehlL/Qiskit_Playground
|
benkoehlL
|
'''
This program uses some methods from quantum chemistry
(and doesn't produce anything good yet)
'''
import numpy as np
from matplotlib.pyplot import plot, draw, show
import pylab, os
from qiskit import *
#from qiskit.chemistry import QiskitChemistry # does no longer exist
from qiskit_nature import *
os.environ["QT_QPA_PLATFORM"] = "xcb"
# input dictionary to configure Qiskit Chemistry for the chemistry problem
qiskit_chemistry_dict = {
'problem': {'random_seed': 750},
'driver' : {'name': 'PYSCF'},
'PYSCF': {'atom': '', 'basis' : 'sto3g'},
'operator': {'name': 'hamiltonian',
'transformation': 'full',
'qubit_mapping': 'parity',
'two_qubit_reduction': True},
'algorithm': {},
}
molecule = 'H .0 .0 -{0}; H .0 .0 {0}'
algorithms = [{'name': 'VQE','operator_mode': 'paulis'},
{'name': 'ExactEigensolver'}
]
optimizer = {'name': 'SPSA', 'max_trials': 200}
variational_form = {'name': 'RYRZ', 'depth': 3, 'entanglement': 'full'}
backend = {'provider': 'qiskit.BasicAer',
'name': 'qasm_simulator',
'shots': 1024}
start = 0.5 # start distance
increment = 0.5 # how much to increase distance by
steps = 20 # number of steps to increase by
energies = np.empty([len(algorithms), steps+1])
hf_energies = np.empty(steps+1)
distances = np.empty(steps+1)
print('Processing step __', end='')
for i in range(steps+1):
print('\b\b{:2d}'.format(i), end='',flush=True)
d = start + i*increment/steps
qiskit_chemistry_dict['PYSCF']['atom'] = molecule.format(d/2)
for j in range(len(algorithms)):
qiskit_chemistry_dict['algorithm'] = algorithms[j]
if algorithms[j]['name'] == 'VQE':
qiskit_chemistry_dict['optimizer'] = optimizer
qiskit_chemistry_dict['variational_form'] = variational_form
qiskit_chemistry_dict['backend'] = backend
else:
# This does no longer work as qiskit.chemistry is deprecated
# The functions may be contained in qiskit_nature
'''
qiskit_chemistry_dict.pop('optimizer')
qiskit_chemistry_dict.pop('variational_form')
qiskit_chemistry_dict.pop('backend')
solver = QiskitChemistry()
result = solver.run(qiskit_chemistry_dict)
energies[j][i] = result['energy']
hf_energies[i] = result['hf_energy']
distances[i] = d
'''
print(' --- complete')
print('Distances: ', distances)
print('Energies: ', energies)
print('Hartree-Fock energies: ', hf_energies)
pylab.plot(distances, hf_energies, label='Hartree-Fock')
for j in range(len(algorithms)):
pylab.plot(distances, energies[j], label=algorithms[j])
pylab.xlabel('Interatomic distance (Angstrom)')
pylab.ylabel('Energy (Hartree)')
pylab.title('H2 Ground State Energy')
pylab.legend(loc='upper right')
draw()
show(block=True)
pylab.plot(distances, np.subtract(hf_energies, energies[1]), label='Hartree-Fock')
pylab.plot(distances, np.subtract(energies[0], energies[1]), label=algorithms[0])
pylab.xlabel('Interatomic distance (Angstrom)')
pylab.ylabel('Energy (Hartree)')
pylab.title('Energy difference from ExactEigensolver')
pylab.legend(loc='upper left')
draw()
show(block=True)
|
https://github.com/benkoehlL/Qiskit_Playground
|
benkoehlL
|
'''
This program implements the quantum Fourier transform (QFT)
'''
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, IBMQ
from qiskit.visualization import circuit_drawer as drawer
from qiskit.tools.visualization import plot_histogram
from qiskit import execute
from qiskit import Aer
import numpy as np
import time, os, shutil
from matplotlib.pyplot import plot, draw, show
def QFT(q, c, n):
qc = QuantumCircuit(q,c)
# First get the most significant bit
for k in range(n):
j = n - k
# now add the Hadamard transform to qubit j-1
qc.h(q[j-1])
# now each qubit from the lowest significance
# takes one conditional phase shift
for i in reversed(range(j-1)):
qc.cp(2*np.pi/2**(j-i), q[i], q[j-1])
# Finally swap the qubits
for i in range(n//2):
qc.swap(q[i], q[n-i-1])
return qc
# QFT is represented in a matrix form with 2^n rows and columns
# where n represents the number of qubits
def QFTmatrix(n):
qft = np.zeros([2**n,2**n], dtype=complex)
for i in range(2**n):
for k in range(2**n):
qft[i,k] = np.exp(i*k*2*2j*np.pi/(2**n))
return(1/np.sqrt(2**n)*qft)
def QFTcircuit(n):
q = QuantumRegister(n, "q")
c = ClassicalRegister(n, "c")
qc = QFT(q, c, n)
backend = Aer.get_backend('unitary_simulator')
job = execute(qc, backend)
actual = job.result().get_unitary()
np.around(actual, 2)
expected = QFTmatrix(n)
delta = actual - expected
print("Deviation: ", round(np.linalg.norm(delta), 10))
return qc
LaTex_folder_QFT = str(os.getcwd())+'/Latex_quantum_gates/Quantum_Fourier_transform/'
if not os.path.exists(LaTex_folder_QFT):
os.makedirs(LaTex_folder_QFT)
else:
shutil.rmtree(LaTex_folder_QFT)
os.makedirs(LaTex_folder_QFT)
n=4
qc = QFTcircuit(n)
# create a LaTex file for the algorithm
LaTex_code = qc.draw(output='latex_source', initial_state=True, justify=None) # draw the circuit
f_name = 'Quantum_Four_transform_'+str(n)+'qubits.tex'
with open(LaTex_folder_QFT+f_name, 'w') as f:
f.write(LaTex_code)
n = 4
q = QuantumRegister(n, "x")
c = ClassicalRegister(n, "c")
qftCircuit = QFT(q, c, n)
initCircuit = QuantumCircuit(q, c)
for qubit in q:
initCircuit.h(qubit)
initCircuit.barrier(q)
qc = QuantumCircuit.compose(initCircuit, qftCircuit)
qc.barrier(q)
qc.measure(q, c)
# on simulator
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend)
k = job.result().get_counts()
print(k)
# on a real quantum computer
provider = IBMQ.load_account()
backend = provider.backend.ibmq_lima
print("Status of backened: ", backend.status())
job = execute(qc, backend=backend, shots = 1024)
lapse = 0
print("This step might take some time.")
time.sleep(3)
interval = 60
while((job.status().name != 'DONE')
and (job.status().name != 'Cancelled')
and (job.status().name != 'ERROR')):
print('Status @ {} seconds'.format(interval * lapse))
print(job.status())
print(job.queue_position())
time.sleep(interval)
lapse +=1
print(job.status())
plt = plot_histogram(job.result().get_counts())
|
https://github.com/benkoehlL/Qiskit_Playground
|
benkoehlL
|
'''
This program realises the quantum k-means algorithm
'''
import numpy as np
from qiskit import *
from qiskit.tools.visualization import plot_histogram
from matplotlib.pyplot import plot, draw, show
circuit_name = 'k_means'
backend = Aer.get_backend('qasm_simulator')
theta_list = [0.01, 0.02, 0.03, 0.04, 0.05,
1.31, 1.32, 1.33, 1.34, 1.35]
qr = QuantumRegister(5,'q')
cr = ClassicalRegister(5, 'c')
qc = QuantumCircuit(qr, cr, name=circuit_name)
# define a loop to compute the distance between each pair of points
for i in range(len(theta_list)-1):
for j in range(1,len(theta_list)-i):
# set the parameters theta about different points
theta_1 = theta_list[i]
theta_2 = theta_list[i+j]
qc.h(qr[2])
qc.h(qr[1])
qc.h(qr[4])
qc.u3(theta_1, np.pi, np.pi, qr[1])
qc.u3(theta_2, np.pi, np.pi, qr[4])
qc.cswap(qr[2], qr[1], qr[4])
qc.h(qr[2])
qc.measure(qr[2], cr[2])
qc.reset(qr)
job = execute(qc, backend=backend, shots=1024)
result = job.result()
print(result.get_counts())
print('theta_1: ', theta_1, '\t', 'theta_2: ', theta_2)
plot_histogram(result.get_counts())
|
https://github.com/benkoehlL/Qiskit_Playground
|
benkoehlL
|
'''
This program uses quantum computing to solve a linear system of equations
'''
import numpy as np
from qiskit import *
from qiskit.tools.visualization import plot_histogram
from matplotlib.pyplot import plot, draw, show
circuit_name = 'solve_linear_system'
backend = Aer.get_backend('qasm_simulator')
qr = QuantumRegister(4, 'q')
cr = ClassicalRegister(4, 'c')
qc = QuantumCircuit(qr, cr, name=circuit_name)
# initilise times that we get the result vector
# and duration T of the manipulation
n0 = 0
n1 = 0
T = 10
for i in range(T):
# set the input |b> state
qc.x(qr[2])
# set the phase estimation circuit
qc.h(qr[0])
qc.h(qr[1])
qc.p(np.pi, qr[0])
qc.p(np.pi/2, qr[1])
qc.cx(qr[1], qr[2])
# The qunatum inverse Fourier transform
qc.h(qr[0])
qc.cp(-np.pi/2, qr[0], qr[1])
qc.h(qr[1])
# R (lambda^-1) rotation
qc.x(qr[1])
qc.cu3(np.pi/16, 0, 0, qr[0], qr[3])
qc.cu3(np.pi/8, 0, 0, qr[1], qr[3])
# uncompuation
qc.x(qr[1])
qc.h(qr[1])
qc.cp(np.pi/2, qr[0], qr[1])
qc.h(qr[0])
qc.cx(qr[1], qr[2])
qc.p(-np.pi/2, qr[1])
qc.p(-np.pi, qr[0])
qc.h(qr[1])
qc.h(qr[0])
# measure the whole quantum register
qc.measure(qr, cr)
job = execute(qc, backend=backend, shots=8192,)
result = job.result()
# get the sum of all results
n0 += result.get_counts(circuit_name)['1000']
n1 += result.get_counts(circuit_name)['1100']
#plot_histogram(result.get_counts())
#draw()
#show(block=True)
# reset the circuit
qc.reset(qr)
# calculate the scale of the elements in result vector and print it
p = n0/n1
print('n0 = ', n0, '\t','n1 = ', n1, '\t','p = ', p)
|
https://github.com/benkoehlL/Qiskit_Playground
|
benkoehlL
|
'''
This is a implementation of the quantum teleportation algorithm
'''
from qiskit import *
from qiskit.visualization import plot_histogram
import os, shutil, numpy
from matplotlib.pyplot import plot, draw, show
LaTex_folder_Quantum_Teleportation = str(os.getcwd())+'/Latex_quantum_gates/Quantum_Teleportation/'
if not os.path.exists(LaTex_folder_Quantum_Teleportation):
os.makedirs(LaTex_folder_Quantum_Teleportation)
else:
shutil.rmtree(LaTex_folder_Quantum_Teleportation)
os.makedirs(LaTex_folder_Quantum_Teleportation)
qc = QuantumCircuit(3,3)
## prepare the state to be teleported
phi = 0*numpy.pi
theta= 0.5*numpy.pi
lam = 0*numpy.pi
qc.u(phi=phi, theta=theta,lam=lam,qubit=0)
## teleport the state
qc.barrier()
qc.h(1)
qc.cx(1,2)
qc.cz(0,1)
qc.h(0)
qc.h(1)
qc.barrier()
qc.measure([0,1],[0,1])
qc.barrier()
qc.x(2).c_if(0,1)
qc.z(2).c_if(1,1)
qc.h(2)
qc.measure(2,2)
LaTex_code = qc.draw(output='latex_source', initial_state=True, justify=None) # draw the circuit
f_name = 'quantum_teleportation.tex'
with open(LaTex_folder_Quantum_Teleportation+f_name, 'w') as f:
f.write(LaTex_code)
# simulation
simulator = Aer.get_backend('qasm_simulator')
result = execute(qc, backend=simulator, shots=100000).result()
counts = {'0':0,
'1': 0}
print(result.get_counts().keys())
for key, value in result.get_counts().items():
if(key[0] == '0'):
counts['0'] += value
else:
counts['1'] += value
print(counts)
plt = plot_histogram(counts)
draw()
show(block=True)
|
https://github.com/benkoehlL/Qiskit_Playground
|
benkoehlL
|
'''
This program sets up the circuits for the randamised benchmarking routine
'''
import qiskit
import numpy as np
import os, shutil
import matplotlib.pyplot as plt
from matplotlib.pyplot import draw, show
import qiskit.ignis.verification.randomized_benchmarking as rb
from qiskit_aer.noise import NoiseModel
from qiskit_aer.noise.errors.standard_errors import depolarizing_error, thermal_relaxation_error
os.environ["QT_QPA_PLATFORM"] = "xcb" # for Linux only
folder_RBM = os.getcwd()+'/RBM/'
if not os.path.exists(folder_RBM):
os.makedirs(folder_RBM)
else:
shutil.rmtree(folder_RBM)
os.makedirs(folder_RBM)
## Generate RB circuits (2Q RB)
# number of qubits
nQ=3
rb_opts = {}
# Number of Cliffords in the sequence
rb_opts['length_vector'] = [1, 10, 20, 50, 75, 100, 125, 150, 175, 200]
# Number of seeds (random sequences)
rb_opts['nseeds'] = 5
# Default pattern
rb_opts['rb_pattern'] = [ [0, 1, 2] ]
rb_circs, xdata = rb.randomized_benchmarking_seq(**rb_opts)
print(len(rb_circs))
for i in range(len(rb_circs)):
for n, circuit in enumerate(rb_circs[i]):
filename = str(folder_RBM+'seed_'+str(i)+'_m_'+str(rb_opts['length_vector'][n]+1)+'.qasm')
circuit.qasm(filename=filename)
# Run on a noisy simulator
noise_model = NoiseModel()
# Depolarizing error on the gates u2, u3 and cx (assuming the u1 is virtual-Z gate and no error)
p1Q = 0.002
p2Q = 0.01
noise_model.add_all_qubit_quantum_error(depolarizing_error(p1Q, 1), 'u2')
noise_model.add_all_qubit_quantum_error(depolarizing_error(2 * p1Q, 1), 'u3')
noise_model.add_all_qubit_quantum_error(depolarizing_error(p2Q, 2), 'cx')
backend = qiskit.Aer.get_backend('qasm_simulator')
# Create the RB fitter
backend = qiskit.Aer.get_backend('qasm_simulator')
basis_gates = ['u1','u2','u3','cx']
shots = 200
transpiled_circs_list = []
rb_fit = rb.RBFitter(None, xdata, rb_opts['rb_pattern'])
for rb_seed, rb_circ_seed in enumerate(rb_circs):
print('Compiling seed %d'%rb_seed)
new_rb_circ_seed = qiskit.compiler.transpile(rb_circ_seed, basis_gates=basis_gates)
transpiled_circs_list.append(new_rb_circ_seed)
print('Simulating seed %d'%rb_seed)
## THIS ONE IS FROM OUR RESULTS NOT THE BACKEND
job = qiskit.execute(new_rb_circ_seed,
backend,
shots=shots,
noise_model=noise_model)
# Add data to the fitter
rb_fit.add_data(job.result())
print('After seed %d, alpha: %f, EPC: %f'%(rb_seed,rb_fit.fit[0]['params'][1], rb_fit.fit[0]['epc']))
plt.figure(figsize=(8, 6))
ax = plt.subplot(1, 1, 1)
# Plot the essence by calling plot_rb_data
rb_fit.plot_rb_data(0, ax=ax, add_label=True, show_plt=False)
# Add title and label
ax.set_title('%d Qubit RB'%(nQ), fontsize=18)
plt.show()
|
https://github.com/benkoehlL/Qiskit_Playground
|
benkoehlL
|
'''
This program implements Shor's algorithm which determines
a number's prime factors. [unfinished]
'''
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit,\
execute, IBMQ, Aer
from qiskit.visualization import circuit_drawer as drawer
from qiskit.tools.visualization import plot_histogram
import numpy as np
from matplotlib.pyplot import plot, draw, show
M = 15
a = 3
e = 8
print("a**2 mod M = ", (a**2)%M)
def NQbitCircuit(p, w, c):
circuit = QuantumCircuit(w, p, c)
# prepare initial state 1 in primary register
circuit.x(p[0])
circuit.barrier(p)
circuit.barrier(w)
# add a Hadamard gate to the working register
for qubit in w:
circuit.h(qubit)
# add additional multiplication by 'a' to the primary register
circuit.cx(w[0], p[1])
circuit.cx(w[0], p[3])
return(circuit)
def NBitQFT(q, c, n):
circuit = QuantumCircuit(q, c)
# Start with the most significant bit
for k in range(n):
j = n-k
# add Hadamard to qubit j-1
circuit.h(q[j-1])
# there is one conditional rotation
# for each qubit with lower significance
for i in reversed(range(j-1)):
circuit.cp(2*np.pi/2**(j-i), q[i], q[j-1])
# swap qubits
for i in range(n//2):
circuit.swap(q[i], q[n-i-1])
return circuit
def Shor_Algorithm(a, n):
# create registers and circuit
p = QuantumRegister(4, 'p')
w = QuantumRegister(n, 'w')
c = ClassicalRegister(n, "c")
circuit = QuantumCircuit(w, p, c)
# add Hadamard gates to working registers
for qubit in w:
circuit.h(qubit)
# add multiplication by 'a' to primary register
circuit.cx(w[0], p[1])
circuit.cx(w[0], p[3])
# build the QFT part starting with the most significant bit
for k in range(n):
j = n - k
# add Hadamard to qubit j-1
if(j-1) != 2:
circuit.h(w[j-1])
# there is one conditional rotation
# for each qubit with lower significance
for i in reversed(range(j-1)):
circuit.cp(2*np.pi/2**(j-i), w[i], w[j-1])
# add the measurements
circuit.barrier(w)
for i in range(len(w)):
circuit.measure(w[i], c[len(w)-1-i])
return circuit
p = QuantumRegister(4, 'p')
w = QuantumRegister(3, 'w')
c = ClassicalRegister(len(w), 'c')
qc = NQbitCircuit(p, w, c)
drawer(qc, output='mpl')
draw()
show(block=True)
backend = Aer.get_backend('statevector_simulator')
job = execute(qc, backend)
state = np.around(job.result().get_statevector(), 2)
print('Non-zero states:')
for i in range(2**(len(p)+len(w))):
if(state[i] != 0):
print("|",i,"> --->", state[i])
print('Expected amplitudes up to normalisation:')
for s in range(2**(len(w))):
x = a**s % M
print("|", x*e + s, "> = |", x, ">|", s, ">")
# // is the floor division
print('Non-zero states and their decomposition: |s> = |s // e> |s mod e> :')
for i in range(2**(len(w)+len(p))):
if(state[i] != 0):
# // is the floor division
print("|", i, "> = |", i // e, ">|", i % e, "> ---> ", state[i])
qc = QuantumCircuit.compose(qc, NBitQFT(w, c,3))
qc.barrier(w)
qc.measure(w, c)
drawer(qc, output='mpl')
draw()
show(block=True)
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend)
counts = job.result().get_counts()
plt = plot_histogram(counts)
draw()
show(block=True)
qc = Shor_Algorithm(a,3)
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend)
counts = job.result().get_counts()
plt = plot_histogram(counts)
draw()
show(block=True)
|
https://github.com/benkoehlL/Qiskit_Playground
|
benkoehlL
|
from qiskit import *
import matplotlib.pyplot as plt
from matplotlib.pyplot import plot, draw, show
import numpy as np
from qiskit.providers.ibmq import least_busy
from qiskit.tools.visualization import plot_histogram
import os, shutil
def dot(s,z):
sum = 0
for i in range(len(str(s))):
sum += int(s[i])*int(z[i])
return(sum%2)
LaTex_folder_Simon = str(os.getcwd())+'/Latex_quantum_gates/Simon_algorithm/'
if not os.path.exists(LaTex_folder_Simon):
os.makedirs(LaTex_folder_Simon)
else:
shutil.rmtree(LaTex_folder_Simon)
os.makedirs(LaTex_folder_Simon)
s = '10'
s_len = len(str(s))
# create quantum register which is double the size of the secret string
qr = QuantumRegister(s_len, 'q')
qr_ancilla = QuantumRegister(s_len, 'qa')
cr = ClassicalRegister(2*s_len, 'c')
qc = QuantumCircuit(qr, qr_ancilla, cr)
# First Hadamard phase
for qubit in qr:
qc.h(qubit)
# Apply barrier just to separate
qc.barrier()
# oracle for s
for qubit1 in qr:
for qubit2 in qr_ancilla:
qc.cx(qubit1, qubit2)
qc.barrier()
# measure ancilla qubits
for i, qubit in enumerate(qr_ancilla):
qc.measure(qubit, cr[i+s_len])
qc.barrier()
# another Hadamard phase
for qubit in qr:
qc.h(qubit)
qc.barrier()
# Measure the input register
for i, qubit in enumerate(qr):
qc.measure(qubit, cr[i])
qc.draw(output='mpl')
draw()
show(block=True)
# create a LaTex file for the algorithm
LaTex_code = qc.draw(output='latex_source', initial_state=True, justify=None)
f_name = 'Simon_algorithm.tex'
with open(LaTex_folder_Simon+f_name, 'w') as f:
f.write(LaTex_code)
# simulate
backend = BasicAer.get_backend('qasm_simulator')
shots = 1000
results = execute(qc, backend=backend, shots = shots).result()
answer = results.get_counts()
# Categorise measurements by input register values
answer_plot = {}
for measureresult in answer.keys():
measureresults_input = measureresult[s_len:]
if measureresults_input in answer_plot:
answer_plot[measureresults_input] += answer[measureresult]
else:
answer_plot[measureresults_input] = answer[measureresult]
# Plot the categorised results
print(answer_plot)
plt = plot_histogram(answer_plot)
draw()
show(block=True)
# Calculate the dot product of the most significant results
print('s , z , s.z (mod 2)')
for z_rev in answer_plot:
if answer_plot[z_rev] >= 0.1*shots:
z = z_rev[::-1]
print( '{}, {}, {}.{} = {}'.format(s, z, s, z, dot(s,z)))
|
https://github.com/benkoehlL/Qiskit_Playground
|
benkoehlL
|
from qiskit import Aer, execute, QuantumRegister, ClassicalRegister,\
QuantumCircuit
from qiskit.visualization import plot_bloch_multivector
from matplotlib.pyplot import plot, draw, show
# list all the available simulation environments
for backend in Aer.backends():
print(backend.name())
if(backend.name() == 'statevector_simulator'):
# load a arbitrary quantum circuit of your choice (here Bell state preparation)
for not0 in [False,True]:
for not1 in [False,True]:
print(not0, '\t', not1)
qr = QuantumRegister(2,name='q')
cr = ClassicalRegister(2, name='c')
qc = QuantumCircuit(qr, cr)
if(not0):
qc.x(qr[0])
if(not1):
qc.x(qr[1])
qc.h(qr[0])
qc.cx(qr[0],qr[1])
qc.measure(qr,cr)
result = execute(qc, backend).result()
stateVectorResult = result.get_statevector(qc)
plot_bloch_multivector(stateVectorResult)
qc.draw(output='mpl')
draw()
show(block=True)
if(backend.name() == 'pulse_simulator'):
print("I do not know how to deal with this yet :)")
else:
# load a arbitrary quantum circuit of your choice (here Bell state preparation)
for not0 in [False,True]:
for not1 in [False,True]:
print(not0, '\t', not1)
qr = QuantumRegister(2,name='q')
cr = ClassicalRegister(2, name='c')
qc = QuantumCircuit(qr, cr)
if(not0):
qc.x(qr[0])
if(not1):
qc.x(qr[1])
qc.h(qr[0])
qc.cx(qr[0],qr[1])
if(backend.name() != 'aer_simulator_unitary'
and backend.name() != 'aer_simulator_superop'
and backend.name() != 'unitary_simulator'):
qc.measure(qr,cr)
job = execute(qc, backend, shots=1000)
result = job.result()
if(backend.name() != 'aer_simulator_unitary'
and backend.name() != 'aer_simulator_superop'
and backend.name() != 'unitary_simulator'):
count = result.get_counts()
print(count)
|
https://github.com/quantumyatra/quantum_computing
|
quantumyatra
|
# import dimod
# import numpy as np
# import pylab as plt
linear = {0: -1, 1: -1}
quadratic = {(0, 1): 2}
bqm = dimod.BinaryQuadraticModel(linear, quadratic, 0.0, dimod.BINARY) # 0.0 is the value for offset
bqm_ising = bqm.change_vartype(dimod.SPIN, inplace=False)
response = dimod.ExactSolver().sample(bqm)
for sample, energy in response.data(['sample', 'energy']):
print(sample, energy)
def Test_offset_values(offset):
linear = {0: -1, 1: -1}
quadratic = {(0, 1): 2}
bqm = dimod.BinaryQuadraticModel(linear, quadratic, offset, dimod.BINARY) # 0.0 is the value for offset
bqm_ising = bqm.change_vartype(dimod.SPIN, inplace=False)
response = dimod.ExactSolver().sample(bqm)
for sample, energy in response.data(['sample', 'energy']):
print(sample, energy)
for offset in [0., 1., 10]:
print ('offset=',offset)
Test_offset_values(offset)
Q = {('x1', 'x2'): 1, ('x1', 'z'): -2, ('x2', 'z'): -2, ('z', 'z'): 3}
from dwave.system import DWaveSampler, EmbeddingComposite
sampler = DWaveSampler()
#from dwave.system import DWaveSampler, EmbeddingComposite
#sampler = DWaveSampler()
#sampler_embedded = EmbeddingComposite(sampler)
linear = {1: 1, 2: 2, 3: 3, 4: 4} # linear term in the Ising hamiltonian h_i s_i terms
# And the quadratic terms s_i \dot s_j terms
quadratic = {(1, 2): 12, (1, 3): 13, (1, 4): 14,
(2, 3): 23, (2, 4): 24,
(3, 4): 34}
bqm_k4 = dimod.BinaryQuadraticModel(linear, quadratic, 0.5, dimod.SPIN)
#bqm_k4
bqm_k4.vartype
import dimod
>>> linear = {1: 1, 2: 2, 3: 3, 4: 4}
>>> quadratic = {(1, 2): 12, (1, 3): 13, (1, 4): 14,
... (2, 3): 23, (2, 4): 24,
... (3, 4): 34}
>>> bqm_k4 = dimod.BinaryQuadraticModel(linear, quadratic, 0.5, dimod.SPIN)
>>> bqm_k4.vartype
<Vartype.SPIN: frozenset([1, -1])>
>>> len(bqm_k4.linear)
4
>>> bqm_k4.contract_variables(2, 3)
>>> len(bqm_k4.linear)
3
>>> bqm_no3_qubo = bqm_k4.binary
|
https://github.com/quantumyatra/quantum_computing
|
quantumyatra
|
# Useful additional packages
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from math import pi
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.tools.visualization import circuit_drawer
from qiskit.quantum_info import state_fidelity
from qiskit import BasicAer
backend = BasicAer.get_backend('unitary_simulator')
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.u3(pi/2,pi/2,pi/2,q)
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.u2(pi/2,pi/2,q)
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.u1(pi/2,q)
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.iden(q)
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.x(q)
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.y(q)
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.z(q)
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.h(q)
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.s(q)
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.sdg(q)
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.t(q)
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.tdg(q)
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.rx(pi/2,q)
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.ry(pi/2,q)
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.rz(pi/2,q)
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/quantumyatra/quantum_computing
|
quantumyatra
|
# Useful additional packages
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from math import pi
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit import Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.visualization import *
from qiskit.providers.aer import UnitarySimulator
from qiskit.tools.visualization import circuit_drawer
from qiskit.quantum_info import state_fidelity
from qiskit import BasicAer
backend = BasicAer.get_backend('unitary_simulator')
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
groverCircuit = QuantumCircuit(qr,cr)
groverCircuit.h(qr)
groverCircuit.draw(output="mpl")
job = execute(groverCircuit, backend)
job.result().get_unitary(groverCircuit, decimals=3)
groverCircuit.measure(qr,cr)
groverCircuit.draw(output="mpl")
simulator = Aer.get_backend('qasm_simulator')
result = execute(groverCircuit, simulator).result()
counts = result.get_counts(groverCircuit)
plot_histogram(counts, title='Grover Intermediate measurement')
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
groverCircuit = QuantumCircuit(qr,cr)
groverCircuit.h(qr)
'''oracle w = |00>'''
groverCircuit.x(qr)
groverCircuit.cz(qr[0],qr[1])
groverCircuit.x(qr)
groverCircuit.draw(output="mpl")
job = execute(groverCircuit, backend)
job.result().get_unitary(groverCircuit, decimals=3)
INIT = 0.5*np.array([[1,1,1,1],[1,-1,1,-1],[1,1,-1,-1],[1,-1,-1,1]])
CZ = np.array([[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,-1]])
XX = np.array([[0,0,0,1],[0,0,1,0],[0,1,0,0],[1,0,0,0]])
'''Oracle'''
ORCL = np.dot(XX,np.dot(CZ,XX))
print(ORCL)
'''FUll circuit matrix so far'''
np.dot(ORCL,INIT)
groverCircuit.measure(qr,cr)
groverCircuit.draw(output="mpl")
simulator = Aer.get_backend('qasm_simulator')
result = execute(groverCircuit, simulator).result()
counts = result.get_counts(groverCircuit)
plot_histogram(counts, title='Grover Intermediate measurement')
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
groverCircuit = QuantumCircuit(qr,cr)
groverCircuit.h(qr)
'''oracle w = |00>'''
groverCircuit.x(qr)
groverCircuit.cz(qr[0],qr[1])
groverCircuit.x(qr)
'''Grover Transform'''
groverCircuit.h(qr)
'''Reflection'''
groverCircuit.z(qr)
groverCircuit.cz(qr[0],qr[1])
'''end of Reflection'''
groverCircuit.h(qr)
'''end of Grover Transform'''
groverCircuit.draw(output="mpl")
job = execute(groverCircuit, backend)
job.result().get_unitary(groverCircuit, decimals=3)
HH = 0.5*np.array([[1,1,1,1],[1,-1,1,-1],[1,1,-1,-1],[1,-1,-1,1]])
ZZ = np.array([[1,0,0,0],[0,-1,0,0],[0,0,-1,0],[0,0,0,1]])
'''Grover Transform'''
GT = np.dot(HH,np.dot(CZ,np.dot(ZZ,HH)))
print(GT)
'''FUll circut matrix'''
np.dot(INIT,np.dot(ORCL,GT))
simulator = Aer.get_backend('qasm_simulator')
result = execute(groverCircuit, simulator).result()
counts = result.get_counts(groverCircuit)
plot_histogram(counts, title='Grover Intermediate measurement')
|
https://github.com/quantumyatra/quantum_computing
|
quantumyatra
|
%matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumCircuit,QuantumRegister,ClassicalRegister, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
def qft_1():
n=1
qc = QuantumCircuit()
q = QuantumRegister(n, 'q')
c = ClassicalRegister(n, 'c')
qc.add_register(q)
qc.add_register(c)
qc.h(q[0])
return qc,q,c
qc,q,c = qft_1()
qc.measure(q[0], c[0])
# Change the background color in mpl
style = {'backgroundcolor': 'lightgreen'}
qc.draw(output='mpl', style = style)
simulator = Aer.get_backend('qasm_simulator')
result = execute(qc, simulator).result()
counts = result.get_counts(qc)
plot_histogram(counts, title='QFT counts')
from qiskit.providers.aer import UnitarySimulator
qc,q,c = qft_1()
# Select the UnitarySimulator from the Aer provider
simulator = Aer.get_backend('unitary_simulator')
# Execute and get counts
result = execute(qc, simulator).result()
unitary = result.get_unitary(qc)
print( unitary)
HI = np.array([[1,0,1,0],[0,1,0,1],[1,0,-1,0],[0,1,0,-1]])
CU1 = np.array([[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,0.+1.j]])
IH = np.array([[1,1,0,0],[1,-1,0,0],[0,0,1,1],[0,0,1,-1]])
SWAP = np.array([[1,0,0,0],[0,0,1,0],[0,1,0,0],[0,0,0,1]])
np.dot(HI,np.dot(CU1,np.dot(IH,SWAP)))
import numpy as np
def qft_2():
n=2
qc = QuantumCircuit()
q = QuantumRegister(n, 'q')
c = ClassicalRegister(n, 'c')
qc.add_register(q)
qc.add_register(c)
qc.h(q[1])
qc.cu1(np.pi / 2, q[0], q[1])
qc.h(q[0])
qc.swap(q[0], q[1])
return qc,q,c
qc,q,c = qft_2()
qc.measure(q, c)
# Change the background color in mpl
style = {'backgroundcolor': 'lightgreen'}
qc.draw(output='mpl', style = style)
simulator = Aer.get_backend('qasm_simulator')
result = execute(qc, simulator).result()
counts = result.get_counts(qc)
plot_histogram(counts, title='QFT counts')
from qiskit.providers.aer import UnitarySimulator
qc,q,c = qft_2()
# Select the UnitarySimulator from the Aer provider
simulator = Aer.get_backend('unitary_simulator')
# Execute and get counts
result = execute(qc, simulator).result()
unitary = result.get_unitary(qc)
print( unitary)
def qft_3():
n = 3
qc = QuantumCircuit()
q = QuantumRegister(n, 'q')
c = ClassicalRegister(n, 'c')
qc.add_register(q)
qc.add_register(c)
qc.h(q[2])
qc.cu1(np.pi / 2, q[1], q[2])
qc.h(q[1])
qc.cu1(np.pi / 4, q[0], q[2])
qc.cu1(np.pi / 2, q[0], q[1])
qc.h(q[0])
qc.swap(q[0], q[2])
return qc,q,c
qc,q,c = qft_3()
qc.measure(q,c)
# Change the background color in mpl
style = {'backgroundcolor': 'lightgreen'}
qc.draw(output='mpl', style = style)
simulator = Aer.get_backend('qasm_simulator')
result = execute(qc, simulator).result()
counts = result.get_counts(qc)
plot_histogram(counts, title='QFT counts')
from qiskit.providers.aer import UnitarySimulator
qc,q,c = qft_3()
# Select the UnitarySimulator from the Aer provider
simulator = Aer.get_backend('unitary_simulator')
# Execute and get counts
result = execute(qc, simulator).result()
unitary = result.get_unitary(qc)
print( unitary)
def qft_4():
n = 4
qc = QuantumCircuit()
q = QuantumRegister(n, 'q')
c = ClassicalRegister(n, 'c')
qc.add_register(q)
qc.add_register(c)
qc.h(q[3])
qc.cu1(np.pi / 2, q[2], q[3])
qc.h(q[2])
qc.cu1(np.pi / 4, q[1], q[3])
qc.cu1(np.pi / 2, q[1], q[2])
qc.h(q[1])
qc.cu1(np.pi / 8, q[0], q[3])
qc.cu1(np.pi / 4, q[0], q[2])
qc.cu1(np.pi / 2, q[0], q[1])
qc.h(q[0])
qc.swap(q[0], q[3])
qc.swap(q[1], q[2])
return qc,q,c
qc,q,c = qft_4()
qc.measure(q,c)
# Change the background color in mpl
style = {'backgroundcolor': 'lightgreen'}
qc.draw(output='mpl', style = style)
simulator = Aer.get_backend('qasm_simulator')
result = execute(qc, simulator).result()
counts = result.get_counts(qc)
plot_histogram(counts, title='QFT counts')
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import Aer, execute
from qiskit.providers.aer import UnitarySimulator
qc = qft_circuit(4)
# Select the UnitarySimulator from the Aer provider
simulator = Aer.get_backend('unitary_simulator')
# Execute and get counts
result = execute(qc, simulator).result()
unitary = result.get_unitary(qc)
print( unitary)
|
https://github.com/quantumyatra/quantum_computing
|
quantumyatra
|
# Useful additional packages
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from math import pi
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.tools.visualization import circuit_drawer
from qiskit.quantum_info import state_fidelity
from qiskit import BasicAer
backend = BasicAer.get_backend('unitary_simulator')
q = QuantumRegister(2)
qc = QuantumCircuit(q)
qc.cx(q[0],q[1])
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.cy(q[0],q[1])
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.cz(q[0],q[1])
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.ch(q[0],q[1])
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.crz(pi/2,q[0],q[1])
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.cu1(pi/2,q[0], q[1])
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.cu3(pi/2, pi/2, pi/2, q[0], q[1])
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.swap(q[0], q[1])
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/quantumyatra/quantum_computing
|
quantumyatra
|
# Useful additional packages
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from math import pi
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.tools.visualization import circuit_drawer
from qiskit.quantum_info import state_fidelity
from qiskit import BasicAer
backend = BasicAer.get_backend('unitary_simulator')
q = QuantumRegister(3)
qc = QuantumCircuit(q)
qc.ccx(q[0], q[1], q[2])
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.cswap(q[0], q[1], q[2])
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/quantumyatra/quantum_computing
|
quantumyatra
|
# Useful additional packages
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from math import pi
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.tools.visualization import circuit_drawer
from qiskit.quantum_info import state_fidelity
from qiskit import BasicAer
backend = BasicAer.get_backend('unitary_simulator')
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.u3(pi/2,pi/2,pi/2,q)
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.u3(pi/2,pi/2,pi/2,q)
qc.u3(pi/2,pi/2,pi/2,q)
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
|
https://github.com/quantumyatra/quantum_computing
|
quantumyatra
|
# Useful additional packages
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from math import pi
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.tools.visualization import circuit_drawer
from qiskit.quantum_info import state_fidelity
from qiskit import BasicAer
backend = BasicAer.get_backend('unitary_simulator')
q = QuantumRegister(2)
qc = QuantumCircuit(q)
qc.u3(pi/2,pi/2,pi/2,q[0])
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
q = QuantumRegister(2)
qc = QuantumCircuit(q)
qc.u3(pi/2,pi/2,pi/2,q[1])
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
q = QuantumRegister(2)
qc = QuantumCircuit(q)
qc.u3(pi/2,pi/2,pi/2,q[0])
qc.u3(pi/2,pi/2,pi/2,q[1])
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
q = QuantumRegister(2)
qc = QuantumCircuit(q)
qc.u3(pi/2,pi/2,pi/2,q[0])
qc.u3(pi/2,pi/2,pi/2,q[0])
qc.u3(pi/2,pi/2,pi/2,q[1])
qc.u3(pi/2,pi/2,pi/2,q[1])
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
|
https://github.com/quantumyatra/quantum_computing
|
quantumyatra
|
# Useful additional packages
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from math import pi
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.tools.visualization import circuit_drawer
from qiskit.quantum_info import state_fidelity
from qiskit import BasicAer
backend = BasicAer.get_backend('unitary_simulator')
q = QuantumRegister(3)
qc = QuantumCircuit(q)
qc.u3(pi/2,pi/2,pi/2,q[0])
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
q = QuantumRegister(3)
qc = QuantumCircuit(q)
qc.u3(pi/2,pi/2,pi/2,q[1])
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
q = QuantumRegister(3)
qc = QuantumCircuit(q)
qc.u3(pi/2,pi/2,pi/2,q[2])
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
q = QuantumRegister(3)
qc = QuantumCircuit(q)
qc.u3(pi/2,pi/2,pi/2,q[0])
qc.u3(pi/2,pi/2,pi/2,q[1])
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
q = QuantumRegister(3)
qc = QuantumCircuit(q)
qc.u3(pi/2,pi/2,pi/2,q[0])
qc.u3(pi/2,pi/2,pi/2,q[1])
qc.u3(pi/2,pi/2,pi/2,q[2])
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
q = QuantumRegister(3)
qc = QuantumCircuit(q)
qc.u3(pi/2,pi/2,pi/2,q[0])
qc.u3(pi/2,pi/2,pi/2,q[0])
qc.u3(pi/4,pi/4,pi/4,q[1])
qc.u3(3*pi/4,3*pi/4,3*pi/4,q[1])
qc.u3(pi/6,pi/6,pi/6,q[2])
qc.u3(5*pi/6,5*pi/6,5*pi/6,q[2])
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
|
https://github.com/quantumyatra/quantum_computing
|
quantumyatra
|
# Useful additional packages
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from math import pi
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.tools.visualization import circuit_drawer
from qiskit.quantum_info import state_fidelity
from qiskit import BasicAer
backend = BasicAer.get_backend('unitary_simulator')
q = QuantumRegister(2)
qc = QuantumCircuit(q)
qc.cu1(pi/2,q[0], q[1])
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
q = QuantumRegister(3)
qc = QuantumCircuit(q)
qc.u3(pi/2,pi/2,pi/2,q[0])
qc.cu1(pi/2,q[0], q[1])
qc.u3(pi/2,pi/2,pi/2,q[1])
qc.cu1(pi/2,q[1], q[2])
qc.u3(pi/2,pi/2,pi/2,q[2])
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
q = QuantumRegister(4)
qc = QuantumCircuit(q)
qc.u3(pi/2,pi/2,pi/2,q[0])
qc.cu1(pi/2,q[0], q[1])
qc.u2(pi/2,pi/2,q[1])
qc.u1(pi/2,q[2])
qc.x(q[0])
qc.ccx(q[1],q[2],q[3])
qc.y(q[1])
qc.z(q[2])
qc.cx(q[2],q[3])
qc.z(q[3])
qc.h(q[3])
qc.s(q[0])
qc.cu1(pi/2,q[1], q[2])
qc.swap(q[0],q[2])
qc.cswap(q[0],q[1],q[3])
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
|
https://github.com/quantumyatra/quantum_computing
|
quantumyatra
|
%matplotlib inline
# Importing standard Qiskit libraries and configuring account
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 qiskit.providers.aer import UnitarySimulator
n =1
q = QuantumRegister(n)
c = ClassicalRegister(n)
circ = QuantumCircuit(q,c)
circ.h(q[0])
circ.measure(q,c)
# Change the background color in mpl
style = {'backgroundcolor': 'lightblue'}
circ.draw(output='mpl', style = style)
simulator = Aer.get_backend('qasm_simulator')
result = execute(circ, simulator).result()
counts = result.get_counts(circ)
plot_histogram(counts, title='Bell-State counts')
n =1
q = QuantumRegister(n)
c = ClassicalRegister(n)
circ = QuantumCircuit(q,c)
circ.h(q[0])
# Select the UnitarySimulator from the Aer provider
simulator = Aer.get_backend('unitary_simulator')
# Execute and get counts
result = execute(circ, simulator).result()
unitary = result.get_unitary(circ)
print( unitary)
n =2
q = QuantumRegister(n)
c = ClassicalRegister(n)
circ = QuantumCircuit(q,c)
circ.h(q[0])
circ.measure(q,c)
# Change the background color in mpl
style = {'backgroundcolor': 'lightgreen'}
circ.draw(output='mpl', style = style)
n =2
q = QuantumRegister(n)
c = ClassicalRegister(n)
circ = QuantumCircuit(q,c)
circ.h(q[0])
# Select the UnitarySimulator from the Aer provider
simulator = Aer.get_backend('unitary_simulator')
# Execute and get counts
result = execute(circ, simulator).result()
unitary = result.get_unitary(circ)
print( unitary)
n =2
q = QuantumRegister(n)
c = ClassicalRegister(n)
circ = QuantumCircuit(q,c)
circ.h(q[1])
circ.measure(q,c)
# Change the background color in mpl
style = {'backgroundcolor': 'lightgreen'}
circ.draw(output='mpl', style = style)
n =2
q = QuantumRegister(n)
c = ClassicalRegister(n)
circ = QuantumCircuit(q,c)
circ.h(q[1])
# Select the UnitarySimulator from the Aer provider
simulator = Aer.get_backend('unitary_simulator')
# Execute and get counts
result = execute(circ, simulator).result()
unitary = result.get_unitary(circ)
print( unitary)
n =2
q = QuantumRegister(n)
c = ClassicalRegister(n)
circ = QuantumCircuit(q,c)
circ.h(q[0])
circ.h(q[1])
circ.measure(q,c)
# Change the background color in mpl
style = {'backgroundcolor': 'lightgreen'}
circ.draw(output='mpl', style = style)
simulator = Aer.get_backend('qasm_simulator')
result = execute(circ, simulator).result()
counts = result.get_counts(circ)
plot_histogram(counts, title='Bell-State counts')
n =2
q = QuantumRegister(n)
c = ClassicalRegister(n)
circ = QuantumCircuit(q,c)
circ.h(q[0])
circ.h(q[1])
# Select the UnitarySimulator from the Aer provider
simulator = Aer.get_backend('unitary_simulator')
# Execute and get counts
result = execute(circ, simulator).result()
unitary = result.get_unitary(circ)
print( unitary)
n = 3
q = QuantumRegister(n)
c = ClassicalRegister(n)
circ = QuantumCircuit(q,c)
circ.h(q[0])
circ.h(q[1])
circ.h(q[2])
circ.measure(q,c)
# Change the background color in mpl
style = {'backgroundcolor': 'lightgreen'}
circ.draw(output='mpl', style = style)
simulator = Aer.get_backend('qasm_simulator')
result = execute(circ, simulator).result()
counts = result.get_counts(circ)
plot_histogram(counts, title='Bell-State counts')
n =3
q = QuantumRegister(n)
c = ClassicalRegister(n)
circ = QuantumCircuit(q,c)
circ.h(q[0])
circ.h(q[1])
circ.h(q[2])
# Select the UnitarySimulator from the Aer provider
simulator = Aer.get_backend('unitary_simulator')
# Execute and get counts
result = execute(circ, simulator).result()
unitary = result.get_unitary(circ)
print( unitary)
n = 8
q = QuantumRegister(n)
c = ClassicalRegister(n)
circ = QuantumCircuit(q,c)
for k in range(8):
circ.h(q[k])
circ.measure(q,c)
# Change the background color in mpl
style = {'backgroundcolor': 'lightpink'}
circ.draw(output='mpl', style = style)
simulator = Aer.get_backend('qasm_simulator')
result = execute(circ, simulator).result()
counts = result.get_counts(circ)
plot_histogram(counts, title='Bell-State counts')
n =8
q = QuantumRegister(n)
c = ClassicalRegister(n)
circ = QuantumCircuit(q,c)
for k in range(8):
circ.h(q[k])
# Select the UnitarySimulator from the Aer provider
simulator = Aer.get_backend('unitary_simulator')
# Execute and get counts
result = execute(circ, simulator).result()
unitary = result.get_unitary(circ)
print( unitary)
unitary.shape
|
https://github.com/quantumyatra/quantum_computing
|
quantumyatra
|
%matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumCircuit,QuantumRegister,ClassicalRegister, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
num_qubits = 2;
num_bits = 2;
bell = QuantumCircuit(2,2)
bell.h(0)
bell.cx(0, 1)
bell.measure([0,1], [0,1])
bell.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
result = execute(bell, simulator).result()
counts = result.get_counts(bell)
plot_histogram(counts, title='Bell-State counts')
num_qubits = 2;
num_bits = 2;
bell = QuantumCircuit(2,2)
bell.h(0)
bell.cx(0, 1)
bell.h(1)
bell.cx(0, 1)
bell.measure([0,1], [0,1])
bell.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
result = execute(bell, simulator).result()
counts = result.get_counts(bell)
plot_histogram(counts, title='Bell-State counts')
n =3
q = QuantumRegister(n)
c = ClassicalRegister(n)
circ = QuantumCircuit(q,c)
circ.h(q[0])
circ.cx(q[0], q[1])
circ.h(q[1])
circ.cx(q[1], q[2])
circ.h(q[2])
circ.measure(q,c)
# Change the background color in mpl
style = {'backgroundcolor': 'lightgreen'}
circ.draw(output='mpl', style = style)
simulator = Aer.get_backend('qasm_simulator')
result = execute(circ, simulator).result()
counts = result.get_counts(circ)
plot_histogram(counts, title='Bell-State counts')
|
https://github.com/quantumyatra/quantum_computing
|
quantumyatra
|
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main')
backend = provider.get_backend('ibmq_armonk')
backend_config = backend.configuration()
assert backend_config.open_pulse, "Backend doesn't support Pulse"
dt = backend_config.dt
print(f"Sampling time: {dt*1e9} ns")
backend_defaults = backend.defaults()
import numpy as np
# unit conversion factors -> all backend properties returned in SI (Hz, sec, etc)
GHz = 1.0e9 # Gigahertz
MHz = 1.0e6 # Megahertz
us = 1.0e-6 # Microseconds
ns = 1.0e-9 # Nanoseconds
# We will find the qubit frequency for the following qubit.
qubit = 0
# The sweep will be centered around the estimated qubit frequency.
# The default frequency is given in Hz
# warning: this will change in a future release
center_frequency_Hz = backend_defaults.qubit_freq_est[qubit]
print(f"Qubit {qubit} has an estimated frequency of {center_frequency_Hz / GHz} GHz.")
# scale factor to remove factors of 10 from the data
scale_factor = 1e-14
# We will sweep 40 MHz around the estimated frequency
frequency_span_Hz = 40 * MHz
# in steps of 1 MHz.
frequency_step_Hz = 1 * MHz
# We will sweep 20 MHz above and 20 MHz below the estimated frequency
frequency_min = center_frequency_Hz - frequency_span_Hz / 2
frequency_max = center_frequency_Hz + frequency_span_Hz / 2
# Construct an np array of the frequencies for our experiment
frequencies_GHz = np.arange(frequency_min / GHz,
frequency_max / GHz,
frequency_step_Hz / GHz)
print(f"The sweep will go from {frequency_min / GHz} GHz to {frequency_max / GHz} GHz \
in steps of {frequency_step_Hz / MHz} MHz.")
# samples need to be multiples of 16
def get_closest_multiple_of_16(num):
return int(num + 8 ) - (int(num + 8 ) % 16)
from qiskit import pulse
from qiskit.pulse import pulse_lib
#from qiskit.pulse import library as pulse_lib
from qiskit import pulse # This is where we access all of our Pulse features!
#from qiskit.pulse import Play
# This Pulse module helps us build sampled pulses for common pulse shapes
#from qiskit.pulse import library as pulse_lib
from qiskit.pulse import pulse_lib
# Drive pulse parameters (us = microseconds)
drive_sigma_us = 0.075 # This determines the actual width of the gaussian
drive_samples_us = drive_sigma_us*8 # This is a truncating parameter, because gaussians don't have
# a natural finite length
drive_sigma = get_closest_multiple_of_16(drive_sigma_us * us /dt) # The width of the gaussian in units of dt
drive_samples = get_closest_multiple_of_16(drive_samples_us * us /dt) # The truncating parameter in units of dt
drive_amp = 0.05
# Drive pulse samples
drive_pulse = pulse_lib.gaussian(duration=drive_samples,
sigma=drive_sigma,
amp=drive_amp,
name='freq_sweep_excitation_pulse')
# Find out which group of qubits need to be acquired with this qubit
meas_map_idx = None
for i, measure_group in enumerate(backend_config.meas_map):
if qubit in measure_group:
meas_map_idx = i
break
assert meas_map_idx is not None, f"Couldn't find qubit {qubit} in the meas_map!"
inst_sched_map = backend_defaults.instruction_schedule_map
measure = inst_sched_map.get('measure', qubits=backend_config.meas_map[meas_map_idx])
measure
### Collect the necessary channels
drive_chan = pulse.DriveChannel(qubit)
meas_chan = pulse.MeasureChannel(qubit)
acq_chan = pulse.AcquireChannel(qubit)
# Create the base schedule
# Start with drive pulse acting on the drive channel
schedule = pulse.Schedule(name='Frequency sweep')
schedule += Play(drive_pulse, drive_chan)
# The left shift `<<` is special syntax meaning to shift the start time of the schedule by some duration
schedule += measure << schedule.duration
# Create the frequency settings for the sweep (MUST BE IN HZ)
frequencies_Hz = frequencies_GHz*GHz
schedule_frequencies = [{drive_chan: freq} for freq in frequencies_Hz]
schedule.draw(label=True)
from qiskit import assemble
num_shots_per_frequency = 1024
frequency_sweep_program = assemble(schedule,
backend=backend,
meas_level=1,
meas_return='avg',
shots=num_shots_per_frequency,
schedule_los=schedule_frequencies)
job = backend.run(frequency_sweep_program)
# print(job.job_id())
from qiskit.tools.monitor import job_monitor
job_monitor(job)
frequency_sweep_results = job.result(timeout=120) # timeout parameter set to 120 seconds
import matplotlib.pyplot as plt
sweep_values = []
for i in range(len(frequency_sweep_results.results)):
# Get the results from the ith experiment
res = frequency_sweep_results.get_memory(i)*scale_factor
# Get the results for `qubit` from this experiment
sweep_values.append(res[qubit])
plt.scatter(frequencies_GHz, np.real(sweep_values), color='black') # plot real part of sweep values
plt.xlim([min(frequencies_GHz), max(frequencies_GHz)])
plt.xlabel("Frequency [GHz]")
plt.ylabel("Measured signal [a.u.]")
plt.show()
from scipy.optimize import curve_fit
def fit_function(x_values, y_values, function, init_params):
fitparams, conv = curve_fit(function, x_values, y_values, init_params)
y_fit = function(x_values, *fitparams)
return fitparams, y_fit
fit_params, y_fit = fit_function(frequencies_GHz,
np.real(sweep_values),
lambda x, A, q_freq, B, C: (A / np.pi) * (B / ((x - q_freq)**2 + B**2)) + C,
[-5, 4.975, 1, 5] # initial parameters for curve_fit
)
plt.scatter(frequencies_GHz, np.real(sweep_values), color='black')
plt.plot(frequencies_GHz, y_fit, color='red')
plt.xlim([min(frequencies_GHz), max(frequencies_GHz)])
plt.xlabel("Frequency [GHz]")
plt.ylabel("Measured Signal [a.u.]")
plt.show()
|
https://github.com/quantumyatra/quantum_computing
|
quantumyatra
|
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/quantumyatra/quantum_computing
|
quantumyatra
|
# Useful additional packages
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from qiskit import QuantumCircuit, execute, Aer
from qiskit.visualization import plot_histogram
ckt=QuantumCircuit(1)
ckt.x(0)
ckt.y(0)
ckt.z(0)
ckt.draw(output='mpl')
sim_uni = Aer.get_backend('unitary_simulator')
job_uni = execute(ckt, sim_uni, shots=1000)
res_uni = job_uni.result()
uni_matrix = res_uni.get_unitary(ckt)
print (uni_matrix)
|
https://github.com/quantumyatra/quantum_computing
|
quantumyatra
|
# Useful additional packages
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from qiskit import QuantumCircuit, execute, Aer
from qiskit.visualization import plot_histogram
#!pip3 install qiskit
for backend in Aer.backends():
print(backend.name() )
sim_qsm = Aer.get_backend('qasm_simulator')
sim_svec = Aer.get_backend('statevector_simulator')
sim_uni = Aer.get_backend('unitary_simulator')
circuit = QuantumCircuit(2,2)
circuit.draw()
from qiskit import QuantumRegister, ClassicalRegister
# construct a circuit
# syntax QuantumCircuit(QuantumRegister(2), ClassicalRegister(2))
#qr=QuantumRegister(2); print (qr)
#cr=ClassicalRegister(2); print (cr)
#circuit1 = QuantumCircuit(qr, cr)
#circuit1.draw()
# Add a Hadamart (H gate) on qubit 0
circuit.h(0)
circuit.cx(0, 1)
#circuit.measure([0,1], [0,1])
job_uni = execute(circuit, sim_uni, shots=1000)
res_uni = job_uni.result()
counts_uni = res_uni.get_counts(circuit)
plot_histogram(counts_uni)
job_qsm = execute(circuit, sim_qsm, shots=1000)
res_qsm = job_qsm.result()
counts_qsm = res_qsm.get_counts(circuit)
circuit.draw()
from qiskit.visualization import plot_histogram
plot_histogram(counts_qsm)
job_svec = execute(circuit, sim_svec, shots=1000)
res_svec = job_svec.result()
counts_svec = res_svec.get_counts(circuit)
plot_histogram(counts_svec)
#This produced errors.
#job_uni = execute(circuit, sim_uni, shots=1000)
#res_uni = job_uni.result()
#counts_uni = res_uni.get_counts(circuit)
#plot_histogram(counts_uni)
ckt = QuantumCircuit(2,2)
ckt.h(0)
ckt.x(0)
ckt.cx(0,1)
ckt.draw('mpl')
qc = QuantumCircuit(5)
qc.h([0, 2])
qc.cx(0, range(1, 5))
qc.measure_all()
job_qsm = execute(qc, sim_qsm, shots=1000)
res_qsm = job_qsm.result()
#print (res_qsm)
counts_qsm = res_qsm.get_counts()
qc.draw('mpl')
plot_histogram(counts_qsm)
qc = QuantumCircuit(3,3)
qc.h(0)
qc.cx(0, 1)
qc.cx(0, 2)
qc.measure([0,1,2],[0,1,2])
qc.draw()
backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
result = execute(qc, backend, shots = 2000).result() # we run the simulation
counts = result.get_counts() # we get the counts
plot_histogram(counts)
|
https://github.com/quantumyatra/quantum_computing
|
quantumyatra
|
#!/usr/bin/env python3
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import Aer, execute
from qiskit.visualization import plot_bloch_multivector, plot_histogram
import numpy as np
import pylab as plt
import sys
sys.path.append("/Users/gshyam/projects/work_projects/machine_learning/QuantumComputing/quantum_computing/utils")
from utils import get_statevector
def get_state_bell_ckt(qc):
backend = Aer.get_backend('statevector_simulator')
res = execute(qc, backend=backend).result()
final_state = res.get_statevector()
counts = res.get_counts()
return (final_state, counts)
qc1 = QuantumCircuit(2)
qc1.h(0)
qc1.cx(0,1)
fig, ax = plt.subplots(1, 2, constrained_layout=True)
qc1.draw(output='mpl', ax=ax[0], scale=1.5)
sv, counts = get_state_bell_ckt(qc1)
plot_histogram(counts, ax=ax[1])
qc1 = QuantumCircuit(2)
qc1.h(0)
qc1.cx(0,1)
qc1.draw(output='mpl')
backend = Aer.get_backend('statevector_simulator')
res = execute(qc1, backend=backend).result()
final_state = res.get_statevector()
counts = res.get_counts()
print (final_state, counts)
plot_histogram(counts)
qc2 = QuantumCircuit(2)
qc2.h(0)
qc2.cx(0,1)
qc2.x(0)
qc2.draw(output='mpl')
backend = Aer.get_backend('statevector_simulator')
res = execute(qc2, backend=backend).result()
final_state = res.get_statevector()
counts = res.get_counts()
print (final_state, counts)
plot_histogram(counts)
qc3 = QuantumCircuit(2)
qc3.h(0)
qc3.cx(0,1)
qc3.x(1)
qc3.draw(output='mpl')
backend = Aer.get_backend('statevector_simulator')
res = execute(qc3, backend=backend).result()
final_state = res.get_statevector()
counts = res.get_counts()
print (final_state, counts)
plot_histogram(counts)
qc4 = QuantumCircuit(2)
qc4.h(0)
qc4.cx(0,1)
qc4.x(1)
qc4.x(0)
qc4.draw(output='mpl')
backend = Aer.get_backend('statevector_simulator')
res = execute(qc4, backend=backend).result()
final_state = res.get_statevector()
counts = res.get_counts()
print (final_state, counts)
plot_histogram(counts)
#!/usr/bin/env python3
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import Aer, execute
from qiskit.visualization import plot_histogram
# Define quantum circuit
N_qubits=2; N_bits=2;
bell= QuantumCircuit(N_qubits, N_bits);
bell.h(0) # Add a hadamard
bell.cx(0, 1) # add a Cnot gate # similar to Last week's discussion
# Measure the result : Syntax QuantumCircuit.measure(qubit, cbit)
#bell.measure([0,1],[0,1])
#bell.draw()
bell.draw(output='mpl')
for backend in Aer.backends():
print(backend.name() )
backend = Aer.get_backend('unitary_simulator')
job_uni = execute(bell, backend)
res_uni = job_uni.result()
print(res_uni.get_unitary(bell, decimals=1))
bell.measure([0,1],[0,1])
backend = Aer.get_backend('unitary_simulator')
N=2
q=QuantumRegister(N)
c=ClassicalRegister(N)
circ = QuantumCircuit(q,c)
circ.h(q[0])
circ.cx(q[0],q[1])
circ.h(q[1])
job = execute(circ, backend)
result = job.result()
print(result.get_unitary(circ, decimals=1))
sim_qsm = Aer.get_backend('qasm_simulator')
job_qsm = execute(bell, sim_qsm, shots=1024) # shots=1024 (default)
res_qsm = job_qsm.result()
print (res_qsm)
counts_qsm = res_qsm.get_counts(bell)
print (counts_qsm)
plot_histogram( counts_qsm, title='Bell-State counts')
# Define quantum circuit
N_qubits=2; N_bits=2;
ckt2= QuantumCircuit(N_qubits, N_bits);
ckt2.h(0)
ckt2.cx(0, 1)
ckt2.h(1) # this time on quibit 1
ckt2.cx(0, 1)
ckt2.measure([0,1],[0,1])
#ckt2.draw()
ckt2.draw(output='mpl', style = {'backgroundcolor':'lightblue'})
sim_qsm = Aer.get_backend('qasm_simulator')
job_qsm = execute(ckt2, sim_qsm, shots=2000)
res_qsm = job_qsm.result()
counts_qsm = res_qsm.get_counts(ckt2)
print (counts_qsm)
plot_histogram( counts_qsm, title='Bell-State counts')
# Define quantum circuit
import pylab as plt
%matplotlib inline
def ckt_(N, init_state, axis):
q=QuantumRegister(N)
c=ClassicalRegister(N)
ckt3= QuantumCircuit(q, c);
#print (q, c, q[0], c[0], q[1], q[2])
ckt3.h(q[init_state])
ckt3.cx(q[0], q[1])
ckt3.h(q[1]) # this time on quibit 1
ckt3.cx(q[1], q[2])
ckt3.h(q[2])
ckt3.cx(q[0], q[2])
ckt3.measure(q, c)
ckt3.draw(output='mpl', ax=axis)
fig, ax = plt.subplots(1, 2) #figsize=(7, 7)
ckt_(3, 0, axis=ax[0])
ckt_(3, 1, axis=ax[1])
N=3;
q=QuantumRegister(N)
c=ClassicalRegister(N)
ckt3= QuantumCircuit(q, c, name='ckt3');
ckt3.h(q[0])
ckt3.cx(q[0], q[1])
ckt3.h(q[1])
ckt3.cx(q[1], q[2])
ckt3.h(q[2])
ckt3.cx(q[0], q[2])
ckt3.measure(q, c)
ckt3.draw(output='mpl')
sim_uni = Aer.get_backend('unitary_simulator')
job_uni = execute(ckt3, sim_uni)
res_uni = job_uni.result()
print (res_uni)
#print (res_uni.get_unitary(ckt3,decimals=1))
sim_qsm = Aer.get_backend('qasm_simulator')
job_qsm = execute(ckt3, sim_qsm, shots=2000)
res_qsm = job_qsm.result()
counts_qsm = res_qsm.get_counts(ckt3)
print (counts_qsm, sum(counts_qsm.values()))
plot_histogram( counts_qsm, title='Bell-State counts')
#ckt3.to_matrix()
N=4;
q=QuantumRegister(N)
c=ClassicalRegister(N)
circ = QuantumCircuit(q, c);
for i in range(0, N-1):
circ.h(q[i])
circ.cx(q[i], q[i+1])
circ.measure(q, c)
sim_qsm = Aer.get_backend('qasm_simulator')
job_qsm = execute(circ, sim_qsm, shots=2000)
res_qsm = job_qsm.result()
counts_qsm = res_qsm.get_counts(circ)
print (len(counts_qsm.values()))
print("Time taken: {} sec".format(res_qsm.time_taken))
%matplotlib inline
plot_histogram( counts_qsm)
|
https://github.com/quantumyatra/quantum_computing
|
quantumyatra
|
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import Aer, execute, BasicAer
from qiskit.visualization import plot_bloch_multivector
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
qc = QuantumCircuit(3, 2)
print(qc.qregs)
print(qc.cregs)
##This is equivalent to the following.
qr = QuantumRegister(3, name='q')
cr = ClassicalRegister(2, name='c')
qc = QuantumCircuit(qr, cr)
# Checking the quantum and classical registers
print(qc.qregs)
print(qc.cregs)
bell = QuantumCircuit(2, 2)
bell.h(0)
bell.cx(0, 1)
#Syntax: QuantumCircuit.measure(qubit, cbit)
bell.measure([0,1], [0,1])
bell.draw(output='mpl')
qr1 = QuantumRegister(1, 'q1')
qr2 = QuantumRegister(1, 'q2')
cr = ClassicalRegister(2, 'c')
circuit = QuantumCircuit(qr2, qr1, cr)
print('Qubit ordering:', circuit.qubits) # quantum
print('Classical bit ordering:', circuit.clbits) # classical
circuit.h([1,0]) # hadamard gate on both 1 and 0 qubits
circuit.measure(1, [0,1]) # 1 qubit and 2 clbit
circuit.draw(output='mpl')
from qiskit.circuit import Gate
# Syntax Gate(name, num_qubits, params, label=None)
my_gate = Gate(name='my_gate', num_qubits=2, params=[])
print (my_gate.params)
circ = QuantumCircuit(qr)
circ.h(0)
circ.append(my_gate, [qr[0], qr[1]])
circ.append(my_gate, [qr[1], qr[2]])
circ.draw(output='mpl')
from qiskit.circuit import QuantumCircuit, Parameter
theta = Parameter('theta')
test_ckt = QuantumCircuit(3)
#Syntax crz(theta, control_qubit, target_qubit, *, ctl=None, tgt=None)
test_ckt.crz(theta,0,2)
test_ckt.crz(theta,1,2)
test_ckt.barrier(0)
test_ckt.barrier()
test_ckt.draw(output='mpl')
from qiskit.extensions import HGate
print (f"Matrix(HGate):\n {HGate().to_matrix() } \n")
qcN = QuantumCircuit(2, 2)
qcN.h(0)
#qcN.cx(0, 1)
qcN.measure([0, 1], [0, 1])
backend = BasicAer.get_backend('statevector_simulator')
res = execute(qcN, backend).result()
out_state = res.get_statevector(qcN, decimals=3)
print (out_state)
plot_bloch_multivector(out_state)
# Build a sub-circuit
sub_q = QuantumRegister(2)
sub_circ = QuantumCircuit(sub_q, name='sub_circ')
sub_circ.h(sub_q[0])
sub_circ.crz(1, sub_q[0], sub_q[1])
sub_circ.barrier()
sub_circ.i(sub_q[1])
sub_circ.u3(1, 2, -2, sub_q[0])
sub_circ.draw('mpl')
# Convert to a gate and stick it into an arbitrary place in the bigger ckt
sub_inst = sub_circ.to_instruction()
q = QuantumRegister(3, 'q')
c = ClassicalRegister(3, 'c')
circ = QuantumCircuit(q, c)
circ.h(q[0])
circ.cx(q[0], q[1])
#circ.cx(qr[1], qr[2])
#circ.append(sub_inst, [q[1], q[2]])
#circ.append(sub_circ, [q[1], q[2]])
circ.draw('mpl')
decomposed_circ = circ.decompose() # Does not modify original circuit
decomposed_circ.draw(output='mpl')
from qiskit.circuit import Parameter
%matplotlib inline
n=5
theta = Parameter('theta')
qc = QuantumCircuit(n, 1)
qc.h(0)
for i in range(n-1):
qc.cx(i, i+1)
qc.barrier()
qc.rz(theta, range(n))
#qc.rz(theta, [0,4])
qc.barrier()
for i in reversed(range(n-1)):
qc.cx(i, i+1)
qc.h(0)
qc.measure(0, 0)
qc.draw(output='mpl')
theta_range = np.linspace(0, 2 * np.pi, 128)
circuits = [qc.bind_parameters({theta: theta_val})
for theta_val in theta_range]
print(circuits[-1].draw(fold=120))
print(circuits[-1].parameters)### Binding parameters to values
job = execute(qc,
backend=BasicAer.get_backend('qasm_simulator'),
parameter_binds=[{theta: theta_val} for theta_val in theta_range],
shots=2000)
counts = [job.result().get_counts(i) for i in range(len(job.result().results))]
plt.figure(figsize=(8,4))
plt.plot(theta_range, list(map(lambda c: c.get('0', 0), counts)), '-.', label='0', color='green')
plt.plot(theta_range, list(map(lambda c: c.get('1', 0), counts)), '-.', label='1', color='maroon')
labs = ['0', r'$\frac{\pi}{2}$', r'$\pi$', r'$\frac{3\pi}{2}$', r'$2\pi$']
plt.xticks([i * np.pi / 2 for i in range(5)], labs, fontsize=16)
plt.xlabel('$\\theta$', fontsize=16);
plt.legend();
import time
from itertools import combinations
from qiskit.compiler import transpile, assemble
from qiskit.test.mock import FakeTokyo
start = time.time()
qcs = []
theta_range = np.linspace(0, 2*np.pi, 16)
for n in theta_range:
qc = QuantumCircuit(5)
for k in range(8):
for i,j in combinations(range(5), 2):
qc.cx(i,j)
qc.rz(n, range(5))
for i,j in combinations(range(5), 2):
qc.cx(i,j)
qcs.append(qc)
compiled_circuits = transpile(qcs, backend=FakeTokyo())
qobj = assemble(compiled_circuits, backend=FakeTokyo())
end = time.time()
print('Time compiling over set of bound circuits: ', end-start)
start = time.time()
qc = QuantumCircuit(5)
theta = Parameter('theta')
for k in range(4):
for i,j in combinations(range(5), 2):
qc.cx(i,j)
qc.rz(theta, range(5))
for i,j in combinations(range(5), 2):
qc.cx(i,j)
transpiled_qc = transpile(qc, backend=FakeTokyo())
qobj = assemble([transpiled_qc.bind_parameters({theta: n})
for n in theta_range], backend=FakeTokyo())
end = time.time()
print('Time compiling over parameterized circuit, then binding: ', end-start)
phi = Parameter('phi')
sub_circ1 = QuantumCircuit(2, name='sc_1')
sub_circ1.rz(phi, 0)
sub_circ1.rx(phi, 1)
sub_circ2 = QuantumCircuit(2, name='sc_2')
sub_circ2.rx(phi, 0)
sub_circ2.rz(phi, 1)
qc = QuantumCircuit(4)
qr = qc.qregs[0]
qc.append(sub_circ1.to_instruction(), [qr[0], qr[1]])
qc.append(sub_circ2.to_instruction(), [qr[0], qr[1]])
qc.append(sub_circ2.to_instruction(), [qr[2], qr[3]])
print(qc.draw())
# The following raises an error: "QiskitError: 'Name conflict on adding parameter: phi'"
# phi2 = Parameter('phi')
# qc.u3(0.1, phi2, 0.3, 0)
p = Parameter('p')
qc = QuantumCircuit(3, name='oracle')
qc.rz(p, 0)
qc.cx(0, 1)
qc.rz(p, 1)
qc.cx(1, 2)
qc.rz(p, 2)
theta = Parameter('theta')
phi = Parameter('phi')
gamma = Parameter('gamma')
qr = QuantumRegister(9)
larger_qc = QuantumCircuit(qr)
larger_qc.append(qc.to_instruction({p: theta}), qr[0:3])
larger_qc.append(qc.to_instruction({p: phi}), qr[3:6])
larger_qc.append(qc.to_instruction({p: gamma}), qr[6:9])
print(larger_qc.draw())
print(larger_qc.decompose().draw())
|
https://github.com/quantumyatra/quantum_computing
|
quantumyatra
|
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
import sys, math, time
from qiskit import BasicAer, execute
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
def get_circuit(Nbits):
q = QuantumRegister(Nbits)
c = ClassicalRegister(Nbits)
ckt = QuantumCircuit(q, c)
ckt.h(q)
ckt.barrier()
ckt.measure(q,c)
return ckt
Nbits = 5;
ckt = get_circuit(Nbits)
ckt.draw(output = 'mpl')
ckt=get_circuit(Nbits)
n_qubits = ckt.n_qubits
backend=BasicAer.get_backend("qasm_simulator")
job = execute(ckt, backend=backend, shots=1000, memory=True)
res = job.result()
bit_str = ''.join(job.result().get_memory())
#print (res)
def get_random_Float(ckt, vmin=0., vmax =10.0, size=20 ):
nbits = 100
n_qubits = ckt.n_qubits
#print (n_qubits)
Nshots = (nbits * size + n_qubits -1) // n_qubits;
#print ('Nshots=',Nshots)
backend=BasicAer.get_backend("qasm_simulator");
job = execute(ckt, backend=backend, shots=Nshots, memory=True);
#print (job.result())
bit_str = ''.join(job.result().get_memory())
#print (bit_str, len(bit_str))
scale = float(vmax-vmin)/float(2**nbits-1)
random_vec = np.array([ vmin + scale*float(int(bit_str[i:i+nbits], 2))
for i in range(0, nbits*size, nbits)], dtype=float)
return random_vec
ckt=get_circuit(Nbits)
Rvec=get_random_Float(ckt)
print (Rvec, len(Rvec))
# Draw a sample from uniform distribution.
t1 = time.time()
sample = get_random_Float(ckt, vmin=-7.67, vmax=19.52, size=100)
#sample = uniform_rand_float64(circuit, glo_num_qubits, size=4321, vmin=-7.67, vmax=19.52)
t2 = time.time() - t1
print (t2)
# Print out some details.
print("Uniform distribution over floating point numbers:")
print(" sample type:", type(sample), ", element type:", sample.dtype,", shape:", sample.shape)
print(" sample min: {:.4f}, max: {:.4f}".format(np.amin(sample), np.amax(sample)))
print(" sampling time: {:.2f} secs".format(t2))
# Plotting the distribution.
plt.hist(sample.ravel(),
bins=min(int(np.ceil(np.sqrt(sample.size))), 100),
density=True, facecolor='b', alpha=0.75)
plt.xlabel("value", size=12)
plt.ylabel("probability", size=12)
plt.title("Uniform distribution over float64 numbers in\
[{:.2f} ... {:.2f}]".format(
np.amin(sample), np.amax(sample)), size=12)
plt.grid(True)
# plt.savefig("uniform_distrib_float.png", bbox_inches="tight")
plt.show()
|
https://github.com/quantumyatra/quantum_computing
|
quantumyatra
|
from qiskit import IBMQ
#token = open('/Users/gshyam/projects/work_projects/machine_learning/ANPA_dataScience/Python2020/TOKEN_BMQ','r')
#print (token)
#IBMQ.save_account(token)
#IBMQ.save_account('dbf31c5ec55e2b7914fe280fe04980f4edd8efa6063471bd9bc4e3617e7cc8348819917b6a01a4e106d8ef02c33f9abbf2920ceb9bbe44056eaec59eb1e910d3')
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import Aer, execute, BasicAer
from qiskit.visualization import plot_bloch_multivector
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import qiskit
print (qiskit.__version__)
print (qiskit.__qiskit_version__)
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
provider.backends()
for backend in provider.backends():
print(backend.status())
real_device = provider.get_backend('ibmq_16_melbourne')
properties = real_device.properties()
coupling_map = real_device.configuration().coupling_map
from qiskit.providers.aer.noise import NoiseModel
noise_model = NoiseModel.from_backend(properties)
qc = QuantumCircuit(2,2)
qc.x(1) # CNOT gate converts (00)
qc.measure(0,0)
qc.measure(1,1)
simulator = Aer.get_backend('qasm_simulator')
job = execute(qc, simulator, shots=1024, noise_model=noise_model,
coupling_map=coupling_map,
basis_gates=noise_model.basis_gates)
job.result().get_counts()
n=8
qc_encode = QuantumCircuit(n)
qc_encode.x(7)
qc_encode.draw(output='mpl')
qc_output = QuantumCircuit(n, n)
for j in range(n):
qc_output.measure(j,j)
qc_output.draw(output='mpl')
job = execute(qc_output, Aer.get_backend('quasm_simulator'))#.result().get_counts()
|
https://github.com/quantumyatra/quantum_computing
|
quantumyatra
|
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import Aer, execute, BasicAer
from qiskit.visualization import plot_bloch_multivector, plot_histogram
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
qc = QuantumCircuit(3)
# apply Hadamard
for q in range(3):
qc.h(q)
qc.draw(output='mpl')
backend = Aer.get_backend('statevector_simulator')
res = execute(qc, backend=backend).result()
final_state = res.get_statevector()
print (final_state)
print (1./np.sqrt(8))
𝑋=[[0, 1] ,[1, 0]]
qc = QuantumCircuit(2)
qc.h(0)
qc.x(1)
qc.draw('mpl')
backend = Aer.get_backend('unitary_simulator')
res = execute(qc, backend=backend).result()
unitary = res.get_unitary()
print (unitary.round(2).real)
qc = QuantumCircuit(3)
qc.z(0)
qc.h(1)
qc.x(2)
qc.draw('mpl')
backend = Aer.get_backend('unitary_simulator')
res = execute(qc, backend=backend).result()
unitary = res.get_unitary()
print (unitary.round(2).real)
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
qc.draw('mpl')
backend = Aer.get_backend('statevector_simulator')
final_state = execute(qc,backend).result().get_statevector()
print (final_state.round(2))
results = execute(qc,backend).result().get_counts()
plot_histogram(results)
qc = QuantumCircuit(2)
qc.h(0)
qc.h(1)
qc.cx(0,1)
qc.draw()
backend_sv =Aer.get_backend('statevector_simulator')
final_state = execute(qc,backend_sv).result().get_statevector()
print (final_state.round(2))
plot_bloch_multivector(final_state)
import qiskit
qiskit.__version__
qc = QuantumCircuit(2)
qc.h(0)
qc.h(1)
qc.z(1)
qc.draw()
final_state = execute(qc,backend_sv).result().get_statevector()
plot_bloch_multivector(final_state)
qc.cx(0,1)
qc.draw()
final_state = execute(qc,backend_sv).result().get_statevector()
print (final_state)
plot_bloch_multivector(final_state)
qc = QuantumCircuit(2)
qc.h(0)
qc.h(1)
qc.cx(0,1)
qc.h(0)
qc.h(1)
display(qc.draw())
backend_uni = Aer.get_backend('unitary_simulator')
unitary = execute(qc,backend_uni).result().get_unitary()
print (unitary.round(2).real)
#array_to_latex(unitary, pretext="\\text{Circuit = }\n")
qc.cx(1,0)
display(qc.draw())
backend_uni = Aer.get_backend('unitary_simulator')
unitary = execute(qc,backend_uni).result().get_unitary()
print (unitary.round(2).real)
|
https://github.com/quantumyatra/quantum_computing
|
quantumyatra
|
from qiskit import QuantumCircuit, Aer, execute
from math import pi
import numpy as np
from qiskit.visualization import plot_bloch_multivector, plot_histogram
qc = QuantumCircuit(2)
qc.h(0)
qc.h(1)
qc.cx(0,1)
qc.draw()
# Let's see the result
statevector_backend = Aer.get_backend('statevector_simulator')
final_state = execute(qc,statevector_backend).result().get_statevector()
# In Jupyter Notebooks we can display this nicely using Latex.
# If not using Jupyter Notebooks you may need to remove the
# array_to_latex function and use print(final_state) instead.
from qiskit_textbook.tools import array_to_latex
array_to_latex(final_state, pretext="\\text{Statevector} = ", precision=1)
plot_bloch_multivector(final_state)
qc = QuantumCircuit(2)
qc.h(0)
qc.h(1)
qc.z(1)
qc.draw()
final_state = execute(qc,statevector_backend).result().get_statevector()
array_to_latex(final_state, pretext="\\text{Statevector} = ", precision=1)
plot_bloch_multivector(final_state)
qc.cx(0,1)
qc.draw()
final_state = execute(qc,statevector_backend).result().get_statevector()
array_to_latex(final_state, pretext="\\text{Statevector} = ", precision=1)
plot_bloch_multivector(final_state)
qc = QuantumCircuit(2)
qc.h(0)
qc.h(1)
qc.cx(0,1)
qc.h(0)
qc.h(1)
display(qc.draw())
# `display` is an IPython tool, remove if it cases an error
unitary_backend = Aer.get_backend('unitary_simulator')
unitary = execute(qc,unitary_backend).result().get_unitary()
array_to_latex(unitary, pretext="\\text{Circuit = }\n")
qc = QuantumCircuit(2)
qc.cx(1,0)
display(qc.draw())
unitary_backend = Aer.get_backend('unitary_simulator')
unitary = execute(qc,unitary_backend).result().get_unitary()
array_to_latex(unitary, pretext="\\text{Circuit = }\n")
qc = QuantumCircuit(2)
qc.cu1(pi/4, 0, 1)
qc.draw()
unitary_backend = Aer.get_backend('unitary_simulator')
unitary = execute(qc,unitary_backend).result().get_unitary()
array_to_latex(unitary, pretext="\\text{Controlled-T} = \n")
qc = QuantumCircuit(2)
qc.h(0)
qc.x(1)
display(qc.draw())
final_state = execute(qc,statevector_backend).result().get_statevector()
plot_bloch_multivector(final_state)
qc.cu1(pi/4, 0, 1)
display(qc.draw())
final_state = execute(qc,statevector_backend).result().get_statevector()
plot_bloch_multivector(final_state)
import qiskit
qiskit.__qiskit_version__
|
https://github.com/quantumyatra/quantum_computing
|
quantumyatra
|
from qiskit import QuantumCircuit, execute
from qiskit import Aer, execute, BasicAer, IBMQ
from qiskit.providers.ibmq import least_busy
from qiskit.visualization import plot_histogram
import numpy as np
def dj_oracle(case, n):
oracle_qc = QuantumCircuit(n+1)
# First, let's deal with the case in which oracle is balanced
if case == "balanced":
# First generate a random number that tells us which CNOTs to
# wrap in X-gates:
b = np.random.randint(1,2**n)
# Next, format 'b' as a binary string of length 'n', padded with zeros:
b_str = format(b, '0'+str(n)+'b')
# Next, we place the first X-gates. Each digit in our binary string
# corresponds to a qubit, if the digit is 0, we do nothing, if it's 1
# we apply an X-gate to that qubit:
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
oracle_qc.x(qubit)
# Do the controlled-NOT gates for each qubit, using the output qubit
# as the target:
for qubit in range(n):
oracle_qc.cx(qubit, n)
# Next, place the final X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
oracle_qc.x(qubit)
# Case in which oracle is constant
elif case == "constant":
# First decide what the fixed output of the oracle will be
# (either always 0 or always 1)
output = np.random.randint(2)
if output == 1:
oracle_qc.x(n)
oracle_gate = oracle_qc.to_gate()
oracle_gate.name = "Oracle" # To show when we display the circuit
return oracle_gate
def dj_algorithm(oracle, n):
dj_circuit = QuantumCircuit(n+1, n)
# Set up the output qubit:
dj_circuit.x(n)
dj_circuit.h(n)
# And set up the input register:
for qubit in range(n):
dj_circuit.h(qubit)
# Let's append the oracle gate to our circuit:
dj_circuit.append(oracle, range(n+1))
# Finally, perform the H-gates again and measure:
for qubit in range(n):
dj_circuit.h(qubit)
for i in range(n):
dj_circuit.measure(i, i)
return dj_circuit
n=4
oracle_gate = dj_oracle('balanced', n)
dj_circuit = dj_algorithm(oracle_gate, n)
dj_circuit.draw('mpl')
backend = BasicAer.get_backend('qasm_simulator')
results = execute(dj_circuit, backend=backend, shots=1024).result()
answer = results.get_counts()
plot_histogram(answer)
# Load our saved IBMQ accounts and get the least busy backend device with greater than or equal to (n+1) qubits
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (n+1) and
not x.configuration().simulator and x.status().operational==True))
print("least busy backend: ", backend)
# Run our circuit on the least busy backend. Monitor the execution of the job in the queue
from qiskit.tools.monitor import job_monitor
shots = 1024
job = execute(dj_circuit, backend=backend, shots=shots, optimization_level=3)
job_monitor(job, interval = 2)
# Get the results of the computation
results = job.result()
counts = results.get_counts()
plot_histogram(counts)
|
https://github.com/quantumyatra/quantum_computing
|
quantumyatra
|
import numpy as np
import pylab as plt
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.visualization import plot_histogram, plot_bloch_multivector
qc = QuantumCircuit(3)
qc.h(2)
qc.draw('mpl')
# UROT_2 gate to x1 depending on x2
from numpy import pi
qc.cu1(pi/2, 1, 2) # CROT from qubit 1 to qubit 2 hence the angle: pi/2^{2-1}
qc.draw('mpl')
qc.cu1(pi/4, 0, 2) # CROT from qubit 2 to qubit 0 hence the angle: pi/2^{2-0}
qc.draw('mpl')
# Repeat the process for 2 and 3
qc.h(1) # Hadamard on 1
qc.cu1(pi/2, 0, 1) # CROT from qubit 0 to qubit 1 hence the angle: pi/2^{1-0}
qc.h(0) # Hadamard on 0
qc.draw('mpl')
# Now swap the qubit 0 and 2 to complete QFT. [NOT CLEAR TO ME]
qc.swap(0,2)
qc.draw('mpl')
def qft_rotations(ckt, n):
if n == 0:
return ckt
n -= 1
ckt.h(n)
for qubit in range(n):
ckt.cu1( pi/2**(n-qubit), qubit, n )
qc = QuantumCircuit(4)
qft_rotations(qc,4)
qc.draw('mpl')
def qft_rotations(ckt, n):
if n == 0:
return ckt
n -= 1
ckt.h(n)
for qubit in range(n):
ckt.cu1( pi/2**(n-qubit), qubit, n )
qft_rotations(ckt, n)
qc = QuantumCircuit(4)
qft_rotations(qc,4)
qc.draw('mpl')
from qiskit_textbook.widgets import scalable_circuit
scalable_circuit(qft_rotations)
def swap_registers(ckt, n):
for qubit in range(n//2):
ckt.swap(qubit, n-qubit-1)
return ckt
def qft(ckt, n):
qft_rotations(ckt, n)
swap_registers(ckt, n)
return ckt
qc = QuantumCircuit(4)
qft(qc, 4)
qc.draw('mpl')
print (f"5 and it's binary: {bin(5)}")
#bin(9)
qc = QuantumCircuit(3)
qc.x(0)
qc.x(2)
qc.draw('mpl')
backend = Aer.get_backend('statevector_simulator')
sv = execute(qc, backend=backend).result().get_statevector()
plot_bloch_multivector(sv)
print (sv.real)
qft(qc, 3)
qc.draw('mpl')
sv = execute(qc, backend=backend).result().get_statevector()
plot_bloch_multivector(sv)
print ('The statevectors are:\n', sv.round(1))
print ('Angle subtended by each states (as a factor of pi):\n',(np.angle(sv)/np.pi).round(2))
# 10
qc = QuantumCircuit(2)
qc.x(0)
qc.draw('mpl')
backend = Aer.get_backend('statevector_simulator')
sv = execute(qc, backend=backend).result().get_statevector()
plot_bloch_multivector(sv)
qft(qc, 2)
qc.draw('mpl')
backend = Aer.get_backend('statevector_simulator')
sv = execute(qc, backend=backend).result().get_statevector()
plot_bloch_multivector(sv)
def inverse_qft(circuit, n):
"""Does the inverse QFT on the first n qubits in circuit"""
# First we create a QFT circuit of the correct size:
qft_circ = qft(QuantumCircuit(n), n)
# Then we take the inverse of this circuit
invqft_circ = qft_circ.inverse()
# And add it to the first n qubits in our existing circuit
circuit.append(invqft_circ, circuit.qubits[:n])
# use .decompose() which allows us to see the individual gates
return circuit.decompose()
nqubits = 3
number = 6
qc = QuantumCircuit(nqubits)
for qubit in range(nqubits):
qc.h(qubit)
qc.u1(number*pi/4,0)
qc.u1(number*pi/2,1)
qc.u1(number*pi,2)
qc.draw('mpl')
backend = Aer.get_backend("statevector_simulator")
sv = execute(qc, backend=backend).result().get_statevector()
plot_bloch_multivector(sv)
print ('The statevectors are:\n', sv.round(1))
print ('Angle subtended by each states (as a factor of pi):\n',(np.angle(sv)/np.pi).round(2))
qc = inverse_qft(qc,nqubits)
qc.measure_all()
qc.draw('mpl')
backend = Aer.get_backend("qasm_simulator")
shots = 2048
job = execute(qc, backend=backend, shots=shots, optimization_level=3)
counts = job.result().get_counts()
plot_histogram(counts)
from qiskit import circuit, quantum_info
num_qubits = 6
qft = circuit.library.QFT(num_qubits, approximation_degree=0, insert_barriers=False)
qft.draw('mpl', fold=500, reverse_bits = True)
# Plot classical vs. quantum Fourier transform, for all basis states..
# By linearity of Fourier transform, all states map correctly.
# The difference in height is due to normalization in quantum.
plt.figure(figsize=(16,16))
for i, basis_state in enumerate([0, 1, 2, 3]):
state = quantum_info.Statevector.from_int(basis_state, dims=2**num_qubits)
#print (state)
classical_fourier = np.fft.ifft(state.data) # classical library function
quantum_fourier = state.evolve(qft).data # quantum library (simulation via quantum_info)
width = 0.5
#fig.suptitle('Input State: ' + str(basis_state), fontsize=16)
plt.subplot(4,2, 2*i+1)
plt.title('state: %1i real'%i)
plt.bar(np.arange(2**num_qubits)-width/2., classical_fourier.real, width, label='classical')
plt.bar(np.arange(2**num_qubits)+width/2., quantum_fourier.real, width, label='quantum')
plt.legend(frameon=False)
plt.subplot(4,2, 2*i+2)
plt.title('state: %1i Imaginary part'%i)
plt.bar(np.arange(2**num_qubits)-width/2., classical_fourier.imag, width, label='classical')
plt.bar(np.arange(2**num_qubits)+width/2., quantum_fourier.imag, width, label='quantum')
plt.legend(frameon=False)
import matplotlib.pyplot as plt
Nt = 256
t = np.arange(Nt)
fft = np.fft.fft(np.sin(t))
ifft = np.fft.ifft(np.sin(t))
freq = np.fft.fftfreq(Nt)
plt.figure(figsize=(16,4))
plt.subplot(121)
plt.title('real')
plt.plot(freq, fft.real, '-o', label='fft (real)')
plt.plot(freq, Nt*ifft.real, '-o', label='Nt * ifft (real)')
plt.legend(fontsize='large')
plt.xlabel('frequency', fontsize='large')
plt.subplot(122)
plt.title('imag')
plt.plot(freq, fft.imag, '-o', label='fft (imag)')
plt.plot(freq, Nt*ifft.imag, '-o', label='Nt * ifft (imag)')
plt.legend(fontsize='large')
plt.xlabel('frequency', fontsize='large')
plt.show()
from qiskit import circuit, quantum_info
num_qubits = 6
qft = circuit.library.QFT(num_qubits, insert_barriers=False)
qft.draw('mpl', fold=500, reverse_bits = True)
basis_state = 2
state = quantum_info.Statevector.from_int(basis_state, dims=2**num_qubits)
quantum_fourier = state.evolve(qft).data
width = 0.5
plt.subplot(121)
plt.bar(np.arange(2**num_qubits)+width/2., quantum_fourier.real, width, label='real')
plt.subplot(122)
plt.bar(np.arange(2**num_qubits)+width/2., quantum_fourier.imag, width, label='imag')
plt.legend(frameon=False)
|
https://github.com/quantumyatra/quantum_computing
|
quantumyatra
|
import numpy as np
import pylab as plt
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.visualization import plot_histogram, plot_bloch_multivector
qpe = QuantumCircuit(4,3)
qpe.x(3)
qpe.draw('mpl')
#Apply Hadamard gate to all the quits
for q in range(3):
qpe.h(q)
qpe.draw('mpl')
repetitions = 1
for q in range(3):
for i in range(repetitions):
qpe.cu1(np.pi/4., q, 3) # controlled U gate : for T gate angle = pi/4
repetitions *= 2
qpe.draw('mpl')
from qiskit.circuit.library import QFT
def qft_dagger(qc, n):
"""n-qubit QFTdagger the first n qubits in the circuit qc"""
for q in range(n//2):
qc.swap(q, n-q-1)
for j in range(n):
for m in range(j):
qc.cu1(-np.pi/(float(2**(j-m))), m, j)
qc.h(j)
def qft_dagger2(qc, n):
"""n-qubit QFTdagger the first n qubits in the circuit qc"""
### WRITE YOUR CODE BETWEEN THESE LINES - START
gate = QFT(n, inverse=True, do_swaps=True )
qc.append(gate, range(n))
### WRITE YOUR CODE BETWEEN THESE LINES - END
# measure the counting register
qpe.barrier()
qft_dagger(qpe, 3)
qpe.barrier()
for n in range(3):
qpe.measure(n,n)
qpe.draw('mpl')
backend = Aer.get_backend('qasm_simulator')
shots = 2048
results = execute(qpe, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
def bin2decimal(binary_str):
if '1' not in binary_str:
return 0
else:
binary = int(binary_str.lstrip('0'))
binary1 = binary
decimal, i = 0, 0
while(binary != 0):
dec = binary % 10
decimal = decimal + dec * pow(2, i)
binary = binary//10
i += 1
return decimal
bin2decimal('001010')
def QPE(N=3):
qc = QuantumCircuit(N+1, N)
qc.x(N)
#Apply Hadamard gate to all the quits
for q in range(N):
qc.h(q)
#Next we perform the controlled unitary operations
repetitions = 1
for q in range(N):
for i in range(repetitions):
qc.cu1(np.pi/4., q, N) # controlled U gate, angle is pi/4 for T gate
repetitions *=2
# measure the counting register
qc.barrier()
qft_dagger(qc, N)
qc.barrier()
for n in range(N):
qc.measure(n,n)
# execute the circuit
backend = Aer.get_backend('qasm_simulator')
Nshots = 2048
results = execute(qc, backend=backend, shots=Nshots).result()
counts = results.get_counts()
for binary in counts:
dec = bin2decimal(binary)
phase = dec/(2**N)
print ('binary:', binary,', decimal:', dec, 'Count ratio:', counts[binary]/Nshots)
print ('phase:', phase)
return counts
#print (counts)
counts = QPE(4)
print (counts)
plot_histogram(counts)
def getting_more_precision(N=3):
qc = QuantumCircuit(N+1, N)
# Prepare our eigenstate |psi>:
qc.x(N)
#Apply Hadamard gate to all the quits
for q in range(N):
qc.h(q)
#controlled-U operations
angle = 2*np.pi/3.
repetitions = 1
for q in range(N):
for i in range(repetitions):
qc.cu1(angle, q, N) # controlled U gate
repetitions *=2
# measure the counting register
qc.barrier()
qft_dagger(qc, N)
qc.barrier()
for n in range(N):
qc.measure(n,n)
# execute the circuit
backend = Aer.get_backend('qasm_simulator')
Nshots = 2048
results = execute(qc, backend=backend, shots=Nshots).result()
counts = results.get_counts()
return counts
def calcPhase(counts, Nqubit):
kL = list(counts.items())
vL = list(counts.values())
maxval1 = max(vL); (k1,v1) = kL[vL.index(maxval1)]; vL.remove(maxval1)
maxval2 = max(vL); (k2,v2) = kL[vL.index(maxval2)];
k1_dec = bin2decimal(k1)
k2_dec = bin2decimal(k2)
phase1 = k1_dec/(2**Nqubit)
phase2 = k2_dec/(2**Nqubit)
print ('the phase lies between [',phase1, ',', phase2, ']')
N=5
counts = getting_more_precision(N)
print (counts)
calcPhase(counts, N)
plot_histogram(counts)
#'11010': 1385
26/32
print ( 6/8, 4/8)
d = {'001': 60, '011': 1397, '010': 358}
list(d.keys())[0]
|
https://github.com/quantumyatra/quantum_computing
|
quantumyatra
|
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, BasicAer, IBMQ
from qiskit.visualization import plot_histogram, plot_bloch_multivector
from qiskit.extensions import Initialize
from qiskit.quantum_info import random_statevector
from utility import *
qr = QuantumRegister(3) # Protocol uses 3 qubits
crz = ClassicalRegister(1) # and 2 classical bits
crx = ClassicalRegister(1) # in 2 different registers
teleportation_circuit = QuantumCircuit(qr, crz, crx)
def create_bell_pair(qc, a, b, print_state_vec=False):
"creates a bell pair in qc using qubits a and b"
qc.h(a)
qc.cx(a,b)
if print_state_vec :
state = get_state_vector(qc)
print (state)
def test_bell_pair():
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
state = get_state_vector(qc)
print (state)
test_bell_pair()
qr = QuantumRegister(3)
crz = ClassicalRegister(1)
crx = ClassicalRegister(1)
teleportation_circuit = QuantumCircuit(qr, crz, crx)
create_bell_pair(teleportation_circuit, 1, 2)
teleportation_circuit.draw(output='mpl')
def alice_gates(qc, psi, a):
qc.cx(psi, a)
qc.h(psi)
qr = QuantumRegister(3)
crz = ClassicalRegister(1)
crx = ClassicalRegister(1)
teleportation_circuit = QuantumCircuit(qr, crz, crx)
create_bell_pair(teleportation_circuit, 1, 2)
teleportation_circuit.barrier()
alice_gates(teleportation_circuit, 0, 1)
teleportation_circuit.draw(output='mpl')
def measure_and_send(qc, a, b):
"""Measures qubits a & b and 'sends' the results to Bob"""
qc.barrier()
qc.measure(a,0)
qc.measure(b,1)
#Set up
qr = QuantumRegister(3)
crz = ClassicalRegister(1)
crx = ClassicalRegister(1)
teleportation_circuit = QuantumCircuit(qr, crz, crx)
# step 1
create_bell_pair(teleportation_circuit, 1, 2)
#step 2
teleportation_circuit.barrier()
alice_gates(teleportation_circuit, 0, 1)
#step 3
measure_and_send(teleportation_circuit, 0, 1)
teleportation_circuit.draw(output='mpl')
def bob_gates(qc, qubit, crz, crx):
# Here we use c_if to control our gates with a classical
# bit instead of a qubit
qc.x(qubit).c_if(crx, 1) # Apply gates if the registers
qc.z(qubit).c_if(crz, 1) # are in the state '1'
#Set up
qr = QuantumRegister(3)
crz = ClassicalRegister(1)
crx = ClassicalRegister(1)
teleportation_circuit = QuantumCircuit(qr, crz, crx)
# step 1
create_bell_pair(teleportation_circuit, 1, 2)
#step 2
teleportation_circuit.barrier()
alice_gates(teleportation_circuit, 0, 1)
#step 3
measure_and_send(teleportation_circuit, 0, 1)
# step 4
teleportation_circuit.barrier()
bob_gates(teleportation_circuit, 2, crz, crx)
teleportation_circuit.draw(output='mpl')
from qiskit.quantum_info import random_statevector
psi = random_statevector(2).data
print (psi)
plot_bloch_multivector(psi)
from IPython.display import display, Markdown, Latex
display(Latex('$\psi$'))
init_gate = Initialize(psi)
#Set up
qr = QuantumRegister(3)
crz = ClassicalRegister(1)
crx = ClassicalRegister(1)
qc = QuantumCircuit(qr, crz, crx)
psi = random_statevector(2).data
init_gate = Initialize(psi)
init_gate.label = "init"
# step 0
qc.append(init_gate, [0] )
qc.barrier()
# step 1
create_bell_pair(qc, 1, 2)
qc.barrier()
#step 2
alice_gates(qc, 0, 1)
#step 3
measure_and_send(qc, 0, 1)
# step 4
#qc.barrier()
bob_gates(qc, 2, crz, crx)
qc.draw(output='mpl')
|
https://github.com/quantumyatra/quantum_computing
|
quantumyatra
|
# importing Qiskit
from qiskit import IBMQ, BasicAer
#from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, execute
# import basic plot tools
from qiskit.visualization import plot_histogram
s='11'
n = 2*len(str(s))
ckt = QuantumCircuit(n)
barriers = True
ckt.h(range(len(str(s))))
# Apply barrier
ckt.barrier()
# Apply the query function
## 2-qubit oracle for s = 11
ckt.cx(0, len(str(s)) + 0)
ckt.cx(0, len(str(s)) + 1)
ckt.cx(1, len(str(s)) + 0)
ckt.cx(1, len(str(s)) + 1)
# Apply barrier
ckt.barrier()
# Apply Hadamard gates to the input register
ckt.h(range(len(str(s))))
# Measure ancilla qubits
ckt.measure_all()
ckt.draw(output='mpl')
|
https://github.com/quantumyatra/quantum_computing
|
quantumyatra
|
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, BasicAer, IBMQ
from qiskit.visualization import plot_histogram, plot_bloch_multivector
from qiskit.extensions import Initialize
from qiskit.quantum_info import random_statevector
from utility import *
#create_bell_pair(qc, a, b): coded in utility.py
def encode_message(qc, qubit, msg):
if msg == "00":
pass # To send 00 we do nothing
elif msg == "10":
qc.x(qubit) # To send 10 we apply an X-gate
elif msg == "01":
qc.z(qubit) # To send 01 we apply a Z-gate
elif msg == "11":
qc.z(qubit) # To send 11, we apply a Z-gate
qc.x(qubit) # followed by an X-gate
else:
print("Invalid Message: Sending '00'")
def decode_message(qc, a, b):
qc.cx(a,b)
qc.h(a)
#put everything together
qc = QuantumCircuit(2)
create_bell_pair(qc, 0, 1)
qc.barrier()
message = "10"
encode_message(qc, 0, message)
qc.barrier()
decode_message(qc, 0, 1)
qc.measure_all()
qc.draw(output = "mpl")
backend = Aer.get_backend('qasm_simulator')
res = execute(qc, backend, shots=1024).result()
measurement_result = res.get_counts(qc)
print(measurement_result)
plot_histogram(measurement_result)
from qiskit import IBMQ
from qiskit.providers.ibmq import least_busy
shots = 256
# Load local account information
IBMQ.load_account()
# Get the least busy backend
provider = IBMQ.get_provider(hub='ibm-q')
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2
and not x.configuration().simulator
and x.status().operational==True))
print("least busy backend: ", backend)
# Run our circuit
job = execute(qc, backend=backend, shots=shots)
from qiskit.tools.monitor import job_monitor
job_monitor(job)
# Plotting our result
result = job.result()
plot_histogram(result.get_counts(qc))
correct_results = result.get_counts(qc)[message]
accuracy = (correct_results/shots)*100
print("Accuracy = %.2f%%" % accuracy)
|
https://github.com/quantumyatra/quantum_computing
|
quantumyatra
|
import numpy as np
np.random.seed(999999)
target_distr = np.random.rand(2)
# We now convert the random vector into a valid probability vector
target_distr /= sum(target_distr)
print (target_distr)
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
def get_var_form(params):
qr = QuantumRegister(1, name="q")
cr = ClassicalRegister(1, name='c')
qc = QuantumCircuit(qr, cr)
qc.u3(params[0], params[1], params[2], qr[0])
qc.measure(qr, cr[0])
return qc
params = [0.1, 0, 0]
qcc = get_var_form(params)
qcc.draw('mpl')
from qiskit import Aer, execute
backend = Aer.get_backend("qasm_simulator")
num_shots = 10000
def get_probability_distribution(counts):
output_distr = [v / num_shots for v in counts.values()]
if len(output_distr) == 1:
output_distr.append(0)
return output_distr
def objective_function(params):
# Obtain a quantum circuit instance from the paramters
qc = get_var_form(params)
# Execute the quantum circuit to obtain the probability distribution associated with the current parameters
result = execute(qc, backend, shots=num_shots).result()
# Obtain the counts for each measured state, and convert those counts into a probability vector
output_distr = get_probability_distribution(result.get_counts(qc))
# Calculate the cost as the distance between the output distribution and the target distribution
cost = sum([np.abs(output_distr[i] - target_distr[i]) for i in range(2)])
return cost
from qiskit.aqua.components.optimizers import COBYLA
# Initialize the COBYLA optimizer
optimizer = COBYLA(maxiter=50, tol=0.0001)
# Create the initial parameters (noting that our single qubit variational form has 3 parameters)
params = np.random.rand(3)
ret = optimizer.optimize(num_vars=3, objective_function=objective_function, initial_point=params)
# Obtain the output distribution using the final parameters
qc = get_var_form(ret[0])
counts = execute(qc, backend, shots=num_shots).result().get_counts(qc)
output_distr = get_probability_distribution(counts)
print("Target Distribution:", target_distr)
print("Obtained Distribution:", output_distr)
print("Output Error (Manhattan Distance):", ret[1])
print("Parameters Found:", ret[0])
from qiskit.circuit.library import EfficientSU2
entanglements = ["linear", "full"]
for entanglement in entanglements:
form = EfficientSU2(num_qubits=4, entanglement=entanglement)
if entanglement == "linear":
print("=============Linear Entanglement:=============")
else:
print("=============Full Entanglement:=============")
# We initialize all parameters to 0 for this demonstration
display(form.draw("mpl", fold=100))
print()
from qiskit.aqua.algorithms import VQE, NumPyEigensolver
import matplotlib.pyplot as plt
import numpy as np
from qiskit.chemistry.components.variational_forms import UCCSD
from qiskit.chemistry.components.initial_states import HartreeFock
from qiskit.circuit.library import EfficientSU2
from qiskit.aqua.components.optimizers import COBYLA, SPSA, SLSQP
from qiskit.aqua.operators import Z2Symmetries
from qiskit import IBMQ, BasicAer, Aer
from qiskit.chemistry.drivers import PySCFDriver, UnitsType
from qiskit.chemistry import FermionicOperator
from qiskit import IBMQ
from qiskit.aqua import QuantumInstance
from qiskit.ignis.mitigation.measurement import CompleteMeasFitter
from qiskit.providers.aer.noise import NoiseModel
def get_qubit_op(dist):
driver = PySCFDriver(atom="Li .0 .0 .0; H .0 .0 " + str(dist), unit=UnitsType.ANGSTROM,
charge=0, spin=0, basis='sto3g')
molecule = driver.run()
freeze_list = [0]
remove_list = [-3, -2]
repulsion_energy = molecule.nuclear_repulsion_energy
num_particles = molecule.num_alpha + molecule.num_beta
num_spin_orbitals = molecule.num_orbitals * 2
remove_list = [x % molecule.num_orbitals for x in remove_list]
freeze_list = [x % molecule.num_orbitals for x in freeze_list]
remove_list = [x - len(freeze_list) for x in remove_list]
remove_list += [x + molecule.num_orbitals - len(freeze_list) for x in remove_list]
freeze_list += [x + molecule.num_orbitals for x in freeze_list]
ferOp = FermionicOperator(h1=molecule.one_body_integrals, h2=molecule.two_body_integrals)
ferOp, energy_shift = ferOp.fermion_mode_freezing(freeze_list)
num_spin_orbitals -= len(freeze_list)
num_particles -= len(freeze_list)
ferOp = ferOp.fermion_mode_elimination(remove_list)
num_spin_orbitals -= len(remove_list)
qubitOp = ferOp.mapping(map_type='parity', threshold=0.00000001)
qubitOp = Z2Symmetries.two_qubit_reduction(qubitOp, num_particles)
shift = energy_shift + repulsion_energy
return qubitOp, num_particles, num_spin_orbitals, shift
dist = 1.
qubitOp, num_particles, num_spin_orbitals, shift = get_qubit_op(dist)
print ( qubitOp, num_particles, num_spin_orbitals, shift )
backend = BasicAer.get_backend("statevector_simulator")
distances = np.arange(0.5, 4.0, 0.1)
exact_energies = []
vqe_energies = []
optimizer = SLSQP(maxiter=5)
for dist in distances:
qubitOp, num_particles, num_spin_orbitals, shift = get_qubit_op(dist)
result = NumPyEigensolver(qubitOp).run()
exact_energies.append(np.real(result.eigenvalues) + shift)
initial_state = HartreeFock(
num_spin_orbitals,
num_particles,
qubit_mapping='parity'
)
var_form = UCCSD(
num_orbitals=num_spin_orbitals,
num_particles=num_particles,
initial_state=initial_state,
qubit_mapping='parity'
)
vqe = VQE(qubitOp, var_form, optimizer)
vqe_result = np.real(vqe.run(backend)['eigenvalue'] + shift)
vqe_energies.append(vqe_result)
print("Interatomic Distance:", np.round(dist, 2), "VQE Result:", vqe_result, "Exact Energy:", exact_energies[-1])
print("All energies have been calculated")
plt.plot(distances, exact_energies, label="Exact Energy")
plt.plot(distances, vqe_energies, label="VQE Energy")
plt.xlabel('Atomic distance (Angstrom)')
plt.ylabel('Energy')
plt.legend()
plt.show()
|
https://github.com/quantumyatra/quantum_computing
|
quantumyatra
|
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.visualization import plot_histogram, plot_bloch_multivector
import numpy as np
import pylab as plt
def NOT(input_bit):
# initialize the QC
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q,c)
# for input 1 flip the q[0] to 1
if input_bit=='1':
qc.x(q[0])
# now do a NOT gate by flipping the q[0]
qc.x(q[0])
qc.measure( q[0], c[0] )
# now exectue the circuit
backend = Aer.get_backend('qasm_simulator')
counts = execute(qc,backend,shots=1000).result().get_counts()
return counts
NOT('1')
def XOR(input1, input2):
# initialize the QC
q = QuantumRegister(2)
c = ClassicalRegister(1)
qc = QuantumCircuit(q,c)
####################################
#
# DO something here...
# the code in the book doesn't do anything
# so it gives 0 always irrespective of the inputs
####################################
qc.measure( q[1], c[0] )
# now exectue the circuit
backend = Aer.get_backend('qasm_simulator')
counts = execute(qc,backend,shots=1000, memory=True).result().get_memory()[0]
return counts
XOR('1', '1')
def AND(input1, input2):
# initialize the QC
q = QuantumRegister(3)
c = ClassicalRegister(1)
qc = QuantumCircuit(q,c)
####################################
#
# DO something here...
# the code in the book only gives 0 always
####################################
qc.measure( q[2], c[0] )
# now exectue the circuit
backend = Aer.get_backend('qasm_simulator')
counts = execute(qc,backend,shots=1000, memory=True).result().get_memory()[0]
return counts
XOR('1', '1')
def AND(input1,input2):
q = QuantumRegister(3) # two qubits in which to encode the input, and one for the output
c = ClassicalRegister(1) # a bit to store the output
qc = QuantumCircuit(q, c) # this is where the quantum program goes
# YOUR QUANTUM PROGRAM GOES HERE
qc.measure(q[2],c[0]) # YOU CAN CHANGE THIS IF YOU WANT TO
# We'll run the program on a simulator
backend = Aer.get_backend('qasm_simulator')
# Since the output will be deterministic, we can use just a single shot to get it
job = execute(qc,backend,shots=1,memory=True)
output = job.result().get_memory()[0]
return output
|
https://github.com/quantumyatra/quantum_computing
|
quantumyatra
|
import numpy as np
#from qiskit import *
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.visualization import plot_histogram, plot_gate_map, plot_circuit_layout
from qiskit.tools.monitor import job_monitor
import matplotlib.pyplot as plt
%matplotlib inline
IBMQ.load_account()
provider = IBMQ.get_provider(group='open')
ghz = QuantumCircuit(5,5)
ghz.h(0)
for idx in range(1,5):
ghz.cx(0,idx)
ghz.barrier(range(5))
ghz.measure(range(5), range(5))
ghz.draw(output='mpl')
from qiskit import transpile
import inspect
inspect.signature(transpile)
provider = IBMQ.get_provider(group='open')
provider.backends(simulator=False)
backend = provider.get_backend('ibmqx2')
backend.configuration().basis_gates
qc = QuantumCircuit(2,1)
qc.h(0)
qc.x(1)
qc.cu1(np.pi/4, 0, 1)
# cu1 is controlled u1 just like CNOT is controlled NOT
qc.h(0)
qc.measure([0], [0])
qc.draw(output='mpl')
qc_basis = qc.decompose()
qc_basis.draw(output='mpl')
print(qc.depth(), ',', qc_basis.depth())
swap_circ = QuantumCircuit(2)
display ( swap_circ.draw(output='mpl') )
swap_circ.swap(0, 1)
display ( swap_circ.decompose().draw(output='mpl') )
ccx_circ = QuantumCircuit(3)
ccx_circ.ccx(0, 1, 2)
ccx_circ.decompose().draw(output='mpl')
backend = provider.get_backend('ibmq_16_melbourne')
plot_gate_map(backend, plot_directed=True)
new_circ_lv0 = transpile(ghz, backend=backend, optimization_level=0)
plot_circuit_layout(new_circ_lv0, backend )
backend = provider.get_backend('ibmq_16_melbourne')
new_circ_lv3 = transpile(ghz, backend=backend, optimization_level=3)
print('Depth:', new_circ_lv3.depth())
plot_circuit_layout(new_circ_lv3, backend)
#job1 = execute(new_circ_lv3, backend)
#job_monitor(job1)
# Virtual -> physical
# 0 -> 11
# 1 -> 12
# 2 -> 10
# 3 -> 2
# 4 -> 4
good_ghz = transpile(ghz, backend, initial_layout=[11,12,10,2,4])
print('Depth:', good_ghz.depth())
plot_circuit_layout(good_ghz, backend)
|
https://github.com/quantumyatra/quantum_computing
|
quantumyatra
|
from qiskit import QuantumCircuit, execute, Aer
from qiskit.visualization import plot_histogram
# For Jupyter Notebooks
%config InlineBackend.figure_format = 'svg' # Makes the images look nice
from qiskit_textbook.widgets import binary_widget
binary_widget(nbits=5)
n = 8
n_q = n
n_b = n
qc_output = QuantumCircuit(n_q,n_b)
for j in range(n):
qc_output.measure(j,j)
qc_output.draw(output='mpl')
counts = execute(qc_output,Aer.get_backend('qasm_simulator')).result().get_counts()
plot_histogram(counts)
qc_encode = QuantumCircuit(n)
qc_encode.x(7)
qc_encode.draw(output='mpl')
qc = qc_encode + qc_output
qc.draw(output='mpl',justify='none')
counts = execute(qc,Aer.get_backend('qasm_simulator')).result().get_counts()
plot_histogram(counts)
qc_encode = QuantumCircuit(n)
qc_encode.x(1)
qc_encode.x(5)
qc_encode.draw(output='mpl')
qc_cnot = QuantumCircuit(2)
qc_cnot.cx(0,1)
qc_cnot.draw(output='mpl')
qc = QuantumCircuit(2,2)
qc.x(0)
qc.cx(0,1)
qc.measure(0,0)
qc.measure(1,1)
qc.draw(output='mpl')
qc_ha = QuantumCircuit(4,2)
# encode inputs in qubits 0 and 1
qc_ha.x(0) # For a=0, remove this line. For a=1, leave it.
qc_ha.x(1) # For b=0, remove this line. For b=1, leave it.
qc_ha.barrier()
# use cnots to write the XOR of the inputs on qubit 2
qc_ha.cx(0,2)
qc_ha.cx(1,2)
qc_ha.barrier()
# extract outputs
qc_ha.measure(2,0) # extract XOR value
qc_ha.measure(3,1)
qc_ha.draw(output='mpl')
qc_ha = QuantumCircuit(4,2)
# encode inputs in qubits 0 and 1
qc_ha.x(0) # For a=0, remove the this line. For a=1, leave it.
qc_ha.x(1) # For b=0, remove the this line. For b=1, leave it.
qc_ha.barrier()
# use cnots to write the XOR of the inputs on qubit 2
qc_ha.cx(0,2)
qc_ha.cx(1,2)
# use ccx to write the AND of the inputs on qubit 3
qc_ha.ccx(0,1,3)
qc_ha.barrier()
# extract outputs
qc_ha.measure(2,0) # extract XOR value
qc_ha.measure(3,1) # extract AND value
qc_ha.draw(output='mpl')
counts = execute(qc_ha,Aer.get_backend('qasm_simulator')).result().get_counts()
plot_histogram(counts)
import qiskit
qiskit.__qiskit_version__
|
https://github.com/quantumyatra/quantum_computing
|
quantumyatra
|
import numpy as np
from sklearn.datasets.samples_generator import make_blobs
from qiskit.aqua.utils import split_dataset_to_data_and_labels
from sklearn import svm
from utility import breast_cancer_pca
from matplotlib import pyplot as plt
%matplotlib inline
%load_ext autoreload
%autoreload 2
n = 2 # number of principal components kept
training_dataset_size = 20
testing_dataset_size = 10
sample_Total, training_input, test_input, class_labels = breast_cancer_pca(training_dataset_size, testing_dataset_size, n)
data_train, _ = split_dataset_to_data_and_labels(training_input)
data_test, _ = split_dataset_to_data_and_labels(test_input)
print (f"data_train[0].shape: {data_train[0].shape}" )
print (f"data_train[1].shape: {data_train[1].shape}" )
# We use the function of scikit learn to generate linearly separable blobs
centers = [(2.5,0),(0,2.5)]
x, y = make_blobs(n_samples=100, centers=centers, n_features=2,random_state=0,cluster_std=0.5)
fig,ax=plt.subplots(1,2,figsize=(12,4))
ax[0].scatter(data_train[0][:,0],data_train[0][:,1],c=data_train[1])
ax[0].set_title('Breast Cancer dataset');
ax[1].scatter(x[:,0],x[:,1],c=y)
ax[1].set_title('Blobs linearly separable');
plt.scatter(data_train[0][:,0],data_train[0][:,1],c=data_train[1])
plt.title('Breast Cancer dataset');
model= svm.LinearSVC()
model.fit(data_train[0], data_train[1])
#small utility function
# some utility functions
def make_meshgrid(x, y, h=.02):
x_min, x_max = x.min() - 1, x.max() + 1
y_min, y_max = y.min() - 1, y.max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
np.arange(y_min, y_max, h))
return xx, yy
def plot_contours(ax, clf, xx, yy, **params):
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
out = ax.contourf(xx, yy, Z, **params)
return out
accuracy_train = model.score(data_train[0], data_train[1])
accuracy_test = model.score(data_test[0], data_test[1])
X0, X1 = data_train[0][:, 0], data_train[0][:, 1]
xx, yy = make_meshgrid(X0, X1)
Z = model.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
fig,ax=plt.subplots(1,2,figsize=(15,5))
ax[0].contourf(xx, yy, Z, cmap=plt.cm.coolwarm)
ax[0].scatter(data_train[0][:,0], data_train[0][:,1], c=data_train[1])
ax[0].set_title('Accuracy on the training set: '+str(accuracy_train));
ax[1].contourf(xx, yy, Z, cmap=plt.cm.coolwarm)
ax[1].scatter(data_test[0][:,0], data_test[0][:,1], c=data_test[1])
ax[1].set_title('Accuracy on the test set: '+str(accuracy_test));
clf = svm.SVC(gamma = 'scale')
clf.fit(data_train[0], data_train[1]);
accuracy_train = clf.score(data_train[0], data_train[1])
accuracy_test = clf.score(data_test[0], data_test[1])
X0, X1 = data_train[0][:, 0], data_train[0][:, 1]
xx, yy = make_meshgrid(X0, X1)
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
fig,ax=plt.subplots(1,2,figsize=(15,5))
ax[0].contourf(xx, yy, Z, cmap=plt.cm.coolwarm)
ax[0].scatter(data_train[0][:,0], data_train[0][:,1], c=data_train[1])
ax[0].set_title('Accuracy on the training set: '+str(accuracy_train));
ax[1].contourf(xx, yy, Z, cmap=plt.cm.coolwarm)
ax[1].scatter(data_test[0][:,0], data_test[0][:,1], c=data_test[1])
ax[1].set_title('Accuracy on the test set: '+str(accuracy_test));
import qiskit as qk
# Creating Qubits
q = qk.QuantumRegister(2)
# Creating Classical Bits
c = qk.ClassicalRegister(2)
circuit = qk.QuantumCircuit(q, c)
circuit.draw('mpl')
# Initialize empty circuit
circuit = qk.QuantumCircuit(q, c)
# Hadamard Gate on the first Qubit
circuit.h(q[0])
# CNOT Gate on the first and second Qubits
circuit.cx(q[0], q[1])
# Measuring the Qubits
circuit.measure(q, c)
circuit.draw('mpl')
# Using Qiskit Aer's Qasm Simulator: Define where do you want to run the simulation.
simulator = qk.BasicAer.get_backend('qasm_simulator')
# Simulating the circuit using the simulator to get the result
job = qk.execute(circuit, simulator, shots=100)
result = job.result()
# Getting the aggregated binary outcomes of the circuit.
counts = result.get_counts(circuit)
print (counts)
from qiskit.aqua.components.feature_maps import SecondOrderExpansion
feature_map = SecondOrderExpansion(feature_dimension=2, depth=1)
x = np.array([0.6, 0.3])
#feature_map.construct_circuit(x)
print(feature_map.construct_circuit(x))
from qiskit.aqua.algorithms import QSVM
qsvm = QSVM(feature_map, training_input, test_input)
#from qiskit.aqua import run_algorithm, QuantumInstance
from qiskit.aqua import algorithm, QuantumInstance
from qiskit import BasicAer
backend = BasicAer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, shots=1024, seed_simulator=10598, seed_transpiler=10598)
result = qsvm.run(quantum_instance)
plt.scatter(training_input['Benign'][:,0], training_input['Benign'][:,1])
plt.scatter(training_input['Malignant'][:,0], training_input['Malignant'][:,1])
length_data = len(training_input['Benign']) + len(training_input['Malignant'])
print("size training set: {}".format(length_data))
#print("Matrix dimension: {}".format(result['kernel_matrix_training'].shape))
print("testing success ratio: ", result['testing_accuracy'])
test_set = np.concatenate((test_input['Benign'], test_input['Malignant']))
y_test = qsvm.predict(test_set, quantum_instance)
plt.scatter(test_set[:, 0], test_set[:,1], c=y_test)
plt.show()
plt.scatter(test_input['Benign'][:,0], test_input['Benign'][:,1])
plt.scatter(test_input['Malignant'][:,0], test_input['Malignant'][:,1])
plt.show()
|
https://github.com/quantumyatra/quantum_computing
|
quantumyatra
|
from qiskit import QuantumRegister, QuantumCircuit, execute, Aer
cq = QuantumRegister(2,'code\_qubit')
lq = QuantumRegister(1,'link\_qubit')
qc = QuantumCircuit(cq,lq)
qc.cx(cq[0],lq[0])
qc.cx(cq[1],lq[0])
print(qc)
qc.draw('mpl')
from qiskit.ignis.verification.topological_codes import RepetitionCode
from qiskit.ignis.verification.topological_codes import GraphDecoder
from qiskit.ignis.verification.topological_codes import lookuptable_decoding, postselection_decoding
d = 2
T = 1
code = RepetitionCode(d,T)
code.circuit
print ( 'code_bits:', code.code_bit, ' d=', code.d, ' T=', code.T)
code.qubit_registers
code.code_qubit
for bit in ['0','1']:
print('\n========= logical',bit,'=========\n')
print( code.circuit[bit] )
d = 2
T = 1
code = RepetitionCode(d,T)
for bit in ['0','1']:
print('\n========= logical',bit,'=========\n')
print( code.circuit[bit] )
empty_code = RepetitionCode(3,0)
def print_circuits(code):
for log in ['0','1']:
print('\n========= logical',log,'=========\n')
print( code.circuit[log] )
print_circuits(empty_code)
empty_code.syndrome_measurement()
print_circuits(empty_code)
empty_code.x()
print_circuits(empty_code)
empty_code.readout()
print_circuits(empty_code)
circuits = code.get_circuit_list()
job = execute( circuits, Aer.get_backend('qasm_simulator') )
raw_results = {}
for log in ['0','1']:
raw_results[log] = job.result().get_counts(log)
print('\n========= logical',log,'=========\n')
print(raw_results[log])
|
https://github.com/quantumyatra/quantum_computing
|
quantumyatra
|
#!/usr/bin/env python3
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import Aer, execute, BasicAer
import numpy as np
import matplotlib.pyplot as plt
def get_state_vector(qc):
backend = BasicAer.get_backend('statevector_simulator')
res = execute(qc, backend).result()
return res.get_statevector(qc, decimals=3)
def create_bell_pair(qc, a, b):
qc.h(a)
qc.cx(a,b)
import numpy as np
import matplotlib.pyplot as plt
import sklearn
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklearn.decomposition import PCA
def breast_cancer_pca(training_size, test_size, n, PLOT_DATA=False):
class_labels = [r'Benign', r'Malignant']
# First the dataset must be imported.
cancer = sklearn.datasets.load_breast_cancer()
# Here the data is divided into 70% training, 30% testing.
X_train, X_test, Y_train, Y_test = train_test_split(cancer.data, cancer.target, test_size=0.3, random_state=109)
# features will be standardized to fit a normal distribution.
scaler = StandardScaler().fit(X_train)
X_train = scaler.transform(X_train)
X_test = scaler.transform(X_test)
# To be able to use this data with the given
# number of qubits, the data must be broken down from
# 30 dimensions to `n` dimensions.
# This is done with Principal Component Analysis (PCA),
# which finds patterns while keeping variation.
pca = PCA(n_components=n).fit(X_train)
X_train = pca.transform(X_train)
X_test = pca.transform(X_test)
# The last step in the data processing is
# to scale the data to be between -1 and 1
samples = np.append(X_train, X_test, axis=0)
minmax_scale = MinMaxScaler((-1, 1)).fit(samples)
X_train = minmax_scale.transform(X_train)
X_test = minmax_scale.transform(X_test)
# Now some sample should be picked to train the model from
training_input = {key: (X_train[Y_train == k, :])[:training_size] for k, key in enumerate(class_labels)}
test_input = {key: (X_train[Y_train == k, :])[training_size:(
training_size+test_size)] for k, key in enumerate(class_labels)}
if PLOT_DATA:
for k in range(0, 2):
x_axis_data = X_train[Y_train == k, 0][:training_size]
y_axis_data = X_train[Y_train == k, 1][:training_size]
label = 'Malignant' if k==1 else 'Benign'
plt.scatter(x_axis_data, y_axis_data, label=label)
plt.title("Breast Cancer Dataset (Dimensionality Reduced With PCA)")
plt.legend()
plt.show()
return X_train, training_input, test_input, class_labels
|
https://github.com/quantumyatra/quantum_computing
|
quantumyatra
|
from jupyter_widget_engine import jupyter_widget_engine
def start(engine):
# set text under screen
engine.screen['text'].description = 'Press any button to begin...'
# set some parameters
engine.started = False
engine.pos = (8,8)
engine.f = 0
def next_frame (engine):
if not engine.started:
# record that the game has started
engine.started = True
# change text under screen
engine.screen['text'].description = 'The game is afoot!'
# set initial player position
(x,y) = engine.pos
engine.screen[x,y].button_style = 'info'
else:
# display frame number in top left corner
engine.f += 1
engine.screen[0,0].description = str(engine.f)
# get current position
(x,y) = engine.pos
# removed player from current position
engine.screen[x,y].button_style = ''
# update based on controller input
if engine.controller['up'].value:
y -= 1
if engine.controller['down'].value:
y += 1
if engine.controller['left'].value:
x -= 1
if engine.controller['right'].value:
x += 1
# put player at new position
engine.screen[x,y].button_style = 'info'
# store new position
engine.pos = (x,y)
engine = jupyter_widget_engine(start,next_frame,L=16)
|
https://github.com/quantumyatra/quantum_computing
|
quantumyatra
|
import numpy as np
import pylab as plt
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.visualization import plot_histogram, plot_bloch_multivector
damage = 0 # damage to the enemy
def attack(damage):
damage = min ( (damage +1/3.), 1 )
return damage
damage = attack(damage)
print (damage)
%matplotlib inline
def plot_satevector(qc):
backend_sv = Aer.get_backend('statevector_simulator')
sv = execute(qc, backend=backend_sv).result().get_statevector()
fig = plot_bloch_multivector(sv)
return fig
qcc = QuantumCircuit(1,1)
qcc.x(0)
fig = plot_satevector(qcc)
fig
damage_qc = QuantumCircuit(1,1)
def attack(damage_qc):
damage_qc.rx(np.pi/3,0)
fig = plot_satevector(damage_qc)
fig
return fig
meas = QuantumCircuit(1,1)
meas.measure(0,0)
fig = attack(damage_qc)
fig
#qc = damage_qc+meas
#counts = execute(qc, Aer.get_backend('qasm_simulator'), shots=1000).result().get_counts()
#print(counts)
#qc.draw('mpl')
def get_damage(damage_qc):
meas = QuantumCircuit(1,1)
meas.measure(0,0)
attack(damage_qc)
Nshots=1000
counts = execute(damage_qc+meas, backend=Aer.get_backend('qasm_simulator'), shots=Nshots).result().get_counts()
damage = counts['1']/Nshots
return damage
damage_qc = QuantumCircuit(1,1)
damage = get_damage(damage_qc)
print(damage)
#damage = attack(damage_qc)
#get_damage(damage)
#damage_qc.draw()
meas = QuantumCircuit(1,1)
meas.measure(0,0)
damage_qc = attack(damage_qc)
qc = damage_qc+meas
counts = execute(qc, Aer.get_backend('qasm_simulator'), shots=1000).result().get_counts()
print(counts)
qc.draw()
#some tests
qc = QuantumCircuit(1,1)
backend = Aer.get_backend('qasm_simulator')
counts = execute(qc, backend=Aer.get_backend('qasm_simulator'), shots=1000).result().get_counts()
counts
!git clone https://github.com/quantumjim/jupyter-widget-game-engine/
!mv jupyter-widget-game-engine/jupyter_widget_engine.py jupyter_widget_engine.py
!mv jupyter-widget-game-engine/jupyter_widget_game.ipynb jupyter_widget_game.ipynb
!rm -r jupyter-widget-game-engine
from jupyter_widget_engine import jupyter_widget_engine
L = 8
def start(engine):
pass
def next_frame(engine):
pass
engine = jupyter_widget_engine(start, next_frame, L=L)
def get_terrain(x,y):
return 'grass'
L = 8
def start(engine):
engine.get_terrain = get_terrain
engine.next_frame(engine)
def next_frame(engine):
for x in range(L):
for y in range(L):
#terrain = engine.get_terrain(x,y)
if engine.get_terrain(x,y) == 'grass':
engine.screen[x,y].button_style = 'success'
engine = jupyter_widget_engine(start, next_frame, L=L)
def get_terrain(x,y):
qc = QuantumCircuit(1,1) # make a circuit
# perform rotations, whose angles depend on x and y
qc.rx( (np.pi/16)*(x+y) ,0)
qc.rx( (np.pi/16)*(x-y) ,0)
# calculate probability for outcome 1
qc.measure(0,0)
counts = execute(qc, Aer.get_backend('qasm_simulator'), shots=1000).result().get_counts()
if '1' in counts:
h = counts['1']/1000
else:
h = 0
# return terrain depending on this probability
# the chosen values here are fairly arbitrarily
if h<0.3:
terrain = 'sea'
elif h<0.7:
terrain = 'sand'
else:
terrain = 'grass'
return terrain
L = 8
def start(engine):
engine.get_terrain = get_terrain
engine.next_frame(engine)
def next_frame(engine):
for x in range(L):
for y in range(L):
terrain = engine.get_terrain(x,y)
if terrain == 'grass':
engine.screen[x,y].button_style = 'success'
elif terrain == 'sand':
engine.screen[x,y].button_style = 'warning'
else:
engine.screen[x,y].button_style = 'info'
engine = jupyter_widget_engine(start, next_frame, L=L)
L = 8
def start(engine):
engine.get_terrain = get_terrain
engine.p_x = 4
engine.p_y = 4
engine.next_frame(engine)
def next_frame(engine):
if engine.controller['up'].value:
engine.p_y -= 1
if engine.controller['down'].value:
engine.p_y += 1
if engine.controller['left'].value:
engine.p_x -= 1
if engine.controller['right'].value:
engine.p_x += 1
s_x = np.floor(engine.p_x/L)
s_y = np.floor(engine.p_y/L)
for x in range(L):
for y in range(L):
terrain = engine.get_terrain(L*s_x+x,L*s_y+y)
if terrain == 'grass':
engine.screen[x,y].button_style = 'success'
elif terrain == 'sand':
engine.screen[x,y].button_style = 'warning'
else:
engine.screen[x,y].button_style = 'info'
engine.screen[engine.p_x%L, engine.p_y%L].button_style = 'danger'
engine = jupyter_widget_engine(start, next_frame, L=L)
|
https://github.com/quantumyatra/quantum_computing
|
quantumyatra
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Utils for using with Qiskit unit tests."""
import logging
import os
import unittest
from enum import Enum
from qiskit import __path__ as qiskit_path
class Path(Enum):
"""Helper with paths commonly used during the tests."""
# Main SDK path: qiskit/
SDK = qiskit_path[0]
# test.python path: qiskit/test/python/
TEST = os.path.normpath(os.path.join(SDK, '..', 'test', 'python'))
# Examples path: examples/
EXAMPLES = os.path.normpath(os.path.join(SDK, '..', 'examples'))
# Schemas path: qiskit/schemas
SCHEMAS = os.path.normpath(os.path.join(SDK, 'schemas'))
# VCR cassettes path: qiskit/test/cassettes/
CASSETTES = os.path.normpath(os.path.join(TEST, '..', 'cassettes'))
# Sample QASMs path: qiskit/test/python/qasm
QASMS = os.path.normpath(os.path.join(TEST, 'qasm'))
def setup_test_logging(logger, log_level, filename):
"""Set logging to file and stdout for a logger.
Args:
logger (Logger): logger object to be updated.
log_level (str): logging level.
filename (str): name of the output file.
"""
# Set up formatter.
log_fmt = ('{}.%(funcName)s:%(levelname)s:%(asctime)s:'
' %(message)s'.format(logger.name))
formatter = logging.Formatter(log_fmt)
# Set up the file handler.
file_handler = logging.FileHandler(filename)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
# Set the logging level from the environment variable, defaulting
# to INFO if it is not a valid level.
level = logging._nameToLevel.get(log_level, logging.INFO)
logger.setLevel(level)
class _AssertNoLogsContext(unittest.case._AssertLogsContext):
"""A context manager used to implement TestCase.assertNoLogs()."""
# pylint: disable=inconsistent-return-statements
def __exit__(self, exc_type, exc_value, tb):
"""
This is a modified version of TestCase._AssertLogsContext.__exit__(...)
"""
self.logger.handlers = self.old_handlers
self.logger.propagate = self.old_propagate
self.logger.setLevel(self.old_level)
if exc_type is not None:
# let unexpected exceptions pass through
return False
if self.watcher.records:
msg = 'logs of level {} or higher triggered on {}:\n'.format(
logging.getLevelName(self.level), self.logger.name)
for record in self.watcher.records:
msg += 'logger %s %s:%i: %s\n' % (record.name, record.pathname,
record.lineno,
record.getMessage())
self._raiseFailure(msg)
|
https://github.com/PKXH/quantum-algorithms
|
PKXH
|
from random import randint,sample
def get_random_bitstring(sz):
return [randint(0,1) for i in range(sz)]
from qiskit import (QuantumCircuit, execute, Aer)
default_backend = Aer.get_backend('qasm_simulator')
X_BASIS = 0
Z_BASIS = 1
def encode_key_bit(qbit, tx_bit, tx_base):
'''
Append encoding of the specified classical bit 'tx_bit' into the specified
base 'tx_base' to the quantum circuit
'''
# flip the quantum 0 to quantum 1 if we received a '1' bit; otherwise leave
# it as a quantum 0.
if tx_bit:
qbit.x(0)
# if we're transmitting using the x-basis, then leave it in the x-basis;
# otherwise flip the qubit into the z-basis
if tx_base == Z_BASIS:
qbit.h(0)
return qbit
def decode_key_bit(qbit, rx_base):
'''
Append measurement of the specified qubit 'qbit' in the specified base 'rx_base'
to the quantum circuit
'''
# flip the qubit if we're measureing in the Z_BASIS so if the qubit
# is originally in the X_BASIS, it will not be in superposition. Then
# go ahead and measure it.
if rx_base == Z_BASIS:
qbit.h(0)
qbit.measure([0],[0])
return qbit
datum = 1
tx_base = 1
rx_base = 1
test_qc = QuantumCircuit(1,1)
test_qc = encode_key_bit(test_qc,datum,tx_base)
test_qc.barrier(0)
test_qc = decode_key_bit(test_qc,rx_base)
test_qc.draw('mpl')
num_bits = 32
# set up Alice's transmission bits
random_tx_bits = get_random_bitstring(num_bits)
random_tx_bases = get_random_bitstring(num_bits)
# set up Bob's receiving bits
random_rx_bases = get_random_bitstring(num_bits)
decoded_rx_bits = []
class SharedChannel:
def __init__(self):
self.datum = None
self.active = False
def transmit_datum(self, datum):
self.datum = datum
self.active = True
def receive_datum(self):
return_datum = self.datum
self.active = False
self.datum = []
return return_datum
class SharedQuantumChannel(SharedChannel):
def __init__(self):
super().__init__()
class SharedClassicalChannel(SharedChannel):
def __init__(self):
super().__init__()
def transmit_data(self, datum):
super().transmit_datum(datum)
def receive_data(self):
return super().receive_datum()
# create shared quantum and classical channels that Alice and Bob will
# use to communicate to each other
sqc = SharedQuantumChannel()
scc = SharedClassicalChannel()
scc.transmit_datum('1')
print(scc.receive_datum())
# Clear decoded bits list and transmit the qbits one by one until the
# receiver has measured every one
decoded_rx_bits = []
for i in range(num_bits):
# create a qubit, encode it, transmit it, receive it,
# and decode it
qbit = QuantumCircuit(1,1)
tx_qbit = encode_key_bit(qbit, random_tx_bits[i], random_tx_bases[i])
sqc.transmit_datum(tx_qbit)
rx_qbit = sqc.receive_datum()
full_circuit = decode_key_bit(rx_qbit, random_rx_bases[i])
job = execute(full_circuit, backend=default_backend, shots=1)
results = job.result()
counts = results.get_counts()
decoded_rx_bits.append(int(max(counts, key=counts.get)))
# decoder reports rx bases to transmitter
scc.transmit_data(random_rx_bases)
rx_bases_used = scc.receive_data()
# sender determines which random rx bases were right
assert(len(rx_bases_used) == len(random_tx_bits))
rx_base_hits = [rx_bases_used[i] == random_tx_bases[i] for i in range(len(random_tx_bits))]
# sender notifies receiver of key hits
scc.transmit_data(rx_base_hits)
rcvd_rx_base_hits = scc.receive_data()
# sender and receiver drop non-hit key bits
sender_key_candidate = [j for i,j in enumerate(random_tx_bits) if rx_base_hits[i]]
receiver_key_candidate = [j for i,j in enumerate(decoded_rx_bits) if rcvd_rx_base_hits[i]]
assert(sender_key_candidate == receiver_key_candidate)
# the receiver chooses some verification bits (1/4th of the decoded key bits)
num_verify_bits = len(receiver_key_candidate)//4
verify_bits_ix = sample(range(len(receiver_key_candidate)), num_verify_bits)
verify_bits = {i:receiver_key_candidate[i] for i in verify_bits_ix}
# the receiver shares verification bits with sender
scc.transmit_data(verify_bits)
chk_verify_bits = scc.receive_data()
assert(verify_bits == chk_verify_bits)
# verify the check bits
verified = all([verify_bits[i] == sender_key_candidate[i] for i in verify_bits.keys()])
# if the check bits check out, strip them out of the key and we're done
if verified:
sender_key = [j for i,j in enumerate(sender_key_candidate) if i not in chk_verify_bits.keys()]
receiver_key = [j for i,j in enumerate(receiver_key_candidate) if i not in verify_bits.keys()]
assert(sender_key == receiver_key)
print('skey: ' + str(sender_key))
print('rkey: ' + str(receiver_key))
|
https://github.com/PKXH/quantum-algorithms
|
PKXH
|
from qiskit import (QuantumCircuit, execute, Aer)
from functools import partial
default_backend = Aer.get_backend('qasm_simulator')
def run_qc_using_backend(backend, qc):
job = execute(qc, backend)
return job.result()
def get_quantum_random_bitstring(sz=1, dump_circuit=False, runner = partial(run_qc_using_backend, default_backend)):
qc = QuantumCircuit(sz,sz)
for ch in range(sz):
qc.h(ch)
qc.measure([ch],[ch])
if dump_circuit:
return qc
else:
return runner(qc)
t = get_quantum_random_bitstring(8,dump_circuit=True)
t.draw('mpl')
from random import randint,sample
def get_random_bitstring(sz):
return [randint(0,1) for i in range(sz)]
t = get_random_bitstring(16)
print(t)
|
https://github.com/codigoscupom/QuantumAlgs
|
codigoscupom
|
import qiskit as q
from qiskit.visualization import plot_histogram, plot_bloch_multivector
import math
qasm_sim = q.Aer.get_backend('qasm_simulator')
statevec_sim = q.Aer.get_backend("statevector_simulator")
c = q.QuantumCircuit(2,2)
c.ry(math.pi/4,0)
c.ry(math.pi/4,1)
orig_statevec = q.execute(c, backend=statevec_sim).result().get_statevector()
c.measure([0,1], [0,1]) # measuring qubit 3, which is impacted by those cnots:
orig_counts = q.execute(c, backend=qasm_sim, shots=1024).result().get_counts()
plot_bloch_multivector(orig_statevec)
|
https://github.com/codigoscupom/QuantumAlgs
|
codigoscupom
|
import numpy as np
from qiskit import *
# Create a Quantum Circuit acting on a quantum register of three qubits
circ = QuantumCircuit(3)
# Add a H gate on qubit 0, putting this qubit in superposition.
circ.h(0)
# Add a CX (CNOT) gate on control qubit 0 and target qubit 1, putting
# the qubits in a Bell state.
circ.cx(0, 1)
# Add a CX (CNOT) gate on control qubit 0 and target qubit 2, putting
# the qubits in a GHZ state.
circ.cx(0, 2)
# circ.draw('mpl')
|
https://github.com/codigoscupom/QuantumAlgs
|
codigoscupom
|
## Programming Quantum Computers
## by Eric Johnston, Nic Harrigan and Mercedes Gimeno-Segovia
## O'Reilly Media
##
## More samples like this can be found at http://oreilly-qc.github.io
## This sample generates a single random bit.
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ, BasicAer
import math
## Uncomment the next line to see diagrams when running in a notebook
#%matplotlib inline
## Example 2-1: Random bit
# Set up the program
reg = QuantumRegister(1, name='reg')
reg_c = ClassicalRegister(1, name='regc')
qc = QuantumCircuit(reg, reg_c)
qc.reset(reg) # write the value 0
qc.h(reg) # put it into a superposition of 0 and 1
result = qc.measure(reg, reg_c) # read the result as a digital bit
backend = BasicAer.get_backend('statevector_simulator')
job = execute(qc, backend)
result = job.result()
print('result: ', result)
counts = result.get_counts(qc)
print('counts:',counts)
# outputstate = result.get_statevector(qc, decimals=3)
# print(outputstate)
# qc.draw() # draw the circuit
|
https://github.com/codigoscupom/QuantumAlgs
|
codigoscupom
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import logging
import math
import numpy as np
from sklearn.utils import shuffle
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
from qiskit.aqua import Pluggable, PluggableType, get_pluggable_class, AquaError
from qiskit.aqua.components.feature_maps import FeatureMap
from qiskit.aqua.utils import get_feature_dimension
from qiskit.aqua.utils import map_label_to_class_name
from qiskit.aqua.utils import split_dataset_to_data_and_labels
from qiskit.aqua.utils import find_regs_by_name
from qiskit.aqua.algorithms.adaptive.vq_algorithm import VQAlgorithm
logger = logging.getLogger(__name__)
def assign_label(measured_key, num_classes):
"""
Classes = 2:
- If odd number of qubits we use majority vote
- If even number of qubits we use parity
Classes = 3
- We use part-parity
{ex. for 2 qubits: [00], [01,10], [11] would be the three labels}
Args:
measured_key (str): measured key
num_classes (int): number of classes
"""
measured_key = np.asarray([int(k) for k in list(measured_key)])
num_qubits = len(measured_key)
if num_classes == 2:
if num_qubits % 2 != 0:
total = np.sum(measured_key)
return 1 if total > num_qubits / 2 else 0
else:
hamming_weight = np.sum(measured_key)
is_odd_parity = hamming_weight % 2
return is_odd_parity
elif num_classes == 3:
first_half = int(np.floor(num_qubits / 2))
modulo = num_qubits % 2
# First half of key
hamming_weight_1 = np.sum(measured_key[0:first_half + modulo])
# Second half of key
hamming_weight_2 = np.sum(measured_key[first_half + modulo:])
is_odd_parity_1 = hamming_weight_1 % 2
is_odd_parity_2 = hamming_weight_2 % 2
return is_odd_parity_1 + is_odd_parity_2
else:
total_size = 2**num_qubits
class_step = np.floor(total_size / num_classes)
decimal_value = measured_key.dot(1 << np.arange(measured_key.shape[-1] - 1, -1, -1))
key_order = int(decimal_value / class_step)
return key_order if key_order < num_classes else num_classes - 1
def cost_estimate(probs, gt_labels, shots=None):
"""Calculate cross entropy
# shots is kept since it may be needed in future.
Args:
shots (int): the number of shots used in quantum computing
probs (numpy.ndarray): NxK array, N is the number of data and K is the number of class
gt_labels (numpy.ndarray): Nx1 array
Returns:
float: cross entropy loss between estimated probs and gt_labels
"""
mylabels = np.zeros(probs.shape)
for i in range(gt_labels.shape[0]):
whichindex = gt_labels[i]
mylabels[i][whichindex] = 1
def cross_entropy(predictions, targets, epsilon=1e-12):
predictions = np.clip(predictions, epsilon, 1. - epsilon)
N = predictions.shape[0]
tmp = np.sum(targets*np.log(predictions), axis=1)
ce = -np.sum(tmp)/N
return ce
x = cross_entropy(probs, mylabels)
return x
def cost_estimate_sigmoid(shots, probs, gt_labels):
"""Calculate sigmoid cross entropy
Args:
shots (int): the number of shots used in quantum computing
probs (numpy.ndarray): NxK array, N is the number of data and K is the number of class
gt_labels (numpy.ndarray): Nx1 array
Returns:
float: sigmoid cross entropy loss between estimated probs and gt_labels
"""
#Error in the order of parameters corrected below - 19 Dec 2018
#x = cost_estimate(shots, probs, gt_labels)
x = cost_estimate(probs, gt_labels, shots)
loss = (1.) / (1. + np.exp(-x))
return loss
def return_probabilities(counts, num_classes):
"""Return the probabilities of given measured counts
Args:
counts ([dict]): N data and each with a dict recording the counts
num_classes (int): number of classes
Returns:
numpy.ndarray: NxK array
"""
probs = np.zeros(((len(counts), num_classes)))
for idx in range(len(counts)):
count = counts[idx]
shots = sum(count.values())
for k, v in count.items():
label = assign_label(k, num_classes)
probs[idx][label] += v / shots
return probs
class VQC(VQAlgorithm):
CONFIGURATION = {
'name': 'VQC',
'description': 'Variational Quantum Classifier',
'input_schema': {
'$schema': 'http://json-schema.org/schema#',
'id': 'vqc_schema',
'type': 'object',
'properties': {
'override_SPSA_params': {
'type': 'boolean',
'default': True
},
'max_evals_grouped': {
'type': 'integer',
'default': 1
},
'minibatch_size': {
'type': 'integer',
'default': -1
}
},
'additionalProperties': False
},
'problems': ['classification'],
'depends': [
{
'pluggable_type': 'optimizer',
'default': {
'name': 'SPSA'
},
},
{
'pluggable_type': 'feature_map',
'default': {
'name': 'SecondOrderExpansion',
'depth': 2
},
},
{
'pluggable_type': 'variational_form',
'default': {
'name': 'RYRZ',
'depth': 3
},
},
],
}
def __init__(
self,
optimizer=None,
feature_map=None,
var_form=None,
training_dataset=None,
test_dataset=None,
datapoints=None,
max_evals_grouped=1,
minibatch_size=-1,
callback=None
):
"""Initialize the object
Args:
optimizer (Optimizer): The classical optimizer to use.
feature_map (FeatureMap): The FeatureMap instance to use.
var_form (VariationalForm): The variational form instance.
training_dataset (dict): The training dataset, in the format: {'A': np.ndarray, 'B': np.ndarray, ...}.
test_dataset (dict): The test dataset, in same format as `training_dataset`.
datapoints (np.ndarray): NxD array, N is the number of data and D is data dimension.
max_evals_grouped (int): The maximum number of evaluations to perform simultaneously.
minibatch_size (int): The size of a mini-batch.
callback (Callable): a callback that can access the intermediate data during the optimization.
Internally, four arguments are provided as follows the index of data batch, the index of evaluation,
parameters of variational form, evaluated value.
Notes:
We use `label` to denotes numeric results and `class` the class names (str).
"""
self.validate(locals())
super().__init__(
var_form=var_form,
optimizer=optimizer,
cost_fn=self._cost_function_wrapper
)
self._optimizer.set_max_evals_grouped(max_evals_grouped)
self._callback = callback
if feature_map is None:
raise AquaError('Missing feature map.')
if training_dataset is None:
raise AquaError('Missing training dataset.')
self._training_dataset, self._class_to_label = split_dataset_to_data_and_labels(
training_dataset)
self._label_to_class = {label: class_name for class_name, label
in self._class_to_label.items()}
self._num_classes = len(list(self._class_to_label.keys()))
if test_dataset is not None:
self._test_dataset = split_dataset_to_data_and_labels(test_dataset,
self._class_to_label)
else:
self._test_dataset = test_dataset
if datapoints is not None and not isinstance(datapoints, np.ndarray):
datapoints = np.asarray(datapoints)
self._datapoints = datapoints
self._minibatch_size = minibatch_size
self._eval_count = 0
self._ret = {}
self._feature_map = feature_map
self._num_qubits = feature_map.num_qubits
@classmethod
def init_params(cls, params, algo_input):
algo_params = params.get(Pluggable.SECTION_KEY_ALGORITHM)
override_spsa_params = algo_params.get('override_SPSA_params')
max_evals_grouped = algo_params.get('max_evals_grouped')
minibatch_size = algo_params.get('minibatch_size')
# Set up optimizer
opt_params = params.get(Pluggable.SECTION_KEY_OPTIMIZER)
# If SPSA then override SPSA params as reqd to our predetermined values
if opt_params['name'] == 'SPSA' and override_spsa_params:
opt_params['c0'] = 4.0
opt_params['c1'] = 0.1
opt_params['c2'] = 0.602
opt_params['c3'] = 0.101
opt_params['c4'] = 0.0
opt_params['skip_calibration'] = True
optimizer = get_pluggable_class(PluggableType.OPTIMIZER,
opt_params['name']).init_params(params)
# Set up feature map
fea_map_params = params.get(Pluggable.SECTION_KEY_FEATURE_MAP)
feature_dimension = get_feature_dimension(algo_input.training_dataset)
fea_map_params['feature_dimension'] = feature_dimension
feature_map = get_pluggable_class(PluggableType.FEATURE_MAP,
fea_map_params['name']).init_params(params)
# Set up variational form, we need to add computed num qubits
# Pass all parameters so that Variational Form can create its dependents
var_form_params = params.get(Pluggable.SECTION_KEY_VAR_FORM)
var_form_params['num_qubits'] = feature_map.num_qubits
var_form = get_pluggable_class(PluggableType.VARIATIONAL_FORM,
var_form_params['name']).init_params(params)
return cls(optimizer, feature_map, var_form, algo_input.training_dataset,
algo_input.test_dataset, algo_input.datapoints, max_evals_grouped,
minibatch_size)
def construct_circuit(self, x, theta, measurement=False):
"""
Construct circuit based on data and parameters in variational form.
Args:
x (numpy.ndarray): 1-D array with D dimension
theta ([numpy.ndarray]): list of 1-D array, parameters sets for variational form
measurement (bool): flag to add measurement
Returns:
QuantumCircuit: the circuit
"""
qr = QuantumRegister(self._num_qubits, name='q')
cr = ClassicalRegister(self._num_qubits, name='c')
qc = QuantumCircuit(qr, cr)
qc += self._feature_map.construct_circuit(x, qr)
qc += self._var_form.construct_circuit(theta, qr)
if measurement:
qc.barrier(qr)
qc.measure(qr, cr)
return qc
def _get_prediction(self, data, theta):
"""
Make prediction on data based on each theta.
Args:
data (numpy.ndarray): 2-D array, NxD, N data points, each with D dimension
theta ([numpy.ndarray]): list of 1-D array, parameters sets for variational form
Returns:
numpy.ndarray or [numpy.ndarray]: list of NxK array
numpy.ndarray or [numpy.ndarray]: list of Nx1 array
"""
# if self._quantum_instance.is_statevector:
# raise ValueError('Selected backend "{}" is not supported.'.format(
# self._quantum_instance.backend_name))
circuits = {}
circuit_id = 0
num_theta_sets = len(theta) // self._var_form.num_parameters
theta_sets = np.split(theta, num_theta_sets)
for theta in theta_sets:
for datum in data:
if self._quantum_instance.is_statevector:
circuit = self.construct_circuit(datum, theta, measurement=False)
else:
circuit = self.construct_circuit(datum, theta, measurement=True)
circuits[circuit_id] = circuit
circuit_id += 1
results = self._quantum_instance.execute(list(circuits.values()))
circuit_id = 0
predicted_probs = []
predicted_labels = []
for _ in theta_sets:
counts = []
for _ in data:
if self._quantum_instance.is_statevector:
temp = results.get_statevector(circuits[circuit_id])
outcome_vector = (temp * temp.conj()).real
# convert outcome_vector to outcome_dict, where key is a basis state and value is the count.
# Note: the count can be scaled linearly, i.e., it does not have to be an integer.
outcome_dict = {}
bitstr_size = int(math.log2(len(outcome_vector)))
for i in range(len(outcome_vector)):
bitstr_i = format(i, '0' + str(bitstr_size) + 'b')
outcome_dict[bitstr_i] = outcome_vector[i]
else:
outcome_dict = results.get_counts(circuits[circuit_id])
counts.append(outcome_dict)
circuit_id += 1
probs = return_probabilities(counts, self._num_classes)
predicted_probs.append(probs)
predicted_labels.append(np.argmax(probs, axis=1))
if len(predicted_probs) == 1:
predicted_probs = predicted_probs[0]
if len(predicted_labels) == 1:
predicted_labels = predicted_labels[0]
return predicted_probs, predicted_labels
# Breaks data into minibatches. Labels are optional, but will be broken into batches if included.
def batch_data(self, data, labels=None, minibatch_size=-1):
label_batches = None
if 0 < minibatch_size < len(data):
batch_size = min(minibatch_size, len(data))
if labels is not None:
shuffled_samples, shuffled_labels = shuffle(data, labels, random_state=self.random)
label_batches = np.array_split(shuffled_labels, batch_size)
else:
shuffled_samples = shuffle(data, random_state=self.random)
batches = np.array_split(shuffled_samples, batch_size)
else:
batches = np.asarray([data])
label_batches = np.asarray([labels])
return batches, label_batches
def is_gradient_really_supported(self):
return self.optimizer.is_gradient_supported and not self.optimizer.is_gradient_ignored
def train(self, data, labels, quantum_instance=None, minibatch_size=-1):
"""Train the models, and save results.
Args:
data (numpy.ndarray): NxD array, N is number of data and D is dimension
labels (numpy.ndarray): Nx1 array, N is number of data
quantum_instance (QuantumInstance): quantum backend with all setting
minibatch_size (int): the size of each minibatched accuracy evalutation
"""
self._quantum_instance = self._quantum_instance if quantum_instance is None else quantum_instance
minibatch_size = minibatch_size if minibatch_size > 0 else self._minibatch_size
self._batches, self._label_batches = self.batch_data(data, labels, minibatch_size)
self._batch_index = 0
if self.initial_point is None:
self.initial_point = self.random.randn(self._var_form.num_parameters)
self._eval_count = 0
grad_fn = None
if minibatch_size > 0 and self.is_gradient_really_supported(): # we need some wrapper
grad_fn = self._gradient_function_wrapper
self._ret = self.find_minimum(
initial_point=self.initial_point,
var_form=self.var_form,
cost_fn=self._cost_function_wrapper,
optimizer=self.optimizer,
gradient_fn = grad_fn # func for computing gradient
)
if self._ret['num_optimizer_evals'] is not None and self._eval_count >= self._ret['num_optimizer_evals']:
self._eval_count = self._ret['num_optimizer_evals']
self._eval_time = self._ret['eval_time']
logger.info('Optimization complete in {} seconds.\nFound opt_params {} in {} evals'.format(
self._eval_time, self._ret['opt_params'], self._eval_count))
self._ret['eval_count'] = self._eval_count
del self._batches
del self._label_batches
del self._batch_index
self._ret['training_loss'] = self._ret['min_val']
# temporary fix: this code should be unified with the gradient api in optimizer.py
def _gradient_function_wrapper(self, theta):
"""Compute and return the gradient at the point theta.
Args:
theta (numpy.ndarray): 1-d array
Returns:
numpy.ndarray: 1-d array with the same shape as theta. The gradient computed
"""
epsilon = 1e-8
f_orig = self._cost_function_wrapper(theta)
grad = np.zeros((len(theta),), float)
for k in range(len(theta)):
theta[k] += epsilon
f_new = self._cost_function_wrapper(theta)
grad[k] = (f_new - f_orig) / epsilon
theta[k] -= epsilon # recover to the center state
if self.is_gradient_really_supported():
self._batch_index += 1 # increment the batch after gradient callback
return grad
def _cost_function_wrapper(self, theta):
batch_index = self._batch_index % len(self._batches)
predicted_probs, predicted_labels = self._get_prediction(self._batches[batch_index], theta)
total_cost = []
if not isinstance(predicted_probs, list):
predicted_probs = [predicted_probs]
for i in range(len(predicted_probs)):
curr_cost = cost_estimate(predicted_probs[i], self._label_batches[batch_index])
total_cost.append(curr_cost)
if self._callback is not None:
self._callback(
self._eval_count,
theta[i * self._var_form.num_parameters:(i + 1) * self._var_form.num_parameters],
curr_cost,
self._batch_index
)
self._eval_count += 1
if not self.is_gradient_really_supported():
self._batch_index += 1 # increment the batch after eval callback
logger.debug('Intermediate batch cost: {}'.format(sum(total_cost)))
return total_cost if len(total_cost) > 1 else total_cost[0]
def test(self, data, labels, quantum_instance=None, minibatch_size=-1, params=None):
"""Predict the labels for the data, and test against with ground truth labels.
Args:
data (numpy.ndarray): NxD array, N is number of data and D is data dimension
labels (numpy.ndarray): Nx1 array, N is number of data
quantum_instance (QuantumInstance): quantum backend with all setting
minibatch_size (int): the size of each minibatched accuracy evalutation
params (list): list of parameters to populate in the variational form
Returns:
float: classification accuracy
"""
# minibatch size defaults to setting in instance variable if not set
minibatch_size = minibatch_size if minibatch_size > 0 else self._minibatch_size
batches, label_batches = self.batch_data(data, labels, minibatch_size)
self.batch_num = 0
if params is None:
params = self.optimal_params
total_cost = 0
total_correct = 0
total_samples = 0
self._quantum_instance = self._quantum_instance if quantum_instance is None else quantum_instance
for batch, label_batch in zip(batches, label_batches):
predicted_probs, predicted_labels = self._get_prediction(batch, params)
total_cost += cost_estimate(predicted_probs, label_batch)
total_correct += np.sum((np.argmax(predicted_probs, axis=1) == label_batch))
total_samples += label_batch.shape[0]
int_accuracy = np.sum((np.argmax(predicted_probs, axis=1) == label_batch)) / label_batch.shape[0]
logger.debug('Intermediate batch accuracy: {:.2f}%'.format(int_accuracy * 100.0))
total_accuracy = total_correct / total_samples
logger.info('Accuracy is {:.2f}%'.format(total_accuracy * 100.0))
self._ret['testing_accuracy'] = total_accuracy
self._ret['test_success_ratio'] = total_accuracy
self._ret['testing_loss'] = total_cost / len(batches)
return total_accuracy
def predict(self, data, quantum_instance=None, minibatch_size=-1, params=None):
"""Predict the labels for the data.
Args:
data (numpy.ndarray): NxD array, N is number of data, D is data dimension
quantum_instance (QuantumInstance): quantum backend with all setting
minibatch_size (int): the size of each minibatched accuracy evalutation
params (list): list of parameters to populate in the variational form
Returns:
list: for each data point, generates the predicted probability for each class
list: for each data point, generates the predicted label (that with the highest prob)
"""
# minibatch size defaults to setting in instance variable if not set
minibatch_size = minibatch_size if minibatch_size > 0 else self._minibatch_size
batches, _ = self.batch_data(data, None, minibatch_size)
if params is None:
params = self.optimal_params
predicted_probs = None
predicted_labels = None
self._quantum_instance = self._quantum_instance if quantum_instance is None else quantum_instance
for i, batch in enumerate(batches):
if len(batches) > 0:
logger.debug('Predicting batch {}'.format(i))
batch_probs, batch_labels = self._get_prediction(batch, params)
if not predicted_probs and not predicted_labels:
predicted_probs = batch_probs
predicted_labels = batch_labels
else:
np.concatenate((predicted_probs, batch_probs))
np.concatenate((predicted_labels, batch_labels))
self._ret['predicted_probs'] = predicted_probs
self._ret['predicted_labels'] = predicted_labels
return predicted_probs, predicted_labels
def _run(self):
self.train(self._training_dataset[0], self._training_dataset[1])
if self._test_dataset is not None:
self.test(self._test_dataset[0], self._test_dataset[1])
if self._datapoints is not None:
predicted_probs, predicted_labels = self.predict(self._datapoints)
self._ret['predicted_classes'] = map_label_to_class_name(predicted_labels,
self._label_to_class)
return self._ret
def get_optimal_cost(self):
if 'opt_params' not in self._ret:
raise AquaError("Cannot return optimal cost before running the algorithm to find optimal params.")
return self._ret['min_val']
def get_optimal_circuit(self):
if 'opt_params' not in self._ret:
raise AquaError("Cannot find optimal circuit before running the algorithm to find optimal params.")
return self._var_form.construct_circuit(self._ret['opt_params'])
def get_optimal_vector(self):
if 'opt_params' not in self._ret:
raise AquaError("Cannot find optimal vector before running the algorithm to find optimal params.")
qc = self.get_optimal_circuit()
if self._quantum_instance.is_statevector:
ret = self._quantum_instance.execute(qc)
self._ret['min_vector'] = ret.get_statevector(qc, decimals=16)
else:
c = ClassicalRegister(qc.width(), name='c')
q = find_regs_by_name(qc, 'q')
qc.add_register(c)
qc.barrier(q)
qc.measure(q, c)
ret = self._quantum_instance.execute(qc)
self._ret['min_vector'] = ret.get_counts(qc)
return self._ret['min_vector']
@property
def optimal_params(self):
if 'opt_params' not in self._ret:
raise AquaError("Cannot find optimal params before running the algorithm.")
return self._ret['opt_params']
@property
def ret(self):
return self._ret
@ret.setter
def ret(self, new_value):
self._ret = new_value
@property
def label_to_class(self):
return self._label_to_class
@property
def class_to_label(self):
return self._class_to_label
def load_model(self, file_path):
model_npz = np.load(file_path)
self._ret['opt_params'] = model_npz['opt_params']
def save_model(self, file_path):
model = {'opt_params': self._ret['opt_params']}
np.savez(file_path, **model)
@property
def test_dataset(self):
return self._test_dataset
@property
def training_dataset(self):
return self._training_dataset
@property
def datapoints(self):
return self._datapoints
|
https://github.com/Andres8bit/IBMQ-Quantum-Qiskit
|
Andres8bit
|
# There exists a theorem in Quantum mechanics called the
# No-Cloning Theorem: which states that you cannot simply
# make an exact copy of an unknown quantum state.
# However by taking advatange of two classical bits and an
# entangled qubit pair, we can transfer states.
# We call this Teleportation.
# To transfer a quantum bit, we must use a third prst to send them
# an entangled qubit pair.
%matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumCircuit, QuantumRegister,ClassicalRegister,execute, BasicAer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from qiskit_textbook.tools import random_state, array_to_latex
from qiskit.extensions import Initialize
import numpy as np
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
#Ex:
#creating our circuit:
qr = QuantumRegister(3) # three qubit system
crz = ClassicalRegister(1) # two different calssi
crx = ClassicalRegister(1)
teleportation_Circuit = QuantumCircuit(qr,crz,crx)
#STEP1:
# creating an entangled pair of qubits.
# This pair creates a special pair called a Bell pair.
# This is done by first placing one qubit into the X-basis:
# \+> and |->, using a Hadamard gate, then applying a CNOT
# gate onto the other qubit controlled by the on in the X-basis.
def create_bell_pair(qc,a,b):
""" Creates a bell pair in qc using qubits a and b"""
qc.h(a) #puts a into |+>
qc.cx(a,b) #CNOT with a as control
#creating our bell pair:
create_bell_pair(teleportation_Circuit,1,2)
teleportation_Circuit.draw()
#STEP2:
# We must apply a CNOT gate to the qubit being sent. Then we apply a Hadamard
# gate.
def teleportation_bit(qc,psi,a):
qc.cx(psi,a)
qc.h(psi)
#applying teleportation bit to our cicuit;
teleportation_Circuit.barrier()
teleportation_bit(teleportation_Circuit,0,1)
teleportation_Circuit.draw()
#STEP3:
# Measure both qubits and store the result in two classical bits.
def measure_and_send(qc,a,b):
"""Measures qubits a & b and 'sends' the results to bob"""
qc.barrier()
qc.measure(a,0)
qc.measure(b,1)
measure_and_send(teleportation_Circuit,0,1)
teleportation_Circuit.draw()
#STEP4:
# Apply gates bepending on the sate of the classical bits:
# 00 -> Do nothing.
# 01 -> Apply X gate.
# 10 -> Apply Z gate.
# 11 -> Apply ZX gate.
def reciever_gates(qc,qubit,crz,crx):
# apply the correct gates if the registers are in the state '1'
qc.x(qubit).c_if(crx,1)
qc.z(qubit).c_if(crz,1)
#Applying reciever gates:
teleportation_Circuit.barrier()
reciever_gates(teleportation_Circuit,2,crz,crx)
teleportation_Circuit.draw()
#============================== Begining of testing Protocol =========================================
psi = random_state(1) # create a random 1 qubitstate
# Display our random qubit state:
array_to_latex(psi,pretext="|\\psi\\rangle =")
# Show Block Sphere:
plot_bloch_multivector(psi)
# gate initialiazation: if the circuit is working correctly then q2 will be in this state at the end
init_gate = Initialize(psi)
init_gate.label = "init"
## setup:
qr = QuantumRegister(3)
crz = ClassicalRegister(1)
crx = ClassicalRegister(1)
qc = QuantumCircuit(qr,crz,crx)
# initial step: 0:
# Initialise q0
qc.append(init_gate,[0])
qc.barrier()
# step 1:
# begin teleportation protocol
create_bell_pair(qc,1,2)
qc.barrier()
# step 2:
# send q1 to q0 and q2 to q1
teleportation_bit(qc,0,1)
# step 3:
#send classical bits from q0 to q1
measure_and_send(qc,0,1)
# step 4:
#q1 decodes qubits
reciever_gates(qc,2,crz,crx)
backend = BasicAer.get_backend('statevector_simulator')
out_vector = execute(qc, backend).result().get_statevector()
plot_bloch_multivector(out_vector)
# step 5:
# takes advantafe of the reversablilty of quantum circuits to reverse randomization:
inverse_init_gate = init_gate.gates_to_uncompute()
qc.append(inverse_init_gate, [2])
#Display circuit:
qc.draw()
# final step: get result using classical bit:
cr_result = ClassicalRegister(1)
qc.add_register(cr_result)
qc.measure(2,2)
qc.draw()
# testing the circuit:
backend = BasicAer.get_backend('qasm_simulator')
counts = execute(qc,backend,shots=1024).result().get_counts()
plot_histogram(counts)
# IBM Quantum computers fo not support instructions after measurements
# however we can use the deferred measurement principle, to postpone
# measurements until the end of our circuit.
# To do this we rewrite our reciever_gates:
def new_reciever_gate(qc,a,b,c):
qc.cz(a,c)
qc.cx(b,c)
# Using our new reciever function:
qc = QuantumCircuit(3,1)
# First, let's initialise Alice's q0
qc.append(init_gate, [0])
qc.barrier()
# Now begins the teleportation protocol
create_bell_pair(qc, 1, 2)
qc.barrier()
# Send q1 to Alice and q2 to Bob
teleportation_bit(qc, 0, 1)
qc.barrier()
# Alice sends classical bits to Bob
new_reciever_gate(qc, 0, 1, 2)
# We undo the initialisation process
qc.append(inverse_init_gate, [2])
# See the results, we only care about the state of qubit 2
qc.measure(2,0)
# View the results:
qc.draw()
# now we will use quantum hardware:
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
provider.backends()
# get the least-busy backend at IBM and run the quantum circuit there
from qiskit.providers.ibmq import least_busy
backend = least_busy(provider.backends(filters=lambda b: b.configuration().n_qubits >= 3 and
not b.configuration().simulator and b.status().operational==True))
job_exp = execute(qc, backend=backend, shots=8192)
# Get results and display:
exp_result = job_exp.result()
exp_measurement_result = exp_result.get_counts(qc)
print(exp_measurement_results)
plot_histogram(exp_measurement_results)
|
https://github.com/Andres8bit/IBMQ-Quantum-Qiskit
|
Andres8bit
|
# Superdense Coding:
# a procedure that allows you to send two classical bits to another party using
# another party using just a single quibt of communication.
#import statements:
from qiskit import*
from qiskit import IBMQ
from qiskit.providers.ibmq import least_busy
from qiskit.visualization import plot_histogram
from qiskit.tools.monitor import job_monitor
# helps to get nicer images:
%config InlineBackend.figure_format = 'svg'
# Define a function that takes a QuantumCircuit and two integers a&b
def create_bell_pair(qc,a,b):
qc.h(a) # Apply a h-gate to the first qubit
qc.cx(a,b) # Apply a CNOT, using the first qubit as the control
# Define a function that takes a QuantumCircuit (qc)
# a wubit index (qubit) and a message string (msg)
def encode_message(qc,qubit,msg):
if msg == "00":
pass # to send 00 we do nothing
elif msg == "10":
qc.x(qubit) # To send 01 we apply x-gate
elif msg == "01":
qc.z(qubit) # To send 01 we apply a z-gate
elif msg == "11":
qc.z(qubit) # To send 11, we apply a z-gate
qc.x(qubit) # followed by an x-gate
else:
print("Ivalid Message: sending '00' ")
# uses a cnot gate followed by a H-gate to decode msg
def decode_message(qc,a,b):
qc.cx(a,b)
qc.h(a)
# our main code portion where we create our circuit:
qc = QuantumCircuit(2) # create a 2 qubit quantum circuit
# entangles our qubits:
create_bell_pair(qc,0,1)
qc.barrier() # used to separate the gates in our diagram
# choose and then encode our msg:
message ="10"
encode_message(qc,0,message)
qc.barrier()
# decode message
decode_message(qc,0,1)
# measure qubits to check message
qc.measure_all()
#draw circuit:
qc.draw(output = "mpl")
#visualize results:
backend = Aer.get_backend('qasm_simulator')
job_sim = execute(qc, backend, shots=1024)
sim_result = job_sim.result()
measurement_result = sim_result.get_counts(qc)
print(measurement_result)
plot_histogram(measurement_result)
# Using a real Quantum Computer:
shots = 256
#load local account inoformation:
IBMQ.load_account()
# Get the lear busy backend:
provider = IBMQ.get_provider(hub='ibm-q')
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2
and not x.configuration().simulator
and x.status().operational==True))
print("least busy backend: ", backend)
# Run our circuit
job = execute(qc, backend=backend, shots=shots)
job_monitor(job)
#plotting results:
result = job.result()
plot_histogram(result.get_counts(qc))
|
https://github.com/Andres8bit/IBMQ-Quantum-Qiskit
|
Andres8bit
|
# Deutsch-Josza:
# first example of a quantum algorithm that performs better than the best classical algorithm.
# Problem: given a string of bits and a hidden boolean function f, which returns either 0 || 1
# The function is guaranteed to either be balanced or constant:
# balance -> return's 0 or 1 with exactly 50/50 probability.
# constant -> return's all 0's or all 1's for any input.
# determine whether the functionc is balanced or constant.
#
# Classical Approach:
# The classical approach requires two queries per bit.
# If the two are the same we have a constant function, otherwise it must be balanced.
# Quantum Approach:
# Using a quantum circuit we can solve this problem with a single query.
# We can express the probability that the function is constatn as a function of k inputs as:
# P(k) = 1- 1/2^(k-1), for k <= 2^(n-1)
# Steps:
# 1. Prepare two quantum registers:
# The first is n-qubit register initialised to |0>.
# The second is a 1-qubit register initialised to |1>\
# 2. Apply a Hadamard gate to each qubit:
# after this step the input register is in an equal superposition of all states.
# When the oracle is balanced, phase kick back adds a negative phase to 1/2 of the states.
# 3. Apply the wuantym oracle |x>|y> to |x|y NOT f(x)>
# 4. Apply a Hadamard gate to each qubit in the first register:
# we reverse step 2 to obtain the init. quantum state of the first register.
# 5. Measure the first register
%matplotlib inline
import numpy as np
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumCircuit, execute, Aer, IBMQ, BasicAer
from qiskit.providers.ibmq import least_busy
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from qiskit.tools.monitor import job_monitor
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
# import basic plot tools
from qiskit.visualization import plot_histogram
# n = 3
# const_oracle = QuantumCircuit(n+1)
# output = np.random.randint(2)
# if output == 1:
# const_oracle.x(n)
# balanced_oracle = QuantumCircuit(n+1)
# b_str = "101"
# # Place X-gates
# for qubit in range(len(b_str)):
# if b_str[qubit] == '1':
# balanced_oracle.x(qubit)
# # Use barrier as divider
# balanced_oracle.barrier()
# Controlled-NOT gates
# for qubit in range(n):
# balanced_oracle.cx(qubit, n)
# balanced_oracle.barrier()
# # Place X-gates
# for qubit in range(len(b_str)):
# if b_str[qubit] == '1':
# balanced_oracle.x(qubit)
# # Show oracle
# balanced_oracle.draw()
def dj_oracle(case, n):
# We need to make a QuantumCircuit object to return
# This circuit has n+1 qubits: the size of the input,
# plus one output qubit
oracle_qc = QuantumCircuit(n+1)
# First, let's deal with the case in which oracle is balanced
if case == "balanced":
# First generate a random number that tells us which CNOTs to
# wrap in X-gates:
b = np.random.randint(1,2**n)
# Next, format 'b' as a binary string of length 'n', padded with zeros:
b_str = format(b, '0'+str(n)+'b')
# Next, we place the first X-gates. Each digit in our binary string
# corresponds to a qubit, if the digit is 0, we do nothing, if it's 1
# we apply an X-gate to that qubit:
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
oracle_qc.x(qubit)
# Do the controlled-NOT gates for each qubit, using the output qubit
# as the target:
for qubit in range(n):
oracle_qc.cx(qubit, n)
# Next, place the final X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
oracle_qc.x(qubit)
# Case in which oracle is constant
if case == "constant":
# First decide what the fixed output of the oracle will be
# (either always 0 or always 1)
output = np.random.randint(2)
if output == 1:
oracle_qc.x(n)
oracle_gate = oracle_qc.to_gate()
oracle_gate.name = "Oracle" # To show when we display the circuit
return oracle_gate
def dj_algorithm(oracle, n):
dj_circuit = QuantumCircuit(n+1, n)
# Set up the output qubit:
dj_circuit.x(n)
dj_circuit.h(n)
# And set up the input register:
for qubit in range(n):
dj_circuit.h(qubit)
# Let's append the oracle gate to our circuit:
dj_circuit.append(oracle, range(n+1))
# Finally, perform the H-gates again and measure:
for qubit in range(n):
dj_circuit.h(qubit)
for i in range(n):
dj_circuit.measure(i, i)
return dj_circuit
n = 4
oracle_gate = dj_oracle('balanced', n)
dj_circuit = dj_algorithm(oracle_gate, n)
dj_circuit.draw()
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
results = execute(dj_circuit, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
# Using a real Quantum Device:
provider = IBMQ.get_provider(hub='ibm-q')
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (n+1) and
not x.configuration().simulator and x.status().operational==True))
print("least busy backend: ", backend)
shots = 1024
job = execute(dj_circuit, backend=backend, shots=shots, optimization_level=3)
job_monitor(job, interval = 2)
results = job.result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/Andres8bit/IBMQ-Quantum-Qiskit
|
Andres8bit
|
%matplotlib inline
# Importing standard Qiskit libraries and configuring account
# initialization
import matplotlib.pyplot as plt
import numpy as np
from qiskit import QuantumCircuit, execute, Aer, IBMQ, BasicAer,ClassicalRegister,QuantumRegister
from qiskit.providers.ibmq import least_busy
from qiskit.compiler import transpile, assemble
from qiskit.tools.monitor import job_monitor
from qiskit.tools.jupyter import *
from qiskit.visualization import *
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
# Bernstein-Vazirani Algorithm:
# Much like the Deutsch-Josza Algorithm.
# We are given a black-box funtion f,
# which takes a string of bits x.
# And returns either 0 or 1.
# Instead of the function being either balanced or constant
# the function is guaranteed to return the bitwise produc of the input
# with some string, s. That is to say:
# given an input x, f(x) = s * x%2.
# Where we are asked to find s
# ======= CLASSICAL SOLUTION: =======
# classically the oracle returns: fs(x) = s*x %2
# Given an input x. Thus, the hidden bit string s can be revealed by
# querying the oracle with the sequence of inputs:
# 1000...00, 0100...00, 0010...00, 0000...01
# Where each query revelas a different s with x = 0100...00 we can find the next least
# significant bit of s and so on.
# Therefore we would need to call fs(x), a total of n times.
# ======= Quantum Solution: =======
# Using a quantum computer, we can solve this problem with 100% confidence
# after only one call to the function f(x).
# the following is the algorithmic steps:
# 1. Initialise the imputs qubits to the |0>^(cnot n) state, and output the qubit to |->
# 2. Apply Hadamard gates to the input register. // place in superposition
# 3. Query the oracle
# 4. Apply Hadamard gates to the input register //undue super position.
# 5. Measure
n = 3
s = '011'
# we need a circuit with n qubits, plus one ancilla qubit.
bv_circuit = QuantumCircuit(n+1,n)
# put ancilla in state |->
bv_circuit.h(n)
bv_circuit.z(n)
# Apply Hadamard gates before querying the oracle
for i in range(n):
bv_circuit.h(i)
# Apply barrier
bv_circuit.barrier()
# Apply the inner-product oracle
s = s[::-1]
for q in range(n):
if s[q] == '0':
bv_circuit.i(q)
else:
bv_circuit.cx(q,n)
# Apply barrier
bv_circuit.barrier()
# Apply Hadamard gates after querying the oracle
for i in range(n):
bv_circuit.h(i)
# Measurement
for i in range(n):
bv_circuit.measure(i,i)
bv_circuit.draw()
# running our circuit on the qasm sumulator:
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
results = execute(bv_circuit,backend=backend,shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
# Load our saved IBMQ accounts and get the least busy backend device with less than or equal to 5 qubits
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
provider.backends()
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits <= 5 and
x.configuration().n_qubits >= 2 and
not x.configuration().simulator and x.status().operational==True))
print("least busy backend: ", backend)
shots = 1024
job = execute(bv_circuit,backend=backend,shots=shots)
job_monitor(job,interval = 2)
results = job.result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/Andres8bit/IBMQ-Quantum-Qiskit
|
Andres8bit
|
%matplotlib inline
# initialization:
%matplotlib inline
%config InlineBackend.figure_format = 'svg'
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumCircuit, execute, BasicAer, IBMQ
from qiskit.providers.ibmq import least_busy
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.tools.monitor import job_monitor
from qiskit.visualization import *
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
# Simon's Algorithm:
# Given an unknown blackbox funnction f,
# which is quaranteed to be either 1:1 or 2:1.
# That is to say
# either: f is a 1 to 1 maping,
# where for every unique x value maps to a single unique f(x).
# or: f is a 2 to 1 maping,
# where exactly 2 unique x vals map to the same f(x).
# Given this blackbox function how quickly can we determine which type of function f is?
# Then is f is 2:1 how quickly can we determine s, where if f is 2:1.
# given x1,x2: f(x1) = f(x)
# it is guaranteed: x1 CNOT x2 = s
# ========== Classical Solution: ============
# The traditional approach requires us to check up to 2^[N-1] + 1 inputs.
# Where N is the number of bits in the input.
# Therefore we would have to check on avg. half of all inputs to be 100% positve the function was 2:1.
# ========== Quantum Solution: ==========
# Steps:
# 1. Two n-qubit input registers are initialized to the 0 state:
# |ψ1> = |0⟩^⊗n |0⟩^⊗n
# 2. Apply a Hadamard transform to the first register:
# |ψ2⟩ = 1/sqrt(2^n)*∑[x∈{0,1}^n] |x⟩|0⟩⊗n
# 3. Apply the query function Qf:
# |ψ3⟩=1/sqrt(2^n) * ∑x∈[{0,1}^n] |x⟩|f(x)⟩
# 4. Measure the second register. A certain value of f(x) will be observed.
# BC of the setting of the problem, the observed value f(x) could
# correspond to two possible inputs: x & y = x⊕s
# Therefore the first register becomes:
# |ψ4⟩ = [1/sqrt(2)]( |x⟩ + |y⟩ )
# 5. Apply Hadamard on the first regisiter:
# |ψ5⟩ = 1/sqrt(2^[n+1])*∑z∈[{0,1}n] [ (−1)^(x⋅z) + (−1)^(y⋅z) ] | z⟩
# 6. Measuring the first register will give an output only if:
# (−1)^(x⋅z)=(−1)^(y⋅z)
# which means:
# x*z = y*z
# x*z = (x XOR s)*z
# x*z = x*(z XOR s)*z
# s*z = 0%2
# A string z whose inner product with s will be measured. Thus, repeating the
# algorithm ~~ n times, we will be able to obtain n different values of z & the
# following system of equations can be written:
#
# s*z1 = 0
# s*z2 = 0
# ...
# s*zn = 0
# From which we can find s using Gaussian elimination.
# currently using a fixed string implementation, should expand to a random general case:
# Creating registers
# qubits and classical bits for querying the oracle and finding the hidden period s
n = 2*len(str(s))
simonCircuit = QuantumCircuit(n)
barriers = True
# Apply Hadamard gates before querying the oracle
simonCircuit.h(range(len(str(s))))
# Apply barrier
if barriers:
simonCircuit.barrier()
# Apply the query function
## 2-qubit oracle for s = 11
simonCircuit.cx(0, len(str(s)) + 0)
simonCircuit.cx(0, len(str(s)) + 1)
simonCircuit.cx(1, len(str(s)) + 0)
simonCircuit.cx(1, len(str(s)) + 1)
# Apply barrier
if barriers:
simonCircuit.barrier()
# Apply Hadamard gates to the input register
simonCircuit.h(range(len(str(s))))
# Measure ancilla qubits
simonCircuit.measure_all()
simonCircuit.draw(output='mpl')
# use local simalator:
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
results = execute(simonCircuit,backend=backend,shots=shots).result()
answer = results.get_counts()
answer_plot = {}
for measresult in answer.keys():
measresult_input = measresult[len(str(s)):]
if measresult_input in answer_plot:
answer_plot[measresult_input] += answer[measresult]
else:
answer_plot[measresult_input] = answer[measresult]
print(answer_plot)
plot_histogram(answer_plot)
# Calculate the dot product of the results
def sdotz(a,b):
accum = 0
for i in range(len(a)):
accum += int(a[i]) * int(b[i])
return( accum % 2 )
print('a,z,s.z(mod 2)')
for z_rev in answer_plot:
z = z_rev[::-1]
print('{},{},{},{}={}'.format(s,z,s,z,sdotz(s,z)))
# Run our circuit on the least busy backend
shots = 1024
job = execute(simonCircuit,backend=backend,shots=shots)
job_monitor(job,interval=2)
# Categorize measurements by input register values
answer_plot = {}
for measresult in answer.keys():
measresult_input = measresult[len(str(s)):]
if measresult_input in answer_plot:
answer_plot[measresult_input] += answer[measresult]
else:
answer_plot[measresult_input] = answer[measresult]
# Plot the categorized results
print( answer_plot )
plot_histogram(answer_plot)
# Calculate the dot product of the most significant results
print('s, z, s.z (mod 2)')
for z_rev in answer_plot:
if answer_plot[z_rev] >= 0.1*shots:
z = z_rev[::-1]
print( '{}, {}, {}.{}={}'.format(s, z, s,z,sdotz(s,z)) )
|
https://github.com/Andres8bit/IBMQ-Quantum-Qiskit
|
Andres8bit
|
#in general we can transform a single CNOT inot a controlled
#version of any rotaion around the Bloch sphere by an angle pi,
#by simply preceding and following it with the correct rotations.
%matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from qiskit.circuit import Gate
from math import pi
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
qc = QuantumCircuit(2)
c =0
t =1
#built in controlled-Z
#recall a Z-GATE converts a |+> qubit to a |-> and vive-versa
qc.cz(c,t)
qc.draw()
#converting a CNOT into a CONTROLLED-Z
qc = QuantumCircuit(2)
qc.h(t)
qc.cx(c,t)
qc.h(t)
qc.draw()
#CONTROLLED-Y GATE.
qc = QuantumCircuit(2)
qc.sdg(t)
qc.cx(c,t)
qc.s(t)
qc.draw()
#CONTROLLED-H GATE
qc = QuantumCircuit(2)
qc.ry(pi/4,t)
qc.cx(c,t)
qc.ry(-pi/4,t)
qc.draw()
#SWAPPING QUBITS:
#sometime we need to move information around in a quantum Computer.
#one option is to move the state between two qubits.
a = 0
b = 1
#swaps states oc qubits a and b
qc = QuantumCircuit(2)
qc.swap(a,b)
qc.draw()
# we will now develope a swap gate using he base gate.
#first we will look at the |1> and |0> cases:
#swaps 1 from a to b:
# puts qubits b in state |1> and qubit a in state |0>
qc = QuantumCircuit(2)
qc.cx(a,b) #copies 1 from a to b
qc.cx(b,a) #uses the 1 on b to rotate the state of a to 0
qc.draw()
#swap back to original state
qc.cx(b,a)
qc.cx(a,b)
qc.draw()
#more general swap gate:
# works for |00>,|01>,|10> and |11>
#note you can change the order of the CNOT gates and get the same results
qc = QuantumCircuit(2)
qc.cx(b,a)
qc.cx(a,b)
qc.cx(b,a)
qc.draw()
#controlled Rotations:
#this circuit rotates qubits about the Y-AXIS by theta/2
qc = QuantumCircuit(2)
theta = pi # theta can be any value
qc.ry(theta/2,t)
qc.cx(c,t)
qc.ry(-theta/2,t)
qc.cx(c,t)
qc.draw()
# we can also create a controlled version of any single
#qubit rotation U
# We must first find three rotations A,B,and C,
#and a phase alpha such that
# ABC = I , e^(ialpha)AZBZC =U
A = Gate('A',1,[])
B = Gate('B',1,[])
C = Gate('C',1,[])
alpha = 1 #arbitratily define alpha
qc = QuantumCircuit(2)
qc.append(C,[t])
qc.cz(c,t)
qc.append(B,[t])
qc.cz(c,t)
qc.append(A,[t])
qc.u1(alpha,c)
qc.draw()
#TOFFOLI:
#The Toffoli is a 3-qubit gate with two control and one target.
#It performs an X on the target only if both controls
# are in state |1>.
# the final state of target is then either the AND or NAND of the two controls,
# depending on if the initial state of target was |0> or |1>.
# the Toffoli can be thought of as a controlled-controoled-NOT:
# note the Toffoli requires at least 6 CNOT gates.
# but there are other ways to produce an AND effect using quantum operations.
qc = QuantumCircuit(3)
a = 0
b = 1
t = 2
#Toffoli with control a and b target t:
qc.ccx(a,b,t)
qc.draw()
# before we built a Toffoli from base quibit operations
# we will build a general controlled-controlled-U.
#For any single-qubit rotation U.
qc = QuantumCircuit(3)
qc.cu1(theta,b,t)
qc.cx(a,b)
qc.cu1(-theta,b,t)
qc.cx(a,b)
qc.cu1(theta,a,t)
qc.draw()
#we can built an AND gate using a CONTROLLED-H GATE and CONTROLLED-Z GATES
qc = QuantumCircuit(3)
qc.ch(a,t)
qc.cz(b,t)
qc.ch(a,t)
qc.draw()
|
https://github.com/Andres8bit/IBMQ-Quantum-Qiskit
|
Andres8bit
|
# Qubits are subject to noise orginating from:
# temperature varations, stray magnetic fields, or operations
# on other qubits.
# Finding a way to mitigate this noise through
# the encoding of our in a way that protects them from noise.
# for some roation R(theta), about some axis it is impossible
# to impent an angle theta with perfect accuracy,such thta you are
# sure that you are not accidentally implement something like
# theta + 0.000000001. That is to say there will always be
# a limit to the accuracy we can achieve.
# As this error adds up through operations the noise will always
# be larger than is tolerable.
# Therefore implementing rotations in a fault tolerant
# Quantum Computer, uses mutiple operations made of T and H
# Gates.
%matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
# The T-GATE:
# Is a rotation around the z-axis by theta = pi/4.
# and is expressed mathematically as Rz(pi/4) = e^(ipi/8Z)
#Ex:
# the default T gate rotating about the z-axis:
qc = QuantumCircuit(1)
qc.t(0)
qc.draw()
# the T-Gate rotating about the x-axis:
qc = QuantumCircuit(1)
qc.h(0)
qc.t(0)
qc.h(0)
qc.draw()
# Putting the two circuits above together we can make the gate:
# Rz(pi/4)Rx(pi/4).
# Bc this is a single-qubit gate,we can think of it as a
# rotation around the Bloch Sphere. That is as a rotaion
# About some axis. It is important to note that this angle
# will always be irrational. Due to its irrationality,
# the angles that result from different repetitions will never
# be the same. Each angle will be somewhere between 0 & 2pi.
# Splitting this interval up into n slices of width 2pi/n.
# For eacg repetition, the resulting angle will fall in one
# of these slices. looking at the angle for the first n+1
# repitioins, it must be true that at least one slicce contains
# two of these angles. Using n1 to denote the number of repetitions
# required for the first and n2 for the second.
# The angle for n2-n1 repetitions stisfies
# theta(n2-n1) != 0, -2pi/n <= theta(n2-n1) <= 2pi/n
# We therefore have he ability to do rotations around small angles.
# We can use this to rotate around angles that are as small as we
# like, just by increasing the number of times we repeat this gate.
# By using small-angle rotations, we can also rotate by any angle
# we like. This won't always be exact, but it is guaranteed to be
# accurate up to 2pi/n, which we can be made as small as we like.
# Using the RzRx rotations allows us to have arbitrary rotaions
# around the Bloch Sphere, through the use of numerous T-Gate operations.
# Therefore the complexity of algorithms in quantum computations is
# often time given in terms of how many T-Gates they require.
qc = QuantumCircuit(1)
# Rx gate rotation about the x-axis:
qc.h(0)
qc.t(0)
qc.h(0)
# Rz gate rotation about the z-axis:
qc.t(0)
qc.draw()
|
https://github.com/Andres8bit/IBMQ-Quantum-Qiskit
|
Andres8bit
|
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/AnshDabkara/Qiskit_Algorithm
|
AnshDabkara
|
from qiskit import IBMQ, Aer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, transpile, assemble
from qiskit.tools.monitor import job_monitor
import matplotlib as mpl
# import basic plot tools
from qiskit.visualization import plot_histogram
bv_circuit=QuantumCircuit(4,3)
#bv_circuit.clear()
bit_string=('111')
bv_circuit.x(3)
bv_circuit.h([0,1,2,3])
bv_circuit.barrier()
bv_circuit.cx(0,3)
bv_circuit.cx(1,3)
bv_circuit.cx(2,3)
bv_circuit.barrier()
bv_circuit.h([0,1,2,3])
bv_circuit.measure([0,1,2],[0,1,2])
bv_circuit.draw('mpl')
aer_sim = Aer.get_backend('aer_simulator') #Local Simulator
shots = 1024 #No. of times the circuit is running
qobj = assemble(bv_circuit, shots = shots)
results = aer_sim.run(qobj).result()
counts = results.get_counts()
plot_histogram(counts) #Plotting the result
bit_string=('1010')
bv_circuit=QuantumCircuit(len(bit_string)+1,len(bit_string))
bv_circuit.clear()
#bv_circuit.x(len(bit_string))
bv_circuit.h(range(len(bit_string)))
bv_circuit.x(len(bit_string))
bv_circuit.h(len(bit_string))
bv_circuit.barrier()
for i, yes in enumerate(reversed(bit_string)):
if yes=='1':
bv_circuit.cx(i,len(bit_string))
bv_circuit.barrier()
bv_circuit.h(range(len(bit_string)))
bv_circuit.h(len(bit_string))
bv_circuit.measure(range(len(bit_string)),range(len(bit_string)))
bv_circuit.draw('mpl')
aer_sim = Aer.get_backend('aer_simulator') #Local Simulator
shots = 1024 #No. of times the circuit is running
qobj = assemble(bv_circuit, shots = shots)
results = aer_sim.run(qobj).result()
counts = results.get_counts()
plot_histogram(counts) #Plotting the result
|
https://github.com/AnshDabkara/Qiskit_Algorithm
|
AnshDabkara
|
# initialization
import numpy as np
# importing Qiskit
from qiskit import IBMQ, Aer
from qiskit import QuantumCircuit, transpile
# import basic plot tools
from qiskit.visualization import plot_histogram
# set the length of the n-bit input string.
n = 3
# Constant Oracle
const_oracle = QuantumCircuit(n+1)
# Random output
output = np.random.randint(2)
if output == 1:
const_oracle.x(n)
const_oracle.draw()
# Balanced Oracle
balanced_oracle = QuantumCircuit(n+1)
# Binary string length
b_str = "101"
# For each qubit in our circuit
# we place an X-gate if the corresponding digit in b_str is 1
# or do nothing if the digit is 0
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
balanced_oracle.draw()
# Creating the controlled-NOT gates
# using each input qubit as a control
# and the output as a target
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Use barrier as divider
balanced_oracle.barrier()
# Controlled-NOT gates
for qubit in range(n):
balanced_oracle.cx(qubit, n)
balanced_oracle.barrier()
# Wrapping the controls in X-gates
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Show oracle
balanced_oracle.draw()
dj_circuit = QuantumCircuit(n+1, n)
# Apply H-gates
for qubit in range(n):
dj_circuit.h(qubit)
# Put qubit in state |->
dj_circuit.x(n)
dj_circuit.h(n)
# Add oracle
dj_circuit = dj_circuit.compose(balanced_oracle)
# Repeat H-gates
for qubit in range(n):
dj_circuit.h(qubit)
dj_circuit.barrier()
# Measure
for i in range(n):
dj_circuit.measure(i, i)
# Display circuit
dj_circuit.draw()
# Viewing the output
# use local simulator
aer_sim = Aer.get_backend('aer_simulator')
results = aer_sim.run(dj_circuit).result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/AnshDabkara/Qiskit_Algorithm
|
AnshDabkara
|
from qiskit import IBMQ, Aer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, transpile, assemble
from qiskit.tools.monitor import job_monitor
import matplotlib as mpl
import numpy as np
# import basic plot tools
from qiskit.visualization import plot_histogram
# length of the n-bit string
n = 4
constant_oracle = QuantumCircuit(n+1)
constant_oracle.clear()
output = np.random.randint(2) # random no. 0/1 as output
if output == 1:
constant_oracle.x(n)
balance_oracle = QuantumCircuit(n+1)
balance_oracle.clear()
b_str = "1000"
# implementing x-gates
for i in range(len(b_str)):
if b_str[i] == '1':
balance_oracle.x(i)
balance_oracle.barrier()
# implementing cnot gates
for qubit in range(n):
balance_oracle.cx(qubit, n)
balance_oracle.barrier()
balance_oracle.draw()
# implemneting x-gates
for i in range (len(b_str)):
if b_str[i] == '1':
balance_oracle.x(i)
balance_oracle.barrier()
dj_circuit = QuantumCircuit(n+1, n)
# Apply H-gates
for qubit in range(n):
dj_circuit.h(qubit)
# Put qubit in state |->
dj_circuit.x(n)
dj_circuit.h(n)
# Add oracle
dj_circuit = dj_circuit.compose(constant_oracle)
# Repeat H-gates
for qubit in range(n):
dj_circuit.h(qubit)
dj_circuit.barrier()
# Measure
for i in range(n):
dj_circuit.measure(i, i)
dj_circuit.draw('mpl')
aer_sim = Aer.get_backend('aer_simulator') #Local Simulator
shots = 1024 #No. of times the circuit is running
qobj = assemble(dj_circuit, shots = shots)
results = aer_sim.run(qobj).result()
counts = results.get_counts()
plot_histogram(counts)
|
https://github.com/AnshDabkara/Qiskit_Algorithm
|
AnshDabkara
|
from qiskit import IBMQ, Aer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, execute, assemble, QuantumRegister, ClassicalRegister
from qiskit.tools.monitor import job_monitor
import matplotlib as mpl
# import basic plot tools
from qiskit.visualization import plot_histogram, plot_bloch_multivector
import numpy as np
from numpy import pi
marked = ('11') # state which we want to search
n = len(marked)
gs_circuit = QuantumCircuit(n+1,n)
gs_circuit.clear()
gs_circuit.x(n)
gs_circuit.h(range(n+1))
gs_circuit.barrier()
# oracle operator
for i, yes in enumerate(marked):
if yes == '0':
gs_circuit.x(i)
gs_circuit.mcx(list(range(n)),n)
for i, yes in enumerate(marked):
if yes == '0':
gs_circuit.x(i)
gs_circuit.barrier()
# diffuser operator
gs_circuit.h(range(n))
gs_circuit.x(range(n))
gs_circuit.cx(0,1)
gs_circuit.x(range(n))
gs_circuit.h(range(n))
gs_circuit.barrier()
# measure
gs_circuit.measure(range(n),range(n))
gs_circuit.draw('mpl')
aer_sim = Aer.get_backend('aer_simulator') #Local Simulator
shots = 1024 #No. of times the circuit is running
qobj = assemble(gs_circuit, shots = shots)
results = aer_sim.run(qobj).result()
counts = results.get_counts()
plot_histogram(counts) #Plotting the result
# Converting the binary string to decimal
b_str = list(counts.keys())[0]
b = int(b_str,2)
print('ans:',b)
|
https://github.com/AnshDabkara/Qiskit_Algorithm
|
AnshDabkara
|
from qiskit import IBMQ, Aer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, execute, assemble, QuantumRegister, ClassicalRegister
from qiskit.tools.monitor import job_monitor
import matplotlib as mpl
# import basic plot tools
from qiskit.visualization import plot_histogram, plot_bloch_multivector
import numpy as np
from numpy import pi
# Initializing the Qubits
ql = QuantumRegister(3, name="ql") # logic qubits
qa = QuantumRegister(2, name="qa") # Ancilla qubits
mea = ClassicalRegister(3, name="mea")
syn = ClassicalRegister(2, name="syn")
qec_circuit = QuantumCircuit(ql,qa,mea,syn)
# Encoding
qec_circuit.clear()
qec_circuit.cx(0,1)
qec_circuit.cx(0,2)
qec_circuit.barrier()
# Bit flip error
n = np.random.randint(3)
qec_circuit.x(n)
qec_circuit.barrier()
# Syndrome Circuit
qec_circuit.cx(0,3)
qec_circuit.cx(1,3)
qec_circuit.cx(0,4)
qec_circuit.cx(2,4)
qec_circuit.barrier()
qec_circuit.measure(qa,syn)
# Recovery cirucit
qec_circuit.barrier()
qec_circuit.mct([3,4],0)
qec_circuit.x(4)
qec_circuit.mct([3,4],1)
qec_circuit.x(4)
qec_circuit.x(3)
qec_circuit.mct([3,4],2)
qec_circuit.x(3)
qec_circuit.barrier()
# Decoding circuit
qec_circuit.cx(0,2)
qec_circuit.cx(0,1)
qec_circuit.barrier()
# measurement
qec_circuit.measure(ql,mea)
qec_circuit.draw("mpl")
qec_circuit.draw('mpl')
aer_sim = Aer.get_backend('aer_simulator')
shots = 1024
t_qec = execute(qec_circuit, aer_sim, shots=shots).result()
counts = t_qec.get_counts()
plot_histogram(counts)
|
https://github.com/AnshDabkara/Qiskit_Algorithm
|
AnshDabkara
|
from qiskit import IBMQ, Aer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, transpile, assemble
from qiskit.tools.monitor import job_monitor
import matplotlib as mpl
# import basic plot tools
from qiskit.visualization import plot_histogram, plot_bloch_multivector
import numpy as np
from numpy import pi
qft_circuit = QuantumCircuit(3)
qft_circuit.clear()
#input state= 5
qft_circuit.x(0)
qft_circuit.x(2)
qft_circuit.h(0)
qft_circuit.cp(pi/2,0,1)
qft_circuit.cp(pi/4,0,2)
qft_circuit.h(1)
qft_circuit.cp(pi/2,1,2)
qft_circuit.h(2)
#qft_circuit.swap(0,2)
qft_circuit.draw('mpl')
#output is the bloch sphere representation in the fourier basis
sim = Aer.get_backend("aer_simulator")
qft_circuit_init = qft_circuit.copy()
qft_circuit_init.save_statevector()
statevector = sim.run(qft_circuit_init).result().get_statevector()
plot_bloch_multivector(statevector)
IBMQ.save_account('')
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
backend = least_busy(provider.backends(filters=lambda b: b.configuration().n_qubits >= 2 and not b.configuration().simulator and b.status().operational==True))
print(backend)
t_qc = transpile(qft_circuit, backend, optimization_level=3)#transpile=assembling the circuit and everything
job = backend.run(t_qc)#backend means device
job_monitor(job)
|
https://github.com/AnshDabkara/Qiskit_Algorithm
|
AnshDabkara
|
from qiskit import IBMQ, Aer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, transpile, assemble
from qiskit.tools.monitor import job_monitor
import matplotlib as mpl
# import basic plot tools
from qiskit.visualization import plot_histogram
game_circuit = QuantumCircuit(2,1)
#game_circuit
game_circuit.clear()
game_circuit.h(0)
game_circuit.h(1)
game_circuit.cx(0,1)
game_circuit.h(1)
game_circuit.measure(1,0)
game_circuit.draw('mpl')
#running on ibm simulator
aer_sim=Aer.get_backend('aer_simulator')
shots=1024
qobj=assemble(game_circuit, shots=1024)
results=aer_sim.run(qobj).result()
counts=results.get_counts()
plot_histogram(counts)
#running on quantum computer
#signing in to ibm using api token
IBMQ.save_account('eb51948e03130da6b3212b337a0276eb3ddfb106e6e3ff49388aaf14efdded08d2624fa55f7d7158e02266b904d46424988e127c44056949754947d624319860')
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
backend = least_busy(provider.backends(filters=lambda b: b.configuration().n_qubits >= 2 and not b.configuration().simulator and b.status().operational==True))
print(backend)
t_qc = transpile(game_circuit, backend, optimization_level=3)#transpile=assembling the circuit and everything
job = backend.run(t_qc)#backend means device
job_monitor(job)
exp_result = job.result()
exp_counts = exp_result.get_counts(game_circuit)
print(exp_counts)
plot_histogram(exp_counts)
|
https://github.com/AnshDabkara/Qiskit_Algorithm
|
AnshDabkara
|
from qiskit import ClassicalRegister , QuantumCircuit, QuantumRegister
import numpy as np
qr = QuantumRegister(2)
cr = ClassicalRegister(3) #For tree classicals bites
qc = QuantumCircuit(qr , cr)
qc.h(qr[0]) #auxiliary qubit
qc.x(qr[1]) # eigenvector
#qc.cp((3/2)*np.pi , qr[0] , qr[1])
qc.cp(3*np.pi , qr[0] , qr[1])
qc.h(qr[0])
qc.measure(qr[0] , cr[0]) # this is the controlled-U^(2^n-1) operator for determine phi_n
qc.draw("mpl")
qc.reset(qr[0])
qc.h(qr[0])
# la valeur du bit du poids le plus faible est dans cr[0].
#Si cr[0] = 1 on enléve le bit de poids le plus faible en fesant la rotation alpha_2
#et on continu le bit n-1 devient le bit le bit de poids le plus faible
#si cr[0] est à 0 alors on peut appliquer directement la matrice unitaire associé sans avoir
#à faire de rotation inverse alpha_k
with qc.if_test((cr[0] , 1)) as else_:
qc.p(-np.pi/2 , qr[0])
#qc.cp((3/8)*np.pi , qr[0] ,qr[1])
qc.cp((3/2)*np.pi , qr[0] ,qr[1])
qc.h(qr[0]) # For make measure in X basis {|0> , |1>}
qc.measure(qr[0] , cr[1])
qc.draw("mpl")
qc.reset(qr[0])
qc.h(qr[0])
# la valeur du bit du poids le plus faible est dans cr[0].
#Si cr[0] = 1 on enléve le bit de poids le plus faible en fesant la rotation alpha_2
#et on continu le bit n-1 devient le bit le bit de poids le plus faible
#si cr[0] est à 0 alors on peut appliquer directement la matrice unitaire associé sans avoir
#à faire de rotation inverse alpha_k
with qc.if_test((cr[1] , 1)) as else_:
qc.p(-(3/4)*np.pi , qr[0])
qc.cp((3/4)*np.pi , qr[0] ,qr[1])
qc.h(qr[0]) # For make measure in X basis {|0> , |1>}
qc.measure(qr[0] , cr[2])
qc.draw("mpl")
from qiskit_aer import AerSimulator
sim = AerSimulator()
job = sim.run(qc, shots=1000)
result = job.result()
counts = result.get_counts()
counts
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/AnshDabkara/Qiskit_Algorithm
|
AnshDabkara
|
import cirq
import numpy as np
from qiskit import QuantumCircuit, execute, Aer
import seaborn as sns
import matplotlib.pyplot as plt
plt.rcParams['figure.figsize'] = (15,10)
q0, q1, q2 = [cirq.LineQubit(i) for i in range(3)]
circuit = cirq.Circuit()
#entagling the 2 quibits in different laboratories
#and preparing the qubit to send
circuit.append(cirq.H(q0))
circuit.append(cirq.H(q1))
circuit.append(cirq.CNOT(q1, q2))
#entangling the qubit we want to send to the one in the first laboratory
circuit.append(cirq.CNOT(q0, q1))
circuit.append(cirq.H(q0))
#measurements
circuit.append(cirq.measure(q0, q1))
#last transformations to obtain the qubit information
circuit.append(cirq.CNOT(q1, q2))
circuit.append(cirq.CZ(q0, q2))
#measure of the qubit in the receiving laboratory along z axis
circuit.append(cirq.measure(q2, key = 'Z'))
circuit
#starting simulation
sim = cirq.Simulator()
results = sim.run(circuit, repetitions=100)
sns.histplot(results.measurements['Z'], discrete = True)
100 - np.count_nonzero(results.measurements['Z']), np.count_nonzero(results.measurements['Z'])
#in qiskit the qubits are integrated in the circuit
qc = QuantumCircuit(3, 1)
#entangling
qc.h(0)
qc.h(1)
qc.cx(1, 2)
qc.cx(0, 1)
#setting for measurment
qc.h(0)
qc.measure([0,1], [0,0])
#transformation to obtain qubit sent
qc.cx(1, 2)
qc.cz(0, 2)
qc.measure(2, 0)
print(qc)
#simulation
simulator = Aer.get_backend('qasm_simulator')
job = execute(qc, simulator, shots=100)
res = job.result().get_counts(qc)
plt.bar(res.keys(), res.values())
res
|
https://github.com/SanNare/qiskit-notebooks
|
SanNare
|
from qiskit import *
from qiskit.tools.visualization import plot_histogram
%matplotlib inline
secretnumber = '101001'
n = len(secretnumber)
circuit = QuantumCircuit(n+1,n)
#circuit.h([0,1,2,3,4,5])
circuit.h(range(n))
circuit.x(n)
circuit.h(n)
circuit.barrier()
for ii,yesno in enumerate(reversed(secretnumber)):
if yesno == '1':
circuit.cx(ii,n)
# circuit.cx(5,6)
# circuit.cx(3,6)
# circuit.cx(0,6)
circuit.barrier()
circuit.h(range(n))
circuit.barrier()
circuit.measure(range(n),range(n))
circuit.draw(output = 'mpl')
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuit,backend = simulator, shots = 1).result()
count = result.get_counts()
print(count)
|
https://github.com/SanNare/qiskit-notebooks
|
SanNare
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.tools.visualization import plot_bloch_multivector, plot_histogram
def logicalAnd(circuit,input_qubits,output_qubit):
circuit.mcx(input_qubits,output_qubit)
def logicalOr(circuit,input_qubits,output_qubit):
for i in input_qubits:
circuit.x(i)
circuit.x(output_qubit)
circuit.mcx(input_qubits,output_qubit)
for i in input_qubits:
circuit.x(i)
# circuit = QuantumCircuit(3)
# logicalAnd(circuit,[0,1],2)
# logicalOr(circuit,[0,1],2)
# %matplotlib inline
# circuit.draw('mpl')
#implementing the function xy + x'y'
circuit = QuantumCircuit(5,1)
#change input by commenting/uncommenting these two lines
circuit.x(0)
# circuit.x(1)
logicalAnd(circuit,[0,1],2)
circuit.x(0)
circuit.x(1)
logicalAnd(circuit,[0,1],3)
logicalOr(circuit,[2,3],4)
circuit.measure(4,0)
%matplotlib inline
circuit.draw(output = 'mpl')
#to run this, remove the classical register and measurement
sv = Statevector.from_label('11000')
nsv = sv.evolve(circuit)
plot_bloch_multivector(nsv.data)
from qiskit import Aer, execute
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuit, simulator, shots=100).result()
counts = result.get_counts(circuit)
print(counts)
plot_histogram(counts)
#implementation of circuit for finding a boolean function in DNF
#encoding used: x + yz => [[1,0,0],[0,1,1]], xy'z + y'z' => [[1,-1,-1],[0,-1,-1]]
def DNF(minterms):
n = len(minterms[0])
m = len(minterms)
circuit = QuantumCircuit(n+m+1,1)
o = n
for t in minterms:
inp = []
for i in range(0,n):
if t[i] == -1:
circuit.x(i)
inp.append(i)
elif t[i] == 1:
inp.append(i)
logicalAnd(circuit,inp,o)
for i in range(0,n):
if t[i] == -1:
circuit.x(i)
o = o+1
logicalOr(circuit,list(range(n,n+m)),n+m)
circuit.measure(n+m,0)
return circuit
circuit = QuantumCircuit(6,1)
#comment/uncomment to modify input
circuit.x(0)
circuit.x(1)
#circuit.x(2)
circuit.append(DNF([[1,0,0],[0,-1,-1]]),[0,1,2,3,4,5],[0]) #f = x + y'z'
circuit.draw(output = 'text')
from qiskit import Aer, execute
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuit, simulator, shots=100).result()
counts = result.get_counts(circuit)
print(counts)
plot_histogram(counts)
|
https://github.com/SanNare/qiskit-notebooks
|
SanNare
|
from qiskit import *
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
circuit = QuantumCircuit(qr,cr)
%matplotlib inline
circuit.draw(output = 'mpl')
circuit.h(qr[0])
circuit.cx(qr[0],qr[1])
circuit.draw(output = 'mpl')
circuit.measure(qr,cr)
circuit.draw(output = 'mpl')
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuit,backend = simulator).result()
from qiskit.tools.visualization import plot_histogram
plot_histogram(result.get_counts(circuit))
IBMQ.load_account()
provider = IBMQ.get_provider('ibm-q')
qcomp = provider.get_backend('ibmq_16_melbourne')
job = execute(circuit,backend = qcomp)
from qiskit.tools.monitor import job_monitor
job_monitor(job)
result = job.result()
plot_histogram(result.get_counts(circuit))
|
https://github.com/SanNare/qiskit-notebooks
|
SanNare
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector, DensityMatrix
from qiskit.tools.visualization import plot_state_qsphere, plot_histogram
def init_message(circuit,n = 1,m = 0,hads = 0):
if isinstance(m,int):
m = bin(m)[2:]
m = m.zfill(n)
if isinstance(hads,int):
hads = bin(hads)[2:]
hads = hads.zfill(n)
for i in range(0,n):
if m[i] == '1':
circuit.x(i)
if hads[i] == '1':
circuit.h(i)
def encrypt(n,key1 = 0,key2 = 0):
circuit = QuantumCircuit(n)
if isinstance(key1,int):
k1 = bin(key1)[2:]
k1 = k1.zfill(n)
if isinstance(key2,int):
k2 = bin(key2)[2:]
k2 = k2.zfill(n)
for i in range(0,n):
if k1[i] == '1':
circuit.x(i)
if k2[i] == '1':
circuit.z(i)
return circuit.to_gate()
def decrypt(n,key1 = 0,key2 = 0):
return encrypt(n,key1,key2).inverse()
n = 2
k1,k2 = 3,3
m = 0
hads = 3
circuit = QuantumCircuit(n)
init_message(circuit,n,m,hads)
#encryption
enc = encrypt(n,k1,k2)
enc.label = 'Enc({},{},{})'.format(n,k1,k2)
circuit.append(enc,list(range(0,n)))
# #decryption: uncomment to apply
# dec = decrypt(n,k1,k2)
# dec.label = 'Dec({},{},{})'.format(n,k1,k2)
# circuit.append(dec,list(range(0,n)))
%matplotlib inline
circuit.draw(output = 'mpl')
#Uncomment to view contents of the encryption and/or decryption circuits
#circuit.decompose().draw(output = 'mpl')
sv = Statevector.from_label("00")
dm = DensityMatrix(sv)
nsv = sv.evolve(circuit)
ndm = dm.evolve(circuit)
print(nsv.data)
print(ndm.data)
|
https://github.com/SanNare/qiskit-notebooks
|
SanNare
|
! pip install qiskit
from qiskit import QuantumCircuit, Aer, IBMQ, execute
from qiskit.tools.monitor import job_monitor
import math
def superpose(n):
circuit = QuantumCircuit(n,n)
for i in range(0,n):
circuit.h(i)
circuit.measure(range(n),range(n))
return circuit
sample = superpose(6)
sample.draw('mpl')
def qrandom_sim(a,b):
n = math.ceil(math.log2(b))
circuit = superpose(n)
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuit,backend = simulator, shots = 1).result()
v = int(list(result.get_counts(circuit).keys())[0],2)
return v%(b-a+1)+a
r = qrandom_sim(2,20)
print(r)
IBMQ.load_account()
def qrandom(a,b):
n = math.ceil(math.log2(b))
circuit = superpose(n)
provider = IBMQ.get_provider('ibm-q')
qcomp = provider.get_backend('ibmq_16_melbourne')
job = execute(circuit,backend = qcomp,shots = 1)
job_monitor(job)
result = job.result()
v = int(list(result.get_counts(circuit).keys())[0],2)
return v%(b-a+1)+a
r = qrandom(20,40)
print(r)
|
https://github.com/SanNare/qiskit-notebooks
|
SanNare
|
from qiskit import *
from qiskit.tools.visualization import plot_histogram,plot_bloch_multivector
circuit = QuantumCircuit(1,1)
circuit.x(0)
simulator = Aer.get_backend('statevector_simulator')
result = execute(circuit,backend = simulator).result()
statevector = result.get_statevector()
print(statevector)
%matplotlib inline
circuit.draw(output = 'mpl')
plot_bloch_multivector(statevector)
circuit.measure([0],[0])
backend = Aer.get_backend('qasm_simulator')
result = execute(circuit,backend = backend,shots = 1024).result()
counts = result.get_counts()
plot_histogram(counts)
circuit = QuantumCircuit(1,1)
circuit.x(0)
simulator = Aer.get_backend('unitary_simulator')
result = execute(circuit,backend = simulator).result()
unitary = result.get_unitary()
print(unitary)
|
https://github.com/SanNare/qiskit-notebooks
|
SanNare
|
from qiskit import QuantumCircuit
from qiskit.tools.visualization import plot_histogram
from qiskit.extensions import UnitaryGate
import numpy as np
def logicalAnd(circuit,input_qubits,output_qubit):
circuit.mcx(input_qubits,output_qubit)
def logicalOr(circuit,input_qubits,output_qubit):
for i in input_qubits:
circuit.x(i)
circuit.x(output_qubit)
circuit.mcx(input_qubits,output_qubit)
for i in input_qubits:
circuit.x(i)
def CNF(maxterms):
n = len(maxterms[0])
m = len(maxterms)
circuit = QuantumCircuit(n+m+1)
o = n
for t in maxterms:
inp = []
for i in range(0,n):
if t[i] == -1:
circuit.x(i)
inp.append(i)
elif t[i] == 1:
inp.append(i)
logicalOr(circuit,inp,o)
for i in range(0,n):
if t[i] == -1:
circuit.x(i)
o = o+1
logicalAnd(circuit,list(range(n,n+m)),n+m)
return circuit.to_gate()
def diffusion(n):
m = np.identity(2**n)
for i in range(1,2**n):
m[i][i] = -1
return UnitaryGate(m)
def grover(maxterms,rounds = 0):
n = len(maxterms[0]) #number of variables
N = 2**n #solution space size
m = len(maxterms) #number of maxterms
if rounds == 0:
r = int(np.ceil(np.pi/(4*np.arcsin(1/np.sqrt(N)))-0.5))
else:
r = rounds
circuit = QuantumCircuit(n+m+1,n)
circuit.x(n+m)
circuit.h(n+m)
for i in range(n):
circuit.h(i)
cnf = CNF(maxterms)
cnf.label = 'Uf'
diff = diffusion(n)
diff.label = 'Diff'
for i in range(r):
circuit.append(cnf,range(n+m+1))
for i in range(n,n+m):
circuit.reset(i)
for i in range(n):
circuit.h(i)
circuit.append(diff,range(n))
for i in range(n):
circuit.h(i)
for i in range(n):
circuit.measure(i,i)
return circuit
maxterms = [[1,1,1],[-1,-1,-1]] # This seems to behave like f(x,y,z) = xyz + x'y'z' (DNF) even though the function is CNF
circuit = grover(maxterms)
#circuit = grover(maxterms)
circuit.draw('mpl')
from qiskit import Aer, execute
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuit, simulator, shots=1000).result()
counts = result.get_counts(circuit)
print(counts)
plot_histogram(counts)
|
https://github.com/SanNare/qiskit-notebooks
|
SanNare
|
# Do the necessary imports
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import IBMQ, Aer, transpile, assemble
from qiskit.visualization import plot_histogram, plot_bloch_multivector, array_to_latex
from qiskit.extensions import Initialize
from qiskit.ignis.verification import marginal_counts
from qiskit.quantum_info import random_statevector
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
## SETUP
# Protocol uses 3 qubits and 2 classical bits in 2 different registers
qr = QuantumRegister(3, name="q") # Protocol uses 3 qubits
crz = ClassicalRegister(1, name="crz") # and 2 classical bits
crx = ClassicalRegister(1, name="crx") # in 2 different registers
teleportation_circuit = QuantumCircuit(qr, crz, crx)
def create_bell_pair(qc, a, b):
qc.h(a)
qc.cx(a,b)
qr = QuantumRegister(3, name="q")
crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx")
teleportation_circuit = QuantumCircuit(qr, crz, crx)
create_bell_pair(teleportation_circuit, 1, 2)
teleportation_circuit.draw()
def alice_gates(qc, psi, a):
qc.cx(psi, a)
qc.h(psi)
qr = QuantumRegister(3, name="q")
crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx")
teleportation_circuit = QuantumCircuit(qr, crz, crx)
## STEP 1
create_bell_pair(teleportation_circuit, 1, 2)
## STEP 2
teleportation_circuit.barrier() # Use barrier to separate steps
alice_gates(teleportation_circuit, 0, 1)
teleportation_circuit.draw()
def measure_and_send(qc, a, b):
"""Measures qubits a & b and 'sends' the results to Bob"""
qc.barrier()
qc.measure(a,0)
qc.measure(b,1)
qr = QuantumRegister(3, name="q")
crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx")
teleportation_circuit = QuantumCircuit(qr, crz, crx)
create_bell_pair(teleportation_circuit, 1, 2)
teleportation_circuit.barrier() # Use barrier to separate steps
alice_gates(teleportation_circuit, 0, 1)
measure_and_send(teleportation_circuit, 0 ,1)
teleportation_circuit.draw()
def bob_gates(qc, qubit, crz, crx):
qc.x(qubit).c_if(crx, 1) # Apply gates if the registers
qc.z(qubit).c_if(crz, 1) # are in the state '1'
qr = QuantumRegister(3, name="q")
crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx")
teleportation_circuit = QuantumCircuit(qr, crz, crx)
## STEP 1
create_bell_pair(teleportation_circuit, 1, 2)
## STEP 2
teleportation_circuit.barrier() # Use barrier to separate steps
alice_gates(teleportation_circuit, 0, 1)
## STEP 3
measure_and_send(teleportation_circuit, 0, 1)
## STEP 4
teleportation_circuit.barrier() # Use barrier to separate steps
bob_gates(teleportation_circuit, 2, crz, crx)
teleportation_circuit.draw()
# Create random 1-qubit state
psi = random_statevector(2)
# Display it nicely
display(array_to_latex(psi, prefix="|\\psi\\rangle ="))
# Show it on a Bloch sphere
plot_bloch_multivector(psi)
init_gate = Initialize(psi)
init_gate.label = "init"
## SETUP
qr = QuantumRegister(3, name="q") # Protocol uses 3 qubits
crz = ClassicalRegister(1, name="crz") # and 2 classical registers
crx = ClassicalRegister(1, name="crx")
qc = QuantumCircuit(qr, crz, crx)
## STEP 0
# First, let's initialize Alice's q0
qc.append(init_gate, [0])
qc.barrier()
## STEP 1
# Now begins the teleportation protocol
create_bell_pair(qc, 1, 2)
qc.barrier()
## STEP 2
# Send q1 to Alice and q2 to Bob
alice_gates(qc, 0, 1)
## STEP 3
# Alice then sends her classical bits to Bob
measure_and_send(qc, 0, 1)
## STEP 4
# Bob decodes qubits
bob_gates(qc, 2, crz, crx)
# Display the circuit
qc.draw()
sim = Aer.get_backend('aer_simulator')
qc.save_statevector()
out_vector = sim.run(qc).result().get_statevector()
plot_bloch_multivector(out_vector)
|
https://github.com/SanNare/qiskit-notebooks
|
SanNare
|
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_qsphere, plot_histogram
def bellstate(n): #returns a bell state depending on the input integer
if n not in [0,1,2,3]:
print('Enter 0,1,2 or 3 only. Value taken as n mod 4 = {}.'.format(n%4))
n = 0
n = bin(n)[2:].zfill(2)
cir = QuantumCircuit(2)
cir.h(0)
cir.cx(0,1)
sv = Statevector.from_label(n[::-1])
return sv.evolve(cir)
psi = bellstate(4)
%matplotlib inline
plot_state_qsphere(psi.data)
def bell(cir,i,j):
cir.h(i)
cir.cx(i,j)
def bell_measure(cir,i,j):
cir.cx(i,j)
cir.h(i)
q = QuantumRegister(6,'q')
c0 = ClassicalRegister(1,'c0')
c1 = ClassicalRegister(1,'c1')
c2 = ClassicalRegister(1,'c2')
c3 = ClassicalRegister(1,'c3')
c4 = ClassicalRegister(1,'c4')
c5 = ClassicalRegister(1,'c5')
circuit = QuantumCircuit(q,c0,c1,c2,c3,c4,c5)
#initialize states
bell(circuit,0,1)
circuit.barrier()
bell(circuit,2,4)
circuit.barrier()
bell(circuit,3,5)
circuit.barrier()
#teleport Alice's first qubit
bell_measure(circuit,0,2)
circuit.barrier()
circuit.measure([0,2],[0,1])
circuit.x(4).c_if(c1,1)
circuit.z(4).c_if(c0,1)
circuit.barrier()
#teleport Alice's second qubit
bell_measure(circuit,1,3)
circuit.barrier()
circuit.measure([1,3],[2,3])
circuit.x(5).c_if(c3,1)
circuit.z(5).c_if(c2,1)
circuit.barrier()
#measure Bob's qubits
circuit.measure([4,5],[4,5])
circuit.draw('mpl')
from qiskit import Aer, execute
from collections import defaultdict
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuit, simulator, shots=10000).result()
counts = result.get_counts(circuit)
print(counts)
plot_histogram(counts)
# count = {s.replace(' ',''):counts[s] for s in counts.keys()}
# print(count)
count = defaultdict(int)
for k in counts.keys():
key = k[0:3]
count[key]+=counts[k]
print(count)
|
https://github.com/aaghazaly/quantum-project-using-qiskit
|
aaghazaly
|
'''
Deutsch-Jozsa Algorithm
Consider a function f(x) that takes as input n-bit strings x and returns 0 or 1. Suppose we are
promised that f(x) is either a constant function that takes the same value c in {0,1} on all
inputs x, or a balanced function that takes each value 0 and 1 on exactly half of the inputs.
The goal is to decide whether f is constant or balanced by making as few function evaluations
as possible. Classically, it requires 2^{n-1}+1 function evaluations in the worst case. Using
the Deutsch-Jozsa algorithm, the question can be answered with just one function evaluation.
Deutsch's algorithm is the simpler case of Deutsch-Jozsa Algorithm which has a function f(x)
which takes 1-bit as input.
Source: https://github.com/Qiskit/ibmqx-user-guides/blob/master/rst/full-user-guide/004-Quantum_Algorithms/080-Deutsch-Jozsa_Algorithm.rst
'''
from qiskit import IBMQ, BasicAer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.tools.monitor import job_monitor
qr = QuantumRegister(2) # Initialize two qubits
cr = ClassicalRegister(2) # Initialize two bits for record measurements
circuit = QuantumCircuit(qr, cr)
circuit.x(qr[1]) # initialize the ancilla qubit in the |1> state
circuit.barrier()
# First step of quantum algorithms - Prepare the superposition
# For superposition, we apply the Hadamard gate on both qubits
circuit.h(qr[0])
circuit.h(qr[1])
circuit.barrier()
# Oracle function
circuit.cx(qr[0], qr[1])
circuit.barrier()
# Apply Hadamard gates after querying oracle function
circuit.h(qr[0])
circuit.h(qr[1])
circuit.barrier()
# Measure qubit
circuit.measure(qr[0], cr[0])
# Run our circuit with local simulator
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
results = execute(circuit, backend=backend, shots=shots).result()
answer = results.get_counts()
print("Simulator result")
for c1c0 in answer:
print(f'c0 = {c1c0[1]} ({answer[c1c0]} shots)')
# C0 observed as 1 in 1024 shots
# It indicates f(0) != f(1)
# Run our circuit with real devices
IBMQ.load_account()
IBMQ.backends()
backend_lb = least_busy(IBMQ.backends(simulator=False))
backend = backend_lb
shots = 1024
job_exp = execute(circuit, backend=backend, shots=shots)
job_monitor(job_exp, interval=2)
results = job_exp.result()
answer = results.get_counts(circuit)
print("Real Device Result")
for c1c0 in answer:
print(f'c0 = {c1c0[1]} ({answer[c1c0]} shots)')
# As we can see in results, most of the results for C0 is 1
# It indicates f(0) != f(1)
# The results with C0 = 0 occur due to errors in the quantum computation.
|
https://github.com/aaghazaly/quantum-project-using-qiskit
|
aaghazaly
|
from argparse import ArgumentParser, Namespace, BooleanOptionalAction
from qiskit import QuantumCircuit as qc
from qiskit import QuantumRegister as qr
from qiskit import transpile
from qiskit_aer import AerSimulator
from qiskit.result import Counts
from matplotlib.pyplot import show, subplots, xticks, yticks
from math import pi, sqrt
from heapq import nlargest
class GroversAlgorithm:
def __init__(self,
title: str = "Grover's Algorithm",
n_qubits: int = 5,
search: set[int] = { 11, 9, 0, 3 },
shots: int = 1000,
fontsize: int = 10,
print: bool = False,
combine_states: bool = False) -> None:
"""
_summary_
Args:
title (str, optional): Window title. Defaults to "Grover's Algorithm".
n_qubits (int, optional): Number of qubits. Defaults to 5.
search (set[int], optional): Set of nonnegative integers to search for using Grover's algorithm. Defaults to { 11, 9, 0, 3 }.
shots (int, optional): Amount of times the algorithm is simulated. Defaults to 10000.
fontsize (int, optional): Histogram's font size. Defaults to 10.
print (bool, optional): Whether or not to print quantum circuit(s). Defaults to False.
combine_states (bool, optional): Whether to combine all non-winning states into 1 bar labeled "Others" or not. Defaults to False.
"""
# Parsing command line arguments
self._parser: ArgumentParser = ArgumentParser(description = "Run grover's algorithm via command line", add_help = False)
self._init_parser(title, n_qubits, search, shots, fontsize, print, combine_states)
self._args: Namespace = self._parser.parse_args()
# Set of nonnegative ints to search for
self.search: set[int] = set(self._args.search)
# Set of m N-qubit binary strings representing target state(s) (i.e. self.search in base 2)
self._targets: set[str] = { f"{s:0{self._args.n_qubits}b}" for s in self.search }
# N-qubit quantum register
self._qubits: qr = qr(self._args.n_qubits, "qubit")
def _print_circuit(self, circuit: qc, name: str) -> None:
"""Print quantum circuit.
Args:
circuit (qc): Quantum circuit to print.
name (str): Quantum circuit's name.
"""
print(f"\n{name}:\n{circuit}")
def _oracle(self, targets: set[str]) -> qc:
"""Mark target state(s) with negative phase.
Args:
targets (set[str]): N-qubit binary string(s) representing target state(s).
Returns:
qc: Quantum circuit representation of oracle.
"""
# Create N-qubit quantum circuit for oracle
oracle = qc(self._qubits, name = "Oracle")
for target in targets:
# Reverse target state since Qiskit uses little-endian for qubit ordering
target = target[::-1]
# Flip zero qubits in target
for i in range(self._args.n_qubits):
if target[i] == "0":
# Pauli-X gate
oracle.x(i)
# Simulate (N - 1)-control Z gate
# 1. Hadamard gate
oracle.h(self._args.n_qubits - 1)
# 2. (N - 1)-control Toffoli gate
oracle.mcx(list(range(self._args.n_qubits - 1)), self._args.n_qubits - 1)
# 3. Hadamard gate
oracle.h(self._args.n_qubits - 1)
# Flip back to original state
for i in range(self._args.n_qubits):
if target[i] == "0":
# Pauli-X gate
oracle.x(i)
# Display oracle, if applicable
if self._args.print: self._print_circuit(oracle, "ORACLE")
return oracle
def _diffuser(self) -> qc:
"""Amplify target state(s) amplitude, which decreases the amplitudes of other states
and increases the probability of getting the correct solution (i.e. target state(s)).
Returns:
qc: Quantum circuit representation of diffuser (i.e. Grover's diffusion operator).
"""
# Create N-qubit quantum circuit for diffuser
diffuser = qc(self._qubits, name = "Diffuser")
# Hadamard gate
diffuser.h(self._qubits)
# Oracle with all zero target state
diffuser.append(self._oracle({"0" * self._args.n_qubits}), list(range(self._args.n_qubits)))
# Hadamard gate
diffuser.h(self._qubits)
# Display diffuser, if applicable
if self._args.print: self._print_circuit(diffuser, "DIFFUSER")
return diffuser
def _grover(self) -> qc:
"""Create quantum circuit representation of Grover's algorithm,
which consists of 4 parts: (1) state preparation/initialization,
(2) oracle, (3) diffuser, and (4) measurement of resulting state.
Steps 2-3 are repeated an optimal number of times (i.e. Grover's
iterate) in order to maximize probability of success of Grover's algorithm.
Returns:
qc: Quantum circuit representation of Grover's algorithm.
"""
# Create N-qubit quantum circuit for Grover's algorithm
grover = qc(self._qubits, name = "Grover Circuit")
# Intialize qubits with Hadamard gate (i.e. uniform superposition)
grover.h(self._qubits)
# # Apply barrier to separate steps
grover.barrier()
# Apply oracle and diffuser (i.e. Grover operator) optimal number of times
for _ in range(int((pi / 4) * sqrt((2 ** self._args.n_qubits) / len(self._targets)))):
grover.append(self._oracle(self._targets), list(range(self._args.n_qubits)))
grover.append(self._diffuser(), list(range(self._args.n_qubits)))
# Measure all qubits once finished
grover.measure_all()
# Display grover circuit, if applicable
if self._args.print: self._print_circuit(grover, "GROVER CIRCUIT")
return grover
def _outcome(self, winners: list[str], counts: Counts) -> None:
"""Print top measurement(s) (state(s) with highest frequency)
and target state(s) in binary and decimal form, determine
if top measurement(s) equals target state(s), then print result.
Args:
winners (list[str]): State(s) (N-qubit binary string(s))
with highest probability of being measured.
counts (Counts): Each state and its respective frequency.
"""
print("WINNER(S):")
print(f"Binary = {winners}\nDecimal = {[ int(key, 2) for key in winners ]}\n")
print("TARGET(S):")
print(f"Binary = {self._targets}\nDecimal = {self.search}\n")
if not all(key in self._targets for key in winners): print("Target(s) not found...")
else:
winners_frequency, total = 0, 0
for value, frequency in counts.items():
if value in winners:
winners_frequency += frequency
total += frequency
print(f"Target(s) found with {winners_frequency / total:.2%} accuracy!")
def _show_histogram(self, histogram_data) -> None:
"""Print outcome and display histogram of simulation results.
Args:
data: Each state and its respective frequency.
"""
# State(s) with highest count and their frequencies
winners = { winner : histogram_data.get(winner) for winner in nlargest(len(self._targets), histogram_data, key = histogram_data.get) }
# Print outcome
self._outcome(list(winners.keys()), histogram_data)
# X-axis and y-axis value(s) for winners, respectively
winners_x_axis = [ str(winner) for winner in [*winners] ]
winners_y_axis = [ *winners.values() ]
# All other states (i.e. non-winners) and their frequencies
others = { state : frequency for state, frequency in histogram_data.items() if state not in winners }
# X-axis and y-axis value(s) for all other states, respectively
other_states_x_axis = "Others" if self._args.combine else [*others]
other_states_y_axis = [ sum([*others.values()]) ] if self._args.combine else [ *others.values() ]
# Create histogram for simulation results
figure, axes = subplots(num = "Grover's Algorithm — Results", layout = "constrained")
axes.bar(winners_x_axis, winners_y_axis, color = "green", label = "Target")
axes.bar(other_states_x_axis, other_states_y_axis, color = "red", label = "Non-target")
axes.legend(fontsize = self._args.fontsize)
axes.grid(axis = "y", ls = "dashed")
axes.set_axisbelow(True)
# Set histogram title, x-axis title, and y-axis title respectively
axes.set_title(f"Outcome of {self._args.shots} Simulations", fontsize = int(self._args.fontsize * 1.45))
axes.set_xlabel("States (Qubits)", fontsize = int(self._args.fontsize * 1.3))
axes.set_ylabel("Frequency", fontsize = int(self._args.fontsize * 1.3))
# Set font properties for x-axis and y-axis labels respectively
xticks(fontsize = self._args.fontsize, family = "monospace", rotation = 0 if self._args.combine else 70)
yticks(fontsize = self._args.fontsize, family = "monospace")
# Set properties for annotations displaying frequency above each bar
annotation = axes.annotate("",
xy = (0, 0),
xytext = (5, 5),
xycoords = "data",
textcoords = "offset pixels",
ha = "center",
va = "bottom",
family = "monospace",
weight = "bold",
fontsize = self._args.fontsize,
bbox = dict(facecolor = "white", alpha = 0.4, edgecolor = "None", pad = 0)
)
def _hover(event) -> None:
"""Display frequency above each bar upon hovering over it.
Args:
event: Matplotlib event.
"""
visibility = annotation.get_visible()
if event.inaxes == axes:
for bars in axes.containers:
for bar in bars:
cont, _ = bar.contains(event)
if cont:
x, y = bar.get_x() + bar.get_width() / 2, bar.get_y() + bar.get_height()
annotation.xy = (x, y)
annotation.set_text(y)
annotation.set_visible(True)
figure.canvas.draw_idle()
return
if visibility:
annotation.set_visible(False)
figure.canvas.draw_idle()
# Display histogram
id = figure.canvas.mpl_connect("motion_notify_event", _hover)
show()
figure.canvas.mpl_disconnect(id)
def run(self) -> None:
"""
Run Grover's algorithm simulation.
"""
# Simulate Grover's algorithm locally
backend = AerSimulator(method = "density_matrix")
# Generate optimized grover circuit for simulation
transpiled_circuit = transpile(self._grover(), backend, optimization_level = 2)
# Run Grover's algorithm simulation
job = backend.run(transpiled_circuit, shots = self._args.shots)
# Get simulation results
results = job.result()
# Get each state's histogram data (including frequency) from simulation results
data = results.get_counts()
# Display simulation results
self._show_histogram(data)
def _init_parser(self,
title: str,
n_qubits: int,
search: set[int],
shots: int,
fontsize: int,
print: bool,
combine_states: bool) -> None:
"""
Helper method to initialize command line argument parser.
Args:
title (str): Window title.
n_qubits (int): Number of qubits.
search (set[int]): Set of nonnegative integers to search for using Grover's algorithm.
shots (int): Amount of times the algorithm is simulated.
fontsize (int): Histogram's font size.
print (bool): Whether or not to print quantum circuit(s).
combine_states (bool): Whether to combine all non-winning states into 1 bar labeled "Others" or not.
"""
self._parser.add_argument("-H, --help",
action = "help",
help = "show this help message and exit")
self._parser.add_argument("-T, --title",
type = str,
default = title,
dest = "title",
metavar = "<title>",
help = f"window title (default: \"{title}\")")
self._parser.add_argument("-n, --n-qubits",
type = int,
default = n_qubits,
dest = "n_qubits",
metavar = "<n_qubits>",
help = f"number of qubits (default: {n_qubits})")
self._parser.add_argument("-s, --search",
default = search,
type = int,
nargs = "+",
dest = "search",
metavar = "<search>",
help = f"nonnegative integers to search for with Grover's algorithm (default: {search})")
self._parser.add_argument("-S, --shots",
type = int,
default = shots,
dest = "shots",
metavar = "<shots>",
help = f"amount of times the algorithm is simulated (default: {shots})")
self._parser.add_argument("-f, --font-size",
type = int,
default = fontsize,
dest = "fontsize",
metavar = "<font_size>",
help = f"histogram's font size (default: {fontsize})")
self._parser.add_argument("-p, --print",
action = BooleanOptionalAction,
type = bool,
default = print,
dest = "print",
help = f"whether or not to print quantum circuit(s) (default: {print})")
self._parser.add_argument("-c, --combine",
action = BooleanOptionalAction,
type = bool,
default = combine_states,
dest = "combine",
help = f"whether to combine all non-winning states into 1 bar labeled \"Others\" or not (default: {combine_states})")
if __name__ == "__main__":
GroversAlgorithm().run()
|
https://github.com/aaghazaly/quantum-project-using-qiskit
|
aaghazaly
|
'''
Shor's Algorithm
Shor's algorithm is a quantum computer algorithm for integer factorization.
Informally, it solves the following problem: Given an integer N, find its
prime factors. It was invented in 1994 by the American mathematician Peter Shor.
Source: https://www.wikiwand.com/en/Shor%27s_algorithm
Factorization problem can reduce to period finding problem. Consider the sequence
of the powers of two
1, 2, 4, 8, 16, 32, 64, 128, ...
Now, let's look at the same sequence 'mod 15':
1, 2, 4, 8, 1, 2, 4, 8, ...
This is a modulo sequence that repeats every four numbers, that is, a periodic modulo
sequence with a period of four. Reduction of factorization of N to the problem of
finding the period of an integer 1 < x < N depends on the following result from number theory:
The function F(a) = x^a mod N is a periodic function, where x is an integer coprime
to N and a >= 0.
Source: https://github.com/Qiskit/qiskit-community-tutorials/blob/b9266a4f9c1f6b3f4cf5117d9c443f9f1c3518cb/algorithms/shor_algorithm.ipynb
'''
import math
from qiskit import IBMQ, BasicAer
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
# We'll build circuit for a^x mod 15 for a = 2
qr = QuantumRegister(5)
cr = ClassicalRegister(5)
circuit = QuantumCircuit(qr, cr)
# Initialize q[0] to |1>
circuit.x(qr[0])
# Apply a**4 mod 15
circuit.h(qr[4])
circuit.h(qr[4])
circuit.measure(qr[4], cr[0])
circuit.reset(qr[4])
# Apply a**2 mod 15
circuit.h(qr[4])
circuit.cx(qr[4], qr[2])
circuit.cx(qr[4], qr[0])
circuit.u1(math.pi/2., qr[4]).c_if(cr, 1)
circuit.u1(math.pi/2., qr[4]).c_if(cr, 1)
circuit.h(qr[4])
circuit.measure(qr[4], cr[1])
circuit.reset(qr[4])
# Apply a mod 15
circuit.h(qr[4])
circuit.cswap(qr[4], qr[3], qr[2])
circuit.cswap(qr[4], qr[2], qr[1])
circuit.cswap(qr[4], qr[1], qr[0])
circuit.u1(3.*math.pi/4., qr[4]).c_if(cr, 3)
circuit.u1(math.pi/2., qr[4]).c_if(cr, 2)
circuit.u1(math.pi/4., qr[4]).c_if(cr, 1)
circuit.h(qr[4])
circuit.measure(qr[4], cr[2])
# Run our circuit with local simulator
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
results = execute(circuit, backend=backend, shots=shots).result()
answer = results.get_counts()
print(answer)
# We see the measurements yield x = 0, 2, 4 and 6 with equal(ish) probability.
# Using the continued fraction expansion for x/2^3, we note that only x = 2 and
# 6 give the correct period r = 4, and thus the factors p = gcd(a^{r/2}+1,15) = 3
# and q = gcd(a^{r/2}-1,15) = 5.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.