%matplotlib inline
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, execute, Aer, IBMQ, assemble, extensions
from qiskit.visualization import *

from os import environ

#local environment variable to store the access token :)
token = environ.get('ibmq_token')

# Loading your IBM Q account(s)
account = IBMQ.save_account(token, overwrite=True)
provider = IBMQ.load_account()

# quasm_sim not necessary
simulator = Aer.get_backend('qasm_simulator')


import numpy as np
from matplotlib.image import imread
import matplotlib.pyplot as plt

from sklearn.datasets import load_digits
digits = load_digits()

# load the list of lists into a list :)
img_data = digits['images']
print(img_data[0])


# setting the figure parameters to the size of the input
plt.rcParams['figure.figsize'] = [4, 4]

# testing one input
A = img_data[5]
B = img_data[5]

# displays image in grayscale
display = plt.imshow(A)
display.set_cmap('gray')


# compress image to a 4x4
r=4

# approx image:
Xapp = np.zeros((r,r))
for i in range(0, len(A), 2):
    for j in range(0, len(A), 2):
        sub_mat = np.zeros(r)
        sub_sum = 0
        sub_sum += A[i][j] + A[i][j+1] + A[i+1][j] + A[i+1][j+1] 
        Xapp[int(i/2)][int(j/2)] = sub_sum/4
        
print(np.array(Xapp))

plt.figure(1)
img = plt.imshow(Xapp)
img.set_cmap('gray')
plt.show()

# Not sure if the inaccurate representation is an accurate one :) ie new unitary imgmap vs original imgmap
# perform full Singular Vector Decomposition (SVD) on compressed image
U, S, VT = np.linalg.svd(Xapp, full_matrices=True)

# take unitary parts for encoding
new_unitary = np.matmul(U, VT)

print(Xapp, new_unitary,sep='\n\n')

display = plt.imshow(new_unitary)
display.set_cmap('gray')

# circuit 2^n = 64, so n=6
qc = QuantumCircuit(2, 2)

# testing basic unitary
identity = np.identity(4)

print(len(new_unitary))
qc.unitary(new_unitary, [0, 1])

# measure qubit's output
qc.measure([0, 1], [0, 1])

qc.draw()


# run simulation 100000 times, stores results in counts
job = execute(qc, simulator, shots=100000)

results = job.result()

counts = results.get_counts(qc)

plot_histogram(counts)

""" NOT SURE HOW TO DECODE YET :("""