qaiji.core.pulse.codec 源代码

# Copyright 2026 Qaiji-IR core developer: Ye Jun <yjmaxpayne@hotmail.com>
# SPDX-License-Identifier: Apache-2.0
"""L1 程序的严格编解码、内容身份与 L2 调度引用。

编码沿用 P 层规则:输入为 UTF-8 字节,f64 为 16 位小写大端十六进制,JSON 数只能是
signed64 整数,键集精确,拒收重复键。编码叶原语来自 ``qaiji.core._codec``。

``qaiji.pulse/0.2`` 文档在根上多一个 ``classical`` 段,每条 ``play`` 多一个 ``dynamic`` 键。
经典类型、表达式与经典操作都是带 ``kind`` 标签的对象,类型带全部字段,往返精确重现。
"""

from __future__ import annotations

import math
from typing import Any, cast

from qaiji.core._codec import (
    CodecFault,
    canonical_json,
    f64_from_hex,
    f64_to_hex,
    parse_json,
    sha256_ref,
)
from qaiji.core._codec import json_pointer as _at
from qaiji.core.classical_expr import (
    Binary,
    BitType,
    Const,
    FixedType,
    FprocRegister,
    Not,
    TimeType,
    Var,
)
from qaiji.core.native import NativeScheduleIR

from .errors import PulseContractError, _fail
from .model import (
    _SHAPES,
    PULSE_SCHEMA_CLASSICAL,
    Acquire,
    Assign,
    ClassicalSection,
    DynamicParam,
    Envelope,
    Frame,
    Play,
    Port,
    PulseProgramIR,
    ReadFproc,
    ShiftPhase,
    _schema_literal,
)

_ROOT = (
    "schema",
    "source_schedule_ref",
    "ports",
    "frames",
    "instructions",
    "conditions",
    "end_ns",
)
# 每种字面量要求自己的精确根键集。未知字面量按 0.1 键集检查,再由构造入口报 SCHEMA。
_ROOT_CLASSICAL = (*_ROOT, "classical")
_CONDITION = ("condition_id", "start_ns", "end_ns")
# 字段表。值为字段种类:"f64" 编码为十六进制;"envelope" 为包络对象;"int"、"bool" 原样编码,
# 解码时先查 JSON 类型;"type"、"expr" 为带标签的经典类型与表达式;"fproc"、"dynamic" 为
# 嵌套记录;"table" 为整数或包络对象数组;"raw" 原样编码。
_FIELDS: dict[type, dict[str, str]] = {
    Port: dict(id="raw", role="raw", targets="raw"),
    Frame: dict(id="raw", port="raw", frequency_hz="raw", phase_rad="f64"),
    Play: dict(
        frame="raw",
        start_ns="raw",
        duration_ns="raw",
        envelope="envelope",
        amplitude="f64",
        phase_rad="f64",
        condition_id="raw",
        source="raw",
    ),
    ShiftPhase: dict(
        frame="raw", at_ns="raw", delta_rad="f64", origin="raw", condition_id="raw", source="raw"
    ),
    Acquire: dict(
        port="raw", start_ns="raw", duration_ns="raw", event_id="raw", condition_id="raw"
    ),
    BitType: {},
    FixedType: dict(width="int", frac_bits="int", signed="bool"),
    TimeType: dict(width="int"),
    Const: dict(value="int", type="type"),
    Var: dict(name="raw"),
    Not: dict(operand="expr"),
    Binary: dict(op="raw", lhs="expr", rhs="expr"),
    FprocRegister: dict(kind="raw", key="raw"),
    ReadFproc: dict(at_ns="raw", dest="raw", fproc="fproc", source="raw"),
    Assign: dict(at_ns="raw", dest="raw", expr="expr", source="raw"),
    DynamicParam: dict(field="raw", var="raw", table="table"),
}
# 0.2 文档的字段表:只有 Play 多一个 dynamic 字段,0.1 的字段集保持不变。
_FIELDS_CLASSICAL = {**_FIELDS, Play: {**_FIELDS[Play], "dynamic": "dynamic"}}
_KINDS: dict[str, type] = {"play": Play, "shift_phase": ShiftPhase, "acquire": Acquire}
_TYPE_KINDS: dict[str, type] = {"bit": BitType, "fixed": FixedType, "time": TimeType}
_EXPR_KINDS: dict[str, type] = {"const": Const, "var": Var, "not": Not, "binary": Binary}
_OP_KINDS: dict[str, type] = {"read_fproc": ReadFproc, "assign": Assign}
_TAGS = {
    cls: name
    for kinds in (_KINDS, _TYPE_KINDS, _EXPR_KINDS, _OP_KINDS)
    for name, cls in kinds.items()
}
# 经典段的成对字段:JSON 对象的两个键名与第二项的字段种类。
_PAIRS = {
    "vars": ("name", "type", "type"),
    "tracked_frames": ("frame", "var", "raw"),
    "predicates": ("condition_id", "var", "raw"),
}
# 这些记录的构造器抛 ValueError 或 TypeError,解码器把它们转为诊断。
_EXPR_RECORDS = frozenset((*_TYPE_KINDS.values(), *_EXPR_KINDS.values(), FprocRegister))


