Metadata-Version: 2.4
Name: cz-qio
Version: 0.1.0
Summary: Python client for qbrain: experiment sequence DSL, backend REST/RPC transport, and measurement result handling
Author-email: XNCZ <xncz@outlook.com>
Project-URL: Homepage, https://pypi.org/project/cz-qio/
Keywords: quantum,quantum-computing,qubit,pulse-sequence,qbrain
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: protobuf>=7.35.0
Requires-Dist: typing_extensions>=4.15.0
Requires-Dist: numpy
Requires-Dist: pyyaml
Requires-Dist: websocket-client
Requires-Dist: msgpack

# cz-qio

`qio` 是量子测控核心（qbrain）的 Python 客户端。你用 Python 描述一个实验序列
（什么时候驱动、驱动多久、什么时候测量），`qio` 负责把它翻译成后端能执行的指令。

分发名为 `cz-qio`，导入名为 `qio`。

## 安装

```shell
uv add cz-qio
```

## 连接后端

`qio` 同时对接两个互相独立的后端：

| 后端 | 缺省地址 | 用途 | 覆盖方式 |
| --- | --- | --- | --- |
| qbrain | `127.0.0.1:22549` | 实验提交、架构与 Directive 管理 | `QIO(api_key=...)`（生产路由尚未实现） |
| qsim-server | `127.0.0.1:22550` | 芯片与分区配置（仅仿真） | 环境变量 `QSIM_URL` 或 `QIO(qsim_url=...)` |

```python
import qio

qc = qio.QIO()          # 连本机 qbrain 与 qsim-server
```

## 示例

`examples/` 下按后端分三个可直接运行的案例，每个案例自带它所需的整套 YAML 配置：

```
examples/
├── zurich/       standard_basic_calibration.ipynb
│                 + channels / instruments / terminals .yml
├── zwdx/         zwdx_qspec.ipynb
│                 + channels / instruments / terminals .yml
└── simulator/    simulator_run.ipynb
                  + 9 个 YAML（含 chip / groups / config）— 10 组 QCQ 夹具
```

这些 notebook 调 `post_arch()` 时不传参数，由**当前工作目录**自动探测
`instruments` / `terminals` / `channels` 三层 YAML。打开 notebook 时工作目录必须是
它所在的 `examples/<后端>/` 目录，否则会报 `FileNotFoundError`。

## 用户指南

以下按「怎么用」组织，每个语法都配一段能直接套用的例子。导入方式统一为：

```python
import qio
from qio.qjob.sequence import Sequence, Square, Idle, DRAG
from qio.qjob.entities import xy, r, z
```

---

## 1. 快速开始：连上后端，跑一个 Rabi

```python
import numpy as np
import qio
from qio.qjob.sequence import Sequence, Square, Idle
from qio.qjob.entities import xy, r

# 连接本地后端（默认 127.0.0.1:22549）
qc = qio.QIO()

# 提交架构配置（YAML 文件路径）
qc.post_arch(
    instruments="instruments.yml",
    terminals="terminals.yml",
    channels="channels.yml",
    components="components.yml",
    quantums="quantums.yml",
    topology="topology.yml",
)

# 绑定各终端的 trigger_delay（仿真/实机通常置 0）
qc.directives.bind(qio.iq("IQ_SIM"))["trigger_delay"] = 0
qc.directives.bind(qio.qa("QA_SIM"))["trigger_delay"] = 0

# 扫驱动时长，观察 Rabi 振荡
durations = np.linspace(0, 150e-9, 51)
seq = Sequence()
with seq.sweep(durations) as dura:
    with seq.repeat(200):                 # 每个点重复 200 shot
        with seq.epoch() as epoch:
            with epoch(xy("CH_XY_Q1")) as drive:
                drive.play(Square(duration=dura, detuning=0, amplitude=0.05,
                                  frequency=4.4558e9, phase=0))
                drive.play(Idle(duration=500e-9))
                drive.barrier(id="measure", align="ASAP")
            with epoch(r("CH_RES1")) as readout:
                readout.barrier("measure", "ASAP")
                readout.measure(
                    stimulus=Square(duration=2e-6, detuning=0, amplitude=0.07,
                                    frequency=6.5e9, phase=0),
                    delay=250e-9,
                    demod=Square(duration=2e-6, detuning=0, amplitude=1,
                                 frequency=6.5e9, phase=0),
                )

# 执行并读取结果
result = seq.execute(qc)
data = result["measurement_results"]["CH_RES1"]      # numpy 数组
p1 = data.real.astype(int).mean(axis=1)              # 每个扫参点的激发概率
```

