Qiskit Experience (Demo)

Preparation

link : https://quantum-computing.ibm.com/

Demo

Qubits & Quantum States, Circuits, Measurements

import numpy as np
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_qsphere
n =1
qc= QuantumCircuit(n,n)
statevec = Statevector.from_instruction(qc).data
print(statevec)
plot_state_qsphere(statevec)
n =6
qc= QuantumCircuit(n,n)
for i in range(n):
qc.h(i)
qc.rz(2*np.pi/n,i)
statevec = Statevector.from_instruction(qc).data
plot_state_qsphere(statevec)
n=2
qz= QuantumCircuit(4)
qc.h(0)
for i in range(n):
qc.cx(0,i+1)
qc.x(2)
statevec = Statevector.from_instruction(qc).data
plot_state_qsphere(statevec)

Part 1

import numpy as np# Importing standard Qiskit libraries and configuring account
from qiskit import IBMQ, BasicAer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, execute
from qiskit.tools.jupyter import *
#import basic plot toold
from qiskit.visualization import plot_histogram
IBMQ.save_account('<your TOKEN>')
provider = IBMQ.load_account()
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":
#We apply controlled-NOT gates for each qubit, using the
#output qubit as the target:
for qubit in range(n):
oracle_qc.cx(qubit,n)

#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(n, case = 'random'):
dj_circuit = QuantumCircuit(n+1,n)
#set up the input register:
for qubit in range(n):
dj_circuit.h(qubit)
#And set up the output qubit:
dj_circuit.x(n)
dj_circuit.h(n)
#Let's append the oracle gate to our ciruit:
if case == 'random':
random = np.random.randint(2)
if random == 0:
case = 'constant'
else:
case = 'balanced'
oracle = dj_oracle(case, n)
dj_circuit.append(oracle, range(n+1))
# Finally,perfom the H-gates again and measure:
for i in range(n):
dj_circuit.h(i)
dj_circuit.measure(i,i)
return dj_circuit
n=4
dj_circuit = dj_algorithm(n)
dj_circuit.draw()
# use local simulator
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
dj_circuit = dj_algorithm(n, 'constant')
result = execute(dj_circuit, backend=backend, shots=shots).result()
answer = result.get_counts()
plot_histogram(answer)
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)
%qiskit_job_watcher
dj_circuit= dj_algorithm(n)
job = execute(dj_circuit, backend=backend, shots=shots, optimization_level=3)
least busy backend:  ibmq_vigo
# Get the result of the computation
results = job.result()
answer = results.get_counts()
plot_histogram(answer)
## job I ran before
backend = provider.get_backend('<your backend>')
old_job = backend.retrieve_job('<your job id>')
result = old_job.result()
answer = results.get_counts()
plot_histogram(answer)

Part 2

import numpy as np# Importing standard Qiskit libraries and configuring account
from qiskit import IBMQ, QuantumCircuit, Aer, execute
from qiskit.quantum_info import Operator
from qiskit.providers.ibmq import least_busy
from qiskit.visualization import plot_histogram
from qiskit.tools.jupyter import *
IBMQ.save_account('<your TOKEN>')
provider = IBMQ.load_account()
def phase_oracle(n, indices_to_mark, name = 'Oracle'):
qc= QuantumCircuit(n, name=name)
oracle_matrix = np.identity(2**n)
for index_to_mark in indices_to_mark:
oracle_matrix[index_to_mark, index_to_mark] = -1
qc.unitary(Operator(oracle_matrix), range(n))
return qc
def diffuser(n):
qc = QuantumCircuit(n, name = 'Diff - "V"')
qc.h(range(n))
qc.append(phase_oracle(n,[0]),range(n))
qc.h(range(n))
return qc
def Grover(n, marked):
qc = QuantumCircuit(n,n)
r = int(np.round(np.pi/(4*np.arcsin(np.sqrt(len(marked)/2**n)))-1/2))
print(f'{n} qubits, bases state {marked} marked, {r} rounds')
qc.h(range(n))
for _ in range(r):
qc.append(phase_oracle(n,marked),range(n))
qc.append(diffuser(n), range(n))
qc.measure(range(n),range(n))
return qc
n = 5
x = np.random.randint(2**n)
marked = [x]
qc = Grover(n, marked)
qc.draw()
backend = Aer.get_backend('qasm_simulator')
result = execute(qc, backend, shots=10000).result()
counts = result.get_counts(qc)
print(counts)
print(np.pi/(4*np.arcsin(np.sqrt(len(marked)/2**n)))-1/2)
plot_histogram(counts)
n = 3
x = np.random.randint(2**n)
y = np.random.randint(2**n)
while y==x:
y = np.random.randint(2**n)
marked = [x,y]
qc = Grover(n, marked)
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits == 5 and not x.configuration().simulator and x.status().operational==True))
#print("least busy backend: ", backend)
backend = provider.get_backend('ibmq_vigo')
%qiskit_job_watcher
shots = 1024
job = execute(qc, backend=backend, shots=shots, optimization_level = 3)
3 qubits, bases state [7, 4] marked, 1 rounds
results = job.result()
answer= results.get_counts()
plot_histogram(answer)
backend = provider.get_backend('<your backend>')
old_job = backend.retrieve_job('<your job id>')
result = old_job.result()
answer = results.get_counts()
plot_histogram(answer)
import numpy as np
from numpy import pi
# importing Qiskit
from qiskit.circuit.library import QFT
from qiskit.quantum_info import Statevector
from qiskit import QuantumCircuit
from qiskit.visualization import plot_bloch_multivector
import warnings
warnings.filterwarnings('ignore')
pi = np.pidef myQFT(nqubits):

