from qiskit import *
from qiskit.visualization import plot_histogram

qc = QuantumCircuit(3,3)
qc.h(0)
qc.cx(0,1)
qc.cx(1,2)
qc.measure([0,1,2],[0,1,2])


qc.draw('mpl')

simulator = Aer.get_backend('qasm_simulator')
result = execute(qc, backend = simulator, shots = 1024).result()

plot_histogram(result.get_counts(qc))

from qiskit import IBMQ
IBMQ.save_account('a9783f33a64e88d038689c3d3a67cb4235d7715268ca95f986cf1e3e514cd601c77d52d8d8cffda397c63ad4f4cd488a6e907452415bf854dd028ae21c78c927')

IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
device = provider.get_backend('ibmqx2')

job = execute(qc, backend = device, shots = 1024)
print(job.job_id())
from qiskit.tools.monitor import job_monitor
job_monitor(job)

device_result = job.result()
plot_histogram(device_result.get_counts(qc))

from qiskit.ignis.mitigation.measurement import (complete_meas_cal, CompleteMeasFitter)

cal_circuits, state_labels = complete_meas_cal(qr = qc.qregs[0], circlabel = 'measerrormitigationcal')

cal_circuits[2].draw('mpl')

len(cal_circuits)

cal_job = execute(cal_circuits, backend = device, shots = 1024, optimization_level = 0)
print(cal_job.job_id())
job_monitor(cal_job)
cal_results = cal_job.result()

plot_histogram(cal_results.get_counts(cal_circuits[3]))

meas_fitter = CompleteMeasFitter(cal_results, state_labels)

meas_fitter.plot_calibration()

meas_filter = meas_fitter.filter

mitigated_result = meas_filter.apply(device_result)

device_counts = device_result.get_counts(qc)
mitigated_counts = mitigated_result.get_counts(qc)
plot_histogram([device_counts,mitigated_counts], legend = ['device, noisy', 'device,mitigated'])

circuit = QuantumCircuit(3,3)
circuit.x(1)
circuit.h(0)
circuit.cx(0,1)
circuit.cx(1,2)
circuit.measure([0,1,2],[0,1,2])


circuit.draw('mpl')

plot_histogram(execute(circuit, backend = simulator, shots = 1024).result().get_counts(circuit))
                       

device_counts_1 = execute(circuit, backend = device,shots = 1024).result().get_counts(circuit)

plot_histogram(device_counts_1)

device_mitigated_counts_1 = meas_filter.apply(device_counts_1)

plot_histogram(device_mitigated_counts_1)

