跳转至

L7 应用层标准化模板

模板类型: 应用层专项 适用范围: L7 算法应用层 版本: 1.0 创建日期: 2026-01-13


📋 模板说明

本文档提供**针对L7应用层的专门模板**,强调项目驱动、算法实现和结果可视化。

适用场景

  • ✅ 算法项目文档
  • ✅ 应用案例研究
  • ✅ 基准测试报告
  • ✅ 教程和学习指南

应用层特点

项目类型 核心内容 关键要素 典型文档
算法实现 QAOA/VQE/QSVM等 数学原理+代码实现 算法项目文档
应用案例 金融/化学/优化 问题建模+结果分析 案例研究文档
教程指南 入门到进阶 Step-by-step 教程文档
基准测试 性能对比 实验设计+可视化 性能报告

📄 标准文档模板

---
title: "[文档标题]"
layer: "L7"
project_type: "Algorithm/Application/Tutorial/Benchmark"
algorithm: "QAOA/VQE/QSVM/QML/其他"
version: "1.0"
date: "YYYY-MM-DD"
author: "[作者名称或团队]"
tags: ["算法", "应用", "基准测试", "教程"]
status: "活跃/草稿/已废弃"
last_updated: "YYYY-MM-DD"
references: ["[ID_Year_Author]", "[ID_Year_Author]"]
related_docs: ["[相对路径/文档1.md]", "[相对路径/文档2.md]"]
code_repos: ["[GitHub链接]"]
requirements: ["numpy>=1.20", "qiskit>=0.40", "其他依赖"]
---

# [文档标题]

**文档版本**: {{version}}
**创建日期**: {{date}}
**维护者**: {{author}}
**所属层级**: L7 算法应用层
**项目类型**: {{project_type}}
**算法类型**: {{algorithm}}

---

## 项目概述

### 项目简介

本项目实现[算法名称],用于[应用场景],解决[具体问题]。

**核心功能**:
- [功能1]
- [功能2]
- [功能3]

**技术栈**:
- **量子框架**: [Qiskit/Cirq/Qibo/PennyLane等]
- **优化器**: [COBYLA/SPSA/SLSQP等]
- **数值计算**: [NumPy/SciPy/Scikit-learn等]
- **可视化**: [Matplotlib/Plotly等]

---

### 项目文件结构
project_name/ ├── README.md # 项目说明文档 ├── requirements.txt # 依赖列表 ├── setup.py # 安装脚本 │ ├── src/ # 源代码目录 │ ├── init.py │ ├── algorithm.py # 算法核心实现 │ ├── problem.py # 问题定义 │ ├── optimizer.py # 优化器配置 │ └── utils.py # 工具函数 │ ├── scripts/ # 脚本目录 │ ├── run_baseline.py # 运行基准测试 │ ├── run_comparison.py # 运行对比实验 │ └── run_visualization.py # 生成可视化 │ ├── notebooks/ # Jupyter笔记本 │ ├── 01_introduction.ipynb # 入门教程 │ ├── 02_algorithm_deepdive.ipynb # 算法详解 │ └── 03_advanced_usage.ipynb # 高级用法 │ ├── tests/ # 测试代码 │ ├── test_algorithm.py │ └── test_optimizer.py │ ├── results/ # 结果输出 │ ├── data/ # 原始数据 │ ├── figures/ # 图表 │ └── reports/ # 分析报告 │ └── docs/ # 文档 ├── architecture.md # 架构说明 ├── api.md # API文档 └── examples.md # 使用示例
**文件说明**:

| 文件/目录 | 说明 | 必需 |
|-----------|------|------|
| README.md | 项目说明 | ✓ |
| requirements.txt | 依赖列表 | ✓ |
| src/algorithm.py | 算法核心实现 | ✓ |
| scripts/run_baseline.py | 基准测试脚本 | ✓ |
| notebooks/ | 教程笔记本 | 推荐 |

---

## 算法原理

### 1. 问题定义

**[问题名称]**

**问题描述**:
[详细描述要解决的问题]

**数学表述**:

给定[问题输入],找到[问题输出],使得[目标函数]达到[最优化目标]。

**形式化定义**:

