import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np

from qiskit import *
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.quantum_info import Statevector
from qiskit.circuit.library import QFT
from qiskit.visualization import plot_state_qsphere
from qiskit.quantum_info import Operator

from qiskit.tools.visualization import plot_histogram
from IPython.display import display, Math, Latex
import math

def reflect(mcq, n):
    for i in range(int(n/2)):
        mcq.swap(i, n-i-1)

def myQFT(mcq, n):
    for x_k in range(n):
        mcq.h(x_k)
        for x_j in range(x_k+1, n):
            angle = math.pi/2**(x_j-x_k)
            mcq.cu1(angle, x_j, x_k)

n = 4
qbt1 = QuantumRegister(n)
cbt1 = ClassicalRegister(n)
mcq1 = QuantumCircuit(qbt1, cbt1)

myQFT(mcq1, n)
mcq1.barrier()
reflect(mcq1, n)
mcq1.barrier()

mcq1.measure(range(n), range(n))

backend = BasicAer.get_backend('qasm_simulator')
atp = 1024
res = execute(mcq1, backend=backend, shots=atp).result()
ans1 = res.get_counts()

mcq1.draw('mpl')

qbt2 = QuantumRegister(n)
cbt2 = ClassicalRegister(n)
mcq2 = QuantumCircuit(qbt2, cbt2)

mcq2.append(QFT(n, do_swaps=True), qbt2)
#mcq2.h(range(n))

mcq2.measure(range(n), range(n))

backend = BasicAer.get_backend('qasm_simulator')
atp = 1024
res = execute(mcq2, backend=backend, shots=atp).result()
ans2 = res.get_counts()

mcq2.draw('mpl')

legend = ['myQFT','qiskitQFT']
plot_histogram([ans1,ans2], legend=legend)