Qiskit Introduction

Qiskit is IBM’s system for writing quantum programs. The main website is Qiskit. The IBM Quantum Lab with the IBM Quantum Composer can be used to develop in the cloud.

IBM notes that Qiskit should be pronounced quiss-kit.

IBM provides a wide range of resouces to learn about quantum programming in their learn section.

In this text, we will be using the Python 3 library for qiskit. This allows us to make quantum circuits inside a python script. It is recommended you install the Anaconda version using these instructions. All examples given in this text are designed and tested under Anaconda with Qiskit installed.

Only a small part of the Qiskit library will be covered in this text. The full documentation is available from IBM.

You will need an IBM Quantum account to access the Composer and available Quantum Computers. Create an account with IBM Quantum.

Quantum Composer

The Quantum Composer is a simple visual took for building circuits. It is a drag-and-drop system for building Quantum Circuits. It is not as useful as the Qiskit libraries, but it is great for experimentation.

The quantum composer can be found at https://quantum-computing.ibm.com/composer.

IBM Quantum Composer Example

You can drag-and-drop gates onto the circuit from the left hand menu. The right sidebar shows the QASM code for the circuit. The bottom of the page shows the result probabilites and Q-Sphere representation. You can also switch either of the bottom windows to the State Vector.

The Quantum Compose is very nice for experimenting with simple gates.

Basic Circuits

Once all the libraries are installed, we can make quantum circuits directly in Python scripts.

We need to include the correct libraries to get access to Qiskit. The library to make circuits is called qiskit. We also need a simulator to run experiments. For now, we will just use BasicAer. The different ways to run experiments will be described later.

#Import the Libraries
from qiskit import *
#For simulations:
from qiskit import BasicAer

With your IBM account you can also access real Quantum Computers. You can set up one of the real systems using these examples. On the free plan, you only get a maximum of 10 minutes per month on a limited number of systems. We will only use the simulators for all examples.

Example of Available Computers

We next need to create a circuit. We ask Python to make us a circuit with three qubits and three classic bits. We will often have the same number of classic and quantum bits because we want to measure every bit. Sometimes we might not care about the final value of all our qubits. In these cases, we can ask for fewer classical bits.

#We need a circuit with
#3 Qubits and 3 classic bits
qc = QuantumCircuit(3,3)

We can then add gates to our circuit. All gates are methods of the circuit object. They take inputs telling which qubits the gate acts on. We will add an \(X\) gate to the qubit on wire 0.

#Add an X gate
qc.x(0)

There is a special object called a barrier. It does not change any values, just draws a line across the circuit. It is useful for viewing the circuit. We add a barrier then measure all the bits. The barrier makes it clear the quantum part of the circuit is over.

#We need to measure to see the results
#Barrier is just for visual
qc.barrier(range(0,3))
qc.measure(0,0)
qc.measure(1,1)
qc.measure(2,2)

Lastly, we need to see what we built. We can ask python to display the circuit as text.

#Print as text
print(qc.draw(output="text"))

The display we get is shown below.

Simple Circuit as Text

Once we make a circuit, we need to execute it. This can be done in multiple ways. For most examples, we will simulate running 2048 random tests through the circuit.

#Run our simulation!
#Create Simulator
backend_sim = BasicAer.get_backend('qasm_simulator')
#Run 2,048 tests
job_sim = execute(qc,backend_sim,shots=2048)
#Get the results
result_sim = job_sim.result()
#Show the count of each outcome
counts = result_sim.get_counts()
print(counts)

The result is printed.

{'001': 2048}

It tells us that all 2048 tests measured 001. This tells us that \(q_{0}\) was a 1 on every single test measurement. \(q_{1}\) was a 0 on every single test measurement \(q_{2}\) was a 0 on every single test measurement. Notice that the least significant bit \(q_0\) is shown at the top of the circuit and displayed at the end when output.

Visualization

There are a few methods to visualize a circuit. As shown above, we can output as plain text. This is the easiest method for testing. It gives you a quick way to see what your circuit looks like.

#Print as text
print(qc.draw(output="text"))

We can also ask Qiskit to output the code as LaTeX source. This is a great method for making slides, poster presentations, or submitting research papers to journals.

#Latex for Slides
print(qc.draw(output="latex_source"))

The output is raw LaTeX code you can put into a document or compile to PDF by itself.

% \documentclass[preview]{standalone}
% If the image is too large to fit on this documentclass use
\documentclass[draft]{beamer}
% img_width = 4, img_depth = 7
\usepackage[size=custom,height=10,width=16,scale=0.7]{beamerposter}
% instead and customize the height and width (in cm) to fit.
% Large images may run out of memory quickly.
% To fix this use the LuaLaTeX compiler, which dynamically
% allocates memory.
\usepackage[braket, qm]{qcircuit}
\usepackage{amsmath}
\pdfmapfile{+sansmathaccent.map}
% \usepackage[landscape]{geometry}
% Comment out the above line if using the beamer documentclass.
\begin{document}

