Skip to main content

HyQ: hybrid quantum algorithms toolkit with backend-agnostic circuits and solvers

Project description

HyQ:混合量子算法工具包

HyQ 是一个轻量级 Python 工具包,用于构建与后端无关的量子线路并运行混合量子算法,例如 VQE、VarQITE、SA‑QITE、SS‑QITE 和 RITE。它提供:

  • 用于构建线路的统一 QuantumCircuit 抽象。
  • 可插拔的后端接口,支持两种执行模式:
    • 采样模式:返回测量计数,类似于硬件或基于采样的模拟器。
    • 状态向量模式:返回精确状态向量,适用于模拟器和可微分算法。
  • 针对 Qiskit、PennyLane 和 TensorCircuit 的后端实现。
  • 统一 Hamiltonian 格式表示 qubit Hamiltonian
  • 可选化学工具,使用 OpenFermion 和 Psi4 生成分子哈密顿量。
  • VQE、VarQITE、QITE 系列求解器,以及 classical reference、Trotter、QPE、QSE、VQD、classical shadow 等算法工具。

推荐的仓库结构

.
├── algorithms/
│   ├── __init__.py
│   ├── classical_eigensolvers.py
│   ├── phase_estimation.py
│   ├── qse.py
│   ├── quantum_chemistry.py
│   ├── shadow.py
│   ├── trotter.py
│   └── vqd.py
├── ansatz/
│   ├── __init__.py
│   ├── base.py
│   ├── HEA.py
│   ├── ryrz.py
│   ├── compact.py
│   └── adapt.py
├── backends/
│   ├── __init__.py
│   ├── base.py
│   ├── core.py
│   ├── _matrix_simulator.py
│   ├── Qiskit.py
│   ├── Pennylane.py
│   ├── Tensorcircuit.py
│   ├── Cirq.py
│   ├── Qulacs.py
│   └── Qutip.py
├── chemistry/
│   ├── __init__.py
│   ├── hamiltonian.py
│   ├── molecule.py
│   └── psi4_driver.py
├── solvers/
│   ├── __init__.py
│   ├── base.py
│   ├── vqe.py
│   ├── var_qite.py
│   ├── sa_qite.py
│   ├── ss_qite.py
│   └── rite.py
├── examples/
├── tutorials/
├── environment.yml
├── requirements.txt
└── README_chinese.md

安装

从 PyPI 安装

pip install hyq
pip install "hyq[qiskit,tensorcircuit]"   # 可选后端
pip install "hyq[all]"                    # 全部可选依赖

安装后与导入名一致:import hyqfrom hyq.backends import get_backend

从源码安装(Conda)

团队统一使用 Conda 管理环境,保证 clone 后各机器依赖一致。环境定义见 environment.yml(Python 3.11、Psi4);Python 包列表与 requirements.txt 同步。

首次安装(服务器 / 本机)

需已安装 Miniconda 或 Anaconda。

git clone <repo-url>
cd hyq-alg-lib

conda env create -f environment.yml
conda activate hyq_alg_lib_env

验证:

python -c "import numpy, torch, qiskit, pennylane, tensorcircuit; print('ok')"
python -c "import psi4; print('psi4', psi4.__version__)"   # 化学模块需要

更新环境(拉取新代码后)

conda activate hyq_alg_lib_env
conda env update -f environment.yml --prune

服务器:conda + pip 分步装(有日志、易排查)

适合 conda env create 长时间无输出时:先用 conda 建 Python 和 Psi4,再用 pip 装其余依赖。

conda create -n hyq_alg_lib_env -c conda-forge python=3.11 psi4=1.10 pip -y
conda activate hyq_alg_lib_env
cd hyq-alg-lib

export TMPDIR=/tmp
pip install -U pip
pip install -v --progress-bar on torch==2.9.1    # 最慢,单独装可看进度
pip install -v --progress-bar on -r requirements.txt 2>&1 | tee pip-install.log

选择默认后端

