Cost Minimization
The pattern at the heart of every variational algorithm: define a quantum cost function, then drive it to its minimum with a classical optimizer.
A minimal variational loop
import qalgora
from qalgora import spin
@qalgora.kernel
def ansatz(theta: float):
q = qalgora.qubit()
ry(theta, q)
cost_op = spin.z(0)
def cost(params):
theta = params[0]
return qalgora.observe(ansatz, cost_op, theta).expectation()
opt = qalgora.optimizers.COBYLA()
minimum, best = opt.optimize(dimensions=1, function=cost)
print("minimum <Z> =", minimum, "at theta =", best[0]) # expected optimum: <Z> = -1 at theta = πSpecification API — not in the open reference build yet
This example shows a qalgora-Q specification API (or a third-party library) that the open reference build does not bundle today. It documents the intended interface; to run code now, use the reference build’s supported core API.Anatomy
- Ansatz — a parameterized kernel that prepares a trial state.
- Cost — an expectation value to minimize (energy, error, loss).
- Optimizer — a classical routine that proposes new parameters.
Everywhere
Many VQE, QAOA, and quantum machine learning models can be written as this variational loop; what
differs is the ansatz, the cost function, the measurement scheme, the constraints, and the choice of
optimizer.
代价最小化
所有变分算法的核心套路:定义一个量子代价函数,再用经典优化器把它压到最小值。
最简变分循环
import qalgora
from qalgora import spin
@qalgora.kernel
def ansatz(theta: float):
q = qalgora.qubit()
ry(theta, q)
cost_op = spin.z(0)
def cost(params):
theta = params[0]
return qalgora.observe(ansatz, cost_op, theta).expectation()
opt = qalgora.optimizers.COBYLA()
minimum, best = opt.optimize(dimensions=1, function=cost)
print("minimum <Z> =", minimum, "at theta =", best[0]) # expected optimum: <Z> = -1 at theta = π规范接口 · 参考实现暂未包含
此示例展示的是 qalgora-Q 规范中的接口(或第三方库),开放参考实现目前尚未内置,仅用于说明预期用法;如需立即运行,请使用参考实现已支持的核心 API。结构解析
- 线路拟设 — 用来制备试探态的参数化内核。
- 代价 — 要最小化的期望值(能量、误差、损失)。
- 优化器 — 不断给出新参数的经典例程。
无处不在
许多 VQE、QAOA 和量子机器学习模型都可以写成这个变分循环;区别在于 ansatz、代价函数、测量方式、约束条件和优化器选择。