qaiji.core.pulse.model 源代码

# Copyright 2026 Qaiji-IR core developer: Ye Jun <yjmaxpayne@hotmail.com>
# SPDX-License-Identifier: Apache-2.0
"""L1 脉冲层的不可修改记录与程序不变量。

时间为整数 ns,频率为整数 Hz,相位为 rad,幅度为 [-1, 1]。所有记录带绝对时间。
程序在构造时检查全部不变量,解码器经同一构造入口。
"""

from __future__ import annotations

import math
import re
from collections.abc import Callable, Mapping
from dataclasses import dataclass
from typing import Any, ClassVar, Literal, cast

from qaiji.core.classical_expr import (
    Binary,
    BitType,
    ClassicalExpr,
    ClassicalType,
    ClassicalTypeError,
    Const,
    FprocRegister,
    Not,
    Var,
    type_of,
)

from .errors import _fail
from .phase import phases_equal

PULSE_SCHEMA = "qaiji.pulse/0.1"
PULSE_SCHEMA_CLASSICAL = "qaiji.pulse/0.2"
_ROLES = ("drive", "readout", "acquire", "flux", "coupler_flux", "two_body_drive")
_FLUX_ROLES = ("flux", "coupler_flux")
_ORIGINS = ("gate", "correction")
_SHAPES: dict[str, tuple[str, ...]] = {
    "constant": (),
    "gaussian": ("rel_sigma",),
    "drag": ("rel_sigma", "beta_ns"),
}
_DYNAMIC_FIELDS = ("phase", "amplitude", "frequency", "envelope")
_REFERENCE = re.compile(r"sha256:[0-9a-f]{64}\Z")
_INT64 = 1 << 63


def _int(value: Any, path: str, minimum: int, code: str = "INTEGER") -> int:
    if type(value) is not int or not -_INT64 <= value < _INT64:
        _fail("INTEGER", path, "Expected a signed64 integer.")
    if value < minimum:
        _fail(code, path, f"Expected an integer of at least {minimum}.")
    return cast(int, value)


def _real(value: Any, path: str) -> float:
    if type(value) not in (int, float):
        _fail("NUMBER", path, "Expected a real number.")
    try:
        result = float(value)
    except OverflowError:
        _fail("NONFINITE", path, "Number exceeds binary64 range.")
    if not math.isfinite(result):
        _fail("NONFINITE", path, "Expected a finite number.")
    return result


def _text(value: Any, path: str) -> str:
    if type(value) is not str or not value:
        _fail("TEXT", path, "Expected nonempty text.")
    try:
        value.encode("utf-8")
    except UnicodeEncodeError:
        _fail("UNICODE", path, "Expected Unicode scalar values.")
    return cast(str, value)


def _choice(value: Any, options: tuple[str, ...], path: str, code: str) -> str:
    if type(value) is not str or value not in options:
        _fail(code, path, "Expected one of: " + ", ".join(options) + ".")
    return cast(str, value)


def _optional(value: Any, check: Callable[[Any, str], Any], path: str) -> None:
    if value is not None:
        check(value, path)


def _sequence(value: Any, path: str) -> tuple[Any, ...]:
    if type(value) not in (list, tuple):
        _fail("TYPE", path, "Expected a list or tuple.")
    return tuple(value)


def _set(obj: Any, name: str, value: Any) -> None:
    object.__setattr__(obj, name, value)