```latex
$$
\text{目标函数: } \min_{x} f(x) = \sum_{i=1}^{n} c_i x_i

\text{约束条件: }
\begin{cases}
\sum_{i=1}^{n} a_{ji} x_i \leq b_j, & \forall j \in \{1, \ldots, m\} \\
x_i \in \{0, 1\}, & \forall i \in \{1, \ldots, n\}
\end{cases}
$$

问题复杂度: - 计算复杂度: [NP-hard/P/其他] - 问题规模: [小规模/中等规模/大规模] - 经典求解难度: [困难/中等/容易]


2. 算法原理

[算法名称]

核心思想: [描述算法的核心思想和工作原理]

算法流程:

输入: [输入参数]
输出: [输出结果]

步骤1: [初始化]
  └─ 构建初始量子态 |ψ₀⟩

步骤2: [参数化电路]
  └─ 应用参数化幺正变换 U(θ)

步骤3: [测量]
  └─ 测量可观测量 O

步骤4: [经典优化]
  └─ 根据测量结果更新参数 θ

步骤5: [收敛检查]
  ├─ 如果收敛: 返回结果
  └─ 如果未收敛: 返回步骤2

量子电路:

graph LR
    A[|0⟩ⁿ] --> B[初始化]
    B --> C[参数化层1]
    C --> D[参数化层2]
    D --> E[...]
    E --> F[测量]
    F --> G[经典优化器]

    style A fill:#feca57
    style C fill:#48dbfb
    style D fill:#48dbfb
    style F fill:#ff6b6b

数学公式:

$$
|\psi(\boldsymbol{\theta})\rangle = U(\boldsymbol{\theta})|0\rangle^{\otimes n}

$$

$$
U(\boldsymbol{\theta}) = \prod_{l=1}^{p} \left[ e^{-i\beta_l H_M} e^{-i\gamma_l H_P} \right]

$$

$$
\langle H_P \rangle_{\boldsymbol{\theta}} = \langle\psi(\boldsymbol{\theta})| H_P |\psi(\boldsymbol{\theta})\rangle
$$

其中: - \(H_P\): 问题哈密顿量 - \(H_M\): 混合哈密顿量 - \(\boldsymbol{\theta} = (\gamma_1, \ldots, \gamma_p, \beta_1, \ldots, \beta_p)\): 可优化参数 - \(p\): 层数 (depth)


3. 量子电路设计

电路结构:

def create_circuit(n_qubits, depth, params):
    """
    创建[算法名称]量子电路

    Args:
        n_qubits (int): 量子比特数
        depth (int): 电路深度(层数)
        params (ndarray): 参数数组 (2*p,)

    Returns:
        QuantumCircuit: 量子电路
    """
    from qiskit import QuantumCircuit
    import numpy as np

    qc = QuantumCircuit(n_qubits)

    # 初始化: 叠加态
    qc.h(range(n_qubits))

    # 参数化层
    p = depth
    for layer in range(p):
        gamma = params[2*layer]
        beta = params[2*layer + 1]

        # 问题哈密顿量演化
        qc.barrier()
        for i in range(n_qubits):
            qc.rz(2*gamma, i)

        # 混合哈密顿量演化
        qc.barrier()
        for i in range(n_qubits):
            qc.rx(2*beta, i)

    # 测量
    qc.measure_all()

    return qc

电路图示例:

对于 [n_qubits=4, depth=2] 的电路:

     ┌───┐                    ┌─────┐┌─────┐┌─────┐┌─────┐┌───┐┌─┐
q_0: ┤ H ├──■─────────────────┤ Rz(2γ_1) ├┤ Rx(2β_1) ├┤ Rz(2γ_2) ├┤ Rx(2β_2) ├┤M├
     └───┘┌─┴─┐               └─────────┘└──────────┘└─────────┘└──────────┘└╥┘
q_1: ─────┤ X ├──■─────────────┤ Rz(2γ_1) ├┤ Rx(2β_1) ├┤ Rz(2γ_2) ├┤ Rx(2β_2) ├┤M├
          └───┘┌─┴─┐          └─────────┘└──────────┘└─────────┘└──────────┘└╥┘
q_2: ─────────┤ X ├──■─────────┤ Rz(2γ_1) ├┤ Rx(2β_1) ├┤ Rz(2γ_2) ├┤ Rx(2β_2) ├┤M├
               └───┘           └─────────┘└──────────┘└─────────┘└──────────┘└╥┘
c: 4/═════════════════════════════════════════════════════════════════════════╩═

核心实现

1. 算法核心类

完整实现:

"""
[算法名称]核心实现

Author: [作者]
Date: [日期]
"""

import numpy as np
from typing import List, Tuple, Dict, Optional, Callable
from dataclasses import dataclass

# 导入量子框架
from qiskit import QuantumCircuit
from qiskit.algorithms import MinimumEigensolver
from qiskit.algorithms.optimizers import Optimizer
from qiskit.primitives import Sampler, Estimator
from qiskit.quantum_info import SparsePauliOp


@dataclass
class AlgorithmConfig:
    """
    算法配置类

    Attributes:
        n_qubits (int): 量子比特数
        depth (int): 电路深度(层数)
        shots (int): 测量次数
        optimizer (Optimizer): 经典优化器
        backend (Backend): 量子后端
    """
    n_qubits: int
    depth: int = 1
    shots: int = 1024
    optimizer: Optional[Optimizer] = None
    backend: Optional[str] = None

    def __post_init__(self):
        """配置验证"""
        if self.n_qubits <= 0:
            raise ValueError("量子比特数必须为正整数")
        if self.depth <= 0:
            raise ValueError("深度必须为正整数")


class QuantumAlgorithm:
    """
    [算法名称]实现类

    该类实现[算法名称]的核心功能,包括电路构建、参数优化和结果分析。

    Attributes:
        config (AlgorithmConfig): 算法配置
        problem_hamiltonian (SparsePauliOp): 问题哈密顿量
        mixer_hamiltonian (SparsePauliOp): 混合哈密顿量
        optimal_params (np.ndarray): 最优参数
        optimal_value (float): 最优目标函数值

    Example:
        >>> config = AlgorithmConfig(n_qubits=4, depth=2)
        >>> algorithm = QuantumAlgorithm(config)
        >>> result = algorithm.run(problem_matrix)
        >>> print(f"最优值: {result['optimal_value']}")
    """

    def __init__(
        self,
        config: AlgorithmConfig,
        problem_hamiltonian: Optional[SparsePauliOp] = None
    ):
        """
        初始化算法

        Args:
            config: 算法配置对象
            problem_hamiltonian: 问题哈密顿量(可选)
        """
        self.config = config
        self.problem_hamiltonian = problem_hamiltonian
        self.mixer_hamiltonian = self._create_mixer_hamiltonian()
        self.optimal_params = None
        self.optimal_value = None

    def _create_mixer_hamiltonian(self) -> SparsePauliOp:
        """
        创建混合哈密顿量

        Returns:
            SparsePauliOp: 混合哈密顿量 (通常为 X 门之和)
        """
        from qiskit.quantum_info import SparsePauliOp

        n = self.config.n_qubits
        # H_M = sum(X_i) for all qubits
        pauli_list = [('X' * n, [0] * n)]  # 简化示例
        return SparsePauliOp.from_list(pauli_list)

    def create_circuit(self, params: np.ndarray) -> QuantumCircuit:
        """
        创建参数化量子电路

        Args:
            params: 参数数组,长度为 2 * depth

        Returns:
            QuantumCircuit: 量子电路

        Raises:
            ValueError: 参数维度不匹配时
        """
        if len(params) != 2 * self.config.depth:
            raise ValueError(
                f"参数长度应为 {2 * self.config.depth}, "
                f"但得到 {len(params)}"
            )

        qc = QuantumCircuit(self.config.n_qubits)

        # 初始化: 叠加态
        qc.h(range(self.config.n_qubits))

        # 参数化层
        for layer in range(self.config.depth):
            gamma = params[2 * layer]
            beta = params[2 * layer + 1]

            # 问题哈密顿量演化
            self._apply_problem_hamiltonian(qc, gamma)

            # 混合哈密顿量演化
            self._apply_mixer_hamiltonian(qc, beta)

        return qc

    def _apply_problem_hamiltonian(
        self,
        qc: QuantumCircuit,
        gamma: float
    ):
        """
        应用问题哈密顿量演化

        Args:
            qc: 量子电路
            gamma: 旋转角度
        """
        # 根据 problem_hamiltonian 应用相应的门
        # 这里是简化示例,实际应根据具体问题哈密顿量实现
        if self.problem_hamiltonian is not None:
            # 应用问题特定的演化
            pass

    def _apply_mixer_hamiltonian(
        self,
        qc: QuantumCircuit,
        beta: float
    ):
        """
        应用混合哈密顿量演化

        Args:
            qc: 量子电路
            beta: 旋转角度
        """
        # 应用 RX 门
        for qubit in range(self.config.n_qubits):
            qc.rx(2 * beta, qubit)

    def objective_function(
        self,
        params: np.ndarray,
        estimator: Optional[Estimator] = None
    ) -> float:
        """
        目标函数

        Args:
            params: 参数数组
            estimator: 量子估计器(可选)

        Returns:
            float: 目标函数值
        """
        # 创建电路
        circuit = self.create_circuit(params)

        # 计算期望值
        if estimator is not None and self.problem_hamiltonian is not None:
            # 使用量子估计器
            job = estimator.run(circuit, self.problem_hamiltonian)
            result = job.result()
            value = result.values[0]
        else:
            # 使用模拟器(简化)
            value = self._simulate_expectation(circuit)

        return value

    def _simulate_expectation(self, circuit: QuantumCircuit) -> float:
        """
        模拟计算期望值(简化实现)

        Args:
            circuit: 量子电路

        Returns:
            float: 期望值
        """
        # 这里是简化实现
        # 实际应该使用完整的量子模拟
        from qiskit_aer import AerSimulator
        from qiskit import transpile

        simulator = AerSimulator()
        compiled = transpile(circuit, simulator)
        result = simulator.run(compiled, shots=self.config.shots).result()
        counts = result.get_counts()

        # 计算期望值(简化)
        expectation = 0.0
        for bitstring, count in counts.items():
            # 根据问题计算能量
            energy = self._compute_energy(bitstring)
            expectation += energy * count / self.config.shots

        return expectation

    def _compute_energy(self, bitstring: str) -> float:
        """
        计算给定比特串的能量

        Args:
            bitstring: 测量结果比特串

        Returns:
            float: 能量值
        """
        # 根据具体问题计算能量
        # 这里是简化示例
        energy = 0.0
        for i, bit in enumerate(bitstring):
            if bit == '1':
                energy -= 1.0  # 简化示例
        return energy

    def run(
        self,
        problem_hamiltonian: Optional[SparsePauliOp] = None,
        initial_point: Optional[np.ndarray] = None
    ) -> Dict:
        """
        运行算法

        Args:
            problem_hamiltonian: 问题哈希顿量
            initial_point: 初始参数点

        Returns:
            Dict: 包含优化结果的字典
            {
                'optimal_value': float,
                'optimal_params': np.ndarray,
                'optimal_bitstring': str,
                'optimization_history': List[float],
                'converged': bool
            }
        """
        if problem_hamiltonian is not None:
            self.problem_hamiltonian = problem_hamiltonian

        # 初始化参数
        if initial_point is None:
            initial_point = np.random.uniform(
                low=0,
                high=2*np.pi,
                size=2 * self.config.depth
            )

        # 设置估计器
        estimator = Estimator()

        # 优化历史
        history = {'objective': [], 'params': []}

        def callback(params):
            """优化回调函数"""
            value = self.objective_function(params, estimator)
            history['objective'].append(value)
            history['params'].append(params.copy())

        # 运行优化
        if self.config.optimizer is not None:
            result = self.config.optimizer.minimize(
                fun=self.objective_function,
                x0=initial_point,
                args=(estimator,)
            )

            self.optimal_params = result.x
            self.optimal_value = result.fun
            converged = result.success
        else:
            # 简化优化(示例)
            from scipy.optimize import minimize

            result = minimize(
                fun=self.objective_function,
                x0=initial_point,
                args=(estimator,),
                method='COBYLA',
                callback=callback
            )

            self.optimal_params = result.x
            self.optimal_value = result.fun
            converged = result.success

        # 获取最优比特串
        optimal_circuit = self.create_circuit(self.optimal_params)
        optimal_bitstring = self._measure_optimal_bitstring(optimal_circuit)

        return {
            'optimal_value': self.optimal_value,
            'optimal_params': self.optimal_params,
            'optimal_bitstring': optimal_bitstring,
            'optimization_history': history['objective'],
            'converged': converged
        }

    def _measure_optimal_bitstring(
        self,
        circuit: QuantumCircuit
    ) -> str:
        """
        测量最优比特串

        Args:
            circuit: 量子电路

        Returns:
            str: 最优比特串
        """
        # 添加测量
        measured_circuit = circuit.copy()
        measured_circuit.measure_all()

        # 运行电路
        from qiskit_aer import AerSimulator
        simulator = AerSimulator()
        result = simulator.run(
            measured_circuit,
            shots=self.config.shots
        ).result()
        counts = result.get_counts()

        # 返回最高频次的比特串
        optimal_bitstring = max(counts, key=counts.get)
        return optimal_bitstring

2. 基准测试脚本

完整脚本:

"""
基准测试脚本

Author: [作者]
Date: [日期]
"""

import numpy as np
import time
import json
from pathlib import Path
from typing import Dict, List

import matplotlib.pyplot as plt
import seaborn as sns

# 导入算法实现
from src.algorithm import QuantumAlgorithm, AlgorithmConfig


def benchmark_algorithm(
    problem_sizes: List[int],
    depths: List[int],
    num_runs: int = 10
) -> Dict:
    """
    运行基准测试

    Args:
        problem_sizes: 问题规模列表
        depths: 电路深度列表
        num_runs: 每个配置的运行次数

    Returns:
        Dict: 测试结果
    """
    results = {
        'problem_sizes': [],
        'depths': [],
        'execution_times': [],
        'optimal_values': [],
        'convergence_rates': []
    }

    for n_qubits in problem_sizes:
        for depth in depths:
            print(f"\n测试配置: {n_qubits} 量子比特, 深度 {depth}")

            # 运行多次
            times = []
            values = []
            converged_count = 0

            for run in range(num_runs):
                # 创建配置
                config = AlgorithmConfig(
                    n_qubits=n_qubits,
                    depth=depth,
                    shots=1024
                )

                # 创建算法实例
                algorithm = QuantumAlgorithm(config)

                # 生成随机问题
                problem_matrix = np.random.randn(n_qubits, n_qubits)
                from qiskit.quantum_info import SparsePauliOp
                problem_hamiltonian = SparsePauliOp.from_list(
                    [('Z' * n_qubits, problem_matrix)]
                )

                # 运行算法
                start_time = time.time()
                result = algorithm.run(problem_hamiltonian)
                elapsed_time = time.time() - start_time

                # 记录结果
                times.append(elapsed_time)
                values.append(result['optimal_value'])
                if result['converged']:
                    converged_count += 1

                print(f"  运行 {run+1}/{num_runs}: "
                      f"时间={elapsed_time:.2f}s, "
                      f"值={result['optimal_value']:.4f}")

            # 汇总结果
            results['problem_sizes'].append(n_qubits)
            results['depths'].append(depth)
            results['execution_times'].append({
                'mean': np.mean(times),
                'std': np.std(times),
                'min': np.min(times),
                'max': np.max(times)
            })
            results['optimal_values'].append({
                'mean': np.mean(values),
                'std': np.std(values),
                'min': np.min(values),
                'max': np.max(values)
            })
            results['convergence_rates'].append(
                converged_count / num_runs
            )

    return results


def save_results(results: Dict, output_dir: str = 'results/data'):
    """
    保存结果到文件

    Args:
        results: 测试结果
        output_dir: 输出目录
    """
    output_path = Path(output_dir)
    output_path.mkdir(parents=True, exist_ok=True)

    # 保存为JSON
    with open(output_path / 'benchmark_results.json', 'w') as f:
        json.dump(results, f, indent=2)

    print(f"\n结果已保存到: {output_path}")


def plot_results(results: Dict, output_dir: str = 'results/figures'):
    """
    绘制结果图表

    Args:
        results: 测试结果
        output_dir: 输出目录
    """
    output_path = Path(output_dir)
    output_path.mkdir(parents=True, exist_ok=True)

    # 设置样式
    sns.set_style('whitegrid')
    plt.rcParams['font.size'] = 12

    # 图1: 执行时间 vs 问题规模
    fig1, ax1 = plt.subplots(figsize=(10, 6))

    problem_sizes = results['problem_sizes']
    depths = results['depths']

    for depth in set(depths):
        mask = [d == depth for d in depths]
        sizes = [problem_sizes[i] for i, m in enumerate(mask) if m]
        times = [results['execution_times'][i]['mean']
                 for i, m in enumerate(mask) if m]

        ax1.plot(sizes, times, marker='o', label=f'depth={depth}')

    ax1.set_xlabel('问题规模 (量子比特数)')
    ax1.set_ylabel('执行时间 (秒)')
    ax1.set_title('执行时间 vs 问题规模')
    ax1.legend()
    ax1.grid(True, alpha=0.3)

    plt.tight_layout()
    plt.savefig(output_path / 'execution_time_vs_size.png', dpi=300)
    plt.close()

    # 图2: 收敛率 vs 深度
    fig2, ax2 = plt.subplots(figsize=(10, 6))

    unique_depths = sorted(set(depths))
    convergence_rates = [
        np.mean([
            results['convergence_rates'][i]
            for i, d in enumerate(depths) if d == depth
        ])
        for depth in unique_depths
    ]

    ax2.bar(unique_depths, convergence_rates, color='steelblue')
    ax2.set_xlabel('电路深度')
    ax2.set_ylabel('收敛率')
    ax2.set_title('收敛率 vs 电路深度')
    ax2.set_ylim([0, 1])
    ax2.grid(True, alpha=0.3, axis='y')

    plt.tight_layout()
    plt.savefig(output_path / 'convergence_rate_vs_depth.png', dpi=300)
    plt.close()

    # 图3: 最优值分布
    fig3, ax3 = plt.subplots(figsize=(10, 6))

    optimal_values = [
        results['optimal_values'][i]['mean']
        for i in range(len(results['problem_sizes']))
    ]

    scatter = ax3.scatter(
        results['problem_sizes'],
        results['depths'],
        c=optimal_values,
        cmap='viridis',
        s=200,
        alpha=0.6,
        edgecolors='black'
    )

    ax3.set_xlabel('问题规模 (量子比特数)')
    ax3.set_ylabel('电路深度')
    ax3.set_title('最优值分布')

    cbar = plt.colorbar(scatter)
    cbar.set_label('最优目标函数值')

    plt.tight_layout()
    plt.savefig(output_path / 'optimal_value_distribution.png', dpi=300)
    plt.close()

    print(f"图表已保存到: {output_path}")


def main():
    """主函数"""
    # 配置测试
    problem_sizes = [4, 6, 8, 10]
    depths = [1, 2, 3]
    num_runs = 5

    print("=" * 60)
    print("算法基准测试")
    print("=" * 60)
    print(f"问题规模: {problem_sizes}")
    print(f"电路深度: {depths}")
    print(f"运行次数: {num_runs}")

    # 运行测试
    results = benchmark_algorithm(
        problem_sizes=problem_sizes,
        depths=depths,
        num_runs=num_runs
    )

    # 保存结果
    save_results(results)

    # 绘制图表
    plot_results(results)

    print("\n" + "=" * 60)
    print("基准测试完成!")
    print("=" * 60)


if __name__ == "__main__":
    main()

使用指南

1. 环境配置

系统要求:

项目 要求
操作系统 Linux / macOS / Windows
Python >= 3.8
内存 >= 4 GB (推荐 8 GB)
磁盘空间 >= 1 GB

安装依赖:

# 克隆仓库
git clone [GitHub链接]
cd project_name

# 创建虚拟环境
python -m venv venv

# 激活虚拟环境
# Linux/macOS:
source venv/bin/activate
# Windows:
venv\Scripts\activate

# 安装依赖
pip install -r requirements.txt

# 验证安装
python -c "import qiskit; print(qiskit.__version__)"

requirements.txt:

# 量子计算框架
qiskit>=0.40.0
qiskit-aer>=0.12.0

# 数值计算
numpy>=1.20.0
scipy>=1.7.0

# 可视化
matplotlib>=3.3.0
seaborn>=0.11.0

# 优化
scikit-optimize>=0.8.0

# 测试
pytest>=6.2.0

# Jupyter
jupyter>=1.0.0
ipykernel>=6.0.0

2. 快速开始

示例1: 基础用法

# 导入必要的库
import numpy as np
from src.algorithm import QuantumAlgorithm, AlgorithmConfig
from qiskit.quantum_info import SparsePauliOp

# 创建配置
config = AlgorithmConfig(
    n_qubits=4,
    depth=2,
    shots=1024
)

# 创建算法实例
algorithm = QuantumAlgorithm(config)

# 定义问题哈密顿量
problem_matrix = np.array([
    [1, 0, 0, 0],
    [0, -1, 0, 0],
    [0, 0, 1, 0],
    [0, 0, 0, -1]
])
problem_hamiltonian = SparsePauliOp.from_list(
    [('ZZII', 1.0), ('ZIZI', -1.0)]
)

# 运行算法
result = algorithm.run(problem_hamiltonian)

# 输出结果
print(f"最优值: {result['optimal_value']}")
print(f"最优比特串: {result['optimal_bitstring']}")
print(f"收敛: {result['converged']}")

示例2: 可视化优化过程

import matplotlib.pyplot as plt

# 运行算法并记录历史
result = algorithm.run(problem_hamiltonian)

# 绘制优化历史
plt.figure(figsize=(10, 6))
plt.plot(result['optimization_history'], marker='o')
plt.xlabel('迭代次数')
plt.ylabel('目标函数值')
plt.title('优化过程')
plt.grid(True, alpha=0.3)
plt.show()

3. Jupyter 教程

教程1: 入门教程

# [算法名称] 入门教程

## 1. 算法简介

[算法简介]

## 2. 基础示例

### 2.1 导入库

```python
import numpy as np
from src.algorithm import QuantumAlgorithm, AlgorithmConfig

