The Variational Quantum Linear Solver

In [3]:
import qiskit
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import Aer, execute
import math
import random
import numpy as np
from scipy.optimize import minimize

Introduction

The Variational Quantum Linear Solver, or the VQLS is a variational quantum algorithm that utilizes VQE in order to solve systems of linear equations more efficiently than classical computational algortihms. Specifically, if we are given some matrix $\textbf{A}$, such that $\textbf{A} |\textbf{x}\rangle \ = \ |\textbf{b}\rangle$, where $|\textbf{b}\rangle$ is some known vector, the VQLS algorithm is theoretically able to find a normalized $|x\rangle$ that is proportional to $|\textbf{x}\rangle$, which makes the above relationship true.

The output of this algorithm is identical to that of the HHL Quantum Linear-Solving Algorithm, except, while HHL provides a much more favourable computation speedup over VQLS, the variational nature of our algorithm allows for it to be performed on NISQ quantum computers, while HHL would require much more robust quantum hardware, and many more qubits.

The Algorithm

To begin, the inputs into this algorithm are evidently the matrix $\textbf{A}$, which we have to decompose into a linear combination of unitaries with complex coefficients:

$$A \ = \ \displaystyle\sum_{n} c_n \ A_n$$

Where each $A_n$ is some unitary, and some unitary $U$ that prepares state $|\textbf{b}\rangle$ from $|0\rangle$. Now, recall the general structure of a variational quantum algorithm. We have to construct a quantum cost function, which can be evaluated with a low-depth parametrized quantum circuit, then output to the classical optimizer. This allows us to search a parameter space for some set of parameters $\alpha$, such that $|\psi(\alpha)\rangle \ = \ \frac{|\textbf{x}\rangle}{|| \textbf{x} ||}$, where $|\psi(k)\rangle$ is the output of out quantum circuit corresponding to some parameter set $k$.

Before we actually begin constructing the cost function, let's take a look at a "high level" overview of the sub-routines within this algorithm, as illustrated in this image from the original paper:

alt text

So essentially, we start off with a qubit register, with each qubit initialized to $|0\rangle$. Our algorithm takes its inputs, then prepares and evaluates the cost function, starting with the creation of some ansatz $V(\alpha)$. If the computed cost is greater than some parameter $\gamma$, the algorithm is run again with updated parameters, and if not, the algorithm terminates, and the ansatz is calculated with the optimal parameters (determined at termination). This gives us the state vector that minimizes our cost function, and therefore the normalized form of $|\textbf{x}\rangle$.

Let's start off by considering the ansatz $V(\alpha)$, which is just a circuit that prepares some arbitrary state $|\psi(k)\rangle$. This allows us to "search" the state space by varying some set of parameters, $k$. Anyways, the ansatz that we will use for this implementation is given as follows:

In [8]:
def apply_fixed_ansatz(qubits, parameters):

    for iz in range (0, len(qubits)):
        circ.ry(parameters[0][iz], qubits[iz])

    circ.cz(qubits[0], qubits[1])
    circ.cz(qubits[2], qubits[0])

    for iz in range (0, len(qubits)):
        circ.ry(parameters[1][iz], qubits[iz])

    circ.cz(qubits[1], qubits[2])
    circ.cz(qubits[2], qubits[0])

    for iz in range (0, len(qubits)):
        circ.ry(parameters[2][iz], qubits[iz])

circ = QuantumCircuit(3)
apply_fixed_ansatz([0, 1, 2], [[1, 1, 1], [1, 1, 1], [1, 1, 1]])
print(circ)
        ┌───────┐               ┌───────┐               ┌───────┐
q_0: |0>┤ Ry(1) ├─■──■──────────┤ Ry(1) ├────■──────────┤ Ry(1) ├
        ├───────┤ │  │ ┌───────┐└───────┘    │ ┌───────┐└───────┘
q_1: |0>┤ Ry(1) ├─■──┼─┤ Ry(1) ├──────────■──┼─┤ Ry(1) ├─────────
        ├───────┤    │ └───────┘┌───────┐ │  │ └───────┘┌───────┐
q_2: |0>┤ Ry(1) ├────■──────────┤ Ry(1) ├─■──■──────────┤ Ry(1) ├
        └───────┘               └───────┘               └───────┘

This is called a fixed hardware ansatz: the configuration of quantum gates remains the same for each run of the circuit, all that changes are the parameters. Unlike the QAOA ansatz, it is not composed solely of Trotterized Hamiltonians. The applications of $Ry$ gates allows us to search the state space, while the $CZ$ gates create "interference" between the different qubit states.

Now, it makes sense for us to consider the actual cost function. The goal of our algorithm will be to minimize cost, so when $|\Phi\rangle \ = \ \textbf{A} |\psi(k)\rangle$ is very close to $|\textbf{b}\rangle$, we want our cost function's output to be very small, and when the vectors are close to being ortohognal, we want the cost function to be very large. Thus, we introduce the "projection" Hamiltonian:

$$H_P \ = \ \mathbb{I} \ - \ |b\rangle \langle b|$$

Where we have:

$$C_P \ = \ \langle \Phi | H_P | \Phi \rangle \ = \ \langle \Phi | (\mathbb{I} \ - \ |b\rangle \langle b|) |\Phi \rangle \ = \ \langle \Phi | \Phi \rangle \ - \ \langle \Phi |b\rangle \langle b | \Phi \rangle$$

Notice how the second term tells us "how much" of $|\Phi\rangle$ lies along $|b\rangle$. We then subtract this from another number to get the desired low number when the inner product of $|\Phi\rangle$ and $|b\rangle$ is greater (they agree more), and the opposite for when they are close to being orthogonal. This is looking good so far! However, there is still one more thing we can do to increase the accuracy of the algorithm: normalizing the cost function. This is due to the fact that if $|\Phi\rangle$ has a small norm, then the cost function will still be low, even if it does not agree with $|\textbf{b}\rangle$. Thus, we replace $|\Phi\rangle$ with $\frac{|\Phi\rangle}{\sqrt{\langle \Phi | \Phi \rangle}}$:

$$\hat{C}_P \ = \ \frac{\langle \Phi | \Phi \rangle}{\langle \Phi | \Phi \rangle} \ - \ \frac{\langle \Phi |b\rangle \langle b | \Phi \rangle}{\langle \Phi | \Phi \rangle} \ = \ 1 \ - \ \frac{\langle \Phi |b\rangle \langle b | \Phi \rangle}{\langle \Phi | \Phi \rangle} \ = \ 1 \ - \ \frac{|\langle b | \Phi \rangle|^2}{\langle \Phi | \Phi \rangle}$$

Ok, so, we have prepared our state $|\psi(k)\rangle$ with the ansatz. Now, we have two values to calculate in order to evaluate the cost function, namely $|\langle b | \Phi \rangle|^2$ and $\langle \Phi | \Phi \rangle$. Luckily, a nifty little quantum subroutine called the Hadamard Test allows us to do this! Essentially, if we have some unitary $U$ and some state $|\phi\rangle$, and we want to find the expectation value of $U$ with respect to the state, $\langle \phi | U | \phi \rangle$, then we can evaluate the following circuit:





