Introduction
Having laid out some mathematical foundations in the
previous part
, we will proceed to discussing quantum gates and circuits in depth here. As usual, we will drive home the theories with worked examples from (qiskit and/or cirq code.
Prerequisite
Understanding quantum gates and circuits will be greatly aided by the knowledge of classical gates (AND, OR, NOT, XOR and the universal gates: NAND and NOR). Also, some familiarity with the Python programming language will help you understand qiskit and/or cirq code.
Classical & Quantum gates
A classical computer, possibly the one you're reading this with, is a sophisticated engineering piece, no doubt. However, the underlying "magic" comprises logic gates. The National Institute of Standards and Technology (NIST) gives this incredible analogical description of classical computers in relation to logic gates (
Traditional computers are like microscopic cities. The roads of these cities are wires with electricity coursing through them. These roads have lots of gates, known as logic gates, which enable computers to do their job. Like physical gates that allow or block cars, logic gates allow or block electricity. Electricity that goes through the gates represents a “1” of digital data, and blocked electricity is a “0.”
When you pick up a motherboard, for instance, you may not see the said gates as they are made of tiny transistors (in modern systems, MOSFETs) in specific combinations. Also, the and referred to in the analogy mean low and high voltage ranges, respectively. Their actual voltage values depend on the hardware.
All schematics were written in and rendered by
@schemd/core
. Check it out.
Logic Gates refresher
Since we will be realizing some classical circuits using quantum gates, it's necessary to get familiar with common logic gates.
NOT () Gate
This gate takes a single classical bit and flips it. For instance, if is the input to this gate, will be seen in the output, vice versa. Just like a flip of a coin. Below, you find both the IEEE symbol of the gate and its truth table:
| in | out |
|---|---|
| 0 | 1 |
| 1 | 0 |
AND () Gate
Borrowing NIST's analogy again (
One kind of logic gate, known as the AND gate, could, for example, quickly determine whether two people agree to a business deal. It takes in two bits of information, and generates a 1 if both incoming bits are 1s. So, if both business people say “yes” (1) to the deal, the AND gate will output 1. If one or both say “no” (0), the AND gate generates a 0 or a no.
From the analogy, the gate usually takes 2 bits (2 people who want to deal). It has the truth table and symbol shown below.
| 0 | 0 | 0 |
| 1 | 0 | 0 |
| 0 | 1 | 0 |
| 1 | 1 | 1 |
OR () Gate
This logic gate also takes 2 bits and functions based on the analogy that if two founders are deciding whether to launch a product, OR says “launch if at least one says yes.” Only when both say no does the result become no. Its symbol and truth table are as follows:
| 0 | 0 | 0 |
| 1 | 0 | 1 |
| 0 | 1 | 1 |
| 1 | 1 | 1 |
XOR () Gate
Exclusive OR (XOR) gate is a core part of an adder circuit and, in algorithms, we use it for bitwise manipulation in problems including finding a number that does not have a duplicate in an array. For a 2-bit input, its output is if and only if the bits are of opposite values. Its truth table sheds more light on this:
| 0 | 0 | 0 |
| 1 | 0 | 1 |
| 0 | 1 | 1 |
| 1 | 1 | 0 |
XOR gate's symbol is as follows:
NAND
NAND (Not AND) is one of the universal gates in digital circuits; the other is NOR (Not OR). It is universal because, with only this single gate, all other gates and circuits can be designed. Its behavior is simply as its name sounds: invert the output of an AND gate!
| 0 | 0 | 1 |
| 1 | 0 | 1 |
| 0 | 1 | 1 |
| 1 | 1 | 0 |
NAND gate's symbol is as follows:
NOR
NOR does the same thing to an OR gate: it inverts its output. Therefore, it only returns when both inputs are . Like NAND, it is universal.
| 0 | 0 | 1 |
| 1 | 0 | 0 |
| 0 | 1 | 0 |
| 1 | 1 | 0 |
Quantum Gates
Just as classical gates are the foundations of classical computers, quantum gates are those of quantum computers. They make it possible for quantum algorithms to run. The fundamental difference between them is that classical gates work on bits whose state is either or (and not both at the same time), whereas quantum gates operate on qubits where and can be superposed and even entangled (this will be discussed in the next part).
Quantum gates can either be single-qubit or multiple-qubit gates (
We will explore the X-, Y-, Z-, H-, S- and T- gates as examples of single-qubit gates. Though there are many multiple-qubit gates, we will only discuss the CNOT gate here. The reason is that the set of H-, CNOT, and T- gates is universal and can approximate any quantum computation to arbitrary precision (
X-Gate
This is the quantum equivalent of the classical NOT gate. In the quantum world, it is called the Pauli X-gate. Just like its classical counterpart, this gate flips its incoming qubit. If is the input, will be the output, vice versa. Mathematically, this gate can be expressed, in matrix form, as:
Now, let's look at the behaviour of this gate on a state, .
If
Then, in matrix form,
Feeding this into the Pauli X-gate, we have:
It got flipped!
Therefore, it can be demonstrated that if we feed ( in matrix form) into an X-gate, we will have:
In the same vein, feeding ( in matrix form) into the gate gives:
The truth table can easily be built from here:
| Input | Output |
|---|---|
Y-Gate
The Pauli Y-gate also flips a qubit. However, unlike the X-gate, it adds a phase to the result. Its matrix is:
Let's feed the same arbitrary state, , into it:
The amplitudes have been swapped, but they now carry the phases and . From here, feeding into the gate gives:
In the same vein, feeding into it gives:
The truth table can be built from here:
| Input | Output |
|---|---|
You may notice that and still give the same measurement probabilities as and , respectively, in the computational basis. This is because an overall phase does not affect the measurement probabilities. However, when the qubit is in a superposition, a phase on one part of the state matters. We will see this with the next gate.
Z-Gate
The Pauli Z-gate is also called the phase-flip gate. Unlike the X- and Y- gates, it does not swap the amplitudes. Instead, it changes the sign of the amplitude. Its matrix is:
Feeding our arbitrary state into it, we have:
For the basis states:
| Input | Output |
|---|---|
You may ask: if and produce the same measurement probability, what exactly changed? When is by itself, the minus sign is a global phase and cannot be observed. However, in a superposition, it changes the relative phase between the amplitudes. For example:
Recall that and . Therefore, . Both states have a probability of returning or when measured in the computational basis. They are, however, different states and behave differently when another gate, such as H, acts on them.
H-Gate
The Hadamard gate, commonly written as H, takes a basis state and puts it in an equal superposition. Its matrix is:
Let's first see its action on our arbitrary qubit:
Now, if is fed into the gate:
In the same vein:
From , the probabilities of measuring and are:
and
Before moving on, there is another interesting property of this gate. Applying H twice returns the original state. Let's confirm that from its matrix:
Therefore, . This also means that and . The gate takes us from the computational basis, , to the Hadamard basis, , and vice versa.
S-Gate
The S-gate is another phase gate. It leaves unchanged but adds a phase of to . Its matrix is:
Applying it to our arbitrary state gives:
Recall from Euler's formula that . Therefore:
The truth table can be built from here:
| Input | Output |
|---|---|
Also, applying S twice produces the Z-gate. From its matrix:
T-Gate
The T-gate works in a similar fashion to the S-gate. It is also called the gate, though the relative phase it adds to is . Its matrix is:
Recall Euler's formula, . Substituting , we have:
Now, let's apply T to our arbitrary state:
| Input | Output |
|---|---|
From here, applying T twice should give S. Let's confirm this from its matrix:
CNOT Gate
All the gates discussed thus far take a single qubit. The Controlled NOT (CNOT or CX) gate takes two: a control and a target. If the control is , the target remains unchanged. However, if the control is , an X-gate is applied to the target. The control itself does not change.
If we represent the control with and the target with , the operation can be written as:
where is XOR. Recall that XOR returns only when its two inputs differ. In the computational basis ordered as , the matrix of the gate is:
Let's work through all four computational basis states:
- : the control is , so the target remains ;
- : the control is , so the target remains ;
- : the control is , so the target flips from to ; and
- : the control is , so the target flips from to .
| Input | Output |
|---|---|
Now, what happens if the control is in a superposition? Let's consider two qubits initialized to . First, we apply H to the first qubit while leaving the second unchanged:
From here, we apply CNOT using the first qubit as the control:
From here, both qubits are in one of the Bell states. Notice that we can no longer separate it into an independent state for the first qubit and another for the second. This is regarded as entanglement. We will properly unpack it in the next part.
Worked examples
Q1:
Design a circuit that rearranges three arbitrary single-qubit states in this manner:
Solution
Given:
where the subscripts represent the wire positions.
To solve this, let's compare the initial and final positions of the states:
| State | Initial wire | Final wire |
|---|---|---|
From the table:
Looking at the movements together, we see that they form a cycle. A SWAP gate exchanges the states in two positions, so we can complete this cycle with two of them.
First, swap the states in positions and :
The states are now in the order . We only need to move to the first position. So, let's swap the states in positions and :
The required circuit is:
Before going to the check, let's show how a SWAP gate can be built with three CNOT gates. Suppose the first and second qubits contain the basis values and , respectively. The gates are applied in this order:
The first subscript denotes the control qubit while the second denotes the target. Also, recall these properties of XOR:
For the first CNOT, is the control. It remains unchanged while the target, , becomes :
For the second CNOT, is now the control and is the target. The new target is:
Therefore:
For the last CNOT, is the control and is the target. The target becomes:
So:
We started with and ended with . The two values have been swapped! We used the basis values and to make the calculation easier. Since quantum gates are linear, the same result holds for arbitrary single-qubit states, including states in superposition.
Check
This is a Google Cirq code for checking the CNOT construction and the final permutation:
import cirq
import numpy as np
# Define three qubits
q1, q2, q3 = cirq.LineQubit.range(3)
# Build the circuit with two SWAP gates
swap_circuit = cirq.Circuit(
cirq.SWAP(q2, q3),
cirq.SWAP(q1, q2),
)
# Build the same circuit using CNOT gates
decomposed_circuit = cirq.Circuit(
# SWAP q2 and q3
cirq.CNOT(q2, q3),
cirq.CNOT(q3, q2),
cirq.CNOT(q2, q3),
# SWAP q1 and q2
cirq.CNOT(q1, q2),
cirq.CNOT(q2, q1),
cirq.CNOT(q1, q2),
)
# Confirm that both circuits have the same unitary matrix
np.testing.assert_allclose(
cirq.unitary(swap_circuit),
cirq.unitary(decomposed_circuit),
atol=1e-8,
)
# Define arbitrary single-qubit states
psi = np.array([1 + 1j, 2], dtype=complex)
phi = np.array([1, -1j], dtype=complex)
eta = np.array([2 - 1j, 1], dtype=complex)
# Normalize the states
psi = psi / np.linalg.norm(psi)
phi = phi / np.linalg.norm(phi)
eta = eta / np.linalg.norm(eta)
# Form |psi>|phi>|eta> and the expected |eta>|psi>|phi>
initial_state = np.kron(np.kron(psi, phi), eta)
expected_state = np.kron(np.kron(eta, psi), phi)
# Simulate the SWAP circuit
result = cirq.Simulator().simulate(
swap_circuit,
qubit_order=[q1, q2, q3],
initial_state=initial_state,
)
# Confirm the final state
np.testing.assert_allclose(
result.final_state_vector,
expected_state,
atol=1e-7,
)
print(swap_circuit)
print("The three-qubit permutation is correct!")
Q2:
Find the unitary matrix represented by each of the following two-qubit circuits:
(a) Apply the Hadamard gate to while leaving unchanged.
(b) Leave unchanged while applying the Hadamard gate to .
Solution
Before going into the two circuits, let's lay out some foundations.
There are qubits in each circuit. Recall that an -qubit gate has a matrix. Therefore, the dimension of each matrix here is:
From the circuits, the matrices involved are the Hadamard matrix, , and the identity matrix, :
Also, recall that the tensor product of:
and another matrix, , is:
(a) Hadamard on
In circuit (a), is applied to while remains unchanged. The identity matrix, , represents the unchanged qubit. Since comes before , the overall operation is:
Now, substitute the matrices:
(b) Hadamard on
In circuit (b), remains unchanged while is applied to . This time, comes before . Therefore, the operation is:
Substitute both matrices:
Check
This is another cirq code for checking both matrices:
import cirq
import numpy as np
# Define the two qubits
x1, x2 = cirq.LineQubit.range(2)
# Circuit (a): H on x1 and I on x2
circuit_a = cirq.Circuit(
cirq.H(x1),
cirq.I(x2),
)
# Circuit (b): I on x1 and H on x2
circuit_b = cirq.Circuit(
cirq.I(x1),
cirq.H(x2),
)
# Define the matrix obtained for circuit (a)
expected_a = np.array(
[
[1, 0, 1, 0],
[0, 1, 0, 1],
[1, 0, -1, 0],
[0, 1, 0, -1],
],
dtype=complex,
) / np.sqrt(2)
# Define the matrix obtained for circuit (b)
expected_b = np.array(
[
[1, 1, 0, 0],
[1, -1, 0, 0],
[0, 0, 1, 1],
[0, 0, 1, -1],
],
dtype=complex,
) / np.sqrt(2)
# Let Cirq obtain the matrices directly from the circuits
unitary_a = cirq.unitary(circuit_a)
unitary_b = cirq.unitary(circuit_b)
# Compare Cirq's matrices with our answers
np.testing.assert_allclose(unitary_a, expected_a, atol=1e-8)
np.testing.assert_allclose(unitary_b, expected_b, atol=1e-8)
print("H tensor I:")
print(np.round(unitary_a, 3))
print("\nI tensor H:")
print(np.round(unitary_b, 3))
Outro
Enjoyed this article? I'm a Software Engineer and Technical Writer actively seeking new opportunities to impact and learn, particularly in areas related to web security, finance, healthcare, and education. If you think my expertise aligns with your team's needs, let's chat! You can find me on LinkedIn and X . I am also an email away.