三层结构记住一句：**`sweep`（扫什么）套 `repeat`（重复几次）套 `epoch`（同一时刻做什么）**。

---

## 2. 连接与架构

### 2.1 QIO 客户端

```python
qc = qio.QIO()               # 默认连本地 127.0.0.1:22549
qc = qio.QIO(api_key="...")  # 生产环境走路由（当前未实现，暂用默认）
```

`QIO` 主要方法：

| 方法 | 作用 |
| --- | --- |
| `post_arch(...)` | 提交架构配置文件，返回架构对象 |
| `get_arch()` | 拉取当前架构 |
| `execute(seq_proto, ...)` | 提交序列并执行，返回结果 |
| `call(method, *args)` | 底层 WebSocket RPC（一般用不到） |
| `.directives` | 参数绑定（见第 4 节） |

### 2.2 提交架构

```python
arch = qc.post_arch(
    instruments="instruments.yml",
    terminals="terminals.yml",
    channels="channels.yml",
    components="components.yml",   # 可选
    quantums="quantums.yml",       # 可选
    topology="topology.yml",       # 可选
)
print(arch.channels.channels)      # 已注册的通道列表
print(arch.terminals.terminals)    # 已注册的终端列表
```

参数都是 YAML 文件路径，传 `None`（或省略）则让后端自动探测。

---

## 3. 构造实验序列（Sequence）

### 3.1 三种控制流：sweep / repeat / epoch

| 控制流 | 写法 | 含义 |
| --- | --- | --- |
| `sweep` | `with seq.sweep(array) as var:` | 扫参：`array` 每个值跑一遍，`var` 是当前值 |
| `repeat` | `with seq.repeat(n):` | 无状态重复 n 次（shot 平均用它） |
| `epoch` | `with seq.epoch() as epoch:` | 同一时刻，多个通道并行做什么 |

嵌套顺序 = 实验嵌套顺序。外层 sweep 是「慢轴」，内层 repeat 是「快轴」。

```python
with seq.sweep(freqs) as f:        # 外层：扫频率
    with seq.sweep(amps) as a:     # 中层：扫振幅（二维扫描）
        with seq.repeat(1000):     # 内层：重复 shot
            with seq.epoch() as epoch:
                ...
```

多个扫参变量：`with seq.sweep(freqs, amps) as (f, a):`。

### 3.2 通道与实体

`epoch(...)` 里写通道，`as` 解包得到通道对象：

```python
with epoch(xy("CH_XY_Q1")) as drive:              # 单通道
    drive.play(...)

with epoch(xy("CH_XY_Q1"), r("CH_RES1")) as (drive, readout):   # 多通道
    drive.play(...)
    readout.measure(...)
```

实体工厂：

| 工厂 | 含义 | 例子 |
| --- | --- | --- |
| `xy("...")` | 驱动通道 | `xy("CH_XY_Q1")` |
| `r("...")` | 读出通道 | `r("CH_RES1")` |
| `z("...")` | 磁通偏置通道 | `z("CH_Z_C")` |

### 3.3 播放波形：play

```python
drive.play(Square(duration=50e-9, detuning=0, amplitude=0.05,
                  frequency=4.4558e9, phase=0))
drive.play(Idle(duration=500e-9))       # 空等 500 ns
```

五种波形，**全部关键字传参、字段不能省**：

| 波形 | 字段 | 用途 |
| --- | --- | --- |
| `Square` | `duration, detuning, amplitude, frequency, phase` | 方波驱动/读出脉冲 |
| `DRAG` | `duration, detuning, coeff, amplitude, frequency, phase` | 带相位补偿的驱动（抑制泄漏） |
| `Idle` | `duration` | 空等待 |
| `ComplexWaveform` | `duration, samples, detuning, amplitude, frequency, phase` | 自定义复采样波形 |
| `ArbitraryWaveform` | `duration, samples, amplitude` | 任意实采样波形（如磁通脉冲） |

字段含义：

- `duration`：持续时长，秒。
- `amplitude`：振幅，无量纲比例。
- `frequency`：载波中心频率，Hz（mixer 架构里由 LO 提供）。
- `detuning`：基带数字频移，Hz，编译时以 `e^{j·2π·detuning·t}` 应用。
- `phase`：相位偏移，rad。
- `coeff`：DRAG 系数，无量纲。

自定义波形例子：

```python
drive.play(ComplexWaveform(duration=100e-9, samples=[1+0j, 0.9+0.1j, ...],
                           detuning=0, amplitude=0.1, frequency=5e9, phase=0))
flux.play(ArbitraryWaveform(duration=200e-9, samples=[0.0, 0.1, 0.2, ...], amplitude=1))
```

### 3.4 对齐：barrier

`barrier` 把多个通道的对齐点强制到同一时刻。`align="ASAP"` 左对齐（尽量早），`align="ALAP"` 右对齐（尽量晚）。

典型用法——驱动结束、读出开始前，两侧各插一个同名 barrier：

```python
with epoch(xy("CH_XY_Q1"), r("CH_RES1")) as (drive, readout):
    drive.play(Square(duration=50e-9, detuning=0, amplitude=0.05,
                      frequency=4.4558e9, phase=0))
    drive.barrier(id="measure", align="ASAP")     # 驱动侧
    readout.barrier("measure", "ASAP")            # 读出侧（同名 barrier 才会对齐）
    readout.measure(...)
```

### 3.5 测量：measure

```python
readout.measure(
    stimulus=Square(duration=2e-6, detuning=0, amplitude=0.07, frequency=6.5e9, phase=0),
    delay=250e-9,                                    # 输入-输出之间的延迟
    demod=Square(duration=2e-6, detuning=0, amplitude=1, frequency=6.5e9, phase=0),
    dest="I_raw",                                    # 可选：结果写入的目标变量名
)
```

`stimulus` 是探测脉冲，`demod` 是解调参考，`delay` 是二者之间的延迟，`dest` 可省略。

### 3.6 扫参：sweep

`seq.sweep(array)` 把数组里的每个值注入成变量，你在波形参数里直接引用它：

```python
durations = np.linspace(0, 150e-9, 51)
with seq.sweep(durations) as dura:
    with seq.epoch() as epoch:
        with epoch(xy("CH_XY_Q1")) as drive:
            drive.play(Square(duration=dura, detuning=0, amplitude=0.05,
                              frequency=4.4558e9, phase=0))   # duration 用扫参变量
```

### 3.7 重复：repeat 与 macro_loop

`repeat(n)` 就是无状态循环，一般用于 shot 平均：

```python
with seq.repeat(1000):
    with seq.epoch() as epoch:
        ...
```

`macro_loop` 更通用：既支持 `repeats`（等价 repeat），也支持 `state`（显式给一串状态字典）：

```python
# 等价于 sweep([0.1, 0.2]) 的显式写法
with seq.macro_loop(state=[{"amp": 0.1}, {"amp": 0.2}]):
    with seq.epoch() as epoch:
        with epoch(xy("CH_XY_Q1")) as drive:
            drive.play(Square(duration=50e-9, detuning=0, amplitude=Variable("amp"),
                              frequency=4.4558e9, phase=0))
```

> 大多数场景用 `sweep` + `repeat` 就够；只有需要手写状态字典时才用 `macro_loop`。

### 3.8 变量与表达式

波形参数可以是「变量」或「表达式」，编译时按当前 sweep 值求值：

```python
from qio.qjob.sequence import Variable, max_

amp = Variable("amp")                # 命名变量（配合 macro_loop 的 state 键）
gain = max_(amp + 0.01, 0)           # 表达式：max(amp + 0.01, 0)
cond = amp > 0.5                     # 比较：生成条件（用于 when）
```

- 算术：`+`、`-`、`*`
- 比较：`==`、`!=`、`>`、`<`（`>=`、`<=` 和除法不支持，会报错）
- 组合函数：`max_()`、`min_()`、`and_()`、`or_()`、`xor_()`

### 3.9 条件分支：when

```python
with epoch(xy("CH_XY_Q1")) as drive:
    drive.when(
        swept_amplitude > 0.5,                     # 条件
        true_branch=lambda b: b.play(Square(duration=50e-9, detuning=0,
                                             amplitude=swept_amplitude,
                                             frequency=4.4558e9, phase=0)),
        false_branch=lambda b: b.play(Square(duration=50e-9, detuning=0,
                                              amplitude=0, frequency=4.4558e9, phase=0)),
    )
```

分支体是 lambda，入参 `b` 代表该分支里的通道，同样有 `play` / `measure` 等方法。

### 3.10 赋值与循环：assign / sync_loop / async_loop

```python
drive.assign("result", 0.25)                       # 给变量赋常量

with drive.sync_loop(repeats=2):                   # 同步循环（后端不展开，硬件直接循环）
    drive.play(pulse)

with drive.async_loop(repeats=4) as loop_ch:       # 异步循环（编译期展开）
    loop_ch.play(pulse)
```

区别：`sync_loop` 不展开、时序可控；`async_loop` 会展开、适合需要多通道对齐的场景。日常基本用不到，`repeat` 已覆盖 shot 平均。

---

## 4. Directive：参数绑定与引用

「参数」是可以扫、可以在实验之间复用的可调量。先用 `bind` 绑定，再用 `[...]` 赋值或读取：

```python
# 绑定一个常量
qc.directives.bind(xy("CH_XY_Q1"))["pi_len"] = 47e-9

# 绑定一个随参数变化的量（lambda）
qc.directives.bind(r("CH_RES1"))["readout_freq"] = lambda detuning: 6.5e9 + detuning

# 读出来，在序列里引用
readout_freq = qc.directives.bind(r("CH_RES1"))["readout_freq"]
with epoch(r("CH_RES1")) as readout:
    readout.measure(stimulus=Square(duration=2e-6, detuning=0, amplitude=0.07,
                                    frequency=readout_freq(0), phase=0),
                    delay=250e-9,
                    demod=Square(duration=2e-6, detuning=0, amplitude=1,
                                 frequency=readout_freq(0), phase=0))
```

要点：

- `bind(entity)` 用实体（通道/终端）绑定一个 directive key。
- 赋值右侧可以是 `Decimal`/`int`/`float`、波形，或「接收参数、返回数值/波形」的 lambda。
- 读出来的 directive 是**可调用的**：`readout_freq(0)` 在序列里引用它，调用不会在 Python 里求值，而是生成一个 `DirectiveRef`，由后端展开。

典型的校准工作流：先在 Rabi 实验里拟合出 π 脉冲长度，再把它写进 directive，供后续 T1/T2 实验引用：

```python
qc.directives.bind(xy("CH_XY_Q1"))["pi_len"] = fitted_pi_len   # 拟合结果写回
```

---

## 5. 执行与读取结果

```python
result = seq.execute(qc)                              # 提交并执行
data = result["measurement_results"]["CH_RES1"]       # 某通道的测量结果（numpy 数组）
```

结果数组的维度是「扫参维度… × shot」。单维扫参时 `data[i]` 是第 i 个扫参点的全部 shot；取激发概率就是：

```python
outcomes = data.real.astype(int)      # 测量结果按整数读出（dressed 能级序号）
p1 = outcomes.mean(axis=1)            # 沿 shot 维度平均 → 每个扫参点的激发概率
```

> 仿真器测量返回的是 dressed 能级序号（0/1/2…），不是 IQ 复数信号；实机则是 IQ 复数。具体语义取决于后端与 `dest` 配置。

如果你已经有序列化好的序列，也可直接走客户端：

```python
result = qc.execute(seq.to_proto().SerializeToString(), analysis_path="analyse.py",
                    module_name="analyse", func_name="analyse")
```

---

## 6. 数值单位

所有物理量统一用 **SI 标准单位**，没有隐式缩放：

| 量 | 单位 |
| --- | --- |
| 时间 | `s`（秒） |
| 频率 | `Hz` |
| 相位 | `rad` |
| 振幅 | 无量纲比例 |

例如 `100e-9` 表示 100 纳秒，`4.4558e9` 表示 4.4558 GHz，`0.05` 表示 5% 振幅。数值可传 `Decimal`、`int` 或 `float`；不要传字符串。

---

## 7. 常见实验模板

### Rabi（扫驱动时长）

见第 1 节快速开始，即 `sweep(durations)` + 方波驱动 + 读出。

### 谱测量（扫驱动频率）

```python
freqs = np.linspace(4.4e9, 4.5e9, 101)
with seq.sweep(freqs) as f:
    with seq.repeat(200):
        with seq.epoch() as epoch:
            with epoch(xy("CH_XY_Q1")) as drive:
                drive.play(Square(duration=400e-9, detuning=0, amplitude=0.05,
                                  frequency=f, phase=0))
            with epoch(r("CH_RES1")) as readout:
                readout.measure(stimulus=Square(duration=2e-6, detuning=0, amplitude=0.07,
                                                frequency=6.5e9, phase=0),
                                delay=250e-9,
                                demod=Square(duration=2e-6, detuning=0, amplitude=1,
                                             frequency=6.5e9, phase=0))
```

### T1（扫等待时长）

```python
gaps = np.linspace(0, 20e-6, 11)
with seq.sweep(gaps) as gap:
    with seq.repeat(200):
        with seq.epoch() as epoch:
            with epoch(xy("CH_XY_Q1"), r("CH_RES1")) as (drive, readout):
                drive.play(Square(duration=47e-9, detuning=0, amplitude=0.05,
                                  frequency=4.4558e9, phase=0))   # π 脉冲
                drive.play(Idle(duration=gap))                     # 等 gap
                drive.barrier(id="measure", align="ASAP")
                readout.barrier("measure", "ASAP")
                readout.measure(...)
```

### Ramsey（π/2 → 等 gap → π/2）

```python
with seq.sweep(gaps) as gap:
    with seq.epoch() as epoch:
        with epoch(xy("CH_XY_Q1"), r("CH_RES1")) as (drive, readout):
            drive.play(Square(duration=23.5e-9, detuning=0, amplitude=0.05,
                              frequency=4.4558e9, phase=0))        # π/2
            drive.play(Idle(duration=gap))
            drive.play(Square(duration=23.5e-9, detuning=0, amplitude=0.05,
                              frequency=4.4558e9, phase=0))        # π/2
            drive.barrier(id="measure", align="ASAP")
            readout.barrier("measure", "ASAP")
            readout.measure(...)
```

---

## 附：常用导入速查

```python
import qio                                             # QIO, xy, z, r, lo, iq, qa, instrument

from qio.qjob.sequence import (
    Sequence, Square, Idle, DRAG, ComplexWaveform, ArbitraryWaveform,
    Variable, VariableExpr, max_, min_, and_, or_, xor_, barrier, sync,
)
from qio.qjob.directives import Directives, Value, Shape
```
