{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# HHL Algorithm\n",
"\n",
"[](https://mindspore-website.obs.cn-north-4.myhuaweicloud.com/notebook/r2.7.0rc1/mindquantum/en/case_library/mindspore_hhl_algorithm.ipynb) \n",
"[](https://mindspore-website.obs.cn-north-4.myhuaweicloud.com/notebook/r2.7.0rc1/mindquantum/en/case_library/mindspore_hhl_algorithm.py) \n",
"[](https://gitee.com/mindspore/docs/blob/r2.7.0rc1/docs/mindquantum/docs/source_en/case_library/hhl_algorithm.ipynb)\n",
"\n",
"## Overview\n",
"\n",
"**Objective of the HHL algorithm:** Given a Hermitian matrix $A$ and a unit vector $\\vec{b}$, the goal is to solve the equation $A \\vec{x} = \\vec{b}$.\n",
"\n",
"Let $\\left| b \\right\\rangle = \\sum_{j=1}^{N} b_{j} \\left| j \\right\\rangle$, where $\\left| j \\right\\rangle$ represents the basis states. The key of the algorithm lies in simulating $e^{i A \\Delta t}$ on $\\left| b \\right\\rangle$.\n",
"\n",
"Assume the spectral decomposition of $A$ is as follows:\n",
"\n",
"$$A = \\sum_{j=1}^{N} \\lambda_{j} \\left| u_{j} \\right\\rangle \\left\\langle u_{j} \\right|$$\n",
"\n",
"Then,\n",
"\n",
"$$e^{i A \\Delta t} = \\sum_{j=1}^{N} e^{i \\lambda_{j} \\Delta t} \\left| u_{j} \\right\\rangle \\left\\langle u_{j} \\right|$$\n",
"\n",
"Express $\\left| b \\right\\rangle$ in terms of the basis $\\left\\lbrace \\left| u_{j} \\right\\rangle \\right\\rbrace$: $\\left| b \\right\\rangle = \\sum_{j=1}^{N} \\beta_{j} \\left| u_{j} \\right\\rangle$.\n",
"\n",
"Using Quantum Phase Estimation (QPE), where $U = e^{i A \\Delta t}$, the resulting transformation is as follows:\n",
"\n",
"$$\\left| b \\right\\rangle \\xrightarrow{\\text{QPE}} \\sum_{j=1}^{N} \\beta_{j} \\left| u_{j} \\right\\rangle | \\widetilde{\\lambda_j} \\rangle$$\n",
"\n",
"Here, $| \\widetilde{\\lambda_j} \\rangle$ is the estimation of the eigenvalue $\\lambda_{j}$ (the tilde represents an estimation, the same applies in the following).\n",
"\n",
"It is easy to see that the solution to the equation is:\n",
"\n",
"$$\\left| x \\right\\rangle = A^{-1} \\left| b \\right\\rangle = \\sum_{j} \\beta_{j} (\\lambda_{j})^{-1} \\left| u_{j} \\right\\rangle$$\n",
"\n",
"Therefore, we only need to extract the information from the quantum state $| \\widetilde{\\lambda_j} \\rangle$.\n",
"\n",
"## Steps of the HHL Algorithm\n",
"\n",
"Below, we provide a detailed explanation of the steps involved in the HHL algorithm, including the mathematical derivations.\n",
"\n",
"### Data Preprocessing\n",
"\n",
"As mentioned earlier, $A$ needs to be Hermitian, i.e., $A^\\dagger = A$. However, this condition can be relaxed. If $A$ is not Hermitian, we can construct $\\tilde{A}$ as follows:\n",
"\n",
"$$\n",
"\\tilde{A} = \\begin{pmatrix}\n",
"0 & A \\\\\n",
"A^{\\dagger } & 0 \\\\\n",
"\\end{pmatrix}\n",
"$$\n",
"\n",
"Then, we solve the equation:\n",
"\n",
"$$\n",
"\\tilde{A} \\vec{y} = \\begin{pmatrix}\n",
"\\vec{b} \\\\\n",
"0 \\\\\n",
"\\end{pmatrix}\n",
"$$\n",
"\n",
"It can be easily verified that the solution to this equation, $\\vec{y}$, has the following form:\n",
"\n",
"$$\n",
"\\vec{y} = \\begin{pmatrix}\n",
"0 \\\\\n",
"\\vec{x} \\\\\n",
"\\end{pmatrix}\n",
"$$\n",
"\n",
"where $A \\vec{x} = \\vec{b}$.\n",
"\n",
"For $\\vec{b}$, since HHL is a quantum algorithm, the input should be a quantum state $|b\\rangle = \\sum_{j=1}^N b_j |j\\rangle$. The details of how to prepare such a quantum state and encode classical information into quantum information are beyond the scope of this algorithm. Here, we assume that the quantum state has been prepared accordingly."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Preparation of Operator $U = e^{i A \\Delta t}$\n",
"\n",
"The efficient preparation of the operator $U = e^{i A \\Delta t}$ is a core problem. As we will see later, the complexity of the entire HHL algorithm mainly depends on the operator $U$, so it is necessary to efficiently simulate $U$.\n",
"\n",
"The preparation of this time evolution operator $U = e^{i A \\Delta t}$ belongs to the problem of quantum system simulation (Hamiltonian simulation), which is an important quantum problem that will not be discussed in detail here.\n",
"\n",
"In the original paper, a **sparsity** constraint was imposed on the matrix $A$ in order to efficiently simulate $e^{i A \\Delta t}$. For general dense matrices $A$, simulating their evolution can be computationally expensive.\n",
"\n",
"Here, we won't go into the proof of the correctness of QPE. Readers only need to know that the input of QPE is a unitary operator $U$ and its eigenvector $|u\\rangle$, and the output is an estimate $\\tilde{\\varphi}$ of the phase $\\varphi$ such that $U |u\\rangle = e^{2 \\pi i \\varphi} |u\\rangle$.\n",
"\n",
"Specifically, using $t$ auxiliary qubits, the action of QPE is as follows:\n",
"\n",
"$$\\left| b \\right\\rangle \\left| 0 \\right\\rangle^{\\otimes t} \\left| 0 \\right\\rangle = \\sum_{j=1}^{N} \\beta_{j} \\left| u_{j} \\right\\rangle \\left| 0 \\right\\rangle^{\\otimes t} \\left| 0 \\right\\rangle\n",
"\\xrightarrow{\\text{QPE}} \\sum_{j=1}^{N} \\beta_{j} \\left| u_{j} \\right\\rangle \\left| \\widetilde{\\varphi_j} \\right\\rangle \\left| 0 \\right\\rangle$$\n",
"\n",
"Here, $\\left| \\widetilde{\\varphi_j} \\right\\rangle$ is the estimate of the phase $\\varphi_{j}$. An additional auxiliary qubit is added after the $t$ auxiliary qubits for the subsequent rotation step.\n",
"\n",
"To better understand, let's take an example:\n",
"Take\n",
"\n",
"$$A = Z = \\left| 0 \\right\\rangle \\left\\langle 0 \\right| - \\left| 1 \\right\\rangle \\left\\langle 1 \\right|$$\n",
"\n",
"Then\n",
"\n",
"$$U = e^{i A \\Delta t } = e^{i \\Delta t} \\left| 0 \\right\\rangle \\left\\langle 0 \\right| + e^{-i \\Delta t} \\left| 1 \\right\\rangle \\left\\langle 1 \\right|$$\n",
"\n",
"The two phases are $\\varphi_{1} = \\Delta t / 2 \\pi$ and $\\varphi_{2} = -\\Delta t / 2 \\pi$.\n",
"\n",
"If we use $t = 4$ auxiliary qubits and take $\\Delta t = \\pi / 4$, then $\\varphi_{1} = 1 / 8$ and $\\varphi_{2} = - 1 / 8$.\n",
"\n",
"The estimated values of the two phases are $\\widetilde{\\varphi_1} = 0.0010 \\times 2^4 = 2$ and $\\widetilde{\\varphi_2} = 0.1110 \\times 2^4 = 14$.\n",
"Since the phase is a decimal between $[0, 1)$, multiplying it by $2^t$ gives its corresponding quantum state $|q_{t_1} \\ldots q_{t_t} \\rangle$.\n",
"It should be noted that because the phase is a decimal modulo $1$, $-0.0010$ is mapped to $0.1110$. To restore the phase (to restore $\\lambda$), we first select a small enough $\\Delta t$ such that $|\\varphi| < 1 / 2$. This way, if $|q_{t_1} \\ldots q_{t_t}\\rangle < 2^{t-1}$ corresponds to a positive number, $|q_{t_1}\\ldots q_{t_t}\\rangle > 2^{t-1}$ corresponds to a negative number.\n",
"\n",
"Through simple quantitative calculations, we obtain the following mapping relationship:\n",
"\n",
"$$\n",
"\\frac{\\lambda \\Delta t}{2 \\pi} = \\varphi = \\begin{cases}\n",
"\\tilde{\\varphi} / 2^{t} & , \\varphi > 0 & , \\tilde{\\varphi} < 2^{t-1} \\\\\n",
"\\tilde{\\varphi} / 2^{t} - 1 & , \\varphi < 0 & , \\tilde{\\varphi} > 2^{t-1}\\\\\n",
"\\end{cases}\n",
"$$\n",
"\n",
"Here, $\\lambda$ is the eigenvalue of $A$, $\\varphi$ is the phase of $U = e^{i A \\Delta t}$, and $\\tilde{\\varphi}$ is the estimate of $\\varphi$."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Conditional Rotation\n",
"\n",
"After QPE, the overall quantum state is as follows:\n",
"\n",
"$$\n",
"\\sum_{j=1}^{N} \\beta_{j} \\left| u_{j} \\right\\rangle \\left| \\widetilde{\\varphi_j} \\right\\rangle \\left| 0 \\right\\rangle\n",
"$$\n",
"\n",
"To extract the information of $\\lambda_j$ from the quantum state $\\left| \\widetilde{\\varphi_j} \\right\\rangle$, we need to use conditional rotation gates $CR(k)$, which have the following effect:\n",
"\n",
"$$\n",
"CR(k) \\left| \\tilde{\\varphi} \\right\\rangle \\left| b \\right\\rangle = \\begin{cases}\n",
"\\left| \\tilde{\\varphi} \\right\\rangle \\left| b \\right\\rangle & , k \\neq \\tilde{\\varphi} \\\\\n",
"\\left| \\tilde{\\varphi} \\right\\rangle R_y \\left( 2 \\arcsin \\frac{C}{\\lambda} \\right) \\left| b \\right\\rangle & , k = \\tilde{\\varphi} \\\\\n",
"\\end{cases}\n",
"$$\n",
"\n",
"In simple terms, the rotation operation is only applied to the subsequent qubits when $k$ selects the correct $\\tilde{\\varphi}$.\n",
"\n",
"Since we don't know the correct $\\tilde{\\varphi}$, we brute force all possible $CR(k)$, where $k = 1, \\ldots , 2^{t}-1$.\n",
"\n",
"The effect of the rotation is straightforward:\n",
"\n",
"$$\n",
"\\prod_{k=1}^{2^{t} - 1} I\\otimes CR(k) \\sum_{j=1}^{N} \\beta_{j} \\left| u_{j} \\right\\rangle \\left| \\widetilde{\\varphi_j} \\right\\rangle \\left| 0 \\right\\rangle\n",
"= \\sum_{j=1}^{N} \\beta_{j} \\left| u_{j} \\right\\rangle \\left| \\widetilde{\\varphi_j} \\right\\rangle \\left( \\sqrt{1 - \\left( \\frac{C}{\\lambda_{j}} \\right)^{2}} \\left| 0 \\right\\rangle + \\frac{C}{\\lambda_{j}} \\left| 1 \\right\\rangle \\right)\n",
"$$\n",
"\n",
"After applying inverse QPE once again, the overall quantum state is as follows:\n",
"\n",
"$$\n",
"\\left| \\psi \\right\\rangle = \\sum_{j=1}^{N} \\beta_{j} \\left| u_{j} \\right\\rangle \\left| 0 \\right\\rangle^{\\otimes t} \\left( \\sqrt{1 - \\left( \\frac{C}{\\lambda_{j}} \\right)^{2}} \\left| 0 \\right\\rangle + \\frac{C}{\\lambda_{j}} \\left| 1 \\right\\rangle \\right)\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Measurement\n",
"\n",
"Measure the last qubit. When the measurement result is $\\left| 1 \\right\\rangle$, the probability is\n",
"\n",
"$$\n",
"p_1 = C^{2} \\sum_{j=1}^{N} ( \\beta_{j} / \\lambda_{j} )^{2}\n",
"$$\n",
"\n",
"After the measurement, the quantum state becomes\n",
"\n",
"$$\n",
"\\left| \\psi_{1} \\right\\rangle = \\frac{1}{\\left( \\sum_{j=1}^{N} \\left( \\beta_{j} / \\lambda_{j} \\right)^{2} \\right)^{-1}} \\sum_{j=1}^{N} \\frac{\\beta_{j}}{\\lambda_{j}} \\left| u_{j} \\right\\rangle \\left| 0 \\right\\rangle^{\\otimes t} \\left| 1 \\right\\rangle\n",
"$$\n",
"\n",
"Clearly, there is no entanglement between the three quantum registers at this point. If we only look at the first quantum register, it is already in the state $|x\\rangle$ (ignoring a normalization factor).\n",
"\n",
"It should be noted that there is a parameter $C$ in the rotation operation. We see that $C$ does not affect the correctness of the final result, but it does affect the probability $p_1$ of obtaining the result. We certainly hope that $C$ can be as large as possible, so that $p_1$ can be maximized. However, $C \\leq \\left\\vert \\lambda_{j} \\right\\vert$, it is smaller than the absolute value of all eigenvalues. If there is no prior information about the smallest absolute value of $\\lambda$, we can only conservatively choose a very small $C$ and then use amplitude amplification techniques to increase the probability of obtaining the result."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Implementation with MindQuantum\n",
"\n",
"Here, we use MindQuantum to implement a simple example to illustrate the process and correctness of the HHL algorithm.\n",
"\n",
"For convenience, we choose a simple matrix $A = Z = \\begin{bmatrix}\n",
"1 & 0 \\\\\n",
"0 & -1\n",
"\\end{bmatrix}$, because its time evolution operator $e^{i Z \\Delta t} = R_z(- 2 \\Delta t)$ is relatively easy to implement."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"eigenvalues of A:\n",
" [ 1. -1.]\n",
"eigenvectors of A:\n",
" [[1. 0.]\n",
" [0. 1.]]\n",
"b: [0.6 0.8]\n",
"Solution of Ax=b is: [ 0.6 -0.8]\n"
]
}
],
"source": [
"import numpy as np\n",
"\n",
"A = np.array([[1, 0], [0, -1]])\n",
"es, vs = np.linalg.eig(A)\n",
"\n",
"print(f\"eigenvalues of A:\\n {es}\")\n",
"print(f\"eigenvectors of A:\\n {vs}\")\n",
"\n",
"b = np.array([0.6, 0.8])\n",
"print(f\"b: {b}\")\n",
"print(f\"Solution of Ax=b is: {np.linalg.solve(A, b)}\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here, we import various required functions:"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"from mindquantum.core.gates import H, X, RY, RZ, Measure, Power, BARRIER\n",
"from mindquantum.core.circuit import Circuit\n",
"from mindquantum.simulator import Simulator"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"For the preparation of the quantum state $|b\\rangle = \\cos\\theta |0\\rangle + \\sin\\theta |1\\rangle$, it can be achieved using an $R_y(2 \\theta)$ gate.\n",
"\n",
"The following code prepares the state $|b\\rangle = 0.6 |0\\rangle + 0.8 |1\\rangle$ and performs a measurement."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"image/svg+xml": [
""
],
"text/plain": [
""
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"circ = Circuit()\n",
"circ += RY(2 * np.arcsin(0.8)).on(0)\n",
"circ += Measure().on(0)\n",
"\n",
"sim = Simulator(backend=\"mqvector\", n_qubits=1)\n",
"res = sim.sampling(circ, shots=10000)\n",
"res.svg()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The following is the step-by-step construction of the complete quantum circuit, with $t = 4$, $\\Delta t = \\pi / 4$, and $C = 0.5$.\n",
"\n",
"- First is QPE.\n",
"- Then comes $CR(k)$, $k = 1, \\ldots, 15$.\n",
"- Next is inverse QPE.\n",
"- Finally, measurement is performed."
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"image/svg+xml": [
""
],
"text/plain": [
""
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from mindquantum.algorithm.library import qft\n",
"\n",
"# q1 ~ q4 : for QPE\n",
"t = 4\n",
"qc = [4, 3, 2, 1]\n",
"\n",
"# store |b> , and store the result |x>\n",
"qb = 5\n",
"\n",
"# use for conditional rotation\n",
"qs = 0\n",
"\n",
"# choose a time evolution\n",
"dt = np.pi / 4\n",
"\n",
"# choose a small C\n",
"C = 0.5\n",
"\n",
"circ = Circuit()\n",
"\n",
"# prepare b\n",
"circ += RY(2 * np.arcsin(0.8)).on(qb)\n",
"\n",
"# QPE\n",
"for i in qc:\n",
" circ += H.on(i)\n",
"\n",
"for (i, q) in enumerate(qc):\n",
" circ += Power(RZ(-2 * dt), 2**i).on(qb, q)\n",
"\n",
"# apply inverse QFT\n",
"circ += qft(list(reversed(qc))).hermitian()\n",
"\n",
"# conditional rotate\n",
"circ += BARRIER\n",
"for k in range(1, 2**t):\n",
" for i in range(t):\n",
" if (k & (1 << i)) == 0:\n",
" circ += X.on(qc[i])\n",
" phi = k / (2**t)\n",
" if k > 2**(t-1):\n",
" phi -= 1.0\n",
" l = 2 * np.pi / dt * phi\n",
" circ += RY(2 * np.arcsin(C / l)).on(qs, qc)\n",
"\n",
" for i in range(t):\n",
" if (k & (1 << i)) == 0:\n",
" circ += X.on(qc[i])\n",
" circ += BARRIER\n",
"\n",
"# apply inverse QPE\n",
"circ += qft(list(reversed(qc)))\n",
"\n",
"for (i, q) in enumerate(qc):\n",
" circ += Power(RZ(2 * dt), 2**i).on(qb, q)\n",
"\n",
"for i in qc:\n",
" circ += H.on(i)\n",
"\n",
"circ.svg()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"How do we verify the correctness of our results? Through measurement. Since the result is a quantum state $|x\\rangle$, currently MindQuantum does not have a method to directly extract the internal values of a specific qubit. Therefore, we can only obtain information about the state through measurement."
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"image/svg+xml": [
""
],
"text/plain": [
""
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"sim = Simulator(backend=\"mqvector\", n_qubits=2 + t)\n",
"sim.apply_circuit(circ)\n",
"\n",
"circ_m = Circuit()\n",
"circ_m += Measure().on(qs)\n",
"circ_m += Measure().on(qb)\n",
"\n",
"res = sim.sampling(circ_m, shots=100000)\n",
"res.svg()"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"0.3612780010344965"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"res.data.get(\"01\", 0) / (res.data.get(\"01\", 0) + res.data.get(\"11\", 0))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"By statistically analyzing the measurement results of `q5` when `q0` is 1, we observe that the proportion of `q5 = 0` is `0.36`, which is consistent with the expected answer.\n",
"\n",
"However, this method only provides information about the magnitude of the amplitudes. To obtain more information, such as phase, adjustments to the measurement would be required, but we won't discuss that here."
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"\n",
"