from qiskit import *
from qiskit import transpile 
import numpy as np
import matplotlib.pyplot as plt
from qiskit.extensions import UnitaryGate
from qiskit import IBMQ 
import sys 
sys.path.append("..")
%matplotlib inline

qiskit.__qiskit_version__

from Modules.iterative_qpe import IQPE 

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

iqpe = IQPE(precision=4,unitary=U,unknown=True) 

q = QuantumCircuit(2, 4)
q.x(1)
phase = iqpe.get_circuit_phase(
    QC=q, clbits=[0, 1, 2, 3], qubits=[1],ancilla=0, show=True, save_circ = True)

phase 

U = QuantumCircuit(2,name='U')
U.cp(2*np.pi*1/6,0,1)
U.draw('mpl')
#.control(num_ctrl_qcubits= 1, label = 'CCu', ctrl_state = '1')

iqpe = IQPE(precision=4,unitary=U,unknown=True) 

q = QuantumCircuit(3, 4)
q.x(1)
q.x(2)
phase = iqpe.get_circuit_phase(
    QC=q, clbits=[0, 1, 2, 3], qubits=[1,2],ancilla=0, show=True,save_circ = True,circ_name = "IQPE_circ.JPG")

print("Phase of the circuit in binary:", phase)


u2 = QuantumCircuit(3)
u2.cp(2*np.pi*(1/6),1,2)
u2.draw('mpl')

estimates = []
for prec in range(2, 9):
    q = QuantumCircuit(4, prec)
    # making eigenvector 
    q.x(2)
    q.x(3)
    iqpe = IQPE(precision=prec, unitary=u2,unknown=True)
    phase = iqpe.get_circuit_phase(
        QC=q, clbits=[i for i in range(prec)], qubits=[1,2,3], ancilla=0)
#     print(phase[0])
    estimates.append(phase[1])

plt.figure(figsize=(9, 7))
plt.plot(list(range(2, 9)), estimates, marker='o',
         label='Estimates', linestyle='dotted',linewidth = 2,color = 'cyan')
plt.plot([0, 10], [0.16667, 0.16667], color='black', label='Actual phase')
plt.title("IQPE estimates for $\\theta = 1/6$", fontsize=16)
plt.xlabel("Number of iterations ", fontsize=14)
plt.ylabel("Estimate of phase", fontsize=14)
plt.legend()

from Modules.iterative_qpe import get_estimate_plot_phase 

IBMQ.load_account()
## provider = IBMQ.get_provider('''ENTER YOUR PROVIDER''')
casb = provider.get_backend('ibmq_casablanca')

get_estimate_plot_phase(theta=0.524, iters = 9,unknown= True, save=True, experiments=5,backend=casb)

get_estimate_plot_phase(0.111, iters= 8, unknown=True, save=True,experiments=3)