Then, the probability of measuring the first qubit to be $0$ is equal to $\frac{1}{2} (1 \ + \ \text{Re}\langle U \rangle)$ and the probability of measuring $1$ is $\frac{1}{2} (1 \ - \ \text{Re}\langle U \rangle)$, so subtracting the two probabilities gives us $\text{Re} \langle U \rangle$. Luckily, the matrices we will be dealing with when we test this algorithm are completely real, so $\text{Re} \langle U \rangle \ = \ \langle U \rangle$, for this specific implementation. Here is how the Hadamard test works. By the circuit diagram, we have as our general state vector:


$$\frac{|0\rangle \ + \ |1\rangle}{\sqrt{2}} \ \otimes \ |\psi\rangle \ = \ \frac{|0\rangle \ \otimes \ |\psi\rangle \ + \ |1\rangle \ \otimes \ |\psi\rangle}{\sqrt{2}}$$


Applying our controlled unitay:


$$\frac{|0\rangle \ \otimes \ |\psi\rangle \ + \ |1\rangle \ \otimes \ |\psi\rangle}{\sqrt{2}} \ \rightarrow \ \frac{|0\rangle \ \otimes \ |\psi\rangle \ + \ |1\rangle \ \otimes \ U|\psi\rangle}{\sqrt{2}}$$


Then applying the Hadamard gate to the first qubit:


$$\frac{|0\rangle \ \otimes \ |\psi\rangle \ + \ |1\rangle \ \otimes \ U|\psi\rangle}{\sqrt{2}} \ \rightarrow \ \frac{1}{2} \ \big[ |0\rangle \ \otimes \ |\psi\rangle \ + \ |1\rangle \ \otimes \ |\psi\rangle \ + \ |0\rangle \ \otimes \ U|\psi\rangle \ - \ |1\rangle \ \otimes \ U|\psi\rangle \big]$$


$$\Rightarrow \ |0\rangle \ \otimes \ (\mathbb{I} \ + \ U)|\psi\rangle \ + \ |1\rangle \ \otimes \ (\mathbb{I} \ - \ U)|\psi\rangle$$


When we take a measurement of the first qubit, remember that in order to find the probability of measuring $0$, we must take the inner product of the state vector with $|0\rangle$, then multiply by its complex conjugate (see the quantum mechanics section if you are not familiar with this). The same follows for the probability of measuring $1$. Thus, we have:


$$P(0) \ = \ \frac{1}{4} \ \langle \psi | (\mathbb{I} \ + \ U) (\mathbb{I} \ + \ U^{\dagger}) |\psi\rangle \ = \ \frac{1}{4} \ \langle \psi | (\mathbb{I}^2 \ + U \ + \ U^{\dagger} \ + \ U^{\dagger} U) |\psi\rangle \ = \ \frac{1}{4} \ \langle \psi | (2\mathbb{I} \ + U \ + \ U^{\dagger}) |\psi\rangle$$


$$\Rightarrow \ \frac{1}{4} \Big[ 2 \ + \ \langle \psi | U^{\dagger} | \psi \rangle \ + \ \langle \psi | U | \psi \rangle \Big] \ = \ \frac{1}{4} \Big[ 2 \ + \ (\langle \psi | U | \psi \rangle)^{*} \ + \ \langle \psi | U | \psi \rangle \Big] \ = \ \frac{1}{2} (1 \ + \ \text{Re} \ \langle \psi | U | \psi \rangle)$$


By a similar procedure, we get:


$$P(1) \ = \ \frac{1}{2} \ (1 \ - \ \text{Re} \ \langle \psi | U | \psi \rangle)$$


And so, by taking the difference:


$$P(0) \ - \ P(1) \ = \ \text{Re} \ \langle \psi | U | \psi \rangle$$


Cool! Now, we can actually implement this for the two values we have to compute. Starting with $\langle \Phi | \Phi \rangle$, we have:


$$\langle \Phi | \Phi \rangle \ = \ \langle \psi(k) | A^{\dagger} A |\psi(k) \rangle \ = \ \langle 0 | V(k)^{\dagger} A^{\dagger} A V(k) |0\rangle \ = \ \langle 0 | V(k)^{\dagger} \Big( \displaystyle\sum_{n} c_n \ A_n \Big)^{\dagger} \Big( \displaystyle\sum_{n} c_n \ A_n \Big) V(k) |0\rangle$$


$$\Rightarrow \ \langle \Phi | \Phi \rangle \ = \ \displaystyle\sum_{m} \displaystyle\sum_{n} c_m^{*} c_n \langle 0 | V(k)^{\dagger} A_m^{\dagger} A_n V(k) |0\rangle$$


and so our task becomes computing every possible term $\langle 0 | V(k)^{\dagger} A_m^{\dagger} A_n V(k) |0\rangle$ using the Hadamard test. This requires us prepare the state $V(k) |0\rangle$, and then perform controlled operations with some control-ancilla qubit for the unitary matrices $A_m^{\dagger}$ and $A_n$. We can implement this in code:

In [9]:
#Creates the Hadamard test

def had_test(gate_type, qubits, ancilla_index, parameters):

    circ.h(ancilla_index)

    apply_fixed_ansatz(qubits, parameters)

    for ie in range (0, len(gate_type[0])):
        if (gate_type[0][ie] == 1):
            circ.cz(ancilla_index, qubits[ie])

    for ie in range (0, len(gate_type[1])):
        if (gate_type[1][ie] == 1):
            circ.cz(ancilla_index, qubits[ie])
    
    circ.h(ancilla_index)
    
circ = QuantumCircuit(4)
had_test([[0, 0, 0], [0, 0, 1]], [1, 2, 3], 0, [[1, 1, 1], [1, 1, 1], [1, 1, 1]])
print(circ)
          ┌───┐                                                     ┌───┐
q_0: |0>──┤ H ├───────────────────────────────────────────────────■─┤ H ├
        ┌─┴───┴─┐               ┌───────┐               ┌───────┐ │ └───┘
q_1: |0>┤ Ry(1) ├─■──■──────────┤ Ry(1) ├────■──────────┤ Ry(1) ├─┼──────
        ├───────┤ │  │ ┌───────┐└───────┘    │ ┌───────┐└───────┘ │      
q_2: |0>┤ Ry(1) ├─■──┼─┤ Ry(1) ├──────────■──┼─┤ Ry(1) ├──────────┼──────
        ├───────┤    │ └───────┘┌───────┐ │  │ └───────┘┌───────┐ │      
q_3: |0>┤ Ry(1) ├────■──────────┤ Ry(1) ├─■──■──────────┤ Ry(1) ├─■──────
        └───────┘               └───────┘               └───────┘        

The reason why we are applying two different "gate_types" is because this represents the pairs of gates shown in the expanded form of $\langle \Phi | \Phi \rangle$.

