Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 15 additions & 12 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,41 +125,41 @@ alg社区基于本源量子提供的pyqpanda-algorithm开源量子算法仓库

如果你觉得已准备好`code review`,且预备提交PR请求,请确保:

- 代码遵循项目的代码风格,并且成功通过CI测试。为了方便起见,你可以先在本地执行,提前进行检查并发现报告问题。`
- 代码遵循项目的代码风格,并且成功通过CI/CD测试。为了方便起见,你可以先在本地执行,提前进行检查并发现报告问题。

- 如果函数或类在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. 审查人员将对您的代码进行审核,并可能要求更改,您可以在本地执行这些操作,然后再次执行上述过程。

### 测试

在pull request您的代码之前,请针对您修改的代码编写单元测试,并需要通过现有的测试。alg的测试基于pytest,[pytest使用文档])包含如何使用pytest编写单元测试。
在pull request您的代码之前,请针对您修改的代码编写单元测试,并需要通过现有的测试。

在编写单元测试之前,您需要先注意一些规范:

Expand Down Expand Up @@ -189,3 +189,6 @@ git merge master
<img src="my-folder/本源量子云小助手.jpg" alt="本源量子官方小助手" width="30%">
</p>




22 changes: 11 additions & 11 deletions CONTRIBUTING_EN.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,35 +107,35 @@ 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/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).

#### 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

Expand Down
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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),对 公司、团队、个人 等 商用、非商用 都自由免费且非常友好,请放心使用和登记。
Expand Down Expand Up @@ -154,3 +171,4 @@ pyqpanda_alg采用Python作为主要语言,对系统的环境要求如下:
<p align="center">
<img src="my-folder/本源量子云小助手.jpg" alt="本源量子官方小助手" width="30%">
</p>

16 changes: 16 additions & 0 deletions README_EN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -116,3 +131,4 @@ Thanks to all contributors, testers, and community supporters. Special thanks to
<p align="center">
<img src="my-folder/本源量子云小助手.jpg" alt="本源量子官方小助手" width="30%">
</p>

18 changes: 2 additions & 16 deletions Tutorials/source/GettingStarted.rst
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,14 @@ 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
---------------------
.. list-table::

* - software
- version
* - `Microsoft Visual C++ Redistributable x64`_
- 2019
* - Python
- >= 3.11 && <= 3.13

Expand All @@ -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``
- >= 3.11 && <= 3.13
2 changes: 1 addition & 1 deletion Tutorials/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
# -- Project information -----------------------------------------------------

project = 'pyqpanda-algorithm'
copyright = '2023, OriginQC'
copyright = '2026, OriginQC'
author = 'OriginQC'

# The short X.Y version
Expand Down
1 change: 0 additions & 1 deletion Tutorials/source/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
176 changes: 176 additions & 0 deletions pyqpanda-algorithm/example/VQE/example_vqe.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
# 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.

"""
VQE (Variational Quantum Eigensolver) Example

This example demonstrates how to use the VQE algorithm to find the ground state
energy of a simple Hamiltonian.
"""

from pyqpanda_alg import VQE
from pyqpanda3.hamiltonian import PauliOperator
import numpy as np


def example_simple_hamiltonian():
"""
Example 1: Simple single-qubit Hamiltonian

Hamiltonian: H = Z
Ground state: |1⟩ with energy -1
"""
print("=" * 60)
print("Example 1: Simple Single-Qubit Hamiltonian")
print("=" * 60)

# Define Hamiltonian: H = Z
hamiltonian = PauliOperator({"Z0": 1.0})

# Create VQE solver
vqe = VQE.VQE(hamiltonian, layers=2, optimizer='COBYLA')

# Run VQE
energy, params = vqe.run(optimizer_options={'maxiter': 100})

print(f"Hamiltonian: H = Z")
print(f"Theoretical ground state energy: -1.0")
print(f"VQE found energy: {energy:.6f}")
print(f"Error: {abs(energy - (-1.0)):.6f}")
print()


def example_two_qubit_hamiltonian():
"""
Example 2: Two-qubit Hamiltonian with interaction

Hamiltonian: H = 0.5*Z0 + 0.5*Z1 + 0.3*X0*X1
"""
print("=" * 60)
print("Example 2: Two-Qubit Hamiltonian with Interaction")
print("=" * 60)

# Define Hamiltonian
hamiltonian = PauliOperator({
"Z0": 0.5,
"Z1": 0.5,
"X0 X1": 0.3
})

# Create VQE solver with more layers for better accuracy
vqe = VQE.VQE(hamiltonian, layers=3, optimizer='COBYLA')

# Run VQE
energy, params = vqe.run(optimizer_options={'maxiter': 200})

print(f"Hamiltonian: H = 0.5*Z0 + 0.5*Z1 + 0.3*X0*X1")
print(f"VQE found energy: {energy:.6f}")
print(f"Number of optimization steps: {len(vqe.energy_history)}")
print()


def example_custom_ansatz():
"""
Example 3: Using custom ansatz circuit
"""
print("=" * 60)
print("Example 3: Custom Ansatz Circuit")
print("=" * 60)

from pyqpanda3.core import QCircuit, RY, RZ, CNOT

# Define custom ansatz
def custom_ansatz(qubit_list, params):
circuit = QCircuit()
n_qubits = len(qubit_list)

# First layer: RY rotations
for i, q in enumerate(qubit_list):
circuit << RY(q, params[i])

# Entangling layer
for i in range(n_qubits - 1):
circuit << CNOT(qubit_list[i], qubit_list[i + 1])

# Second layer: RZ rotations
for i, q in enumerate(qubit_list):
circuit << RZ(q, params[n_qubits + i])

return circuit

# Define Hamiltonian
hamiltonian = PauliOperator({
"Z0": 1.0,
"Z1": 1.0,
"X0 X1": 0.5
})

# Create VQE with custom ansatz
initial_params = np.random.uniform(-np.pi, np.pi, 4) # 2 qubits * 2 params
vqe = VQE.VQE(
hamiltonian,
ansatz=custom_ansatz,
initial_params=initial_params,
optimizer='COBYLA'
)

# Run VQE
energy, params = vqe.run(optimizer_options={'maxiter': 150})

print(f"Custom ansatz with RY-CNOT-RZ structure")
print(f"VQE found energy: {energy:.6f}")
print()


def example_energy_convergence():
"""
Example 4: Track energy convergence during optimization
"""
print("=" * 60)
print("Example 4: Energy Convergence Tracking")
print("=" * 60)

# Define Hamiltonian
hamiltonian = PauliOperator({
"Z0": 1.0,
"X0": 0.5
})

# Create VQE solver
vqe = VQE.VQE(hamiltonian, layers=2, optimizer='COBYLA')

# Run VQE
energy, params = vqe.run(optimizer_options={'maxiter': 100})

print(f"Hamiltonian: H = Z0 + 0.5*X0")
print(f"Final energy: {energy:.6f}")
print(f"Optimization steps: {len(vqe.energy_history)}")
print(f"Initial energy: {vqe.energy_history[0]:.6f}")
print(f"Final energy: {vqe.energy_history[-1]:.6f}")
print(f"Energy reduction: {vqe.energy_history[0] - vqe.energy_history[-1]:.6f}")
print()


if __name__ == "__main__":
print("\n" + "=" * 60)
print("VQE (Variational Quantum Eigensolver) Examples")
print("=" * 60 + "\n")

# Run all examples
example_simple_hamiltonian()
example_two_qubit_hamiltonian()
example_custom_ansatz()
example_energy_convergence()

print("=" * 60)
print("All examples completed successfully!")
print("=" * 60)
Loading