2.2 创建简单问题

# 定义问题
n_qubits = 4
config = AlgorithmConfig(n_qubits=n_qubits, depth=1)
algorithm = QuantumAlgorithm(config)

2.3 运行算法

result = algorithm.run()
print(f"结果: {result}")

3. 可视化

3.1 绘制量子电路

from qiskit import QuantumCircuit
qc = algorithm.create_circuit(np.random.rand(2))
qc.draw('mpl')

3.2 分析结果

# 绘制优化历史
import matplotlib.pyplot as plt
plt.plot(result['optimization_history'])
plt.show()
---

## 结果分析

### 1. 性能指标

**关键指标**:

| 指标 | 定义 | 目标 | 实际 | 状态 |
|------|------|------|------|------|
| 执行时间 | 算法总运行时间 | < 60s | [值] | ✓/✗ |
| 收敛率 | 成功收敛的概率 | > 90% | [值] | ✓/✗ |
| 解质量 | 与经典最优解的差距 | < 5% | [值] | ✓/✗ |
| 可扩展性 | 规模增加时性能下降 | < O(n³) | [复杂度] | ✓/✗ |

---

### 2. 结果可视化

**可视化代码示例**:

```python
import matplotlib.pyplot as plt
import seaborn as sns

# 设置样式
sns.set_style('whitegrid')
fig, axes = plt.subplots(2, 2, figsize=(15, 10))

# 图1: 优化历史
axes[0, 0].plot(result['optimization_history'], marker='o')
axes[0, 0].set_xlabel('迭代')
axes[0, 0].set_ylabel('目标函数值')
axes[0, 0].set_title('优化过程')
axes[0, 0].grid(True, alpha=0.3)

# 图2: 解的分布
axes[0, 1].hist(optimal_values, bins=30, edgecolor='black')
axes[0, 1].set_xlabel('目标函数值')
axes[0, 1].set_ylabel('频次')
axes[0, 1].set_title('解的分布')

# 图3: 收敛率 vs 深度
depths = [1, 2, 3, 4]
convergence_rates = [0.85, 0.90, 0.92, 0.88]
axes[1, 0].bar(depths, convergence_rates)
axes[1, 0].set_xlabel('电路深度')
axes[1, 0].set_ylabel('收敛率')
axes[1, 0].set_title('收敛率 vs 深度')
axes[1, 0].set_ylim([0, 1])

# 图4: 执行时间 vs 规模
sizes = [4, 6, 8, 10]
times = [5.2, 12.3, 28.7, 65.4]
axes[1, 1].plot(sizes, times, marker='o', linewidth=2)
axes[1, 1].set_xlabel('问题规模')
axes[1, 1].set_ylabel('执行时间 (秒)')
axes[1, 1].set_title('执行时间 vs 规模')
axes[1, 1].grid(True, alpha=0.3)

plt.tight_layout()
plt.savefig('results/figures/performance_analysis.png', dpi=300)
plt.show()


3. 与经典算法对比

对比实验:

算法 平均执行时间 最优解质量 可扩展性
[量子算法] [time] s [quality]% [评分]
经典算法1 [time] s [quality]% [评分]
经典算法2 [time] s [quality]% [评分]

优势分析: - [优势1] - [优势2]

劣势分析: - [劣势1] - [劣势2]


学习资源

1. 内部资源

资源 路径 说明
Jupyter笔记本 notebooks/ 交互式教程
API文档 docs/api.md 完整API参考
代码示例 examples/ 各种使用场景
测试代码 tests/ 单元测试示例

2. 外部资源

学术论文: - [ID_Year_Author]: [论文标题] - [ID_Year_Author]: [论文标题]

在线教程: - [教程名称]: [URL] - [视频课程]: [URL]

社区资源: - [论坛/社区]: [URL] - [Stack Overflow标签]: [URL]


常见问题

Q1: 如何选择合适的深度?

A: 深度的选择需要权衡表达能力(深度越大)和优化难度(深度越大越难优化)。

经验法则: - 小规模问题 (n < 10): depth = 1-2 - 中等规模问题 (10 ≤ n < 20): depth = 2-3 - 大规模问题 (n ≥ 20): depth = 3-5

建议通过实验确定最优深度。


Q2: 算法不收敛怎么办?

A: 尝试以下方法:

  1. 调整初始点: 使用不同的随机初始化
  2. 更换优化器: 尝试 SPSA、GRADIENT等不同优化器
  3. 降低深度: 减少电路深度
  4. 增加采样次数: 提高 shots 参数
# 示例: 更换优化器
from qiskit.algorithms.optimizers import SPSA

config = AlgorithmConfig(
    n_qubits=4,
    depth=2,
    optimizer=SPSA(maxiter=100)
)

Q3: 如何评估解的质量?

A: 与经典最优解对比:

# 经典求解
from scipy.optimize import linear_sum_assignment

classical_solution = solve_classically(problem)

# 量子求解
quantum_solution = algorithm.run(problem)

# 计算近似比
approximation_ratio = (
    quantum_solution['optimal_value'] /
    classical_solution['optimal_value']
)
print(f"近似比: {approximation_ratio:.3f}")

版本历史

版本 日期 修改内容 作者
1.0 YYYY-MM-DD 初始版本 [作者]

[文档结束]

如有任何问题或建议,请联系维护团队: {{author}}

---

## 🎨 模板使用指南

### 1. 应用层特色章节

相比通用模板,应用层模板增加了以下特色章节:

- **算法原理**: 数学公式、电路设计、伪代码
- **核心实现**: 完整的Python类实现
- **基准测试**: 标准化的测试脚本
- **结果可视化**: 详细的可视化代码
- **使用指南**: 环境配置和快速开始
- **学习资源**: 教程和文档链接

---

### 2. 项目文件结构

**标准项目结构**:
project/ ├── README.md # 必需 ├── requirements.txt # 必需 ├── src/ # 必需 │ └── algorithm.py ├── scripts/ # 推荐 │ └── run_baseline.py ├── notebooks/ # 推荐 │ └── tutorial.ipynb ├── tests/ # 推荐 └── results/ # 推荐
---

### 3. 算法文档要求

**算法原理章节应包含**:

1. **问题定义**: 数学表述和复杂度分析
2. **算法流程**: 清晰的步骤说明
3. **量子电路**: 电路图和参数化说明
4. **数学公式**: 完整的数学推导

**示例结构**:

```latex
## 算法原理

### 问题定义

目标: $\min_x f(x) = x^T Q x$

约束: $x_i \in \{0, 1\}$

### 算法流程

1. 初始化: $|\psi_0\rangle = H^{\otimes n}|0\rangle$
2. 参数化演化: $|\psi(\theta)\rangle = U(\theta)|\psi_0\rangle$
3. 测量与优化


4. 代码实现要求

核心类应包含:

  1. 配置类: 使用dataclass定义配置
  2. 算法类: 完整的类实现
  3. 类型标注: 所有函数使用类型提示
  4. 文档字符串: 详细的docstring
  5. 单元测试: 测试关键功能

✅ 质量检查清单

应用层文档发布前,请额外确认:

□ 包含完整的项目文件结构
□ 算法原理章节有数学公式
□ 代码示例完整可运行
□ 提供基准测试脚本
□ 包含结果可视化代码
□ 使用指南有环境配置说明
□ 包含至少1个Jupyter笔记本
□ 常见问题至少包含3个FAQ
□ 所有依赖列在requirements.txt中
□ 包含学习资源链接

📞 模板支持

维护团队: templates@quantum-kb.example.com 问题反馈: https://github.com/quantum-kb/templates/issues


模板版本: 1.0 最后更新: 2026-01-13