It is also important to note that for the purposes of this implementation (the systems of equations we will actually be sovling, we are only concerned with the gates $Z$ and $\mathbb{I}$, so I only include support for these gates (The code includes number "identifiers" that signify the application of different gates, $0$ for $\mathbb{I}$ and $1$ for $Z$).

Now, we can move on to the second value we must calculate, which is $|\langle b | \Phi \rangle|^2$. We get:


$$|\langle b | \Phi \rangle|^2 \ = \ |\langle b | A V(k) | 0 \rangle|^2 \ = \ |\langle 0 | U^{\dagger} A V(k) | 0 \rangle|^2 \ = \ \langle 0 | U^{\dagger} A V(k) | 0 \rangle \langle 0 | V(k)^{\dagger} A^{\dagger} U |0\rangle$$


All we have to do now is the same expansion as before for the product $\langle 0 | U^{\dagger} A V(k) | 0 \rangle \langle 0 | V(k)^{\dagger} A^{\dagger} U |0\rangle$:


$$\langle 0 | U^{\dagger} A V(k) | 0 \rangle^2 \ = \ \displaystyle\sum_{m} \displaystyle\sum_{n} c_m^{*} c_n \langle 0 | U^{\dagger} A_n V(k) | 0 \rangle \langle 0 | V(k)^{\dagger} A_m^{\dagger} U |0\rangle$$


Now, again, for the purposes of this demonstration, we will soon see that all the outputs/expectation values of our implementation will be real, so we have:

$$\Rightarrow \ \langle 0 | U^{\dagger} A V(k) | 0 \rangle \ = \ (\langle 0 | U^{\dagger} A V(k) | 0 \rangle)^{*} \ = \ \langle 0 | V(k)^{\dagger} A^{\dagger} U |0\rangle$$


Thus, in this particular implementation:


$$|\langle b | \Phi \rangle|^2 \ = \ \displaystyle\sum_{m} \displaystyle\sum_{n} c_m c_n \langle 0 | U^{\dagger} A_n V(k) | 0 \rangle \langle 0 | U^{\dagger} A_m V(k) | 0 \rangle$$


There is a sophisticated way of solving for this value, using a newly-proposed subroutine called the Hadamard Overlap Test (see cited paper), but for this tutorial, we will just be using a standard Hadamard Test, where we control each matrix. This unfortauntely requires the use of an extra ancilla qubit. We essentially just place a control on each of the gates involved in the ancilla, the $|b\rangle$ preparation unitary, and the $A_n$ unitaries. We get something like this for the controlled-ansatz:

In [10]:
#Creates controlled anstaz for calculating |<b|psi>|^2 with a Hadamard test

def control_fixed_ansatz(qubits, parameters, ancilla, reg):

    for i in range (0, len(qubits)):
        circ.cry(parameters[0][i], qiskit.circuit.Qubit(reg, ancilla), qiskit.circuit.Qubit(reg, qubits[i]))

    circ.ccx(ancilla, qubits[1], 4)
    circ.cz(qubits[0], 4)
    circ.ccx(ancilla, qubits[1], 4)

    circ.ccx(ancilla, qubits[0], 4)
    circ.cz(qubits[2], 4)
    circ.ccx(ancilla, qubits[0], 4)

    for i in range (0, len(qubits)):
        circ.cry(parameters[1][i], qiskit.circuit.Qubit(reg, ancilla), qiskit.circuit.Qubit(reg, qubits[i]))

    circ.ccx(ancilla, qubits[2], 4)
    circ.cz(qubits[1], 4)
    circ.ccx(ancilla, qubits[2], 4)

    circ.ccx(ancilla, qubits[0], 4)
    circ.cz(qubits[2], 4)
    circ.ccx(ancilla, qubits[0], 4)

    for i in range (0, len(qubits)):
        circ.cry(parameters[2][i], qiskit.circuit.Qubit(reg, ancilla), qiskit.circuit.Qubit(reg, qubits[i]))

q_reg = QuantumRegister(5)
circ = QuantumCircuit(q_reg)
control_fixed_ansatz([1, 2, 3], [[1, 1, 1], [1, 1, 1], [1, 1, 1]], 0, q_reg)
print(circ)
                                                                            »
q2_0: |0>─────────────────■────────────────────■────■────────────────────■──»
         ┌─────────────┐┌─┴─┐┌──────────────┐┌─┴─┐  │                    │  »
q2_1: |0>┤ U3(0.5,0,0) ├┤ X ├┤ U3(-0.5,0,0) ├┤ X ├──┼────────────────────┼──»
         ├─────────────┤└───┘└──────────────┘└───┘┌─┴─┐┌──────────────┐┌─┴─┐»
q2_2: |0>┤ U3(0.5,0,0) ├──────────────────────────┤ X ├┤ U3(-0.5,0,0) ├┤ X ├»
         ├─────────────┤                          └───┘└──────────────┘└───┘»
q2_3: |0>┤ U3(0.5,0,0) ├────────────────────────────────────────────────────»
         └─────────────┘                                                    »
q2_4: |0>───────────────────────────────────────────────────────────────────»
                                                                            »
«                                                                         »
«q2_0: ──■────────────────────■────■───────■────■──────────────────────■──»
«        │                    │    │       │    │                      │  »
«q2_1: ──┼────────────────────┼────┼───■───┼────■──────────────────────■──»
«        │                    │    │   │   │    │  ┌─────────────┐     │  »
«q2_2: ──┼────────────────────┼────■───┼───■────┼──┤ U3(0.5,0,0) ├─────┼──»
«      ┌─┴─┐┌──────────────┐┌─┴─┐  │   │   │    │  └─────────────┘     │  »
«q2_3: ┤ X ├┤ U3(-0.5,0,0) ├┤ X ├──┼───┼───┼────┼──────────────────■───┼──»
«      └───┘└──────────────┘└───┘┌─┴─┐ │ ┌─┴─┐┌─┴─┐                │ ┌─┴─┐»
«q2_4: ──────────────────────────┤ X ├─■─┤ X ├┤ X ├────────────────■─┤ X ├»
«                                └───┘   └───┘└───┘                  └───┘»
«                                                                   »
«q2_0: ────────────────────────────────■────────────────────■────■──»
«                     ┌─────────────┐┌─┴─┐┌──────────────┐┌─┴─┐  │  »
«q2_1: ───────────────┤ U3(0.5,0,0) ├┤ X ├┤ U3(-0.5,0,0) ├┤ X ├──┼──»
«                     └─────────────┘└───┘└──────────────┘└───┘┌─┴─┐»
«q2_2: ────────────────────────────────────────────────────────┤ X ├»
«      ┌─────────────┐                                         └───┘»
«q2_3: ┤ U3(0.5,0,0) ├──────────────────────────────────────────────»
«      └─────────────┘                                              »
«q2_4: ─────────────────────────────────────────────────────────────»
«                                                                   »
«                                                                  »
«q2_0: ──────────────────■────■────────────────────■────■───────■──»
«                        │    │                    │    │       │  »
«q2_1: ──────────────────┼────┼────────────────────┼────┼───────┼──»
«      ┌──────────────┐┌─┴─┐  │                    │    │       │  »
«q2_2: ┤ U3(-0.5,0,0) ├┤ X ├──┼────────────────────┼────┼───■───┼──»
«      └──────────────┘└───┘┌─┴─┐┌──────────────┐┌─┴─┐  │   │   │  »
«q2_3: ─────────────────────┤ X ├┤ U3(-0.5,0,0) ├┤ X ├──■───┼───■──»
«                           └───┘└──────────────┘└───┘┌─┴─┐ │ ┌─┴─┐»
«q2_4: ───────────────────────────────────────────────┤ X ├─■─┤ X ├»
«                                                     └───┘   └───┘»
«                                                                     »
«q2_0: ─────────────────■───────■──────────────────────────────────■──»
«                       │       │                 ┌─────────────┐┌─┴─┐»
«q2_1: ─────────────────■───────■─────────────────┤ U3(0.5,0,0) ├┤ X ├»
«      ┌─────────────┐  │       │                 └─────────────┘└───┘»
«q2_2: ┤ U3(0.5,0,0) ├──┼───────┼─────────────────────────────────────»
«      └─────────────┘  │       │  ┌─────────────┐                    »
«q2_3: ─────────────────┼───■───┼──┤ U3(0.5,0,0) ├────────────────────»
«                     ┌─┴─┐ │ ┌─┴─┐└─────────────┘                    »
«q2_4: ───────────────┤ X ├─■─┤ X ├───────────────────────────────────»
«                     └───┘   └───┘                                   »
«                                                                          »
«q2_0: ──────────────────■────■────────────────────■────■──────────────────»
«      ┌──────────────┐┌─┴─┐  │                    │    │                  »
«q2_1: ┤ U3(-0.5,0,0) ├┤ X ├──┼────────────────────┼────┼──────────────────»
«      └──────────────┘└───┘┌─┴─┐┌──────────────┐┌─┴─┐  │                  »
«q2_2: ─────────────────────┤ X ├┤ U3(-0.5,0,0) ├┤ X ├──┼──────────────────»
«                           └───┘└──────────────┘└───┘┌─┴─┐┌──────────────┐»
«q2_3: ───────────────────────────────────────────────┤ X ├┤ U3(-0.5,0,0) ├»
«                                                     └───┘└──────────────┘»
«q2_4: ────────────────────────────────────────────────────────────────────»
«                                                                          »
«           
«q2_0: ──■──
«        │  
«q2_1: ──┼──
«        │  
«q2_2: ──┼──
«      ┌─┴─┐
«q2_3: ┤ X ├
«      └───┘
«q2_4: ─────
«           

Notice the extra qubit, q0_4. This is an ancilla, and allows us to create a $CCZ$ gate, as is shown in the circuit. Now, we also have to create the circuit for $U$. In our implementation, we will pick $U$ as:


$$U \ = \ H_1 H_2 H_3$$


Thus, we have:

In [11]:
def control_b(ancilla, qubits):

    for ia in qubits:
        circ.ch(ancilla, ia)

circ = QuantumCircuit(4)
control_b(0, [1, 2, 3])
print(circ)
                       
q_0: |0>──■────■────■──
        ┌─┴─┐  │    │  
q_1: |0>┤ H ├──┼────┼──
        └───┘┌─┴─┐  │  
q_2: |0>─────┤ H ├──┼──
             └───┘┌─┴─┐
q_3: |0>──────────┤ H ├
                  └───┘

Finally, we construct our new Hadamard test:

In [12]:
#Create the controlled Hadamard test, for calculating <psi|psi>

def special_had_test(gate_type, qubits, ancilla_index, parameters, reg):

    circ.h(ancilla_index)

    control_fixed_ansatz(qubits, parameters, ancilla_index, reg)

    for ty in range (0, len(gate_type)):
        if (gate_type[ty] == 1):
            circ.cz(ancilla_index, qubits[ty])


    control_b(ancilla_index, qubits)
    
    circ.h(ancilla_index)

q_reg = QuantumRegister(5)
circ = QuantumCircuit(q_reg)
special_had_test([[0, 0, 0], [0, 0, 1]], [1, 2, 3], 0, [[1, 1, 1], [1, 1, 1], [1, 1, 1]], q_reg)
print(circ)
              ┌───┐                                                         »
q3_0: |0>─────┤ H ├───────■────────────────────■────■────────────────────■──»
         ┌────┴───┴────┐┌─┴─┐┌──────────────┐┌─┴─┐  │                    │  »
q3_1: |0>┤ U3(0.5,0,0) ├┤ X ├┤ U3(-0.5,0,0) ├┤ X ├──┼────────────────────┼──»
         ├─────────────┤└───┘└──────────────┘└───┘┌─┴─┐┌──────────────┐┌─┴─┐»
q3_2: |0>┤ U3(0.5,0,0) ├──────────────────────────┤ X ├┤ U3(-0.5,0,0) ├┤ X ├»
         ├─────────────┤                          └───┘└──────────────┘└───┘»
q3_3: |0>┤ U3(0.5,0,0) ├────────────────────────────────────────────────────»
         └─────────────┘                                                    »
q3_4: |0>───────────────────────────────────────────────────────────────────»
                                                                            »
«                                                                         »
«q3_0: ──■────────────────────■────■───────■────■──────────────────────■──»
«        │                    │    │       │    │                      │  »
«q3_1: ──┼────────────────────┼────┼───■───┼────■──────────────────────■──»
«        │                    │    │   │   │    │  ┌─────────────┐     │  »
«q3_2: ──┼────────────────────┼────■───┼───■────┼──┤ U3(0.5,0,0) ├─────┼──»
«      ┌─┴─┐┌──────────────┐┌─┴─┐  │   │   │    │  └─────────────┘     │  »
«q3_3: ┤ X ├┤ U3(-0.5,0,0) ├┤ X ├──┼───┼───┼────┼──────────────────■───┼──»
«      └───┘└──────────────┘└───┘┌─┴─┐ │ ┌─┴─┐┌─┴─┐                │ ┌─┴─┐»
«q3_4: ──────────────────────────┤ X ├─■─┤ X ├┤ X ├────────────────■─┤ X ├»
«                                └───┘   └───┘└───┘                  └───┘»
«                                                                   »
«q3_0: ────────────────────────────────■────────────────────■────■──»
«                     ┌─────────────┐┌─┴─┐┌──────────────┐┌─┴─┐  │  »
«q3_1: ───────────────┤ U3(0.5,0,0) ├┤ X ├┤ U3(-0.5,0,0) ├┤ X ├──┼──»
«                     └─────────────┘└───┘└──────────────┘└───┘┌─┴─┐»
«q3_2: ────────────────────────────────────────────────────────┤ X ├»
«      ┌─────────────┐                                         └───┘»
«q3_3: ┤ U3(0.5,0,0) ├──────────────────────────────────────────────»
«      └─────────────┘                                              »
«q3_4: ─────────────────────────────────────────────────────────────»
«                                                                   »
«                                                                  »
«q3_0: ──────────────────■────■────────────────────■────■───────■──»
«                        │    │                    │    │       │  »
«q3_1: ──────────────────┼────┼────────────────────┼────┼───────┼──»
«      ┌──────────────┐┌─┴─┐  │                    │    │       │  »
«q3_2: ┤ U3(-0.5,0,0) ├┤ X ├──┼────────────────────┼────┼───■───┼──»
«      └──────────────┘└───┘┌─┴─┐┌──────────────┐┌─┴─┐  │   │   │  »
«q3_3: ─────────────────────┤ X ├┤ U3(-0.5,0,0) ├┤ X ├──■───┼───■──»
«                           └───┘└──────────────┘└───┘┌─┴─┐ │ ┌─┴─┐»
«q3_4: ───────────────────────────────────────────────┤ X ├─■─┤ X ├»
«                                                     └───┘   └───┘»
«                                                                     »
«q3_0: ─────────────────■───────■──────────────────────────────────■──»
«                       │       │                 ┌─────────────┐┌─┴─┐»
«q3_1: ─────────────────■───────■─────────────────┤ U3(0.5,0,0) ├┤ X ├»
«      ┌─────────────┐  │       │                 └─────────────┘└───┘»
«q3_2: ┤ U3(0.5,0,0) ├──┼───────┼─────────────────────────────────────»
«      └─────────────┘  │       │  ┌─────────────┐                    »
«q3_3: ─────────────────┼───■───┼──┤ U3(0.5,0,0) ├────────────────────»
«                     ┌─┴─┐ │ ┌─┴─┐└─────────────┘                    »
«q3_4: ───────────────┤ X ├─■─┤ X ├───────────────────────────────────»
«                     └───┘   └───┘                                   »
«                                                                          »
«q3_0: ──────────────────■────■────────────────────■────■──────────────────»
«      ┌──────────────┐┌─┴─┐  │                    │    │                  »
«q3_1: ┤ U3(-0.5,0,0) ├┤ X ├──┼────────────────────┼────┼──────────────────»
«      └──────────────┘└───┘┌─┴─┐┌──────────────┐┌─┴─┐  │                  »
«q3_2: ─────────────────────┤ X ├┤ U3(-0.5,0,0) ├┤ X ├──┼──────────────────»
«                           └───┘└──────────────┘└───┘┌─┴─┐┌──────────────┐»
«q3_3: ───────────────────────────────────────────────┤ X ├┤ U3(-0.5,0,0) ├»
«                                                     └───┘└──────────────┘»
«q3_4: ────────────────────────────────────────────────────────────────────»
«                                                                          »
«                          ┌───┐
«q3_0: ──■────■────■────■──┤ H ├
«        │  ┌─┴─┐  │    │  └───┘
«q3_1: ──┼──┤ H ├──┼────┼───────
«        │  └───┘┌─┴─┐  │       
«q3_2: ──┼───────┤ H ├──┼───────
«      ┌─┴─┐     └───┘┌─┴─┐     
«q3_3: ┤ X ├──────────┤ H ├─────
«      └───┘          └───┘     
«q3_4: ─────────────────────────
«                               

This is for the specific implementation when all of our parameters are set to $1$, and the set of gates $A_n$ is simply [0, 0, 0], and [0, 0, 1], which corresponds to the identity matrix on all qubits, as well as the $Z$ matrix on the third qubit (with my "code notation").

Now, we are ready to calculate the final cost function. This simply involves us taking the products of all combinations of the expectation outputs from the different circuits, multiplying by their respective coefficients, and arranging into the cost function that we discussed previously!

In [23]:
#Implements the entire cost function on the quantum circuit

def calculate_cost_function(parameters):
    
    global opt

    overall_sum_1 = 0
    
    parameters = [parameters[0:3], parameters[3:6], parameters[6:9]]

    for i in range(0, len(gate_set)):
        for j in range(0, len(gate_set)):

            global circ

            qctl = QuantumRegister(5)
            qc = ClassicalRegister(5)
            circ = QuantumCircuit(qctl, qc)

            backend = Aer.get_backend('statevector_simulator')
            
            multiply = coefficient_set[i]*coefficient_set[j]

            had_test([gate_set[i], gate_set[j]], [1, 2, 3], 0, parameters)

            job = execute(circ, backend)

            result = job.result()
            outputstate = result.get_statevector(circ, decimals=100)
            o = outputstate

            m_sum = 0
            for l in range (0, len(o)):
                if (l%2 == 1):
                    n = float(o[l])**2
                    m_sum+=n

            overall_sum_1+=multiply*(1-(2*m_sum))

    overall_sum_2 = 0

    for i in range(0, len(gate_set)):
        for j in range(0, len(gate_set)):

            multiply = coefficient_set[i]*coefficient_set[j]
            mult = 1

            for extra in range(0, 2):

                qctl = QuantumRegister(5)
                qc = ClassicalRegister(5)
                circ = QuantumCircuit(qctl, qc)

                backend = Aer.get_backend('statevector_simulator')

                if (extra == 0):
                    special_had_test(gate_set[i], [1, 2, 3], 0, parameters, qctl)
                if (extra == 1):
                    special_had_test(gate_set[j], [1, 2, 3], 0, parameters, qctl)

                job = execute(circ, backend)

                result = job.result()
                outputstate = result.get_statevector(circ, decimals=100)
                o = outputstate

                m_sum = 0
                for l in range (0, len(o)):
                    if (l%2 == 1):
                        n = float(o[l])**2
                        m_sum+=n
                mult = mult*(1-(2*m_sum))

            overall_sum_2+=multiply*mult
            
    print(1-float(overall_sum_2/overall_sum_1))

    return 1-float(overall_sum_2/overall_sum_1)

This code may look long and daunting, but it isn't! In this simulation, I'm taking a numerical approach, where I'm calculating the amplitude squared of each state corresponding to a measurement of the ancilla Hadamard test qubit in the $1$ state, then calculating $P(0) \ - \ P(1) \ = \ 1 \ - \ 2P(1)$ with that information. This is very exact, but is not realistic, as a real quantum device would have to sample the circuit many times to generate these probabilities (I'll discuss sampling later). In addition, this code is not completely optimized (it completes more evaluations of the quantum circuit than it has to), but this is the simplest way in which the code can be implemented, and I will be optimizing it in an update to thiss tutorial in the near future.

