From a075fc8396c9893eed40151c923b114cab5a1835 Mon Sep 17 00:00:00 2001
From: OriginQuantumCloud
Date: Wed, 28 Jan 2026 16:21:32 +0800
Subject: [PATCH 01/10] Update CONTRIBUTING.md
---
CONTRIBUTING.md | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 3ed6232..153fe91 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -159,7 +159,7 @@ git merge master
### 测试
-在pull request您的代码之前,请针对您修改的代码编写单元测试,并需要通过现有的测试。alg的测试基于pytest,[pytest使用文档])包含如何使用pytest编写单元测试。
+在pull request您的代码之前,请针对您修改的代码编写单元测试,并需要通过现有的测试。
在编写单元测试之前,您需要先注意一些规范:
@@ -189,3 +189,4 @@ git merge master
+
From e5423a9d7440d3502465d4245a8e1b0b768d452b Mon Sep 17 00:00:00 2001
From: OriginQuantumCloud
Date: Wed, 28 Jan 2026 18:13:31 +0800
Subject: [PATCH 02/10] Update CONTRIBUTING.md
---
CONTRIBUTING.md | 23 ++++++++++++-----------
1 file changed, 12 insertions(+), 11 deletions(-)
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 153fe91..d3dfedd 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -125,36 +125,36 @@ alg社区基于本源量子提供的pyqpanda-algorithm开源量子算法仓库
如果你觉得已准备好`code review`,且预备提交PR请求,请确保:
-- 代码遵循项目的代码风格,并且成功通过CI测试。为了方便起见,你可以先在本地执行,提前进行检查并发现报告问题。`
+- 代码遵循项目的代码风格,并且成功通过CI测试。为了方便起见,你可以先在本地执行,提前进行检查并发现报告问题。
-- 如果函数或类在PR期间被修改,请相应更新。如果你的拉取请求是添加一个新的类、函数或模块,那面向用户,请确保你也添加了这些内容文档索引。``
+- 如果函数或类在PR期间被修改,请相应更新。如果你的拉取请求是添加一个新的类、函数或模块,那面向用户,请确保你也添加了这些内容文档索引。
- 确保如果你的更改将对其他用户产生影响(新功能, 弃用、移除等),你已经添加了相关说明。
-在创建Pull Request之前,需要先fork alg [repo](https://github.com/OriginQ/pyqpanda-algorithm),然后使用这个fork中分支向官方仓库创建 Pull Request。在创建pull request时应选择推送到alg官方仓库的`master`分支。
+在创建Pull Request之前,需要先fork alg [repo](https://github.com/OriginQ/pyqpanda-algorithm),然后使用这个fork中分支向官方仓库创建 Pull Request。在创建pull request时应选择推送到alg官方仓库的`develop`分支。
fork 和 Pull Request的基本流程如下:
1. Fork alg的仓库 [repo page](https://github.com/OriginQ/pyqpanda-algorithm)。并把你的克隆仓库下载到你的本机。
-2. 从master分支创建一个新的分支:`git checkout master -b new_branch_name`,其中`new_branch_name` 是你的新分支的名称。
+2. 从`develop`分支创建一个新的分支:`git checkout develop -b new_branch_name`,其中`new_branch_name` 是你的新分支的名称。
3. 把你的修改提交到你自己的分支。
-4. 如果你的克隆仓库与alg的官方仓库不同步,你需要先更新你的克隆仓库的master分支,然后再把master分支合并到你自己的分支(在合并的过程中,你可能要修改一些合并冲突):
+4. 如果你的克隆仓库与alg的官方仓库不同步,你需要先更新你的克隆仓库的`develop`分支,然后再把`develop`分支合并到你自己的分支(在合并的过程中,你可能要修改一些合并冲突):
```
-# Update your local master.
+# Update your local develop.
git fetch upstream
-git checkout master
-git merge upstream/master
-# Merge local master into your branch.
+git checkout develop
+git merge upstream/develop
+# Merge local develop into your branch.
git checkout new_branch_name
-git merge master
+git merge develop
```
5. 把你修改的推送到你克隆的仓库。
`git push origin new_branch_name`
-6. 经过以上的操作,你就可以把你工作 Pull Request 给alg的官方仓库了,在pull request需要选择官方仓库的``master`分支。
+6. 经过以上的操作,你就可以把你工作 Pull Request 给alg的官方仓库了,在pull request需要选择官方仓库的`develop`分支。
7. 审查人员将对您的代码进行审核,并可能要求更改,您可以在本地执行这些操作,然后再次执行上述过程。
### 测试
@@ -190,3 +190,4 @@ git merge master
+
From fccdb9885f081fbaff3aae8efbc71f3a68746774 Mon Sep 17 00:00:00 2001
From: OriginQuantumCloud
Date: Wed, 28 Jan 2026 18:19:01 +0800
Subject: [PATCH 03/10] Update CONTRIBUTING_EN.md
---
CONTRIBUTING_EN.md | 20 ++++++++++----------
1 file changed, 10 insertions(+), 10 deletions(-)
diff --git a/CONTRIBUTING_EN.md b/CONTRIBUTING_EN.md
index e92249d..5015504 100644
--- a/CONTRIBUTING_EN.md
+++ b/CONTRIBUTING_EN.md
@@ -114,28 +114,28 @@ Before submitting a PR, ensure:
#### PR Workflow
-1. Fork the alg repository ([repo page](https://github.com/OriginQ/QPanda-2)) and clone it locally.
+1. Fork the alg repository ([repo page]([https://github.com/OriginQ/QPanda-2](https://github.com/OriginQ/pyqpanda-algorithm))) and clone it locally.
-2. Create a new branch from `master`:
- `git checkout master -b new_branch_name`
+2. Create a new branch from `develop`:
+ `git checkout develop -b new_branch_name`
3. Commit your changes to the new branch.
-4. Sync your forked `master` with the official repository (resolve merge conflicts if needed):
+4. Sync your forked `develop` with the official repository (resolve merge conflicts if needed):
```bash
- # Update local master
+ # Update local develop
git fetch upstream
- git checkout master
- git merge upstream/master
- # Merge master into your branch
+ git checkout develop
+ git merge upstream/develop
+ # Merge develop into your branch
git checkout new_branch_name
- git merge master
+ git merge develop
```
### Testing
-Write unit tests for modified code and pass all existing tests before submitting a PR. alg uses pytest; refer to the [pytest Primer]for guidance.
+Write unit tests for modified code and pass all existing tests before submitting a PR.
#### Testing Guidelines
From 6506f61bb927e315b411da91acb3dee3d5d77322 Mon Sep 17 00:00:00 2001
From: OriginQuantumCloud
Date: Wed, 28 Jan 2026 18:23:38 +0800
Subject: [PATCH 04/10] Update CONTRIBUTING_EN.md
---
CONTRIBUTING_EN.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/CONTRIBUTING_EN.md b/CONTRIBUTING_EN.md
index 5015504..420af45 100644
--- a/CONTRIBUTING_EN.md
+++ b/CONTRIBUTING_EN.md
@@ -107,7 +107,7 @@ To claim an issue (e.g., `good first issue`, `enhancement issue`):
Before submitting a PR, ensure:
-- Code complies with the project’s style and passes CI tests (run `tox` locally to check).
+- Code complies with the project’s style and passes CI tests.
- Relevant documentation (including docstrings) is updated.
- Additional tests are added for impactful changes.
- Release notes are added for user-facing changes (mark the PR as a changelog).
From 91d9c1206dbb6259d9f99bfb94ed014fb48fc19f Mon Sep 17 00:00:00 2001
From: OriginQuantumCloud
Date: Thu, 29 Jan 2026 09:50:22 +0800
Subject: [PATCH 05/10] Update CONTRIBUTING.md
---
CONTRIBUTING.md | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index d3dfedd..1a0069d 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -125,7 +125,7 @@ alg社区基于本源量子提供的pyqpanda-algorithm开源量子算法仓库
如果你觉得已准备好`code review`,且预备提交PR请求,请确保:
-- 代码遵循项目的代码风格,并且成功通过CI测试。为了方便起见,你可以先在本地执行,提前进行检查并发现报告问题。
+- 代码遵循项目的代码风格,并且成功通过CI/CD测试。为了方便起见,你可以先在本地执行,提前进行检查并发现报告问题。
- 如果函数或类在PR期间被修改,请相应更新。如果你的拉取请求是添加一个新的类、函数或模块,那面向用户,请确保你也添加了这些内容文档索引。
@@ -191,3 +191,4 @@ git merge develop
+
From 9500cb968d325a6087a3610dd790573f71b3fd7a Mon Sep 17 00:00:00 2001
From: OriginQuantumCloud
Date: Thu, 29 Jan 2026 09:51:03 +0800
Subject: [PATCH 06/10] Update CONTRIBUTING_EN.md
---
CONTRIBUTING_EN.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/CONTRIBUTING_EN.md b/CONTRIBUTING_EN.md
index 420af45..a55cb6d 100644
--- a/CONTRIBUTING_EN.md
+++ b/CONTRIBUTING_EN.md
@@ -107,7 +107,7 @@ To claim an issue (e.g., `good first issue`, `enhancement issue`):
Before submitting a PR, ensure:
-- Code complies with the project’s style and passes CI tests.
+- Code complies with the project’s style and passes CI/CD tests.
- Relevant documentation (including docstrings) is updated.
- Additional tests are added for impactful changes.
- Release notes are added for user-facing changes (mark the PR as a changelog).
From 09730d33478c382bfce692c3548570f607c20ba4 Mon Sep 17 00:00:00 2001
From: shenzhi-git
Date: Mon, 2 Feb 2026 16:09:21 +0800
Subject: [PATCH 07/10] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E4=BB=A3?=
=?UTF-8?q?=E7=A0=81=E4=B8=AD=E7=9A=84test?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
Tutorials/source/GettingStarted.rst | 18 ++----------------
Tutorials/source/conf.py | 2 +-
Tutorials/source/index.rst | 1 -
pyqpanda-algorithm/pyqpanda_alg/QAOA/qaoa.py | 1 -
.../pyqpanda_alg/QSVM/quantum_kernel_svm.py | 1 -
pyqpanda-algorithm/setup.py | 6 ++----
test/QAOA/Test_complete_xy_mixer.py | 17 +----------------
.../Test_default_circuits_linear_w_state.py | 2 +-
...st_default_circuits_prepare_dicke_state.py | 3 +--
test/QAOA/Test_dstate_linear_w_state.py | 2 +-
test/QAOA/Test_dstate_prepare_dicke_state.py | 2 +-
test/QAOA/Test_init_d_state.py | 19 +++++--------------
test/QAOA/Test_qaoa_QAOA_calculate_energy.py | 11 +++--------
test/QAOA/Test_qaoa_p_0.py | 8 --------
test/QAOA/Test_qaoa_p_1.py | 8 --------
test/QAOA/Test_qaoa_parameter_interpolate.py | 12 +++---------
.../Test_qaoa_pauli_z_operator_to_circuit.py | 12 ++----------
test/QAOA/Test_qaoa_problem_to_z_operator.py | 6 +++---
test/QAOA/Test_spsa_minimize.py | 10 +---------
test/QAOA/Test_xy_mixer.py | 17 +----------------
test/QARM/Test_qarm.py | 1 -
test/QPCA/Test_qpca.py | 5 -----
test/QSVM/Test_qsvm.py | 2 --
test/pytest.ini | 1 -
24 files changed, 28 insertions(+), 139 deletions(-)
diff --git a/Tutorials/source/GettingStarted.rst b/Tutorials/source/GettingStarted.rst
index 0a7d0cd..7452a10 100644
--- a/Tutorials/source/GettingStarted.rst
+++ b/Tutorials/source/GettingStarted.rst
@@ -11,7 +11,7 @@ It contains many practical quantum application algorithms. Installation and use
Configuration
>>>>>>>>>>>>>>>>>>>
-pyqpanda_alg uses C++ as the host language, and its environmental requirements for the system are as follows:
+pyqpanda_alg's environmental requirements for the system are as follows:
Windows
---------------------
@@ -19,8 +19,6 @@ Windows
* - software
- version
- * - `Microsoft Visual C++ Redistributable x64`_
- - 2019
* - Python
- >= 3.11 && <= 3.13
@@ -34,16 +32,4 @@ Linux
* - GCC
- >= 7.5
* - Python
- - >= 3.11 && <= 3.13
-
-
-Install
->>>>>>>>>>>>>>>>>
-
-If you have already installed the python environment and the pip tool, enter the following command in the terminal or console:
-
- .. code-block:: python
-
- pip install pyqpanda_alg
-
-.. note:: If you encounter permission problems under linux, you need to add ``sudo``
\ No newline at end of file
+ - >= 3.11 && <= 3.13
\ No newline at end of file
diff --git a/Tutorials/source/conf.py b/Tutorials/source/conf.py
index f5ccd16..3a09a15 100644
--- a/Tutorials/source/conf.py
+++ b/Tutorials/source/conf.py
@@ -19,7 +19,7 @@
# -- Project information -----------------------------------------------------
project = 'pyqpanda-algorithm'
-copyright = '2023, OriginQC'
+copyright = '2026, OriginQC'
author = 'OriginQC'
# The short X.Y version
diff --git a/Tutorials/source/index.rst b/Tutorials/source/index.rst
index 0866854..4c50a5d 100644
--- a/Tutorials/source/index.rst
+++ b/Tutorials/source/index.rst
@@ -30,7 +30,6 @@ Overall, it provides a standardized set of tools for developers, allowing them t
autoapi/pyqpanda_alg/QAOA/index
autoapi/pyqpanda_alg/QARM/index
- autoapi/pyqpanda_alg/QAlgBase/index
autoapi/pyqpanda_alg/QKmeans/index
autoapi/pyqpanda_alg/QPCA/index
autoapi/pyqpanda_alg/QSVM/index
diff --git a/pyqpanda-algorithm/pyqpanda_alg/QAOA/qaoa.py b/pyqpanda-algorithm/pyqpanda_alg/QAOA/qaoa.py
index 688e01e..210f421 100644
--- a/pyqpanda-algorithm/pyqpanda_alg/QAOA/qaoa.py
+++ b/pyqpanda-algorithm/pyqpanda_alg/QAOA/qaoa.py
@@ -482,7 +482,6 @@ def run_qaoa_circuit(self, gammas, betas, shots=-1):
.. code-block:: python
- import pyqpanda as pq
import sympy as sp
from pyqpanda_alg.QAOA.qaoa import *
diff --git a/pyqpanda-algorithm/pyqpanda_alg/QSVM/quantum_kernel_svm.py b/pyqpanda-algorithm/pyqpanda_alg/QSVM/quantum_kernel_svm.py
index 562976b..4b6da4c 100644
--- a/pyqpanda-algorithm/pyqpanda_alg/QSVM/quantum_kernel_svm.py
+++ b/pyqpanda-algorithm/pyqpanda_alg/QSVM/quantum_kernel_svm.py
@@ -209,7 +209,6 @@ def evaluate(self, x_vec: np.ndarray, y_vec: np.ndarray = None) -> np.ndarray:
import os
import numpy as np
- import pyqpanda as pq
from sklearn.svm import SVC
import matplotlib
try:
diff --git a/pyqpanda-algorithm/setup.py b/pyqpanda-algorithm/setup.py
index fd4b50e..f8aca03 100644
--- a/pyqpanda-algorithm/setup.py
+++ b/pyqpanda-algorithm/setup.py
@@ -6,7 +6,6 @@
requirements = open('requirements.txt').readlines()
requirements = [r.strip() for r in requirements]
-
is_win = (platform.system() == 'Windows')
if is_win:
pd_files = ['*.pyd', '*.dll', '*.pyi']
@@ -20,10 +19,9 @@
license = "Apache Licence",
author = "OriginQ",
install_requires=requirements,
- description= "A Quantum Algorithm Development and Runtime Environment Kit, based on pyqpanda.",
+ description= "A Quantum Algorithm Development and Runtime Environment Kit, based on pyqpanda3.",
packages = find_packages(),
- py_modules = ['psi4_wrapper'],
package_data={
'':pd_files
},
@@ -39,4 +37,4 @@
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.13"
],
-)
+)
\ No newline at end of file
diff --git a/test/QAOA/Test_complete_xy_mixer.py b/test/QAOA/Test_complete_xy_mixer.py
index 821d618..2983593 100644
--- a/test/QAOA/Test_complete_xy_mixer.py
+++ b/test/QAOA/Test_complete_xy_mixer.py
@@ -3,7 +3,6 @@
# import pytest
# import numpy as np
#
-# # 添加项目路径到系统路径
# sys.path.append((Path.cwd().parent.parent).__str__())
#
# from pyqpanda3.core import QProg, RX, CPUQVM
@@ -11,14 +10,11 @@
#
#
# class TestCompleteXYMixer:
-# """测试 complete_xy_mixer 接口"""
#
# def setup_method(self):
-# """测试前的初始化"""
# self.machine = CPUQVM()
#
# def calculate_hamming_weight_distribution(self, prob_dict, max_weight):
-# """计算汉明权重分布"""
# weight_probs = {}
# for weight in range(max_weight + 1):
# prob = sum(value for key, value in prob_dict.items()
@@ -27,20 +23,16 @@
# return weight_probs
#
# def test_complete_xy_mixer_hamming_weight_preservation(self):
-# """测试XY mixer应该保持汉明权重"""
# n_qubits = 4
# prog = QProg(n_qubits)
# qubits = prog.qubits()
#
-# # 创建初始状态 - 使用随机RX门创建复杂初始状态
# for q in qubits:
# prog << RX(q, np.random.random() * 2 * np.pi)
#
-# # 获取初始状态的概率分布
# self.machine.run(prog, shots=1)
# original_result = self.machine.result().get_prob_dict()
#
-# # 计算初始汉明权重分布
# original_weight_probs = self.calculate_hamming_weight_distribution(original_result, n_qubits)
#
# # 应用 complete_xy_mixer
@@ -48,27 +40,20 @@
# circuit = default_circuits.complete_xy_mixer(qubits, beta)
# prog << circuit
#
-# # 获取应用mixer后的概率分布
# self.machine.run(prog, shots=1)
# final_result = self.machine.result().get_prob_dict()
#
-# # 计算最终汉明权重分布
# final_weight_probs = self.calculate_hamming_weight_distribution(final_result, n_qubits)
-#
-# # 打印详细的权重分布变化
# print("\nHamming weight distribution comparison:")
# for weight in range(n_qubits + 1):
# original_prob = original_weight_probs.get(weight, 0)
# final_prob = final_weight_probs.get(weight, 0)
# print(f"Hamming weight {weight}: {original_prob:.4f} -> {final_prob:.4f}")
#
-# # XY mixer应该保持汉明权重(在统计误差范围内)
-# # 由于有限shots和数值精度,允许一定的误差
-# tolerance = 0.05 # 5% 容忍度
+# tolerance = 0.05
# assert abs(original_prob - final_prob) < tolerance, \
# f"Hamming weight {weight} not preserved within tolerance: {original_prob:.4f} -> {final_prob:.4f}"
#
#
# if __name__ == "__main__":
-# # 运行测试
# pytest.main([__file__, "-v", "-s"])
\ No newline at end of file
diff --git a/test/QAOA/Test_default_circuits_linear_w_state.py b/test/QAOA/Test_default_circuits_linear_w_state.py
index 99b41bb..fd45bfb 100644
--- a/test/QAOA/Test_default_circuits_linear_w_state.py
+++ b/test/QAOA/Test_default_circuits_linear_w_state.py
@@ -63,5 +63,5 @@
#
#
# if __name__ == "__main__":
-# # 运行测试
+# # run test
# pytest.main([__file__, "-v"])
\ No newline at end of file
diff --git a/test/QAOA/Test_default_circuits_prepare_dicke_state.py b/test/QAOA/Test_default_circuits_prepare_dicke_state.py
index 157ebef..0d34f58 100644
--- a/test/QAOA/Test_default_circuits_prepare_dicke_state.py
+++ b/test/QAOA/Test_default_circuits_prepare_dicke_state.py
@@ -3,7 +3,6 @@
# import pytest
# import numpy as np
#
-# # 添加项目路径到系统路径
# sys.path.append((Path.cwd().parent.parent).__str__())
#
# from pyqpanda_alg.QAOA import default_circuits
@@ -45,5 +44,5 @@
#
#
# if __name__ == "__main__":
-# # 运行测试
+# # run test
# pytest.main([__file__, "-v"])
\ No newline at end of file
diff --git a/test/QAOA/Test_dstate_linear_w_state.py b/test/QAOA/Test_dstate_linear_w_state.py
index 5a91289..0a8aad5 100644
--- a/test/QAOA/Test_dstate_linear_w_state.py
+++ b/test/QAOA/Test_dstate_linear_w_state.py
@@ -55,5 +55,5 @@
#
#
# if __name__ == "__main__":
-# # 运行测试
+# # run test
# pytest.main([__file__, "-v"])
\ No newline at end of file
diff --git a/test/QAOA/Test_dstate_prepare_dicke_state.py b/test/QAOA/Test_dstate_prepare_dicke_state.py
index d2125ec..f8d1670 100644
--- a/test/QAOA/Test_dstate_prepare_dicke_state.py
+++ b/test/QAOA/Test_dstate_prepare_dicke_state.py
@@ -44,5 +44,5 @@
#
#
# if __name__ == "__main__":
-# # 直接运行测试
+# # 直接run test
# pytest.main([__file__, "-v"])
\ No newline at end of file
diff --git a/test/QAOA/Test_init_d_state.py b/test/QAOA/Test_init_d_state.py
index 69e7e4e..cda266a 100644
--- a/test/QAOA/Test_init_d_state.py
+++ b/test/QAOA/Test_init_d_state.py
@@ -3,7 +3,6 @@
# import pytest
# import numpy as np
#
-# # 添加项目路径到系统路径
# sys.path.append((Path.cwd().parent.parent).__str__())
#
# from pyqpanda3.core import QProg, CPUQVM
@@ -11,14 +10,11 @@
#
#
# class TestInitDState:
-# """测试 init_d_state 接口"""
#
# def setup_method(self):
-# """测试前的初始化"""
# self.machine = CPUQVM()
#
# def calculate_domain_hamming_weights(self, result_key, domains):
-# """计算测量结果中每个域的汉明权重"""
# domain_weights = []
# for domain in domains:
# weight = sum(1 for idx in domain if result_key[idx] == '1')
@@ -26,24 +22,20 @@
# return domain_weights
#
# def test_init_d_state_integer_domains(self):
-# """测试整数分区方式的Dicke态初始化"""
# n_qubits = 6
-# k = 2 # 每个域的汉明权重
-# domains = 2 # 分成2个域
+# k = 2
+# domains = 2
#
# prog = QProg(n_qubits)
# qubits = prog.qubits()
#
-# # 创建Dicke态初始化电路
# init_circuit_func = default_circuits.init_d_state(domains, k)
# init_circuit = init_circuit_func(qubits)
# prog << init_circuit
#
-# # 运行量子程序
# self.machine.run(prog, shots=1000)
# results = self.machine.result().get_prob_dict(qubits)
#
-# # 计算域的分区(均匀分成k份)
# domain_size = n_qubits // domains
# domain_list = [list(range(i * domain_size, (i + 1) * domain_size)) for i in range(domains)]
#
@@ -51,13 +43,12 @@
# valid_states = 0
#
# for key, prob in results.items():
-# if prob > 0.001: # 忽略概率很小的状态
-# key_reversed = key[::-1] # 反转键以匹配量子比特顺序
+# if prob > 0.001:
+# key_reversed = key[::-1]
# domain_weights = self.calculate_domain_hamming_weights(key_reversed, domain_list)
#
# print(f"State {key_reversed}: domain weights = {domain_weights}, prob = {prob:.4f}")
#
-# # 验证每个域的汉明权重都等于k
# for weight in domain_weights:
# assert weight == k, f"Domain weight should be {k}, but got {weight} for state {key_reversed}"
#
@@ -67,5 +58,5 @@
#
#
# if __name__ == "__main__":
-# # 运行测试
+# # run test
# pytest.main([__file__, "-v", "-s"])
\ No newline at end of file
diff --git a/test/QAOA/Test_qaoa_QAOA_calculate_energy.py b/test/QAOA/Test_qaoa_QAOA_calculate_energy.py
index 7b20a19..ec8dd1e 100644
--- a/test/QAOA/Test_qaoa_QAOA_calculate_energy.py
+++ b/test/QAOA/Test_qaoa_QAOA_calculate_energy.py
@@ -4,7 +4,6 @@
# import sympy as sp
# import numpy as np
#
-# # 添加项目路径
# sys.path.append((Path.cwd().parent.parent).__str__())
#
# from pyqpanda_alg.QAOA.qaoa import QAOA, p_1
@@ -12,18 +11,14 @@
#
#
# class TestCalculateEnergy:
-# """测试calculate_energy接口"""
#
# def test_basic_functionality_with_symbolic_problem(self):
-# """测试基本功能:使用符号问题计算能量"""
-# # 创建测试问题:f = 2*x0*x1 + 3*x2 - 1
+# # f = 2*x0*x1 + 3*x2 - 1
# vars = sp.symbols('x0:3')
# f = 2*vars[0]*vars[1] + 3*vars[2] - 1
#
-# # 初始化QAOA
# qaoa_f = QAOA(f)
#
-# # 测试不同的解
# test_cases = [
# ([1, 0, 0], 2*1*0 + 3*0 - 1), # f(1,0,0) = -1
# ([0, 1, 1], 2*0*1 + 3*1 - 1), # f(0,1,1) = 2
@@ -35,8 +30,8 @@
# for solution, expected_energy in test_cases:
# calculated_energy = qaoa_f.calculate_energy(solution)
# assert abs(calculated_energy - expected_energy) < 1e-10, \
-# f"解 {solution} 的能量计算错误: 期望 {expected_energy}, 得到 {calculated_energy}"
+# f"solve {solution} error : expect {expected_energy}, get {calculated_energy}"
#
# if __name__ == "__main__":
-# # 运行测试
+# # run test
# pytest.main([__file__, "-v"])
\ No newline at end of file
diff --git a/test/QAOA/Test_qaoa_p_0.py b/test/QAOA/Test_qaoa_p_0.py
index ed0695f..3bc7fd8 100644
--- a/test/QAOA/Test_qaoa_p_0.py
+++ b/test/QAOA/Test_qaoa_p_0.py
@@ -2,26 +2,19 @@
# from pathlib import Path
# import pytest
#
-# # 添加项目路径到系统路径
# sys.path.append((Path.cwd().parent.parent).__str__())
#
-# # 导入测试所需的模块
# from pyqpanda_alg.QAOA import qaoa
# from pyqpanda3.hamiltonian import PauliOperator
#
#
# class TestP0Interface:
-# """测试 qaoa.p_0 接口的功能性"""
#
# def test_p0_basic_functionality(self):
-# """测试 p_0 接口的基本功能 - 返回 PauliOperator 对象"""
-# # 测试不同索引的 Pauli 算符生成
# operator_0 = qaoa.p_0(0)
#
-# # 验证返回对象类型
# assert isinstance(operator_0, PauliOperator)
#
-# # 验证算符有字符串表示
# assert str(operator_0) is not None
# assert len(str(operator_0)) > 0
#
@@ -29,5 +22,4 @@
#
#
# if __name__ == "__main__":
-# # 运行测试
# pytest.main([__file__, "-v", "-s"])
\ No newline at end of file
diff --git a/test/QAOA/Test_qaoa_p_1.py b/test/QAOA/Test_qaoa_p_1.py
index 00457f0..ad80dce 100644
--- a/test/QAOA/Test_qaoa_p_1.py
+++ b/test/QAOA/Test_qaoa_p_1.py
@@ -2,30 +2,22 @@
# from pathlib import Path
# import pytest
#
-# # 添加项目路径到系统路径
# sys.path.append((Path.cwd().parent.parent).__str__())
#
-# # 导入测试所需的模块
# from pyqpanda_alg.QAOA import qaoa
# from pyqpanda3.hamiltonian import PauliOperator
#
#
# class TestP1Interface:
-# """测试 qaoa.p_1 接口的功能性"""
#
# def test_p1_basic_functionality(self):
-# """测试 p_1 接口的基本功能"""
-# # 测试不同索引的 Pauli 算符生成
# operator_0 = qaoa.p_1(0)
# operator_1 = qaoa.p_1(1)
# operator_2 = qaoa.p_1(2)
#
-# # 验证返回对象类型
# assert isinstance(operator_0, PauliOperator)
# assert isinstance(operator_1, PauliOperator)
# assert isinstance(operator_2, PauliOperator)
-#
-# # 验证不同索引生成的算符不同
# assert str(operator_0) != str(operator_1)
# assert str(operator_1) != str(operator_2)
#
diff --git a/test/QAOA/Test_qaoa_parameter_interpolate.py b/test/QAOA/Test_qaoa_parameter_interpolate.py
index a94a3a0..4670fc5 100644
--- a/test/QAOA/Test_qaoa_parameter_interpolate.py
+++ b/test/QAOA/Test_qaoa_parameter_interpolate.py
@@ -3,30 +3,24 @@
import pytest
import numpy as np
-# 添加项目路径到系统路径
sys.path.append((Path.cwd().parent.parent).__str__())
-# 导入测试所需的模块
from pyqpanda_alg.QAOA import qaoa
class TestParameterInterpolate:
- """测试 qaoa.parameter_interpolate 接口的功能性"""
def test_basic_functionality(self):
- """测试基本功能 - 2p个参数插值为2(p+1)个参数"""
- # 使用示例中的测试用例
initial_parameter = np.array([0.1, 0.2, 0.2, 0.1])
new_parameter = qaoa.parameter_interpolate(initial_parameter)
- # 验证返回对象类型和形状
assert isinstance(new_parameter, np.ndarray)
assert new_parameter.shape == (6,) # 2*(2+1)=6
- print(f"输入: {initial_parameter}")
- print(f"输出: {new_parameter}")
+ print(f"{initial_parameter}")
+ print(f"{new_parameter}")
if __name__ == "__main__":
- # 运行测试
+ # run test
pytest.main([__file__, "-v", "-s"])
\ No newline at end of file
diff --git a/test/QAOA/Test_qaoa_pauli_z_operator_to_circuit.py b/test/QAOA/Test_qaoa_pauli_z_operator_to_circuit.py
index 5e988bb..fdaab1b 100644
--- a/test/QAOA/Test_qaoa_pauli_z_operator_to_circuit.py
+++ b/test/QAOA/Test_qaoa_pauli_z_operator_to_circuit.py
@@ -4,7 +4,6 @@
# import sympy as sp
# import numpy as np
#
-# # 添加项目路径
# sys.path.append((Path.cwd().parent.parent).__str__())
#
# from pyqpanda_alg.QAOA import qaoa
@@ -12,32 +11,25 @@
#
#
# class TestPauliZOperatorToCircuit:
-# """测试pauli_z_operator_to_circuit接口"""
#
# @classmethod
# def setup_class(cls):
-# """测试类初始化"""
# cls.machine = CPUQVM()
#
# def setup_method(self):
-# """每个测试方法前的设置"""
# self.prog = QProg(3)
# self.qubits = self.prog.qubits()
#
# def test_basic_functionality(self):
-# """测试基本功能:构造exp(-iH γ)的量子线路"""
-# # 创建测试问题:f = 2*x0*x1 + 3*x2 - 1
+# # f = 2*x0*x1 + 3*x2 - 1
# vars = sp.symbols('x0:3')
# f = 2*vars[0]*vars[1] + 3*vars[2] - 1
#
-# # 将问题转换为Pauli Z算子
# operator = qaoa.problem_to_z_operator(f)
#
-# # 构造量子线路
# gamma = 1.0
# circuit, _ = qaoa.pauli_z_operator_to_circuit(operator, self.qubits, gamma)
#
-# # 验证线路不为空
# assert circuit is not None
# originir_str = circuit.originir()
# assert isinstance(originir_str, str)
@@ -45,5 +37,5 @@
#
#
# if __name__ == "__main__":
-# # 运行测试
+# # run test
# pytest.main([__file__, "-v", "-s"])
\ No newline at end of file
diff --git a/test/QAOA/Test_qaoa_problem_to_z_operator.py b/test/QAOA/Test_qaoa_problem_to_z_operator.py
index 2d8aa8d..4fc0fd5 100644
--- a/test/QAOA/Test_qaoa_problem_to_z_operator.py
+++ b/test/QAOA/Test_qaoa_problem_to_z_operator.py
@@ -21,10 +21,10 @@
#
# assert str(hamiltonian) is not None
# assert len(str(hamiltonian)) > 0
-# print(f"原始表达式: {f}")
-# print(f"转换后的哈密顿量: {hamiltonian}")
+# print(f"{f}")
+# print(f"{hamiltonian}")
#
#
# if __name__ == "__main__":
-# # 运行测试
+# # run test
# pytest.main([__file__, "-v", "-s"])
\ No newline at end of file
diff --git a/test/QAOA/Test_spsa_minimize.py b/test/QAOA/Test_spsa_minimize.py
index 819e394..655f036 100644
--- a/test/QAOA/Test_spsa_minimize.py
+++ b/test/QAOA/Test_spsa_minimize.py
@@ -3,17 +3,14 @@
import sys
from pathlib import Path
-# 添加模块路径
sys.path.append((Path.cwd().parent.parent).__str__())
from pyqpanda_alg.QAOA import spsa
class TestSPSAMinimize:
- """spsa_minimize接口测试类"""
@pytest.fixture
def noise_function(self):
- """创建带噪声的测试函数"""
class NoiseF:
def __init__(self):
self.eval_count = 0
@@ -21,7 +18,6 @@ def __init__(self):
def eval_f(self, x):
self.eval_count += 1
- # 添加高斯噪声的二次函数
return np.linalg.norm(x**2 + np.random.normal(0, 0.1, size=len(x)))
def record(self, x):
@@ -31,13 +27,11 @@ def record(self, x):
@pytest.fixture
def simple_function(self):
- """创建简单的测试函数(无噪声)"""
def func(x):
- return np.sum(x**2) # 简单的二次函数
+ return np.sum(x**2)
return func
def test_spsa_basic_functionality(self, noise_function):
- """测试SPSA基本功能"""
x0 = np.array([1.0, 2.0, 3.0, 4.0])
result = spsa.spsa_minimize(
@@ -47,11 +41,9 @@ def test_spsa_basic_functionality(self, noise_function):
maxiter=50
)
- # 验证结果类型和形状
assert isinstance(result, np.ndarray)
assert result.shape == x0.shape
- # 验证回调函数被调用
assert len(noise_function.history) > 0
assert noise_function.eval_count > 0
diff --git a/test/QAOA/Test_xy_mixer.py b/test/QAOA/Test_xy_mixer.py
index 359dfad..bed781f 100644
--- a/test/QAOA/Test_xy_mixer.py
+++ b/test/QAOA/Test_xy_mixer.py
@@ -3,7 +3,6 @@
# import pytest
# import numpy as np
#
-# # 添加项目路径到系统路径
# sys.path.append((Path.cwd().parent.parent).__str__())
#
# from pyqpanda3.core import QProg, QCircuit, RX, CPUQVM
@@ -11,57 +10,45 @@
#
#
# class TestXYMixer:
-# """测试 xy_mixer 接口"""
#
# def setup_method(self):
-# """测试前的初始化"""
# self.machine = CPUQVM()
#
# def calculate_domain_hamming_weights(self, prob_dict, domains):
-# """计算每个域的汉明权重分布"""
# domain_probs = {}
# for result_key, prob_value in prob_dict.items():
# domain_weights = []
# for domain in domains:
-# # 计算该域的汉明权重
# weight = sum(1 for idx in domain if result_key[idx] == '1')
# domain_weights.append(weight)
#
-# # 将权重元组作为键
# weight_key = tuple(domain_weights)
# domain_probs[weight_key] = domain_probs.get(weight_key, 0) + prob_value
#
# return domain_probs
#
# def test_xy_mixer_integer_domains_parity(self):
-# """测试整数分区方式的parity XY mixer"""
# n_qubits = 4
-# k_domains = 2 # 分成2个域
+# k_domains = 2
#
# prog = QProg(n_qubits)
# qubits = prog.qubits()
#
-# # 创建初始状态
# for q in qubits:
# prog << RX(q, np.random.random() * np.pi)
#
-# # 获取初始状态的概率分布
# self.machine.run(prog, shots=1)
# origin_result = self.machine.result().get_prob_dict()
#
-# # 创建XY mixer电路
# circuit = default_circuits.xy_mixer(k_domains, 'PXY')(qubits, np.pi/2)
# prog << circuit
#
-# # 获取最终状态的概率分布
# self.machine.run(prog, shots=1)
# final_result = self.machine.result().get_prob_dict()
#
-# # 计算域的分区(均匀分成k份)
# domain_size = n_qubits // k_domains
# domains = [list(range(i * domain_size, (i + 1) * domain_size)) for i in range(k_domains)]
#
-# # 计算每个域的汉明权重分布
# origin_domain_probs = self.calculate_domain_hamming_weights(origin_result, domains)
# final_domain_probs = self.calculate_domain_hamming_weights(final_result, domains)
#
@@ -71,11 +58,9 @@
# final_prob = final_domain_probs.get(weight_combo, 0)
# print(f"Domain weights {weight_combo}: {origin_prob:.4f} -> {final_prob:.4f}")
#
-# # 每个域的汉明权重应该保持
# tolerance = 0.06
# assert abs(origin_prob - final_prob) < tolerance, \
# f"Domain weights {weight_combo} not preserved: {origin_prob:.4f} -> {final_prob:.4f}"
#
# if __name__ == "__main__":
-# # 运行测试
# pytest.main([__file__, "-v", "-s"])
\ No newline at end of file
diff --git a/test/QARM/Test_qarm.py b/test/QARM/Test_qarm.py
index 7f1a7a0..339b1f5 100644
--- a/test/QARM/Test_qarm.py
+++ b/test/QARM/Test_qarm.py
@@ -26,7 +26,6 @@ def read(file_path):
def test_qarm_normal_case():
- """测试正常情况下的QARM执行"""
data_path = QARM.__path__[0]
data_file = os.path.join(data_path, 'dataset/data2.txt')
trans_data = read(data_file)
diff --git a/test/QPCA/Test_qpca.py b/test/QPCA/Test_qpca.py
index ca2c40d..31a1047 100644
--- a/test/QPCA/Test_qpca.py
+++ b/test/QPCA/Test_qpca.py
@@ -4,23 +4,18 @@
import pytest
import numpy as np
-# 添加项目路径到系统路径
sys.path.append((Path.cwd().parent.parent).__str__())
class TestQPCA:
- """QPCA测试类"""
@pytest.fixture
def sample_data(self):
- """提供标准测试数据"""
return np.array([[-1, 2], [-2, -1], [-1, -2], [1, 3], [2, 1], [3, 2]])
def test_qpca_normal(self, sample_data):
- """测试QPCA正常功能"""
from pyqpanda_alg.QPCA import qpca
- # 执行QPCA
data_q = qpca(sample_data, 1)
assert data_q.shape == (6,1)
diff --git a/test/QSVM/Test_qsvm.py b/test/QSVM/Test_qsvm.py
index d1e3744..6b5aeb4 100644
--- a/test/QSVM/Test_qsvm.py
+++ b/test/QSVM/Test_qsvm.py
@@ -14,7 +14,6 @@
def _read_vqc_qsvm_data(path):
- """读取量子SVM数据"""
train_features = np.loadtxt(os.path.join(path, "dataset/qsvm_train_features.txt"))
test_features = np.loadtxt(os.path.join(path, "dataset/qsvm_test_features.txt"))
train_labels = np.loadtxt(os.path.join(path, "dataset/qsvm_train_labels.txt"))
@@ -24,7 +23,6 @@ def _read_vqc_qsvm_data(path):
def test_data_loading():
- """测试数据加载功能"""
train_features, test_features, train_labels, test_labels, samples = _read_vqc_qsvm_data(data_path)
assert train_features.shape[1] == 2
diff --git a/test/pytest.ini b/test/pytest.ini
index 2887f64..6b75de7 100644
--- a/test/pytest.ini
+++ b/test/pytest.ini
@@ -1,6 +1,5 @@
[pytest]
testpaths =
- QAlgBase
QAOA
QRAM
QPCA
From 4f8ae66b6caa19ded988bdda9efe3260efb3c1f8 Mon Sep 17 00:00:00 2001
From: OriginQuantumCloud
Date: Tue, 3 Feb 2026 10:11:33 +0800
Subject: [PATCH 08/10] Update README.md
---
README.md | 18 ++++++++++++++++++
1 file changed, 18 insertions(+)
diff --git a/README.md b/README.md
index a12fbe0..2e76294 100644
--- a/README.md
+++ b/README.md
@@ -126,6 +126,23 @@ pyqpanda_alg采用Python作为主要语言,对系统的环境要求如下:
------
+## 仓库分支说明
+本项目采用「稳定分支 + 开发分支」的协作模式,不同分支承担不同职责,方便你根据需求选择对应分支操作:
+
+### 📌 main(主分支)
+- **核心定位**:main 分支是项目的**稳定发布分支**,存放的是经过充分测试、可直接使用的开源量子算法代码。
+- **使用场景**:如果你想研究、学习量子算法的核心实现,或直接基于成熟代码进行二次开发,可直接拉取/使用 main 分支的内容。
+- **重要说明**:main 分支不接收任何直接提交或 Pull Request(PR),确保核心代码始终稳定、无已知问题。
+
+### 🛠️ develop(开发分支)
+- **核心定位**:develop 分支是项目的**协作开发分支**,用于整合社区贡献、迭代新功能、修复问题。
+- **提交场景**:如果你想参与项目贡献,包括但不限于:提交 Bug 修复代码、完善项目文档、补充量子算法的示例代码、提出/实现新的功能建议、优化现有算法的性能或可读性,请将所有 Pull Request(PR)**统一提交至 develop 分支**。
+- **协作说明**:我们会定期审核 develop 分支的贡献内容,经测试验证后合并至 main 分支,让优质贡献同步到稳定版本中。
+
+感谢你的理解与配合!
+
+------
+
## 开源许可
使用 [Apache License 2.0](https://gitee.com/OriginQ/alg/blob/master/LICENSE),对 公司、团队、个人 等 商用、非商用 都自由免费且非常友好,请放心使用和登记。
@@ -154,3 +171,4 @@ pyqpanda_alg采用Python作为主要语言,对系统的环境要求如下:
+
From 5d7af4cab02763626b22ffa98a033dc796bd3f49 Mon Sep 17 00:00:00 2001
From: OriginQuantumCloud
Date: Tue, 3 Feb 2026 10:13:29 +0800
Subject: [PATCH 09/10] Update README_EN.md
---
README_EN.md | 16 ++++++++++++++++
1 file changed, 16 insertions(+)
diff --git a/README_EN.md b/README_EN.md
index d74c953..1a645c8 100644
--- a/README_EN.md
+++ b/README_EN.md
@@ -90,6 +90,21 @@ pyqpanda_alg is primarily developed in Python with the following system requirem
------
+## Branch Explanation
+This project follows a "stable branch + development branch" collaboration model, with different branches serving distinct purposes to help you choose the right one for your needs.
+
+### 📌 main (Main Branch)
+- **Core Purpose**: The `main` branch is the project's **stable release branch**, containing fully tested, production-ready open-source quantum algorithm code.
+- **Usage Scenario**: If you want to study, learn the core implementation of quantum algorithms, or directly build upon mature code for secondary development, you can pull and use the content from the `main` branch.
+- **Important Note**: The `main` branch does **not** accept any direct commits or Pull Requests (PRs), ensuring the core code remains stable and bug-free.
+
+### 🛠️ develop (Development Branch)
+- **Core Purpose**: The `develop` branch is the project's **collaborative development branch**, used for integrating community contributions, iterating new features, and fixing issues.
+- **Submission Scenario**: If you wish to contribute to the project, including but not limited to:Submitting bug fixes、Improving project documentation (e.g., README, code comments)、Adding example code for quantum algorithms、Proposing or implementing new feature suggestions、Optimizing the performance or readability of existing algorithms,please submit all Pull Requests (PRs) **to the `develop` branch only**.
+- **Collaboration Note**: We regularly review contributions on the `develop` branch. After testing and validation, approved changes will be merged into the `main` branch, so high-quality contributions are synced to the stable release.
+
+------
+
## Open Source License
Licensed under [Apache License 2.0](https://gitee.com/OriginQ/alg/blob/master/LICENSE), free and friendly for commercial/non-commercial use by companies, teams, and individuals. Feel free to use and register.
@@ -116,3 +131,4 @@ Thanks to all contributors, testers, and community supporters. Special thanks to
+
From a0a867f9007a6e5aed02308a0082cb504f9eaf67 Mon Sep 17 00:00:00 2001
From: 1446170411 <1446170411@qq.com>
Date: Mon, 27 Jul 2026 20:55:44 +0800
Subject: [PATCH 10/10] =?UTF-8?q?=E3=80=90=E4=BB=A3=E7=A0=81=E8=B4=A1?=
=?UTF-8?q?=E7=8C=AE=E3=80=91=E6=96=B0=E5=A2=9EQPE=E9=87=8F=E5=AD=90?=
=?UTF-8?q?=E7=9B=B8=E4=BD=8D=E4=BC=B0=E8=AE=A1=E7=AE=97=E6=B3=95?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.../pyqpanda_alg/QPE/__init__.py | 16 ++
pyqpanda-algorithm/pyqpanda_alg/QPE/qpe.py | 260 ++++++++++++++++++
pyqpanda-algorithm/pyqpanda_alg/__init__.py | 109 ++++----
.../test/10-VQE/demo03-qpe-basic.ipynb | 91 ++++++
.../test/10-VQE/demo04-qpe-advanced.ipynb | 92 +++++++
test/QPE/Test_qpe.py | 91 ++++++
6 files changed, 605 insertions(+), 54 deletions(-)
create mode 100644 pyqpanda-algorithm/pyqpanda_alg/QPE/__init__.py
create mode 100644 pyqpanda-algorithm/pyqpanda_alg/QPE/qpe.py
create mode 100644 pyqpanda-algorithm/test/10-VQE/demo03-qpe-basic.ipynb
create mode 100644 pyqpanda-algorithm/test/10-VQE/demo04-qpe-advanced.ipynb
create mode 100644 test/QPE/Test_qpe.py
diff --git a/pyqpanda-algorithm/pyqpanda_alg/QPE/__init__.py b/pyqpanda-algorithm/pyqpanda_alg/QPE/__init__.py
new file mode 100644
index 0000000..b794f3c
--- /dev/null
+++ b/pyqpanda-algorithm/pyqpanda_alg/QPE/__init__.py
@@ -0,0 +1,16 @@
+'''
+Quantum Phase Estimation (QPE)
+
+QPE is a fundamental quantum algorithm that estimates the phase φ
+of an eigenvalue e^(2πiφ) of a unitary operator U. Given an
+eigenstate |ψ⟩ such that U|ψ⟩ = e^(2πiφ)|ψ⟩, QPE outputs an
+n-bit estimate of φ.
+
+This module provides:
+
+ - QPE : Standard Quantum Phase Estimation.
+'''
+
+from .qpe import QPE
+
+__all__ = ['QPE']
diff --git a/pyqpanda-algorithm/pyqpanda_alg/QPE/qpe.py b/pyqpanda-algorithm/pyqpanda_alg/QPE/qpe.py
new file mode 100644
index 0000000..69590a9
--- /dev/null
+++ b/pyqpanda-algorithm/pyqpanda_alg/QPE/qpe.py
@@ -0,0 +1,260 @@
+# 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.
+
+from pyqpanda3.core import CPUQVM, QCircuit, QProg, H, measure
+import numpy as np
+
+from ..plugin import *
+
+
+class QPE:
+ """
+ Quantum Phase Estimation (QPE).
+
+ Estimates the phase :math:`\\varphi` of the eigenvalue
+ :math:`e^{2\\pi i \\varphi}` of a unitary operator :math:`U`,
+ given an eigenstate :math:`|\\psi\\rangle` such that
+ :math:`U|\\psi\\rangle = e^{2\\pi i \\varphi}|\\psi\\rangle`.
+
+ Parameters
+ ----------
+ unitary : callable
+ Function ``f(target_qubits) -> QCircuit`` that returns the
+ unitary circuit :math:`U` acting on the target qubits.
+ The circuit should not include measurement gates.
+ n_count : int, optional
+ Number of counting (estimation) qubits. Larger values give
+ higher precision. Default 4.
+ n_target : int, optional
+ Number of target (eigenstate) qubits. Default 1.
+ state_prep : callable, optional
+ Function ``f(target_qubits) -> QCircuit`` that prepares the
+ eigenstate :math:`|\\psi\\rangle` on the target qubits.
+ If not given, the target qubits start in :math:`|0\\rangle`.
+
+ Attributes
+ ----------
+ n_count : int
+ Number of counting qubits.
+ n_target : int
+ Number of target qubits.
+ n_qubits : int
+ Total number of qubits (= n_count + n_target).
+
+ Methods
+ -------
+ build_circuit()
+ Build the full QPE circuit (no measurement).
+
+ run(shots=-1)
+ Run QPE and return the estimated phase :math:`\\varphi`
+ as a float in :math:`[0, 1)`.
+
+ run_dict(shots=-1)
+ Run QPE and return a probability dictionary over the
+ counting-qubit bitstrings.
+
+ References
+ ----------
+ .. [1] Kitaev A Y. Quantum measurements and the Abelian
+ Stabilizer Problem. 1995.
+ https://arxiv.org/abs/quant-ph/9511026
+ .. [2] Nielsen M A, Chuang I L. Quantum Computation and
+ Quantum Information. Cambridge University Press, 2010.
+
+ Examples
+ --------
+ Estimate the phase of the Pauli-Z operator:
+
+ >>> from pyqpanda3.core import Z
+ >>> from pyqpanda_alg.QPE import QPE
+ >>> def u_z(tq):
+ ... cir = QCircuit()
+ ... cir << Z(tq[0])
+ ... return cir
+ >>> qpe = QPE(unitary=u_z, n_count=4, n_target=1)
+ >>> phi = qpe.run()
+ >>> print(f"Phase estimate: {phi:.4f}")
+ """
+
+ # ── constructor ──────────────────────────────────────────
+
+ def __init__(self,
+ unitary,
+ n_count=4,
+ n_target=1,
+ state_prep=None):
+ if unitary is None:
+ raise ValueError("unitary must be provided")
+ self._unitary = unitary
+ self.n_count = n_count
+ self.n_target = n_target
+ self.n_qubits = n_count + n_target
+ self._state_prep = state_prep
+ self._circuit = None # cached circuit
+
+ # ── helper: controlled-U^(2^k) ───────────────────────────
+
+ def _controlled_u_power(self, q_count, q_targets, power):
+ """
+ Build controlled-U^(2^power) acting on target qubits,
+ controlled by a single counting qubit.
+
+ Parameters
+ ----------
+ q_count : Qubit
+ The control (counting) qubit.
+ q_targets : list[Qubit]
+ The target qubits.
+ power : int
+ The exponent k, so that the operation is U^(2^k).
+
+ Returns
+ -------
+ QCircuit
+ """
+ repetitions = 1 << power # 2^power
+ if repetitions == 0:
+ repetitions = 1
+
+ cir = QCircuit()
+ base_u = self._unitary(q_targets)
+ # Repeat U 2^power times, each controlled by q_count
+ for _ in range(repetitions):
+ cir << base_u.control([q_count])
+ return cir
+
+ # ── build full QPE circuit ───────────────────────────────
+
+ def build_circuit(self):
+ """
+ Build the full QPE circuit (no measurement).
+
+ The circuit consists of:
+ 1. Hadamard gates on all counting qubits.
+ 2. Controlled-U^(2^k) gates for k = 0, ..., n_count-1.
+ 3. Inverse QFT on the counting qubits.
+
+ Returns
+ -------
+ QCircuit
+ """
+ q_all = QProg(self.n_qubits).qubits()
+ q_count = q_all[:self.n_count] # counting register
+ q_target = q_all[self.n_count:] # target register
+
+ cir = QCircuit()
+
+ # Step 0: prepare eigenstate (if provided)
+ if self._state_prep is not None:
+ cir << self._state_prep(q_target)
+
+ # Step 1: Hadamard on all counting qubits
+ cir << hadamard_circuit(q_count)
+
+ # Step 2: controlled-U^(2^k) for each counting qubit
+ # q_count[0] controls U^1, q_count[1] controls U^2, ...
+ for k in range(self.n_count):
+ cir << self._controlled_u_power(
+ q_count[k], q_target, k
+ )
+
+ # Step 3: inverse QFT on counting qubits
+ cir << QFT(q_count).dagger()
+
+ self._circuit = cir
+ return cir
+
+ # ── run and return phase ─────────────────────────────────
+
+ def run(self, shots=-1):
+ """
+ Run QPE and return the estimated phase as a float.
+
+ Parameters
+ ----------
+ shots : int, optional
+ Number of measurement shots. ``-1`` (default) uses the
+ state-vector simulator. Positive values use sampling.
+
+ Returns
+ -------
+ float
+ Phase estimate :math:`\\varphi \\in [0, 1)`.
+ """
+ qvm = CPUQVM()
+ cir = self.build_circuit()
+ prog = QProg(self.n_qubits)
+ q_all = prog.qubits()
+ q_count = q_all[:self.n_count]
+
+ prog << cir
+
+ if shots == -1:
+ qvm.run(prog, shots=1)
+ prob_dict = qvm.result().get_prob_dict(q_count)
+ prob_dict = parse_quantum_result_dict(
+ prob_dict, q_count, select_max=1
+ )
+ best_bitstring = list(prob_dict.keys())[0]
+ elif shots > 0:
+ prog << measure_all(q_count, q_count)
+ qvm.run(prog, shots=shots)
+ counts = qvm.result().get_counts()
+ best_bitstring = max(counts, key=counts.get)
+ else:
+ raise ValueError(f"Invalid shots: {shots}")
+
+ # Convert bitstring to phase φ = integer / 2^n_count
+ phase_int = int(best_bitstring, 2)
+ phi = phase_int / (1 << self.n_count)
+ return phi
+
+ # ── run and return raw probability dict ──────────────────
+
+ def run_dict(self, shots=-1):
+ """
+ Run QPE and return the full probability distribution over
+ the counting-register bitstrings.
+
+ Parameters
+ ----------
+ shots : int, optional
+ ``-1`` for state-vector, positive for sampling.
+
+ Returns
+ -------
+ dict[str, float]
+ Mapping from n_count-bit binary strings to probabilities.
+ """
+ qvm = CPUQVM()
+ cir = self.build_circuit()
+ prog = QProg(self.n_qubits)
+ q_all = prog.qubits()
+ q_count = q_all[:self.n_count]
+
+ prog << cir
+
+ if shots == -1:
+ qvm.run(prog, shots=1)
+ prob_dict = qvm.result().get_prob_dict(q_count)
+ return parse_quantum_result_dict(
+ prob_dict, q_count, select_max=-1
+ )
+ elif shots > 0:
+ prog << measure_all(q_count, q_count)
+ qvm.run(prog, shots=shots)
+ counts = qvm.result().get_counts()
+ total = sum(counts.values())
+ return {k: v / total for k, v in counts.items()}
+ else:
+ raise ValueError(f"Invalid shots: {shots}")
diff --git a/pyqpanda-algorithm/pyqpanda_alg/__init__.py b/pyqpanda-algorithm/pyqpanda_alg/__init__.py
index 12d6808..412d7d5 100644
--- a/pyqpanda-algorithm/pyqpanda_alg/__init__.py
+++ b/pyqpanda-algorithm/pyqpanda_alg/__init__.py
@@ -1,54 +1,55 @@
-'''
-A Quantum Optimization Algorithm Set, based on pyqpanda.
-
-The **QMengJi** is a collection of fundamental quantum optimization algorithms and
-functions that are commonly used in developer's optimization problems.
-
-The QMengJi provides standardized set of tools and building blocks for writing quantum programs.
-
-Some key functions included in the QMengJi are:
-
-Quantum Approximate Optimization Algorithm : This is a quantum algorithm that can be used to search the lowest energy
-eigenstate of a Hamiltonian. It is considered to be one of the candidate algorithms for quantum advantage.
-Developer can construct object by QAOA(problem, arg1, arg2…) and directly call QAOA.run(args) to optimize their
-user-defined problem.
-
-Overall, the QMengJi provides a standardized set of tools for developers, allowing them to optimize functions with
-binary variables, such as combinatorial optimization problems, that may have many practical implications.
-Developers can use quantum algorithms directly to obtain results without knowing anything about quantum computing, or
-build their own suitable quantum circuits to obtain more customized results according to their requirements.It is an
-important resource for solving optimization problems and advancing research on quantum optimization algorithms.
-
-'''
-'''
-pyqpanda-algorithm Python\n
-Copyright (C) Origin Quantum 2017-2023\n
-Licensed Under Apache Licence 2.0
-'''
-
-import warnings
-warnings.filterwarnings("ignore", category=SyntaxWarning)
-
-from . import QAOA
-# from . import VQE
-# from . import HHL
-# from . import QAOA
-from . import QARM
-from . import QKmeans
-# from . import QLuoShu
-from . import QPCA
-# from . import QSolver
-from . import QSVM
-# from . import extensions
-# import warnings
-
-#QFinance
-from . import QUBO
-from . import QCmp
-from . import QAE
-from . import QSVD
-from . import QSVR
-from . import Grover
-from . import QmRMR
-from . import QSEncode
-
+'''
+A Quantum Optimization Algorithm Set, based on pyqpanda.
+
+The **QMengJi** is a collection of fundamental quantum optimization algorithms and
+functions that are commonly used in developer's optimization problems.
+
+The QMengJi provides standardized set of tools and building blocks for writing quantum programs.
+
+Some key functions included in the QMengJi are:
+
+Quantum Approximate Optimization Algorithm : This is a quantum algorithm that can be used to search the lowest energy
+eigenstate of a Hamiltonian. It is considered to be one of the candidate algorithms for quantum advantage.
+Developer can construct object by QAOA(problem, arg1, arg2…) and directly call QAOA.run(args) to optimize their
+user-defined problem.
+
+Overall, the QMengJi provides a standardized set of tools for developers, allowing them to optimize functions with
+binary variables, such as combinatorial optimization problems, that may have many practical implications.
+Developers can use quantum algorithms directly to obtain results without knowing anything about quantum computing, or
+build their own suitable quantum circuits to obtain more customized results according to their requirements.It is an
+important resource for solving optimization problems and advancing research on quantum optimization algorithms.
+
+'''
+'''
+pyqpanda-algorithm Python\n
+Copyright (C) Origin Quantum 2017-2023\n
+Licensed Under Apache Licence 2.0
+'''
+
+import warnings
+warnings.filterwarnings("ignore", category=SyntaxWarning)
+
+from . import QAOA
+# from . import VQE
+# from . import HHL
+# from . import QAOA
+from . import QARM
+from . import QKmeans
+# from . import QLuoShu
+from . import QPCA
+from . import QPE
+# from . import QSolver
+from . import QSVM
+# from . import extensions
+# import warnings
+
+#QFinance
+from . import QUBO
+from . import QCmp
+from . import QAE
+from . import QSVD
+from . import QSVR
+from . import Grover
+from . import QmRMR
+from . import QSEncode
+
diff --git a/pyqpanda-algorithm/test/10-VQE/demo03-qpe-basic.ipynb b/pyqpanda-algorithm/test/10-VQE/demo03-qpe-basic.ipynb
new file mode 100644
index 0000000..c13fb5d
--- /dev/null
+++ b/pyqpanda-algorithm/test/10-VQE/demo03-qpe-basic.ipynb
@@ -0,0 +1,91 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import sys\n",
+ "from pathlib import Path\n",
+ "sys.path.append(str(Path.cwd().parent.parent))\n",
+ "\n",
+ "import numpy as np\n",
+ "from pyqpanda3.core import QCircuit, Z, X\n",
+ "from pyqpanda_alg.QPE import QPE"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# QPE Demo 1: Basic Phase Estimation\n",
+ "\n",
+ "This notebook demonstrates QPE with the Pauli-Z operator.\n",
+ "\n",
+ "- Z|0⟩ = |0⟩ = e^(2πi·0)|0⟩ → φ = 0\n",
+ "- Z|1⟩ = -|1⟩ = e^(2πi·0.5)|1⟩ → φ = 0.5"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Define Z unitary\n",
+ "def u_z(tq):\n",
+ " cir = QCircuit()\n",
+ " cir << Z(tq[0])\n",
+ " return cir"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# QPE on |0⟩ (default) — should give φ = 0\n",
+ "qpe = QPE(unitary=u_z, n_count=4, n_target=1)\n",
+ "phi = qpe.run()\n",
+ "print(f\"Phase of Z on |0⟩: φ = {phi:.4f} (expect 0.0)\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# QPE on |1⟩ — should give φ = 0.5\n",
+ "def prep_one(tq):\n",
+ " cir = QCircuit()\n",
+ " cir << X(tq[0])\n",
+ " return cir\n",
+ "\n",
+ "qpe2 = QPE(unitary=u_z, n_count=4, n_target=1, state_prep=prep_one)\n",
+ "phi2 = qpe2.run()\n",
+ "print(f\"Phase of Z on |1⟩: φ = {phi2:.4f} (expect 0.5)\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Show full probability distribution (4 counting qubits → 16 bins)\n",
+ "dist = qpe2.run_dict()\n",
+ "for k, v in sorted(dist.items()):\n",
+ " bar = '█' * int(v * 50)\n",
+ " print(f\" |{k}⟩ {v:.4f} {bar}\")"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 4
+}
diff --git a/pyqpanda-algorithm/test/10-VQE/demo04-qpe-advanced.ipynb b/pyqpanda-algorithm/test/10-VQE/demo04-qpe-advanced.ipynb
new file mode 100644
index 0000000..98ddf41
--- /dev/null
+++ b/pyqpanda-algorithm/test/10-VQE/demo04-qpe-advanced.ipynb
@@ -0,0 +1,92 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import sys\n",
+ "from pathlib import Path\n",
+ "sys.path.append(str(Path.cwd().parent.parent))\n",
+ "\n",
+ "import numpy as np\n",
+ "from pyqpanda3.core import QCircuit, RZ, RX, RY\n",
+ "from pyqpanda_alg.QPE import QPE"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# QPE Demo 2: Custom Unitary & Precision\n",
+ "\n",
+ "This notebook shows QPE with rotation gates and tests\n",
+ "how precision improves with more counting qubits.\n",
+ "\n",
+ "- RZ(θ)|0⟩ = e^(-iθ/2)|0⟩ → φ = -θ/(4π) mod 1\n",
+ "- More counting qubits → higher precision"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# RZ(π/2): φ = -π/8 mod 1 = 0.875\n",
+ "def u_rz(tq):\n",
+ " cir = QCircuit()\n",
+ " cir << RZ(tq[0], np.pi / 2)\n",
+ " return cir\n",
+ "\n",
+ "qpe = QPE(unitary=u_rz, n_count=6, n_target=1)\n",
+ "phi = qpe.run()\n",
+ "print(f\"RZ(π/2): φ = {phi:.4f} (expect 0.875)\")\n",
+ "print(f\"Precision: 1/2^{qpe.n_count} = {1/(1< 0.01:\n",
+ " phi_val = int(k, 2) / (1 << 6)\n",
+ " print(f\" |{k}⟩ φ={phi_val:.4f} prob={v:.4f}\")"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 4
+}
diff --git a/test/QPE/Test_qpe.py b/test/QPE/Test_qpe.py
new file mode 100644
index 0000000..5a0e88b
--- /dev/null
+++ b/test/QPE/Test_qpe.py
@@ -0,0 +1,91 @@
+import pytest
+import sys
+from pathlib import Path
+
+_project_root = Path(__file__).resolve().parent.parent.parent
+_pkg_root = _project_root / "pyqpanda-algorithm"
+sys.path.insert(0, str(_project_root))
+sys.path.insert(0, str(_pkg_root))
+
+import numpy as np
+from pyqpanda3.core import QCircuit, Z, X, RZ
+from pyqpanda_alg.QPE import QPE
+
+
+class TestQPE:
+ """Tests for the Quantum Phase Estimation algorithm."""
+
+ def test_initialization(self):
+ def u_z(tq):
+ cir = QCircuit()
+ cir << Z(tq[0])
+ return cir
+ qpe = QPE(unitary=u_z, n_count=4, n_target=1)
+ assert qpe.n_count == 4
+ assert qpe.n_target == 1
+ assert qpe.n_qubits == 5
+
+ def test_build_circuit(self):
+ def u_z(tq):
+ cir = QCircuit()
+ cir << Z(tq[0])
+ return cir
+ qpe = QPE(unitary=u_z, n_count=3, n_target=1)
+ cir = qpe.build_circuit()
+ assert cir is not None
+
+ def test_phase_z_zero(self):
+ def u_z(tq):
+ cir = QCircuit()
+ cir << Z(tq[0])
+ return cir
+ qpe = QPE(unitary=u_z, n_count=4, n_target=1)
+ phi = qpe.run()
+ assert abs(phi - 0.0) < 0.1
+
+ def test_phase_z_one(self):
+ def u_z(tq):
+ cir = QCircuit()
+ cir << Z(tq[0])
+ return cir
+ def prep_one(tq):
+ from pyqpanda3.core import X
+ cir = QCircuit()
+ cir << X(tq[0])
+ return cir
+ qpe = QPE(unitary=u_z, n_count=4, n_target=1, state_prep=prep_one)
+ phi = qpe.run()
+ assert abs(phi - 0.5) < 0.1
+
+ def test_phase_rotation(self):
+ def u_rz(tq):
+ cir = QCircuit()
+ cir << RZ(tq[0], np.pi / 2)
+ return cir
+ qpe = QPE(unitary=u_rz, n_count=4, n_target=1)
+ phi = qpe.run()
+ assert abs(phi - 0.875) < 0.1
+
+ def test_run_dict(self):
+ def u_z(tq):
+ cir = QCircuit()
+ cir << Z(tq[0])
+ return cir
+ qpe = QPE(unitary=u_z, n_count=2, n_target=1)
+ d = qpe.run_dict()
+ assert isinstance(d, dict)
+ assert len(d) > 0
+ assert abs(sum(d.values()) - 1.0) < 1e-10
+
+ def test_shots_mode(self):
+ def u_z(tq):
+ cir = QCircuit()
+ cir << Z(tq[0])
+ return cir
+ qpe = QPE(unitary=u_z, n_count=4, n_target=1)
+ phi = qpe.run(shots=1000)
+ assert abs(phi - 0.0) < 0.1
+
+
+if __name__ == "__main__":
+ pytest.main([__file__, "-v", "-s"])