import matplotlib.pyplot as plt
import numpy as np
!pip install qiskit
from qiskit import IBMQ, Aer, assemble, transpile, execute
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit.providers.ibmq import least_busy
!pip install qiskit.visualization
from qiskit.visualization import *
from qiskit.tools.jupyter import *
!pip install ibm_quantum_widgets
from ibm_quantum_widgets import *
from qiskit.tools.monitor import job_monitor


provider = IBMQ.load_account()
num_qubits = 2
grover_circuit = QuantumCircuit(num_qubits, num_qubits)

def initialize_circ(qc, qubits):
  for q in qubits:
    qc.h(q)
  return qc

grover_circuit = initialize_circ(grover_circuit, [0,1])
grover_circuit.barrier()
grover_circuit.draw()

grover_circuit.cz(0, 1)
grover_circuit.barrier()
grover_circuit.draw()

grover_circuit.h([0, 1])
grover_circuit.z([0, 1])
grover_circuit.cz(0, 1)
grover_circuit.h([0, 1])
grover_circuit.barrier()
grover_circuit.measure([0,1], [0, 1])
grover_circuit.draw()

backend = Aer.get_backend('qasm_simulator')
job = execute(grover_circuit, backend, shots = 1)
result = job.result()
counts = result.get_counts()
print(counts)


device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and 
                                   not x.configuration().simulator and x.status().operational==True))
print(device)

transpiled_grover_circuit = transpile(grover_circuit, device, optimization_level=3)
job = device.run(transpiled_grover_circuit)
job_monitor(job, interval=2)

results = job.result()
answer = results.get_counts(grover_circuit)
plot_histogram(answer)