The final step is to actually use this code to solve a real linear system. We will first be looking at the example:


$$A \ = \ 0.45 Z_3 \ + \ 0.55 \mathbb{I}$$


In order to minimize the cost function, we use the COBYLA optimizer method, which we repeatedly applying. Our search space for parameters is determined by $\frac{k}{1000} \ k \ \in \ \{0, \ 3000\}$, which is initially chosen randomly. We will run the optimizer for $200$ steps, then terminate and apply the ansatz for our optimal parameters, to get our optimized state vector! In addition, we will compute some post-processing, to see if our algorithm actually works! In order to do this, we will apply $A$ to our optimal vector $|\psi\rangle_o$, normalize it, then calculate the inner product squared of this vector and the solution vector, $|b\rangle$! We can put this all into code as:

In [25]:
coefficient_set = [0.55, 0.45]
gate_set = [[0, 0, 0], [0, 0, 1]]

out = minimize(calculate_cost_function, x0=[float(random.randint(0,3000))/1000 for i in range(0, 9)], method="COBYLA", options={'maxiter':200})
print(out)

out_f = [out['x'][0:3], out['x'][3:6], out['x'][6:9]]

circ = QuantumCircuit(3, 3)
apply_fixed_ansatz([0, 1, 2], out_f)

backend = Aer.get_backend('statevector_simulator')