[文档] @dataclass(frozen=True, slots=True, kw_only=True) class Port: """物理信号端口。``targets`` 是端口作用的比特,非空且互不相同。""" id: str role: Literal["drive", "readout", "acquire", "flux", "coupler_flux", "two_body_drive"] targets: tuple[int, ...] __hash__: ClassVar[Any] = None def __post_init__(self) -> None: _text(self.id, "/id") _choice(self.role, _ROLES, "/role", "ROLE") targets = self.targets if ( type(targets) not in (list, tuple) or not targets or any(type(q) is not int or not 0 <= q < _INT64 for q in targets) or len(set(targets)) != len(targets) ): _fail("TARGETS", "/targets", "Expected nonempty, distinct, nonnegative qubits.") _set(self, "targets", tuple(targets))
[文档] @dataclass(frozen=True, slots=True, kw_only=True) class Frame: """端口上的载波帧。``phase_rad`` 是程序时间 0 的帧相位。""" id: str port: str frequency_hz: int phase_rad: float __hash__: ClassVar[Any] = None def __post_init__(self) -> None: _text(self.id, "/id") _text(self.port, "/port") _int(self.frequency_hz, "/frequency_hz", -_INT64) _set(self, "phase_rad", _real(self.phase_rad, "/phase_rad"))
[文档] @dataclass(frozen=True, slots=True, kw_only=True) class Envelope: """连续时间包络。``constant`` 无参数,``gaussian`` 需 ``rel_sigma``,``drag`` 另需 ``beta_ns``。""" shape: Literal["constant", "gaussian", "drag"] rel_sigma: float | None = None beta_ns: float | None = None __hash__: ClassVar[Any] = None def __post_init__(self) -> None: shape = _choice(self.shape, tuple(_SHAPES), "/shape", "ENVELOPE") for name in ("rel_sigma", "beta_ns"): value = getattr(self, name) if (name in _SHAPES[shape]) != (value is not None): _fail("ENVELOPE", "/" + name, f"Field does not match envelope shape {shape}.") if value is not None: _set(self, name, _real(value, "/" + name)) if self.rel_sigma is not None and self.rel_sigma <= 0: _fail("ENVELOPE", "/rel_sigma", "Expected a positive rel_sigma.")
[文档] @dataclass(frozen=True, slots=True, kw_only=True) class Play: """在帧上播放一个包络。``phase_rad`` 相对于帧,载波相位由帧给出。 ``dynamic`` 为至多一个动态参数,追踪帧上的 ``Play`` 不得带它。 """ frame: str start_ns: int duration_ns: int envelope: Envelope amplitude: float phase_rad: float condition_id: str | None = None source: int | None = None dynamic: DynamicParam | None = None __hash__: ClassVar[Any] = None def __post_init__(self) -> None: _text(self.frame, "/frame") _int(self.start_ns, "/start_ns", 0, "TIME") _int(self.duration_ns, "/duration_ns", 1, "DURATION") if type(self.envelope) is not Envelope: _fail("TYPE", "/envelope", "Expected Envelope.") amplitude = _real(self.amplitude, "/amplitude") if not -1.0 <= amplitude <= 1.0: _fail("AMPLITUDE", "/amplitude", "Expected an amplitude in [-1, 1].") _set(self, "amplitude", amplitude) _set(self, "phase_rad", _real(self.phase_rad, "/phase_rad")) _optional(self.condition_id, _text, "/condition_id") _optional(self.source, lambda value, path: _int(value, path, 0), "/source") if self.dynamic is not None and type(self.dynamic) is not DynamicParam: _fail("TYPE", "/dynamic", "Expected DynamicParam.")
[文档] @dataclass(frozen=True, slots=True, kw_only=True) class ShiftPhase: """零时长的帧相位增量。``gate`` 来自 L2 的 Z、RZ,``correction`` 来自两比特门。""" frame: str at_ns: int delta_rad: float origin: Literal["gate", "correction"] condition_id: str | None = None source: int | None = None __hash__: ClassVar[Any] = None def __post_init__(self) -> None: _text(self.frame, "/frame") _int(self.at_ns, "/at_ns", 0, "TIME") _set(self, "delta_rad", _real(self.delta_rad, "/delta_rad")) _choice(self.origin, _ORIGINS, "/origin", "ORIGIN") _optional(self.condition_id, _text, "/condition_id") _optional(self.source, lambda value, path: _int(value, path, 0), "/source")
[文档] @dataclass(frozen=True, slots=True, kw_only=True) class Acquire: """在 acquire 端口上采集一个 L2 测量事件。""" port: str start_ns: int duration_ns: int event_id: str condition_id: str | None = None __hash__: ClassVar[Any] = None def __post_init__(self) -> None: _text(self.port, "/port") _int(self.start_ns, "/start_ns", 0, "TIME") _int(self.duration_ns, "/duration_ns", 1, "DURATION") _text(self.event_id, "/event_id") _optional(self.condition_id, _text, "/condition_id")
[文档] @dataclass(frozen=True, slots=True, kw_only=True) class DynamicParam: """``Play`` 的一个动态参数,取值来自经典变量 ``var``。 ``frequency`` 与 ``envelope`` 的变量值是 ``table`` 的下标,``table`` 分别为整数 Hz 频率序列与 ``Envelope`` 序列。``phase`` 与 ``amplitude`` 不带 ``table``。 Raises: PulseContractError: ``field`` 不合法,或 ``table`` 与 ``field`` 不匹配,类别为 ``INVALID_PROGRAM``,诊断码 ``DYNAMIC_PARAM``。 """ field: Literal["phase", "amplitude", "frequency", "envelope"] var: str table: tuple[int, ...] | tuple[Envelope, ...] | None = None __hash__: ClassVar[Any] = None def __post_init__(self) -> None: field = _choice(self.field, _DYNAMIC_FIELDS, "/field", "DYNAMIC_PARAM") _text(self.var, "/var") if field in ("phase", "amplitude"): if self.table is not None: _fail("DYNAMIC_PARAM", "/table", f"Field {field} takes no table.") return if self.table is None or type(self.table) not in (list, tuple) or not self.table: _fail("DYNAMIC_PARAM", "/table", f"Field {field} needs a nonempty table.") table = tuple(self.table) for index, item in enumerate(table): if field == "frequency": if type(item) is not int: _fail("DYNAMIC_PARAM", "/table", "Frequency tables hold integer Hz.") _int(item, f"/table/{index}", -_INT64) elif type(item) is not Envelope: _fail("DYNAMIC_PARAM", "/table", "Envelope tables hold Envelope records.") _set(self, "table", table)
[文档] @dataclass(frozen=True, slots=True, kw_only=True) class ReadFproc: """在 ``at_ns`` 把反馈处理器寄存器的值读入变量 ``dest``。 ``at_ns`` 是值可用的最早时刻。``source`` 的含义与 ``Play.source`` 相同。 """ at_ns: int dest: str fproc: FprocRegister source: int | None = None __hash__: ClassVar[Any] = None def __post_init__(self) -> None: _int(self.at_ns, "/at_ns", 0, "TIME") _text(self.dest, "/dest") if type(self.fproc) is not FprocRegister: _fail("TYPE", "/fproc", "Expected FprocRegister.") _optional(self.source, lambda value, path: _int(value, path, 0), "/source")
[文档] @dataclass(frozen=True, slots=True, kw_only=True) class Assign: """在 ``at_ns`` 把经典表达式 ``expr`` 的值写入变量 ``dest``。 ``at_ns`` 是值可用的最早时刻。``source`` 的含义与 ``Play.source`` 相同。 """ at_ns: int dest: str expr: ClassicalExpr source: int | None = None __hash__: ClassVar[Any] = None def __post_init__(self) -> None: _int(self.at_ns, "/at_ns", 0, "TIME") _text(self.dest, "/dest") _expr_vars(self.expr, "/expr") _optional(self.source, lambda value, path: _int(value, path, 0), "/source")
[文档] @dataclass(frozen=True, slots=True, kw_only=True) class ClassicalSection: """L1 程序的经典段:变量声明、经典操作、追踪帧与谓词绑定。 ``vars`` 为 ``(name, type)``,``tracked_frames`` 为 ``(frame_id, 相位变量)``, ``predicates`` 为 ``(condition_id, 位变量)``,三者都按首项严格递增。``ops`` 按 ``at_ns`` 非降序,同刻保持给定顺序。读者看见的写入为列表中排在它前面的写入。 ``Assign.at_ns`` 不得早于它读的变量在此前最后一次写入的 ``at_ns``。 Raises: PulseContractError: 段为空(``NON_CANONICAL``)、引用未声明变量 (``UNDECLARED_VAR``)、``Assign`` 早于输入(``CLASSICAL_ORDER``)、``ops`` 未按 时间排序(``ORDER``)、写入值类型不等于 ``dest`` 类型或谓词变量不是比特 (``CLASSICAL_TYPE``),或记录不合法。 """ vars: tuple[tuple[str, ClassicalType], ...] ops: tuple[ReadFproc | Assign, ...] tracked_frames: tuple[tuple[str, str], ...] predicates: tuple[tuple[str, str], ...] __hash__: ClassVar[Any] = None def __post_init__(self) -> None: declared = _pairs(self.vars, "/vars", lambda value, path: _var_type(value, path)) ops = _sequence(self.ops, "/ops") tracked = _pairs(self.tracked_frames, "/tracked_frames", _text) predicates = _pairs(self.predicates, "/predicates", _text) if not (declared or ops or tracked or predicates): _fail("NON_CANONICAL", "", "Empty classical sections are not canonical.") types = dict(declared) names = set(types) ready: dict[str, int] = {} for index, op in enumerate(ops): path = f"/ops/{index}" if type(op) not in (ReadFproc, Assign): _fail("TYPE", path, "Expected ReadFproc or Assign.") if type(op) is Assign: for name in _expr_vars(op.expr, path + "/expr"): _declared(name, names, path + "/expr") if op.at_ns < ready.get(name, 0): _fail( "CLASSICAL_ORDER", path + "/at_ns", f"Assign reads {name} before it is available.", ) # 列表顺序即时间顺序,读者看见的写入恰为列在它前面的写入。 if index and op.at_ns < ops[index - 1].at_ns: _fail("ORDER", path + "/at_ns", "Classical ops must be sorted by at_ns.") _declared(op.dest, names, path + "/dest") _check_op_type(op, types, path) ready[op.dest] = op.at_ns for field, pairs in (("tracked_frames", tracked), ("predicates", predicates)): for index, (_, name) in enumerate(pairs): _declared(name, names, f"/{field}/{index}/1") if field == "predicates" and not isinstance(types[name], BitType): _fail( "CLASSICAL_TYPE", f"/predicates/{index}/1", f"Predicate variable {name} must be a bit.", ) _set(self, "vars", declared) _set(self, "ops", ops) _set(self, "tracked_frames", tracked) _set(self, "predicates", predicates)
def _check_op_type(op: ReadFproc | Assign, types: Mapping[str, ClassicalType], path: str) -> None: """经典操作写入值的类型必须等于 ``dest`` 的声明类型;测量结果是比特。""" dest = types[op.dest] if type(op) is ReadFproc: if op.fproc.kind == "measurement" and not isinstance(dest, BitType): _fail("CLASSICAL_TYPE", path + "/dest", f"Measurement reads need a bit, got {dest}.") return try: got = type_of(cast(Assign, op).expr, types) except ClassicalTypeError as error: _fail("CLASSICAL_TYPE", path + "/expr", f"{error}.") if got != dest: _fail("CLASSICAL_TYPE", path + "/expr", f"Expression has type {got}, {op.dest} has {dest}.") def _var_type(value: Any, path: str) -> None: if not isinstance(value, ClassicalType): _fail("TYPE", path, "Expected BitType, FixedType or TimeType.") def _pairs(value: Any, path: str, check: Callable[[Any, str], Any]) -> tuple[tuple[str, Any], ...]: """检查 ``(键, 值)`` 序列:键为非空文本且严格递增,值由 ``check`` 检查。""" result: list[tuple[str, Any]] = [] for index, item in enumerate(_sequence(value, path)): item_path = f"{path}/{index}" if type(item) not in (list, tuple) or len(item) != 2: _fail("TYPE", item_path, "Expected a pair.") key = _text(item[0], item_path + "/0") check(item[1], item_path + "/1") if result and key <= result[-1][0]: _fail("ORDER", item_path, "Keys must be unique and sorted.") result.append((key, item[1])) return tuple(result) def _expr_vars(expr: Any, path: str) -> tuple[str, ...]: """返回表达式读的变量名(按出现顺序)。 节点不是经典表达式时报 ``TYPE``。常量超出交换格式的 signed64 整数时报 ``INTEGER``, 使编码结果总能被解码。 """ match expr: case Const(): _int(expr.value, path, -_INT64) return () case Var(): return (_text(expr.name, path),) case Not(): return _expr_vars(expr.operand, path) case Binary(): return _expr_vars(expr.lhs, path) + _expr_vars(expr.rhs, path) _fail("TYPE", path, "Expected a classical expression.") def _declared(name: str, names: set[str], path: str) -> None: if name not in names: _fail("UNDECLARED_VAR", path, f"Variable {name} is not declared.") type Instruction = Play | ShiftPhase | Acquire _RANK: dict[type, int] = {ShiftPhase: 0, Play: 1, Acquire: 2}
[文档] @dataclass(frozen=True, slots=True, kw_only=True) class PulseProgramIR: """L1 脉冲程序。构造时检查全部不变量。 ``conditions`` 镜像 L2 的条件区间,顺序与 L2 相同,每项为 ``(condition_id, start_ns, end_ns)``。 ``instructions`` 按 ``(时刻, 帧或端口, 种类, source)`` 严格递增:同刻同帧的 ``ShiftPhase`` 排在 ``Play`` 前,``source`` 为 None 时排在前。 Raises: PulseContractError: 记录或不变量不合法,类别为 ``INVALID_PROGRAM``。 """ source_schedule_ref: str ports: tuple[Port, ...] frames: tuple[Frame, ...] instructions: tuple[Instruction, ...] conditions: tuple[tuple[str, int, int], ...] end_ns: int schema: str = PULSE_SCHEMA classical: ClassicalSection | None = None __hash__: ClassVar[Any] = None def __post_init__(self) -> None: if self.schema not in (PULSE_SCHEMA, PULSE_SCHEMA_CLASSICAL): _fail( "SCHEMA", "/schema", f"Expected schema {PULSE_SCHEMA} or {PULSE_SCHEMA_CLASSICAL}." ) ref = self.source_schedule_ref if type(ref) is not str or not _REFERENCE.fullmatch(ref): _fail("REFERENCE", "/source_schedule_ref", "Expected a lowercase sha256 reference.") end = _int(self.end_ns, "/end_ns", 0, "TIME") ports = _declarations(self.ports, Port, "/ports") frames = _declarations(self.frames, Frame, "/frames") roles = {port.id: port.role for port in ports} frame_roles: dict[str, str] = {} for index, frame in enumerate(frames): if frame.port not in roles: _fail("PORT_REF", f"/frames/{index}/port", "Undeclared port.") if roles[frame.port] in _FLUX_ROLES and frame.frequency_hz != 0: _fail("FREQUENCY", f"/frames/{index}/frequency_hz", "Flux frames have frequency 0.") frame_roles[frame.id] = roles[frame.port] conditions, windows = _conditions(self.conditions, end) instructions = _sequence(self.instructions, "/instructions") _check_instructions(instructions, roles, frame_roles, windows, end) _check_condition_phase(instructions, conditions, self.classical) _check_classical(self.classical, instructions, frame_roles, windows) _set(self, "ports", ports) _set(self, "frames", frames) _set(self, "conditions", conditions) _set(self, "instructions", instructions) expected = _schema_literal(self) if self.schema != expected: if self.schema == PULSE_SCHEMA_CLASSICAL: _fail( "NON_CANONICAL", "/schema", f"Programs without classical features use {PULSE_SCHEMA}.", ) _fail("SCHEMA", "/schema", f"Programs with classical features use {expected}.")
def _has_classical_features(program: PulseProgramIR) -> bool: """判定程序是否含经典特性。这是选择 schema 字面量的唯一判定。 编码器选字面量与构造入口(解码器经它)的字面量检查都经 ``_schema_literal`` 调用本函数。 程序带经典段,或任一 ``Play`` 带动态参数时为真。构造器拒收全空段与未引用变量, 所以这与「段内至少 1 条操作、追踪帧或谓词绑定,或至少 1 个动态参数」等价。 """ return program.classical is not None or any( type(item) is Play and item.dynamic is not None for item in program.instructions ) def _schema_literal(program: PulseProgramIR) -> str: """按经典特性返回程序的规范 schema 字面量。""" return PULSE_SCHEMA_CLASSICAL if _has_classical_features(program) else PULSE_SCHEMA def _declarations[T](value: Any, cls: type[T], path: str) -> tuple[T, ...]: items = _sequence(value, path) for index, item in enumerate(items): if type(item) is not cls: _fail("TYPE", f"{path}/{index}", f"Expected {cls.__name__}.") if index and item.id <= items[index - 1].id: # type: ignore[attr-defined] _fail("ORDER", f"{path}/{index}", "Ids must be unique and sorted.") return items def _conditions( value: Any, end: int ) -> tuple[tuple[tuple[str, int, int], ...], dict[str, tuple[int, int]]]: windows: dict[str, tuple[int, int]] = {} result: list[tuple[str, int, int]] = [] for index, item in enumerate(_sequence(value, "/conditions")): path = f"/conditions/{index}" if type(item) not in (list, tuple) or len(item) != 3: _fail("CONDITION", path, "Expected (condition_id, start_ns, end_ns).") cid = _text(item[0], path + "/condition_id") start = _int(item[1], path + "/start_ns", 0, "TIME") stop = _int(item[2], path + "/end_ns", 0, "TIME") if not start <= stop <= end: _fail("CONDITION", path, "Expected start_ns <= end_ns <= program end_ns.") if cid in windows: _fail("CONDITION", path, "Condition ids must be unique.") windows[cid] = (start, stop) result.append((cid, start, stop)) return tuple(result), windows def _check_instructions( items: tuple[Any, ...], roles: Mapping[str, str], frame_roles: Mapping[str, str], windows: dict[str, tuple[int, int]], end: int, ) -> None: events: set[str] = set() previous: tuple[int, str, int, int] | None = None for index, item in enumerate(items): path = f"/instructions/{index}" kind = type(item) if kind not in _RANK: _fail("TYPE", path, "Expected Play, ShiftPhase or Acquire.") if kind is Acquire: target = item.port if target not in roles: _fail("PORT_REF", path + "/port", "Undeclared port.") if roles[target] != "acquire": _fail("ACQUIRE_PORT", path + "/port", "Acquire needs an acquire port.") if item.event_id in events: _fail("EVENT", path + "/event_id", "Acquire event ids must be unique.") events.add(item.event_id) else: target = item.frame if target not in frame_roles: _fail("FRAME_REF", path + "/frame", "Undeclared frame.") if kind is ShiftPhase and frame_roles[target] != "drive": _fail("SHIFT_PORT", path + "/frame", "ShiftPhase must act on a drive frame.") start = item.at_ns if kind is ShiftPhase else item.start_ns stop = start if kind is ShiftPhase else start + item.duration_ns condition = item.condition_id if condition is not None and condition not in windows: _fail("CONDITION_REF", path + "/condition_id", "Undeclared condition.") if stop > end: _fail("END", path, "Instruction ends after the program end_ns.") if ( condition is not None and not windows[condition][0] <= start <= stop <= windows[condition][1] ): _fail("WINDOW", path, "Conditional instruction lies outside its condition region.") source = getattr(item, "source", None) key = (start, target, _RANK[kind], -1 if source is None else source) if previous is not None and key <= previous: _fail( "ORDER", path, "Instructions must be strictly sorted by (time, target, kind, source).", ) previous = key def _check_classical( section: Any, items: tuple[Any, ...], frame_roles: Mapping[str, str], windows: Mapping[str, tuple[int, int]], ) -> None: """检查经典段与指令、帧、条件、采集事件之间的引用,以及变量是否都被引用。""" if section is not None and type(section) is not ClassicalSection: _fail("TYPE", "/classical", "Expected ClassicalSection.") names = {name for name, _ in section.vars} if section is not None else set() used: set[str] = set() tracked = {frame for frame, _ in section.tracked_frames} if section is not None else set() events = {item.event_id for item in items if type(item) is Acquire} for index, item in enumerate(items): if type(item) is not Play or item.dynamic is None: continue path = f"/instructions/{index}/dynamic" _declared(item.dynamic.var, names, path + "/var") if item.frame in tracked: _fail("DYNAMIC_PARAM", path, "Plays on tracked frames take no dynamic parameter.") used.add(item.dynamic.var) if section is None: return for index, op in enumerate(section.ops): used.add(op.dest) if isinstance(op, Assign): used.update(_expr_vars(op.expr, "")) elif op.fproc.kind == "measurement" and op.fproc.key not in events: _fail( "FPROC_SOURCE", f"/classical/ops/{index}/fproc", f"No Acquire has event id {op.fproc.key}.", ) for field, targets, code in ( ("tracked_frames", frame_roles, "FRAME_REF"), ("predicates", windows, "CONDITION_REF"), ): for index, (key, name) in enumerate(getattr(section, field)): if key not in targets: _fail(code, f"/classical/{field}/{index}/0", f"Undeclared target {key}.") used.add(name) for index, (name, _) in enumerate(section.vars): if name not in used: _fail("UNUSED_VAR", f"/classical/vars/{index}", f"Variable {name} is never used.") def _check_condition_phase( items: tuple[Any, ...], conditions: tuple[tuple[str, int, int], ...], section: Any ) -> None: """每个条件区间内,每个未追踪帧上条件 ShiftPhase 的和按 2π 取模为 0。 追踪帧上的条件 ShiftPhase 在条件成立时把增量加到帧变量,净值可以非零。 ``section`` 不是 ``ClassicalSection`` 时按无追踪帧处理,类型错误由经典段检查报告。 """ tracked = ( {frame for frame, _ in section.tracked_frames} if type(section) is ClassicalSection else set() ) sums: dict[tuple[str, str], list[float]] = {} for item in items: if type(item) is ShiftPhase and item.condition_id is not None and item.frame not in tracked: sums.setdefault((item.condition_id, item.frame), []).append(item.delta_rad) for index, (cid, _, _) in enumerate(conditions): for (condition, frame), deltas in sorted(sums.items()): if condition == cid and not phases_equal(math.fsum(deltas), 0.0): _fail( "CONDITION_PHASE", f"/conditions/{index}", f"Net frame phase on {frame} is not a multiple of 2*pi.", )