[文档] def dump_pulse_program(program: PulseProgramIR) -> bytes: """编码 L1 程序的规范字节。 Args: program: 待编码的程序。 Returns: 规范 JSON 的 UTF-8 字节:键排序、无空白、f64 为十六进制。 Raises: PulseContractError: ``program`` 不是 ``PulseProgramIR``(``TYPE``)。 """ if type(program) is not PulseProgramIR: _fail("TYPE", "", "Expected PulseProgramIR.") schema = _schema_literal(program) fields = _FIELDS_CLASSICAL if schema == PULSE_SCHEMA_CLASSICAL else _FIELDS tree = dict( schema=schema, source_schedule_ref=program.source_schedule_ref, end_ns=program.end_ns, ports=[_encode(port) for port in program.ports], frames=[_encode(frame) for frame in program.frames], conditions=[dict(zip(_CONDITION, item, strict=True)) for item in program.conditions], instructions=[_tagged_encode(item, fields) for item in program.instructions], ) if schema == PULSE_SCHEMA_CLASSICAL: tree["classical"] = _encode_section(program.classical) return canonical_json(tree)
[文档] def pulse_program_id(program: PulseProgramIR) -> str: """计算 L1 程序的内容身份:``sha256(schema + b"\\0" + 规范字节)``。 Args: program: 待计算身份的程序。 Returns: 带 ``sha256:`` 前缀的小写摘要。 Raises: PulseContractError: ``program`` 不是 ``PulseProgramIR``(``TYPE``)。 """ content = dump_pulse_program(program) return sha256_ref(program.schema.encode("utf-8") + b"\0" + content)
[文档] def native_schedule_ref(schedule: NativeScheduleIR) -> str: """计算 L2 调度的引用:``sha256(schema_version + b"\\0" + to_json() 字节)``。 L1 程序的 ``source_schedule_ref`` 取该值。``check_pulse_program`` 检查二者相等。 Args: schedule: L2 原生调度。 Returns: 带 ``sha256:`` 前缀的小写摘要。 Raises: PulseContractError: ``schedule`` 不是 ``NativeScheduleIR``(``TYPE``)。 """ if type(schedule) is not NativeScheduleIR: _fail("TYPE", "", "Expected NativeScheduleIR.") content = schedule.to_json().encode("utf-8") return sha256_ref(schedule.schema_version.encode("utf-8") + b"\0" + content)
[文档] def load_pulse_program(data: bytes) -> PulseProgramIR: """严格解码 L1 程序,并经构造入口检查全部不变量。 Args: data: 规范或非规范的 UTF-8 JSON 字节。 Returns: 解码得到的程序。 Raises: PulseContractError: 字节、键集、数值编码、记录或不变量不合法。诊断路径为 JSON Pointer。 """ root = _object(_parse(data), "") classical = root.get("schema") == PULSE_SCHEMA_CLASSICAL _keys(root, _ROOT_CLASSICAL if classical else _ROOT, "") fields = _FIELDS_CLASSICAL if classical else _FIELDS conditions = [] for index, item in enumerate(_array(root["conditions"], "/conditions")): path = _at("/conditions", index) obj = _object(item, path) _keys(obj, _CONDITION, path) conditions.append(tuple(obj[name] for name in _CONDITION)) instructions = [ _tagged(item, _KINDS, _at("/instructions", index), fields) for index, item in enumerate(_array(root["instructions"], "/instructions")) ] values = dict( schema=root["schema"], source_schedule_ref=root["source_schedule_ref"], ports=[ _record(item, Port, _at("/ports", i)) for i, item in enumerate(_array(root["ports"], "/ports")) ], frames=[ _record(item, Frame, _at("/frames", i)) for i, item in enumerate(_array(root["frames"], "/frames")) ], instructions=instructions, conditions=conditions, end_ns=root["end_ns"], ) if classical: # null 段解码为 None,由构造入口经特性判定拒收;解码器不另设判定。 section = root["classical"] values["classical"] = None if section is None else _section(section, "/classical") return cast(PulseProgramIR, _construct(PulseProgramIR, values, ""))
def _encode(record: Any, fields: dict[type, dict[str, str]] = _FIELDS) -> dict[str, Any]: return { name: _encode_value(kind, getattr(record, name)) for name, kind in fields[type(record)].items() } def _tagged_encode(record: Any, fields: dict[type, dict[str, str]] = _FIELDS) -> dict[str, Any]: return {"kind": _TAGS[type(record)], **_encode(record, fields)} def _encode_value(kind: str, value: Any) -> Any: if kind == "f64": return f64_to_hex(value) if kind == "envelope": return {"shape": value.shape} | { field: f64_to_hex(getattr(value, field)) for field in _SHAPES[value.shape] } if value is None: return None if kind in ("type", "expr"): return _tagged_encode(value) if kind in ("fproc", "dynamic"): return _encode(value) if kind == "table": return [ _encode_value("envelope" if type(item) is Envelope else "raw", item) for item in value ] return list(value) if type(value) is tuple else value def _encode_section(section: ClassicalSection | None) -> dict[str, Any] | None: if section is None: return None tree: dict[str, Any] = {"ops": [_tagged_encode(op) for op in section.ops]} for name, (first, second, kind) in _PAIRS.items(): tree[name] = [ {first: key, second: _encode_value(kind, value)} for key, value in getattr(section, name) ] return tree def _section(value: Any, path: str) -> ClassicalSection: obj = _object(value, path) _keys(obj, ("ops", *_PAIRS), path) ops_path = _at(path, "ops") values: dict[str, Any] = { "ops": [ _tagged(item, _OP_KINDS, _at(ops_path, index)) for index, item in enumerate(_array(obj["ops"], ops_path)) ] } for name, (first, second, kind) in _PAIRS.items(): field_path = _at(path, name) pairs = [] for index, item in enumerate(_array(obj[name], field_path)): item_path = _at(field_path, index) entry = _object(item, item_path) _keys(entry, (first, second), item_path) pairs.append((entry[first], _decode_value(kind, entry[second], _at(item_path, second)))) values[name] = pairs return cast(ClassicalSection, _construct(ClassicalSection, values, path)) def _parse(data: Any) -> Any: try: return parse_json(data) except CodecFault as fault: _fail(fault.code, fault.path, fault.message) def _object(value: Any, path: str) -> dict[str, Any]: if type(value) is not dict: _fail("JSON_TYPE", path, "Expected an object.") return cast(dict[str, Any], value) def _array(value: Any, path: str) -> list[Any]: if type(value) is not list: _fail("JSON_TYPE", path, "Expected an array.") return cast(list[Any], value) def _keys(value: dict[str, Any], expected: tuple[str, ...], path: str) -> None: if set(value) != set(expected): _fail("KEYS", path, "Fields do not match the declared record.") def _f64(value: Any, path: str) -> float: number = f64_from_hex(value) if number is None: _fail("BINARY64", path, "Expected 16 lowercase hexadecimal digits.") if not math.isfinite(number): _fail("NONFINITE", path, "Expected finite binary64.") return number def _envelope(value: Any, path: str) -> Envelope: obj = _object(value, path) shape = obj.get("shape") if type(shape) is not str or shape not in _SHAPES: _fail("ENVELOPE", _at(path, "shape"), "Unknown envelope shape.") _keys(obj, ("shape", *_SHAPES[shape]), path) values = {"shape": shape} | {name: _f64(obj[name], _at(path, name)) for name in _SHAPES[shape]} return cast(Envelope, _construct(Envelope, values, path)) def _record(value: Any, cls: type, path: str, fields: dict[type, dict[str, str]] = _FIELDS) -> Any: obj = _object(value, path) table = fields[cls] _keys(obj, tuple(table), path) values = {name: _decode_value(kind, obj[name], _at(path, name)) for name, kind in table.items()} return _construct(cls, values, path) def _decode_value(kind: str, value: Any, path: str) -> Any: if kind == "f64": return _f64(value, path) if kind == "envelope": return _envelope(value, path) if kind in ("int", "bool"): if type(value) is not (int if kind == "int" else bool): _fail( "JSON_TYPE", path, f"Expected a JSON {'integer' if kind == 'int' else 'boolean'}." ) return value if kind == "type": return _tagged(value, _TYPE_KINDS, path) if kind == "expr": return _tagged(value, _EXPR_KINDS, path) if value is None: return None if kind == "fproc": return _record(value, FprocRegister, path) if kind == "dynamic": return _record(value, DynamicParam, path) if kind == "table": # 对象元素按包络解码;其余元素原样交给 DynamicParam 检查。 return [ _envelope(item, _at(path, index)) if type(item) is dict else item for index, item in enumerate(_array(value, path)) ] return value def _tagged( value: Any, kinds: dict[str, type], path: str, fields: dict[type, dict[str, str]] = _FIELDS ) -> Any: obj = _object(value, path) kind = obj.get("kind") if type(kind) is not str or kind not in kinds: _fail("KIND", _at(path, "kind"), "Unknown record kind.") record = {name: item for name, item in obj.items() if name != "kind"} return _record(record, kinds[kind], path, fields) def _construct(cls: type, values: dict[str, Any], path: str) -> Any: try: return cls(**values) except PulseContractError as error: diagnostic = error.diagnostics[0] _fail(diagnostic.code, path + diagnostic.path, diagnostic.message, diagnostic.category) except (TypeError, ValueError) as error: if cls not in _EXPR_RECORDS: raise _fail("CLASSICAL_RECORD", path, str(error))