job = execute(circ, backend)

result = job.result()
o = result.get_statevector(circ, decimals=10)

a1 = coefficient_set[1]*np.array([[1,0,0,0,0,0,0,0], [0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0], [0,0,0,1,0,0,0,0], [0,0,0,0,-1,0,0,0], [0,0,0,0,0,-1,0,0], [0,0,0,0,0,0,-1,0], [0,0,0,0,0,0,0,-1]])
a2 = coefficient_set[0]*np.array([[1,0,0,0,0,0,0,0], [0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0], [0,0,0,1,0,0,0,0], [0,0,0,0,1,0,0,0], [0,0,0,0,0,1,0,0], [0,0,0,0,0,0,1,0], [0,0,0,0,0,0,0,1]])
a3 = np.add(a1, a2)

b = np.array([float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8))])

print((b.dot(a3.dot(o)/(np.linalg.norm(a3.dot(o)))))**2)
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/ipykernel_launcher.py:35: ComplexWarning: Casting complex values to real discards the imaginary part
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/ipykernel_launcher.py:70: ComplexWarning: Casting complex values to real discards the imaginary part
0.9831625609596678
0.714912455705426
0.7529880773718886
0.7535739217359092
0.38887933377570305
0.43787060968759484
0.9995074080630343
0.2725579992425663
0.34530912011383297
0.9811319924317494
0.7407761170344858
0.5630549481302094
0.2619730646995667
0.5389930132093528
0.25184270902020445
0.46908713020131154
0.4422184803430059
0.5893271821377166
0.2855692599105859
0.9116589313008762
0.29141167608440854
0.525824549202996
0.3295799342424929
0.30350926168129244
0.2539859257368158
0.3327968430140976
0.24442108645671845
0.2517400354018866
0.2847112665247806
0.24842609523000503
0.2450669400424792
0.25131199264152904
0.24451533011721582
0.26335589503798007
0.2548752033305517
0.24510223330719405
0.2420596901101676
0.2333295382174383
0.23710075617997817
0.2306670755821555
0.2240817114520406
0.22095423921532442
0.22211478241995253
0.21943556733156278
0.21730082800773365
0.21590344336007627
0.2140042924689879
0.20779024131304558
0.19719922332846085
0.19063091169721802
0.18578926566423037
0.17465465726304008
0.16495804769184486
0.15721213367172704
0.14826522592046276
0.13806348685646574
0.12776798028305525
0.11798170459767032
0.11146257140379046
0.10058460669094504
0.09347679346943738
0.08313862031945529
0.07497083397659365
0.06912244971828985
0.06303824406711311
0.063427225342084
0.05936678092714909
0.055818687403525136
0.05302312997909753
0.05543758840441915
0.054974276427438906
0.05429900370813945
0.052694017684379424
0.05237037425296587
0.05988596588670281
0.05756655792876397
0.04440544552284542
0.04740962048207942
0.04660859805780415
0.04489334591892946
0.04580247191928066
0.0375166325571078
0.03988978231458584
0.0375970231652315
0.036082779501486306
0.040529570149290595
0.039093987789943774
0.035904235417706265
0.03638778154701572
0.03641423421024703
0.03555253652129542
0.037657699533344635
0.037145421392184685
0.03308982948205241
0.03242172992965053
0.034966630919115116
0.03171088893536056
0.032075781550268134
0.03234245039688666
0.0315564587195295
0.03162660915901372
0.03107315383737974
0.02947301627995158
0.02880150404815962
0.029156887615918503
0.028645430241494685
0.02795262891576311
0.028653267891823764
0.027902176216327845
0.026434434570602017
0.025671431131693012
0.02521146097948157
0.024913178149970627
0.024171072224127288
0.02333237280100109
0.023456442818372225
0.023317166504144504
0.024497422245249312
0.023396859798709757
0.022063295677102635
0.022346562291048255
0.022290380173742408
0.02159645358423612
0.022438304991653113
0.021321463584655587
0.020412927478190457
0.020092737071547906
0.020463840191913163
0.019624969597142772
0.01965588161387155
0.01967197447592106
0.019360692343968977
0.018949380033071894
0.0182654724232979
0.018607809610731385
0.0184265748265251
0.018663278534589156
0.018222387329481893
0.01807679908204518
0.019049293822393176
0.016883807674721973
0.01594351338081923
0.01552040946028932
0.01521549832303104
0.015177429132839149
0.015620245241075414
0.015628680106564707
0.014516602093362807
0.01352375716643961
0.013348860659593065
0.013342038519289168
0.013033014608608728
0.013962922928118848
0.012716119050846464
0.012169688416967195
0.01192232728587328
0.011792207814985245
0.01365329146978933
0.01158875950921634
0.011195313935059903
0.010920555584017388
0.01115898577674479
0.010201877155896821
0.010657302475341246
0.010729019137815432
0.00964621886416972
0.009209795683734256
0.00968367826173111
0.009261610502754203
0.009388371177821764
0.009037626965632262
0.010236705431579507
0.009051287134295483
0.008798115231816395
0.008780859100836702
0.009210513132848819
0.008233841209075887
0.008071810329476459
0.007993122880147974
0.007967125451031953
0.007756262468621156
0.007751763376797061
0.007911252121015067
0.007936184277404612
0.007590953476323659
0.007198216193537776
0.007121240970198728
0.0072037497321087995
0.007123452876170111
0.0072507436813531445
0.007387319091008426
0.006900090719671237
0.006546974413554674
0.006543424070501902
0.006550636458743542
0.006702224181074357
0.006662711864537707
0.006235439513391672
0.006067529070167055
0.005907904334877201
     fun: 0.005907904334877201
   maxcv: 0.0
 message: 'Maximum number of function evaluations has been exceeded.'
    nfev: 200
  status: 2
 success: False
       x: array([3.17231031, 0.66099822, 0.94311286, 1.65284435, 1.1750949 ,
       0.94517854, 3.04031284, 0.84369061, 2.92924202])
