Our example uses a Bell state circuit to illustrate all the fundamental Qiskit basics.
Sample program output,
counts
are randomized each time.First we take the quantum state vector immediately after the input.
We understand that the first element of
input:
state:
Statevector([1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j],
dims=(2, 2))
probs:
[1. 0. 0. 0.]
Statevector
is , and has probability of 1.0.Next we take the state after a Hadamard gate on the first qubit:
We now understand that the second element of the
h:
state:
Statevector([0.70710678+0.j, 0.70710678+0.j, 0. +0.j,
0. +0.j],
dims=(2, 2))
probs:
[0.5 0.5 0. 0. ]
Statevector
is , and now we have a 50/50 propabability split for the first bit.Then we apply the CNOT gate:
which leaves us with the final .
cx:
state:
Statevector([0.70710678+0.j, 0. +0.j, 0. +0.j,
0.70710678+0.j],
dims=(2, 2))
probs:
[0.5 0. 0. 0.5]
Then we print the circuit a bit:
qc without measure:
┌───┐
q_0: ┤ H ├──■──
└───┘┌─┴─┐
q_1: ─────┤ X ├
└───┘
c: 2/══════════
qc with measure:
┌───┐ ┌─┐
q_0: ┤ H ├──■──┤M├───
└───┘┌─┴─┐└╥┘┌─┐
q_1: ─────┤ X ├─╫─┤M├
└───┘ ║ └╥┘
c: 2/═══════════╩══╩═
0 1
qasm:
OPENQASM 2.0;
include "qelib1.inc";
qreg q[2];
creg c[2];
h q[0];
cx q[0],q[1];
measure q[0] -> c[0];
measure q[1] -> c[1];
And finally we compile the circuit and do some sample measurements:
qct:
┌───┐ ┌─┐
q_0: ┤ H ├──■──┤M├───
└───┘┌─┴─┐└╥┘┌─┐
q_1: ─────┤ X ├─╫─┤M├
└───┘ ║ └╥┘
c: 2/═══════════╩══╩═
0 1
counts={'11': 484, '00': 516}
counts={'11': 493, '00': 507}
qiskit/hello.py
#!/usr/bin/env python
from qiskit import QuantumCircuit, transpile
from qiskit_aer import Aer, AerSimulator
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_histogram
def print_state(qc):
# Get state vector
state = Aer.get_backend('statevector_simulator').run(qc, shots=1).result().get_statevector()
print('state:')
print(state)
probs = state.probabilities()
print('probs:')
print(probs)
qc = QuantumCircuit(2, 2)
print('input:')
print_state(qc)
print()
qc.h(0)
print('h:')
print_state(qc)
print()
qc.cx(0, 1)
print('cx:')
print_state(qc)
print()
print('qc without measure:')
print(qc)
# Add measures and simulate some runs.
# Can't get state properly with measures.
qc.measure([0, 1], [0, 1])
# Print the circuit in a bunch of ways.
print('qc with measure:')
print(qc)
print('qasm:')
print(qc.qasm())
# Works but slows things down.
#qc.draw('mpl', filename='hello_qc.svg')
# Compile the circuit, and simulat it.
simulator = AerSimulator()
qct = transpile(qc, simulator)
# No changes in this specific case, as the simulator likely supports all gates.
print('qct:')
print(qct)
job = simulator.run(qc, shots=1000)
result = job.result()
counts = result.get_counts(qc)
print(f'{counts=}')
job = simulator.run(qc, shots=1000)
result = job.result()
counts = result.get_counts(qc)
print(f'{counts=}')
#plot_histogram(counts, filename='hello_hist.svg')