from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ, BasicAer
from qiskit.visualization import plot_bloch_multivector,plot_bloch_vector, plot_histogram
from qiskit.quantum_info import Statevector
import numpy as np 
import matplotlib

backend = BasicAer.get_backend('qasm_simulator')
shots = 1024

style = {'backgroundcolor': 'lightyellow'} # Style of the circuits

qreg1 = QuantumRegister(2) # The quantum register of the qubits, in this case 2 qubits
register1 = ClassicalRegister(1) 

qc = QuantumCircuit(qreg1, register1)

#qc.x(0)
qc.x(1)
qc.barrier()
qc.draw(output='mpl', style=style) 

qc.h(0)
qc.h(1)
qc.barrier()
qc.draw(output='mpl', style=style) 



qc.cx(0,1)
qc.barrier()
qc.draw(output='mpl', style=style) 

qc.h(0)
qc.draw(output='mpl', style=style) 

qc.measure(qreg1[0],register1)
qc.draw(output='mpl', style=style) 

results = execute(qc, backend=backend, shots=shots).result()
answer = results.get_counts()

plot_histogram(answer)

def oracleBalance1(qcir):
    qcir.cx(0,1)
    qcir.barrier()
    
    return qcir  

def oracleBalance2(qcir):
    qcir.x(1)
    qcir.cx(0,1)
    qcir.barrier()
    
    return qcir  

def oracleConstant1(qcir):
    
    qcir.x(1)
    qcir.barrier()
    
    return qcir  

def oracleConstant2(qcir):
    
    qcir.barrier()
    
    return qcir  

def deutsch(oracle):
    
    Qreg = QuantumRegister(2)
    Creg = ClassicalRegister(1) 
    qcirc = QuantumCircuit(Qreg, Creg)
    
    qcirc.x(1)
    
    qcirc.h(0)
    qcirc.h(1)
    qcirc.barrier()
    
    qcirc = oracle(qcirc)
    
    qcirc.h(0)
    qcirc.barrier()
    
    qcirc.measure(Qreg[0],Creg)
   
    return qcirc

resultBalanced1 = deutsch(oracleBalance1)
resultBalanced1.draw(output='mpl', style=style)

resultsB1 = execute(resultBalanced1, backend=backend, shots=shots).result()
answerB1 = resultsB1.get_counts()

plot_histogram(answerB1)

resultBalanced2 = deutsch(oracleBalance1)
resultBalanced2.draw(output='mpl', style=style)

resultsB2 = execute(resultBalanced2, backend=backend, shots=shots).result()
answerB2 = resultsB2.get_counts()

plot_histogram(answerB2)

resultConstant1 = deutsch(oracleConstant1)
resultConstant1.draw(output='mpl', style=style) 

resultsC1= execute(resultConstant1, backend=backend, shots=shots).result()
answerC1 = resultsC1.get_counts()

plot_histogram(answerC1)

resultConstant2 = deutsch(oracleConstant2)
resultConstant2.draw(output='mpl', style=style) 

resultsC2= execute(resultConstant2, backend=backend, shots=shots).result()
answerC2 = resultsC2.get_counts()

plot_histogram(answerC2)

