qalgora-Q Docs Hub量子文档 ✦ Ask AI✦ 问问文档

Computing Expectation Values

The observe primitive estimates ⟨ψ|H|ψ⟩ for a spin operator H — the workhorse of variational algorithms.

A single observable

import qalgora
from qalgora import spin, x, ry

@qalgora.kernel
def ansatz(theta: float):
    q = qalgora.qvector(2)
    x(q[0])
    ry(theta, q[1])
    x.ctrl(q[1], q[0])

H = 5.907 - 2.143 * spin.x(0) * spin.x(1) + 0.218 * spin.z(0)
print(qalgora.observe(ansatz, H, 0.59).expectation())

Batching a parameter sweep

The reference build sweeps parameters with a plain Python loop — point by point, not a single batched submission. A batched / multi-GPU backend that fans these evaluations out in parallel is planned (规划中); the loop below evaluates each point sequentially on the CPU simulator.

import numpy as np
angles = np.linspace(0, 2 * np.pi, 50)
energies = [qalgora.observe(ansatz, H, a).expectation() for a in angles]   # point-by-point loop
Parallelism (planned · 规划中)
A multi-GPU target that shards term-by-term and parameter-by-parameter evaluation across devices — turning a long sweep into a near-constant-time batch — is planned. On the CPU reference build the sweep runs sequentially, so wall-clock time scales with the number of points.

计算期望值

observe 原语用来估算自旋算符 H 的期望值 ⟨ψ|H|ψ⟩,是变分算法的核心工具。

单个可观测量

import qalgora
from qalgora import spin, x, ry

@qalgora.kernel
def ansatz(theta: float):
    q = qalgora.qvector(2)
    x(q[0])
    ry(theta, q[1])
    x.ctrl(q[1], q[0])

H = 5.907 - 2.143 * spin.x(0) * spin.x(1) + 0.218 * spin.z(0)
print(qalgora.observe(ansatz, H, 0.59).expectation())

批量参数扫描

当前用 Python 循环扫描;规划中的批处理/多 GPU 后端可并行分发;下面是逐点循环,不是一次性提交。

import numpy as np
angles = np.linspace(0, 2 * np.pi, 50)
energies = [qalgora.observe(ansatz, H, a).expectation() for a in angles]   # 逐点循环
并行(规划中)
把每一项、每个参数的计算拆分到各设备、将漫长扫描变成近乎常数时间批处理的多 GPU 后端尚属规划中。在 CPU 参考实现上,扫描按顺序逐点执行,墙钟时间随点数增加。