myQFT_circuit = QuantumCircuit(nqubits)

for qubit in range(nqubits):
myQFT_circuit.h(qubit)
for otherqubit in range(qubit+1, nqubits):
myQFT_circuit.cu1( pi / (2** (otherqubit-qubit)), otherqubit, qubit)

return myQFT_circuit
def QFT(nqubits):

QFT_circuit = QuantumCircuit(nqubits)

for qubit in range(nqubits):
QFT_circuit.h(qubit)
for otherqubit in range(qubit+1, nqubits):
QFT_circuit.cu1( pi / (2** (otherqubit-qubit)), otherqubit, qubit)

return QFT_circuit
display(myQFT(4).draw)
display(QFT(4).draw)
<bound method QuantumCircuit.draw of <qiskit.circuit.quantumcircuit.QuantumCircuit object at 0x0000024922ADB788>><bound method QuantumCircuit.draw of <qiskit.circuit.quantumcircuit.QuantumCircuit object at 0x0000024922ADB7C8>>
state = '00'
sv = Statevector.from_label(state)
print(sv)
mycircuit = QuantumCircuit(len(state))
mycircuit.initialize(sv.data, mycircuit.qubits[::-1])
print("Computaional basis")
display(plot_bloch_multivector(sv.data))
sv = sv.evolve(myQFT(len(state)))
print("Fourier basis")
mycircuit.append(myQFT(len(state)), mycircuit.qubits)
display(plot_bloch_multivector(sv.data))
state = '000'
sv = Statevector.from_label(state)
print(sv)
mycircuit = QuantumCircuit(len(state))
mycircuit.initialize(sv.data, mycircuit.qubits[::-1])
print(f'Computaional basis | {state}>')
display(plot_bloch_multivector(sv.data))
sv = sv.evolve(QFT(len(state)))
print(f'Fourier basis | {state}>')
mycircuit.append(QFT(len(state)), mycircuit.qubits)
display(plot_bloch_multivector(sv.data))
n_qubits = 3
states = [format(x, f'0{n_qubits}b') for x in range(2**n_qubits)]
states.append(state[0])
for ii, state in enumerate(states):
mycircuit = QuantumCircuit(len(state))
sv = Statevector.from_label(state)
print(sv)
mycircuit.initialize(sv.data, mycircuit.qubits[::1])
print('====================================')
print("Computaional basis")
display(plot_bloch_multivector(sv.data))
sv = sv.evolve(myQFT(len(state)))
print("Fourier basis")
mycircuit.append(myQFT(len(state)), mycircuit.qubits)
display(plot_bloch_multivector(sv.data))
print('====================================')
state = '001'
sv = Statevector.from_label(state)
print(sv)
mycircuit = QuantumCircuit(len(state))
mycircuit.initialize(sv.data, mycircuit.qubits[::-1])
print(f'Computaional basis | {state}>')
display(plot_bloch_multivector(sv.data))
sv = sv.evolve(QFT(len(state)))
print(f'Fourier basis | {state}>')
mycircuit.append(QFT(len(state)), mycircuit.qubits)
display(plot_bloch_multivector(sv.data))

Part 1

import mathN = 5*3
a = 13
math.gcd(a, N)
1
import matplotlib.pyplot as plotterz = list(range(N))
y = [a**z0 % N for z0 in z]
plotter.plot(z,y)
plotter.xlabel('z')
plotter.ylabel(f'{a}^z (mod {N})')
plotter.show()
r = z[y[1:].index(1)+1]
print(f'r = {r}')
r = 4
if r %2 == 0:
x = (a**(r/2)) % N
print(f'x = {x}')
if ((x+1) % N) != 0:
print(math.gcd((int(x)+1), N), math.gcd(int(x), N))
else:
print("x +1 is 0 (mod N)")
else:
print(f'r = {r} is odd')
x = 4.0
5 1
import mathN = 11*7
a = 18
math.gcd(a, N)
1
import matplotlib.pyplot as plotterz = list(range(N))
y = [a**z0 % N for z0 in z]
plotter.plot(z,y)
plotter.xlabel('z')
plotter.ylabel(f'{a}^z (mod {N})')
plotter.show()
r = z[y[1:].index(1)+1]
print(f'r = {r}')
r = 30
if r %2 == 0:
x = (a**(r/2)) % N
print(f'x = {x}')
if ((x+1) % N) != 0:
print(math.gcd((int(x)+1), N), math.gcd(int(x), N))
else:
print("x +1 is 0 (mod N)")
else:
print(f'r = {r} is odd')
x = 43.0
11 1

Part 2

import numpy as np
pi = np.pi
for y in range(15):
coeff = np.exp(-1j*3*pi/8 * y) + \
np.exp(-1j*7*pi/8 * y) + \
np.exp(-1j*11*pi/8 * y) + \
np.exp(-1j*15*pi/8 * y)
if abs(coeff) < 1e-10: coeff = 0
print(y, coeff)
0 (4+0j)
1 0
2 0
3 0
4 (-5.757077917265737e-15+4j)
5 0
6 0
7 0
8 (-4-1.1514155834531474e-14j)
9 0
10 0
11 0
12 (2.2600304269997962e-14-4j)
13 0

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store