(0.9940920956678407-0j)

As you can see, our cost function has acheived a fairly low value of $0.005907904334877201$, and when we calculate our classical cost function, we get $0.9940920956678407$, which agrees perfectly with what we measured, the vectors $|\psi\rangle_o$ and $|b\rangle$ are very similar!

Let's do another test! This time, we will keep $|b\rangle$ the same, but we will have:


$$A \ = \ 0.55 \mathbb{I} \ + \ 0.225 Z_2 \ + \ 0.225 Z_3$$

Again, we run our optimization code:

In [27]:
coefficient_set = [0.55, 0.225, 0.225]
gate_set = [[0, 0, 0], [0, 1, 0], [0, 0, 1]]

out = minimize(calculate_cost_function, x0=[float(random.randint(0,3000))/1000 for i in range(0, 9)], method="COBYLA", options={'maxiter':200})
print(out)

out_f = [out['x'][0:3], out['x'][3:6], out['x'][6:9]]

circ = QuantumCircuit(3, 3)
apply_fixed_ansatz([0, 1, 2], out_f)

backend = Aer.get_backend('statevector_simulator')

job = execute(circ, backend)

result = job.result()
o = result.get_statevector(circ, decimals=10)

a1 = coefficient_set[2]*np.array([[1,0,0,0,0,0,0,0], [0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0], [0,0,0,1,0,0,0,0], [0,0,0,0,-1,0,0,0], [0,0,0,0,0,-1,0,0], [0,0,0,0,0,0,-1,0], [0,0,0,0,0,0,0,-1]])
a0 = coefficient_set[1]*np.array([[1,0,0,0,0,0,0,0], [0,1,0,0,0,0,0,0], [0,0,-1,0,0,0,0,0], [0,0,0,-1,0,0,0,0], [0,0,0,0,1,0,0,0], [0,0,0,0,0,1,0,0], [0,0,0,0,0,0,-1,0], [0,0,0,0,0,0,0,-1]])
a2 = coefficient_set[0]*np.array([[1,0,0,0,0,0,0,0], [0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0], [0,0,0,1,0,0,0,0], [0,0,0,0,1,0,0,0], [0,0,0,0,0,1,0,0], [0,0,0,0,0,0,1,0], [0,0,0,0,0,0,0,1]])

