from qiskit import *

qc = QuantumCircuit()

qr = QuantumRegister(2,'qreg')

qc.add_register( qr )

qc.qregs

qc.draw(output='mpl')

qc.h()

qc.h( qr[0] )

qc.cx( qr[0], qr[1] );

qc.draw(output='mpl')

vector_sim = Aer.get_backend('statevector_simulator')

Aer.backends()

job = execute( qc, vector_sim )

ket = job.result().get_statevector()
for amplitude in ket:
    print(amplitude)

new_qc = QuantumCircuit( qr )

new_qc.initialize( ket, qr )

new_qc.draw(output='mpl')

cr = ClassicalRegister(2,'creg')

qc.add_register(cr)

qc.measure(qr[0],cr[0])
qc.measure(qr[1],cr[1])

qc.draw(output='mpl')

emulator = Aer.get_backend('qasm_simulator')

job = execute( qc, emulator, shots=8192 )

hist = job.result().get_counts()
print(hist)

from qiskit.tools.visualization import plot_histogram

plot_histogram( hist )

job = execute( qc, emulator, shots=10, memory=True )
samples = job.result().get_memory()
print(samples)

qubit = QuantumRegister(8)
bit = ClassicalRegister(8)
circuit = QuantumCircuit(qubit,bit)

circuit.x(qubit[7])
circuit.measure(qubit,bit) # this is a way to do all the qc.measure(qr8[j],cr8[j]) at once

execute( circuit, emulator, shots=8192 ).result().get_counts()

qc = QuantumCircuit(3)

qc.h(1)

qc.draw(output='mpl')

qc = QuantumCircuit(2,1)

qc.h(0)
qc.cx(0,1)
qc.measure(1,0)

qc.draw(output='mpl')

sub_circuit = QuantumCircuit(3, name='toggle_cx')
sub_circuit.cx(0,1)
sub_circuit.cx(1,2)
sub_circuit.cx(0,1)
sub_circuit.cx(1,2)

sub_circuit.draw(output='mpl')

toggle_cx = sub_circuit.to_instruction()

qr = QuantumRegister(4)
new_qc = QuantumCircuit(qr)

new_qc.append(toggle_cx, [qr[1],qr[2],qr[3]])

new_qc.draw(output='mpl')

IBMQ.load_account()

provider = IBMQ.get_provider(hub='ibm-q')
provider.backends()

for backend in provider.backends():
    print( backend.status() )

real_device = provider.get_backend('ibmq_16_melbourne')

properties = real_device.properties()
coupling_map = real_device.configuration().coupling_map

from qiskit.providers.aer import noise

noise_model = noise.device.basic_device_noise_model(properties)

qc = QuantumCircuit(2,2)
qc.x(1)
qc.measure(0,0)
qc.measure(1,1)

job = execute(qc, emulator, shots=1024, noise_model=noise_model,
                    coupling_map=coupling_map,
                    basis_gates=noise_model.basis_gates)

job.result().get_counts()