\begin{equation*}
    \Qcircuit @C=1.0em @R=0.2em @!R {
        \lstick{ {q}_{0} :  } & \gate{\mathrm{X}} \barrier[0em]{2} & \qw & \meter & \qw & \qw & \qw & \qw\\
        \lstick{ {q}_{1} :  } & \qw & \qw & \qw & \meter & \qw & \qw & \qw\\
        \lstick{ {q}_{2} :  } & \qw & \qw & \qw & \qw & \meter & \qw & \qw\\
        \lstick{c:} & \lstick{/_{_{3}}} \cw & \cw & \dstick{_{_{0}}} \cw \cwx[-3] & \dstick{_{_{1}}} \cw \cwx[-2] & \dstick{_{_{2}}} \cw \cwx[-1] & \cw & \cw\\
    }
\end{equation*}

\end{document}

We can also ask Qiskit to use the matplot library to make an image for us. This makes a nice colorful PNG formatted image. It is harder to debug with PNG images because you need to keep reopening the image to see the circuit. Save this method until you are reasonable confident it will look correct from the text output.

#Matplot to make an image
qc.draw(output="mpl",filename="cicuit.png")

The image for our circuit is shown below.

PNG version of Circuit

Experiments

We can choose different methods for experimenting with our circuits.

Most the the time, we will use the qasm_simulator. This simulates multiple runs of an imaginary quantum computer and only gives us back the measured results. This is most similar to using a real quantum computer. We only get the measured results at the end.

#Run our simulation!
#Create Simulator
backend_sim = BasicAer.get_backend('qasm_simulator')
#Run 2,048 tests
job_sim = execute(qc,backend_sim,shots=2048)
#Get the results
result_sim = job_sim.result()
#Show the count of each outcome
counts = result_sim.get_counts()
print(counts)

The output is just the number of tests that measured each result {'001': 2048}.

We can also ask for the state vector using a different simulator.

#Use a State Vector Back end
backend = BasicAer.get_backend('statevector_simulator')
job=execute(qc,backend)
results = job.result()
#Get the state vector to 3 decminal places
SV=results.get_statevector(qc,decimals=3)
print(SV)

This simulator can give us the full state vector as a result. Look closely at where the \(1\) result appear on these results.

[0.+0.j 1.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j]

The state vector results are ordered as follows:

[ #Where (q_2, q_1, q_0)
    0.+0.j (000) 
    1.+0.j (001)
    0.+0.j (010)
    0.+0.j (011)
    0.+0.j (100)
    0.+0.j (101)
    0.+0.j (110)
    0.+0.j (111)
]

This is very useful for looking at the theory. It is not something we could measure in a real quantum computer. It also tends to be a slower simulator because it needs to track the entire state vector.

All experiments in this text will use one of the two simulators. Save your limited free time for experiments you really want to run, not examples from these notes.

Histograms

We can ask qiskit to generate an image of our Histogram from the counts we got out of our experiment.

We need to include an additional command from the visualization package.

#For the Histogram
from qiskit.visualization import plot_histogram

Then we can ask it to generate a histogram from the counts. We can then ask the histogram to be saved as an image.

fig = plot_histogram(counts)
fig.savefig("histogram.png")

The figure our circuit generated is shown below.

Histogram Example

You can get counts from either simulator to generate the histogram.

Bloch Spheres

We can also ask qiskit to draw the Bloch Spheres for us. We just need to provide it with our state vector. Notice that we need to include a visualizations package to get this feature. If you measure your qubits, this will be reflected in the Bloch Sphere. If you want to see the superposition, remember not to measure and collapse the system.

#Import the Libraries
from qiskit import *
#For simulations:
from qiskit import BasicAer
#For the Bloch Sphere
from qiskit.visualization import plot_bloch_multivector

#Make a trivial Bloch Sphere

qc = QuantumCircuit(1,1)
qc.h(0)

#Use a State Vector Back end
backend = BasicAer.get_backend('statevector_simulator')
job=execute(qc,backend)
results = job.result()
#Get the state vector to 3 decminal places
SV=results.get_statevector(qc,decimals=3)

fig = plot_bloch_multivector(SV)
fig.savefig("bloch1.png")

If we apply this to the examples we have been working with previously, we can see all three Qubits represented.

3 Qubit System from above

QSphere

When a system is in a coherent superposition state, we cannot draw the Bloch Sphere. There is no one sphere that shows all possible outputs. For example, the following system has 4 possible states.

qc = QuantumCircuit(2,2)
qc.h(0)
qc.h(1)
qc.cx(0,1)

The circuit is shown below.

Four cases of a CX using H

We cannot show the Bloch Sphere for this state, but we can display the quantum state information using the qsphere visualizer.

The qsphere visualizer show all possible outcomes. The size of the points is proportional to the probability. The color represents the phase.

We need to import the visualization library.

from qiskit.visualization import plot_state_qsphere

Then we can ask it to generate the image.

fig = plot_state_qsphere(SV)
fig.savefig(filename)

The image we create is shown below.

Q-Sphere Example