from qiskit import QuantumCircuit, execute, transpile, Aer 
from qiskit.extensions import UnitaryGate
import numpy as np 
import os  
from qiskit.extensions import UnitaryGate
import sys 
import matplotlib.pyplot as plt 
%matplotlib inline 

os.makedirs(name = 'Plots',exist_ok=True)

 sys.path.append("..")

 from Modules.normal_SPEA import SPEA 

# uncomment & RUN to use actual backends

# from qiskit import IBMQ 
# IBMQ.load_account()
# provider = IBMQ.get_provider(hub='??your_provider??')
# santiago = provider.get_backend('ibmq_santiago')
# casablanca = provider.get_backend('ibmq_casablanca')


sim = Aer.get_backend('qasm_simulator')

U1 = QuantumCircuit(1)
U1.x(0)
U1.draw('mpl')

spe = SPEA(U1,resolution= 10,error = 4,max_iters=12)

result = spe.get_eigen_pair(progress = False,algo = 'alternate',backend = Aer.get_backend('qasm_simulator'))

result 

# original theta = 0.2 
t = []
for resolution in range(10,50,5):
    spe = SPEA(U1,resolution= resolution,max_iters=10)    
    res = spe.get_eigen_pair(backend = sim,algo = 'alternate',target_cost = 0.9)
    theta = res['theta']
    t.append(theta)

plt.figure(dpi = 100,figsize=(8,6))
plt.title("Eigenphase estimation for X gate",fontsize = 15)
plt.grid()
plt.plot(list(range(10,50,5)),t,marker = 'o',color='g',label = 'Estimates',alpha=0.7)
plt.plot([10,50],[0.5,0.5],color='black',label = "True")
plt.plot([10,50],[0,0],color='black')
plt.plot([10,50],[1,1],color='black')

plt.legend()
plt.xlabel("Resolution of theta ")
plt.ylabel("Estimates")
plt.savefig("Plots/SPE_PLOT1.jpg",dpi = 200)

u2 = UnitaryGate(data=np.array([[1,0],
                               [0, np.exp(2*np.pi*1j*(1/5))]]))

# original theta = 0.2 
t = []
for resolution in range(20,80,5):
    spe = SPEA(u2,resolution= resolution,max_iters=10)    
    res = spe.get_eigen_pair(backend = sim,algo = 'alternate',target_cost = 0.94)
    theta = res['theta']
    t.append(theta)

plt.figure(dpi = 100,figsize = (8,6))
plt.title("Eigenphase estimation for theta = 1/5, 0",fontsize = 15)
plt.grid()
plt.plot(list(range(20,80,5)),t,marker = 'o',color='g',label = 'Estimates',alpha=0.7)
plt.plot([10,80],[0.2,0.2],color='black',label = "True")
plt.plot([10,80],[0,0],color='black')
plt.plot([10,80],[1,1],color='black')

plt.legend()
plt.xlabel("Resolution of theta ")
plt.ylabel("Estimates")
plt.savefig("Plots/SPE_PLOT2.jpg",dpi = 200)

