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

CQTech submission #60

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
89 changes: 62 additions & 27 deletions test.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
import cirq
import qiskit
from qiskit import quantum_info
from qiskit.execute_function import execute
from qiskit import BasicAer
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 +19,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 +47,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
#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 +77,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,22 +116,49 @@ def test():

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


############################
# YOUR CODE HERE #
############################
from qiskit import QuantumCircuit, Aer
from qiskit.compiler import transpile
from qiskit.providers.fake_provider import FakeRueschlikon


def encode(image):
circuit=cirq.Circuit()
if image[0][0]==0:
circuit.append(cirq.rx(np.pi).on(cirq.LineQubit(0)))
return circuit
amp = np.sum(np.ravel(image)**2)
x_ = np.ravel(image) / np.sqrt(amp)
qc = QuantumCircuit(10, name="AmplitudeEncoding")
sv = np.zeros(2**10)
sv[:len(x_)] = x_
qc.initialize(sv)
return transpile(qc, backend=FakeRueschlikon())

def decode(histogram):
if 1 in histogram.keys():
image=np.array([[0,0],[0,0]])
else:
image=np.array([[1,1],[1,1]])
image = np.zeros(max(histogram.keys())+1)

for key in histogram.keys():
image[key] = np.sqrt(histogram[key])

image = image[:784].reshape((28,28))

return image

def simulate(circuit: qiskit.QuantumCircuit) -> dict:
"""Simulates the circuit, gives 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)):
population = abs(state_vector[i]) ** 2
if population > 1e-9:
histogram[i] = population

return histogram

def run_part1(image):
#encode image into a circuit
circuit=encode(image)
Expand All @@ -141,18 +173,21 @@ 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')

#encode image into circuit
circuit=encode(image)

#append with classifier circuit

circuit.append(classifier)
nq1 = circuit.width()
nq2 = classifier.width()
nq = max(nq1, nq2)
qc = qiskit.QuantumCircuit(nq)
qc.append(circuit.to_instruction(), list(range(nq1)))
qc.append(classifier.to_instruction(), list(range(nq2)))

#simulate circuit
histogram=simulate(circuit)
histogram=simulate(qc)

#convert histogram to category
label=histogram_to_category(histogram)
Expand Down
182 changes: 0 additions & 182 deletions test_qiskit.py

This file was deleted.