%matplotlib inline
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, execute, Aer, IBMQ, assemble
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
data = [0.1, 0.2, 0.3, 0.4]
angles = []


"""# normalize the datapoints if datapoints >= 1 
max_val = max(digit_data[0])
norm_data = []
for i in A:
    temp_row = []
    for j in i:
        temp_row.append(j/max_val)
    norm_data.append(temp_row)
    
print(norm_data)
"""

# encode data as angular rotations on bloch sphere
for i in data:
    angles.append(2*np.arcsin(np.sqrt(i)))
print(data, angles, sep='\n')

# circuit with 2 qubits, 2 cbits
qc = QuantumCircuit(4, 4)

# apply RY gate using theta
for i in range(4):
    qc.ry(angles[i], i)

# measure each qubit's output
for i in range(4):
    qc.measure(i, i)

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)

# retrieving original data as the 
# expected value of each set of bits i.e
# add probabilities of all outputs with their 4th bit set on
bit4 = []
bit3 = []
bit2 = []
bit1 = []
# creating an array to access E(psi) more easily
for i in counts:
    prob = counts[i]/100000
    bit4.append([i[0], prob])
    bit3.append([i[1], prob])
    bit2.append([i[2], prob])
    bit1.append([i[3], prob])
    
# array of bit's arrays...
bits = [bit4, bit3, bit2, bit1]
q_data = []

# finding the expected value of each bit, appending to array
for nth_bit in bits:
    e_val = 0.0
    for bit in nth_bit:
#        print(bit[0], bit[1])
        if int(bit[0]) == 1:
            e_val += bit[1]
#            print('added')
    q_data.append(round(e_val, 2))

print(q_data, '\nData Retrieved, just backwards')

