project 2
project 2
# Compute entropy
entropy = -np.sum(np.abs(frqi_state) ** 2 * np.log2(np.abs(frqi_state) ** 2␣
,→+ 1e-10))
# Example usage
state_size = 2 ** 8 # Adjust the size based on your actual FRQI state size
frqi_state = generate_random_frqi_state(state_size)
# Compute statistics
mean_value, std_dev, entropy = compute_frqi_statistics(frqi_state)
# Example usage
state_size = 2 ** 8 # Adjust the size based on your actual FRQI state size
frqi_state = generate_random_frqi_state(state_size)
1
plt.figure(figsize=(12, 6))
plt.tight_layout()
plt.show()
plt.figure(figsize=(8, 5))
plt.bar(labels, values, color=['orange', 'purple', 'red'])
plt.title('Statistics of FRQI State')
plt.ylabel('Value')
plt.show()
2
[ ]:
3
[1]: import numpy as np
# Key points
preparation_complexity = "polynomial"
qic_algorithm = "color-integrated controlled rotations"
processing_operators = np.array(["colors", "positions", "colors and positions"])
experiment_results = np.array(["storage and retrieval", "QIC compression", "line␣
,→detection"])
# Key points
preparation_complexity = "polynomial"
qic_algorithm = "color-integrated controlled rotations"
processing_operators = np.array(["colors", "positions", "colors and positions"])
experiment_results = np.array(["storage and retrieval", "QIC compression", "line␣
,→detection"])
1
# Extracting relevant information for plotting
labels = summary_array[:, 0]
values = summary_array[:, 1]
[ ]:
2
[1]: import numpy as np
[[ 5.00000000e-01 0.00000000e+00]
[ 5.00000000e-01 0.00000000e+00]]
[[ 4.32978028e-17 0.00000000e+00]
[ 7.07106781e-01 0.00000000e+00]]
[[-5.00000000e-01 -0.00000000e+00]
[ 5.00000000e-01 0.00000000e+00]]]
def frqi_state(theta):
"""
Creates the FRQI state of a 2x2 image.
Args:
theta: A list of 4 angles, one for each pixel of the image.
Returns:
The FRQI state of the image as a numpy array.
"""
n = 2 # Number of qubits per pixel
m = 2**n # Number of basis states per pixel
1
binary_string = np.binary_repr(i, m).zfill(m)
for j in range(m):
basis_states[i, i] += (-1)**int(binary_string[j]) * 2**-(j + 1)
return frqi_state
# Example usage
theta = [np.pi/4, np.pi/3, np.pi/2, np.pi/6]
frqi_state = frqi_state(theta)
print(frqi_state)
2
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j]
[0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j]
[0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j]
[0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j]
[0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j]
[0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j]
[0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j]
[0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j]
[0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
3
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j]
[0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j]
[0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j]
[0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j
0.00000000e+00+0.j]]
4
print("\nImaginary part:")
print(frqi_state.imag)
Real part:
[[0.70710678 0.70710678 0.70710678 0.70710678]
[0.8660254 0.8660254 0.8660254 0.8660254 ]
[0.5 0.5 0.5 0.5 ]
[0.80901699 0.80901699 0.80901699 0.80901699]]
Imaginary part:
[[0.70710678 0.70710678 0.70710678 0.70710678]
[0.5 0.5 0.5 0.5 ]
[0.8660254 0.8660254 0.8660254 0.8660254 ]
[0.58778525 0.58778525 0.58778525 0.58778525]]
[ ]:
5
[ ]: # Name: circuit.py
# Author: Isaac Cilia Attard
# Date: 04/10/2022
# Description: Implements the QFT circuit as detailed in the README.
"""NumPy packages"""
import numpy as np
from numpy import pi
"""Qiskit package"""
from qiskit import QuantumCircuit
[ ]: # Name: encoder.py
# Author: Isaac Cilia Attard
# Date: 07/10/2022
# Description: Encodes classical bits onto a quantum circuit.
"""NumPy packages"""
import numpy as np
"""OpenCV package"""
import cv2
1
"""IBM Qiskit package"""
from qiskit import QuantumCircuit
"""QFT circuit generator"""
from circuit import qft
quantum_circuit.x(n)
elif bit == 0:
pass
n += 1 # Continues to encode the next qubit
return quantum_circuit # Returns the finalised quantum circuit
[ ]: # Name: main.py
# Author: Isaac Cilia Attard
# Date: 08/10/2022
# Description: Offers an image to the QFT circuit and displays the results.
"""Qiskit packages"""
from qiskit import Aer
from qiskit.visualization import plot_bloch_multivector
"""Matplotlib package"""
import matplotlib.pyplot as plt
"""Circuit and encoder packages"""
from circuit import qft
from encoder import basis_encode, image_to_binary
2
statevector = simulator.run(qc_init).result().get_statevector()
plot_bloch_multivector(statevector)
3
[ ]: from qiskit import IBMQ, QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute, QuantumRegister
from qiskit.qasm import pi
from qiskit.tools.visualization import plot_histogram, circuit_drawer
from qiskit import execute, Aer, BasicAer
import numpy as np
import random
import keras
from keras.models import Sequential
from keras.layers import Dense, Activation
from keras.datasets import mnist
import matplotlib.pyplot as plt
from sklearn.metrics import mean_squared_error, mean_absolute_error,␣
,→mutual_info_score, r2_score
1
circ.cx(c2, t)
circ.tdg(t)
circ.cx(c1, t)
circ.t(t)
circ.cx(c2, t)
circ.tdg(t)
circ.h(t)
circ.t(t)
circ.cx(c0, t)
circ.tdg(t)
circ.h(t)
2
circ.cx(c2,t)
circ.rz(-angle/4,t)
circ.h(t)
circ.t(t)
circ.cx(c0,t)
circ.tdg(t)
circ.h(t)
def mary_8(circ, angle, t, c0, c1, c2, c3, c4, c5, c6):
circ.h(t)
circ.t(t)
rccx(circ, t, c0, c1)
circ.tdg(t)
circ.h(t)
rccx(circ, t, c2, c3)
circ.rz(angle/4,t)
rcccx(circ, t, c4, c5, c6)
circ.rz(-angle/4,t)
rccx(circ, t, c2, c3)
circ.rz(angle/4,t)
rcccx(circ, t, c4, c5, c6)
circ.rz(-angle/4,t)
circ.h(t)
circ.t(t)
rccx(circ, t, c0, c1)
circ.tdg(t)
circ.h(t)
print(bin)
clist = []
for i in bin:
clist.append(int(i))
for i in range(len(clist)):
if clist[i] == 0:
circ.x(controls[-i-1])
3
circ.x(controls[3])
margolus(circ, controls[3], controls[4], controls[5])
circ.x(controls[4])
circ.x(controls[5])
circ.x(controls[5])
circ.x(controls[4])
margolus(circ, controls[3], controls[4], controls[5])
circ.x(controls[3])
circ.x(controls[2])
margolus(circ, controls[1], controls[2], controls[3])
circ.x(controls[1])
circ.x(controls[0])
margolus(circ, anc, controls[0], controls[1])
for i in range(len(clist)):
if clist[i] == 0:
circ.x(controls[-i-1])
clist = []
for i in bin:
clist.append(int(i))
# print("angle", angle)
# print("clist - bin",clist)
for i in range(len(clist)):
if clist[i] == 0:
circ.x(controls[-i-1])
4
# circuit_drawer(circ,output='mpl', filename='my_circuit_rccx.png')
circ.x(controls[4])
circ.x(controls[5])
rccx(circ, controls[4], controls[6], controls[7])
rccx(circ, controls[5], controls[8], controls[9])
for i in range(len(clist)):
if clist[i] == 0:
circ.x(controls[-i-1])
# for i in range(len(clist)):
# circ.x(controls[i])
def image_normalization(image):
image = resizeimage.resize_cover(image, [32, 32])
w, h = 32, 32
image = np.array([[image.getpixel((x,y))[0] for x in range(w)] for y in␣
,→range(h)])
return generated_image
if __name__ == '__main__':
# (x_train, y_train), (x_test, y_test) = mnist.load_data()
# img_num = 1
5
# #plt.savefig('mnistimg'+str(img_num)+'.png')
# plt.show()
backends = Aer.backends()
#print("Aer backends:",backends)
qubit = 12
qc = QuantumCircuit(qubit,qubit)
# qc.x(range(2,qubit))
qc.measure(range(qubit),range(qubit))
backend_sim = Aer.get_backend('qasm_simulator')
#print(qc.depth())
numOfShots = 1000000
result = execute(qc, backend_sim, shots=numOfShots).result()
#circuit_drawer(qc).show()
#plot_histogram(result.get_counts(qc))
print(result.get_counts(qc))
# generated image
genimg = np.array([])
#### decode
6
for i in range(len(x_train)):
try:
genimg = np.append(genimg,[np.sqrt(result.
,→get_counts(qc)[format(i, '010b')+'01']/numOfShots)])
except KeyError:
genimg = np.append(genimg,[0.0])
# inverse nomalization
genimg *= 32.0 * 255.0
x_train = np.sin(x_train)
x_train *= 255.0
# convert type
genimg = genimg.astype('int')
for i in circuit.qubits:
circuit.x(i)
qubits = circuit.qubits
ancilla = qubits[0]
circuit.h(ancilla)
quantum_adder(circuit, -1)
7
circuit.h(ancilla)
circuit.x(ancilla)
# circuit.measure(ancilla, clbit)
# backend = Aer.get_backend('qasm_simulator')
# job_sim = execute(circuit, backend)
# sim_result = job_sim.result()
# print(sim_result.get_counts(circuit))
[ ]: import utils
from qiskit import IBMQ, QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute, QuantumRegister
from qiskit.qasm import pi
from qiskit.tools.visualization import plot_histogram, circuit_drawer
from qiskit.visualization import plot_state_city, plot_bloch_multivector
from qiskit.visualization import plot_state_paulivec, plot_state_hinton
from qiskit.visualization import plot_state_qsphere
from qiskit.visualization import plot_histogram, plot_gate_map,␣
,→plot_circuit_layout
IBMQ.load_account()
provider = IBMQ.get_provider( group='open', project='main')
#target image
image=utils.get_Cat_image()
8
#normalized image
normalized_image=utils.image_normalization(image,32,True)
#get target image pixel values for comparison with output image
img_arr=utils.get_image_pixel_value(image,32)
# create circuit
qc = QuantumCircuit(anc, img, anc2, c)
#Edge Detection
# qed.quantum_edge_detection()
qc.measure(img, c[1:12])
print(qc.depth())
numOfShots = 1000000
# backend = provider.get_backend('ibmq_16_melbourne')
# noise_model = NoiseModel.from_backend(backend)
# # Get coupling map from backend
# coupling_map = backend.configuration().coupling_map
# # Get basis gates from noise model
# basis_gates = noise_model.basis_gates
9
# result = execute(qc, Aer.get_backend('qasm_simulator'),␣
,→shots=numOfShots,coupling_map=coupling_map,
# basis_gates=basis_gates,
# noise_model=noise_model).result()
genimg = np.array([])
#### decode
for i in range(len(normalized_image)):
try:
genimg = np.append(genimg,[np.sqrt(result.
,→get_counts(qc)[format(i, '010b')+'10']/numOfShots)])
except KeyError:
genimg = np.append(genimg,[0.0])
# inverse nomalization
genimg *= size * 255.0
# genimg = np.sin(genimg)
same,notSame= utils.get_count_of_pixel(img_arr,genimg)
print(same,notSame)
percentage= (same/1024)*100
print ("Total image recovered "+ str(percentage))
# convert type
genimg = genimg.astype('int')
genimg = genimg.reshape((size,size))
plt.imshow(genimg, cmap='gray', vmin=0, vmax=255)
plt.savefig('Result'+'.png')
plt.show()
import utils
from qiskit import IBMQ, QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute, QuantumRegister
from qiskit.qasm import pi
from qiskit.tools.visualization import plot_histogram, circuit_drawer
10
from qiskit.visualization import plot_state_city, plot_bloch_multivector
from qiskit.visualization import plot_state_paulivec, plot_state_hinton
from qiskit.visualization import plot_state_qsphere
from qiskit.visualization import plot_histogram, plot_gate_map,␣
,→plot_circuit_layout
IBMQ.load_account()
provider = IBMQ.get_provider( group='open', project='main')
#target image
images=utils.get_Cat_320_image()
for k in range(10):
for j in range(10):
normalized_image=utils.
,→large_image_normalization(images,32+(32*k),32+(32*j))
genimg= np.array([])
anc = QuantumRegister(1, "anc")
img = QuantumRegister(11, "img")
anc2 = QuantumRegister(1, "anc2")
c = ClassicalRegister(12)
qc = QuantumCircuit(anc, img, anc2, c)
11
for i in range(len(normalized_image)):
if normalized_image[i] != 0:
frqi.c10mary(qc, 2 * normalized_image[i], format(i,␣
,→'010b'), img[0], anc2[0], [img[j] for j in range(1,len(img))])
qc.measure(img, c[1:12])
print(qc.depth())
numOfShots = 1000000
result = execute(qc, Aer.get_backend('qasm_simulator'),␣
,→shots=numOfShots).result()
for i in range(len(normalized_image)):
try:
genimg = np.append(genimg,[np.sqrt(result.
,→get_counts(qc)[format(i, '010b')+'10']/numOfShots)])
except KeyError:
genimg = np.append(genimg,[0.0])
new_im.paste(im,(32*k,32*j))
new_im.show()
new_im.save('Result_320.png')
[ ]: import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from resizeimage import resizeimage
from PIL import Image, ImageOps
def get_MNIST_data():
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
return x_train
def get_Cat_320_image():
return Image.open("cat_320.png").convert('LA')
def get_Cat_image():
return Image.open("cat.png").convert('LA')
def large_image_normalization(images,w,h):
image=np.array([])
for y in range(h-32,h):
12
for x in range(w-32,w):
image=np.append(image,images.getpixel((x,y))[0])
genimg = image.reshape((32,32))
image = image.flatten()
# change type
image = image.astype('float64')
# Normalization(0~pi/2)
image /= 255.0
generated_image=image
# generated_image = np.arcsin(image)
print(generated_image)
image=images
return generated_image
def image_normalization(image,size,show):
image = resizeimage.resize_cover(image, [size, size])
w, h = size, size
image = np.array([[image.getpixel((x,y))[0] for x in range(w)] for y in␣
,→range(h)])
image = image.flatten()
image = image.astype('float64')
image /= 255.0
generated_image = np.arcsin(image)
# print(generated_image)
return generated_image
def generate_image(size):
w, h = size, size
data = np.zeros((h, w, 3), dtype=np.uint8)
w_bound=int(w/2)
h_bound=int(h/2)
data[0:w_bound, 0:h_bound] = [255, 0, 0] # red patch in upper left
data[0:w_bound, h_bound+1:h] = [0, 255, 0] # red patch in upper left
data[w_bound+1:w, 0:h_bound] = [0, 0, 255] # red patch in upper left
data[w_bound+1:w, h_bound+1:h] = [128, 128, 128] # red patch in upper left
13
return imgq.convert('LA')
def get_image_pixel_value(image,size):
img_arr= np.array([[image.getpixel((x,y))[0] for x in range(size)] for y in␣
,→range(size)])
img_arr = img_arr.flatten()
return img_arr
def get_count_of_pixel(arr1,arr2):
same=0
notsame=0
for i in range(len(arr1)):
if arr1[i]==arr2[i]:
same+=1
else:
notsame+=1
return (same,notsame)
14
One of the most interesting area where Quantum science and technology is
being utilized is Quantum Image Processing. With a multitude of advances in
technology, image processing has become an extensively researched upon area of
technology. It is being employed in various different disciplines and areas of
research. Facial recognition, automated vehicles, image Photoshop and numerous
other techniques use image processing as their basis. Utilizing Quantum
technology in image processing is what Quantum image processing is all about. As
is evident until now, quantum image processing will be a lot more efficient in terms
of speed and time than its classical counterpart. It will also prove to be extremely
useful for simple day to day applications like simple face recognition on a mobile
phone or criminal detection at a police station, but all of this might be possible in a
fraction of time and with much less error than is now using classical techniques.
Image compression, edge detection, image storage, image retrieval, binary image
line detection are just some of the tasks achievable by quantum image processing
[1, 4].
In order to carry out Quantum Image Processing, the image must first be
transformed into its quantum counterpart known as the quantum image. This state
can be achieved by a number of different processes like FRQI (Flexible
Representation of Quantum Image), NEQR (Novel Enhanced Quantum
Representation), QBIP (Quantum Boolean Image Processing) and a variety of
others [6]. Here we discusses the FRQI technique in detail. The FRQI state
represents the classical images, after a transformation, as quantum images on a
quantum computer in a normalized state. This state carries the information about
the colours in an image and their respective positions. It is quite an efficient
method for the preparation of an image on which various different quantum image
processing algorithms can be applied to achieve desired results. Not only does
FRQI provide a representation to images but can also prove to be extremely useful
for the exploration of other tasks performed by the quantum computers regarding
image processing [1, 2]. Preparing this state requires a polynomial number of
simple operations and gates [2, 4]. We work with a 2x2 image i.e. 4 pixels image,
where the color and its position is encoded in the FRQI state as shown below,
, (1)
. (2)
Mathematical Formulations
The FRQI state contains coded information in the form of colour and its related
pixel position as shown below. FRQI state is prepared through a unitary
transformation which has two steps. First applying the hadamard transform H =
I⊗H⊗2, where I is the 2D identity matrix and H is the hadamard gate, on |0⟩⊗3,
producing the state |H⟩,
. (3)
State |0⟩ is initialised on all three qubits and hadamard gate is applied on the first
two, creating superposition. The third qubit is our ancillary qubit. In the second
step, controlled rotations are applied on the |H⟩ state as defined by,
. (4)
where
. (5)
Equation ’(1)’ is our state obtained after applying the hadamard transform. Now,
the controlled rotation operators are applied in succession as follows.
(6)
!
!
In above equation, the second term vanishes and are just numeric
representation of two qubit states in Zeeman basis,
1. |0⟩ = |00⟩
2. |1⟩ = |01⟩
3. |2⟩ = |10⟩
4. |3⟩ = |11⟩.
qr =qk.QuantumRegister(3)
cr = qk.ClassicalRegister(3)
qc= qk.QuantumCircuit(qr,cr)
qc.h(qr[0])
qc.h(qr[1])
#pi/4=0.7853
qc.cu3(0.7853,0,0,qr[0],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(-0.7853,0,0,qr[1],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(0.7853,0,0,qr[0],qr[2])
#pi/12=0.2617
qc.x(qr[1])
qc.cu3(0.2617,0,0,qr[0],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(-0.2617,0,0,qr[1],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(0.2617,0,0,qr[0],qr[2])
#pi/6=0.5234
1
qc.x(qr[0])
qc.x(qr[1])
qc.cu3(0.5234,0,0,qr[0],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(-0.5234,0,0,qr[1],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(0.5234,0,0,qr[0],qr[2])
#pi/16=0.1963
qc.x(qr[1])
qc.cu3(0.1963,0,0,qr[0],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(-0.1963,0,0,qr[1],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(0.1963,0,0,qr[0],qr[2])
qc.barrier(qr)
qc.measure(qr,cr)
# In[41]:
2
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(qc, backend_sim)
result_sim = job_sim.result()
# In[42]:
counts = result_sim.get_counts(qc)
print(counts)
"""
img = Image.new('RGB', (60, 30), color = 'red')
img.save('pil_red.png')
"""
# Create a NumPy array, which has four elements. The top-left should be pure␣
,→red, the top-right should be pure blue, the bottom-left should be pure green,␣
def double_size(im):
rows = len(im)
cols = len(im[0])
half_r = rows/2
half_c = cols/2
r = im[0]
first = r[0]
second = r[int(cols/2)]
for i in range(rows):
for j in range(cols):
for k in range(3):
new_im[i][j][k] = first[k]
for j in range(cols, cols * 2):
for k in range(3):
new_im[i][j][k] = second[k]
r = im[int(rows/2)]
first = r[0]
second = r[int(cols/2)]
3
for i in range(rows, rows * 2):
for j in range(cols):
for k in range(3):
new_im[i][j][k] = first[k]
for j in range(cols, cols * 2):
for k in range(3):
new_im[i][j][k] = second[k]
return new_im
def make_image(pixels):
def get_smallest():
pixels = np.array([[[255, 0, 0], [0, 255, 0]], [[0, 0, 255], [255, 255,␣
0]]])
,→
return pixels
"""
pixels = np.array([[[255, 0, 0], [255, 0, 0], [255, 0, 0], [255, 0, 0], [0, 255,␣
,→0], [0, 255, 0], [0, 255, 0], [0, 255, 0]],
[[255, 0, 0], [255, 0, 0], [255, 0, 0], [255, 0, 0], [0, 255, 0], [0,␣
,→255, 0], [0, 255, 0], [0, 255, 0]],
[[255, 0, 0], [255, 0, 0], [255, 0, 0], [255, 0, 0], [0, 255, 0], [0,␣
,→255, 0], [0, 255, 0], [0, 255, 0]],
[[255, 0, 0], [255, 0, 0], [255, 0, 0], [255, 0, 0], [0, 255, 0], [0,␣
,→255, 0], [0, 255, 0], [0, 255, 0]],
[[0, 0, 255], [0, 0, 255], [0, 0, 255], [0, 0, 255], [255, 255, 0],␣
,→[255, 255, 0], [255, 255, 0], [255, 255, 0]],
[[0, 0, 255], [0, 0, 255], [0, 0, 255], [0, 0, 255], [255, 255, 0],␣
,→[255, 255, 0], [255, 255, 0], [255, 255, 0]],
[[0, 0, 255], [0, 0, 255], [0, 0, 255], [0, 0, 255], [255, 255, 0],␣
,→[255, 255, 0], [255, 255, 0], [255, 255, 0]],
[[0, 0, 255], [0, 0, 255], [0, 0, 255], [0, 0, 255], [255, 255, 0],␣
,→[255, 255, 0], [255, 255, 0], [255, 255, 0]]])
"""
"""
4
def rgb_to_theta(rgb):
r, g, b = rgb
theta = (pi/2) * ((r/2) + (g/4) + (b/8))
#print("Theta is ", theta)
return theta
def theta_to_rgb(theta):
r = floor(theta/(pi/4))
g = floor(theta/(pi/8))
b = floor(theta/(pi/16))
print("rgb = ", [r, g, b])
def test_it():
list = []
for i in range(2):
for j in range(2):
for k in range(2):
list.append([i, j, k])
i = 0
for elem in list:
print("i ============== ", i)
i += 1
print(elem)
theta = rgb_to_theta(elem)
theta_to_rgb(theta)
"""
def rgb_to_theta(rgb):
r, g, b = rgb
theta = (pi/2) * ((r/256) + (g/(256**2)) + (b/256**3))
print("Theta is ", theta)
return theta
def theta_to_rgb(theta):
r = floor(theta/((pi/2) * (1/256)))
5
theta = theta - r*((pi/2) * (1/256))
print("After R, theta is ", theta)
g = floor(theta/((pi/2) * (1/256**2)))
theta = theta - g*((pi/2) * (1/256**2))
print("After G, theta is ", theta)
b = floor(theta/((pi/2) * (1/256**3)))
def test_it():
list = []
for i in range(5):
for j in range(5):
for k in range(5):
list.append([i, j, k])
i = 0
for elem in list:
print("i ============== ", i)
i += 1
print(elem)
theta = rgb_to_theta(elem)
theta_to_rgb(theta)
=========================================
# coding: utf-8
# In[40]:
import qiskit as qk
from qiskit import Aer,execute
from math import pi
#pi = 3.14159
def run():
qr =qk.QuantumRegister(3)
cr = qk.ClassicalRegister(3)
qc= qk.QuantumCircuit(qr,cr)
6
# Circuit for I(theta) starts here
#qc.x(qr[0])
#qc.x(qr[1])
###
qc.barrier(qr)
qc.measure(qr,cr)
# In[41]:
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(qc, backend_sim, shots=10000)
result_sim = job_sim.result()
# In[42]:
counts = result_sim.get_counts(qc)
print(counts)
###
"""
#pi/12=0.2617
qc.x(qr[1])
qc.cu3(angles[1],0,0,qr[0],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(-angles[1],0,0,qr[1],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(angles[1],0,0,qr[0],qr[2])
#pi/6=0.5234
qc.x(qr[0])
qc.x(qr[1])
qc.cu3(angles[2],0,0,qr[0],qr[2])
qc.cx(qr[0],qr[1])
7
qc.cu3(-angles[2],0,0,qr[1],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(angles[2],0,0,qr[0],qr[2])
#pi/16=0.1963
qc.x(qr[1])
qc.cu3(angles[3],0,0,qr[0],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(-angles[3],0,0,qr[1],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(angles[3],0,0,qr[0],qr[2])
qc.barrier(qr)
qc.measure(qr,cr)
# In[41]:
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(qc, backend_sim, shots=10000)
result_sim = job_sim.result()
# In[42]:
counts = result_sim.get_counts(qc)
print(counts)
"""
======================
def probs(results):
angles = []
if ("000" in results):
prob = results["000"]/num_shots
# to get the angle back cos^-1(sqrt(probability))
angles.append(acos(sqrt(4 *prob)))
else:
angles.append(pi/2)
if ("001" in results):
probs.append(results["001"]/num_shots)
else:
probs.append(0.)
if ("010" in results):
probs.append(results["010"]/num_shots)
else:
8
probs.append(0.)
if ("011" in results):
probs.append(results["011"]/num_shots)
else:
probs.append(0.)
print(probs)
========
if ("000" in results):
prob = results["000"]/num_shots
# to get the angle back cos^-1(sqrt(4 * probability))
angles.append(acos(sqrt(4 *prob)))
else:
angles.append(pi/2)
r, g, b = rgb
# storing the angle in degrees instead of radians
theta = (90) * ((r/256) + (g/(256**2)) + (b/256**3))
return theta
theta *= 256
b = floor(theta/(90/256))
9
return [r,g,b]
"""
pixels = np.array([[[255, 0, 0], [255, 0, 0], [255, 0, 0], [255, 0, 0], [0, 255,␣
,→0], [0, 255, 0], [0, 255, 0], [0, 255, 0]],
[[255, 0, 0], [255, 0, 0], [255, 0, 0], [255, 0, 0], [0, 255, 0], [0,␣
,→255, 0], [0, 255, 0], [0, 255, 0]],
[[255, 0, 0], [255, 0, 0], [255, 0, 0], [255, 0, 0], [0, 255, 0], [0,␣
,→255, 0], [0, 255, 0], [0, 255, 0]],
[[255, 0, 0], [255, 0, 0], [255, 0, 0], [255, 0, 0], [0, 255, 0], [0,␣
,→255, 0], [0, 255, 0], [0, 255, 0]],
[[0, 0, 255], [0, 0, 255], [0, 0, 255], [0, 0, 255], [255, 255, 0],␣
,→[255, 255, 0], [255, 255, 0], [255, 255, 0]],
[[0, 0, 255], [0, 0, 255], [0, 0, 255], [0, 0, 255], [255, 255, 0],␣
,→[255, 255, 0], [255, 255, 0], [255, 255, 0]],
[[0, 0, 255], [0, 0, 255], [0, 0, 255], [0, 0, 255], [255, 255, 0],␣
,→[255, 255, 0], [255, 255, 0], [255, 255, 0]],
[[0, 0, 255], [0, 0, 255], [0, 0, 255], [0, 0, 255], [255, 255, 0],␣
,→[255, 255, 0], [255, 255, 0], [255, 255, 0]]])
"""
"""
# I can put this into a for loop if I need to.
# probs for 1st pixel
if ("000" in results):
prob["000"] = results["000"]/num_shots
else:
prob["000"] = 0.
if ("100" in results):
prob["100"] = results["100"]/num_shots
else:
prob["100"] = 0.
if ("101" in results):
prob["101"] = results["101"]/num_shots
else:
prob["101"] = 0.
10
if ("010" in results):
prob["010"] = results["010"]/num_shots
else:
prob["010"] = 0.
if ("110" in results):
prob["110"] = results["110"]/num_shots
else:
prob["110"] = 0.
if ("111" in results):
prob["111"] = results["111"]/num_shots
else:
prob["111"] = 0.
angles = []
# now need to recover the angles
zero_prob = prob["000"]/(prob["000"] + prob["100"])
angles.append(acos(sqrt(zero_prob)))
===========================
qc.cu3(angles[0],0,0,qr[6],qr[7])
11
qc.ccx(qr[0], qr[1], qr[4])
===========================
pixels = np.array([[[250, 5, 5], [5, 250, 5], [5, 5, 250], [250, 250, 5]],
[[250, 5, 250], [5, 250, 250], [100, 50, 5], [5, 100, 50]],
[[100, 100, 100], [100, 150, 200], [200, 100, 150], [150, 200,␣
,→150]],
[[75, 180, 105], [180, 105, 75], [105, 180, 75], [128, 128,␣
,→128]]])
===========================
def get_xs():
chars = ["0","1"]
vals = []
for i in chars:
for j in chars:
for k in chars:
for l in chars:
vals.append(i + j + k + l)
total = []
for i in range(16):
x_vals = []
word = vals[i]
for j in range(4):
if(word[j] == '0'):
x_vals.append('x')
else:
x_vals.append('_')
total.append(x_vals)
for k in range(16):
for q in range(4):
if (x_vals[q] == 'x'):
if (vals[k][q] == '0'):
new_val = []
for r in range(4):
if (r != q):
new_val.
,→append(vals[k][r])
else:
12
new_val.
append('1')
,→
vals[k] = new_val
else:
new_val = []
for r in range(4):
if (r != q):
new_val.
append(vals[k][r])
,→
else:
new_val.
append('0')
,→
vals[k] = new_val
print(total)
[ ]: # coding: utf-8
# In[40]:
import qiskit as qk
from qiskit import Aer,execute
from math import pi, sqrt, acos
from image_testing import r_num, g_num, b_num
num_shots = 100000
def probs(results):
prob = {}
angles = []
for c in chars:
for d in chars:
zero = "0" + c + d
one = "1" + c + d
13
zero_prob = prob[zero]/(prob[zero] + prob[one])
angles.append(acos(sqrt(zero_prob)))
return angles
def probs4(results):
prob = {}
else:
prob[state] = 0.
angles = []
for c in chars:
for d in chars:
for e in chars:
for f in chars:
zero = "0000" + c + d + e + f
one = "1000" + c + d + e + f
zero_prob = prob[zero]/(prob[zero] +␣
,→prob[one])
angles.append(acos(sqrt(zero_prob)))
return angles
def run(angles):
qr =qk.QuantumRegister(3)
cr = qk.ClassicalRegister(3)
qc= qk.QuantumCircuit(qr,cr)
14
qc.x(qr[0])
qc.x(qr[1])
#pi/4=0.7853
qc.cu3(angles[0],0,0,qr[0],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(-angles[0],0,0,qr[1],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(angles[0],0,0,qr[1],qr[2])
#pi/12=0.2617
qc.x(qr[0])
qc.cu3(angles[1],0,0,qr[0],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(-angles[1],0,0,qr[1],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(angles[1],0,0,qr[1],qr[2])
#pi/6=0.5234
qc.x(qr[0])
qc.x(qr[1])
qc.cu3(angles[2],0,0,qr[0],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(-angles[2],0,0,qr[1],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(angles[2],0,0,qr[1],qr[2])
#pi/16=0.1963
qc.x(qr[0])
qc.cu3(angles[3],0,0,qr[0],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(-angles[3],0,0,qr[1],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(angles[3],0,0,qr[1],qr[2])
qc.barrier(qr)
qc.measure(qr,cr)
# In[41]:
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(qc, backend_sim, shots=num_shots)
result_sim = job_sim.result()
# In[42]:
15
counts = result_sim.get_counts(qc)
new_angles = probs(counts)
return new_angles
def run_4(angles):
# can just pass in the same angles as I did for 2x2. No need to double␣
them.
,→
for i in range(len(angles)):
angles[i] = 2 * angles[i]
qc= qk.QuantumCircuit(qr,cr)
for i in range(16):
qc.x(qr[0])
if (i % 4 == 2):
qc.x(qr[1])
if (i == 0 or i == 8):
qc.x(qr[1])
qc.x(qr[2])
qc.x(qr[3])
if (i == 4 or i == 12):
qc.x(qr[1])
qc.x(qr[2])
16
qc.cu3(angles[i],0,0,qr[6],qr[7])
"""
################
# pixel shifting
#C3not
qc.ccx(qr[0], qr[1], qr[4])
qc.ccx(qr[2], qr[4], qr[5])
qc.cx(qr[5], qr[3])
#C2not
qc.ccx(qr[0], qr[1], qr[2])
#CNOT
qc.cx(qr[0], qr[1])
#NOT
qc.x(qr[0])
################
"""
qc.barrier(qr)
qc.measure(qr,cr)
# In[41]:
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(qc, backend_sim, shots=num_shots)
result_sim = job_sim.result()
# In[42]:
counts = result_sim.get_counts(qc)
#print(counts)
new_angles = probs4(counts)
return new_angles
17
"""
def test():
for i in range(16):
angles = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
angles[i] = pi/2
run_4(angles)
#print("==============\n", i, "\n==============")
break
"""
def get_xs():
chars = ["0","1"]
vals = []
for i in chars:
for j in chars:
for k in chars:
for l in chars:
for m in chars:
for n in chars:
vals.append(i + j + k +␣
,→l + m + n)
total = []
for i in range(64):
x_vals = []
word = vals[i]
for j in range(6):
if(word[j] == '0'):
x_vals.append('x')
else:
x_vals.append('_')
total.append(x_vals)
for k in range(64):
for q in range(6):
18
if (x_vals[q] == 'x'):
if (vals[k][q] == '0'):
new_val = []
for r in range(6):
if (r != q):
new_val.
append(vals[k][r])
,→
else:
new_val.
append('1')
,→
vals[k] = new_val
else:
new_val = []
for r in range(6):
if (r != q):
new_val.
append(vals[k][r])
,→
else:
new_val.
append('0')
,→
vals[k] = new_val
print(total)
[ ]: # coding: utf-8
# In[40]:
import qiskit as qk
from qiskit import Aer,execute
pi = 3.14
def run():
qr =qk.QuantumRegister(3)
cr = qk.ClassicalRegister(3)
qc= qk.QuantumCircuit(qr,cr)
qc.h(qr[0])
qc.h(qr[1])
19
# Circuit for I(theta) starts here
qc.x(qr[0])
qc.x(qr[1])
qc.cx(qr[0],qr[1])
qc.cu3(-angles[0],0,0,qr[1],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(angles[0],0,0,qr[0],qr[2])
#pi/12=0.2617
qc.x(qr[1])
qc.cu3(angles[1],0,0,qr[0],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(-angles[1],0,0,qr[1],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(angles[1],0,0,qr[0],qr[2])
#pi/6=0.5234
qc.x(qr[0])
qc.x(qr[1])
qc.cu3(angles[2],0,0,qr[0],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(-angles[2],0,0,qr[1],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(angles[2],0,0,qr[0],qr[2])
#pi/16=0.1963
qc.x(qr[1])
qc.cu3(angles[3],0,0,qr[0],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(-angles[3],0,0,qr[1],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(angles[3],0,0,qr[0],qr[2])
20
qc.barrier(qr)
qc.measure(qr,cr)
# In[41]:
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(qc, backend_sim)
result_sim = job_sim.result()
# In[42]:
counts = result_sim.get_counts(qc)
print(counts)
[ ]: # coding: utf-8
# In[40]:
import qiskit as qk
from qiskit import Aer,execute
from math import pi, sqrt, acos
from image_testing import r_num, g_num, b_num
num_shots = 100000000
def probs(results):
prob = {}
angles = []
for c in chars:
for d in chars:
zero = "0" + c + d
one = "1" + c + d
zero_prob = prob[zero]/(prob[zero] + prob[one])
angles.append(acos(sqrt(zero_prob)))
return angles
def probs4(results):
21
prob = {}
else:
prob[state] = 0.
angles = []
for c in chars:
for d in chars:
for e in chars:
for f in chars:
zero = "0000" + c + d + e + f
one = "1000" + c + d + e + f
zero_prob = prob[zero]/(prob[zero] +␣
,→prob[one])
angles.append(acos(sqrt(zero_prob)))
return angles
def run(angles):
qr =qk.QuantumRegister(3)
cr = qk.ClassicalRegister(3)
qc= qk.QuantumCircuit(qr,cr)
# angles to rotate by
red = (pi/2) * (1/r_num)
green = (pi/2) * (1/g_num)
blue = (pi/2) * (1/b_num)
# shift by
s = 8 * 2
22
# Circuit for I(theta) starts here
qc.x(qr[0])
qc.x(qr[1])
#pi/4=0.7853
qc.cu3(angles[0],0,0,qr[0],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(-angles[0],0,0,qr[1],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(angles[0],0,0,qr[1],qr[2])
#pi/12=0.2617
qc.x(qr[0])
qc.cu3(angles[1],0,0,qr[0],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(-angles[1],0,0,qr[1],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(angles[1],0,0,qr[1],qr[2])
#pi/6=0.5234
qc.x(qr[0])
qc.x(qr[1])
qc.cu3(angles[2],0,0,qr[0],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(-angles[2],0,0,qr[1],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(angles[2],0,0,qr[1],qr[2])
#pi/16=0.1963
qc.x(qr[0])
qc.cu3(angles[3],0,0,qr[0],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(-angles[3],0,0,qr[1],qr[2])
qc.cx(qr[0],qr[1])
qc.cu3(angles[3],0,0,qr[1],qr[2])
qc.u3(s * red,0,0,qr[2])
qc.barrier(qr)
qc.measure(qr,cr)
# In[41]:
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(qc, backend_sim, shots=num_shots)
23
result_sim = job_sim.result()
# In[42]:
counts = result_sim.get_counts(qc)
new_angles = probs(counts)
return new_angles
def run_4(angles):
# can just pass in the same angles as I did for 2x2. No need to double␣
them.
,→
for i in range(len(angles)):
angles[i] = 2 * angles[i]
qc= qk.QuantumCircuit(qr,cr)
for i in range(16):
qc.x(qr[0])
if (i % 4 == 2):
qc.x(qr[1])
if (i == 0 or i == 8):
qc.x(qr[1])
qc.x(qr[2])
qc.x(qr[3])
if (i == 4 or i == 12):
qc.x(qr[1])
qc.x(qr[2])
24
qc.ccx(qr[2], qr[4], qr[5])
qc.ccx(qr[3], qr[5], qr[6])
qc.cu3(angles[i],0,0,qr[6],qr[7])
"""
################
# pixel shifting
#C3not
qc.ccx(qr[0], qr[1], qr[4])
qc.ccx(qr[2], qr[4], qr[5])
qc.cx(qr[5], qr[3])
#C2not
qc.ccx(qr[0], qr[1], qr[2])
#CNOT
qc.cx(qr[0], qr[1])
#NOT
qc.x(qr[0])
################
"""
qc.barrier(qr)
qc.measure(qr,cr)
# In[41]:
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(qc, backend_sim, shots=num_shots)
result_sim = job_sim.result()
# In[42]:
counts = result_sim.get_counts(qc)
#print(counts)
25
new_angles = probs4(counts)
return new_angles
"""
def test():
for i in range(16):
angles = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
angles[i] = pi/2
run_4(angles)
#print("==============\n", i, "\n==============")
break
"""
def get_xs():
chars = ["0","1"]
vals = []
for i in chars:
for j in chars:
for k in chars:
for l in chars:
vals.append(i + j + k + l)
total = []
for i in range(16):
x_vals = []
word = vals[i]
for j in range(4):
if(word[j] == '0'):
x_vals.append('x')
else:
x_vals.append('_')
total.append(x_vals)
for k in range(16):
for q in range(4):
26
if (x_vals[q] == 'x'):
if (vals[k][q] == '0'):
new_val = []
for r in range(4):
if (r != q):
new_val.
append(vals[k][r])
,→
else:
new_val.
append('1')
,→
vals[k] = new_val
else:
new_val = []
for r in range(4):
if (r != q):
new_val.
append(vals[k][r])
,→
else:
new_val.
append('0')
,→
vals[k] = new_val
print(total)
r_num = 16
g_num = r_num ** 2
b_num = r_num ** 3
"""
img = Image.new('RGB', (60, 30), color = 'red')
img.save('pil_red.png')
"""
# Create a NumPy array, which has four elements. The top-left should be pure␣
,→red, the top-right should be pure blue, the bottom-left should be pure green,␣
def double_size(im):
rows = len(im)
27
cols = len(im[0])
#half_r = rows/2
#half_c = cols/2
r = im[0]
first = r[0]
second = r[int(cols/2)]
for i in range(rows):
for j in range(cols):
for k in range(3):
new_im[i][j][k] = first[k]
for j in range(cols, cols * 2):
for k in range(3):
new_im[i][j][k] = second[k]
r = im[int(rows/2)]
first = r[0]
second = r[int(cols/2)]
return new_im
"""
[[[250, 5, 5], [5, 250, 5], [250, 5, 5], [5, 250, 5]]
[[5, 5, 250], [250, 250, 5], [250, 5, 5], [5, 250, 5]]
[[250, 5, 5], [5, 250, 5], [250, 5, 5], [5, 250, 5]]
[[250, 5, 5], [5, 250, 5], [250, 5, 5], [5, 250, 5]]]
"""
def double_size4(im):
rows = len(im)
cols = len(im[0])
r = im[0]
first = r[0]
28
second = r[int(cols/4)]
third = r[int(cols/2)]
fourth = r[int(3 * cols/4)]
for i in range(int(rows/2)):
for j in range(int(cols/2)):
for k in range(3):
new_im[i][j][k] = first[k]
for j in range(int(cols/2), cols):
for k in range(3):
new_im[i][j][k] = second[k]
for j in range(cols, int(cols * (3/2))):
for k in range(3):
new_im[i][j][k] = third[k]
for j in range(int(cols * (3/2)), cols * 2):
for k in range(3):
new_im[i][j][k] = fourth[k]
r = im[int(rows/4)]
first = r[0]
second = r[int(cols/4)]
third = r[int(cols/2)]
fourth = r[int(3 * cols/4)]
r = im[int(rows/2)]
first = r[0]
second = r[int(cols/4)]
third = r[int(cols/2)]
fourth = r[int(3 * cols/4)]
29
for k in range(3):
new_im[i][j][k] = first[k]
for j in range(int(cols/2), cols):
for k in range(3):
new_im[i][j][k] = second[k]
for j in range(cols, int(cols * (3/2))):
for k in range(3):
new_im[i][j][k] = third[k]
for j in range(int(cols * (3/2)), cols * 2):
for k in range(3):
new_im[i][j][k] = fourth[k]
r = im[int(3 * rows/4)]
first = r[0]
second = r[int(cols/4)]
third = r[int(cols/2)]
fourth = r[int(3 * cols/4)]
return new_im
# given an rgb image as a regular python list, converts it into a numpy array␣
,→image
def make_image(rgbs):
rows = len(rgbs)
cols = len(rgbs[0])
30
new_im[i][j][k] = rgbs[i][j][k]
new_im = scale_up(new_im)
return new_im
def scale_up(image):
rows = len(image)
cols = len(image[0])
scale = 256/r_num
new_im = np.zeros(((rows, cols, 3)))
for i in range(rows):
for j in range(rows):
for k in range(3):
new_im[i][j][k] = image[i][j][k] * scale
return new_im
# since we're having to use a scaled down version (only 64 or 16 color values),␣
,→need to scale down image
def scale_down(image):
rows = len(image)
cols = len(image[0])
scale = 256/r_num
new_im = np.zeros(((rows, cols, 3)))
for i in range(rows):
for j in range(rows):
for k in range(3):
new_im[i][j][k] = floor(image[i][j][k] / scale)
return new_im
31
def get_image():
pixels = np.array([[[17, 17, 17], [240, 17, 17]], [[17, 240, 17], [17,␣
,→17, 240]]])
scaled = scale_down(pixels)
"""
# Windows looking symbol
pixels = np.array([[[250, 5, 5], [5, 250, 5]], [[5, 5, 250], [250, 250,␣
5]]])
,→
scaled = scale_down(pixels)
"""
return scaled
def get_image4():
pixels = np.array([[[239, 239, 239], [239, 239, 239], [239, 239, 239],␣
,→[239, 239, 239]],
[[239, 239, 239], [239, 239, 239], [239, 239, 239], [239, 239,␣
,→239]],
[[239, 239, 239], [239, 239, 239], [239, 239, 239], [239, 239,␣
,→239]],
[[239, 239, 239], [239, 239, 239], [239, 239, 239], [239, 239,␣
,→239]]])
"""
# 4test w16 and changed to less extreme vals
pixels = np.array([[[239, 16, 16], [239, 100, 100], [239, 175, 175],␣
,→[230, 230, 230]],
[[175, 16, 16], [16, 16, 100], [16, 16, 239], [175, 239, 175]],
[[100, 16, 16], [16, 16, 150], [16, 16, 200], [100, 239, 100]],
[[16, 16, 16], [16, 100, 16], [16, 175, 16], [16, 239, 16]]])
"""
"""
# 4test
pixels = np.array([[[250, 5, 5], [250, 100, 100], [250, 175, 175], [235,␣
,→235, 235]],
"""
pixels = np.array([[[250, 5, 5], [200, 5, 5], [150, 5, 5], [100, 5, 5]],
[[200, 5, 5], [5, 5, 100], [5, 5, 250], [150, 5, 5]],
32
[[150, 5, 5], [5, 5, 150], [5, 5, 200], [200, 5, 5]],
[[100, 5, 5], [150, 5, 5], [200, 5, 5], [250, 5, 5]]])
"""
scaled = scale_down(pixels)
return scaled
def rgb_to_theta(rgb):
r, g, b = rgb
theta = (pi/2) * ((r/r_num) + (g/g_num) + (b/b_num))
#print("Theta is ", theta)
return theta
def theta_to_rgb(theta):
r = floor(theta/(pi/(r_num * 2)))
theta = theta - r*(pi/(r_num * 2))
g = floor(theta/(pi/(g_num * 2)))
theta = theta - g*(pi/(g_num * 2))
b = floor(theta/(pi/(b_num * 2)))
return [r,g,b]
def test_it():
list = []
for i in range(2):
for j in range(2):
for k in range(2):
list.append([i, j, k])
i = 0
for elem in list:
print("i ============== ", i)
i += 1
print(elem)
theta = rgb_to_theta(elem)
theta_to_rgb(theta)
def test_image():
im = get_image()
33
im = scale_up(im)
for i in range(7):
im = double_size(im)
show_image(im, "aman_test")
[ ]: import i_theta
import image_testing
from math import pi
if __name__ == '__main__':
image = image_testing.get_image()
angles = []
# convert all rgb pixel values into angles in [0, pi/2]
for i in range(size):
for j in range(size):
angles.append((image_testing.rgb_to_theta(image[i][j])))
new_angles = i_theta.run(angles)
im = []
i = 0
# converting all the recovered angles, back into rgb values
for ang in new_angles:
rgb = image_testing.theta_to_rgb(ang)
print(rgb)
if (i % 2 == 0):
row = []
row.append(rgb)
if (i % 2 != 0):
im.append(row)
i += 1
34
new_image = image_testing.make_image(im)
for i in range(7):
new_image = image_testing.double_size(new_image)
image_testing.show_image(new_image, "ijijiijjij")
[ ]: import i_theta
import image_testing
from math import pi
if __name__ == '__main__':
image = image_testing.get_image4()
angles = []
# convert all rgb pixel values into angles in [0, pi/2]
for i in range(size):
for j in range(size):
angles.append((image_testing.rgb_to_theta(image[i][j])))
new_angles = i_theta.run_4(angles)
im = []
i = 0
# converting all the recovered angles, back into rgb values
for ang in new_angles:
rgb = image_testing.theta_to_rgb(ang)
print(rgb)
if (i % 4 == 0):
row = []
row.append(rgb)
if (i % 4 == 3):
im.append(row)
35
i += 1
new_image = image_testing.make_image(im)
for i in range(6):
new_image = image_testing.double_size4(new_image)
image_testing.show_image(new_image, "Four_w16_100-000-000_SHIFTED")
num_measurements = 10000
def run():
qc.measure(q, c)
backend_sim = Aer.get_backend('qasm_simulator')
print(result_sim.get_counts(qc))
36
[1]: import numpy as np
import matplotlib.pyplot as plt
for i in range(rows):
for j in range(cols):
# Quantum-inspired blur: Each pixel is replaced by the average of␣
,→its neighbors
return blurred_image
plt.show()
1
[2]: import numpy as np
import matplotlib.pyplot as plt
2
plt.subplot(1, 2, 2)
plt.title('Blurred Image')
plt.imshow(blurred_image, cmap='gray')
plt.axis('off')
plt.show()
[ ]:
3
[1]: import numpy as np
import matplotlib.pyplot as plt
def display_colored_boxes():
# Create a 4x4 grid with different colors
colors = np.random.rand(4, 4, 3) # Generating random RGB values
plt.show()
1
[2]: import numpy as np
import matplotlib.pyplot as plt
def display_colored_boxes():
# Create a 4x4 grid with different colors
colors = np.random.rand(4, 4, 3) # Generating random RGB values
plt.show()
2
[3]: import numpy as np
import matplotlib.pyplot as plt
def display_colored_boxes():
# Create a 4x4 grid with different colors
colors = np.random.rand(4, 4, 3) # Generating random RGB values
plt.show()
3
display_colored_boxes()
def display_colored_boxes():
# Create a 4x4 grid with different colors
colors = np.random.rand(4, 4, 3) # Generating random RGB values
plt.show()
4
# Call the function to display colored boxes
display_colored_boxes()
# Adjust layout
plt.tight_layout()
5
# Show the plot
plt.show()
[ ]:
6
[1]: import numpy as np
import matplotlib.pyplot as plt
def create_colored_image():
# Create a 4x4 grid with colors: red, green, blue, yellow
colors = {
'red': (1, 0, 0),
'green': (0, 1, 0),
'blue': (0, 0, 1),
'yellow': (1, 1, 0)
}
image_size = 4
color_image = np.zeros((image_size, image_size, 3))
for i in range(image_size):
for j in range(image_size):
if i < image_size // 2 and j < image_size // 2:
color_image[i, j] = colors['red']
elif i < image_size // 2:
color_image[i, j] = colors['green']
elif j < image_size // 2:
color_image[i, j] = colors['blue']
else:
color_image[i, j] = colors['yellow']
return color_image
def display_colored_image(image):
# Display the colored image
plt.imshow(image)
plt.axis('off')
plt.show()
1
[2]: import numpy as np
import matplotlib.pyplot as plt
from scipy.ndimage import gaussian_filter
def create_colored_image():
colors = {
'red': (1, 0, 0),
'green': (0, 1, 0),
'blue': (0, 0, 1),
'yellow': (1, 1, 0)
}
image_size = 4
color_image = np.zeros((image_size, image_size, 3))
for i in range(image_size):
for j in range(image_size):
if i < image_size // 2 and j < image_size // 2:
color_image[i, j] = colors['red']
elif i < image_size // 2:
color_image[i, j] = colors['green']
elif j < image_size // 2:
color_image[i, j] = colors['blue']
2
else:
color_image[i, j] = colors['yellow']
return color_image
return blurred_image
3
4
[ ]:
5
[1]: import numpy as np
[[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]]
[[[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]]
1
[[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]]
[[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]]
[[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]]
[[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]]
[[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]]
[[255 128 0]
[255 128 0]
2
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]]
[[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]
[255 128 0]]]
[ ]:
3
[1]: import numpy as np
import matplotlib.pyplot as plt
1
2
3
[ ]:
4
[1]: from qiskit import *
from qiskit import IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
import skimage.color
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
style.use('bmh')
import math
# Convert the RBG component of the image to B&W image, as a numpy (uint8) array
if len(image_raw.shape) == 2:
image_raw = skimage.color.gray2rgb(image_raw)
print(image_raw.shape)
image = []
for i in range(image_size):
image.append([])
for j in range(image_size):
image[i].append(image_raw[i][j][0] / 255)
image = np.array(image)
print('Image shape (numpy array):', image.shape)
1
plt.yticks(range(0, image.shape[1]+1, 32))
plt.imshow(image, extent=[0, image.shape[0], image.shape[1], 0], cmap='viridis')
plt.show()
2
# Return the normalized image as a numpy array
return np.array(image_norm)
total qbits 11
gridx=32
gridy=32
image_splits = []
image_ip_pro = np.array(image_ip)
for h in range(0,imageHeight,gridy):
for w in range(0,imageWidth,gridx):
# bbox=(x*gridx, y*gridy, x*gridx+gridx, y*gridy+gridy)
# slice_bit=image_ip.crop(bbox)
# slice_bit = np.array(slice_bit)
slice_bit = image_ip_pro[h:h+gridy, w:w+gridx,0]
slice_bit = slice_bit / 255
image_splits.append(slice_bit)
# plt.imshow(image_splits[0])
# plt.show()
# plt.imshow(image_splits[1])
# plt.show()
[ ]: import time
edges = []
tot_time = time.time()
3
for i in range(len(image_splits)):
start_time = time.time()
img = image_splits[i]
print(img.shape)
image_norm_h = amplitude_encode(img)
image_norm_v = amplitude_encode(img.T)
print('encoding', time.time() - start_time)
print(image_norm_h.shape)
# horizontal
qc_h.initialize(image_norm_h, range(1, total_qb))
qc_h.h(0)
qc_h.unitary(D2n_1, range(total_qb))
qc_h.h(0)
print('horizontal', time.time() - start_time)
# display(qc_h.draw('mpl', fold=-1))
# vertical
qc_v.initialize(image_norm_v, range(1, total_qb))
qc_v.h(0)
qc_v.unitary(D2n_1, range(total_qb))
qc_v.h(0)
print('vertical', time.time() - start_time)
# display(qc_v.draw('mpl', fold=-1))
# forming the circuit
circ_list = [qc_h, qc_v]
(32, 32)
encoding 0.0007760524749755859
(1024,)
horizontal 0.7311007976531982
4
vertical 1.435943603515625
running 144.20826506614685
extracting 144.20990562438965
144.34677839279175
(32, 32)
encoding 0.0006000995635986328
(1024,)
horizontal 0.5885050296783447
vertical 1.1858634948730469
running 292.49501490592957
extracting 292.49710845947266
5
292.62941813468933
(32, 32)
encoding 0.000667572021484375
(1024,)
horizontal 0.8226900100708008
vertical 1.6138217449188232
running 441.564177274704
extracting 441.56613755226135
6
441.69841623306274
(32, 32)
encoding 0.0006420612335205078
(1024,)
horizontal 0.5834693908691406
vertical 1.412827730178833
running 582.2895851135254
extracting 582.2910220623016
7
582.426659822464
(32, 32)
encoding 0.0005407333374023438
(1024,)
horizontal 0.7885682582855225
vertical 1.658304214477539
running 737.131618976593
extracting 737.1332285404205
8
737.4328744411469
(32, 32)
encoding 0.0007634162902832031
(1024,)
horizontal 1.0512843132019043
vertical 1.8754756450653076
running 888.8279981613159
extracting 888.8295588493347
9
889.009110212326
(32, 32)
encoding 0.0007188320159912109
(1024,)
horizontal 0.7772834300994873
vertical 1.5633196830749512
[ ]:
10
[1]: import numpy as np
def qft(matrix):
# Apply Quantum Fourier Transform on a 2D NumPy matrix
for u in range(rows):
for v in range(cols):
factor = np.exp(2j * np.pi * (u * np.arange(rows) / rows + v * np.
,→arange(cols) / cols))
# Example usage
image = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]], dtype=np.complex128)
qft_result = qft(image)
Original Image:
[[1.+0.j 2.+0.j 3.+0.j]
[4.+0.j 5.+0.j 6.+0.j]
[7.+0.j 8.+0.j 9.+0.j]]
def qft(matrix):
rows, cols = matrix.shape
result = np.zeros((rows, cols), dtype=np.complex128)
for u in range(rows):
for v in range(cols):
1
factor = np.exp(2j * np.pi * (u * np.arange(rows) / rows + v * np.
arange(cols) / cols))
,→
u, v = np.meshgrid(np.arange(image_size), np.arange(image_size))
ax.plot_surface(u, v, np.abs(qft_result), cmap='viridis')
ax.set_xlabel('U-axis')
ax.set_ylabel('V-axis')
ax.set_zlabel('Magnitude')
2
[ ]:
3
Designing a quantum image classifier using Data Re-uploading Quantum Convolution and a
Data Re-uploading Classifier Scheme involves combining concepts from quantum computing
and machine learning. This is a complex task, and the field is still evolving. Below is a
simplified outline of the steps you might consider when designing such a quantum image
classifier: