Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

group code #56

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added quantum_classfier.pkl
Binary file not shown.
Binary file removed quantum_classifier.pickle
Binary file not shown.
5 changes: 5 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
matplotlib==3.6.3
numpy==1.23.5
qiskit==0.41.0
qiskit_terra==0.22.4
scikit_learn==1.2.1
128 changes: 94 additions & 34 deletions test.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
import cirq
import qiskit
from qiskit import quantum_info, QuantumCircuit
from itertools import chain
from qiskit.execute_function import execute
from qiskit import BasicAer
from qiskit.circuit.library import ZZFeatureMap
import numpy as np
import pickle
import json
import os
import sys
from collections import Counter
from sklearn.metrics import mean_squared_error
from typing import Dict, List
import matplotlib.pyplot as plt

if len(sys.argv) > 1:
data_path = sys.argv[1]
Expand All @@ -14,13 +21,12 @@

#define utility functions

def simulate(circuit: cirq.Circuit) -> dict:
"""This function simulates a Cirq circuit (without measurement) and outputs results in the format of histogram.
"""
simulator = cirq.Simulator()
result = simulator.simulate(circuit)

state_vector=result.final_state_vector
def simulate(circuit: qiskit.QuantumCircuit) -> dict:
"""Simulate the circuit, give the state vector as the result."""
backend = BasicAer.get_backend('statevector_simulator')
job = execute(circuit, backend)
result = job.result()
state_vector = result.get_statevector()

histogram = dict()
for i in range(len(state_vector)):
Expand All @@ -43,17 +49,17 @@ def histogram_to_category(histogram):

return positive

def count_gates(circuit: cirq.Circuit):
"""Returns the number of 1-qubit gates, number of 2-qubit gates, number of 3-qubit gates...."""
counter=Counter([len(op.qubits) for op in circuit.all_operations()])

def count_gates(circuit: qiskit.QuantumCircuit) -> Dict[int, int]:
"""Returns the number of gate operations with each number of qubits."""
counter = Counter([len(gate[1]) for gate in circuit.data])
#feel free to comment out the following two lines. But make sure you don't have k-qubit gates in your circuit
#for k>2
for i in range(2,20):
assert counter[i]==0

return counter


def image_mse(image1,image2):
# Using sklearns mean squared error:
# https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_squared_error.html
Expand All @@ -73,6 +79,7 @@ def test():
for image in images:
#encode image into circuit
circuit,image_re=run_part1(image)
image_re = np.asarray(image_re)

#count the number of 2qubit gates used
gatecount+=count_gates(circuit)[2]
Expand Down Expand Up @@ -111,21 +118,61 @@ def test():

print(score_part1, ",", score_part2, ",", data_path, sep="")


############################
# YOUR CODE HERE #
############################
# GLOBAL VARIABLES
DIM = 28
NUM_QUBITS = 10

def encode_img(image, register_num):
''' encoding of image using QPIE method '''
img = list(chain(*image))
pix_val = img

# normalize
pix_norm = np.linalg.norm(pix_val)
pix_val = np.array(pix_val)
arr_norm = pix_val/pix_norm
arr_norm = arr_norm.tolist()

# Encode onto the quantum register
qc = QuantumCircuit(register_num)
# test = arr_norm.append(np.zeros(2**10-arr_norm.shape))
test = arr_norm + np.zeros(2**register_num-DIM**2).tolist()
qc.initialize(test, qc.qubits)
return qc


def encode(image):
circuit=cirq.Circuit()
if image[0][0]==0:
circuit.append(cirq.rx(np.pi).on(cirq.LineQubit(0)))
return circuit
''' final wrapper function (for submission) '''
return encode_img(255*255*image, register_num=NUM_QUBITS)


def decode_img(histogram):
''' decoding (written by prathu) '''
pixelnums = list(range(DIM**2))
for pix in pixelnums:
if pix not in histogram.keys():
# grayscale pixel value is 0
histogram.update({pix: 0})

histnew = dict(sorted(histogram.items()))

histdata = []
# for i in enumerate(histnew):
for i in range(len(histnew)):
histdata.append(histnew[i])
histdata = np.array(histdata)
histarr = np.reshape(histdata, (DIM, DIM))

return histarr


def decode(histogram):
if 1 in histogram.keys():
image=np.array([[0,0],[0,0]])
else:
image=np.array([[1,1],[1,1]])
return image
''' final wrapper function (for submission) '''
return decode_img(histogram)

def run_part1(image):
#encode image into a circuit
Expand All @@ -141,32 +188,45 @@ def run_part1(image):

def run_part2(image):
# load the quantum classifier circuit
with open('quantum_classifier.pickle', 'rb') as f:
classifier=pickle.load(f)
# classifier=qiskit.QuantumCircuit.from_qasm_file('quantum_classifier.qasm')

with open('quantum_classifier_500samples.pkl','rb') as f:
contents = pickle.load(f)

classifier = contents['qsvm']#for classical feature maps
pca = contents['pca'] #for classical feature maps

#encode image into circuit
circuit=encode(image)
img = pca.transform(image.reshape(-1, DIM*DIM)) #for classical feature maps

circuit=encode(image)

#append with classifier circuit

circuit.append(classifier)
nq1 = circuit.width() #uncomment for quantum feature map
nq2 = classifier.width() #uncomment for quantum feature map
# nq = max(nq1, nq2) #uncomment for quantum feature map
qc = qiskit.QuantumCircuit(nq2) #uncomment for quantum feature map and make nq2 to nq
# qc.append(circuit.to_instruction(), list(range(nq1))) #uncomment for quantum feature map
qc.append(classifier.to_instruction(), list(range(nq2))) #uncomment for quantum feature map

#simulate circuit
histogram=simulate(circuit)

# histogram=simulate(qc) #uncomment for quantum feature map

label = classifier.predict(img)[0] #for classical feature maps
#convert histogram to category
label=histogram_to_category(histogram)
# label=histogram_to_category(histogram) #uncomment for quantum feature map

#thresholding the label, any way you want
if label>0.5:
label=1
else:
label=0
#uncomment for quantum feature map
# if label>0.5:
# label=1
# else:
# label=0

return circuit,label

############################
# END YOUR CODE #
############################

test()
test()
182 changes: 0 additions & 182 deletions test_qiskit.py

This file was deleted.