提交 f43b4d97 编写于 作者: Q Quleaf

slight update

上级 ae59b7d7
...@@ -55,7 +55,7 @@ Paddle Quantum aims at establishing a bridge between artificial intelligence (AI ...@@ -55,7 +55,7 @@ Paddle Quantum aims at establishing a bridge between artificial intelligence (AI
## Features ## Features
- Easy-to-use - Easy-to-use
- Many online learning resources (23+ tutorials) - Many online learning resources (37+ tutorials)
- High efficiency in building QNN with various QNN templates - High efficiency in building QNN with various QNN templates
- Automatic differentiation - Automatic differentiation
- Versatile - Versatile
...@@ -90,7 +90,7 @@ pip install -e . ...@@ -90,7 +90,7 @@ pip install -e .
### Environment setup for Quantum Chemistry module ### Environment setup for Quantum Chemistry module
Our qchem module is based on `Openfermion` and `Psi4`, so before executing quantum chemistry, we have to install the two Python packages first. Our `qchem` module is based on `Openfermion` and `Psi4`, so before executing quantum chemistry, we have to install the two Python packages first.
> It is recommended that these Python packages be installed in a Python 3.8 environment. > It is recommended that these Python packages be installed in a Python 3.8 environment.
......
...@@ -55,7 +55,7 @@ ...@@ -55,7 +55,7 @@
## 特色 ## 特色
- 轻松上手 - 轻松上手
- 丰富的在线学习资源(23+ 教程案例) - 丰富的在线学习资源(37+ 教程案例)
- 通过模板高效搭建量子神经网络 - 通过模板高效搭建量子神经网络
- 自动微分框架 - 自动微分框架
- 功能丰富 - 功能丰富
...@@ -91,7 +91,7 @@ pip install -e . ...@@ -91,7 +91,7 @@ pip install -e .
### 量子化学模块的环境设置 ### 量子化学模块的环境设置
我们的量子化学模块是基于 `Openfermion``Psi4` 进行开发的,所以在运行量子化学模块之前需要先行安装这两个Python包。 我们的量子化学模块是基于 `Openfermion``Psi4` 进行开发的,所以在运行量子化学模块之前需要先行安装这两个 Python 包。
> 推荐在 Python3.8 环境中安装这些 Python包。 > 推荐在 Python3.8 环境中安装这些 Python包。
......
...@@ -334,7 +334,7 @@ class MCalculus: ...@@ -334,7 +334,7 @@ class MCalculus:
# Measurement pattern of CNOT by 15 qubits, c.f. [arXiv: quant-ph/0301052v2] # Measurement pattern of CNOT by 15 qubits, c.f. [arXiv: quant-ph/0301052v2]
# Note: due to the '1' in byproduct Z of qubit-7, we manually add a Z gate after qubit 7 to match this # Note: due to the '1' in byproduct Z of qubit-7, we manually add a Z gate after qubit 7 to match this
elif name == "cnot_15": # Control Not gate elif name == "cnot_15": # Controlled Not gate
input1, input2 = input_ input1, input2 = input_
output1, output2 = output_ output1, output2 = output_
ancilla = self.__set_ancilla_label(input_, output_, [7, 5]) ancilla = self.__set_ancilla_label(input_, output_, [7, 5])
...@@ -381,7 +381,7 @@ class MCalculus: ...@@ -381,7 +381,7 @@ class MCalculus:
commands = [E12, E23, E34, E45, E48, E56, E67, E716, E1617, E910, E1011, E1112, E812, E1213, E1314, E1415, commands = [E12, E23, E34, E45, E48, E56, E67, E716, E1617, E910, E1011, E1112, E812, E1213, E1314, E1415,
M1, M2, M3, M4, M5, M6, M8, M12, M9, M10, M11, M13, M14, M7, M16, X15, X17, Z15, Z17] M1, M2, M3, M4, M5, M6, M8, M12, M9, M10, M11, M13, M14, M7, M16, X15, X17, Z15, Z17]
elif name == 'cz': # Control Z gate elif name == 'cz': # Controlled Z gate
commands = [Pattern.CommandE(input_)] commands = [Pattern.CommandE(input_)]
elif name == 'm': # Single-qubit measurement elif name == 'm': # Single-qubit measurement
......
...@@ -108,7 +108,7 @@ class Circuit: ...@@ -108,7 +108,7 @@ class Circuit:
.. math:: .. math::
H = \frac{1}{\sqrt{2}}\begin{bmatrix} 1&1\\1&-1 \end{bmatrix} \frac{1}{\sqrt{2}}\begin{bmatrix} 1&1\\1&-1 \end{bmatrix}
Args: Args:
which_qubit (int): 作用量子门的量子位编号 which_qubit (int): 作用量子门的量子位编号
...@@ -236,7 +236,7 @@ class Circuit: ...@@ -236,7 +236,7 @@ class Circuit:
.. math:: .. math::
T = \begin{bmatrix} 1&0\\0& i} \end{bmatrix} \begin{bmatrix} 1&0\\0& i \end{bmatrix}
Args: Args:
which_qubit (int): 作用量子门的量子位编号 which_qubit (int): 作用量子门的量子位编号
...@@ -268,7 +268,7 @@ class Circuit: ...@@ -268,7 +268,7 @@ class Circuit:
.. math:: .. math::
T = \begin{bmatrix} 1&0\\0& e^{i\pi/ 4} \end{bmatrix} \begin{bmatrix} 1&0\\0& e^{i\pi/ 4} \end{bmatrix}
Args: Args:
which_qubit (int): 作用量子门的量子位编号 which_qubit (int): 作用量子门的量子位编号
...@@ -491,10 +491,7 @@ class Circuit: ...@@ -491,10 +491,7 @@ class Circuit:
.. math:: .. math::
\begin{align} \begin{bmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 1 \\ 0 & 0 & 1 & 0 \end{bmatrix}
CNOT &=|0\rangle \langle 0|\otimes I + |1 \rangle \langle 1|\otimes X\\
&=\begin{bmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 1 \\ 0 & 0 & 1 & 0 \end{bmatrix}
\end{align}
Args: Args:
which_qubits (list): 作用量子门的量子位,其中列表第一个元素为控制位,第二个元素为受控位 which_qubits (list): 作用量子门的量子位,其中列表第一个元素为控制位,第二个元素为受控位
...@@ -531,10 +528,7 @@ class Circuit: ...@@ -531,10 +528,7 @@ class Circuit:
.. math:: .. math::
\begin{align} \begin{bmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 1 \\ 0 & 0 & 1 & 0 \end{bmatrix}
CNOT &=|0\rangle \langle 0|\otimes I + |1 \rangle \langle 1|\otimes X\\
&=\begin{bmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 1 \\ 0 & 0 & 1 & 0 \end{bmatrix}
\end{align}
Args: Args:
which_qubits (list): 作用量子门的量子位,其中列表第一个元素为控制位,第二个元素为受控位 which_qubits (list): 作用量子门的量子位,其中列表第一个元素为控制位,第二个元素为受控位
...@@ -571,10 +565,7 @@ class Circuit: ...@@ -571,10 +565,7 @@ class Circuit:
.. math:: .. math::
\begin{align} \begin{bmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & -1 \end{bmatrix}
CZ &=|0\rangle \langle 0|\otimes I + |1 \rangle \langle 1|\otimes Z\\
&=\begin{bmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & -1 \end{bmatrix}
\end{align}
Args: Args:
which_qubits (list): 作用量子门的量子位,其中列表第一个元素为控制位,第二个元素为受控位 which_qubits (list): 作用量子门的量子位,其中列表第一个元素为控制位,第二个元素为受控位
......
...@@ -654,8 +654,7 @@ class MBQC: ...@@ -654,8 +654,7 @@ class MBQC:
r"""获取 MBQC 模型运行后的经典输出结果。 r"""获取 MBQC 模型运行后的经典输出结果。
Returns: Returns:
str or dict: 如果用户输入是测量模式,则返回测量输出节点得到的比特串,与原电路的测量结果相一致,没有被测量的比特位填充 "?"; str or dict: 如果用户输入是测量模式,则返回测量输出节点得到的比特串,与原电路的测量结果相一致,没有被测量的比特位填充 "?",如果用户输入是图,则返回所有节点的测量结果
如果用户输入是图,则返回所有节点的测量结果
""" """
# If the input is pattern, return the equivalent result as the circuit model # If the input is pattern, return the equivalent result as the circuit model
if self.__pattern is not None: if self.__pattern is not None:
......
...@@ -254,7 +254,7 @@ def t_gate(): ...@@ -254,7 +254,7 @@ def t_gate():
def cz_gate(): def cz_gate():
r"""定义 ``Control Z`` 门。 r"""定义 ``Controlled-Z`` 门。
其矩阵形式为: 其矩阵形式为:
...@@ -263,7 +263,7 @@ def cz_gate(): ...@@ -263,7 +263,7 @@ def cz_gate():
\begin{bmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & -1 \end{bmatrix} \begin{bmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & -1 \end{bmatrix}
Returns: Returns:
Tensor: ``Control Z`` 门矩阵对应的 ``Tensor`` 形式 Tensor: ``Controlled-Z`` 门矩阵对应的 ``Tensor`` 形式
代码示例: 代码示例:
...@@ -287,7 +287,7 @@ def cz_gate(): ...@@ -287,7 +287,7 @@ def cz_gate():
def cnot_gate(): def cnot_gate():
r"""定义 ``Control NOT (CNOT)`` 门。 r"""定义 ``Controlled-NOT (CNOT)`` 门。
其矩阵形式为: 其矩阵形式为:
...@@ -296,7 +296,7 @@ def cnot_gate(): ...@@ -296,7 +296,7 @@ def cnot_gate():
\begin{bmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 1 \\ 0 & 0 & 1 & 0 \end{bmatrix} \begin{bmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 1 \\ 0 & 0 & 1 & 0 \end{bmatrix}
Returns: Returns:
Tensor: ``Control NOT (CNOT)`` 门矩阵对应的 ``Tensor`` 形式 Tensor: ``Controlled-NOT (CNOT)`` 门矩阵对应的 ``Tensor`` 形式
代码示例: 代码示例:
...@@ -540,16 +540,13 @@ def basis(label, theta=to_tensor([0], dtype='float64')): ...@@ -540,16 +540,13 @@ def basis(label, theta=to_tensor([0], dtype='float64')):
常用的测量方式有 XY-平面测量,YZ-平面测量,X 测量,Y 测量,Z 测量。 常用的测量方式有 XY-平面测量,YZ-平面测量,X 测量,Y 测量,Z 测量。
.. math:: .. math::
\begin{align*}
M^{XY}(\theta) = {R_{z}(\theta)|+\rangle, R_{z}(\theta)|-\rangle} & M^{XY}(\theta) = \{R_{z}(\theta)|+\rangle, R_{z}(\theta)|-\rangle\}\\
& M^{YZ}(\theta) = \{R_{x}(\theta)|0\rangle, R_{x}(\theta)|1\rangle\}\\
M^{YZ}(\theta) = {R_{x}(\theta)|0\rangle, R_{x}(\theta)|1\rangle} & X = M^{XY}(0)\\
& Y = M^{YZ}(\pi / 2) = M^{XY}(-\pi / 2)\\
X = M^{XY}(0) & Z = M_{YZ}(0)
\end{align*}
Y = M^{YZ}(\pi / 2) = M^{XY}(-\pi / 2)
Z = M_{YZ}(0)
Args: Args:
label (str): 测量基索引字符,"XY" 表示 XY-平面测量,"YZ" 表示 YZ-平面测量,"X" 表示 X 测量,"Y" 表示 Y 测量,"Z" 表示 Z 测量 label (str): 测量基索引字符,"XY" 表示 XY-平面测量,"YZ" 表示 YZ-平面测量,"X" 表示 X 测量,"Y" 表示 Y 测量,"Z" 表示 Z 测量
......
...@@ -29,11 +29,8 @@ from paddle import matmul ...@@ -29,11 +29,8 @@ from paddle import matmul
from paddle import transpose from paddle import transpose
from paddle import concat, ones from paddle import concat, ones
from paddle import zeros from paddle import zeros
from scipy.linalg import logm, sqrtm
from scipy import sparse from scipy import sparse
import matplotlib.pyplot as plt
import matplotlib as mpl import matplotlib as mpl
from math import sqrt
from paddle_quantum import simulator from paddle_quantum import simulator
import matplotlib.animation as animation import matplotlib.animation as animation
...@@ -280,7 +277,7 @@ def NKron(matrix_A, matrix_B, *args): ...@@ -280,7 +277,7 @@ def NKron(matrix_A, matrix_B, *args):
Tensor: 输入矩阵的Kronecker积 Tensor: 输入矩阵的Kronecker积
.. code-block:: python .. code-block:: python
from paddle_quantum.state import density_op_random from paddle_quantum.state import density_op_random
from paddle_quantum.utils import NKron from paddle_quantum.utils import NKron
A = density_op_random(2) A = density_op_random(2)
...@@ -305,7 +302,7 @@ def dagger(matrix): ...@@ -305,7 +302,7 @@ def dagger(matrix):
代码示例: 代码示例:
.. code-block:: python .. code-block:: python
from paddle_quantum.utils import dagger from paddle_quantum.utils import dagger
import numpy as np import numpy as np
rho = paddle.to_tensor(np.array([[1+1j, 2+2j], [3+3j, 4+4j]])) rho = paddle.to_tensor(np.array([[1+1j, 2+2j], [3+3j, 4+4j]]))
...@@ -1522,3 +1519,83 @@ def plot_rotation_in_bloch_sphere( ...@@ -1522,3 +1519,83 @@ def plot_rotation_in_bloch_sphere(
update(len(bloch_vectors) - 2) update(len(bloch_vectors) - 2)
plt.show() plt.show()
def pauli_basis(n):
r"""生成 n 量子比特的泡利基空间
Args:
n (int): 量子比特的数量
Return:
tuple:
basis_str: 泡利基空间的一组基底表示(array形式)
label_str: 泡利基空间对应的一组基底表示(标签形式),形如``[ 'X', 'Y', 'Z', 'I']``
"""
sigma_x = np.array([[0, 1], [1, 0]], dtype=np.complex128)
sigma_y = np.array([[0, -1j], [1j, 0]], dtype=np.complex128)
sigma_z = np.array([[1, 0], [0, -1]], dtype=np.complex128)
sigma_id = np.array([[1, 0], [0, 1]], dtype=np.complex128)
pauli = [sigma_x, sigma_y, sigma_z, sigma_id]
labels = ['X', 'Y', 'Z', 'I']
num_qubits = n
num = 1
if num_qubits > 0:
basis_str = pauli[:]
label_str = labels[:]
pauli_basis = pauli[:]
palui_label = labels[:]
while num < num_qubits:
length = len(basis_str)
for i in range(4):
for j in range(length):
basis_str.append(np.kron(basis_str[j], pauli_basis[i]))
label_str.append(label_str[j] + palui_label[i])
basis_str = basis_str[-1:-4**(num+1)-1:-1]
label_str = label_str[-1:-4**(num+1)-1:-1]
num += 1
return basis_str, label_str
def decompose(matrix):
r"""生成 n 量子比特的泡利基空间
Args:
matrix (numpy.ndarray): 要分解的矩阵
Return:
pauli_form (list): 返回矩阵分解后的哈密顿量,形如 ``[[1, 'Z0, Z1'], [2, 'I']]``
"""
if np.log2(len(matrix)) % 1 != 0:
print("Please input correct matrix!")
return -1
basis_space, label_str = pauli_basis(np.log2(len(matrix)))
coefficients = [] # 对应的系数
pauli_word = [] # 对应的label
pauli_form = [] # 输出pauli_str list形式:[[1, 'Z0, Z1'], [2, 'I']]
for i in range(len(basis_space)):
# 求系数
a_ij = 1/len(matrix) * np.trace(matrix@basis_space[i])
if a_ij != 0:
if a_ij.imag != 0:
coefficients.append(a_ij)
else:
coefficients.append(a_ij.real)
pauli_word.append(label_str[i])
for i in range(len(coefficients)):
pauli_site = [] # 临时存放一个基
pauli_site.append(coefficients[i])
word = ''
for j in range(len(pauli_word[0])):
if pauli_word[i] == 'I'*int(np.log2(len(matrix))):
word = 'I' # 和Hamiltonian类似,若全是I就用一个I指代
break
if pauli_word[i][j] == 'I':
continue # 如果是I就不加数字下标
if j != 0 and len(word) != 0:
word += ','
word += pauli_word[i][j]
word += str(j) # 对每一个label加标签,说明是作用在哪个比特
pauli_site.append(word) # 添加上对应作用的门
pauli_form.append(pauli_site)
return pauli_form
...@@ -2,9 +2,10 @@ ...@@ -2,9 +2,10 @@
## 概述 ## 概述
基于测量的量子计算(Measurement-Based Quantum Computation, MBQC)模块是基于量桨开发的通用量子计算模拟工具。与传统的量子电路模型不同,MBQC 具有其独特的运行方式 [1-8],因而常见的电路模拟工具无法直接用于该模型的模拟。为了促进对 MBQC 的进一步研究和探索,我们在模块中设计并提供了模拟 MBQC 所需的多个核心模块。 基于测量的量子计算(Measurement-Based Quantum Computation, MBQC)模块是基于量桨开发的通用量子计算模拟工具。与传统的量子电路模型不同,MBQC 具有其独特的运行方式 [1-8],因而常见的电路模拟工具无法直接用于该模型的模拟。为了促进对 MBQC 的进一步研究和探索,我们设计并提供了模拟 MBQC 所需的多个核心模块。
一方面,与其他常见的量子电路模拟器一样,我们可以利用 MBQC 模块快速实现量子神经网络的搭建与训练,在诸如量子化学,量子自然语言处理,量子金融等人工智能领域具有强大的应用前景。另一方面,MBQC 模块在某些特殊情形下可以展现出其运算效率上的独特优势,特别是在多比特浅层量子电路模拟时可以大幅度降低计算资源的消耗,从而有潜力实现更大规模的量子算法模拟。 一方面,与其他常见的量子电路模拟器一样,我们可以利用 MBQC 模块快速实现量子神经网络的搭建与训练,在诸如量子化学,量子自然语言处理,量子金融等人工智能领域具有广阔的应用前景。另一方面,MBQC
模块在某些特殊情形下可以展现出其运算效率上的独特优势,特别是在多比特浅层量子电路模拟时可以大幅度降低计算资源的消耗,从而有潜力实现更大规模的量子算法模拟。
我们的模块是业界首个、目前也是唯一一个支持模拟 MBQC 量子计算模型的系统性工具。我们由衷地期待广大的量子计算爱好者和开发者进行使用和学习。欢迎加入我们,共同探索 MBQC 中更多的奥秘! 我们的模块是业界首个、目前也是唯一一个支持模拟 MBQC 量子计算模型的系统性工具。我们由衷地期待广大的量子计算爱好者和开发者进行使用和学习。欢迎加入我们,共同探索 MBQC 中更多的奥秘!
...@@ -62,7 +63,8 @@ state_out = mbqc.get_quantum_output() ...@@ -62,7 +63,8 @@ state_out = mbqc.get_quantum_output()
#### 测量模式调用方法 #### 测量模式调用方法
MBQC 和电路模型一样都可以实现通用量子计算,并且两者之间存在一一对应的关系。然而将电路模型转化到等价的 MBQC 测量模式过程复杂且计算量大 [9]。为此,我们在模块中提供了由量子电路模型自动翻译为测量模式的转义模块 `transpiler` 。我们可以直接使用类似于 [UAnstaz](https://qml.baidu.com/api/paddle_quantum.circuit.uansatz.html) 的调用格式来构建量子电路,将其自动翻译成测量模式,再接入模拟模块中运行。同样地,这里我们以实现单比特 `Hadamard` 门为例,简要展示其用法。 MBQC 和电路模型一样都可以实现通用量子计算,并且两者之间存在一一对应的关系。然而将电路模型转化为等价的 MBQC 测量模式过程复杂且计算量大 [9]。为此,我们在模块中提供了将量子电路模型自动翻译为测量模式的转义模块
`transpiler` 。我们可以直接使用类似于 [UAnstaz](https://qml.baidu.com/api/paddle_quantum.circuit.uansatz.html) 的调用格式来构建量子电路,将其自动翻译成测量模式,再接入模拟模块中运行。同样地,这里我们以实现单比特 `Hadamard` 门为例,简要展示其用法。
```python ```python
# 引入模块 # 引入模块
......
...@@ -2,11 +2,11 @@ ...@@ -2,11 +2,11 @@
## Introduction ## Introduction
Measurement-Based Quantum Computation (MBQC) module is a simulation tool for universal quantum computing, developed based on Baidu PaddlePaddle. Unlike the conventional quantum circuit model, MBQC has its unique way of computing [1-8] and thus common circuit simulation tools cannot be directly used for the simulation of this model. To facilitate further research and exploration of MBQC, we have designed and provided several core modules in the module that are required for simulation. Measurement-Based Quantum Computation (MBQC) module is a simulation tool for universal quantum computing, developed based on Paddle Quantum. Unlike the conventional quantum circuit model, MBQC has its unique way of computing [1-8] and thus common circuit simulation tools cannot be directly used for the simulation of this model. To facilitate further research and exploration of MBQC, we have designed and provided several core modules that are required for simulation.
On the one hand, as with common quantum circuit simulators, we can use the module to quickly build and train quantum neural networks, which have powerful application prospects in the field of artificial intelligence such as quantum chemistry, quantum natural language processing, and quantum finance. On the other hand, the MBQC module demonstrates its unique advantages in computational efficiency in some special cases, especially in quantum shallow circuit simulations, where the required computational resource can be significantly reduced, leading to a potential opportunity for larger-scale quantum algorithm simulations. On the one hand, as with common quantum circuit simulators, we can use the module to quickly build and train quantum neural networks, which have powerful application prospects in the field of artificial intelligence such as quantum chemistry, quantum natural language processing, and quantum finance. On the other hand, the MBQC module demonstrates its unique advantages in computational efficiency in some special cases, especially in quantum shallow circuit simulations, where the required computational resource can be significantly reduced, leading to a potential opportunity for larger-scale quantum algorithm simulations.
Our module is currently the first and the only systematic tool in the industry that supports the simulation of MBQC. We sincerely look forward to its learning and usage by quantum computing enthusiasts and researchers. Welcome to join us and discover the infinite possibilities of MBQC together! Our module is the first and only systematic tool in the industry that supports the simulation of MBQC. We sincerely look forward to its learning and usage by quantum computing enthusiasts and researchers. Welcome to join us and discover the infinite possibilities of MBQC together!
## Features ## Features
...@@ -103,7 +103,9 @@ shortly. ...@@ -103,7 +103,9 @@ shortly.
- Q: How is the MBQC physically implemented? - Q: How is the MBQC physically implemented?
A: The difficulty in the physical implementation of MBQC is mainly the preparation of resource states. Unlike the superconducting techniques used in the quantum circuit model, the resource states are mostly prepared using linear optics or cold atoms, see e.g. [2,12,13] for the currently available techniques for the resource states preparation. A: The difficulty in the physical implementation of MBQC is mainly the preparation of resource states. Unlike
the superconducting techniques used in the quantum circuit model, the resource states are mostly prepared using
linear optics or cold atoms, see e.g. [2,12,13] for the existing techniques of resource states preparation.
## References ## References
......
...@@ -16,18 +16,24 @@ ...@@ -16,18 +16,24 @@
"source": [ "source": [
"## 概述\n", "## 概述\n",
"\n", "\n",
"量子计算利用量子世界中特有的运行规律,为我们提供了一条全新的并且非常有前景的信息处理方式。其计算的本质是通过特定的方式将初始制备的量子态演化成我们预期的另一个量子态,然后在该量子态上做测量以获得计算结果。但是在不同模型下,量子态的演化方式各异。我们比较常用的**量子电路模型 (quantum circuit model)** [1,2] 是通过对量子态进行量子门操作来完成演化,该模型可以理解为经典计算模型的量子版本,并且被广泛地应用在量子计算领域中。**基于测量的量子计算 (measurement-based quantum computation, MBQC)** 是一种完全不同于量子电路模型的计算方式。\n", "量子计算利用量子世界中特有的运行规律,为我们提供了一种全新的并且非常有前景的信息处理方式。其计算的本质是通过特定的方式将初始制备的量子态演化成我们预期的另一个量子态,然后在演化后的量子态上做测量以获得计算结果。但是在不同模型下,量子态的演化方式各异。比较常用的**量子电路模型 (quantum circuit model)** [1,2] 通过对量子态进行量子门操作来完成演化,该模型可以理解为经典计算模型的量子版本,被广泛地应用在量子计算领域中。而**基于测量的量子计算 (measurement-based quantum computation, MBQC)** 是一种完全不同于量子电路模型的计算方式。\n",
"\n", "\n",
"顾名思义,MBQC 模型的计算过程是通过量子测量完成的。基于测量的量子计算主要有两种子模型:**隐形传态量子计算 (teleportation-based quantum computing, TQC)** 模型 [3-5] 和**单向量子计算机 (one-way quantum computer, 1WQC)** 模型 [6-9]。其中,前者需要用到多量子比特的联合测量,而后者只需要单比特测量即可。有趣的是,这两种子模型在被分别提出后,被证明是高度相关并且一一对应的 [10]。所以我们后面将不加声明地,**默认讨论的 MBQC 模型为 1WQC 模型。**\n", "顾名思义,MBQC 模型的计算过程是通过量子测量完成的。基于测量的量子计算主要有两种子模型:**隐形传态量子计算 (teleportation-based quantum computing, TQC)** 模型 [3-5]\n",
"和**单向量子计算机 (one-way quantum computer, 1WQC)** 模型\n",
"[6-9]。其中,前者需要用到多量子比特的联合测量,而后者只需要单比特测量即可。有趣的是,这两种子模型在被分别提出后,被证明是高度相关并且一一对应的 [10]。所以我们此后将不加声明地,**默认讨论的 MBQC 模型为 1WQC 模型。**\n",
"\n", "\n",
"与电路模型不同,MBQC 是量子计算特有的一种模型,没有经典计算的对应。该模型的核心思想在于对一个量子纠缠态的部分比特进行测量,未被测量的量子系统将会实现相应的演化,并且通过对测量方式的控制,我们可以实现任意需要的演化。MBQC 模型下的计算过程主要分为三个步骤:第一步,准备一个**资源态 (resource state)**,即一个高度纠缠的多体量子态,该量子态可以在计算开始之前准备好,且可以与具体计算任务无关;第二步,对准备好的资源态的每个比特依次做单比特测量,其中后续比特的测量方式可以根据已经被测量的比特的测量结果做出相应调整,即允许**适应性测量 (adaptive measurement)**;第三步,对测量后得到的量子态进行 **副产品纠正 (byproduct correction)**。最后,我们对所有比特的测量结果进行经典数据处理,即可得到需要的计算结果。\n", "与电路模型不同,MBQC 是量子计算特有的一种模型,没有经典计算模型的对应。该模型的核心思想在于对一个量子纠缠态的部分比特进行测量,未被测量的量子系统将会实现相应的演化,并且通过对测量方式的控制,我们可以实现任意需要的演化。MBQC\n",
"模型下的计算过程主要分为三个步骤:第一步,准备一个**资源态 (resource state)**,即一个高度纠缠的多体量子态,该量子态可以在计算开始之前准备好,且可以与具体计算任务无关;第二步,对准备好的资源态的每个比特依次做单比特测量,其中后续比特的测量方式可以根据已经被测量的比特的测量结果做出相应调整,即允许**适应性测量 (adaptive measurement)**;第三步,对测量后得到的量子态进行 **副产品纠正 (byproduct correction)**。最后,我们对所有比特的测量结果进行经典数据处理,即可得到需要的计算结果。\n",
"\n", "\n",
"图 1 给出了一个 MBQC 模型下的算法示例。图中的网格代表了一种常用的量子资源态,(称为**团簇态,cluster state**,详见下文),网格上的每个节点都代表了一个量子比特,整个网格则代表了一个高度纠缠的量子态。我们依次对每个比特进行测量(节点中的 $X, Y, Z, XY$ 等表示对应的测量基),对测量后的量子态进行副产品纠正(消除 Pauli $X$ 算符和 Pauli $Z$ 算符),即可完成计算。\n", "图 1 给出了一个 MBQC 模型下的算法示例。图中的网格代表了一种常用的量子资源态,(称为**团簇态,cluster state**,详见下文),网格上的每个节点都代表了一个量子比特,整个网格则代表了一个高度纠缠的量子态。我们依次对每个比特进行测量(节点中的 $X, Y, Z, XY$ 等表示对应的测量基),对测量后的量子态进行副产品纠正(消除 Pauli $X$ 算符和 Pauli $Z$ 算符),即可完成计算。\n",
"\n", "\n",
"![MBQC example](./figures/mbqc-fig-general_pattern.jpg)\n", "![MBQC example](./figures/mbqc-fig-general_pattern.jpg)\n",
"<div style=\"text-align:center\">图 1: 通过对网格上的每个比特进行测量来完成计算 </div>\n", "<div style=\"text-align:center\">图 1: 通过对网格上的每个比特进行测量来完成计算 </div>\n",
"\n", "\n",
"MBQC 模型的计算方式给我们带来了诸多好处。比如说,如果第一步制备的量子态噪声太大,我们则可以**在计算开始之前(即测量之前)** 丢弃这个态,并重新制备,以此保证计算结果的准确性;由于资源态可以与计算任务无关,因此可以应用在安全代理计算中 [11,12],保护计算的隐私;另外,单比特量子测量在实验上比量子门更容易实现,保真度更高,无适应性依赖关系的量子测量则可以同步进行,从而降低整个计算的深度,对量子系统相干时间要求更低。MBQC 模型实现上的技术难点主要在于第一步资源态的制备,该量子态高度纠缠,并且所需的比特数比通常电路模型的多很多。关于资源态制备的相关进展,有兴趣的读者可以参见 [13,14] 。表格 1 概括了 MBQC 模型与量子电路模型的优势和限制。\n", "MBQC 模型的计算方式给我们带来了诸多好处。比如说,如果第一步制备的量子态噪声太大,我们则可以**在计算开始之前(即测量之前)**\n",
"丢弃这个态,并重新制备,以此保证计算结果的准确性;由于资源态可以与计算任务无关,因此可以应用在安全代理计算中 [11,\n",
"12],保护计算的隐私;另外,单比特量子测量在实验上比量子门更容易实现,保真度更高,并且无适应性依赖关系的量子测量可以同步进行,从而降低整个计算的深度,对量子系统相干时间要求更低。MBQC\n",
"模型实现上的技术难点主要在于第一步资源态的制备,该量子态高度纠缠,并且制备所需的比特数比通常电路模型的多很多。关于资源态制备的相关进展,有兴趣的读者可以参见 [13,14] 。表格 1 概括了 MBQC 模型与量子电路模型的优势和限制。\n",
"\n", "\n",
"| | 量子电路模型 | 基于测量的量子计算模型 |\n", "| | 量子电路模型 | 基于测量的量子计算模型 |\n",
"|:---: | :---: | :---: |\n", "|:---: | :---: | :---: |\n",
...@@ -47,11 +53,13 @@ ...@@ -47,11 +53,13 @@
"source": [ "source": [
"## 预备知识\n", "## 预备知识\n",
"\n", "\n",
"在正式介绍 MBQC 模型及其我们的模块之前,我们首先回顾一下掌握 MBQC 模型需要用到的两个核心知识点。\n", "在正式介绍 MBQC 模型以及我们的模块之前,我们首先回顾一下掌握 MBQC 模型需要用到的两个核心知识点。\n",
"\n", "\n",
"### 1. 图与图态\n", "### 1. 图与图态\n",
" \n", " \n",
"对于任意给定一个图 $G=(V, E)$,其中,$V$ 是点的集合,$E$ 是边的集合,我们可以定义一个量子态与之对应。具体的做法为,将图 $G$ 中每个节点对应一个加态 $|+\\rangle = (|0\\rangle + |1\\rangle) / \\sqrt{2}$,如果图中两个节点之间有边相连,则将对应节点上的加态之间作用控制 Z 门, $CZ = |0\\rangle\\langle0| \\otimes I + |1\\rangle\\langle1|\\otimes Z$。由此步骤生成的量子态称为图 $G$ 的**图态** (graph state),记为 $|G\\rangle$,具体数学表达式如下:\n", "对于任意给定一个图 $G=(V, E)$,其中,$V$ 是点的集合,$E$ 是边的集合,我们可以定义一个量子态与之对应。具体的做法为,将图 $G$ 中每个节点对应一个加态 $|+\\rangle = (|0\\rangle +\n",
"|1\\rangle) / \\sqrt{2}$,如果图中两个节点之间有边相连,则将对应节点上的加态之间作用控制 Z 门, $CZ = |0\\rangle\\langle0| \\otimes I +\n",
"|1\\rangle\\langle1|\\otimes Z$。由此步骤生成的量子态称为图 $G$ 的**图态 (graph state)**,记为 $|G\\rangle$,具体数学表达式如下:\n",
" \n", " \n",
"$$\n", "$$\n",
"|G\\rangle = \\prod_{(a,b) \\in E} CZ_{ab} \\left(\\bigotimes_{v \\in V}|+\\rangle_v\\right). \\tag{1}\n", "|G\\rangle = \\prod_{(a,b) \\in E} CZ_{ab} \\left(\\bigotimes_{v \\in V}|+\\rangle_v\\right). \\tag{1}\n",
...@@ -95,7 +103,9 @@ ...@@ -95,7 +103,9 @@
"\n", "\n",
"- **量子图态准备**:即准备一个多体纠缠态。一般地,我们给出图(点和边)的信息,初始化图中节点为加态,根据图中节点的连线方式作用控制 Z 门,便可以生成量子图态。以此对应关系,每当我们给定一个图的信息,我们便可以在其上定义对应的量子图态。此外,我们还可以根据需要选择性替换图态中某些节点上的加态为指定的输入态。\n", "- **量子图态准备**:即准备一个多体纠缠态。一般地,我们给出图(点和边)的信息,初始化图中节点为加态,根据图中节点的连线方式作用控制 Z 门,便可以生成量子图态。以此对应关系,每当我们给定一个图的信息,我们便可以在其上定义对应的量子图态。此外,我们还可以根据需要选择性替换图态中某些节点上的加态为指定的输入态。\n",
"- **单比特测量**:按照特定的测量方式对上一步准备好的量子图态进行单比特测量,测量角度可以根据已获得的测量结果进行动态调整。无适应性依赖关系的测量可以交换顺序或同时进行。\n", "- **单比特测量**:按照特定的测量方式对上一步准备好的量子图态进行单比特测量,测量角度可以根据已获得的测量结果进行动态调整。无适应性依赖关系的测量可以交换顺序或同时进行。\n",
"- **副产品纠正**:由于测量结果的随机性,未测量量子态的演化方式不能唯一确定,换句话说,未测量的量子态有可能会进行一些多余的演化。我们称这些多余的演化为副产品(byproduct)。因而算法的最后一步就是对副产品进行纠正,得到我们预期的演化结果。如果算法最后要求输出的不是一个量子态,而是对演化完的量子态继续进行测量并获取经典结果的话,副产品的影响只需要通过经典数据处理来修正即可。因此,MBQC 模型的主要步骤为前两步,第三步是否进行则是取决于我们想要获得的是量子态的输出还是测量结果的经典输出。\n", "- **副产品纠正**:由于测量结果的随机性,未测量量子态的演化方式不能唯一确定,换句话说,未测量的量子态有可能会进行一些多余的演化。我们称这些多余的演化为**副产品(byproduct\n",
")**。因而算法的最后一步就是对副产品进行纠正,得到我们预期的演化结果。如果算法最后要求输出的不是一个量子态,而是对演化完的量子态继续进行测量并获取经典结果的话,副产品的影响只需要通过经典数据处理来修正即可。因此,MBQC\n",
"模型的主要步骤为前两步,第三步是否进行则是取决于我们想要获得的是量子态的输出还是测量结果的经典输出。\n",
"\n", "\n",
"依次进行上述三个步骤,我们可以概括出 MBQC 模型“三步走”的流程,即:量子图态准备、单比特测量和副产品纠正。\n", "依次进行上述三个步骤,我们可以概括出 MBQC 模型“三步走”的流程,即:量子图态准备、单比特测量和副产品纠正。\n",
"\n", "\n",
......
...@@ -136,7 +136,7 @@ ...@@ -136,7 +136,7 @@
"<div style=\"text-align:center\">Table 2: Frequently used methods of the class MBQC and their functionalities </div>\n", "<div style=\"text-align:center\">Table 2: Frequently used methods of the class MBQC and their functionalities </div>\n",
"<br/>\n", "<br/>\n",
"\n", "\n",
"In the ``simulator`` module, we provide two simulation modes, \"graph\" and \"pattern\", corresponding to the two equivalent descriptions of the MBQC computation process respectively. If we set a graph, the whole computation needs to follow the \"three-step\" process. It is worth mentioning that we design a ** vertex dynamic classification algorithm** to simulate the MBQC computation process efficiently. Roughly speaking, we integrate the first two steps of the process, change the execution order of entanglement and measurement operations automatically to reduce the number of effective qubits involved in the computation and thereby improve the efficiency. The outline to use the simulation module is as follows:\n", "In the ``simulator`` module, we provide two simulation modes, \"graph\" and \"pattern\", corresponding to the two equivalent descriptions of the MBQC computation process respectively. If we set a graph, the whole computation needs to follow the \"three-step\" process. It is worth mentioning that we design a **vertex dynamic classification algorithm** to simulate the MBQC computation process efficiently. Roughly speaking, we integrate the first two steps of the process, change the execution order of entanglement and measurement operations automatically to reduce the number of effective qubits involved in the computation and thereby improve the efficiency. The outline to use the simulation module is as follows:\n",
"\n", "\n",
"```python\n", "```python\n",
"\"\"\"\n", "\"\"\"\n",
......
...@@ -2,15 +2,16 @@ ...@@ -2,15 +2,16 @@
"cells": [ "cells": [
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {},
"source": [ "source": [
"# MBQC 模型下求解多项式组合优化问题\n", "# MBQC 模型下求解多项式组合优化问题\n",
"\n", "\n",
"<em> Copyright (c) 2021 Institute for Quantum Computing, Baidu Inc. All Rights Reserved. </em>" "<em> Copyright (c) 2021 Institute for Quantum Computing, Baidu Inc. All Rights Reserved. </em>"
], ]
"metadata": {}
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {},
"source": [ "source": [
"在[基于测量的量子近似优化算法](QAOA_CN.ipynb)中,我们介绍了多项式无约束布尔优化问题(polynomial unconstrained boolean optimization problem, PUBO),并提出了**基于测量的量子近似优化算法(MB-QAOA)** 对该类问题的求解方式,感兴趣的读者可以参阅前面的内容。这里我们给出两个示例作为 MB-QAOA 的实战演示:一个具体的 PUBO 问题和一个最大割问题。\n", "在[基于测量的量子近似优化算法](QAOA_CN.ipynb)中,我们介绍了多项式无约束布尔优化问题(polynomial unconstrained boolean optimization problem, PUBO),并提出了**基于测量的量子近似优化算法(MB-QAOA)** 对该类问题的求解方式,感兴趣的读者可以参阅前面的内容。这里我们给出两个示例作为 MB-QAOA 的实战演示:一个具体的 PUBO 问题和一个最大割问题。\n",
"\n", "\n",
...@@ -29,12 +30,13 @@ ...@@ -29,12 +30,13 @@
"$$\n", "$$\n",
"\n", "\n",
"代码实现上,我们规定输入多项式的标准形式为一个列表,列表中的第一个元素为多项式的最大变量数,列表的第二个元素为一个字典,字典的键为每个单项式涉及的变量(常数则为 ‘cons’),变量之间用逗号隔开,值为该单项式的系数。比如,我们希望输入一个三元多项式 $x_1 + x_2 - x_3 + x_1 x_2 - x_1 x_2 x_3 + 0.5$,应输入如下代码:" "代码实现上,我们规定输入多项式的标准形式为一个列表,列表中的第一个元素为多项式的最大变量数,列表的第二个元素为一个字典,字典的键为每个单项式涉及的变量(常数则为 ‘cons’),变量之间用逗号隔开,值为该单项式的系数。比如,我们希望输入一个三元多项式 $x_1 + x_2 - x_3 + x_1 x_2 - x_1 x_2 x_3 + 0.5$,应输入如下代码:"
], ]
"metadata": {}
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": {},
"outputs": [],
"source": [ "source": [
"# 变量数\n", "# 变量数\n",
"var_num = 3\n", "var_num = 3\n",
...@@ -42,12 +44,11 @@ ...@@ -42,12 +44,11 @@
"poly_dict = {'x_1': 1, 'x_2': 1, 'x_3': -1, 'x_1,x_2': 1, 'x_1,x_2,x_3': -1, 'cons':0.5}\n", "poly_dict = {'x_1': 1, 'x_2': 1, 'x_3': -1, 'x_1,x_2': 1, 'x_1,x_2,x_3': -1, 'cons':0.5}\n",
"# 构造符合约定的多项式\n", "# 构造符合约定的多项式\n",
"polynomial = [var_num, poly_dict]" "polynomial = [var_num, poly_dict]"
], ]
"outputs": [],
"metadata": {}
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {},
"source": [ "source": [
"**注意:** 由于我们考虑的变量为布尔值,所以每个单项式中变量指数最大为 1,即输入的多项式字典的键中,每个变量最多出现一次。例如:{'x_1,x_1,x_2': 1} 为不符合规范的输入。我们同样约定自变量的下角标从 \"1\" 开始,与数学习惯相一致。并且为了统一输入规范,自变量需要连续编号,不能出现输入多项式为 $x_1x_2 + x_6$ 的情况,应该改为 $x_1x_2 + x_3$,否则我们会以报错的形式提醒输入不符合规范。\n", "**注意:** 由于我们考虑的变量为布尔值,所以每个单项式中变量指数最大为 1,即输入的多项式字典的键中,每个变量最多出现一次。例如:{'x_1,x_1,x_2': 1} 为不符合规范的输入。我们同样约定自变量的下角标从 \"1\" 开始,与数学习惯相一致。并且为了统一输入规范,自变量需要连续编号,不能出现输入多项式为 $x_1x_2 + x_6$ 的情况,应该改为 $x_1x_2 + x_3$,否则我们会以报错的形式提醒输入不符合规范。\n",
"\n", "\n",
...@@ -61,19 +62,20 @@ ...@@ -61,19 +62,20 @@
"from paddle_quantum.mbqc.QAOA.pubo import random_poly\n", "from paddle_quantum.mbqc.QAOA.pubo import random_poly\n",
"```\n", "```\n",
"**注意:** 随机生成的多项式并不一定是合法的!因此我们需要在计算之前检查多项式的合法性。" "**注意:** 随机生成的多项式并不一定是合法的!因此我们需要在计算之前检查多项式的合法性。"
], ]
"metadata": {}
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {},
"source": [ "source": [
"### 求解 PUBO 问题的代码实现" "### 求解 PUBO 问题的代码实现"
], ]
"metadata": {}
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": {},
"outputs": [],
"source": [ "source": [
"# 引入记时模块\n", "# 引入记时模块\n",
"from time import perf_counter\n", "from time import perf_counter\n",
...@@ -85,20 +87,20 @@ ...@@ -85,20 +87,20 @@
"from paddle_quantum.mbqc.QAOA.pubo import dict_to_symbol, is_poly_valid, brute_force_search\n", "from paddle_quantum.mbqc.QAOA.pubo import dict_to_symbol, is_poly_valid, brute_force_search\n",
"# 引入 qaoa 模块 \n", "# 引入 qaoa 模块 \n",
"from paddle_quantum.mbqc.QAOA.qaoa import MBQC_QAOA_Net, get_solution_string" "from paddle_quantum.mbqc.QAOA.qaoa import MBQC_QAOA_Net, get_solution_string"
], ]
"outputs": [],
"metadata": {}
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {},
"source": [ "source": [
"利用 MB-QAOA 算法,我们可以定义 PUBO 主函数 ``mbqc_pubo``,输入目标函数和 QAOA 算法深度,最终返回最优解对应的比特串。在主函数中,**最核心的是 MBQC_QAOA_Net 类**,其集成了 MB-QAOA 以及优化网络,感兴趣的读者可以返回到 [基于测量的量子近似优化算法](QAOA_CN.ipynb) 中查看,这里我们直接调用。" "利用 MB-QAOA 算法,我们可以定义 PUBO 主函数 ``mbqc_pubo``,输入目标函数和 QAOA 算法深度,最终返回最优解对应的比特串。在主函数中,**最核心的是 MBQC_QAOA_Net 类**,其集成了 MB-QAOA 以及优化网络,感兴趣的读者可以返回到 [基于测量的量子近似优化算法](QAOA_CN.ipynb) 中查看,这里我们直接调用。"
], ]
"metadata": {}
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": {},
"outputs": [],
"source": [ "source": [
"# 定义 MBQC 模型求解 PUBO 问题的主函数\n", "# 定义 MBQC 模型求解 PUBO 问题的主函数\n",
"def mbqc_pubo(OBJ_POLY, DEPTH, SEED, LR, ITR, EPOCH, SHOTS=1024):\n", "def mbqc_pubo(OBJ_POLY, DEPTH, SEED, LR, ITR, EPOCH, SHOTS=1024):\n",
...@@ -151,33 +153,35 @@ ...@@ -151,33 +153,35 @@
" # 返回最优解和最优值\n", " # 返回最优解和最优值\n",
" opt = [solution_str, value]\n", " opt = [solution_str, value]\n",
" return opt" " return opt"
], ]
"outputs": [],
"metadata": {}
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {},
"source": [ "source": [
"为了检验训练结果的正确性,我们在 `pubo` 中定义了 `brute_force_search` 函数,用遍历的方法在解空间里暴力搜索 PUBO 问题的解,方便与 MBQC 模型训练得到的解进行对比。\n", "为了检验训练结果的正确性,我们在 `pubo` 中定义了 `brute_force_search` 函数,用遍历的方法在解空间里暴力搜索 PUBO 问题的解,方便与 MBQC 模型训练得到的解进行对比。\n",
"\n", "\n",
"```python\n", "```python\n",
"from paddle_quantum.mbqc.QAOA.pubo import brute_force_search\n", "from paddle_quantum.mbqc.QAOA.pubo import brute_force_search\n",
"```" "```"
], ]
"metadata": {}
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {},
"source": [ "source": [
"### Main 函数\n", "### Main 函数\n",
"\n", "\n",
"主函数定义后,我们就可以输入参数运行啦!" "主函数定义后,我们就可以输入参数运行啦!"
], ]
"metadata": {}
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": {
"tags": []
},
"outputs": [],
"source": [ "source": [
"# 定义主函数\n", "# 定义主函数\n",
"def main():\n", "def main():\n",
...@@ -221,14 +225,13 @@ ...@@ -221,14 +225,13 @@
"\n", "\n",
"if __name__ == '__main__':\n", "if __name__ == '__main__':\n",
" main()" " main()"
], ]
"outputs": [],
"metadata": {
"tags": []
}
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {
"tags": []
},
"source": [ "source": [
"## 示例:最大割问题\n", "## 示例:最大割问题\n",
"\n", "\n",
...@@ -239,37 +242,35 @@ ...@@ -239,37 +242,35 @@
"在图论中,一个图由 $G = (V, E)$ 表示,其中 $V$ 为图的点集合,$E$ 为边集合。例如一个正方形就可以由 $G = (V,E)$ 其中 $V = [1,2,3,4]$, $E = [(1,2),(2,3),(3,4),(1,4)]$ 来表示。\n", "在图论中,一个图由 $G = (V, E)$ 表示,其中 $V$ 为图的点集合,$E$ 为边集合。例如一个正方形就可以由 $G = (V,E)$ 其中 $V = [1,2,3,4]$, $E = [(1,2),(2,3),(3,4),(1,4)]$ 来表示。\n",
"\n", "\n",
"代码上,我们可以用 `maxcut` 中的 `plot_graph` 画出给定的图。" "代码上,我们可以用 `maxcut` 中的 `plot_graph` 画出给定的图。"
], ]
"metadata": {
"tags": []
}
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": {
"tags": []
},
"outputs": [],
"source": [ "source": [
"from paddle_quantum.mbqc.QAOA.maxcut import plot_graph\n", "from paddle_quantum.mbqc.QAOA.maxcut import plot_graph\n",
"V = [1,2,3,4]\n", "V = [1,2,3,4]\n",
"E = [(1,2),(2,3),(3,4),(1,4)]\n", "E = [(1,2),(2,3),(3,4),(1,4)]\n",
"G = [V, E] \n", "G = [V, E] \n",
"plot_graph(G,\"A square\")" "plot_graph(G,\"A square\")"
], ]
"outputs": [],
"metadata": {
"tags": []
}
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {},
"source": [ "source": [
"一个图的割是指将该图的顶点集 $V$ 分割成两个互不相交的子集合 $S_0$ 和 $S_1$ 的一种划分。如果图中边的两个顶点被划分到不同集合中,那么记录得一分,总得分则定义为这个割的大小。最大割问题就是要找到一个割使得该割的大小最大。\n", "一个图的割是指将该图的顶点集 $V$ 分割成两个互不相交的子集合 $S_0$ 和 $S_1$ 的一种划分。如果图中边的两个顶点被划分到不同集合中,那么记录得一分,总得分则定义为这个割的大小。最大割问题就是要找到一个割使得该割的大小最大。\n",
"\n", "\n",
"比如对应如上所述正方形图 $G$, 其中一个最大割就是将点 $1$ 和 $3$ 分为同一个集合 $S_0$ 中,点 $2$ 和 $4$ 分到另一个集合 $S_1$ 中。 " "比如对应如上所述正方形图 $G$, 其中一个最大割就是将点 $1$ 和 $3$ 分为同一个集合 $S_0$ 中,点 $2$ 和 $4$ 分到另一个集合 $S_1$ 中。 "
], ]
"metadata": {}
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {},
"source": [ "source": [
"### 转化为 PUBO 问题\n", "### 转化为 PUBO 问题\n",
"\n", "\n",
...@@ -292,12 +293,13 @@ ...@@ -292,12 +293,13 @@
"$$\n", "$$\n",
"\n", "\n",
"在 `maxcut` 当中,我们定义了 `graph_to_poly` 函数,可以输入待分割的图,返回等价的 PUBO 问题的目标多项式。" "在 `maxcut` 当中,我们定义了 `graph_to_poly` 函数,可以输入待分割的图,返回等价的 PUBO 问题的目标多项式。"
], ]
"metadata": {}
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": {},
"outputs": [],
"source": [ "source": [
"# 引入 maxcut 模块\n", "# 引入 maxcut 模块\n",
"from paddle_quantum.mbqc.QAOA.maxcut import graph_to_poly\n", "from paddle_quantum.mbqc.QAOA.maxcut import graph_to_poly\n",
...@@ -311,22 +313,22 @@ ...@@ -311,22 +313,22 @@
"# 将图转化为对应 PUBO 问题的目标多项式\n", "# 将图转化为对应 PUBO 问题的目标多项式\n",
"poly = graph_to_poly(G)\n", "poly = graph_to_poly(G)\n",
"print(\"与图等价的目标多项式为:\\n\", poly)" "print(\"与图等价的目标多项式为:\\n\", poly)"
], ]
"outputs": [],
"metadata": {}
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {},
"source": [ "source": [
"### 求解最大割问题的代码实现\n", "### 求解最大割问题的代码实现\n",
"\n", "\n",
"得到等价的目标多项式之后,我们便可以仿照 PUBO 的流程,把最大割问题作为 PUBO 问题来求解。具体代码如下:" "得到等价的目标多项式之后,我们便可以仿照 PUBO 的流程,把最大割问题作为 PUBO 问题来求解。具体代码如下:"
], ]
"metadata": {}
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": {},
"outputs": [],
"source": [ "source": [
"# 引入符号运算模块\n", "# 引入符号运算模块\n",
"from sympy import symbols\n", "from sympy import symbols\n",
...@@ -336,20 +338,20 @@ ...@@ -336,20 +338,20 @@
"from paddle_quantum.mbqc.QAOA.qaoa import MBQC_QAOA_Net, get_solution_string\n", "from paddle_quantum.mbqc.QAOA.qaoa import MBQC_QAOA_Net, get_solution_string\n",
"# 引入 maxcut 模块\n", "# 引入 maxcut 模块\n",
"from paddle_quantum.mbqc.QAOA. maxcut import plot_graph, graph_to_poly, plot_solution" "from paddle_quantum.mbqc.QAOA. maxcut import plot_graph, graph_to_poly, plot_solution"
], ]
"outputs": [],
"metadata": {}
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {},
"source": [ "source": [
"利用 MB-QAOA 算法,我们可以定义 MaxCut 主函数,将图输入到 MB-QAOA 算法中,最终返回求得的解并画出割的方式。" "利用 MB-QAOA 算法,我们可以定义 MaxCut 主函数,将图输入到 MB-QAOA 算法中,最终返回求得的解并画出割的方式。"
], ]
"metadata": {}
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": {},
"outputs": [],
"source": [ "source": [
"# 定义 MaxCut 主函数\n", "# 定义 MaxCut 主函数\n",
"def mbqc_maxcut(GRAPH, DEPTH, SEED, LR, ITR, EPOCH, SHOTS=1024):\n", "def mbqc_maxcut(GRAPH, DEPTH, SEED, LR, ITR, EPOCH, SHOTS=1024):\n",
...@@ -405,22 +407,24 @@ ...@@ -405,22 +407,24 @@
"\n", "\n",
" # 返回最优解和对应的最优值\n", " # 返回最优解和对应的最优值\n",
" return mbqc_opt" " return mbqc_opt"
], ]
"outputs": [],
"metadata": {}
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {},
"source": [ "source": [
"### Main 函数\n", "### Main 函数\n",
"\n", "\n",
"主函数定义后,我们就可以输入参数运行啦!" "主函数定义后,我们就可以输入参数运行啦!"
], ]
"metadata": {}
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": {
"tags": []
},
"outputs": [],
"source": [ "source": [
"def main():\n", "def main():\n",
" # 以正方形的 MaxCut 问题为例,输入节点和边信息\n", " # 以正方形的 MaxCut 问题为例,输入节点和边信息\n",
...@@ -445,33 +449,27 @@ ...@@ -445,33 +449,27 @@
"\n", "\n",
"if __name__ == '__main__':\n", "if __name__ == '__main__':\n",
" main()" " main()"
], ]
"outputs": [],
"metadata": {
"tags": []
}
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {},
"source": [ "source": [
"至此,我们完成了本教程的两个完整示例。MB-QAOA 算法实现预示着 MBQC 模型在量子机器学习领域强大的潜力。很显然,MBQC 模型所能够处理的算法不仅有 QAOA,我们非常期待 MBQC 这种非同寻常的计算方式能在某些特殊情境下展现出无与伦比的优势!\n", "至此,我们完成了本教程的两个完整示例。MB-QAOA 算法实现预示着 MBQC 模型在量子机器学习领域强大的潜力。很显然,MBQC 模型所能够处理的算法不仅有 QAOA,我们非常期待 MBQC 这种非同寻常的计算方式能在某些特殊情境下展现出无与伦比的优势!"
"\n", ]
"接下来的一个教程将会给出我们在 MBQC 模型优势上的一个探索,一起去学习吧!"
],
"metadata": {}
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {
"tags": []
},
"source": [ "source": [
"---\n", "---\n",
"\n", "\n",
"## 参考文献\n", "## 参考文献\n",
"\n", "\n",
"[1] Farhi, Edward, et al. \"A quantum approximate optimization algorithm.\" [arXiv preprint arXiv:1411.4028 (2014).](https://arxiv.org/abs/1411.4028)" "[1] Farhi, Edward, et al. \"A quantum approximate optimization algorithm.\" [arXiv preprint arXiv:1411.4028 (2014).](https://arxiv.org/abs/1411.4028)"
], ]
"metadata": {
"tags": []
}
} }
], ],
"metadata": { "metadata": {
...@@ -537,4 +535,4 @@ ...@@ -537,4 +535,4 @@
}, },
"nbformat": 4, "nbformat": 4,
"nbformat_minor": 4 "nbformat_minor": 4
} }
\ No newline at end of file
...@@ -2,15 +2,16 @@ ...@@ -2,15 +2,16 @@
"cells": [ "cells": [
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {},
"source": [ "source": [
"# Polynomial Unconstrained Boolean Optimization Problem in MBQC\n", "# Polynomial Unconstrained Boolean Optimization Problem in MBQC\n",
"\n", "\n",
"<em> Copyright (c) 2021 Institute for Quantum Computing, Baidu Inc. All Rights Reserved. </em>" "<em> Copyright (c) 2021 Institute for Quantum Computing, Baidu Inc. All Rights Reserved. </em>"
], ]
"metadata": {}
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {},
"source": [ "source": [
"In the tutorial [Measurement-based Quantum Approximate Optimization Algorithm](QAOA_EN.ipynb), we give a brief introduction to the **polynomial unconstrained boolean optimization (PUBO) problem** and propose the **measurement-based quantum approximate optimization algorithm (MB-QAOA)** to solve it. For interested readers, please refer to the previous tutorial for more information. In this tutorial, we will showcase two specific examples as practical demonstrations of MB-QAOA. The first one is a concrete PUBO problem, while the second one is a **maximum cut (MaxCut)** problem.\n", "In the tutorial [Measurement-based Quantum Approximate Optimization Algorithm](QAOA_EN.ipynb), we give a brief introduction to the **polynomial unconstrained boolean optimization (PUBO) problem** and propose the **measurement-based quantum approximate optimization algorithm (MB-QAOA)** to solve it. For interested readers, please refer to the previous tutorial for more information. In this tutorial, we will showcase two specific examples as practical demonstrations of MB-QAOA. The first one is a concrete PUBO problem, while the second one is a **maximum cut (MaxCut)** problem.\n",
"\n", "\n",
...@@ -29,12 +30,13 @@ ...@@ -29,12 +30,13 @@
"$$\n", "$$\n",
"\n", "\n",
"For code implementation, we require that a standard polynomial is input as a list whose first item is the number of variables and the second item is a dictionary of all the monomials ('cons' stands for the constant item). In the dictionary, we make monomial variables split with ',' as keys and the corresponding coefficients as values. For example, suppose we want to input a polynomial $x_1 + x_2 - x_3 + x_1 x_2 - x_1 x_2 x_3 + 0.5$, we need to code as follows: " "For code implementation, we require that a standard polynomial is input as a list whose first item is the number of variables and the second item is a dictionary of all the monomials ('cons' stands for the constant item). In the dictionary, we make monomial variables split with ',' as keys and the corresponding coefficients as values. For example, suppose we want to input a polynomial $x_1 + x_2 - x_3 + x_1 x_2 - x_1 x_2 x_3 + 0.5$, we need to code as follows: "
], ]
"metadata": {}
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": {},
"outputs": [],
"source": [ "source": [
"# Number of variables\n", "# Number of variables\n",
"var_num = 3\n", "var_num = 3\n",
...@@ -42,12 +44,11 @@ ...@@ -42,12 +44,11 @@
"poly_dict = {'x_1': 1, 'x_2': 1, 'x_3': -1, 'x_1,x_2': 1, 'x_1,x_2,x_3': -1, 'cons':0.5}\n", "poly_dict = {'x_1': 1, 'x_2': 1, 'x_3': -1, 'x_1,x_2': 1, 'x_1,x_2,x_3': -1, 'cons':0.5}\n",
"# Construct the list required\n", "# Construct the list required\n",
"polynomial = [var_num, poly_dict]" "polynomial = [var_num, poly_dict]"
], ]
"outputs": [],
"metadata": {}
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {},
"source": [ "source": [
"**Note:** As the variables are boolean, the power of variables in a monomial should be no greater than 1. That is, each variable should appear at most once in a key of the dictionary. For instance, it is not a valid to input something like {'x_1,x_1,x_2': 1}. Also, we set variable subscripts by consecutive numbers starting from '1' to be consistent with math conventions. A polynomial like $x_1 x_2 + x_6$ will raise an error automatically. A valid polynomial should be like $x_1x_2 + x_3$. \n", "**Note:** As the variables are boolean, the power of variables in a monomial should be no greater than 1. That is, each variable should appear at most once in a key of the dictionary. For instance, it is not a valid to input something like {'x_1,x_1,x_2': 1}. Also, we set variable subscripts by consecutive numbers starting from '1' to be consistent with math conventions. A polynomial like $x_1 x_2 + x_6$ will raise an error automatically. A valid polynomial should be like $x_1x_2 + x_3$. \n",
"\n", "\n",
...@@ -62,19 +63,20 @@ ...@@ -62,19 +63,20 @@
"from paddle_quantum.mbqc.QAOA.pubo import random_poly\n", "from paddle_quantum.mbqc.QAOA.pubo import random_poly\n",
"```\n", "```\n",
"**Note:** The randomly generated polynomial is not always valid and we still need to check the validity before calculation." "**Note:** The randomly generated polynomial is not always valid and we still need to check the validity before calculation."
], ]
"metadata": {}
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {},
"source": [ "source": [
"### Code implementation to slove PUBO problem" "### Code implementation to slove PUBO problem"
], ]
"metadata": {}
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": {},
"outputs": [],
"source": [ "source": [
"# Import time module\n", "# Import time module\n",
"from time import perf_counter\n", "from time import perf_counter\n",
...@@ -86,20 +88,20 @@ ...@@ -86,20 +88,20 @@
"from paddle_quantum.mbqc.QAOA.pubo import dict_to_symbol,is_poly_valid,brute_force_search\n", "from paddle_quantum.mbqc.QAOA.pubo import dict_to_symbol,is_poly_valid,brute_force_search\n",
"# Import qaoa module\n", "# Import qaoa module\n",
"from paddle_quantum.mbqc.QAOA.qaoa import MBQC_QAOA_Net, get_solution_string" "from paddle_quantum.mbqc.QAOA.qaoa import MBQC_QAOA_Net, get_solution_string"
], ]
"outputs": [],
"metadata": {}
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {},
"source": [ "source": [
"We define a function ``mbqc_pubo`` which takes in the objective polynomial and returns an optimal solution. **The core part of ``mbqc_pubo`` is the ``MBQC_QAOA_Net`` class**, which integrates MB-QAOA and the optimization net. Please refer to [Measurement-Based Quantum Approximate Optimization Algorithm](QAOA_EN.ipynb) for more details. Here we directly call the function." "We define a function ``mbqc_pubo`` which takes in the objective polynomial and returns an optimal solution. **The core part of ``mbqc_pubo`` is the ``MBQC_QAOA_Net`` class**, which integrates MB-QAOA and the optimization net. Please refer to [Measurement-Based Quantum Approximate Optimization Algorithm](QAOA_EN.ipynb) for more details. Here we directly call the function."
], ]
"metadata": {}
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": {},
"outputs": [],
"source": [ "source": [
"# Define the PUBO main function\n", "# Define the PUBO main function\n",
"def mbqc_pubo(OBJ_POLY, DEPTH, SEED, LR, ITR, EPOCH, SHOTS=1024):\n", "def mbqc_pubo(OBJ_POLY, DEPTH, SEED, LR, ITR, EPOCH, SHOTS=1024):\n",
...@@ -153,33 +155,35 @@ ...@@ -153,33 +155,35 @@
" opt = [solution_str, value]\n", " opt = [solution_str, value]\n",
"\n", "\n",
" return opt" " return opt"
], ]
"outputs": [],
"metadata": {}
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {},
"source": [ "source": [
"To check the correctness of the training result, we provide a `brute_force_search` function in `pubo` that finds a global optimal value by brute force search. We can compare the training result with the optimal one.\n", "To check the correctness of the training result, we provide a `brute_force_search` function in `pubo` that finds a global optimal value by brute force search. We can compare the training result with the optimal one.\n",
"\n", "\n",
"```python\n", "```python\n",
"from paddle_quantum.mbqc.QAOA.pubo import brute_force_search\n", "from paddle_quantum.mbqc.QAOA.pubo import brute_force_search\n",
"```" "```"
], ]
"metadata": {}
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {},
"source": [ "source": [
"### Main function\n", "### Main function\n",
"\n", "\n",
"After defining the main function, let's input the parameters to run the code!" "After defining the main function, let's input the parameters to run the code!"
], ]
"metadata": {}
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": {
"tags": []
},
"outputs": [],
"source": [ "source": [
"# Define the main function\n", "# Define the main function\n",
"def main():\n", "def main():\n",
...@@ -223,14 +227,13 @@ ...@@ -223,14 +227,13 @@
"\n", "\n",
"if __name__ == '__main__':\n", "if __name__ == '__main__':\n",
" main()" " main()"
], ]
"outputs": [],
"metadata": {
"tags": []
}
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {
"tags": []
},
"source": [ "source": [
"## Example: MaxCut\n", "## Example: MaxCut\n",
"\n", "\n",
...@@ -241,37 +244,35 @@ ...@@ -241,37 +244,35 @@
"In graph theory, a graph is represented by $G = (V, E)$, where $V$ is a set of vertices and $E$ is a set of edges. For example, a square can be characterized by the graph $G = (V,E)$ with $V = [1,2,3,4]$ and $E = [(1,2),(2,3),(3,4),(1,4)]$.\n", "In graph theory, a graph is represented by $G = (V, E)$, where $V$ is a set of vertices and $E$ is a set of edges. For example, a square can be characterized by the graph $G = (V,E)$ with $V = [1,2,3,4]$ and $E = [(1,2),(2,3),(3,4),(1,4)]$.\n",
"\n", "\n",
"For code implementation, we can use the `plot_graph` function in `maxcut` to plot a graph." "For code implementation, we can use the `plot_graph` function in `maxcut` to plot a graph."
], ]
"metadata": {
"tags": []
}
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": {
"tags": []
},
"outputs": [],
"source": [ "source": [
"from paddle_quantum.mbqc.QAOA.maxcut import plot_graph\n", "from paddle_quantum.mbqc.QAOA.maxcut import plot_graph\n",
"V = [1,2,3,4]\n", "V = [1,2,3,4]\n",
"E = [(1,2),(2,3),(3,4),(1,4)]\n", "E = [(1,2),(2,3),(3,4),(1,4)]\n",
"G = [V, E] \n", "G = [V, E] \n",
"plot_graph(G,\"A square\")" "plot_graph(G,\"A square\")"
], ]
"outputs": [],
"metadata": {
"tags": []
}
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {},
"source": [ "source": [
"A cut in the graph is a partition separating the vertices set $V$ into two complementary subsets $S_0$ and $S_1$. If two vertices of an edge in the graph are separated into different subsets, we score a goal. The size of a cut is defined by the total scores that we get. Then the MaxCut problem is to find a cut of graph with maximal size. \n", "A cut in the graph is a partition separating the vertices set $V$ into two complementary subsets $S_0$ and $S_1$. If two vertices of an edge in the graph are separated into different subsets, we score a goal. The size of a cut is defined by the total scores that we get. Then the MaxCut problem is to find a cut of graph with maximal size. \n",
"\n", "\n",
"As for the above square $G$, one of the optimal solutions to the MaxCut problem is to put $1$ and $3$ into subset $S_0$ and put $2$ and $4$ into subset $S_1$. " "As for the above square $G$, one of the optimal solutions to the MaxCut problem is to put $1$ and $3$ into subset $S_0$ and put $2$ and $4$ into subset $S_1$. "
], ]
"metadata": {}
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {},
"source": [ "source": [
"### Transformation to a PUBO problem\n", "### Transformation to a PUBO problem\n",
"\n", "\n",
...@@ -294,12 +295,13 @@ ...@@ -294,12 +295,13 @@
"$$\n", "$$\n",
"\n", "\n",
"We provide a function `graph_to_poly` in `maxcut` which takes in the graph to be cut and returns the equivalent objective polynomial in PUBO." "We provide a function `graph_to_poly` in `maxcut` which takes in the graph to be cut and returns the equivalent objective polynomial in PUBO."
], ]
"metadata": {}
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": {},
"outputs": [],
"source": [ "source": [
"# Import maxcut module\n", "# Import maxcut module\n",
"from paddle_quantum.mbqc.QAOA.maxcut import graph_to_poly\n", "from paddle_quantum.mbqc.QAOA.maxcut import graph_to_poly\n",
...@@ -313,22 +315,22 @@ ...@@ -313,22 +315,22 @@
"# Transform the graph to the equivalent polynomial\n", "# Transform the graph to the equivalent polynomial\n",
"poly = graph_to_poly(G)\n", "poly = graph_to_poly(G)\n",
"print(\"The equivalent objective polynomial is:\\n\", poly)" "print(\"The equivalent objective polynomial is:\\n\", poly)"
], ]
"outputs": [],
"metadata": {}
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {},
"source": [ "source": [
"### Code implementation to solve MaxCut problem\n", "### Code implementation to solve MaxCut problem\n",
"\n", "\n",
"Once obtaining the objective polynomial, we can follow the same process as the previous example and solve the MaxCut problem as a special case of PUBO. The complete code implementation is as follows:" "Once obtaining the objective polynomial, we can follow the same process as the previous example and solve the MaxCut problem as a special case of PUBO. The complete code implementation is as follows:"
], ]
"metadata": {}
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": {},
"outputs": [],
"source": [ "source": [
"# Import symbol calculaion module\n", "# Import symbol calculaion module\n",
"from sympy import symbols\n", "from sympy import symbols\n",
...@@ -338,20 +340,20 @@ ...@@ -338,20 +340,20 @@
"from paddle_quantum.mbqc.QAOA.qaoa import MBQC_QAOA_Net, get_solution_string\n", "from paddle_quantum.mbqc.QAOA.qaoa import MBQC_QAOA_Net, get_solution_string\n",
"# Import maxcut module\n", "# Import maxcut module\n",
"from paddle_quantum.mbqc.QAOA.maxcut import plot_graph, graph_to_poly, plot_solution" "from paddle_quantum.mbqc.QAOA.maxcut import plot_graph, graph_to_poly, plot_solution"
], ]
"outputs": [],
"metadata": {}
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {},
"source": [ "source": [
"We define the main function for MaxCut that takes in the graph to be cut and returns the optimal training results." "We define the main function for MaxCut that takes in the graph to be cut and returns the optimal training results."
], ]
"metadata": {}
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": {},
"outputs": [],
"source": [ "source": [
"# Define the MaxCut main function\n", "# Define the MaxCut main function\n",
"def mbqc_maxcut(GRAPH, DEPTH, SEED, LR, ITR, EPOCH, SHOTS=1024):\n", "def mbqc_maxcut(GRAPH, DEPTH, SEED, LR, ITR, EPOCH, SHOTS=1024):\n",
...@@ -407,22 +409,24 @@ ...@@ -407,22 +409,24 @@
" mbqc_opt = [mbqc_solution, mbqc_value]\n", " mbqc_opt = [mbqc_solution, mbqc_value]\n",
"\n", "\n",
" return mbqc_opt" " return mbqc_opt"
], ]
"outputs": [],
"metadata": {}
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {},
"source": [ "source": [
"### Main function\n", "### Main function\n",
"\n", "\n",
"After defining the main function, let's input the parameters to run the code!" "After defining the main function, let's input the parameters to run the code!"
], ]
"metadata": {}
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": {
"tags": []
},
"outputs": [],
"source": [ "source": [
"def main():\n", "def main():\n",
" # A graph to be cut\n", " # A graph to be cut\n",
...@@ -447,34 +451,28 @@ ...@@ -447,34 +451,28 @@
"\n", "\n",
"if __name__ == '__main__':\n", "if __name__ == '__main__':\n",
" main()" " main()"
], ]
"outputs": [],
"metadata": {
"tags": []
}
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {},
"source": [ "source": [
"Now, we have completed the demonstration of two examples. The implementation of MB-QAOA indicates a great potential of MBQC in the field of quantum machine learning. Apparently, MBQC model can realize quantities of algorithms far beyond QAOA. We therefore are \n", "Now, we have completed the demonstration of two examples. The implementation of MB-QAOA indicates a great potential of MBQC in the field of quantum machine learning. Apparently, MBQC model can realize quantities of algorithms far beyond QAOA. We therefore are \n",
"looking forward to exploring more on this and to show some unparalleled advantages in practice. \n", "looking forward to exploring more on this and to show some unparalleled advantages in practice."
"\n", ]
"As a matter of fact, we have found an interesting application of MBQC in simulating a special class of quantum circuits! So, let's continue our exploration to the next tutorial together."
],
"metadata": {}
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {
"tags": []
},
"source": [ "source": [
"---\n", "---\n",
"\n", "\n",
"## References\n", "## References\n",
"\n", "\n",
"[1] Farhi, Edward, et al. \"A quantum approximate optimization algorithm.\" [arXiv preprint arXiv:1411.4028 (2014).](https://arxiv.org/abs/1411.4028)" "[1] Farhi, Edward, et al. \"A quantum approximate optimization algorithm.\" [arXiv preprint arXiv:1411.4028 (2014).](https://arxiv.org/abs/1411.4028)"
], ]
"metadata": {
"tags": []
}
} }
], ],
"metadata": { "metadata": {
...@@ -540,4 +538,4 @@ ...@@ -540,4 +538,4 @@
}, },
"nbformat": 4, "nbformat": 4,
"nbformat_minor": 4 "nbformat_minor": 4
} }
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册