from matplotlib import pyplot
from qiskit import *
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import IBMQ, Aer, execute,assemble,QuantumCircuit, aqua
from qiskit.visualization import plot_histogram, plot_bloch_vector, plot_bloch_multivector
from qiskit.quantum_info import Statevector
from qiskit.extensions import *
provider = IBMQ.load_account()

from qiskit.quantum_info import random_unitary
from qiskit.providers.aer import QasmSimulator, StatevectorSimulator, UnitarySimulator
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
import math
from math import pi, sqrt

from scipy.special import rel_entr
from random import seed
from random import random
import cmath


#Possible Bin
bins_list=[];
for i in range(76):
    bins_list.append((i)/75)
#Center of the Bean
bins_x=[]    
for i in range(75):
    bins_x.append(bins_list[1]+bins_list[i])
def P_harr(l,u,N):
    return (1-l)**(N-1)-(1-u)**(N-1)
#Harr historgram
P_harr_hist=[]
for i in range(75):
    P_harr_hist.append(P_harr(bins_list[i],bins_list[i+1],2))    
#Imaginary    
j=(-1)**(1/2)

backend = Aer.get_backend('qasm_simulator')
for x in range(1,20,1):
    print()
arr = []
for nsh in range(1,20,1):
    arr.append([])
    for lp in range(1,10,1):
        nshot=int(round(1000*(nsh)**1.5,0))
        nparam=1000*lp
        fidelity=[]    
        for x in range(nparam):
            qr = QuantumRegister(1)
            cr = ClassicalRegister(1)
            qc = QuantumCircuit(qr, cr)

            u13=UnitaryGate(random_unitary(2))
            qc.append(u13, [qr[0]] )
            u13=UnitaryGate(random_unitary(2))
            qc.append(u13, [qr[0]] )

            qc.measure(qr[0],cr[0])
            job = execute(qc, backend, shots=nshot)
            result = job.result()
            count =result.get_counts()

            if '0' in count and '1' in count:
                ratio=count['0']/nshot
            elif '0' in count and '1' not in count:
                ratio=count['0']/nshot
            else:
                ratio=0

            fidelity.append(ratio)   
            #Kullback Leibler divergence
        weights = np.ones_like(fidelity)/float(len(fidelity))            
        P_U_hist=np.histogram(fidelity, bins=bins_list, weights=weights, range=[0, 1])[0];
        #Kullback Leibler divergence
        print(nshot,'shots per simulation',nparam,'distribution size')
        arr[nsh-1].append(sum(rel_entr(P_U_hist, P_harr_hist)))


import sys
import numpy
qasm=arr
numpy.set_printoptions(threshold=sys.maxsize)
np.savetxt("KLDivg_qasm.txt",qasm,fmt='%.2f')

backend = Aer.get_backend('statevector_simulator')
for x in range(1,20,1):
    print()
arr = []
for nsh in range(1,20,1):
    arr.append([])
    for lp in range(1,10,1):
        nshot=int(round(1000*(nsh)**1.5,0))
        nparam=1000*lp
        fidelity=[]    
        for x in range(nparam):
            qr = QuantumRegister(1)
            cr = ClassicalRegister(1)
            qc = QuantumCircuit(qr, cr)

            u13=UnitaryGate(random_unitary(2))
            qc.append(u13, [qr[0]] )
            u13=UnitaryGate(random_unitary(2))
            qc.append(u13, [qr[0]] )

            qc.measure(qr[0],cr[0])
            job = execute(qc, backend, shots=nshot)
            result = job.result()
            count =result.get_counts()

            if '0' in count and '1' in count:
                ratio=count['0']/nshot
            elif '0' in count and '1' not in count:
                ratio=count['0']/nshot
            else:
                ratio=0

            fidelity.append(ratio)   
            #Kullback Leibler divergence
        weights = np.ones_like(fidelity)/float(len(fidelity))            
        P_U_hist=np.histogram(fidelity, bins=bins_list, weights=weights, range=[0, 1])[0];
        #Kullback Leibler divergence
        print(nshot,'shots per simulation',nparam,'distribution size')
        arr[nsh-1].append(sum(rel_entr(P_U_hist, P_harr_hist)))


import sys
import numpy
statevector=arr
numpy.set_printoptions(threshold=sys.maxsize)
np.savetxt("KLDivg_statevector.txt",statevector,fmt='%.2f')

##Plot

import pandas as pd
import matplotlib.pyplot as plt

#loading dataset

x = [i+1 for i in range(19)]
y = [i[0] for i in arr]
plt.plot(x, y, 'o', color='red', label='L=1');
x = [i+1 for i in range(19)]
y = [i[1] for i in arr]
plt.plot(x, y, 'o', color='blue', label='L=2');
x = [i+1 for i in range(19)]
y = [i[2] for i in arr]
plt.plot(x, y, 'o', color='black', label='L=3');
x = [i+1 for i in range(19)]
y = [i[3] for i in arr]
plt.plot(x, y, 'o', color='green', label='L=4');
x = [i+1 for i in range(19)]
y = [i[3] for i in arr]
plt.plot(x, y, 'o', color='purple', label='L=5');
plt.legend(loc='upper right')

plt.yscale('log',base=10) 
plt.xlabel('Circuit ID')
plt.ylabel('Expressibility')

# Create names on the x axis
plt.xticks([i+1 for i in range(19)])
plt.show()