提交 eadbc3eb 编写于 作者: Q Quleaf

update to v2.1.1

上级 fbcf1296
# Byte-compiled / optimized / DLL files
.idea
.DS_Store
.vscode/
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
.python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# .dat file
*.dat
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# qchem_data folder when run psi4 calculation
qchem_data/
output
*.egg-info
.ipynb_checkpoints
\ No newline at end of file
......@@ -33,7 +33,7 @@ English | [简体中文](README_CN.md)
</a>
<!-- PyPI -->
<a href="https://pypi.org/project/paddle-quantum/">
<img src="https://img.shields.io/badge/pypi-v2.1.0-orange.svg?style=flat-square&logo=pypi"/>
<img src="https://img.shields.io/badge/pypi-v2.1.1-orange.svg?style=flat-square&logo=pypi"/>
</a>
<!-- Python -->
<a href="https://www.python.org/">
......@@ -71,7 +71,7 @@ Paddle Quantum aims at establishing a bridge between artificial intelligence (AI
### Install PaddlePaddle
This dependency will be automatically satisfied when users install Paddle Quantum. Please refer to [PaddlePaddle](https://www.paddlepaddle.org.cn/install/quick)'s official installation and configuration page. This project requires PaddlePaddle 2.0.1+.
This dependency will be automatically satisfied when users install Paddle Quantum. Please refer to [PaddlePaddle](https://www.paddlepaddle.org.cn/install/quick)'s official installation and configuration page. This project requires PaddlePaddle 2.1.1+.
### Install Paddle Quantum
......@@ -147,6 +147,9 @@ We provide tutorials covering quantum simulation, machine learning, combinatoria
2. [Solving Max-Cut Problem with QAOA](./tutorial/combinatorial_optimization/MAXCUT_EN.ipynb)
3. [Large-scale QAOA via Divide-and-Conquer](./tutorial/combinatorial_optimization/DC-QAOA_EN.ipynb)
4. [Travelling Salesman Problem](./tutorial/combinatorial_optimization/TSP_EN.ipynb)
5. [Quantum Finance Application on Arbitrage Opportunity Optimization](./tutorial/combinatorial_optimization/ArbitrageOpportunityOptimation_EN.ipynb)
6. [Quantum Finance Application on Portfolio Optimization](./tutorial/combinatorial_optimization/PortfolioOptimization_EN.ipynb)
7. [Quantum Finance Application on Portfolio Diversification](./tutorial/combinatorial_optimization/PortfolioDiversification_EN.ipynb)
- [LOCC with QNN (LOCCNet)](./tutorial/locc)
1. [Local Operations and Classical Communication in QNN (LOCCNet)](./tutorial/locc/LOCCNET_Tutorial_EN.ipynb)
......@@ -159,6 +162,7 @@ We provide tutorials covering quantum simulation, machine learning, combinatoria
- [QNN Research](./tutorial/qnn_research)
1. [The Barren Plateaus Phenomenon on Quantum Neural Networks (Barren Plateaus)](./tutorial/qnn_research/BarrenPlateaus_EN.ipynb)
2. [Noise Model and Quantum Channel](./tutorial/qnn_research/Noise_EN.ipynb)
3. [Calculating Gradient Using Quantum Circuit](./tutorial/qnn_research/Gradient_EN.ipynb)
With the latest LOCCNet module, Paddle Quantum can efficiently simulate distributed quantum information processing tasks. Interested readers can start with this [tutorial on LOCCNet](./tutorial/locc/LOCCNET_Tutorial_EN.ipynb). In addition, Paddle Quantum supports QNN training on GPU. For users who want to get into more details, please check out the tutorial [Use Paddle Quantum on GPU](./introduction/PaddleQuantum_GPU_EN.ipynb). Moreover, Paddle Quantum could design robust quantum algorithms under noise. For more information, please see [Noise tutorial](./tutorial/qnn_research/Noise_EN.ipynb).
......
......@@ -34,7 +34,7 @@
</a>
<!-- PyPI -->
<a href="https://pypi.org/project/paddle-quantum/">
<img src="https://img.shields.io/badge/pypi-v2.1.0-orange.svg?style=flat-square&logo=pypi"/>
<img src="https://img.shields.io/badge/pypi-v2.1.1-orange.svg?style=flat-square&logo=pypi"/>
</a>
<!-- Python -->
<a href="https://www.python.org/">
......@@ -71,7 +71,7 @@
### 安装 PaddlePaddle
当用户安装 Paddle Quantum 时会自动下载安装这个关键依赖包。关于 PaddlePaddle 更全面的安装信息请参考 [PaddlePaddle](https://www.paddlepaddle.org.cn/install/quick) 安装配置页面。此项目需求 PaddlePaddle 2.0.1+。
当用户安装 Paddle Quantum 时会自动下载安装这个关键依赖包。关于 PaddlePaddle 更全面的安装信息请参考 [PaddlePaddle](https://www.paddlepaddle.org.cn/install/quick) 安装配置页面。此项目需求 PaddlePaddle 2.1.1+。
### 安装 Paddle Quantum
......@@ -153,6 +153,9 @@ Paddle Quantum(量桨)建立起了人工智能与量子计算的桥梁,为
2. [QAOA 求解最大割问题](./tutorial/combinatorial_optimization/MAXCUT_CN.ipynb)
3. [大规模量子近似优化分治算法(DC-QAOA)](./tutorial/combinatorial_optimization/DC-QAOA_CN.ipynb)
4. [旅行商问题](./tutorial/combinatorial_optimization/TSP_CN.ipynb)
5. [量子金融应用:最佳套利机会](./tutorial/combinatorial_optimization/ArbitrageOpportunityOptimation_CN.ipynb)
6. [量子金融应用:投资组合优化](./tutorial/combinatorial_optimization/PortfolioOptimization_CN.ipynb)
7. [量子金融应用:投资组合分散化](./tutorial/combinatorial_optimization/PortfolioDiversification_CN.ipynb)
- [LOCC 量子神经网络(LOCCNet)](./tutorial/locc)
1. [LOCC 量子神经网络](./tutorial/locc/LOCCNET_Tutorial_CN.ipynb)
......@@ -165,6 +168,7 @@ Paddle Quantum(量桨)建立起了人工智能与量子计算的桥梁,为
- [量子神经网络研究](./tutorial/qnn_research)
1. [量子神经网络的贫瘠高原效应(Barren Plateaus)](./tutorial/qnn_research/BarrenPlateaus_CN.ipynb)
2. [噪声模型与量子信道](./tutorial/qnn_research/Noise_CN.ipynb)
3. [使用量子电路计算梯度](./tutorial/qnn_research/Gradient_CN.ipynb)
随着 LOCCNet 模组的推出,量桨现已支持分布式量子信息处理任务的高效模拟和开发。感兴趣的读者请参见[教程](./tutorial/locc/LOCCNET_Tutorial_CN.ipynb)。Paddle Quantum 也支持在 GPU 上进行量子机器学习的训练,具体的方法请参考案例:[在 GPU 上使用 Paddle Quantum](./introduction/PaddleQuantum_GPU_CN.ipynb)。此外,量桨可以基于噪声模块进行含噪算法的开发以及研究,详情请见[噪声模块教程](./tutorial/qnn_research/Noise_CN.ipynb)
......
......@@ -981,7 +981,7 @@
"theta = np.random.randn(DEPTH, N, 1)\n",
"\n",
"# 调用内置的 |00..0> 初始态\n",
"initial_state1 = vec(N)\n",
"initial_state1 = vec(0, N)\n",
"# 调用内置的随机量子态 |psi>\n",
"initial_state2 = vec_random(N)\n",
" \n",
......
......@@ -788,7 +788,7 @@
"theta = np.random.randn(DEPTH, N, 1)\n",
"\n",
"# Call the built-in |00..0> initial state\n",
"initial_state1 = vec(N)\n",
"initial_state1 = vec(0, N)\n",
"# Call the built-in random quantum state |psi>\n",
"initial_state2 = vec_random(N)\n",
" \n",
......
......@@ -71,15 +71,15 @@ class Net(paddle.nn.Layer):
# Use computational basis to calculate each expectation value, which is the same
# as a diagonal element in U^dagger*H*U
loss_components = [
loss_struct[0][0],
loss_struct[1][1],
loss_struct[2][2],
loss_struct[3][3]
]
loss_components = []
for i in range(len(loss_struct)):
loss_components.append(loss_struct[i][i])
# Calculate the weighted loss function
loss = 4 * loss_components[0] + 3 * loss_components[1] + 2 * loss_components[2] + 1 * loss_components[3]
loss = 0
for i in range(len(loss_components)):
weight = 4 - i
loss += weight * loss_components[i]
return loss, loss_components
......@@ -128,17 +128,36 @@ def main():
loss_components = Paddle_SSVQE(H)
print('The estimated ground state energy is: ', loss_components[0].numpy())
print('The theoretical ground state energy: ', numpy.linalg.eigh(H)[0][0])
print('The estimated 1st excited state energy is: ', loss_components[1].numpy())
print('The theoretical 1st excited state energy: ', numpy.linalg.eigh(H)[0][1])
print('The estimated 2nd excited state energy is: ', loss_components[2].numpy())
print('The theoretical 2nd excited state energy: ', numpy.linalg.eigh(H)[0][2])
print('The estimated 3rd excited state energy is: ', loss_components[3].numpy())
print('The theoretical 3rd excited state energy: ', numpy.linalg.eigh(H)[0][3])
def output_ordinalvalue(num):
r"""
Convert to ordinal value
Args:
num (int): input number
Return:
(str): output ordinal value
"""
if num == 1:
return str(num) + "st"
elif num == 2:
return str(num) + "nd"
elif num == 3:
return str(num) + "rd"
else:
return str(num) + 'th'
for i in range(len(loss_components)):
if i == 0:
print('The estimated ground state energy is: ', loss_components[i].numpy())
print('The theoretical ground state energy is: ', numpy.linalg.eigh(H)[0][i])
else:
print('The estimated {} excited state energy is: {}'.format(
output_ordinalvalue(i), loss_components[i].numpy())
)
print('The theoretical {} excited state energy is: {}'.format(
output_ordinalvalue(i), numpy.linalg.eigh(H)[0][i])
)
if __name__ == '__main__':
......
此差异已折叠。
# Copyright (c) 2021 Institute for Quantum Computing, Baidu Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
ExpecVal Class
"""
import paddle
from paddle.autograd import PyLayer
__all__ = [
"ExpecVal"
]
class ExpecVal(PyLayer):
r"""PaddlePaddle 自定义 Python 算子,用来计算量子电路输出的量子态关于可观测量 H 的期望值。
"""
@staticmethod
def forward(ctx, cir, theta, grad_func, hamiltonian, delta=None, shots=0):
r"""前向函数。
Hint:
如果想输入的可观测量的矩阵为 :math:`0.7Z\otimes X\otimes I+0.2I\otimes Z\otimes I` 。则 ``H`` 的 ``list`` 形式为 ``[[0.7, 'Z0, X1'], [0.2, 'Z1']]`` 。
Args:
cir (UAnsatz): 目标量子电路
theta (paddle.Tensor): 量子电路中的需要被优化的参数
grad_func (string): 用于计算梯度的函数名,应为 ``'finite_diff'`` 或 ``'param_shift'``
hamiltonian (list or Hamiltonian): 记录哈密顿量信息的列表或 ``Hamiltonian`` 类的对象
delta (float): 差分法中需要用到的 delta,默认为 ``None``
shots (int, optional): 表示测量次数;默认为 0,表示返回期望值的精确值,即测量无穷次后的期望值
Returns:
paddle.Tensor: 量子电路输出的量子态关于可观测量 H 的期望值
代码示例:
.. code-block:: python
import numpy as np
import paddle
from paddle_quantum.circuit import UAnsatz
from paddle_quantum.expecval import ExpecVal
N = 2
D = 2
theta = paddle.uniform(shape=[N * D], dtype='float64', min=0.0, max=np.pi * 2)
theta.stop_gradient = False
cir = UAnsatz(N)
cir.real_entangled_layer(theta, D)
cir.run_state_vector()
H = [[1.0, 'z0,z1']]
delta = 0.01
shots = 0
z = ExpecVal.apply(cir, cir.get_param(), 'finite_diff', H, delta, shots)
print(z)
::
Tensor(shape=[1], dtype=float64, place=CPUPlace, stop_gradient=False,
[0.61836319])
"""
assert grad_func in {'finite_diff', 'param_shift'}, "grad_func must be one of 'finite_diff' or 'param_shift'"
# Pass grad_func, cir, theta, delta, shots, and Hamiltonian into the backward function by adding temporary attributes
ctx.grad_func = grad_func
ctx.cir = cir
ctx.theta = theta
ctx.delta = delta
ctx.shots = shots
ctx.Hamiltonian = hamiltonian
# Compute the expectation value
cir.update_param(theta)
expec_val = cir.expecval(ctx.Hamiltonian, shots)
return expec_val
@staticmethod
def backward(ctx, dy):
r"""反向函数。
Args:
dy (paddle.Tensor): 前向函数输出的期望值的梯度
Returns:
paddle.Tensor: 前向函数中输入的参数 ``theta`` 的梯度
代码示例:
.. code-block:: python
import numpy as np
import paddle
from paddle_quantum.circuit import UAnsatz
from paddle_quantum.expecval import ExpecVal
N = 2
D = 2
theta = paddle.uniform(shape=[N * D], dtype='float64', min=0.0, max=np.pi * 2)
theta.stop_gradient = False
cir = UAnsatz(N)
cir.real_entangled_layer(theta, D)
cir.run_state_vector()
H = [[1.0, 'z0,z1']]
delta = 0.01
shots = 0
z = ExpecVal.apply(cir, cir.get_param(), 'finite_diff', H, delta, shots)
temp = paddle.square(z)
temp.backward()
"""
# Get expec_func, grad_func, theta, delta, and args
cir = ctx.cir
grad_func = ctx.grad_func
delta = ctx.delta
shots = ctx.shots
Hamiltonian = ctx.Hamiltonian
# Compute the gradient
if grad_func == "finite_diff":
assert delta is not None, "Finite difference gradient requires an input 'delta'"
grad = dy * cir.finite_difference_gradient(Hamiltonian, delta, shots)
else:
grad = dy * cir.param_shift_gradient(Hamiltonian, shots)
grad.stop_gradient = False
return paddle.reshape(grad, ctx.theta.shape)
# Copyright (c) 2021 Institute for Quantum Computing, Baidu Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Functions and data simulator class of quantum finance
"""
import fastdtw
import numpy as np
from paddle_quantum.utils import Hamiltonian
__all__ = [
"DataSimulator",
"portfolio_optimization_hamiltonian",
"portfolio_diversification_hamiltonian",
"arbitrage_opportunities_hamiltonian"
]
class DataSimulator:
r"""用于生成和计算投资组合优化和投资分散化问题要用的数据和相关参数
"""
def __init__(self, stocks, start=None, end=None):
r"""构造函数,用于实例化一个 ``DataSimulator`` 对象。
Args:
stocks (list): 表示所有可投资股票的名字
start (datetime): 默认为 ``None``,表示随机生成股票数据时交易日的起始日期
end (datetime): 默认为 ``None``,表示随机生成股票数据时交易日的结束日期
"""
self._n = len(stocks)
self._stocks = stocks
if start and end:
self._start = start
self._end = end
self._data = []
self.asset_return_mean = None
self.asset_return_cov = None
def set_data(self, data):
r"""决定实验使用的数据是随机生成的还是用户本地输入的
Args:
data (list): 用户输入的股票数据
"""
if len(data) == self._n:
self._data = data
else:
print("invalid data, data is still empty.")
self._data = []
def randomly_generate(self):
r"""根据开始日期和结束日期随机生成用于实验的股票数据
Note:
若要随机生成股票数据,需要以 ``datetime`` 包中的格式指定开始日期和结束日期,如 ``start = datetime.datetime(2016, 1, 1)``
"""
if self._start and self._end:
num_days = (self._end - self._start).days
for _ in self._stocks:
fluctuation = np.random.standard_normal(num_days)
fluctuation = np.cumsum(fluctuation)
data_i = np.random.randint(1, 101, size=1) + fluctuation
trimmed_data_i = [max(data_i[j], 0) for j in range(num_days)]
if 0 in trimmed_data_i:
zero_ind = trimmed_data_i.index(0)
trimmed_data_i = trimmed_data_i[:zero_ind] + [0 for _ in range(num_days - zero_ind)]
self._data.append(trimmed_data_i)
else:
print("Please provide the start time and the end time you want to generate stock data.")
def get_asset_return_mean_vector(self):
r"""用于计算所有可投资股票的平均投资回报率
Returns:
list: 所有可投资的股票的平均投资回报率
"""
returns = []
for i in range(self._n):
return_i = [self._data[i][j + 1] / self._data[i][j] - 1
if self._data[i][j] != 0
else np.nan for j in range(len(self._data[i]) - 1)]
returns.append(return_i)
self.asset_return_mean = np.mean(returns, axis=1)
return self.asset_return_mean
def get_asset_return_covariance_matrix(self):
r"""用于计算所有可投资股票回报率之间的协方差矩阵
Returns:
list: 所有可投资股票回报率之间的协方差矩阵
"""
returns = []
for i in range(self._n):
return_i = [self._data[i][j + 1] / self._data[i][j] - 1
if self._data[i][j] != 0
else np.nan for j in range(len(self._data[i]) - 1)]
returns.append(return_i)
self.asset_return_cov = np.cov(returns)
return self.asset_return_cov
def get_similarity_matrix(self):
r"""计算各股票之间的相似矩阵
通过动态时间规整算法(Dynamic Time Warping, DTW)计算两股票之间的相似性
Returns:
list: 各股票间的相似矩阵
"""
self.rho = np.zeros((self._n, self._n))
for i in range(0, self._n):
self.rho[i, i] = 1
for j in range(i + 1, self._n):
curr_rho, _ = fastdtw.fastdtw(self._data[i], self._data[j])
curr_rho = 1 / curr_rho
self.rho[i, j] = curr_rho
self.rho[j, i] = curr_rho
return self.rho
def portfolio_optimization_hamiltonian(penalty, mu, sigma, q, budget):
r"""构建投资组合优化问题的哈密顿量
Args:
penalty (int): 惩罚参数
mu (list): 各股票的预期回报率
sigma (list): 各股票回报率间的协方差矩阵
q (float): 投资股票的风险
budget (int): 投资预算, 即要投资的股票数量
.. math::
C(x) = q \sum_i \sum_j S_{ji}x_ix_j - \sum_{i}x_i \mu_i + A \left(B - \sum_i x_i\right)^2
Hint:
将布尔变量 :math:`x_i` 映射到哈密顿矩阵上,:math:`x_i \mapsto \frac{I-Z_i}{2}`
Returns:
Hamiltonian: 投资组合优化问题的哈密顿量
"""
n = len(mu)
H_C_list1 = []
for i in range(n):
for j in range(n):
sigma_ij = sigma[i][j]
H_C_list1.append([sigma_ij / 4, 'I'])
if i != j:
H_C_list1.append([sigma_ij / 4, 'Z' + str(i) + ',Z' + str(j)])
else:
H_C_list1.append([sigma_ij / 4, 'I'])
H_C_list1.append([- sigma_ij / 4, 'Z' + str(i)])
H_C_list1.append([- sigma_ij / 4, 'Z' + str((j))])
H_C_list1 = [[q * c, s] for (c, s) in H_C_list1]
H_C_list2 = []
for i in range(n):
H_C_list2.append([- mu[i] / 2, 'I'])
H_C_list2.append([mu[i] / 2, 'Z' + str(i)])
H_C_list3 = [[budget ** 2, 'I']]
for i in range(n):
H_C_list3.append([- 2 * budget / 2, 'I'])
H_C_list3.append([2 * budget / 2, 'Z' + str(i)])
H_C_list3.append([2 / 4, 'I'])
H_C_list3.append([- 2 / 4, 'Z' + str(i)])
for ii in range(i):