Running your first Program
Once a kernel is defined, qalgora-Q gives you four primitives to execute it:
sample, run, observe, and get_state.
(run is a specification interface — not yet bundled in the open reference build;
use sample / observe / get_state to run code today.)
Sample — measurement statistics
import qalgora
@qalgora.kernel
def bell_sample():
q = qalgora.qvector(2)
h(q[0])
x.ctrl(q[0], q[1])
mz(q) # measured — for sampling
@qalgora.kernel
def bell_state():
q = qalgora.qvector(2)
h(q[0])
x.ctrl(q[0], q[1]) # no measurement — for observe / get_state
counts = qalgora.sample(bell_sample, shots_count=1000)
print(counts) # { 00:~500, 11:~500 }
Run — typed return values
@qalgora.kernel
def coin() -> bool:
q = qalgora.qubit(); h(q)
return mz(q)
flips = qalgora.run(coin, shots_count=20) # list[bool], one entry per shot
print("heads:", sum(flips))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.Observe — expectation values
from qalgora import spin
print(qalgora.observe(bell_state, spin.z(0) * spin.z(1)).expectation())
Get state — raw amplitudes (CPU statevector)
In the reference build, get_state returns the raw complex amplitudes directly from
the CPU statevector simulator — no GPU required. A planned gpu target would run the same
call GPU-accelerated.
print(qalgora.get_state(bell_state)) # CPU statevector simulator (reference build)
# A future qalgora.set_target("gpu") would run the same call GPU-accelerated (planned).
Tip
Use sample for bitstring distributions, observe for energies/operators,
and get_state when you need the raw amplitudes (simulation only).
运行第一个程序
定义好内核后,qalgora-Q 提供四种原语来执行它:
sample、run、observe 和 get_state。
(其中 run 是规范接口——开放参考实现尚未内置,目前请用
sample / observe / get_state 运行代码。)
Sample — 测量统计
import qalgora
@qalgora.kernel
def bell_sample():
q = qalgora.qvector(2)
h(q[0])
x.ctrl(q[0], q[1])
mz(q) # 带测量——用于采样
@qalgora.kernel
def bell_state():
q = qalgora.qvector(2)
h(q[0])
x.ctrl(q[0], q[1]) # 不测量——用于 observe / get_state
counts = qalgora.sample(bell_sample, shots_count=1000)
print(counts) # { 00:~500, 11:~500 }
Run — 带类型的返回值
@qalgora.kernel
def coin() -> bool:
q = qalgora.qubit(); h(q)
return mz(q)
flips = qalgora.run(coin, shots_count=20) # list[bool],每次采样一个
print("heads:", sum(flips))规范接口 · 参考实现暂未包含
此示例展示的是 qalgora-Q 规范中的接口(或第三方库),开放参考实现目前尚未内置,仅用于说明预期用法;如需立即运行,请使用参考实现已支持的核心 API。Observe — 期望值
from qalgora import spin
print(qalgora.observe(bell_state, spin.z(0) * spin.z(1)).expectation())
获取原始振幅 — CPU 态矢量
在参考实现里,get_state 直接从 CPU 态矢量模拟器返回原始复振幅,无需 GPU。规划中的 gpu 目标计划以 GPU 加速执行同一调用。
print(qalgora.get_state(bell_state)) # CPU 态矢量模拟器(参考实现)
# 未来的 qalgora.set_target("gpu") 会以 GPU 加速执行同一调用(规划中)。
小贴士
用 sample 获取比特串分布,用 observe 计算能量或算符期望值,
需要原始振幅时(仅限模拟)则使用 get_state。