a3 = np.add(np.add(a2, a0), a1)

b = np.array([float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8))])

print((b.dot(a3.dot(o)/(np.linalg.norm(a3.dot(o)))))**2)
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/ipykernel_launcher.py:35: ComplexWarning: Casting complex values to real discards the imaginary part
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/ipykernel_launcher.py:70: ComplexWarning: Casting complex values to real discards the imaginary part
0.8833056895221885
0.7404062275757255
0.8091891476664499
0.5951720668847402
0.39062534343372135
0.2931639114976957
0.5604281659812129
0.560080687994932
0.4803820195483641
0.5324588876270797
0.4685752608919278
0.3282579558887714
0.24711074171070913
0.2844236577697423
0.25260564852823797
0.3150509699174163
0.2992825712207584
0.2139070770671957
0.2244990546173472
0.22613139095989798
0.172829276048014
0.1600018428675094
0.19562164408593274
0.1587687310399153
0.17179896136502615
0.15123167889056754
0.1310353184387082
0.14748215199832526
0.12955815255339975
0.12938049063121726
0.1507987572368068
0.15614975859029057
0.12583784975341972
0.1370405913395396
0.12190998301674683
0.13850716852312062
0.14937640643261818
0.12490627765037154
0.126062749819002
0.11862847675452592
0.12757317305757454
0.11629015246752805
0.09545897096537115
0.0844605964901024
0.09215242076941255
0.07930000643513602
0.08295022225910409
0.06880125309019802
0.08789085024962462
0.0723822703567113
0.058960738324484896
0.056295204949769584
0.050240678318537846
0.04862239722404582
0.055474029210123676
0.04083178628298989
0.031132847620148896
0.016056639832908615
0.01686491697274073
0.015490388498731411
0.01562984776458587
0.01577706325406525
0.01393481747356018
0.011078923747476321
0.007931871992739037
0.009189516314713653
0.007179211217900883
0.013201983069383583
0.00826294682496198
0.011680689511930464
0.018056710444077972
0.007335967048391123
0.027127591463935397
0.012070902637693615
0.007143062809405132
0.0117395654651401
0.006705055189160314
0.0067266104437182506
0.006754904523539995
0.005294953545512349
0.007544273046776517
0.005458623097653215
0.0050339577062862295
0.0024171197249938103
0.0016098687721065597
0.0032127849094635286
0.001373458196467836
0.0018154527446835322
0.0026063693356888074
0.0018413611793377527
0.0012656961602972583
0.001912613576024902
0.0013032878567653672
0.004780452278314473
0.001248468156262672
0.0012787369680381522
0.0012037205835343512
0.0011819210497052701
0.0016027785143645223
0.0013230294807701215
0.0013609173328812396
0.000993732252732915
0.0017779800894820452
0.0010510907889442755
0.0009585942467664754
0.0008629138723946772
0.0010207518625582335
0.0006872668365267565
0.0007062083333057023
0.0007503080958982666
0.000717567162378363
0.0006974796215615253
0.0008486177438721265
0.000731447125851159
0.0006952466460919959
0.0007171419288046765
0.0006876656453529417
0.0006411945852227152
0.0006275005832183655
0.0006110590451339215
0.0006290570042071231
0.0006190654053689348
0.0006313325807618675
0.0006213165772820384
0.0006300475953494589
0.0006285936302956596
0.0005852557855583473
0.000570849350115421
0.0005452201202065243
0.0005709851427690982
0.0005471887071138992
0.0005232308682776576
0.0005093662530177845
0.0005154825245138328
0.0005145268097240807
0.0005064587932218645
0.00048581679698223024
0.00047943478559497876
0.00046007172799755747
0.00043227019767499986
0.00041912544469857593
0.00042180585008277927
0.000416069680302944
0.000418961174539767
0.00041967137368525975
0.000423278283357309
0.00040882739119119105
0.000418054628174791
0.00040851017821808
0.0003929850801126511
0.00040519315841125447
0.00040283350265402085
0.00039305189321792167
0.00038345878865808647
0.00037134728038545894
0.00037184830193537355
0.000364222816488069
0.00036072429475597634
0.0003651575913563576
0.0003681988225339161
0.0003515884890532561
0.00033802764625257
0.00033391666385085284
0.0003339117476462983
0.0003228565502255698
0.00031204476190105357
0.0003024559400898186
0.00029174856775104896
0.00029017513764806324
0.0002888164939010007
0.00028381992889803254
0.00027023425572603177
0.0002584110031729203
0.00024804727164196017
0.00024058938257442986
0.00023633531008837583
0.00023716593024381005
0.00022830894277114933
0.00022049997496431661
0.00021843001411114837
0.00021941925638713222
0.00021066898491861608
0.00019966662854398187
0.0001905276970799452
0.00018340012108675197
0.0001773014823526209
0.00017482860435513725
0.00017237614918474975
0.0001667601670679586
0.00015890940988982916
0.00015275818329618662
0.00014971835524424382
0.00014134077118210797
0.00013506290672615773
0.00012918291166186258
0.00012854441887910628
0.0001322011719223637
0.00012002700169067015
0.0001162558506269118
0.0001115758871370609
     fun: 0.0001115758871370609
   maxcv: 0.0
 message: 'Maximum number of function evaluations has been exceeded.'
    nfev: 200
  status: 2
 success: False
       x: array([3.14090809, 2.17686771, 2.05968755, 3.16561892, 2.62000129,
       1.76616971, 1.55745791, 2.33026238, 3.02413357])
(0.9998884241081756-0j)

Again, very low error, $0.0001115758871370609$, and the classical cost function agrees, being $0.9998884241081756$! Great, so it works!

Now, we have found that this algorithm works in theory. I tried to run some simulations with a circuit that samples the circuit instead of calculating the probabilities numerically. Now, let's try to sample the quantum circuit, as a real quantum computer would do! For some reason, this simulation would only converge somewhat well for a ridiculously high number of "shots" (runs of the circuit, in order to calculate the probability distribution of outcomes). I think that this is mostly to do with limitations in the classical optimizer (COBYLA), due to the noisy nature of sampling a quantum circuit (a measurement with the same parameters won't always yield the same outcome). Luckily, there are other optimizers that are built for noisy functions, such as SPSA, but we won't be looking into that in this tutorial. Let's try our sampling for our second value of $A$, with the same matrix $U$:

In [15]:
#Implements the entire cost function on the quantum circuit (sampling, 100000 shots)

