Path: blob/main/notebooks/ch-algorithms/grover.ipynb
3328 views
Grover’s Algorithm
In this section, we introduce Grover's algorithm and how it can be used to solve unstructured search problems. We then implement Grover's algorithm on actual problems using Qiskit, run on a simulator and an actual device.
Contents
Introduction 1.1 Algorithm overview 1.2 Grover Step by step 1.3 State preparation 1.4 The Oracle 1.5 The diffusion operator
Example: 2 Qubits 2.1 Simulation 2.2 Device
Example: 3 Qubits 3.1 Simulation 3.2 Device
Problems 4.1 Solving Sudoku using Grover's Algorithm 4.2 Solving the triangle problem using Grover's Algorithm
1. Introduction
You have likely heard that one of the many advantages a quantum computer has over a classical computer is its superior speed searching databases. Grover's algorithm demonstrates this capability. This algorithm can speed up an unstructured search problem quadratically, but its uses extend beyond that; it can serve as a general trick or subroutine to obtain quadratic run time improvements for a variety of other algorithms. This is called the amplitude amplification trick.
Suppose you are given a large list of items. Among these items there is one item with a unique property that we wish to locate; we will call this one the winner . Think of each item in the list as a box of a particular color. Say all items in the list are gray except the winner , which is purple.
To find the purple box -- the marked item -- using classical computation, one would have to check on average of these boxes, and in the worst case, all of them. On a quantum computer, however, we can find the marked item in roughly steps with Grover's amplitude amplification trick. A quadratic speedup is indeed a substantial time-saver for finding marked items in long lists. Additionally, the algorithm does not use the list's internal structure, which makes it generic; this is why it immediately provides a quadratic quantum speed-up for many classical problems.
1.1 Algorithm Overview
Grover's algorithm consists of three main algorithms steps: state preparation, the oracle, and the diffusion operator. The state preparation is where we create the search space, which is all possible cases the answer could take. In the list example we mentioned above, the search space would be all the items of that list. The oracle is what marks the correct answer, or answers we are looking for, and the diffusion operator magnifies these answers so they can stand out and be measured at the end of the algorithm.
So how does the algorithm work? Before looking at the list of items, we have no idea where the marked item is. Therefore, any guess of its location is as good as any other, which can be expressed in terms of a uniform superposition:
If at this point we were to measure in the standard basis , this superposition would collapse, according to the fifth quantum law, to any one of the basis states with the same probability of . Our chances of guessing the right value is therefore in , as could be expected. Hence, on average we would need to try about times to guess the correct item.
Enter the procedure called amplitude amplification, which is how a quantum computer significantly enhances this probability. This procedure stretches out (amplifies) the amplitude of the marked item, which shrinks the other items' amplitude, so that measuring the final state will return the right item with near-certainty.
This algorithm has a nice geometrical interpretation in terms of two reflections, which generate a rotation in a two-dimensional plane. The only two special states we need to consider are the winner and the uniform superposition . These two vectors span a two-dimensional plane in the vector space ParseError: KaTeX parse error: Undefined control sequence: \cssId at position 1: \̲c̲s̲s̲I̲d̲{vspace}{\mathb…. They are not quite perpendicular because occurs in the superposition with amplitude as well. We can, however, introduce an additional state that is in the span of these two vectors, which is perpendicular to and is obtained from by removing and rescaling.
Step 1: The amplitude amplification procedure starts out in the uniform superposition , which is easily constructed from or using another symmetric entangled states.
The left graphic corresponds to the two-dimensional plane spanned by perpendicular vectors and which allows to express the initial state as where . The right graphic is a bar graph of the amplitudes of the state .
Step 2: We apply the oracle reflection to the state .
Geometrically this corresponds to a reflection of the state about . This transformation means that the amplitude in front of the state becomes negative, which in turn means that the average amplitude (indicated by a dashed line) has been lowered.
Step 3: We now apply an additional reflection () about the state : . This transformation maps the state to and completes the transformation.
Two reflections always correspond to a rotation. The transformation rotates the initial state closer towards the winner . The action of the reflection in the amplitude bar diagram can be understood as a reflection about the average amplitude. Since the average amplitude has been lowered by the first reflection, this transformation boosts the negative amplitude of to roughly three times its original value, while it decreases the other amplitudes. We then go to step 2 to repeat the application. This procedure will be repeated several times to zero in on the winner.
After steps we will be in the state where:
How many times do we need to apply the rotation? It turns out that roughly rotations suffice. This becomes clear when looking at the amplitudes of the state . We can see that the amplitude of grows linearly with the number of applications . However, since we are dealing with amplitudes and not probabilities, the vector space's dimension enters as a square root. Therefore it is the amplitude, and not just the probability, that is being amplified in this procedure.
To calculate the number of rotations we need to know the size of the search space and the number of answers we are looking for. The get the optimal number of iterations , we can follow the equation:
Where N is the size of the search space and m is the number of answers we want.
1.2 Grover Step by Step
Now that we went through how Grover's algorithm actually work, let's go a little bit in depth about the construction and different cases for each of its components.
1.2.1 Preparing the Search Space
The first step of Grover's algorithm is the initial state preparation. As we just mentioned, the search space is all possible values we need to search through to find the answer we want. For the examples in this textbook, our 'database' is comprised of all the possible computational basis states our qubits can be in. For example, if we have 3 qubits, our list is the states (i.e the states ). So, in this case the size of our search space will be .
In some cases, if we know the range within the search space where the answer is guaranteed to be, we can eliminate the redundant basis out of our search space to speed up the algorithm and decrease the size of the circuit. Generally speaking, we can prepare our state using any symmetric states, such as GHZ-states, W-states, or Dicke-states.
For example, if we are trying to solve a problem with one answer using 4 qubits, and we prepare our state using the Hadamard gate (i.e. forming the Hilbert Space), N will be 16. But, if we know that the answer is within states when only one qubit has the value of 1 at any time, we can then use the W-state instead of the full Hilbert space to prepare our states. Doing that, decreased the size of the search space from 16 to 4 and the number of optimal iterations from 3 to 1.
1.2.2 Creating the Oracle
The second and most important step of Grover’s algorithm is the oracle. Oracles add a negative phase to the solution states so they can standout from the rest and be measured. I.e. for any state in the computational basis:
This oracle will be a diagonal matrix, where the entry that correspond to the marked item will have a negative phase. For example, if we have three qubits and , our oracle will have the matrix:
What makes Grover’s algorithm so powerful is how easy it is to convert a problem to an oracle of this form. There are many computational problems in which it is difficult to find a solution, but relatively easy to verify a solution. For example, we can easily verify a solution to a sudoku by checking all the rules are satisfied. For these problems, we can create a function that takes a proposed solution , and returns if is not a solution () and for a valid solution (). Our oracle can then be described as:
and the oracle's matrix will be a diagonal matrix of the form:
Detail
If we have our classical function , we can convert it to a reversible circuit of the form:
If we initialize the 'output' qubit in the state , the phase kickback effect turns this into a Grover oracle (similar to the workings of the Deutsch-Jozsa oracle):
We then ignore the auxiliary () qubit.
1.2.3 The Diffusion Operator
Finally, after the oracle has marked the correct answer by making it negative, the last step of Grover's algorithm which is the diffusion operator.
The construction of the diffusion operator depends on what we decide to use to prepare our initial states. Generally, the diffusion operator has the following construction.
For the next part of this chapter, we will create example oracles where we know beforehand, and not worry ourselves with whether these oracles are useful or not. At the end of the chapter, we will cover a short example where we create an oracle to solve a problem (sudoku) and a famous graph problem, the triangle finding problem.
2. Example: 2 Qubits
Let's first have a look at the case of Grover's algorithm for which is realized with 2 qubits. In this particular case, only one rotation is required to rotate the initial state to the winner [3]:
Following the above introduction, in the case we have
After steps, we have
where
In order to obtain we need , which with inserted above results to . This implies that after rotation the searched element is found.
We will now follow through an example using a specific oracle.
Oracle for
Let's look at the case . The oracle in this case acts as follows:
or:
which you may recognise as the controlled-Z gate. Thus, for this example, our oracle is simply the controlled-Z gate:
Reflection
In order to complete the circuit we need to implement the additional reflection . Since this is a reflection about , we want to add a negative phase to every state orthogonal to .
One way we can do this is to use the operation that transforms the state , which we already know is the Hadamard gate applied to each qubit:
Then we apply a circuit that adds a negative phase to the states orthogonal to :
i.e. the signs of each state are flipped except for . As can easily be verified, one way of implementing is the following circuit:
Finally, we do the operation that transforms the state (the H-gate again):
The complete circuit for looks like this:
Full Circuit for
Since in the particular case of only one rotation is required we can combine the above components to build the full circuit for Grover's algorithm for the case :
2.1 Qiskit Implementation
We now implement Grover's algorithm for the above case of 2 qubits for .
We start by preparing a quantum circuit with two qubits:
Then we simply need to write out the commands for the circuit depicted above. First, we need to initialize the state . Let's create a general function (for any number of qubits) so we can use it again later:
Apply the Oracle for . This oracle is specific to 2 qubits:
We now want to apply the diffuser (). As with the circuit that initialises , we'll create a general diffuser (for any number of qubits) so we can use it later in other problems.
This is our finished circuit.
As expected, the amplitude of every state that is not is 0, this means we have a 100% chance of measuring :
We confirm that in the majority of the cases the state is measured. The other results are due to errors in the quantum computation.
3. Example: 3 Qubits
We now go through the example of Grover's algorithm for 3 qubits with two marked states and , following the implementation found in Reference [2]. The quantum circuit to solve the problem using a phase oracle is:
Apply Hadamard gates to qubits initialised to to create a uniform superposition:
Mark states and using a phase oracle:
Perform the reflection around the average amplitude:
Apply Hadamard gates to the qubits
Apply X gates to the qubits
Apply a doubly controlled Z gate between the 1, 2 (controls) and 3 (target) qubits
Apply X gates to the qubits
Apply Hadamard gates to the qubits
Measure the qubits to retrieve states and
Note that since there are 2 solutions and 8 possibilities, we will only need to run one iteration (steps 2 & 3).
3.1 Qiskit Implementation
We now implement Grover's algorithm for the above example for -qubits and searching for two marked states and . Note: Remember that Qiskit orders it's qubits the opposite way round to this resource, so the circuit drawn will appear flipped about the horizontal.
We create a phase oracle that will mark states and as the results (step 1).
In the last section, we used a diffuser specific to 2 qubits, in the cell below we will create a general diffuser for any number of qubits.
Detail
Creating a General Diffuser
Remember that we can create from :
And a multi-controlled-Z gate () inverts the phase of the state :
Applying an X-gate to each qubit performs the transformation:
So:
Using these properties together, we can create using H-gates, X-gates, and a single multi-controlled-Z gate:
Note that we can ignore the global phase of -1.
We'll now put the pieces together, with the creation of a uniform superposition at the start of the circuit and a measurement at the end. Note that since there are 2 solutions and 8 possibilities, we will only need to run one iteration.
As we can see, the algorithm discovers our marked states and .
As we can (hopefully) see, there is a higher chance of measuring and . The other results are due to errors in the quantum computation.
4. Problems
The function grover_problem_oracle
below takes a number of qubits (n
), and a variant
and returns an n-qubit oracle. The function will always return the same oracle for the same n
and variant
. You can see the solutions to each oracle by setting print_solutions = True
when calling grover_problem_oracle
.
grover_problem_oracle(4, variant=2)
uses 4 qubits and has 1 solution. a. How many iterations do we need to have a > 90% chance of measuring this solution? b. Use Grover's algorithm to find this solution state. c. What happens if we apply more iterations the number we calculated in problem 1a above? Why?With 2 solutions and 4 qubits, how many iterations do we need for a >90% chance of measuring a solution? Test your answer using the oracle
grover_problem_oracle(4, variant=1)
(which has two solutions).Create a function,
grover_solver(oracle, iterations)
that takes as input:A Grover oracle as a gate (
oracle
)An integer number of iterations (
iterations
)
and returns a
QuantumCircuit
that performs Grover's algorithm on the 'oracle
' gate, with 'iterations
' iterations.
4.1 Solving Sudoku using Grover's Algorithm
The oracles used throughout this chapter so far have been created with prior knowledge of their solutions. We will now solve a simple problem using Grover's algorithm, for which we do not necessarily know the solution beforehand. Our problem is a 2×2 binary sudoku, which in our case has two simple rules:
No column may contain the same value twice
No row may contain the same value twice
If we assign each square in our sudoku to a variable like so:
we want our circuit to output a solution to this sudoku.
Note that, while this approach of using Grover's algorithm to solve this problem is not practical (you can probably find the solution in your head!), the purpose of this example is to demonstrate the conversion of classical decision problems into oracles for Grover's algorithm.
4.1.1 Turning the Problem into a Circuit
We want to create an oracle that will help us solve this problem, and we will start by creating a circuit that identifies a correct solution. Similar to how we created a classical adder using quantum circuits in The Atoms of Computation, we simply need to create a classical function on a quantum circuit that checks whether the state of our variable bits is a valid solution.
Since we need to check down both columns and across both rows, there are 4 conditions we need to check:
Remember we are comparing classical (computational basis) states. For convenience, we can compile this set of comparisons into a list of clauses:
We will assign the value of each variable to a bit in our circuit. To check these clauses computationally, we will use the XOR
gate (we came across this in the atoms of computation).
Convince yourself that the output0
bit in the circuit below will only be flipped if input0 ≠ input1
:
This circuit checks whether input0 == input1
and stores the output to output0
. To check each clause, we repeat this circuit for each pairing in clause_list
and store the output to a new bit:
The final state of the bits c0, c1, c2, c3
will only all be 1
in the case that the assignments of v0, v1, v2, v3
are a solution to the sudoku. To complete our checking circuit, we want a single bit to be 1
if (and only if) all the clauses are satisfied, this way we can look at just one bit to see if our assignment is a solution. We can do this using a multi-controlled-Toffoli-gate:
The circuit above takes as input an initial assignment of the bits v0
, v1
, v2
and v3
, and all other bits should be initialised to 0
. After running the circuit, the state of the out0
bit tells us if this assignment is a solution or not; out0 = 0
means the assignment is not a solution, and out0 = 1
means the assignment is a solution.
Important: Before you continue, it is important you fully understand this circuit and are convinced it works as stated in the paragraph above.
4.1.2 Uncomputing, and Completing the Oracle
We can now turn this checking circuit into a Grover oracle using phase kickback. To recap, we have 3 registers:
One register which stores our sudoku variables (we'll say )
One register that stores our clauses (this starts in the state which we'll abbreviate to )
And one qubit () that we've been using to store the output of our checking circuit.
To create an oracle, we need our circuit () to perform the transformation:
If we set the out0
qubit to the superposition state we have:
If , then we have the state:
(i.e. no change). But if (i.e. ), we introduce a negative phase to the qubit:
This is a functioning oracle that uses two auxiliary registers in the state :
To adapt our checking circuit into a Grover oracle, we need to guarantee the bits in the second register (c
) are always returned to the state after the computation. To do this, we simply repeat the part of the circuit that computes the clauses which guarantees c0 = c1 = c2 = c3 = 0
after our circuit has run. We call this step 'uncomputation'.
In summary, the circuit above performs:
and if the initial state of ,:
4.1.3 The Full Algorithm
All that's left to do now is to put all these components together.
There are two bit strings with a much higher probability of measurement than any of the others, 0110
and 1001
. These correspond to the assignments:
and
which are the two solutions to our sudoku! The aim of this section is to show how we can create Grover oracles from real problems. While this specific problem is trivial, the process can be applied (allowing large enough circuits) to any decision problem. To recap, the steps are:
Your turn
Create a reversible classical circuit that identifies a correct solution
Use phase kickback and uncomputation to turn this circuit into an oracle
Use Grover's algorithm to solve this oracle
4.2 The Triangle-finding Problem Using Grover
One of the famous graph theory problems is the triangle-finding problem. In the triangle-finding problem, we are given a graph that may or may not contain a triangle. Our task is to find the triangle/s within the graph and point out the nodes that form the triangle. For example, the graph below is a 4-node graph with a triangle between nodes 1
,2
, and 3
.
We can apply Grover's algorithm to this problem, we are going to give the algorithm a list of edges and the number of nodes in the graph. The algorithm, then, will do the rest. It will try to check if there's a triangle in the graph or not, and if so it will mark the nodes forming that triangle.
Now, let's go through Grover's algorithm steps and see how can we construct each step to solve the triangle finding problem. But first, let's define our input, which is the list of edges.
4.2.1 The state preparation
To solve the problem, let's first focus on the example above, which is the case of finding a triangle in a 4-node graph. to do that, we need to go over all subgraphs within our graph and check if any of them a triangle. To do that we will need 4-qubits, each qubit represents a node in the graph. The state of the qubit will indicate whether the node in any subgraph or not. For example, in the graph above, the triangle is between nodes 0,1, and 2, we can rephrase that using the state 1110
. The nodes with state 1 are in the subgraph (triangle) and the node with state 0 is not.
For the state preparation, we will need to create a superposition of all possible states 0000
, to 1111
, which can be done simply using 4
Hadamard gates. Doing so, will we need to rotate over the oracle and diffusion 3
times.
But, if each 1
in the state represent an active node, we don't really need to look through the entire Hilbert space, we only need to look through the subgraphs with three nodes.
This is a good example of using another type of symmetric states to prepare the search space. Here since we only need to consider states with three 1's, we can think of another way to form our search space. One way to create a superposition over only states with three active nodes is through using the W-state followed by 4 NOT gates
. This will decrease the number of rotations needed from 3
to 1
.
So, we first need to implement the W-state. W-states have the form:
In our case, we need to construct states as described in reference 6.
4.2.2 The oracle
The oracle is what's gonna mark the correct answer. In these cases, the oracle needs to take every subgraph and count the number of edges in that subgraph. If the number of edges is 3
, then we have a triangle, if not, it will proceed to the next subgraph.
For every edge in the graph, we will need one or two CNOT
gates. These CNOT
gates will apply to two ancillary qubits, that should be in state 11
if a triangle is found. The number of ancillary qubits here is two because a triangle has 3 edges
that is . Then the final step in the oracle is to apply one more Toffoli
, that will only be active if a triangle is found by changing the state of another qubit, let's call it, tri_flag
, to 1
.
Reminder
4.2.3 The diffusion operator
As we said before, the diffusion operator construction depends on the type of state preparation we used, in this case, the W-state. So, we need the inverses W-state, a multi-controlled Z gate and the original W-state to form the diffusion operator.
4.2.4 Putting it all together
Now that we have all the components of the algorithm built and running, we can put them together.
Now, let's run the code and plot the histogram to see if our algorithm works as expected.
5. References
L. K. Grover (1996), "A fast quantum mechanical algorithm for database search", Proceedings of the 28th Annual ACM Symposium on the Theory of Computing (STOC 1996), doi:10.1145/237814.237866, arXiv:quant-ph/9605043
C. Figgatt, D. Maslov, K. A. Landsman, N. M. Linke, S. Debnath & C. Monroe (2017), "Complete 3-Qubit Grover search on a programmable quantum computer", Nature Communications, Vol 8, Art 1918, doi:10.1038/s41467-017-01904-7, arXiv:1703.10535
I. Chuang & M. Nielsen, "Quantum Computation and Quantum Information", Cambridge: Cambridge University Press, 2000.
Marconi, C., Aloy, A., Tura, J., & Sanpera, A. (2021). Entangled symmetric states and copositive matrices. Quantum, 5, 561.
R. Prevedel, G. Cronenberg, M. S. Tame, M. Paternostro, P. Walther, M. S. Kim, and A. Zeilinger, “Experimental realization of dicke states of up to six qubits for multiparty quantum networking,” Physical Review Letters, vol. 103, no. 2, Jul 2009.
D. Cruz, R. Fournier, F. Gremion, A. Jeannerot, K. Komagata, T. Tosic, J. Thiesbrummel, C. L. Chan, N. Macris, M.-A. Dupertuis et al., “Efficient quantum algorithms for ghz and w states, and implementation on the ibm quantum computer,” Advanced Quantum Technologies, vol. 2, no. 5-6, p.1900015, 2019. https://doi.org/10.1002/qute.201900015
Magniez, F., Santha, M., & Szegedy, M. (2007). Quantum algorithms for the triangle problem. SIAM Journal on Computing, 37(2), 413-424.