至少安装一个后端后,通过环境变量指定默认后端(以下为 Linux / macOS):

export HYQ_BACKEND=tensorcircuit   # 可微分状态向量算法(推荐 VQE / VarQITE)
# export HYQ_BACKEND=qiskit        # QASM、采样、线路转换
# export HYQ_BACKEND=pennylane     # 可微分原型

Windows PowerShell:$env:HYQ_BACKEND="tensorcircuit"

维护者:在服务器上固化环境

在目标 Linux 机器上确认教程与测试通过后,可将 environment.ymlpip: 段的版本与线上一致;必要时用精简导出辅助核对:

conda env export --from-history | head -50

Hamiltonian 标准格式

最新版本统一推荐使用如下格式:

hamiltonian = [
    (-1.0, "ZI"),
    (-1.0, "IZ"),
    (0.5, "XX"),
]

其中字符串第 i 个字符对应第 i 个 qubit,支持 I/X/Y/Z

后端能力概览

后端 采样 run_sampling 状态向量 get_statevector PyTorch 自动微分 推荐用途
Qiskit 支持 支持 不支持 采样、QASM、绘图、编译
PennyLane 支持 支持 支持 可微分模拟和算法原型
TensorCircuit 支持 支持 支持 VQE / VarQITE 等梯度算法
Cirq 支持 支持 不支持 备用门级模拟后端
Qulacs 支持 支持 不支持 快速状态向量模拟
QuTiP 支持 支持 不支持 QuTiP 生态入口和教学

可用后端可通过:

from backends import available_backends, set_backend, get_backend

print(available_backends())
backend = set_backend("tensorcircuit")

最小线路示例

import torch
from backends.core import QuantumCircuit
from backends.Tensorcircuit import TensorCircuitBackend

qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)

backend = TensorCircuitBackend()
state = backend.get_statevector(qc)
print(state)

counts = backend.run_sampling(qc, shots=1024, measure_qubits=[0, 1])
print(counts)

使用求解器

import torch
from backends.core import QuantumCircuit
from backends.Tensorcircuit import TensorCircuitBackend
from solvers.vqe import VQESolver

backend = TensorCircuitBackend()
solver = VQESolver(backend)

def ansatz(params):
    qc = QuantumCircuit(2)
    qc.ry(0, params[0])
    qc.cx(0, 1)
    return qc

hamiltonian = [(-1.0, "ZI"), (-1.0, "IZ"), (0.5, "XX")]
init_params = torch.tensor([0.1], dtype=torch.float64)
energy, params, history = solver.solve(ansatz, init_params, hamiltonian, steps=100, lr=0.1)

生成分子哈密顿量

from chemistry.hamiltonian import Hamiltonian

symbols = ["H", "H"]
geometry = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.74]]

ham = Hamiltonian(symbols, geometry, charge=0, multiplicity=1, basis="sto-3g")
terms, n_qubits, n_electrons = ham.get_processed_hamiltonian(
    n_active_electrons=2,
    n_active_orbitals=2,
    mapping="jw",
    reverse_endian=False,
)

VQE 示例

import torch
from backends.core import QuantumCircuit
from backends.Tensorcircuit import TensorCircuitBackend
from solvers.vqe import VQESolver

backend = TensorCircuitBackend()
solver = VQESolver(backend)

def ansatz(params):
    qc = QuantumCircuit(2)
    qc.ry(0, params[0])
    qc.cx(0, 1)
    return qc

hamiltonian = [
    (-1.0, "ZI"),
    (-1.0, "IZ"),
    (0.5, "XX"),
]

init_params = torch.tensor([0.1], dtype=torch.float64)
energy, params, history = solver.solve(
    ansatz,
    init_params,
    hamiltonian,
    steps=100,
    lr=0.1,
)

print(energy)
print(params)

Quantum Phase Estimation

import numpy as np
from backends.core import QuantumCircuit
from algorithms import build_qpe_circuit, phases_from_counts

