# Your first Qiskit application
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit

qr = QuantumRegister(2) # qubits indexed as qr[0], qr[1] and qr[2]
cr = ClassicalRegister(2) # classical bits indexed as cr[0], cr[1] and cr[2]
circuit = QuantumCircuit(qr, cr)

circuit.h(qr[0])
circuit.cx(qr[0], qr[1])
circuit.measure(qr, cr)

circuit.draw()

circuit.draw(output='latex_source')

print(circuit.qasm())

from qiskit import Aer, execute

# pick a backend, in this case a simulator
backend = Aer.get_backend('qasm_simulator')

# start a simulation job on the backend
job = execute(circuit, backend, shots=1000)

# collect the job results and display them
result = job.result()
counts = result.get_counts(circuit)
print(counts)

from qiskit.tools.visualization import plot_histogram
plot_histogram(counts)

from qiskit import IBMQ

IBMQ.load_accounts()
IBMQ.backends()

# OPTION 1: pick a specific backend
backend = IBMQ.get_backend('ibmq_16_melbourne')
# OPTION 2: pick the least busy backend
from qiskit.providers.ibmq import least_busy
backend = least_busy(IBMQ.backends(simulator=False))

# start a simulation job on the backend
job = execute(circuit, backend, shots=1000)

# collect the job results and display them
result = job.result()
counts = result.get_counts(circuit)
print(counts)

# OPTION 1: pick a specific backend
backend = IBMQ.get_backend('ibmq_16_melbourne')
# OPTION 2: pick the least busy backend
from qiskit.providers.ibmq import least_busy
backend = least_busy(IBMQ.backends(simulator=False))

# start a simulation job on the backend
job = execute(circuit, backend, shots=1000)

# monitor the job
from qiskit.tools.monitor import job_monitor
job_monitor(job)

# collect the job results and display them
result = job.result()
counts = result.get_counts(circuit)
print(counts)

plot_histogram(counts)

%qiskit_backend_monitor backend

qr = QuantumRegister(7, 'q')
qr = QuantumRegister(7, 'q')
tpl_circuit = QuantumCircuit(qr)
tpl_circuit.h(qr[3])
tpl_circuit.cx(qr[0], qr[6])
tpl_circuit.cx(qr[6], qr[0])
tpl_circuit.cx(qr[0], qr[1])
tpl_circuit.cx(qr[3], qr[1])
tpl_circuit.cx(qr[3], qr[0])
tpl_circuit.draw()

from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import BasicSwap
from qiskit.transpiler import transpile
from qiskit.mapper import CouplingMap

help(BasicSwap)

coupling = [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6]]

simulator = Aer.get_backend('qasm_simulator')
coupling_map = CouplingMap(couplinglist=coupling)
pass_manager = PassManager()
pass_manager.append([BasicSwap(coupling_map=coupling_map)])
basic_circ = transpile(tpl_circuit, simulator, pass_manager=pass_manager)
basic_circ.draw()

IBMQ.backends()

realdevice = IBMQ.get_backend('ibmq_16_melbourne')
tpl_realdevice = transpile(tpl_circuit, backend = realdevice)
tpl_realdevice.draw(line_length = 250)