def calculate_cost_function(parameters):

    global opt

    overall_sum_1 = 0
    
    parameters = [parameters[0:3], parameters[3:6], parameters[6:9]]

    for i in range(0, len(gate_set)):
        for j in range(0, len(gate_set)):

            global circ

            qctl = QuantumRegister(5)
            qc = ClassicalRegister(1)
            circ = QuantumCircuit(qctl, qc)

            backend = Aer.get_backend('qasm_simulator')
            
            multiply = coefficient_set[i]*coefficient_set[j]

            had_test([gate_set[i], gate_set[j]], [1, 2, 3], 0, parameters)

            circ.measure(0, 0)

            job = execute(circ, backend, shots=100000)

            result = job.result()
            outputstate = result.get_counts(circ)

            if ('1' in outputstate.keys()):
                m_sum = float(outputstate["1"])/100000
            else:
                m_sum = 0

            overall_sum_1+=multiply*(1-2*m_sum)

    overall_sum_2 = 0

    for i in range(0, len(gate_set)):
        for j in range(0, len(gate_set)):

            multiply = coefficient_set[i]*coefficient_set[j]
            mult = 1

            for extra in range(0, 2):

                qctl = QuantumRegister(5)
                qc = ClassicalRegister(1)
                
                circ = QuantumCircuit(qctl, qc)

                backend = Aer.get_backend('qasm_simulator')

                if (extra == 0):
                    special_had_test(gate_set[i], [1, 2, 3], 0, parameters, qctl)
                if (extra == 1):
                    special_had_test(gate_set[j], [1, 2, 3], 0, parameters, qctl)

                circ.measure(0, 0)

                job = execute(circ, backend, shots=100000)

                result = job.result()
                outputstate = result.get_counts(circ)

                if ('1' in outputstate.keys()):
                    m_sum = float(outputstate["1"])/100000
                else:
                    m_sum = 0

                mult = mult*(1-2*m_sum)
            
            overall_sum_2+=multiply*mult
            
    print(1-float(overall_sum_2/overall_sum_1))

    return 1-float(overall_sum_2/overall_sum_1)
In [16]:
coefficient_set = [0.55, 0.225, 0.225]
gate_set = [[0, 0, 0], [0, 1, 0], [0, 0, 1]]

out = minimize(calculate_cost_function, x0=[float(random.randint(0,3000))/1000 for i in range(0, 9)], method="COBYLA", options={'maxiter':200})
print(out)

out_f = [out['x'][0:3], out['x'][3:6], out['x'][6:9]]

circ = QuantumCircuit(3, 3)
apply_fixed_ansatz([0, 1, 2], out_f)

backend = Aer.get_backend('statevector_simulator')

job = execute(circ, backend)

result = job.result()
o = result.get_statevector(circ, decimals=10)

a1 = coefficient_set[2]*np.array([[1,0,0,0,0,0,0,0], [0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0], [0,0,0,1,0,0,0,0], [0,0,0,0,-1,0,0,0], [0,0,0,0,0,-1,0,0], [0,0,0,0,0,0,-1,0], [0,0,0,0,0,0,0,-1]])
a0 = coefficient_set[1]*np.array([[1,0,0,0,0,0,0,0], [0,1,0,0,0,0,0,0], [0,0,-1,0,0,0,0,0], [0,0,0,-1,0,0,0,0], [0,0,0,0,1,0,0,0], [0,0,0,0,0,1,0,0], [0,0,0,0,0,0,-1,0], [0,0,0,0,0,0,0,-1]])
a2 = coefficient_set[0]*np.array([[1,0,0,0,0,0,0,0], [0,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0], [0,0,0,1,0,0,0,0], [0,0,0,0,1,0,0,0], [0,0,0,0,0,1,0,0], [0,0,0,0,0,0,1,0], [0,0,0,0,0,0,0,1]])

a3 = np.add(np.add(a2, a0), a1)

b = np.array([float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8)),float(1/np.sqrt(8))])

print((b.dot(a3.dot(o)/(np.linalg.norm(a3.dot(o)))))**2)
0.8367103788436497
0.7148710439728692
0.8472916820290619
0.6684217728672097
0.6204540862003505
0.48320953009803347
0.5524018686660065
0.6600568030865614
0.4543924845264439
0.4331738501571404
0.7223098948085269
0.6389624092262558
0.5610966938622768
0.4900673149774074
0.35956600130107197
0.3172619836354691
0.33956024013263075
0.32595505068299924
0.42619099290041396
0.27262379257243075
0.1056197780159075
0.3649759904214662
0.23234497678669153
0.19641858545457236
0.13691397503815317
0.16597120254045572
0.27694802421951803
0.37485142708483155
0.2544151463886435
0.11246143309087209
0.14181356273765167
0.07015901353669018
0.09920239632875139
0.09948761337998635
0.14184169586474749
0.10569052469756868
0.14532575059767083
0.11480759004021734
0.03750339657564061
0.07119901819539054
0.061502804132651856
0.05318717523193128
0.056058380304796374
0.0746784040917482
0.05441230423108967
0.05467688283319805
0.05791668421945817
0.05223278393765918
0.05939272293632325
0.06921505639866765
0.07390071355663874
0.04105308506641303
0.047763651904778714
0.048921939543102866
0.0736336436245173
0.07429398245696428
0.04635093215684494
0.06647371729144658
0.05444129892130434
0.05703802358920218
0.05576537231308454
0.07311688744602385
0.06765398043935089
0.042505138999036296
0.060181400577737354
0.05086337384429751
0.07011936556261777
0.06462638676549326
0.05256482191909062
0.05821651162494279
0.051202925363357576
0.04961269813116076
0.03711896679680893
0.06785395379937675
0.07175636590040035
0.03700981821914373
0.05248495031608247
0.06354018533943195
0.057949648610918336
0.0663240709996149
0.0628206767716748
0.054605112218120255
0.041664816763141266
0.04464293699392341
0.06340368716046885
0.05965617146012514
0.06523211100374937
0.04153988526258423
0.04408866925717747
0.05990492273102621
0.04555626637126731
0.0358077476140638
0.05466741179158696
0.05143602957514515
0.07689244956525798
0.061283749585028024
0.04705052612849048
0.04094344848698461
0.06655007121072642
0.055622878557913924
0.07604577707602356
0.0696804883352129
0.03677467713908489
     fun: 0.03677467713908489
   maxcv: 0.0
 message: 'Optimization terminated successfully.'
    nfev: 103
  status: 1
 success: True
       x: array([3.1092751 , 2.84541129, 2.19177542, 2.26913578, 1.03921624,
       2.24045306, 2.50589403, 4.27790656, 2.48093736])
(0.9465619648128146-0j)

So as you can see, not amazing, our solution is still off by a fairly significant margin ($3.677\%$ error isn't awful, but ideally, we want it to be much closer to 0). Again, I think this is due to the optimizer itself, not the actual quantum circuit. I will be making an update to this Notebook once I fugre out how to correct this problem (likely with the intoruction of a noisy optimizer, as I previously mentioned).

Acknowledgements

This implementation is based off of the work presented in the research paper "Variational Quantum Linear Solver: A Hybrid Algorithm for Linear Systems", written by Carlos Bravo-Prieto, Ryan LaRose, M. Cerezo, Yiğit Subaşı, Lukasz Cincio, and Patrick J. Coles, which is available at this link.

Special thanks to Carlos Bravo-Prieto for personally helping me out, by answering some of my questions concerning the paper!

In [ ]: