qaiji.core.pulse.check 源代码

# Copyright 2026 Qaiji-IR core developer: Ye Jun <yjmaxpayne@hotmail.com>
# SPDX-License-Identifier: Apache-2.0
"""L1 程序与 L2 原生调度的一致性检查,以及经典变量与目标脉冲字段的宽度检查。"""

from __future__ import annotations

import math
from bisect import bisect_right
from collections.abc import Mapping
from dataclasses import dataclass
from typing import Any, NoReturn

from qaiji.core.classical_expr import (
    Binary,
    BitType,
    ClassicalExpr,
    ClassicalType,
    Const,
    FixedType,
    Not,
    Var,
    value_range,
)
from qaiji.core.native import (
    ClassicalAssignment,
    ConditionRegion,
    NativeOperation,
    NativeScheduleIR,
)
from qaiji.core.native.model import (
    _has_classical_features,
    _referenced_bits,
    _register_bit,
)

from .codec import native_schedule_ref
from .errors import _fail
from .model import (
    Acquire,
    Assign,
    ClassicalSection,
    Play,
    Port,
    PulseProgramIR,
    ReadFproc,
)
from .phase import phases_equal

_PULSED = ("RX90", "CZ", "MEASURE")
_VIRTUAL = ("Z", "RZ")
_PLAY_ROLES = {
    "RX90": ("drive",),
    "MEASURE": ("readout",),
    "CZ": ("flux", "coupler_flux", "two_body_drive"),
}


[文档] def check_pulse_program(program: PulseProgramIR, schedule: NativeScheduleIR) -> None: """检查 L1 程序与生成它的 L2 调度一致。 检查项: 1. ``source_schedule_ref`` 等于 ``native_schedule_ref(schedule)``,``end_ns`` 与条件区间相同。 2. ``instructions`` 中的每条记录落在对应 L2 操作的时间内,条件与该操作相同。``Acquire`` 对应其测量事件的操作,其余记录对应 ``source`` 指向的操作。 3. 来源:``Play`` 只来自 RX90、CZ、MEASURE。``origin="gate"`` 的 ``ShiftPhase`` 只来自 Z、RZ,时刻等于操作起点,增量与 −θ 按 ``phases_equal`` 相等(Z 取 θ = π)。 ``origin="correction"`` 的 ``ShiftPhase`` 只来自 CZ,帧在 CZ 的比特上。 4. 目标:RX90 的 ``Play`` 在本比特的驱动帧上,MEASURE 的在本比特的读出帧上,CZ 的在 flux 类帧上且帧的比特属于 CZ,或在目标恰为 CZ 比特对的两体驱动帧上。 ``Acquire`` 的端口属于被测比特。 5. 覆盖:每个 Z、RZ 在比特 q 的每个 ``targets == (q,)`` 的驱动帧上各有 1 条 gate ``ShiftPhase``。每个 RX90、CZ、MEASURE 至少有 1 条 ``Play``。 6. 测量:每个 MEASURE 有 1 条读出 ``Play``。``Acquire`` 与 L2 测量事件一一对应。 7. 测量读取:``ReadFproc`` 的 ``source`` 等于所读事件的 ``operation_index``,``at_ns`` 不早于 该事件的 ``ready_ns``。只检查 ``fproc.kind == "measurement"`` 的记录。 8. 经典记录的来源:``source`` 不为 None 时,是 L2 操作的合法下标,即 ``0 <= source < len(schedule.operations)``。 9. 变量:L2 有赋值的变量在 L1 中有相同的名字与类型。L2 没有赋值的变量可以不声明。 L1 声明同名变量时,类型须相同。其余 L1 变量是临时变量。 10. 赋值:对每个 L2 变量,L1 依次写入的值等于 L2 依次赋的值。第 k 次写入不早于 L2 第 k 次 赋值的 ``at_ns``。 11. 谓词:谓词记录与 L2 的谓词条件一一对应,等值条件没有记录。在条件的 ``start_ns``, 记录的变量等于 L2 谓词的值。该变量的值取自 ``at_ns <= start_ns`` 的最后一次写入。 12. 追踪帧:恰好是 ``tracked_qubits`` 中每个比特 q 的全部 ``targets == (q,)`` 的驱动帧。 相位变量的类型是 ``FixedType(w, w, signed=False)``。它们各不相同,不与 L2 变量同名, 也没有 ``ops`` 写入。 L2 没有经典特性时,不检查第 7、9、10 项。此时有谓词记录或追踪帧的程序仍被拒收。 程序没有经典段时,各字段视为空。L2 的谓词或赋值按名读取多比特寄存器时,L1 不能表示该值, 所以本函数拒收该调度,代码为 ``SCHEDULE_CLASSICAL``。1 位寄存器可以按名读取。 局限: 1. 值的比较是结构性的。本函数拒收代数上等价但写法不同的表达式,也拒收省略了多余写入的 L1 程序。 2. 不检查寄存器是否在读取前被后来的测量覆盖,也不检查 ALU 延迟。它们由目标负责。 3. 不检查动态参数使用的变量与数值。动态参数可以使用任一已声明变量,包括追踪帧的相位 变量。也不比较 ``Play`` 的相位。 4. 对 ``Assign`` 与 extern 读取,只检查 ``source`` 是否在范围内,不检查它的归属。 5. 相位变量在时刻 0 的值定义为 0。目标必须在首次使用前把它置为 0,本函数不能验证这一点。 6. L2 没有经典特性时,不检查 L1 变量的来源与取值。 7. 过深的表达式可能抛出 ``RecursionError``。 Args: program: 待检查的 L1 程序。 schedule: 生成该程序的 L2 调度。 Raises: PulseContractError: 程序与调度不一致,或者调度按名读取多比特寄存器,类别为 ``SCHEDULE_MISMATCH``。 """ if type(program) is not PulseProgramIR: _mismatch("TYPE", "", "Expected PulseProgramIR.") if type(schedule) is not NativeScheduleIR: _mismatch("TYPE", "", "Expected NativeScheduleIR.") if program.source_schedule_ref != native_schedule_ref(schedule): _mismatch("SCHEDULE_REF", "/source_schedule_ref", "Reference differs from the schedule.") _check_whole_registers(schedule) if program.end_ns != schedule.end_ns: _mismatch("END", "/end_ns", "End time differs from the schedule.") windows = tuple((r.condition_id, r.start_ns, r.end_ns) for r in schedule.conditions) if program.conditions != windows: _mismatch("CONDITIONS", "/conditions", "Condition regions differ from the schedule.") plays, shifts = _check_records(program, schedule) _check_coverage(program, schedule, plays, shifts) _check_classical(program, schedule)
[文档] @dataclass(frozen=True, slots=True, kw_only=True) class FieldSpec: """目标的一个脉冲字段:位宽与是否取模。 Example: >>> FieldSpec(width=17, modular=True).width 17 Raises: PulseContractError: ``width`` 不是不小于 1 的 ``int``,或 ``modular`` 不是 ``bool``, 类别为 ``INVALID_PROGRAM``,诊断码 ``FIELD_SPEC``。 """ width: int modular: bool = False def __post_init__(self) -> None: if type(self.width) is not int or self.width < 1: _fail("FIELD_SPEC", "/width", "Expected an integer width of at least 1.") if type(self.modular) is not bool: _fail("FIELD_SPEC", "/modular", "Expected a bool.")
[文档] def check_field_widths(program: PulseProgramIR, fields: Mapping[str, FieldSpec]) -> tuple[str, ...]: """检查经典变量能否写入目标的脉冲字段。 用途为带 ``dynamic`` 的 ``Play``(字段为 ``dynamic.field``)与追踪帧的相位变量(字段为 ``phase``)。每个用途依次检查: 1. ``fields`` 描述了该字段。``phase`` 字段按设计取模,描述为非取模时拒收。 2. 变量声明宽度等于字段宽度,比特宽度为 1。取模字段同样检查。 3. 取模字段不做值域检查,用途路径记入返回值。 4. ``amplitude`` 的变量值域按小数位换算后落在 [-1, 1];``frequency``、``envelope`` 的 变量值域落在 ``table`` 的下标范围内。 变量值域取读者看见的最后一次写入:``Play`` 看见 ``at_ns`` 不晚于 ``start_ns`` 的写入, ``Assign`` 看见 ``ops`` 中排在它前面的写入。看不见任何写入或由 ``ReadFproc`` 写入的变量 取声明全范围,因为寄存器初值未知。``Assign`` 写入取 ``value_range`` 的结果,越出声明 范围时取声明全范围,因为求值会回绕。 Args: program: 待检查的 L1 程序。 fields: 字段名到目标字段描述的映射。 Returns: 取模用途的 JSON Pointer 路径,按检查顺序,即声明过的取模变换。 Raises: PulseContractError: 类别为 ``INVALID_PROGRAM``。字段未描述或 ``phase`` 描述为 非取模时诊断码为 ``FIELD_SPEC``,宽度不等时为 ``FIELD_WIDTH``,值域证明不了 时为 ``FIELD_RANGE``。 """ if type(program) is not PulseProgramIR: _fail("TYPE", "", "Expected PulseProgramIR.") section = program.classical if section is None: return () types = dict(section.vars) uses = [ ( f"/instructions/{index}/dynamic", item.dynamic.field, item.dynamic.var, item.dynamic.table, item.start_ns, ) for index, item in enumerate(program.instructions) if type(item) is Play and item.dynamic is not None ] # 追踪帧用途的字段为 phase,只能取模、不做值域检查,所以读取时刻不影响结果。 uses += [ (f"/classical/tracked_frames/{index}/1", "phase", var, None, 0) for index, (_, var) in enumerate(section.tracked_frames) ] ranges = _VariableRanges(section) recorded: list[str] = [] for path, field, var, table, at_ns in uses: spec = fields.get(field) if spec is None: _fail("FIELD_SPEC", path, f"Target describes no field {field}.") if field == "phase" and not spec.modular: _fail("FIELD_SPEC", path, "Target must describe field phase as modular.") var_path = path + "/var" if path.endswith("/dynamic") else path kind = types[var] width = 1 if isinstance(kind, BitType) else kind.width if width != spec.width: _fail( "FIELD_WIDTH", var_path, f"Variable {var} has {width} bits, field has {spec.width}." ) if spec.modular: recorded.append(path) continue if field == "amplitude": unit = 1 << (kind.frac_bits if isinstance(kind, FixedType) else 0) limits = (-unit, unit) else: # 余下为 frequency 与 envelope。DynamicParam 保证这两个字段的 table 非空。 limits = (0, len(table or ()) - 1) low, high = ranges.of(var, at_ns) if not limits[0] <= low <= high <= limits[1]: _fail( "FIELD_RANGE", var_path, f"Cannot prove variable {var} in [{limits[0]}, {limits[1]}] for field {field}.", ) return tuple(recorded)
class _VariableRanges: """按可见写入求经典变量的原始整数值域,区间运算全部交给 ``value_range``。 ``ops`` 按 ``at_ns`` 非降序,所以任何读者看见的写入都是 ``ops`` 的一个前缀。 """ def __init__(self, section: ClassicalSection) -> None: self._types = dict(section.vars) self._ops = section.ops self._known: dict[tuple[str, int], tuple[int, int]] = {} def of(self, name: str, at_ns: int) -> tuple[int, int]: """返回 ``Play`` 在 ``at_ns`` 读到的变量 ``name`` 的值域。 ``Play`` 看见 ``at_ns`` 不晚于读取时刻的写入。 """ return self._before(name, sum(1 for op in self._ops if op.at_ns <= at_ns)) def _before(self, name: str, count: int) -> tuple[int, int]: """返回 ``ops`` 前 ``count`` 项执行后变量 ``name`` 的值域。 取其中最后一次写入的值域。没有写入或由 ``ReadFproc`` 写入时取声明全范围。 """ key = (name, count) if key not in self._known: full = value_range(Var(name), {}, self._types) self._known[key] = full for index in range(count - 1, -1, -1): op = self._ops[index] if op.dest != name: continue if isinstance(op, Assign): inputs = {var: self._before(var, index) for var in _expr_names(op.expr)} got = value_range(op.expr, inputs, self._types) self._known[key] = got if full[0] <= got[0] <= got[1] <= full[1] else full break return self._known[key] def _expr_names(expr: ClassicalExpr) -> set[str]: """返回表达式读到的变量名。""" if isinstance(expr, Var): return {expr.name} if isinstance(expr, Not): return _expr_names(expr.operand) if isinstance(expr, Binary): return _expr_names(expr.lhs) | _expr_names(expr.rhs) return set() def _mismatch(code: str, path: str, message: str) -> NoReturn: _fail(code, path, message, "SCHEDULE_MISMATCH") def _check_records( program: PulseProgramIR, schedule: NativeScheduleIR ) -> tuple[dict[int, list[Play]], dict[int, set[str]]]: ops, events = schedule.operations, {e.event_id: e for e in schedule.events} ports = {port.id: port for port in program.ports} frame_ports = {frame.id: ports[frame.port] for frame in program.frames} plays: dict[int, list[Play]] = {} shifts: dict[int, set[str]] = {} acquired: set[str] = set() for index, item in enumerate(program.instructions): path = f"/instructions/{index}" if isinstance(item, Acquire): event = events.get(item.event_id) if event is None: _mismatch("EVENT_REF", path + "/event_id", "Unknown measurement event.") acquired.add(item.event_id) op = ops[event.operation_index] if ports[item.port].targets != op.qubits: _mismatch("TARGET", path + "/port", "Acquire port does not match the qubit.") _check_op(item, op, path) continue if item.source is None or not 0 <= item.source < len(ops): _mismatch("SOURCE", path + "/source", "Expected an operation index of the schedule.") op = ops[item.source] if isinstance(item, Play): if op.kind not in _PULSED: _mismatch( "PLAY_SOURCE", path + "/source", "Play must come from RX90, CZ or MEASURE." ) _check_target(frame_ports[item.frame], op, path + "/frame") plays.setdefault(item.source, []).append(item) elif item.origin == "gate": if op.kind not in _VIRTUAL: _mismatch( "SHIFT_SOURCE", path + "/source", "Gate ShiftPhase must come from Z or RZ." ) if item.at_ns != op.start_ns: _mismatch("TIME", path, "Gate ShiftPhase must occur at the operation start.") theta = math.pi if op.kind == "Z" else op.params[0] if not phases_equal(item.delta_rad, -theta): _mismatch("SHIFT_DELTA", path + "/delta_rad", "Expected delta_rad = -theta.") shifts.setdefault(item.source, set()).add(item.frame) elif op.kind != "CZ": _mismatch("SHIFT_SOURCE", path + "/source", "Correction ShiftPhase must come from CZ.") elif not set(frame_ports[item.frame].targets) <= set(op.qubits): _mismatch("TARGET", path + "/frame", "Correction frame is not on a CZ qubit.") _check_op(item, op, path) if set(events) - acquired: _mismatch("EVENT_MISSING", "/instructions", "A measurement event has no Acquire.") return plays, shifts def _check_target(port: Port, op: NativeOperation, path: str) -> None: """检查单比特目标、flux 子集与两体驱动的精确比特对。""" if op.kind == "CZ" and port.role == "two_body_drive": fits = len(port.targets) == 2 and sorted(port.targets) == sorted(op.qubits) elif op.kind == "CZ": fits = set(port.targets) <= set(op.qubits) else: fits = port.targets == op.qubits if port.role not in _PLAY_ROLES[op.kind] or not fits: _mismatch("TARGET", path, "Play frame does not match the operation qubits and role.") def _check_op(item: Any, op: NativeOperation, path: str) -> None: start = getattr(item, "at_ns", None) if start is None: start, stop = item.start_ns, item.start_ns + item.duration_ns else: stop = start if start < op.start_ns or stop > op.start_ns + op.duration_ns: _mismatch("TIME", path, "Record lies outside its operation.") if item.condition_id != op.condition_id: _mismatch("CONDITION", path + "/condition_id", "Condition differs from the operation.") def _check_coverage( program: PulseProgramIR, schedule: NativeScheduleIR, plays: dict[int, list[Play]], shifts: dict[int, set[str]], ) -> None: ports = {port.id: port for port in program.ports} frame_ports = {frame.id: ports[frame.port] for frame in program.frames} for index, op in enumerate(schedule.operations): if op.kind in _VIRTUAL: drive = { frame for frame, port in frame_ports.items() if port.role == "drive" and port.targets == op.qubits } if shifts.get(index, set()) != drive: _mismatch( "SHIFT_FRAMES", "/instructions", f"Operation {index} misses drive frames." ) elif op.kind in _PULSED and not plays.get(index): _mismatch("PLAY_MISSING", "/instructions", f"Operation {index} has no Play.") if op.kind == "MEASURE": readout = [p for p in plays.get(index, []) if frame_ports[p.frame].role == "readout"] if len(readout) != 1: _mismatch("READOUT", "/instructions", f"Operation {index} needs one readout Play.") def _classical_nodes( schedule: NativeScheduleIR, ) -> list[tuple[str, ClassicalAssignment | ConditionRegion, ClassicalExpr]]: """按源序返回赋值与谓词条件,每项为 ``(L2 路径, 记录, 表达式)``。""" nodes: list[tuple[str, ClassicalAssignment | ConditionRegion, ClassicalExpr]] = [ (f"$.assignments[{i}]", item, item.expr) for i, item in enumerate(schedule.assignments) ] nodes.extend( (f"$.conditions[{i}]", region, region.predicate) for i, region in enumerate(schedule.conditions) if region.predicate is not None ) return sorted(nodes, key=lambda node: node[1].gate_index) def _check_whole_registers(schedule: NativeScheduleIR) -> None: """拒收按名读取多比特寄存器的谓词与赋值,因为 L1 不能把多次测量合成一个字。""" registers = {register.name: register.size for register in schedule.registers} for path, _, expr in _classical_nodes(schedule): for name in sorted(_expr_names(expr)): if _register_bit(name, registers) == (name, None) and registers[name] > 1: # 路径指向 L1 文档,L2 中的位置写在消息里。 _mismatch( "SCHEDULE_CLASSICAL", "/source_schedule_ref", f"L1 cannot represent the read of multi-bit register {name} at {path}.", ) def _check_classical(program: PulseProgramIR, schedule: NativeScheduleIR) -> None: """比较经典段与调度的经典部分。程序没有经典段时,各字段视为空。""" section = program.classical declared = dict(section.vars) if section else {} ops = section.ops if section else () predicates = section.predicates if section else () tracked = section.tracked_frames if section else () numbers: dict[tuple[Any, ...], int] = {} expected: dict[str, int] = {} writes: dict[str, list[tuple[int, int]]] = {} has_features = _has_classical_features(schedule) if has_features: _check_measurement_reads(ops, schedule) _check_sources(ops, schedule) if has_features: _check_variables(declared, schedule) assigned, expected = _schedule_values(schedule, numbers) writes = _section_values(declared, ops, numbers) _check_assignments(assigned, writes, ops) _check_predicates(predicates, schedule, expected, writes, ops) _check_tracked_frames(program, schedule, tracked, declared, ops) def _check_measurement_reads( ops: tuple[ReadFproc | Assign, ...], schedule: NativeScheduleIR ) -> None: # 事件必定存在:程序的构造器要求键有对应的 Acquire,_check_records 要求 Acquire 有对应的事件。 events = {event.event_id: event for event in schedule.events} reads = [ (f"/classical/ops/{i}", op, events[op.fproc.key]) for i, op in enumerate(ops) if isinstance(op, ReadFproc) and op.fproc.kind == "measurement" ] for path, op, event in reads: if op.source != event.operation_index: _mismatch("READ_SOURCE", path + "/source", "Source is not the measured operation.") for path, op, event in reads: if op.at_ns < event.ready_ns: _mismatch("READ_TIME", path + "/at_ns", "Read occurs before the result is ready.") def _check_sources(ops: tuple[ReadFproc | Assign, ...], schedule: NativeScheduleIR) -> None: for i, op in enumerate(ops): if op.source is not None and not 0 <= op.source < len(schedule.operations): _mismatch("SOURCE", f"/classical/ops/{i}/source", "Source is not an L2 operation.") def _check_variables(declared: dict[str, ClassicalType], schedule: NativeScheduleIR) -> None: """有赋值的变量必须声明。没有赋值的变量可以不声明,声明时类型也须相同。""" required = declared.keys() | {item.target for item in schedule.assignments} for variable in schedule.classical_vars: if variable.name in required and declared.get(variable.name) != variable.type: _mismatch( "CLASSICAL_VARS", "/classical/vars", f"Variable {variable.name} is missing or has a different type.", ) def _value_number( expr: ClassicalExpr, numbers: dict[tuple[Any, ...], int], values: Mapping[str, int] ) -> int: """返回表达式的值编号。``values`` 给出各名字当前的编号。相同的键得到相同的编号。""" key: tuple[Any, ...] if isinstance(expr, Var): return values[expr.name] if isinstance(expr, Const): key = ("const", expr.type, expr.value) elif isinstance(expr, Not): key = ("not", _value_number(expr.operand, numbers, values)) else: left = _value_number(expr.lhs, numbers, values) key = ("binary", expr.op, left, _value_number(expr.rhs, numbers, values)) return numbers.setdefault(key, len(numbers)) def _schedule_values( schedule: NativeScheduleIR, numbers: dict[tuple[Any, ...], int] ) -> tuple[dict[str, list[tuple[int, int]]], dict[str, int]]: """返回每个 L2 变量的赋值序列 ``(at_ns, 编号)``,以及每个谓词条件的编号。""" registers = {register.name: register.size for register in schedule.registers} order = {name: i for i, name in enumerate(registers)} assigned: dict[str, list[tuple[int, int]]] = {v.name: [] for v in schedule.classical_vars} # 构造器接受对未赋值变量的读取。L1 没有对应的值,所以这里的键不与 L1 共用。 current = {name: numbers.setdefault(("unset", name), len(numbers)) for name in assigned} predicates: dict[str, int] = {} for _, node, expr in _classical_nodes(schedule): bits = _referenced_bits(expr, registers, order) events = {bit: read.event_id for bit, read in zip(bits, node.reads, strict=True)} values = {} for name in _expr_names(expr): reference = _register_bit(name, registers) if reference is None: values[name] = current[name] else: # 多比特寄存器已被拒收,所以按名读取的寄存器只有 0 号比特。 key = ("event", events[reference[0], reference[1] or 0]) values[name] = numbers.setdefault(key, len(numbers)) number = _value_number(expr, numbers, values) if isinstance(node, ClassicalAssignment): current[node.target] = number assigned[node.target].append((node.at_ns, number)) else: predicates[node.condition_id] = number return assigned, predicates def _section_values( declared: dict[str, ClassicalType], ops: tuple[ReadFproc | Assign, ...], numbers: dict[tuple[Any, ...], int], ) -> dict[str, list[tuple[int, int]]]: """返回每个 L1 变量的写入序列 ``(操作下标, 编号)``。""" current = {name: numbers.setdefault(("initial", name), len(numbers)) for name in declared} writes: dict[str, list[tuple[int, int]]] = {} for index, op in enumerate(ops): if isinstance(op, Assign): number = _value_number(op.expr, numbers, current) else: measured = op.fproc.kind == "measurement" key = ("event", op.fproc.key) if measured else ("read", index) number = numbers.setdefault(key, len(numbers)) current[op.dest] = number writes.setdefault(op.dest, []).append((index, number)) return writes def _check_assignments( assigned: dict[str, list[tuple[int, int]]], writes: dict[str, list[tuple[int, int]]], ops: tuple[ReadFproc | Assign, ...], ) -> None: for name, items in assigned.items(): if [number for _, number in writes.get(name, [])] != [number for _, number in items]: _mismatch( "ASSIGN_VALUE", "/classical/ops", f"Writes of {name} differ from its assignments." ) for name, items in assigned.items(): for (index, _), (at_ns, _) in zip(writes.get(name, []), items, strict=True): if ops[index].at_ns < at_ns: _mismatch( "ASSIGN_TIME", f"/classical/ops/{index}/at_ns", f"Write of {name} occurs before its assignment.", ) def _check_predicates( predicates: tuple[tuple[str, str], ...], schedule: NativeScheduleIR, expected: dict[str, int], writes: dict[str, list[tuple[int, int]]], ops: tuple[ReadFproc | Assign, ...], ) -> None: """检查谓词记录的条件与取值。``expected`` 给出每个谓词条件的编号。""" if {condition_id for condition_id, _ in predicates} != expected.keys(): _mismatch( "PREDICATES", "/classical/predicates", "Records differ from the predicate conditions." ) starts = {region.condition_id: region.start_ns for region in schedule.conditions} for i, (condition_id, name) in enumerate(predicates): # ``ops`` 按时间排序,所以每个变量的写入也按时间排序。 found = writes.get(name, []) seen = bisect_right(found, starts[condition_id], key=lambda write: ops[write[0]].at_ns) if not seen or found[seen - 1][1] != expected[condition_id]: _mismatch( "PREDICATE_VALUE", f"/classical/predicates/{i}/1", f"Variable {name} differs from the predicate of {condition_id}.", ) def _check_tracked_frames( program: PulseProgramIR, schedule: NativeScheduleIR, tracked: tuple[tuple[str, str], ...], declared: dict[str, ClassicalType], ops: tuple[ReadFproc | Assign, ...], ) -> None: """检查追踪帧的集合,再检查相位变量的类型与独占。""" targets = {(qubit,) for qubit in schedule.tracked_qubits} drives = {p.id for p in program.ports if p.role == "drive" and p.targets in targets} frames = {frame.id for frame in program.frames if frame.port in drives} if {frame for frame, _ in tracked} != frames: _mismatch( "TRACKED_FRAMES", "/classical/tracked_frames", "Records differ from the drive frames of the tracked qubits.", ) used = {variable.name for variable in schedule.classical_vars} | {op.dest for op in ops} for i, (_, name) in enumerate(tracked): kind = declared[name] turn = isinstance(kind, FixedType) and kind.width == kind.frac_bits and not kind.signed if not turn or name in used: _mismatch( "TRACKED_VAR", f"/classical/tracked_frames/{i}/1", f"Phase variable {name} has a wrong type, is shared or written, " "or names a schedule variable.", ) used.add(name)