import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, IBMQ, execute, assemble
from qiskit.providers.ibmq import least_busy
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *

# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()

## Creating function for Equal Superposition states of two qubits:
def initialize(qc):
    qc.h(0)         # Applying H gates to both qubits
    qc.h(1)         # and initializing grover circuit
    qc.barrier()
grover_circuit = QuantumCircuit(2)
initialize(grover_circuit)
grover_circuit.draw('mpl') 

# Let's try to find the position of |11>:
def oracle_11(qc):  # Apply a controlled Z gate
    qc.cz(0,1)
    qc.barrier()
oracle_11(grover_circuit)
grover_circuit.draw('mpl')    

# Creating Grover's Diffusion operator:
def u_g(qc):
    qc.h(0)
    qc.h(1)
    qc.x(0)
    qc.x(1)
    qc.h(1)
    qc.cx(0,1)
    qc.x(0)
    qc.h(1)
    qc.h(0)
    qc.x(1)
    qc.h(1)
    qc.barrier()
u_g(grover_circuit)        # temporary circuit just to see what U_s looks like
grover_circuit.draw('mpl')    

# Finally we measure the circuit:
grover_circuit.measure_all()
grover_circuit.draw('mpl')

# Simulating the Circuit:
backend = Aer.get_backend('qasm_simulator')
job = execute(grover_circuit, backend, shots = 1024)
result = job.result()
counts = result.get_counts()
plot_histogram(counts)

# Experimenting with real device:
IBMQ.load_account()
# Getting the least busy backend
provider = IBMQ.get_provider(hub='ibm-q')
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 
                                       and not x.configuration().simulator 
                                       and x.status().operational==True))
print("least busy backend: ", backend)

# Running the circuit on the least busy backend. Monitor the execution of the job in the queue
from qiskit.tools.monitor import job_monitor
transpiled_grover_circuit = transpile(grover_circuit, backend, optimization_level=3)
qobj = assemble(transpiled_grover_circuit)
job = backend.run(qobj)
job_monitor(job, interval=2)

# Getting the results from the computation
results = job.result()
answer = results.get_counts(grover_circuit)
plot_histogram(answer)