from qiskit import *
import numpy as np
import math
import qiskit
nshots = 8192
IBMQ.load_account()
#provider= qiskit.IBMQ.get_provider(hub='ibm-q-research-2',group='federal-uni-sant-1',project='main')
provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
device = provider.get_backend('ibmq_belem')
simulator = Aer.get_backend('qasm_simulator')
from qiskit.tools.monitor import job_monitor
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter

dth = math.pi/10
th = np.arange(0,math.pi+dth,dth)
ph = 0; lb = 0
N = len(th)
F_the = np.zeros(N); F_sim = np.zeros(N); F_exp = np.zeros(N)
for j in range(0,N):
    F_the[j] = math.cos(th[j]/2)**2
    qr = QuantumRegister(3)
    cr = ClassicalRegister(1)
    qc = QuantumCircuit(qr,cr)
    qc.u(th[j],ph,lb,qr[2])
    qc.h(qr[0])
    qc.cswap(qr[0],qr[1],qr[2])
    qc.h(qr[0])
    qc.measure(qr[0],cr[0])
    job_sim = execute(qc, backend=simulator, shots=nshots)
    counts = job_sim.result().get_counts(qc)
    if '0' in counts:
        F_sim[j] = 2*counts['0']/nshots - 1
    job_exp = execute(qc, backend=device, shots=nshots)
    print(job_exp.job_id())
    job_monitor(job_exp)
    counts = job_exp.result().get_counts(qc)
    if '0' in counts:
        F_exp[j] = 2*counts['0']/nshots - 1
qc.draw('mpl')

qc.decompose().decompose().draw('mpl') # o circuito é "profundo" por causa da swap controlada

F_the, F_sim, F_exp

from matplotlib import pyplot as plt

plt.plot(th, F_the, label=r'$F_{the}$')
plt.plot(th, F_sim, '*', label=r'$F_{sim}$')
plt.plot(th, F_exp, 'o', label=r'$F_{exp}$')
plt.xlabel(r'$\theta$')
plt.legend()
plt.show()