phi = 0.375
unitary = QuantumCircuit(1)
unitary.p(0, 2 * np.pi * phi)

qpe = build_qpe_circuit(unitary, n_ancilla=3)
print(qpe)

# 后端采样后:
# counts = backend.run_sampling(qpe, shots=2048, measure_qubits=[0, 1, 2])
# result = phases_from_counts(counts, n_ancilla=3)

QSE:Quantum Subspace Expansion

import numpy as np
from algorithms import quantum_subspace_expansion

reference_state = np.array([1.0, 0.0], dtype=np.complex128)
hamiltonian = [(1.0, "Z"), (0.2, "X")]
excitation_terms = [[(1.0, "X")]]

result = quantum_subspace_expansion(
    reference_state=reference_state,
    hamiltonian=hamiltonian,
    excitation_terms=excitation_terms,
    n_qubits=1,
)

print(result.energies)
print(result.kept_subspace_dimension)

VQD:Variational Quantum Deflation 辅助工具

import numpy as np
from algorithms import deflated_eigensystem, vqd_objective_from_matrix

H = np.diag([0.0, 1.0, 2.0]).astype(np.complex128)
ground_state = np.array([1.0, 0.0, 0.0], dtype=np.complex128)

vals, vecs = deflated_eigensystem(H, previous_states=[ground_state], betas=[5.0])
print(vals)

breakdown = vqd_objective_from_matrix(
    H,
    candidate_state=vecs[:, 0],
    previous_states=[ground_state],
    betas=[5.0],
)
print(breakdown)

Classical Shadow

from algorithms import ClassicalShadow

shadow = ClassicalShadow(
    backend=backend,
    circuit=qc,
    seed=123,
)

shadow.collect(5000)
print(shadow.estimate_observable("XX"))

hamiltonian = [(1.0, "II"), (0.5, "XX"), (-0.3, "ZZ")]
print(shadow.estimate_hamiltonian(hamiltonian))

量子化学辅助函数

import numpy as np
from algorithms import (
    fci_reference_energy,
    chemical_accuracy_error,
    mp2_energy_from_integrals,
    state_fidelity,
    particle_number_expectation,
    spin_z_expectation,
)

hamiltonian = [(1.0, "Z"), (0.2, "X")]
ref = fci_reference_energy(hamiltonian, n_qubits=1)
print(ref)
print(chemical_accuracy_error(estimated_energy=-1.018, reference_energy=ref))

state = np.array([0.0, 0.0, 0.0, 2.0], dtype=np.complex128)
print(particle_number_expectation(state, n_qubits=2))
print(spin_z_expectation(state, n_qubits=2))

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

hyq-26.1.0.tar.gz (77.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

hyq-26.1.0-py3-none-any.whl (95.7 kB view details)

Uploaded Python 3

File details

Details for the file hyq-26.1.0.tar.gz.

File metadata

  • Download URL: hyq-26.1.0.tar.gz
  • Upload date:
  • Size: 77.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.15

File hashes

Hashes for hyq-26.1.0.tar.gz
Algorithm Hash digest
SHA256 39d4f0d641a7baf0783b1e26eac7a8d0d85f271b340ce9b4d3f084cc18c14774
MD5 e46dfd3d1ffd5aafca7e0e8c601d6727
BLAKE2b-256 c2a0012d292ba72e0121d44fb65f7d0e52cf5dafb0809f6eea1cda8057b297fc

See more details on using hashes here.

File details

Details for the file hyq-26.1.0-py3-none-any.whl.

File metadata

  • Download URL: hyq-26.1.0-py3-none-any.whl
  • Upload date:
  • Size: 95.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.15

File hashes

Hashes for hyq-26.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 a968c866195b145685fb356a4608bc953cbac4004c4d81d63ecf30aaf20ff564
MD5 7c67018b87182f9d8878c5449b87c56a
BLAKE2b-256 a26a4d9a2683b0be8f2cbb2aff650f29173a22cd296c468780db30613b70bee6

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page