Building Your Own Quantum Circuits in Python (With Colorful Diagrams) | by Rishabh Anand | Towards Data Science

For a crash course on Quantum Computing, do check out the previous article.
TLDR: Here, I talk about Qiskit, an open-source Python module for building quantum circuits and simulating operations on Qubits. We’ll look through sample code and then move on to an in-depth explanation of what the code does with very intuitive, colorful diagrams!
In my previous article, I mentioned that models can be built to simulate processes of interest in the universe. In order to build these models, we make use of quantum circuits, for which we need a module to manipulate and run quantum programs on quantum devices.
In this article, we’ll look at Qiskit — a Python module that makes quantum prototyping a stress-free task owing to its simple and easily-readable syntax. Qiskit was developed by IBM Research to make it easier for anyone to interface with a Quantum Computer.
In my previous article, I spoke about the Hadamard, Controlled-NOT and the Pauli-X Gates. The Hadamard Gate takes in a single Qubit and outputs a bit with an equal probability of becoming a 1 or 0.
The Controlled-NOT (CNOT) Gate takes in 2 Qubits and flips a Qubit from one state of ket 0 to ket 1 only if the control Qubit is ket 1. Otherwise, it leaves it unchanged.
Now that we have recapped what the gates do, we can finally go on to defining our own circuit and simulating it to get the final state of the Qubits and bits!
Note: the Pauli X and Y Gates are not covered in this tutorial.
Building your own Quantum Circuits is easy because of Qiskit’s great documentation and resources. Before moving on to something complex, let’s run through the basics of building a circuit from scratch. Here, we’ll decompose the circuit code into digestible parts. Let’s begin!
Before writing Quantum Circuits, we need to install Qiskit. To do so, you can simply install the package via pip:
$ pip install qiskit
To test out your installation, open up the Python console and type in import qiskit as qk. If it runs without any errors, you’re good to go!
Note: If you run into any problems, the Qiskit GitHub Issues page has the solutions to most beginner problems. However, if you still have any burning questions, feel free to drop a comment down below or contact me via Twitter or LinkedIn.
Now that we have Qiskit configured, let’s work some Qubits and Bits. To instantiate Qubits and Bits in Qiskit, we can use the QuantumRegister and ClassicalRegister objects to create them. Here, we create 2 of each type:
The registers hold a record of the Qubits and Bits that are being used by our circuit. Having the Qubits and Bits in our hands, let’s construct our circuit:
Let’s add some gates into our circuit to manipulate and work with our Qubits and Bits and finally measure the final Qubits:
Let’s visualize our circuit so we have a rough idea of the transformations applied to our Qubits:
If we print this circuit to console, we can see a circuit diagram printed for convenience purposes (Thanks IBM!). It should look something like this:
Congrats! You have just built a Quantum Circuit. Now that we have that in place, let’s simulate the circuit and run it using a simulator. Qiskit provides components that have various simulator backends that manipulate the Qubits in different ways. The components are Aer, Ignis, Terra, and Aqua.
To simulate the circuit, let’s use Aer’s QasmSimulator that aims to mimic a real Quantum Device. To use Aer’s simulator, we can simply create a simulation job and collect the results at the end. The Qasm Simulator runs the circuit for 1024 times (by default).
‘Qasm Simulator’ sounds like something out of a video game. Don’t worry if it sounds intimidating. All it does is create a classical simulation on your local machine to mimic what would happen in an actual quantum machine. Invariably, it is a pseudo-simulation, as the Qiskit documentation calls it.
In the end, we can see that there is a 0.481 (492/1024) probability that the circuit outputs ‘00’ as the bitstring while there is a 0.519 (532/1024) probability that the output bitstring is ‘11’.
This way, by simulating our circuits, we can convert this bitstring into their decimal or hexadecimal counterparts and see the values they give out.
After doing all this, you may ask, what’s the point of all this? We have some idea on how to build circuits and what the individual components do. How do they go together? How do they all fit in? Those are valid questions.
Quantum Computing deals with probabilities ie. the chance of an event occurring. For this, we assume that the event is completely random. Quantum Circuits enable us to take Qubits, put them into superpositions, measure them and get the final outcome.
To illustrate one such application of complete randomness without bias, let’s build a random number generator! This way, we can see the power of Superposition and how the final result is a completely random number without any one-sidedness.
Additionally, instead of running it on a local simulation that is classical in nature (cannot reflect the sheer awesomeness of a quantum computer), let’s hook up our circuit and run it on the actual IBM Quantum Computers located nearest to you!
Before we perform any Quantum magic, we need to connect to the IBM Quantum Computer nearest to your region. To do so, visit the IBM Q website and login or create an account if you’re new.
When logged in, click the profile icon located at the top right-hand corner. Go to the My Account page and go to the Advanced tab. There, you’ll see an area for your API Token. If you don’t have one go ahead and generate one.
We can finally start writing a client-side circuit that interfaces with the IBM Q Machine closest to you, shown on the panel to the left.
For this tutorial, I’ll be using the ibmqx4 system which can hold and manipulate a maximum of 4 Qubits. You might see other available machines on your dashboard depending on your location so don’t worry if you don’t see mine. Choose the one you like (pick the coolest sounding one 😎).
Next up, let’s connect to the quantum computer using the following lines of code:
Before we build a circuit, let’s create a record of Qubits and Classical Bits for our random number generator that generates numbers between 0 and 7 (n=3).
Now, we need to construct a circuit that returns a Superposition of a Qubit and collapses it to a bitstring that represents an integer between 0 and 2^n — 1. To do that, we can apply the Hadamard Gate on the 3 Qubits to put them all in a Superposition with a 50–50 chance of being a 1 or 0.
If we visualize this circuit, it’ll look like this:
Now, it’s time for the exciting part. Let’s instantiate the Quantum Backend that’s going to run our circuit. Remember you used the Qasm Simulator up above? In the same way, my ibmqx4 machine is the simulator here (here, it’s the real deal!). Let’s connect our backend simulator:
Shots here refers to the number of times the circuit is being run. Here we only want 1 randomly generated number, so we set it to 1.
Note: You can play around with the number and set it to something like 1000 to see a histogram of the generated numbers over the 1000 runs.
Next up is the main event function the runs a job on the ibmqx4 Quantum Computer and returns a completely random number between 0 and 7:
Now, it’s the moment of truth. Let’s run the complete circuit on our Quantum Computer allocated to us:
The code here will take a few minutes to run and took 3 credits from my account (you’re given 15, to begin with). When I ran the circuit, the final output was 6.
With that, congrats for coming this far! You’ve just built a Quantum Circuit. Let’s revisit the steps to successfully run a quantum program:
Note: The full code for the Quantum Random Number Generator can be found here.
You’ve just built a Quantum Circuit! That’s awesome! You are taking one step forward on your journey to becoming an expert. By thinking of simple processes that require manipulation of bits and converting the problem into one that can be solved by a Quantum Computer, it’s good practice to getting a firm grasp over the concepts.
Learning about the principles behind Quantum Computing was surely very demanding! There’s so much theory floating around that having a grounded understanding of what’s going on is very important.
Learning about Qiskit was really fun and the documentation and resources provided by IBM Research went a long way in helping me understand what’s going on. Of all the quantum processors including Google Cirq and QuTiP, Qiskit was the most enjoyable to learn and implement circuits with.
Quantum Computing is gaining pace at a promising rate. Researchers are making progress in democratizing the usage of Quantum Computers to perform tasks and tackle problems that were once considered impossible to solve.
However, Quantum Computing theory has not reached a stage where it is fully accessible to everyone. It may be due to the clunkiness of Quantum Computers, the colossal facilities and the enormous amount of resources that are needed to keep the field active.
Notwithstanding this, hopefully, this article has given some insight into what’s going on in the field and has sparked some interest in you! If you have any questions or want to talk about anything, you can catch me blatantly procrastinating on Twitter or LinkedIn.
My next article will probably be focussed on the mathematics behind Quantum Computing and how the different gates and logic manipulate the Qubits. We’ll be doing a rundown of the quantum algorithms and how they go about doing what they do!
Till then I’ll see you in the next one!
Original article by Rishabh Anand
Do check out my other articles on technology and Machine Learning, and reviews of up-and-coming software innovations.